Beispiel #1
0
def _make_position(location_string, offset=0):
    """Turn a Swiss location position into a SeqFeature position object (PRIVATE).

    An offset of -1 is used with a start location to make it pythonic.
    """
    if location_string == "?":
        return SeqFeature.UnknownPosition()
    # Hack so that feature from 0 to 0 becomes 0 to 0, not -1 to 0.
    try:
        return SeqFeature.ExactPosition(max(0, offset + int(location_string)))
    except ValueError:
        pass
    if location_string.startswith("<"):
        try:
            return SeqFeature.BeforePosition(
                max(0, offset + int(location_string[1:])))
        except ValueError:
            pass
    elif location_string.startswith(">"):  # e.g. ">13"
        try:
            return SeqFeature.AfterPosition(
                max(0, offset + int(location_string[1:])))
        except ValueError:
            pass
    elif location_string.startswith("?"):  # e.g. "?22"
        try:
            return SeqFeature.UncertainPosition(
                max(0, offset + int(location_string[1:])))
        except ValueError:
            pass
    raise NotImplementedError("Cannot parse location '%s'" % location_string)
Beispiel #2
0
 def _parse_position(element, offset=0):
     try:
         position = int(element.attrib["position"]) + offset
     except KeyError as err:
         position = None
     status = element.attrib.get("status", "")
     if status == "unknown":
         assert position is None
         return SeqFeature.UnknownPosition()
     elif not status:
         return SeqFeature.ExactPosition(position)
     elif status == "greater than":
         return SeqFeature.AfterPosition(position)
     elif status == "less than":
         return SeqFeature.BeforePosition(position)
     elif status == "uncertain":
         return SeqFeature.UncertainPosition(position)
     else:
         raise NotImplementedError("Position status %r" % status)
Beispiel #3
0
def _retrieve_features(adaptor, primary_id):
    sql = (
        'SELECT seqfeature_id, type.name, "rank"'
        " FROM seqfeature join term type on (type_term_id = type.term_id)"
        " WHERE bioentry_id = %s"
        ' ORDER BY "rank"'
    )
    results = adaptor.execute_and_fetchall(sql, (primary_id,))
    seq_feature_list = []
    for seqfeature_id, seqfeature_type, seqfeature_rank in results:
        # Get qualifiers [except for db_xref which is stored separately]
        qvs = adaptor.execute_and_fetchall(
            "SELECT name, value"
            " FROM seqfeature_qualifier_value  join term using (term_id)"
            " WHERE seqfeature_id = %s"
            ' ORDER BY "rank"',
            (seqfeature_id,),
        )
        qualifiers = {}
        for qv_name, qv_value in qvs:
            qualifiers.setdefault(qv_name, []).append(qv_value)
        # Get db_xrefs [special case of qualifiers]
        qvs = adaptor.execute_and_fetchall(
            "SELECT dbxref.dbname, dbxref.accession"
            " FROM dbxref join seqfeature_dbxref using (dbxref_id)"
            " WHERE seqfeature_dbxref.seqfeature_id = %s"
            ' ORDER BY "rank"',
            (seqfeature_id,),
        )
        for qv_name, qv_value in qvs:
            value = "%s:%s" % (qv_name, qv_value)
            qualifiers.setdefault("db_xref", []).append(value)
        # Get locations
        results = adaptor.execute_and_fetchall(
            "SELECT location_id, start_pos, end_pos, strand"
            " FROM location"
            " WHERE seqfeature_id = %s"
            ' ORDER BY "rank"',
            (seqfeature_id,),
        )
        locations = []
        # convert to Python standard form
        # Convert strand = 0 to strand = None
        # re: comment in Loader.py:
        # Biopython uses None when we don't know strand information but
        # BioSQL requires something (non null) and sets this as zero
        # So we'll use the strand or 0 if Biopython spits out None
        for location_id, start, end, strand in results:
            if start:
                start -= 1
            if strand == 0:
                strand = None
            if strand not in (+1, -1, None):
                raise ValueError(
                    "Invalid strand %s found in database for "
                    "seqfeature_id %s" % (strand, seqfeature_id)
                )
            if start is not None and end is not None and end < start:
                import warnings
                from Bio import BiopythonWarning

                warnings.warn(
                    "Inverted location start/end (%i and %i) for "
                    "seqfeature_id %s" % (start, end, seqfeature_id),
                    BiopythonWarning,
                )

            # For SwissProt unknown positions (?)
            if start is None:
                start = SeqFeature.UnknownPosition()
            if end is None:
                end = SeqFeature.UnknownPosition()

            locations.append((location_id, start, end, strand))
        # Get possible remote reference information
        remote_results = adaptor.execute_and_fetchall(
            "SELECT location_id, dbname, accession, version"
            " FROM location join dbxref using (dbxref_id)"
            " WHERE seqfeature_id = %s",
            (seqfeature_id,),
        )
        lookup = {}
        for location_id, dbname, accession, version in remote_results:
            if version and version != "0":
                v = "%s.%s" % (accession, version)
            else:
                v = accession
            # subfeature remote location db_ref are stored as a empty string
            # when not present
            if dbname == "":
                dbname = None
            lookup[location_id] = (dbname, v)

        feature = SeqFeature.SeqFeature(type=seqfeature_type)
        # Store the key as a private property
        feature._seqfeature_id = seqfeature_id
        feature.qualifiers = qualifiers
        if len(locations) == 0:
            pass
        elif len(locations) == 1:
            location_id, start, end, strand = locations[0]
            # See Bug 2677, we currently don't record the location_operator
            # For consistency with older versions Biopython, default to "".
            feature.location_operator = _retrieve_location_qualifier_value(
                adaptor, location_id
            )
            dbname, version = lookup.get(location_id, (None, None))
            feature.location = SeqFeature.FeatureLocation(start, end)
            feature.strand = strand
            feature.ref_db = dbname
            feature.ref = version
        else:
            locs = []
            for location in locations:
                location_id, start, end, strand = location
                dbname, version = lookup.get(location_id, (None, None))
                locs.append(
                    SeqFeature.FeatureLocation(
                        start, end, strand=strand, ref=version, ref_db=dbname
                    )
                )
            # Locations are typically in biological in order (see negative
            # strands below), but because of remote locations for
            # sub-features they are not necessarily in numerical order:
            strands = {l.strand for l in locs}
            if len(strands) == 1 and -1 in strands:
                # Evil hack time for backwards compatibility
                # TODO - Check if BioPerl and (old) Biopython did the same,
                # we may have an existing incompatibility lurking here...
                locs = locs[::-1]
            feature.location = SeqFeature.CompoundLocation(locs, "join")
            # TODO - See Bug 2677 - we don't yet record location operator,
            # so for consistency with older versions of Biopython default
            # to assuming its a join.
        seq_feature_list.append(feature)
    return seq_feature_list
Beispiel #4
0
    def parse(self):
        """Parse the input."""
        assert self.entry.tag == NS + 'entry'

        def append_to_annotations(key, value):
            if key not in self.ParsedSeqRecord.annotations:
                self.ParsedSeqRecord.annotations[key] = []
            if value not in self.ParsedSeqRecord.annotations[key]:
                self.ParsedSeqRecord.annotations[key].append(value)

        def _parse_name(element):
            self.ParsedSeqRecord.name = element.text
            self.ParsedSeqRecord.dbxrefs.append(self.dbname + ':' +
                                                element.text)

        def _parse_accession(element):
            append_to_annotations(
                'accessions',
                element.text)  # to cope with SwissProt plain text parser
            self.ParsedSeqRecord.dbxrefs.append(self.dbname + ':' +
                                                element.text)

        def _parse_protein(element):
            """Parse protein names (PRIVATE)."""
            descr_set = False
            for protein_element in element.getchildren():
                if protein_element.tag in [
                        NS + 'recommendedName', NS + 'alternativeName'
                ]:  #recommendedName tag are parsed before
                    #use protein fields for name and description
                    for rec_name in protein_element.getchildren():
                        ann_key = '%s_%s' % (protein_element.tag.replace(
                            NS, ''), rec_name.tag.replace(NS, ''))
                        append_to_annotations(ann_key, rec_name.text)
                        if (rec_name.tag == NS + 'fullName') and not descr_set:
                            self.ParsedSeqRecord.description = rec_name.text
                            descr_set = True
                elif protein_element.tag == NS + 'component':
                    pass  #not parsed
                elif protein_element.tag == NS + 'domain':
                    pass  #not parsed

        def _parse_gene(element):
            for genename_element in element.getchildren():
                if 'type' in genename_element.attrib:
                    ann_key = 'gene_%s_%s' % (genename_element.tag.replace(
                        NS, ''), genename_element.attrib['type'])
                    if genename_element.attrib['type'] == 'primary':
                        self.ParsedSeqRecord.annotations[
                            ann_key] = genename_element.text
                    else:
                        append_to_annotations(ann_key, genename_element.text)

        def _parse_geneLocation(element):
            append_to_annotations('geneLocation', element.attrib['type'])

        def _parse_organism(element):
            organism_name = com_name = sci_name = ''
            for organism_element in element.getchildren():
                if organism_element.tag == NS + 'name':
                    if organism_element.text:
                        if organism_element.attrib['type'] == 'scientific':
                            sci_name = organism_element.text
                        elif organism_element.attrib['type'] == 'common':
                            com_name = organism_element.text
                        else:
                            #e.g. synonym
                            append_to_annotations("organism_name",
                                                  organism_element.text)
                elif organism_element.tag == NS + 'dbReference':
                    self.ParsedSeqRecord.dbxrefs.append(
                        organism_element.attrib['type'] + ':' +
                        organism_element.attrib['id'])
                elif organism_element.tag == NS + 'lineage':
                    for taxon_element in organism_element.getchildren():
                        if taxon_element.tag == NS + 'taxon':
                            append_to_annotations('taxonomy',
                                                  taxon_element.text)
            if sci_name and com_name:
                organism_name = '%s (%s)' % (sci_name, com_name)
            elif sci_name:
                organism_name = sci_name
            elif com_name:
                organism_name = com_name
            self.ParsedSeqRecord.annotations['organism'] = organism_name

        def _parse_organismHost(element):
            for organism_element in element.getchildren():
                if organism_element.tag == NS + 'name':
                    append_to_annotations("organism_host",
                                          organism_element.text)

        def _parse_keyword(element):
            append_to_annotations('keywords', element.text)

        def _parse_comment(element):
            """Parse comments (PRIVATE).

            Comment fields are very heterogeneus. each type has his own (frequently mutated) schema.
            To store all the contained data, more complex data structures are needed, such as
            annidated dictionaries. This is left to end user, by optionally setting:

            return_raw_comments=True

            the orginal XMLs is returned in the annotation fields.

            available comment types at december 2009:
                "allergen"
                "alternative products"
                "biotechnology"
                "biophysicochemical properties"
                "catalytic activity"
                "caution"
                "cofactor"
                "developmental stage"
                "disease"
                "domain"
                "disruption phenotype"
                "enzyme regulation"
                "function"
                "induction"
                "miscellaneous"
                "pathway"
                "pharmaceutical"
                "polymorphism"
                "PTM"
                "RNA editing"
                "similarity"
                "subcellular location"
                "sequence caution"
                "subunit"
                "tissue specificity"
                "toxic dose"
                "online information"
                "mass spectrometry"
                "interaction"
            """

            simple_comments = [
                "allergen",
                "biotechnology",
                "biophysicochemical properties",
                "catalytic activity",
                "caution",
                "cofactor",
                "developmental stage",
                "disease",
                "domain",
                "disruption phenotype",
                "enzyme regulation",
                "function",
                "induction",
                "miscellaneous",
                "pathway",
                "pharmaceutical",
                "polymorphism",
                "PTM",
                "RNA editing",  #positions not parsed
                "similarity",
                "subunit",
                "tissue specificity",
                "toxic dose",
            ]

            if element.attrib['type'] in simple_comments:
                ann_key = 'comment_%s' % element.attrib['type'].replace(
                    ' ', '')
                for text_element in element.getiterator(NS + 'text'):
                    if text_element.text:
                        append_to_annotations(ann_key, text_element.text)
            elif element.attrib['type'] == 'subcellular location':
                for subloc_element in element.getiterator(
                        NS + 'subcellularLocation'):
                    for el in subloc_element.getchildren():
                        if el.text:
                            ann_key = 'comment_%s_%s' % (
                                element.attrib['type'].replace(
                                    ' ', ''), el.tag.replace(NS, ''))
                            append_to_annotations(ann_key, el.text)
            elif element.attrib['type'] == 'interaction':
                for interact_element in element.getiterator(NS +
                                                            'interactant'):
                    ann_key = 'comment_%s_intactId' % element.attrib['type']
                    append_to_annotations(ann_key,
                                          interact_element.attrib['intactId'])
            elif element.attrib['type'] == 'alternative products':
                for alt_element in element.getiterator(NS + 'isoform'):
                    ann_key = 'comment_%s_isoform' % element.attrib[
                        'type'].replace(' ', '')
                    for id_element in alt_element.getiterator(NS + 'id'):
                        append_to_annotations(ann_key, id_element.text)
            elif element.attrib['type'] == 'mass spectrometry':
                ann_key = 'comment_%s' % element.attrib['type'].replace(
                    ' ', '')
                start = end = 0
                for loc_element in element.getiterator(NS + 'location'):
                    pos_els = loc_element.getiterator(NS + 'position')
                    pos_els = list(pos_els)
                    # this try should be avoided, maybe it is safer to skip postion parsing for mass spectrometry
                    try:
                        if pos_els:
                            end = int(pos_els[0].attrib['position'])
                            start = end - 1
                        else:
                            start = int(
                                loc_element.getiterator(NS + 'begin')
                                [0].attrib['position']) - 1
                            end = int(
                                loc_element.getiterator(NS + 'end')
                                [0].attrib['position'])
                    except:  #undefined positions or erroneusly mapped
                        pass
                mass = element.attrib['mass']
                method = element.attrib[
                    'mass']  #TODO - Check this, looks wrong!
                if start == end == 0:
                    append_to_annotations(ann_key,
                                          'undefined:%s|%s' % (mass, method))
                else:
                    append_to_annotations(
                        ann_key, '%s..%s:%s|%s' % (start, end, mass, method))
            elif element.attrib['type'] == 'sequence caution':
                pass  #not parsed: few information, complex structure
            elif element.attrib['type'] == 'online information':
                for link_element in element.getiterator(NS + 'link'):
                    ann_key = 'comment_%s' % element.attrib['type'].replace(
                        ' ', '')
                    for id_element in link_element.getiterator(NS + 'link'):
                        append_to_annotations(
                            ann_key, '%s@%s' % (element.attrib['name'],
                                                link_element.attrib['uri']))

            #return raw XML comments if needed
            if self.return_raw_comments:
                ann_key = 'comment_%s_xml' % element.attrib['type'].replace(
                    ' ', '')
                append_to_annotations(ann_key, ElementTree.tostring(element))

        def _parse_dbReference(element):
            self.ParsedSeqRecord.dbxrefs.append(element.attrib['type'] + ':' +
                                                element.attrib['id'])
            #e.g.
            # <dbReference type="PDB" key="11" id="2GEZ">
            #   <property value="X-ray" type="method"/>
            #   <property value="2.60 A" type="resolution"/>
            #   <property value="A/C/E/G=1-192, B/D/F/H=193-325" type="chains"/>
            # </dbReference>
            if 'type' in element.attrib:
                if element.attrib['type'] == 'PDB':
                    method = ""
                    resolution = ""
                    for ref_element in element.getchildren():
                        if ref_element.tag == NS + 'property':
                            dat_type = ref_element.attrib['type']
                            if dat_type == 'method':
                                method = ref_element.attrib['value']
                            if dat_type == 'resolution':
                                resolution = ref_element.attrib['value']
                            if dat_type == 'chains':
                                pairs = ref_element.attrib['value'].split(',')
                                for elem in pairs:
                                    pair = elem.strip().split('=')
                                    if pair[1] != '-':
                                        #TODO - How best to store these, do SeqFeatures make sense?
                                        feature = SeqFeature.SeqFeature()
                                        feature.type = element.attrib['type']
                                        feature.qualifiers[
                                            'name'] = element.attrib['id']
                                        feature.qualifiers['method'] = method
                                        feature.qualifiers[
                                            'resolution'] = resolution
                                        feature.qualifiers['chains'] = pair[
                                            0].split('/')
                                        start = int(pair[1].split('-')[0]) - 1
                                        end = int(pair[1].split('-')[1])
                                        feature.location = SeqFeature.FeatureLocation(
                                            start, end)
                                        #self.ParsedSeqRecord.features.append(feature)

            for ref_element in element.getchildren():
                if ref_element.tag == NS + 'property':
                    pass  # this data cannot be fitted in a seqrecord object with a simple list. however at least ensembl and EMBL parsing can be improved to add entries in dbxrefs

        def _parse_reference(element):
            reference = SeqFeature.Reference()
            authors = []
            scopes = []
            tissues = []
            journal_name = ''
            pub_type = ''
            pub_date = ''
            for ref_element in element.getchildren():
                if ref_element.tag == NS + 'citation':
                    pub_type = ref_element.attrib['type']
                    if pub_type == 'submission':
                        pub_type += ' to the ' + ref_element.attrib['db']
                    if 'name' in ref_element.attrib:
                        journal_name = ref_element.attrib['name']
                    pub_date = ref_element.attrib.get('date', '')
                    j_volume = ref_element.attrib.get('volume', '')
                    j_first = ref_element.attrib.get('first', '')
                    j_last = ref_element.attrib.get('last', '')
                    for cit_element in ref_element.getchildren():
                        if cit_element.tag == NS + 'title':
                            reference.title = cit_element.text
                        elif cit_element.tag == NS + 'authorList':
                            for person_element in cit_element.getchildren():
                                authors.append(person_element.attrib['name'])
                        elif cit_element.tag == NS + 'dbReference':
                            self.ParsedSeqRecord.dbxrefs.append(
                                cit_element.attrib['type'] + ':' +
                                cit_element.attrib['id'])
                            if cit_element.attrib['type'] == 'PubMed':
                                reference.pubmed_id = cit_element.attrib['id']
                            elif ref_element.attrib['type'] == 'MEDLINE':
                                reference.medline_id = cit_element.attrib['id']
                elif ref_element.tag == NS + 'scope':
                    scopes.append(ref_element.text)
                elif ref_element.tag == NS + 'source':
                    for source_element in ref_element.getchildren():
                        if source_element.tag == NS + 'tissue':
                            tissues.append(source_element.text)
            if scopes:
                scopes_str = 'Scope: ' + ', '.join(scopes)
            else:
                scopes_str = ''
            if tissues:
                tissues_str = 'Tissue: ' + ', '.join(tissues)
            else:
                tissues_str = ''

            reference.location = [
            ]  #locations cannot be parsed since they are actually written in free text inside scopes so all the references are put in the annotation.
            reference.authors = ', '.join(authors)
            if journal_name:
                if pub_date and j_volume and j_first and j_last:
                    reference.journal = REFERENCE_JOURNAL % dict(
                        name=journal_name,
                        volume=j_volume,
                        first=j_first,
                        last=j_last,
                        pub_date=pub_date)
                else:
                    reference.journal = journal_name
            reference.comment = ' | '.join(
                (pub_type, pub_date, scopes_str, tissues_str))
            append_to_annotations('references', reference)

        def _parse_position(element, offset=0):
            try:
                position = int(element.attrib['position']) + offset
            except KeyError, err:
                position = None
            status = element.attrib.get('status', '')
            if status == 'unknown':
                assert position is None
                return SeqFeature.UnknownPosition()
            elif not status:
                return SeqFeature.ExactPosition(position)
            elif status == 'greater than':
                return SeqFeature.AfterPosition(position)
            elif status == 'less than':
                return SeqFeature.BeforePosition(position)
            elif status == 'uncertain':
                return SeqFeature.UncertainPosition(position)
            else:
                raise NotImplementedError("Position status %r" % status)