Reset repository and upload final project (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/_base.py +45 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer2_text.py +377 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_domtab.py +378 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_tab.py +337 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_text.py +457 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.__base.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_tab.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_text.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/__init__.py +233 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/_base.py +39 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_tab.py +486 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_text.py +542 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/._interproscan_xml.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/__init__.py +96 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/interproscan_xml.py +196 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/__init__.py +684 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_index.py +35 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.__base.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hit.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hsp.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._query.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/__init__.py +59 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/_base.py +69 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hit.py +464 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hsp.py +1228 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/query.py +737 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_utils.py +169 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/Seq.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py +2332 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AbiIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AceIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._FastaIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GckIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GfaIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._IgIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._InsdcIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._Interfaces.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._NibIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PdbIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PhdIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PirIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._QualityIO.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SeqXmlIO.py +0 -0
.gitattributes
CHANGED
|
@@ -63,3 +63,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 63 |
.venv_haddock/bin/python3.12 filter=lfs diff=lfs merge=lfs -text
|
| 64 |
.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 65 |
.venv_haddock/lib/python3.12/site-packages/Bio/Cluster/_cluster.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 63 |
.venv_haddock/bin/python3.12 filter=lfs diff=lfs merge=lfs -text
|
| 64 |
.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 65 |
.venv_haddock/lib/python3.12/site-packages/Bio/Cluster/_cluster.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
.venv_haddock/lib/python3.12/site-packages/freesasa.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
.venv_haddock/lib/python3.12/site-packages/haddock/bin/haddock-restraints filter=lfs diff=lfs merge=lfs -text
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/_base.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO base classes for HMMER-related code."""
|
| 7 |
+
|
| 8 |
+
from Bio.SearchIO._index import SearchIndexer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class _BaseHmmerTextIndexer(SearchIndexer):
|
| 12 |
+
"""Base indexer class for HMMER plain text output."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, *args, **kwargs):
|
| 15 |
+
super().__init__(*args, **kwargs)
|
| 16 |
+
self._preamble = b""
|
| 17 |
+
|
| 18 |
+
def get_raw(self, offset):
|
| 19 |
+
"""Return the raw record from the file as a bytes string."""
|
| 20 |
+
handle = self._handle
|
| 21 |
+
qresult_raw = b""
|
| 22 |
+
|
| 23 |
+
# read header first
|
| 24 |
+
if not self._preamble:
|
| 25 |
+
handle.seek(0)
|
| 26 |
+
while True:
|
| 27 |
+
line = handle.readline()
|
| 28 |
+
if line.startswith(self.qresult_start):
|
| 29 |
+
break
|
| 30 |
+
qresult_raw += line
|
| 31 |
+
else:
|
| 32 |
+
qresult_raw += self._preamble
|
| 33 |
+
|
| 34 |
+
# and read the qresult raw string
|
| 35 |
+
handle.seek(offset)
|
| 36 |
+
while True:
|
| 37 |
+
# preserve whitespace, don't use read_forward
|
| 38 |
+
line = handle.readline()
|
| 39 |
+
qresult_raw += line
|
| 40 |
+
|
| 41 |
+
# break when we've reached qresult end
|
| 42 |
+
if line.startswith(self.qresult_end) or not line:
|
| 43 |
+
break
|
| 44 |
+
|
| 45 |
+
return qresult_raw
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer2_text.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Kai Blin. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO parser for HMMER 2 text output."""
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._model import Hit
|
| 11 |
+
from Bio.SearchIO._model import HSP
|
| 12 |
+
from Bio.SearchIO._model import HSPFragment
|
| 13 |
+
from Bio.SearchIO._model import QueryResult
|
| 14 |
+
from Bio.SearchIO._utils import read_forward
|
| 15 |
+
|
| 16 |
+
from ._base import _BaseHmmerTextIndexer
|
| 17 |
+
|
| 18 |
+
__all__ = ("Hmmer2TextParser", "Hmmer2TextIndexer")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
_HSP_ALIGN_LINE = re.compile(r"(\S+):\s+domain (\d+) of (\d+)")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _HitPlaceholder:
|
| 25 |
+
def createHit(self, hsp_list):
|
| 26 |
+
hit = Hit(hsp_list)
|
| 27 |
+
hit.id_ = self.id_
|
| 28 |
+
hit.evalue = self.evalue
|
| 29 |
+
hit.bitscore = self.bitscore
|
| 30 |
+
if self.description:
|
| 31 |
+
hit.description = self.description
|
| 32 |
+
hit.domain_obs_num = self.domain_obs_num
|
| 33 |
+
return hit
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Hmmer2TextParser:
|
| 37 |
+
"""Iterator for the HMMER 2.0 text output."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, handle):
|
| 40 |
+
"""Initialize the class."""
|
| 41 |
+
self.handle = handle
|
| 42 |
+
self.buf = []
|
| 43 |
+
self._meta = self.parse_preamble()
|
| 44 |
+
|
| 45 |
+
def __iter__(self):
|
| 46 |
+
"""Iterate over Hmmer2TextParser, yields query results."""
|
| 47 |
+
for qresult in self.parse_qresult():
|
| 48 |
+
qresult.program = self._meta.get("program")
|
| 49 |
+
qresult.target = self._meta.get("target")
|
| 50 |
+
qresult.version = self._meta.get("version")
|
| 51 |
+
yield qresult
|
| 52 |
+
|
| 53 |
+
def read_next(self, rstrip=True):
|
| 54 |
+
"""Return the next non-empty line, trailing whitespace removed."""
|
| 55 |
+
if len(self.buf) > 0:
|
| 56 |
+
return self.buf.pop()
|
| 57 |
+
self.line = self.handle.readline()
|
| 58 |
+
while self.line and rstrip and not self.line.strip():
|
| 59 |
+
self.line = self.handle.readline()
|
| 60 |
+
if self.line:
|
| 61 |
+
if rstrip:
|
| 62 |
+
self.line = self.line.rstrip()
|
| 63 |
+
return self.line
|
| 64 |
+
|
| 65 |
+
def push_back(self, line):
|
| 66 |
+
"""Un-read a line that should not be parsed yet."""
|
| 67 |
+
self.buf.append(line)
|
| 68 |
+
|
| 69 |
+
def parse_key_value(self):
|
| 70 |
+
"""Parse key-value pair separated by colon."""
|
| 71 |
+
key, value = self.line.split(":", 1)
|
| 72 |
+
return key.strip(), value.strip()
|
| 73 |
+
|
| 74 |
+
def parse_preamble(self):
|
| 75 |
+
"""Parse HMMER2 preamble."""
|
| 76 |
+
meta = {}
|
| 77 |
+
state = "GENERIC"
|
| 78 |
+
while self.read_next():
|
| 79 |
+
if state == "GENERIC":
|
| 80 |
+
if self.line.startswith("hmm"):
|
| 81 |
+
meta["program"] = self.line.split("-")[0].strip()
|
| 82 |
+
elif self.line.startswith("HMMER is"):
|
| 83 |
+
continue
|
| 84 |
+
elif self.line.startswith("HMMER"):
|
| 85 |
+
meta["version"] = self.line.split()[1]
|
| 86 |
+
elif self.line.count("-") == 36:
|
| 87 |
+
state = "OPTIONS"
|
| 88 |
+
continue
|
| 89 |
+
|
| 90 |
+
assert state == "OPTIONS"
|
| 91 |
+
assert "program" in meta
|
| 92 |
+
|
| 93 |
+
if self.line.count("-") == 32:
|
| 94 |
+
break
|
| 95 |
+
|
| 96 |
+
key, value = self.parse_key_value()
|
| 97 |
+
if meta["program"] == "hmmsearch":
|
| 98 |
+
if key == "Sequence database":
|
| 99 |
+
meta["target"] = value
|
| 100 |
+
continue
|
| 101 |
+
elif meta["program"] == "hmmpfam":
|
| 102 |
+
if key == "HMM file":
|
| 103 |
+
meta["target"] = value
|
| 104 |
+
continue
|
| 105 |
+
meta[key] = value
|
| 106 |
+
|
| 107 |
+
return meta
|
| 108 |
+
|
| 109 |
+
def parse_qresult(self):
|
| 110 |
+
"""Parse a HMMER2 query block."""
|
| 111 |
+
while self.read_next():
|
| 112 |
+
if not self.line.startswith("Query"):
|
| 113 |
+
return
|
| 114 |
+
_, id_ = self.parse_key_value()
|
| 115 |
+
self.qresult = QueryResult(id=id_)
|
| 116 |
+
|
| 117 |
+
description = None
|
| 118 |
+
|
| 119 |
+
while self.read_next() and not self.line.startswith("Scores"):
|
| 120 |
+
if self.line.startswith("Accession"):
|
| 121 |
+
self.qresult.accession = self.parse_key_value()[1]
|
| 122 |
+
if self.line.startswith("Description"):
|
| 123 |
+
description = self.parse_key_value()[1]
|
| 124 |
+
|
| 125 |
+
hit_placeholders = self.parse_hits()
|
| 126 |
+
if len(hit_placeholders) > 0:
|
| 127 |
+
self.parse_hsps(hit_placeholders)
|
| 128 |
+
self.parse_hsp_alignments()
|
| 129 |
+
|
| 130 |
+
while not self.line.startswith("Query"):
|
| 131 |
+
self.read_next()
|
| 132 |
+
if not self.line:
|
| 133 |
+
break
|
| 134 |
+
self.buf.append(self.line)
|
| 135 |
+
|
| 136 |
+
if description is not None:
|
| 137 |
+
self.qresult.description = description
|
| 138 |
+
yield self.qresult
|
| 139 |
+
|
| 140 |
+
def parse_hits(self):
|
| 141 |
+
"""Parse a HMMER2 hit block, beginning with the hit table."""
|
| 142 |
+
hit_placeholders = []
|
| 143 |
+
while self.read_next():
|
| 144 |
+
if self.line.startswith("Parsed"):
|
| 145 |
+
break
|
| 146 |
+
if self.line.find("no hits") > -1:
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
if (
|
| 150 |
+
self.line.startswith("Sequence")
|
| 151 |
+
or self.line.startswith("Model")
|
| 152 |
+
or self.line.startswith("-------- ")
|
| 153 |
+
):
|
| 154 |
+
continue
|
| 155 |
+
|
| 156 |
+
fields = self.line.split()
|
| 157 |
+
id_ = fields.pop(0)
|
| 158 |
+
domain_obs_num = int(fields.pop())
|
| 159 |
+
evalue = float(fields.pop())
|
| 160 |
+
bitscore = float(fields.pop())
|
| 161 |
+
description = " ".join(fields).strip()
|
| 162 |
+
|
| 163 |
+
hit = _HitPlaceholder()
|
| 164 |
+
hit.id_ = id_
|
| 165 |
+
hit.evalue = evalue
|
| 166 |
+
hit.bitscore = bitscore
|
| 167 |
+
hit.description = description
|
| 168 |
+
hit.domain_obs_num = domain_obs_num
|
| 169 |
+
hit_placeholders.append(hit)
|
| 170 |
+
|
| 171 |
+
return hit_placeholders
|
| 172 |
+
|
| 173 |
+
def parse_hsps(self, hit_placeholders):
|
| 174 |
+
"""Parse a HMMER2 hsp block, beginning with the hsp table."""
|
| 175 |
+
# HSPs may occur in different order than the hits
|
| 176 |
+
# so store Hit objects separately first
|
| 177 |
+
unordered_hits = {}
|
| 178 |
+
while self.read_next():
|
| 179 |
+
if (
|
| 180 |
+
self.line.startswith("Alignments")
|
| 181 |
+
or self.line.startswith("Histogram")
|
| 182 |
+
or self.line == "//"
|
| 183 |
+
):
|
| 184 |
+
break
|
| 185 |
+
if (
|
| 186 |
+
self.line.startswith("Model")
|
| 187 |
+
or self.line.startswith("Sequence")
|
| 188 |
+
or self.line.startswith("--------")
|
| 189 |
+
):
|
| 190 |
+
continue
|
| 191 |
+
|
| 192 |
+
(
|
| 193 |
+
id_,
|
| 194 |
+
domain,
|
| 195 |
+
seq_f,
|
| 196 |
+
seq_t,
|
| 197 |
+
seq_compl,
|
| 198 |
+
hmm_f,
|
| 199 |
+
hmm_t,
|
| 200 |
+
hmm_compl,
|
| 201 |
+
score,
|
| 202 |
+
evalue,
|
| 203 |
+
) = self.line.split()
|
| 204 |
+
|
| 205 |
+
frag = HSPFragment(id_, self.qresult.id)
|
| 206 |
+
frag.molecule_type = "protein"
|
| 207 |
+
if self._meta["program"] == "hmmpfam":
|
| 208 |
+
frag.hit_start = int(hmm_f) - 1
|
| 209 |
+
frag.hit_end = int(hmm_t)
|
| 210 |
+
frag.query_start = int(seq_f) - 1
|
| 211 |
+
frag.query_end = int(seq_t)
|
| 212 |
+
elif self._meta["program"] == "hmmsearch":
|
| 213 |
+
frag.query_start = int(hmm_f) - 1
|
| 214 |
+
frag.query_end = int(hmm_t)
|
| 215 |
+
frag.hit_start = int(seq_f) - 1
|
| 216 |
+
frag.hit_end = int(seq_t)
|
| 217 |
+
|
| 218 |
+
hsp = HSP([frag])
|
| 219 |
+
hsp.evalue = float(evalue)
|
| 220 |
+
hsp.bitscore = float(score)
|
| 221 |
+
hsp.domain_index = int(domain.split("/")[0])
|
| 222 |
+
if self._meta["program"] == "hmmpfam":
|
| 223 |
+
hsp.hit_endtype = hmm_compl
|
| 224 |
+
hsp.query_endtype = seq_compl
|
| 225 |
+
elif self._meta["program"] == "hmmsearch":
|
| 226 |
+
hsp.query_endtype = hmm_compl
|
| 227 |
+
hsp.hit_endtype = seq_compl
|
| 228 |
+
|
| 229 |
+
if id_ not in unordered_hits:
|
| 230 |
+
placeholder = [p for p in hit_placeholders if p.id_ == id_][0]
|
| 231 |
+
hit = placeholder.createHit([hsp])
|
| 232 |
+
unordered_hits[id_] = hit
|
| 233 |
+
else:
|
| 234 |
+
hit = unordered_hits[id_]
|
| 235 |
+
hsp.hit_description = hit.description
|
| 236 |
+
hit.append(hsp)
|
| 237 |
+
|
| 238 |
+
# The placeholder list is in the correct order, so use that order for
|
| 239 |
+
# the Hit objects in the qresult
|
| 240 |
+
for p in hit_placeholders:
|
| 241 |
+
self.qresult.append(unordered_hits[p.id_])
|
| 242 |
+
|
| 243 |
+
def parse_hsp_alignments(self):
|
| 244 |
+
"""Parse a HMMER2 HSP alignment block."""
|
| 245 |
+
if not self.line.startswith("Alignments"):
|
| 246 |
+
return
|
| 247 |
+
|
| 248 |
+
while self.read_next():
|
| 249 |
+
if self.line == "//" or self.line.startswith("Histogram"):
|
| 250 |
+
break
|
| 251 |
+
|
| 252 |
+
match = re.search(_HSP_ALIGN_LINE, self.line)
|
| 253 |
+
if match is None:
|
| 254 |
+
continue
|
| 255 |
+
|
| 256 |
+
id_ = match.group(1)
|
| 257 |
+
idx = int(match.group(2))
|
| 258 |
+
num = int(match.group(3))
|
| 259 |
+
|
| 260 |
+
hit = self.qresult[id_]
|
| 261 |
+
if hit.domain_obs_num != num:
|
| 262 |
+
continue
|
| 263 |
+
|
| 264 |
+
frag = hit[idx - 1][0]
|
| 265 |
+
|
| 266 |
+
hmmseq = ""
|
| 267 |
+
consensus = ""
|
| 268 |
+
otherseq = ""
|
| 269 |
+
structureseq = ""
|
| 270 |
+
pad = 0
|
| 271 |
+
while self.read_next() and self.line.startswith(" "):
|
| 272 |
+
# if there's structure information, parse that
|
| 273 |
+
if self.line[16:18] == "CS":
|
| 274 |
+
structureseq += self.line[19:].strip()
|
| 275 |
+
|
| 276 |
+
if not self.read_next():
|
| 277 |
+
break
|
| 278 |
+
|
| 279 |
+
# skip the *-> start marker if it exists
|
| 280 |
+
if self.line[19:22] == "*->":
|
| 281 |
+
seq = self.line[22:]
|
| 282 |
+
pad = 3
|
| 283 |
+
else:
|
| 284 |
+
seq = self.line[19:]
|
| 285 |
+
pad = 0
|
| 286 |
+
|
| 287 |
+
hmmseq += seq
|
| 288 |
+
line_len = len(seq)
|
| 289 |
+
if not self.read_next(rstrip=False):
|
| 290 |
+
break
|
| 291 |
+
consensus += self.line[19 + pad : 19 + pad + line_len]
|
| 292 |
+
# If there's no consensus sequence, hmmer2 doesn't
|
| 293 |
+
# bother to put spaces here, so add extra padding
|
| 294 |
+
extra_padding = len(hmmseq) - len(consensus)
|
| 295 |
+
consensus += " " * extra_padding
|
| 296 |
+
|
| 297 |
+
if not self.read_next():
|
| 298 |
+
break
|
| 299 |
+
|
| 300 |
+
# if we have a line break in the end marker, we get a
|
| 301 |
+
# whitespace-only otherseq line, making split()[0] return
|
| 302 |
+
# the end coordinate. That'll be a -, which is a valid character
|
| 303 |
+
# in the sequence, meaning we can't just strip it.
|
| 304 |
+
parts = self.line[19:].split()
|
| 305 |
+
if len(parts) == 2:
|
| 306 |
+
otherseq += self.line[19:].split()[0].strip()
|
| 307 |
+
|
| 308 |
+
self.push_back(self.line)
|
| 309 |
+
|
| 310 |
+
# get rid of the end marker
|
| 311 |
+
if hmmseq.endswith("<-*"):
|
| 312 |
+
hmmseq = hmmseq[:-3]
|
| 313 |
+
consensus = consensus[:-3]
|
| 314 |
+
|
| 315 |
+
# add similarity sequence to annotation
|
| 316 |
+
frag.aln_annotation["similarity"] = consensus
|
| 317 |
+
|
| 318 |
+
# if there's structure information, add it to the fragment
|
| 319 |
+
if structureseq:
|
| 320 |
+
frag.aln_annotation["CS"] = structureseq
|
| 321 |
+
|
| 322 |
+
if self._meta["program"] == "hmmpfam":
|
| 323 |
+
frag.hit = hmmseq
|
| 324 |
+
frag.query = otherseq
|
| 325 |
+
else:
|
| 326 |
+
frag.hit = otherseq
|
| 327 |
+
frag.query = hmmseq
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class Hmmer2TextIndexer(_BaseHmmerTextIndexer):
|
| 331 |
+
"""Indexer for hmmer2-text format."""
|
| 332 |
+
|
| 333 |
+
_parser = Hmmer2TextParser
|
| 334 |
+
qresult_start = b"Query"
|
| 335 |
+
# qresults_ends for hmmpfam and hmmsearch
|
| 336 |
+
# need to anticipate both since hmmsearch have different query end mark
|
| 337 |
+
qresult_end = b"//"
|
| 338 |
+
|
| 339 |
+
def __iter__(self):
|
| 340 |
+
"""Iterate over Hmmer2TextIndexer; yields query results' key, offsets, 0."""
|
| 341 |
+
handle = self._handle
|
| 342 |
+
handle.seek(0)
|
| 343 |
+
start_offset = handle.tell()
|
| 344 |
+
regex_id = re.compile(rb"Query\s*(?:sequence|HMM)?:\s*(.*)")
|
| 345 |
+
|
| 346 |
+
# determine flag for hmmsearch
|
| 347 |
+
is_hmmsearch = False
|
| 348 |
+
line = read_forward(handle)
|
| 349 |
+
if line.startswith(b"hmmsearch"):
|
| 350 |
+
is_hmmsearch = True
|
| 351 |
+
|
| 352 |
+
while True:
|
| 353 |
+
end_offset = handle.tell()
|
| 354 |
+
|
| 355 |
+
if line.startswith(self.qresult_start):
|
| 356 |
+
regx = re.search(regex_id, line)
|
| 357 |
+
qresult_key = regx.group(1).strip()
|
| 358 |
+
# qresult start offset is the offset of this line
|
| 359 |
+
# (starts with the start mark)
|
| 360 |
+
start_offset = end_offset - len(line)
|
| 361 |
+
elif line.startswith(self.qresult_end):
|
| 362 |
+
yield qresult_key.decode(), start_offset, 0
|
| 363 |
+
start_offset = end_offset
|
| 364 |
+
elif not line:
|
| 365 |
+
# HACK: since hmmsearch can only have one query result
|
| 366 |
+
if is_hmmsearch:
|
| 367 |
+
yield qresult_key.decode(), start_offset, 0
|
| 368 |
+
break
|
| 369 |
+
|
| 370 |
+
line = read_forward(handle)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# if not used as a module, run the doctest
|
| 374 |
+
if __name__ == "__main__":
|
| 375 |
+
from Bio._utils import run_doctest
|
| 376 |
+
|
| 377 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_domtab.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO parser for HMMER domain table output format."""
|
| 7 |
+
|
| 8 |
+
from itertools import chain
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._model import Hit
|
| 11 |
+
from Bio.SearchIO._model import HSP
|
| 12 |
+
from Bio.SearchIO._model import HSPFragment
|
| 13 |
+
from Bio.SearchIO._model import QueryResult
|
| 14 |
+
|
| 15 |
+
from .hmmer3_tab import Hmmer3TabIndexer
|
| 16 |
+
from .hmmer3_tab import Hmmer3TabParser
|
| 17 |
+
|
| 18 |
+
__all__ = (
|
| 19 |
+
"Hmmer3DomtabHmmhitParser",
|
| 20 |
+
"Hmmer3DomtabHmmqueryParser",
|
| 21 |
+
"Hmmer3DomtabHmmhitIndexer",
|
| 22 |
+
"Hmmer3DomtabHmmqueryIndexer",
|
| 23 |
+
"Hmmer3DomtabHmmhitWriter",
|
| 24 |
+
"Hmmer3DomtabHmmqueryWriter",
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Hmmer3DomtabParser(Hmmer3TabParser):
|
| 29 |
+
"""Base hmmer3-domtab iterator."""
|
| 30 |
+
|
| 31 |
+
def _parse_row(self):
|
| 32 |
+
"""Return a dictionary of parsed row values (PRIVATE)."""
|
| 33 |
+
assert self.line
|
| 34 |
+
cols = [x for x in self.line.strip().split(" ") if x]
|
| 35 |
+
# if len(cols) > 23, we have extra description columns
|
| 36 |
+
# combine them all into one string in the 19th column
|
| 37 |
+
if len(cols) > 23:
|
| 38 |
+
cols[22] = " ".join(cols[22:])
|
| 39 |
+
elif len(cols) < 23:
|
| 40 |
+
cols.append("")
|
| 41 |
+
assert len(cols) == 23
|
| 42 |
+
|
| 43 |
+
# assign parsed column data into qresult, hit, and hsp dicts
|
| 44 |
+
qresult = {}
|
| 45 |
+
qresult["id"] = cols[3] # query name
|
| 46 |
+
qresult["accession"] = cols[4] # query accession
|
| 47 |
+
qresult["seq_len"] = int(cols[5]) # qlen
|
| 48 |
+
hit = {}
|
| 49 |
+
hit["id"] = cols[0] # target name
|
| 50 |
+
hit["accession"] = cols[1] # target accession
|
| 51 |
+
hit["seq_len"] = int(cols[2]) # tlen
|
| 52 |
+
hit["evalue"] = float(cols[6]) # evalue
|
| 53 |
+
hit["bitscore"] = float(cols[7]) # score
|
| 54 |
+
hit["bias"] = float(cols[8]) # bias
|
| 55 |
+
hit["description"] = cols[22] # description of target
|
| 56 |
+
hsp = {}
|
| 57 |
+
hsp["domain_index"] = int(cols[9]) # # (domain number)
|
| 58 |
+
# not parsing cols[10] since it's basically len(hit)
|
| 59 |
+
hsp["evalue_cond"] = float(cols[11]) # c-evalue
|
| 60 |
+
hsp["evalue"] = float(cols[12]) # i-evalue
|
| 61 |
+
hsp["bitscore"] = float(cols[13]) # score
|
| 62 |
+
hsp["bias"] = float(cols[14]) # bias
|
| 63 |
+
hsp["env_start"] = int(cols[19]) - 1 # env from
|
| 64 |
+
hsp["env_end"] = int(cols[20]) # env to
|
| 65 |
+
hsp["acc_avg"] = float(cols[21]) # acc
|
| 66 |
+
frag = {}
|
| 67 |
+
# strand is always 0, since HMMER now only handles protein
|
| 68 |
+
frag["hit_strand"] = frag["query_strand"] = 0
|
| 69 |
+
frag["hit_start"] = int(cols[15]) - 1 # hmm from
|
| 70 |
+
frag["hit_end"] = int(cols[16]) # hmm to
|
| 71 |
+
frag["query_start"] = int(cols[17]) - 1 # ali from
|
| 72 |
+
frag["query_end"] = int(cols[18]) # ali to
|
| 73 |
+
# HMMER results are always protein
|
| 74 |
+
frag["molecule_type"] = "protein"
|
| 75 |
+
|
| 76 |
+
# switch hmm<-->ali coordinates if hmm is not hit
|
| 77 |
+
if not self.hmm_as_hit:
|
| 78 |
+
frag["hit_end"], frag["query_end"] = (frag["query_end"], frag["hit_end"])
|
| 79 |
+
frag["hit_start"], frag["query_start"] = (
|
| 80 |
+
frag["query_start"],
|
| 81 |
+
frag["hit_start"],
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
return {"qresult": qresult, "hit": hit, "hsp": hsp, "frag": frag}
|
| 85 |
+
|
| 86 |
+
def _parse_qresult(self):
|
| 87 |
+
"""Return QueryResult objects (PRIVATE)."""
|
| 88 |
+
# state values, determines what to do for each line
|
| 89 |
+
state_EOF = 0
|
| 90 |
+
state_QRES_NEW = 1
|
| 91 |
+
state_QRES_SAME = 3
|
| 92 |
+
state_HIT_NEW = 2
|
| 93 |
+
state_HIT_SAME = 4
|
| 94 |
+
# dummies for initial states
|
| 95 |
+
qres_state = None
|
| 96 |
+
hit_state = None
|
| 97 |
+
file_state = None
|
| 98 |
+
# dummies for initial id caches
|
| 99 |
+
prev_qid = None
|
| 100 |
+
prev_hid = None
|
| 101 |
+
# dummies for initial parsed value containers
|
| 102 |
+
cur, prev = None, None
|
| 103 |
+
hit_list, hsp_list = [], []
|
| 104 |
+
cur_qid = None
|
| 105 |
+
cur_hid = None
|
| 106 |
+
while True:
|
| 107 |
+
# store previous line's parsed values, for every line after the 1st
|
| 108 |
+
if cur is not None:
|
| 109 |
+
prev = cur
|
| 110 |
+
prev_qid = cur_qid
|
| 111 |
+
prev_hid = cur_hid
|
| 112 |
+
# only parse the line if it's not EOF
|
| 113 |
+
if self.line and not self.line.startswith("#"):
|
| 114 |
+
cur = self._parse_row()
|
| 115 |
+
cur_qid = cur["qresult"]["id"]
|
| 116 |
+
cur_hid = cur["hit"]["id"]
|
| 117 |
+
else:
|
| 118 |
+
file_state = state_EOF
|
| 119 |
+
# mock ID values since the line is empty
|
| 120 |
+
cur_qid, cur_hid = None, None
|
| 121 |
+
|
| 122 |
+
# get the state of hit and qresult
|
| 123 |
+
if prev_qid != cur_qid:
|
| 124 |
+
qres_state = state_QRES_NEW
|
| 125 |
+
else:
|
| 126 |
+
qres_state = state_QRES_SAME
|
| 127 |
+
# new hits are hits with different ids or hits in a new qresult
|
| 128 |
+
if prev_hid != cur_hid or qres_state == state_QRES_NEW:
|
| 129 |
+
hit_state = state_HIT_NEW
|
| 130 |
+
else:
|
| 131 |
+
hit_state = state_HIT_SAME
|
| 132 |
+
|
| 133 |
+
# start creating objects after the first line (i.e. prev is filled)
|
| 134 |
+
if prev is not None:
|
| 135 |
+
# each line is basically an HSP with one HSPFragment
|
| 136 |
+
frag = HSPFragment(prev_hid, prev_qid)
|
| 137 |
+
for attr, value in prev["frag"].items():
|
| 138 |
+
setattr(frag, attr, value)
|
| 139 |
+
hsp = HSP([frag])
|
| 140 |
+
for attr, value in prev["hsp"].items():
|
| 141 |
+
setattr(hsp, attr, value)
|
| 142 |
+
hsp_list.append(hsp)
|
| 143 |
+
|
| 144 |
+
# create hit object when we've finished parsing all its hsps
|
| 145 |
+
# i.e. when hit state is state_HIT_NEW
|
| 146 |
+
if hit_state == state_HIT_NEW:
|
| 147 |
+
hit = Hit(hsp_list)
|
| 148 |
+
for attr, value in prev["hit"].items():
|
| 149 |
+
setattr(hit, attr, value)
|
| 150 |
+
hit_list.append(hit)
|
| 151 |
+
hsp_list = []
|
| 152 |
+
|
| 153 |
+
# create qresult and yield if we're at a new qresult or EOF
|
| 154 |
+
if qres_state == state_QRES_NEW or file_state == state_EOF:
|
| 155 |
+
qresult = QueryResult(hit_list, prev_qid)
|
| 156 |
+
for attr, value in prev["qresult"].items():
|
| 157 |
+
setattr(qresult, attr, value)
|
| 158 |
+
yield qresult
|
| 159 |
+
# if current line is EOF, break
|
| 160 |
+
if file_state == state_EOF:
|
| 161 |
+
break
|
| 162 |
+
hit_list = []
|
| 163 |
+
|
| 164 |
+
self.line = self.handle.readline()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class Hmmer3DomtabHmmhitParser(Hmmer3DomtabParser):
|
| 168 |
+
"""HMMER domain table parser using hit coordinates.
|
| 169 |
+
|
| 170 |
+
Parser for the HMMER domain table format that assumes HMM profile
|
| 171 |
+
coordinates are hit coordinates.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
hmm_as_hit = True
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class Hmmer3DomtabHmmqueryParser(Hmmer3DomtabParser):
|
| 178 |
+
"""HMMER domain table parser using query coordinates.
|
| 179 |
+
|
| 180 |
+
Parser for the HMMER domain table format that assumes HMM profile
|
| 181 |
+
coordinates are query coordinates.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
hmm_as_hit = False
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class Hmmer3DomtabHmmhitIndexer(Hmmer3TabIndexer):
|
| 188 |
+
"""HMMER domain table indexer using hit coordinates.
|
| 189 |
+
|
| 190 |
+
Indexer class for HMMER domain table output that assumes HMM profile
|
| 191 |
+
coordinates are hit coordinates.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
_parser = Hmmer3DomtabHmmhitParser
|
| 195 |
+
_query_id_idx = 3
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Hmmer3DomtabHmmqueryIndexer(Hmmer3TabIndexer):
|
| 199 |
+
"""HMMER domain table indexer using query coordinates.
|
| 200 |
+
|
| 201 |
+
Indexer class for HMMER domain table output that assumes HMM profile
|
| 202 |
+
coordinates are query coordinates.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
_parser = Hmmer3DomtabHmmqueryParser
|
| 206 |
+
_query_id_idx = 3
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class Hmmer3DomtabHmmhitWriter:
|
| 210 |
+
"""HMMER domain table writer using hit coordinates.
|
| 211 |
+
|
| 212 |
+
Writer for hmmer3-domtab output format which writes hit coordinates
|
| 213 |
+
as HMM profile coordinates.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
hmm_as_hit = True
|
| 217 |
+
|
| 218 |
+
def __init__(self, handle):
|
| 219 |
+
"""Initialize the class."""
|
| 220 |
+
self.handle = handle
|
| 221 |
+
|
| 222 |
+
def write_file(self, qresults):
|
| 223 |
+
"""Write to the handle.
|
| 224 |
+
|
| 225 |
+
Returns a tuple of how many QueryResult, Hit, and HSP objects were written.
|
| 226 |
+
|
| 227 |
+
"""
|
| 228 |
+
handle = self.handle
|
| 229 |
+
qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
first_qresult = next(qresults)
|
| 233 |
+
except StopIteration:
|
| 234 |
+
handle.write(self._build_header())
|
| 235 |
+
else:
|
| 236 |
+
# write header
|
| 237 |
+
handle.write(self._build_header(first_qresult))
|
| 238 |
+
# and then the qresults
|
| 239 |
+
for qresult in chain([first_qresult], qresults):
|
| 240 |
+
if qresult:
|
| 241 |
+
handle.write(self._build_row(qresult))
|
| 242 |
+
qresult_counter += 1
|
| 243 |
+
hit_counter += len(qresult)
|
| 244 |
+
hsp_counter += sum(len(hit) for hit in qresult)
|
| 245 |
+
frag_counter += sum(len(hit.fragments) for hit in qresult)
|
| 246 |
+
|
| 247 |
+
return qresult_counter, hit_counter, hsp_counter, frag_counter
|
| 248 |
+
|
| 249 |
+
def _build_header(self, first_qresult=None):
|
| 250 |
+
"""Return the header string of a domain HMMER table output (PRIVATE)."""
|
| 251 |
+
# calculate whitespace required
|
| 252 |
+
# adapted from HMMER's source: src/p7_tophits.c#L1157
|
| 253 |
+
if first_qresult:
|
| 254 |
+
# qnamew = max(20, len(first_qresult.id))
|
| 255 |
+
qnamew = 20
|
| 256 |
+
tnamew = max(20, len(first_qresult[0].id))
|
| 257 |
+
try:
|
| 258 |
+
qaccw = max(10, len(first_qresult.acc))
|
| 259 |
+
taccw = max(10, len(first_qresult[0].acc))
|
| 260 |
+
except AttributeError:
|
| 261 |
+
qaccw, taccw = 10, 10
|
| 262 |
+
else:
|
| 263 |
+
qnamew, tnamew, qaccw, taccw = 20, 20, 10, 10
|
| 264 |
+
# Turn black code style off
|
| 265 |
+
# fmt: off
|
| 266 |
+
header = ("#%*s %22s %40s %11s %11s %11s\n"
|
| 267 |
+
% (tnamew + qnamew - 1 + 15 + taccw + qaccw, "", "--- full sequence ---",
|
| 268 |
+
"-------------- this domain -------------", "hmm coord",
|
| 269 |
+
"ali coord", "env coord"))
|
| 270 |
+
header += ("#%-*s %-*s %5s %-*s %-*s %5s %9s %6s %5s %3s %3s %9s "
|
| 271 |
+
"%9s %6s %5s %5s %5s %5s %5s %5s %5s %4s %s\n"
|
| 272 |
+
% (tnamew - 1,
|
| 273 |
+
" target name", taccw, "accession", "tlen", qnamew,
|
| 274 |
+
"query name", qaccw, "accession", "qlen", "E-value", "score",
|
| 275 |
+
"bias", "#", "of", "c-Evalue", "i-Evalue", "score", "bias",
|
| 276 |
+
"from", "to", "from", "to", "from", "to", "acc",
|
| 277 |
+
"description of target"))
|
| 278 |
+
header += ("#%*s %*s %5s %*s %*s %5s %9s %6s %5s %3s %3s %9s %9s "
|
| 279 |
+
"%6s %5s %5s %5s %5s %5s %5s %5s %4s %s\n"
|
| 280 |
+
% (tnamew - 1,
|
| 281 |
+
"-------------------", taccw, "----------", "-----",
|
| 282 |
+
qnamew, "--------------------", qaccw, "----------",
|
| 283 |
+
"-----", "---------", "------", "-----", "---", "---",
|
| 284 |
+
"---------", "---------", "------", "-----", "-----", "-----",
|
| 285 |
+
"-----", "-----", "-----", "-----", "----",
|
| 286 |
+
"---------------------"))
|
| 287 |
+
# Turn black code style on
|
| 288 |
+
# fmt: on
|
| 289 |
+
return header
|
| 290 |
+
|
| 291 |
+
def _build_row(self, qresult):
|
| 292 |
+
"""Return a string or one row or more of the QueryResult object (PRIVATE)."""
|
| 293 |
+
rows = ""
|
| 294 |
+
|
| 295 |
+
# calculate whitespace required
|
| 296 |
+
# adapted from HMMER's source: src/p7_tophits.c#L1083
|
| 297 |
+
qnamew = max(20, len(qresult.id))
|
| 298 |
+
tnamew = max(20, len(qresult[0].id))
|
| 299 |
+
try:
|
| 300 |
+
qaccw = max(10, len(qresult.accession))
|
| 301 |
+
taccw = max(10, len(qresult[0].accession))
|
| 302 |
+
qresult_acc = qresult.accession
|
| 303 |
+
except AttributeError:
|
| 304 |
+
qaccw, taccw = 10, 10
|
| 305 |
+
qresult_acc = "-"
|
| 306 |
+
|
| 307 |
+
for hit in qresult:
|
| 308 |
+
# try to get hit accession
|
| 309 |
+
try:
|
| 310 |
+
hit_acc = hit.accession
|
| 311 |
+
except AttributeError:
|
| 312 |
+
hit_acc = "-"
|
| 313 |
+
|
| 314 |
+
for hsp in hit.hsps:
|
| 315 |
+
if self.hmm_as_hit:
|
| 316 |
+
hmm_to = hsp.hit_end
|
| 317 |
+
hmm_from = hsp.hit_start + 1
|
| 318 |
+
ali_to = hsp.query_end
|
| 319 |
+
ali_from = hsp.query_start + 1
|
| 320 |
+
else:
|
| 321 |
+
hmm_to = hsp.query_end
|
| 322 |
+
hmm_from = hsp.query_start + 1
|
| 323 |
+
ali_to = hsp.hit_end
|
| 324 |
+
ali_from = hsp.hit_start + 1
|
| 325 |
+
|
| 326 |
+
rows += (
|
| 327 |
+
"%-*s %-*s %5d %-*s %-*s %5d %9.2g %6.1f %5.1f %3d"
|
| 328 |
+
" %3d %9.2g %9.2g %6.1f %5.1f %5d %5d %5ld %5ld"
|
| 329 |
+
" %5d %5d %4.2f %s\n"
|
| 330 |
+
% (
|
| 331 |
+
tnamew,
|
| 332 |
+
hit.id,
|
| 333 |
+
taccw,
|
| 334 |
+
hit_acc,
|
| 335 |
+
hit.seq_len,
|
| 336 |
+
qnamew,
|
| 337 |
+
qresult.id,
|
| 338 |
+
qaccw,
|
| 339 |
+
qresult_acc,
|
| 340 |
+
qresult.seq_len,
|
| 341 |
+
hit.evalue,
|
| 342 |
+
hit.bitscore,
|
| 343 |
+
hit.bias,
|
| 344 |
+
hsp.domain_index,
|
| 345 |
+
len(hit.hsps),
|
| 346 |
+
hsp.evalue_cond,
|
| 347 |
+
hsp.evalue,
|
| 348 |
+
hsp.bitscore,
|
| 349 |
+
hsp.bias,
|
| 350 |
+
hmm_from,
|
| 351 |
+
hmm_to,
|
| 352 |
+
ali_from,
|
| 353 |
+
ali_to,
|
| 354 |
+
hsp.env_start + 1,
|
| 355 |
+
hsp.env_end,
|
| 356 |
+
hsp.acc_avg,
|
| 357 |
+
hit.description,
|
| 358 |
+
)
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
return rows
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class Hmmer3DomtabHmmqueryWriter(Hmmer3DomtabHmmhitWriter):
|
| 365 |
+
"""HMMER domain table writer using query coordinates.
|
| 366 |
+
|
| 367 |
+
Writer for hmmer3-domtab output format which writes query coordinates
|
| 368 |
+
as HMM profile coordinates.
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
hmm_as_hit = False
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# if not used as a module, run the doctest
|
| 375 |
+
if __name__ == "__main__":
|
| 376 |
+
from Bio._utils import run_doctest
|
| 377 |
+
|
| 378 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO parser for HMMER table output format."""
|
| 7 |
+
|
| 8 |
+
from itertools import chain
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._index import SearchIndexer
|
| 11 |
+
from Bio.SearchIO._model import Hit
|
| 12 |
+
from Bio.SearchIO._model import HSP
|
| 13 |
+
from Bio.SearchIO._model import HSPFragment
|
| 14 |
+
from Bio.SearchIO._model import QueryResult
|
| 15 |
+
|
| 16 |
+
__all__ = ("Hmmer3TabParser", "Hmmer3TabIndexer", "Hmmer3TabWriter")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Hmmer3TabParser:
|
| 20 |
+
"""Parser for the HMMER table format."""
|
| 21 |
+
|
| 22 |
+
def __init__(self, handle):
|
| 23 |
+
"""Initialize the class."""
|
| 24 |
+
self.handle = handle
|
| 25 |
+
self.line = self.handle.readline()
|
| 26 |
+
|
| 27 |
+
def __iter__(self):
|
| 28 |
+
"""Iterate over Hmmer3TabParser, yields query results."""
|
| 29 |
+
header_mark = "#"
|
| 30 |
+
# read through the header if it exists
|
| 31 |
+
while self.line.startswith(header_mark):
|
| 32 |
+
self.line = self.handle.readline()
|
| 33 |
+
# if we have result rows, parse it
|
| 34 |
+
if self.line:
|
| 35 |
+
yield from self._parse_qresult()
|
| 36 |
+
|
| 37 |
+
def _parse_row(self):
|
| 38 |
+
"""Return a dictionary of parsed row values (PRIVATE)."""
|
| 39 |
+
cols = [x for x in self.line.strip().split(" ") if x]
|
| 40 |
+
if len(cols) < 18:
|
| 41 |
+
raise ValueError("Less columns than expected, only %i" % len(cols))
|
| 42 |
+
# if len(cols) > 19, we have extra description columns
|
| 43 |
+
# combine them all into one string in the 19th column
|
| 44 |
+
cols[18] = " ".join(cols[18:])
|
| 45 |
+
|
| 46 |
+
# assign parsed column data into qresult, hit, and hsp dicts
|
| 47 |
+
qresult = {}
|
| 48 |
+
qresult["id"] = cols[2] # query name
|
| 49 |
+
qresult["accession"] = cols[3] # query accession
|
| 50 |
+
hit = {}
|
| 51 |
+
hit["id"] = cols[0] # target name
|
| 52 |
+
hit["accession"] = cols[1] # target accession
|
| 53 |
+
hit["evalue"] = float(cols[4]) # evalue (full sequence)
|
| 54 |
+
hit["bitscore"] = float(cols[5]) # score (full sequence)
|
| 55 |
+
hit["bias"] = float(cols[6]) # bias (full sequence)
|
| 56 |
+
hit["domain_exp_num"] = float(cols[10]) # exp
|
| 57 |
+
hit["region_num"] = int(cols[11]) # reg
|
| 58 |
+
hit["cluster_num"] = int(cols[12]) # clu
|
| 59 |
+
hit["overlap_num"] = int(cols[13]) # ov
|
| 60 |
+
hit["env_num"] = int(cols[14]) # env
|
| 61 |
+
hit["domain_obs_num"] = int(cols[15]) # dom
|
| 62 |
+
hit["domain_reported_num"] = int(cols[16]) # rep
|
| 63 |
+
hit["domain_included_num"] = int(cols[17]) # inc
|
| 64 |
+
hit["description"] = cols[18] # description of target
|
| 65 |
+
hsp = {}
|
| 66 |
+
hsp["evalue"] = float(cols[7]) # evalue (best 1 domain)
|
| 67 |
+
hsp["bitscore"] = float(cols[8]) # score (best 1 domain)
|
| 68 |
+
hsp["bias"] = float(cols[9]) # bias (best 1 domain)
|
| 69 |
+
# strand is always 0, since HMMER now only handles protein
|
| 70 |
+
frag = {}
|
| 71 |
+
frag["hit_strand"] = frag["query_strand"] = 0
|
| 72 |
+
frag["molecule_type"] = "protein"
|
| 73 |
+
|
| 74 |
+
return {"qresult": qresult, "hit": hit, "hsp": hsp, "frag": frag}
|
| 75 |
+
|
| 76 |
+
def _parse_qresult(self):
|
| 77 |
+
"""Return QueryResult objects (PRIVATE)."""
|
| 78 |
+
# state values, determines what to do for each line
|
| 79 |
+
state_EOF = 0
|
| 80 |
+
state_QRES_NEW = 1
|
| 81 |
+
state_QRES_SAME = 3
|
| 82 |
+
# initial value dummies
|
| 83 |
+
qres_state = None
|
| 84 |
+
file_state = None
|
| 85 |
+
prev_qid = None
|
| 86 |
+
cur, prev = None, None
|
| 87 |
+
# container for Hit objects, used to create QueryResult
|
| 88 |
+
hit_list = []
|
| 89 |
+
cur_qid = None
|
| 90 |
+
while True:
|
| 91 |
+
# store previous line's parsed values for all lines after the first
|
| 92 |
+
if cur is not None:
|
| 93 |
+
prev = cur
|
| 94 |
+
prev_qid = cur_qid
|
| 95 |
+
# only parse the result row if it's not EOF
|
| 96 |
+
# NOTE: we are not parsing the extra '#' lines appended to the end
|
| 97 |
+
# of hmmer31b1 tabular results since storing them in qresult
|
| 98 |
+
# objects means we can not do a single-pass parsing
|
| 99 |
+
if self.line and not self.line.startswith("#"):
|
| 100 |
+
cur = self._parse_row()
|
| 101 |
+
cur_qid = cur["qresult"]["id"]
|
| 102 |
+
else:
|
| 103 |
+
file_state = state_EOF
|
| 104 |
+
# mock value for cur_qid, since we have nothing to parse
|
| 105 |
+
cur_qid = None
|
| 106 |
+
|
| 107 |
+
if prev_qid != cur_qid:
|
| 108 |
+
qres_state = state_QRES_NEW
|
| 109 |
+
else:
|
| 110 |
+
qres_state = state_QRES_SAME
|
| 111 |
+
|
| 112 |
+
if prev is not None:
|
| 113 |
+
# since domain tab formats only have 1 Hit per line
|
| 114 |
+
# we always create HSPFragment, HSP, and Hit per line
|
| 115 |
+
prev_hid = prev["hit"]["id"]
|
| 116 |
+
|
| 117 |
+
# create fragment and HSP and set their attributes
|
| 118 |
+
frag = HSPFragment(prev_hid, prev_qid)
|
| 119 |
+
for attr, value in prev["frag"].items():
|
| 120 |
+
setattr(frag, attr, value)
|
| 121 |
+
hsp = HSP([frag])
|
| 122 |
+
for attr, value in prev["hsp"].items():
|
| 123 |
+
setattr(hsp, attr, value)
|
| 124 |
+
|
| 125 |
+
# create Hit and set its attributes
|
| 126 |
+
hit = Hit([hsp])
|
| 127 |
+
for attr, value in prev["hit"].items():
|
| 128 |
+
setattr(hit, attr, value)
|
| 129 |
+
hit_list.append(hit)
|
| 130 |
+
|
| 131 |
+
# create qresult and yield if we're at a new qresult or at EOF
|
| 132 |
+
if qres_state == state_QRES_NEW or file_state == state_EOF:
|
| 133 |
+
qresult = QueryResult(hit_list, prev_qid)
|
| 134 |
+
for attr, value in prev["qresult"].items():
|
| 135 |
+
setattr(qresult, attr, value)
|
| 136 |
+
yield qresult
|
| 137 |
+
# if we're at EOF, break
|
| 138 |
+
if file_state == state_EOF:
|
| 139 |
+
break
|
| 140 |
+
hit_list = []
|
| 141 |
+
|
| 142 |
+
self.line = self.handle.readline()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class Hmmer3TabIndexer(SearchIndexer):
|
| 146 |
+
"""Indexer class for HMMER table output."""
|
| 147 |
+
|
| 148 |
+
_parser = Hmmer3TabParser
|
| 149 |
+
# denotes column location for query identifier
|
| 150 |
+
_query_id_idx = 2
|
| 151 |
+
|
| 152 |
+
def __iter__(self):
|
| 153 |
+
"""Iterate over the file handle; yields key, start offset, and length."""
|
| 154 |
+
handle = self._handle
|
| 155 |
+
handle.seek(0)
|
| 156 |
+
query_id_idx = self._query_id_idx
|
| 157 |
+
qresult_key = None
|
| 158 |
+
header_mark = b"#"
|
| 159 |
+
split_mark = b" "
|
| 160 |
+
# set line with initial mock value, to emulate header
|
| 161 |
+
line = header_mark
|
| 162 |
+
|
| 163 |
+
# read through header
|
| 164 |
+
while line.startswith(header_mark):
|
| 165 |
+
start_offset = handle.tell()
|
| 166 |
+
line = handle.readline()
|
| 167 |
+
|
| 168 |
+
# and index the qresults
|
| 169 |
+
while True:
|
| 170 |
+
end_offset = handle.tell()
|
| 171 |
+
|
| 172 |
+
if not line:
|
| 173 |
+
break
|
| 174 |
+
|
| 175 |
+
cols = [x for x in line.strip().split(split_mark) if x]
|
| 176 |
+
if qresult_key is None:
|
| 177 |
+
qresult_key = cols[query_id_idx]
|
| 178 |
+
else:
|
| 179 |
+
curr_key = cols[query_id_idx]
|
| 180 |
+
|
| 181 |
+
if curr_key != qresult_key:
|
| 182 |
+
adj_end = end_offset - len(line)
|
| 183 |
+
yield (qresult_key.decode(), start_offset, adj_end - start_offset)
|
| 184 |
+
qresult_key = curr_key
|
| 185 |
+
start_offset = adj_end
|
| 186 |
+
|
| 187 |
+
line = handle.readline()
|
| 188 |
+
if not line:
|
| 189 |
+
yield (qresult_key.decode(), start_offset, end_offset - start_offset)
|
| 190 |
+
break
|
| 191 |
+
|
| 192 |
+
def get_raw(self, offset):
|
| 193 |
+
"""Return the raw bytes string of a QueryResult object from the given offset."""
|
| 194 |
+
handle = self._handle
|
| 195 |
+
handle.seek(offset)
|
| 196 |
+
query_id_idx = self._query_id_idx
|
| 197 |
+
qresult_key = None
|
| 198 |
+
qresult_raw = b""
|
| 199 |
+
split_mark = b" "
|
| 200 |
+
|
| 201 |
+
while True:
|
| 202 |
+
line = handle.readline()
|
| 203 |
+
if not line:
|
| 204 |
+
break
|
| 205 |
+
cols = [x for x in line.strip().split(split_mark) if x]
|
| 206 |
+
if qresult_key is None:
|
| 207 |
+
qresult_key = cols[query_id_idx]
|
| 208 |
+
else:
|
| 209 |
+
curr_key = cols[query_id_idx]
|
| 210 |
+
if curr_key != qresult_key:
|
| 211 |
+
break
|
| 212 |
+
qresult_raw += line
|
| 213 |
+
|
| 214 |
+
return qresult_raw
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class Hmmer3TabWriter:
|
| 218 |
+
"""Writer for hmmer3-tab output format."""
|
| 219 |
+
|
| 220 |
+
def __init__(self, handle):
|
| 221 |
+
"""Initialize the class."""
|
| 222 |
+
self.handle = handle
|
| 223 |
+
|
| 224 |
+
def write_file(self, qresults):
|
| 225 |
+
"""Write to the handle.
|
| 226 |
+
|
| 227 |
+
Returns a tuple of how many QueryResult, Hit, and HSP objects were written.
|
| 228 |
+
|
| 229 |
+
"""
|
| 230 |
+
handle = self.handle
|
| 231 |
+
qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0
|
| 232 |
+
|
| 233 |
+
try:
|
| 234 |
+
first_qresult = next(qresults)
|
| 235 |
+
except StopIteration:
|
| 236 |
+
handle.write(self._build_header())
|
| 237 |
+
else:
|
| 238 |
+
# write header
|
| 239 |
+
handle.write(self._build_header(first_qresult))
|
| 240 |
+
# and then the qresults
|
| 241 |
+
for qresult in chain([first_qresult], qresults):
|
| 242 |
+
if qresult:
|
| 243 |
+
handle.write(self._build_row(qresult))
|
| 244 |
+
qresult_counter += 1
|
| 245 |
+
hit_counter += len(qresult)
|
| 246 |
+
hsp_counter += sum(len(hit) for hit in qresult)
|
| 247 |
+
frag_counter += sum(len(hit.fragments) for hit in qresult)
|
| 248 |
+
|
| 249 |
+
return qresult_counter, hit_counter, hsp_counter, frag_counter
|
| 250 |
+
|
| 251 |
+
def _build_header(self, first_qresult=None):
|
| 252 |
+
"""Return the header string of a HMMER table output (PRIVATE)."""
|
| 253 |
+
# calculate whitespace required
|
| 254 |
+
# adapted from HMMER's source: src/p7_tophits.c#L1083
|
| 255 |
+
if first_qresult is not None:
|
| 256 |
+
# qnamew = max(20, len(first_qresult.id))
|
| 257 |
+
qnamew = 20 # why doesn't the above work?
|
| 258 |
+
tnamew = max(20, len(first_qresult[0].id))
|
| 259 |
+
qaccw = max(10, len(first_qresult.accession))
|
| 260 |
+
taccw = max(10, len(first_qresult[0].accession))
|
| 261 |
+
else:
|
| 262 |
+
qnamew, tnamew, qaccw, taccw = 20, 20, 10, 10
|
| 263 |
+
# Turn black code style off
|
| 264 |
+
# fmt: off
|
| 265 |
+
header = ("#%*s %22s %22s %33s\n"
|
| 266 |
+
% (tnamew + qnamew + taccw + qaccw + 2, "",
|
| 267 |
+
"--- full sequence ----", "--- best 1 domain ----",
|
| 268 |
+
"--- domain number estimation ----"))
|
| 269 |
+
header += ("#%-*s %-*s %-*s %-*s %9s %6s %5s %9s %6s %5s %5s %3s "
|
| 270 |
+
"%3s %3s %3s %3s %3s %3s %s\n"
|
| 271 |
+
% (tnamew - 1, " target name",
|
| 272 |
+
taccw, "accession", qnamew, "query name", qaccw,
|
| 273 |
+
"accession", " E-value", " score", " bias",
|
| 274 |
+
" E-value", " score", " bias", "exp",
|
| 275 |
+
"reg", "clu", " ov", "env", "dom", "rep",
|
| 276 |
+
"inc", "description of target"))
|
| 277 |
+
header += ("#%*s %*s %*s %*s %9s %6s %5s %9s %6s %5s %5s %3s %3s "
|
| 278 |
+
"%3s %3s %3s %3s %3s %s\n"
|
| 279 |
+
% (tnamew - 1, "-------------------",
|
| 280 |
+
taccw, "----------", qnamew, "--------------------", qaccw,
|
| 281 |
+
"----------", "---------", "------", "-----", "---------",
|
| 282 |
+
"------", "-----", "---", "---", "---", "---", "---", "---",
|
| 283 |
+
"---", "---", "---------------------"))
|
| 284 |
+
# Turn black code style on
|
| 285 |
+
# fmt: on
|
| 286 |
+
return header
|
| 287 |
+
|
| 288 |
+
def _build_row(self, qresult):
|
| 289 |
+
"""Return a string or one row or more of the QueryResult object (PRIVATE)."""
|
| 290 |
+
rows = ""
|
| 291 |
+
|
| 292 |
+
# calculate whitespace required
|
| 293 |
+
# adapted from HMMER's source: src/p7_tophits.c#L1083
|
| 294 |
+
qnamew = max(20, len(qresult.id))
|
| 295 |
+
tnamew = max(20, len(qresult[0].id))
|
| 296 |
+
qaccw = max(10, len(qresult.accession))
|
| 297 |
+
taccw = max(10, len(qresult[0].accession))
|
| 298 |
+
|
| 299 |
+
for hit in qresult:
|
| 300 |
+
rows += (
|
| 301 |
+
"%-*s %-*s %-*s %-*s %9.2g %6.1f %5.1f %9.2g %6.1f"
|
| 302 |
+
" %5.1f %5.1f %3d %3d %3d %3d %3d %3d %3d %s\n"
|
| 303 |
+
% (
|
| 304 |
+
tnamew,
|
| 305 |
+
hit.id,
|
| 306 |
+
taccw,
|
| 307 |
+
hit.accession,
|
| 308 |
+
qnamew,
|
| 309 |
+
qresult.id,
|
| 310 |
+
qaccw,
|
| 311 |
+
qresult.accession,
|
| 312 |
+
hit.evalue,
|
| 313 |
+
hit.bitscore,
|
| 314 |
+
hit.bias,
|
| 315 |
+
hit.hsps[0].evalue,
|
| 316 |
+
hit.hsps[0].bitscore,
|
| 317 |
+
hit.hsps[0].bias,
|
| 318 |
+
hit.domain_exp_num,
|
| 319 |
+
hit.region_num,
|
| 320 |
+
hit.cluster_num,
|
| 321 |
+
hit.overlap_num,
|
| 322 |
+
hit.env_num,
|
| 323 |
+
hit.domain_obs_num,
|
| 324 |
+
hit.domain_reported_num,
|
| 325 |
+
hit.domain_included_num,
|
| 326 |
+
hit.description,
|
| 327 |
+
)
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
return rows
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
# if not used as a module, run the doctest
|
| 334 |
+
if __name__ == "__main__":
|
| 335 |
+
from Bio._utils import run_doctest
|
| 336 |
+
|
| 337 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_text.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO parser for HMMER plain text output format."""
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._model import Hit
|
| 11 |
+
from Bio.SearchIO._model import HSP
|
| 12 |
+
from Bio.SearchIO._model import HSPFragment
|
| 13 |
+
from Bio.SearchIO._model import QueryResult
|
| 14 |
+
from Bio.SearchIO._utils import read_forward
|
| 15 |
+
|
| 16 |
+
from ._base import _BaseHmmerTextIndexer
|
| 17 |
+
|
| 18 |
+
__all__ = ("Hmmer3TextParser", "Hmmer3TextIndexer")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# precompile regex patterns for faster processing
|
| 22 |
+
# regex for program name capture
|
| 23 |
+
_RE_PROGRAM = re.compile(r"^# .*?(\w?hmm\w+) :: .*$")
|
| 24 |
+
# regex for version string capture
|
| 25 |
+
_RE_VERSION = re.compile(r"# \w+ ([\w+\.]+) .*; http.*$")
|
| 26 |
+
# regex for option string capture
|
| 27 |
+
_RE_OPT = re.compile(r"^# (.+):\s+(.+)$")
|
| 28 |
+
# regex for parsing query id and length, for parsing
|
| 29 |
+
_QRE_ID_LEN_PTN = r"^Query:\s*(.*)\s+\[\w=(\d+)\]"
|
| 30 |
+
_QRE_ID_LEN = re.compile(_QRE_ID_LEN_PTN)
|
| 31 |
+
# regex for hsp validation
|
| 32 |
+
_HRE_VALIDATE = re.compile(r"score:\s(-?\d+\.?\d+)\sbits.*value:\s(.*)")
|
| 33 |
+
# regexes for parsing hsp alignment blocks
|
| 34 |
+
_HRE_ANNOT_LINE = re.compile(r"^(\s+)(.+)\s(\w+)")
|
| 35 |
+
_HRE_ID_LINE = re.compile(r"^(\s+\S+\s+[0-9-]+ )(.+?)(\s+[0-9-]+)")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Hmmer3TextParser:
|
| 39 |
+
"""Parser for the HMMER 3.0 text output."""
|
| 40 |
+
|
| 41 |
+
def __init__(self, handle):
|
| 42 |
+
"""Initialize the class."""
|
| 43 |
+
self.handle = handle
|
| 44 |
+
self.line = read_forward(self.handle)
|
| 45 |
+
self._meta = self._parse_preamble()
|
| 46 |
+
|
| 47 |
+
def __iter__(self):
|
| 48 |
+
"""Iterate over query results."""
|
| 49 |
+
yield from self._parse_qresult()
|
| 50 |
+
|
| 51 |
+
def _read_until(self, bool_func):
|
| 52 |
+
"""Read the file handle until the given function returns True (PRIVATE)."""
|
| 53 |
+
while True:
|
| 54 |
+
if not self.line or bool_func(self.line):
|
| 55 |
+
return
|
| 56 |
+
else:
|
| 57 |
+
self.line = read_forward(self.handle)
|
| 58 |
+
|
| 59 |
+
def _parse_preamble(self):
|
| 60 |
+
"""Parse HMMER preamble (lines beginning with '#') (PRIVATE)."""
|
| 61 |
+
meta = {}
|
| 62 |
+
# bool flag for storing state ~ whether we are parsing the option
|
| 63 |
+
# lines or not
|
| 64 |
+
has_opts = False
|
| 65 |
+
while True:
|
| 66 |
+
# no pound sign means we've left the preamble
|
| 67 |
+
if not self.line.startswith("#"):
|
| 68 |
+
break
|
| 69 |
+
# dashes could either mean we are entering or leaving the options
|
| 70 |
+
# section ~ so it's a switch for the has_opts flag
|
| 71 |
+
elif "- - -" in self.line:
|
| 72 |
+
if not has_opts:
|
| 73 |
+
# if flag is false, that means we're entering opts
|
| 74 |
+
# so switch the flag accordingly
|
| 75 |
+
has_opts = True
|
| 76 |
+
else:
|
| 77 |
+
# if flag is true, that means we've reached the end of opts
|
| 78 |
+
# so we can break out of the function
|
| 79 |
+
break
|
| 80 |
+
elif not has_opts:
|
| 81 |
+
# try parsing program
|
| 82 |
+
regx = re.search(_RE_PROGRAM, self.line)
|
| 83 |
+
if regx:
|
| 84 |
+
meta["program"] = regx.group(1)
|
| 85 |
+
# try parsing version
|
| 86 |
+
regx = re.search(_RE_VERSION, self.line)
|
| 87 |
+
if regx:
|
| 88 |
+
meta["version"] = regx.group(1)
|
| 89 |
+
elif has_opts:
|
| 90 |
+
regx = re.search(_RE_OPT, self.line)
|
| 91 |
+
# if target in regx.group(1), then we store the key as target
|
| 92 |
+
if "target" in regx.group(1):
|
| 93 |
+
meta["target"] = regx.group(2).strip()
|
| 94 |
+
else:
|
| 95 |
+
meta[regx.group(1)] = regx.group(2)
|
| 96 |
+
|
| 97 |
+
self.line = read_forward(self.handle)
|
| 98 |
+
|
| 99 |
+
return meta
|
| 100 |
+
|
| 101 |
+
def _parse_qresult(self):
|
| 102 |
+
"""Parse a HMMER3 query block (PRIVATE)."""
|
| 103 |
+
self._read_until(lambda line: line.startswith("Query:"))
|
| 104 |
+
|
| 105 |
+
while self.line:
|
| 106 |
+
regx = re.search(_QRE_ID_LEN, self.line)
|
| 107 |
+
|
| 108 |
+
while not regx:
|
| 109 |
+
self.line = read_forward(self.handle)
|
| 110 |
+
regx = re.search(_QRE_ID_LEN, self.line)
|
| 111 |
+
|
| 112 |
+
# get query id and length
|
| 113 |
+
qid = regx.group(1).strip()
|
| 114 |
+
# store qresult attributes
|
| 115 |
+
qresult_attrs = {
|
| 116 |
+
"seq_len": int(regx.group(2)),
|
| 117 |
+
"program": self._meta.get("program"),
|
| 118 |
+
"version": self._meta.get("version"),
|
| 119 |
+
"target": self._meta.get("target"),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
# get description and accession, if they exist
|
| 123 |
+
qdesc = "<unknown description>" # placeholder
|
| 124 |
+
while not self.line.startswith("Scores for "):
|
| 125 |
+
self.line = read_forward(self.handle)
|
| 126 |
+
|
| 127 |
+
if self.line.startswith("Accession:"):
|
| 128 |
+
acc = self.line.strip().split(" ", 1)[1]
|
| 129 |
+
qresult_attrs["accession"] = acc.strip()
|
| 130 |
+
elif self.line.startswith("Description:"):
|
| 131 |
+
qdesc = self.line.strip().split(" ", 1)[1].strip()
|
| 132 |
+
qresult_attrs["description"] = qdesc
|
| 133 |
+
|
| 134 |
+
# parse the query hits
|
| 135 |
+
while self.line and "//" not in self.line:
|
| 136 |
+
hit_list = self._parse_hit(qid, qdesc)
|
| 137 |
+
# read through the statistics summary
|
| 138 |
+
# TODO: parse and store this information?
|
| 139 |
+
if self.line.startswith("Internal pipeline"):
|
| 140 |
+
while self.line and "//" not in self.line:
|
| 141 |
+
self.line = read_forward(self.handle)
|
| 142 |
+
|
| 143 |
+
# create qresult, set its attributes and yield
|
| 144 |
+
# not initializing hit_list directly to handle empty hits
|
| 145 |
+
# (i.e. need to set its query description manually)
|
| 146 |
+
qresult = QueryResult(id=qid, hits=hit_list)
|
| 147 |
+
for attr, value in qresult_attrs.items():
|
| 148 |
+
setattr(qresult, attr, value)
|
| 149 |
+
yield qresult
|
| 150 |
+
self.line = read_forward(self.handle)
|
| 151 |
+
|
| 152 |
+
# Skip line beginning with '# Alignment of', which are output
|
| 153 |
+
# when running phmmer with the '-A' flag.
|
| 154 |
+
if self.line.startswith("#"):
|
| 155 |
+
self.line = self.handle.readline()
|
| 156 |
+
|
| 157 |
+
# HMMER >= 3.1 outputs '[ok]' at the end of all results file,
|
| 158 |
+
# which means we can break the main loop when we see the line
|
| 159 |
+
if "[ok]" in self.line:
|
| 160 |
+
break
|
| 161 |
+
|
| 162 |
+
def _parse_hit(self, qid, qdesc):
|
| 163 |
+
"""Parse a HMMER3 hit block, beginning with the hit table (PRIVATE)."""
|
| 164 |
+
# get to the end of the hit table delimiter and read one more line
|
| 165 |
+
self._read_until(lambda line: line.startswith(" ------- ------ -----"))
|
| 166 |
+
self.line = read_forward(self.handle)
|
| 167 |
+
|
| 168 |
+
# assume every hit is in inclusion threshold until the inclusion
|
| 169 |
+
# threshold line is encountered
|
| 170 |
+
is_included = True
|
| 171 |
+
|
| 172 |
+
# parse the hit table
|
| 173 |
+
hit_attr_list = []
|
| 174 |
+
while True:
|
| 175 |
+
if not self.line:
|
| 176 |
+
return []
|
| 177 |
+
elif self.line.startswith(" ------ inclusion"):
|
| 178 |
+
is_included = False
|
| 179 |
+
self.line = read_forward(self.handle)
|
| 180 |
+
# if there are no hits, then there are no hsps
|
| 181 |
+
# so we forward-read until 'Internal pipeline..'
|
| 182 |
+
elif self.line.startswith(" [No hits detected that satisfy reporting"):
|
| 183 |
+
while True:
|
| 184 |
+
self.line = read_forward(self.handle)
|
| 185 |
+
if self.line.startswith("Internal pipeline"):
|
| 186 |
+
assert len(hit_attr_list) == 0
|
| 187 |
+
return []
|
| 188 |
+
elif self.line.startswith("Domain annotation for each "):
|
| 189 |
+
hit_list = self._create_hits(hit_attr_list, qid, qdesc)
|
| 190 |
+
return hit_list
|
| 191 |
+
# entering hit results row
|
| 192 |
+
# parse the columns into a list
|
| 193 |
+
row = [x for x in self.line.strip().split(" ") if x]
|
| 194 |
+
# join the description words if it's >1 word
|
| 195 |
+
if len(row) > 10:
|
| 196 |
+
row[9] = " ".join(row[9:])
|
| 197 |
+
# if there's no description, set it to an empty string
|
| 198 |
+
elif len(row) < 10:
|
| 199 |
+
row.append("")
|
| 200 |
+
assert len(row) == 10
|
| 201 |
+
# create the hit object
|
| 202 |
+
hit_attrs = {
|
| 203 |
+
"id": row[8],
|
| 204 |
+
"query_id": qid,
|
| 205 |
+
"evalue": float(row[0]),
|
| 206 |
+
"bitscore": float(row[1]),
|
| 207 |
+
"bias": float(row[2]),
|
| 208 |
+
# row[3:6] is not parsed, since the info is available
|
| 209 |
+
# at the HSP level
|
| 210 |
+
"domain_exp_num": float(row[6]),
|
| 211 |
+
"domain_obs_num": int(row[7]),
|
| 212 |
+
"description": row[9],
|
| 213 |
+
"is_included": is_included,
|
| 214 |
+
}
|
| 215 |
+
hit_attr_list.append(hit_attrs)
|
| 216 |
+
|
| 217 |
+
self.line = read_forward(self.handle)
|
| 218 |
+
|
| 219 |
+
def _create_hits(self, hit_attrs, qid, qdesc):
|
| 220 |
+
"""Parse a HMMER3 hsp block, beginning with the hsp table (PRIVATE)."""
|
| 221 |
+
# read through until the beginning of the hsp block
|
| 222 |
+
self._read_until(lambda line: line.startswith(("Internal pipeline", ">>")))
|
| 223 |
+
|
| 224 |
+
# start parsing the hsp block
|
| 225 |
+
hit_list = []
|
| 226 |
+
while True:
|
| 227 |
+
if self.line.startswith("Internal pipeline"):
|
| 228 |
+
# by this time we should've emptied the hit attr list
|
| 229 |
+
assert len(hit_attrs) == 0
|
| 230 |
+
return hit_list
|
| 231 |
+
assert self.line.startswith(">>")
|
| 232 |
+
hid, hdesc = self.line[len(">> ") :].split(" ", 1)
|
| 233 |
+
hdesc = hdesc.strip()
|
| 234 |
+
|
| 235 |
+
# read through the hsp table header and move one more line
|
| 236 |
+
self._read_until(
|
| 237 |
+
lambda line: line.startswith(
|
| 238 |
+
(" --- ------ ----- --------", " [No individual domains")
|
| 239 |
+
)
|
| 240 |
+
)
|
| 241 |
+
self.line = read_forward(self.handle)
|
| 242 |
+
|
| 243 |
+
# parse the hsp table for the current hit
|
| 244 |
+
hsp_list = []
|
| 245 |
+
while True:
|
| 246 |
+
# break out of hsp parsing if there are no hits, it's the last hsp
|
| 247 |
+
# or it's the start of a new hit
|
| 248 |
+
if (
|
| 249 |
+
self.line.startswith(" [No targets detected that satisfy")
|
| 250 |
+
or self.line.startswith(" [No individual domains")
|
| 251 |
+
or self.line.startswith("Internal pipeline statistics summary:")
|
| 252 |
+
or self.line.startswith(" Alignments for each domain:")
|
| 253 |
+
or self.line.startswith(">>")
|
| 254 |
+
):
|
| 255 |
+
hit_attr = hit_attrs.pop(0)
|
| 256 |
+
hit = Hit(hsp_list)
|
| 257 |
+
for attr, value in hit_attr.items():
|
| 258 |
+
if attr == "description":
|
| 259 |
+
cur_val = getattr(hit, attr)
|
| 260 |
+
if cur_val and value and cur_val.startswith(value):
|
| 261 |
+
continue
|
| 262 |
+
setattr(hit, attr, value)
|
| 263 |
+
if not hit:
|
| 264 |
+
hit.query_description = qdesc
|
| 265 |
+
hit_list.append(hit)
|
| 266 |
+
break
|
| 267 |
+
|
| 268 |
+
parsed = [x for x in self.line.strip().split(" ") if x]
|
| 269 |
+
assert len(parsed) == 16
|
| 270 |
+
# parsed column order:
|
| 271 |
+
# index, is_included, bitscore, bias, evalue_cond, evalue
|
| 272 |
+
# hmmfrom, hmmto, query_ends, hit_ends, alifrom, alito,
|
| 273 |
+
# envfrom, envto, acc_avg
|
| 274 |
+
frag = HSPFragment(hid, qid)
|
| 275 |
+
# set query and hit descriptions if they are defined / nonempty string
|
| 276 |
+
if qdesc:
|
| 277 |
+
frag.query_description = qdesc
|
| 278 |
+
if hdesc:
|
| 279 |
+
frag.hit_description = hdesc
|
| 280 |
+
# HMMER3 results are always protein
|
| 281 |
+
frag.molecule_type = "protein"
|
| 282 |
+
# depending on whether the program is hmmsearch, hmmscan, or phmmer
|
| 283 |
+
# {hmm,ali}{from,to} can either be hit_{from,to} or query_{from,to}
|
| 284 |
+
# for hmmscan, hit is the hmm profile, query is the sequence
|
| 285 |
+
if self._meta.get("program") == "hmmscan":
|
| 286 |
+
# adjust 'from' and 'to' coordinates to 0-based ones
|
| 287 |
+
frag.hit_start = int(parsed[6]) - 1
|
| 288 |
+
frag.hit_end = int(parsed[7])
|
| 289 |
+
frag.query_start = int(parsed[9]) - 1
|
| 290 |
+
frag.query_end = int(parsed[10])
|
| 291 |
+
elif self._meta.get("program") in ["hmmsearch", "phmmer"]:
|
| 292 |
+
# adjust 'from' and 'to' coordinates to 0-based ones
|
| 293 |
+
frag.hit_start = int(parsed[9]) - 1
|
| 294 |
+
frag.hit_end = int(parsed[10])
|
| 295 |
+
frag.query_start = int(parsed[6]) - 1
|
| 296 |
+
frag.query_end = int(parsed[7])
|
| 297 |
+
# strand is always 0, since HMMER now only handles protein
|
| 298 |
+
frag.hit_strand = frag.query_strand = 0
|
| 299 |
+
|
| 300 |
+
hsp = HSP([frag])
|
| 301 |
+
hsp.domain_index = int(parsed[0])
|
| 302 |
+
hsp.is_included = parsed[1] == "!"
|
| 303 |
+
hsp.bitscore = float(parsed[2])
|
| 304 |
+
hsp.bias = float(parsed[3])
|
| 305 |
+
hsp.evalue_cond = float(parsed[4])
|
| 306 |
+
hsp.evalue = float(parsed[5])
|
| 307 |
+
if self._meta.get("program") == "hmmscan":
|
| 308 |
+
# adjust 'from' and 'to' coordinates to 0-based ones
|
| 309 |
+
hsp.hit_endtype = parsed[8]
|
| 310 |
+
hsp.query_endtype = parsed[11]
|
| 311 |
+
elif self._meta.get("program") in ["hmmsearch", "phmmer"]:
|
| 312 |
+
# adjust 'from' and 'to' coordinates to 0-based ones
|
| 313 |
+
hsp.hit_endtype = parsed[11]
|
| 314 |
+
hsp.query_endtype = parsed[8]
|
| 315 |
+
# adjust 'from' and 'to' coordinates to 0-based ones
|
| 316 |
+
hsp.env_start = int(parsed[12]) - 1
|
| 317 |
+
hsp.env_end = int(parsed[13])
|
| 318 |
+
hsp.env_endtype = parsed[14]
|
| 319 |
+
hsp.acc_avg = float(parsed[15])
|
| 320 |
+
|
| 321 |
+
hsp_list.append(hsp)
|
| 322 |
+
self.line = read_forward(self.handle)
|
| 323 |
+
|
| 324 |
+
# parse the hsp alignments
|
| 325 |
+
if self.line.startswith(" Alignments for each domain:"):
|
| 326 |
+
self._parse_aln_block(hid, hit.hsps)
|
| 327 |
+
|
| 328 |
+
def _parse_aln_block(self, hid, hsp_list):
|
| 329 |
+
"""Parse a HMMER3 HSP alignment block (PRIVATE)."""
|
| 330 |
+
self.line = read_forward(self.handle)
|
| 331 |
+
dom_counter = 0
|
| 332 |
+
while True:
|
| 333 |
+
if self.line.startswith(">>") or self.line.startswith("Internal pipeline"):
|
| 334 |
+
return hsp_list
|
| 335 |
+
assert self.line.startswith(" == domain %i" % (dom_counter + 1))
|
| 336 |
+
# alias hsp to local var
|
| 337 |
+
# but note that we're still changing the attrs of the actual
|
| 338 |
+
# hsp inside the qresult as we're not creating a copy
|
| 339 |
+
frag = hsp_list[dom_counter][0]
|
| 340 |
+
# XXX: should we validate again here? regex is expensive..
|
| 341 |
+
# regx = re.search(_HRE_VALIDATE, self.line)
|
| 342 |
+
# assert hsp.bitscore == float(regx.group(1))
|
| 343 |
+
# assert hsp.evalue_cond == float(regx.group(2))
|
| 344 |
+
hmmseq = ""
|
| 345 |
+
aliseq = ""
|
| 346 |
+
annot = {}
|
| 347 |
+
aln_prefix_len = None
|
| 348 |
+
self.line = self.handle.readline()
|
| 349 |
+
|
| 350 |
+
# parse all the alignment blocks in the hsp
|
| 351 |
+
while True:
|
| 352 |
+
regx = None
|
| 353 |
+
|
| 354 |
+
# check for hit or query line
|
| 355 |
+
# we don't check for the hit or query id specifically
|
| 356 |
+
# to anticipate special cases where query id == hit id
|
| 357 |
+
regx = re.search(_HRE_ID_LINE, self.line)
|
| 358 |
+
if regx:
|
| 359 |
+
# Try to capture the block prefix len, to parse the similarity
|
| 360 |
+
# string later.
|
| 361 |
+
if aln_prefix_len is None:
|
| 362 |
+
aln_prefix_len = len(regx.group(1))
|
| 363 |
+
else:
|
| 364 |
+
assert aln_prefix_len == len(regx.group(1))
|
| 365 |
+
# the first hit/query self.line we encounter is the hmmseq
|
| 366 |
+
if len(hmmseq) == len(aliseq):
|
| 367 |
+
hmmseq += regx.group(2)
|
| 368 |
+
# and for subsequent self.lines, len(hmmseq) is either
|
| 369 |
+
# > or == len(aliseq)
|
| 370 |
+
elif len(hmmseq) > len(aliseq):
|
| 371 |
+
aliseq += regx.group(2)
|
| 372 |
+
assert len(hmmseq) >= len(aliseq)
|
| 373 |
+
# check for start of new domain
|
| 374 |
+
elif (
|
| 375 |
+
self.line.startswith(" == domain")
|
| 376 |
+
or self.line.startswith(">>")
|
| 377 |
+
or self.line.startswith("Internal pipeline")
|
| 378 |
+
):
|
| 379 |
+
frag.aln_annotation = annot
|
| 380 |
+
if self._meta.get("program") == "hmmscan":
|
| 381 |
+
frag.hit = hmmseq
|
| 382 |
+
frag.query = aliseq
|
| 383 |
+
elif self._meta.get("program") in ["hmmsearch", "phmmer"]:
|
| 384 |
+
frag.hit = aliseq
|
| 385 |
+
frag.query = hmmseq
|
| 386 |
+
dom_counter += 1
|
| 387 |
+
hmmseq = ""
|
| 388 |
+
aliseq = ""
|
| 389 |
+
annot = {}
|
| 390 |
+
aln_prefix_len = None
|
| 391 |
+
break
|
| 392 |
+
# check if it's an annotation line and parse it
|
| 393 |
+
# len(hmmseq) is only != len(aliseq) when the cursor is parsing
|
| 394 |
+
# the similarity character.
|
| 395 |
+
elif len(hmmseq) == len(aliseq):
|
| 396 |
+
regx = re.search(_HRE_ANNOT_LINE, self.line)
|
| 397 |
+
if regx:
|
| 398 |
+
annot_name = regx.group(3)
|
| 399 |
+
if annot_name in annot:
|
| 400 |
+
annot[annot_name] += regx.group(2)
|
| 401 |
+
else:
|
| 402 |
+
annot[annot_name] = regx.group(2)
|
| 403 |
+
# otherwise, assume we are seeing the similarity string (the string
|
| 404 |
+
# between the two alignments). We do that by checking if we have
|
| 405 |
+
# defined the aln_prefix_len variable, which is the length of string
|
| 406 |
+
# from the beginning of the line to the start of the actual alignment
|
| 407 |
+
# (sans the IDs). We need this string to see how many characters we
|
| 408 |
+
# should strip from the beginning of the line. We can't call `strip()`
|
| 409 |
+
# since the similarity string might start with empty characters.
|
| 410 |
+
elif aln_prefix_len is not None:
|
| 411 |
+
similarity = (
|
| 412 |
+
self.line[aln_prefix_len:].removesuffix("\n").removesuffix("\r")
|
| 413 |
+
)
|
| 414 |
+
if "similarity" not in annot:
|
| 415 |
+
annot["similarity"] = similarity
|
| 416 |
+
else:
|
| 417 |
+
annot["similarity"] += similarity
|
| 418 |
+
|
| 419 |
+
self.line = self.handle.readline()
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class Hmmer3TextIndexer(_BaseHmmerTextIndexer):
|
| 423 |
+
"""Indexer class for HMMER plain text output."""
|
| 424 |
+
|
| 425 |
+
_parser = Hmmer3TextParser
|
| 426 |
+
qresult_start = b"Query: "
|
| 427 |
+
qresult_end = b"//"
|
| 428 |
+
|
| 429 |
+
def __iter__(self):
|
| 430 |
+
"""Iterate over Hmmer3TextIndexer; yields query results' key, offsets, 0."""
|
| 431 |
+
handle = self._handle
|
| 432 |
+
handle.seek(0)
|
| 433 |
+
start_offset = handle.tell()
|
| 434 |
+
regex_id = re.compile(_QRE_ID_LEN_PTN.encode())
|
| 435 |
+
|
| 436 |
+
while True:
|
| 437 |
+
line = read_forward(handle)
|
| 438 |
+
end_offset = handle.tell()
|
| 439 |
+
|
| 440 |
+
if line.startswith(self.qresult_start):
|
| 441 |
+
regx = re.search(regex_id, line)
|
| 442 |
+
qresult_key = regx.group(1).strip()
|
| 443 |
+
# qresult start offset is the offset of this line
|
| 444 |
+
# (starts with the start mark)
|
| 445 |
+
start_offset = end_offset - len(line)
|
| 446 |
+
elif line.startswith(self.qresult_end):
|
| 447 |
+
yield qresult_key.decode(), start_offset, 0
|
| 448 |
+
start_offset = end_offset
|
| 449 |
+
elif not line:
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
# if not used as a module, run the doctest
|
| 454 |
+
if __name__ == "__main__":
|
| 455 |
+
from Bio._utils import run_doctest
|
| 456 |
+
|
| 457 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.__base.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_tab.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_text.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/__init__.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 by Samuel Prince. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of the Biopython distribution and governed by your
|
| 4 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 5 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 6 |
+
# package.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
"""Bio.SearchIO support for Infernal output formats.
|
| 10 |
+
|
| 11 |
+
This module adds support for parsing Infernal outputs. Infernal is a
|
| 12 |
+
suite of programs for searching DNA sequence databases for RNA structure
|
| 13 |
+
and sequence similarities using covariance models (CMs).
|
| 14 |
+
|
| 15 |
+
Bio.SearchIO.InfernalIO was tested on the following Infernal versions and flavors:
|
| 16 |
+
|
| 17 |
+
- Infernal (1.0.0+): cmscan and cmsearch
|
| 18 |
+
|
| 19 |
+
More information on HMMER are available through these links:
|
| 20 |
+
- Web page: http://eddylab.org/infernal/
|
| 21 |
+
- User guide: http://eddylab.org/infernal/Userguide.pdf
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
Supported formats
|
| 25 |
+
=================
|
| 26 |
+
|
| 27 |
+
Bio.SearchIO.InfernalIO supports the following Infernal output formats:
|
| 28 |
+
- Plain text - 'infernal-text' - parsing, indexing
|
| 29 |
+
- Tabular - 'infernal-tab' - parsing, indexing
|
| 30 |
+
|
| 31 |
+
For all output formats, Infernal uses 'mdl' for 'query' and 'seq' for 'hit'.
|
| 32 |
+
InfernalIO is aware of this different naming scheme, and will use 'query'
|
| 33 |
+
and 'hit' to fit SearchIO's object model.
|
| 34 |
+
|
| 35 |
+
Infernal sometime reports 'local ends' (i.e., a large insertion or deletion
|
| 36 |
+
in the optimal alignment), which are expresented by a number in brackets in
|
| 37 |
+
the alignment (ex. AUUAC*[88]*GUAGU). In InfernalIO, these local alignment
|
| 38 |
+
are split into fragments of the same HSP.
|
| 39 |
+
|
| 40 |
+
infernal-text
|
| 41 |
+
=============
|
| 42 |
+
|
| 43 |
+
The Infernal plain text parser supports output files with alignment
|
| 44 |
+
blocks (default) or without (with the '-noali' flag). If the alignment blocks
|
| 45 |
+
are present, it can parse files with variable alignment width (using the
|
| 46 |
+
'-notextw' or '-textw' flag). Both CM or HMM searches (with the '--hmmonly'
|
| 47 |
+
flag) output are supported. The parser only supports non-verbose output formats.
|
| 48 |
+
|
| 49 |
+
The following SearchIO objects attributes are provided.
|
| 50 |
+
|
| 51 |
+
+-----------------+-------------------------+----------------------------------+
|
| 52 |
+
| Object | Attribute | Value |
|
| 53 |
+
+=================+=========================+==================================+
|
| 54 |
+
| QueryResult | accession | query accession |
|
| 55 |
+
| +-------------------------+----------------------------------+
|
| 56 |
+
| | description | query sequence description |
|
| 57 |
+
| +-------------------------+----------------------------------+
|
| 58 |
+
| | id | query sequence ID |
|
| 59 |
+
| +-------------------------+----------------------------------+
|
| 60 |
+
| | program | Infernal flavor |
|
| 61 |
+
| +-------------------------+----------------------------------+
|
| 62 |
+
| | seq_len | full length of query sequence |
|
| 63 |
+
| +-------------------------+----------------------------------+
|
| 64 |
+
| | target | target search database |
|
| 65 |
+
| +-------------------------+----------------------------------+
|
| 66 |
+
| | version | Infernal version |
|
| 67 |
+
+-----------------+-------------------------+----------------------------------+
|
| 68 |
+
| Hit | description | hit sequence description |
|
| 69 |
+
| +-------------------------+----------------------------------+
|
| 70 |
+
| | id | hit sequence ID |
|
| 71 |
+
+-----------------+-------------------------+----------------------------------+
|
| 72 |
+
| HSP | evalue | hsp evalue |
|
| 73 |
+
| +-------------------------+----------------------------------+
|
| 74 |
+
| | bias | hsp bias |
|
| 75 |
+
| +-------------------------+----------------------------------+
|
| 76 |
+
| | bitscore | hsp score |
|
| 77 |
+
| +-------------------------+----------------------------------+
|
| 78 |
+
| | gc | gc fraction |
|
| 79 |
+
| +-------------------------+----------------------------------+
|
| 80 |
+
| | is_included | boolean, whether the hit of the |
|
| 81 |
+
| | | hsp is in the inclusion |
|
| 82 |
+
| | | threshold |
|
| 83 |
+
| +-------------------------+----------------------------------+
|
| 84 |
+
| | query_start | query start position |
|
| 85 |
+
| +-------------------------+----------------------------------+
|
| 86 |
+
| | query_end | query end position |
|
| 87 |
+
| +-------------------------+----------------------------------+
|
| 88 |
+
| | query_endtype | query sequence end types (e.g., |
|
| 89 |
+
| | | '[]', '..', '[.', '.]', etc.) |
|
| 90 |
+
| +-------------------------+----------------------------------+
|
| 91 |
+
| | hit_start | hit start position |
|
| 92 |
+
| +-------------------------+----------------------------------+
|
| 93 |
+
| | hit_end | hit end position |
|
| 94 |
+
| +-------------------------+----------------------------------+
|
| 95 |
+
| | hit_endtype | hit sequence end types |
|
| 96 |
+
| +-------------------------+----------------------------------+
|
| 97 |
+
| | acc_avg | expected accuracy per alignment |
|
| 98 |
+
| | | residue (acc column) |
|
| 99 |
+
| +-------------------------+----------------------------------+
|
| 100 |
+
| | model | type of model used (cm or hmm) |
|
| 101 |
+
| +-------------------------+----------------------------------+
|
| 102 |
+
| | truncated | indicate if the hit is truncated |
|
| 103 |
+
| | | (5', 3' or both) or not |
|
| 104 |
+
+-----------------+-------------------------+----------------------------------+
|
| 105 |
+
| HSPFragment | aln_annotation | alignment similarity string and |
|
| 106 |
+
| | | other annotations (PP, CS, |
|
| 107 |
+
| | | similarity and NC (except for |
|
| 108 |
+
| | | --hmmonly)) |
|
| 109 |
+
| +-------------------------+----------------------------------+
|
| 110 |
+
| | aln_span | length of alignment fragment |
|
| 111 |
+
| +-------------------------+----------------------------------+
|
| 112 |
+
| | hit | hit sequence |
|
| 113 |
+
| +-------------------------+----------------------------------+
|
| 114 |
+
| | hit_start | local alignment sequence start |
|
| 115 |
+
| | | coordinate (seq from) |
|
| 116 |
+
| +-------------------------+----------------------------------+
|
| 117 |
+
| | hit_end | local alignment sequence end |
|
| 118 |
+
| | | coordinate (seq to) |
|
| 119 |
+
| +-------------------------+----------------------------------+
|
| 120 |
+
| | hit_strand | hit sequence strand |
|
| 121 |
+
| +-------------------------+----------------------------------+
|
| 122 |
+
| | query | query sequence |
|
| 123 |
+
| +-------------------------+----------------------------------+
|
| 124 |
+
| | query_start | local model alignment start |
|
| 125 |
+
| | | coordinate (mdl from) |
|
| 126 |
+
| +-------------------------+----------------------------------+
|
| 127 |
+
| | query_end | local model alignment end |
|
| 128 |
+
| | | coordinate (mdl to) |
|
| 129 |
+
+-----------------+-------------------------+----------------------------------+
|
| 130 |
+
|
| 131 |
+
infernal-tab
|
| 132 |
+
============
|
| 133 |
+
|
| 134 |
+
The Infernal plain text parser supports the standard cmsearch tabular output and
|
| 135 |
+
cmscan tabular output files formats 1, 2 and 3 (inferred automatically from the
|
| 136 |
+
header).
|
| 137 |
+
|
| 138 |
+
Rows marked with '*' denotes attributes not available in the default format.
|
| 139 |
+
|
| 140 |
+
+-----------------+-------------------------+----------------------------------+
|
| 141 |
+
| Object | Attribute | Value |
|
| 142 |
+
+=================+=========================+==================================+
|
| 143 |
+
| QueryResult | accession | query accession |
|
| 144 |
+
| +-------------------------+----------------------------------+
|
| 145 |
+
| | id | query sequence ID |
|
| 146 |
+
| +-------------------------+----------------------------------+
|
| 147 |
+
| | clan* | Rfam clan |
|
| 148 |
+
| +-------------------------+----------------------------------+
|
| 149 |
+
| | seq_len* | query sequence length |
|
| 150 |
+
+-----------------+-------------------------+----------------------------------+
|
| 151 |
+
| Hit | description | hit sequence description |
|
| 152 |
+
| +-------------------------+----------------------------------+
|
| 153 |
+
| | id | hit sequence ID |
|
| 154 |
+
| +-------------------------+----------------------------------+
|
| 155 |
+
| | accession | hit accession |
|
| 156 |
+
| +-------------------------+----------------------------------+
|
| 157 |
+
| | seq_len* | hit sequence length |
|
| 158 |
+
+-----------------+-------------------------+----------------------------------+
|
| 159 |
+
| HSP | evalue | hsp evalue |
|
| 160 |
+
| +-------------------------+----------------------------------+
|
| 161 |
+
| | bias | hsp bias |
|
| 162 |
+
| +-------------------------+----------------------------------+
|
| 163 |
+
| | bitscore | hsp score |
|
| 164 |
+
| +-------------------------+----------------------------------+
|
| 165 |
+
| | gc | gc fraction |
|
| 166 |
+
| +-------------------------+----------------------------------+
|
| 167 |
+
| | is_included | boolean, whether the hit of the |
|
| 168 |
+
| | | hsp is in the inclusion |
|
| 169 |
+
| | | threshold |
|
| 170 |
+
| +-------------------------+----------------------------------+
|
| 171 |
+
| | model | type of model used (cm or hmm) |
|
| 172 |
+
| +-------------------------+----------------------------------+
|
| 173 |
+
| | truncated | indicate if the hit is truncated |
|
| 174 |
+
| | | (5', 3' or both) or not |
|
| 175 |
+
| +-------------------------+----------------------------------+
|
| 176 |
+
| | pipeline_pass | pipeline pass at which the hit |
|
| 177 |
+
| | | was identified |
|
| 178 |
+
| +-------------------------+----------------------------------+
|
| 179 |
+
| | olp* | overlap status of this hit ('*', |
|
| 180 |
+
| | | '^', '$' or '=') |
|
| 181 |
+
| +-------------------------+----------------------------------+
|
| 182 |
+
| | anyidx* | index of the best scoring |
|
| 183 |
+
| | | overlapping hit (or none if |
|
| 184 |
+
| | | there are no overlap) |
|
| 185 |
+
| +-------------------------+----------------------------------+
|
| 186 |
+
| | afrct1* | fraction of this hit that |
|
| 187 |
+
| | | overlap with anyidx hit (or none |
|
| 188 |
+
| | | if there are no overlap) |
|
| 189 |
+
| +-------------------------+----------------------------------+
|
| 190 |
+
| | afrct2* | fraction of anyidx hit |
|
| 191 |
+
| | | with this hit (or none if there |
|
| 192 |
+
| | | are no overlap) |
|
| 193 |
+
| +-------------------------+----------------------------------+
|
| 194 |
+
| | winidx* | index of the best scoring hit |
|
| 195 |
+
| | | that overlaps with this hit that |
|
| 196 |
+
| | | is marked as '^' (or none if |
|
| 197 |
+
| | | there are no overlap) |
|
| 198 |
+
| +-------------------------+----------------------------------+
|
| 199 |
+
| | wfrct1* | fraction of this hit that |
|
| 200 |
+
| | | overlap with winidx hit (or none |
|
| 201 |
+
| | | if there are no overlap) |
|
| 202 |
+
| +-------------------------+----------------------------------+
|
| 203 |
+
| | wfrct2* | fraction of winidx hit |
|
| 204 |
+
| | | with this hit (or none if there |
|
| 205 |
+
| | | are no overlap) |
|
| 206 |
+
+-----------------+-------------------------+----------------------------------+
|
| 207 |
+
| HSPFragment | hit_start | local alignment sequence start |
|
| 208 |
+
| (also via HSP) | | coordinate (seq from) |
|
| 209 |
+
| +-------------------------+----------------------------------+
|
| 210 |
+
| | hit_end | local alignment sequence end |
|
| 211 |
+
| | | coordinate (seq to) |
|
| 212 |
+
| +-------------------------+----------------------------------+
|
| 213 |
+
| | hit_strand | hit sequence strand |
|
| 214 |
+
| +-------------------------+----------------------------------+
|
| 215 |
+
| | query_start | local model alignment start |
|
| 216 |
+
| | | coordinate (mdl from) |
|
| 217 |
+
| +-------------------------+----------------------------------+
|
| 218 |
+
| | query_end | local model alignment end |
|
| 219 |
+
| | | coordinate (mdl to) |
|
| 220 |
+
+-----------------+-------------------------+----------------------------------+
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
from .infernal_tab import InfernalTabParser
|
| 224 |
+
from .infernal_tab import InfernalTabIndexer
|
| 225 |
+
from .infernal_text import InfernalTextParser
|
| 226 |
+
from .infernal_text import InfernalTextIndexer
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# if not used as a module, run the doctest
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
from Bio._utils import run_doctest
|
| 232 |
+
|
| 233 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/_base.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 by Samuel Prince. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of the Biopython distribution and governed by your
|
| 4 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 5 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 6 |
+
# package.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
"""Bio.SearchIO base classes for Infernal-related code."""
|
| 10 |
+
|
| 11 |
+
from Bio.SearchIO._model import Hit
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class _BaseInfernalParser:
|
| 15 |
+
"""Abstract class for Infernal parser objects."""
|
| 16 |
+
|
| 17 |
+
def _add_hit_to_dict(self, hit_attrs, hsp, hit_dict):
|
| 18 |
+
"""Add a hit information to the hit container (PRIVATE)."""
|
| 19 |
+
# add the hit to the container dict, creating a new
|
| 20 |
+
# entry if it does not exist yet
|
| 21 |
+
hid = hit_attrs["id"]
|
| 22 |
+
if hid not in hit_dict:
|
| 23 |
+
hit_dict[hid] = {"attrs": hit_attrs, "hsps": []}
|
| 24 |
+
else:
|
| 25 |
+
assert hit_dict[hid]["attrs"]["query_id"] == hit_attrs["query_id"]
|
| 26 |
+
assert hit_dict[hid]["attrs"]["description"] == hit_attrs["description"]
|
| 27 |
+
|
| 28 |
+
hit_dict[hid]["hsps"].append(hsp)
|
| 29 |
+
|
| 30 |
+
def _hit_to_list(self, hit_dict):
|
| 31 |
+
"""Create a Hit list from the hit container (PRIVATE)."""
|
| 32 |
+
|
| 33 |
+
hit_list = []
|
| 34 |
+
for hit_info in hit_dict.values():
|
| 35 |
+
hit = Hit(hit_info["hsps"])
|
| 36 |
+
for attr, value in hit_info["attrs"].items():
|
| 37 |
+
setattr(hit, attr, value)
|
| 38 |
+
hit_list.append(hit)
|
| 39 |
+
return hit_list
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_tab.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 by Samuel Prince. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of the Biopython distribution and governed by your
|
| 4 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 5 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 6 |
+
# package.
|
| 7 |
+
|
| 8 |
+
"""Bio.SearchIO parser for Infernal tabular output format."""
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._index import SearchIndexer
|
| 11 |
+
from Bio.SearchIO._model import HSP
|
| 12 |
+
from Bio.SearchIO._model import HSPFragment
|
| 13 |
+
from Bio.SearchIO._model import QueryResult
|
| 14 |
+
|
| 15 |
+
from ._base import _BaseInfernalParser
|
| 16 |
+
from Bio.File import _open_for_random_access
|
| 17 |
+
|
| 18 |
+
__all__ = ("InfernalTabParser", "InfernalTabIndexer")
|
| 19 |
+
|
| 20 |
+
# tabular format column names
|
| 21 |
+
_TAB_FORMAT = {
|
| 22 |
+
1: (
|
| 23 |
+
"target_name",
|
| 24 |
+
"target_acc",
|
| 25 |
+
"query_name",
|
| 26 |
+
"query_acc",
|
| 27 |
+
"mdl",
|
| 28 |
+
"mdl_from",
|
| 29 |
+
"mdl_to",
|
| 30 |
+
"seq_from",
|
| 31 |
+
"seq_to",
|
| 32 |
+
"strand",
|
| 33 |
+
"trunc",
|
| 34 |
+
"pass",
|
| 35 |
+
"gc",
|
| 36 |
+
"bias",
|
| 37 |
+
"score",
|
| 38 |
+
"evalue",
|
| 39 |
+
"inc",
|
| 40 |
+
"description",
|
| 41 |
+
),
|
| 42 |
+
2: (
|
| 43 |
+
"idx",
|
| 44 |
+
"target_name",
|
| 45 |
+
"target_acc",
|
| 46 |
+
"query_name",
|
| 47 |
+
"query_acc",
|
| 48 |
+
"clan",
|
| 49 |
+
"mdl",
|
| 50 |
+
"mdl_from",
|
| 51 |
+
"mdl_to",
|
| 52 |
+
"seq_from",
|
| 53 |
+
"seq_to",
|
| 54 |
+
"strand",
|
| 55 |
+
"trunc",
|
| 56 |
+
"pass",
|
| 57 |
+
"gc",
|
| 58 |
+
"bias",
|
| 59 |
+
"score",
|
| 60 |
+
"evalue",
|
| 61 |
+
"inc",
|
| 62 |
+
"olp",
|
| 63 |
+
"anyidx",
|
| 64 |
+
"afrct1",
|
| 65 |
+
"afrct2",
|
| 66 |
+
"winidx",
|
| 67 |
+
"wfrct1",
|
| 68 |
+
"wfrct2",
|
| 69 |
+
"mdl_len",
|
| 70 |
+
"seq_len",
|
| 71 |
+
"description",
|
| 72 |
+
),
|
| 73 |
+
3: (
|
| 74 |
+
"target_name",
|
| 75 |
+
"target_acc",
|
| 76 |
+
"query_name",
|
| 77 |
+
"query_acc",
|
| 78 |
+
"mdl",
|
| 79 |
+
"mdl_from",
|
| 80 |
+
"mdl_to",
|
| 81 |
+
"seq_from",
|
| 82 |
+
"seq_to",
|
| 83 |
+
"strand",
|
| 84 |
+
"trunc",
|
| 85 |
+
"pass",
|
| 86 |
+
"gc",
|
| 87 |
+
"bias",
|
| 88 |
+
"score",
|
| 89 |
+
"evalue",
|
| 90 |
+
"inc",
|
| 91 |
+
"mdl_len",
|
| 92 |
+
"seq_len",
|
| 93 |
+
"description",
|
| 94 |
+
),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
_TABULAR_FMT_1_HEADER_FIELDS = [
|
| 98 |
+
"target name",
|
| 99 |
+
"accession",
|
| 100 |
+
"query name",
|
| 101 |
+
"accession",
|
| 102 |
+
"mdl",
|
| 103 |
+
"mdl from",
|
| 104 |
+
"mdl to",
|
| 105 |
+
"seq from",
|
| 106 |
+
"seq to",
|
| 107 |
+
"strand",
|
| 108 |
+
"trunc",
|
| 109 |
+
"pass",
|
| 110 |
+
"gc",
|
| 111 |
+
"bias",
|
| 112 |
+
"score",
|
| 113 |
+
"E-value",
|
| 114 |
+
"inc",
|
| 115 |
+
"description of target",
|
| 116 |
+
]
|
| 117 |
+
_TABULAR_FMT_2_HEADER_FIELDS = [
|
| 118 |
+
"idx",
|
| 119 |
+
"target name",
|
| 120 |
+
"accession",
|
| 121 |
+
"query name",
|
| 122 |
+
"accession",
|
| 123 |
+
"clan name",
|
| 124 |
+
"mdl",
|
| 125 |
+
"mdl from",
|
| 126 |
+
"mdl to",
|
| 127 |
+
"seq from",
|
| 128 |
+
"seq to",
|
| 129 |
+
"strand",
|
| 130 |
+
"trunc",
|
| 131 |
+
"pass",
|
| 132 |
+
"gc",
|
| 133 |
+
"bias",
|
| 134 |
+
"score",
|
| 135 |
+
"E-value",
|
| 136 |
+
"inc",
|
| 137 |
+
"olp",
|
| 138 |
+
"anyidx",
|
| 139 |
+
"afrct1",
|
| 140 |
+
"afrct2",
|
| 141 |
+
"winidx",
|
| 142 |
+
"wfrct1",
|
| 143 |
+
"wfrct2",
|
| 144 |
+
"mdl len",
|
| 145 |
+
"seq len",
|
| 146 |
+
"description of target",
|
| 147 |
+
]
|
| 148 |
+
_TABULAR_FMT_3_HEADER_FIELDS = [
|
| 149 |
+
"target name",
|
| 150 |
+
"accession",
|
| 151 |
+
"query name",
|
| 152 |
+
"accession",
|
| 153 |
+
"mdl",
|
| 154 |
+
"mdl from",
|
| 155 |
+
"mdl to",
|
| 156 |
+
"seq from",
|
| 157 |
+
"seq to",
|
| 158 |
+
"strand",
|
| 159 |
+
"trunc",
|
| 160 |
+
"pass",
|
| 161 |
+
"gc",
|
| 162 |
+
"bias",
|
| 163 |
+
"score",
|
| 164 |
+
"E-value",
|
| 165 |
+
"inc",
|
| 166 |
+
"mdl len",
|
| 167 |
+
"seq len",
|
| 168 |
+
"description of target",
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
+
# column to class attribute map
|
| 172 |
+
_COLUMN_QRESULT = {
|
| 173 |
+
"query_name": ("id", str),
|
| 174 |
+
"query_acc": ("accession", str),
|
| 175 |
+
"seq_len": ("seq_len", int),
|
| 176 |
+
"clan": ("clan", str),
|
| 177 |
+
}
|
| 178 |
+
_COLUMN_HIT = {
|
| 179 |
+
"target_name": ("id", str),
|
| 180 |
+
"target_acc": ("accession", str),
|
| 181 |
+
"query_name": ("query_id", str),
|
| 182 |
+
"description": ("description", str),
|
| 183 |
+
"mdl_len": ("seq_len", int),
|
| 184 |
+
}
|
| 185 |
+
_COLUMN_HSP = {
|
| 186 |
+
"score": ("bitscore", float),
|
| 187 |
+
"evalue": ("evalue", float),
|
| 188 |
+
"bias": ("bias", float),
|
| 189 |
+
"gc": ("gc", float),
|
| 190 |
+
"mdl": ("model", str),
|
| 191 |
+
"trunc": ("truncated", str),
|
| 192 |
+
"pass": ("pipeline_pass", int),
|
| 193 |
+
"inc": ("is_included", lambda x: True if x == "!" else False),
|
| 194 |
+
"olp": ("olp", str),
|
| 195 |
+
"anyidx": ("anyidx", lambda x: None if x == "-" else int(x)),
|
| 196 |
+
"afrct1": ("afrct1", lambda x: None if x == "-" else float(x)),
|
| 197 |
+
"afrct2": ("afrct2", lambda x: None if x == "-" else float(x)),
|
| 198 |
+
"winidx": ("winidx", lambda x: None if (x == "-" or x == '"') else int(x)),
|
| 199 |
+
"wfrct1": ("wfrct1", lambda x: None if (x == "-" or x == '"') else float(x)),
|
| 200 |
+
"wfrct2": ("wfrct2", lambda x: None if (x == "-" or x == '"') else float(x)),
|
| 201 |
+
}
|
| 202 |
+
_COLUMN_FRAG = {
|
| 203 |
+
"mdl_from": ("query_start", int),
|
| 204 |
+
"mdl_to": ("query_end", int),
|
| 205 |
+
"seq_from": ("hit_start", int),
|
| 206 |
+
"seq_to": ("hit_end", int),
|
| 207 |
+
"strand": ("hit_strand", str),
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _infer_tabular_format(handle, is_byte=False):
|
| 212 |
+
"""Infer tabular format from the tabular file header. (PRIVATE)"""
|
| 213 |
+
# infernal tabular output columns are space separated files with spaces in
|
| 214 |
+
# column names, ex:
|
| 215 |
+
# #target name accession
|
| 216 |
+
# #------------------- ---------
|
| 217 |
+
# so we use the second line of the header where the is not spaces to
|
| 218 |
+
# determine the position of the headers labels. Then we can get the label names
|
| 219 |
+
# and compare the the different tabular format names. This label comparison is done
|
| 220 |
+
# (instead of counting fields) to avoid issues if future tabular format have the
|
| 221 |
+
# same number of fields, but with different signification
|
| 222 |
+
|
| 223 |
+
def process_line(handle, is_byte):
|
| 224 |
+
"""Process a line from the handle, decoding byte stream."""
|
| 225 |
+
line = handle.readline().strip()
|
| 226 |
+
return line.decode() if is_byte else line
|
| 227 |
+
|
| 228 |
+
header_label = process_line(handle, is_byte)
|
| 229 |
+
header_delim = process_line(handle, is_byte)
|
| 230 |
+
|
| 231 |
+
if header_label == "" or header_delim == "":
|
| 232 |
+
raise ValueError(
|
| 233 |
+
"Unexpected empty line in the header of Infernal tabular output."
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# get the indices of the spaces fields delimiter from the second header line
|
| 237 |
+
# the end of the file is added to the indices to process the last field
|
| 238 |
+
indices = [idx for idx, char in enumerate(header_delim) if char == " "] + [
|
| 239 |
+
len(header_delim)
|
| 240 |
+
]
|
| 241 |
+
prev_idx = 1
|
| 242 |
+
fields = []
|
| 243 |
+
for idx in indices:
|
| 244 |
+
fields.append(header_label[prev_idx:idx].strip())
|
| 245 |
+
prev_idx = idx
|
| 246 |
+
|
| 247 |
+
# compare the headers fields to the possible fields to determine the format
|
| 248 |
+
if fields == _TABULAR_FMT_1_HEADER_FIELDS:
|
| 249 |
+
return 1
|
| 250 |
+
elif fields == _TABULAR_FMT_2_HEADER_FIELDS:
|
| 251 |
+
return 2
|
| 252 |
+
elif fields == _TABULAR_FMT_3_HEADER_FIELDS:
|
| 253 |
+
return 3
|
| 254 |
+
else:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
"Cannot determine the tabular format from the header. \
|
| 257 |
+
The tabular file is likely incorrect or its format is unsupported. \
|
| 258 |
+
Tabular format 1, 2 and 3 are currently supported)."
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class InfernalTabParser(_BaseInfernalParser):
|
| 263 |
+
"""Parser for the Infernal tabular format."""
|
| 264 |
+
|
| 265 |
+
def __init__(self, handle, _fmt=None):
|
| 266 |
+
"""Initialize the class."""
|
| 267 |
+
self.handle = handle
|
| 268 |
+
if isinstance(_fmt, int):
|
| 269 |
+
assert _fmt in {1, 2, 3}
|
| 270 |
+
self.fmt = _fmt
|
| 271 |
+
else:
|
| 272 |
+
self.fmt = _infer_tabular_format(handle=handle)
|
| 273 |
+
|
| 274 |
+
def __iter__(self):
|
| 275 |
+
"""Iterate over InfernalTabParser, yields query results."""
|
| 276 |
+
# read through the header (and footer if there is no results)
|
| 277 |
+
self.line = self.handle.readline()
|
| 278 |
+
while self.line.startswith("#"):
|
| 279 |
+
self.line = self.handle.readline()
|
| 280 |
+
# if we have result rows, parse them
|
| 281 |
+
if self.line:
|
| 282 |
+
yield from self._parse_qresult()
|
| 283 |
+
|
| 284 |
+
def _parse_row(self):
|
| 285 |
+
"""Return a dictionary of parsed row values (PRIVATE)."""
|
| 286 |
+
cols = [x for x in self.line.strip().split(" ") if x]
|
| 287 |
+
if len(cols) < len(_TAB_FORMAT[self.fmt]):
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f"Less columns than expected for format {self.fmt}, only {len(cols)}"
|
| 290 |
+
)
|
| 291 |
+
# combine extra description columns into one string
|
| 292 |
+
cols[len(_TAB_FORMAT[self.fmt]) - 1] = " ".join(
|
| 293 |
+
cols[len(_TAB_FORMAT[self.fmt]) - 1 :]
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
qresult, hit, hsp, frag = {}, {}, {}, {}
|
| 297 |
+
for sname, value in zip(
|
| 298 |
+
_TAB_FORMAT[self.fmt], cols[: len(_TAB_FORMAT[self.fmt])]
|
| 299 |
+
):
|
| 300 |
+
# iterate over each dict, mapping pair to determine
|
| 301 |
+
# attribute name and value of each column
|
| 302 |
+
for parsed_dict, mapping in (
|
| 303 |
+
(qresult, _COLUMN_QRESULT),
|
| 304 |
+
(hit, _COLUMN_HIT),
|
| 305 |
+
(hsp, _COLUMN_HSP),
|
| 306 |
+
(frag, _COLUMN_FRAG),
|
| 307 |
+
):
|
| 308 |
+
# process parsed value according to mapping
|
| 309 |
+
if sname in mapping:
|
| 310 |
+
attr_name, caster = mapping[sname]
|
| 311 |
+
if caster is not str:
|
| 312 |
+
value = caster(value)
|
| 313 |
+
parsed_dict[attr_name] = value
|
| 314 |
+
|
| 315 |
+
# adjust start and end coordinates according to strand
|
| 316 |
+
self._adjust_coords(frag)
|
| 317 |
+
|
| 318 |
+
return {"qresult": qresult, "hit": hit, "hsp": hsp, "frag": frag}
|
| 319 |
+
|
| 320 |
+
def _adjust_coords(self, frag):
|
| 321 |
+
"""Adjust start and end coordinates according to strand (PRIVATE)."""
|
| 322 |
+
strand = frag["hit_strand"]
|
| 323 |
+
assert strand is not None
|
| 324 |
+
# switch start <--> end coordinates if strand is -1 and the strand to an integer (0 or -1)
|
| 325 |
+
if strand == "-":
|
| 326 |
+
hit_start = frag["hit_start"]
|
| 327 |
+
hit_end = frag["hit_end"]
|
| 328 |
+
frag["hit_start"] = hit_end
|
| 329 |
+
frag["hit_end"] = hit_start
|
| 330 |
+
frag["hit_strand"] = -1
|
| 331 |
+
else:
|
| 332 |
+
frag["hit_strand"] = 0
|
| 333 |
+
|
| 334 |
+
def _parse_qresult(self):
|
| 335 |
+
"""Yield QueryResult objects (PRIVATE)."""
|
| 336 |
+
# state values, determines what to do for each line
|
| 337 |
+
state_EOF = 0
|
| 338 |
+
state_QRES_NEW = 1
|
| 339 |
+
state_QRES_SAME = 3
|
| 340 |
+
# dummies for initial states
|
| 341 |
+
qres_state = None
|
| 342 |
+
file_state = None
|
| 343 |
+
cur_qid = None
|
| 344 |
+
cur_hid = None
|
| 345 |
+
# dummies for initial id caches
|
| 346 |
+
prev_qid = None
|
| 347 |
+
prev_hid = None
|
| 348 |
+
# dummies for initial parsed value containers
|
| 349 |
+
cur, prev = None, None
|
| 350 |
+
hit_dict = {}
|
| 351 |
+
|
| 352 |
+
while True:
|
| 353 |
+
# store previous line's parsed values for all lines after the first
|
| 354 |
+
if cur is not None:
|
| 355 |
+
prev = cur
|
| 356 |
+
prev_qid = cur_qid
|
| 357 |
+
prev_hid = cur_hid
|
| 358 |
+
# only parse the result row if it's not EOF or a comment line
|
| 359 |
+
if self.line and not self.line.startswith("#"):
|
| 360 |
+
cur = self._parse_row()
|
| 361 |
+
cur_qid = cur["qresult"]["id"]
|
| 362 |
+
cur_hid = cur["hit"]["id"]
|
| 363 |
+
else:
|
| 364 |
+
file_state = state_EOF
|
| 365 |
+
# mock values for cur_qid and cur_hid since the line is empty
|
| 366 |
+
cur_qid, cur_hid = None, None
|
| 367 |
+
|
| 368 |
+
# get the state of hit and qresult
|
| 369 |
+
if prev_qid != cur_qid:
|
| 370 |
+
qres_state = state_QRES_NEW
|
| 371 |
+
else:
|
| 372 |
+
qres_state = state_QRES_SAME
|
| 373 |
+
|
| 374 |
+
# creating objects for the previously parsed line(s), so nothing is done
|
| 375 |
+
# in the first parsed line (prev == None)
|
| 376 |
+
if prev is not None:
|
| 377 |
+
# create fragment and HSP and set their attributes
|
| 378 |
+
# and append to hit container
|
| 379 |
+
frag = HSPFragment(prev_hid, prev_qid)
|
| 380 |
+
for attr, value in prev["frag"].items():
|
| 381 |
+
setattr(frag, attr, value)
|
| 382 |
+
hsp = HSP([frag])
|
| 383 |
+
for attr, value in prev["hsp"].items():
|
| 384 |
+
setattr(hsp, attr, value)
|
| 385 |
+
self._add_hit_to_dict(prev["hit"], hsp, hit_dict)
|
| 386 |
+
|
| 387 |
+
# create qresult and yield if we're at a new qresult or at EOF
|
| 388 |
+
if qres_state == state_QRES_NEW or file_state == state_EOF:
|
| 389 |
+
# create the hit list from the temporary container
|
| 390 |
+
qresult = QueryResult(self._hit_to_list(hit_dict), prev_qid)
|
| 391 |
+
for attr, value in prev["qresult"].items():
|
| 392 |
+
setattr(qresult, attr, value)
|
| 393 |
+
yield qresult
|
| 394 |
+
# if we're at EOF, break
|
| 395 |
+
if file_state == state_EOF:
|
| 396 |
+
break
|
| 397 |
+
hit_dict = {}
|
| 398 |
+
|
| 399 |
+
self.line = self.handle.readline()
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class InfernalTabIndexer(SearchIndexer):
|
| 403 |
+
"""Indexer class for Infernal tabular output."""
|
| 404 |
+
|
| 405 |
+
_parser = InfernalTabParser
|
| 406 |
+
|
| 407 |
+
def __init__(self, filename):
|
| 408 |
+
"""Initialize the class."""
|
| 409 |
+
# the index of the query id column in the tabular file varies depending on the fmt
|
| 410 |
+
# we need to use the format set by the user, or infer the format to parse the records
|
| 411 |
+
with _open_for_random_access(filename) as handle:
|
| 412 |
+
fmt = _infer_tabular_format(handle, is_byte=True)
|
| 413 |
+
self._query_id_idx = 3 if fmt == 2 else 2
|
| 414 |
+
|
| 415 |
+
SearchIndexer.__init__(self, filename, _fmt=fmt)
|
| 416 |
+
|
| 417 |
+
def __iter__(self):
|
| 418 |
+
"""Iterate over the file handle; yields key, start offset, and length."""
|
| 419 |
+
handle = self._handle
|
| 420 |
+
handle.seek(0)
|
| 421 |
+
qresult_key = None
|
| 422 |
+
start_offset = handle.tell()
|
| 423 |
+
|
| 424 |
+
# set line with mock value
|
| 425 |
+
line = b"#"
|
| 426 |
+
|
| 427 |
+
# read through header
|
| 428 |
+
while line.startswith(b"#"):
|
| 429 |
+
start_offset = handle.tell()
|
| 430 |
+
line = handle.readline()
|
| 431 |
+
|
| 432 |
+
# index the qresults
|
| 433 |
+
while True:
|
| 434 |
+
# get end offset here since we only know a qresult ends after
|
| 435 |
+
# encountering the next one
|
| 436 |
+
end_offset = handle.tell()
|
| 437 |
+
|
| 438 |
+
if not line:
|
| 439 |
+
break
|
| 440 |
+
|
| 441 |
+
cols = [x for x in line.strip().split(b" ") if x]
|
| 442 |
+
|
| 443 |
+
if qresult_key is None:
|
| 444 |
+
qresult_key = cols[self._query_id_idx]
|
| 445 |
+
else:
|
| 446 |
+
curr_key = cols[self._query_id_idx]
|
| 447 |
+
if curr_key != qresult_key:
|
| 448 |
+
adj_end = end_offset - len(line)
|
| 449 |
+
yield (qresult_key.decode(), start_offset, adj_end - start_offset)
|
| 450 |
+
qresult_key = curr_key
|
| 451 |
+
start_offset = adj_end
|
| 452 |
+
|
| 453 |
+
line = handle.readline()
|
| 454 |
+
if not line or line.startswith(b"#"):
|
| 455 |
+
yield (qresult_key.decode(), start_offset, end_offset - start_offset)
|
| 456 |
+
break
|
| 457 |
+
|
| 458 |
+
def get_raw(self, offset):
|
| 459 |
+
"""Return the raw bytes string of a QueryResult object from the given offset."""
|
| 460 |
+
handle = self._handle
|
| 461 |
+
qresult_key = None
|
| 462 |
+
qresult_raw = b""
|
| 463 |
+
|
| 464 |
+
# read the qresult raw string
|
| 465 |
+
handle.seek(offset)
|
| 466 |
+
while True:
|
| 467 |
+
line = handle.readline()
|
| 468 |
+
if not line or line.startswith(b"#"):
|
| 469 |
+
break
|
| 470 |
+
cols = [x for x in line.strip().split(b" ") if x]
|
| 471 |
+
if qresult_key is None:
|
| 472 |
+
qresult_key = cols[self._query_id_idx]
|
| 473 |
+
else:
|
| 474 |
+
curr_key = cols[self._query_id_idx]
|
| 475 |
+
if curr_key != qresult_key:
|
| 476 |
+
break
|
| 477 |
+
qresult_raw += line
|
| 478 |
+
|
| 479 |
+
return qresult_raw
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# if not used as a module, run the doctest
|
| 483 |
+
if __name__ == "__main__":
|
| 484 |
+
from Bio._utils import run_doctest
|
| 485 |
+
|
| 486 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_text.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 by Samuel Prince. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of the Biopython distribution and governed by your
|
| 4 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 5 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 6 |
+
# package.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
"""Bio.SearchIO parser for Infernal plain text output format."""
|
| 10 |
+
|
| 11 |
+
import operator
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
from Bio.SearchIO._index import SearchIndexer
|
| 15 |
+
from Bio.SearchIO._model import HSP
|
| 16 |
+
from Bio.SearchIO._model import HSPFragment
|
| 17 |
+
from Bio.SearchIO._model import QueryResult
|
| 18 |
+
from Bio.SearchIO._utils import read_forward
|
| 19 |
+
|
| 20 |
+
from ._base import _BaseInfernalParser
|
| 21 |
+
|
| 22 |
+
__all__ = ("InfernalTextParser", "InfernalTextIndexer")
|
| 23 |
+
|
| 24 |
+
# precompile regex patterns for faster processing
|
| 25 |
+
# program name
|
| 26 |
+
_RE_PROGRAM = re.compile(r"^# .*?(\w?cm\w+) :: .*$")
|
| 27 |
+
# version string
|
| 28 |
+
_RE_VERSION = re.compile(r"# INFERNAL+ ([\w+\.]{2,}) .*$")
|
| 29 |
+
# option string
|
| 30 |
+
_RE_OPT = re.compile(r"^# (.+):\s+(.+)$")
|
| 31 |
+
# numbers only
|
| 32 |
+
_RE_NUMERIC = re.compile(r"\d+")
|
| 33 |
+
_RE_NOT_NUMERIC = re.compile(r"\D")
|
| 34 |
+
# letters only
|
| 35 |
+
_RE_LETTERS = re.compile(r"[^A-Za-z]")
|
| 36 |
+
# missing segments in the alignment block
|
| 37 |
+
_RE_SPLIT_ALN = re.compile(r"(\*\[[ 0-9]+\]\*)+")
|
| 38 |
+
|
| 39 |
+
# divider for Infernal plain text output, these divider are
|
| 40 |
+
# always taken from the beginning of the line to be usable in
|
| 41 |
+
# self.line.startswith() method
|
| 42 |
+
# header options
|
| 43 |
+
_DIV_HEADER_OPT = "# - - -"
|
| 44 |
+
# query
|
| 45 |
+
_DIV_QUERY_END = "//"
|
| 46 |
+
_DIV_QUERY_START = "Query:"
|
| 47 |
+
# hits
|
| 48 |
+
_DIV_HITS_END_CM = "Internal CM pipeline statistics summary:"
|
| 49 |
+
_DIV_HITS_END_HMM = "Internal HMM-only pipeline statistics summary:"
|
| 50 |
+
_DIV_HIT_SCORE_TABLE = "Hit scores:"
|
| 51 |
+
_DIV_HIT_ALIGNMENT = "Hit alignments:"
|
| 52 |
+
_DIV_NO_HIT = " [No hits detected that satisfy reporting thresholds]"
|
| 53 |
+
_DIV_TABLE_START = " ---- --------- ------"
|
| 54 |
+
_DIV_INC_THRESHOLD = " ------ inclusion threshold ------"
|
| 55 |
+
# hit alignment
|
| 56 |
+
_DIV_ALIGNMENT_START = ">> "
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class InfernalTextParser(_BaseInfernalParser):
|
| 60 |
+
"""Parser for the Infernal text output."""
|
| 61 |
+
|
| 62 |
+
def __init__(self, handle):
|
| 63 |
+
"""Initialize the class."""
|
| 64 |
+
self.handle = handle
|
| 65 |
+
self.line = read_forward(self.handle)
|
| 66 |
+
self._meta = self._parse_header()
|
| 67 |
+
|
| 68 |
+
def __iter__(self):
|
| 69 |
+
"""Iterate over query results."""
|
| 70 |
+
yield from self._parse_qresult()
|
| 71 |
+
|
| 72 |
+
def _read_until(self, bool_func):
|
| 73 |
+
"""Read the file handle until the given function returns True (PRIVATE)."""
|
| 74 |
+
while True:
|
| 75 |
+
if not self.line or bool_func(self.line):
|
| 76 |
+
return
|
| 77 |
+
self.line = read_forward(self.handle)
|
| 78 |
+
|
| 79 |
+
def _parse_header(self):
|
| 80 |
+
"""Parse Infernal header (PRIVATE)."""
|
| 81 |
+
meta = {}
|
| 82 |
+
# set the default value for the presence of alignment
|
| 83 |
+
# as this information is important for the hit section parsing
|
| 84 |
+
meta["show alignments in output"] = "yes"
|
| 85 |
+
# bool flag for storing state ~ whether we are parsing the option
|
| 86 |
+
# lines or not
|
| 87 |
+
has_opts = False
|
| 88 |
+
while True:
|
| 89 |
+
# no pound sign means we've left the preamble
|
| 90 |
+
if not self.line.startswith("#"):
|
| 91 |
+
break
|
| 92 |
+
# dashes could either mean we are entering or leaving the options
|
| 93 |
+
# section, so it's a switch for the has_opts flag
|
| 94 |
+
elif self.line.startswith(_DIV_HEADER_OPT):
|
| 95 |
+
if not has_opts:
|
| 96 |
+
# if flag is false, that means we're entering opts
|
| 97 |
+
# so switch the flag accordingly
|
| 98 |
+
has_opts = True
|
| 99 |
+
else:
|
| 100 |
+
# if flag is true, that means we've reached the end of opts
|
| 101 |
+
# so we can break out of the function
|
| 102 |
+
break
|
| 103 |
+
elif not has_opts:
|
| 104 |
+
# try parsing program
|
| 105 |
+
regx = re.search(_RE_PROGRAM, self.line)
|
| 106 |
+
if regx:
|
| 107 |
+
meta["program"] = regx.group(1)
|
| 108 |
+
# try parsing version
|
| 109 |
+
regx = re.search(_RE_VERSION, self.line)
|
| 110 |
+
if regx:
|
| 111 |
+
meta["version"] = regx.group(1)
|
| 112 |
+
elif has_opts:
|
| 113 |
+
regx = re.search(_RE_OPT, self.line)
|
| 114 |
+
# if target in regx.group(1), then we store the key as target
|
| 115 |
+
if "target" in regx.group(1):
|
| 116 |
+
meta["target"] = regx.group(2).strip()
|
| 117 |
+
else:
|
| 118 |
+
meta[regx.group(1)] = regx.group(2)
|
| 119 |
+
|
| 120 |
+
self.line = read_forward(self.handle)
|
| 121 |
+
|
| 122 |
+
return meta
|
| 123 |
+
|
| 124 |
+
def _parse_qresult(self):
|
| 125 |
+
"""Parse a Infernal query block (PRIVATE)."""
|
| 126 |
+
self._read_until(lambda line: line.startswith(_DIV_QUERY_START))
|
| 127 |
+
|
| 128 |
+
while self.line:
|
| 129 |
+
# create qresult for query id
|
| 130 |
+
if self.line.startswith(_DIV_QUERY_START):
|
| 131 |
+
qid = self.line.strip().split()[1]
|
| 132 |
+
qlen = int(re.sub(_RE_NOT_NUMERIC, "", self.line.strip().split()[-1]))
|
| 133 |
+
|
| 134 |
+
# store qresult attributes
|
| 135 |
+
qresult_attrs = {
|
| 136 |
+
"id": qid,
|
| 137 |
+
"seq_len": qlen,
|
| 138 |
+
"program": self._meta.get("program"),
|
| 139 |
+
"version": self._meta.get("version"),
|
| 140 |
+
"target": self._meta.get("target"),
|
| 141 |
+
}
|
| 142 |
+
else:
|
| 143 |
+
self.line = read_forward(self.handle)
|
| 144 |
+
|
| 145 |
+
# get description and accession, if they exist
|
| 146 |
+
qdesc = "<unknown description>" # placeholder
|
| 147 |
+
while not self.line.startswith(_DIV_HIT_SCORE_TABLE):
|
| 148 |
+
self.line = read_forward(self.handle)
|
| 149 |
+
|
| 150 |
+
if self.line.startswith("Accession:"):
|
| 151 |
+
acc = self.line.strip().split(" ", 1)[1]
|
| 152 |
+
qresult_attrs["accession"] = acc.strip()
|
| 153 |
+
elif self.line.startswith("Description:"):
|
| 154 |
+
qdesc = self.line.strip().split(" ", 1)[1].strip()
|
| 155 |
+
qresult_attrs["description"] = qdesc
|
| 156 |
+
|
| 157 |
+
# parse the query hits
|
| 158 |
+
# initializing hit_list directly to handle empty hits
|
| 159 |
+
hit_list = []
|
| 160 |
+
while self.line and not self.line.startswith(_DIV_QUERY_END):
|
| 161 |
+
hit_list = self._parse_hit(qid, qdesc)
|
| 162 |
+
# read through the statistics summary
|
| 163 |
+
if self.line.startswith(_DIV_HITS_END_CM) or self.line.startswith(
|
| 164 |
+
_DIV_HITS_END_HMM
|
| 165 |
+
):
|
| 166 |
+
while self.line and not self.line.startswith(_DIV_QUERY_END):
|
| 167 |
+
self.line = read_forward(self.handle)
|
| 168 |
+
# create qresult, set its attributes and yield
|
| 169 |
+
qresult = QueryResult(id=qid, hits=hit_list)
|
| 170 |
+
for attr, value in qresult_attrs.items():
|
| 171 |
+
setattr(qresult, attr, value)
|
| 172 |
+
yield qresult
|
| 173 |
+
self.line = read_forward(self.handle)
|
| 174 |
+
|
| 175 |
+
# Infernal outputs '[ok]' at the end of all results file,
|
| 176 |
+
# which means we can break the main loop when we see the line
|
| 177 |
+
if "[ok]" in self.line:
|
| 178 |
+
break
|
| 179 |
+
|
| 180 |
+
def _parse_hit(self, qid, qdesc):
|
| 181 |
+
"""Parse an Infernal hit (PRIVATE)."""
|
| 182 |
+
# state values, determines what to do for each block
|
| 183 |
+
hit_end = False
|
| 184 |
+
in_score_table = False
|
| 185 |
+
parsing_hits = False
|
| 186 |
+
prev_line = None
|
| 187 |
+
# hits are not guaranteed to be in order, and duplicate hit
|
| 188 |
+
# IDs will raise a ValueError. to avoid this, hits are stored in
|
| 189 |
+
# a temporary dictionary and the hit list required to create
|
| 190 |
+
# the QueryResult is generated at the end of the query block
|
| 191 |
+
hit_dict = {}
|
| 192 |
+
|
| 193 |
+
# set the divider based on the output type (with or without alignment)
|
| 194 |
+
if self._meta["show alignments in output"] == "no":
|
| 195 |
+
div_hit_start = _DIV_HIT_SCORE_TABLE
|
| 196 |
+
else:
|
| 197 |
+
div_hit_start = _DIV_ALIGNMENT_START
|
| 198 |
+
|
| 199 |
+
while True:
|
| 200 |
+
if not self.line:
|
| 201 |
+
raise ValueError("Unexpected end of file")
|
| 202 |
+
# if there are no hits, forward-read to the end of the query
|
| 203 |
+
elif self.line.startswith(_DIV_NO_HIT):
|
| 204 |
+
while True:
|
| 205 |
+
self.line = read_forward(self.handle)
|
| 206 |
+
if self.line.startswith(_DIV_HITS_END_CM) or self.line.startswith(
|
| 207 |
+
_DIV_HITS_END_HMM
|
| 208 |
+
):
|
| 209 |
+
hit_end = True
|
| 210 |
+
return []
|
| 211 |
+
# entering hit alignment block
|
| 212 |
+
elif self.line.startswith(div_hit_start):
|
| 213 |
+
# for --noali output, move to the beginning of the hit score table
|
| 214 |
+
if self._meta["show alignments in output"] == "no":
|
| 215 |
+
assert not in_score_table
|
| 216 |
+
self._read_until(lambda line: line.startswith(_DIV_TABLE_START))
|
| 217 |
+
self.line = read_forward(self.handle)
|
| 218 |
+
parsing_hits = in_score_table = True
|
| 219 |
+
else:
|
| 220 |
+
self._parse_hit_from_alignment(qid, hit_dict)
|
| 221 |
+
parsing_hits = True
|
| 222 |
+
# we've reached the end of the hit section
|
| 223 |
+
elif self.line.startswith(_DIV_HITS_END_CM) or self.line.startswith(
|
| 224 |
+
_DIV_HITS_END_HMM
|
| 225 |
+
):
|
| 226 |
+
hit_end = True
|
| 227 |
+
parsing_hits = False
|
| 228 |
+
# Read through the scores table. For regular output this information
|
| 229 |
+
# is not needed, so we can skip it. For --noali output, this table
|
| 230 |
+
# contains the HSP information
|
| 231 |
+
else:
|
| 232 |
+
# for --noali output, keep the line
|
| 233 |
+
if in_score_table:
|
| 234 |
+
if self.line.strip():
|
| 235 |
+
prev_line = self.line
|
| 236 |
+
else:
|
| 237 |
+
parsing_hits = in_score_table = False
|
| 238 |
+
|
| 239 |
+
# read one line at the time
|
| 240 |
+
self.line = self.handle.readline()
|
| 241 |
+
|
| 242 |
+
# for --noali output, parse the scores table row
|
| 243 |
+
if in_score_table and prev_line is not None:
|
| 244 |
+
if not prev_line.startswith(_DIV_INC_THRESHOLD):
|
| 245 |
+
self._parse_scores_table_row(prev_line, qid, hit_dict)
|
| 246 |
+
|
| 247 |
+
# we've reached the end of the query block hits
|
| 248 |
+
# creating the Hit objects for this query
|
| 249 |
+
if hit_end:
|
| 250 |
+
return self._hit_to_list(hit_dict)
|
| 251 |
+
|
| 252 |
+
def _parse_hit_from_alignment(self, qid, hit_dict):
|
| 253 |
+
"""Parse an Infernal hit alignment (PRIVATE)."""
|
| 254 |
+
hid, hdesc = self.line[len(_DIV_ALIGNMENT_START) :].split(" ", 1)
|
| 255 |
+
hdesc = hdesc.strip()
|
| 256 |
+
|
| 257 |
+
# read through the hit table header and move one more line
|
| 258 |
+
self._read_until(lambda line: line.startswith(_DIV_TABLE_START))
|
| 259 |
+
self.line = read_forward(self.handle)
|
| 260 |
+
|
| 261 |
+
# parse the hit table
|
| 262 |
+
row = [x for x in self.line.strip().split() if x]
|
| 263 |
+
assert len(row) == 16
|
| 264 |
+
|
| 265 |
+
# create hit and append to hit container
|
| 266 |
+
hit_attrs = {"id": hid, "query_id": qid, "description": hdesc}
|
| 267 |
+
hsp_attrs = {
|
| 268 |
+
"evalue": float(row[2]),
|
| 269 |
+
"bitscore": float(row[3]),
|
| 270 |
+
"bias": float(row[4]),
|
| 271 |
+
"model": row[5],
|
| 272 |
+
"truncated": row[14],
|
| 273 |
+
"gc": float(row[15]),
|
| 274 |
+
"avg_acc": float(row[13]),
|
| 275 |
+
"query_endtype": row[8],
|
| 276 |
+
"hit_endtype": row[12],
|
| 277 |
+
"is_included": True if row[1] == "!" else False,
|
| 278 |
+
}
|
| 279 |
+
query_start = int(row[6])
|
| 280 |
+
query_end = int(row[7])
|
| 281 |
+
hit_start = int(row[9]) if row[11] == "+" else int(row[10])
|
| 282 |
+
hit_end = int(row[10]) if row[11] == "+" else int(row[9])
|
| 283 |
+
hit_strand = 0 if row[11] == "+" else -1
|
| 284 |
+
|
| 285 |
+
# move to the HSP alignment block
|
| 286 |
+
self.line = read_forward(self.handle)
|
| 287 |
+
|
| 288 |
+
# create the hsp
|
| 289 |
+
frag_list = self._parse_aln_block(
|
| 290 |
+
hit_attrs["id"],
|
| 291 |
+
hit_attrs["query_id"],
|
| 292 |
+
hsp_attrs["model"],
|
| 293 |
+
query_start,
|
| 294 |
+
query_end,
|
| 295 |
+
hit_start,
|
| 296 |
+
hit_end,
|
| 297 |
+
hit_strand,
|
| 298 |
+
)
|
| 299 |
+
hsp = HSP(frag_list)
|
| 300 |
+
for attr, value in hsp_attrs.items():
|
| 301 |
+
setattr(hsp, attr, value)
|
| 302 |
+
|
| 303 |
+
# add the hit to the container
|
| 304 |
+
self._add_hit_to_dict(hit_attrs, hsp, hit_dict)
|
| 305 |
+
|
| 306 |
+
def _parse_scores_table_row(self, row, qid, hit_dict):
|
| 307 |
+
"""Parse an Infernal hit scores table (when used with --noali) (PRIVATE)."""
|
| 308 |
+
|
| 309 |
+
# parse the columns into a list
|
| 310 |
+
row = [x for x in row.strip().split(" ") if x]
|
| 311 |
+
# join the description words if it's >1 word
|
| 312 |
+
if len(row) > 12:
|
| 313 |
+
row[12] = " ".join(row[12:])
|
| 314 |
+
# if there's no description, set it to an empty string
|
| 315 |
+
elif len(row) < 12:
|
| 316 |
+
row.append("")
|
| 317 |
+
assert len(row) == 12
|
| 318 |
+
|
| 319 |
+
# parse the attributes
|
| 320 |
+
hit_attrs = {"id": row[5], "query_id": qid, "description": row[12]}
|
| 321 |
+
hsp_attrs = {
|
| 322 |
+
"evalue": float(row[2]),
|
| 323 |
+
"bitscore": float(row[3]),
|
| 324 |
+
"bias": float(row[4]),
|
| 325 |
+
"model": row[9],
|
| 326 |
+
"truncated": row[10],
|
| 327 |
+
"gc": float(row[11]),
|
| 328 |
+
"is_included": True if row[1] == "!" else False,
|
| 329 |
+
}
|
| 330 |
+
hsp_frag_attrs = {
|
| 331 |
+
"hit_start": int(row[6]) if row[8] == "+" else int(row[7]),
|
| 332 |
+
"hit_end": int(row[7]) if row[8] == "+" else int(row[6]),
|
| 333 |
+
"hit_strand": 0 if row[8] == "+" else -1,
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
# create the hsp fragment and set it's attributes
|
| 337 |
+
hsp_frag = HSPFragment(row[5], qid)
|
| 338 |
+
for attr, value in hsp_frag_attrs.items():
|
| 339 |
+
setattr(hsp_frag, attr, value)
|
| 340 |
+
|
| 341 |
+
# create the hsp and set it's attributes
|
| 342 |
+
hsp = HSP([hsp_frag])
|
| 343 |
+
for attr, value in hsp_attrs.items():
|
| 344 |
+
setattr(hsp, attr, value)
|
| 345 |
+
|
| 346 |
+
# add the hit to the container
|
| 347 |
+
self._add_hit_to_dict(hit_attrs, hsp, hit_dict)
|
| 348 |
+
|
| 349 |
+
def _parse_aln_block(
|
| 350 |
+
self, hid, qid, model, query_start, query_end, hit_start, hit_end, hit_strand
|
| 351 |
+
):
|
| 352 |
+
"""Parse a Infernal HSP alignment block (PRIVATE)."""
|
| 353 |
+
frag_list = []
|
| 354 |
+
model_seq = ""
|
| 355 |
+
hit_seq = ""
|
| 356 |
+
if model == "cm":
|
| 357 |
+
annot = {"NC": "", "CS": "", "similarity": "", "PP": ""}
|
| 358 |
+
else:
|
| 359 |
+
annot = {"CS": "", "similarity": "", "PP": ""}
|
| 360 |
+
while True:
|
| 361 |
+
# we've reached the end of the alignment section
|
| 362 |
+
if (
|
| 363 |
+
self.line.startswith(_DIV_ALIGNMENT_START)
|
| 364 |
+
or self.line.startswith(_DIV_HITS_END_CM)
|
| 365 |
+
or self.line.startswith(_DIV_HITS_END_HMM)
|
| 366 |
+
):
|
| 367 |
+
# Process local end in infernal hit alignment. Local end are
|
| 368 |
+
# large insertion or deletion indicated by *[NN]* where N is
|
| 369 |
+
# the number of model positions are deleted or the number of
|
| 370 |
+
# residues are inserted in the sequence. We split the
|
| 371 |
+
# alignment block in HSPs on these local ends.
|
| 372 |
+
|
| 373 |
+
# get local ends string (*[NN]*) indexes in the model sequence
|
| 374 |
+
# there can be more than one local ends back-to-back
|
| 375 |
+
local_aln_idx = [
|
| 376 |
+
(0, 0)
|
| 377 |
+
] # there is always at least one local alignment starting at 0
|
| 378 |
+
local_aln_idx += [
|
| 379 |
+
(m.start(0), m.end(0))
|
| 380 |
+
for m in re.finditer(_RE_SPLIT_ALN, model_seq)
|
| 381 |
+
]
|
| 382 |
+
|
| 383 |
+
prev_hit_start = hit_start if hit_strand == 0 else hit_end
|
| 384 |
+
prev_model_start = query_start
|
| 385 |
+
hsps = []
|
| 386 |
+
|
| 387 |
+
for i in range(len(local_aln_idx)):
|
| 388 |
+
local_start = local_aln_idx[i][1]
|
| 389 |
+
local_end = (
|
| 390 |
+
local_aln_idx[i + 1][0] if i + 1 < len(local_aln_idx) else None
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# hsp hit position. forward strand moves up, reverse strand moves down
|
| 394 |
+
op = operator.add if hit_strand == 0 else operator.sub
|
| 395 |
+
cur_hit_seq = hit_seq[local_start:local_end]
|
| 396 |
+
cur_hit_gap_size = self._local_aln_gap_size(
|
| 397 |
+
local_aln_idx[i], hit_seq
|
| 398 |
+
)
|
| 399 |
+
cur_hit_start = op(prev_hit_start, cur_hit_gap_size)
|
| 400 |
+
cur_hit_end = op(
|
| 401 |
+
cur_hit_start, len(re.sub(_RE_LETTERS, "", cur_hit_seq))
|
| 402 |
+
)
|
| 403 |
+
# adjust start and end elements positon
|
| 404 |
+
if hit_strand == 0 and i == 0:
|
| 405 |
+
cur_hit_end -= 1
|
| 406 |
+
if hit_strand == -1 and i == 0:
|
| 407 |
+
cur_hit_end += 1
|
| 408 |
+
prev_hit_start = cur_hit_end
|
| 409 |
+
# hsp model position
|
| 410 |
+
cur_model_seq = model_seq[local_start:local_end].replace(".", "-")
|
| 411 |
+
cur_model_gap_size = self._local_aln_gap_size(
|
| 412 |
+
local_aln_idx[i], model_seq
|
| 413 |
+
)
|
| 414 |
+
cur_model_start = prev_model_start + cur_model_gap_size
|
| 415 |
+
cur_model_end = cur_model_start + len(
|
| 416 |
+
re.sub(_RE_LETTERS, "", cur_model_seq)
|
| 417 |
+
)
|
| 418 |
+
if i == 0:
|
| 419 |
+
cur_model_end -= 1
|
| 420 |
+
prev_model_start = cur_model_end
|
| 421 |
+
# annotations
|
| 422 |
+
cur_annot = {k: v[local_start:local_end] for k, v in annot.items()}
|
| 423 |
+
|
| 424 |
+
# create the hsp fragment and add to container
|
| 425 |
+
frag = HSPFragment(hid, qid)
|
| 426 |
+
frag.query = cur_model_seq
|
| 427 |
+
frag.hit = cur_hit_seq
|
| 428 |
+
frag.query_start = cur_model_start
|
| 429 |
+
frag.query_end = cur_model_end
|
| 430 |
+
frag.hit_start = cur_hit_start if hit_strand == 0 else cur_hit_end
|
| 431 |
+
frag.hit_end = cur_hit_end if hit_strand == 0 else cur_hit_start
|
| 432 |
+
frag.hit_strand = hit_strand
|
| 433 |
+
frag.aln_annotation = cur_annot
|
| 434 |
+
|
| 435 |
+
frag_list.append(frag)
|
| 436 |
+
|
| 437 |
+
return frag_list
|
| 438 |
+
|
| 439 |
+
# parse the alignment blocks in the hsp
|
| 440 |
+
# each block have 4 (hmmonly) or 5 (cm) lines followed by an empty line
|
| 441 |
+
block_size = 6 if model == "cm" else 5
|
| 442 |
+
offset = 1 if model == "cm" else 0 # offset for the annotation line indexes
|
| 443 |
+
lines = [None] * block_size
|
| 444 |
+
for i in range(block_size):
|
| 445 |
+
lines[i] = self.line
|
| 446 |
+
self.line = read_forward(self.handle)
|
| 447 |
+
|
| 448 |
+
# get the position of the alignment in the string using the PP line
|
| 449 |
+
blklen = len(lines[4 + offset].strip().split()[0])
|
| 450 |
+
blkstart = len(lines[4 + offset]) - blklen - 4
|
| 451 |
+
blkend = len(lines[4 + offset]) - 4
|
| 452 |
+
model_seq += lines[1 + offset][blkstart:blkend]
|
| 453 |
+
hit_seq += lines[3 + offset][blkstart:blkend]
|
| 454 |
+
# NC line is specific to cm model searches
|
| 455 |
+
if model == "cm":
|
| 456 |
+
annot["NC"] += lines[0][blkstart:blkend]
|
| 457 |
+
annot["CS"] += lines[0 + offset][blkstart:blkend]
|
| 458 |
+
annot["similarity"] += lines[2 + offset][blkstart:blkend]
|
| 459 |
+
annot["PP"] += lines[4 + offset][blkstart:blkend]
|
| 460 |
+
|
| 461 |
+
def _local_aln_gap_size(self, cur_aln_idx, seq):
|
| 462 |
+
"""Calculate the gap size between the local alignments (PRIVATE)."""
|
| 463 |
+
gap_len = 0
|
| 464 |
+
if cur_aln_idx[1] > 0:
|
| 465 |
+
gap_len = sum(
|
| 466 |
+
[
|
| 467 |
+
int(n)
|
| 468 |
+
for n in re.findall(
|
| 469 |
+
_RE_NUMERIC, seq[cur_aln_idx[0] : cur_aln_idx[1]]
|
| 470 |
+
)
|
| 471 |
+
]
|
| 472 |
+
)
|
| 473 |
+
assert gap_len > 0
|
| 474 |
+
return gap_len
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class InfernalTextIndexer(SearchIndexer):
|
| 478 |
+
"""Indexer class for Infernal plain text output."""
|
| 479 |
+
|
| 480 |
+
_parser = InfernalTextParser
|
| 481 |
+
|
| 482 |
+
def __init__(self, *args, **kwargs):
|
| 483 |
+
"""Initialize the class."""
|
| 484 |
+
super().__init__(*args, **kwargs)
|
| 485 |
+
self._preamble = b""
|
| 486 |
+
|
| 487 |
+
def __iter__(self):
|
| 488 |
+
"""Iterate over InfernalTextIndexer; yields query results' key, offsets, 0."""
|
| 489 |
+
handle = self._handle
|
| 490 |
+
handle.seek(0)
|
| 491 |
+
start_offset = handle.tell()
|
| 492 |
+
|
| 493 |
+
while True:
|
| 494 |
+
line = read_forward(handle)
|
| 495 |
+
end_offset = handle.tell()
|
| 496 |
+
|
| 497 |
+
if line.startswith(_DIV_QUERY_START.encode()):
|
| 498 |
+
qresult_key = line.strip().split()[1]
|
| 499 |
+
# qresult start offset is the offset of this line
|
| 500 |
+
# (starts with the start mark)
|
| 501 |
+
start_offset = end_offset - len(line)
|
| 502 |
+
elif line.startswith(_DIV_QUERY_END.encode()):
|
| 503 |
+
yield qresult_key.decode(), start_offset, 0
|
| 504 |
+
start_offset = end_offset
|
| 505 |
+
elif not line:
|
| 506 |
+
break
|
| 507 |
+
|
| 508 |
+
def get_raw(self, offset):
|
| 509 |
+
"""Return the raw record from the file as a bytes string."""
|
| 510 |
+
handle = self._handle
|
| 511 |
+
qresult_raw = b""
|
| 512 |
+
|
| 513 |
+
# read header
|
| 514 |
+
if not self._preamble:
|
| 515 |
+
handle.seek(0)
|
| 516 |
+
while True:
|
| 517 |
+
line = handle.readline()
|
| 518 |
+
if line.startswith(_DIV_QUERY_START.encode()):
|
| 519 |
+
break
|
| 520 |
+
self._preamble += line
|
| 521 |
+
|
| 522 |
+
qresult_raw += self._preamble
|
| 523 |
+
|
| 524 |
+
# read the qresult raw string
|
| 525 |
+
handle.seek(offset)
|
| 526 |
+
while True:
|
| 527 |
+
# preserve whitespace, don't use read_forward
|
| 528 |
+
line = handle.readline()
|
| 529 |
+
qresult_raw += line
|
| 530 |
+
|
| 531 |
+
# break when we've reached qresult end
|
| 532 |
+
if line.startswith(_DIV_QUERY_END.encode()) or not line:
|
| 533 |
+
break
|
| 534 |
+
|
| 535 |
+
return qresult_raw
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
# if not used as a module, run the doctest
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
from Bio._utils import run_doctest
|
| 541 |
+
|
| 542 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/._interproscan_xml.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 by Adhemar Zerlotini. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of the Biopython distribution and governed by your
|
| 4 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 5 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 6 |
+
# package.
|
| 7 |
+
"""Bio.SearchIO support for InterProScan output formats.
|
| 8 |
+
|
| 9 |
+
This module adds support for parsing InterProScan XML output.
|
| 10 |
+
The InterProScan is available as a command line program or on
|
| 11 |
+
EMBL-EBI's web page.
|
| 12 |
+
Bio.SearchIO.InterproscanIO was tested on the following version:
|
| 13 |
+
|
| 14 |
+
- versions: 5.26-65.0 (interproscan-model-2.1.xsd)
|
| 15 |
+
|
| 16 |
+
More information about InterProScan are available through these links:
|
| 17 |
+
- Publication: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3998142/
|
| 18 |
+
- Web interface: https://www.ebi.ac.uk/interpro/search/sequence-search
|
| 19 |
+
- Documentation: https://github.com/ebi-pf-team/interproscan/wiki
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
Supported format
|
| 23 |
+
================
|
| 24 |
+
|
| 25 |
+
Bio.SearchIO.InterproscanIO supports the following format:
|
| 26 |
+
|
| 27 |
+
- XML - 'interproscan-xml' - parsing
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
interproscan-xml
|
| 31 |
+
================
|
| 32 |
+
|
| 33 |
+
The interproscan-xml parser follows the InterProScan XML described here:
|
| 34 |
+
https://github.com/ebi-pf-team/interproscan/wiki/OutputFormats
|
| 35 |
+
|
| 36 |
+
+--------------+--------------------+------------------------------------------+
|
| 37 |
+
| Object | Attribute | XML Element |
|
| 38 |
+
+==============+====================+==========================================+
|
| 39 |
+
| QueryResult | target | ``InterPro`` |
|
| 40 |
+
| +--------------------+------------------------------------------+
|
| 41 |
+
| | program | ``InterProScan`` |
|
| 42 |
+
| +--------------------+------------------------------------------+
|
| 43 |
+
| | version | ``protein-matches.interproscan-version`` |
|
| 44 |
+
+--------------+--------------------+------------------------------------------+
|
| 45 |
+
| Hit | accession | ``signature.name`` |
|
| 46 |
+
| +--------------------+------------------------------------------+
|
| 47 |
+
| | id | ``signature.ac`` |
|
| 48 |
+
| +--------------------+------------------------------------------+
|
| 49 |
+
| | description | ``signature.desc`` |
|
| 50 |
+
| +--------------------+------------------------------------------+
|
| 51 |
+
| | dbxrefs | ``IPR:entry.ac`` |
|
| 52 |
+
| | | ``go-xref.id`` |
|
| 53 |
+
| | | ``pathway-xref.db:pathway-xref.id`` |
|
| 54 |
+
| +--------------------+------------------------------------------+
|
| 55 |
+
| | attributes | |
|
| 56 |
+
| | ['Target'] | ``*-match`` / ``*-location`` |
|
| 57 |
+
| | ['Target version'] | ``signature-library-release.library`` |
|
| 58 |
+
| | ['Hit type'] | ``signature-library-release.version`` |
|
| 59 |
+
+--------------+--------------------+------------------------------------------+
|
| 60 |
+
| HSP | bitscore | ``*-location.score`` |
|
| 61 |
+
| +--------------------+------------------------------------------+
|
| 62 |
+
| | evalue | ``*-location.evalue`` |
|
| 63 |
+
+--------------+--------------------+------------------------------------------+
|
| 64 |
+
| HSPFragment | query_start | ``*-location.start`` |
|
| 65 |
+
| (also via +--------------------+------------------------------------------+
|
| 66 |
+
| HSP) | query_end | ``*-location.end`` |
|
| 67 |
+
| +--------------------+------------------------------------------+
|
| 68 |
+
| | hit_start | ``*-location.hmm-start`` |
|
| 69 |
+
| +--------------------+------------------------------------------+
|
| 70 |
+
| | hit_end | ``*-location.hmm-end`` |
|
| 71 |
+
| +--------------------+------------------------------------------+
|
| 72 |
+
| | query | ``sequence`` |
|
| 73 |
+
+--------------+--------------------+------------------------------------------+
|
| 74 |
+
|
| 75 |
+
InterProScan XML files may contain a match with multiple locations or multiple
|
| 76 |
+
matches to the same protein with a single location. In both cases, the match
|
| 77 |
+
is uniquely stored as a HIT object and the locations as HSP objects.
|
| 78 |
+
|
| 79 |
+
``HSP.*start == *start - 1`` (Since every start position is 0-based in Biopython)
|
| 80 |
+
|
| 81 |
+
``HSP.aln_span == query-end - query-start``
|
| 82 |
+
|
| 83 |
+
The types of matches or locations (eg. hmmer3-match, hmmer3-location,
|
| 84 |
+
coils-match, panther-location) are stored in hit.attributes['Hit type'].
|
| 85 |
+
For instance, for every 'phobious-match', there will be a 'phobious-location'.
|
| 86 |
+
Therefore, Hit.type will store the string excluding '-match' or '-location'
|
| 87 |
+
('phobious', in this example).
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
from .interproscan_xml import InterproscanXmlParser
|
| 91 |
+
|
| 92 |
+
# if not used as a module, run the doctest
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
from Bio._utils import run_doctest
|
| 95 |
+
|
| 96 |
+
run_doctest()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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 by Adhemar Zerlotini. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of the Biopython distribution and governed by your
|
| 4 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 5 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 6 |
+
# package.
|
| 7 |
+
|
| 8 |
+
"""Bio.SearchIO parser for InterProScan XML output formats."""
|
| 9 |
+
# for more info: https://github.com/ebi-pf-team/interproscan/wiki/OutputFormats
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
from xml.etree import ElementTree
|
| 13 |
+
|
| 14 |
+
from Bio.SearchIO._model import Hit
|
| 15 |
+
from Bio.SearchIO._model import HSP
|
| 16 |
+
from Bio.SearchIO._model import HSPFragment
|
| 17 |
+
from Bio.SearchIO._model import QueryResult
|
| 18 |
+
|
| 19 |
+
# element - hit attribute name mapping
|
| 20 |
+
_ELEM_HIT = {
|
| 21 |
+
"name": ("accession", str),
|
| 22 |
+
"ac": ("id", str),
|
| 23 |
+
"desc": ("description", str),
|
| 24 |
+
}
|
| 25 |
+
# element - hsp attribute name mapping
|
| 26 |
+
_ELEM_HSP = {"score": ("bitscore", float), "evalue": ("evalue", float)}
|
| 27 |
+
# element - fragment attribute name mapping
|
| 28 |
+
_ELEM_FRAG = {
|
| 29 |
+
"start": ("query_start", int),
|
| 30 |
+
"end": ("query_end", int),
|
| 31 |
+
"hmm-start": ("hit_start", int),
|
| 32 |
+
"hmm-end": ("hit_end", int),
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class InterproscanXmlParser:
|
| 37 |
+
"""Parser for the InterProScan XML format."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, handle):
|
| 40 |
+
"""Initialize the class."""
|
| 41 |
+
self.xml_iter = iter(ElementTree.iterparse(handle, events=("start", "end")))
|
| 42 |
+
self._meta = self._parse_header()
|
| 43 |
+
|
| 44 |
+
def __iter__(self):
|
| 45 |
+
"""Iterate qresults."""
|
| 46 |
+
yield from self._parse_qresult()
|
| 47 |
+
|
| 48 |
+
def _parse_header(self):
|
| 49 |
+
"""Parse the header for the InterProScan version (PRIVATE)."""
|
| 50 |
+
event, elem = next(self.xml_iter)
|
| 51 |
+
meta = {}
|
| 52 |
+
meta["target"] = "InterPro"
|
| 53 |
+
meta["program"] = "InterProScan"
|
| 54 |
+
meta["version"] = elem.attrib["interproscan-version"]
|
| 55 |
+
# store the namespace value
|
| 56 |
+
self.NS = re.sub("protein-matches", "", elem.tag)
|
| 57 |
+
return meta
|
| 58 |
+
|
| 59 |
+
def _parse_qresult(self):
|
| 60 |
+
"""Parse query results (PRIVATE)."""
|
| 61 |
+
for event, elem in self.xml_iter:
|
| 62 |
+
if event == "end" and elem.tag == self.NS + "protein":
|
| 63 |
+
# store the query sequence
|
| 64 |
+
seq = elem.find(self.NS + "sequence")
|
| 65 |
+
query_seq = seq.text
|
| 66 |
+
|
| 67 |
+
# store the query id and description
|
| 68 |
+
xref = elem.find(self.NS + "xref")
|
| 69 |
+
query_id = xref.attrib["id"]
|
| 70 |
+
query_desc = xref.attrib["name"]
|
| 71 |
+
|
| 72 |
+
# parse each hit
|
| 73 |
+
hit_list = []
|
| 74 |
+
for hit_new in self._parse_hit(
|
| 75 |
+
elem.find(self.NS + "matches"), query_id, query_seq
|
| 76 |
+
):
|
| 77 |
+
# interproscan results contain duplicate hits rather than
|
| 78 |
+
# a single hit with multiple hsps. In this case the hsps
|
| 79 |
+
# of a duplicate hit will be appended to the already
|
| 80 |
+
# existing hit
|
| 81 |
+
for hit in hit_list:
|
| 82 |
+
if hit.id == hit_new.id:
|
| 83 |
+
for hsp in hit_new.hsps:
|
| 84 |
+
hit.hsps.append(hsp)
|
| 85 |
+
break
|
| 86 |
+
else:
|
| 87 |
+
hit_list.append(hit_new)
|
| 88 |
+
|
| 89 |
+
# create qresult and assign attributes
|
| 90 |
+
qresult = QueryResult(hit_list, query_id)
|
| 91 |
+
setattr(qresult, "description", query_desc)
|
| 92 |
+
for key, value in self._meta.items():
|
| 93 |
+
setattr(qresult, key, value)
|
| 94 |
+
yield qresult
|
| 95 |
+
|
| 96 |
+
def _parse_hit(self, root_hit_elem, query_id, query_seq=None):
|
| 97 |
+
"""Parse hit (PRIVATE)."""
|
| 98 |
+
# feed the loop below an empty list so iteration still works
|
| 99 |
+
if root_hit_elem is None:
|
| 100 |
+
root_hit_elem = []
|
| 101 |
+
|
| 102 |
+
for hit_elem in root_hit_elem:
|
| 103 |
+
# store the match/location type
|
| 104 |
+
hit_type = re.sub(r"%s(\w+)-match" % self.NS, r"\1", hit_elem.find(".").tag)
|
| 105 |
+
# store the hit id
|
| 106 |
+
signature = hit_elem.find(self.NS + "signature")
|
| 107 |
+
hit_id = signature.attrib["ac"]
|
| 108 |
+
|
| 109 |
+
# store xrefs and alt_descs
|
| 110 |
+
xrefs = self._parse_xrefs(signature.find(self.NS + "entry"))
|
| 111 |
+
|
| 112 |
+
# parse each hsp
|
| 113 |
+
hsps = list(
|
| 114 |
+
self._parse_hsp(
|
| 115 |
+
hit_elem.find(self.NS + "locations"), query_id, hit_id, query_seq
|
| 116 |
+
)
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# create hit and assign attributes
|
| 120 |
+
hit = Hit(hsps, hit_id)
|
| 121 |
+
setattr(hit, "dbxrefs", xrefs)
|
| 122 |
+
for key, (attr, caster) in _ELEM_HIT.items():
|
| 123 |
+
value = signature.attrib.get(key)
|
| 124 |
+
if value is not None:
|
| 125 |
+
setattr(hit, attr, caster(value))
|
| 126 |
+
# format specific attributes
|
| 127 |
+
hit.attributes["Hit type"] = hit_type
|
| 128 |
+
signature_lib = signature.find(self.NS + "signature-library-release")
|
| 129 |
+
hit.attributes["Target"] = str(signature_lib.attrib.get("library"))
|
| 130 |
+
hit.attributes["Target version"] = str(signature_lib.attrib.get("version"))
|
| 131 |
+
|
| 132 |
+
yield hit
|
| 133 |
+
|
| 134 |
+
def _parse_hsp(self, root_hsp_elem, query_id, hit_id, query_seq=None):
|
| 135 |
+
"""Parse hsp (PRIVATE)."""
|
| 136 |
+
# feed the loop below an empty list so iteration still works
|
| 137 |
+
if root_hsp_elem is None:
|
| 138 |
+
root_hsp_elem = []
|
| 139 |
+
|
| 140 |
+
for hsp_elem in root_hsp_elem:
|
| 141 |
+
# create frag and assign attributes
|
| 142 |
+
frag = HSPFragment(hit_id, query_id)
|
| 143 |
+
setattr(frag, "molecule_type", "protein")
|
| 144 |
+
if query_seq is not None:
|
| 145 |
+
setattr(frag, "query", query_seq)
|
| 146 |
+
for key, (attr, caster) in _ELEM_FRAG.items():
|
| 147 |
+
value = hsp_elem.attrib.get(key)
|
| 148 |
+
if value is not None:
|
| 149 |
+
# start should be 0-based
|
| 150 |
+
if attr.endswith("start"):
|
| 151 |
+
value = caster(value) - 1
|
| 152 |
+
# store query start and end to calculate aln_span
|
| 153 |
+
if attr == "query_start":
|
| 154 |
+
start = int(value)
|
| 155 |
+
if attr == "query_end":
|
| 156 |
+
end = int(value)
|
| 157 |
+
setattr(frag, attr, caster(value))
|
| 158 |
+
# calculate aln_span and store
|
| 159 |
+
setattr(frag, "aln_span", end - start)
|
| 160 |
+
|
| 161 |
+
# create hsp and assign attributes
|
| 162 |
+
hsp = HSP([frag])
|
| 163 |
+
setattr(hsp, "query_id", query_id)
|
| 164 |
+
setattr(hsp, "hit_id", hit_id)
|
| 165 |
+
for key, (attr, caster) in _ELEM_HSP.items():
|
| 166 |
+
value = hsp_elem.attrib.get(key)
|
| 167 |
+
if value is not None:
|
| 168 |
+
setattr(hsp, attr, caster(value))
|
| 169 |
+
yield hsp
|
| 170 |
+
|
| 171 |
+
def _parse_xrefs(self, root_entry_elem):
|
| 172 |
+
"""Parse xrefs (PRIVATE)."""
|
| 173 |
+
xrefs = []
|
| 174 |
+
# store entry id and description
|
| 175 |
+
if root_entry_elem is not None:
|
| 176 |
+
xrefs.append("IPR:" + root_entry_elem.attrib["ac"])
|
| 177 |
+
|
| 178 |
+
# store go-xrefs and pathway-refs id and description
|
| 179 |
+
if root_entry_elem is not None:
|
| 180 |
+
xref_elems = []
|
| 181 |
+
xref_elems = xref_elems + root_entry_elem.findall(self.NS + "go-xref")
|
| 182 |
+
xref_elems = xref_elems + root_entry_elem.findall(self.NS + "pathway-xref")
|
| 183 |
+
|
| 184 |
+
for entry in xref_elems:
|
| 185 |
+
xref = entry.attrib["id"]
|
| 186 |
+
if ":" not in xref:
|
| 187 |
+
xref = entry.attrib["db"] + ":" + xref
|
| 188 |
+
xrefs.append(xref)
|
| 189 |
+
return xrefs
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# if not used as a module, run the doctest
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
from Bio._utils import run_doctest
|
| 195 |
+
|
| 196 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/__init__.py
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
|
| 7 |
+
"""Biopython interface for sequence search program outputs.
|
| 8 |
+
|
| 9 |
+
The SearchIO submodule provides parsers, indexers, and writers for outputs from
|
| 10 |
+
various sequence search programs. It provides an API similar to SeqIO and
|
| 11 |
+
AlignIO, with the following main functions: ``parse``, ``read``, ``to_dict``,
|
| 12 |
+
``index``, ``index_db``, ``write``, and ``convert``.
|
| 13 |
+
|
| 14 |
+
SearchIO parses a search output file's contents into a hierarchy of four nested
|
| 15 |
+
objects: QueryResult, Hit, HSP, and HSPFragment. Each of them models a part of
|
| 16 |
+
the search output file:
|
| 17 |
+
|
| 18 |
+
- QueryResult represents a search query. This is the main object returned
|
| 19 |
+
by the input functions and it contains all other objects.
|
| 20 |
+
- Hit represents a database hit,
|
| 21 |
+
- HSP represents high-scoring alignment region(s) in the hit,
|
| 22 |
+
- HSPFragment represents a contiguous alignment within the HSP
|
| 23 |
+
|
| 24 |
+
In addition to the four objects above, SearchIO is also tightly integrated with
|
| 25 |
+
the SeqRecord objects (see SeqIO) and MultipleSeqAlignment objects (see
|
| 26 |
+
AlignIO). SeqRecord objects are used to store the actual matching hit and query
|
| 27 |
+
sequences, while MultipleSeqAlignment objects store the alignment between them.
|
| 28 |
+
|
| 29 |
+
A detailed description of these objects' features and their example usages are
|
| 30 |
+
available in their respective documentations.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
Input
|
| 34 |
+
=====
|
| 35 |
+
The main function for parsing search output files is Bio.SearchIO.parse(...).
|
| 36 |
+
This function parses a given search output file and returns a generator object
|
| 37 |
+
that yields one QueryResult object per iteration.
|
| 38 |
+
|
| 39 |
+
``parse`` takes two arguments: 1) a file handle or a filename of the input file
|
| 40 |
+
(the search output file) and 2) the format name.
|
| 41 |
+
|
| 42 |
+
>>> from Bio import SearchIO
|
| 43 |
+
>>> for qresult in SearchIO.parse('Blast/mirna.xml', 'blast-xml'):
|
| 44 |
+
... print("%s %s" % (qresult.id, qresult.description))
|
| 45 |
+
...
|
| 46 |
+
33211 mir_1
|
| 47 |
+
33212 mir_2
|
| 48 |
+
33213 mir_3
|
| 49 |
+
|
| 50 |
+
SearchIO also provides the Bio.SearchIO.read(...) function, which is intended
|
| 51 |
+
for use on search output files containing only one query. ``read`` returns one
|
| 52 |
+
QueryResult object and will raise an exception if the source file contains more
|
| 53 |
+
than one query:
|
| 54 |
+
|
| 55 |
+
>>> qresult = SearchIO.read('Blast/xml_2226_blastp_004.xml', 'blast-xml')
|
| 56 |
+
>>> print("%s %s" % (qresult.id, qresult.description))
|
| 57 |
+
...
|
| 58 |
+
gi|11464971:4-101 pleckstrin [Mus musculus]
|
| 59 |
+
|
| 60 |
+
>>> SearchIO.read('Blast/mirna.xml', 'blast-xml')
|
| 61 |
+
Traceback (most recent call last):
|
| 62 |
+
...
|
| 63 |
+
ValueError: ...
|
| 64 |
+
|
| 65 |
+
For accessing search results of large output files, you may use the indexing
|
| 66 |
+
functions Bio.SearchIO.index(...) or Bio.SearchIO.index_db(...). They have a
|
| 67 |
+
similar interface to their counterparts in SeqIO and AlignIO, with the addition
|
| 68 |
+
of optional, format-specific keyword arguments.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
Output
|
| 72 |
+
======
|
| 73 |
+
SearchIO has write support for several formats, accessible from the
|
| 74 |
+
Bio.SearchIO.write(...) function. This function returns a tuple of four
|
| 75 |
+
numbers: the number of QueryResult, Hit, HSP, and HSPFragment written::
|
| 76 |
+
|
| 77 |
+
qresults = SearchIO.parse('Blast/mirna.xml', 'blast-xml')
|
| 78 |
+
SearchIO.write(qresults, 'results.tab', 'blast-tab')
|
| 79 |
+
<stdout> (3, 239, 277, 277)
|
| 80 |
+
|
| 81 |
+
Note that different writers may require different attribute values of the
|
| 82 |
+
SearchIO objects. This limits the scope of writable search results to search
|
| 83 |
+
results possessing the required attributes.
|
| 84 |
+
|
| 85 |
+
For example, the writer for HMMER domain table output requires
|
| 86 |
+
the conditional e-value attribute from each HSP object, among others. If you
|
| 87 |
+
try to write to the HMMER domain table format and your HSPs do not have this
|
| 88 |
+
attribute, an exception will be raised.
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
Conversion
|
| 92 |
+
==========
|
| 93 |
+
SearchIO provides a shortcut function Bio.SearchIO.convert(...) to convert a
|
| 94 |
+
given file into another format. Under the hood, ``convert`` simply parses a given
|
| 95 |
+
output file and writes it to another using the ``parse`` and ``write`` functions.
|
| 96 |
+
|
| 97 |
+
Note that the same restrictions found in Bio.SearchIO.write(...) apply to the
|
| 98 |
+
convert function as well.
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
Conventions
|
| 102 |
+
===========
|
| 103 |
+
The main goal of creating SearchIO is to have a common, easy to use interface
|
| 104 |
+
across different search output files. As such, we have also created some
|
| 105 |
+
conventions / standards for SearchIO that extend beyond the common object model.
|
| 106 |
+
These conventions apply to all files parsed by SearchIO, regardless of their
|
| 107 |
+
individual formats.
|
| 108 |
+
|
| 109 |
+
Python-style sequence coordinates
|
| 110 |
+
---------------------------------
|
| 111 |
+
|
| 112 |
+
When storing sequence coordinates (start and end values), SearchIO uses
|
| 113 |
+
the Python-style slice convention: zero-based and half-open intervals. For
|
| 114 |
+
example, if in a BLAST XML output file the start and end coordinates of an
|
| 115 |
+
HSP are 10 and 28, they would become 9 and 28 in SearchIO. The start
|
| 116 |
+
coordinate becomes 9 because Python indices start from zero, while the end
|
| 117 |
+
coordinate remains 28 as Python slices omit the last item in an interval.
|
| 118 |
+
|
| 119 |
+
Beside giving you the benefits of standardization, this convention also
|
| 120 |
+
makes the coordinates usable for slicing sequences. For example, given a
|
| 121 |
+
full query sequence and the start and end coordinates of an HSP, one can
|
| 122 |
+
use the coordinates to extract part of the query sequence that results in
|
| 123 |
+
the database hit.
|
| 124 |
+
|
| 125 |
+
When these objects are written to an output file using
|
| 126 |
+
SearchIO.write(...), the coordinate values are restored to their
|
| 127 |
+
respective format's convention. Using the example above, if the HSP would
|
| 128 |
+
be written to an XML file, the start and end coordinates would become 10
|
| 129 |
+
and 28 again.
|
| 130 |
+
|
| 131 |
+
Sequence coordinate order
|
| 132 |
+
-------------------------
|
| 133 |
+
|
| 134 |
+
Some search output formats reverse the start and end coordinate sequences
|
| 135 |
+
according to the sequence's strand.
|
| 136 |
+
|
| 137 |
+
In SearchIO, start coordinates are always smaller than the end
|
| 138 |
+
coordinates, regardless of their originating strand. This ensures
|
| 139 |
+
consistency when using the coordinates to slice full sequences.
|
| 140 |
+
|
| 141 |
+
Note that this coordinate order convention is only enforced in the
|
| 142 |
+
HSPFragment level. If an HSP object has several HSPFragment objects, each
|
| 143 |
+
individual fragment will conform to this convention. But the order of the
|
| 144 |
+
fragments within the HSP object follows what the search output file uses.
|
| 145 |
+
|
| 146 |
+
Similar to the coordinate style convention, the start and end coordinates'
|
| 147 |
+
order are restored to their respective formats when the objects are
|
| 148 |
+
written using Bio.SearchIO.write(...).
|
| 149 |
+
|
| 150 |
+
Frames and strand values
|
| 151 |
+
------------------------
|
| 152 |
+
|
| 153 |
+
SearchIO only allows -1, 0, 1 and None as strand values. For frames, the
|
| 154 |
+
only allowed values are integers from -3 to 3 (inclusive) and None. Both
|
| 155 |
+
of these are standard Biopython conventions.
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
Supported Formats
|
| 159 |
+
=================
|
| 160 |
+
Below is a list of search program output formats supported by SearchIO.
|
| 161 |
+
|
| 162 |
+
Support for parsing, indexing, and writing:
|
| 163 |
+
|
| 164 |
+
- blast-tab - BLAST+ tabular output. Both variants without comments
|
| 165 |
+
(-m 6 flag) and with comments (-m 7 flag) are supported.
|
| 166 |
+
- blast-xml - BLAST+ XML output.
|
| 167 |
+
- blat-psl - The default output of BLAT (PSL format). Variants with or
|
| 168 |
+
without header are both supported. PSLX (PSL + sequences)
|
| 169 |
+
is also supported.
|
| 170 |
+
- hmmer3-tab - HMMER3 table output.
|
| 171 |
+
- hmmer3-domtab - HMMER3 domain table output. When using this format, the
|
| 172 |
+
program name has to be specified. For example, for parsing
|
| 173 |
+
hmmscan output, the name would be 'hmmscan-domtab'.
|
| 174 |
+
|
| 175 |
+
Support for parsing and indexing:
|
| 176 |
+
|
| 177 |
+
- exonerate-text - Exonerate plain text output.
|
| 178 |
+
- exonerate-vulgar - Exonerate vulgar line.
|
| 179 |
+
- exonerate-cigar - Exonerate cigar line.
|
| 180 |
+
- fasta-m10 - Bill Pearson's FASTA -m 10 output.
|
| 181 |
+
- hmmer3-text - HMMER3 regular text output format. Supported HMMER3
|
| 182 |
+
subprograms are hmmscan, hmmsearch, and phmmer.
|
| 183 |
+
- hmmer2-text - HMMER2 regular text output format. Supported HMMER2
|
| 184 |
+
subprograms are hmmpfam, hmmsearch.
|
| 185 |
+
- infernal-tab - Infernal tabular output.
|
| 186 |
+
- infernal-text - Infernal regular text output. Supported Infernal
|
| 187 |
+
subprograms are cmsearch and cmscan.
|
| 188 |
+
|
| 189 |
+
Support for parsing:
|
| 190 |
+
|
| 191 |
+
- hhsuite2-text - HHSUITE plain text output.
|
| 192 |
+
|
| 193 |
+
Each of these formats have different keyword arguments available for use with
|
| 194 |
+
the main SearchIO functions. More details and examples are available in each
|
| 195 |
+
of the format's documentation.
|
| 196 |
+
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
from Bio.File import as_handle
|
| 200 |
+
from Bio.SearchIO._model import Hit
|
| 201 |
+
from Bio.SearchIO._model import HSP
|
| 202 |
+
from Bio.SearchIO._model import HSPFragment
|
| 203 |
+
from Bio.SearchIO._model import QueryResult
|
| 204 |
+
from Bio.SearchIO._utils import get_processor
|
| 205 |
+
|
| 206 |
+
__all__ = ("read", "parse", "to_dict", "index", "index_db", "write", "convert")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# dictionary of supported formats for parse() and read()
|
| 210 |
+
_ITERATOR_MAP = {
|
| 211 |
+
"blast-tab": ("BlastIO", "BlastTabParser"),
|
| 212 |
+
"blast-xml": ("BlastIO", "BlastXmlParser"),
|
| 213 |
+
"blat-psl": ("BlatIO", "BlatPslParser"),
|
| 214 |
+
"exonerate-cigar": ("ExonerateIO", "ExonerateCigarParser"),
|
| 215 |
+
"exonerate-text": ("ExonerateIO", "ExonerateTextParser"),
|
| 216 |
+
"exonerate-vulgar": ("ExonerateIO", "ExonerateVulgarParser"),
|
| 217 |
+
"fasta-m10": ("FastaIO", "FastaM10Parser"),
|
| 218 |
+
"hhsuite2-text": ("HHsuiteIO", "Hhsuite2TextParser"),
|
| 219 |
+
"hhsuite3-text": ("HHsuiteIO", "Hhsuite2TextParser"),
|
| 220 |
+
"hmmer2-text": ("HmmerIO", "Hmmer2TextParser"),
|
| 221 |
+
"hmmer3-text": ("HmmerIO", "Hmmer3TextParser"),
|
| 222 |
+
"hmmer3-tab": ("HmmerIO", "Hmmer3TabParser"),
|
| 223 |
+
# for hmmer3-domtab, the specific program is part of the format name
|
| 224 |
+
# as we need it distinguish hit / target coordinates
|
| 225 |
+
"hmmscan3-domtab": ("HmmerIO", "Hmmer3DomtabHmmhitParser"),
|
| 226 |
+
"hmmsearch3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryParser"),
|
| 227 |
+
"infernal-tab": ("InfernalIO", "InfernalTabParser"),
|
| 228 |
+
"infernal-text": ("InfernalIO", "InfernalTextParser"),
|
| 229 |
+
"interproscan-xml": ("InterproscanIO", "InterproscanXmlParser"),
|
| 230 |
+
"phmmer3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryParser"),
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
# dictionary of supported formats for index()
|
| 234 |
+
_INDEXER_MAP = {
|
| 235 |
+
"blast-tab": ("BlastIO", "BlastTabIndexer"),
|
| 236 |
+
"blast-xml": ("BlastIO", "BlastXmlIndexer"),
|
| 237 |
+
"blat-psl": ("BlatIO", "BlatPslIndexer"),
|
| 238 |
+
"exonerate-cigar": ("ExonerateIO", "ExonerateCigarIndexer"),
|
| 239 |
+
"exonerate-text": ("ExonerateIO", "ExonerateTextIndexer"),
|
| 240 |
+
"exonerate-vulgar": ("ExonerateIO", "ExonerateVulgarIndexer"),
|
| 241 |
+
"fasta-m10": ("FastaIO", "FastaM10Indexer"),
|
| 242 |
+
"hmmer2-text": ("HmmerIO", "Hmmer2TextIndexer"),
|
| 243 |
+
"hmmer3-text": ("HmmerIO", "Hmmer3TextIndexer"),
|
| 244 |
+
"hmmer3-tab": ("HmmerIO", "Hmmer3TabIndexer"),
|
| 245 |
+
"hmmscan3-domtab": ("HmmerIO", "Hmmer3DomtabHmmhitIndexer"),
|
| 246 |
+
"hmmsearch3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryIndexer"),
|
| 247 |
+
"infernal-tab": ("InfernalIO", "InfernalTabIndexer"),
|
| 248 |
+
"infernal-text": ("InfernalIO", "InfernalTextIndexer"),
|
| 249 |
+
"phmmer3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryIndexer"),
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
# dictionary of supported formats for write()
|
| 253 |
+
_WRITER_MAP = {
|
| 254 |
+
"blast-tab": ("BlastIO", "BlastTabWriter"),
|
| 255 |
+
"blast-xml": ("BlastIO", "BlastXmlWriter"),
|
| 256 |
+
"blat-psl": ("BlatIO", "BlatPslWriter"),
|
| 257 |
+
"hmmer3-tab": ("HmmerIO", "Hmmer3TabWriter"),
|
| 258 |
+
"hmmscan3-domtab": ("HmmerIO", "Hmmer3DomtabHmmhitWriter"),
|
| 259 |
+
"hmmsearch3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryWriter"),
|
| 260 |
+
"phmmer3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryWriter"),
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def parse(handle, format=None, **kwargs):
|
| 265 |
+
"""Iterate over search tool output file as QueryResult objects.
|
| 266 |
+
|
| 267 |
+
Arguments:
|
| 268 |
+
- handle - Handle to the file, or the filename as a string.
|
| 269 |
+
- format - Lower case string denoting one of the supported formats.
|
| 270 |
+
- kwargs - Format-specific keyword arguments.
|
| 271 |
+
|
| 272 |
+
This function is used to iterate over each query in a given search output
|
| 273 |
+
file:
|
| 274 |
+
|
| 275 |
+
>>> from Bio import SearchIO
|
| 276 |
+
>>> qresults = SearchIO.parse('Blast/mirna.xml', 'blast-xml')
|
| 277 |
+
>>> qresults
|
| 278 |
+
<generator object ...>
|
| 279 |
+
>>> for qresult in qresults:
|
| 280 |
+
... print("Search %s has %i hits" % (qresult.id, len(qresult)))
|
| 281 |
+
...
|
| 282 |
+
Search 33211 has 100 hits
|
| 283 |
+
Search 33212 has 44 hits
|
| 284 |
+
Search 33213 has 95 hits
|
| 285 |
+
|
| 286 |
+
Depending on the file format, ``parse`` may also accept additional keyword
|
| 287 |
+
argument(s) that modifies the behavior of the format parser. Here is a
|
| 288 |
+
simple example, where the keyword argument enables parsing of a commented
|
| 289 |
+
BLAST tabular output file:
|
| 290 |
+
|
| 291 |
+
>>> from Bio import SearchIO
|
| 292 |
+
>>> for qresult in SearchIO.parse('Blast/mirna.tab', 'blast-tab', comments=True):
|
| 293 |
+
... print("Search %s has %i hits" % (qresult.id, len(qresult)))
|
| 294 |
+
...
|
| 295 |
+
Search 33211 has 100 hits
|
| 296 |
+
Search 33212 has 44 hits
|
| 297 |
+
Search 33213 has 95 hits
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
# get the iterator object and do error checking
|
| 301 |
+
iterator = get_processor(format, _ITERATOR_MAP)
|
| 302 |
+
|
| 303 |
+
# HACK: force BLAST XML decoding to use utf-8
|
| 304 |
+
handle_kwargs = {}
|
| 305 |
+
if format == "blast-xml":
|
| 306 |
+
handle_kwargs["encoding"] = "utf-8"
|
| 307 |
+
|
| 308 |
+
# and start iterating
|
| 309 |
+
with as_handle(handle, **handle_kwargs) as source_file:
|
| 310 |
+
generator = iterator(source_file, **kwargs)
|
| 311 |
+
yield from generator
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def read(handle, format=None, **kwargs):
|
| 315 |
+
"""Turn a search output file containing one query into a single QueryResult.
|
| 316 |
+
|
| 317 |
+
- handle - Handle to the file, or the filename as a string.
|
| 318 |
+
- format - Lower case string denoting one of the supported formats.
|
| 319 |
+
- kwargs - Format-specific keyword arguments.
|
| 320 |
+
|
| 321 |
+
``read`` is used for parsing search output files containing exactly one query:
|
| 322 |
+
|
| 323 |
+
>>> from Bio import SearchIO
|
| 324 |
+
>>> qresult = SearchIO.read('Blast/xml_2226_blastp_004.xml', 'blast-xml')
|
| 325 |
+
>>> print("%s %s" % (qresult.id, qresult.description))
|
| 326 |
+
...
|
| 327 |
+
gi|11464971:4-101 pleckstrin [Mus musculus]
|
| 328 |
+
|
| 329 |
+
If the given handle has no results, an exception will be raised:
|
| 330 |
+
|
| 331 |
+
>>> from Bio import SearchIO
|
| 332 |
+
>>> qresult = SearchIO.read('Blast/tab_2226_tblastn_002.txt', 'blast-tab')
|
| 333 |
+
Traceback (most recent call last):
|
| 334 |
+
...
|
| 335 |
+
ValueError: No query results found in handle
|
| 336 |
+
|
| 337 |
+
Similarly, if the given handle has more than one result, an exception will
|
| 338 |
+
be raised:
|
| 339 |
+
|
| 340 |
+
>>> from Bio import SearchIO
|
| 341 |
+
>>> qresult = SearchIO.read('Blast/tab_2226_tblastn_001.txt', 'blast-tab')
|
| 342 |
+
Traceback (most recent call last):
|
| 343 |
+
...
|
| 344 |
+
ValueError: More than one query result found in handle
|
| 345 |
+
|
| 346 |
+
Like ``parse``, ``read`` may also accept keyword argument(s) depending on the
|
| 347 |
+
search output file format.
|
| 348 |
+
|
| 349 |
+
"""
|
| 350 |
+
query_results = parse(handle, format, **kwargs)
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
query_result = next(query_results)
|
| 354 |
+
except StopIteration:
|
| 355 |
+
raise ValueError("No query results found in handle") from None
|
| 356 |
+
try:
|
| 357 |
+
next(query_results)
|
| 358 |
+
raise ValueError("More than one query result found in handle")
|
| 359 |
+
except StopIteration:
|
| 360 |
+
pass
|
| 361 |
+
|
| 362 |
+
return query_result
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def to_dict(qresults, key_function=None):
|
| 366 |
+
"""Turn a QueryResult iterator or list into a dictionary.
|
| 367 |
+
|
| 368 |
+
- qresults - Iterable returning QueryResult objects.
|
| 369 |
+
- key_function - Optional callback function which when given a
|
| 370 |
+
QueryResult object should return a unique key for the
|
| 371 |
+
dictionary. Defaults to using .id of the result.
|
| 372 |
+
|
| 373 |
+
This function enables access of QueryResult objects from a single search
|
| 374 |
+
output file using its identifier.
|
| 375 |
+
|
| 376 |
+
>>> from Bio import SearchIO
|
| 377 |
+
>>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml')
|
| 378 |
+
>>> search_dict = SearchIO.to_dict(qresults)
|
| 379 |
+
>>> list(search_dict)
|
| 380 |
+
['gi|195230749:301-1383', 'gi|325053704:108-1166', ..., 'gi|53729353:216-1313']
|
| 381 |
+
>>> search_dict['gi|156630997:105-1160']
|
| 382 |
+
QueryResult(id='gi|156630997:105-1160', 5 hits)
|
| 383 |
+
|
| 384 |
+
By default, the dictionary key is the QueryResult's string ID. This may be
|
| 385 |
+
changed by supplying a callback function that returns the desired identifier.
|
| 386 |
+
Here is an example using a function that removes the 'gi|' part in the
|
| 387 |
+
beginning of the QueryResult ID.
|
| 388 |
+
|
| 389 |
+
>>> from Bio import SearchIO
|
| 390 |
+
>>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml')
|
| 391 |
+
>>> key_func = lambda qresult: qresult.id.split('|')[1]
|
| 392 |
+
>>> search_dict = SearchIO.to_dict(qresults, key_func)
|
| 393 |
+
>>> list(search_dict)
|
| 394 |
+
['195230749:301-1383', '325053704:108-1166', ..., '53729353:216-1313']
|
| 395 |
+
>>> search_dict['156630997:105-1160']
|
| 396 |
+
QueryResult(id='gi|156630997:105-1160', 5 hits)
|
| 397 |
+
|
| 398 |
+
Note that the callback function does not change the QueryResult's ID value.
|
| 399 |
+
It only changes the key value used to retrieve the associated QueryResult.
|
| 400 |
+
|
| 401 |
+
As this function loads all QueryResult objects into memory, it may be
|
| 402 |
+
unsuitable for dealing with files containing many queries. In that case, it
|
| 403 |
+
is recommended that you use either ``index`` or ``index_db``.
|
| 404 |
+
|
| 405 |
+
Since Python 3.7, the default dict class maintains key order, meaning
|
| 406 |
+
this dictionary will reflect the order of records given to it. For
|
| 407 |
+
CPython and PyPy, this was already implemented for Python 3.6, so
|
| 408 |
+
effectively you can always assume the record order is preserved.
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
def _default_key_function(rec):
|
| 412 |
+
return rec.id
|
| 413 |
+
|
| 414 |
+
if key_function is None:
|
| 415 |
+
key_function = _default_key_function
|
| 416 |
+
|
| 417 |
+
qdict = {}
|
| 418 |
+
for qresult in qresults:
|
| 419 |
+
key = key_function(qresult)
|
| 420 |
+
if key in qdict:
|
| 421 |
+
raise ValueError("Duplicate key %r" % key)
|
| 422 |
+
qdict[key] = qresult
|
| 423 |
+
return qdict
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def index(filename, format=None, key_function=None, **kwargs):
|
| 427 |
+
"""Indexes a search output file and returns a dictionary-like object.
|
| 428 |
+
|
| 429 |
+
- filename - string giving name of file to be indexed
|
| 430 |
+
- format - Lower case string denoting one of the supported formats.
|
| 431 |
+
- key_function - Optional callback function which when given a
|
| 432 |
+
QueryResult should return a unique key for the dictionary.
|
| 433 |
+
- kwargs - Format-specific keyword arguments.
|
| 434 |
+
|
| 435 |
+
Index returns a pseudo-dictionary object with QueryResult objects as its
|
| 436 |
+
values and a string identifier as its keys. The function is mainly useful
|
| 437 |
+
for dealing with large search output files, as it enables access to any
|
| 438 |
+
given QueryResult object much faster than using parse or read.
|
| 439 |
+
|
| 440 |
+
Index works by storing in-memory the start locations of all queries in a
|
| 441 |
+
file. When a user requests access to the query, this function will jump
|
| 442 |
+
to its start position, parse the whole query, and return it as a
|
| 443 |
+
QueryResult object:
|
| 444 |
+
|
| 445 |
+
>>> from Bio import SearchIO
|
| 446 |
+
>>> search_idx = SearchIO.index('Blast/wnts.xml', 'blast-xml')
|
| 447 |
+
>>> search_idx
|
| 448 |
+
SearchIO.index('Blast/wnts.xml', 'blast-xml', key_function=None)
|
| 449 |
+
>>> sorted(search_idx)
|
| 450 |
+
['gi|156630997:105-1160', 'gi|195230749:301-1383', ..., 'gi|53729353:216-1313']
|
| 451 |
+
>>> search_idx['gi|195230749:301-1383']
|
| 452 |
+
QueryResult(id='gi|195230749:301-1383', 5 hits)
|
| 453 |
+
>>> search_idx.close()
|
| 454 |
+
|
| 455 |
+
If the file is BGZF compressed, this is detected automatically. Ordinary
|
| 456 |
+
GZIP files are not supported:
|
| 457 |
+
|
| 458 |
+
>>> from Bio import SearchIO
|
| 459 |
+
>>> search_idx = SearchIO.index('Blast/wnts.xml.bgz', 'blast-xml')
|
| 460 |
+
>>> search_idx
|
| 461 |
+
SearchIO.index('Blast/wnts.xml.bgz', 'blast-xml', key_function=None)
|
| 462 |
+
>>> search_idx['gi|195230749:301-1383']
|
| 463 |
+
QueryResult(id='gi|195230749:301-1383', 5 hits)
|
| 464 |
+
>>> search_idx.close()
|
| 465 |
+
|
| 466 |
+
You can supply a custom callback function to alter the default identifier
|
| 467 |
+
string. This function should accept as its input the QueryResult ID string
|
| 468 |
+
and return a modified version of it.
|
| 469 |
+
|
| 470 |
+
>>> from Bio import SearchIO
|
| 471 |
+
>>> key_func = lambda id: id.split('|')[1]
|
| 472 |
+
>>> search_idx = SearchIO.index('Blast/wnts.xml', 'blast-xml', key_func)
|
| 473 |
+
>>> search_idx
|
| 474 |
+
SearchIO.index('Blast/wnts.xml', 'blast-xml', key_function=<function <lambda> at ...>)
|
| 475 |
+
>>> sorted(search_idx)
|
| 476 |
+
['156630997:105-1160', ..., '371502086:108-1205', '53729353:216-1313']
|
| 477 |
+
>>> search_idx['156630997:105-1160']
|
| 478 |
+
QueryResult(id='gi|156630997:105-1160', 5 hits)
|
| 479 |
+
>>> search_idx.close()
|
| 480 |
+
|
| 481 |
+
Note that the callback function does not change the QueryResult's ID value.
|
| 482 |
+
It only changes the key value used to retrieve the associated QueryResult.
|
| 483 |
+
|
| 484 |
+
"""
|
| 485 |
+
if not isinstance(filename, str):
|
| 486 |
+
raise TypeError("Need a filename (not a handle)")
|
| 487 |
+
|
| 488 |
+
from Bio.File import _IndexedSeqFileDict
|
| 489 |
+
|
| 490 |
+
proxy_class = get_processor(format, _INDEXER_MAP)
|
| 491 |
+
repr = f"SearchIO.index({filename!r}, {format!r}, key_function={key_function!r})"
|
| 492 |
+
return _IndexedSeqFileDict(
|
| 493 |
+
proxy_class(filename, **kwargs), key_function, repr, "QueryResult"
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def index_db(index_filename, filenames=None, format=None, key_function=None, **kwargs):
|
| 498 |
+
"""Indexes several search output files into an SQLite database.
|
| 499 |
+
|
| 500 |
+
- index_filename - The SQLite filename.
|
| 501 |
+
- filenames - List of strings specifying file(s) to be indexed, or when
|
| 502 |
+
indexing a single file this can be given as a string.
|
| 503 |
+
(optional if reloading an existing index, but must match)
|
| 504 |
+
- format - Lower case string denoting one of the supported formats.
|
| 505 |
+
(optional if reloading an existing index, but must match)
|
| 506 |
+
- key_function - Optional callback function which when given a
|
| 507 |
+
QueryResult identifier string should return a unique
|
| 508 |
+
key for the dictionary.
|
| 509 |
+
- kwargs - Format-specific keyword arguments.
|
| 510 |
+
|
| 511 |
+
The ``index_db`` function is similar to ``index`` in that it indexes the start
|
| 512 |
+
position of all queries from search output files. The main difference is
|
| 513 |
+
instead of storing these indices in-memory, they are written to disk as an
|
| 514 |
+
SQLite database file. This allows the indices to persist between Python
|
| 515 |
+
sessions. This enables access to any queries in the file without any
|
| 516 |
+
indexing overhead, provided it has been indexed at least once.
|
| 517 |
+
|
| 518 |
+
>>> from Bio import SearchIO
|
| 519 |
+
>>> idx_filename = ":memory:" # Use a real filename, this is in RAM only!
|
| 520 |
+
>>> db_idx = SearchIO.index_db(idx_filename, 'Blast/mirna.xml', 'blast-xml')
|
| 521 |
+
>>> sorted(db_idx)
|
| 522 |
+
['33211', '33212', '33213']
|
| 523 |
+
>>> db_idx['33212']
|
| 524 |
+
QueryResult(id='33212', 44 hits)
|
| 525 |
+
>>> db_idx.close()
|
| 526 |
+
|
| 527 |
+
``index_db`` can also index multiple files and store them in the same
|
| 528 |
+
database, making it easier to group multiple search files and access them
|
| 529 |
+
from a single interface.
|
| 530 |
+
|
| 531 |
+
>>> from Bio import SearchIO
|
| 532 |
+
>>> idx_filename = ":memory:" # Use a real filename, this is in RAM only!
|
| 533 |
+
>>> files = ['Blast/mirna.xml', 'Blast/wnts.xml']
|
| 534 |
+
>>> db_idx = SearchIO.index_db(idx_filename, files, 'blast-xml')
|
| 535 |
+
>>> sorted(db_idx)
|
| 536 |
+
['33211', '33212', '33213', 'gi|156630997:105-1160', ..., 'gi|53729353:216-1313']
|
| 537 |
+
>>> db_idx['33212']
|
| 538 |
+
QueryResult(id='33212', 44 hits)
|
| 539 |
+
>>> db_idx.close()
|
| 540 |
+
|
| 541 |
+
One common example where this is helpful is if you had a large set of
|
| 542 |
+
query sequences (say ten thousand) which you split into ten query files
|
| 543 |
+
of one thousand sequences each in order to run as ten separate BLAST jobs
|
| 544 |
+
on a cluster. You could use ``index_db`` to index the ten BLAST output
|
| 545 |
+
files together for seamless access to all the results as one dictionary.
|
| 546 |
+
|
| 547 |
+
Note that ':memory:' rather than an index filename tells SQLite to hold
|
| 548 |
+
the index database in memory. This is useful for quick tests, but using
|
| 549 |
+
the Bio.SearchIO.index(...) function instead would use less memory.
|
| 550 |
+
|
| 551 |
+
BGZF compressed files are supported, and detected automatically. Ordinary
|
| 552 |
+
GZIP compressed files are not supported.
|
| 553 |
+
|
| 554 |
+
See also Bio.SearchIO.index(), Bio.SearchIO.to_dict(), and the Python module
|
| 555 |
+
glob which is useful for building lists of files.
|
| 556 |
+
"""
|
| 557 |
+
# cast filenames to list if it's a string
|
| 558 |
+
# (can we check if it's a string or a generator?)
|
| 559 |
+
if isinstance(filenames, str):
|
| 560 |
+
filenames = [filenames]
|
| 561 |
+
|
| 562 |
+
from Bio.File import _SQLiteManySeqFilesDict
|
| 563 |
+
|
| 564 |
+
repr = f"SearchIO.index_db({index_filename!r}, filenames={filenames!r}, {format!r}, key_function={key_function!r})"
|
| 565 |
+
|
| 566 |
+
def proxy_factory(format, filename=None):
|
| 567 |
+
"""Given a filename returns proxy object, else boolean if format OK."""
|
| 568 |
+
if filename:
|
| 569 |
+
return get_processor(format, _INDEXER_MAP)(filename, **kwargs)
|
| 570 |
+
else:
|
| 571 |
+
return format in _INDEXER_MAP
|
| 572 |
+
|
| 573 |
+
return _SQLiteManySeqFilesDict(
|
| 574 |
+
index_filename, filenames, proxy_factory, format, key_function, repr
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def write(qresults, handle, format=None, **kwargs):
|
| 579 |
+
"""Write QueryResult objects to a file in the given format.
|
| 580 |
+
|
| 581 |
+
- qresults - An iterator returning QueryResult objects or a single
|
| 582 |
+
QueryResult object.
|
| 583 |
+
- handle - Handle to the file, or the filename as a string.
|
| 584 |
+
- format - Lower case string denoting one of the supported formats.
|
| 585 |
+
- kwargs - Format-specific keyword arguments.
|
| 586 |
+
|
| 587 |
+
The ``write`` function writes QueryResult object(s) into the given output
|
| 588 |
+
handle / filename. You can supply it with a single QueryResult object or an
|
| 589 |
+
iterable returning one or more QueryResult objects. In both cases, the
|
| 590 |
+
function will return a tuple of four values: the number of QueryResult, Hit,
|
| 591 |
+
HSP, and HSPFragment objects it writes to the output file::
|
| 592 |
+
|
| 593 |
+
from Bio import SearchIO
|
| 594 |
+
qresults = SearchIO.parse('Blast/mirna.xml', 'blast-xml')
|
| 595 |
+
SearchIO.write(qresults, 'results.tab', 'blast-tab')
|
| 596 |
+
<stdout> (3, 239, 277, 277)
|
| 597 |
+
|
| 598 |
+
The output of different formats may be adjusted using the format-specific
|
| 599 |
+
keyword arguments. Here is an example that writes BLAT PSL output file with
|
| 600 |
+
a header::
|
| 601 |
+
|
| 602 |
+
from Bio import SearchIO
|
| 603 |
+
qresults = SearchIO.parse('Blat/psl_34_001.psl', 'blat-psl')
|
| 604 |
+
SearchIO.write(qresults, 'results.tab', 'blat-psl', header=True)
|
| 605 |
+
<stdout> (2, 13, 22, 26)
|
| 606 |
+
|
| 607 |
+
"""
|
| 608 |
+
# turn qresults into an iterator if it's a single QueryResult object
|
| 609 |
+
if isinstance(qresults, QueryResult):
|
| 610 |
+
qresults = iter([qresults])
|
| 611 |
+
else:
|
| 612 |
+
qresults = iter(qresults)
|
| 613 |
+
|
| 614 |
+
# get the writer object and do error checking
|
| 615 |
+
writer_class = get_processor(format, _WRITER_MAP)
|
| 616 |
+
|
| 617 |
+
# write to the handle
|
| 618 |
+
with as_handle(handle, "w") as target_file:
|
| 619 |
+
writer = writer_class(target_file, **kwargs)
|
| 620 |
+
# count how many qresults, hits, and hsps
|
| 621 |
+
qresult_count, hit_count, hsp_count, frag_count = writer.write_file(qresults)
|
| 622 |
+
|
| 623 |
+
return qresult_count, hit_count, hsp_count, frag_count
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def convert(in_file, in_format, out_file, out_format, in_kwargs=None, out_kwargs=None):
|
| 627 |
+
"""Convert between two search output formats, return number of records.
|
| 628 |
+
|
| 629 |
+
- in_file - Handle to the input file, or the filename as string.
|
| 630 |
+
- in_format - Lower case string denoting the format of the input file.
|
| 631 |
+
- out_file - Handle to the output file, or the filename as string.
|
| 632 |
+
- out_format - Lower case string denoting the format of the output file.
|
| 633 |
+
- in_kwargs - Dictionary of keyword arguments for the input function.
|
| 634 |
+
- out_kwargs - Dictionary of keyword arguments for the output function.
|
| 635 |
+
|
| 636 |
+
The convert function is a shortcut function for ``parse`` and ``write``. It has
|
| 637 |
+
the same return type as ``write``. Format-specific arguments may be passed to
|
| 638 |
+
the convert function, but only as dictionaries.
|
| 639 |
+
|
| 640 |
+
Here is an example of using ``convert`` to convert from a BLAST+ XML file
|
| 641 |
+
into a tabular file with comments::
|
| 642 |
+
|
| 643 |
+
from Bio import SearchIO
|
| 644 |
+
in_file = 'Blast/mirna.xml'
|
| 645 |
+
in_fmt = 'blast-xml'
|
| 646 |
+
out_file = 'results.tab'
|
| 647 |
+
out_fmt = 'blast-tab'
|
| 648 |
+
out_kwarg = {'comments': True}
|
| 649 |
+
SearchIO.convert(in_file, in_fmt, out_file, out_fmt, out_kwargs=out_kwarg)
|
| 650 |
+
<stdout> (3, 239, 277, 277)
|
| 651 |
+
|
| 652 |
+
Given that different search output file provide different statistics and
|
| 653 |
+
different level of details, the convert function is limited only to
|
| 654 |
+
converting formats that have the same statistics and for conversion to
|
| 655 |
+
formats with the same level of detail, or less.
|
| 656 |
+
|
| 657 |
+
For example, converting from a BLAST+ XML output to a HMMER table file
|
| 658 |
+
is not possible, as these are two search programs with different kinds of
|
| 659 |
+
statistics. In theory, you may provide the necessary values required by the
|
| 660 |
+
HMMER table file (e.g. conditional e-values, envelope coordinates, etc).
|
| 661 |
+
However, these values are likely to hold little meaning as they are not true
|
| 662 |
+
HMMER-computed values.
|
| 663 |
+
|
| 664 |
+
Another example is converting from BLAST+ XML to BLAST+ tabular file. This
|
| 665 |
+
is possible, as BLAST+ XML provide all the values necessary to create a
|
| 666 |
+
BLAST+ tabular file. However, the reverse conversion may not be possible.
|
| 667 |
+
There are more details covered in the XML file that are not found in a
|
| 668 |
+
tabular file (e.g. the lambda and kappa values)
|
| 669 |
+
|
| 670 |
+
"""
|
| 671 |
+
if in_kwargs is None:
|
| 672 |
+
in_kwargs = {}
|
| 673 |
+
if out_kwargs is None:
|
| 674 |
+
out_kwargs = {}
|
| 675 |
+
|
| 676 |
+
qresults = parse(in_file, in_format, **in_kwargs)
|
| 677 |
+
return write(qresults, out_file, out_format, **out_kwargs)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
# if not used as a module, run the doctest
|
| 681 |
+
if __name__ == "__main__":
|
| 682 |
+
from Bio._utils import run_doctest
|
| 683 |
+
|
| 684 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_index.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# Revisions copyright 2012-2016 by Peter Cock. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This file is part of the Biopython distribution and governed by your
|
| 5 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 6 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 7 |
+
# package.
|
| 8 |
+
|
| 9 |
+
"""Custom indexing for Bio.SearchIO objects."""
|
| 10 |
+
|
| 11 |
+
from io import StringIO
|
| 12 |
+
|
| 13 |
+
from Bio.File import _IndexedSeqFileProxy
|
| 14 |
+
from Bio.File import _open_for_random_access
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SearchIndexer(_IndexedSeqFileProxy):
|
| 18 |
+
"""Base class for file format specific random access.
|
| 19 |
+
|
| 20 |
+
Subclasses for each file format should define '_parser' and optionally
|
| 21 |
+
'get_raw' methods.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, filename, **kwargs):
|
| 25 |
+
"""Initialize the class."""
|
| 26 |
+
self._handle = _open_for_random_access(filename)
|
| 27 |
+
self._kwargs = kwargs
|
| 28 |
+
|
| 29 |
+
def _parse(self, handle):
|
| 30 |
+
"""Pass handle and arguments to the next iterable (PRIVATE)."""
|
| 31 |
+
return next(iter(self._parser(handle, **self._kwargs)))
|
| 32 |
+
|
| 33 |
+
def get(self, offset):
|
| 34 |
+
"""Get offset and convert it from bytes to string."""
|
| 35 |
+
return self._parse(StringIO(self.get_raw(offset).decode()))
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.__base.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hit.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hsp.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._query.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO objects to model similarity search program outputs.
|
| 7 |
+
|
| 8 |
+
The SearchIO object model consists of a hierarchy of four nested objects:
|
| 9 |
+
|
| 10 |
+
* QueryResult, to represent a search query.
|
| 11 |
+
|
| 12 |
+
This is the top-level object returned by the main SearchIO ``parse`` and
|
| 13 |
+
``read`` functions. QueryResult objects may contain zero or more Hit
|
| 14 |
+
objects, each accessible by its ID string (like in Python dictionaries)
|
| 15 |
+
or integer index (like in Python lists).
|
| 16 |
+
|
| 17 |
+
* Hit, to represent a database entry containing a full or partial sequence
|
| 18 |
+
match with the query sequence.
|
| 19 |
+
|
| 20 |
+
Hit objects contain one or more HSP objects, each accessible by its integer
|
| 21 |
+
index. They behave very similar to a Python list.
|
| 22 |
+
|
| 23 |
+
* HSP, to represent a region of significant alignment(s) between the query
|
| 24 |
+
and hit sequences.
|
| 25 |
+
|
| 26 |
+
HSP objects contain one or more HSPFragment objects, each accessible by
|
| 27 |
+
its integer index. In most cases, the HSP objects are where the bulk of
|
| 28 |
+
search result statistics (e.g. e-value, bitscore) are stored. Like Hit
|
| 29 |
+
objects, HSPs also behave very similar to a Python list.
|
| 30 |
+
|
| 31 |
+
* HSPFragment, to represent a single contiguous alignment between the query
|
| 32 |
+
and hit sequences.
|
| 33 |
+
|
| 34 |
+
HSPFragment objects may store hit and query sequences resulting from the
|
| 35 |
+
sequence search. If present, these sequences are stored as SeqRecord
|
| 36 |
+
objects (see SeqRecord). If both of them are present, HSPFragment will
|
| 37 |
+
create a MultipleSeqAlignment object from both sequences.
|
| 38 |
+
|
| 39 |
+
Most search programs only have HSPs with one HSPFragment in them, making
|
| 40 |
+
these two objects inseparable. However, there are programs (e.g. BLAT and
|
| 41 |
+
Exonerate) which may have more than one HSPFragment objects in any given
|
| 42 |
+
HSP. If you are not using these programs, you can safely consider HSP and
|
| 43 |
+
HSPFragment as a single union.
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
from .hit import Hit
|
| 48 |
+
from .hsp import HSP
|
| 49 |
+
from .hsp import HSPFragment
|
| 50 |
+
from .query import QueryResult
|
| 51 |
+
|
| 52 |
+
__all__ = ("QueryResult", "Hit", "HSP", "HSPFragment")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# if not used as a module, run the doctest
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
from Bio._utils import run_doctest
|
| 58 |
+
|
| 59 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/_base.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Abstract base classes for the SearchIO object model."""
|
| 7 |
+
|
| 8 |
+
from typing import Union
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._utils import getattr_str
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class _BaseSearchObject:
|
| 14 |
+
"""Abstract class for SearchIO objects."""
|
| 15 |
+
|
| 16 |
+
_NON_STICKY_ATTRS: tuple | tuple[str] = ()
|
| 17 |
+
|
| 18 |
+
def _transfer_attrs(self, obj):
|
| 19 |
+
"""Transfer instance attributes to the given object (PRIVATE).
|
| 20 |
+
|
| 21 |
+
This method is used to transfer attributes set externally (for example
|
| 22 |
+
using ``setattr``) to a new object created from this one (for example
|
| 23 |
+
from slicing).
|
| 24 |
+
|
| 25 |
+
The reason this method is necessary is because different parsers will
|
| 26 |
+
set different attributes for each QueryResult, Hit, HSP, or HSPFragment
|
| 27 |
+
objects, depending on the attributes they found in the search output
|
| 28 |
+
file. Ideally, we want these attributes to 'stick' with any new instance
|
| 29 |
+
object created from the original one.
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
# list of attribute names we don't want to transfer
|
| 33 |
+
for attr in self.__dict__:
|
| 34 |
+
if attr not in self._NON_STICKY_ATTRS:
|
| 35 |
+
setattr(obj, attr, self.__dict__[attr])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class _BaseHSP(_BaseSearchObject):
|
| 39 |
+
"""Abstract base class for HSP objects."""
|
| 40 |
+
|
| 41 |
+
def _str_hsp_header(self):
|
| 42 |
+
"""Print the alignment header info (PRIVATE)."""
|
| 43 |
+
lines = []
|
| 44 |
+
# set query id line
|
| 45 |
+
qid_line = f" Query: {self.query_id} {self.query_description}"
|
| 46 |
+
qid_line = qid_line[:77] + "..." if len(qid_line) > 80 else qid_line
|
| 47 |
+
# set hit id line
|
| 48 |
+
hid_line = f" Hit: {self.hit_id} {self.hit_description}"
|
| 49 |
+
hid_line = hid_line[:77] + "..." if len(hid_line) > 80 else hid_line
|
| 50 |
+
lines.append(qid_line)
|
| 51 |
+
lines.append(hid_line)
|
| 52 |
+
|
| 53 |
+
# coordinates
|
| 54 |
+
query_start = getattr_str(self, "query_start")
|
| 55 |
+
query_end = getattr_str(self, "query_end")
|
| 56 |
+
hit_start = getattr_str(self, "hit_start")
|
| 57 |
+
hit_end = getattr_str(self, "hit_end")
|
| 58 |
+
|
| 59 |
+
# strands
|
| 60 |
+
try:
|
| 61 |
+
qstrand = self.query_strand
|
| 62 |
+
hstrand = self.hit_strand
|
| 63 |
+
except ValueError:
|
| 64 |
+
qstrand = self.query_strand_all[0]
|
| 65 |
+
hstrand = self.hit_strand_all[0]
|
| 66 |
+
lines.append(f"Query range: [{query_start}:{query_end}] ({qstrand!r})")
|
| 67 |
+
lines.append(f" Hit range: [{hit_start}:{hit_end}] ({hstrand!r})")
|
| 68 |
+
|
| 69 |
+
return "\n".join(lines)
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hit.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO object to model a single database hit."""
|
| 7 |
+
|
| 8 |
+
from itertools import chain
|
| 9 |
+
|
| 10 |
+
from Bio.SearchIO._utils import allitems
|
| 11 |
+
from Bio.SearchIO._utils import getattr_str
|
| 12 |
+
from Bio.SearchIO._utils import optionalcascade
|
| 13 |
+
|
| 14 |
+
from ._base import _BaseSearchObject
|
| 15 |
+
from .hsp import HSP
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Hit(_BaseSearchObject):
|
| 19 |
+
"""Class representing a single database hit of a search result.
|
| 20 |
+
|
| 21 |
+
Hit objects are the second-level container in the SearchIO module. They
|
| 22 |
+
are the objects contained within a QueryResult (see QueryResult). They
|
| 23 |
+
themselves are container for HSP objects and will contain at least one
|
| 24 |
+
HSP.
|
| 25 |
+
|
| 26 |
+
To have a quick look at a Hit and its contents, invoke ``print`` on it::
|
| 27 |
+
|
| 28 |
+
>>> from Bio import SearchIO
|
| 29 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 30 |
+
>>> hit = qresult[3]
|
| 31 |
+
>>> print(hit)
|
| 32 |
+
Query: 33211
|
| 33 |
+
mir_1
|
| 34 |
+
Hit: gi|301171322|ref|NR_035857.1| (86)
|
| 35 |
+
Pan troglodytes microRNA mir-520c (MIR520C), microRNA
|
| 36 |
+
HSPs: ---- -------- --------- ------ --------------- ---------------------
|
| 37 |
+
# E-value Bit score Span Query range Hit range
|
| 38 |
+
---- -------- --------- ------ --------------- ---------------------
|
| 39 |
+
0 8.9e-20 100.47 60 [1:61] [13:73]
|
| 40 |
+
1 3.3e-06 55.39 60 [0:60] [13:73]
|
| 41 |
+
|
| 42 |
+
You can invoke ``len`` on a Hit object to see how many HSP objects it contains::
|
| 43 |
+
|
| 44 |
+
>>> len(hit)
|
| 45 |
+
2
|
| 46 |
+
|
| 47 |
+
Hit objects behave very similar to Python lists. You can retrieve the HSP
|
| 48 |
+
object inside a Hit using the HSP's integer index. Hit objects can also be
|
| 49 |
+
sliced, which will return a new Hit objects containing only the sliced HSPs::
|
| 50 |
+
|
| 51 |
+
# HSP items inside the Hit can be retrieved using its integer index
|
| 52 |
+
>>> hit[0]
|
| 53 |
+
HSP(hit_id='gi|301171322|ref|NR_035857.1|', query_id='33211', 1 fragments)
|
| 54 |
+
|
| 55 |
+
# slicing returns a new Hit
|
| 56 |
+
>>> hit
|
| 57 |
+
Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps)
|
| 58 |
+
>>> hit[:1]
|
| 59 |
+
Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 1 hsps)
|
| 60 |
+
>>> print(hit[1:])
|
| 61 |
+
Query: 33211
|
| 62 |
+
mir_1
|
| 63 |
+
Hit: gi|301171322|ref|NR_035857.1| (86)
|
| 64 |
+
Pan troglodytes microRNA mir-520c (MIR520C), microRNA
|
| 65 |
+
HSPs: ---- -------- --------- ------ --------------- ---------------------
|
| 66 |
+
# E-value Bit score Span Query range Hit range
|
| 67 |
+
---- -------- --------- ------ --------------- ---------------------
|
| 68 |
+
0 3.3e-06 55.39 60 [0:60] [13:73]
|
| 69 |
+
|
| 70 |
+
Hit objects provide ``filter`` and ``map`` methods, which are analogous to
|
| 71 |
+
Python's built-in ``filter`` and ``map`` except that they return a new Hit
|
| 72 |
+
object instead of a list.
|
| 73 |
+
|
| 74 |
+
Here is an example of using ``filter`` to select for HSPs whose e-value is
|
| 75 |
+
less than 1e-10::
|
| 76 |
+
|
| 77 |
+
>>> evalue_filter = lambda hsp: hsp.evalue < 1e-10
|
| 78 |
+
>>> filtered_hit = hit.filter(evalue_filter)
|
| 79 |
+
>>> len(hit)
|
| 80 |
+
2
|
| 81 |
+
>>> len(filtered_hit)
|
| 82 |
+
1
|
| 83 |
+
>>> print(filtered_hit)
|
| 84 |
+
Query: 33211
|
| 85 |
+
mir_1
|
| 86 |
+
Hit: gi|301171322|ref|NR_035857.1| (86)
|
| 87 |
+
Pan troglodytes microRNA mir-520c (MIR520C), microRNA
|
| 88 |
+
HSPs: ---- -------- --------- ------ --------------- ---------------------
|
| 89 |
+
# E-value Bit score Span Query range Hit range
|
| 90 |
+
---- -------- --------- ------ --------------- ---------------------
|
| 91 |
+
0 8.9e-20 100.47 60 [1:61] [13:73]
|
| 92 |
+
|
| 93 |
+
There are also other methods which are counterparts of Python lists' methods
|
| 94 |
+
with the same names: ``append``, ``index``, ``pop``, and ``sort``. Consult their
|
| 95 |
+
respective documentations for more details and examples of their usage.
|
| 96 |
+
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
# attributes we don't want to transfer when creating a new Hit class
|
| 100 |
+
# from this one
|
| 101 |
+
_NON_STICKY_ATTRS = ("_items",)
|
| 102 |
+
|
| 103 |
+
def __init__(self, hsps=(), id=None, query_id=None):
|
| 104 |
+
"""Initialize a Hit object.
|
| 105 |
+
|
| 106 |
+
:param hsps: HSP objects contained in the Hit object
|
| 107 |
+
:type hsps: iterable yielding HSP
|
| 108 |
+
:param id: hit ID
|
| 109 |
+
:type id: string
|
| 110 |
+
:param query_id: query ID
|
| 111 |
+
:type query_id: string
|
| 112 |
+
|
| 113 |
+
If multiple HSP objects are used for initialization, they must all
|
| 114 |
+
have the same ``query_id``, ``query_description``, ``hit_id``, and
|
| 115 |
+
``hit_description`` properties.
|
| 116 |
+
"""
|
| 117 |
+
# default attribute values
|
| 118 |
+
self._id = id
|
| 119 |
+
self._id_alt = []
|
| 120 |
+
self._query_id = query_id
|
| 121 |
+
self._description = None
|
| 122 |
+
self._description_alt = []
|
| 123 |
+
self._query_description = None
|
| 124 |
+
self.attributes = {}
|
| 125 |
+
self.dbxrefs = []
|
| 126 |
+
|
| 127 |
+
# TODO - Move this into the for look below in case
|
| 128 |
+
# hsps is a single use iterator?
|
| 129 |
+
for attr in ("query_id", "query_description", "hit_id", "hit_description"):
|
| 130 |
+
# HACK: setting the if clause to '> 1' allows for empty hit objects.
|
| 131 |
+
# This makes it easier to work with file formats with unpredictable
|
| 132 |
+
# hit-hsp ordering. The empty hit object itself is nonfunctional,
|
| 133 |
+
# however, since all its cascading properties are empty.
|
| 134 |
+
if len({getattr(hsp, attr) for hsp in hsps}) > 1:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"Hit object can not contain HSPs with more than one %s." % attr
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
self._items = []
|
| 140 |
+
for hsp in hsps:
|
| 141 |
+
# validate each HSP
|
| 142 |
+
self._validate_hsp(hsp)
|
| 143 |
+
# and store it them as an instance attribute
|
| 144 |
+
self.append(hsp)
|
| 145 |
+
|
| 146 |
+
def __repr__(self):
|
| 147 |
+
"""Return string representation of Hit object."""
|
| 148 |
+
return f"Hit(id={self.id!r}, query_id={self.query_id!r}, {len(self)!r} hsps)"
|
| 149 |
+
|
| 150 |
+
def __iter__(self):
|
| 151 |
+
"""Iterate over hsps."""
|
| 152 |
+
return iter(self.hsps)
|
| 153 |
+
|
| 154 |
+
def __len__(self):
|
| 155 |
+
"""Return number of hsps."""
|
| 156 |
+
return len(self.hsps)
|
| 157 |
+
|
| 158 |
+
def __bool__(self):
|
| 159 |
+
"""Return True if there are hsps."""
|
| 160 |
+
return bool(self.hsps)
|
| 161 |
+
|
| 162 |
+
def __contains__(self, hsp):
|
| 163 |
+
"""Return True if hsp in items."""
|
| 164 |
+
return hsp in self._items
|
| 165 |
+
|
| 166 |
+
def __str__(self):
|
| 167 |
+
"""Return a human readable summary of the Hit object."""
|
| 168 |
+
lines = []
|
| 169 |
+
|
| 170 |
+
# set query id line
|
| 171 |
+
qid_line = "Query: %s" % self.query_id
|
| 172 |
+
lines.append(qid_line)
|
| 173 |
+
if self.query_description:
|
| 174 |
+
line = " %s" % self.query_description
|
| 175 |
+
line = line[:77] + "..." if len(line) > 80 else line
|
| 176 |
+
lines.append(line)
|
| 177 |
+
|
| 178 |
+
# set hit id line
|
| 179 |
+
hid_line = " Hit: %s" % self.id
|
| 180 |
+
try:
|
| 181 |
+
seq_len = self.seq_len
|
| 182 |
+
except AttributeError:
|
| 183 |
+
pass
|
| 184 |
+
else:
|
| 185 |
+
hid_line += " (%i)" % seq_len
|
| 186 |
+
lines.append(hid_line)
|
| 187 |
+
if self.description:
|
| 188 |
+
line = " %s" % self.description
|
| 189 |
+
line = line[:77] + "..." if len(line) > 80 else line
|
| 190 |
+
lines.append(line)
|
| 191 |
+
|
| 192 |
+
# set attributes lines
|
| 193 |
+
for key, value in sorted(self.attributes.items()):
|
| 194 |
+
lines.append(f" {key}: {value}")
|
| 195 |
+
|
| 196 |
+
# set dbxrefs line
|
| 197 |
+
if self.dbxrefs:
|
| 198 |
+
lines.append("Database cross-references: " + ", ".join(self.dbxrefs))
|
| 199 |
+
|
| 200 |
+
# set hsp line and table
|
| 201 |
+
if not self.hsps:
|
| 202 |
+
lines.append(" HSPs: ?")
|
| 203 |
+
else:
|
| 204 |
+
lines.append(
|
| 205 |
+
" HSPs: %s %s %s %s %s %s"
|
| 206 |
+
% ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21)
|
| 207 |
+
)
|
| 208 |
+
pattern = "%11s %8s %9s %6s %15s %21s"
|
| 209 |
+
lines.append(
|
| 210 |
+
pattern
|
| 211 |
+
% ("#", "E-value", "Bit score", "Span", "Query range", "Hit range")
|
| 212 |
+
)
|
| 213 |
+
lines.append(
|
| 214 |
+
pattern % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21)
|
| 215 |
+
)
|
| 216 |
+
for idx, hsp in enumerate(self.hsps):
|
| 217 |
+
# evalue
|
| 218 |
+
evalue = getattr_str(hsp, "evalue", fmt="%.2g")
|
| 219 |
+
# bitscore
|
| 220 |
+
bitscore = getattr_str(hsp, "bitscore", fmt="%.2f")
|
| 221 |
+
# alignment length
|
| 222 |
+
aln_span = getattr_str(hsp, "aln_span")
|
| 223 |
+
# query region
|
| 224 |
+
query_start = getattr_str(hsp, "query_start")
|
| 225 |
+
query_end = getattr_str(hsp, "query_end")
|
| 226 |
+
query_range = f"[{query_start}:{query_end}]"
|
| 227 |
+
# max column length is 18
|
| 228 |
+
query_range = (
|
| 229 |
+
query_range[:13] + "~]" if len(query_range) > 15 else query_range
|
| 230 |
+
)
|
| 231 |
+
# hit region
|
| 232 |
+
hit_start = getattr_str(hsp, "hit_start")
|
| 233 |
+
hit_end = getattr_str(hsp, "hit_end")
|
| 234 |
+
hit_range = f"[{hit_start}:{hit_end}]"
|
| 235 |
+
hit_range = hit_range[:19] + "~]" if len(hit_range) > 21 else hit_range
|
| 236 |
+
# append the hsp row
|
| 237 |
+
lines.append(
|
| 238 |
+
pattern % (idx, evalue, bitscore, aln_span, query_range, hit_range)
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
return "\n".join(lines)
|
| 242 |
+
|
| 243 |
+
def __getitem__(self, idx):
|
| 244 |
+
"""Return the HSP object at the given index."""
|
| 245 |
+
# if key is slice, return a new Hit instance
|
| 246 |
+
if isinstance(idx, slice):
|
| 247 |
+
obj = self.__class__(self.hsps[idx])
|
| 248 |
+
self._transfer_attrs(obj)
|
| 249 |
+
return obj
|
| 250 |
+
return self._items[idx]
|
| 251 |
+
|
| 252 |
+
def __setitem__(self, idx, hsps):
|
| 253 |
+
"""Assign hsps to index idx."""
|
| 254 |
+
# handle case if hsps is a list of hsp
|
| 255 |
+
if isinstance(hsps, (list, tuple)):
|
| 256 |
+
for hsp in hsps:
|
| 257 |
+
self._validate_hsp(hsp)
|
| 258 |
+
else:
|
| 259 |
+
self._validate_hsp(hsps)
|
| 260 |
+
|
| 261 |
+
self._items[idx] = hsps
|
| 262 |
+
|
| 263 |
+
def __delitem__(self, idx):
|
| 264 |
+
"""Delete item of index idx."""
|
| 265 |
+
del self._items[idx]
|
| 266 |
+
|
| 267 |
+
# hsp properties #
|
| 268 |
+
def _validate_hsp(self, hsp):
|
| 269 |
+
"""Validate an HSP object (PRIVATE).
|
| 270 |
+
|
| 271 |
+
Valid HSP objects have the same hit_id as the Hit object ID and the
|
| 272 |
+
same query_id as the Hit object's query_id.
|
| 273 |
+
|
| 274 |
+
"""
|
| 275 |
+
if not isinstance(hsp, HSP):
|
| 276 |
+
raise TypeError("Hit objects can only contain HSP objects.")
|
| 277 |
+
# HACK: to make validation during __init__ work
|
| 278 |
+
if self._items:
|
| 279 |
+
if self.id is not None:
|
| 280 |
+
if hsp.hit_id != self.id:
|
| 281 |
+
raise ValueError(
|
| 282 |
+
"Expected HSP with hit ID %r, found %r instead."
|
| 283 |
+
% (self.id, hsp.hit_id)
|
| 284 |
+
)
|
| 285 |
+
else:
|
| 286 |
+
self.id = hsp.hit_id
|
| 287 |
+
|
| 288 |
+
if self.description is not None:
|
| 289 |
+
if hsp.hit_description != self.description:
|
| 290 |
+
raise ValueError(
|
| 291 |
+
"Expected HSP with hit description %r, found %r instead."
|
| 292 |
+
% (self.description, hsp.hit_description)
|
| 293 |
+
)
|
| 294 |
+
else:
|
| 295 |
+
self.description = hsp.hit_description
|
| 296 |
+
|
| 297 |
+
if self.query_id is not None:
|
| 298 |
+
if hsp.query_id != self.query_id:
|
| 299 |
+
raise ValueError(
|
| 300 |
+
"Expected HSP with query ID %r, found %r instead."
|
| 301 |
+
% (self.query_id, hsp.query_id)
|
| 302 |
+
)
|
| 303 |
+
else:
|
| 304 |
+
self.query_id = hsp.query_id
|
| 305 |
+
|
| 306 |
+
if self.query_description is not None:
|
| 307 |
+
if hsp.query_description != self.query_description:
|
| 308 |
+
raise ValueError(
|
| 309 |
+
"Expected HSP with query description %r, found %r instead."
|
| 310 |
+
% (self.query_description, hsp.query_description)
|
| 311 |
+
)
|
| 312 |
+
else:
|
| 313 |
+
self.query_description = hsp.query_description
|
| 314 |
+
|
| 315 |
+
# properties #
|
| 316 |
+
description = optionalcascade(
|
| 317 |
+
"_description", "hit_description", """Hit description"""
|
| 318 |
+
)
|
| 319 |
+
query_description = optionalcascade(
|
| 320 |
+
"_query_description",
|
| 321 |
+
"query_description",
|
| 322 |
+
"""Description of the query that produced the hit""",
|
| 323 |
+
)
|
| 324 |
+
id = optionalcascade("_id", "hit_id", """Hit ID string.""")
|
| 325 |
+
query_id = optionalcascade(
|
| 326 |
+
"_query_id", "query_id", """ID string of the query that produced the hit"""
|
| 327 |
+
)
|
| 328 |
+
# returns all hsps
|
| 329 |
+
hsps = allitems(doc="""HSP objects contained in the Hit""")
|
| 330 |
+
|
| 331 |
+
@property
|
| 332 |
+
def id_all(self):
|
| 333 |
+
"""Alternative ID(s) of the Hit."""
|
| 334 |
+
return [self.id] + self._id_alt
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def description_all(self):
|
| 338 |
+
"""Alternative descriptions of the Hit."""
|
| 339 |
+
return [self.description] + self._description_alt
|
| 340 |
+
|
| 341 |
+
@property
|
| 342 |
+
def fragments(self):
|
| 343 |
+
"""Access the HSPFragment objects contained in the Hit."""
|
| 344 |
+
return list(chain(*self._items))
|
| 345 |
+
|
| 346 |
+
# public methods #
|
| 347 |
+
def append(self, hsp):
|
| 348 |
+
"""Add a HSP object to the end of Hit.
|
| 349 |
+
|
| 350 |
+
Parameters
|
| 351 |
+
hsp -- HSP object to append.
|
| 352 |
+
|
| 353 |
+
Any HSP object appended must have the same ``hit_id`` property as the
|
| 354 |
+
Hit object's ``id`` property and the same ``query_id`` property as the
|
| 355 |
+
Hit object's ``query_id`` property.
|
| 356 |
+
|
| 357 |
+
"""
|
| 358 |
+
self._validate_hsp(hsp)
|
| 359 |
+
self._items.append(hsp)
|
| 360 |
+
|
| 361 |
+
def filter(self, func=None):
|
| 362 |
+
"""Create new Hit object whose HSP objects pass the filter function.
|
| 363 |
+
|
| 364 |
+
:param func: function for filtering
|
| 365 |
+
:type func: callable, accepts HSP, returns bool
|
| 366 |
+
|
| 367 |
+
``filter`` is analogous to Python's built-in ``filter`` function, except
|
| 368 |
+
that instead of returning a list it returns a ``Hit`` object. Here is an
|
| 369 |
+
example of using ``filter`` to select for HSPs having bitscores bigger
|
| 370 |
+
than 60::
|
| 371 |
+
|
| 372 |
+
>>> from Bio import SearchIO
|
| 373 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 374 |
+
>>> hit = qresult[3]
|
| 375 |
+
>>> evalue_filter = lambda hsp: hsp.bitscore > 60
|
| 376 |
+
>>> filtered_hit = hit.filter(evalue_filter)
|
| 377 |
+
>>> len(hit)
|
| 378 |
+
2
|
| 379 |
+
>>> len(filtered_hit)
|
| 380 |
+
1
|
| 381 |
+
>>> print(filtered_hit)
|
| 382 |
+
Query: 33211
|
| 383 |
+
mir_1
|
| 384 |
+
Hit: gi|301171322|ref|NR_035857.1| (86)
|
| 385 |
+
Pan troglodytes microRNA mir-520c (MIR520C), microRNA
|
| 386 |
+
HSPs: ---- -------- --------- ------ --------------- ---------------------
|
| 387 |
+
# E-value Bit score Span Query range Hit range
|
| 388 |
+
---- -------- --------- ------ --------------- ---------------------
|
| 389 |
+
0 8.9e-20 100.47 60 [1:61] [13:73]
|
| 390 |
+
|
| 391 |
+
"""
|
| 392 |
+
hsps = list(filter(func, self.hsps))
|
| 393 |
+
if hsps:
|
| 394 |
+
obj = self.__class__(hsps)
|
| 395 |
+
self._transfer_attrs(obj)
|
| 396 |
+
return obj
|
| 397 |
+
|
| 398 |
+
def index(self, hsp):
|
| 399 |
+
"""Return the index of a given HSP object, zero-based.
|
| 400 |
+
|
| 401 |
+
:param hsp: object to look up
|
| 402 |
+
:type hsp: HSP
|
| 403 |
+
|
| 404 |
+
"""
|
| 405 |
+
return self._items.index(hsp)
|
| 406 |
+
|
| 407 |
+
def map(self, func=None):
|
| 408 |
+
"""Create new Hit object, mapping the given function to its HSPs.
|
| 409 |
+
|
| 410 |
+
:param func: function for mapping
|
| 411 |
+
:type func: callable, accepts HSP, returns HSP
|
| 412 |
+
|
| 413 |
+
``map`` is analogous to Python's built-in ``map`` function. It is applied to
|
| 414 |
+
all HSPs contained in the Hit object and returns a new Hit object.
|
| 415 |
+
|
| 416 |
+
"""
|
| 417 |
+
if func is not None:
|
| 418 |
+
hsps = [func(x) for x in self.hsps[:]] # this creates a shallow copy
|
| 419 |
+
else:
|
| 420 |
+
hsps = self.hsps[:]
|
| 421 |
+
if hsps:
|
| 422 |
+
obj = self.__class__(hsps)
|
| 423 |
+
self._transfer_attrs(obj)
|
| 424 |
+
return obj
|
| 425 |
+
|
| 426 |
+
def pop(self, index=-1):
|
| 427 |
+
"""Remove and returns the HSP object at the specified index.
|
| 428 |
+
|
| 429 |
+
:param index: index of HSP object to pop
|
| 430 |
+
:type index: int
|
| 431 |
+
|
| 432 |
+
"""
|
| 433 |
+
return self._items.pop(index)
|
| 434 |
+
|
| 435 |
+
def sort(self, key=None, reverse=False, in_place=True):
|
| 436 |
+
"""Sort the HSP objects.
|
| 437 |
+
|
| 438 |
+
:param key: sorting function
|
| 439 |
+
:type key: callable, accepts HSP, returns key for sorting
|
| 440 |
+
:param reverse: whether to reverse sorting results or no
|
| 441 |
+
:type reverse: bool
|
| 442 |
+
:param in_place: whether to do in-place sorting or no
|
| 443 |
+
:type in_place: bool
|
| 444 |
+
|
| 445 |
+
``sort`` defaults to sorting in-place, to mimic Python's ``list.sort``
|
| 446 |
+
method. If you set the ``in_place`` argument to False, it will treat
|
| 447 |
+
return a new, sorted Hit object and keep the initial one unsorted
|
| 448 |
+
|
| 449 |
+
"""
|
| 450 |
+
if in_place:
|
| 451 |
+
self._items.sort(key=key, reverse=reverse)
|
| 452 |
+
else:
|
| 453 |
+
hsps = self.hsps[:]
|
| 454 |
+
hsps.sort(key=key, reverse=reverse)
|
| 455 |
+
obj = self.__class__(hsps)
|
| 456 |
+
self._transfer_attrs(obj)
|
| 457 |
+
return obj
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# if not used as a module, run the doctest
|
| 461 |
+
if __name__ == "__main__":
|
| 462 |
+
from Bio._utils import run_do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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO objects to model high scoring regions between query and hit."""
|
| 7 |
+
|
| 8 |
+
import warnings
|
| 9 |
+
from operator import ge
|
| 10 |
+
from operator import le
|
| 11 |
+
|
| 12 |
+
from Bio import BiopythonWarning
|
| 13 |
+
from Bio.Align import MultipleSeqAlignment
|
| 14 |
+
from Bio.SearchIO._utils import allitems
|
| 15 |
+
from Bio.SearchIO._utils import fragcascade
|
| 16 |
+
from Bio.SearchIO._utils import fullcascade
|
| 17 |
+
from Bio.SearchIO._utils import getattr_str
|
| 18 |
+
from Bio.SearchIO._utils import singleitem
|
| 19 |
+
from Bio.Seq import Seq
|
| 20 |
+
from Bio.SeqRecord import SeqRecord
|
| 21 |
+
|
| 22 |
+
from ._base import _BaseHSP
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class HSP(_BaseHSP):
|
| 26 |
+
"""Class representing high-scoring region(s) between query and hit.
|
| 27 |
+
|
| 28 |
+
HSP (high-scoring pair) objects are contained by Hit objects (see Hit).
|
| 29 |
+
In most cases, HSP objects store the bulk of the statistics and results
|
| 30 |
+
(e.g. e-value, bitscores, query sequence, etc.) produced by a search
|
| 31 |
+
program.
|
| 32 |
+
|
| 33 |
+
Depending on the search output file format, a given HSP will contain one
|
| 34 |
+
or more HSPFragment object(s). Examples of search programs that produce HSP
|
| 35 |
+
with one HSPFragments are BLAST, HMMER, and FASTA. Other programs such as
|
| 36 |
+
BLAT or Exonerate may produce HSPs containing more than one HSPFragment.
|
| 37 |
+
However, their native terminologies may differ: in BLAT these fragments
|
| 38 |
+
are called 'blocks' while in Exonerate they are called exons or NER.
|
| 39 |
+
|
| 40 |
+
Here are examples from each type of HSP. The first one comes from a BLAST
|
| 41 |
+
search::
|
| 42 |
+
|
| 43 |
+
>>> from Bio import SearchIO
|
| 44 |
+
>>> blast_qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 45 |
+
>>> blast_hsp = blast_qresult[1][0] # the first HSP from the second hit
|
| 46 |
+
>>> blast_hsp
|
| 47 |
+
HSP(hit_id='gi|301171311|ref|NR_035856.1|', query_id='33211', 1 fragments)
|
| 48 |
+
>>> print(blast_hsp)
|
| 49 |
+
Query: 33211 mir_1
|
| 50 |
+
Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ...
|
| 51 |
+
Query range: [1:61] (1)
|
| 52 |
+
Hit range: [0:60] (1)
|
| 53 |
+
Quick stats: evalue 1.7e-22; bitscore 109.49
|
| 54 |
+
Fragments: 1 (60 columns)
|
| 55 |
+
Query - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|
| 56 |
+
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| 57 |
+
Hit - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|
| 58 |
+
|
| 59 |
+
For HSPs with a single HSPFragment, you can invoke ``print`` on it and see the
|
| 60 |
+
underlying sequence alignment, if it exists. This is not the case for HSPs
|
| 61 |
+
with more than one HSPFragment. Below is an example, using an HSP from a
|
| 62 |
+
BLAT search. Invoking ``print`` on these HSPs will instead show a table of the
|
| 63 |
+
HSPFragment objects it contains::
|
| 64 |
+
|
| 65 |
+
>>> blat_qresult = SearchIO.read('Blat/mirna.pslx', 'blat-psl', pslx=True)
|
| 66 |
+
>>> blat_hsp = blat_qresult[1][0] # the first HSP from the second hit
|
| 67 |
+
>>> blat_hsp
|
| 68 |
+
HSP(hit_id='chr11', query_id='blat_1', 2 fragments)
|
| 69 |
+
>>> print(blat_hsp)
|
| 70 |
+
Query: blat_1 <unknown description>
|
| 71 |
+
Hit: chr11 <unknown description>
|
| 72 |
+
Query range: [42:67] (-1)
|
| 73 |
+
Hit range: [59018929:59018955] (1)
|
| 74 |
+
Quick stats: evalue ?; bitscore ?
|
| 75 |
+
Fragments: --- -------------- ---------------------- ----------------------
|
| 76 |
+
# Span Query range Hit range
|
| 77 |
+
--- -------------- ---------------------- ----------------------
|
| 78 |
+
0 6 [61:67] [59018929:59018935]
|
| 79 |
+
1 16 [42:58] [59018939:59018955]
|
| 80 |
+
|
| 81 |
+
Notice that in HSPs with more than one HSPFragments, the HSP's ``query_range``
|
| 82 |
+
``hit_range`` properties encompasses all fragments it contains.
|
| 83 |
+
|
| 84 |
+
You can check whether an HSP has more than one HSPFragments or not using the
|
| 85 |
+
``is_fragmented`` property::
|
| 86 |
+
|
| 87 |
+
>>> blast_hsp.is_fragmented
|
| 88 |
+
False
|
| 89 |
+
>>> blat_hsp.is_fragmented
|
| 90 |
+
True
|
| 91 |
+
|
| 92 |
+
Since HSP objects are also containers similar to Python lists, you can
|
| 93 |
+
access a single fragment in an HSP using its integer index::
|
| 94 |
+
|
| 95 |
+
>>> blat_fragment = blat_hsp[0]
|
| 96 |
+
>>> print(blat_fragment)
|
| 97 |
+
Query: blat_1 <unknown description>
|
| 98 |
+
Hit: chr11 <unknown description>
|
| 99 |
+
Query range: [61:67] (-1)
|
| 100 |
+
Hit range: [59018929:59018935] (1)
|
| 101 |
+
Fragments: 1 (6 columns)
|
| 102 |
+
Query - tatagt
|
| 103 |
+
Hit - tatagt
|
| 104 |
+
|
| 105 |
+
This applies to HSPs objects with a single fragment as well::
|
| 106 |
+
|
| 107 |
+
>>> blast_fragment = blast_hsp[0]
|
| 108 |
+
>>> print(blast_fragment)
|
| 109 |
+
Query: 33211 mir_1
|
| 110 |
+
Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ...
|
| 111 |
+
Query range: [1:61] (1)
|
| 112 |
+
Hit range: [0:60] (1)
|
| 113 |
+
Fragments: 1 (60 columns)
|
| 114 |
+
Query - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|
| 115 |
+
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| 116 |
+
Hit - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|
| 117 |
+
|
| 118 |
+
Regardless of the search output file format, HSP objects provide the
|
| 119 |
+
properties listed below. These properties always return values in a list,
|
| 120 |
+
due to the HSP object itself being a list-like container. However, for
|
| 121 |
+
HSP objects with a single HSPFragment, shortcut properties that fetches
|
| 122 |
+
the item from the list are also provided.
|
| 123 |
+
|
| 124 |
+
+----------------------+---------------------+-----------------------------+
|
| 125 |
+
| Property | Shortcut | Value |
|
| 126 |
+
+======================+=====================+=============================+
|
| 127 |
+
| aln_all | aln | HSP alignments as |
|
| 128 |
+
| | | MultipleSeqAlignment object |
|
| 129 |
+
+----------------------+---------------------+-----------------------------+
|
| 130 |
+
| aln_annotation_all | aln_annotation | dictionary of annotation(s) |
|
| 131 |
+
| | | of all fragments' alignments|
|
| 132 |
+
+----------------------+---------------------+-----------------------------+
|
| 133 |
+
| fragments | fragment | HSPFragment objects |
|
| 134 |
+
+----------------------+---------------------+-----------------------------+
|
| 135 |
+
| hit_all | hit | hit sequence as SeqRecord |
|
| 136 |
+
| | | objects |
|
| 137 |
+
+----------------------+---------------------+-----------------------------+
|
| 138 |
+
| hit_features_all | hit_features | SeqFeatures of all hit |
|
| 139 |
+
| | | fragments |
|
| 140 |
+
+----------------------+---------------------+-----------------------------+
|
| 141 |
+
| hit_start_all | hit_start* | start coordinates of the |
|
| 142 |
+
| | | hit fragments |
|
| 143 |
+
+----------------------+---------------------+-----------------------------+
|
| 144 |
+
| hit_end_all | hit_end* | end coordinates of the hit |
|
| 145 |
+
| | | fragments |
|
| 146 |
+
+----------------------+---------------------+-----------------------------+
|
| 147 |
+
| hit_span_all | hit_span* | sizes of each hit fragments |
|
| 148 |
+
+----------------------+---------------------+-----------------------------+
|
| 149 |
+
| hit_strand_all | hit_strand | strand orientations of the |
|
| 150 |
+
| | | hit fragments |
|
| 151 |
+
+----------------------+---------------------+-----------------------------+
|
| 152 |
+
| hit_frame_all | hit_frame | reading frames of the hit |
|
| 153 |
+
| | | fragments |
|
| 154 |
+
+----------------------+---------------------+-----------------------------+
|
| 155 |
+
| hit_range_all | hit_range | tuples of start and end |
|
| 156 |
+
| | | coordinates of each hit |
|
| 157 |
+
| | | fragment |
|
| 158 |
+
+----------------------+---------------------+-----------------------------+
|
| 159 |
+
| query_all | query | query sequence as SeqRecord |
|
| 160 |
+
| | | object |
|
| 161 |
+
+----------------------+---------------------+-----------------------------+
|
| 162 |
+
| query_features_all | query_features | SeqFeatures of all query |
|
| 163 |
+
| | | fragments |
|
| 164 |
+
+----------------------+---------------------+-----------------------------+
|
| 165 |
+
| query_start_all | query_start* | start coordinates of the |
|
| 166 |
+
| | | fragments |
|
| 167 |
+
+----------------------+---------------------+-----------------------------+
|
| 168 |
+
| query_end_all | query_end* | end coordinates of the |
|
| 169 |
+
| | | query fragments |
|
| 170 |
+
+----------------------+---------------------+-----------------------------+
|
| 171 |
+
| query_span_all | query_span* | sizes of each query |
|
| 172 |
+
| | | fragments |
|
| 173 |
+
+----------------------+---------------------+-----------------------------+
|
| 174 |
+
| query_strand_all | query_strand | strand orientations of the |
|
| 175 |
+
| | | query fragments |
|
| 176 |
+
+----------------------+---------------------+-----------------------------+
|
| 177 |
+
| query_frame_all | query_frame | reading frames of the query |
|
| 178 |
+
| | | fragments |
|
| 179 |
+
+----------------------+---------------------+-----------------------------+
|
| 180 |
+
| query_range_all | query_range | tuples of start and end |
|
| 181 |
+
| | | coordinates of each query |
|
| 182 |
+
| | | fragment |
|
| 183 |
+
+----------------------+---------------------+-----------------------------+
|
| 184 |
+
|
| 185 |
+
For all types of HSP objects, the property will return the values in a list.
|
| 186 |
+
Shortcuts are only applicable for HSPs with one fragment. Except the ones
|
| 187 |
+
noted, if they are used on an HSP with more than one fragments, an exception
|
| 188 |
+
will be raised.
|
| 189 |
+
|
| 190 |
+
For properties that may be used in HSPs with multiple or single fragments
|
| 191 |
+
(``*_start``, ``*_end``, and ``*_span`` properties), their interpretation depends
|
| 192 |
+
on how many fragment the HSP has:
|
| 193 |
+
|
| 194 |
+
+------------+---------------------------------------------------+
|
| 195 |
+
| Property | Value |
|
| 196 |
+
+============+===================================================+
|
| 197 |
+
| hit_start | smallest coordinate value of all hit fragments |
|
| 198 |
+
+------------+---------------------------------------------------+
|
| 199 |
+
| hit_end | largest coordinate value of all hit fragments |
|
| 200 |
+
+------------+---------------------------------------------------+
|
| 201 |
+
| hit_span | difference between ``hit_start`` and ``hit_end`` |
|
| 202 |
+
+------------+---------------------------------------------------+
|
| 203 |
+
| query_start| smallest coordinate value of all query fragments |
|
| 204 |
+
+------------+---------------------------------------------------+
|
| 205 |
+
| query_end | largest coordinate value of all query fragments |
|
| 206 |
+
+------------+---------------------------------------------------+
|
| 207 |
+
| query_span | difference between ``query_start`` and |
|
| 208 |
+
| | ``query_end`` |
|
| 209 |
+
+------------+---------------------------------------------------+
|
| 210 |
+
|
| 211 |
+
In addition to the objects listed above, HSP objects also provide the
|
| 212 |
+
following properties and/or attributes:
|
| 213 |
+
|
| 214 |
+
+--------------------+------------------------------------------------------+
|
| 215 |
+
| Property | Value |
|
| 216 |
+
+====================+======================================================+
|
| 217 |
+
| aln_span | total number of residues in all HSPFragment objects |
|
| 218 |
+
+--------------------+------------------------------------------------------+
|
| 219 |
+
| molecule_type | molecule_type of the hit and query SeqRecord objects |
|
| 220 |
+
+--------------------+------------------------------------------------------+
|
| 221 |
+
| is_fragmented | boolean, whether there are multiple fragments or not |
|
| 222 |
+
+--------------------+------------------------------------------------------+
|
| 223 |
+
| hit_id | ID of the hit sequence |
|
| 224 |
+
+--------------------+------------------------------------------------------+
|
| 225 |
+
| hit_description | description of the hit sequence |
|
| 226 |
+
+--------------------+------------------------------------------------------+
|
| 227 |
+
| hit_inter_ranges | list of hit sequence coordinates of the regions |
|
| 228 |
+
| | between fragments |
|
| 229 |
+
+--------------------+------------------------------------------------------+
|
| 230 |
+
| hit_inter_spans | list of lengths of the regions between hit fragments |
|
| 231 |
+
+--------------------+------------------------------------------------------+
|
| 232 |
+
| output_index | 0-based index for storing the order by which the HSP |
|
| 233 |
+
| | appears in the output file (default: -1). |
|
| 234 |
+
+--------------------+------------------------------------------------------+
|
| 235 |
+
| query_id | ID of the query sequence |
|
| 236 |
+
+--------------------+------------------------------------------------------+
|
| 237 |
+
| query_description | description of the query sequence |
|
| 238 |
+
+--------------------+------------------------------------------------------+
|
| 239 |
+
| query_inter_ranges | list of query sequence coordinates of the regions |
|
| 240 |
+
| | between fragments |
|
| 241 |
+
+--------------------+------------------------------------------------------+
|
| 242 |
+
| query_inter_spans | list of lengths of the regions between query |
|
| 243 |
+
| | fragments |
|
| 244 |
+
+--------------------+------------------------------------------------------+
|
| 245 |
+
|
| 246 |
+
.. [1] may be used in HSPs with multiple fragments
|
| 247 |
+
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
# attributes we don't want to transfer when creating a new Hit class
|
| 251 |
+
# from this one
|
| 252 |
+
_NON_STICKY_ATTRS = ("_items",)
|
| 253 |
+
|
| 254 |
+
def __init__(self, fragments=(), output_index=-1):
|
| 255 |
+
"""Initialize an HSP object.
|
| 256 |
+
|
| 257 |
+
:param fragments: fragments contained in the HSP object
|
| 258 |
+
:type fragments: iterable yielding HSPFragment
|
| 259 |
+
:param output_index: optional index / ordering of the HSP fragment in
|
| 260 |
+
the original input file.
|
| 261 |
+
:type output_index: integer
|
| 262 |
+
|
| 263 |
+
HSP objects must be initialized with a list containing at least one
|
| 264 |
+
HSPFragment object. If multiple HSPFragment objects are used for
|
| 265 |
+
initialization, they must all have the same ``query_id``,
|
| 266 |
+
``query_description``, ``hit_id``, ``hit_description``, and
|
| 267 |
+
``molecule_type`` properties.
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
if not fragments:
|
| 271 |
+
raise ValueError("HSP objects must have at least one HSPFragment object.")
|
| 272 |
+
# TODO - Move this into the for look in case hsps is a single use
|
| 273 |
+
# iterable?
|
| 274 |
+
# check that all fragments contain the same IDs, descriptions,
|
| 275 |
+
# molecule_type
|
| 276 |
+
for attr in (
|
| 277 |
+
"query_id",
|
| 278 |
+
"query_description",
|
| 279 |
+
"hit_id",
|
| 280 |
+
"hit_description",
|
| 281 |
+
"molecule_type",
|
| 282 |
+
):
|
| 283 |
+
if len({getattr(frag, attr) for frag in fragments}) != 1:
|
| 284 |
+
raise ValueError(
|
| 285 |
+
"HSP object can not contain fragments with more than one %s." % attr
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
self.output_index = output_index
|
| 289 |
+
self._items = []
|
| 290 |
+
for fragment in fragments:
|
| 291 |
+
self._validate_fragment(fragment)
|
| 292 |
+
self._items.append(fragment)
|
| 293 |
+
|
| 294 |
+
def __repr__(self):
|
| 295 |
+
"""Return string representation of HSP object."""
|
| 296 |
+
return "%s(hit_id=%r, query_id=%r, %r fragments)" % (
|
| 297 |
+
self.__class__.__name__,
|
| 298 |
+
self.hit_id,
|
| 299 |
+
self.query_id,
|
| 300 |
+
len(self),
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def __iter__(self):
|
| 304 |
+
"""Iterate over HSP items."""
|
| 305 |
+
return iter(self._items)
|
| 306 |
+
|
| 307 |
+
def __contains__(self, fragment):
|
| 308 |
+
"""Return True if HSPFragment is on HSP items."""
|
| 309 |
+
return fragment in self._items
|
| 310 |
+
|
| 311 |
+
def __len__(self):
|
| 312 |
+
"""Return number of HSPs items."""
|
| 313 |
+
return len(self._items)
|
| 314 |
+
|
| 315 |
+
def __bool__(self):
|
| 316 |
+
"""Return True if it has HSPs."""
|
| 317 |
+
return bool(self._items)
|
| 318 |
+
|
| 319 |
+
def __str__(self):
|
| 320 |
+
"""Return a human readable summary of the HSP object."""
|
| 321 |
+
lines = []
|
| 322 |
+
# set hsp info line
|
| 323 |
+
statline = []
|
| 324 |
+
# evalue
|
| 325 |
+
evalue = getattr_str(self, "evalue", fmt="%.2g")
|
| 326 |
+
statline.append("evalue " + evalue)
|
| 327 |
+
# bitscore
|
| 328 |
+
bitscore = getattr_str(self, "bitscore", fmt="%.2f")
|
| 329 |
+
statline.append("bitscore " + bitscore)
|
| 330 |
+
lines.append("Quick stats: " + "; ".join(statline))
|
| 331 |
+
|
| 332 |
+
if len(self.fragments) == 1:
|
| 333 |
+
return "\n".join(
|
| 334 |
+
[self._str_hsp_header(), "\n".join(lines), self.fragments[0]._str_aln()]
|
| 335 |
+
)
|
| 336 |
+
else:
|
| 337 |
+
lines.append(
|
| 338 |
+
" Fragments: %s %s %s %s" % ("-" * 3, "-" * 14, "-" * 22, "-" * 22)
|
| 339 |
+
)
|
| 340 |
+
pattern = "%16s %14s %22s %22s"
|
| 341 |
+
lines.append(pattern % ("#", "Span", "Query range", "Hit range"))
|
| 342 |
+
lines.append(pattern % ("-" * 3, "-" * 14, "-" * 22, "-" * 22))
|
| 343 |
+
for idx, block in enumerate(self.fragments):
|
| 344 |
+
# set hsp line and table
|
| 345 |
+
# alignment span
|
| 346 |
+
aln_span = getattr_str(block, "aln_span")
|
| 347 |
+
# query region
|
| 348 |
+
query_start = getattr_str(block, "query_start")
|
| 349 |
+
query_end = getattr_str(block, "query_end")
|
| 350 |
+
query_range = "[%s:%s]" % (query_start, query_end)
|
| 351 |
+
# max column length is 20
|
| 352 |
+
query_range = (
|
| 353 |
+
query_range[:20] + "~]" if len(query_range) > 22 else query_range
|
| 354 |
+
)
|
| 355 |
+
# hit region
|
| 356 |
+
hit_start = getattr_str(block, "hit_start")
|
| 357 |
+
hit_end = getattr_str(block, "hit_end")
|
| 358 |
+
hit_range = "[%s:%s]" % (hit_start, hit_end)
|
| 359 |
+
hit_range = hit_range[:20] + "~]" if len(hit_range) > 22 else hit_range
|
| 360 |
+
# append the hsp row
|
| 361 |
+
lines.append(pattern % (str(idx), aln_span, query_range, hit_range))
|
| 362 |
+
|
| 363 |
+
return self._str_hsp_header() + "\n" + "\n".join(lines)
|
| 364 |
+
|
| 365 |
+
def __getitem__(self, idx):
|
| 366 |
+
"""Return object of index idx."""
|
| 367 |
+
# if key is slice, return a new HSP instance
|
| 368 |
+
if isinstance(idx, slice):
|
| 369 |
+
obj = self.__class__(self._items[idx])
|
| 370 |
+
self._transfer_attrs(obj)
|
| 371 |
+
return obj
|
| 372 |
+
return self._items[idx]
|
| 373 |
+
|
| 374 |
+
def __setitem__(self, idx, fragments):
|
| 375 |
+
"""Set an item of index idx with the given fragments."""
|
| 376 |
+
# handle case if hsps is a list of hsp
|
| 377 |
+
if isinstance(fragments, (list, tuple)):
|
| 378 |
+
for fragment in fragments:
|
| 379 |
+
self._validate_fragment(fragment)
|
| 380 |
+
else:
|
| 381 |
+
self._validate_fragment(fragments)
|
| 382 |
+
|
| 383 |
+
self._items[idx] = fragments
|
| 384 |
+
|
| 385 |
+
def __delitem__(self, idx):
|
| 386 |
+
"""Delete item of index idx."""
|
| 387 |
+
# note that this may result in an empty HSP object, which should be
|
| 388 |
+
# invalid
|
| 389 |
+
del self._items[idx]
|
| 390 |
+
|
| 391 |
+
def _validate_fragment(self, fragment):
|
| 392 |
+
if not isinstance(fragment, HSPFragment):
|
| 393 |
+
raise TypeError("HSP objects can only contain HSPFragment objects.")
|
| 394 |
+
# HACK: to make validation during __init__ work
|
| 395 |
+
if self._items:
|
| 396 |
+
if fragment.hit_id != self.hit_id:
|
| 397 |
+
raise ValueError(
|
| 398 |
+
"Expected HSPFragment with hit ID %r, found %r instead."
|
| 399 |
+
% (self.id, fragment.hit_id)
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
if fragment.hit_description != self.hit_description:
|
| 403 |
+
raise ValueError(
|
| 404 |
+
"Expected HSPFragment with hit description %r, found %r instead."
|
| 405 |
+
% (self.description, fragment.hit_description)
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
if fragment.query_id != self.query_id:
|
| 409 |
+
raise ValueError(
|
| 410 |
+
"Expected HSPFragment with query ID %r, found %r instead."
|
| 411 |
+
% (self.query_id, fragment.query_id)
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
if fragment.query_description != self.query_description:
|
| 415 |
+
raise ValueError(
|
| 416 |
+
"Expected HSP with query description %r, found %r instead."
|
| 417 |
+
% (self.query_description, fragment.query_description)
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
def _aln_span_get(self):
|
| 421 |
+
# length of all alignments
|
| 422 |
+
# alignment span can be its own attribute, or computed from
|
| 423 |
+
# query / hit length
|
| 424 |
+
return sum(frg.aln_span for frg in self.fragments)
|
| 425 |
+
|
| 426 |
+
aln_span = property(
|
| 427 |
+
fget=_aln_span_get, doc="Total number of columns in all HSPFragment objects."
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
# coordinate properties #
|
| 431 |
+
def _get_coords(self, seq_type, coord_type):
|
| 432 |
+
assert seq_type in ("hit", "query")
|
| 433 |
+
assert coord_type in ("start", "end")
|
| 434 |
+
coord_name = "%s_%s" % (seq_type, coord_type)
|
| 435 |
+
coords = [getattr(frag, coord_name) for frag in self.fragments]
|
| 436 |
+
if None in coords:
|
| 437 |
+
warnings.warn(
|
| 438 |
+
"'None' exist in %s coordinates; ignored" % (coord_name),
|
| 439 |
+
BiopythonWarning,
|
| 440 |
+
)
|
| 441 |
+
return coords
|
| 442 |
+
|
| 443 |
+
def _hit_start_get(self):
|
| 444 |
+
return min(self._get_coords("hit", "start"))
|
| 445 |
+
|
| 446 |
+
hit_start = property(
|
| 447 |
+
fget=_hit_start_get, doc="Smallest coordinate value of all hit fragments."
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
def _query_start_get(self):
|
| 451 |
+
return min(self._get_coords("query", "start"))
|
| 452 |
+
|
| 453 |
+
query_start = property(
|
| 454 |
+
fget=_query_start_get, doc="Smallest coordinate value of all query fragments."
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
def _hit_end_get(self):
|
| 458 |
+
return max(self._get_coords("hit", "end"))
|
| 459 |
+
|
| 460 |
+
hit_end = property(
|
| 461 |
+
fget=_hit_end_get, doc="Largest coordinate value of all hit fragments."
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
def _query_end_get(self):
|
| 465 |
+
return max(self._get_coords("query", "end"))
|
| 466 |
+
|
| 467 |
+
query_end = property(
|
| 468 |
+
fget=_query_end_get, doc="Largest coordinate value of all hit fragments."
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# coordinate-dependent properties #
|
| 472 |
+
def _hit_span_get(self):
|
| 473 |
+
try:
|
| 474 |
+
return self.hit_end - self.hit_start
|
| 475 |
+
except TypeError: # triggered if any of the coordinates are None
|
| 476 |
+
return None
|
| 477 |
+
|
| 478 |
+
hit_span = property(
|
| 479 |
+
fget=_hit_span_get, doc="The number of hit residues covered by the HSP."
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
def _query_span_get(self):
|
| 483 |
+
try:
|
| 484 |
+
return self.query_end - self.query_start
|
| 485 |
+
except TypeError: # triggered if any of the coordinates are None
|
| 486 |
+
return None
|
| 487 |
+
|
| 488 |
+
query_span = property(
|
| 489 |
+
fget=_query_span_get, doc="The number of query residues covered by the HSP."
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
def _hit_range_get(self):
|
| 493 |
+
return (self.hit_start, self.hit_end)
|
| 494 |
+
|
| 495 |
+
hit_range = property(
|
| 496 |
+
fget=_hit_range_get, doc="Tuple of HSP hit start and end coordinates."
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
def _query_range_get(self):
|
| 500 |
+
return (self.query_start, self.query_end)
|
| 501 |
+
|
| 502 |
+
query_range = property(
|
| 503 |
+
fget=_query_range_get, doc="Tuple of HSP query start and end coordinates."
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
def _inter_ranges_get(self, seq_type):
|
| 507 |
+
# this property assumes that there are no mixed strands in a hit/query
|
| 508 |
+
assert seq_type in ("query", "hit")
|
| 509 |
+
strand = getattr(self, "%s_strand_all" % seq_type)[0]
|
| 510 |
+
coords = getattr(self, "%s_range_all" % seq_type)
|
| 511 |
+
# determine function used to set inter range
|
| 512 |
+
# start and end coordinates, given two pairs
|
| 513 |
+
# of fragment start and end coordinates
|
| 514 |
+
if strand == -1:
|
| 515 |
+
startfunc, endfunc = min, max
|
| 516 |
+
else:
|
| 517 |
+
startfunc, endfunc = max, min
|
| 518 |
+
inter_coords = []
|
| 519 |
+
for idx, coord in enumerate(coords[:-1]):
|
| 520 |
+
start = startfunc(coords[idx])
|
| 521 |
+
end = endfunc(coords[idx + 1])
|
| 522 |
+
inter_coords.append((min(start, end), max(start, end)))
|
| 523 |
+
|
| 524 |
+
return inter_coords
|
| 525 |
+
|
| 526 |
+
def _hit_inter_ranges_get(self):
|
| 527 |
+
return self._inter_ranges_get("hit")
|
| 528 |
+
|
| 529 |
+
hit_inter_ranges = property(
|
| 530 |
+
fget=_hit_inter_ranges_get,
|
| 531 |
+
doc="Hit sequence coordinates of the regions between fragments.",
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
def _query_inter_ranges_get(self):
|
| 535 |
+
return self._inter_ranges_get("query")
|
| 536 |
+
|
| 537 |
+
query_inter_ranges = property(
|
| 538 |
+
fget=_query_inter_ranges_get,
|
| 539 |
+
doc="Query sequence coordinates of the regions between fragments.",
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
def _inter_spans_get(self, seq_type):
|
| 543 |
+
assert seq_type in ("query", "hit")
|
| 544 |
+
attr_name = "%s_inter_ranges" % seq_type
|
| 545 |
+
return [coord[1] - coord[0] for coord in getattr(self, attr_name)]
|
| 546 |
+
|
| 547 |
+
def _hit_inter_spans_get(self):
|
| 548 |
+
return self._inter_spans_get("hit")
|
| 549 |
+
|
| 550 |
+
hit_inter_spans = property(
|
| 551 |
+
fget=_hit_inter_spans_get, doc="Lengths of regions between hit fragments."
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
def _query_inter_spans_get(self):
|
| 555 |
+
return self._inter_spans_get("query")
|
| 556 |
+
|
| 557 |
+
query_inter_spans = property(
|
| 558 |
+
fget=_query_inter_spans_get, doc="Lengths of regions between query fragments."
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
# shortcuts for fragments' properties #
|
| 562 |
+
|
| 563 |
+
# bool check if there's more than one fragments
|
| 564 |
+
is_fragmented = property(
|
| 565 |
+
lambda self: len(self) > 1,
|
| 566 |
+
doc="Whether the HSP has more than one HSPFragment objects.",
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# first item properties with setters
|
| 570 |
+
hit_description = fullcascade(
|
| 571 |
+
"hit_description", doc="Description of the hit sequence."
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
query_description = fullcascade(
|
| 575 |
+
"query_description", doc="Description of the query sequence."
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
hit_id = fullcascade("hit_id", doc="ID of the hit sequence.")
|
| 579 |
+
|
| 580 |
+
query_id = fullcascade("query_id", doc="ID of the query sequence.")
|
| 581 |
+
|
| 582 |
+
molecule_type = fullcascade(
|
| 583 |
+
"molecule_type", doc="molecule_type of the hit and query SeqRecord objects."
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# properties for single-fragment HSPs
|
| 587 |
+
fragment = singleitem(doc="HSPFragment object, first fragment.")
|
| 588 |
+
|
| 589 |
+
hit = singleitem("hit", doc="Hit sequence as a SeqRecord object, first fragment.")
|
| 590 |
+
|
| 591 |
+
query = singleitem(
|
| 592 |
+
"query", doc="Query sequence as a SeqRecord object, first fragment."
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
aln = singleitem(
|
| 596 |
+
"aln", doc="Alignment of the first fragment as a MultipleSeqAlignment object."
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
aln_annotation = singleitem(
|
| 600 |
+
"aln_annotation",
|
| 601 |
+
doc="Dictionary of annotation(s) of the first fragment's alignment.",
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
hit_features = singleitem(
|
| 605 |
+
"hit_features", doc="Hit sequence features, first fragment."
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
query_features = singleitem(
|
| 609 |
+
"query_features", doc="Query sequence features, first fragment."
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
hit_strand = singleitem("hit_strand", doc="Hit strand orientation, first fragment.")
|
| 613 |
+
|
| 614 |
+
query_strand = singleitem(
|
| 615 |
+
"query_strand", doc="Query strand orientation, first fragment."
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
hit_frame = singleitem(
|
| 619 |
+
"hit_frame", doc="Hit sequence reading frame, first fragment."
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
query_frame = singleitem(
|
| 623 |
+
"query_frame", doc="Query sequence reading frame, first fragment."
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
# properties for multi-fragment HSPs
|
| 627 |
+
fragments = allitems(doc="List of all HSPFragment objects.")
|
| 628 |
+
|
| 629 |
+
hit_all = allitems(
|
| 630 |
+
"hit", doc="List of all fragments' hit sequences as SeqRecord objects."
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
query_all = allitems(
|
| 634 |
+
"query", doc="List of all fragments' query sequences as SeqRecord objects."
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
aln_all = allitems(
|
| 638 |
+
"aln", doc="List of all fragments' alignments as MultipleSeqAlignment objects."
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
aln_annotation_all = allitems(
|
| 642 |
+
"aln_annotation",
|
| 643 |
+
doc="Dictionary of annotation(s) of all fragments' alignments.",
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
hit_features_all = allitems(
|
| 647 |
+
"hit_features", doc="List of all hit sequence features."
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
query_features_all = allitems(
|
| 651 |
+
"query_features", doc="List of all query sequence features."
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
hit_strand_all = allitems(
|
| 655 |
+
"hit_strand", doc="List of all fragments' hit sequence strands."
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
query_strand_all = allitems(
|
| 659 |
+
"query_strand", doc="List of all fragments' query sequence strands"
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
hit_frame_all = allitems(
|
| 663 |
+
"hit_frame", doc="List of all fragments' hit sequence reading frames."
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
query_frame_all = allitems(
|
| 667 |
+
"query_frame", doc="List of all fragments' query sequence reading frames."
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
hit_start_all = allitems(
|
| 671 |
+
"hit_start", doc="List of all fragments' hit start coordinates."
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
query_start_all = allitems(
|
| 675 |
+
"query_start", doc="List of all fragments' query start coordinates."
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
hit_end_all = allitems("hit_end", doc="List of all fragments' hit end coordinates.")
|
| 679 |
+
|
| 680 |
+
query_end_all = allitems(
|
| 681 |
+
"query_end", doc="List of all fragments' query end coordinates."
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
hit_span_all = allitems("hit_span", doc="List of all fragments' hit sequence size.")
|
| 685 |
+
|
| 686 |
+
query_span_all = allitems(
|
| 687 |
+
"query_span", doc="List of all fragments' query sequence size."
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
hit_range_all = allitems(
|
| 691 |
+
"hit_range", doc="List of all fragments' hit start and end coordinates."
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
query_range_all = allitems(
|
| 695 |
+
"query_range", doc="List of all fragments' query start and end coordinates."
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
class HSPFragment(_BaseHSP):
|
| 700 |
+
"""Class representing a contiguous alignment of hit-query sequence.
|
| 701 |
+
|
| 702 |
+
HSPFragment forms the core of any parsed search output file. Depending on
|
| 703 |
+
the search output file format, it may contain the actual query and/or hit
|
| 704 |
+
sequences that produces the search hits. These sequences are stored as
|
| 705 |
+
SeqRecord objects (see SeqRecord):
|
| 706 |
+
|
| 707 |
+
>>> from Bio import SearchIO
|
| 708 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 709 |
+
>>> fragment = qresult[0][0][0] # first hit, first hsp, first fragment
|
| 710 |
+
>>> print(fragment)
|
| 711 |
+
Query: 33211 mir_1
|
| 712 |
+
Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520...
|
| 713 |
+
Query range: [0:61] (1)
|
| 714 |
+
Hit range: [0:61] (1)
|
| 715 |
+
Fragments: 1 (61 columns)
|
| 716 |
+
Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|
| 717 |
+
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| 718 |
+
Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|
| 719 |
+
|
| 720 |
+
# the query sequence is a SeqRecord object
|
| 721 |
+
>>> fragment.query.__class__
|
| 722 |
+
<class 'Bio.SeqRecord.SeqRecord'>
|
| 723 |
+
>>> print(fragment.query)
|
| 724 |
+
ID: 33211
|
| 725 |
+
Name: aligned query sequence
|
| 726 |
+
Description: mir_1
|
| 727 |
+
Number of features: 0
|
| 728 |
+
/molecule_type=DNA
|
| 729 |
+
Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG')
|
| 730 |
+
|
| 731 |
+
# the hit sequence is a SeqRecord object as well
|
| 732 |
+
>>> fragment.hit.__class__
|
| 733 |
+
<class 'Bio.SeqRecord.SeqRecord'>
|
| 734 |
+
>>> print(fragment.hit)
|
| 735 |
+
ID: gi|262205317|ref|NR_030195.1|
|
| 736 |
+
Name: aligned hit sequence
|
| 737 |
+
Description: Homo sapiens microRNA 520b (MIR520B), microRNA
|
| 738 |
+
Number of features: 0
|
| 739 |
+
/molecule_type=DNA
|
| 740 |
+
Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG')
|
| 741 |
+
|
| 742 |
+
# when both query and hit are present, we get a MultipleSeqAlignment object
|
| 743 |
+
>>> fragment.aln.__class__
|
| 744 |
+
<class 'Bio.Align.MultipleSeqAlignment'>
|
| 745 |
+
>>> print(fragment.aln)
|
| 746 |
+
Alignment with 2 rows and 61 columns
|
| 747 |
+
CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 33211
|
| 748 |
+
CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1|
|
| 749 |
+
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
def __init__(
|
| 753 |
+
self,
|
| 754 |
+
hit_id="<unknown id>",
|
| 755 |
+
query_id="<unknown id>",
|
| 756 |
+
hit=None,
|
| 757 |
+
query=None,
|
| 758 |
+
molecule_type=None,
|
| 759 |
+
):
|
| 760 |
+
"""Initialize the class."""
|
| 761 |
+
self._molecule_type = molecule_type
|
| 762 |
+
self.aln_annotation = {}
|
| 763 |
+
|
| 764 |
+
self._hit_id = hit_id
|
| 765 |
+
self._query_id = query_id
|
| 766 |
+
|
| 767 |
+
for seq_type in ("query", "hit"):
|
| 768 |
+
# query or hit attributes default attributes
|
| 769 |
+
setattr(self, "_%s_description" % seq_type, "<unknown description>")
|
| 770 |
+
setattr(self, "_%s_features" % seq_type, [])
|
| 771 |
+
# query or hit attributes whose default attribute is None
|
| 772 |
+
for attr in ("strand", "frame", "start", "end"):
|
| 773 |
+
setattr(self, "%s_%s" % (seq_type, attr), None)
|
| 774 |
+
# self.query or self.hit
|
| 775 |
+
if eval(seq_type):
|
| 776 |
+
setattr(self, seq_type, eval(seq_type))
|
| 777 |
+
else:
|
| 778 |
+
setattr(self, seq_type, None)
|
| 779 |
+
|
| 780 |
+
def __repr__(self):
|
| 781 |
+
"""Return HSPFragment info; hit id, query id, number of columns."""
|
| 782 |
+
info = "hit_id=%r, query_id=%r" % (self.hit_id, self.query_id)
|
| 783 |
+
try:
|
| 784 |
+
info += ", %i columns" % len(self)
|
| 785 |
+
except AttributeError:
|
| 786 |
+
pass
|
| 787 |
+
return "%s(%s)" % (self.__class__.__name__, info)
|
| 788 |
+
|
| 789 |
+
def __len__(self):
|
| 790 |
+
"""Return alignment span."""
|
| 791 |
+
return self.aln_span
|
| 792 |
+
|
| 793 |
+
def __str__(self):
|
| 794 |
+
"""Return string of HSP header and alignments."""
|
| 795 |
+
return self._str_hsp_header() + "\n" + self._str_aln()
|
| 796 |
+
|
| 797 |
+
def __getitem__(self, idx):
|
| 798 |
+
"""Return object of index idx."""
|
| 799 |
+
if self.aln is not None:
|
| 800 |
+
obj = self.__class__(
|
| 801 |
+
hit_id=self.hit_id,
|
| 802 |
+
query_id=self.query_id,
|
| 803 |
+
molecule_type=self.molecule_type,
|
| 804 |
+
)
|
| 805 |
+
# transfer query and hit attributes
|
| 806 |
+
# let SeqRecord handle feature slicing, then retrieve the sliced
|
| 807 |
+
# features into the sliced HSPFragment
|
| 808 |
+
if self.query is not None:
|
| 809 |
+
obj.query = self.query[idx]
|
| 810 |
+
obj.query_features = obj.query.features
|
| 811 |
+
if self.hit is not None:
|
| 812 |
+
obj.hit = self.hit[idx]
|
| 813 |
+
obj.hit_features = obj.hit.features
|
| 814 |
+
# description, strand, frame
|
| 815 |
+
for attr in ("description", "strand", "frame"):
|
| 816 |
+
for seq_type in ("hit", "query"):
|
| 817 |
+
attr_name = "%s_%s" % (seq_type, attr)
|
| 818 |
+
self_val = getattr(self, attr_name)
|
| 819 |
+
setattr(obj, attr_name, self_val)
|
| 820 |
+
# alignment annotation should be transferred, since we can compute
|
| 821 |
+
# the resulting annotation
|
| 822 |
+
obj.aln_annotation = {}
|
| 823 |
+
for key, value in self.aln_annotation.items():
|
| 824 |
+
assert len(value[idx]) == len(obj)
|
| 825 |
+
obj.aln_annotation[key] = value[idx]
|
| 826 |
+
return obj
|
| 827 |
+
else:
|
| 828 |
+
raise TypeError(
|
| 829 |
+
"Slicing for HSP objects without alignment is not supported."
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
def _str_aln(self):
|
| 833 |
+
lines = []
|
| 834 |
+
# alignment length
|
| 835 |
+
aln_span = getattr_str(self, "aln_span")
|
| 836 |
+
lines.append(" Fragments: 1 (%s columns)" % aln_span)
|
| 837 |
+
# sequences
|
| 838 |
+
if self.query is not None and self.hit is not None:
|
| 839 |
+
try:
|
| 840 |
+
qseq = self.query.seq
|
| 841 |
+
except AttributeError: # query is None
|
| 842 |
+
qseq = "?"
|
| 843 |
+
try:
|
| 844 |
+
hseq = self.hit.seq
|
| 845 |
+
except AttributeError: # hit is None
|
| 846 |
+
hseq = "?"
|
| 847 |
+
|
| 848 |
+
# similarity line
|
| 849 |
+
simil = ""
|
| 850 |
+
if "similarity" in self.aln_annotation and isinstance(
|
| 851 |
+
self.aln_annotation.get("similarity"), str
|
| 852 |
+
):
|
| 853 |
+
simil = self.aln_annotation["similarity"]
|
| 854 |
+
|
| 855 |
+
if self.aln_span <= 67:
|
| 856 |
+
lines.append("%10s - %s" % ("Query", qseq))
|
| 857 |
+
if simil:
|
| 858 |
+
lines.append(" %s" % simil)
|
| 859 |
+
lines.append("%10s - %s" % ("Hit", hseq))
|
| 860 |
+
else:
|
| 861 |
+
# adjust continuation character length, so we don't display
|
| 862 |
+
# the same residues twice
|
| 863 |
+
if self.aln_span - 66 > 3:
|
| 864 |
+
cont = "~" * 3
|
| 865 |
+
else:
|
| 866 |
+
cont = "~" * (self.aln_span - 66)
|
| 867 |
+
lines.append("%10s - %s%s%s" % ("Query", qseq[:59], cont, qseq[-5:]))
|
| 868 |
+
if simil:
|
| 869 |
+
lines.append(" %s%s%s" % (simil[:59], cont, simil[-5:]))
|
| 870 |
+
lines.append("%10s - %s%s%s" % ("Hit", hseq[:59], cont, hseq[-5:]))
|
| 871 |
+
|
| 872 |
+
return "\n".join(lines)
|
| 873 |
+
|
| 874 |
+
# sequence properties #
|
| 875 |
+
def _set_seq(self, seq, seq_type):
|
| 876 |
+
"""Check the given sequence for attribute setting (PRIVATE).
|
| 877 |
+
|
| 878 |
+
:param seq: sequence to check
|
| 879 |
+
:type seq: string or SeqRecord
|
| 880 |
+
:param seq_type: sequence type
|
| 881 |
+
:type seq_type: string, choice of 'hit' or 'query'
|
| 882 |
+
|
| 883 |
+
"""
|
| 884 |
+
assert seq_type in ("hit", "query")
|
| 885 |
+
if seq is None:
|
| 886 |
+
return seq # return immediately if seq is None
|
| 887 |
+
else:
|
| 888 |
+
if not isinstance(seq, (str, SeqRecord)):
|
| 889 |
+
raise TypeError(
|
| 890 |
+
"%s sequence must be a string or a SeqRecord object." % seq_type
|
| 891 |
+
)
|
| 892 |
+
# check length if the opposite sequence is not None
|
| 893 |
+
opp_type = "hit" if seq_type == "query" else "query"
|
| 894 |
+
opp_seq = getattr(self, "_%s" % opp_type, None)
|
| 895 |
+
if opp_seq is not None:
|
| 896 |
+
if len(seq) != len(opp_seq):
|
| 897 |
+
raise ValueError(
|
| 898 |
+
"Sequence lengths do not match. Expected: %r (%s); found: %r (%s)."
|
| 899 |
+
% (len(opp_seq), opp_type, len(seq), seq_type)
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
seq_id = getattr(self, "%s_id" % seq_type)
|
| 903 |
+
seq_desc = getattr(self, "%s_description" % seq_type)
|
| 904 |
+
seq_feats = getattr(self, "%s_features" % seq_type)
|
| 905 |
+
seq_name = "aligned %s sequence" % seq_type
|
| 906 |
+
|
| 907 |
+
if isinstance(seq, SeqRecord):
|
| 908 |
+
seq.id = seq_id
|
| 909 |
+
seq.description = seq_desc
|
| 910 |
+
seq.name = seq_name
|
| 911 |
+
seq.features = seq_feats
|
| 912 |
+
seq.annotations["molecule_type"] = self.molecule_type
|
| 913 |
+
elif isinstance(seq, str):
|
| 914 |
+
seq = SeqRecord(
|
| 915 |
+
Seq(seq),
|
| 916 |
+
id=seq_id,
|
| 917 |
+
name=seq_name,
|
| 918 |
+
description=seq_desc,
|
| 919 |
+
features=seq_feats,
|
| 920 |
+
annotations={"molecule_type": self.molecule_type},
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
return seq
|
| 924 |
+
|
| 925 |
+
def _hit_get(self):
|
| 926 |
+
return self._hit
|
| 927 |
+
|
| 928 |
+
def _hit_set(self, value):
|
| 929 |
+
self._hit = self._set_seq(value, "hit")
|
| 930 |
+
|
| 931 |
+
hit = property(
|
| 932 |
+
fget=_hit_get,
|
| 933 |
+
fset=_hit_set,
|
| 934 |
+
doc="Hit sequence as a SeqRecord object, defaults to None.",
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
def _query_get(self):
|
| 938 |
+
return self._query
|
| 939 |
+
|
| 940 |
+
def _query_set(self, value):
|
| 941 |
+
self._query = self._set_seq(value, "query")
|
| 942 |
+
|
| 943 |
+
query = property(
|
| 944 |
+
fget=_query_get,
|
| 945 |
+
fset=_query_set,
|
| 946 |
+
doc="Query sequence as a SeqRecord object, defaults to None.",
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
def _aln_get(self):
|
| 950 |
+
if self.query is None and self.hit is None:
|
| 951 |
+
return None
|
| 952 |
+
if self.hit is None:
|
| 953 |
+
msa = MultipleSeqAlignment([self.query])
|
| 954 |
+
elif self.query is None:
|
| 955 |
+
msa = MultipleSeqAlignment([self.hit])
|
| 956 |
+
else:
|
| 957 |
+
msa = MultipleSeqAlignment([self.query, self.hit])
|
| 958 |
+
molecule_type = self.molecule_type
|
| 959 |
+
if molecule_type is not None:
|
| 960 |
+
msa.molecule_type = molecule_type
|
| 961 |
+
return msa
|
| 962 |
+
|
| 963 |
+
aln = property(
|
| 964 |
+
fget=_aln_get,
|
| 965 |
+
doc="Query-hit alignment as a MultipleSeqAlignment object, defaults to None.",
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
def _molecule_type_get(self):
|
| 969 |
+
return self._molecule_type
|
| 970 |
+
|
| 971 |
+
def _molecule_type_set(self, value):
|
| 972 |
+
self._molecule_type = value
|
| 973 |
+
try:
|
| 974 |
+
self.query.annotations["molecule_type"] = value
|
| 975 |
+
except AttributeError:
|
| 976 |
+
pass
|
| 977 |
+
try:
|
| 978 |
+
self.hit.annotations["molecule_type"] = value
|
| 979 |
+
except AttributeError:
|
| 980 |
+
pass
|
| 981 |
+
|
| 982 |
+
molecule_type = property(
|
| 983 |
+
fget=_molecule_type_get,
|
| 984 |
+
fset=_molecule_type_set,
|
| 985 |
+
doc="molecule type used in the fragment's "
|
| 986 |
+
"sequence records and alignment, defaults to None.",
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
def _aln_span_get(self):
|
| 990 |
+
# length of alignment (gaps included)
|
| 991 |
+
# alignment span can be its own attribute, or computed from
|
| 992 |
+
# query / hit length
|
| 993 |
+
try:
|
| 994 |
+
self._aln_span
|
| 995 |
+
except AttributeError:
|
| 996 |
+
if self.query is not None:
|
| 997 |
+
self._aln_span = len(self.query)
|
| 998 |
+
elif self.hit is not None:
|
| 999 |
+
self._aln_span = len(self.hit)
|
| 1000 |
+
|
| 1001 |
+
return self._aln_span
|
| 1002 |
+
|
| 1003 |
+
def _aln_span_set(self, value):
|
| 1004 |
+
self._aln_span = value
|
| 1005 |
+
|
| 1006 |
+
aln_span = property(
|
| 1007 |
+
fget=_aln_span_get,
|
| 1008 |
+
fset=_aln_span_set,
|
| 1009 |
+
doc="The number of alignment columns covered by the fragment.",
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
# id, description, and features properties #
|
| 1013 |
+
hit_description = fragcascade("description", "hit", doc="Hit sequence description.")
|
| 1014 |
+
|
| 1015 |
+
query_description = fragcascade(
|
| 1016 |
+
"description", "query", doc="Query sequence description."
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
hit_id = fragcascade("id", "hit", doc="Hit sequence ID.")
|
| 1020 |
+
|
| 1021 |
+
query_id = fragcascade("id", "query", doc="Query sequence ID.")
|
| 1022 |
+
|
| 1023 |
+
hit_features = fragcascade("features", "hit", doc="Hit sequence features.")
|
| 1024 |
+
|
| 1025 |
+
query_features = fragcascade("features", "query", doc="Query sequence features.")
|
| 1026 |
+
|
| 1027 |
+
# strand properties #
|
| 1028 |
+
def _prep_strand(self, strand):
|
| 1029 |
+
# follow SeqFeature's convention
|
| 1030 |
+
if strand not in (-1, 0, 1, None):
|
| 1031 |
+
raise ValueError("Strand should be -1, 0, 1, or None; not %r" % strand)
|
| 1032 |
+
return strand
|
| 1033 |
+
|
| 1034 |
+
def _get_strand(self, seq_type):
|
| 1035 |
+
assert seq_type in ("hit", "query")
|
| 1036 |
+
strand = getattr(self, "_%s_strand" % seq_type)
|
| 1037 |
+
|
| 1038 |
+
if strand is None:
|
| 1039 |
+
# try to compute strand from frame
|
| 1040 |
+
frame = getattr(self, "%s_frame" % seq_type)
|
| 1041 |
+
if frame is not None:
|
| 1042 |
+
try:
|
| 1043 |
+
strand = frame // abs(frame)
|
| 1044 |
+
except ZeroDivisionError:
|
| 1045 |
+
strand = 0
|
| 1046 |
+
setattr(self, "%s_strand" % seq_type, strand)
|
| 1047 |
+
|
| 1048 |
+
return strand
|
| 1049 |
+
|
| 1050 |
+
def _hit_strand_get(self):
|
| 1051 |
+
return self._get_strand("hit")
|
| 1052 |
+
|
| 1053 |
+
def _hit_strand_set(self, value):
|
| 1054 |
+
self._hit_strand = self._prep_strand(value)
|
| 1055 |
+
|
| 1056 |
+
hit_strand = property(
|
| 1057 |
+
fget=_hit_strand_get,
|
| 1058 |
+
fset=_hit_strand_set,
|
| 1059 |
+
doc="Hit sequence strand, defaults to None.",
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
def _query_strand_get(self):
|
| 1063 |
+
return self._get_strand("query")
|
| 1064 |
+
|
| 1065 |
+
def _query_strand_set(self, value):
|
| 1066 |
+
self._query_strand = self._prep_strand(value)
|
| 1067 |
+
|
| 1068 |
+
query_strand = property(
|
| 1069 |
+
fget=_query_strand_get,
|
| 1070 |
+
fset=_query_strand_set,
|
| 1071 |
+
doc="Query sequence strand, defaults to None.",
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
# frame properties #
|
| 1075 |
+
def _prep_frame(self, frame):
|
| 1076 |
+
if frame not in (-3, -2, -1, 0, 1, 2, 3, None):
|
| 1077 |
+
raise ValueError(
|
| 1078 |
+
"Strand should be an integer between -3 and 3, or None; not %r" % frame
|
| 1079 |
+
)
|
| 1080 |
+
return frame
|
| 1081 |
+
|
| 1082 |
+
def _hit_frame_get(self):
|
| 1083 |
+
return self._hit_frame
|
| 1084 |
+
|
| 1085 |
+
def _hit_frame_set(self, value):
|
| 1086 |
+
self._hit_frame = self._prep_frame(value)
|
| 1087 |
+
|
| 1088 |
+
hit_frame = property(
|
| 1089 |
+
fget=_hit_frame_get,
|
| 1090 |
+
fset=_hit_frame_set,
|
| 1091 |
+
doc="Hit sequence reading frame, defaults to None.",
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
def _query_frame_get(self):
|
| 1095 |
+
"""Get query sequence reading frame (PRIVATE)."""
|
| 1096 |
+
return self._query_frame
|
| 1097 |
+
|
| 1098 |
+
def _query_frame_set(self, value):
|
| 1099 |
+
"""Set query sequence reading frame (PRIVATE)."""
|
| 1100 |
+
self._query_frame = self._prep_frame(value)
|
| 1101 |
+
|
| 1102 |
+
query_frame = property(
|
| 1103 |
+
fget=_query_frame_get,
|
| 1104 |
+
fset=_query_frame_set,
|
| 1105 |
+
doc="Query sequence reading frame, defaults to None.",
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
# coordinate properties #
|
| 1109 |
+
def _prep_coord(self, coord, opp_coord_name, op):
|
| 1110 |
+
# coord must either be None or int
|
| 1111 |
+
if coord is None:
|
| 1112 |
+
return coord
|
| 1113 |
+
assert isinstance(coord, int)
|
| 1114 |
+
# try to get opposite coordinate, if it's not present, return
|
| 1115 |
+
try:
|
| 1116 |
+
opp_coord = getattr(self, opp_coord_name)
|
| 1117 |
+
except AttributeError:
|
| 1118 |
+
return coord
|
| 1119 |
+
# if opposite coordinate is None, return
|
| 1120 |
+
if opp_coord is None:
|
| 1121 |
+
return coord
|
| 1122 |
+
# otherwise compare it to coord ('>=' or '<=')
|
| 1123 |
+
else:
|
| 1124 |
+
assert op(coord, opp_coord)
|
| 1125 |
+
return coord
|
| 1126 |
+
|
| 1127 |
+
def _hit_start_get(self):
|
| 1128 |
+
"""Get the sequence hit start coordinate (PRIVATE)."""
|
| 1129 |
+
return self._hit_start
|
| 1130 |
+
|
| 1131 |
+
def _hit_start_set(self, value):
|
| 1132 |
+
"""Set the sequence hit start coordinate (PRIVATE)."""
|
| 1133 |
+
self._hit_start = self._prep_coord(value, "hit_end", le)
|
| 1134 |
+
|
| 1135 |
+
hit_start = property(
|
| 1136 |
+
fget=_hit_start_get,
|
| 1137 |
+
fset=_hit_start_set,
|
| 1138 |
+
doc="Hit sequence start coordinate, defaults to None.",
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
def _query_start_get(self):
|
| 1142 |
+
"""Get the query sequence start coordinate (PRIVATE)."""
|
| 1143 |
+
return self._query_start
|
| 1144 |
+
|
| 1145 |
+
def _query_start_set(self, value):
|
| 1146 |
+
"""Set the query sequence start coordinate (PRIVATE)."""
|
| 1147 |
+
self._query_start = self._prep_coord(value, "query_end", le)
|
| 1148 |
+
|
| 1149 |
+
query_start = property(
|
| 1150 |
+
fget=_query_start_get,
|
| 1151 |
+
fset=_query_start_set,
|
| 1152 |
+
doc="Query sequence start coordinate, defaults to None.",
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
def _hit_end_get(self):
|
| 1156 |
+
"""Get the hit sequence end coordinate (PRIVATE)."""
|
| 1157 |
+
return self._hit_end
|
| 1158 |
+
|
| 1159 |
+
def _hit_end_set(self, value):
|
| 1160 |
+
"""Set the hit sequence end coordinate (PRIVATE)."""
|
| 1161 |
+
self._hit_end = self._prep_coord(value, "hit_start", ge)
|
| 1162 |
+
|
| 1163 |
+
hit_end = property(
|
| 1164 |
+
fget=_hit_end_get,
|
| 1165 |
+
fset=_hit_end_set,
|
| 1166 |
+
doc="Hit sequence end coordinate, defaults to None.",
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
def _query_end_get(self):
|
| 1170 |
+
"""Get the query sequence end coordinate (PRIVATE)."""
|
| 1171 |
+
return self._query_end
|
| 1172 |
+
|
| 1173 |
+
def _query_end_set(self, value):
|
| 1174 |
+
"""Set the query sequence end coordinate (PRIVATE)."""
|
| 1175 |
+
self._query_end = self._prep_coord(value, "query_start", ge)
|
| 1176 |
+
|
| 1177 |
+
query_end = property(
|
| 1178 |
+
fget=_query_end_get,
|
| 1179 |
+
fset=_query_end_set,
|
| 1180 |
+
doc="Query sequence end coordinate, defaults to None.",
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
# coordinate-dependent properties #
|
| 1184 |
+
def _hit_span_get(self):
|
| 1185 |
+
"""Return the number of residues covered by the hit sequence (PRIVATE)."""
|
| 1186 |
+
try:
|
| 1187 |
+
return self.hit_end - self.hit_start
|
| 1188 |
+
except TypeError: # triggered if any of the coordinates are None
|
| 1189 |
+
return None
|
| 1190 |
+
|
| 1191 |
+
hit_span = property(
|
| 1192 |
+
fget=_hit_span_get, doc="The number of residues covered by the hit sequence."
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
def _query_span_get(self):
|
| 1196 |
+
"""Return the number or residues covered by the query (PRIVATE)."""
|
| 1197 |
+
try:
|
| 1198 |
+
return self.query_end - self.query_start
|
| 1199 |
+
except TypeError: # triggered if any of the coordinates are None
|
| 1200 |
+
return None
|
| 1201 |
+
|
| 1202 |
+
query_span = property(
|
| 1203 |
+
fget=_query_span_get,
|
| 1204 |
+
doc="The number of residues covered by the query sequence.",
|
| 1205 |
+
)
|
| 1206 |
+
|
| 1207 |
+
def _hit_range_get(self):
|
| 1208 |
+
"""Return the start and end of a hit (PRIVATE)."""
|
| 1209 |
+
return (self.hit_start, self.hit_end)
|
| 1210 |
+
|
| 1211 |
+
hit_range = property(
|
| 1212 |
+
fget=_hit_range_get, doc="Tuple of hit start and end coordinates."
|
| 1213 |
+
)
|
| 1214 |
+
|
| 1215 |
+
def _query_range_get(self):
|
| 1216 |
+
"""Return the start and end of a query (PRIVATE)."""
|
| 1217 |
+
return (self.query_start, self.query_end)
|
| 1218 |
+
|
| 1219 |
+
query_range = property(
|
| 1220 |
+
fget=_query_range_get, doc="Tuple of query start and end coordinates."
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
|
| 1224 |
+
# if not used as a module, run the doctest
|
| 1225 |
+
if __name__ == "__main__":
|
| 1226 |
+
from Bio._utils import run_doctest
|
| 1227 |
+
|
| 1228 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/query.py
ADDED
|
@@ -0,0 +1,737 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Bio.SearchIO object to model search results from a single query."""
|
| 7 |
+
|
| 8 |
+
from copy import deepcopy
|
| 9 |
+
from itertools import chain
|
| 10 |
+
|
| 11 |
+
from Bio.SearchIO._utils import optionalcascade
|
| 12 |
+
|
| 13 |
+
from ._base import _BaseSearchObject
|
| 14 |
+
from .hit import Hit
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class QueryResult(_BaseSearchObject):
|
| 18 |
+
"""Class representing search results from a single query.
|
| 19 |
+
|
| 20 |
+
QueryResult is the container object that stores all search hits from a
|
| 21 |
+
single search query. It is the top-level object returned by SearchIO's two
|
| 22 |
+
main functions, ``read`` and ``parse``. Depending on the search results and
|
| 23 |
+
search output format, a QueryResult object will contain zero or more Hit
|
| 24 |
+
objects (see Hit).
|
| 25 |
+
|
| 26 |
+
You can take a quick look at a QueryResult's contents and attributes by
|
| 27 |
+
invoking ``print`` on it::
|
| 28 |
+
|
| 29 |
+
>>> from Bio import SearchIO
|
| 30 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 31 |
+
>>> print(qresult)
|
| 32 |
+
Program: blastn (2.2.27+)
|
| 33 |
+
Query: 33211 (61)
|
| 34 |
+
mir_1
|
| 35 |
+
Target: refseq_rna
|
| 36 |
+
Hits: ---- ----- ----------------------------------------------------------
|
| 37 |
+
# # HSP ID + description
|
| 38 |
+
---- ----- ----------------------------------------------------------
|
| 39 |
+
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
|
| 40 |
+
1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA...
|
| 41 |
+
2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ...
|
| 42 |
+
3 2 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA...
|
| 43 |
+
4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA...
|
| 44 |
+
5 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52...
|
| 45 |
+
6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51...
|
| 46 |
+
7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA...
|
| 47 |
+
8 1 gi|262205451|ref|NR_030222.1| Homo sapiens microRNA 51...
|
| 48 |
+
9 2 gi|301171447|ref|NR_035871.1| Pan troglodytes microRNA...
|
| 49 |
+
10 1 gi|301171276|ref|NR_035852.1| Pan troglodytes microRNA...
|
| 50 |
+
11 1 gi|262205290|ref|NR_030188.1| Homo sapiens microRNA 51...
|
| 51 |
+
...
|
| 52 |
+
|
| 53 |
+
If you just want to know how many hits a QueryResult has, you can invoke
|
| 54 |
+
``len`` on it. Alternatively, you can simply type its name in the interpreter::
|
| 55 |
+
|
| 56 |
+
>>> len(qresult)
|
| 57 |
+
100
|
| 58 |
+
>>> qresult
|
| 59 |
+
QueryResult(id='33211', 100 hits)
|
| 60 |
+
|
| 61 |
+
QueryResult behaves like a hybrid of Python's built-in list and dictionary.
|
| 62 |
+
You can retrieve its items (Hit objects) using the integer index of the
|
| 63 |
+
item, just like regular Python lists::
|
| 64 |
+
|
| 65 |
+
>>> first_hit = qresult[0]
|
| 66 |
+
>>> first_hit
|
| 67 |
+
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps)
|
| 68 |
+
|
| 69 |
+
You can slice QueryResult objects as well. Slicing will return a new
|
| 70 |
+
QueryResult object containing only the sliced hits::
|
| 71 |
+
|
| 72 |
+
>>> sliced_qresult = qresult[:3] # slice the first three hits
|
| 73 |
+
>>> len(qresult)
|
| 74 |
+
100
|
| 75 |
+
>>> len(sliced_qresult)
|
| 76 |
+
3
|
| 77 |
+
>>> print(sliced_qresult)
|
| 78 |
+
Program: blastn (2.2.27+)
|
| 79 |
+
Query: 33211 (61)
|
| 80 |
+
mir_1
|
| 81 |
+
Target: refseq_rna
|
| 82 |
+
Hits: ---- ----- ----------------------------------------------------------
|
| 83 |
+
# # HSP ID + description
|
| 84 |
+
---- ----- ----------------------------------------------------------
|
| 85 |
+
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
|
| 86 |
+
1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA...
|
| 87 |
+
2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ...
|
| 88 |
+
|
| 89 |
+
Like Python dictionaries, you can also retrieve hits using the hit's ID.
|
| 90 |
+
This is useful for retrieving hits that you know should exist in a given
|
| 91 |
+
search::
|
| 92 |
+
|
| 93 |
+
>>> hit = qresult['gi|262205317|ref|NR_030195.1|']
|
| 94 |
+
>>> hit
|
| 95 |
+
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps)
|
| 96 |
+
|
| 97 |
+
You can also replace a Hit in QueryResult with another Hit using either the
|
| 98 |
+
integer index or hit key string. Note that the replacing object must be a
|
| 99 |
+
Hit that has the same ``query_id`` property as the QueryResult object.
|
| 100 |
+
|
| 101 |
+
If you're not sure whether a QueryResult contains a particular hit, you can
|
| 102 |
+
use the hit ID to check for membership first::
|
| 103 |
+
|
| 104 |
+
>>> 'gi|262205317|ref|NR_030195.1|' in qresult
|
| 105 |
+
True
|
| 106 |
+
>>> 'gi|262380031|ref|NR_023426.1|' in qresult
|
| 107 |
+
False
|
| 108 |
+
|
| 109 |
+
Or, if you just want to know the rank / position of a given hit, you can
|
| 110 |
+
use the hit ID as an argument for the ``index`` method. Note that the values
|
| 111 |
+
returned will be zero-based. So zero (0) means the hit is the first in the
|
| 112 |
+
QueryResult, three (3) means the hit is the fourth item, and so on. If the
|
| 113 |
+
hit does not exist in the QueryResult, a ``ValueError`` will be raised.
|
| 114 |
+
|
| 115 |
+
>>> qresult.index('gi|262205317|ref|NR_030195.1|')
|
| 116 |
+
0
|
| 117 |
+
>>> qresult.index('gi|262205330|ref|NR_030198.1|')
|
| 118 |
+
5
|
| 119 |
+
>>> qresult.index('gi|262380031|ref|NR_023426.1|')
|
| 120 |
+
Traceback (most recent call last):
|
| 121 |
+
...
|
| 122 |
+
ValueError: ...
|
| 123 |
+
|
| 124 |
+
To ease working with a large number of hits, QueryResult has several
|
| 125 |
+
``filter`` and ``map`` methods, analogous to Python's built-in functions with
|
| 126 |
+
the same names. There are ``filter`` and ``map`` methods available for
|
| 127 |
+
operations over both Hit objects or HSP objects. As an example, here we are
|
| 128 |
+
using the ``hit_map`` method to rename all hit IDs within a QueryResult::
|
| 129 |
+
|
| 130 |
+
>>> def renamer(hit):
|
| 131 |
+
... hit.id = hit.id.split('|')[3]
|
| 132 |
+
... return hit
|
| 133 |
+
>>> mapped_qresult = qresult.hit_map(renamer)
|
| 134 |
+
>>> print(mapped_qresult)
|
| 135 |
+
Program: blastn (2.2.27+)
|
| 136 |
+
Query: 33211 (61)
|
| 137 |
+
mir_1
|
| 138 |
+
Target: refseq_rna
|
| 139 |
+
Hits: ---- ----- ----------------------------------------------------------
|
| 140 |
+
# # HSP ID + description
|
| 141 |
+
---- ----- ----------------------------------------------------------
|
| 142 |
+
0 1 NR_030195.1 Homo sapiens microRNA 520b (MIR520B), micr...
|
| 143 |
+
1 1 NR_035856.1 Pan troglodytes microRNA mir-520b (MIR520B...
|
| 144 |
+
2 1 NR_032573.1 Macaca mulatta microRNA mir-519a (MIR519A)...
|
| 145 |
+
...
|
| 146 |
+
|
| 147 |
+
The principle for other ``map`` and ``filter`` methods are similar: they accept
|
| 148 |
+
a function, applies it, and returns a new QueryResult object.
|
| 149 |
+
|
| 150 |
+
There are also other methods useful for working with list-like objects:
|
| 151 |
+
``append``, ``pop``, and ``sort``. More details and examples are available in
|
| 152 |
+
their respective documentations.
|
| 153 |
+
|
| 154 |
+
Finally, just like Python lists and dictionaries, QueryResult objects are
|
| 155 |
+
iterable. Iteration over QueryResults will yield Hit objects::
|
| 156 |
+
|
| 157 |
+
>>> for hit in qresult[:4]: # iterate over the first four items
|
| 158 |
+
... hit
|
| 159 |
+
...
|
| 160 |
+
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps)
|
| 161 |
+
Hit(id='gi|301171311|ref|NR_035856.1|', query_id='33211', 1 hsps)
|
| 162 |
+
Hit(id='gi|270133242|ref|NR_032573.1|', query_id='33211', 1 hsps)
|
| 163 |
+
Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps)
|
| 164 |
+
|
| 165 |
+
If you need access to all the hits in a QueryResult object, you can get
|
| 166 |
+
them in a list using the ``hits`` property. Similarly, access to all hit IDs is
|
| 167 |
+
available through the ``hit_keys`` property.
|
| 168 |
+
|
| 169 |
+
>>> qresult.hits
|
| 170 |
+
[Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps), ...]
|
| 171 |
+
>>> qresult.hit_keys
|
| 172 |
+
['gi|262205317|ref|NR_030195.1|', 'gi|301171311|ref|NR_035856.1|', ...]
|
| 173 |
+
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
# attributes we don't want to transfer when creating a new QueryResult class
|
| 177 |
+
# from this one
|
| 178 |
+
_NON_STICKY_ATTRS = ("_items", "__alt_hit_ids")
|
| 179 |
+
|
| 180 |
+
def __init__(self, hits=(), id=None, hit_key_function=None):
|
| 181 |
+
"""Initialize a QueryResult object.
|
| 182 |
+
|
| 183 |
+
:param id: query sequence ID
|
| 184 |
+
:type id: string
|
| 185 |
+
:param hits: iterator yielding Hit objects
|
| 186 |
+
:type hits: iterable
|
| 187 |
+
:param hit_key_function: function to define hit keys
|
| 188 |
+
:type hit_key_function: callable, accepts Hit objects, returns string
|
| 189 |
+
|
| 190 |
+
"""
|
| 191 |
+
# default values
|
| 192 |
+
self._id = id
|
| 193 |
+
self._hit_key_function = hit_key_function or _hit_key_func
|
| 194 |
+
self._items = {}
|
| 195 |
+
self._description = None
|
| 196 |
+
self.__alt_hit_ids = {}
|
| 197 |
+
self.program = "<unknown program>"
|
| 198 |
+
self.target = "<unknown target>"
|
| 199 |
+
self.version = "<unknown version>"
|
| 200 |
+
|
| 201 |
+
# validate Hit objects and fill up self._items
|
| 202 |
+
for hit in hits:
|
| 203 |
+
# validation is handled by __setitem__
|
| 204 |
+
self.append(hit)
|
| 205 |
+
|
| 206 |
+
def __iter__(self):
|
| 207 |
+
"""Iterate over hits."""
|
| 208 |
+
return iter(self.hits)
|
| 209 |
+
|
| 210 |
+
@property
|
| 211 |
+
def hits(self):
|
| 212 |
+
"""Hit objects contained in the QueryResult."""
|
| 213 |
+
return list(self._items.values())
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def hit_keys(self):
|
| 217 |
+
"""Hit IDs of the Hit objects contained in the QueryResult."""
|
| 218 |
+
return list(self._items.keys())
|
| 219 |
+
|
| 220 |
+
@property
|
| 221 |
+
def items(self):
|
| 222 |
+
"""List of tuples of Hit IDs and Hit objects."""
|
| 223 |
+
return list(self._items.items())
|
| 224 |
+
|
| 225 |
+
def iterhits(self):
|
| 226 |
+
"""Return an iterator over the Hit objects."""
|
| 227 |
+
yield from self._items.values()
|
| 228 |
+
|
| 229 |
+
def iterhit_keys(self):
|
| 230 |
+
"""Return an iterator over the ID of the Hit objects."""
|
| 231 |
+
yield from self._items
|
| 232 |
+
|
| 233 |
+
def iteritems(self):
|
| 234 |
+
"""Return an iterator yielding tuples of Hit ID and Hit objects."""
|
| 235 |
+
yield from self._items.items()
|
| 236 |
+
|
| 237 |
+
def __contains__(self, hit_key):
|
| 238 |
+
"""Return True if hit key in items or alternative hit identifiers."""
|
| 239 |
+
if isinstance(hit_key, Hit):
|
| 240 |
+
return self._hit_key_function(hit_key) in self._items
|
| 241 |
+
return hit_key in self._items or hit_key in self.__alt_hit_ids
|
| 242 |
+
|
| 243 |
+
def __len__(self):
|
| 244 |
+
"""Return the number of items."""
|
| 245 |
+
return len(self._items)
|
| 246 |
+
|
| 247 |
+
def __bool__(self):
|
| 248 |
+
"""Return True if there are items."""
|
| 249 |
+
return bool(self._items)
|
| 250 |
+
|
| 251 |
+
def __repr__(self):
|
| 252 |
+
"""Return string representation of the QueryResult object."""
|
| 253 |
+
return "QueryResult(id=%r, %r hits)" % (self.id, len(self))
|
| 254 |
+
|
| 255 |
+
def __str__(self):
|
| 256 |
+
"""Return a human readable summary of the QueryResult object."""
|
| 257 |
+
lines = []
|
| 258 |
+
|
| 259 |
+
# set program and version line
|
| 260 |
+
lines.append("Program: %s (%s)" % (self.program, self.version))
|
| 261 |
+
|
| 262 |
+
# set query id line
|
| 263 |
+
qid_line = " Query: %s" % self.id
|
| 264 |
+
try:
|
| 265 |
+
seq_len = self.seq_len
|
| 266 |
+
except AttributeError:
|
| 267 |
+
pass
|
| 268 |
+
else:
|
| 269 |
+
qid_line += " (%i)" % seq_len
|
| 270 |
+
lines.append(qid_line)
|
| 271 |
+
if self.description:
|
| 272 |
+
line = " %s" % self.description
|
| 273 |
+
line = line[:77] + "..." if len(line) > 80 else line
|
| 274 |
+
lines.append(line)
|
| 275 |
+
|
| 276 |
+
# set target line
|
| 277 |
+
lines.append(" Target: %s" % self.target)
|
| 278 |
+
|
| 279 |
+
# set hit lines
|
| 280 |
+
if not self.hits:
|
| 281 |
+
lines.append(" Hits: 0")
|
| 282 |
+
else:
|
| 283 |
+
lines.append(" Hits: %s %s %s" % ("-" * 4, "-" * 5, "-" * 58))
|
| 284 |
+
pattern = "%13s %5s %s"
|
| 285 |
+
lines.append(pattern % ("#", "# HSP", "ID + description"))
|
| 286 |
+
lines.append(pattern % ("-" * 4, "-" * 5, "-" * 58))
|
| 287 |
+
for idx, hit in enumerate(self.hits):
|
| 288 |
+
if idx < 30:
|
| 289 |
+
hid_line = "%s %s" % (hit.id, hit.description)
|
| 290 |
+
if len(hid_line) > 58:
|
| 291 |
+
hid_line = hid_line[:55] + "..."
|
| 292 |
+
lines.append(pattern % (idx, len(hit), hid_line))
|
| 293 |
+
elif idx > len(self.hits) - 4:
|
| 294 |
+
hid_line = "%s %s" % (hit.id, hit.description)
|
| 295 |
+
if len(hid_line) > 58:
|
| 296 |
+
hid_line = hid_line[:55] + "..."
|
| 297 |
+
lines.append(pattern % (idx, len(hit), hid_line))
|
| 298 |
+
elif idx == 30:
|
| 299 |
+
lines.append("%14s" % "~~~")
|
| 300 |
+
|
| 301 |
+
return "\n".join(lines)
|
| 302 |
+
|
| 303 |
+
def __getitem__(self, hit_key):
|
| 304 |
+
"""Return a QueryResult object that matches the hit_key."""
|
| 305 |
+
# retrieval using slice objects returns another QueryResult object
|
| 306 |
+
if isinstance(hit_key, slice):
|
| 307 |
+
# should we return just a list of Hits instead of a full blown
|
| 308 |
+
# QueryResult object if it's a slice?
|
| 309 |
+
hits = list(self.hits)[hit_key]
|
| 310 |
+
obj = self.__class__(hits, self.id, self._hit_key_function)
|
| 311 |
+
self._transfer_attrs(obj)
|
| 312 |
+
return obj
|
| 313 |
+
|
| 314 |
+
# if key is an int, then retrieve the Hit at the int index
|
| 315 |
+
elif isinstance(hit_key, int):
|
| 316 |
+
length = len(self)
|
| 317 |
+
if 0 <= hit_key < length:
|
| 318 |
+
for idx, item in enumerate(self.iterhits()):
|
| 319 |
+
if idx == hit_key:
|
| 320 |
+
return item
|
| 321 |
+
elif -1 * length <= hit_key < 0:
|
| 322 |
+
for idx, item in enumerate(self.iterhits()):
|
| 323 |
+
if length + hit_key == idx:
|
| 324 |
+
return item
|
| 325 |
+
raise IndexError("list index out of range")
|
| 326 |
+
|
| 327 |
+
# if key is a string, then do a regular dictionary retrieval
|
| 328 |
+
# falling back on alternative hit IDs
|
| 329 |
+
try:
|
| 330 |
+
return self._items[hit_key]
|
| 331 |
+
except KeyError:
|
| 332 |
+
return self._items[self.__alt_hit_ids[hit_key]]
|
| 333 |
+
|
| 334 |
+
def __setitem__(self, hit_key, hit):
|
| 335 |
+
"""Add an item of key hit_key and value hit."""
|
| 336 |
+
# only accept string keys
|
| 337 |
+
if not isinstance(hit_key, str):
|
| 338 |
+
raise TypeError("QueryResult object keys must be a string.")
|
| 339 |
+
# hit must be a Hit object
|
| 340 |
+
if not isinstance(hit, Hit):
|
| 341 |
+
raise TypeError("QueryResult objects can only contain Hit objects.")
|
| 342 |
+
qid = self.id
|
| 343 |
+
hqid = hit.query_id
|
| 344 |
+
# and it must have the same query ID as this object's ID
|
| 345 |
+
# unless it's the query ID is None (default for empty objects), in which
|
| 346 |
+
# case we want to use the hit's query ID as the query ID
|
| 347 |
+
if qid is not None:
|
| 348 |
+
if hqid != qid:
|
| 349 |
+
raise ValueError(
|
| 350 |
+
"Expected Hit with query ID %r, found %r instead." % (qid, hqid)
|
| 351 |
+
)
|
| 352 |
+
else:
|
| 353 |
+
self.id = hqid
|
| 354 |
+
# same thing with descriptions
|
| 355 |
+
qdesc = self.description
|
| 356 |
+
hqdesc = hit.query_description
|
| 357 |
+
if qdesc is not None:
|
| 358 |
+
if hqdesc != qdesc:
|
| 359 |
+
raise ValueError(
|
| 360 |
+
"Expected Hit with query description %r, found %r instead."
|
| 361 |
+
% (qdesc, hqdesc)
|
| 362 |
+
)
|
| 363 |
+
else:
|
| 364 |
+
self.description = hqdesc
|
| 365 |
+
|
| 366 |
+
# remove existing alt_id references, if hit_key already exists
|
| 367 |
+
if hit_key in self._items:
|
| 368 |
+
for alt_key in self._items[hit_key].id_all[1:]:
|
| 369 |
+
del self.__alt_hit_ids[alt_key]
|
| 370 |
+
|
| 371 |
+
# if hit_key is already present as an alternative ID
|
| 372 |
+
# delete it from the alternative ID dict
|
| 373 |
+
if hit_key in self.__alt_hit_ids:
|
| 374 |
+
del self.__alt_hit_ids[hit_key]
|
| 375 |
+
|
| 376 |
+
self._items[hit_key] = hit
|
| 377 |
+
for alt_id in hit.id_all[1:]:
|
| 378 |
+
self.__alt_hit_ids[alt_id] = hit_key
|
| 379 |
+
|
| 380 |
+
def __delitem__(self, hit_key):
|
| 381 |
+
"""Delete item of key hit_key."""
|
| 382 |
+
# if hit_key an integer or slice, get the corresponding key first
|
| 383 |
+
# and put it into a list
|
| 384 |
+
if isinstance(hit_key, int):
|
| 385 |
+
hit_keys = [list(self.hit_keys)[hit_key]]
|
| 386 |
+
# the same, if it's a slice
|
| 387 |
+
elif isinstance(hit_key, slice):
|
| 388 |
+
hit_keys = list(self.hit_keys)[hit_key]
|
| 389 |
+
# otherwise put it in a list
|
| 390 |
+
else:
|
| 391 |
+
hit_keys = [hit_key]
|
| 392 |
+
|
| 393 |
+
for key in hit_keys:
|
| 394 |
+
deleted = False
|
| 395 |
+
if key in self._items:
|
| 396 |
+
del self._items[key]
|
| 397 |
+
deleted = True
|
| 398 |
+
if key in self.__alt_hit_ids:
|
| 399 |
+
del self._items[self.__alt_hit_ids[key]]
|
| 400 |
+
del self.__alt_hit_ids[key]
|
| 401 |
+
deleted = True
|
| 402 |
+
if not deleted:
|
| 403 |
+
raise KeyError(repr(key))
|
| 404 |
+
|
| 405 |
+
# properties #
|
| 406 |
+
id = optionalcascade("_id", "query_id", """QueryResult ID string""")
|
| 407 |
+
description = optionalcascade(
|
| 408 |
+
"_description", "query_description", """QueryResult description"""
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
@property
|
| 412 |
+
def hsps(self):
|
| 413 |
+
"""Access the HSP objects contained in the QueryResult."""
|
| 414 |
+
return sorted(
|
| 415 |
+
(hsp for hsp in chain(*self.hits)), key=lambda hsp: hsp.output_index
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
@property
|
| 419 |
+
def fragments(self):
|
| 420 |
+
"""Access the HSPFragment objects contained in the QueryResult."""
|
| 421 |
+
return list(chain(*self.hsps))
|
| 422 |
+
|
| 423 |
+
# public methods #
|
| 424 |
+
def absorb(self, hit):
|
| 425 |
+
"""Add a Hit object to the end of QueryResult.
|
| 426 |
+
|
| 427 |
+
If the QueryResult already has a Hit with the same ID, append the new
|
| 428 |
+
Hit's HSPs into the existing Hit.
|
| 429 |
+
|
| 430 |
+
:param hit: object to absorb
|
| 431 |
+
:type hit: Hit
|
| 432 |
+
|
| 433 |
+
This method is used for file formats that may output the same Hit in
|
| 434 |
+
separate places, such as BLAT or Exonerate. In both formats, Hit
|
| 435 |
+
with different strands are put in different places. However, SearchIO
|
| 436 |
+
considers them to be the same as a Hit object should be all database
|
| 437 |
+
entries with the same ID, regardless of strand orientation.
|
| 438 |
+
|
| 439 |
+
"""
|
| 440 |
+
try:
|
| 441 |
+
self.append(hit)
|
| 442 |
+
except ValueError:
|
| 443 |
+
assert hit.id in self
|
| 444 |
+
for hsp in hit:
|
| 445 |
+
self[hit.id].append(hsp)
|
| 446 |
+
|
| 447 |
+
def append(self, hit):
|
| 448 |
+
"""Add a Hit object to the end of QueryResult.
|
| 449 |
+
|
| 450 |
+
:param hit: object to append
|
| 451 |
+
:type hit: Hit
|
| 452 |
+
|
| 453 |
+
Any Hit object appended must have the same ``query_id`` property as the
|
| 454 |
+
QueryResult's ``id`` property. If the hit key already exists, a
|
| 455 |
+
``ValueError`` will be raised.
|
| 456 |
+
|
| 457 |
+
"""
|
| 458 |
+
# if a custom hit_key_function is supplied, use it to define th hit key
|
| 459 |
+
if self._hit_key_function is not None:
|
| 460 |
+
hit_key = self._hit_key_function(hit)
|
| 461 |
+
else:
|
| 462 |
+
hit_key = hit.id
|
| 463 |
+
|
| 464 |
+
if hit_key not in self and all(pid not in self for pid in hit.id_all[1:]):
|
| 465 |
+
self[hit_key] = hit
|
| 466 |
+
else:
|
| 467 |
+
raise ValueError(
|
| 468 |
+
"The ID or alternative IDs of Hit %r exists in this QueryResult."
|
| 469 |
+
% hit_key
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
def hit_filter(self, func=None):
|
| 473 |
+
"""Create new QueryResult object whose Hit objects pass the filter function.
|
| 474 |
+
|
| 475 |
+
:param func: filter function
|
| 476 |
+
:type func: callable, accepts Hit, returns bool
|
| 477 |
+
|
| 478 |
+
Here is an example of using ``hit_filter`` to select Hits whose
|
| 479 |
+
description begins with the string 'Homo sapiens', case sensitive::
|
| 480 |
+
|
| 481 |
+
>>> from Bio import SearchIO
|
| 482 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 483 |
+
>>> def desc_filter(hit):
|
| 484 |
+
... return hit.description.startswith('Homo sapiens')
|
| 485 |
+
...
|
| 486 |
+
>>> len(qresult)
|
| 487 |
+
100
|
| 488 |
+
>>> filtered = qresult.hit_filter(desc_filter)
|
| 489 |
+
>>> len(filtered)
|
| 490 |
+
39
|
| 491 |
+
>>> print(filtered[:4])
|
| 492 |
+
Program: blastn (2.2.27+)
|
| 493 |
+
Query: 33211 (61)
|
| 494 |
+
mir_1
|
| 495 |
+
Target: refseq_rna
|
| 496 |
+
Hits: ---- ----- ----------------------------------------------------------
|
| 497 |
+
# # HSP ID + description
|
| 498 |
+
---- ----- ----------------------------------------------------------
|
| 499 |
+
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
|
| 500 |
+
1 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52...
|
| 501 |
+
2 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51...
|
| 502 |
+
3 1 gi|262205451|ref|NR_030222.1| Homo sapiens microRNA 51...
|
| 503 |
+
|
| 504 |
+
Note that instance attributes (other than the hits) from the unfiltered
|
| 505 |
+
QueryResult are retained in the filtered object.
|
| 506 |
+
|
| 507 |
+
>>> qresult.program == filtered.program
|
| 508 |
+
True
|
| 509 |
+
>>> qresult.target == filtered.target
|
| 510 |
+
True
|
| 511 |
+
|
| 512 |
+
"""
|
| 513 |
+
hits = list(filter(func, self.hits))
|
| 514 |
+
obj = self.__class__(hits, self.id, self._hit_key_function)
|
| 515 |
+
self._transfer_attrs(obj)
|
| 516 |
+
return obj
|
| 517 |
+
|
| 518 |
+
def hit_map(self, func=None):
|
| 519 |
+
"""Create new QueryResult object, mapping the given function to its Hits.
|
| 520 |
+
|
| 521 |
+
:param func: map function
|
| 522 |
+
:type func: callable, accepts Hit, returns Hit
|
| 523 |
+
|
| 524 |
+
Here is an example of using ``hit_map`` with a function that discards all
|
| 525 |
+
HSPs in a Hit except for the first one::
|
| 526 |
+
|
| 527 |
+
>>> from Bio import SearchIO
|
| 528 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 529 |
+
>>> print(qresult[:8])
|
| 530 |
+
Program: blastn (2.2.27+)
|
| 531 |
+
Query: 33211 (61)
|
| 532 |
+
mir_1
|
| 533 |
+
Target: refseq_rna
|
| 534 |
+
Hits: ---- ----- ----------------------------------------------------------
|
| 535 |
+
# # HSP ID + description
|
| 536 |
+
---- ----- ----------------------------------------------------------
|
| 537 |
+
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
|
| 538 |
+
1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA...
|
| 539 |
+
2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ...
|
| 540 |
+
3 2 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA...
|
| 541 |
+
4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA...
|
| 542 |
+
5 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52...
|
| 543 |
+
6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51...
|
| 544 |
+
7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA...
|
| 545 |
+
|
| 546 |
+
>>> top_hsp = lambda hit: hit[:1]
|
| 547 |
+
>>> mapped_qresult = qresult.hit_map(top_hsp)
|
| 548 |
+
>>> print(mapped_qresult[:8])
|
| 549 |
+
Program: blastn (2.2.27+)
|
| 550 |
+
Query: 33211 (61)
|
| 551 |
+
mir_1
|
| 552 |
+
Target: refseq_rna
|
| 553 |
+
Hits: ---- ----- ----------------------------------------------------------
|
| 554 |
+
# # HSP ID + description
|
| 555 |
+
---- ----- ----------------------------------------------------------
|
| 556 |
+
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
|
| 557 |
+
1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA...
|
| 558 |
+
2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ...
|
| 559 |
+
3 1 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA...
|
| 560 |
+
4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA...
|
| 561 |
+
5 1 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52...
|
| 562 |
+
6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51...
|
| 563 |
+
7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA...
|
| 564 |
+
|
| 565 |
+
"""
|
| 566 |
+
hits = [deepcopy(hit) for hit in self.hits]
|
| 567 |
+
if func is not None:
|
| 568 |
+
hits = [func(x) for x in hits]
|
| 569 |
+
obj = self.__class__(hits, self.id, self._hit_key_function)
|
| 570 |
+
self._transfer_attrs(obj)
|
| 571 |
+
return obj
|
| 572 |
+
|
| 573 |
+
def hsp_filter(self, func=None):
|
| 574 |
+
"""Create new QueryResult object whose HSP objects pass the filter function.
|
| 575 |
+
|
| 576 |
+
``hsp_filter`` is the same as ``hit_filter``, except that it filters
|
| 577 |
+
directly on each HSP object in every Hit. If the filtering removes
|
| 578 |
+
all HSP objects in a given Hit, the entire Hit will be discarded. This
|
| 579 |
+
will result in the QueryResult having less Hit after filtering.
|
| 580 |
+
"""
|
| 581 |
+
hits = [x for x in (hit.filter(func) for hit in self.hits) if x]
|
| 582 |
+
obj = self.__class__(hits, self.id, self._hit_key_function)
|
| 583 |
+
self._transfer_attrs(obj)
|
| 584 |
+
return obj
|
| 585 |
+
|
| 586 |
+
def hsp_map(self, func=None):
|
| 587 |
+
"""Create new QueryResult object, mapping the given function to its HSPs.
|
| 588 |
+
|
| 589 |
+
``hsp_map`` is the same as ``hit_map``, except that it applies the given
|
| 590 |
+
function to all HSP objects in every Hit, instead of the Hit objects.
|
| 591 |
+
"""
|
| 592 |
+
hits = [x for x in (hit.map(func) for hit in list(self.hits)[:]) if x]
|
| 593 |
+
obj = self.__class__(hits, self.id, self._hit_key_function)
|
| 594 |
+
self._transfer_attrs(obj)
|
| 595 |
+
return obj
|
| 596 |
+
|
| 597 |
+
# marker for default self.pop() return value
|
| 598 |
+
# this method is adapted from Python's built in OrderedDict.pop
|
| 599 |
+
# implementation
|
| 600 |
+
__marker = object()
|
| 601 |
+
|
| 602 |
+
def pop(self, hit_key=-1, default=__marker):
|
| 603 |
+
"""Remove the specified hit key and return the Hit object.
|
| 604 |
+
|
| 605 |
+
:param hit_key: key of the Hit object to return
|
| 606 |
+
:type hit_key: int or string
|
| 607 |
+
:param default: return value if no Hit exists with the given key
|
| 608 |
+
:type default: object
|
| 609 |
+
|
| 610 |
+
By default, ``pop`` will remove and return the last Hit object in the
|
| 611 |
+
QueryResult object. To remove specific Hit objects, you can use its
|
| 612 |
+
integer index or hit key.
|
| 613 |
+
|
| 614 |
+
>>> from Bio import SearchIO
|
| 615 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 616 |
+
>>> len(qresult)
|
| 617 |
+
100
|
| 618 |
+
>>> for hit in qresult[:5]:
|
| 619 |
+
... print(hit.id)
|
| 620 |
+
...
|
| 621 |
+
gi|262205317|ref|NR_030195.1|
|
| 622 |
+
gi|301171311|ref|NR_035856.1|
|
| 623 |
+
gi|270133242|ref|NR_032573.1|
|
| 624 |
+
gi|301171322|ref|NR_035857.1|
|
| 625 |
+
gi|301171267|ref|NR_035851.1|
|
| 626 |
+
|
| 627 |
+
# remove the last hit
|
| 628 |
+
>>> qresult.pop()
|
| 629 |
+
Hit(id='gi|397513516|ref|XM_003827011.1|', query_id='33211', 1 hsps)
|
| 630 |
+
|
| 631 |
+
# remove the first hit
|
| 632 |
+
>>> qresult.pop(0)
|
| 633 |
+
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps)
|
| 634 |
+
|
| 635 |
+
# remove hit with the given ID
|
| 636 |
+
>>> qresult.pop('gi|301171322|ref|NR_035857.1|')
|
| 637 |
+
Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps)
|
| 638 |
+
|
| 639 |
+
"""
|
| 640 |
+
# if key is an integer (index)
|
| 641 |
+
# get the ID for the Hit object at that index
|
| 642 |
+
if isinstance(hit_key, int):
|
| 643 |
+
# raise the appropriate error if there is no hit
|
| 644 |
+
if not self:
|
| 645 |
+
raise IndexError("pop from empty list")
|
| 646 |
+
hit_key = list(self.hit_keys)[hit_key]
|
| 647 |
+
|
| 648 |
+
try:
|
| 649 |
+
hit = self._items.pop(hit_key)
|
| 650 |
+
# remove all alternative IDs of the popped hit
|
| 651 |
+
for alt_id in hit.id_all[1:]:
|
| 652 |
+
self.__alt_hit_ids.pop(alt_id, None)
|
| 653 |
+
except KeyError:
|
| 654 |
+
try:
|
| 655 |
+
hit = self.pop(self.__alt_hit_ids[hit_key])
|
| 656 |
+
except KeyError:
|
| 657 |
+
# hit_key is not a valid id
|
| 658 |
+
# use the default if it has been set
|
| 659 |
+
if default is not self.__marker:
|
| 660 |
+
hit = default
|
| 661 |
+
else:
|
| 662 |
+
raise KeyError(hit_key) from None
|
| 663 |
+
return hit
|
| 664 |
+
|
| 665 |
+
def index(self, hit_key):
|
| 666 |
+
"""Return the index of a given hit key, zero-based.
|
| 667 |
+
|
| 668 |
+
:param hit_key: hit ID
|
| 669 |
+
:type hit_key: string
|
| 670 |
+
|
| 671 |
+
This method is useful for finding out the integer index (usually
|
| 672 |
+
correlated with search rank) of a given hit key.
|
| 673 |
+
|
| 674 |
+
>>> from Bio import SearchIO
|
| 675 |
+
>>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
|
| 676 |
+
>>> qresult.index('gi|301171259|ref|NR_035850.1|')
|
| 677 |
+
7
|
| 678 |
+
|
| 679 |
+
"""
|
| 680 |
+
if isinstance(hit_key, Hit):
|
| 681 |
+
return list(self.hit_keys).index(hit_key.id)
|
| 682 |
+
try:
|
| 683 |
+
return list(self.hit_keys).index(hit_key)
|
| 684 |
+
except ValueError:
|
| 685 |
+
if hit_key in self.__alt_hit_ids:
|
| 686 |
+
return self.index(self.__alt_hit_ids[hit_key])
|
| 687 |
+
raise
|
| 688 |
+
|
| 689 |
+
def sort(self, key=None, reverse=False, in_place=True):
|
| 690 |
+
"""Sort the Hit objects.
|
| 691 |
+
|
| 692 |
+
:param key: sorting function
|
| 693 |
+
:type key: callable, accepts Hit, returns key for sorting
|
| 694 |
+
:param reverse: whether to reverse sorting results or no
|
| 695 |
+
:type reverse: bool
|
| 696 |
+
:param in_place: whether to do in-place sorting or no
|
| 697 |
+
:type in_place: bool
|
| 698 |
+
|
| 699 |
+
``sort`` defaults to sorting in-place, to mimic Python's ``list.sort``
|
| 700 |
+
method. If you set the ``in_place`` argument to False, it will treat
|
| 701 |
+
return a new, sorted QueryResult object and keep the initial one
|
| 702 |
+
unsorted.
|
| 703 |
+
|
| 704 |
+
"""
|
| 705 |
+
if key is None:
|
| 706 |
+
# if reverse is True, reverse the hits
|
| 707 |
+
if reverse:
|
| 708 |
+
sorted_hits = list(self.hits)[::-1]
|
| 709 |
+
# otherwise (default options) make a copy of the hits
|
| 710 |
+
else:
|
| 711 |
+
sorted_hits = list(self.hits)[:]
|
| 712 |
+
else:
|
| 713 |
+
sorted_hits = sorted(self.hits, key=key, reverse=reverse)
|
| 714 |
+
|
| 715 |
+
# if sorting is in-place, don't create a new QueryResult object
|
| 716 |
+
if in_place:
|
| 717 |
+
self._items = {self._hit_key_function(hit): hit for hit in sorted_hits}
|
| 718 |
+
# otherwise, return a new sorted QueryResult object
|
| 719 |
+
else:
|
| 720 |
+
obj = self.__class__(sorted_hits, self.id, self._hit_key_function)
|
| 721 |
+
self._transfer_attrs(obj)
|
| 722 |
+
return obj
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _hit_key_func(hit):
|
| 726 |
+
"""Map hit to its identifier (PRIVATE).
|
| 727 |
+
|
| 728 |
+
Default hit key function for QueryResult.__init__ use.
|
| 729 |
+
"""
|
| 730 |
+
return hit.id
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
# if not used as a module, run the doctest
|
| 734 |
+
if __name__ == "__main__":
|
| 735 |
+
from Bio._utils import run_doctest
|
| 736 |
+
|
| 737 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_utils.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
|
| 2 |
+
# This file is part of the Biopython distribution and governed by your
|
| 3 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 4 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 5 |
+
# package.
|
| 6 |
+
"""Common SearchIO utility functions."""
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def getattr_str(obj, attr, fmt=None, fallback="?"):
|
| 12 |
+
"""Return string of the given object's attribute.
|
| 13 |
+
|
| 14 |
+
Defaults to the given fallback value if attribute is not present.
|
| 15 |
+
"""
|
| 16 |
+
try:
|
| 17 |
+
value = getattr(obj, attr)
|
| 18 |
+
except AttributeError:
|
| 19 |
+
return fallback
|
| 20 |
+
if fmt is None:
|
| 21 |
+
return str(value)
|
| 22 |
+
return fmt % value
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def read_forward(handle):
|
| 26 |
+
"""Read through whitespaces, return the first non-whitespace line."""
|
| 27 |
+
while True:
|
| 28 |
+
line = handle.readline()
|
| 29 |
+
# if line is empty or line has characters and stripping does not remove
|
| 30 |
+
# them, return the line
|
| 31 |
+
if (not line) or (line and line.strip()):
|
| 32 |
+
return line
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_processor(format, mapping):
|
| 36 |
+
"""Return the object to process the given format according to the mapping.
|
| 37 |
+
|
| 38 |
+
:param format: format name
|
| 39 |
+
:type format: string, lower case
|
| 40 |
+
:param mapping: mapping of format name and its processor object
|
| 41 |
+
:type mapping: dictionary {string: object}
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
# map file format to iterator name
|
| 45 |
+
try:
|
| 46 |
+
obj_info = mapping[format]
|
| 47 |
+
except KeyError:
|
| 48 |
+
# handle the errors with helpful messages
|
| 49 |
+
if format is None:
|
| 50 |
+
raise ValueError("Format required (lower case string)") from None
|
| 51 |
+
elif not isinstance(format, str):
|
| 52 |
+
raise TypeError("Need a string for the file format (lower case)") from None
|
| 53 |
+
elif format != format.lower():
|
| 54 |
+
raise ValueError("Format string %r should be lower case" % format) from None
|
| 55 |
+
else:
|
| 56 |
+
raise ValueError(
|
| 57 |
+
"Unknown format %r. Supported formats are %r"
|
| 58 |
+
% (format, "', '".join(mapping))
|
| 59 |
+
) from None
|
| 60 |
+
|
| 61 |
+
mod_name, obj_name = obj_info
|
| 62 |
+
mod = __import__("Bio.SearchIO.%s" % mod_name, fromlist=[""])
|
| 63 |
+
|
| 64 |
+
return getattr(mod, obj_name)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def singleitem(attr=None, doc=""):
|
| 68 |
+
"""Property for fetching attribute from first entry of container.
|
| 69 |
+
|
| 70 |
+
Returns a property that fetches the given attribute from
|
| 71 |
+
the first item in a SearchIO container object.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def getter(self):
|
| 75 |
+
if len(self._items) > 1:
|
| 76 |
+
raise ValueError("More than one HSPFragment objects found in HSP")
|
| 77 |
+
if attr is None:
|
| 78 |
+
return self._items[0]
|
| 79 |
+
return getattr(self._items[0], attr)
|
| 80 |
+
|
| 81 |
+
return property(fget=getter, doc=doc)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def allitems(attr=None, doc=""):
|
| 85 |
+
"""Property for fetching attribute from all entries of container.
|
| 86 |
+
|
| 87 |
+
Returns a property that fetches the given attributes from
|
| 88 |
+
all items in a SearchIO container object.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def getter(self):
|
| 92 |
+
if attr is None:
|
| 93 |
+
return self._items
|
| 94 |
+
return [getattr(frag, attr) for frag in self._items]
|
| 95 |
+
|
| 96 |
+
return property(fget=getter, doc=doc)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def fullcascade(attr, doc=""):
|
| 100 |
+
"""Return a getter property with a cascading setter.
|
| 101 |
+
|
| 102 |
+
This is similar to ``optionalcascade``, but for SearchIO containers that have
|
| 103 |
+
at least one item (HSP). The getter always retrieves the attribute
|
| 104 |
+
value from the first item. If the items have more than one attribute values,
|
| 105 |
+
an error will be raised. The setter behaves like ``partialcascade``, except
|
| 106 |
+
that it only sets attributes to items in the object, not the object itself.
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def getter(self):
|
| 111 |
+
return getattr(self._items[0], attr)
|
| 112 |
+
|
| 113 |
+
def setter(self, value):
|
| 114 |
+
for item in self:
|
| 115 |
+
setattr(item, attr, value)
|
| 116 |
+
|
| 117 |
+
return property(fget=getter, fset=setter, doc=doc)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def optionalcascade(cont_attr, item_attr, doc=""):
|
| 121 |
+
"""Return a getter property with a cascading setter.
|
| 122 |
+
|
| 123 |
+
This is used for the ``id`` and ``description`` properties of the container
|
| 124 |
+
objects with zero or more items. These items have their own private
|
| 125 |
+
attributes that stores query and/or hit ID and description. When the
|
| 126 |
+
container has zero items, attribute values are always retrieved from the
|
| 127 |
+
container's attribute. Otherwise, the first item's attribute is used.
|
| 128 |
+
|
| 129 |
+
To keep the container items' query and/or hit ID and description in-sync,
|
| 130 |
+
the setter cascades any new value given to the items' values.
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
def getter(self):
|
| 135 |
+
if self._items:
|
| 136 |
+
# don't use self._items here, so QueryResult can use this property
|
| 137 |
+
# as well (the underlying dict is not integer-indexable)
|
| 138 |
+
return getattr(self[0], item_attr)
|
| 139 |
+
else:
|
| 140 |
+
return getattr(self, cont_attr)
|
| 141 |
+
|
| 142 |
+
def setter(self, value):
|
| 143 |
+
setattr(self, cont_attr, value)
|
| 144 |
+
for item in self:
|
| 145 |
+
setattr(item, item_attr, value)
|
| 146 |
+
|
| 147 |
+
return property(fget=getter, fset=setter, doc=doc)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def fragcascade(attr, seq_type, doc=""):
|
| 151 |
+
"""Return a getter property with cascading setter, for HSPFragment objects.
|
| 152 |
+
|
| 153 |
+
Similar to ``partialcascade``, but for HSPFragment objects and acts on ``query``
|
| 154 |
+
or ``hit`` properties of the object if they are not None.
|
| 155 |
+
|
| 156 |
+
"""
|
| 157 |
+
assert seq_type in ("hit", "query")
|
| 158 |
+
attr_name = f"_{seq_type}_{attr}"
|
| 159 |
+
|
| 160 |
+
def getter(self):
|
| 161 |
+
return getattr(self, attr_name)
|
| 162 |
+
|
| 163 |
+
def setter(self, value):
|
| 164 |
+
setattr(self, attr_name, value)
|
| 165 |
+
seq = getattr(self, seq_type)
|
| 166 |
+
if seq is not None:
|
| 167 |
+
setattr(seq, attr, value)
|
| 168 |
+
|
| 169 |
+
return property(fget=getter, fset=setter, doc=doc)
|
.venv_haddock/lib/python3.12/site-packages/Bio/Seq.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py
ADDED
|
@@ -0,0 +1,2332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2000-2003 Jeff Chang.
|
| 2 |
+
# Copyright 2001-2008 Brad Chapman.
|
| 3 |
+
# Copyright 2005-2024 by Peter Cock.
|
| 4 |
+
# Copyright 2006-2009 Michiel de Hoon.
|
| 5 |
+
# All rights reserved.
|
| 6 |
+
#
|
| 7 |
+
# This file is part of the Biopython distribution and governed by your
|
| 8 |
+
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
|
| 9 |
+
# Please see the LICENSE file that should have been included as part of this
|
| 10 |
+
# package.
|
| 11 |
+
"""Represent a Sequence Feature holding info about a part of a sequence.
|
| 12 |
+
|
| 13 |
+
This is heavily modeled after the Biocorba SeqFeature objects, and
|
| 14 |
+
may be pretty biased towards GenBank stuff since I'm writing it
|
| 15 |
+
for the GenBank parser output...
|
| 16 |
+
|
| 17 |
+
What's here:
|
| 18 |
+
|
| 19 |
+
Base class to hold a Feature
|
| 20 |
+
----------------------------
|
| 21 |
+
|
| 22 |
+
Classes:
|
| 23 |
+
- SeqFeature
|
| 24 |
+
|
| 25 |
+
Hold information about a Reference
|
| 26 |
+
----------------------------------
|
| 27 |
+
|
| 28 |
+
This is an attempt to create a General class to hold Reference type
|
| 29 |
+
information.
|
| 30 |
+
|
| 31 |
+
Classes:
|
| 32 |
+
- Reference
|
| 33 |
+
|
| 34 |
+
Specify locations of a feature on a Sequence
|
| 35 |
+
--------------------------------------------
|
| 36 |
+
|
| 37 |
+
This aims to handle, in Ewan Birney's words, 'the dreaded fuzziness issue'.
|
| 38 |
+
This has the advantages of allowing us to handle fuzzy stuff in case anyone
|
| 39 |
+
needs it, and also be compatible with BioPerl etc and BioSQL.
|
| 40 |
+
|
| 41 |
+
Classes:
|
| 42 |
+
- Location - abstract base class of SimpleLocation and CompoundLocation.
|
| 43 |
+
- SimpleLocation - Specify the start and end location of a feature.
|
| 44 |
+
- CompoundLocation - Collection of SimpleLocation objects (for joins etc).
|
| 45 |
+
- Position - abstract base class of ExactPosition, WithinPosition,
|
| 46 |
+
BetweenPosition, AfterPosition, OneOfPosition, UncertainPosition, and
|
| 47 |
+
UnknownPosition.
|
| 48 |
+
- ExactPosition - Specify the position as being exact.
|
| 49 |
+
- WithinPosition - Specify a position occurring within some range.
|
| 50 |
+
- BetweenPosition - Specify a position occurring between a range (OBSOLETE?).
|
| 51 |
+
- BeforePosition - Specify the position as being found before some base.
|
| 52 |
+
- AfterPosition - Specify the position as being found after some base.
|
| 53 |
+
- OneOfPosition - Specify a position consisting of multiple alternative positions.
|
| 54 |
+
- UncertainPosition - Specify a specific position which is uncertain.
|
| 55 |
+
- UnknownPosition - Represents missing information like '?' in UniProt.
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
Exceptions:
|
| 59 |
+
- LocationParserError - Exception indicating a failure to parse a location
|
| 60 |
+
string.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
import functools
|
| 65 |
+
import re
|
| 66 |
+
import warnings
|
| 67 |
+
from abc import ABC
|
| 68 |
+
from abc import abstractmethod
|
| 69 |
+
|
| 70 |
+
from Bio import BiopythonParserWarning
|
| 71 |
+
from Bio.Seq import MutableSeq
|
| 72 |
+
from Bio.Seq import reverse_complement
|
| 73 |
+
from Bio.Seq import Seq
|
| 74 |
+
|
| 75 |
+
# Regular expressions for location parsing
|
| 76 |
+
|
| 77 |
+
_reference = r"(?:[a-zA-Z][a-zA-Z0-9_\.\|]*[a-zA-Z0-9]?\:)"
|
| 78 |
+
_oneof_position = r"one\-of\(\d+[,\d+]+\)"
|
| 79 |
+
|
| 80 |
+
_oneof_location = rf"[<>]?(?:\d+|{_oneof_position})\.\.[<>]?(?:\d+|{_oneof_position})"
|
| 81 |
+
|
| 82 |
+
_any_location = rf"({_reference}?{_oneof_location}|complement\({_oneof_location}\)|[^,]+|complement\([^,]+\))"
|
| 83 |
+
|
| 84 |
+
_split = re.compile(_any_location).split
|
| 85 |
+
|
| 86 |
+
assert _split("123..145")[1::2] == ["123..145"]
|
| 87 |
+
assert _split("123..145,200..209")[1::2] == ["123..145", "200..209"]
|
| 88 |
+
assert _split("one-of(200,203)..300")[1::2] == ["one-of(200,203)..300"]
|
| 89 |
+
assert _split("complement(123..145),200..209")[1::2] == [
|
| 90 |
+
"complement(123..145)",
|
| 91 |
+
"200..209",
|
| 92 |
+
]
|
| 93 |
+
assert _split("123..145,one-of(200,203)..209")[1::2] == [
|
| 94 |
+
"123..145",
|
| 95 |
+
"one-of(200,203)..209",
|
| 96 |
+
]
|
| 97 |
+
assert _split("123..145,one-of(200,203)..one-of(209,211),300")[1::2] == [
|
| 98 |
+
"123..145",
|
| 99 |
+
"one-of(200,203)..one-of(209,211)",
|
| 100 |
+
"300",
|
| 101 |
+
]
|
| 102 |
+
assert _split("123..145,complement(one-of(200,203)..one-of(209,211)),300")[1::2] == [
|
| 103 |
+
"123..145",
|
| 104 |
+
"complement(one-of(200,203)..one-of(209,211))",
|
| 105 |
+
"300",
|
| 106 |
+
]
|
| 107 |
+
assert _split("123..145,200..one-of(209,211),300")[1::2] == [
|
| 108 |
+
"123..145",
|
| 109 |
+
"200..one-of(209,211)",
|
| 110 |
+
"300",
|
| 111 |
+
]
|
| 112 |
+
assert _split("123..145,200..one-of(209,211)")[1::2] == [
|
| 113 |
+
"123..145",
|
| 114 |
+
"200..one-of(209,211)",
|
| 115 |
+
]
|
| 116 |
+
assert _split(
|
| 117 |
+
"complement(149815..150200),complement(293787..295573),NC_016402.1:6618..6676,181647..181905"
|
| 118 |
+
)[1::2] == [
|
| 119 |
+
"complement(149815..150200)",
|
| 120 |
+
"complement(293787..295573)",
|
| 121 |
+
"NC_016402.1:6618..6676",
|
| 122 |
+
"181647..181905",
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
_pair_location = r"[<>]?-?\d+\.\.[<>]?-?\d+"
|
| 126 |
+
|
| 127 |
+
_between_location = r"\d+\^\d+"
|
| 128 |
+
|
| 129 |
+
_within_position = r"\(\d+\.\d+\)"
|
| 130 |
+
_within_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" % (
|
| 131 |
+
_within_position,
|
| 132 |
+
_within_position,
|
| 133 |
+
)
|
| 134 |
+
_within_position = r"\((\d+)\.(\d+)\)"
|
| 135 |
+
_re_within_position = re.compile(_within_position)
|
| 136 |
+
assert _re_within_position.match("(3.9)")
|
| 137 |
+
|
| 138 |
+
_oneof_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" % (_oneof_position, _oneof_position)
|
| 139 |
+
_oneof_position = r"one\-of\((\d+[,\d+]+)\)"
|
| 140 |
+
_re_oneof_position = re.compile(_oneof_position)
|
| 141 |
+
assert _re_oneof_position.match("one-of(6,9)")
|
| 142 |
+
assert not _re_oneof_position.match("one-of(3)")
|
| 143 |
+
assert _re_oneof_position.match("one-of(3,6)")
|
| 144 |
+
assert _re_oneof_position.match("one-of(3,6,9)")
|
| 145 |
+
|
| 146 |
+
_solo_location = r"[<>]?\d+"
|
| 147 |
+
_solo_bond = r"bond\(%s\)" % _solo_location
|
| 148 |
+
|
| 149 |
+
_re_location_category = re.compile(
|
| 150 |
+
r"^(?P<pair>%s)|(?P<between>%s)|(?P<within>%s)|(?P<oneof>%s)|(?P<bond>%s)|(?P<solo>%s)$"
|
| 151 |
+
% (
|
| 152 |
+
_pair_location,
|
| 153 |
+
_between_location,
|
| 154 |
+
_within_location,
|
| 155 |
+
_oneof_location,
|
| 156 |
+
_solo_bond,
|
| 157 |
+
_solo_location,
|
| 158 |
+
)
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class LocationParserError(ValueError):
|
| 163 |
+
"""Could not parse a feature location string."""
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class SeqFeature:
|
| 167 |
+
"""Represent a Sequence Feature on an object.
|
| 168 |
+
|
| 169 |
+
Attributes:
|
| 170 |
+
- location - the location of the feature on the sequence (SimpleLocation)
|
| 171 |
+
- type - the specified type of the feature (ie. CDS, exon, repeat...)
|
| 172 |
+
- id - A string identifier for the feature.
|
| 173 |
+
- qualifiers - A dictionary of qualifiers on the feature. These are
|
| 174 |
+
analogous to the qualifiers from a GenBank feature table. The keys of
|
| 175 |
+
the dictionary are qualifier names, the values are the qualifier
|
| 176 |
+
values.
|
| 177 |
+
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
def __init__(
|
| 181 |
+
self,
|
| 182 |
+
location=None,
|
| 183 |
+
type="",
|
| 184 |
+
id="<unknown id>",
|
| 185 |
+
qualifiers=None,
|
| 186 |
+
sub_features=None,
|
| 187 |
+
):
|
| 188 |
+
"""Initialize a SeqFeature on a sequence.
|
| 189 |
+
|
| 190 |
+
location can either be a SimpleLocation (with strand argument also
|
| 191 |
+
given if required), or None.
|
| 192 |
+
|
| 193 |
+
e.g. With no strand, on the forward strand, and on the reverse strand:
|
| 194 |
+
|
| 195 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 196 |
+
>>> f1 = SeqFeature(SimpleLocation(5, 10), type="domain")
|
| 197 |
+
>>> f1.location.strand == None
|
| 198 |
+
True
|
| 199 |
+
>>> f2 = SeqFeature(SimpleLocation(7, 110, strand=1), type="CDS")
|
| 200 |
+
>>> f2.location.strand == +1
|
| 201 |
+
True
|
| 202 |
+
>>> f3 = SeqFeature(SimpleLocation(9, 108, strand=-1), type="CDS")
|
| 203 |
+
>>> f3.location.strand == -1
|
| 204 |
+
True
|
| 205 |
+
|
| 206 |
+
For exact start/end positions, an integer can be used (as shown above)
|
| 207 |
+
as shorthand for the ExactPosition object. For non-exact locations, the
|
| 208 |
+
SimpleLocation must be specified via the appropriate position objects.
|
| 209 |
+
"""
|
| 210 |
+
if (
|
| 211 |
+
location is not None
|
| 212 |
+
and not isinstance(location, SimpleLocation)
|
| 213 |
+
and not isinstance(location, CompoundLocation)
|
| 214 |
+
):
|
| 215 |
+
raise TypeError(
|
| 216 |
+
"SimpleLocation, CompoundLocation (or None) required for the location"
|
| 217 |
+
)
|
| 218 |
+
self.location = location
|
| 219 |
+
self.type = type
|
| 220 |
+
self.id = id
|
| 221 |
+
self.qualifiers = {}
|
| 222 |
+
if qualifiers is not None:
|
| 223 |
+
self.qualifiers.update(qualifiers)
|
| 224 |
+
if sub_features is not None:
|
| 225 |
+
raise TypeError("Rather than sub_features, use a CompoundLocation")
|
| 226 |
+
|
| 227 |
+
def __eq__(self, other):
|
| 228 |
+
"""Check if two SeqFeature objects should be considered equal."""
|
| 229 |
+
return (
|
| 230 |
+
isinstance(other, SeqFeature)
|
| 231 |
+
and self.id == other.id
|
| 232 |
+
and self.type == other.type
|
| 233 |
+
and self.location == other.location
|
| 234 |
+
and self.qualifiers == other.qualifiers
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def __repr__(self):
|
| 238 |
+
"""Represent the feature as a string for debugging."""
|
| 239 |
+
answer = f"{self.__class__.__name__}({self.location!r}"
|
| 240 |
+
if self.type:
|
| 241 |
+
answer += f", type={self.type!r}"
|
| 242 |
+
if self.id and self.id != "<unknown id>":
|
| 243 |
+
answer += f", id={self.id!r}"
|
| 244 |
+
if self.qualifiers:
|
| 245 |
+
answer += ", qualifiers=..."
|
| 246 |
+
answer += ")"
|
| 247 |
+
return answer
|
| 248 |
+
|
| 249 |
+
def __str__(self):
|
| 250 |
+
"""Return the full feature as a python string."""
|
| 251 |
+
out = f"type: {self.type}\n"
|
| 252 |
+
out += f"location: {self.location}\n"
|
| 253 |
+
if self.id and self.id != "<unknown id>":
|
| 254 |
+
out += f"id: {self.id}\n"
|
| 255 |
+
out += "qualifiers:\n"
|
| 256 |
+
for qual_key in sorted(self.qualifiers):
|
| 257 |
+
out += f" Key: {qual_key}, Value: {self.qualifiers[qual_key]}\n"
|
| 258 |
+
return out
|
| 259 |
+
|
| 260 |
+
def _shift(self, offset):
|
| 261 |
+
"""Return a copy of the feature with its location shifted (PRIVATE).
|
| 262 |
+
|
| 263 |
+
The annotation qualifiers are copied.
|
| 264 |
+
"""
|
| 265 |
+
return SeqFeature(
|
| 266 |
+
location=self.location._shift(offset),
|
| 267 |
+
type=self.type,
|
| 268 |
+
id=self.id,
|
| 269 |
+
qualifiers=self.qualifiers.copy(),
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def _flip(self, length):
|
| 273 |
+
"""Return a copy of the feature with its location flipped (PRIVATE).
|
| 274 |
+
|
| 275 |
+
The argument length gives the length of the parent sequence. For
|
| 276 |
+
example a location 0..20 (+1 strand) with parent length 30 becomes
|
| 277 |
+
after flipping 10..30 (-1 strand). Strandless (None) or unknown
|
| 278 |
+
strand (0) remain like that - just their end points are changed.
|
| 279 |
+
|
| 280 |
+
The annotation qualifiers are copied.
|
| 281 |
+
"""
|
| 282 |
+
return SeqFeature(
|
| 283 |
+
location=self.location._flip(length),
|
| 284 |
+
type=self.type,
|
| 285 |
+
id=self.id,
|
| 286 |
+
qualifiers=self.qualifiers.copy(),
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
def extract(self, parent_sequence, references=None):
|
| 290 |
+
"""Extract the feature's sequence from supplied parent sequence.
|
| 291 |
+
|
| 292 |
+
The parent_sequence can be a Seq like object or a string, and will
|
| 293 |
+
generally return an object of the same type. The exception to this is
|
| 294 |
+
a MutableSeq as the parent sequence will return a Seq object.
|
| 295 |
+
|
| 296 |
+
This should cope with complex locations including complements, joins
|
| 297 |
+
and fuzzy positions. Even mixed strand features should work! This
|
| 298 |
+
also covers features on protein sequences (e.g. domains), although
|
| 299 |
+
here reverse strand features are not permitted. If the
|
| 300 |
+
location refers to other records, they must be supplied in the
|
| 301 |
+
optional dictionary references.
|
| 302 |
+
|
| 303 |
+
>>> from Bio.Seq import Seq
|
| 304 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 305 |
+
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
|
| 306 |
+
>>> f = SeqFeature(SimpleLocation(8, 15), type="domain")
|
| 307 |
+
>>> f.extract(seq)
|
| 308 |
+
Seq('VALIVIC')
|
| 309 |
+
|
| 310 |
+
If the SimpleLocation is None, e.g. when parsing invalid locus
|
| 311 |
+
locations in the GenBank parser, extract() will raise a ValueError.
|
| 312 |
+
|
| 313 |
+
>>> from Bio.Seq import Seq
|
| 314 |
+
>>> from Bio.SeqFeature import SeqFeature
|
| 315 |
+
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
|
| 316 |
+
>>> f = SeqFeature(None, type="domain")
|
| 317 |
+
>>> f.extract(seq)
|
| 318 |
+
Traceback (most recent call last):
|
| 319 |
+
...
|
| 320 |
+
ValueError: The feature's .location is None. Check the sequence file for a valid location.
|
| 321 |
+
|
| 322 |
+
Note - currently only compound features of type "join" are supported.
|
| 323 |
+
"""
|
| 324 |
+
if self.location is None:
|
| 325 |
+
raise ValueError(
|
| 326 |
+
"The feature's .location is None. Check the "
|
| 327 |
+
"sequence file for a valid location."
|
| 328 |
+
)
|
| 329 |
+
return self.location.extract(parent_sequence, references=references)
|
| 330 |
+
|
| 331 |
+
def translate(
|
| 332 |
+
self,
|
| 333 |
+
parent_sequence,
|
| 334 |
+
table="Standard",
|
| 335 |
+
start_offset=None,
|
| 336 |
+
stop_symbol="*",
|
| 337 |
+
to_stop=False,
|
| 338 |
+
cds=None,
|
| 339 |
+
gap=None,
|
| 340 |
+
):
|
| 341 |
+
"""Get a translation of the feature's sequence.
|
| 342 |
+
|
| 343 |
+
This method is intended for CDS or other features that code proteins
|
| 344 |
+
and is a shortcut that will both extract the feature and
|
| 345 |
+
translate it, taking into account the codon_start and transl_table
|
| 346 |
+
qualifiers, if they are present. If they are not present the
|
| 347 |
+
value of the arguments "table" and "start_offset" are used.
|
| 348 |
+
|
| 349 |
+
The "cds" parameter is set to "True" if the feature is of type
|
| 350 |
+
"CDS" but can be overridden by giving an explicit argument.
|
| 351 |
+
|
| 352 |
+
The arguments stop_symbol, to_stop and gap have the same meaning
|
| 353 |
+
as Seq.translate, refer to that documentation for further information.
|
| 354 |
+
|
| 355 |
+
Arguments:
|
| 356 |
+
- parent_sequence - A DNA or RNA sequence.
|
| 357 |
+
- table - Which codon table to use if there is no transl_table
|
| 358 |
+
qualifier for this feature. This can be either a name
|
| 359 |
+
(string), an NCBI identifier (integer), or a CodonTable
|
| 360 |
+
object (useful for non-standard genetic codes). This
|
| 361 |
+
defaults to the "Standard" table.
|
| 362 |
+
- start_offset - offset at which the first complete codon of a
|
| 363 |
+
coding feature can be found, relative to the first base of
|
| 364 |
+
that feature. Has a valid value of 0, 1 or 2. NOTE: this
|
| 365 |
+
uses python's 0-based numbering whereas the codon_start
|
| 366 |
+
qualifier in files from NCBI use 1-based numbering.
|
| 367 |
+
Will override a codon_start qualifier
|
| 368 |
+
|
| 369 |
+
>>> from Bio.Seq import Seq
|
| 370 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 371 |
+
>>> seq = Seq("GGTTACACTTACCGATAATGTCTCTGATGA")
|
| 372 |
+
>>> f = SeqFeature(SimpleLocation(0, 30), type="CDS")
|
| 373 |
+
>>> f.qualifiers['transl_table'] = [11]
|
| 374 |
+
|
| 375 |
+
Note that features of type CDS are subject to the usual
|
| 376 |
+
checks at translation. But you can override this behavior
|
| 377 |
+
by giving explicit arguments:
|
| 378 |
+
|
| 379 |
+
>>> f.translate(seq, cds=False)
|
| 380 |
+
Seq('GYTYR*CL**')
|
| 381 |
+
|
| 382 |
+
Now use the start_offset argument to change the frame. Note
|
| 383 |
+
this uses python 0-based numbering.
|
| 384 |
+
|
| 385 |
+
>>> f.translate(seq, start_offset=1, cds=False)
|
| 386 |
+
Seq('VTLTDNVSD')
|
| 387 |
+
|
| 388 |
+
Alternatively use the codon_start qualifier to do the same
|
| 389 |
+
thing. Note: this uses 1-based numbering, which is found
|
| 390 |
+
in files from NCBI.
|
| 391 |
+
|
| 392 |
+
>>> f.qualifiers['codon_start'] = [2]
|
| 393 |
+
>>> f.translate(seq, cds=False)
|
| 394 |
+
Seq('VTLTDNVSD')
|
| 395 |
+
"""
|
| 396 |
+
# see if this feature should be translated in a different
|
| 397 |
+
# frame using the "codon_start" qualifier
|
| 398 |
+
if start_offset is None:
|
| 399 |
+
try:
|
| 400 |
+
start_offset = int(self.qualifiers["codon_start"][0]) - 1
|
| 401 |
+
except KeyError:
|
| 402 |
+
start_offset = 0
|
| 403 |
+
|
| 404 |
+
if start_offset not in [0, 1, 2]:
|
| 405 |
+
raise ValueError(
|
| 406 |
+
"The start_offset must be 0, 1, or 2. "
|
| 407 |
+
f"The supplied value is {start_offset}. "
|
| 408 |
+
"Check the value of either the codon_start qualifier "
|
| 409 |
+
"or the start_offset argument"
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
feat_seq = self.extract(parent_sequence)[start_offset:]
|
| 413 |
+
codon_table = self.qualifiers.get("transl_table", [table])[0]
|
| 414 |
+
|
| 415 |
+
if cds is None:
|
| 416 |
+
cds = self.type == "CDS"
|
| 417 |
+
|
| 418 |
+
return feat_seq.translate(
|
| 419 |
+
table=codon_table,
|
| 420 |
+
stop_symbol=stop_symbol,
|
| 421 |
+
to_stop=to_stop,
|
| 422 |
+
cds=cds,
|
| 423 |
+
gap=gap,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
def __bool__(self):
|
| 427 |
+
"""Boolean value of an instance of this class (True).
|
| 428 |
+
|
| 429 |
+
This behavior is for backwards compatibility, since until the
|
| 430 |
+
__len__ method was added, a SeqFeature always evaluated as True.
|
| 431 |
+
|
| 432 |
+
Note that in comparison, Seq objects, strings, lists, etc, will all
|
| 433 |
+
evaluate to False if they have length zero.
|
| 434 |
+
|
| 435 |
+
WARNING: The SeqFeature may in future evaluate to False when its
|
| 436 |
+
length is zero (in order to better match normal python behavior)!
|
| 437 |
+
"""
|
| 438 |
+
return True
|
| 439 |
+
|
| 440 |
+
def __len__(self):
|
| 441 |
+
"""Return the length of the region where the feature is located.
|
| 442 |
+
|
| 443 |
+
>>> from Bio.Seq import Seq
|
| 444 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 445 |
+
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
|
| 446 |
+
>>> f = SeqFeature(SimpleLocation(8, 15), type="domain")
|
| 447 |
+
>>> len(f)
|
| 448 |
+
7
|
| 449 |
+
>>> f.extract(seq)
|
| 450 |
+
Seq('VALIVIC')
|
| 451 |
+
>>> len(f.extract(seq))
|
| 452 |
+
7
|
| 453 |
+
|
| 454 |
+
This is a proxy for taking the length of the feature's location:
|
| 455 |
+
|
| 456 |
+
>>> len(f.location)
|
| 457 |
+
7
|
| 458 |
+
|
| 459 |
+
For simple features this is the same as the region spanned (end
|
| 460 |
+
position minus start position using Pythonic counting). However, for
|
| 461 |
+
a compound location (e.g. a CDS as the join of several exons) the
|
| 462 |
+
gaps are not counted (e.g. introns). This ensures that len(f) matches
|
| 463 |
+
len(f.extract(parent_seq)), and also makes sure things work properly
|
| 464 |
+
with features wrapping the origin etc.
|
| 465 |
+
"""
|
| 466 |
+
return len(self.location)
|
| 467 |
+
|
| 468 |
+
def __iter__(self):
|
| 469 |
+
"""Iterate over the parent positions within the feature.
|
| 470 |
+
|
| 471 |
+
The iteration order is strand aware, and can be thought of as moving
|
| 472 |
+
along the feature using the parent sequence coordinates:
|
| 473 |
+
|
| 474 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 475 |
+
>>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain")
|
| 476 |
+
>>> len(f)
|
| 477 |
+
5
|
| 478 |
+
>>> for i in f: print(i)
|
| 479 |
+
9
|
| 480 |
+
8
|
| 481 |
+
7
|
| 482 |
+
6
|
| 483 |
+
5
|
| 484 |
+
>>> list(f)
|
| 485 |
+
[9, 8, 7, 6, 5]
|
| 486 |
+
|
| 487 |
+
This is a proxy for iterating over the location,
|
| 488 |
+
|
| 489 |
+
>>> list(f.location)
|
| 490 |
+
[9, 8, 7, 6, 5]
|
| 491 |
+
"""
|
| 492 |
+
return iter(self.location)
|
| 493 |
+
|
| 494 |
+
def __contains__(self, value):
|
| 495 |
+
"""Check if an integer position is within the feature.
|
| 496 |
+
|
| 497 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 498 |
+
>>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain")
|
| 499 |
+
>>> len(f)
|
| 500 |
+
5
|
| 501 |
+
>>> [i for i in range(15) if i in f]
|
| 502 |
+
[5, 6, 7, 8, 9]
|
| 503 |
+
|
| 504 |
+
For example, to see which features include a SNP position, you could
|
| 505 |
+
use this:
|
| 506 |
+
|
| 507 |
+
>>> from Bio import SeqIO
|
| 508 |
+
>>> record = SeqIO.read("GenBank/NC_000932.gb", "gb")
|
| 509 |
+
>>> for f in record.features:
|
| 510 |
+
... if 1750 in f:
|
| 511 |
+
... print("%s %s" % (f.type, f.location))
|
| 512 |
+
source [0:154478](+)
|
| 513 |
+
gene [1716:4347](-)
|
| 514 |
+
tRNA join{[4310:4347](-), [1716:1751](-)}
|
| 515 |
+
|
| 516 |
+
Note that for a feature defined as a join of several subfeatures (e.g.
|
| 517 |
+
the union of several exons) the gaps are not checked (e.g. introns).
|
| 518 |
+
In this example, the tRNA location is defined in the GenBank file as
|
| 519 |
+
complement(join(1717..1751,4311..4347)), so that position 1760 falls
|
| 520 |
+
in the gap:
|
| 521 |
+
|
| 522 |
+
>>> for f in record.features:
|
| 523 |
+
... if 1760 in f:
|
| 524 |
+
... print("%s %s" % (f.type, f.location))
|
| 525 |
+
source [0:154478](+)
|
| 526 |
+
gene [1716:4347](-)
|
| 527 |
+
|
| 528 |
+
Note that additional care may be required with fuzzy locations, for
|
| 529 |
+
example just before a BeforePosition:
|
| 530 |
+
|
| 531 |
+
>>> from Bio.SeqFeature import SeqFeature, SimpleLocation
|
| 532 |
+
>>> from Bio.SeqFeature import BeforePosition
|
| 533 |
+
>>> f = SeqFeature(SimpleLocation(BeforePosition(3), 8), type="domain")
|
| 534 |
+
>>> len(f)
|
| 535 |
+
5
|
| 536 |
+
>>> [i for i in range(10) if i in f]
|
| 537 |
+
[3, 4, 5, 6, 7]
|
| 538 |
+
|
| 539 |
+
Note that is is a proxy for testing membership on the location.
|
| 540 |
+
|
| 541 |
+
>>> [i for i in range(10) if i in f.location]
|
| 542 |
+
[3, 4, 5, 6, 7]
|
| 543 |
+
"""
|
| 544 |
+
return value in self.location
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
# --- References
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
# TODO -- Will this hold PubMed and Medline information decently?
|
| 551 |
+
class Reference:
|
| 552 |
+
"""Represent a Generic Reference object.
|
| 553 |
+
|
| 554 |
+
Attributes:
|
| 555 |
+
- location - A list of Location objects specifying regions of
|
| 556 |
+
the sequence that the references correspond to. If no locations are
|
| 557 |
+
specified, the entire sequence is assumed.
|
| 558 |
+
- authors - A big old string, or a list split by author, of authors
|
| 559 |
+
for the reference.
|
| 560 |
+
- title - The title of the reference.
|
| 561 |
+
- journal - Journal the reference was published in.
|
| 562 |
+
- medline_id - A medline reference for the article.
|
| 563 |
+
- pubmed_id - A pubmed reference for the article.
|
| 564 |
+
- comment - A place to stick any comments about the reference.
|
| 565 |
+
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
def __init__(self):
|
| 569 |
+
"""Initialize the class."""
|
| 570 |
+
self.location = []
|
| 571 |
+
self.authors = ""
|
| 572 |
+
self.consrtm = ""
|
| 573 |
+
self.title = ""
|
| 574 |
+
self.journal = ""
|
| 575 |
+
self.medline_id = ""
|
| 576 |
+
self.pubmed_id = ""
|
| 577 |
+
self.comment = ""
|
| 578 |
+
|
| 579 |
+
def __str__(self):
|
| 580 |
+
"""Return the full Reference object as a python string."""
|
| 581 |
+
out = ""
|
| 582 |
+
for single_location in self.location:
|
| 583 |
+
out += f"location: {single_location}\n"
|
| 584 |
+
out += f"authors: {self.authors}\n"
|
| 585 |
+
if self.consrtm:
|
| 586 |
+
out += f"consrtm: {self.consrtm}\n"
|
| 587 |
+
out += f"title: {self.title}\n"
|
| 588 |
+
out += f"journal: {self.journal}\n"
|
| 589 |
+
out += f"medline id: {self.medline_id}\n"
|
| 590 |
+
out += f"pubmed id: {self.pubmed_id}\n"
|
| 591 |
+
out += f"comment: {self.comment}\n"
|
| 592 |
+
return out
|
| 593 |
+
|
| 594 |
+
def __repr__(self):
|
| 595 |
+
"""Represent the Reference object as a string for debugging."""
|
| 596 |
+
# TODO - Update this is __init__ later accepts values
|
| 597 |
+
return f"{self.__class__.__name__}(title={self.title!r}, ...)"
|
| 598 |
+
|
| 599 |
+
def __eq__(self, other):
|
| 600 |
+
"""Check if two Reference objects should be considered equal.
|
| 601 |
+
|
| 602 |
+
Note prior to Biopython 1.70 the location was not compared, as
|
| 603 |
+
until then __eq__ for the SimpleLocation class was not defined.
|
| 604 |
+
"""
|
| 605 |
+
return (
|
| 606 |
+
self.authors == other.authors
|
| 607 |
+
and self.consrtm == other.consrtm
|
| 608 |
+
and self.title == other.title
|
| 609 |
+
and self.journal == other.journal
|
| 610 |
+
and self.medline_id == other.medline_id
|
| 611 |
+
and self.pubmed_id == other.pubmed_id
|
| 612 |
+
and self.comment == other.comment
|
| 613 |
+
and self.location == other.location
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
# --- Handling feature locations
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class Location(ABC):
|
| 621 |
+
"""Abstract base class representing a location."""
|
| 622 |
+
|
| 623 |
+
@abstractmethod
|
| 624 |
+
def __repr__(self):
|
| 625 |
+
"""Represent the Location object as a string for debugging."""
|
| 626 |
+
return f"{self.__class__.__name__}(...)"
|
| 627 |
+
|
| 628 |
+
@staticmethod
|
| 629 |
+
def fromstring(text, length=None, circular=False, stranded=True):
|
| 630 |
+
"""Create a Location object from a string.
|
| 631 |
+
|
| 632 |
+
This should accept any valid location string in the INSDC Feature Table
|
| 633 |
+
format (https://www.insdc.org/submitting-standards/feature-table/) as
|
| 634 |
+
used in GenBank, DDBJ and EMBL files.
|
| 635 |
+
|
| 636 |
+
Simple examples:
|
| 637 |
+
|
| 638 |
+
>>> Location.fromstring("123..456", 1000)
|
| 639 |
+
SimpleLocation(ExactPosition(122), ExactPosition(456), strand=1)
|
| 640 |
+
>>> Location.fromstring("complement(<123..>456)", 1000)
|
| 641 |
+
SimpleLocation(BeforePosition(122), AfterPosition(456), strand=-1)
|
| 642 |
+
|
| 643 |
+
A more complex location using within positions,
|
| 644 |
+
|
| 645 |
+
>>> Location.fromstring("(9.10)..(20.25)", 1000)
|
| 646 |
+
SimpleLocation(WithinPosition(8, left=8, right=9), WithinPosition(25, left=20, right=25), strand=1)
|
| 647 |
+
|
| 648 |
+
Notice how that will act as though it has overall start 8 and end 25.
|
| 649 |
+
|
| 650 |
+
Zero length between feature,
|
| 651 |
+
|
| 652 |
+
>>> Location.fromstring("123^124", 1000)
|
| 653 |
+
SimpleLocation(ExactPosition(123), ExactPosition(123), strand=1)
|
| 654 |
+
|
| 655 |
+
The expected sequence length is needed for a special case, a between
|
| 656 |
+
position at the start/end of a circular genome:
|
| 657 |
+
|
| 658 |
+
>>> Location.fromstring("1000^1", 1000)
|
| 659 |
+
SimpleLocation(ExactPosition(1000), ExactPosition(1000), strand=1)
|
| 660 |
+
|
| 661 |
+
Apart from this special case, between positions P^Q must have P+1==Q,
|
| 662 |
+
|
| 663 |
+
>>> Location.fromstring("123^456", 1000)
|
| 664 |
+
Traceback (most recent call last):
|
| 665 |
+
...
|
| 666 |
+
Bio.SeqFeature.LocationParserError: invalid feature location '123^456'
|
| 667 |
+
|
| 668 |
+
You can optionally provide a reference name:
|
| 669 |
+
|
| 670 |
+
>>> Location.fromstring("AL391218.9:105173..108462", 2000000)
|
| 671 |
+
SimpleLocation(ExactPosition(105172), ExactPosition(108462), strand=1, ref='AL391218.9')
|
| 672 |
+
|
| 673 |
+
>>> Location.fromstring("<2644..159", 2868, "circular")
|
| 674 |
+
CompoundLocation([SimpleLocation(BeforePosition(2643), ExactPosition(2868), strand=1), SimpleLocation(ExactPosition(0), ExactPosition(159), strand=1)], 'join')
|
| 675 |
+
"""
|
| 676 |
+
if text.startswith("complement("):
|
| 677 |
+
if text[-1] != ")":
|
| 678 |
+
raise ValueError(f"closing bracket missing in '{text}'")
|
| 679 |
+
text = text[11:-1]
|
| 680 |
+
strand = -1
|
| 681 |
+
elif stranded:
|
| 682 |
+
strand = 1
|
| 683 |
+
else:
|
| 684 |
+
strand = None
|
| 685 |
+
|
| 686 |
+
# Determine if we have a simple location or a compound location
|
| 687 |
+
if text.startswith("join("):
|
| 688 |
+
operator = "join"
|
| 689 |
+
parts = _split(text[5:-1])[1::2]
|
| 690 |
+
# assert parts[0] == "" and parts[-1] == ""
|
| 691 |
+
elif text.startswith("order("):
|
| 692 |
+
operator = "order"
|
| 693 |
+
parts = _split(text[6:-1])[1::2]
|
| 694 |
+
# assert parts[0] == "" and parts[-1] == ""
|
| 695 |
+
elif text.startswith("bond("):
|
| 696 |
+
operator = "bond"
|
| 697 |
+
parts = _split(text[5:-1])[1::2]
|
| 698 |
+
# assert parts[0] == "" and parts[-1] == ""
|
| 699 |
+
else:
|
| 700 |
+
loc = SimpleLocation.fromstring(text, length, circular)
|
| 701 |
+
loc.strand = strand
|
| 702 |
+
if strand == -1:
|
| 703 |
+
loc.parts.reverse()
|
| 704 |
+
return loc
|
| 705 |
+
locs = []
|
| 706 |
+
for part in parts:
|
| 707 |
+
loc = SimpleLocation.fromstring(part, length, circular)
|
| 708 |
+
if loc is None:
|
| 709 |
+
break
|
| 710 |
+
if loc.strand == -1:
|
| 711 |
+
if strand == -1:
|
| 712 |
+
raise LocationParserError("double complement in '{text}'?")
|
| 713 |
+
else:
|
| 714 |
+
loc.strand = strand
|
| 715 |
+
locs.extend(loc.parts)
|
| 716 |
+
else:
|
| 717 |
+
if len(locs) == 1:
|
| 718 |
+
return loc
|
| 719 |
+
# Historically a join on the reverse strand has been represented
|
| 720 |
+
# in Biopython with both the parent SeqFeature and its children
|
| 721 |
+
# (the exons for a CDS) all given a strand of -1. Likewise, for
|
| 722 |
+
# a join feature on the forward strand they all have strand +1.
|
| 723 |
+
# However, we must also consider evil mixed strand examples like
|
| 724 |
+
# this, join(complement(69611..69724),139856..140087,140625..140650)
|
| 725 |
+
if strand == -1:
|
| 726 |
+
# Whole thing was wrapped in complement(...)
|
| 727 |
+
for loc in locs:
|
| 728 |
+
assert loc.strand == -1
|
| 729 |
+
# Reverse the backwards order used in GenBank files
|
| 730 |
+
# with complement(join(...))
|
| 731 |
+
locs = locs[::-1]
|
| 732 |
+
return CompoundLocation(locs, operator=operator)
|
| 733 |
+
# Not recognized
|
| 734 |
+
if "order" in text and "join" in text:
|
| 735 |
+
# See Bug 3197
|
| 736 |
+
raise LocationParserError(
|
| 737 |
+
f"failed to parse feature location '{text}' containing a combination of 'join' and 'order' (nested operators) are illegal"
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
# See issue #937. Note that NCBI has already fixed this record.
|
| 741 |
+
if ",)" in text:
|
| 742 |
+
warnings.warn(
|
| 743 |
+
"Dropping trailing comma in malformed feature location",
|
| 744 |
+
BiopythonParserWarning,
|
| 745 |
+
)
|
| 746 |
+
text = text.replace(",)", ")")
|
| 747 |
+
return Location.fromstring(text)
|
| 748 |
+
|
| 749 |
+
raise LocationParserError(f"failed to parse feature location '{text}'")
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
class SimpleLocation(Location):
|
| 753 |
+
"""Specify the location of a feature along a sequence.
|
| 754 |
+
|
| 755 |
+
The SimpleLocation is used for simple continuous features, which can
|
| 756 |
+
be described as running from a start position to and end position
|
| 757 |
+
(optionally with a strand and reference information). More complex
|
| 758 |
+
locations made up from several non-continuous parts (e.g. a coding
|
| 759 |
+
sequence made up of several exons) are described using a SeqFeature
|
| 760 |
+
with a CompoundLocation.
|
| 761 |
+
|
| 762 |
+
Note that the start and end location numbering follow Python's scheme,
|
| 763 |
+
thus a GenBank entry of 123..150 (one based counting) becomes a location
|
| 764 |
+
of [122:150] (zero based counting).
|
| 765 |
+
|
| 766 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 767 |
+
>>> f = SimpleLocation(122, 150)
|
| 768 |
+
>>> print(f)
|
| 769 |
+
[122:150]
|
| 770 |
+
>>> print(f.start)
|
| 771 |
+
122
|
| 772 |
+
>>> print(f.end)
|
| 773 |
+
150
|
| 774 |
+
>>> print(f.strand)
|
| 775 |
+
None
|
| 776 |
+
|
| 777 |
+
Note the strand defaults to None. If you are working with nucleotide
|
| 778 |
+
sequences you'd want to be explicit if it is the forward strand:
|
| 779 |
+
|
| 780 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 781 |
+
>>> f = SimpleLocation(122, 150, strand=+1)
|
| 782 |
+
>>> print(f)
|
| 783 |
+
[122:150](+)
|
| 784 |
+
>>> print(f.strand)
|
| 785 |
+
1
|
| 786 |
+
|
| 787 |
+
Note that for a parent sequence of length n, the SimpleLocation
|
| 788 |
+
start and end must satisfy the inequality 0 <= start <= end <= n.
|
| 789 |
+
This means even for features on the reverse strand of a nucleotide
|
| 790 |
+
sequence, we expect the 'start' coordinate to be less than the
|
| 791 |
+
'end'.
|
| 792 |
+
|
| 793 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 794 |
+
>>> r = SimpleLocation(122, 150, strand=-1)
|
| 795 |
+
>>> print(r)
|
| 796 |
+
[122:150](-)
|
| 797 |
+
>>> print(r.start)
|
| 798 |
+
122
|
| 799 |
+
>>> print(r.end)
|
| 800 |
+
150
|
| 801 |
+
>>> print(r.strand)
|
| 802 |
+
-1
|
| 803 |
+
|
| 804 |
+
i.e. Rather than thinking of the 'start' and 'end' biologically in a
|
| 805 |
+
strand aware manner, think of them as the 'left most' or 'minimum'
|
| 806 |
+
boundary, and the 'right most' or 'maximum' boundary of the region
|
| 807 |
+
being described. This is particularly important with compound
|
| 808 |
+
locations describing non-continuous regions.
|
| 809 |
+
|
| 810 |
+
In the example above we have used standard exact positions, but there
|
| 811 |
+
are also specialised position objects used to represent fuzzy positions
|
| 812 |
+
as well, for example a GenBank location like complement(<123..150)
|
| 813 |
+
would use a BeforePosition object for the start.
|
| 814 |
+
"""
|
| 815 |
+
|
| 816 |
+
def __init__(self, start, end, strand=None, ref=None, ref_db=None):
|
| 817 |
+
"""Initialize the class.
|
| 818 |
+
|
| 819 |
+
start and end arguments specify the values where the feature begins
|
| 820 |
+
and ends. These can either by any of the ``*Position`` objects that
|
| 821 |
+
inherit from Position, or can just be integers specifying the position.
|
| 822 |
+
In the case of integers, the values are assumed to be exact and are
|
| 823 |
+
converted in ExactPosition arguments. This is meant to make it easy
|
| 824 |
+
to deal with non-fuzzy ends.
|
| 825 |
+
|
| 826 |
+
i.e. Short form:
|
| 827 |
+
|
| 828 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 829 |
+
>>> loc = SimpleLocation(5, 10, strand=-1)
|
| 830 |
+
>>> print(loc)
|
| 831 |
+
[5:10](-)
|
| 832 |
+
|
| 833 |
+
Explicit form:
|
| 834 |
+
|
| 835 |
+
>>> from Bio.SeqFeature import SimpleLocation, ExactPosition
|
| 836 |
+
>>> loc = SimpleLocation(ExactPosition(5), ExactPosition(10), strand=-1)
|
| 837 |
+
>>> print(loc)
|
| 838 |
+
[5:10](-)
|
| 839 |
+
|
| 840 |
+
Other fuzzy positions are used similarly,
|
| 841 |
+
|
| 842 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 843 |
+
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
|
| 844 |
+
>>> loc2 = SimpleLocation(BeforePosition(5), AfterPosition(10), strand=-1)
|
| 845 |
+
>>> print(loc2)
|
| 846 |
+
[<5:>10](-)
|
| 847 |
+
|
| 848 |
+
For nucleotide features you will also want to specify the strand,
|
| 849 |
+
use 1 for the forward (plus) strand, -1 for the reverse (negative)
|
| 850 |
+
strand, 0 for stranded but strand unknown (? in GFF3), or None for
|
| 851 |
+
when the strand does not apply (dot in GFF3), e.g. features on
|
| 852 |
+
proteins.
|
| 853 |
+
|
| 854 |
+
>>> loc = SimpleLocation(5, 10, strand=+1)
|
| 855 |
+
>>> print(loc)
|
| 856 |
+
[5:10](+)
|
| 857 |
+
>>> print(loc.strand)
|
| 858 |
+
1
|
| 859 |
+
|
| 860 |
+
Normally feature locations are given relative to the parent
|
| 861 |
+
sequence you are working with, but an explicit accession can
|
| 862 |
+
be given with the optional ref and db_ref strings:
|
| 863 |
+
|
| 864 |
+
>>> loc = SimpleLocation(105172, 108462, ref="AL391218.9", strand=1)
|
| 865 |
+
>>> print(loc)
|
| 866 |
+
AL391218.9[105172:108462](+)
|
| 867 |
+
>>> print(loc.ref)
|
| 868 |
+
AL391218.9
|
| 869 |
+
|
| 870 |
+
"""
|
| 871 |
+
# TODO - Check 0 <= start <= end (<= length of reference)
|
| 872 |
+
if isinstance(start, Position):
|
| 873 |
+
self._start = start
|
| 874 |
+
elif isinstance(start, int):
|
| 875 |
+
self._start = ExactPosition(start)
|
| 876 |
+
else:
|
| 877 |
+
raise TypeError(f"start={start!r} {type(start)}")
|
| 878 |
+
if isinstance(end, Position):
|
| 879 |
+
self._end = end
|
| 880 |
+
elif isinstance(end, int):
|
| 881 |
+
self._end = ExactPosition(end)
|
| 882 |
+
else:
|
| 883 |
+
raise TypeError(f"end={end!r} {type(end)}")
|
| 884 |
+
if (
|
| 885 |
+
isinstance(self.start, int)
|
| 886 |
+
and isinstance(self.end, int)
|
| 887 |
+
and self.start > self.end
|
| 888 |
+
):
|
| 889 |
+
raise ValueError(
|
| 890 |
+
f"End location ({self.end}) must be greater than "
|
| 891 |
+
f"or equal to start location ({self.start})"
|
| 892 |
+
)
|
| 893 |
+
self.strand = strand
|
| 894 |
+
self.ref = ref
|
| 895 |
+
self.ref_db = ref_db
|
| 896 |
+
|
| 897 |
+
@staticmethod
|
| 898 |
+
def fromstring(text, length=None, circular=False):
|
| 899 |
+
"""Create a SimpleLocation object from a string."""
|
| 900 |
+
if text.startswith("complement("):
|
| 901 |
+
text = text[11:-1]
|
| 902 |
+
strand = -1
|
| 903 |
+
else:
|
| 904 |
+
strand = None
|
| 905 |
+
# Try simple cases first for speed
|
| 906 |
+
try:
|
| 907 |
+
s, e = text.split("..")
|
| 908 |
+
s = int(s) - 1
|
| 909 |
+
e = int(e)
|
| 910 |
+
except ValueError:
|
| 911 |
+
pass
|
| 912 |
+
else:
|
| 913 |
+
if 0 <= s < e:
|
| 914 |
+
return SimpleLocation(s, e, strand)
|
| 915 |
+
# Try general case
|
| 916 |
+
try:
|
| 917 |
+
ref, text = text.split(":")
|
| 918 |
+
except ValueError:
|
| 919 |
+
ref = None
|
| 920 |
+
m = _re_location_category.match(text)
|
| 921 |
+
if m is None:
|
| 922 |
+
raise LocationParserError(f"Could not parse feature location '{text}'")
|
| 923 |
+
for key, value in m.groupdict().items():
|
| 924 |
+
if value is not None:
|
| 925 |
+
break
|
| 926 |
+
assert value == text
|
| 927 |
+
if key == "bond":
|
| 928 |
+
# e.g. bond(196)
|
| 929 |
+
warnings.warn(
|
| 930 |
+
"Dropping bond qualifier in feature location",
|
| 931 |
+
BiopythonParserWarning,
|
| 932 |
+
)
|
| 933 |
+
text = text[5:-1]
|
| 934 |
+
s_pos = Position.fromstring(text, -1)
|
| 935 |
+
e_pos = Position.fromstring(text)
|
| 936 |
+
elif key == "solo":
|
| 937 |
+
# e.g. "123"
|
| 938 |
+
s_pos = Position.fromstring(text, -1)
|
| 939 |
+
e_pos = Position.fromstring(text)
|
| 940 |
+
elif key in ("pair", "within", "oneof"):
|
| 941 |
+
s, e = text.split("..")
|
| 942 |
+
# Attempt to fix features that span the origin
|
| 943 |
+
s_pos = Position.fromstring(s, -1)
|
| 944 |
+
e_pos = Position.fromstring(e)
|
| 945 |
+
# We have seen Ensembl data in "GenBank Format" with length zero in the LOCUS
|
| 946 |
+
# and variation features with s_pos >= e_pos - they are not origin wrapping!
|
| 947 |
+
if e_pos <= s_pos and length and s_pos < length:
|
| 948 |
+
# Assuming this is meant to be origin wrapping.
|
| 949 |
+
# Create a CompoundLocation of the wrapped feature,
|
| 950 |
+
# consisting of two SimpleLocation objects to extend to
|
| 951 |
+
# the list of feature locations.
|
| 952 |
+
if not circular:
|
| 953 |
+
raise LocationParserError(
|
| 954 |
+
f"it appears that '{text}' is a feature that spans the"
|
| 955 |
+
" origin, but the sequence topology is undefined"
|
| 956 |
+
)
|
| 957 |
+
warnings.warn(
|
| 958 |
+
f"Attempting to fix invalid location {text!r} as it looks"
|
| 959 |
+
" like incorrect origin wrapping. Please fix input file,"
|
| 960 |
+
" this could have unintended behavior.",
|
| 961 |
+
BiopythonParserWarning,
|
| 962 |
+
)
|
| 963 |
+
|
| 964 |
+
f1 = SimpleLocation(s_pos, length, strand)
|
| 965 |
+
f2 = SimpleLocation(0, e_pos, strand)
|
| 966 |
+
|
| 967 |
+
if strand == -1:
|
| 968 |
+
# For complementary features spanning the origin
|
| 969 |
+
return f2 + f1
|
| 970 |
+
else:
|
| 971 |
+
return f1 + f2
|
| 972 |
+
elif key == "between":
|
| 973 |
+
# A between location like "67^68" (one based counting) is a
|
| 974 |
+
# special case (note it has zero length). In python slice
|
| 975 |
+
# notation this is 67:67, a zero length slice. See Bug 2622
|
| 976 |
+
# Further more, on a circular genome of length N you can have
|
| 977 |
+
# a location N^1 meaning the junction at the origin. See Bug 3098.
|
| 978 |
+
# NOTE - We can imagine between locations like "2^4", but this
|
| 979 |
+
# is just "3". Similarly, "2^5" is just "3..4"
|
| 980 |
+
s, e = text.split("^")
|
| 981 |
+
s = int(s)
|
| 982 |
+
e = int(e)
|
| 983 |
+
if s + 1 == e or (s == length and e == 1):
|
| 984 |
+
s_pos = ExactPosition(s)
|
| 985 |
+
e_pos = s_pos
|
| 986 |
+
else:
|
| 987 |
+
raise LocationParserError(f"invalid feature location '{text}'")
|
| 988 |
+
if s_pos < 0:
|
| 989 |
+
raise LocationParserError(
|
| 990 |
+
f"negative starting position in feature location '{text}'"
|
| 991 |
+
)
|
| 992 |
+
return SimpleLocation(s_pos, e_pos, strand, ref=ref)
|
| 993 |
+
|
| 994 |
+
def _get_strand(self):
|
| 995 |
+
"""Get function for the strand property (PRIVATE)."""
|
| 996 |
+
return self._strand
|
| 997 |
+
|
| 998 |
+
def _set_strand(self, value):
|
| 999 |
+
"""Set function for the strand property (PRIVATE)."""
|
| 1000 |
+
if value not in [+1, -1, 0, None]:
|
| 1001 |
+
raise ValueError(f"Strand should be +1, -1, 0 or None, not {value!r}")
|
| 1002 |
+
self._strand = value
|
| 1003 |
+
|
| 1004 |
+
strand = property(
|
| 1005 |
+
fget=_get_strand,
|
| 1006 |
+
fset=_set_strand,
|
| 1007 |
+
doc="Strand of the location (+1, -1, 0 or None).",
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
def __str__(self):
|
| 1011 |
+
"""Return a representation of the SimpleLocation object (with python counting).
|
| 1012 |
+
|
| 1013 |
+
For the simple case this uses the python splicing syntax, [122:150]
|
| 1014 |
+
(zero based counting) which GenBank would call 123..150 (one based
|
| 1015 |
+
counting).
|
| 1016 |
+
"""
|
| 1017 |
+
answer = f"[{self._start}:{self._end}]"
|
| 1018 |
+
if self.ref and self.ref_db:
|
| 1019 |
+
answer = f"{self.ref_db}:{self.ref}{answer}"
|
| 1020 |
+
elif self.ref:
|
| 1021 |
+
answer = self.ref + answer
|
| 1022 |
+
# Is ref_db without ref meaningful?
|
| 1023 |
+
if self.strand is None:
|
| 1024 |
+
return answer
|
| 1025 |
+
elif self.strand == +1:
|
| 1026 |
+
return answer + "(+)"
|
| 1027 |
+
elif self.strand == -1:
|
| 1028 |
+
return answer + "(-)"
|
| 1029 |
+
else:
|
| 1030 |
+
# strand = 0, stranded but strand unknown, ? in GFF3
|
| 1031 |
+
return answer + "(?)"
|
| 1032 |
+
|
| 1033 |
+
def __repr__(self):
|
| 1034 |
+
"""Represent the SimpleLocation object as a string for debugging."""
|
| 1035 |
+
optional = ""
|
| 1036 |
+
if self.strand is not None:
|
| 1037 |
+
optional += f", strand={self.strand!r}"
|
| 1038 |
+
if self.ref is not None:
|
| 1039 |
+
optional += f", ref={self.ref!r}"
|
| 1040 |
+
if self.ref_db is not None:
|
| 1041 |
+
optional += f", ref_db={self.ref_db!r}"
|
| 1042 |
+
return f"{self.__class__.__name__}({self.start!r}, {self.end!r}{optional})"
|
| 1043 |
+
|
| 1044 |
+
def __add__(self, other):
|
| 1045 |
+
"""Combine location with another SimpleLocation object, or shift it.
|
| 1046 |
+
|
| 1047 |
+
You can add two feature locations to make a join CompoundLocation:
|
| 1048 |
+
|
| 1049 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1050 |
+
>>> f1 = SimpleLocation(5, 10)
|
| 1051 |
+
>>> f2 = SimpleLocation(20, 30)
|
| 1052 |
+
>>> combined = f1 + f2
|
| 1053 |
+
>>> print(combined)
|
| 1054 |
+
join{[5:10], [20:30]}
|
| 1055 |
+
|
| 1056 |
+
This is thus equivalent to:
|
| 1057 |
+
|
| 1058 |
+
>>> from Bio.SeqFeature import CompoundLocation
|
| 1059 |
+
>>> join = CompoundLocation([f1, f2])
|
| 1060 |
+
>>> print(join)
|
| 1061 |
+
join{[5:10], [20:30]}
|
| 1062 |
+
|
| 1063 |
+
You can also use sum(...) in this way:
|
| 1064 |
+
|
| 1065 |
+
>>> join = sum([f1, f2])
|
| 1066 |
+
>>> print(join)
|
| 1067 |
+
join{[5:10], [20:30]}
|
| 1068 |
+
|
| 1069 |
+
Furthermore, you can combine a SimpleLocation with a CompoundLocation
|
| 1070 |
+
in this way.
|
| 1071 |
+
|
| 1072 |
+
Separately, adding an integer will give a new SimpleLocation with
|
| 1073 |
+
its start and end offset by that amount. For example:
|
| 1074 |
+
|
| 1075 |
+
>>> print(f1)
|
| 1076 |
+
[5:10]
|
| 1077 |
+
>>> print(f1 + 100)
|
| 1078 |
+
[105:110]
|
| 1079 |
+
>>> print(200 + f1)
|
| 1080 |
+
[205:210]
|
| 1081 |
+
|
| 1082 |
+
This can be useful when editing annotation.
|
| 1083 |
+
"""
|
| 1084 |
+
if isinstance(other, SimpleLocation):
|
| 1085 |
+
return CompoundLocation([self, other])
|
| 1086 |
+
elif isinstance(other, int):
|
| 1087 |
+
return self._shift(other)
|
| 1088 |
+
else:
|
| 1089 |
+
# This will allow CompoundLocation's __radd__ to be called:
|
| 1090 |
+
return NotImplemented
|
| 1091 |
+
|
| 1092 |
+
def __radd__(self, other):
|
| 1093 |
+
"""Return a SimpleLocation object by shifting the location by an integer amount."""
|
| 1094 |
+
if isinstance(other, int):
|
| 1095 |
+
return self._shift(other)
|
| 1096 |
+
else:
|
| 1097 |
+
return NotImplemented
|
| 1098 |
+
|
| 1099 |
+
def __sub__(self, other):
|
| 1100 |
+
"""Subtracting an integer will shift the start and end by that amount.
|
| 1101 |
+
|
| 1102 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1103 |
+
>>> f1 = SimpleLocation(105, 150)
|
| 1104 |
+
>>> print(f1)
|
| 1105 |
+
[105:150]
|
| 1106 |
+
>>> print(f1 - 100)
|
| 1107 |
+
[5:50]
|
| 1108 |
+
|
| 1109 |
+
This can be useful when editing annotation. You can also add an integer
|
| 1110 |
+
to a feature location (which shifts in the opposite direction).
|
| 1111 |
+
"""
|
| 1112 |
+
if isinstance(other, int):
|
| 1113 |
+
return self._shift(-other)
|
| 1114 |
+
else:
|
| 1115 |
+
return NotImplemented
|
| 1116 |
+
|
| 1117 |
+
def __nonzero__(self):
|
| 1118 |
+
"""Return True regardless of the length of the feature.
|
| 1119 |
+
|
| 1120 |
+
This behavior is for backwards compatibility, since until the
|
| 1121 |
+
__len__ method was added, a SimpleLocation always evaluated as True.
|
| 1122 |
+
|
| 1123 |
+
Note that in comparison, Seq objects, strings, lists, etc, will all
|
| 1124 |
+
evaluate to False if they have length zero.
|
| 1125 |
+
|
| 1126 |
+
WARNING: The SimpleLocation may in future evaluate to False when its
|
| 1127 |
+
length is zero (in order to better match normal python behavior)!
|
| 1128 |
+
"""
|
| 1129 |
+
return True
|
| 1130 |
+
|
| 1131 |
+
def __len__(self):
|
| 1132 |
+
"""Return the length of the region described by the SimpleLocation object.
|
| 1133 |
+
|
| 1134 |
+
Note that extra care may be needed for fuzzy locations, e.g.
|
| 1135 |
+
|
| 1136 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1137 |
+
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
|
| 1138 |
+
>>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
|
| 1139 |
+
>>> len(loc)
|
| 1140 |
+
5
|
| 1141 |
+
"""
|
| 1142 |
+
return int(self._end) - int(self._start)
|
| 1143 |
+
|
| 1144 |
+
def __contains__(self, value):
|
| 1145 |
+
"""Check if an integer position is within the SimpleLocation object.
|
| 1146 |
+
|
| 1147 |
+
Note that extra care may be needed for fuzzy locations, e.g.
|
| 1148 |
+
|
| 1149 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1150 |
+
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
|
| 1151 |
+
>>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
|
| 1152 |
+
>>> len(loc)
|
| 1153 |
+
5
|
| 1154 |
+
>>> [i for i in range(15) if i in loc]
|
| 1155 |
+
[5, 6, 7, 8, 9]
|
| 1156 |
+
"""
|
| 1157 |
+
if not isinstance(value, int):
|
| 1158 |
+
raise ValueError(
|
| 1159 |
+
"Currently we only support checking for integer "
|
| 1160 |
+
"positions being within a SimpleLocation."
|
| 1161 |
+
)
|
| 1162 |
+
if value < self._start or value >= self._end:
|
| 1163 |
+
return False
|
| 1164 |
+
else:
|
| 1165 |
+
return True
|
| 1166 |
+
|
| 1167 |
+
def __iter__(self):
|
| 1168 |
+
"""Iterate over the parent positions within the SimpleLocation object.
|
| 1169 |
+
|
| 1170 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1171 |
+
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
|
| 1172 |
+
>>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
|
| 1173 |
+
>>> len(loc)
|
| 1174 |
+
5
|
| 1175 |
+
>>> for i in loc: print(i)
|
| 1176 |
+
5
|
| 1177 |
+
6
|
| 1178 |
+
7
|
| 1179 |
+
8
|
| 1180 |
+
9
|
| 1181 |
+
>>> list(loc)
|
| 1182 |
+
[5, 6, 7, 8, 9]
|
| 1183 |
+
>>> [i for i in range(15) if i in loc]
|
| 1184 |
+
[5, 6, 7, 8, 9]
|
| 1185 |
+
|
| 1186 |
+
Note this is strand aware:
|
| 1187 |
+
|
| 1188 |
+
>>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10), strand = -1)
|
| 1189 |
+
>>> list(loc)
|
| 1190 |
+
[9, 8, 7, 6, 5]
|
| 1191 |
+
"""
|
| 1192 |
+
if self.strand == -1:
|
| 1193 |
+
yield from range(self._end - 1, self._start - 1, -1)
|
| 1194 |
+
else:
|
| 1195 |
+
yield from range(self._start, self._end)
|
| 1196 |
+
|
| 1197 |
+
def __eq__(self, other):
|
| 1198 |
+
"""Implement equality by comparing all the location attributes."""
|
| 1199 |
+
if not isinstance(other, SimpleLocation):
|
| 1200 |
+
return False
|
| 1201 |
+
return (
|
| 1202 |
+
self._start == other.start
|
| 1203 |
+
and self._end == other.end
|
| 1204 |
+
and self._strand == other.strand
|
| 1205 |
+
and self.ref == other.ref
|
| 1206 |
+
and self.ref_db == other.ref_db
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
def _shift(self, offset):
|
| 1210 |
+
"""Return a copy of the SimpleLocation shifted by an offset (PRIVATE).
|
| 1211 |
+
|
| 1212 |
+
Returns self when location is relative to an external reference.
|
| 1213 |
+
"""
|
| 1214 |
+
# TODO - What if offset is a fuzzy position?
|
| 1215 |
+
if self.ref or self.ref_db:
|
| 1216 |
+
return self
|
| 1217 |
+
return SimpleLocation(
|
| 1218 |
+
start=self._start + offset,
|
| 1219 |
+
end=self._end + offset,
|
| 1220 |
+
strand=self.strand,
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
def _flip(self, length):
|
| 1224 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE).
|
| 1225 |
+
|
| 1226 |
+
Returns self when location is relative to an external reference.
|
| 1227 |
+
"""
|
| 1228 |
+
if self.ref or self.ref_db:
|
| 1229 |
+
return self
|
| 1230 |
+
# Note this will flip the start and end too!
|
| 1231 |
+
if self.strand == +1:
|
| 1232 |
+
flip_strand = -1
|
| 1233 |
+
elif self.strand == -1:
|
| 1234 |
+
flip_strand = +1
|
| 1235 |
+
else:
|
| 1236 |
+
# 0 or None
|
| 1237 |
+
flip_strand = self.strand
|
| 1238 |
+
return SimpleLocation(
|
| 1239 |
+
start=self._end._flip(length),
|
| 1240 |
+
end=self._start._flip(length),
|
| 1241 |
+
strand=flip_strand,
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
@property
|
| 1245 |
+
def parts(self):
|
| 1246 |
+
"""Read only list of sections (always one, the SimpleLocation object).
|
| 1247 |
+
|
| 1248 |
+
This is a convenience property allowing you to write code handling
|
| 1249 |
+
both SimpleLocation objects (with one part) and more complex
|
| 1250 |
+
CompoundLocation objects (with multiple parts) interchangeably.
|
| 1251 |
+
"""
|
| 1252 |
+
return [self]
|
| 1253 |
+
|
| 1254 |
+
@property
|
| 1255 |
+
def start(self):
|
| 1256 |
+
"""Start location - left most (minimum) value, regardless of strand.
|
| 1257 |
+
|
| 1258 |
+
Read only, returns an integer like position object, possibly a fuzzy
|
| 1259 |
+
position.
|
| 1260 |
+
"""
|
| 1261 |
+
return self._start
|
| 1262 |
+
|
| 1263 |
+
@property
|
| 1264 |
+
def end(self):
|
| 1265 |
+
"""End location - right most (maximum) value, regardless of strand.
|
| 1266 |
+
|
| 1267 |
+
Read only, returns an integer like position object, possibly a fuzzy
|
| 1268 |
+
position.
|
| 1269 |
+
"""
|
| 1270 |
+
return self._end
|
| 1271 |
+
|
| 1272 |
+
def extract(self, parent_sequence, references=None):
|
| 1273 |
+
"""Extract the sequence from supplied parent sequence using the SimpleLocation object.
|
| 1274 |
+
|
| 1275 |
+
The parent_sequence can be a Seq like object or a string, and will
|
| 1276 |
+
generally return an object of the same type. The exception to this is
|
| 1277 |
+
a MutableSeq as the parent sequence will return a Seq object.
|
| 1278 |
+
If the location refers to other records, they must be supplied
|
| 1279 |
+
in the optional dictionary references.
|
| 1280 |
+
|
| 1281 |
+
>>> from Bio.Seq import Seq
|
| 1282 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1283 |
+
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
|
| 1284 |
+
>>> feature_loc = SimpleLocation(8, 15)
|
| 1285 |
+
>>> feature_loc.extract(seq)
|
| 1286 |
+
Seq('VALIVIC')
|
| 1287 |
+
|
| 1288 |
+
"""
|
| 1289 |
+
if self.ref or self.ref_db:
|
| 1290 |
+
if not references:
|
| 1291 |
+
raise ValueError(
|
| 1292 |
+
f"Feature references another sequence ({self.ref}),"
|
| 1293 |
+
" references mandatory"
|
| 1294 |
+
)
|
| 1295 |
+
elif self.ref not in references:
|
| 1296 |
+
# KeyError?
|
| 1297 |
+
raise ValueError(
|
| 1298 |
+
f"Feature references another sequence ({self.ref}),"
|
| 1299 |
+
" not found in references"
|
| 1300 |
+
)
|
| 1301 |
+
parent_sequence = references[self.ref]
|
| 1302 |
+
f_seq = parent_sequence[int(self.start) : int(self.end)]
|
| 1303 |
+
if isinstance(f_seq, MutableSeq):
|
| 1304 |
+
f_seq = Seq(f_seq)
|
| 1305 |
+
if self.strand == -1:
|
| 1306 |
+
f_seq = reverse_complement(f_seq)
|
| 1307 |
+
return f_seq
|
| 1308 |
+
|
| 1309 |
+
|
| 1310 |
+
FeatureLocation = SimpleLocation # OBSOLETE; for backward compatibility only.
|
| 1311 |
+
|
| 1312 |
+
|
| 1313 |
+
class CompoundLocation(Location):
|
| 1314 |
+
"""For handling joins etc where a feature location has several parts."""
|
| 1315 |
+
|
| 1316 |
+
def __init__(self, parts, operator="join"):
|
| 1317 |
+
"""Initialize the class.
|
| 1318 |
+
|
| 1319 |
+
>>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
|
| 1320 |
+
>>> f1 = SimpleLocation(10, 40, strand=+1)
|
| 1321 |
+
>>> f2 = SimpleLocation(50, 59, strand=+1)
|
| 1322 |
+
>>> f = CompoundLocation([f1, f2])
|
| 1323 |
+
>>> len(f) == len(f1) + len(f2) == 39 == len(list(f))
|
| 1324 |
+
True
|
| 1325 |
+
>>> print(f.operator)
|
| 1326 |
+
join
|
| 1327 |
+
>>> 5 in f
|
| 1328 |
+
False
|
| 1329 |
+
>>> 15 in f
|
| 1330 |
+
True
|
| 1331 |
+
>>> f.strand
|
| 1332 |
+
1
|
| 1333 |
+
|
| 1334 |
+
Notice that the strand of the compound location is computed
|
| 1335 |
+
automatically - in the case of mixed strands on the sub-locations
|
| 1336 |
+
the overall strand is set to None.
|
| 1337 |
+
|
| 1338 |
+
>>> f = CompoundLocation([SimpleLocation(3, 6, strand=+1),
|
| 1339 |
+
... SimpleLocation(10, 13, strand=-1)])
|
| 1340 |
+
>>> print(f.strand)
|
| 1341 |
+
None
|
| 1342 |
+
>>> len(f)
|
| 1343 |
+
6
|
| 1344 |
+
>>> list(f)
|
| 1345 |
+
[3, 4, 5, 12, 11, 10]
|
| 1346 |
+
|
| 1347 |
+
The example above doing list(f) iterates over the coordinates within the
|
| 1348 |
+
feature. This allows you to use max and min on the location, to find the
|
| 1349 |
+
range covered:
|
| 1350 |
+
|
| 1351 |
+
>>> min(f)
|
| 1352 |
+
3
|
| 1353 |
+
>>> max(f)
|
| 1354 |
+
12
|
| 1355 |
+
|
| 1356 |
+
More generally, you can use the compound location's start and end which
|
| 1357 |
+
give the full span covered, 0 <= start <= end <= full sequence length.
|
| 1358 |
+
|
| 1359 |
+
>>> f.start == min(f)
|
| 1360 |
+
True
|
| 1361 |
+
>>> f.end == max(f) + 1
|
| 1362 |
+
True
|
| 1363 |
+
|
| 1364 |
+
This is consistent with the behavior of the SimpleLocation for a single
|
| 1365 |
+
region, where again the 'start' and 'end' do not necessarily give the
|
| 1366 |
+
biological start and end, but rather the 'minimal' and 'maximal'
|
| 1367 |
+
coordinate boundaries.
|
| 1368 |
+
|
| 1369 |
+
Note that adding locations provides a more intuitive method of
|
| 1370 |
+
construction:
|
| 1371 |
+
|
| 1372 |
+
>>> f = SimpleLocation(3, 6, strand=+1) + SimpleLocation(10, 13, strand=-1)
|
| 1373 |
+
>>> len(f)
|
| 1374 |
+
6
|
| 1375 |
+
>>> list(f)
|
| 1376 |
+
[3, 4, 5, 12, 11, 10]
|
| 1377 |
+
"""
|
| 1378 |
+
self.operator = operator
|
| 1379 |
+
self.parts = list(parts)
|
| 1380 |
+
for loc in self.parts:
|
| 1381 |
+
if not isinstance(loc, SimpleLocation):
|
| 1382 |
+
raise ValueError(
|
| 1383 |
+
"CompoundLocation should be given a list of "
|
| 1384 |
+
"SimpleLocation objects, not %s" % loc.__class__
|
| 1385 |
+
)
|
| 1386 |
+
if len(parts) < 2:
|
| 1387 |
+
raise ValueError(
|
| 1388 |
+
f"CompoundLocation should have at least 2 parts, not {parts!r}"
|
| 1389 |
+
)
|
| 1390 |
+
|
| 1391 |
+
def __str__(self):
|
| 1392 |
+
"""Return a representation of the CompoundLocation object (with python counting)."""
|
| 1393 |
+
return "%s{%s}" % (self.operator, ", ".join(str(loc) for loc in self.parts))
|
| 1394 |
+
|
| 1395 |
+
def __repr__(self):
|
| 1396 |
+
"""Represent the CompoundLocation object as string for debugging."""
|
| 1397 |
+
return f"{self.__class__.__name__}({self.parts!r}, {self.operator!r})"
|
| 1398 |
+
|
| 1399 |
+
def _get_strand(self):
|
| 1400 |
+
"""Get function for the strand property (PRIVATE)."""
|
| 1401 |
+
# Historically a join on the reverse strand has been represented
|
| 1402 |
+
# in Biopython with both the parent SeqFeature and its children
|
| 1403 |
+
# (the exons for a CDS) all given a strand of -1. Likewise, for
|
| 1404 |
+
# a join feature on the forward strand they all have strand +1.
|
| 1405 |
+
# However, we must also consider evil mixed strand examples like
|
| 1406 |
+
# this, join(complement(69611..69724),139856..140087,140625..140650)
|
| 1407 |
+
if len({loc.strand for loc in self.parts}) == 1:
|
| 1408 |
+
return self.parts[0].strand
|
| 1409 |
+
else:
|
| 1410 |
+
return None # i.e. mixed strands
|
| 1411 |
+
|
| 1412 |
+
def _set_strand(self, value):
|
| 1413 |
+
"""Set function for the strand property (PRIVATE)."""
|
| 1414 |
+
# Should this be allowed/encouraged?
|
| 1415 |
+
for loc in self.parts:
|
| 1416 |
+
loc.strand = value
|
| 1417 |
+
|
| 1418 |
+
strand = property(
|
| 1419 |
+
fget=_get_strand,
|
| 1420 |
+
fset=_set_strand,
|
| 1421 |
+
doc="""Overall strand of the compound location.
|
| 1422 |
+
|
| 1423 |
+
If all the parts have the same strand, that is returned. Otherwise
|
| 1424 |
+
for mixed strands, this returns None.
|
| 1425 |
+
|
| 1426 |
+
>>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
|
| 1427 |
+
>>> f1 = SimpleLocation(15, 17, strand=1)
|
| 1428 |
+
>>> f2 = SimpleLocation(20, 30, strand=-1)
|
| 1429 |
+
>>> f = f1 + f2
|
| 1430 |
+
>>> f1.strand
|
| 1431 |
+
1
|
| 1432 |
+
>>> f2.strand
|
| 1433 |
+
-1
|
| 1434 |
+
>>> f.strand
|
| 1435 |
+
>>> f.strand is None
|
| 1436 |
+
True
|
| 1437 |
+
|
| 1438 |
+
If you set the strand of a CompoundLocation, this is applied to
|
| 1439 |
+
all the parts - use with caution:
|
| 1440 |
+
|
| 1441 |
+
>>> f.strand = 1
|
| 1442 |
+
>>> f1.strand
|
| 1443 |
+
1
|
| 1444 |
+
>>> f2.strand
|
| 1445 |
+
1
|
| 1446 |
+
>>> f.strand
|
| 1447 |
+
1
|
| 1448 |
+
|
| 1449 |
+
""",
|
| 1450 |
+
)
|
| 1451 |
+
|
| 1452 |
+
def __add__(self, other):
|
| 1453 |
+
"""Combine locations, or shift the location by an integer offset.
|
| 1454 |
+
|
| 1455 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1456 |
+
>>> f1 = SimpleLocation(15, 17) + SimpleLocation(20, 30)
|
| 1457 |
+
>>> print(f1)
|
| 1458 |
+
join{[15:17], [20:30]}
|
| 1459 |
+
|
| 1460 |
+
You can add another SimpleLocation:
|
| 1461 |
+
|
| 1462 |
+
>>> print(f1 + SimpleLocation(40, 50))
|
| 1463 |
+
join{[15:17], [20:30], [40:50]}
|
| 1464 |
+
>>> print(SimpleLocation(5, 10) + f1)
|
| 1465 |
+
join{[5:10], [15:17], [20:30]}
|
| 1466 |
+
|
| 1467 |
+
You can also add another CompoundLocation:
|
| 1468 |
+
|
| 1469 |
+
>>> f2 = SimpleLocation(40, 50) + SimpleLocation(60, 70)
|
| 1470 |
+
>>> print(f2)
|
| 1471 |
+
join{[40:50], [60:70]}
|
| 1472 |
+
>>> print(f1 + f2)
|
| 1473 |
+
join{[15:17], [20:30], [40:50], [60:70]}
|
| 1474 |
+
|
| 1475 |
+
Also, as with the SimpleLocation, adding an integer shifts the
|
| 1476 |
+
location's coordinates by that offset:
|
| 1477 |
+
|
| 1478 |
+
>>> print(f1 + 100)
|
| 1479 |
+
join{[115:117], [120:130]}
|
| 1480 |
+
>>> print(200 + f1)
|
| 1481 |
+
join{[215:217], [220:230]}
|
| 1482 |
+
>>> print(f1 + (-5))
|
| 1483 |
+
join{[10:12], [15:25]}
|
| 1484 |
+
"""
|
| 1485 |
+
if isinstance(other, SimpleLocation):
|
| 1486 |
+
return CompoundLocation(self.parts + [other], self.operator)
|
| 1487 |
+
elif isinstance(other, CompoundLocation):
|
| 1488 |
+
if self.operator != other.operator:
|
| 1489 |
+
# Handle join+order -> order as a special case?
|
| 1490 |
+
raise ValueError(
|
| 1491 |
+
f"Mixed operators {self.operator} and {other.operator}"
|
| 1492 |
+
)
|
| 1493 |
+
return CompoundLocation(self.parts + other.parts, self.operator)
|
| 1494 |
+
elif isinstance(other, int):
|
| 1495 |
+
return self._shift(other)
|
| 1496 |
+
else:
|
| 1497 |
+
raise NotImplementedError
|
| 1498 |
+
|
| 1499 |
+
def __radd__(self, other):
|
| 1500 |
+
"""Add a feature to the left."""
|
| 1501 |
+
if isinstance(other, SimpleLocation):
|
| 1502 |
+
return CompoundLocation([other] + self.parts, self.operator)
|
| 1503 |
+
elif isinstance(other, int):
|
| 1504 |
+
return self._shift(other)
|
| 1505 |
+
else:
|
| 1506 |
+
raise NotImplementedError
|
| 1507 |
+
|
| 1508 |
+
def __contains__(self, value):
|
| 1509 |
+
"""Check if an integer position is within the CompoundLocation object."""
|
| 1510 |
+
for loc in self.parts:
|
| 1511 |
+
if value in loc:
|
| 1512 |
+
return True
|
| 1513 |
+
return False
|
| 1514 |
+
|
| 1515 |
+
def __nonzero__(self):
|
| 1516 |
+
"""Return True regardless of the length of the feature.
|
| 1517 |
+
|
| 1518 |
+
This behavior is for backwards compatibility, since until the
|
| 1519 |
+
__len__ method was added, a SimpleLocation always evaluated as True.
|
| 1520 |
+
|
| 1521 |
+
Note that in comparison, Seq objects, strings, lists, etc, will all
|
| 1522 |
+
evaluate to False if they have length zero.
|
| 1523 |
+
|
| 1524 |
+
WARNING: The SimpleLocation may in future evaluate to False when its
|
| 1525 |
+
length is zero (in order to better match normal python behavior)!
|
| 1526 |
+
"""
|
| 1527 |
+
return True
|
| 1528 |
+
|
| 1529 |
+
def __len__(self):
|
| 1530 |
+
"""Return the length of the CompoundLocation object."""
|
| 1531 |
+
return sum(len(loc) for loc in self.parts)
|
| 1532 |
+
|
| 1533 |
+
def __iter__(self):
|
| 1534 |
+
"""Iterate over the parent positions within the CompoundLocation object."""
|
| 1535 |
+
for loc in self.parts:
|
| 1536 |
+
yield from loc
|
| 1537 |
+
|
| 1538 |
+
def __eq__(self, other):
|
| 1539 |
+
"""Check if all parts of CompoundLocation are equal to all parts of other CompoundLocation."""
|
| 1540 |
+
if not isinstance(other, CompoundLocation):
|
| 1541 |
+
return False
|
| 1542 |
+
if len(self.parts) != len(other.parts):
|
| 1543 |
+
return False
|
| 1544 |
+
if self.operator != other.operator:
|
| 1545 |
+
return False
|
| 1546 |
+
for self_part, other_part in zip(self.parts, other.parts):
|
| 1547 |
+
if self_part != other_part:
|
| 1548 |
+
return False
|
| 1549 |
+
return True
|
| 1550 |
+
|
| 1551 |
+
def _shift(self, offset):
|
| 1552 |
+
"""Return a copy of the CompoundLocation shifted by an offset (PRIVATE)."""
|
| 1553 |
+
return CompoundLocation(
|
| 1554 |
+
[loc._shift(offset) for loc in self.parts], self.operator
|
| 1555 |
+
)
|
| 1556 |
+
|
| 1557 |
+
def _flip(self, length):
|
| 1558 |
+
"""Return a copy of the locations after the parent is reversed (PRIVATE).
|
| 1559 |
+
|
| 1560 |
+
Note that the order of the parts is NOT reversed unless all parts
|
| 1561 |
+
have strand=None, since the order has meaning for stranded features.
|
| 1562 |
+
Consider a CDS on the forward strand with exons small, medium
|
| 1563 |
+
and large (in length). Once we change the frame of reference
|
| 1564 |
+
to the reverse complement strand, the start codon is still part of
|
| 1565 |
+
the small exon, and the stop codon still part of the large exon -
|
| 1566 |
+
so the part order remains the same!
|
| 1567 |
+
|
| 1568 |
+
Here is an artificial example, were the features map to the two upper
|
| 1569 |
+
case regions and the lower case runs of n are not used:
|
| 1570 |
+
|
| 1571 |
+
>>> from Bio.Seq import Seq
|
| 1572 |
+
>>> from Bio.SeqFeature import SimpleLocation
|
| 1573 |
+
>>> dna = Seq("nnnnnAGCATCCTGCTGTACnnnnnnnnGAGAMTGCCATGCCCCTGGAGTGAnnnnn")
|
| 1574 |
+
>>> small = SimpleLocation(5, 20, strand=1)
|
| 1575 |
+
>>> large = SimpleLocation(28, 52, strand=1)
|
| 1576 |
+
>>> location = small + large
|
| 1577 |
+
>>> print(small)
|
| 1578 |
+
[5:20](+)
|
| 1579 |
+
>>> print(large)
|
| 1580 |
+
[28:52](+)
|
| 1581 |
+
>>> print(location)
|
| 1582 |
+
join{[5:20](+), [28:52](+)}
|
| 1583 |
+
>>> for part in location.parts:
|
| 1584 |
+
... print(len(part))
|
| 1585 |
+
...
|
| 1586 |
+
15
|
| 1587 |
+
24
|
| 1588 |
+
|
| 1589 |
+
As you can see, this is a silly example where each "exon" is a word:
|
| 1590 |
+
|
| 1591 |
+
>>> print(small.extract(dna).translate())
|
| 1592 |
+
SILLY
|
| 1593 |
+
>>> print(large.extract(dna).translate())
|
| 1594 |
+
EXAMPLE*
|
| 1595 |
+
>>> print(location.extract(dna).translate())
|
| 1596 |
+
SILLYEXAMPLE*
|
| 1597 |
+
>>> for part in location.parts:
|
| 1598 |
+
... print(part.extract(dna).translate())
|
| 1599 |
+
...
|
| 1600 |
+
SILLY
|
| 1601 |
+
EXAMPLE*
|
| 1602 |
+
|
| 1603 |
+
Now, let's look at this from the reverse strand frame of reference:
|
| 1604 |
+
|
| 1605 |
+
>>> flipped_dna = dna.reverse_complement()
|
| 1606 |
+
>>> flipped_location = location._flip(len(dna))
|
| 1607 |
+
>>> print(flipped_location.extract(flipped_dna).translate())
|
| 1608 |
+
SILLYEXAMPLE*
|
| 1609 |
+
>>> for part in flipped_location.parts:
|
| 1610 |
+
... print(part.extract(flipped_dna).translate())
|
| 1611 |
+
...
|
| 1612 |
+
SILLY
|
| 1613 |
+
EXAMPLE*
|
| 1614 |
+
|
| 1615 |
+
The key point here is the first part of the CompoundFeature is still the
|
| 1616 |
+
small exon, while the second part is still the large exon:
|
| 1617 |
+
|
| 1618 |
+
>>> for part in flipped_location.parts:
|
| 1619 |
+
... print(len(part))
|
| 1620 |
+
...
|
| 1621 |
+
15
|
| 1622 |
+
24
|
| 1623 |
+
>>> print(flipped_location)
|
| 1624 |
+
join{[37:52](-), [5:29](-)}
|
| 1625 |
+
|
| 1626 |
+
Notice the parts are not reversed. However, there was a bug here in older
|
| 1627 |
+
versions of Biopython which would have given join{[5:29](-), [37:52](-)}
|
| 1628 |
+
and the translation would have wrongly been "EXAMPLE*SILLY" instead.
|
| 1629 |
+
|
| 1630 |
+
When all the parts have strand None, the order of the parts is reversed.
|
| 1631 |
+
In principle this does not change the meaning of the location, but improves
|
| 1632 |
+
the representation of feature locations spanning the origin in circular
|
| 1633 |
+
molecules.
|
| 1634 |
+
|
| 1635 |
+
>>> loc = SimpleLocation(4, 6, None) + SimpleLocation(0, 1, None)
|
| 1636 |
+
>>> print(loc)
|
| 1637 |
+
join{[4:6], [0:1]}
|
| 1638 |
+
>>> print(loc._flip(6))
|
| 1639 |
+
join{[5:6], [0:2]}
|
| 1640 |
+
|
| 1641 |
+
join{[0:2], [5:6]} would not be properly represented in SnapGene, Benchling, etc.
|
| 1642 |
+
"""
|
| 1643 |
+
if all(loc.strand is None for loc in self.parts):
|
| 1644 |
+
return CompoundLocation(
|
| 1645 |
+
[loc._flip(length) for loc in self.parts[::-1]], self.operator
|
| 1646 |
+
)
|
| 1647 |
+
else:
|
| 1648 |
+
return CompoundLocation(
|
| 1649 |
+
[loc._flip(length) for loc in self.parts], self.operator
|
| 1650 |
+
)
|
| 1651 |
+
|
| 1652 |
+
@property
|
| 1653 |
+
def start(self):
|
| 1654 |
+
"""Start location - left most (minimum) value, regardless of strand.
|
| 1655 |
+
|
| 1656 |
+
Read only, returns an integer like position object, possibly a fuzzy
|
| 1657 |
+
position.
|
| 1658 |
+
|
| 1659 |
+
For the special case of a CompoundLocation wrapping the origin of a
|
| 1660 |
+
circular genome, this will return zero.
|
| 1661 |
+
"""
|
| 1662 |
+
return min(loc.start for loc in self.parts)
|
| 1663 |
+
|
| 1664 |
+
@property
|
| 1665 |
+
def end(self):
|
| 1666 |
+
"""End location - right most (maximum) value, regardless of strand.
|
| 1667 |
+
|
| 1668 |
+
Read only, returns an integer like position object, possibly a fuzzy
|
| 1669 |
+
position.
|
| 1670 |
+
|
| 1671 |
+
For the special case of a CompoundLocation wrapping the origin of
|
| 1672 |
+
a circular genome this will match the genome length.
|
| 1673 |
+
"""
|
| 1674 |
+
return max(loc.end for loc in self.parts)
|
| 1675 |
+
|
| 1676 |
+
@property
|
| 1677 |
+
def ref(self):
|
| 1678 |
+
"""Not present in CompoundLocation, dummy method for API compatibility."""
|
| 1679 |
+
return None
|
| 1680 |
+
|
| 1681 |
+
@property
|
| 1682 |
+
def ref_db(self):
|
| 1683 |
+
"""Not present in CompoundLocation, dummy method for API compatibility."""
|
| 1684 |
+
return None
|
| 1685 |
+
|
| 1686 |
+
def extract(self, parent_sequence, references=None):
|
| 1687 |
+
"""Extract the sequence from supplied parent sequence using the CompoundLocation object.
|
| 1688 |
+
|
| 1689 |
+
The parent_sequence can be a Seq like object or a string, and will
|
| 1690 |
+
generally return an object of the same type. The exception to this is
|
| 1691 |
+
a MutableSeq as the parent sequence will return a Seq object.
|
| 1692 |
+
If the location refers to other records, they must be supplied
|
| 1693 |
+
in the optional dictionary references.
|
| 1694 |
+
|
| 1695 |
+
>>> from Bio.Seq import Seq
|
| 1696 |
+
>>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
|
| 1697 |
+
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
|
| 1698 |
+
>>> fl1 = SimpleLocation(2, 8)
|
| 1699 |
+
>>> fl2 = SimpleLocation(10, 15)
|
| 1700 |
+
>>> fl3 = CompoundLocation([fl1,fl2])
|
| 1701 |
+
>>> fl3.extract(seq)
|
| 1702 |
+
Seq('QHKAMILIVIC')
|
| 1703 |
+
|
| 1704 |
+
"""
|
| 1705 |
+
# This copes with mixed strand features & all on reverse:
|
| 1706 |
+
parts = [
|
| 1707 |
+
loc.extract(parent_sequence, references=references) for loc in self.parts
|
| 1708 |
+
]
|
| 1709 |
+
f_seq = functools.reduce(lambda x, y: x + y, parts)
|
| 1710 |
+
return f_seq
|
| 1711 |
+
|
| 1712 |
+
|
| 1713 |
+
class Position(ABC):
|
| 1714 |
+
"""Abstract base class representing a position."""
|
| 1715 |
+
|
| 1716 |
+
@abstractmethod
|
| 1717 |
+
def __repr__(self):
|
| 1718 |
+
"""Represent the Position object as a string for debugging."""
|
| 1719 |
+
return f"{self.__class__.__name__}(...)"
|
| 1720 |
+
|
| 1721 |
+
@staticmethod
|
| 1722 |
+
def fromstring(text, offset=0):
|
| 1723 |
+
"""Build a Position object from the text string.
|
| 1724 |
+
|
| 1725 |
+
For an end position, leave offset as zero (default):
|
| 1726 |
+
|
| 1727 |
+
>>> Position.fromstring("5")
|
| 1728 |
+
ExactPosition(5)
|
| 1729 |
+
|
| 1730 |
+
For a start position, set offset to minus one (for Python counting):
|
| 1731 |
+
|
| 1732 |
+
>>> Position.fromstring("5", -1)
|
| 1733 |
+
ExactPosition(4)
|
| 1734 |
+
|
| 1735 |
+
This also covers fuzzy positions:
|
| 1736 |
+
|
| 1737 |
+
>>> p = Position.fromstring("<5")
|
| 1738 |
+
>>> p
|
| 1739 |
+
BeforePosition(5)
|
| 1740 |
+
>>> print(p)
|
| 1741 |
+
<5
|
| 1742 |
+
>>> int(p)
|
| 1743 |
+
5
|
| 1744 |
+
|
| 1745 |
+
>>> Position.fromstring(">5")
|
| 1746 |
+
AfterPosition(5)
|
| 1747 |
+
|
| 1748 |
+
By default assumes an end position, so note the integer behavior:
|
| 1749 |
+
|
| 1750 |
+
>>> p = Position.fromstring("one-of(5,8,11)")
|
| 1751 |
+
>>> p
|
| 1752 |
+
OneOfPosition(11, choices=[ExactPosition(5), ExactPosition(8), ExactPosition(11)])
|
| 1753 |
+
>>> print(p)
|
| 1754 |
+
one-of(5,8,11)
|
| 1755 |
+
>>> int(p)
|
| 1756 |
+
11
|
| 1757 |
+
|
| 1758 |
+
>>> Position.fromstring("(8.10)")
|
| 1759 |
+
WithinPosition(10, left=8, right=10)
|
| 1760 |
+
|
| 1761 |
+
Fuzzy start positions:
|
| 1762 |
+
|
| 1763 |
+
>>> p = Position.fromstring("<5", -1)
|
| 1764 |
+
>>> p
|
| 1765 |
+
BeforePosition(4)
|
| 1766 |
+
>>> print(p)
|
| 1767 |
+
<4
|
| 1768 |
+
>>> int(p)
|
| 1769 |
+
4
|
| 1770 |
+
|
| 1771 |
+
Notice how the integer behavior changes too!
|
| 1772 |
+
|
| 1773 |
+
>>> p = Position.fromstring("one-of(5,8,11)", -1)
|
| 1774 |
+
>>> p
|
| 1775 |
+
OneOfPosition(4, choices=[ExactPosition(4), ExactPosition(7), ExactPosition(10)])
|
| 1776 |
+
>>> print(p)
|
| 1777 |
+
one-of(4,7,10)
|
| 1778 |
+
>>> int(p)
|
| 1779 |
+
4
|
| 1780 |
+
|
| 1781 |
+
"""
|
| 1782 |
+
if offset != 0 and offset != -1:
|
| 1783 |
+
raise ValueError(
|
| 1784 |
+
"To convert one-based indices to zero-based indices, offset must be either 0 (for end positions) or -1 (for start positions)."
|
| 1785 |
+
)
|
| 1786 |
+
if text == "?":
|
| 1787 |
+
return UnknownPosition()
|
| 1788 |
+
if text.startswith("?"):
|
| 1789 |
+
return UncertainPosition(int(text[1:]) + offset)
|
| 1790 |
+
if text.startswith("<"):
|
| 1791 |
+
return BeforePosition(int(text[1:]) + offset)
|
| 1792 |
+
if text.startswith(">"):
|
| 1793 |
+
return AfterPosition(int(text[1:]) + offset)
|
| 1794 |
+
m = _re_within_position.match(text)
|
| 1795 |
+
if m is not None:
|
| 1796 |
+
s, e = m.groups()
|
| 1797 |
+
s = int(s) + offset
|
| 1798 |
+
e = int(e) + offset
|
| 1799 |
+
if offset == -1:
|
| 1800 |
+
default = s
|
| 1801 |
+
else:
|
| 1802 |
+
default = e
|
| 1803 |
+
return WithinPosition(default, left=s, right=e)
|
| 1804 |
+
m = _re_oneof_position.match(text)
|
| 1805 |
+
if m is not None:
|
| 1806 |
+
positions = m.groups()[0]
|
| 1807 |
+
parts = [ExactPosition(int(pos) + offset) for pos in positions.split(",")]
|
| 1808 |
+
if offset == -1:
|
| 1809 |
+
default = min(int(pos) for pos in parts)
|
| 1810 |
+
else:
|
| 1811 |
+
default = max(int(pos) for pos in parts)
|
| 1812 |
+
return OneOfPosition(default, choices=parts)
|
| 1813 |
+
return ExactPosition(int(text) + offset)
|
| 1814 |
+
|
| 1815 |
+
|
| 1816 |
+
class ExactPosition(int, Position):
|
| 1817 |
+
"""Specify the specific position of a boundary.
|
| 1818 |
+
|
| 1819 |
+
Arguments:
|
| 1820 |
+
- position - The position of the boundary.
|
| 1821 |
+
- extension - An optional argument which must be zero since we don't
|
| 1822 |
+
have an extension. The argument is provided so that the same number
|
| 1823 |
+
of arguments can be passed to all position types.
|
| 1824 |
+
|
| 1825 |
+
In this case, there is no fuzziness associated with the position.
|
| 1826 |
+
|
| 1827 |
+
>>> p = ExactPosition(5)
|
| 1828 |
+
>>> p
|
| 1829 |
+
ExactPosition(5)
|
| 1830 |
+
>>> print(p)
|
| 1831 |
+
5
|
| 1832 |
+
|
| 1833 |
+
>>> isinstance(p, Position)
|
| 1834 |
+
True
|
| 1835 |
+
>>> isinstance(p, int)
|
| 1836 |
+
True
|
| 1837 |
+
|
| 1838 |
+
Integer comparisons and operations should work as expected:
|
| 1839 |
+
|
| 1840 |
+
>>> p == 5
|
| 1841 |
+
True
|
| 1842 |
+
>>> p < 6
|
| 1843 |
+
True
|
| 1844 |
+
>>> p <= 5
|
| 1845 |
+
True
|
| 1846 |
+
>>> p + 10
|
| 1847 |
+
ExactPosition(15)
|
| 1848 |
+
|
| 1849 |
+
"""
|
| 1850 |
+
|
| 1851 |
+
def __new__(cls, position, extension=0):
|
| 1852 |
+
"""Create an ExactPosition object."""
|
| 1853 |
+
if extension != 0:
|
| 1854 |
+
raise AttributeError(f"Non-zero extension {extension} for exact position.")
|
| 1855 |
+
return int.__new__(cls, position)
|
| 1856 |
+
|
| 1857 |
+
# Must define this on Python 3.8 onwards because we redefine __repr__
|
| 1858 |
+
def __str__(self):
|
| 1859 |
+
"""Return a representation of the ExactPosition object (with python counting)."""
|
| 1860 |
+
return str(int(self))
|
| 1861 |
+
|
| 1862 |
+
def __repr__(self):
|
| 1863 |
+
"""Represent the ExactPosition object as a string for debugging."""
|
| 1864 |
+
return "%s(%i)" % (self.__class__.__name__, int(self))
|
| 1865 |
+
|
| 1866 |
+
def __add__(self, offset):
|
| 1867 |
+
"""Return a copy of the position object with its location shifted (PRIVATE)."""
|
| 1868 |
+
# By default preserve any subclass
|
| 1869 |
+
return self.__class__(int(self) + offset)
|
| 1870 |
+
|
| 1871 |
+
def _flip(self, length):
|
| 1872 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 1873 |
+
# By default preserve any subclass
|
| 1874 |
+
return self.__class__(length - int(self))
|
| 1875 |
+
|
| 1876 |
+
|
| 1877 |
+
class UncertainPosition(ExactPosition):
|
| 1878 |
+
"""Specify a specific position which is uncertain.
|
| 1879 |
+
|
| 1880 |
+
This is used in UniProt, e.g. ?222 for uncertain position 222, or in the
|
| 1881 |
+
XML format explicitly marked as uncertain. Does not apply to GenBank/EMBL.
|
| 1882 |
+
"""
|
| 1883 |
+
|
| 1884 |
+
|
| 1885 |
+
class UnknownPosition(Position):
|
| 1886 |
+
"""Specify a specific position which is unknown (has no position).
|
| 1887 |
+
|
| 1888 |
+
This is used in UniProt, e.g. ? or in the XML as unknown.
|
| 1889 |
+
"""
|
| 1890 |
+
|
| 1891 |
+
def __repr__(self):
|
| 1892 |
+
"""Represent the UnknownPosition object as a string for debugging."""
|
| 1893 |
+
return f"{self.__class__.__name__}()"
|
| 1894 |
+
|
| 1895 |
+
def __hash__(self):
|
| 1896 |
+
"""Return the hash value of the UnknownPosition object."""
|
| 1897 |
+
return hash(None)
|
| 1898 |
+
|
| 1899 |
+
def __add__(self, offset):
|
| 1900 |
+
"""Return a copy of the position object with its location shifted (PRIVATE)."""
|
| 1901 |
+
return self
|
| 1902 |
+
|
| 1903 |
+
def _flip(self, length):
|
| 1904 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 1905 |
+
return self
|
| 1906 |
+
|
| 1907 |
+
|
| 1908 |
+
class WithinPosition(int, Position):
|
| 1909 |
+
"""Specify the position of a boundary within some coordinates.
|
| 1910 |
+
|
| 1911 |
+
Arguments:
|
| 1912 |
+
- position - The default integer position
|
| 1913 |
+
- left - The start (left) position of the boundary
|
| 1914 |
+
- right - The end (right) position of the boundary
|
| 1915 |
+
|
| 1916 |
+
This allows dealing with a location like ((11.14)..100). This
|
| 1917 |
+
indicates that the start of the sequence is somewhere between 11
|
| 1918 |
+
and 14. Since this is a start coordinate, it should act like
|
| 1919 |
+
it is at position 11 (or in Python counting, 10).
|
| 1920 |
+
|
| 1921 |
+
>>> p = WithinPosition(10, 10, 13)
|
| 1922 |
+
>>> p
|
| 1923 |
+
WithinPosition(10, left=10, right=13)
|
| 1924 |
+
>>> print(p)
|
| 1925 |
+
(10.13)
|
| 1926 |
+
>>> int(p)
|
| 1927 |
+
10
|
| 1928 |
+
|
| 1929 |
+
Basic integer comparisons and operations should work as though
|
| 1930 |
+
this were a plain integer:
|
| 1931 |
+
|
| 1932 |
+
>>> p == 10
|
| 1933 |
+
True
|
| 1934 |
+
>>> p in [9, 10, 11]
|
| 1935 |
+
True
|
| 1936 |
+
>>> p < 11
|
| 1937 |
+
True
|
| 1938 |
+
>>> p + 10
|
| 1939 |
+
WithinPosition(20, left=20, right=23)
|
| 1940 |
+
|
| 1941 |
+
>>> isinstance(p, WithinPosition)
|
| 1942 |
+
True
|
| 1943 |
+
>>> isinstance(p, Position)
|
| 1944 |
+
True
|
| 1945 |
+
>>> isinstance(p, int)
|
| 1946 |
+
True
|
| 1947 |
+
|
| 1948 |
+
Note this also applies for comparison to other position objects,
|
| 1949 |
+
where again the integer behavior is used:
|
| 1950 |
+
|
| 1951 |
+
>>> p == 10
|
| 1952 |
+
True
|
| 1953 |
+
>>> p == ExactPosition(10)
|
| 1954 |
+
True
|
| 1955 |
+
>>> p == BeforePosition(10)
|
| 1956 |
+
True
|
| 1957 |
+
>>> p == AfterPosition(10)
|
| 1958 |
+
True
|
| 1959 |
+
|
| 1960 |
+
If this were an end point, you would want the position to be 13
|
| 1961 |
+
(the right/larger value, not the left/smaller value as above):
|
| 1962 |
+
|
| 1963 |
+
>>> p2 = WithinPosition(13, 10, 13)
|
| 1964 |
+
>>> p2
|
| 1965 |
+
WithinPosition(13, left=10, right=13)
|
| 1966 |
+
>>> print(p2)
|
| 1967 |
+
(10.13)
|
| 1968 |
+
>>> int(p2)
|
| 1969 |
+
13
|
| 1970 |
+
>>> p2 == 13
|
| 1971 |
+
True
|
| 1972 |
+
>>> p2 == ExactPosition(13)
|
| 1973 |
+
True
|
| 1974 |
+
|
| 1975 |
+
"""
|
| 1976 |
+
|
| 1977 |
+
def __new__(cls, position, left, right):
|
| 1978 |
+
"""Create a WithinPosition object."""
|
| 1979 |
+
if not (position == left or position == right):
|
| 1980 |
+
raise RuntimeError(
|
| 1981 |
+
"WithinPosition: %r should match left %r or "
|
| 1982 |
+
"right %r" % (position, left, right)
|
| 1983 |
+
)
|
| 1984 |
+
obj = int.__new__(cls, position)
|
| 1985 |
+
obj._left = left
|
| 1986 |
+
obj._right = right
|
| 1987 |
+
return obj
|
| 1988 |
+
|
| 1989 |
+
def __getnewargs__(self):
|
| 1990 |
+
"""Return the arguments accepted by __new__.
|
| 1991 |
+
|
| 1992 |
+
Necessary to allow pickling and unpickling of class instances.
|
| 1993 |
+
"""
|
| 1994 |
+
return (int(self), self._left, self._right)
|
| 1995 |
+
|
| 1996 |
+
def __repr__(self):
|
| 1997 |
+
"""Represent the WithinPosition object as a string for debugging."""
|
| 1998 |
+
return "%s(%i, left=%i, right=%i)" % (
|
| 1999 |
+
self.__class__.__name__,
|
| 2000 |
+
int(self),
|
| 2001 |
+
self._left,
|
| 2002 |
+
self._right,
|
| 2003 |
+
)
|
| 2004 |
+
|
| 2005 |
+
def __str__(self):
|
| 2006 |
+
"""Return a representation of the WithinPosition object (with python counting)."""
|
| 2007 |
+
return f"({self._left}.{self._right})"
|
| 2008 |
+
|
| 2009 |
+
def __add__(self, offset):
|
| 2010 |
+
"""Return a copy of the position object with its location shifted."""
|
| 2011 |
+
return self.__class__(
|
| 2012 |
+
int(self) + offset, self._left + offset, self._right + offset
|
| 2013 |
+
)
|
| 2014 |
+
|
| 2015 |
+
def _flip(self, length):
|
| 2016 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 2017 |
+
return self.__class__(
|
| 2018 |
+
length - int(self), length - self._right, length - self._left
|
| 2019 |
+
)
|
| 2020 |
+
|
| 2021 |
+
|
| 2022 |
+
class BetweenPosition(int, Position):
|
| 2023 |
+
"""Specify the position of a boundary between two coordinates (OBSOLETE?).
|
| 2024 |
+
|
| 2025 |
+
Arguments:
|
| 2026 |
+
- position - The default integer position
|
| 2027 |
+
- left - The start (left) position of the boundary
|
| 2028 |
+
- right - The end (right) position of the boundary
|
| 2029 |
+
|
| 2030 |
+
This allows dealing with a position like 123^456. This
|
| 2031 |
+
indicates that the start of the sequence is somewhere between
|
| 2032 |
+
123 and 456. It is up to the parser to set the position argument
|
| 2033 |
+
to either boundary point (depending on if this is being used as
|
| 2034 |
+
a start or end of the feature). For example as a feature end:
|
| 2035 |
+
|
| 2036 |
+
>>> p = BetweenPosition(456, 123, 456)
|
| 2037 |
+
>>> p
|
| 2038 |
+
BetweenPosition(456, left=123, right=456)
|
| 2039 |
+
>>> print(p)
|
| 2040 |
+
(123^456)
|
| 2041 |
+
>>> int(p)
|
| 2042 |
+
456
|
| 2043 |
+
|
| 2044 |
+
Integer equality and comparison use the given position,
|
| 2045 |
+
|
| 2046 |
+
>>> p == 456
|
| 2047 |
+
True
|
| 2048 |
+
>>> p in [455, 456, 457]
|
| 2049 |
+
True
|
| 2050 |
+
>>> p > 300
|
| 2051 |
+
True
|
| 2052 |
+
|
| 2053 |
+
The old legacy properties of position and extension give the
|
| 2054 |
+
starting/lower/left position as an integer, and the distance
|
| 2055 |
+
to the ending/higher/right position as an integer. Note that
|
| 2056 |
+
the position object will act like either the left or the right
|
| 2057 |
+
end-point depending on how it was created:
|
| 2058 |
+
|
| 2059 |
+
>>> p2 = BetweenPosition(123, left=123, right=456)
|
| 2060 |
+
>>> int(p) == int(p2)
|
| 2061 |
+
False
|
| 2062 |
+
>>> p == 456
|
| 2063 |
+
True
|
| 2064 |
+
>>> p2 == 123
|
| 2065 |
+
True
|
| 2066 |
+
|
| 2067 |
+
Note this potentially surprising behavior:
|
| 2068 |
+
|
| 2069 |
+
>>> BetweenPosition(123, left=123, right=456) == ExactPosition(123)
|
| 2070 |
+
True
|
| 2071 |
+
>>> BetweenPosition(123, left=123, right=456) == BeforePosition(123)
|
| 2072 |
+
True
|
| 2073 |
+
>>> BetweenPosition(123, left=123, right=456) == AfterPosition(123)
|
| 2074 |
+
True
|
| 2075 |
+
|
| 2076 |
+
i.e. For equality (and sorting) the position objects behave like
|
| 2077 |
+
integers.
|
| 2078 |
+
|
| 2079 |
+
"""
|
| 2080 |
+
|
| 2081 |
+
def __new__(cls, position, left, right):
|
| 2082 |
+
"""Create a new instance in BetweenPosition object."""
|
| 2083 |
+
assert position == left or position == right
|
| 2084 |
+
# TODO - public API for getting left/right, especially the unknown one
|
| 2085 |
+
obj = int.__new__(cls, position)
|
| 2086 |
+
obj._left = left
|
| 2087 |
+
obj._right = right
|
| 2088 |
+
return obj
|
| 2089 |
+
|
| 2090 |
+
def __getnewargs__(self):
|
| 2091 |
+
"""Return the arguments accepted by __new__.
|
| 2092 |
+
|
| 2093 |
+
Necessary to allow pickling and unpickling of class instances.
|
| 2094 |
+
"""
|
| 2095 |
+
return (int(self), self._left, self._right)
|
| 2096 |
+
|
| 2097 |
+
def __repr__(self):
|
| 2098 |
+
"""Represent the BetweenPosition object as a string for debugging."""
|
| 2099 |
+
return "%s(%i, left=%i, right=%i)" % (
|
| 2100 |
+
self.__class__.__name__,
|
| 2101 |
+
int(self),
|
| 2102 |
+
self._left,
|
| 2103 |
+
self._right,
|
| 2104 |
+
)
|
| 2105 |
+
|
| 2106 |
+
def __str__(self):
|
| 2107 |
+
"""Return a representation of the BetweenPosition object (with python counting)."""
|
| 2108 |
+
return f"({self._left}^{self._right})"
|
| 2109 |
+
|
| 2110 |
+
def __add__(self, offset):
|
| 2111 |
+
"""Return a copy of the position object with its location shifted (PRIVATE)."""
|
| 2112 |
+
return self.__class__(
|
| 2113 |
+
int(self) + offset, self._left + offset, self._right + offset
|
| 2114 |
+
)
|
| 2115 |
+
|
| 2116 |
+
def _flip(self, length):
|
| 2117 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 2118 |
+
return self.__class__(
|
| 2119 |
+
length - int(self), length - self._right, length - self._left
|
| 2120 |
+
)
|
| 2121 |
+
|
| 2122 |
+
|
| 2123 |
+
class BeforePosition(int, Position):
|
| 2124 |
+
"""Specify a position where the actual location occurs before it.
|
| 2125 |
+
|
| 2126 |
+
Arguments:
|
| 2127 |
+
- position - The upper boundary of where the location can occur.
|
| 2128 |
+
- extension - An optional argument which must be zero since we don't
|
| 2129 |
+
have an extension. The argument is provided so that the same number
|
| 2130 |
+
of arguments can be passed to all position types.
|
| 2131 |
+
|
| 2132 |
+
This is used to specify positions like (<10..100) where the location
|
| 2133 |
+
occurs somewhere before position 10.
|
| 2134 |
+
|
| 2135 |
+
>>> p = BeforePosition(5)
|
| 2136 |
+
>>> p
|
| 2137 |
+
BeforePosition(5)
|
| 2138 |
+
>>> print(p)
|
| 2139 |
+
<5
|
| 2140 |
+
>>> int(p)
|
| 2141 |
+
5
|
| 2142 |
+
>>> p + 10
|
| 2143 |
+
BeforePosition(15)
|
| 2144 |
+
|
| 2145 |
+
Note this potentially surprising behavior:
|
| 2146 |
+
|
| 2147 |
+
>>> p == ExactPosition(5)
|
| 2148 |
+
True
|
| 2149 |
+
>>> p == AfterPosition(5)
|
| 2150 |
+
True
|
| 2151 |
+
|
| 2152 |
+
Just remember that for equality and sorting the position objects act
|
| 2153 |
+
like integers.
|
| 2154 |
+
"""
|
| 2155 |
+
|
| 2156 |
+
# Subclasses int so can't use __init__
|
| 2157 |
+
def __new__(cls, position, extension=0):
|
| 2158 |
+
"""Create a new instance in BeforePosition object."""
|
| 2159 |
+
if extension != 0:
|
| 2160 |
+
raise AttributeError(f"Non-zero extension {extension} for exact position.")
|
| 2161 |
+
return int.__new__(cls, position)
|
| 2162 |
+
|
| 2163 |
+
def __repr__(self):
|
| 2164 |
+
"""Represent the location as a string for debugging."""
|
| 2165 |
+
return "%s(%i)" % (self.__class__.__name__, int(self))
|
| 2166 |
+
|
| 2167 |
+
def __str__(self):
|
| 2168 |
+
"""Return a representation of the BeforePosition object (with python counting)."""
|
| 2169 |
+
return f"<{int(self)}"
|
| 2170 |
+
|
| 2171 |
+
def __add__(self, offset):
|
| 2172 |
+
"""Return a copy of the position object with its location shifted (PRIVATE)."""
|
| 2173 |
+
return self.__class__(int(self) + offset)
|
| 2174 |
+
|
| 2175 |
+
def _flip(self, length):
|
| 2176 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 2177 |
+
return AfterPosition(length - int(self))
|
| 2178 |
+
|
| 2179 |
+
|
| 2180 |
+
class AfterPosition(int, Position):
|
| 2181 |
+
"""Specify a position where the actual location is found after it.
|
| 2182 |
+
|
| 2183 |
+
Arguments:
|
| 2184 |
+
- position - The lower boundary of where the location can occur.
|
| 2185 |
+
- extension - An optional argument which must be zero since we don't
|
| 2186 |
+
have an extension. The argument is provided so that the same number
|
| 2187 |
+
of arguments can be passed to all position types.
|
| 2188 |
+
|
| 2189 |
+
This is used to specify positions like (>10..100) where the location
|
| 2190 |
+
occurs somewhere after position 10.
|
| 2191 |
+
|
| 2192 |
+
>>> p = AfterPosition(7)
|
| 2193 |
+
>>> p
|
| 2194 |
+
AfterPosition(7)
|
| 2195 |
+
>>> print(p)
|
| 2196 |
+
>7
|
| 2197 |
+
>>> int(p)
|
| 2198 |
+
7
|
| 2199 |
+
>>> p + 10
|
| 2200 |
+
AfterPosition(17)
|
| 2201 |
+
|
| 2202 |
+
>>> isinstance(p, AfterPosition)
|
| 2203 |
+
True
|
| 2204 |
+
>>> isinstance(p, Position)
|
| 2205 |
+
True
|
| 2206 |
+
>>> isinstance(p, int)
|
| 2207 |
+
True
|
| 2208 |
+
|
| 2209 |
+
Note this potentially surprising behavior:
|
| 2210 |
+
|
| 2211 |
+
>>> p == ExactPosition(7)
|
| 2212 |
+
True
|
| 2213 |
+
>>> p == BeforePosition(7)
|
| 2214 |
+
True
|
| 2215 |
+
|
| 2216 |
+
Just remember that for equality and sorting the position objects act
|
| 2217 |
+
like integers.
|
| 2218 |
+
"""
|
| 2219 |
+
|
| 2220 |
+
# Subclasses int so can't use __init__
|
| 2221 |
+
def __new__(cls, position, extension=0):
|
| 2222 |
+
"""Create a new instance of the AfterPosition object."""
|
| 2223 |
+
if extension != 0:
|
| 2224 |
+
raise AttributeError(f"Non-zero extension {extension} for exact position.")
|
| 2225 |
+
return int.__new__(cls, position)
|
| 2226 |
+
|
| 2227 |
+
def __repr__(self):
|
| 2228 |
+
"""Represent the location as a string for debugging."""
|
| 2229 |
+
return "%s(%i)" % (self.__class__.__name__, int(self))
|
| 2230 |
+
|
| 2231 |
+
def __str__(self):
|
| 2232 |
+
"""Return a representation of the AfterPosition object (with python counting)."""
|
| 2233 |
+
return f">{int(self)}"
|
| 2234 |
+
|
| 2235 |
+
def __add__(self, offset):
|
| 2236 |
+
"""Return a copy of the position object with its location shifted (PRIVATE)."""
|
| 2237 |
+
return self.__class__(int(self) + offset)
|
| 2238 |
+
|
| 2239 |
+
def _flip(self, length):
|
| 2240 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 2241 |
+
return BeforePosition(length - int(self))
|
| 2242 |
+
|
| 2243 |
+
|
| 2244 |
+
class OneOfPosition(int, Position):
|
| 2245 |
+
"""Specify a position where the location can be multiple positions.
|
| 2246 |
+
|
| 2247 |
+
This models the GenBank 'one-of(1888,1901)' function, and tries
|
| 2248 |
+
to make this fit within the Biopython Position models. If this was
|
| 2249 |
+
a start position it should act like 1888, but as an end position 1901.
|
| 2250 |
+
|
| 2251 |
+
>>> p = OneOfPosition(1888, [ExactPosition(1888), ExactPosition(1901)])
|
| 2252 |
+
>>> p
|
| 2253 |
+
OneOfPosition(1888, choices=[ExactPosition(1888), ExactPosition(1901)])
|
| 2254 |
+
>>> int(p)
|
| 2255 |
+
1888
|
| 2256 |
+
|
| 2257 |
+
Integer comparisons and operators act like using int(p),
|
| 2258 |
+
|
| 2259 |
+
>>> p == 1888
|
| 2260 |
+
True
|
| 2261 |
+
>>> p <= 1888
|
| 2262 |
+
True
|
| 2263 |
+
>>> p > 1888
|
| 2264 |
+
False
|
| 2265 |
+
>>> p + 100
|
| 2266 |
+
OneOfPosition(1988, choices=[ExactPosition(1988), ExactPosition(2001)])
|
| 2267 |
+
|
| 2268 |
+
>>> isinstance(p, OneOfPosition)
|
| 2269 |
+
True
|
| 2270 |
+
>>> isinstance(p, Position)
|
| 2271 |
+
True
|
| 2272 |
+
>>> isinstance(p, int)
|
| 2273 |
+
True
|
| 2274 |
+
|
| 2275 |
+
"""
|
| 2276 |
+
|
| 2277 |
+
def __new__(cls, position, choices):
|
| 2278 |
+
"""Initialize with a set of possible positions.
|
| 2279 |
+
|
| 2280 |
+
choices is a list of Position derived objects, specifying possible
|
| 2281 |
+
locations.
|
| 2282 |
+
|
| 2283 |
+
position is an integer specifying the default behavior.
|
| 2284 |
+
"""
|
| 2285 |
+
if position not in choices:
|
| 2286 |
+
raise ValueError(
|
| 2287 |
+
f"OneOfPosition: {position!r} should match one of {choices!r}"
|
| 2288 |
+
)
|
| 2289 |
+
obj = int.__new__(cls, position)
|
| 2290 |
+
obj.position_choices = choices
|
| 2291 |
+
return obj
|
| 2292 |
+
|
| 2293 |
+
def __getnewargs__(self):
|
| 2294 |
+
"""Return the arguments accepted by __new__.
|
| 2295 |
+
|
| 2296 |
+
Necessary to allow pickling and unpickling of class instances.
|
| 2297 |
+
"""
|
| 2298 |
+
return (int(self), self.position_choices)
|
| 2299 |
+
|
| 2300 |
+
def __repr__(self):
|
| 2301 |
+
"""Represent the OneOfPosition object as a string for debugging."""
|
| 2302 |
+
return "%s(%i, choices=%r)" % (
|
| 2303 |
+
self.__class__.__name__,
|
| 2304 |
+
int(self),
|
| 2305 |
+
self.position_choices,
|
| 2306 |
+
)
|
| 2307 |
+
|
| 2308 |
+
def __str__(self):
|
| 2309 |
+
"""Return a representation of the OneOfPosition object (with python counting)."""
|
| 2310 |
+
out = "one-of("
|
| 2311 |
+
for position in self.position_choices:
|
| 2312 |
+
out += f"{position},"
|
| 2313 |
+
# replace the last comma with the closing parenthesis
|
| 2314 |
+
return out[:-1] + ")"
|
| 2315 |
+
|
| 2316 |
+
def __add__(self, offset):
|
| 2317 |
+
"""Return a copy of the position object with its location shifted (PRIVATE)."""
|
| 2318 |
+
return self.__class__(
|
| 2319 |
+
int(self) + offset, [p + offset for p in self.position_choices]
|
| 2320 |
+
)
|
| 2321 |
+
|
| 2322 |
+
def _flip(self, length):
|
| 2323 |
+
"""Return a copy of the location after the parent is reversed (PRIVATE)."""
|
| 2324 |
+
return self.__class__(
|
| 2325 |
+
length - int(self), [p._flip(length) for p in self.position_choices[::-1]]
|
| 2326 |
+
)
|
| 2327 |
+
|
| 2328 |
+
|
| 2329 |
+
if __name__ == "__main__":
|
| 2330 |
+
from Bio._utils import run_doctest
|
| 2331 |
+
|
| 2332 |
+
run_doctest()
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AbiIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AceIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._FastaIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GckIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GfaIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._IgIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._InsdcIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._Interfaces.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._NibIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PdbIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PhdIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PirIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._QualityIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SeqXmlIO.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|