]> git.donarmstrong.com Git - biopieces.git/blob - bp_bin/classify_taxonomy
7e845718d81d49aca3c75ce70c6df33c722a32a1
[biopieces.git] / bp_bin / classify_taxonomy
1 #!/usr/bin/env ruby
2
3 # Copyright (C) 2007-2012 Martin A. Hansen.
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
19 # http://www.gnu.org/copyleft/gpl.html
20
21 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
22
23 # This program is part of the Biopieces framework (www.biopieces.org).
24
25 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
26
27 # Classify records with taxonomy information.
28
29 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
30
31 require 'pp'
32 require 'maasha/biopieces'
33
34 # Class containing methods to construct a taxonomic tree recursively
35 # for the classification of organisms. Currently only works with GreenGenes type of entries
36 class TaxNode
37   attr_accessor :level, :name, :count, :score, :children
38
39   # Method to initalize a TaxNode object.
40   def initialize(level, name, count, score)
41     @level    = level   # Taxonomic level e.g. phylum, class, etc
42     @name     = name    # Name of organism
43     @count    = count   # Number of times this organism was encountered
44     @score    = score   # Similarity score
45     @children = {}
46   end
47
48   # Method to add to the taxonomic tree a GreenGenes entry.
49   def add_gg(s_id, score, size)
50     node = self
51
52     s_id.scan(/ ([\w])__([^;]+)/) do
53       level = expand_level($1)
54       name  = $2
55
56       if node.children[name].nil?
57         node.children[name] = TaxNode.new(level, name, size * 1, size * score)
58       else
59         node.children[name].count += size * 1
60         node.children[name].score += size * score
61       end
62
63       node = node.children[name]
64     end
65   end
66
67   # Method to merge two TaxNodes.
68   def merge(node_new, node_old = self)
69     node_new.children.each do |name, child|
70       if node_old.children[name]
71         node_old.count += node_new.count
72         node_old.score += node_new.score
73       else
74         node_old.children[name] = child
75       end
76
77       merge(child, node_old.children[name])
78     end
79   end
80
81   # Method to flatten a taxonomic tree turning this into a list by recursive depth first traversal.
82   def flatten(node = self, list = [])
83     list << TaxNode.new(node.level, node.name, node.count, node.score)
84
85     node.children.each_value do |child|
86       flatten(child, list)
87     end
88
89     list
90   end
91
92   # Method to recursively trim a taxonomic tree so that it only contains an unbranched tree,
93   # which gives the lowest common ancestor.
94   def lowest_common_ancestor(node = self)
95     node.children = {} if node.children.size > 1
96
97     node.children.each do |name, child|
98       lowest_common_ancestor(child)
99     end
100   end
101
102   # Method for iterating over a taxonomic tree.
103   def each
104     self.flatten.each do |node|
105       yield node
106     end
107
108     self
109   end
110
111   # Method to convert a TaxNode to a Biopiece record.
112   def to_bp
113     record = {}
114     record[:REC_TYPE] = "Classification"
115     record[:LEVEL]    = @level
116     record[:NAME]     = @name
117     record[:COUNT]    = @count
118     record[:SCORE]    = @count == 0 ? 0.0 : (@score / @count).round(2)
119
120     record
121   end
122
123   private
124
125   # Method containing a helper hash to expand the phylogenetic level name.
126   def expand_level(level)
127     hash = {
128       'd' => "domain",
129       'k' => "kingdom",
130       'p' => "phylum",
131       'c' => "class",
132       'o' => "order",
133       'f' => "family",
134       'g' => "genus",
135       's' => "species"
136     }
137
138     raise "unknown level: #{level}" unless hash[level]
139
140     hash[level]
141   end
142 end
143
144 casts = []
145 casts << {:long=>'LCA',  :short=>'l', :type=>'flag', :mandatory=>false, :default=>nil, :allowed=>nil, :disallowed=>nil}
146 casts << {:long=>'size', :short=>'s', :type=>'uint', :mandatory=>false, :default=>nil, :allowed=>nil, :disallowed=>nil}
147
148 options = Biopieces.options_parse(ARGV, casts)
149
150 tax_tree = TaxNode.new("root", "Root", 0, 0.0)
151 tax_hash = {}
152
153 Biopieces.open(options[:stream_in], options[:stream_out]) do |input, output|
154   input.each_record do |record|
155     if record[:Q_ID] and record[:S_ID] and record[:SCORE]
156       size = 1
157
158       if options[:size]
159         if record[:Q_ID].match(/_(\d+)$/)
160           size = $1.to_i
161 #        else
162 #          raise BiopiecesError, "Could not extract size from Q_ID: #{record[:Q_ID]}"
163         end
164       end
165
166       if options[:LCA]
167         tax_hash[record[:Q_ID]] = TaxNode.new("root", "Root", 0, 0.0) unless tax_hash[record[:Q_ID]]
168         tax_hash[record[:Q_ID]].add_gg(record[:S_ID], record[:SCORE].to_f, size)
169       else
170         tax_tree.add_gg(record[:S_ID], record[:SCORE].to_f, size)
171       end
172     else
173       output.puts record
174     end
175   end
176
177   if options[:LCA]
178     tax_hash.each_value do |tree|
179       tree.lowest_common_ancestor
180     end
181
182     tax_hash.each_value do |tree|
183       tax_tree.merge(tree)
184     end
185   end
186
187   tax_tree.each do |node|
188     output.puts node.to_bp unless node.level == 'root'
189   end
190 end
191
192
193 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
194
195
196 __END__