Debian Codegraph @

biom/cli/table_validator.py

raw
1 #!/usr/bin/env python
2 # -----------------------------------------------------------------------------
3 # Copyright (c) 2011-2017, The BIOM Format Development Team.
4 #
5 # Distributed under the terms of the Modified BSD License.
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
8 # -----------------------------------------------------------------------------
9
10 import json
11 import sys
12 import h5py
13 from datetime import datetime
14 from operator import and_
15 from functools import reduce
16
17 import click
18 import numpy as np
19
20 from biom.cli import cli
21 from biom.util import biom_open, is_hdf5_file
22
23
24 @cli.command(name='validate-table')
25 @click.option('-i', '--input-fp', required=True,
26 type=click.Path(exists=True, dir_okay=False),
27 help='The input filepath to validate against the BIOM format'
28 ' specification')
29 @click.option('-f', '--format-version', default=None,
30 help='The specific format version to validate against')
31 def validate_table(input_fp, format_version):
32 """Validate a BIOM-formatted file.
33
34 Test a file for adherence to the Biological Observation Matrix (BIOM)
35 format specification. This specification is defined at
36 http://biom-format.org
37
38 Example usage:
39
40 Validate the contents of table.biom for adherence to the BIOM format
41 specification
42
43 $ biom validate-table -i table.biom
44
45 """
46 valid, report = _validate_table(input_fp, format_version)
47 click.echo("\n".join(report))
48 if valid:
49 # apparently silence is too quiet to be golden.
50 click.echo("The input file is a valid BIOM-formatted file.")
51 sys.exit(0)
52 else:
53 click.echo("The input file is not a valid BIOM-formatted file.")
54 sys.exit(1)
55
56
57 def _validate_table(input_fp, format_version=None):
58 result = TableValidator()(table=input_fp, format_version=format_version)
59 return result['valid_table'], result['report_lines']
60
61
62 # Refactor in the future. Also need to address #664
63 class TableValidator:
64
65 FormatURL = "http://biom-format.org"
66 TableTypes = {
67 'otu table',
68 'pathway table',
69 'function table',
70 'ortholog table',
71 'gene table',
72 'metabolite table',
73 'taxon table',
74 }
75 MatrixTypes = {'sparse', 'dense'}
76 ElementTypes = {'int': int, 'str': str, 'float': float, 'unicode': str}
77 HDF5FormatVersions = {(2, 0), (2, 0, 0), (2, 1), (2, 1, 0)}
78
79 def run(self, **kwargs):
80 is_json = not is_hdf5_file(kwargs['table'])
81
82 if kwargs['format_version'] in [None, 'None']:
83 if is_json:
84 kwargs['format_version'] = '1.0.0'
85 else:
86 kwargs['format_version'] = '2.1'
87 elif is_json:
88 if kwargs['format_version'] != "1.0.0":
89 raise ValueError("Only format 1.0.0 is valid for JSON")
90 else:
91 fmt_ver = [int(v) for v in kwargs['format_version'].split('.')]
92 if tuple(fmt_ver) not in self.HDF5FormatVersions:
93 raise ValueError("Unrecognized format version: %s" %
94 kwargs['format_version'])
95
96 with biom_open(kwargs['table']) as f:
97 if is_json:
98 try:
99 kwargs['table'] = json.load(f)
100 except ValueError:
101 # if we hit this, we've already determined the file is
102 # not hdf5, so if it also is not json then it cannot be
103 # a valid biom-format file with the current formats.
104 raise ValueError("The provided table does not appear to "
105 "be biom-format 1.0.0, 2.0.0 or 2.1.0.")
106 return self._validate_json(**kwargs)
107 else:
108 kwargs['table'] = f
109
110 if not isinstance(f, h5py.File):
111 print("Attempting to validate an HDF5 BIOM table, but the "
112 "table does not appear to be in HDF5 format!")
113 sys.exit(1)
114 return self._validate_hdf5(**kwargs)
115
116 def __call__(self, table, format_version=None):
117 return self.run(table=table, format_version=format_version)
118
119 def _validate_hdf5(self, **kwargs):
120 table = kwargs['table']
121
122 report_lines = []
123 valid_table = True
124
125 required_attrs = [
126 ('format-url', self._valid_format_url),
127 ('format-version', self._valid_hdf5_format_version),
128 ('type', self._valid_type),
129 ('shape', self._valid_shape),
130 ('nnz', self._valid_nnz),
131 ('generated-by', self._valid_generated_by),
132 ('id', self._valid_nullable_id),
133 ('creation-date', self._valid_creation_date)
134 ]
135
136 required_groups = ['observation', 'sample',
137 'observation/matrix', 'sample/matrix']
138
139 required_datasets = ['observation/ids',
140 'observation/matrix/data',
141 'observation/matrix/indices',
142 'observation/matrix/indptr',
143 'sample/ids',
144 'sample/matrix/data',
145 'sample/matrix/indices',
146 'sample/matrix/indptr']
147
148 for required_attr, attr_validator in required_attrs:
149 if required_attr not in table.attrs:
150 valid_table = False
151 report_lines.append("Missing attribute: '%s'" % required_attr)
152 continue
153
154 status_msg = attr_validator(table)
155
156 if len(status_msg) > 0:
157 valid_table = False
158 report_lines.append(status_msg)
159
160 for group in required_groups:
161 if group not in table:
162 report_lines.append("Missing required '%s' group" % group)
163 valid_table = False
164
165 for dataset in required_datasets:
166 if dataset not in table:
167 report_lines.append("Missing required '%s' dataset" % dataset)
168 valid_table = False
169
170 if 'shape' in table.attrs:
171 n_obs, n_samp = table.attrs['shape']
172 obs_ids = table.get('observation/ids', None)
173 samp_ids = table.get('sample/ids', None)
174
175 if obs_ids is None:
176 valid_table = False
177 report_lines.append("observation/ids does not exist, cannot "
178 "validate shape")
179
180 if samp_ids is None:
181 valid_table = False
182 report_lines.append("sample/ids does not exist, cannot "
183 "validate shape")
184
185 if n_obs != len(obs_ids):
186 valid_table = False
187 report_lines.append("Number of observation IDs is not equal "
188 "to the described shape")
189
190 if n_samp != len(samp_ids):
191 valid_table = False
192 report_lines.append("Number of sample IDs is not equal "
193 "to the described shape")
194 else:
195 report_lines.append("Missing 'shape' attribute")
196 valid_table = False
197
198 if 'format-version' in table.attrs:
199 t_ver = '.'.join([str(v) for v in table.attrs['format-version']])
200 if kwargs['format_version'] in ['2.0', '2.0.0']:
201 if t_ver != '2.0':
202 error = "Table indicates it is version %s" % t_ver
203 else:
204 report_lines.append("WARNING: 2.0 is not actively "
205 "supported!")
206 error = self._valid_hdf5_metadata_v200(table)
207
208 if error is not None:
209 report_lines.append(error)
210 else:
211 if t_ver != '2.1':
212 error = "Table indicates it is version %s" % t_ver
213 else:
214 error = self._valid_hdf5_metadata_v210(table)
215
216 if error is not None:
217 report_lines.append(error)
218
219 return {'valid_table': valid_table, 'report_lines': report_lines}
220
221 def _valid_hdf5_metadata_v200(self, table):
222 no_md = np.array(["[]"])
223 try:
224 json.loads(table['observation'].get('metadata', no_md)[0])
225 except ValueError:
226 return ("Observation metadata do not appear to be formatted"
227 " correctly")
228
229 try:
230 json.loads(table['sample'].get('metadata', no_md)[0])
231 except ValueError:
232 return ("Sample metadata do not appear to be formatted"
233 " correctly")
234
235 def _valid_hdf5_metadata_v210(self, table):
236 if 'observation/metadata' not in table:
237 return "Observation/metadata group is missing"
238 if 'observation/group-metadata' not in table:
239 return "Observation/group-metadata is missing"
240 if 'sample/metadata' not in table:
241 return "Sample/metadata group is missing"
242 if 'sample/group-metadata' not in table:
243 return "Sample/group-metadata is missing"
244
245 n_obs_ids = len(table['observation/ids'])
246 n_samp_ids = len(table['sample/ids'])
247 for name, ds in table['observation/metadata'].items():
248 if len(ds) != n_obs_ids:
249 return "%s has %d entries, but expected %d" % (name, len(ds),
250 n_obs_ids)
251 for name, ds in table['sample/metadata'].items():
252 if len(ds) != n_samp_ids:
253 return "%s has %d entries, but expected %d" % (name, len(ds),
254 n_samp_ids)
255
256 def _validate_json(self, **kwargs):
257 table_json = kwargs['table']
258
259 # Need to make this an attribute so that we have this info during
260 # validation.
261 self._format_version = kwargs['format_version']
262
263 report_lines = []
264 valid_table = True
265
266 required_keys = [
267 ('format', self._valid_format),
268 ('format_url', self._valid_format_url),
269 ('type', self._valid_type),
270 ('rows', self._valid_rows),
271 ('columns', self._valid_columns),
272 ('shape', self._valid_shape),
273 ('data', self._valid_data),
274 ('matrix_type', self._valid_matrix_type),
275 ('matrix_element_type', self._valid_matrix_element_type),
276 ('generated_by', self._valid_generated_by),
277 ('id', self._valid_nullable_id),
278 ('date', self._valid_datetime)
279 ]
280
281 for key, method in required_keys:
282 if key not in table_json:
283 valid_table = False
284 report_lines.append("Missing field: '%s'" % key)
285 continue
286
287 status_msg = method(table_json)
288
289 if len(status_msg) > 0:
290 valid_table = False
291 report_lines.append(status_msg)
292
293 if 'shape' in table_json:
294 if ('rows' in table_json and
295 len(table_json['rows']) != table_json['shape'][0]):
296 valid_table = False
297 report_lines.append("Number of rows in 'rows' is not equal to "
298 "'shape'")
299
300 if ('columns' in table_json and
301 len(table_json['columns']) != table_json['shape'][1]):
302 valid_table = False
303 report_lines.append("Number of columns in 'columns' is not "
304 "equal to 'shape'")
305
306 return {'valid_table': valid_table, 'report_lines': report_lines}
307
308 def _json_or_hdf5_get(self, table, key):
309 if hasattr(table, 'attrs'):
310 item = table.attrs.get(key, None)
311 if item is not None and isinstance(item, bytes):
312 item = item.decode('utf8')
313 return item
314 else:
315 return table.get(key, None)
316
317 def _json_or_hdf5_key(self, table, key):
318 if hasattr(table, 'attrs'):
319 return key.replace('_', '-')
320 else:
321 return key
322
323 def _is_int(self, x):
324 """Return True if x is an int or numpy int"""
325 return np.issubdtype(type(x), np.integer)
326
327 def _valid_nnz(self, table):
328 """Check if nnz seems correct"""
329 if not self._is_int(table.attrs['nnz']):
330 return "nnz is not an integer!"
331 if table.attrs['nnz'] < 0:
332 return "nnz is negative!"
333 return ''
334
335 def _valid_format_url(self, table):
336 """Check if format_url is correct"""
337 key = self._json_or_hdf5_key(table, 'format_url')
338 value = self._json_or_hdf5_get(table, key)
339
340 if value != self.FormatURL:
341 return "Invalid '%s'" % key
342 else:
343 return ''
344
345 def _valid_shape(self, table):
346 """Matrix header is (int, int) representing the size of a 2D matrix"""
347 a, b = self._json_or_hdf5_get(table, 'shape')
348
349 if not (self._is_int(a) and self._is_int(b)):
350 return "'shape' values do not appear to be integers"
351 else:
352 return ''
353
354 def _valid_matrix_type(self, table_json):
355 """Check if a valid matrix type exists"""
356 if table_json['matrix_type'] not in self.MatrixTypes:
357 return "Unknown 'matrix_type'"
358 else:
359 return ''
360
361 def _valid_matrix_element_type(self, table_json):
362 """Check if a valid element type exists"""
363 if table_json['matrix_element_type'] not in self.ElementTypes:
364 return "Unknown 'matrix_element_type'"
365 else:
366 return ''
367
368 def _valid_date(self, val):
369 valid_times = ["%Y-%m-%d",
370 "%Y-%m-%dT%H:%M",
371 "%Y-%m-%dT%H:%M:%S",
372 "%Y-%m-%dT%H:%M:%S.%f"]
373 if isinstance(val, bytes):
374 val = val.decode('utf8')
375
376 valid_time = False
377 for fmt in valid_times:
378 try:
379 datetime.strptime(val, fmt)
380 valid_time = True
381 break
382 except: # noqa
383 pass
384
385 if valid_time:
386 return ''
387 else:
388 return "Timestamp does not appear to be ISO 8601"
389
390 def _valid_creation_date(self, table):
391 """Verify datetime can be parsed
392
393 Expects ISO 8601 datetime format (for example, 2011-12-19T19:00:00
394 note that a 'T' separates the date
395 and time)
396 """
397 return self._valid_date(table.attrs['creation-date'])
398
399 def _valid_datetime(self, table):
400 """Verify datetime can be parsed
401
402 Expects ISO 8601 datetime format (for example, 2011-12-19T19:00:00
403 note that a 'T' separates the date
404 and time)
405 """
406 return self._valid_date(table['date'])
407
408 def _valid_sparse_data(self, table_json):
409 """All index positions must be integers and values are of dtype"""
410 dtype = self.ElementTypes[table_json['matrix_element_type']]
411 n_rows, n_cols = table_json['shape']
412 n_rows -= 1 # adjust for 0-based index
413 n_cols -= 1 # adjust for 0-based index
414
415 for idx, coord in enumerate(table_json['data']):
416 try:
417 x, y, val = coord
418 except: # noqa
419 return "Bad matrix entry idx %d: %s" % (idx, repr(coord))
420
421 if not self._is_int(x) or not self._is_int(y):
422 return "Bad x or y type at idx %d: %s" % (idx, repr(coord))
423
424 if not isinstance(val, dtype):
425 return "Bad value at idx %d: %s" % (idx, repr(coord))
426
427 if x < 0 or x > n_rows:
428 return "x out of bounds at idx %d: %s" % (idx, repr(coord))
429
430 if y < 0 or y > n_cols:
431 return "y out of bounds at idx %d: %s" % (idx, repr(coord))
432
433 return ''
434
435 def _valid_dense_data(self, table_json):
436 """All elements must be of dtype and correspond to shape"""
437 dtype = self.ElementTypes[table_json['matrix_element_type']]
438 n_rows, n_cols = table_json['shape']
439
440 for row in table_json['data']:
441 if len(row) != n_cols:
442 return "Incorrect number of cols: %s" % repr(row)
443
444 if not reduce(and_, [isinstance(v, dtype) for v in row]):
445 return "Bad datatype in row: %s" % repr(row)
446
447 if len(table_json['data']) != n_rows:
448 return "Incorrect number of rows in matrix"
449
450 return ''
451
452 def _valid_hdf5_format_version(self, table):
453 """Format must be the expected version"""
454 ver = table.attrs['format-version']
455 if tuple(ver) not in self.HDF5FormatVersions:
456 return "Invalid format version '%s'" % str(ver)
457 else:
458 return ""
459
460 def _valid_format(self, table_json):
461 """Format must be the expected version"""
462 formal = f"Biological Observation Matrix {self._format_version}"
463
464 if table_json['format'] not in [formal, self._format_version]:
465 return f"Invalid format '{table_json['format']}', must be '{self._format_version}'" # noqa: E501
466 else:
467 return ''
468
469 def _valid_type(self, table):
470 """Table must be a known table type"""
471 key = self._json_or_hdf5_key(table, 'type')
472 value = self._json_or_hdf5_get(table, key)
473 if value is None or value == "":
474 return "Unknown table type, however that is likely okay."
475 if value.lower() not in self.TableTypes:
476 return "Unknown BIOM type: %s" % value
477 else:
478 return ''
479
480 def _valid_generated_by(self, table):
481 """Validate the generated_by field"""
482 key = self._json_or_hdf5_key(table, 'generated_by')
483 value = self._json_or_hdf5_get(table, key)
484 if not value:
485 return "'generated_by' is not populated"
486
487 return ''
488
489 def _valid_nullable_id(self, table_json):
490 """Validate the table id"""
491 # this is nullable and don't actually care what is in here
492 return ''
493
494 def _valid_id(self, record):
495 """Validate id for a row or column"""
496 if not record['id']:
497 return "'id' in %s appears empty" % record
498 else:
499 return ''
500
501 def _valid_metadata(self, record):
502 """Validate the metadata field for a row or column"""
503 # this is nullable and don't actually care what is in here
504 if record['metadata'] is None:
505 return ''
506 if isinstance(record['metadata'], dict):
507 return ''
508
509 return "metadata is neither null or an object"
510
511 def _valid_rows(self, table_json):
512 """Validate the 'rows' under 'table'"""
513 required_keys = [('id', self._valid_id),
514 ('metadata', self._valid_metadata)]
515 required_by_type = {}
516 ttype = table_json.get('type')
517 if ttype is None:
518 ttype = ""
519 required_keys.extend(
520 required_by_type.get(ttype.lower(), []))
521
522 for idx, row in enumerate(table_json['rows']):
523 for key, method in required_keys:
524 if key not in row:
525 return "ROW IDX %d MISSING '%s' FIELD" % (idx, key)
526
527 result = method(row)
528 if len(result) > 0:
529 return result
530 return ''
531
532 def _valid_columns(self, table_json):
533 """Validate the 'columns' under 'table'"""
534 required_keys = [('id', self._valid_id),
535 ('metadata', self._valid_metadata)]
536 required_by_type = {}
537 ttype = table_json.get('type')
538 if ttype is None:
539 ttype = ""
540 required_keys.extend(
541 required_by_type.get(ttype.lower(), []))
542
543 for idx, col in enumerate(table_json['columns']):
544 for key, method in required_keys:
545 if key not in col:
546 return "COL IDX %d MISSING '%s' FIELD" % (idx, key)
547
548 result = method(col)
549 if len(result) > 0:
550 return result
551 return ''
552
553 def _valid_data(self, table_json):
554 """Validate the 'matrix' under 'table'"""
555 if table_json['matrix_type'].lower() == 'sparse':
556 return self._valid_sparse_data(table_json)
557 elif table_json['matrix_type'].lower() == 'dense':
558 return self._valid_dense_data(table_json)
559 else:
560 return "Unknown matrix type"