Debian Codegraph @

airr/schema.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 AIRR Data Representation Schema
3 """
4
5 # Imports
6 import sys
7 import yaml
8 import yamlordereddictloader
9 from collections import OrderedDict
10 from pkg_resources import resource_stream
11
12 with resource_stream(__name__, 'specs/airr-schema.yaml') as f:
13 DEFAULT_SPEC = yaml.load(f, Loader=yamlordereddictloader.Loader)
14
15
16 class ValidationError(Exception):
17 """
18 Exception raised when validation errors are encountered.
19 """
20 pass
21
22
23 class Schema:
24 """
25 AIRR schema definitions
26
27 Attributes:
28 definition: name of the schema definition.
29 info (collections.OrderedDict): schema info.
30 properties (collections.OrderedDict): field definitions.
31 required (list): list of mandatory fields.
32 optional (list): list of non-required fields.
33 false_values (list): accepted string values for False.
34 true_values (list): accepted values for True.
35 """
36 # Boolean list for pandas
37 true_values = ['True', 'true', 'TRUE', 'T', 't', '1']
38 false_values = ['False', 'false', 'FALSE', 'F', 'f', '0']
39
40 # Generate dicts for booleans
41 _to_bool_map = {x: True for x in true_values + [1, True]}
42 _to_bool_map.update({x: False for x in false_values + [0, False]})
43 _from_bool_map = {k: 'T' if v else 'F' for k, v in _to_bool_map.items()}
44
45 def __init__(self, definition):
46 """
47 Initialization
48
49 Arguments:
50 definition (string): the schema definition to load.
51
52 Returns:
53 airr.schema.Schema : schema object.
54 """
55 # Info is not a valid schema
56 if definition == 'Info':
57 raise KeyError('Info is an invalid schema definition name')
58
59 # Load object definition
60 if isinstance(definition, dict): # on-the-fly definition of a nested object
61 self.definition = definition
62 spec = {'Info': []}
63 else:
64 spec = DEFAULT_SPEC
65
66 try:
67 self.definition = spec[definition]
68 except KeyError:
69 raise KeyError('Schema definition %s cannot be found in the specifications' % definition)
70 except:
71 raise
72
73 try:
74 self.info = spec['Info']
75 except KeyError:
76 raise KeyError('Info object cannot be found in the specifications')
77 except:
78 raise
79
80 if self.definition.get('properties') is not None:
81 self.properties = self.definition['properties']
82 try:
83 self.required = self.definition['required']
84 except KeyError:
85 self.required = []
86 except:
87 raise
88 elif self.definition.get('allOf') is not None:
89 self.properties = {}
90 self.required = []
91 for s in self.definition['allOf']:
92 if s.get('$ref') is not None:
93 schema_name = s['$ref'].split('/')[-1]
94 # cannot use cache here
95 schema = Schema(schema_name)
96 # no nested allOf ...
97 self.properties.update(schema.properties)
98 self.required.extend(schema.required)
99 elif s.get('properties') is not None:
100 self.properties.update(s.get('properties'))
101 if s.get('required') is not None:
102 self.required.extend(s.get('required'))
103 else:
104 raise KeyError('Cannot find properties for schema definition %s' % definition)
105
106 self.optional = [f for f in self.properties if f not in self.required]
107
108 def spec(self, field):
109 """
110 Get the properties for a field
111
112 Arguments:
113 name (str): field name.
114
115 Returns:
116 collections.OrderedDict: definition for the field.
117 """
118 return self.properties.get(field, None)
119
120 def type(self, field):
121 """
122 Get the type for a field
123
124 Arguments:
125 name (str): field name.
126
127 Returns:
128 str: the type definition for the field
129 """
130 field_spec = self.properties.get(field, None)
131 field_type = field_spec.get('type', None) if field_spec else None
132 return field_type
133
134 def pandas_types(self):
135 """
136 Map of schema types to pandas types
137
138 Returns:
139 dict: mapping dictionary for pandas types
140 """
141 type_mapping = {}
142 for property in self.properties:
143 if self.type(property) == 'boolean':
144 type_mapping[property] = bool
145 elif self.type(property) == 'integer':
146 type_mapping[property] = 'Int64'
147 elif self.type(property) == 'number':
148 type_mapping[property] = 'float64'
149 elif self.type(property) == 'string':
150 type_mapping[property] = str
151
152 return type_mapping
153
154 def to_bool(self, value, validate=False):
155 """
156 Convert a string to a boolean
157
158 Arguments:
159 value (str): logical value as a string.
160 validate (bool): when True raise a ValidationError for an invalid value.
161 Otherwise, set invalid values to None.
162
163 Returns:
164 bool: conversion of the string to True or False.
165
166 Raises:
167 airr.ValidationError: raised if value is invalid when validate is set True.
168 """
169 if value == '' or value is None:
170 return None
171
172 bool_value = self._to_bool_map.get(value, None)
173 if bool_value is None and validate:
174 raise ValidationError('invalid bool %s' % value)
175 else:
176 return bool_value
177
178 def from_bool(self, value, validate=False):
179 """
180 Converts a boolean to a string
181
182 Arguments:
183 value (bool): logical value.
184 validate (bool): when True raise a ValidationError for an invalid value.
185 Otherwise, set invalid values to None.
186
187 Returns:
188 str: conversion of True or False or 'T' or 'F'.
189
190 Raises:
191 airr.ValidationError: raised if value is invalid when validate is set True.
192 """
193 if value == '' or value is None:
194 return ''
195
196 str_value = self._from_bool_map.get(value, None)
197 if str_value is None and validate:
198 raise ValidationError('invalid bool %s' % value)
199 else:
200 return str_value
201
202 def to_int(self, value, validate=False):
203 """
204 Converts a string to an integer
205
206 Arguments:
207 value (str): integer value as a string.
208 validate (bool): when True raise a ValidationError for an invalid value.
209 Otherwise, set invalid values to None.
210
211 Returns:
212 int: conversion of the string to an integer.
213
214 Raises:
215 airr.ValidationError: raised if value is invalid when validate is set True.
216 """
217 if value == '' or value is None:
218 return None
219 if isinstance(value, int):
220 return value
221
222 try:
223 return int(value)
224 except ValueError:
225 if validate:
226 raise ValidationError('invalid int %s' % value)
227 else:
228 return None
229
230 def to_float(self, value, validate=False):
231 """
232 Converts a string to a float
233
234 Arguments:
235 value (str): float value as a string.
236 validate (bool): when True raise a ValidationError for an invalid value.
237 Otherwise, set invalid values to None.
238
239 Returns:
240 float: conversion of the string to a float.
241
242 Raises:
243 airr.ValidationError: raised if value is invalid when validate is set True.
244 """
245 if value == '' or value is None:
246 return None
247 if isinstance(value, float):
248 return value
249
250 try:
251 return float(value)
252 except ValueError:
253 if validate:
254 raise ValidationError('invalid float %s' % value)
255 else:
256 return None
257
258 def validate_header(self, header):
259 """
260 Validate header against the schema
261
262 Arguments:
263 header (list): list of header fields.
264
265 Returns:
266 bool: True if a ValidationError exception is not raised.
267
268 Raises:
269 airr.ValidationError: raised if header fails validation.
270 """
271 # Check for missing header
272 if header is None:
273 raise ValidationError('missing header')
274
275 # Check required fields
276 missing_fields = [f for f in self.required if f not in header]
277
278 if missing_fields:
279 raise ValidationError('missing required fields (%s)' % ', '.join(missing_fields))
280 else:
281 return True
282
283 def validate_row(self, row):
284 """
285 Validate Rearrangements row data against schema
286
287 Arguments:
288 row (dict): dictionary containing a single record.
289
290 Returns:
291 bool: True if a ValidationError exception is not raised.
292
293 Raises:
294 airr.ValidationError: raised if row fails validation.
295 """
296 for f in row:
297 # Empty strings are valid
298 if row[f] == '' or row[f] is None:
299 continue
300
301 # Check types
302 spec = self.type(f)
303 try:
304 if spec == 'boolean': self.to_bool(row[f], validate=True)
305 if spec == 'integer': self.to_int(row[f], validate=True)
306 if spec == 'number': self.to_float(row[f], validate=True)
307 except ValidationError as e:
308 raise ValidationError('field %s has %s' % (f, e))
309
310 return True
311
312 def validate_object(self, obj, missing=True, nonairr=True, context=None):
313 """
314 Validate Repertoire object data against schema
315
316 Arguments:
317 obj (dict): dictionary containing a single repertoire object.
318 missing (bool): provides warnings for missing optional fields.
319 nonairr (bool: provides warning for non-AIRR fields that cannot be validated.
320 context (string): used by recursion to indicate place in object hierarchy
321
322 Returns:
323 bool: True if a ValidationError exception is not raised.
324
325 Raises:
326 airr.ValidationError: raised if object fails validation.
327 """
328 # object has to be a dictionary
329 if not hasattr(obj, 'items'):
330 if context is None:
331 raise ValidationError('object is not a dictionary')
332 else:
333 raise ValidationError('field "%s" is not a dictionary object' % context)
334
335 # first warn about non-AIRR fields
336 if nonairr:
337 for f in obj:
338 if context is None: full_field = f
339 else: full_field = context + '.' + f
340 if self.properties.get(f) is None:
341 sys.stderr.write('Warning: Object has non-AIRR field that cannot be validated (' + full_field + ').\n')
342
343 # now walk through schema and check types
344 for f in self.properties:
345 if context is None: full_field = f
346 else: full_field = context + '.' + f
347 spec = self.spec(f)
348 xairr = spec.get('x-airr')
349
350 # check if deprecated
351 if xairr and xairr.get('deprecated'):
352 continue
353
354 # check if null and if key is missing
355 is_missing_key = False
356 is_null = False
357 if obj.get(f) is None:
358 is_null = True
359 if obj.get(f, 'missing') == 'missing':
360 is_missing_key = True
361
362 # check MiAIRR keys exist
363 if xairr and xairr.get('miairr'):
364 if is_missing_key:
365 raise ValidationError('MiAIRR field "%s" is missing' % full_field)
366
367 # check if required field
368 if f in self.required and is_missing_key:
369 raise ValidationError('Required field "%s" is missing' % full_field)
370
371 # check if identifier field
372 if xairr and xairr.get('identifier'):
373 if is_missing_key:
374 if xairr.get('nullable'):
375 sys.stderr.write(
376 'Warning: Nullable identifier field "%s" is missing.\n' % full_field)
377 else:
378 raise ValidationError('Not-nullable identifier field "%s" is missing' % full_field)
379
380 # check nullable requirements
381 if is_null:
382 if not xairr:
383 # default is true
384 continue
385 if xairr.get('nullable') or xairr.get('nullable', 'missing') == 'missing':
386 # nullable is allowed
387 continue
388 else:
389 # nullable not allowed
390 raise ValidationError('Non-nullable field "%s" is null or missing' % full_field)
391
392 # if get to here, field should exist with non null value
393
394 # check types
395 field_type = self.type(f)
396 if field_type is None:
397 # for referenced object, recursively call validate with object and schema
398 if spec.get('$ref') is not None:
399 schema_name = spec['$ref'].split('/')[-1]
400 if AIRRSchema.get(schema_name):
401 schema = AIRRSchema[schema_name]
402 else:
403 schema = Schema(schema_name)
404 schema.validate_object(obj[f], missing, nonairr, full_field)
405 else:
406 raise ValidationError('Internal error: field "%s" in schema not handled by validation. File a bug report.' % full_field)
407 elif field_type == 'array':
408 if not isinstance(obj[f], list):
409 raise ValidationError('field "%s" is not an array' % full_field)
410
411 # for array, check each object in it
412 for row in obj[f]:
413 if spec['items'].get('$ref') is not None:
414 schema_name = spec['items']['$ref'].split('/')[-1]
415 schema = Schema(schema_name)
416 schema.validate_object(row, missing, nonairr, full_field)
417 elif spec['items'].get('allOf') is not None:
418 for s in spec['items']['allOf']:
419 if s.get('$ref') is not None:
420 schema_name = s['$ref'].split('/')[-1]
421 if AIRRSchema.get(schema_name):
422 schema = AIRRSchema[schema_name]
423 else:
424 schema = Schema(schema_name)
425 schema.validate_object(row, missing, False, full_field)
426 elif spec['items'].get('enum') is not None:
427 if row not in spec['items']['enum']:
428 raise ValidationError('field "%s" has value "%s" not among possible enumeration values' % (full_field, row))
429 elif spec['items'].get('type') == 'string':
430 if not isinstance(row, str):
431 raise ValidationError('array field "%s" does not have string type: %s' % (full_field, row))
432 elif spec['items'].get('type') == 'boolean':
433 if not isinstance(row, bool):
434 raise ValidationError('array field "%s" does not have boolean type: %s' % (full_field, row))
435 elif spec['items'].get('type') == 'integer':
436 if not isinstance(row, int):
437 raise ValidationError('array field "%s" does not have integer type: %s' % (full_field, row))
438 elif spec['items'].get('type') == 'number':
439 if not isinstance(row, float) and not isinstance(row, int):
440 raise ValidationError('array field "%s" does not have number type: %s' % (full_field, row))
441 elif spec['items'].get('type') == 'object':
442 sub_schema = Schema({'properties': spec['items'].get('properties')})
443 sub_schema.validate_object(row, missing, nonairr, context)
444 else:
445 raise ValidationError('Internal error: array field "%s" in schema not handled by validation. File a bug report.' % full_field)
446 elif field_type == 'object':
447 # right now all arrays of objects use $ref
448 raise ValidationError('Internal error: field "%s" in schema not handled by validation. File a bug report.' % full_field)
449 else:
450 # check basic types
451 if field_type == 'string':
452 if not isinstance(obj[f], str):
453 raise ValidationError('Field "%s" does not have string type: %s' % (full_field, obj[f]))
454 elif field_type == 'boolean':
455 if not isinstance(obj[f], bool):
456 raise ValidationError('Field "%s" does not have boolean type: %s' % (full_field, obj[f]))
457 elif field_type == 'integer':
458 if not isinstance(obj[f], int):
459 raise ValidationError('Field "%s" does not have integer type: %s' % (full_field, obj[f]))
460 elif field_type == 'number':
461 if not isinstance(obj[f], float) and not isinstance(obj[f], int):
462 raise ValidationError('Field "%s" does not have number type: %s' % (full_field, obj[f]))
463 else:
464 raise ValidationError('Internal error: Field "%s" with type %s in schema not handled by validation. File a bug report.' % (full_field, field_type))
465
466 # check basic types enums
467 enums = spec.get('enum')
468
469 if enums is not None:
470 field_value = obj[f]
471 if field_value not in enums:
472 raise ValidationError(
473 'field "%s" has value "%s" not among possible enumeration values %s' % (full_field, field_value, enums)
474 )
475
476 return True
477
478 def template(self):
479 """
480 Create an empty template object
481
482 Returns:
483 collections.OrderedDict: dictionary with all schema properties set as None or an empty list.
484 """
485 # Set defaults for each data type
486 type_default = {'boolean': False, 'integer': 0, 'number': 0.0, 'string': '', 'array':[]}
487
488 # Fetch schema template definition for a $ref string
489 def _reference(ref):
490 x = ref.split('/')[-1]
491 schema = AIRRSchema.get(x, Schema(x))
492 return(schema.template())
493
494 # Get default value
495 def _default(spec):
496 if 'nullable' in spec['x-airr'] and not spec['x-airr']['nullable']:
497 if 'enum' in spec:
498 return spec['enum'][0]
499 else:
500 return type_default.get(spec['type'], None)
501 else:
502 return None
503
504 # Populate empty object
505 object = OrderedDict()
506 for k, spec in self.properties.items():
507 # Skip deprecated
508 if 'x-airr' in spec and spec['x-airr'].get('deprecated', False):
509 continue
510
511 # Population values
512 if '$ref' in spec:
513 object[k] = _reference(spec['$ref'])
514 elif spec['type'] == 'array':
515 if '$ref' in spec['items']:
516 object[k] = [_reference(spec['items']['$ref'])]
517 else:
518 object[k] = []
519 elif 'x-airr' in spec:
520 object[k] = _default(spec)
521 else:
522 object[k] = None
523
524 return(object)
525
526
527 # Preloaded schema
528 AIRRSchema = {
529 'Info': Schema('InfoObject'),
530 'DataFile': Schema('DataFile'),
531 'Alignment': Schema('Alignment'),
532 'Rearrangement': Schema('Rearrangement'),
533 'Repertoire': Schema('Repertoire'),
534 'RepertoireGroup': Schema('RepertoireGroup'),
535 'Ontology': Schema('Ontology'),
536 'Study': Schema('Study'),
537 'Subject': Schema('Subject'),
538 'Diagnosis': Schema('Diagnosis'),
539 'SampleProcessing': Schema('SampleProcessing'),
540 'CellProcessing': Schema('CellProcessing'),
541 'PCRTarget': Schema('PCRTarget'),
542 'NucleicAcidProcessing': Schema('NucleicAcidProcessing'),
543 'SequencingRun': Schema('SequencingRun'),
544 'SequencingData': Schema('SequencingData'),
545 'DataProcessing': Schema('DataProcessing'),
546 'GermlineSet': Schema('GermlineSet'),
547 'Acknowledgement': Schema('Acknowledgement'),
548 'RearrangedSequence': Schema('RearrangedSequence'),
549 'UnrearrangedSequence': Schema('UnrearrangedSequence'),
550 'SequenceDelineationV': Schema('SequenceDelineationV'),
551 'AlleleDescription': Schema('AlleleDescription'),
552 'GenotypeSet': Schema('GenotypeSet'),
553 'Genotype': Schema('Genotype'),
554 'Cell': Schema('Cell'),
555 'Clone': Schema('Clone')
556 }
557
558 InfoSchema = AIRRSchema['Info']
559 DataFileSchema = AIRRSchema['DataFile']
560 AlignmentSchema = AIRRSchema['Alignment']
561 RearrangementSchema = AIRRSchema['Rearrangement']
562 RepertoireSchema = AIRRSchema['Repertoire']
563 GermlineSetSchema = AIRRSchema['GermlineSet']
564 GenotypeSetSchema = AIRRSchema['GenotypeSet']