| 1 |
""" |
| 2 |
Reference library for AIRR schema for Ig/TCR rearrangements |
| 3 |
""" |
| 4 |
from __future__ import print_function |
| 5 |
import sys |
| 6 |
import csv |
| 7 |
from airr.schema import RearrangementSchema, ValidationError |
| 8 |
|
| 9 |
|
| 10 |
class RearrangementReader: |
| 11 |
""" |
| 12 |
Iterator for reading Rearrangement objects in TSV format |
| 13 |
|
| 14 |
Attributes: |
| 15 |
fields (list): field names in the input Rearrangement file. |
| 16 |
external_fields (list): list of fields in the input file that are not |
| 17 |
part of the Rearrangement definition. |
| 18 |
""" |
| 19 |
@property |
| 20 |
def fields(self): |
| 21 |
""" |
| 22 |
Get list of fields |
| 23 |
|
| 24 |
Returns: |
| 25 |
list : field names. |
| 26 |
""" |
| 27 |
return self.dict_reader.fieldnames |
| 28 |
|
| 29 |
@property |
| 30 |
def external_fields(self): |
| 31 |
""" |
| 32 |
Get list of field that are not in the Rearrangement schema |
| 33 |
|
| 34 |
Returns: |
| 35 |
list : field names. |
| 36 |
""" |
| 37 |
return [f for f in self.dict_reader.fieldnames \ |
| 38 |
if f not in self.schema.properties] |
| 39 |
|
| 40 |
def __init__(self, handle, base=1, validate=False, debug=False): |
| 41 |
""" |
| 42 |
Initialization |
| 43 |
|
| 44 |
Arguments: |
| 45 |
handle (file): file handle of the open Rearrangement file. |
| 46 |
base (int): one of 0 or 1 specifying the coordinate schema in the input file. |
| 47 |
If 1, then the file is assumed to contain 1-based closed intervals |
| 48 |
that will be converted to python style 0-based half-open intervals |
| 49 |
for known fields. If 0, then values will be unchanged. |
| 50 |
validate (bool): perform validation. If True then basic validation will be |
| 51 |
performed will reading the data. A ValidationError exception |
| 52 |
will be raised if an error is found. |
| 53 |
debug (bool): debug state. If True prints debug information. |
| 54 |
|
| 55 |
Returns: |
| 56 |
airr.io.RearrangementReader: reader object. |
| 57 |
""" |
| 58 |
# arguments |
| 59 |
self.handle = handle |
| 60 |
self.base = base |
| 61 |
self.debug = debug |
| 62 |
self.validate = validate |
| 63 |
self.schema = RearrangementSchema |
| 64 |
|
| 65 |
# data reader, collect field names |
| 66 |
self.dict_reader = csv.DictReader(self.handle, dialect='excel-tab') |
| 67 |
|
| 68 |
def __iter__(self): |
| 69 |
""" |
| 70 |
Iterator initializer |
| 71 |
|
| 72 |
Returns: |
| 73 |
airr.io.RearrangementReader |
| 74 |
""" |
| 75 |
# Validate fields |
| 76 |
if (self.validate): |
| 77 |
self.schema.validate_header(self.dict_reader.fieldnames) |
| 78 |
|
| 79 |
return self |
| 80 |
|
| 81 |
def __next__(self): |
| 82 |
""" |
| 83 |
Next method |
| 84 |
|
| 85 |
Returns: |
| 86 |
dict: parsed Rearrangement data. |
| 87 |
""" |
| 88 |
try: |
| 89 |
row = next(self.dict_reader) |
| 90 |
except StopIteration: |
| 91 |
raise StopIteration |
| 92 |
|
| 93 |
for f in row: |
| 94 |
# row entry with no header |
| 95 |
if f is None: |
| 96 |
if self.validate: |
| 97 |
raise ValidationError('row has extra data') |
| 98 |
else: |
| 99 |
raise ValueError('row has extra data') |
| 100 |
|
| 101 |
# Convert types |
| 102 |
spec = self.schema.type(f) |
| 103 |
try: |
| 104 |
if spec == 'boolean': |
| 105 |
row[f] = self.schema.to_bool(row[f], validate=self.validate) |
| 106 |
if spec == 'integer': |
| 107 |
row[f] = self.schema.to_int(row[f], validate=self.validate) |
| 108 |
if spec == 'number': |
| 109 |
row[f] = self.schema.to_float(row[f], validate=self.validate) |
| 110 |
except ValidationError as e: |
| 111 |
raise ValidationError('field %s has %s' %(f, e)) |
| 112 |
|
| 113 |
# Adjust coordinates |
| 114 |
if f and f.endswith('_start') and self.base == 1: |
| 115 |
try: |
| 116 |
row[f] = row[f] - 1 |
| 117 |
except TypeError: |
| 118 |
row[f] = None |
| 119 |
|
| 120 |
return row |
| 121 |
|
| 122 |
def close(self): |
| 123 |
""" |
| 124 |
Closes the Rearrangement file |
| 125 |
""" |
| 126 |
self.handle.close() |
| 127 |
|
| 128 |
def next(self): |
| 129 |
""" |
| 130 |
Next method |
| 131 |
""" |
| 132 |
return self.__next__() |
| 133 |
|
| 134 |
|
| 135 |
class RearrangementWriter: |
| 136 |
""" |
| 137 |
Writer class for Rearrangement objects in TSV format |
| 138 |
|
| 139 |
Attributes: |
| 140 |
fields (list): field names in the output Rearrangement file. |
| 141 |
external_fields (list): list of fields in the output file that are not |
| 142 |
part of the Rearrangement definition. |
| 143 |
""" |
| 144 |
@property |
| 145 |
def fields(self): |
| 146 |
""" |
| 147 |
Get list of fields |
| 148 |
|
| 149 |
Returns: |
| 150 |
list : field names. |
| 151 |
""" |
| 152 |
return self.dict_writer.fieldnames |
| 153 |
|
| 154 |
@property |
| 155 |
def external_fields(self): |
| 156 |
""" |
| 157 |
Get list of field that are not in the Rearrangements schema |
| 158 |
|
| 159 |
Returns: |
| 160 |
list : field names. |
| 161 |
""" |
| 162 |
return [f for f in self.dict_writer.fieldnames \ |
| 163 |
if f not in self.schema.properties] |
| 164 |
|
| 165 |
def __init__(self, handle, fields=None, base=1, debug=False): |
| 166 |
""" |
| 167 |
Initialization |
| 168 |
|
| 169 |
Arguments: |
| 170 |
handle (file): file handle of the open Rearrangements file. |
| 171 |
fields (list) : list of non-required fields to add. May include fields undefined by the schema. |
| 172 |
base (int): one of 0 or 1 specifying the coordinate schema in the output file. |
| 173 |
Data provided to the write is assumed to be in python style 0-based |
| 174 |
half-open intervals. If 1, then data will be converted to 1-based |
| 175 |
closed intervals for known fields before writing. If 0, then values will be unchanged. |
| 176 |
debug (bool): debug state. If True prints debug information. |
| 177 |
|
| 178 |
Returns: |
| 179 |
airr.io.RearrangementWriter: writer object. |
| 180 |
""" |
| 181 |
# arguments |
| 182 |
self.handle = handle |
| 183 |
self.base = base |
| 184 |
self.debug = debug |
| 185 |
self.schema = RearrangementSchema |
| 186 |
|
| 187 |
# order fields according to spec |
| 188 |
field_names = list(self.schema.required) |
| 189 |
if fields is not None: |
| 190 |
additional_fields = [] |
| 191 |
for f in fields: |
| 192 |
if f in self.schema.required: |
| 193 |
continue |
| 194 |
elif f in self.schema.optional: |
| 195 |
field_names.append(f) |
| 196 |
else: |
| 197 |
additional_fields.append(f) |
| 198 |
field_names.extend(additional_fields) |
| 199 |
|
| 200 |
# open writer and write header |
| 201 |
self.dict_writer = csv.DictWriter(self.handle, fieldnames=field_names, dialect='excel-tab', |
| 202 |
extrasaction='ignore', lineterminator='\n') |
| 203 |
self.dict_writer.writeheader() |
| 204 |
|
| 205 |
def close(self): |
| 206 |
""" |
| 207 |
Closes the Rearrangement file |
| 208 |
""" |
| 209 |
self.handle.close() |
| 210 |
|
| 211 |
def write(self, row): |
| 212 |
""" |
| 213 |
Write a row to the Rearrangement file |
| 214 |
|
| 215 |
Arguments: |
| 216 |
row (dict): row to write. |
| 217 |
""" |
| 218 |
# validate row |
| 219 |
if self.debug: |
| 220 |
for field in self.schema.required: |
| 221 |
if row.get(field, None) is None: |
| 222 |
sys.stderr.write('Warning: Record is missing AIRR required field (' + field + ').\n') |
| 223 |
|
| 224 |
for f in row.keys(): |
| 225 |
# Adjust coordinates |
| 226 |
if f.endswith('_start') and self.base == 1: |
| 227 |
try: |
| 228 |
row[f] = self.schema.to_int(row[f]) + 1 |
| 229 |
except TypeError: |
| 230 |
row[f] = None |
| 231 |
|
| 232 |
# Convert types |
| 233 |
spec = self.schema.type(f) |
| 234 |
if spec == 'boolean': row[f] = self.schema.from_bool(row[f]) |
| 235 |
|
| 236 |
self.dict_writer.writerow(row) |
| 237 |
|
| 238 |
|
| 239 |
# TODO: pandas validation need if we load with pandas directly |
| 240 |
# def validate_df(df, airr_schema): |
| 241 |
# valid = True |
| 242 |
# |
| 243 |
# # check required fields |
| 244 |
# missing_fields = set(airr_schema.required) - set(df.columns) |
| 245 |
# if len(missing_fields) > 0: |
| 246 |
# print('Warning: file is missing mandatory fields: {}'.format(', '.join(missing_fields))) |
| 247 |
# valid = False |
| 248 |
# |
| 249 |
# if not valid: |
| 250 |
# raise ValueError('invalid AIRR data file') |
| 251 |
|
| 252 |
|