-
Notifications
You must be signed in to change notification settings - Fork 0
/
seq_file.rb
321 lines (281 loc) · 8.94 KB
/
seq_file.rb
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
# Copyright 2014 - 2016 Ryan Moore
# Contact: moorer@udel.edu
#
# This file is part of parse_fasta.
#
# parse_fasta 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.
#
# parse_fasta 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 parse_fasta. If not, see <http://www.gnu.org/licenses/>.
require "zlib"
module ParseFasta
class SeqFile
# @!attribute type
# @return [Symbol] the type of the SeqFile (:fasta or :fastq)
attr_accessor :type
# @param fname [String] the name of the fastA or fastQ file to
# parse
#
# @raise [ParseFasta::Error::FileNotFoundError] if the file is not
# found
# @raise [ParseFasta::Error::DataFormatError] if the file doesn't
# start with a '>' or a '@'
def initialize fname
type = check_file fname
@gzipped = gzipped? fname
@cr_only = nil
if !@gzipped
# check for \r only
@cr_only = cr_only? fname
end
@fname = fname
@type = type
end
# An alias for SeqFile.new
#
# @return [SeqFile] a SeqFile object
def self.open fname
self.new fname
end
# Analagous to IO#each_line, SeqFile#each_record is used to go
# through a fastA or fastQ file record by record. It will accept
# gzipped files as well.
#
# If the input is a fastA file, then the record that is yielded
# will have the desc and qual instance variables be nil. If it is
# a fastQ record then those instance variables will not be nil.
#
# @example Parsing a fastA file
# ParseFasta::SeqFile.open("seqs.fa").each_record do |rec|
# puts [rec.header, rec.seq].join "\t"
#
# rec.desc.nil? #=> true
# rec.qual.nil? #=> true
# end
# @example Parsing a gzipped fastQ file
# ParseFasta::SeqFile.open("seqs.fq.gz").each_record do |rec|
# puts [rec.header, rec.seq, rec.desc, rec.qual].join "\t"
# end
#
# @yieldparam record [ParseFasta::Record] A Record object with all
# the info of the record
#
# @raise [ParseFasta::Error::SequenceFormatError] if a fastA file
# contains a record with a '>' character in the header
def each_record &b
line_parser = "parse_#{@type}_lines"
if @type == :fastq && !@gzipped && !@cr_only
each_record_fastq_fast @fname, &b
elsif @gzipped
each_record_gzipped line_parser, &b
else
each_record_non_gzipped line_parser, &b
end
end
private
def each_record_non_gzipped line_parser, &b
File.open(@fname, "rt") do |f|
self.send line_parser, f, &b
end
end
def each_record_gzipped line_parser, &b
File.open(@fname, "rt") do |file|
loop do
begin
gz_reader = Zlib::GzipReader.new file
self.send line_parser, gz_reader, &b
# check if there are any more blobs to read
if (unused = gz_reader.unused)
# rewind to the start of the last blob
file.seek -unused.length, IO::SEEK_END
else
# there are no more blobs to read
break
end
end
end
end
end
# def parse_fastq_line line, header, seq, desc, qual, count, &b
# line.chomp!
# case count
# when 0
# header = line[1..-1]
# when 1
# seq = line
# when 2
# desc = line[1..-1]
# when 3
# count = -1
# qual = line
# yield Record.new(header: header,
# seq: seq,
# desc: desc,
# qual: qual)
# else
# raise ParseFasta::Error::ParseFastaError,
# "Something went wrong in parse_fastq_line"
# end
# count += 1
# [header, seq, desc, qual, count]
# end
# def parse_fasta_line line, header, sequence, &b
# line.chomp!
# len = line.length
# if header.empty? && line.start_with?(">")
# header = line[1, len] # drop the '>'
# elsif line.start_with? ">"
# yield Record.new(header: header.strip, seq: sequence)
# header = line[1, len]
# sequence = ""
# else
# sequence << line
# end
# [header, sequence]
# end
def parse_fasta_lines file_reader, &b
header = ""
sequence = ""
line_reader = which_line_reader file_reader
if @cr_only || @gzipped
file_reader.send(*line_reader) do |line|
header, sequence =
parse_fasta_line line,
header,
sequence,
ParseFasta::Error::DataFormatError,
&b
end
else
each_line(file_reader.path) do |line|
header, sequence =
parse_fasta_line line,
header,
sequence,
ParseFasta::Error::DataFormatError,
&b
end
end
# yield the final seq
yield Record.new(header: header.strip, seq: sequence)
end
def parse_fastq_lines file_reader, &b
count = 0
header = ""
seq = ""
desc = ""
qual = ""
line_reader = which_line_reader file_reader
if @cr_only || @gzipped
file_reader.send(*line_reader) do |line|
header, seq, desc, qual, count =
parse_fastq_line(line,
header,
seq,
desc,
qual,
count,
&b)
end
else
each_line(file_reader.path) do |line|
header, seq, desc, qual, count =
parse_fastq_line(line,
header,
seq,
desc,
qual,
count,
&b)
end
end
end
def gzipped? fname
begin
f = Zlib::GzipReader.open fname
return true
rescue Zlib::GzipFile::Error => e
return false
ensure
f.close if f
end
end
# The Zlib::GzipReader can't handle files where the line separator
# is \r. This could all be avoided by using IO.popen("gzip -cd
# #{fname}", "rt"), but will gzip always be available?
def which_line_reader file_reader
line_reader = [:each_line]
# a valid fasta file must have at least two lines, the header
# and the sequence
begin
enum = file_reader.each_line
# if this was ruby v2.3, then we could just call .size on enum
2.times do
enum.next
end
rescue StopIteration
# Zlib::GzipReader can handle \n and \r\n, but not \r, so if
# we get here, the file has \r only for line endings
line_reader = [:each, "\r"]
ensure
file_reader.rewind
end
line_reader
end
def get_first_char fname
if File.exists? fname
begin
f = Zlib::GzipReader.open fname
rescue Zlib::GzipFile::Error
f = File.open fname
end
begin
first_char = f.each_char.peek[0]
return first_char
ensure
f.close
end
else
raise ParseFasta::Error::FileNotFoundError,
"No such file or directory -- #{fname}"
end
end
def check_file fname
first_char = get_first_char fname
if first_char == ">"
:fasta
elsif first_char == "@"
:fastq
else
raise ParseFasta::Error::DataFormatError,
"The file does not look like fastA or fastQ " +
"-- #{fname}"
end
end
# only called on non-gz files
def cr_only? fname
lineno = 0
# when not using "t" mode, \r are not counted as newlines, but
# \n or \r\n will be
File.open(fname).each_line do |line|
lineno += 1
if lineno >= 2
break
end
end
if lineno >= 2
false
else
true
end
end
end
end