| 1 |
"""Record validation logic.""" |
| 2 |
|
| 3 |
import logging |
| 4 |
# If Biopython is not available, all checks will return False |
| 5 |
try: |
| 6 |
from Bio import SeqIO |
| 7 |
from Bio.SeqFeature import BeforePosition, AfterPosition |
| 8 |
HAVE_BIOPYTHON = True |
| 9 |
except ImportError: # pragma: no cover |
| 10 |
HAVE_BIOPYTHON = False |
| 11 |
|
| 12 |
|
| 13 |
VALIDATION_LEVELS = {'none', 'loads', 'all', 'correct'} |
| 14 |
|
| 15 |
|
| 16 |
def run_extended_validation(handle, file_format, validation_level): |
| 17 |
"""Check if the dowloaded sequence file can load.""" |
| 18 |
if not HAVE_BIOPYTHON: |
| 19 |
return False |
| 20 |
# we wrote to the handle, so rewind it |
| 21 |
handle.seek(0) |
| 22 |
try: |
| 23 |
processed_seq = False |
| 24 |
records = [] |
| 25 |
for rec in SeqIO.parse(handle, file_format): |
| 26 |
processed_seq = True |
| 27 |
if validation_level == 'loads': |
| 28 |
continue |
| 29 |
if validation_level == 'correct': |
| 30 |
## Correct possible errors from downloaded a restricted-range genbank file |
| 31 |
## Will write over the downloaded file |
| 32 |
newfeats = [] |
| 33 |
for f in rec.features: |
| 34 |
try: |
| 35 |
if not isinstance(f.location.start, BeforePosition) and not isinstance(f.location.end, AfterPosition): |
| 36 |
newfeats.append(f) |
| 37 |
except AttributeError: |
| 38 |
newfeats.append(f) |
| 39 |
rec.features = newfeats |
| 40 |
records.append(rec) |
| 41 |
if not processed_seq: |
| 42 |
logging.error('no seq') |
| 43 |
|
| 44 |
if validation_level == 'correct': |
| 45 |
## rewrite StringIO data |
| 46 |
handle.truncate(0) |
| 47 |
handle.seek(0) |
| 48 |
SeqIO.write(records, handle, 'genbank') |
| 49 |
return processed_seq |
| 50 |
except (ValueError, AssertionError) as err: |
| 51 |
logging.error(err) |
| 52 |
return False |
| 53 |
except Exception as err: |
| 54 |
logging.error("Unhandled exception %s while parsing sequence file.", err) |
| 55 |
return False |