Source code

Download source archive ↓

upstream-extended/community/tools/biopython/converters/utils.py

1#!/usr/bin/env python
2
3from Bio import Seq
4from Bio.Alphabet import generic_dna
5
6
7def check_gff(gff_iterator):
8    """
9    Check GFF files before feeding to SeqIO to be sure they have sequences.
10    """
11    for rec in gff_iterator:
12        if isinstance(rec.seq, Seq.UnknownSeq):
13            print("Warning: FASTA sequence not found for '%s' in GFF file" % (rec.id))
14            rec.seq.alphabet = generic_dna
15        yield flatten_features(rec)
16
17
18def flatten_features(rec):
19    """
20    Make sub_features in an input rec flat for output.
21
22    GenBank does not handle nested features, so we want to make
23    everything top level.
24    """
25    out = []
26    for f in rec.features:
27        cur = [f]
28        while len(cur) > 0:
29            nextf = []
30            for curf in cur:
31                out.append(curf)
32                if len(curf.sub_features) > 0:
33                    nextf.extend(curf.sub_features)
34            cur = nextf
35    rec.features = out
36    return rec
37
38
39def fix_ncbi_id(fasta_iter):
40    """
41    GenBank identifiers can only be 16 characters; try to shorten NCBI.
42    """
43    for rec in fasta_iter:
44        if len(rec.name) > 16 and rec.name.find("|") > 0:
45            new_id = [x for x in rec.name.split("|") if x][0]
46            print("Warning: shortening NCBI name %s to %s" % (rec.id, new_id))
47            rec.id = new_id
48            rec.name = new_id
49        yield rec