-
Notifications
You must be signed in to change notification settings - Fork 0
/
fasta_file.rb
196 lines (173 loc) · 5.41 KB
/
fasta_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
# Copyright 2014, 2015 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'
# Provides simple interface for parsing fasta format files. Gzipped
# files are no problem.
class FastaFile < File
# Use it like IO::open
#
# @param fname [String] the name of the file to open
#
# @return [FastaFile] a FastaFile
def self.open(fname, *args)
begin
handle = Zlib::GzipReader.open(fname)
rescue Zlib::GzipFile::Error => e
handle = File.open(fname)
end
unless handle.each_char.peek[0] == '>'
raise ParseFasta::DataFormatError
end
handle.close
super
end
# Returns the records in the fasta file as a hash map with the
# headers as keys and the Sequences as values.
#
# @example Read a fastA into a hash table.
# seqs = FastaFile.open('reads.fa').to_hash
#
# @return [Hash] A hash with headers as keys, sequences as the
# values (Sequence objects)
#
# @raise [ParseFasta::SequenceFormatError] if sequence has a '>'
def to_hash
hash = {}
self.each_record do |head, seq|
hash[head] = seq
end
hash
end
# Analagous to IO#each_line, #each_record is used to go through a
# fasta file record by record. It will accept gzipped files as well.
#
# @param separate_lines [Object] If truthy, separate lines of record
# into an array of Sequences, but if falsy, yield a Sequence
# object for the sequence instead.
#
# @example Parsing a fasta file (default behavior, gzip files are fine)
# FastaFile.open('reads.fna.gz').each_record do |header, sequence|
# puts [header, sequence.gc].join("\t")
# end
#
# @example Parsing a fasta file (with truthy value param)
# FastaFile.open('reads.fna').each_record(1) do |header, sequence|
# # header => 'sequence_1'
# # sequence => ['AACTG', 'AGTCGT', ... ]
# end
#
# @yield The header and sequence for each record in the fasta
# file to the block
#
# @yieldparam header [String] The header of the fasta record without
# the leading '>'
#
# @yieldparam sequence [Sequence, Array<Sequence>] The sequence of the
# fasta record. If `separate_lines` is falsy (the default
# behavior), will be Sequence, but if truthy will be
# Array<String>.
#
# @raise [ParseFasta::SequenceFormatError] if sequence has a '>'
def each_record(separate_lines=nil)
begin
f = Zlib::GzipReader.open(self)
rescue Zlib::GzipFile::Error => e
f = self
end
if separate_lines
f.each("\n>") do |line|
header, sequence = parse_line_separately(line)
yield(header.strip, sequence)
end
# f.each_with_index(">") do |line, idx|
# if idx.zero?
# if line != ">"
# raise ParseFasta::DataFormatError
# end
# else
# header, sequence = parse_line_separately(line)
# yield(header.strip, sequence)
# end
# end
else
f.each("\n>") do |line|
header, sequence = parse_line(line)
yield(header.strip, Sequence.new(sequence || ""))
end
# f.each_with_index(sep=/^>/) do |line, idx|
# if idx.zero?
# if line != ">"
# raise ParseFasta::DataFormatError
# end
# else
# header, sequence = parse_line(line)
# yield(header.strip, Sequence.new(sequence || ""))
# end
# end
end
f.close if f.instance_of?(Zlib::GzipReader)
return f
end
# Fast version of #each_record
#
# Yields the sequence as a String, not Sequence. No separate lines
# option.
#
# @note If the fastA file has spaces in the sequence, they will be
# retained. If this is a problem, use #each_record instead.
#
# @yield The header and sequence for each record in the fasta
# file to the block
#
# @yieldparam header [String] The header of the fasta record without
# the leading '>'
#
# @yieldparam sequence [String] The sequence of the fasta record
#
# @raise [ParseFasta::SequenceFormatError] if sequence has a '>'
def each_record_fast
begin
f = Zlib::GzipReader.open(self)
rescue Zlib::GzipFile::Error => e
f = self
end
f.each("\n>") do |line|
header, sequence = parse_line(line)
raise ParseFasta::SequenceFormatError if sequence.include? ">"
yield(header.strip, sequence)
end
f.close if f.instance_of?(Zlib::GzipReader)
return f
end
private
def parse_line(line)
line.split("\n", 2).map { |s| s.gsub(/\n|^>|>$/, '') }
end
def parse_line_separately(line)
header, sequence =
line.split("\n", 2).map { |s| s.gsub(/^>|>$/, '') }
if sequence.nil?
sequences = []
else
sequences = sequence.split("\n")
.reject { |s| s.empty? }
.map { |s| Sequence.new(s) }
end
[header, sequences]
end
end