Debian Codegraph @

biom/cli/uc_processor.py

raw
1 # ----------------------------------------------------------------------------
2 # Copyright (c) 2011-2017, The BIOM Format Development Team.
3 #
4 # Distributed under the terms of the Modified BSD License.
5 #
6 # The full license is in the file COPYING.txt, distributed with this software.
7 # ----------------------------------------------------------------------------
8
9
10 import click
11
12 from biom.cli import cli
13 from biom.cli.util import write_biom_table
14 from biom.parse import parse_uc
15 from biom.exception import TableException
16
17
18 @cli.command('from-uc')
19 @click.option('-i', '--input-fp', required=True,
20 type=click.Path(exists=True, dir_okay=False),
21 help='The input uc filepath.')
22 @click.option('-o', '--output-fp', required=True,
23 type=click.Path(writable=True),
24 help='The output BIOM filepath')
25 @click.option('--rep-set-fp', type=click.Path(exists=True, dir_okay=False),
26 help="Fasta file containing representative sequences with "
27 "where sequences are labeled with OTU identifiers, and "
28 "description fields contain original sequence identifiers. "
29 "This output is created, for example, by vsearch with the "
30 "--relabel_sha1 --relabel_keep options.",
31 required=False)
32 def from_uc(input_fp, output_fp, rep_set_fp):
33 """Create a BIOM table from a vsearch/uclust/usearch BIOM file.
34
35 Example usage:
36
37 Simple BIOM creation:
38
39 $ biom from-uc -i in.uc -o out.biom
40
41 BIOM creation with OTU re-naming:
42
43 $ biom from-uc -i in.uc -o out.biom --rep-set-fp rep-set.fna
44
45 """
46 input_f = open(input_fp)
47 if rep_set_fp is not None:
48 rep_set_f = open(rep_set_fp)
49 else:
50 rep_set_f = None
51 table = _from_uc(input_f, rep_set_f)
52 write_biom_table(table, 'hdf5', output_fp)
53
54
55 def _id_map_from_fasta(fasta_lines):
56 result = {}
57 for line in fasta_lines:
58 if line.startswith('>'):
59 try:
60 obs_id, seq_id = line.split()[:2]
61 except ValueError:
62 raise ValueError('Sequence identifiers in fasta file '
63 'must contain at least two space-'
64 'separated fields.')
65 result[seq_id] = obs_id[1:]
66 else:
67 pass
68 return result
69
70
71 def _from_uc(input_f, rep_set_f=None):
72 table = parse_uc(input_f)
73
74 if rep_set_f is not None:
75 obs_id_map = _id_map_from_fasta(rep_set_f)
76 try:
77 table.update_ids(obs_id_map, axis='observation', strict=True,
78 inplace=True)
79 except TableException:
80 raise ValueError('Not all sequence identifiers in the input BIOM '
81 'file are present in description fields in the '
82 'representative sequence fasta file.')
83
84 return table