-
Notifications
You must be signed in to change notification settings - Fork 4
/
sff_extractor.py
executable file
·1553 lines (1281 loc) · 53.4 KB
/
sff_extractor.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/python3
'''This software extracts the seq, qual and ancillary information from an sff
file, like the ones used by the 454 sequencer.
Optionally, it can also split paired-end reads if given the linker sequence.
The splitting is done with maximum match, i.e., every occurence of the linker
sequence will be removed, even if occuring multiple times.'''
#Copyright 2014 Francisco Pina Martins <[email protected]>
#copyright Jose Blanca and Bastien Chevreux
#COMAV institute, Universidad Politecnica de Valencia (UPV)
#Valencia, Spain
# additions to handle paired end reads by Bastien Chevreux
# bugfixes for linker specific lengths: Lionel Guy
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = 'Jose Blanca and Bastien Chevreux'
__copyright__ = 'Copyright 2008, Jose Blanca, COMAV, and Bastien Chevreux'
__license__ = 'GPLv3 or later'
__version__ = '0.3.0'
__email__ = '[email protected]'
__status__ = 'beta'
import struct
import sys
import os
import subprocess
import tempfile
fake_sff_name = 'fake_sff_name'
# readname as key: lines with matches from SSAHA, one best match
ssahapematches = {}
# linker readname as key: length of linker sequence
linkerlengths = {}
# set to true if something really fishy is going on with the sequences
stern_warning = False
def read_bin_fragment(struct_def, fileh, offset=0, data=None,
byte_padding=None):
'''It reads a chunk of a binary file.
You have to provide the struct, a file object, the offset (where to start
reading).
Also you can provide an optional dict that will be populated with the
extracted data.
If a byte_padding is given the number of bytes read will be a multiple of
that number, adding the required pad at the end.
It returns the number of bytes reads and the data dict.
'''
if data is None:
data = {}
#we read each item
bytes_read = 0
for item in struct_def:
#we go to the place and read
fileh.seek(offset + bytes_read)
n_bytes = struct.calcsize(item[1])
buffer = fileh.read(n_bytes)
read = struct.unpack('>' + item[1], buffer)
if len(read) == 1:
read = read[0]
elif type(read[0]) != int:
read = tuple(map(lambda x: x.decode("utf-8"), read))
data[item[0]] = read
bytes_read += n_bytes
#if there is byte_padding the bytes_to_read should be a multiple of the
#byte_padding
if byte_padding is not None:
pad = byte_padding
bytes_read = ((bytes_read + pad - 1) // pad) * pad
return (bytes_read, data)
def check_magic(magic):
'''It checks that the magic number of the file matches the sff magic.'''
if magic != 779314790:
raise RuntimeError('This file does not seems to be an sff file.')
def check_version(version):
'''It checks that the version is supported, otherwise it raises an error.'''
supported = ('\x00', '\x00', '\x00', '\x01')
i = 0
for item in version:
if version[i] != supported[i]:
raise RuntimeError('SFF version not supported. Please contact the author of the software.')
i += 1
def read_header(fileh):
'''It reads the header from the sff file and returns a dict with the
information'''
#first we read the first part of the header
head_struct = [
('magic_number', 'I'),
('version', 'cccc'),
('index_offset', 'Q'),
('index_length', 'I'),
('number_of_reads', 'I'),
('header_length', 'H'),
('key_length', 'H'),
('number_of_flows_per_read', 'H'),
('flowgram_format_code', 'B'),
]
data = {}
first_bytes, data = read_bin_fragment(struct_def=head_struct, fileh=fileh,
offset=0, data=data)
check_magic(data['magic_number'])
check_version(data['version'])
#now that we know the number_of_flows_per_read and the key_length
#we can read the second part of the header
struct2 = [
('flow_chars', str(data['number_of_flows_per_read']) + 'c'),
('key_sequence', str(data['key_length']) + 'c')
]
read_bin_fragment(struct_def=struct2, fileh=fileh, offset=first_bytes,
data=data)
return data
def read_sequence(header, fileh, fposition):
'''It reads one read from the sff file located at the fposition and
returns a dict with the information.'''
header_length = header['header_length']
index_offset = header['index_offset']
index_length = header['index_length']
#the sequence struct
read_header_1 = [
('read_header_length', 'H'),
('name_length', 'H'),
('number_of_bases', 'I'),
('clip_qual_left', 'H'),
('clip_qual_right', 'H'),
('clip_adapter_left', 'H'),
('clip_adapter_right', 'H'),
]
def read_header_2(name_length):
'''It returns the struct definition for the second part of the header'''
return [('name', str(name_length) +'c')]
def read_data(number_of_bases):
'''It returns the struct definition for the read data section.'''
#size = {'c': 1, 'B':1, 'H':2, 'I':4, 'Q':8}
if header['flowgram_format_code'] == 1:
flow_type = 'H'
else:
raise Error('file version not supported')
number_of_bases = str(number_of_bases)
return [
('flowgram_values', str(header['number_of_flows_per_read']) +
flow_type),
('flow_index_per_base', number_of_bases + 'B'),
('bases', number_of_bases + 'c'),
('quality_scores', number_of_bases + 'B'),
]
data = {}
#we read the first part of the header
bytes_read, data = read_bin_fragment(struct_def=read_header_1,
fileh=fileh, offset=fposition, data=data)
read_bin_fragment(struct_def=read_header_2(data['name_length']),
fileh=fileh, offset=fposition + bytes_read, data=data)
#we join the letters of the name
data['name'] = ''.join(data['name'])
offset = data['read_header_length']
#we read the sequence and the quality
read_data_st = read_data(data['number_of_bases'])
bytes_read, data = read_bin_fragment(struct_def=read_data_st,
fileh=fileh, offset=fposition + offset,
data=data, byte_padding=8)
#we join the bases
data['bases'] = ''.join(data['bases'])
#print "pre cqr: ", data['clip_qual_right']
#print "pre car: ", data['clip_adapter_right']
#print "pre cql: ", data['clip_qual_left']
#print "pre cal: ", data['clip_adapter_left']
# bugfix: 0 values for clips in SFF mean: not computed
# see http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?cmd=show&f=formats&m=doc&s=formats#sff
# i.e.: right clip values must be set to length of sequences
# if that happens so that we can work with normal ranges
if data['clip_qual_right'] == 0 :
data['clip_qual_right'] = data['number_of_bases'];
if data['clip_adapter_right'] == 0 :
data['clip_adapter_right'] = data['number_of_bases'];
# correct for the case the right clip is <= than the left clip
# in this case, left clip is 0 are set to 0 (right clip == 0 means
# "whole sequence")
if data['clip_qual_right'] <= data['clip_qual_left'] :
data['clip_qual_right'] = 0
data['clip_qual_left'] = 0
if data['clip_adapter_right'] <= data['clip_adapter_left'] :
data['clip_adapter_right'] = 0
data['clip_adapter_left'] = 0
#the clipping section follows the NCBI's guidelines Trace Archive RFC
#http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?cmd=show&f=rfc&m=doc&s=rfc
#if there's no adapter clip: qual -> vector
#else: qual-> qual
# adapter -> vector
if not data['clip_adapter_left']:
data['clip_adapter_left'], data['clip_qual_left'] = data['clip_qual_left'], data['clip_adapter_left']
if not data['clip_adapter_right']:
data['clip_adapter_right'], data['clip_qual_right'] = data['clip_qual_right'], data['clip_adapter_right']
# see whether we have to override the minimum left clips
if config['min_leftclip'] > 0:
if data['clip_adapter_left'] >0 and data['clip_adapter_left'] < config['min_leftclip']:
data['clip_adapter_left'] = config['min_leftclip']
if data['clip_qual_left'] >0 and data['clip_qual_left'] < config['min_leftclip']:
data['clip_qual_left'] = config['min_leftclip']
#print "post cqr: ", data['clip_qual_right']
#print "post car: ", data['clip_adapter_right']
#print "post cql: ", data['clip_qual_left']
#print "post cal: ", data['clip_adapter_left']
# for handling the -c (clip) option gently, we already clip here
# and set all clip points to the sequence end points
if config['clip']:
data['bases'], data['quality_scores'] = clip_read(data)
data['number_of_bases']=len(data['bases'])
data['clip_qual_right'] = data['number_of_bases']
data['clip_adapter_right'] = data['number_of_bases']
data['clip_qual_left'] = 0
data['clip_adapter_left'] = 0
return data['read_header_length'] + bytes_read, data
def sequences(fileh, header):
'''It returns a generator with the data for each read.'''
#now we can read all the sequences
fposition = header['header_length'] #position in the file
reads_read = 0
while True:
if fposition == header['index_offset']:
#we have to skip the index section
fposition += index_length
continue
else:
bytes_read, seq_data = read_sequence(header=header, fileh=fileh,
fposition=fposition)
yield seq_data
fposition += bytes_read
reads_read += 1
if reads_read >= header['number_of_reads']:
break
def remove_last_xmltag_in_file(fname, tag=None):
'''Given an xml file name and a tag, it removes the last tag of the
file if it matches the given tag. Tag removal is performed via file
truncation.
It the given tag is not the last in the file, a RunTimeError will be
raised.
The resulting xml file will be not xml valid. This function is a hack
that allows to append records to xml files in a quick and dirty way.
'''
fh = open(fname, 'r+')
#we have to read from the end to the start of the file and keep the
#string enclosed by </ >
i = -1
last_tag = [] #the chars that form the last tag
start_offset = None #in which byte does the last tag starts?
end_offset = None #in which byte does the last tag ends?
while True:
fh.seek(i, 2)
char = fh.read(1)
if not char.isspace():
last_tag.append(char)
if char == '>':
end_offset = i
if char == '<':
start_offset = i
break
i -= 1
#we have read the last tag backwards
last_tag = ''.join(last_tag[::-1])
#we remove the </ and >
last_tag = last_tag.rstrip('>').lstrip('</')
#we check that we're removing the asked tag
if tag is not None and tag != last_tag:
etxt=join('The given xml tag (',tag,') was not the last one in the file');
raise RuntimeError(etxt)
# while we are at it: also remove all white spaces in that line :-)
i -= 1
while True:
fh.seek(i, 2)
char = fh.read(1)
if not char == ' ' and not char == '\t':
break;
if fh.tell() == 1:
break;
i -= 1
fh.truncate();
fh.close()
return last_tag
def create_basic_xml_info(readname, fname):
'''Formats a number of read specific infos into XML format.
Currently formated: name and the tags set from command line
'''
to_print = [' <trace>\n']
to_print.append(' <trace_name>')
to_print.append(readname)
to_print.append('</trace_name>\n')
#extra information
#do we have extra info for this file?
info = None
if config['xml_info']:
#with this name?
if fname in config['xml_info']:
info = config['xml_info'][fname]
else:
#with no name?
try:
info = config['xml_info'][fake_sff_name]
except KeyError:
pass
#we print the info that we have
if info:
for key in info:
to_print.append(' <' + key + '>' + info[key] + \
'</' + key +'>\n')
return ''.join(to_print)
def create_clip_xml_info(readlen, adapl, adapr, quall, qualr):
'''Takes the clip values of the read and formats them into XML
Corrects "wrong" values that might have resulted through
simplified calculations earlier in the process of conversion
(especially during splitting of paired-end reads)
'''
to_print = [""]
# if right borders are >= to read length, they don't need
# to be printed
if adapr >= readlen:
adapr = 0
if qualr >= readlen:
qualr = 0
# BaCh
# when called via split_paired_end(), some values may be < 0
# (when clip values were 0 previously)
# instead of putting tons of if clauses for different calculations there,
# I centralise corrective measure here
# set all values <0 to 0
if adapr < 0:
adapr = 0
if qualr <0:
qualr = 0
if adapl < 0:
adapl = 0
if quall <0:
quall = 0
if quall:
to_print.append(' <clip_quality_left>')
to_print.append(str(quall))
to_print.append('</clip_quality_left>\n')
if qualr:
to_print.append(' <clip_quality_right>')
to_print.append(str(qualr))
to_print.append('</clip_quality_right>\n')
if adapl:
to_print.append(' <clip_vector_left>')
to_print.append(str(adapl))
to_print.append('</clip_vector_left>\n')
if adapr:
to_print.append(' <clip_vector_right>')
to_print.append(str(adapr))
to_print.append('</clip_vector_right>\n')
return ''.join(to_print)
def create_xml_for_unpaired_read(data, fname):
'''Given the data for one read it returns an str with the xml ancillary
data.'''
to_print = [create_basic_xml_info(data['name'],fname)]
#clippings in the XML only if we do not hard clip
if not config['clip']:
to_print.append(create_clip_xml_info(data['number_of_bases'],data['clip_adapter_left'], data['clip_adapter_right'], data['clip_qual_left'], data['clip_qual_right']));
to_print.append(' </trace>\n')
return ''.join(to_print)
def format_as_fasta(name,seq,qual):
name_line = ''.join(('>', name,'\n'))
seqstring = ''.join((name_line, seq, '\n'))
qual_line = ' '.join([str(q) for q in qual])
qualstring = ''.join((name_line, qual_line, '\n'))
return seqstring, qualstring
def format_as_fastq(name,seq,qual):
qual_line = ''.join([chr(q+33) for q in qual])
#seqstring = ''.join(('@', name,'\n', seq, '\n+', name,'\n', qual_line, '\n'))
seqstring = ''.join(('@', name,'\n', seq, '\n+\n', qual_line, '\n'))
return seqstring
def get_read_data(data):
'''Given the data for one read it returns 2 strs with the fasta seq
and fasta qual.'''
#seq and qual
if config['mix_case']:
seq = sequence_case(data)
qual = data['quality_scores']
else :
seq = data['bases']
qual = data['quality_scores']
return seq, qual
def extract_read_info(data, fname):
'''Given the data for one read it returns 3 strs with the fasta seq, fasta
qual and xml ancillary data.'''
seq,qual = get_read_data(data)
seqstring, qualstring = format_as_fasta(data['name'],seq,qual)
#name_line = ''.join(('>', data['name'],'\n'))
#seq = ''.join((name_line, seq, '\n'))
#qual_line = ' '.join([str(q) for q in qual])
#qual = ''.join((name_line, qual_line, '\n'))
xmlstring = create_xml_for_unpaired_read(data, fname)
return seqstring, qualstring, xmlstring
def write_sequence(name,seq,qual,seq_fh,qual_fh):
'''Write sequence and quality FASTA and FASTA qual filehandles
(or into FASTQ and XML)
if sequence length is 0, don't write'''
if len(seq) == 0 : return
if qual_fh is None:
seq_fh.write(format_as_fastq(name,seq,qual))
else:
seqstring, qualstring = format_as_fasta(name,seq,qual)
seq_fh.write(seqstring)
qual_fh.write(qualstring)
return
def write_unpaired_read(data, sff_fh, seq_fh, qual_fh, xml_fh):
'''Writes an unpaired read into FASTA, FASTA qual and XML filehandles
(or into FASTQ and XML)
if sequence length is 0, don't write'''
seq,qual = get_read_data(data)
if len(seq) == 0 : return
write_sequence(data['name'],seq,qual,seq_fh,qual_fh)
anci = create_xml_for_unpaired_read(data, sff_fh.name)
if anci is not None:
xml_fh.write(anci)
return
def reverse_complement(seq):
'''Returns the reverse complement of a DNA sequence as string'''
compdict = {
'a': 't',
'c': 'g',
'g': 'c',
't': 'a',
'u': 't',
'm': 'k',
'r': 'y',
'w': 'w',
's': 's',
'y': 'r',
'k': 'm',
'v': 'b',
'h': 'd',
'd': 'h',
'b': 'v',
'x': 'x',
'n': 'n',
'A': 'T',
'C': 'G',
'G': 'C',
'T': 'A',
'U': 'T',
'M': 'K',
'R': 'Y',
'W': 'W',
'S': 'S',
'Y': 'R',
'K': 'M',
'V': 'B',
'H': 'D',
'D': 'H',
'B': 'V',
'X': 'X',
'N': 'N',
'*': '*'
}
complseq = ''.join([compdict[base] for base in seq])
# python hack to reverse a list/string/etc
complseq = complseq[::-1]
return complseq
def mask_sequence(seq, maskchar, fpos, tpos):
'''Given a sequence, mask it with maskchar starting at fpos (including) and
ending at tpos (excluding)
'''
if len(maskchar) > 1:
raise RuntimeError("Internal error: more than one character given to mask_sequence")
if fpos<0:
fpos = 0
if tpos > len(seq):
tpos = len(seq)
newseq = ''.join((seq[:fpos],maskchar*(tpos-fpos), seq[tpos:]))
return newseq
def fragment_sequences(sequence, qualities, splitchar):
'''Works like split() on strings, except it does this on a sequence
and the corresponding list with quality values.
Returns a tuple for each fragment, each sublist has the fragment
sequence as first and the fragment qualities as second elemnt'''
# this is slow (due to zip and list appends... use an iterator over
# the sequence find find variations and splices on seq and qual
if len(sequence) != len(qualities):
print(sequence, qualities)
raise RuntimeError("Internal error: length of sequence and qualities don't match???")
retlist = ([])
if len(sequence) == 0:
return retlist
actseq = ([])
actqual = ([])
if sequence[0] != splitchar:
inseq = True
else:
inseq = False
for char,qual in zip(sequence,qualities):
if inseq:
if char != splitchar:
actseq.append(char)
actqual.append(qual)
else:
retlist.append((''.join(actseq), actqual))
actseq = ([])
actqual = ([])
inseq = False
else:
if char != splitchar:
inseq = True
actseq.append(char)
actqual.append(qual)
if inseq and len(actseq):
retlist.append((''.join(actseq), actqual))
return retlist
def calc_subseq_boundaries(maskedseq, maskchar):
'''E.g.:
........xxxxxxxx..........xxxxxxxxxxxxxxxxxxxxx.........
to
(0,8),(8,16),(16,26),(26,47),(47,56)
'''
blist = ([])
if len(maskedseq) == 0:
return blist
inmask = True
if maskedseq[0] != maskchar:
inmask = False
start = 0
for spos in range(len(maskedseq)):
if inmask and maskedseq[spos] != maskchar:
blist.append(([start,spos]))
start = spos
inmask = False
elif not inmask and maskedseq[spos] == maskchar:
blist.append(([start,spos]))
start = spos
inmask = True
blist.append(([start,spos+1]))
return blist
def correct_for_smallhits(maskedseq, maskchar, linkername):
'''If partial hits were found, take preventive measure: grow
the masked areas by 20 bases in each direction
Returns either unchanged "maskedseq" or a new sequence
with some more characters masked.
'''
global linkerlengths
CEBUG = 0
if CEBUG : print("correct_for_smallhits")
if CEBUG : print("Masked seq\n", maskedseq)
if CEBUG : print("Linkername: ", linkername)
if len(maskedseq) == 0:
return maskedseq
growl=40
growl2=int(growl/2)
boundaries = calc_subseq_boundaries(maskedseq,maskchar)
if CEBUG : print("Boundaries: ", boundaries)
foundpartial = False
for bounds in boundaries:
if CEBUG : print("\tbounds: ", bounds)
left, right = bounds
if left != 0 and right != len(maskedseq):
if maskedseq[left] == maskchar:
# allow 10% discrepancy
# -linkerlengths[linkername]/10
# that's a kind of safety net if there are slight sequencing
# errors in the linker itself
if right-left < linkerlengths[linkername]-linkerlengths[linkername]/10:
if CEBUG : print("\t\tPartial: found " + str(right-left) + " gaps, " + linkername + " is " + str(linkerlengths[linkername]) + " nt long.")
foundpartial = True
if not foundpartial:
return maskedseq
# grow
newseq = ""
for bounds in boundaries:
if CEBUG : print("Bounds: ", bounds)
left, right = bounds
if maskedseq[left] == maskchar:
newseq += maskedseq[left:right]
else:
clearstart = 0
if left > 0 :
clearstart = left+growl2
clearstop = len(maskedseq)
if right < len(maskedseq):
clearstop = right-growl2
if CEBUG : print("clearstart, clearstop: ",clearstart, clearstop)
if clearstop <= clearstart:
newseq += maskchar * (right-left)
else:
if clearstart != left:
newseq += maskchar * growl2
newseq += maskedseq[clearstart:clearstop]
if clearstop != right:
newseq += maskchar * growl2
#print "newseq\n",newseq
return newseq
def split_paired_end(data, sff_fh, seq_fh, qual_fh, xml_fh):
'''Splits a paired end read and writes sequences into FASTA, FASTA qual
and XML traceinfo file. Returns the number of sequences created.
As the linker sequence may be anywhere in the read, including the ends
and overlapping with bad quality sequence, we need to perform some
computing and eventually set new clip points.
If the resulting split yields only one sequence (because linker was not
present or overlapping with left or right clip), only one sequence will be
written. The read name will have no postfix, making it an unpaired-read.
If the read can be split, two reads will be written. In standard mode,
both reads will be in forward direction (as in the sequence form the SFF)
and the read names will have /1 and /2 appended. In compatibility mode,
the side left of the linker will be named ".r" and will be written in
reverse complement into the file to conform with what older assemblers and
scaffolders expect when reading paired-end data. The side right of the
linker will be named ".f"
If SSAHA found partial linker (linker sequences < length of linker),
the sequences will get a "_pl" furthermore be cut back thoroughly.
If SSAHA found multiple occurences of the linker, the names will get an
additional "_mlc" within the name to show that there was "multiple
linker contamination".
For multiple or partial linker, the "good" parts of the reads are stored
with a "_part<number>" name, additionally they will not get template
information in the XML and the naming scheme will make them unpaired read.
'''
global ssahapematches
CEBUG = 0
maskchar = "#"
if CEBUG : print("Need to split: " + data['name'])
numseqs = 0;
readname = data['name']
readlen = data['number_of_bases']
leftclip, rightclip = return_merged_clips(data)
seq, qual = get_read_data(data)
if CEBUG : print("Original read:\n",seq)
maskedseq = seq
if leftclip > 0:
maskedseq = mask_sequence(maskedseq, maskchar, 0, leftclip-1)
if rightclip < len(maskedseq):
maskedseq = mask_sequence(maskedseq, maskchar, rightclip, len(maskedseq))
leftclip, rightclip = return_merged_clips(data)
readlen = data['number_of_bases']
if CEBUG : print("Readname:", readname)
if CEBUG : print("Readlen:", readlen)
if CEBUG : print("Num matches:", str(len(ssahapematches[data['name']])))
if CEBUG : print("matches:", ssahapematches[data['name']])
for match in ssahapematches[data['name']]:
score = int(match[0])
linkername = match[2]
leftreadhit = int(match[3])
rightreadhit = int(match[4])
#leftlinkerhit = int(match[5])
#rightlinkerhit = int(match[6])
#direction = match[7]
#hitlen = int(match[8])
#hitidentity = float(match[9])
if CEBUG : print(match)
if CEBUG : print("Match with score:", score)
if CEBUG : print("Read before:\n", maskedseq)
maskedseq = mask_sequence(maskedseq, maskchar, leftreadhit-1, rightreadhit)
if CEBUG : print("Masked seq:\n", maskedseq)
correctedseq = correct_for_smallhits(maskedseq, maskchar, linkername)
if len(maskedseq) != len(correctedseq):
raise RuntimeError("Internal error: maskedseq != correctedseq")
partialhits = False
if correctedseq != maskedseq:
if CEBUG : print("Partial hits in", readname)
if CEBUG : print("Original seq:\n", seq)
if CEBUG : print("Masked seq:\n", maskedseq)
if CEBUG : print("Corrected seq\n", correctedseq)
partialhits = True
readname += "_pl"
maskedseq = correctedseq
fragments = fragment_sequences(maskedseq, qual, maskchar)
if CEBUG : print("Fragments (", len(fragments), "): ", fragments)
mlcflag = False
#if len(ssahapematches[data['name']]) > 1:
# #print "Multi linker contamination"
# mlcflag = True
# readname += "_mlc"
if len(fragments) > 2:
if CEBUG : print("Multi linker contamination")
mlcflag = True
readname += "_mlc"
#print fragments
if mlcflag or partialhits:
fragcounter = 1
readname += "_part"
for frag in fragments:
actseq = frag[0]
if len(actseq) >= 20:
actqual = frag[1]
oname = readname + str(fragcounter)
#seq_fh.write(">"+oname+"\n")
#seq_fh.write(actseq+"\n")
#qual_fh.write(">"+oname+"\n")
#qual_fh.write(' '.join((str(q) for q in actqual)))
#qual_fh.write("\n")
write_sequence(oname,actseq,actqual,seq_fh,qual_fh)
to_print = [create_basic_xml_info(oname,sff_fh.name)]
# No clipping in XML ... the multiple and partial fragments
# are clipped "hard"
# No template ID and trace_end: we don't know the
# orientation of the fragments. Even if it were
# only two, the fact we had multiple linkers
# says something went wrong, so simply do not
# write any paired-end information for all these fragments
to_print.append(' </trace>\n')
xml_fh.write(''.join(to_print))
numseqs += 1
fragcounter += 1
else:
if len(fragments) >2:
raise RuntimeError("Unexpected: more than two fragments detected in " + readname + ". please contact the authors.")
# nothing will happen for 0 fragments
if len(fragments) == 1:
#print "Tada1"
boundaries = calc_subseq_boundaries(maskedseq,maskchar)
if len(boundaries) < 1 or len(boundaries) >3:
raise RuntimeError("Unexpected case: ", str(len(boundaries)), "boundaries for 1 fragment of ", readname)
if len(boundaries) == 3:
# case: mask char on both sides of sequence
#print "bounds3"
data['clip_adapter_left']=boundaries[0][1]
data['clip_adapter_right']=boundaries[2][0]
elif len(boundaries) == 2:
# case: mask char left or right of sequence
#print "bounds2",
if maskedseq[0] == maskchar :
# case: mask char left
#print "left"
data['clip_adapter_left']=boundaries[0][1]
else:
# case: mask char right
#print "right"
data['clip_adapter_right']=boundaries[1][0]
data['name'] = data['name'] # + ".fn"
write_unpaired_read(data, sff_fh, seq_fh, qual_fh, xml_fh)
numseqs = 1
elif len(fragments) == 2:
#print "Tada2"
############## First read
if config['want_fr']:
oname = readname + ".r"
else:
oname = readname + "/1"
seq, qual = get_read_data(data)
startsearch = False
for spos in range(len(maskedseq)):
if maskedseq[spos] != maskchar:
startsearch = True;
else:
if startsearch:
break
#print "\nspos: ", spos
lqual = qual[:spos];
if config['want_fr']:
actseq = reverse_complement(seq[:spos])
# python hack to reverse a list/string/etc
lqual = lqual[::-1];
else:
actseq = seq[:spos]
lreadlen = len(actseq)
write_sequence(oname,actseq,lqual,seq_fh,qual_fh)
to_print = [create_basic_xml_info(oname,sff_fh.name)]
if config['want_fr']:
to_print.append(create_clip_xml_info(lreadlen, 0, lreadlen+1-data['clip_adapter_left'], 0, lreadlen+1-data['clip_qual_left']));
else:
to_print.append(create_clip_xml_info(lreadlen, data['clip_adapter_left'], 0, data['clip_qual_left'], 0));
to_print.append(' <template_id>')
to_print.append(readname)
to_print.append('</template_id>\n')
# BaCh 24.06.2012: trace_end really is only for F/R pairs, unsuited for 454 or IonTorrent
#to_print.append(' <trace_end>r</trace_end>\n')
to_print.append(' </trace>\n')
xml_fh.write(''.join(to_print))
############## Second read
if config['want_fr']:
oname = readname + ".f"
else:
oname = readname + "/2"
startsearch = False
for spos in range(len(maskedseq)-1,-1,-1):
if maskedseq[spos] != maskchar:
startsearch = True;
else:
if startsearch:
break
actseq = seq[spos+1:]
actqual = qual[spos+1:];
#print "\nspos: ", spos
#print "rseq:", actseq
#seq_fh.write(">"+oname+"\n")
#seq_fh.write(actseq+"\n")
#qual_fh.write(">"+oname+"\n")
#qual_fh.write(' '.join((str(q) for q in actqual)))
#qual_fh.write("\n")
write_sequence(oname,actseq,actqual,seq_fh,qual_fh)
rreadlen = len(actseq)
to_print = [create_basic_xml_info(oname,sff_fh.name)]
to_print.append(create_clip_xml_info(rreadlen, 0, rreadlen-(readlen-data['clip_adapter_right']), 0, rreadlen-(readlen-data['clip_qual_right'])));
to_print.append(' <template_id>')
to_print.append(readname)
to_print.append('</template_id>\n')
# BaCh 24.06.2012: trace_end really is only for F/R pairs, unsuited for 454 or IonTorrent
#to_print.append(' <trace_end>f</trace_end>\n')
to_print.append(' </trace>\n')
xml_fh.write(''.join(to_print))
numseqs = 2
return numseqs
def extract_reads_from_sff(conf, sff_files):
'''Given the configuration and the list of sff_files it writes the seqs,
qualities and ancillary data into the output file(s).
If file for paired-end linker was given, first extracts all sequences
of an SFF and searches these against the linker(s) with SSAHA2 to
create needed information to split reads.
'''
global ssahapematches
if __name__ != "__main__":
global config
config = conf
if len(sff_files) == 0 :
raise RuntimeError("No SFF file given?")
#we go through all input files
for sff_file in sff_files:
if not os.path.getsize(sff_file):
raise RuntimeError('Empty file? : ' + sff_file)
fh = open(sff_file, 'r')
fh.close()
openmode = 'w'
if config['append']:
openmode = 'a'
seq_fh = open(config['seq_fname'], openmode)
xml_fh = open(config['xml_fname'], openmode)
if config['want_fastq']:
qual_fh = None
try:
os.remove(config['qual_fname'])
except :