comparison kraken_taxonomy_report.py @ 0:3f1a0d47ea8d draft

planemo upload for repository https://github.com/galaxyproject/tools-iuc/blob/master/tools/kraken_taxonomy_report/ commit 1c0a7aff7c5f6578a11e6e8e9bface8d02e7f8a1
author iuc
date Wed, 01 Jun 2016 17:25:40 -0400
parents
children b97694b21bc3
comparison
equal deleted inserted replaced
-1:000000000000 0:3f1a0d47ea8d
1 #!/usr/bin/env python
2
3 # Reports a summary of Kraken's results
4 # and optionally creates a newick Tree
5 # Copyright (c) 2016 Daniel Blankenberg
6 # Licensed under the Academic Free License version 3.0
7 # https://github.com/blankenberg/Kraken-Taxonomy-Report
8
9 import sys
10 import os
11 import optparse
12 import re
13
14 __VERSION__ = '0.0.1'
15
16 __URL__ = "https://github.com/blankenberg/Kraken-Taxonomy-Report"
17
18 # Rank names were pulled from ncbi nodes.dmp on 02/02/2016
19 # cat nodes.dmp | cut -f 5 | sort | uniq
20 # "root" is added manually
21 NO_RANK_NAME = "no rank"
22 RANK_NAMES = [ NO_RANK_NAME,
23 "root",
24 "superkingdom",
25 "kingdom",
26 "subkingdom",
27 "superphylum",
28 "phylum",
29 "subphylum",
30 "superclass",
31 "class",
32 "subclass",
33 "infraclass",
34 "superorder",
35 "order",
36 "suborder",
37 "infraorder",
38 "parvorder",
39 "superfamily",
40 "family",
41 "subfamily",
42 "tribe",
43 "subtribe",
44 "genus",
45 "subgenus",
46 "species group",
47 "species subgroup",
48 "species",
49 "subspecies",
50 "varietas",
51 "forma" ]
52 # NB: We put 'no rank' at top of list for generating trees, due to e.g.
53 # root (root) -> cellular organisms (no rank) -> bacteria (superkingdom)
54
55 RANK_NAME_TO_INTS = dict( [ (y, x) for (x, y) in enumerate( RANK_NAMES ) ] )
56 RANK_NAMES_INTS = range( len( RANK_NAMES ) )
57
58 NO_RANK_INT = RANK_NAMES.index( NO_RANK_NAME )
59 NO_RANK_CODE = 'n'
60
61 PRIMARY_RANK_NAMES = [ 'species', 'genus', 'family', 'order', 'class', 'phylum', 'kingdom' ]
62 RANK_INT_TO_CODE = {}
63 for name in PRIMARY_RANK_NAMES:
64 RANK_INT_TO_CODE[ RANK_NAMES.index( name ) ] = name[0]
65 RANK_INT_TO_CODE[ RANK_NAMES.index( 'superkingdom' ) ] = 'd'
66 PRIMARY_RANK_NAMES.append( 'superkingdom' )
67
68 NAME_STUB = "%s__%s"
69 NAME_RE = re.compile( "(\t| |\||\.;)" )
70 NAME_REPL = "_"
71
72
73 def get_kraken_db_path( db ):
74 assert db, ValueError( "You must provide a kraken database" )
75 k_db_path = os.getenv('KRAKEN_DB_PATH', None )
76 if k_db_path:
77 db = os.path.join( k_db_path, db )
78 return db
79
80
81 def load_taxonomy( db_path, sanitize_names=False ):
82 child_lists = {}
83 name_map = {}
84 rank_map = {}
85 with open( os.path.join( db_path, "taxonomy/names.dmp" ) ) as fh:
86 for line in fh:
87 line = line.rstrip( "\n\r" )
88 if line.endswith( "\t|" ):
89 line = line[:-2]
90 fields = line.split( "\t|\t" )
91 node_id = fields[0]
92 name = fields[1]
93 if sanitize_names:
94 name = NAME_RE.sub( NAME_REPL, name )
95 name_type = fields[3]
96 if name_type == "scientific name":
97 name_map[ node_id ] = name
98
99 with open( os.path.join( db_path, "taxonomy/nodes.dmp" ) ) as fh:
100 for line in fh:
101 line = line.rstrip( "\n\r" )
102 fields = line.split( "\t|\t" )
103 node_id = fields[0]
104 parent_id = fields[1]
105 rank = RANK_NAME_TO_INTS.get( fields[2].lower(), None )
106 if rank is None:
107 # This should never happen, unless new taxonomy ranks are created
108 print >> sys.stderr, 'Unrecognized rank: Node "%s" is "%s", setting to "%s"' % ( node_id, fields[2], NO_RANK_NAME )
109 rank = NO_RANK_INT
110 if node_id == '1':
111 parent_id = '0'
112 if parent_id not in child_lists:
113 child_lists[ parent_id ] = []
114 child_lists[ parent_id ].append( node_id )
115 rank_map[node_id] = rank
116 return ( child_lists, name_map, rank_map )
117
118
119 def dfs_summation( node, counts, child_lists ):
120 children = child_lists.get( node, None )
121 if children:
122 for child in children:
123 dfs_summation( child, counts, child_lists )
124 counts[ node ] = counts.get( node, 0 ) + counts.get( child, 0 )
125
126
127 def dfs_report( node, file_data, hit_taxa, rank_map, name_map, child_lists, output_lines, options, name=None, tax=None ):
128 if not options.summation and ( not options.show_zeros and node not in hit_taxa ):
129 return
130 rank_int = rank_map[node]
131 code = RANK_INT_TO_CODE.get( rank_int, NO_RANK_CODE )
132 if ( code != NO_RANK_CODE or options.intermediate ) and ( options.show_zeros or node in hit_taxa):
133 if name is None:
134 name = ""
135 else:
136 name = "%s|" % name
137 if tax is None:
138 tax = ''
139 else:
140 tax = "%s;" % tax
141 sanitized_name = name_map[ node ]
142 name_stub = NAME_STUB % ( code, sanitized_name )
143 name = name + name_stub
144 tax = tax + name_stub
145 if options.name_id:
146 output = node
147 elif options.name_long:
148 output = name
149 else:
150 output = sanitized_name
151 for val in file_data:
152 output = "%s\t%i" % ( output, val.get( node, 0 ) )
153 if options.show_rank:
154 output = "%s\t%s" % ( output, RANK_NAMES[ rank_int ] )
155 if options.taxonomy:
156 output = "%s\t%s" % ( output, tax )
157 output_lines[ rank_int ].append( output )
158 children = child_lists.get( node )
159 if children:
160 for child in children:
161 dfs_report( child, file_data, hit_taxa, rank_map, name_map, child_lists, output_lines, options, name=name, tax=tax )
162
163
164 def write_tree( child_lists, name_map, rank_map, options, branch_length=1 ):
165 # Uses Biopython, only load if making tree
166 import Bio.Phylo
167 from Bio.Phylo import BaseTree
168
169 def _get_name( node_id ):
170 if options.name_id:
171 return node_id
172 return name_map[node_id]
173 nodes = {}
174 root_node_id = child_lists["0"][0]
175 nodes[root_node_id] = BaseTree.Clade( name=_get_name( root_node_id), branch_length=branch_length )
176
177 def recurse_children( parent_id ):
178 if options.cluster is not None and rank_map[parent_id] == options.cluster:
179 # Short circuit if we found our rank, prevents 'hanging' no ranks from being output
180 # e.g. clustering by "species" (Escherichia coli), but have "no rank" below (Escherichia coli K-12) in test_db
181 return
182 if parent_id not in nodes:
183 nodes[parent_id] = BaseTree.Clade( name=_get_name( parent_id ), branch_length=branch_length )
184 for child_id in child_lists.get( parent_id, [] ):
185 if options.cluster is None or ( rank_map[child_id] <= options.cluster ):
186 if child_id not in nodes:
187 nodes[child_id] = BaseTree.Clade(name=_get_name( child_id ), branch_length=branch_length)
188 nodes[parent_id].clades.append(nodes[child_id])
189 recurse_children( child_id )
190 recurse_children( root_node_id )
191 tree = BaseTree.Tree(root=nodes[root_node_id])
192 Bio.Phylo.write( [tree], options.output_tree, 'newick' )
193
194
195 def __main__():
196 parser = optparse.OptionParser( usage="%prog [options] file1 file...fileN" )
197 parser.add_option( '-v', '--version', dest='version', action='store_true', default=False, help='print version and exit' )
198 parser.add_option( '', '--show-zeros', dest='show_zeros', action='store_true', default=False, help='Show empty nodes' )
199 parser.add_option( '', '--header-line', dest='header_line', action='store_true', default=False, help='Provide a header on output' )
200 parser.add_option( '', '--intermediate', dest='intermediate', action='store_true', default=False, help='Intermediate Ranks' )
201 parser.add_option( '', '--name-id', dest='name_id', action='store_true', default=False, help='Use Taxa ID instead of Name' )
202 parser.add_option( '', '--name-long', dest='name_long', action='store_true', default=False, help='Use Long taxa ID instead of base name' )
203 parser.add_option( '', '--taxonomy', dest='taxonomy', action='store_true', default=False, help='Output taxonomy in last column' )
204 parser.add_option( '', '--cluster', dest='cluster', action='store', type="string", default=None, help='Cluster counts to specified rank' )
205 parser.add_option( '', '--summation', dest='summation', action='store_true', default=False, help='Add summation of child counts to each taxa' )
206 parser.add_option( '', '--sanitize-names', dest='sanitize_names', action='store_true', default=False, help='Replace special chars (\t| |\||\.;) with underscore (_)' )
207 parser.add_option( '', '--show-rank', dest='show_rank', action='store_true', default=False, help='Output column with Rank name' )
208 parser.add_option( '', '--db', dest='db', action='store', type="string", default=None, help='Name of Kraken database' )
209 parser.add_option( '', '--output', dest='output', action='store', type="string", default=None, help='Name of output file' )
210 parser.add_option( '', '--output-tree', dest='output_tree', action='store', type="string", default=None, help='Name of output file to place newick tree' )
211 (options, args) = parser.parse_args()
212 if options.version:
213 print >> sys.stderr, "Kraken Taxonomy Report (%s) version %s" % ( __URL__, __VERSION__ )
214 sys.exit()
215 if not args:
216 print >> sys.stderr, parser.get_usage()
217 sys.exit()
218
219 if options.cluster:
220 cluster_name = options.cluster.lower()
221 cluster = RANK_NAME_TO_INTS.get( cluster_name, None )
222 assert cluster is not None, ValueError( '"%s" is not a valid rank for clustering.' % options.cluster )
223 if cluster_name not in PRIMARY_RANK_NAMES:
224 assert options.intermediate, ValueError( 'You cannot cluster by "%s", unless you enable intermediate ranks.' % options.cluster )
225 ranks_to_report = [ cluster ]
226 options.cluster = cluster
227 # When clustering we need to do summatation
228 options.summation = True
229 else:
230 options.cluster = None # make empty string into None
231 ranks_to_report = RANK_NAMES_INTS
232
233 if options.output:
234 output_fh = open( options.output, 'wb+' )
235 else:
236 output_fh = sys.stdout
237
238 db_path = get_kraken_db_path( options.db )
239 ( child_lists, name_map, rank_map ) = load_taxonomy( db_path, sanitize_names=options.sanitize_names )
240 file_data = []
241 hit_taxa = []
242 for input_filename in args:
243 taxo_counts = {}
244 with open( input_filename ) as fh:
245 for line in fh:
246 fields = line.split( "\t" )
247 taxo_counts[ fields[2] ] = taxo_counts.get( fields[2], 0 ) + 1
248 clade_counts = taxo_counts.copy() # fixme remove copying?
249 if options.summation:
250 dfs_summation( '1', clade_counts, child_lists )
251 for key, value in clade_counts.items():
252 if value and key not in hit_taxa:
253 hit_taxa.append( key )
254 file_data.append( clade_counts )
255
256 if options.header_line:
257 output_fh.write( "#ID\t" )
258 output_fh.write( "\t".join( args ) )
259 if options.show_rank:
260 output_fh.write( "\trank" )
261 if options.taxonomy:
262 output_fh.write( "\ttaxonomy" )
263 output_fh.write( '\n' )
264
265 output_lines = dict( [ ( x, [] ) for x in RANK_NAMES_INTS ] )
266 dfs_report( '1', file_data, hit_taxa, rank_map, name_map, child_lists, output_lines, options, name=None, tax=None )
267
268 for rank_int in ranks_to_report:
269 for line in output_lines.get( rank_int, [] ):
270 output_fh.write( line )
271 output_fh.write( '\n' )
272 fh.close()
273 if options.output_tree:
274 write_tree( child_lists, name_map, rank_map, options )
275
276
277 if __name__ == "__main__":
278 __main__()