Debian Codegraph @

biom/cli/table_converter.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 import load_table
13 from biom.cli import cli
14 from biom.cli.util import write_biom_table
15 from biom.parse import MetadataMap
16
17
18 table_types = ["OTU table",
19 "Pathway table",
20 "Function table",
21 "Ortholog table",
22 "Gene table",
23 "Metabolite table",
24 "Taxon table",
25 "Table"]
26
27 observation_metadata_types = {
28 'sc_separated': lambda x: [e.strip() for e in x.split(';')],
29 'naive': lambda x: x
30 }
31 observation_metadata_types['taxonomy'] = \
32 observation_metadata_types['sc_separated']
33
34 observation_metadata_formatters = {
35 'sc_separated': lambda x: '; '.join(x),
36 'naive': lambda x: x
37 }
38
39
40 @cli.command(name='convert')
41 @click.option('-i', '--input-fp', required=True,
42 type=click.Path(exists=True, dir_okay=False),
43 help='The input BIOM table')
44 @click.option('-o', '--output-fp', required=True,
45 type=click.Path(exists=False, dir_okay=False),
46 help='The output BIOM table')
47 @click.option('-m', '--sample-metadata-fp', required=False,
48 type=click.Path(exists=True, dir_okay=False),
49 help='The sample metadata mapping file (will add sample '
50 'metadata to the input BIOM table, if provided).')
51 @click.option('--observation-metadata-fp', required=False,
52 type=click.Path(exists=True, dir_okay=False),
53 help='The observation metadata mapping file (will add '
54 'observation metadata to the input BIOM table, if '
55 'provided).')
56 @click.option('--to-json', default=False, is_flag=True,
57 help='Output as JSON-formatted table.')
58 @click.option('--to-hdf5', default=False, is_flag=True,
59 help='Output as HDF5-formatted table.')
60 @click.option('--to-tsv', default=False, is_flag=True,
61 help='Output as TSV-formatted (classic) table.')
62 @click.option('--collapsed-samples', default=False, is_flag=True,
63 help='If --to_hdf5 is passed and the original table is a '
64 'BIOM table with collapsed samples, this will '
65 'update the sample metadata of the table to '
66 'the supported HDF5 collapsed format.')
67 @click.option('--collapsed-observations', default=False, is_flag=True,
68 help='If --to_hdf5 is passed and the original table is a '
69 'BIOM table with collapsed observations, this will '
70 'update the observation metadata of the table '
71 'to the supported HDF5 collapsed format.')
72 @click.option('--header-key', required=False, type=click.STRING,
73 help='The observation metadata to include from the input '
74 'BIOM table file when creating a tsv table file. '
75 'By default no observation metadata will be included.')
76 @click.option('--output-metadata-id', required=False, type=click.STRING,
77 help='The name to be given to the observation metadata '
78 'column when creating a tsv table file if the column '
79 'should be renamed.')
80 @click.option('--table-type', required=False,
81 type=click.Choice(table_types),
82 help='The type of the table.')
83 @click.option('--process-obs-metadata', required=False,
84 type=click.Choice(
85 observation_metadata_types),
86 help='Process metadata associated with observations when '
87 'converting from a classic table.')
88 @click.option('--tsv-metadata-formatter', required=False,
89 default='sc_separated',
90 type=click.Choice(
91 observation_metadata_formatters),
92 help='Method for formatting the observation metadata.')
93 def convert(input_fp, output_fp, sample_metadata_fp, observation_metadata_fp,
94 to_json, to_hdf5, to_tsv, collapsed_samples,
95 collapsed_observations, header_key, output_metadata_id, table_type,
96 process_obs_metadata, tsv_metadata_formatter):
97 """Convert to/from the BIOM table format.
98
99 Convert between BIOM table formats. See examples here:
100 http://biom-format.org/documentation/biom_conversion.html
101
102 Example usage:
103
104 Convert a "classic" BIOM file (tab-separated text) to an HDF5 BIOM
105 formatted OTU table:
106
107 $ biom convert -i table.txt -o table.biom --to-hdf5
108 """
109 if sum([to_tsv, to_hdf5, to_json]) > 1:
110 raise ValueError("--to-tsv, --to-json, and --to-hdf5 are mutually "
111 "exclusive. You can only pass one of these options.")
112
113 table = load_table(input_fp)
114 if sample_metadata_fp is not None:
115 with open(sample_metadata_fp) as f:
116 sample_metadata_f = MetadataMap.from_file(f)
117 else:
118 sample_metadata_f = None
119 if observation_metadata_fp is not None:
120 with open(observation_metadata_fp) as f:
121 observation_metadata_f = MetadataMap.from_file(f)
122 else:
123 observation_metadata_f = None
124
125 _convert(table, output_fp, sample_metadata_f, observation_metadata_f,
126 to_json, to_hdf5, to_tsv, collapsed_samples,
127 collapsed_observations, header_key, output_metadata_id,
128 table_type, process_obs_metadata, tsv_metadata_formatter)
129
130
131 def _convert(table, output_filepath, sample_metadata=None,
132 observation_metadata=None, to_json=False, to_hdf5=False,
133 to_tsv=False, collapsed_samples=False,
134 collapsed_observations=False, header_key=None,
135 output_metadata_id=None, table_type=None,
136 process_obs_metadata=None, tsv_metadata_formatter='sc_separated'):
137
138 if sum([to_tsv, to_hdf5, to_json]) == 0:
139 raise ValueError("Must specify an output format")
140 elif sum([to_tsv, to_hdf5, to_json]) > 1:
141 raise ValueError("Can only specify a single output format")
142
143 if table_type is None:
144 if table.type in [None, "None"]:
145 table.type = "Table"
146 else:
147 pass
148 else:
149 table.type = table_type
150
151 if tsv_metadata_formatter is not None:
152 obs_md_fmt_f = observation_metadata_formatters[tsv_metadata_formatter]
153
154 if sample_metadata is not None:
155 table.add_metadata(sample_metadata)
156
157 # if the user does not specify a name for the output metadata column,
158 # set it to the same as the header key
159 output_metadata_id = output_metadata_id or header_key
160
161 if process_obs_metadata is not None and not to_tsv:
162 if table.metadata(axis='observation') is None:
163 raise ValueError("Observation metadata processing requested "
164 "but it doesn't appear that there is any "
165 "metadata to operate on!")
166
167 # and if this came in as TSV, then we expect only a single type of
168 # metadata
169 md_key = list(table.metadata(axis='observation')[0].keys())[0]
170
171 process_f = observation_metadata_types[process_obs_metadata]
172 it = zip(table.ids(axis='observation'),
173 table.metadata(axis='observation'))
174 new_md = {id_: {md_key: process_f(md[md_key])} for id_, md in it}
175
176 if observation_metadata:
177 for k, v in observation_metadata.items():
178 new_md[k].update(v)
179 table.add_metadata(new_md, 'observation')
180
181 if to_tsv:
182 result = table.to_tsv(header_key=header_key,
183 header_value=output_metadata_id,
184 metadata_formatter=obs_md_fmt_f)
185 with open(output_filepath, 'w') as f:
186 f.write(result)
187 return
188 elif to_json:
189 fmt = 'json'
190 result = table
191 elif to_hdf5:
192 fmt = 'hdf5'
193 result = table
194 if collapsed_observations:
195 metadata = [{'collapsed_ids': sorted(md.keys())}
196 for md in result.metadata(axis='observation')]
197 result._observation_metadata = metadata
198 if collapsed_samples:
199 metadata = [{'collapsed_ids': sorted(md.keys())}
200 for md in result.metadata()]
201 result._sample_metadata = metadata
202 if collapsed_observations or collapsed_samples:
203 # We have changed the metadata, it is safer to make sure that
204 # it is correct
205 result._cast_metadata()
206 write_biom_table(result, fmt, output_filepath)
207
208 return