| 1 |
""" |
| 2 |
Interface functions for file operations |
| 3 |
""" |
| 4 |
from __future__ import absolute_import |
| 5 |
|
| 6 |
# System imports |
| 7 |
import gzip |
| 8 |
import json |
| 9 |
import sys |
| 10 |
import pandas as pd |
| 11 |
import yaml |
| 12 |
import yamlordereddictloader |
| 13 |
from collections import OrderedDict |
| 14 |
from itertools import chain |
| 15 |
from io import open |
| 16 |
from warnings import warn |
| 17 |
|
| 18 |
if (sys.version_info > (3, 0)): |
| 19 |
from io import StringIO |
| 20 |
else: |
| 21 |
# Python 2 code in this block |
| 22 |
from io import BytesIO as StringIO |
| 23 |
|
| 24 |
# Load imports |
| 25 |
from airr.io import RearrangementReader, RearrangementWriter |
| 26 |
from airr.schema import Schema, RearrangementSchema, RepertoireSchema, AIRRSchema, DataFileSchema, ValidationError |
| 27 |
|
| 28 |
#### Rearrangement #### |
| 29 |
|
| 30 |
def read_rearrangement(filename, validate=False, debug=False): |
| 31 |
""" |
| 32 |
Open an iterator to read an AIRR rearrangements file |
| 33 |
|
| 34 |
Arguments: |
| 35 |
file (str): path to the input file. |
| 36 |
validate (bool): whether to validate data as it is read, raising a ValidationError |
| 37 |
exception in the event of an error. |
| 38 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 39 |
|
| 40 |
Returns: |
| 41 |
airr.io.RearrangementReader: iterable reader class. |
| 42 |
""" |
| 43 |
if filename.endswith(".gz"): |
| 44 |
handle = gzip.open(filename, 'r') |
| 45 |
else: |
| 46 |
handle = open(filename, 'r') |
| 47 |
|
| 48 |
return RearrangementReader(handle, validate=validate, debug=debug) |
| 49 |
|
| 50 |
|
| 51 |
def create_rearrangement(filename, fields=None, debug=False): |
| 52 |
""" |
| 53 |
Create an empty AIRR rearrangements file writer |
| 54 |
|
| 55 |
Arguments: |
| 56 |
filename (str): output file path. |
| 57 |
fields (list): additional non-required fields to add to the output. |
| 58 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 59 |
|
| 60 |
Returns: |
| 61 |
airr.io.RearrangementWriter: open writer class. |
| 62 |
""" |
| 63 |
return RearrangementWriter(open(filename, 'w+'), fields=fields, debug=debug) |
| 64 |
|
| 65 |
|
| 66 |
def derive_rearrangement(out_filename, in_filename, fields=None, debug=False): |
| 67 |
""" |
| 68 |
Create an empty AIRR rearrangements file with fields derived from an existing file |
| 69 |
|
| 70 |
Arguments: |
| 71 |
out_filename (str): output file path. |
| 72 |
in_filename (str): existing file to derive fields from. |
| 73 |
fields (list): additional non-required fields to add to the output. |
| 74 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 75 |
|
| 76 |
Returns: |
| 77 |
airr.io.RearrangementWriter: open writer class. |
| 78 |
""" |
| 79 |
reader = RearrangementReader(open(in_filename, 'r')) |
| 80 |
in_fields = list(reader.fields) |
| 81 |
if fields is not None: |
| 82 |
in_fields.extend([f for f in fields if f not in in_fields]) |
| 83 |
|
| 84 |
return RearrangementWriter(open(out_filename, 'w+'), fields=in_fields, debug=debug) |
| 85 |
|
| 86 |
|
| 87 |
def load_rearrangement(filename, validate=False, debug=False): |
| 88 |
""" |
| 89 |
Load the contents of an AIRR rearrangements file into a data frame |
| 90 |
|
| 91 |
Arguments: |
| 92 |
filename (str): input file path. |
| 93 |
validate (bool): whether to validate data as it is read, raising a ValidationError |
| 94 |
exception in the event of an error. |
| 95 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 96 |
|
| 97 |
Returns: |
| 98 |
pandas.DataFrame: Rearrangement records as rows of a data frame. |
| 99 |
""" |
| 100 |
# TODO: test pandas.DataFrame.read_csv with converters argument as an alterative |
| 101 |
schema = RearrangementSchema |
| 102 |
|
| 103 |
df = pd.read_csv(filename, sep='\t', header=0, index_col=None, |
| 104 |
dtype=schema.pandas_types(), true_values=schema.true_values, |
| 105 |
false_values=schema.false_values) |
| 106 |
# added to use RearrangementReader without modifying it: |
| 107 |
buffer = StringIO() # create an empty buffer |
| 108 |
df.to_csv(buffer, sep='\t', index=False) # fill buffer |
| 109 |
buffer.seek(0) # set to the start of the stream |
| 110 |
|
| 111 |
reader = RearrangementReader(buffer, validate=validate, debug=debug) |
| 112 |
|
| 113 |
df = pd.DataFrame(list(reader)) |
| 114 |
return df |
| 115 |
|
| 116 |
|
| 117 |
def dump_rearrangement(dataframe, filename, debug=False): |
| 118 |
""" |
| 119 |
Write the contents of a data frame to an AIRR rearrangements file |
| 120 |
|
| 121 |
Arguments: |
| 122 |
dataframe (pandas.DataFrame): data frame of rearrangement data. |
| 123 |
filename (str): output file path. |
| 124 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 125 |
|
| 126 |
Returns: |
| 127 |
bool: True if the file is written without error. |
| 128 |
""" |
| 129 |
# TODO: test pandas.DataFrame.to_csv with converters argument as an alterative |
| 130 |
# dataframe.to_csv(handle, sep='\t', header=True, index=False, encoding='utf-8') |
| 131 |
|
| 132 |
fields = dataframe.columns.tolist() |
| 133 |
with open(filename, 'w+') as handle: |
| 134 |
writer = RearrangementWriter(handle, fields=fields, debug=debug) |
| 135 |
for __, row in dataframe.iterrows(): |
| 136 |
writer.write(row.to_dict()) |
| 137 |
|
| 138 |
return True |
| 139 |
|
| 140 |
|
| 141 |
def merge_rearrangement(out_filename, in_filenames, drop=False, debug=False): |
| 142 |
""" |
| 143 |
Merge one or more AIRR rearrangements files |
| 144 |
|
| 145 |
Arguments: |
| 146 |
out_filename (str): output file path. |
| 147 |
in_filenames (list): list of input files to merge. |
| 148 |
drop (bool): drop flag. If True then drop fields that do not exist in all input |
| 149 |
files, otherwise combine fields from all input files. |
| 150 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 151 |
|
| 152 |
Returns: |
| 153 |
bool: True if files were successfully merged, otherwise False. |
| 154 |
""" |
| 155 |
try: |
| 156 |
# gather fields from input files |
| 157 |
readers = (RearrangementReader(open(f, 'r'), debug=False) for f in in_filenames) |
| 158 |
field_list = [x.fields for x in readers] |
| 159 |
if drop: |
| 160 |
field_set = set.intersection(*map(set, field_list)) |
| 161 |
else: |
| 162 |
field_set = set.union(*map(set, field_list)) |
| 163 |
field_order = OrderedDict([(f, None) for f in chain(*field_list)]) |
| 164 |
out_fields = [f for f in field_order if f in field_set] |
| 165 |
|
| 166 |
# write input files to output file sequentially |
| 167 |
readers = (RearrangementReader(open(f, 'r'), debug=debug) for f in in_filenames) |
| 168 |
with open(out_filename, 'w+') as handle: |
| 169 |
writer = RearrangementWriter(handle, fields=out_fields, debug=debug) |
| 170 |
for reader in readers: |
| 171 |
for r in reader: writer.write(r) |
| 172 |
reader.close() |
| 173 |
except Exception as e: |
| 174 |
sys.stderr.write('Error occurred while merging AIRR rearrangement files: %s\n' % e) |
| 175 |
return False |
| 176 |
|
| 177 |
return True |
| 178 |
|
| 179 |
|
| 180 |
def validate_rearrangement(filename, debug=False): |
| 181 |
""" |
| 182 |
Validates an AIRR rearrangements file |
| 183 |
|
| 184 |
Arguments: |
| 185 |
filename (str): path of the file to validate. |
| 186 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 187 |
|
| 188 |
Returns: |
| 189 |
bool: True if files passed validation, otherwise False. |
| 190 |
""" |
| 191 |
valid = True |
| 192 |
if debug: |
| 193 |
sys.stderr.write('Validating: %s\n' % filename) |
| 194 |
|
| 195 |
# Open reader |
| 196 |
handle = open(filename, 'r') |
| 197 |
reader = RearrangementReader(handle, validate=True) |
| 198 |
|
| 199 |
# Validate header |
| 200 |
try: |
| 201 |
iter(reader) |
| 202 |
except ValidationError as e: |
| 203 |
valid = False |
| 204 |
if debug: |
| 205 |
sys.stderr.write('%s has validation error: %s\n' % (filename, e)) |
| 206 |
|
| 207 |
# Validate each row |
| 208 |
i = 0 |
| 209 |
while True: |
| 210 |
try: |
| 211 |
i = i + 1 |
| 212 |
next(reader) |
| 213 |
except StopIteration: |
| 214 |
break |
| 215 |
except ValidationError as e: |
| 216 |
valid = False |
| 217 |
if debug: |
| 218 |
sys.stderr.write('%s at record %i has validation error: %s\n' % (filename, i, e)) |
| 219 |
|
| 220 |
# Close |
| 221 |
handle.close() |
| 222 |
|
| 223 |
return valid |
| 224 |
|
| 225 |
#### AIRR Data Model #### |
| 226 |
|
| 227 |
def read_airr(filename, format=None, validate=False, model=True, debug=False): |
| 228 |
""" |
| 229 |
Load an AIRR Data file |
| 230 |
|
| 231 |
Arguments: |
| 232 |
filename (str): path to the input file. |
| 233 |
format (str): input file format valid strings are "yaml" or "json". If set to None, |
| 234 |
the file format will be automatically detected from the file extension. |
| 235 |
validate (bool): whether to validate data as it is read, raising a ValidationError |
| 236 |
exception in the event of a validation failure. |
| 237 |
model (bool): If True only validate objects defined in the AIRR DataFile schema. |
| 238 |
If False, attempt validation of all top-level objects. |
| 239 |
Ignored if validate=False. |
| 240 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 241 |
|
| 242 |
Returns: |
| 243 |
dict: dictionary of AIRR Data objects. |
| 244 |
""" |
| 245 |
# Because the AIRR Data File is read in completely, we do not bother with a reader class. |
| 246 |
# Determine file type from extension and use appropriate loader |
| 247 |
ext = str.lower(filename.split('.')[-1]) if not format else format |
| 248 |
if ext in ('yaml', 'yml'): |
| 249 |
with open(filename, 'r', encoding='utf-8') as handle: |
| 250 |
data = yaml.load(handle, Loader=yamlordereddictloader.Loader) |
| 251 |
elif ext == 'json': |
| 252 |
with open(filename, 'r', encoding='utf-8') as handle: |
| 253 |
data = json.load(handle) |
| 254 |
else: |
| 255 |
if debug: sys.stderr.write('Unknown file type: %s. Supported file extensions are "yaml", "yml" or "json"\n' % ext) |
| 256 |
raise TypeError('Unknown file type: %s. Supported file extensions are "yaml", "yml" or "json"\n' % ext) |
| 257 |
data = None |
| 258 |
|
| 259 |
# Validate if requested |
| 260 |
if validate: |
| 261 |
if debug: sys.stderr.write('Validating: %s\n' % filename) |
| 262 |
try: |
| 263 |
valid = validate_airr(data, model=model, debug=debug) |
| 264 |
except ValidationError as e: |
| 265 |
if debug: sys.stderr.write('%s failed validation\n' % filename) |
| 266 |
raise ValidationError(e) |
| 267 |
|
| 268 |
# We do not perform any additional processing |
| 269 |
return data |
| 270 |
|
| 271 |
|
| 272 |
def validate_airr(data, model=True, debug=False): |
| 273 |
""" |
| 274 |
Validates an AIRR Data file |
| 275 |
|
| 276 |
Arguments: |
| 277 |
data (dict): dictionary containing AIRR Data Model objects |
| 278 |
model (bool): If True only validate objects defined in the AIRR DataFile schema. |
| 279 |
If False, attempt validation of all top-level objects |
| 280 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 281 |
|
| 282 |
Returns: |
| 283 |
bool: True if files passed validation, otherwise False. |
| 284 |
""" |
| 285 |
# Type check that input type is either dict or OrderedDict |
| 286 |
if not hasattr(data, 'items'): |
| 287 |
if debug: sys.stderr.write('Data parameter is not a dictionary\n') |
| 288 |
raise TypeError('Data parameter is not a dictionary') |
| 289 |
|
| 290 |
# Loop through each AIRR object and validate |
| 291 |
valid = True |
| 292 |
for k, object in data.items(): |
| 293 |
if k in ('Info', 'DataFile'): continue |
| 294 |
if not object: continue |
| 295 |
|
| 296 |
# Check for DataFile schema |
| 297 |
if model and k not in DataFileSchema.properties: |
| 298 |
if debug: sys.stderr.write('Skipping non-DataFile object: %s\n' % k) |
| 299 |
continue |
| 300 |
|
| 301 |
# Get Schema |
| 302 |
schema = AIRRSchema.get(k, Schema(k)) |
| 303 |
|
| 304 |
# Determine input type and set appropriate iterator |
| 305 |
if hasattr(object, 'items'): |
| 306 |
# Validate named array (dict) |
| 307 |
obj_iter = object.items() |
| 308 |
# Validate named array (dict) or a single object (dict) |
| 309 |
# obj_iter = object.items() if 'definition' not in object.keys() else [0, object] |
| 310 |
elif isinstance(object, list): |
| 311 |
# Validate array |
| 312 |
obj_iter = enumerate(object) |
| 313 |
else: |
| 314 |
# Unrecognized data structure |
| 315 |
valid = False |
| 316 |
if debug: sys.stderr.write('%s is an unrecognized data structure: %s\n' % k) |
| 317 |
continue |
| 318 |
|
| 319 |
# Validate each record in array |
| 320 |
for i, record in obj_iter: |
| 321 |
try: |
| 322 |
schema.validate_object(record) |
| 323 |
except ValidationError as e: |
| 324 |
valid = False |
| 325 |
if debug: sys.stderr.write('%s at array position %s with validation error: %s\n' % (k, i, e)) |
| 326 |
|
| 327 |
if not valid: |
| 328 |
raise ValidationError('AIRR Data Model has validation failures') |
| 329 |
|
| 330 |
return valid |
| 331 |
|
| 332 |
|
| 333 |
def write_airr(filename, data, format=None, info=None, validate=False, model=True, debug=False): |
| 334 |
""" |
| 335 |
Write an AIRR Data file |
| 336 |
|
| 337 |
Arguments: |
| 338 |
filename (str): path to the output file. |
| 339 |
data (dict): dictionary of AIRR Data Model objects. |
| 340 |
format (str): output file format valid strings are "yaml" or "json". If set to None, |
| 341 |
the file format will be automatically detected from the file extension. |
| 342 |
info (object): info object to write. Will write current AIRR Schema info if not specified. |
| 343 |
validate (bool): whether to validate data before it is written, raising a ValidationError |
| 344 |
exception in the event of a validation failure. |
| 345 |
model (bool): If True only validate and write objects defined in the AIRR DataFile schema. |
| 346 |
If False, attempt validation and write of all top-level objects |
| 347 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 348 |
|
| 349 |
Returns: |
| 350 |
bool: True if the file is written without error. |
| 351 |
""" |
| 352 |
# Type check that input type is either dict or OrderedDict |
| 353 |
if not hasattr(data, 'items'): |
| 354 |
if debug: sys.stderr.write('Data parameter is not a dictionary\n') |
| 355 |
raise TypeError('Data parameter is not a dictionary') |
| 356 |
|
| 357 |
# Validate if requested |
| 358 |
if validate: |
| 359 |
if debug: sys.stderr.write('Validating: %s\n' % filename) |
| 360 |
try: |
| 361 |
valid = validate_airr(data, model=model, debug=debug) |
| 362 |
except ValidationError as e: |
| 363 |
if debug: sys.stderr.write(e) |
| 364 |
raise ValidationError(e) |
| 365 |
|
| 366 |
md = OrderedDict() |
| 367 |
if info is None: |
| 368 |
info = RearrangementSchema.info.copy() |
| 369 |
info['title'] = 'AIRR Data File' |
| 370 |
info['description'] = 'AIRR Data File written by AIRR Standards Python Library' |
| 371 |
md['Info'] = info |
| 372 |
|
| 373 |
# Loop through each object and add them to the output dict |
| 374 |
for k, obj in data.items(): |
| 375 |
if k in ('Info', 'DataFile'): continue |
| 376 |
if not obj: continue |
| 377 |
if model and k not in DataFileSchema.properties: |
| 378 |
if debug: sys.stderr.write('Skipping non-DataFile object: %s\n' % k) |
| 379 |
continue |
| 380 |
md[k] = obj |
| 381 |
|
| 382 |
# Determine file type from extension and use appropriate loader |
| 383 |
ext = str.lower(filename.split('.')[-1]) if not format else format |
| 384 |
if ext in ('yaml', 'yml'): |
| 385 |
with open(filename, 'w') as handle: |
| 386 |
yaml.dump(md, handle, default_flow_style=False) |
| 387 |
elif ext == 'json': |
| 388 |
with open(filename, 'w') as handle: |
| 389 |
json.dump(md, handle, sort_keys=False, indent=2) |
| 390 |
else: |
| 391 |
if debug: |
| 392 |
sys.stderr.write('Unknown file type: %s. Supported file extensions are "yaml", "yml" or "json"\n' % ext) |
| 393 |
raise TypeError('Unknown file type: %s. Supported file extensions are "yaml", "yml" or "json"\n' % ext) |
| 394 |
|
| 395 |
return True |
| 396 |
|
| 397 |
|
| 398 |
#### Deprecated #### |
| 399 |
|
| 400 |
def repertoire_template(): |
| 401 |
""" |
| 402 |
Return a blank repertoire object from the template. This object has the complete |
| 403 |
structure with all of the fields and all values set to None or empty string. |
| 404 |
|
| 405 |
Returns: |
| 406 |
object: empty repertoire object. |
| 407 |
|
| 408 |
.. deprecated:: 1.4 |
| 409 |
Use :meth:`schema.Schema.template` instead. |
| 410 |
""" |
| 411 |
# Deprecation |
| 412 |
warn('repertoire_template is deprecated and will be removed in a future release.\nUse schema.Schema.template instead.\n', |
| 413 |
DeprecationWarning, stacklevel=2) |
| 414 |
|
| 415 |
# Build template |
| 416 |
object = RepertoireSchema.template() |
| 417 |
|
| 418 |
return object |
| 419 |
|
| 420 |
|
| 421 |
def load_repertoire(filename, validate=False, debug=False): |
| 422 |
""" |
| 423 |
Load an AIRR repertoire metadata file |
| 424 |
|
| 425 |
Arguments: |
| 426 |
filename (str): path to the input file. |
| 427 |
validate (bool): whether to validate data as it is read, raising a ValidationError |
| 428 |
exception in the event of an error. |
| 429 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 430 |
|
| 431 |
Returns: |
| 432 |
dict: dictionary of AIRR Data objects. |
| 433 |
|
| 434 |
.. deprecated:: 1.4 |
| 435 |
Use :func:`read_airr` instead. |
| 436 |
""" |
| 437 |
# Deprecation |
| 438 |
warn('load_repertoire is deprecated and will be removed in a future release.\nUse read_airr instead.\n', |
| 439 |
DeprecationWarning, stacklevel=2) |
| 440 |
|
| 441 |
# use standard load function, we only validate Repertoire if requested |
| 442 |
md = read_airr(filename, validate=validate, debug=debug) |
| 443 |
|
| 444 |
if md.get('Repertoire') is None: |
| 445 |
if debug: |
| 446 |
sys.stderr.write('%s is missing "Repertoire" key\n' % (filename)) |
| 447 |
raise KeyError('Repertoire object cannot be found in the file') |
| 448 |
|
| 449 |
# validate if requested |
| 450 |
if validate: |
| 451 |
valid = True |
| 452 |
reps = md['Repertoire'] |
| 453 |
i = 0 |
| 454 |
for r in reps: |
| 455 |
try: |
| 456 |
RepertoireSchema.validate_object(r) |
| 457 |
except ValidationError as e: |
| 458 |
valid = False |
| 459 |
if debug: |
| 460 |
sys.stderr.write('%s has repertoire at array position %i with validation error: %s\n' % (filename, i, e)) |
| 461 |
i = i + 1 |
| 462 |
if not valid: |
| 463 |
raise ValidationError('Repertoire file %s has validation errors\n' % (filename)) |
| 464 |
|
| 465 |
# we do not perform any additional processing |
| 466 |
return md |
| 467 |
|
| 468 |
|
| 469 |
def validate_repertoire(filename, debug=False): |
| 470 |
""" |
| 471 |
Validates an AIRR repertoire metadata file |
| 472 |
|
| 473 |
Arguments: |
| 474 |
filename (str): path of the file to validate. |
| 475 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 476 |
|
| 477 |
Returns: |
| 478 |
bool: True if files passed validation, otherwise False. |
| 479 |
|
| 480 |
.. deprecated:: 1.4 |
| 481 |
Use :func:`validate_airr` instead. |
| 482 |
""" |
| 483 |
# Deprecation |
| 484 |
warn('validate_repertoire is deprecated and will be removed in a future release.\nUse validate_airr instead.\n', |
| 485 |
DeprecationWarning, stacklevel=2) |
| 486 |
|
| 487 |
valid = True |
| 488 |
if debug: |
| 489 |
sys.stderr.write('Validating: %s\n' % filename) |
| 490 |
|
| 491 |
# load with validate |
| 492 |
try: |
| 493 |
data = load_repertoire(filename, validate=True, debug=debug) |
| 494 |
except TypeError: |
| 495 |
valid = False |
| 496 |
except KeyError: |
| 497 |
valid = False |
| 498 |
except ValidationError as e: |
| 499 |
valid = False |
| 500 |
if debug: |
| 501 |
sys.stderr.write('%s has validation error: %s\n' % (filename, e)) |
| 502 |
|
| 503 |
return valid |
| 504 |
|
| 505 |
def write_repertoire(filename, repertoires, info=None, debug=False): |
| 506 |
""" |
| 507 |
Write an AIRR repertoire metadata file |
| 508 |
|
| 509 |
Arguments: |
| 510 |
file (str): path to the output file. |
| 511 |
repertoires (list): array of repertoire objects. |
| 512 |
info (object): info object to write. Will write current AIRR Schema info if not specified. |
| 513 |
debug (bool): debug flag. If True print debugging information to standard error. |
| 514 |
|
| 515 |
Returns: |
| 516 |
bool: True if the file is written without error. |
| 517 |
|
| 518 |
.. deprecated:: 1.4 |
| 519 |
Use :func:`write_airr` instead. |
| 520 |
""" |
| 521 |
# Deprecation |
| 522 |
warn('write_repertoire is deprecated and will be removed in a future release.\nUse write_airr instead.\n', |
| 523 |
DeprecationWarning, stacklevel=2) |
| 524 |
|
| 525 |
if not isinstance(repertoires, list): |
| 526 |
if debug: |
| 527 |
sys.stderr.write('Repertoires parameter is not a list\n') |
| 528 |
raise TypeError('Repertoires parameter is not a list') |
| 529 |
|
| 530 |
md = OrderedDict() |
| 531 |
if info is None: |
| 532 |
info = RearrangementSchema.info.copy() |
| 533 |
info['title'] = 'Repertoire metadata' |
| 534 |
info['description'] = 'Repertoire metadata written by AIRR Standards Python Library' |
| 535 |
md['Info'] = info |
| 536 |
md['Repertoire'] = repertoires |
| 537 |
|
| 538 |
return write_airr(filename, md, info=info, debug=debug) |