diff --git a/.gitattributes b/.gitattributes index 291b37d686dbc6444c8c2011d00f9cf1bf7d93e4..f7f9a841aeba8a63368ebd41a01e2c3b39d03bcf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -63,3 +63,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv_haddock/bin/python3.12 filter=lfs diff=lfs merge=lfs -text .venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text .venv_haddock/lib/python3.12/site-packages/Bio/Cluster/_cluster.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text +.venv_haddock/lib/python3.12/site-packages/freesasa.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text +.venv_haddock/lib/python3.12/site-packages/haddock/bin/haddock-restraints filter=lfs diff=lfs merge=lfs -text diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/_base.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..3c20ad7eb7e85a15a2e6e4bcb5fdf5372401b333 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/_base.py @@ -0,0 +1,45 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO base classes for HMMER-related code.""" + +from Bio.SearchIO._index import SearchIndexer + + +class _BaseHmmerTextIndexer(SearchIndexer): + """Base indexer class for HMMER plain text output.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._preamble = b"" + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + handle = self._handle + qresult_raw = b"" + + # read header first + if not self._preamble: + handle.seek(0) + while True: + line = handle.readline() + if line.startswith(self.qresult_start): + break + qresult_raw += line + else: + qresult_raw += self._preamble + + # and read the qresult raw string + handle.seek(offset) + while True: + # preserve whitespace, don't use read_forward + line = handle.readline() + qresult_raw += line + + # break when we've reached qresult end + if line.startswith(self.qresult_end) or not line: + break + + return qresult_raw diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer2_text.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer2_text.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2060ab77013bc2e47d31c98ac40fa7d558862d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer2_text.py @@ -0,0 +1,377 @@ +# Copyright 2012 by Kai Blin. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO parser for HMMER 2 text output.""" + +import re + +from Bio.SearchIO._model import Hit +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult +from Bio.SearchIO._utils import read_forward + +from ._base import _BaseHmmerTextIndexer + +__all__ = ("Hmmer2TextParser", "Hmmer2TextIndexer") + + +_HSP_ALIGN_LINE = re.compile(r"(\S+):\s+domain (\d+) of (\d+)") + + +class _HitPlaceholder: + def createHit(self, hsp_list): + hit = Hit(hsp_list) + hit.id_ = self.id_ + hit.evalue = self.evalue + hit.bitscore = self.bitscore + if self.description: + hit.description = self.description + hit.domain_obs_num = self.domain_obs_num + return hit + + +class Hmmer2TextParser: + """Iterator for the HMMER 2.0 text output.""" + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + self.buf = [] + self._meta = self.parse_preamble() + + def __iter__(self): + """Iterate over Hmmer2TextParser, yields query results.""" + for qresult in self.parse_qresult(): + qresult.program = self._meta.get("program") + qresult.target = self._meta.get("target") + qresult.version = self._meta.get("version") + yield qresult + + def read_next(self, rstrip=True): + """Return the next non-empty line, trailing whitespace removed.""" + if len(self.buf) > 0: + return self.buf.pop() + self.line = self.handle.readline() + while self.line and rstrip and not self.line.strip(): + self.line = self.handle.readline() + if self.line: + if rstrip: + self.line = self.line.rstrip() + return self.line + + def push_back(self, line): + """Un-read a line that should not be parsed yet.""" + self.buf.append(line) + + def parse_key_value(self): + """Parse key-value pair separated by colon.""" + key, value = self.line.split(":", 1) + return key.strip(), value.strip() + + def parse_preamble(self): + """Parse HMMER2 preamble.""" + meta = {} + state = "GENERIC" + while self.read_next(): + if state == "GENERIC": + if self.line.startswith("hmm"): + meta["program"] = self.line.split("-")[0].strip() + elif self.line.startswith("HMMER is"): + continue + elif self.line.startswith("HMMER"): + meta["version"] = self.line.split()[1] + elif self.line.count("-") == 36: + state = "OPTIONS" + continue + + assert state == "OPTIONS" + assert "program" in meta + + if self.line.count("-") == 32: + break + + key, value = self.parse_key_value() + if meta["program"] == "hmmsearch": + if key == "Sequence database": + meta["target"] = value + continue + elif meta["program"] == "hmmpfam": + if key == "HMM file": + meta["target"] = value + continue + meta[key] = value + + return meta + + def parse_qresult(self): + """Parse a HMMER2 query block.""" + while self.read_next(): + if not self.line.startswith("Query"): + return + _, id_ = self.parse_key_value() + self.qresult = QueryResult(id=id_) + + description = None + + while self.read_next() and not self.line.startswith("Scores"): + if self.line.startswith("Accession"): + self.qresult.accession = self.parse_key_value()[1] + if self.line.startswith("Description"): + description = self.parse_key_value()[1] + + hit_placeholders = self.parse_hits() + if len(hit_placeholders) > 0: + self.parse_hsps(hit_placeholders) + self.parse_hsp_alignments() + + while not self.line.startswith("Query"): + self.read_next() + if not self.line: + break + self.buf.append(self.line) + + if description is not None: + self.qresult.description = description + yield self.qresult + + def parse_hits(self): + """Parse a HMMER2 hit block, beginning with the hit table.""" + hit_placeholders = [] + while self.read_next(): + if self.line.startswith("Parsed"): + break + if self.line.find("no hits") > -1: + break + + if ( + self.line.startswith("Sequence") + or self.line.startswith("Model") + or self.line.startswith("-------- ") + ): + continue + + fields = self.line.split() + id_ = fields.pop(0) + domain_obs_num = int(fields.pop()) + evalue = float(fields.pop()) + bitscore = float(fields.pop()) + description = " ".join(fields).strip() + + hit = _HitPlaceholder() + hit.id_ = id_ + hit.evalue = evalue + hit.bitscore = bitscore + hit.description = description + hit.domain_obs_num = domain_obs_num + hit_placeholders.append(hit) + + return hit_placeholders + + def parse_hsps(self, hit_placeholders): + """Parse a HMMER2 hsp block, beginning with the hsp table.""" + # HSPs may occur in different order than the hits + # so store Hit objects separately first + unordered_hits = {} + while self.read_next(): + if ( + self.line.startswith("Alignments") + or self.line.startswith("Histogram") + or self.line == "//" + ): + break + if ( + self.line.startswith("Model") + or self.line.startswith("Sequence") + or self.line.startswith("--------") + ): + continue + + ( + id_, + domain, + seq_f, + seq_t, + seq_compl, + hmm_f, + hmm_t, + hmm_compl, + score, + evalue, + ) = self.line.split() + + frag = HSPFragment(id_, self.qresult.id) + frag.molecule_type = "protein" + if self._meta["program"] == "hmmpfam": + frag.hit_start = int(hmm_f) - 1 + frag.hit_end = int(hmm_t) + frag.query_start = int(seq_f) - 1 + frag.query_end = int(seq_t) + elif self._meta["program"] == "hmmsearch": + frag.query_start = int(hmm_f) - 1 + frag.query_end = int(hmm_t) + frag.hit_start = int(seq_f) - 1 + frag.hit_end = int(seq_t) + + hsp = HSP([frag]) + hsp.evalue = float(evalue) + hsp.bitscore = float(score) + hsp.domain_index = int(domain.split("/")[0]) + if self._meta["program"] == "hmmpfam": + hsp.hit_endtype = hmm_compl + hsp.query_endtype = seq_compl + elif self._meta["program"] == "hmmsearch": + hsp.query_endtype = hmm_compl + hsp.hit_endtype = seq_compl + + if id_ not in unordered_hits: + placeholder = [p for p in hit_placeholders if p.id_ == id_][0] + hit = placeholder.createHit([hsp]) + unordered_hits[id_] = hit + else: + hit = unordered_hits[id_] + hsp.hit_description = hit.description + hit.append(hsp) + + # The placeholder list is in the correct order, so use that order for + # the Hit objects in the qresult + for p in hit_placeholders: + self.qresult.append(unordered_hits[p.id_]) + + def parse_hsp_alignments(self): + """Parse a HMMER2 HSP alignment block.""" + if not self.line.startswith("Alignments"): + return + + while self.read_next(): + if self.line == "//" or self.line.startswith("Histogram"): + break + + match = re.search(_HSP_ALIGN_LINE, self.line) + if match is None: + continue + + id_ = match.group(1) + idx = int(match.group(2)) + num = int(match.group(3)) + + hit = self.qresult[id_] + if hit.domain_obs_num != num: + continue + + frag = hit[idx - 1][0] + + hmmseq = "" + consensus = "" + otherseq = "" + structureseq = "" + pad = 0 + while self.read_next() and self.line.startswith(" "): + # if there's structure information, parse that + if self.line[16:18] == "CS": + structureseq += self.line[19:].strip() + + if not self.read_next(): + break + + # skip the *-> start marker if it exists + if self.line[19:22] == "*->": + seq = self.line[22:] + pad = 3 + else: + seq = self.line[19:] + pad = 0 + + hmmseq += seq + line_len = len(seq) + if not self.read_next(rstrip=False): + break + consensus += self.line[19 + pad : 19 + pad + line_len] + # If there's no consensus sequence, hmmer2 doesn't + # bother to put spaces here, so add extra padding + extra_padding = len(hmmseq) - len(consensus) + consensus += " " * extra_padding + + if not self.read_next(): + break + + # if we have a line break in the end marker, we get a + # whitespace-only otherseq line, making split()[0] return + # the end coordinate. That'll be a -, which is a valid character + # in the sequence, meaning we can't just strip it. + parts = self.line[19:].split() + if len(parts) == 2: + otherseq += self.line[19:].split()[0].strip() + + self.push_back(self.line) + + # get rid of the end marker + if hmmseq.endswith("<-*"): + hmmseq = hmmseq[:-3] + consensus = consensus[:-3] + + # add similarity sequence to annotation + frag.aln_annotation["similarity"] = consensus + + # if there's structure information, add it to the fragment + if structureseq: + frag.aln_annotation["CS"] = structureseq + + if self._meta["program"] == "hmmpfam": + frag.hit = hmmseq + frag.query = otherseq + else: + frag.hit = otherseq + frag.query = hmmseq + + +class Hmmer2TextIndexer(_BaseHmmerTextIndexer): + """Indexer for hmmer2-text format.""" + + _parser = Hmmer2TextParser + qresult_start = b"Query" + # qresults_ends for hmmpfam and hmmsearch + # need to anticipate both since hmmsearch have different query end mark + qresult_end = b"//" + + def __iter__(self): + """Iterate over Hmmer2TextIndexer; yields query results' key, offsets, 0.""" + handle = self._handle + handle.seek(0) + start_offset = handle.tell() + regex_id = re.compile(rb"Query\s*(?:sequence|HMM)?:\s*(.*)") + + # determine flag for hmmsearch + is_hmmsearch = False + line = read_forward(handle) + if line.startswith(b"hmmsearch"): + is_hmmsearch = True + + while True: + end_offset = handle.tell() + + if line.startswith(self.qresult_start): + regx = re.search(regex_id, line) + qresult_key = regx.group(1).strip() + # qresult start offset is the offset of this line + # (starts with the start mark) + start_offset = end_offset - len(line) + elif line.startswith(self.qresult_end): + yield qresult_key.decode(), start_offset, 0 + start_offset = end_offset + elif not line: + # HACK: since hmmsearch can only have one query result + if is_hmmsearch: + yield qresult_key.decode(), start_offset, 0 + break + + line = read_forward(handle) + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_domtab.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_domtab.py new file mode 100644 index 0000000000000000000000000000000000000000..d052b5268ba3814e9da75d2cac083dc84008c0f5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_domtab.py @@ -0,0 +1,378 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO parser for HMMER domain table output format.""" + +from itertools import chain + +from Bio.SearchIO._model import Hit +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult + +from .hmmer3_tab import Hmmer3TabIndexer +from .hmmer3_tab import Hmmer3TabParser + +__all__ = ( + "Hmmer3DomtabHmmhitParser", + "Hmmer3DomtabHmmqueryParser", + "Hmmer3DomtabHmmhitIndexer", + "Hmmer3DomtabHmmqueryIndexer", + "Hmmer3DomtabHmmhitWriter", + "Hmmer3DomtabHmmqueryWriter", +) + + +class Hmmer3DomtabParser(Hmmer3TabParser): + """Base hmmer3-domtab iterator.""" + + def _parse_row(self): + """Return a dictionary of parsed row values (PRIVATE).""" + assert self.line + cols = [x for x in self.line.strip().split(" ") if x] + # if len(cols) > 23, we have extra description columns + # combine them all into one string in the 19th column + if len(cols) > 23: + cols[22] = " ".join(cols[22:]) + elif len(cols) < 23: + cols.append("") + assert len(cols) == 23 + + # assign parsed column data into qresult, hit, and hsp dicts + qresult = {} + qresult["id"] = cols[3] # query name + qresult["accession"] = cols[4] # query accession + qresult["seq_len"] = int(cols[5]) # qlen + hit = {} + hit["id"] = cols[0] # target name + hit["accession"] = cols[1] # target accession + hit["seq_len"] = int(cols[2]) # tlen + hit["evalue"] = float(cols[6]) # evalue + hit["bitscore"] = float(cols[7]) # score + hit["bias"] = float(cols[8]) # bias + hit["description"] = cols[22] # description of target + hsp = {} + hsp["domain_index"] = int(cols[9]) # # (domain number) + # not parsing cols[10] since it's basically len(hit) + hsp["evalue_cond"] = float(cols[11]) # c-evalue + hsp["evalue"] = float(cols[12]) # i-evalue + hsp["bitscore"] = float(cols[13]) # score + hsp["bias"] = float(cols[14]) # bias + hsp["env_start"] = int(cols[19]) - 1 # env from + hsp["env_end"] = int(cols[20]) # env to + hsp["acc_avg"] = float(cols[21]) # acc + frag = {} + # strand is always 0, since HMMER now only handles protein + frag["hit_strand"] = frag["query_strand"] = 0 + frag["hit_start"] = int(cols[15]) - 1 # hmm from + frag["hit_end"] = int(cols[16]) # hmm to + frag["query_start"] = int(cols[17]) - 1 # ali from + frag["query_end"] = int(cols[18]) # ali to + # HMMER results are always protein + frag["molecule_type"] = "protein" + + # switch hmm<-->ali coordinates if hmm is not hit + if not self.hmm_as_hit: + frag["hit_end"], frag["query_end"] = (frag["query_end"], frag["hit_end"]) + frag["hit_start"], frag["query_start"] = ( + frag["query_start"], + frag["hit_start"], + ) + + return {"qresult": qresult, "hit": hit, "hsp": hsp, "frag": frag} + + def _parse_qresult(self): + """Return QueryResult objects (PRIVATE).""" + # state values, determines what to do for each line + state_EOF = 0 + state_QRES_NEW = 1 + state_QRES_SAME = 3 + state_HIT_NEW = 2 + state_HIT_SAME = 4 + # dummies for initial states + qres_state = None + hit_state = None + file_state = None + # dummies for initial id caches + prev_qid = None + prev_hid = None + # dummies for initial parsed value containers + cur, prev = None, None + hit_list, hsp_list = [], [] + cur_qid = None + cur_hid = None + while True: + # store previous line's parsed values, for every line after the 1st + if cur is not None: + prev = cur + prev_qid = cur_qid + prev_hid = cur_hid + # only parse the line if it's not EOF + if self.line and not self.line.startswith("#"): + cur = self._parse_row() + cur_qid = cur["qresult"]["id"] + cur_hid = cur["hit"]["id"] + else: + file_state = state_EOF + # mock ID values since the line is empty + cur_qid, cur_hid = None, None + + # get the state of hit and qresult + if prev_qid != cur_qid: + qres_state = state_QRES_NEW + else: + qres_state = state_QRES_SAME + # new hits are hits with different ids or hits in a new qresult + if prev_hid != cur_hid or qres_state == state_QRES_NEW: + hit_state = state_HIT_NEW + else: + hit_state = state_HIT_SAME + + # start creating objects after the first line (i.e. prev is filled) + if prev is not None: + # each line is basically an HSP with one HSPFragment + frag = HSPFragment(prev_hid, prev_qid) + for attr, value in prev["frag"].items(): + setattr(frag, attr, value) + hsp = HSP([frag]) + for attr, value in prev["hsp"].items(): + setattr(hsp, attr, value) + hsp_list.append(hsp) + + # create hit object when we've finished parsing all its hsps + # i.e. when hit state is state_HIT_NEW + if hit_state == state_HIT_NEW: + hit = Hit(hsp_list) + for attr, value in prev["hit"].items(): + setattr(hit, attr, value) + hit_list.append(hit) + hsp_list = [] + + # create qresult and yield if we're at a new qresult or EOF + if qres_state == state_QRES_NEW or file_state == state_EOF: + qresult = QueryResult(hit_list, prev_qid) + for attr, value in prev["qresult"].items(): + setattr(qresult, attr, value) + yield qresult + # if current line is EOF, break + if file_state == state_EOF: + break + hit_list = [] + + self.line = self.handle.readline() + + +class Hmmer3DomtabHmmhitParser(Hmmer3DomtabParser): + """HMMER domain table parser using hit coordinates. + + Parser for the HMMER domain table format that assumes HMM profile + coordinates are hit coordinates. + """ + + hmm_as_hit = True + + +class Hmmer3DomtabHmmqueryParser(Hmmer3DomtabParser): + """HMMER domain table parser using query coordinates. + + Parser for the HMMER domain table format that assumes HMM profile + coordinates are query coordinates. + """ + + hmm_as_hit = False + + +class Hmmer3DomtabHmmhitIndexer(Hmmer3TabIndexer): + """HMMER domain table indexer using hit coordinates. + + Indexer class for HMMER domain table output that assumes HMM profile + coordinates are hit coordinates. + """ + + _parser = Hmmer3DomtabHmmhitParser + _query_id_idx = 3 + + +class Hmmer3DomtabHmmqueryIndexer(Hmmer3TabIndexer): + """HMMER domain table indexer using query coordinates. + + Indexer class for HMMER domain table output that assumes HMM profile + coordinates are query coordinates. + """ + + _parser = Hmmer3DomtabHmmqueryParser + _query_id_idx = 3 + + +class Hmmer3DomtabHmmhitWriter: + """HMMER domain table writer using hit coordinates. + + Writer for hmmer3-domtab output format which writes hit coordinates + as HMM profile coordinates. + """ + + hmm_as_hit = True + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + + def write_file(self, qresults): + """Write to the handle. + + Returns a tuple of how many QueryResult, Hit, and HSP objects were written. + + """ + handle = self.handle + qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0 + + try: + first_qresult = next(qresults) + except StopIteration: + handle.write(self._build_header()) + else: + # write header + handle.write(self._build_header(first_qresult)) + # and then the qresults + for qresult in chain([first_qresult], qresults): + if qresult: + handle.write(self._build_row(qresult)) + qresult_counter += 1 + hit_counter += len(qresult) + hsp_counter += sum(len(hit) for hit in qresult) + frag_counter += sum(len(hit.fragments) for hit in qresult) + + return qresult_counter, hit_counter, hsp_counter, frag_counter + + def _build_header(self, first_qresult=None): + """Return the header string of a domain HMMER table output (PRIVATE).""" + # calculate whitespace required + # adapted from HMMER's source: src/p7_tophits.c#L1157 + if first_qresult: + # qnamew = max(20, len(first_qresult.id)) + qnamew = 20 + tnamew = max(20, len(first_qresult[0].id)) + try: + qaccw = max(10, len(first_qresult.acc)) + taccw = max(10, len(first_qresult[0].acc)) + except AttributeError: + qaccw, taccw = 10, 10 + else: + qnamew, tnamew, qaccw, taccw = 20, 20, 10, 10 + # Turn black code style off + # fmt: off + header = ("#%*s %22s %40s %11s %11s %11s\n" + % (tnamew + qnamew - 1 + 15 + taccw + qaccw, "", "--- full sequence ---", + "-------------- this domain -------------", "hmm coord", + "ali coord", "env coord")) + header += ("#%-*s %-*s %5s %-*s %-*s %5s %9s %6s %5s %3s %3s %9s " + "%9s %6s %5s %5s %5s %5s %5s %5s %5s %4s %s\n" + % (tnamew - 1, + " target name", taccw, "accession", "tlen", qnamew, + "query name", qaccw, "accession", "qlen", "E-value", "score", + "bias", "#", "of", "c-Evalue", "i-Evalue", "score", "bias", + "from", "to", "from", "to", "from", "to", "acc", + "description of target")) + header += ("#%*s %*s %5s %*s %*s %5s %9s %6s %5s %3s %3s %9s %9s " + "%6s %5s %5s %5s %5s %5s %5s %5s %4s %s\n" + % (tnamew - 1, + "-------------------", taccw, "----------", "-----", + qnamew, "--------------------", qaccw, "----------", + "-----", "---------", "------", "-----", "---", "---", + "---------", "---------", "------", "-----", "-----", "-----", + "-----", "-----", "-----", "-----", "----", + "---------------------")) + # Turn black code style on + # fmt: on + return header + + def _build_row(self, qresult): + """Return a string or one row or more of the QueryResult object (PRIVATE).""" + rows = "" + + # calculate whitespace required + # adapted from HMMER's source: src/p7_tophits.c#L1083 + qnamew = max(20, len(qresult.id)) + tnamew = max(20, len(qresult[0].id)) + try: + qaccw = max(10, len(qresult.accession)) + taccw = max(10, len(qresult[0].accession)) + qresult_acc = qresult.accession + except AttributeError: + qaccw, taccw = 10, 10 + qresult_acc = "-" + + for hit in qresult: + # try to get hit accession + try: + hit_acc = hit.accession + except AttributeError: + hit_acc = "-" + + for hsp in hit.hsps: + if self.hmm_as_hit: + hmm_to = hsp.hit_end + hmm_from = hsp.hit_start + 1 + ali_to = hsp.query_end + ali_from = hsp.query_start + 1 + else: + hmm_to = hsp.query_end + hmm_from = hsp.query_start + 1 + ali_to = hsp.hit_end + ali_from = hsp.hit_start + 1 + + rows += ( + "%-*s %-*s %5d %-*s %-*s %5d %9.2g %6.1f %5.1f %3d" + " %3d %9.2g %9.2g %6.1f %5.1f %5d %5d %5ld %5ld" + " %5d %5d %4.2f %s\n" + % ( + tnamew, + hit.id, + taccw, + hit_acc, + hit.seq_len, + qnamew, + qresult.id, + qaccw, + qresult_acc, + qresult.seq_len, + hit.evalue, + hit.bitscore, + hit.bias, + hsp.domain_index, + len(hit.hsps), + hsp.evalue_cond, + hsp.evalue, + hsp.bitscore, + hsp.bias, + hmm_from, + hmm_to, + ali_from, + ali_to, + hsp.env_start + 1, + hsp.env_end, + hsp.acc_avg, + hit.description, + ) + ) + + return rows + + +class Hmmer3DomtabHmmqueryWriter(Hmmer3DomtabHmmhitWriter): + """HMMER domain table writer using query coordinates. + + Writer for hmmer3-domtab output format which writes query coordinates + as HMM profile coordinates. + """ + + hmm_as_hit = False + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_tab.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_tab.py new file mode 100644 index 0000000000000000000000000000000000000000..f99f454cfe25a3c5540581e90e94dea55f592b56 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_tab.py @@ -0,0 +1,337 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO parser for HMMER table output format.""" + +from itertools import chain + +from Bio.SearchIO._index import SearchIndexer +from Bio.SearchIO._model import Hit +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult + +__all__ = ("Hmmer3TabParser", "Hmmer3TabIndexer", "Hmmer3TabWriter") + + +class Hmmer3TabParser: + """Parser for the HMMER table format.""" + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + self.line = self.handle.readline() + + def __iter__(self): + """Iterate over Hmmer3TabParser, yields query results.""" + header_mark = "#" + # read through the header if it exists + while self.line.startswith(header_mark): + self.line = self.handle.readline() + # if we have result rows, parse it + if self.line: + yield from self._parse_qresult() + + def _parse_row(self): + """Return a dictionary of parsed row values (PRIVATE).""" + cols = [x for x in self.line.strip().split(" ") if x] + if len(cols) < 18: + raise ValueError("Less columns than expected, only %i" % len(cols)) + # if len(cols) > 19, we have extra description columns + # combine them all into one string in the 19th column + cols[18] = " ".join(cols[18:]) + + # assign parsed column data into qresult, hit, and hsp dicts + qresult = {} + qresult["id"] = cols[2] # query name + qresult["accession"] = cols[3] # query accession + hit = {} + hit["id"] = cols[0] # target name + hit["accession"] = cols[1] # target accession + hit["evalue"] = float(cols[4]) # evalue (full sequence) + hit["bitscore"] = float(cols[5]) # score (full sequence) + hit["bias"] = float(cols[6]) # bias (full sequence) + hit["domain_exp_num"] = float(cols[10]) # exp + hit["region_num"] = int(cols[11]) # reg + hit["cluster_num"] = int(cols[12]) # clu + hit["overlap_num"] = int(cols[13]) # ov + hit["env_num"] = int(cols[14]) # env + hit["domain_obs_num"] = int(cols[15]) # dom + hit["domain_reported_num"] = int(cols[16]) # rep + hit["domain_included_num"] = int(cols[17]) # inc + hit["description"] = cols[18] # description of target + hsp = {} + hsp["evalue"] = float(cols[7]) # evalue (best 1 domain) + hsp["bitscore"] = float(cols[8]) # score (best 1 domain) + hsp["bias"] = float(cols[9]) # bias (best 1 domain) + # strand is always 0, since HMMER now only handles protein + frag = {} + frag["hit_strand"] = frag["query_strand"] = 0 + frag["molecule_type"] = "protein" + + return {"qresult": qresult, "hit": hit, "hsp": hsp, "frag": frag} + + def _parse_qresult(self): + """Return QueryResult objects (PRIVATE).""" + # state values, determines what to do for each line + state_EOF = 0 + state_QRES_NEW = 1 + state_QRES_SAME = 3 + # initial value dummies + qres_state = None + file_state = None + prev_qid = None + cur, prev = None, None + # container for Hit objects, used to create QueryResult + hit_list = [] + cur_qid = None + while True: + # store previous line's parsed values for all lines after the first + if cur is not None: + prev = cur + prev_qid = cur_qid + # only parse the result row if it's not EOF + # NOTE: we are not parsing the extra '#' lines appended to the end + # of hmmer31b1 tabular results since storing them in qresult + # objects means we can not do a single-pass parsing + if self.line and not self.line.startswith("#"): + cur = self._parse_row() + cur_qid = cur["qresult"]["id"] + else: + file_state = state_EOF + # mock value for cur_qid, since we have nothing to parse + cur_qid = None + + if prev_qid != cur_qid: + qres_state = state_QRES_NEW + else: + qres_state = state_QRES_SAME + + if prev is not None: + # since domain tab formats only have 1 Hit per line + # we always create HSPFragment, HSP, and Hit per line + prev_hid = prev["hit"]["id"] + + # create fragment and HSP and set their attributes + frag = HSPFragment(prev_hid, prev_qid) + for attr, value in prev["frag"].items(): + setattr(frag, attr, value) + hsp = HSP([frag]) + for attr, value in prev["hsp"].items(): + setattr(hsp, attr, value) + + # create Hit and set its attributes + hit = Hit([hsp]) + for attr, value in prev["hit"].items(): + setattr(hit, attr, value) + hit_list.append(hit) + + # create qresult and yield if we're at a new qresult or at EOF + if qres_state == state_QRES_NEW or file_state == state_EOF: + qresult = QueryResult(hit_list, prev_qid) + for attr, value in prev["qresult"].items(): + setattr(qresult, attr, value) + yield qresult + # if we're at EOF, break + if file_state == state_EOF: + break + hit_list = [] + + self.line = self.handle.readline() + + +class Hmmer3TabIndexer(SearchIndexer): + """Indexer class for HMMER table output.""" + + _parser = Hmmer3TabParser + # denotes column location for query identifier + _query_id_idx = 2 + + def __iter__(self): + """Iterate over the file handle; yields key, start offset, and length.""" + handle = self._handle + handle.seek(0) + query_id_idx = self._query_id_idx + qresult_key = None + header_mark = b"#" + split_mark = b" " + # set line with initial mock value, to emulate header + line = header_mark + + # read through header + while line.startswith(header_mark): + start_offset = handle.tell() + line = handle.readline() + + # and index the qresults + while True: + end_offset = handle.tell() + + if not line: + break + + cols = [x for x in line.strip().split(split_mark) if x] + if qresult_key is None: + qresult_key = cols[query_id_idx] + else: + curr_key = cols[query_id_idx] + + if curr_key != qresult_key: + adj_end = end_offset - len(line) + yield (qresult_key.decode(), start_offset, adj_end - start_offset) + qresult_key = curr_key + start_offset = adj_end + + line = handle.readline() + if not line: + yield (qresult_key.decode(), start_offset, end_offset - start_offset) + break + + def get_raw(self, offset): + """Return the raw bytes string of a QueryResult object from the given offset.""" + handle = self._handle + handle.seek(offset) + query_id_idx = self._query_id_idx + qresult_key = None + qresult_raw = b"" + split_mark = b" " + + while True: + line = handle.readline() + if not line: + break + cols = [x for x in line.strip().split(split_mark) if x] + if qresult_key is None: + qresult_key = cols[query_id_idx] + else: + curr_key = cols[query_id_idx] + if curr_key != qresult_key: + break + qresult_raw += line + + return qresult_raw + + +class Hmmer3TabWriter: + """Writer for hmmer3-tab output format.""" + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + + def write_file(self, qresults): + """Write to the handle. + + Returns a tuple of how many QueryResult, Hit, and HSP objects were written. + + """ + handle = self.handle + qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0 + + try: + first_qresult = next(qresults) + except StopIteration: + handle.write(self._build_header()) + else: + # write header + handle.write(self._build_header(first_qresult)) + # and then the qresults + for qresult in chain([first_qresult], qresults): + if qresult: + handle.write(self._build_row(qresult)) + qresult_counter += 1 + hit_counter += len(qresult) + hsp_counter += sum(len(hit) for hit in qresult) + frag_counter += sum(len(hit.fragments) for hit in qresult) + + return qresult_counter, hit_counter, hsp_counter, frag_counter + + def _build_header(self, first_qresult=None): + """Return the header string of a HMMER table output (PRIVATE).""" + # calculate whitespace required + # adapted from HMMER's source: src/p7_tophits.c#L1083 + if first_qresult is not None: + # qnamew = max(20, len(first_qresult.id)) + qnamew = 20 # why doesn't the above work? + tnamew = max(20, len(first_qresult[0].id)) + qaccw = max(10, len(first_qresult.accession)) + taccw = max(10, len(first_qresult[0].accession)) + else: + qnamew, tnamew, qaccw, taccw = 20, 20, 10, 10 + # Turn black code style off + # fmt: off + header = ("#%*s %22s %22s %33s\n" + % (tnamew + qnamew + taccw + qaccw + 2, "", + "--- full sequence ----", "--- best 1 domain ----", + "--- domain number estimation ----")) + header += ("#%-*s %-*s %-*s %-*s %9s %6s %5s %9s %6s %5s %5s %3s " + "%3s %3s %3s %3s %3s %3s %s\n" + % (tnamew - 1, " target name", + taccw, "accession", qnamew, "query name", qaccw, + "accession", " E-value", " score", " bias", + " E-value", " score", " bias", "exp", + "reg", "clu", " ov", "env", "dom", "rep", + "inc", "description of target")) + header += ("#%*s %*s %*s %*s %9s %6s %5s %9s %6s %5s %5s %3s %3s " + "%3s %3s %3s %3s %3s %s\n" + % (tnamew - 1, "-------------------", + taccw, "----------", qnamew, "--------------------", qaccw, + "----------", "---------", "------", "-----", "---------", + "------", "-----", "---", "---", "---", "---", "---", "---", + "---", "---", "---------------------")) + # Turn black code style on + # fmt: on + return header + + def _build_row(self, qresult): + """Return a string or one row or more of the QueryResult object (PRIVATE).""" + rows = "" + + # calculate whitespace required + # adapted from HMMER's source: src/p7_tophits.c#L1083 + qnamew = max(20, len(qresult.id)) + tnamew = max(20, len(qresult[0].id)) + qaccw = max(10, len(qresult.accession)) + taccw = max(10, len(qresult[0].accession)) + + for hit in qresult: + rows += ( + "%-*s %-*s %-*s %-*s %9.2g %6.1f %5.1f %9.2g %6.1f" + " %5.1f %5.1f %3d %3d %3d %3d %3d %3d %3d %s\n" + % ( + tnamew, + hit.id, + taccw, + hit.accession, + qnamew, + qresult.id, + qaccw, + qresult.accession, + hit.evalue, + hit.bitscore, + hit.bias, + hit.hsps[0].evalue, + hit.hsps[0].bitscore, + hit.hsps[0].bias, + hit.domain_exp_num, + hit.region_num, + hit.cluster_num, + hit.overlap_num, + hit.env_num, + hit.domain_obs_num, + hit.domain_reported_num, + hit.domain_included_num, + hit.description, + ) + ) + + return rows + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_text.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_text.py new file mode 100644 index 0000000000000000000000000000000000000000..faf942230d611630bb333f85d514c4bd4bda1d0a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/HmmerIO/hmmer3_text.py @@ -0,0 +1,457 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO parser for HMMER plain text output format.""" + +import re + +from Bio.SearchIO._model import Hit +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult +from Bio.SearchIO._utils import read_forward + +from ._base import _BaseHmmerTextIndexer + +__all__ = ("Hmmer3TextParser", "Hmmer3TextIndexer") + + +# precompile regex patterns for faster processing +# regex for program name capture +_RE_PROGRAM = re.compile(r"^# .*?(\w?hmm\w+) :: .*$") +# regex for version string capture +_RE_VERSION = re.compile(r"# \w+ ([\w+\.]+) .*; http.*$") +# regex for option string capture +_RE_OPT = re.compile(r"^# (.+):\s+(.+)$") +# regex for parsing query id and length, for parsing +_QRE_ID_LEN_PTN = r"^Query:\s*(.*)\s+\[\w=(\d+)\]" +_QRE_ID_LEN = re.compile(_QRE_ID_LEN_PTN) +# regex for hsp validation +_HRE_VALIDATE = re.compile(r"score:\s(-?\d+\.?\d+)\sbits.*value:\s(.*)") +# regexes for parsing hsp alignment blocks +_HRE_ANNOT_LINE = re.compile(r"^(\s+)(.+)\s(\w+)") +_HRE_ID_LINE = re.compile(r"^(\s+\S+\s+[0-9-]+ )(.+?)(\s+[0-9-]+)") + + +class Hmmer3TextParser: + """Parser for the HMMER 3.0 text output.""" + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + self.line = read_forward(self.handle) + self._meta = self._parse_preamble() + + def __iter__(self): + """Iterate over query results.""" + yield from self._parse_qresult() + + def _read_until(self, bool_func): + """Read the file handle until the given function returns True (PRIVATE).""" + while True: + if not self.line or bool_func(self.line): + return + else: + self.line = read_forward(self.handle) + + def _parse_preamble(self): + """Parse HMMER preamble (lines beginning with '#') (PRIVATE).""" + meta = {} + # bool flag for storing state ~ whether we are parsing the option + # lines or not + has_opts = False + while True: + # no pound sign means we've left the preamble + if not self.line.startswith("#"): + break + # dashes could either mean we are entering or leaving the options + # section ~ so it's a switch for the has_opts flag + elif "- - -" in self.line: + if not has_opts: + # if flag is false, that means we're entering opts + # so switch the flag accordingly + has_opts = True + else: + # if flag is true, that means we've reached the end of opts + # so we can break out of the function + break + elif not has_opts: + # try parsing program + regx = re.search(_RE_PROGRAM, self.line) + if regx: + meta["program"] = regx.group(1) + # try parsing version + regx = re.search(_RE_VERSION, self.line) + if regx: + meta["version"] = regx.group(1) + elif has_opts: + regx = re.search(_RE_OPT, self.line) + # if target in regx.group(1), then we store the key as target + if "target" in regx.group(1): + meta["target"] = regx.group(2).strip() + else: + meta[regx.group(1)] = regx.group(2) + + self.line = read_forward(self.handle) + + return meta + + def _parse_qresult(self): + """Parse a HMMER3 query block (PRIVATE).""" + self._read_until(lambda line: line.startswith("Query:")) + + while self.line: + regx = re.search(_QRE_ID_LEN, self.line) + + while not regx: + self.line = read_forward(self.handle) + regx = re.search(_QRE_ID_LEN, self.line) + + # get query id and length + qid = regx.group(1).strip() + # store qresult attributes + qresult_attrs = { + "seq_len": int(regx.group(2)), + "program": self._meta.get("program"), + "version": self._meta.get("version"), + "target": self._meta.get("target"), + } + + # get description and accession, if they exist + qdesc = "" # placeholder + while not self.line.startswith("Scores for "): + self.line = read_forward(self.handle) + + if self.line.startswith("Accession:"): + acc = self.line.strip().split(" ", 1)[1] + qresult_attrs["accession"] = acc.strip() + elif self.line.startswith("Description:"): + qdesc = self.line.strip().split(" ", 1)[1].strip() + qresult_attrs["description"] = qdesc + + # parse the query hits + while self.line and "//" not in self.line: + hit_list = self._parse_hit(qid, qdesc) + # read through the statistics summary + # TODO: parse and store this information? + if self.line.startswith("Internal pipeline"): + while self.line and "//" not in self.line: + self.line = read_forward(self.handle) + + # create qresult, set its attributes and yield + # not initializing hit_list directly to handle empty hits + # (i.e. need to set its query description manually) + qresult = QueryResult(id=qid, hits=hit_list) + for attr, value in qresult_attrs.items(): + setattr(qresult, attr, value) + yield qresult + self.line = read_forward(self.handle) + + # Skip line beginning with '# Alignment of', which are output + # when running phmmer with the '-A' flag. + if self.line.startswith("#"): + self.line = self.handle.readline() + + # HMMER >= 3.1 outputs '[ok]' at the end of all results file, + # which means we can break the main loop when we see the line + if "[ok]" in self.line: + break + + def _parse_hit(self, qid, qdesc): + """Parse a HMMER3 hit block, beginning with the hit table (PRIVATE).""" + # get to the end of the hit table delimiter and read one more line + self._read_until(lambda line: line.startswith(" ------- ------ -----")) + self.line = read_forward(self.handle) + + # assume every hit is in inclusion threshold until the inclusion + # threshold line is encountered + is_included = True + + # parse the hit table + hit_attr_list = [] + while True: + if not self.line: + return [] + elif self.line.startswith(" ------ inclusion"): + is_included = False + self.line = read_forward(self.handle) + # if there are no hits, then there are no hsps + # so we forward-read until 'Internal pipeline..' + elif self.line.startswith(" [No hits detected that satisfy reporting"): + while True: + self.line = read_forward(self.handle) + if self.line.startswith("Internal pipeline"): + assert len(hit_attr_list) == 0 + return [] + elif self.line.startswith("Domain annotation for each "): + hit_list = self._create_hits(hit_attr_list, qid, qdesc) + return hit_list + # entering hit results row + # parse the columns into a list + row = [x for x in self.line.strip().split(" ") if x] + # join the description words if it's >1 word + if len(row) > 10: + row[9] = " ".join(row[9:]) + # if there's no description, set it to an empty string + elif len(row) < 10: + row.append("") + assert len(row) == 10 + # create the hit object + hit_attrs = { + "id": row[8], + "query_id": qid, + "evalue": float(row[0]), + "bitscore": float(row[1]), + "bias": float(row[2]), + # row[3:6] is not parsed, since the info is available + # at the HSP level + "domain_exp_num": float(row[6]), + "domain_obs_num": int(row[7]), + "description": row[9], + "is_included": is_included, + } + hit_attr_list.append(hit_attrs) + + self.line = read_forward(self.handle) + + def _create_hits(self, hit_attrs, qid, qdesc): + """Parse a HMMER3 hsp block, beginning with the hsp table (PRIVATE).""" + # read through until the beginning of the hsp block + self._read_until(lambda line: line.startswith(("Internal pipeline", ">>"))) + + # start parsing the hsp block + hit_list = [] + while True: + if self.line.startswith("Internal pipeline"): + # by this time we should've emptied the hit attr list + assert len(hit_attrs) == 0 + return hit_list + assert self.line.startswith(">>") + hid, hdesc = self.line[len(">> ") :].split(" ", 1) + hdesc = hdesc.strip() + + # read through the hsp table header and move one more line + self._read_until( + lambda line: line.startswith( + (" --- ------ ----- --------", " [No individual domains") + ) + ) + self.line = read_forward(self.handle) + + # parse the hsp table for the current hit + hsp_list = [] + while True: + # break out of hsp parsing if there are no hits, it's the last hsp + # or it's the start of a new hit + if ( + self.line.startswith(" [No targets detected that satisfy") + or self.line.startswith(" [No individual domains") + or self.line.startswith("Internal pipeline statistics summary:") + or self.line.startswith(" Alignments for each domain:") + or self.line.startswith(">>") + ): + hit_attr = hit_attrs.pop(0) + hit = Hit(hsp_list) + for attr, value in hit_attr.items(): + if attr == "description": + cur_val = getattr(hit, attr) + if cur_val and value and cur_val.startswith(value): + continue + setattr(hit, attr, value) + if not hit: + hit.query_description = qdesc + hit_list.append(hit) + break + + parsed = [x for x in self.line.strip().split(" ") if x] + assert len(parsed) == 16 + # parsed column order: + # index, is_included, bitscore, bias, evalue_cond, evalue + # hmmfrom, hmmto, query_ends, hit_ends, alifrom, alito, + # envfrom, envto, acc_avg + frag = HSPFragment(hid, qid) + # set query and hit descriptions if they are defined / nonempty string + if qdesc: + frag.query_description = qdesc + if hdesc: + frag.hit_description = hdesc + # HMMER3 results are always protein + frag.molecule_type = "protein" + # depending on whether the program is hmmsearch, hmmscan, or phmmer + # {hmm,ali}{from,to} can either be hit_{from,to} or query_{from,to} + # for hmmscan, hit is the hmm profile, query is the sequence + if self._meta.get("program") == "hmmscan": + # adjust 'from' and 'to' coordinates to 0-based ones + frag.hit_start = int(parsed[6]) - 1 + frag.hit_end = int(parsed[7]) + frag.query_start = int(parsed[9]) - 1 + frag.query_end = int(parsed[10]) + elif self._meta.get("program") in ["hmmsearch", "phmmer"]: + # adjust 'from' and 'to' coordinates to 0-based ones + frag.hit_start = int(parsed[9]) - 1 + frag.hit_end = int(parsed[10]) + frag.query_start = int(parsed[6]) - 1 + frag.query_end = int(parsed[7]) + # strand is always 0, since HMMER now only handles protein + frag.hit_strand = frag.query_strand = 0 + + hsp = HSP([frag]) + hsp.domain_index = int(parsed[0]) + hsp.is_included = parsed[1] == "!" + hsp.bitscore = float(parsed[2]) + hsp.bias = float(parsed[3]) + hsp.evalue_cond = float(parsed[4]) + hsp.evalue = float(parsed[5]) + if self._meta.get("program") == "hmmscan": + # adjust 'from' and 'to' coordinates to 0-based ones + hsp.hit_endtype = parsed[8] + hsp.query_endtype = parsed[11] + elif self._meta.get("program") in ["hmmsearch", "phmmer"]: + # adjust 'from' and 'to' coordinates to 0-based ones + hsp.hit_endtype = parsed[11] + hsp.query_endtype = parsed[8] + # adjust 'from' and 'to' coordinates to 0-based ones + hsp.env_start = int(parsed[12]) - 1 + hsp.env_end = int(parsed[13]) + hsp.env_endtype = parsed[14] + hsp.acc_avg = float(parsed[15]) + + hsp_list.append(hsp) + self.line = read_forward(self.handle) + + # parse the hsp alignments + if self.line.startswith(" Alignments for each domain:"): + self._parse_aln_block(hid, hit.hsps) + + def _parse_aln_block(self, hid, hsp_list): + """Parse a HMMER3 HSP alignment block (PRIVATE).""" + self.line = read_forward(self.handle) + dom_counter = 0 + while True: + if self.line.startswith(">>") or self.line.startswith("Internal pipeline"): + return hsp_list + assert self.line.startswith(" == domain %i" % (dom_counter + 1)) + # alias hsp to local var + # but note that we're still changing the attrs of the actual + # hsp inside the qresult as we're not creating a copy + frag = hsp_list[dom_counter][0] + # XXX: should we validate again here? regex is expensive.. + # regx = re.search(_HRE_VALIDATE, self.line) + # assert hsp.bitscore == float(regx.group(1)) + # assert hsp.evalue_cond == float(regx.group(2)) + hmmseq = "" + aliseq = "" + annot = {} + aln_prefix_len = None + self.line = self.handle.readline() + + # parse all the alignment blocks in the hsp + while True: + regx = None + + # check for hit or query line + # we don't check for the hit or query id specifically + # to anticipate special cases where query id == hit id + regx = re.search(_HRE_ID_LINE, self.line) + if regx: + # Try to capture the block prefix len, to parse the similarity + # string later. + if aln_prefix_len is None: + aln_prefix_len = len(regx.group(1)) + else: + assert aln_prefix_len == len(regx.group(1)) + # the first hit/query self.line we encounter is the hmmseq + if len(hmmseq) == len(aliseq): + hmmseq += regx.group(2) + # and for subsequent self.lines, len(hmmseq) is either + # > or == len(aliseq) + elif len(hmmseq) > len(aliseq): + aliseq += regx.group(2) + assert len(hmmseq) >= len(aliseq) + # check for start of new domain + elif ( + self.line.startswith(" == domain") + or self.line.startswith(">>") + or self.line.startswith("Internal pipeline") + ): + frag.aln_annotation = annot + if self._meta.get("program") == "hmmscan": + frag.hit = hmmseq + frag.query = aliseq + elif self._meta.get("program") in ["hmmsearch", "phmmer"]: + frag.hit = aliseq + frag.query = hmmseq + dom_counter += 1 + hmmseq = "" + aliseq = "" + annot = {} + aln_prefix_len = None + break + # check if it's an annotation line and parse it + # len(hmmseq) is only != len(aliseq) when the cursor is parsing + # the similarity character. + elif len(hmmseq) == len(aliseq): + regx = re.search(_HRE_ANNOT_LINE, self.line) + if regx: + annot_name = regx.group(3) + if annot_name in annot: + annot[annot_name] += regx.group(2) + else: + annot[annot_name] = regx.group(2) + # otherwise, assume we are seeing the similarity string (the string + # between the two alignments). We do that by checking if we have + # defined the aln_prefix_len variable, which is the length of string + # from the beginning of the line to the start of the actual alignment + # (sans the IDs). We need this string to see how many characters we + # should strip from the beginning of the line. We can't call `strip()` + # since the similarity string might start with empty characters. + elif aln_prefix_len is not None: + similarity = ( + self.line[aln_prefix_len:].removesuffix("\n").removesuffix("\r") + ) + if "similarity" not in annot: + annot["similarity"] = similarity + else: + annot["similarity"] += similarity + + self.line = self.handle.readline() + + +class Hmmer3TextIndexer(_BaseHmmerTextIndexer): + """Indexer class for HMMER plain text output.""" + + _parser = Hmmer3TextParser + qresult_start = b"Query: " + qresult_end = b"//" + + def __iter__(self): + """Iterate over Hmmer3TextIndexer; yields query results' key, offsets, 0.""" + handle = self._handle + handle.seek(0) + start_offset = handle.tell() + regex_id = re.compile(_QRE_ID_LEN_PTN.encode()) + + while True: + line = read_forward(handle) + end_offset = handle.tell() + + if line.startswith(self.qresult_start): + regx = re.search(regex_id, line) + qresult_key = regx.group(1).strip() + # qresult start offset is the offset of this line + # (starts with the start mark) + start_offset = end_offset - len(line) + elif line.startswith(self.qresult_end): + yield qresult_key.decode(), start_offset, 0 + start_offset = end_offset + elif not line: + break + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.__base.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.__base.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/.__base.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_tab.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_tab.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_tab.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_text.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_text.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/._infernal_text.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..342580f5b843b1165858aa8184c7f021f76c2734 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/__init__.py @@ -0,0 +1,233 @@ +# Copyright 2024 by Samuel Prince. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + + +"""Bio.SearchIO support for Infernal output formats. + +This module adds support for parsing Infernal outputs. Infernal is a +suite of programs for searching DNA sequence databases for RNA structure +and sequence similarities using covariance models (CMs). + +Bio.SearchIO.InfernalIO was tested on the following Infernal versions and flavors: + + - Infernal (1.0.0+): cmscan and cmsearch + +More information on HMMER are available through these links: + - Web page: http://eddylab.org/infernal/ + - User guide: http://eddylab.org/infernal/Userguide.pdf + + +Supported formats +================= + +Bio.SearchIO.InfernalIO supports the following Infernal output formats: + - Plain text - 'infernal-text' - parsing, indexing + - Tabular - 'infernal-tab' - parsing, indexing + +For all output formats, Infernal uses 'mdl' for 'query' and 'seq' for 'hit'. +InfernalIO is aware of this different naming scheme, and will use 'query' +and 'hit' to fit SearchIO's object model. + +Infernal sometime reports 'local ends' (i.e., a large insertion or deletion +in the optimal alignment), which are expresented by a number in brackets in +the alignment (ex. AUUAC*[88]*GUAGU). In InfernalIO, these local alignment +are split into fragments of the same HSP. + +infernal-text +============= + +The Infernal plain text parser supports output files with alignment +blocks (default) or without (with the '-noali' flag). If the alignment blocks +are present, it can parse files with variable alignment width (using the +'-notextw' or '-textw' flag). Both CM or HMM searches (with the '--hmmonly' +flag) output are supported. The parser only supports non-verbose output formats. + +The following SearchIO objects attributes are provided. + ++-----------------+-------------------------+----------------------------------+ +| Object | Attribute | Value | ++=================+=========================+==================================+ +| QueryResult | accession | query accession | +| +-------------------------+----------------------------------+ +| | description | query sequence description | +| +-------------------------+----------------------------------+ +| | id | query sequence ID | +| +-------------------------+----------------------------------+ +| | program | Infernal flavor | +| +-------------------------+----------------------------------+ +| | seq_len | full length of query sequence | +| +-------------------------+----------------------------------+ +| | target | target search database | +| +-------------------------+----------------------------------+ +| | version | Infernal version | ++-----------------+-------------------------+----------------------------------+ +| Hit | description | hit sequence description | +| +-------------------------+----------------------------------+ +| | id | hit sequence ID | ++-----------------+-------------------------+----------------------------------+ +| HSP | evalue | hsp evalue | +| +-------------------------+----------------------------------+ +| | bias | hsp bias | +| +-------------------------+----------------------------------+ +| | bitscore | hsp score | +| +-------------------------+----------------------------------+ +| | gc | gc fraction | +| +-------------------------+----------------------------------+ +| | is_included | boolean, whether the hit of the | +| | | hsp is in the inclusion | +| | | threshold | +| +-------------------------+----------------------------------+ +| | query_start | query start position | +| +-------------------------+----------------------------------+ +| | query_end | query end position | +| +-------------------------+----------------------------------+ +| | query_endtype | query sequence end types (e.g., | +| | | '[]', '..', '[.', '.]', etc.) | +| +-------------------------+----------------------------------+ +| | hit_start | hit start position | +| +-------------------------+----------------------------------+ +| | hit_end | hit end position | +| +-------------------------+----------------------------------+ +| | hit_endtype | hit sequence end types | +| +-------------------------+----------------------------------+ +| | acc_avg | expected accuracy per alignment | +| | | residue (acc column) | +| +-------------------------+----------------------------------+ +| | model | type of model used (cm or hmm) | +| +-------------------------+----------------------------------+ +| | truncated | indicate if the hit is truncated | +| | | (5', 3' or both) or not | ++-----------------+-------------------------+----------------------------------+ +| HSPFragment | aln_annotation | alignment similarity string and | +| | | other annotations (PP, CS, | +| | | similarity and NC (except for | +| | | --hmmonly)) | +| +-------------------------+----------------------------------+ +| | aln_span | length of alignment fragment | +| +-------------------------+----------------------------------+ +| | hit | hit sequence | +| +-------------------------+----------------------------------+ +| | hit_start | local alignment sequence start | +| | | coordinate (seq from) | +| +-------------------------+----------------------------------+ +| | hit_end | local alignment sequence end | +| | | coordinate (seq to) | +| +-------------------------+----------------------------------+ +| | hit_strand | hit sequence strand | +| +-------------------------+----------------------------------+ +| | query | query sequence | +| +-------------------------+----------------------------------+ +| | query_start | local model alignment start | +| | | coordinate (mdl from) | +| +-------------------------+----------------------------------+ +| | query_end | local model alignment end | +| | | coordinate (mdl to) | ++-----------------+-------------------------+----------------------------------+ + +infernal-tab +============ + +The Infernal plain text parser supports the standard cmsearch tabular output and +cmscan tabular output files formats 1, 2 and 3 (inferred automatically from the +header). + +Rows marked with '*' denotes attributes not available in the default format. + ++-----------------+-------------------------+----------------------------------+ +| Object | Attribute | Value | ++=================+=========================+==================================+ +| QueryResult | accession | query accession | +| +-------------------------+----------------------------------+ +| | id | query sequence ID | +| +-------------------------+----------------------------------+ +| | clan* | Rfam clan | +| +-------------------------+----------------------------------+ +| | seq_len* | query sequence length | ++-----------------+-------------------------+----------------------------------+ +| Hit | description | hit sequence description | +| +-------------------------+----------------------------------+ +| | id | hit sequence ID | +| +-------------------------+----------------------------------+ +| | accession | hit accession | +| +-------------------------+----------------------------------+ +| | seq_len* | hit sequence length | ++-----------------+-------------------------+----------------------------------+ +| HSP | evalue | hsp evalue | +| +-------------------------+----------------------------------+ +| | bias | hsp bias | +| +-------------------------+----------------------------------+ +| | bitscore | hsp score | +| +-------------------------+----------------------------------+ +| | gc | gc fraction | +| +-------------------------+----------------------------------+ +| | is_included | boolean, whether the hit of the | +| | | hsp is in the inclusion | +| | | threshold | +| +-------------------------+----------------------------------+ +| | model | type of model used (cm or hmm) | +| +-------------------------+----------------------------------+ +| | truncated | indicate if the hit is truncated | +| | | (5', 3' or both) or not | +| +-------------------------+----------------------------------+ +| | pipeline_pass | pipeline pass at which the hit | +| | | was identified | +| +-------------------------+----------------------------------+ +| | olp* | overlap status of this hit ('*', | +| | | '^', '$' or '=') | +| +-------------------------+----------------------------------+ +| | anyidx* | index of the best scoring | +| | | overlapping hit (or none if | +| | | there are no overlap) | +| +-------------------------+----------------------------------+ +| | afrct1* | fraction of this hit that | +| | | overlap with anyidx hit (or none | +| | | if there are no overlap) | +| +-------------------------+----------------------------------+ +| | afrct2* | fraction of anyidx hit | +| | | with this hit (or none if there | +| | | are no overlap) | +| +-------------------------+----------------------------------+ +| | winidx* | index of the best scoring hit | +| | | that overlaps with this hit that | +| | | is marked as '^' (or none if | +| | | there are no overlap) | +| +-------------------------+----------------------------------+ +| | wfrct1* | fraction of this hit that | +| | | overlap with winidx hit (or none | +| | | if there are no overlap) | +| +-------------------------+----------------------------------+ +| | wfrct2* | fraction of winidx hit | +| | | with this hit (or none if there | +| | | are no overlap) | ++-----------------+-------------------------+----------------------------------+ +| HSPFragment | hit_start | local alignment sequence start | +| (also via HSP) | | coordinate (seq from) | +| +-------------------------+----------------------------------+ +| | hit_end | local alignment sequence end | +| | | coordinate (seq to) | +| +-------------------------+----------------------------------+ +| | hit_strand | hit sequence strand | +| +-------------------------+----------------------------------+ +| | query_start | local model alignment start | +| | | coordinate (mdl from) | +| +-------------------------+----------------------------------+ +| | query_end | local model alignment end | +| | | coordinate (mdl to) | ++-----------------+-------------------------+----------------------------------+ +""" + +from .infernal_tab import InfernalTabParser +from .infernal_tab import InfernalTabIndexer +from .infernal_text import InfernalTextParser +from .infernal_text import InfernalTextIndexer + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/_base.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f87d353c82b44df05345b651865bb8d08037fe94 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/_base.py @@ -0,0 +1,39 @@ +# Copyright 2024 by Samuel Prince. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + + +"""Bio.SearchIO base classes for Infernal-related code.""" + +from Bio.SearchIO._model import Hit + + +class _BaseInfernalParser: + """Abstract class for Infernal parser objects.""" + + def _add_hit_to_dict(self, hit_attrs, hsp, hit_dict): + """Add a hit information to the hit container (PRIVATE).""" + # add the hit to the container dict, creating a new + # entry if it does not exist yet + hid = hit_attrs["id"] + if hid not in hit_dict: + hit_dict[hid] = {"attrs": hit_attrs, "hsps": []} + else: + assert hit_dict[hid]["attrs"]["query_id"] == hit_attrs["query_id"] + assert hit_dict[hid]["attrs"]["description"] == hit_attrs["description"] + + hit_dict[hid]["hsps"].append(hsp) + + def _hit_to_list(self, hit_dict): + """Create a Hit list from the hit container (PRIVATE).""" + + hit_list = [] + for hit_info in hit_dict.values(): + hit = Hit(hit_info["hsps"]) + for attr, value in hit_info["attrs"].items(): + setattr(hit, attr, value) + hit_list.append(hit) + return hit_list diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_tab.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_tab.py new file mode 100644 index 0000000000000000000000000000000000000000..bd6c4907c2394684c89ea4bacb888057e44a56d3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_tab.py @@ -0,0 +1,486 @@ +# Copyright 2024 by Samuel Prince. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Bio.SearchIO parser for Infernal tabular output format.""" + +from Bio.SearchIO._index import SearchIndexer +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult + +from ._base import _BaseInfernalParser +from Bio.File import _open_for_random_access + +__all__ = ("InfernalTabParser", "InfernalTabIndexer") + +# tabular format column names +_TAB_FORMAT = { + 1: ( + "target_name", + "target_acc", + "query_name", + "query_acc", + "mdl", + "mdl_from", + "mdl_to", + "seq_from", + "seq_to", + "strand", + "trunc", + "pass", + "gc", + "bias", + "score", + "evalue", + "inc", + "description", + ), + 2: ( + "idx", + "target_name", + "target_acc", + "query_name", + "query_acc", + "clan", + "mdl", + "mdl_from", + "mdl_to", + "seq_from", + "seq_to", + "strand", + "trunc", + "pass", + "gc", + "bias", + "score", + "evalue", + "inc", + "olp", + "anyidx", + "afrct1", + "afrct2", + "winidx", + "wfrct1", + "wfrct2", + "mdl_len", + "seq_len", + "description", + ), + 3: ( + "target_name", + "target_acc", + "query_name", + "query_acc", + "mdl", + "mdl_from", + "mdl_to", + "seq_from", + "seq_to", + "strand", + "trunc", + "pass", + "gc", + "bias", + "score", + "evalue", + "inc", + "mdl_len", + "seq_len", + "description", + ), +} + +_TABULAR_FMT_1_HEADER_FIELDS = [ + "target name", + "accession", + "query name", + "accession", + "mdl", + "mdl from", + "mdl to", + "seq from", + "seq to", + "strand", + "trunc", + "pass", + "gc", + "bias", + "score", + "E-value", + "inc", + "description of target", +] +_TABULAR_FMT_2_HEADER_FIELDS = [ + "idx", + "target name", + "accession", + "query name", + "accession", + "clan name", + "mdl", + "mdl from", + "mdl to", + "seq from", + "seq to", + "strand", + "trunc", + "pass", + "gc", + "bias", + "score", + "E-value", + "inc", + "olp", + "anyidx", + "afrct1", + "afrct2", + "winidx", + "wfrct1", + "wfrct2", + "mdl len", + "seq len", + "description of target", +] +_TABULAR_FMT_3_HEADER_FIELDS = [ + "target name", + "accession", + "query name", + "accession", + "mdl", + "mdl from", + "mdl to", + "seq from", + "seq to", + "strand", + "trunc", + "pass", + "gc", + "bias", + "score", + "E-value", + "inc", + "mdl len", + "seq len", + "description of target", +] + +# column to class attribute map +_COLUMN_QRESULT = { + "query_name": ("id", str), + "query_acc": ("accession", str), + "seq_len": ("seq_len", int), + "clan": ("clan", str), +} +_COLUMN_HIT = { + "target_name": ("id", str), + "target_acc": ("accession", str), + "query_name": ("query_id", str), + "description": ("description", str), + "mdl_len": ("seq_len", int), +} +_COLUMN_HSP = { + "score": ("bitscore", float), + "evalue": ("evalue", float), + "bias": ("bias", float), + "gc": ("gc", float), + "mdl": ("model", str), + "trunc": ("truncated", str), + "pass": ("pipeline_pass", int), + "inc": ("is_included", lambda x: True if x == "!" else False), + "olp": ("olp", str), + "anyidx": ("anyidx", lambda x: None if x == "-" else int(x)), + "afrct1": ("afrct1", lambda x: None if x == "-" else float(x)), + "afrct2": ("afrct2", lambda x: None if x == "-" else float(x)), + "winidx": ("winidx", lambda x: None if (x == "-" or x == '"') else int(x)), + "wfrct1": ("wfrct1", lambda x: None if (x == "-" or x == '"') else float(x)), + "wfrct2": ("wfrct2", lambda x: None if (x == "-" or x == '"') else float(x)), +} +_COLUMN_FRAG = { + "mdl_from": ("query_start", int), + "mdl_to": ("query_end", int), + "seq_from": ("hit_start", int), + "seq_to": ("hit_end", int), + "strand": ("hit_strand", str), +} + + +def _infer_tabular_format(handle, is_byte=False): + """Infer tabular format from the tabular file header. (PRIVATE)""" + # infernal tabular output columns are space separated files with spaces in + # column names, ex: + # #target name accession + # #------------------- --------- + # so we use the second line of the header where the is not spaces to + # determine the position of the headers labels. Then we can get the label names + # and compare the the different tabular format names. This label comparison is done + # (instead of counting fields) to avoid issues if future tabular format have the + # same number of fields, but with different signification + + def process_line(handle, is_byte): + """Process a line from the handle, decoding byte stream.""" + line = handle.readline().strip() + return line.decode() if is_byte else line + + header_label = process_line(handle, is_byte) + header_delim = process_line(handle, is_byte) + + if header_label == "" or header_delim == "": + raise ValueError( + "Unexpected empty line in the header of Infernal tabular output." + ) + + # get the indices of the spaces fields delimiter from the second header line + # the end of the file is added to the indices to process the last field + indices = [idx for idx, char in enumerate(header_delim) if char == " "] + [ + len(header_delim) + ] + prev_idx = 1 + fields = [] + for idx in indices: + fields.append(header_label[prev_idx:idx].strip()) + prev_idx = idx + + # compare the headers fields to the possible fields to determine the format + if fields == _TABULAR_FMT_1_HEADER_FIELDS: + return 1 + elif fields == _TABULAR_FMT_2_HEADER_FIELDS: + return 2 + elif fields == _TABULAR_FMT_3_HEADER_FIELDS: + return 3 + else: + raise ValueError( + "Cannot determine the tabular format from the header. \ + The tabular file is likely incorrect or its format is unsupported. \ + Tabular format 1, 2 and 3 are currently supported)." + ) + + +class InfernalTabParser(_BaseInfernalParser): + """Parser for the Infernal tabular format.""" + + def __init__(self, handle, _fmt=None): + """Initialize the class.""" + self.handle = handle + if isinstance(_fmt, int): + assert _fmt in {1, 2, 3} + self.fmt = _fmt + else: + self.fmt = _infer_tabular_format(handle=handle) + + def __iter__(self): + """Iterate over InfernalTabParser, yields query results.""" + # read through the header (and footer if there is no results) + self.line = self.handle.readline() + while self.line.startswith("#"): + self.line = self.handle.readline() + # if we have result rows, parse them + if self.line: + yield from self._parse_qresult() + + def _parse_row(self): + """Return a dictionary of parsed row values (PRIVATE).""" + cols = [x for x in self.line.strip().split(" ") if x] + if len(cols) < len(_TAB_FORMAT[self.fmt]): + raise ValueError( + f"Less columns than expected for format {self.fmt}, only {len(cols)}" + ) + # combine extra description columns into one string + cols[len(_TAB_FORMAT[self.fmt]) - 1] = " ".join( + cols[len(_TAB_FORMAT[self.fmt]) - 1 :] + ) + + qresult, hit, hsp, frag = {}, {}, {}, {} + for sname, value in zip( + _TAB_FORMAT[self.fmt], cols[: len(_TAB_FORMAT[self.fmt])] + ): + # iterate over each dict, mapping pair to determine + # attribute name and value of each column + for parsed_dict, mapping in ( + (qresult, _COLUMN_QRESULT), + (hit, _COLUMN_HIT), + (hsp, _COLUMN_HSP), + (frag, _COLUMN_FRAG), + ): + # process parsed value according to mapping + if sname in mapping: + attr_name, caster = mapping[sname] + if caster is not str: + value = caster(value) + parsed_dict[attr_name] = value + + # adjust start and end coordinates according to strand + self._adjust_coords(frag) + + return {"qresult": qresult, "hit": hit, "hsp": hsp, "frag": frag} + + def _adjust_coords(self, frag): + """Adjust start and end coordinates according to strand (PRIVATE).""" + strand = frag["hit_strand"] + assert strand is not None + # switch start <--> end coordinates if strand is -1 and the strand to an integer (0 or -1) + if strand == "-": + hit_start = frag["hit_start"] + hit_end = frag["hit_end"] + frag["hit_start"] = hit_end + frag["hit_end"] = hit_start + frag["hit_strand"] = -1 + else: + frag["hit_strand"] = 0 + + def _parse_qresult(self): + """Yield QueryResult objects (PRIVATE).""" + # state values, determines what to do for each line + state_EOF = 0 + state_QRES_NEW = 1 + state_QRES_SAME = 3 + # dummies for initial states + qres_state = None + file_state = None + cur_qid = None + cur_hid = None + # dummies for initial id caches + prev_qid = None + prev_hid = None + # dummies for initial parsed value containers + cur, prev = None, None + hit_dict = {} + + while True: + # store previous line's parsed values for all lines after the first + if cur is not None: + prev = cur + prev_qid = cur_qid + prev_hid = cur_hid + # only parse the result row if it's not EOF or a comment line + if self.line and not self.line.startswith("#"): + cur = self._parse_row() + cur_qid = cur["qresult"]["id"] + cur_hid = cur["hit"]["id"] + else: + file_state = state_EOF + # mock values for cur_qid and cur_hid since the line is empty + cur_qid, cur_hid = None, None + + # get the state of hit and qresult + if prev_qid != cur_qid: + qres_state = state_QRES_NEW + else: + qres_state = state_QRES_SAME + + # creating objects for the previously parsed line(s), so nothing is done + # in the first parsed line (prev == None) + if prev is not None: + # create fragment and HSP and set their attributes + # and append to hit container + frag = HSPFragment(prev_hid, prev_qid) + for attr, value in prev["frag"].items(): + setattr(frag, attr, value) + hsp = HSP([frag]) + for attr, value in prev["hsp"].items(): + setattr(hsp, attr, value) + self._add_hit_to_dict(prev["hit"], hsp, hit_dict) + + # create qresult and yield if we're at a new qresult or at EOF + if qres_state == state_QRES_NEW or file_state == state_EOF: + # create the hit list from the temporary container + qresult = QueryResult(self._hit_to_list(hit_dict), prev_qid) + for attr, value in prev["qresult"].items(): + setattr(qresult, attr, value) + yield qresult + # if we're at EOF, break + if file_state == state_EOF: + break + hit_dict = {} + + self.line = self.handle.readline() + + +class InfernalTabIndexer(SearchIndexer): + """Indexer class for Infernal tabular output.""" + + _parser = InfernalTabParser + + def __init__(self, filename): + """Initialize the class.""" + # the index of the query id column in the tabular file varies depending on the fmt + # we need to use the format set by the user, or infer the format to parse the records + with _open_for_random_access(filename) as handle: + fmt = _infer_tabular_format(handle, is_byte=True) + self._query_id_idx = 3 if fmt == 2 else 2 + + SearchIndexer.__init__(self, filename, _fmt=fmt) + + def __iter__(self): + """Iterate over the file handle; yields key, start offset, and length.""" + handle = self._handle + handle.seek(0) + qresult_key = None + start_offset = handle.tell() + + # set line with mock value + line = b"#" + + # read through header + while line.startswith(b"#"): + start_offset = handle.tell() + line = handle.readline() + + # index the qresults + while True: + # get end offset here since we only know a qresult ends after + # encountering the next one + end_offset = handle.tell() + + if not line: + break + + cols = [x for x in line.strip().split(b" ") if x] + + if qresult_key is None: + qresult_key = cols[self._query_id_idx] + else: + curr_key = cols[self._query_id_idx] + if curr_key != qresult_key: + adj_end = end_offset - len(line) + yield (qresult_key.decode(), start_offset, adj_end - start_offset) + qresult_key = curr_key + start_offset = adj_end + + line = handle.readline() + if not line or line.startswith(b"#"): + yield (qresult_key.decode(), start_offset, end_offset - start_offset) + break + + def get_raw(self, offset): + """Return the raw bytes string of a QueryResult object from the given offset.""" + handle = self._handle + qresult_key = None + qresult_raw = b"" + + # read the qresult raw string + handle.seek(offset) + while True: + line = handle.readline() + if not line or line.startswith(b"#"): + break + cols = [x for x in line.strip().split(b" ") if x] + if qresult_key is None: + qresult_key = cols[self._query_id_idx] + else: + curr_key = cols[self._query_id_idx] + if curr_key != qresult_key: + break + qresult_raw += line + + return qresult_raw + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_text.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_text.py new file mode 100644 index 0000000000000000000000000000000000000000..bd3bd5e1604a286b1d3602b627bd7a8ee014d36f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InfernalIO/infernal_text.py @@ -0,0 +1,542 @@ +# Copyright 2024 by Samuel Prince. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + + +"""Bio.SearchIO parser for Infernal plain text output format.""" + +import operator +import re + +from Bio.SearchIO._index import SearchIndexer +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult +from Bio.SearchIO._utils import read_forward + +from ._base import _BaseInfernalParser + +__all__ = ("InfernalTextParser", "InfernalTextIndexer") + +# precompile regex patterns for faster processing +# program name +_RE_PROGRAM = re.compile(r"^# .*?(\w?cm\w+) :: .*$") +# version string +_RE_VERSION = re.compile(r"# INFERNAL+ ([\w+\.]{2,}) .*$") +# option string +_RE_OPT = re.compile(r"^# (.+):\s+(.+)$") +# numbers only +_RE_NUMERIC = re.compile(r"\d+") +_RE_NOT_NUMERIC = re.compile(r"\D") +# letters only +_RE_LETTERS = re.compile(r"[^A-Za-z]") +# missing segments in the alignment block +_RE_SPLIT_ALN = re.compile(r"(\*\[[ 0-9]+\]\*)+") + +# divider for Infernal plain text output, these divider are +# always taken from the beginning of the line to be usable in +# self.line.startswith() method +# header options +_DIV_HEADER_OPT = "# - - -" +# query +_DIV_QUERY_END = "//" +_DIV_QUERY_START = "Query:" +# hits +_DIV_HITS_END_CM = "Internal CM pipeline statistics summary:" +_DIV_HITS_END_HMM = "Internal HMM-only pipeline statistics summary:" +_DIV_HIT_SCORE_TABLE = "Hit scores:" +_DIV_HIT_ALIGNMENT = "Hit alignments:" +_DIV_NO_HIT = " [No hits detected that satisfy reporting thresholds]" +_DIV_TABLE_START = " ---- --------- ------" +_DIV_INC_THRESHOLD = " ------ inclusion threshold ------" +# hit alignment +_DIV_ALIGNMENT_START = ">> " + + +class InfernalTextParser(_BaseInfernalParser): + """Parser for the Infernal text output.""" + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + self.line = read_forward(self.handle) + self._meta = self._parse_header() + + def __iter__(self): + """Iterate over query results.""" + yield from self._parse_qresult() + + def _read_until(self, bool_func): + """Read the file handle until the given function returns True (PRIVATE).""" + while True: + if not self.line or bool_func(self.line): + return + self.line = read_forward(self.handle) + + def _parse_header(self): + """Parse Infernal header (PRIVATE).""" + meta = {} + # set the default value for the presence of alignment + # as this information is important for the hit section parsing + meta["show alignments in output"] = "yes" + # bool flag for storing state ~ whether we are parsing the option + # lines or not + has_opts = False + while True: + # no pound sign means we've left the preamble + if not self.line.startswith("#"): + break + # dashes could either mean we are entering or leaving the options + # section, so it's a switch for the has_opts flag + elif self.line.startswith(_DIV_HEADER_OPT): + if not has_opts: + # if flag is false, that means we're entering opts + # so switch the flag accordingly + has_opts = True + else: + # if flag is true, that means we've reached the end of opts + # so we can break out of the function + break + elif not has_opts: + # try parsing program + regx = re.search(_RE_PROGRAM, self.line) + if regx: + meta["program"] = regx.group(1) + # try parsing version + regx = re.search(_RE_VERSION, self.line) + if regx: + meta["version"] = regx.group(1) + elif has_opts: + regx = re.search(_RE_OPT, self.line) + # if target in regx.group(1), then we store the key as target + if "target" in regx.group(1): + meta["target"] = regx.group(2).strip() + else: + meta[regx.group(1)] = regx.group(2) + + self.line = read_forward(self.handle) + + return meta + + def _parse_qresult(self): + """Parse a Infernal query block (PRIVATE).""" + self._read_until(lambda line: line.startswith(_DIV_QUERY_START)) + + while self.line: + # create qresult for query id + if self.line.startswith(_DIV_QUERY_START): + qid = self.line.strip().split()[1] + qlen = int(re.sub(_RE_NOT_NUMERIC, "", self.line.strip().split()[-1])) + + # store qresult attributes + qresult_attrs = { + "id": qid, + "seq_len": qlen, + "program": self._meta.get("program"), + "version": self._meta.get("version"), + "target": self._meta.get("target"), + } + else: + self.line = read_forward(self.handle) + + # get description and accession, if they exist + qdesc = "" # placeholder + while not self.line.startswith(_DIV_HIT_SCORE_TABLE): + self.line = read_forward(self.handle) + + if self.line.startswith("Accession:"): + acc = self.line.strip().split(" ", 1)[1] + qresult_attrs["accession"] = acc.strip() + elif self.line.startswith("Description:"): + qdesc = self.line.strip().split(" ", 1)[1].strip() + qresult_attrs["description"] = qdesc + + # parse the query hits + # initializing hit_list directly to handle empty hits + hit_list = [] + while self.line and not self.line.startswith(_DIV_QUERY_END): + hit_list = self._parse_hit(qid, qdesc) + # read through the statistics summary + if self.line.startswith(_DIV_HITS_END_CM) or self.line.startswith( + _DIV_HITS_END_HMM + ): + while self.line and not self.line.startswith(_DIV_QUERY_END): + self.line = read_forward(self.handle) + # create qresult, set its attributes and yield + qresult = QueryResult(id=qid, hits=hit_list) + for attr, value in qresult_attrs.items(): + setattr(qresult, attr, value) + yield qresult + self.line = read_forward(self.handle) + + # Infernal outputs '[ok]' at the end of all results file, + # which means we can break the main loop when we see the line + if "[ok]" in self.line: + break + + def _parse_hit(self, qid, qdesc): + """Parse an Infernal hit (PRIVATE).""" + # state values, determines what to do for each block + hit_end = False + in_score_table = False + parsing_hits = False + prev_line = None + # hits are not guaranteed to be in order, and duplicate hit + # IDs will raise a ValueError. to avoid this, hits are stored in + # a temporary dictionary and the hit list required to create + # the QueryResult is generated at the end of the query block + hit_dict = {} + + # set the divider based on the output type (with or without alignment) + if self._meta["show alignments in output"] == "no": + div_hit_start = _DIV_HIT_SCORE_TABLE + else: + div_hit_start = _DIV_ALIGNMENT_START + + while True: + if not self.line: + raise ValueError("Unexpected end of file") + # if there are no hits, forward-read to the end of the query + elif self.line.startswith(_DIV_NO_HIT): + while True: + self.line = read_forward(self.handle) + if self.line.startswith(_DIV_HITS_END_CM) or self.line.startswith( + _DIV_HITS_END_HMM + ): + hit_end = True + return [] + # entering hit alignment block + elif self.line.startswith(div_hit_start): + # for --noali output, move to the beginning of the hit score table + if self._meta["show alignments in output"] == "no": + assert not in_score_table + self._read_until(lambda line: line.startswith(_DIV_TABLE_START)) + self.line = read_forward(self.handle) + parsing_hits = in_score_table = True + else: + self._parse_hit_from_alignment(qid, hit_dict) + parsing_hits = True + # we've reached the end of the hit section + elif self.line.startswith(_DIV_HITS_END_CM) or self.line.startswith( + _DIV_HITS_END_HMM + ): + hit_end = True + parsing_hits = False + # Read through the scores table. For regular output this information + # is not needed, so we can skip it. For --noali output, this table + # contains the HSP information + else: + # for --noali output, keep the line + if in_score_table: + if self.line.strip(): + prev_line = self.line + else: + parsing_hits = in_score_table = False + + # read one line at the time + self.line = self.handle.readline() + + # for --noali output, parse the scores table row + if in_score_table and prev_line is not None: + if not prev_line.startswith(_DIV_INC_THRESHOLD): + self._parse_scores_table_row(prev_line, qid, hit_dict) + + # we've reached the end of the query block hits + # creating the Hit objects for this query + if hit_end: + return self._hit_to_list(hit_dict) + + def _parse_hit_from_alignment(self, qid, hit_dict): + """Parse an Infernal hit alignment (PRIVATE).""" + hid, hdesc = self.line[len(_DIV_ALIGNMENT_START) :].split(" ", 1) + hdesc = hdesc.strip() + + # read through the hit table header and move one more line + self._read_until(lambda line: line.startswith(_DIV_TABLE_START)) + self.line = read_forward(self.handle) + + # parse the hit table + row = [x for x in self.line.strip().split() if x] + assert len(row) == 16 + + # create hit and append to hit container + hit_attrs = {"id": hid, "query_id": qid, "description": hdesc} + hsp_attrs = { + "evalue": float(row[2]), + "bitscore": float(row[3]), + "bias": float(row[4]), + "model": row[5], + "truncated": row[14], + "gc": float(row[15]), + "avg_acc": float(row[13]), + "query_endtype": row[8], + "hit_endtype": row[12], + "is_included": True if row[1] == "!" else False, + } + query_start = int(row[6]) + query_end = int(row[7]) + hit_start = int(row[9]) if row[11] == "+" else int(row[10]) + hit_end = int(row[10]) if row[11] == "+" else int(row[9]) + hit_strand = 0 if row[11] == "+" else -1 + + # move to the HSP alignment block + self.line = read_forward(self.handle) + + # create the hsp + frag_list = self._parse_aln_block( + hit_attrs["id"], + hit_attrs["query_id"], + hsp_attrs["model"], + query_start, + query_end, + hit_start, + hit_end, + hit_strand, + ) + hsp = HSP(frag_list) + for attr, value in hsp_attrs.items(): + setattr(hsp, attr, value) + + # add the hit to the container + self._add_hit_to_dict(hit_attrs, hsp, hit_dict) + + def _parse_scores_table_row(self, row, qid, hit_dict): + """Parse an Infernal hit scores table (when used with --noali) (PRIVATE).""" + + # parse the columns into a list + row = [x for x in row.strip().split(" ") if x] + # join the description words if it's >1 word + if len(row) > 12: + row[12] = " ".join(row[12:]) + # if there's no description, set it to an empty string + elif len(row) < 12: + row.append("") + assert len(row) == 12 + + # parse the attributes + hit_attrs = {"id": row[5], "query_id": qid, "description": row[12]} + hsp_attrs = { + "evalue": float(row[2]), + "bitscore": float(row[3]), + "bias": float(row[4]), + "model": row[9], + "truncated": row[10], + "gc": float(row[11]), + "is_included": True if row[1] == "!" else False, + } + hsp_frag_attrs = { + "hit_start": int(row[6]) if row[8] == "+" else int(row[7]), + "hit_end": int(row[7]) if row[8] == "+" else int(row[6]), + "hit_strand": 0 if row[8] == "+" else -1, + } + + # create the hsp fragment and set it's attributes + hsp_frag = HSPFragment(row[5], qid) + for attr, value in hsp_frag_attrs.items(): + setattr(hsp_frag, attr, value) + + # create the hsp and set it's attributes + hsp = HSP([hsp_frag]) + for attr, value in hsp_attrs.items(): + setattr(hsp, attr, value) + + # add the hit to the container + self._add_hit_to_dict(hit_attrs, hsp, hit_dict) + + def _parse_aln_block( + self, hid, qid, model, query_start, query_end, hit_start, hit_end, hit_strand + ): + """Parse a Infernal HSP alignment block (PRIVATE).""" + frag_list = [] + model_seq = "" + hit_seq = "" + if model == "cm": + annot = {"NC": "", "CS": "", "similarity": "", "PP": ""} + else: + annot = {"CS": "", "similarity": "", "PP": ""} + while True: + # we've reached the end of the alignment section + if ( + self.line.startswith(_DIV_ALIGNMENT_START) + or self.line.startswith(_DIV_HITS_END_CM) + or self.line.startswith(_DIV_HITS_END_HMM) + ): + # Process local end in infernal hit alignment. Local end are + # large insertion or deletion indicated by *[NN]* where N is + # the number of model positions are deleted or the number of + # residues are inserted in the sequence. We split the + # alignment block in HSPs on these local ends. + + # get local ends string (*[NN]*) indexes in the model sequence + # there can be more than one local ends back-to-back + local_aln_idx = [ + (0, 0) + ] # there is always at least one local alignment starting at 0 + local_aln_idx += [ + (m.start(0), m.end(0)) + for m in re.finditer(_RE_SPLIT_ALN, model_seq) + ] + + prev_hit_start = hit_start if hit_strand == 0 else hit_end + prev_model_start = query_start + hsps = [] + + for i in range(len(local_aln_idx)): + local_start = local_aln_idx[i][1] + local_end = ( + local_aln_idx[i + 1][0] if i + 1 < len(local_aln_idx) else None + ) + + # hsp hit position. forward strand moves up, reverse strand moves down + op = operator.add if hit_strand == 0 else operator.sub + cur_hit_seq = hit_seq[local_start:local_end] + cur_hit_gap_size = self._local_aln_gap_size( + local_aln_idx[i], hit_seq + ) + cur_hit_start = op(prev_hit_start, cur_hit_gap_size) + cur_hit_end = op( + cur_hit_start, len(re.sub(_RE_LETTERS, "", cur_hit_seq)) + ) + # adjust start and end elements positon + if hit_strand == 0 and i == 0: + cur_hit_end -= 1 + if hit_strand == -1 and i == 0: + cur_hit_end += 1 + prev_hit_start = cur_hit_end + # hsp model position + cur_model_seq = model_seq[local_start:local_end].replace(".", "-") + cur_model_gap_size = self._local_aln_gap_size( + local_aln_idx[i], model_seq + ) + cur_model_start = prev_model_start + cur_model_gap_size + cur_model_end = cur_model_start + len( + re.sub(_RE_LETTERS, "", cur_model_seq) + ) + if i == 0: + cur_model_end -= 1 + prev_model_start = cur_model_end + # annotations + cur_annot = {k: v[local_start:local_end] for k, v in annot.items()} + + # create the hsp fragment and add to container + frag = HSPFragment(hid, qid) + frag.query = cur_model_seq + frag.hit = cur_hit_seq + frag.query_start = cur_model_start + frag.query_end = cur_model_end + frag.hit_start = cur_hit_start if hit_strand == 0 else cur_hit_end + frag.hit_end = cur_hit_end if hit_strand == 0 else cur_hit_start + frag.hit_strand = hit_strand + frag.aln_annotation = cur_annot + + frag_list.append(frag) + + return frag_list + + # parse the alignment blocks in the hsp + # each block have 4 (hmmonly) or 5 (cm) lines followed by an empty line + block_size = 6 if model == "cm" else 5 + offset = 1 if model == "cm" else 0 # offset for the annotation line indexes + lines = [None] * block_size + for i in range(block_size): + lines[i] = self.line + self.line = read_forward(self.handle) + + # get the position of the alignment in the string using the PP line + blklen = len(lines[4 + offset].strip().split()[0]) + blkstart = len(lines[4 + offset]) - blklen - 4 + blkend = len(lines[4 + offset]) - 4 + model_seq += lines[1 + offset][blkstart:blkend] + hit_seq += lines[3 + offset][blkstart:blkend] + # NC line is specific to cm model searches + if model == "cm": + annot["NC"] += lines[0][blkstart:blkend] + annot["CS"] += lines[0 + offset][blkstart:blkend] + annot["similarity"] += lines[2 + offset][blkstart:blkend] + annot["PP"] += lines[4 + offset][blkstart:blkend] + + def _local_aln_gap_size(self, cur_aln_idx, seq): + """Calculate the gap size between the local alignments (PRIVATE).""" + gap_len = 0 + if cur_aln_idx[1] > 0: + gap_len = sum( + [ + int(n) + for n in re.findall( + _RE_NUMERIC, seq[cur_aln_idx[0] : cur_aln_idx[1]] + ) + ] + ) + assert gap_len > 0 + return gap_len + + +class InfernalTextIndexer(SearchIndexer): + """Indexer class for Infernal plain text output.""" + + _parser = InfernalTextParser + + def __init__(self, *args, **kwargs): + """Initialize the class.""" + super().__init__(*args, **kwargs) + self._preamble = b"" + + def __iter__(self): + """Iterate over InfernalTextIndexer; yields query results' key, offsets, 0.""" + handle = self._handle + handle.seek(0) + start_offset = handle.tell() + + while True: + line = read_forward(handle) + end_offset = handle.tell() + + if line.startswith(_DIV_QUERY_START.encode()): + qresult_key = line.strip().split()[1] + # qresult start offset is the offset of this line + # (starts with the start mark) + start_offset = end_offset - len(line) + elif line.startswith(_DIV_QUERY_END.encode()): + yield qresult_key.decode(), start_offset, 0 + start_offset = end_offset + elif not line: + break + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + handle = self._handle + qresult_raw = b"" + + # read header + if not self._preamble: + handle.seek(0) + while True: + line = handle.readline() + if line.startswith(_DIV_QUERY_START.encode()): + break + self._preamble += line + + qresult_raw += self._preamble + + # read the qresult raw string + handle.seek(offset) + while True: + # preserve whitespace, don't use read_forward + line = handle.readline() + qresult_raw += line + + # break when we've reached qresult end + if line.startswith(_DIV_QUERY_END.encode()) or not line: + break + + return qresult_raw + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/._interproscan_xml.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/._interproscan_xml.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/._interproscan_xml.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..620a519d66ebfffdac151641f756c2c145665f72 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/__init__.py @@ -0,0 +1,96 @@ +# Copyright 2018 by Adhemar Zerlotini. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO support for InterProScan output formats. + +This module adds support for parsing InterProScan XML output. +The InterProScan is available as a command line program or on +EMBL-EBI's web page. +Bio.SearchIO.InterproscanIO was tested on the following version: + +- versions: 5.26-65.0 (interproscan-model-2.1.xsd) + +More information about InterProScan are available through these links: +- Publication: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3998142/ +- Web interface: https://www.ebi.ac.uk/interpro/search/sequence-search +- Documentation: https://github.com/ebi-pf-team/interproscan/wiki + + +Supported format +================ + +Bio.SearchIO.InterproscanIO supports the following format: + +- XML - 'interproscan-xml' - parsing + + +interproscan-xml +================ + +The interproscan-xml parser follows the InterProScan XML described here: +https://github.com/ebi-pf-team/interproscan/wiki/OutputFormats + ++--------------+--------------------+------------------------------------------+ +| Object | Attribute | XML Element | ++==============+====================+==========================================+ +| QueryResult | target | ``InterPro`` | +| +--------------------+------------------------------------------+ +| | program | ``InterProScan`` | +| +--------------------+------------------------------------------+ +| | version | ``protein-matches.interproscan-version`` | ++--------------+--------------------+------------------------------------------+ +| Hit | accession | ``signature.name`` | +| +--------------------+------------------------------------------+ +| | id | ``signature.ac`` | +| +--------------------+------------------------------------------+ +| | description | ``signature.desc`` | +| +--------------------+------------------------------------------+ +| | dbxrefs | ``IPR:entry.ac`` | +| | | ``go-xref.id`` | +| | | ``pathway-xref.db:pathway-xref.id`` | +| +--------------------+------------------------------------------+ +| | attributes | | +| | ['Target'] | ``*-match`` / ``*-location`` | +| | ['Target version'] | ``signature-library-release.library`` | +| | ['Hit type'] | ``signature-library-release.version`` | ++--------------+--------------------+------------------------------------------+ +| HSP | bitscore | ``*-location.score`` | +| +--------------------+------------------------------------------+ +| | evalue | ``*-location.evalue`` | ++--------------+--------------------+------------------------------------------+ +| HSPFragment | query_start | ``*-location.start`` | +| (also via +--------------------+------------------------------------------+ +| HSP) | query_end | ``*-location.end`` | +| +--------------------+------------------------------------------+ +| | hit_start | ``*-location.hmm-start`` | +| +--------------------+------------------------------------------+ +| | hit_end | ``*-location.hmm-end`` | +| +--------------------+------------------------------------------+ +| | query | ``sequence`` | ++--------------+--------------------+------------------------------------------+ + +InterProScan XML files may contain a match with multiple locations or multiple +matches to the same protein with a single location. In both cases, the match +is uniquely stored as a HIT object and the locations as HSP objects. + +``HSP.*start == *start - 1`` (Since every start position is 0-based in Biopython) + +``HSP.aln_span == query-end - query-start`` + +The types of matches or locations (eg. hmmer3-match, hmmer3-location, +coils-match, panther-location) are stored in hit.attributes['Hit type']. +For instance, for every 'phobious-match', there will be a 'phobious-location'. +Therefore, Hit.type will store the string excluding '-match' or '-location' +('phobious', in this example). +""" + +from .interproscan_xml import InterproscanXmlParser + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/interproscan_xml.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/interproscan_xml.py new file mode 100644 index 0000000000000000000000000000000000000000..a0a317e1958151807af9d89d3ce75d925444216e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/InterproscanIO/interproscan_xml.py @@ -0,0 +1,196 @@ +# Copyright 2018 by Adhemar Zerlotini. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Bio.SearchIO parser for InterProScan XML output formats.""" +# for more info: https://github.com/ebi-pf-team/interproscan/wiki/OutputFormats + +import re +from xml.etree import ElementTree + +from Bio.SearchIO._model import Hit +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult + +# element - hit attribute name mapping +_ELEM_HIT = { + "name": ("accession", str), + "ac": ("id", str), + "desc": ("description", str), +} +# element - hsp attribute name mapping +_ELEM_HSP = {"score": ("bitscore", float), "evalue": ("evalue", float)} +# element - fragment attribute name mapping +_ELEM_FRAG = { + "start": ("query_start", int), + "end": ("query_end", int), + "hmm-start": ("hit_start", int), + "hmm-end": ("hit_end", int), +} + + +class InterproscanXmlParser: + """Parser for the InterProScan XML format.""" + + def __init__(self, handle): + """Initialize the class.""" + self.xml_iter = iter(ElementTree.iterparse(handle, events=("start", "end"))) + self._meta = self._parse_header() + + def __iter__(self): + """Iterate qresults.""" + yield from self._parse_qresult() + + def _parse_header(self): + """Parse the header for the InterProScan version (PRIVATE).""" + event, elem = next(self.xml_iter) + meta = {} + meta["target"] = "InterPro" + meta["program"] = "InterProScan" + meta["version"] = elem.attrib["interproscan-version"] + # store the namespace value + self.NS = re.sub("protein-matches", "", elem.tag) + return meta + + def _parse_qresult(self): + """Parse query results (PRIVATE).""" + for event, elem in self.xml_iter: + if event == "end" and elem.tag == self.NS + "protein": + # store the query sequence + seq = elem.find(self.NS + "sequence") + query_seq = seq.text + + # store the query id and description + xref = elem.find(self.NS + "xref") + query_id = xref.attrib["id"] + query_desc = xref.attrib["name"] + + # parse each hit + hit_list = [] + for hit_new in self._parse_hit( + elem.find(self.NS + "matches"), query_id, query_seq + ): + # interproscan results contain duplicate hits rather than + # a single hit with multiple hsps. In this case the hsps + # of a duplicate hit will be appended to the already + # existing hit + for hit in hit_list: + if hit.id == hit_new.id: + for hsp in hit_new.hsps: + hit.hsps.append(hsp) + break + else: + hit_list.append(hit_new) + + # create qresult and assign attributes + qresult = QueryResult(hit_list, query_id) + setattr(qresult, "description", query_desc) + for key, value in self._meta.items(): + setattr(qresult, key, value) + yield qresult + + def _parse_hit(self, root_hit_elem, query_id, query_seq=None): + """Parse hit (PRIVATE).""" + # feed the loop below an empty list so iteration still works + if root_hit_elem is None: + root_hit_elem = [] + + for hit_elem in root_hit_elem: + # store the match/location type + hit_type = re.sub(r"%s(\w+)-match" % self.NS, r"\1", hit_elem.find(".").tag) + # store the hit id + signature = hit_elem.find(self.NS + "signature") + hit_id = signature.attrib["ac"] + + # store xrefs and alt_descs + xrefs = self._parse_xrefs(signature.find(self.NS + "entry")) + + # parse each hsp + hsps = list( + self._parse_hsp( + hit_elem.find(self.NS + "locations"), query_id, hit_id, query_seq + ) + ) + + # create hit and assign attributes + hit = Hit(hsps, hit_id) + setattr(hit, "dbxrefs", xrefs) + for key, (attr, caster) in _ELEM_HIT.items(): + value = signature.attrib.get(key) + if value is not None: + setattr(hit, attr, caster(value)) + # format specific attributes + hit.attributes["Hit type"] = hit_type + signature_lib = signature.find(self.NS + "signature-library-release") + hit.attributes["Target"] = str(signature_lib.attrib.get("library")) + hit.attributes["Target version"] = str(signature_lib.attrib.get("version")) + + yield hit + + def _parse_hsp(self, root_hsp_elem, query_id, hit_id, query_seq=None): + """Parse hsp (PRIVATE).""" + # feed the loop below an empty list so iteration still works + if root_hsp_elem is None: + root_hsp_elem = [] + + for hsp_elem in root_hsp_elem: + # create frag and assign attributes + frag = HSPFragment(hit_id, query_id) + setattr(frag, "molecule_type", "protein") + if query_seq is not None: + setattr(frag, "query", query_seq) + for key, (attr, caster) in _ELEM_FRAG.items(): + value = hsp_elem.attrib.get(key) + if value is not None: + # start should be 0-based + if attr.endswith("start"): + value = caster(value) - 1 + # store query start and end to calculate aln_span + if attr == "query_start": + start = int(value) + if attr == "query_end": + end = int(value) + setattr(frag, attr, caster(value)) + # calculate aln_span and store + setattr(frag, "aln_span", end - start) + + # create hsp and assign attributes + hsp = HSP([frag]) + setattr(hsp, "query_id", query_id) + setattr(hsp, "hit_id", hit_id) + for key, (attr, caster) in _ELEM_HSP.items(): + value = hsp_elem.attrib.get(key) + if value is not None: + setattr(hsp, attr, caster(value)) + yield hsp + + def _parse_xrefs(self, root_entry_elem): + """Parse xrefs (PRIVATE).""" + xrefs = [] + # store entry id and description + if root_entry_elem is not None: + xrefs.append("IPR:" + root_entry_elem.attrib["ac"]) + + # store go-xrefs and pathway-refs id and description + if root_entry_elem is not None: + xref_elems = [] + xref_elems = xref_elems + root_entry_elem.findall(self.NS + "go-xref") + xref_elems = xref_elems + root_entry_elem.findall(self.NS + "pathway-xref") + + for entry in xref_elems: + xref = entry.attrib["id"] + if ":" not in xref: + xref = entry.attrib["db"] + ":" + xref + xrefs.append(xref) + return xrefs + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2187023e41d8111ff9f0dd7e887f72156334243b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/__init__.py @@ -0,0 +1,684 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Biopython interface for sequence search program outputs. + +The SearchIO submodule provides parsers, indexers, and writers for outputs from +various sequence search programs. It provides an API similar to SeqIO and +AlignIO, with the following main functions: ``parse``, ``read``, ``to_dict``, +``index``, ``index_db``, ``write``, and ``convert``. + +SearchIO parses a search output file's contents into a hierarchy of four nested +objects: QueryResult, Hit, HSP, and HSPFragment. Each of them models a part of +the search output file: + + - QueryResult represents a search query. This is the main object returned + by the input functions and it contains all other objects. + - Hit represents a database hit, + - HSP represents high-scoring alignment region(s) in the hit, + - HSPFragment represents a contiguous alignment within the HSP + +In addition to the four objects above, SearchIO is also tightly integrated with +the SeqRecord objects (see SeqIO) and MultipleSeqAlignment objects (see +AlignIO). SeqRecord objects are used to store the actual matching hit and query +sequences, while MultipleSeqAlignment objects store the alignment between them. + +A detailed description of these objects' features and their example usages are +available in their respective documentations. + + +Input +===== +The main function for parsing search output files is Bio.SearchIO.parse(...). +This function parses a given search output file and returns a generator object +that yields one QueryResult object per iteration. + +``parse`` takes two arguments: 1) a file handle or a filename of the input file +(the search output file) and 2) the format name. + + >>> from Bio import SearchIO + >>> for qresult in SearchIO.parse('Blast/mirna.xml', 'blast-xml'): + ... print("%s %s" % (qresult.id, qresult.description)) + ... + 33211 mir_1 + 33212 mir_2 + 33213 mir_3 + +SearchIO also provides the Bio.SearchIO.read(...) function, which is intended +for use on search output files containing only one query. ``read`` returns one +QueryResult object and will raise an exception if the source file contains more +than one query: + + >>> qresult = SearchIO.read('Blast/xml_2226_blastp_004.xml', 'blast-xml') + >>> print("%s %s" % (qresult.id, qresult.description)) + ... + gi|11464971:4-101 pleckstrin [Mus musculus] + + >>> SearchIO.read('Blast/mirna.xml', 'blast-xml') + Traceback (most recent call last): + ... + ValueError: ... + +For accessing search results of large output files, you may use the indexing +functions Bio.SearchIO.index(...) or Bio.SearchIO.index_db(...). They have a +similar interface to their counterparts in SeqIO and AlignIO, with the addition +of optional, format-specific keyword arguments. + + +Output +====== +SearchIO has write support for several formats, accessible from the +Bio.SearchIO.write(...) function. This function returns a tuple of four +numbers: the number of QueryResult, Hit, HSP, and HSPFragment written:: + + qresults = SearchIO.parse('Blast/mirna.xml', 'blast-xml') + SearchIO.write(qresults, 'results.tab', 'blast-tab') + (3, 239, 277, 277) + +Note that different writers may require different attribute values of the +SearchIO objects. This limits the scope of writable search results to search +results possessing the required attributes. + +For example, the writer for HMMER domain table output requires +the conditional e-value attribute from each HSP object, among others. If you +try to write to the HMMER domain table format and your HSPs do not have this +attribute, an exception will be raised. + + +Conversion +========== +SearchIO provides a shortcut function Bio.SearchIO.convert(...) to convert a +given file into another format. Under the hood, ``convert`` simply parses a given +output file and writes it to another using the ``parse`` and ``write`` functions. + +Note that the same restrictions found in Bio.SearchIO.write(...) apply to the +convert function as well. + + +Conventions +=========== +The main goal of creating SearchIO is to have a common, easy to use interface +across different search output files. As such, we have also created some +conventions / standards for SearchIO that extend beyond the common object model. +These conventions apply to all files parsed by SearchIO, regardless of their +individual formats. + +Python-style sequence coordinates +--------------------------------- + +When storing sequence coordinates (start and end values), SearchIO uses +the Python-style slice convention: zero-based and half-open intervals. For +example, if in a BLAST XML output file the start and end coordinates of an +HSP are 10 and 28, they would become 9 and 28 in SearchIO. The start +coordinate becomes 9 because Python indices start from zero, while the end +coordinate remains 28 as Python slices omit the last item in an interval. + +Beside giving you the benefits of standardization, this convention also +makes the coordinates usable for slicing sequences. For example, given a +full query sequence and the start and end coordinates of an HSP, one can +use the coordinates to extract part of the query sequence that results in +the database hit. + +When these objects are written to an output file using +SearchIO.write(...), the coordinate values are restored to their +respective format's convention. Using the example above, if the HSP would +be written to an XML file, the start and end coordinates would become 10 +and 28 again. + +Sequence coordinate order +------------------------- + +Some search output formats reverse the start and end coordinate sequences +according to the sequence's strand. + +In SearchIO, start coordinates are always smaller than the end +coordinates, regardless of their originating strand. This ensures +consistency when using the coordinates to slice full sequences. + +Note that this coordinate order convention is only enforced in the +HSPFragment level. If an HSP object has several HSPFragment objects, each +individual fragment will conform to this convention. But the order of the +fragments within the HSP object follows what the search output file uses. + +Similar to the coordinate style convention, the start and end coordinates' +order are restored to their respective formats when the objects are +written using Bio.SearchIO.write(...). + +Frames and strand values +------------------------ + +SearchIO only allows -1, 0, 1 and None as strand values. For frames, the +only allowed values are integers from -3 to 3 (inclusive) and None. Both +of these are standard Biopython conventions. + + +Supported Formats +================= +Below is a list of search program output formats supported by SearchIO. + +Support for parsing, indexing, and writing: + + - blast-tab - BLAST+ tabular output. Both variants without comments + (-m 6 flag) and with comments (-m 7 flag) are supported. + - blast-xml - BLAST+ XML output. + - blat-psl - The default output of BLAT (PSL format). Variants with or + without header are both supported. PSLX (PSL + sequences) + is also supported. + - hmmer3-tab - HMMER3 table output. + - hmmer3-domtab - HMMER3 domain table output. When using this format, the + program name has to be specified. For example, for parsing + hmmscan output, the name would be 'hmmscan-domtab'. + +Support for parsing and indexing: + + - exonerate-text - Exonerate plain text output. + - exonerate-vulgar - Exonerate vulgar line. + - exonerate-cigar - Exonerate cigar line. + - fasta-m10 - Bill Pearson's FASTA -m 10 output. + - hmmer3-text - HMMER3 regular text output format. Supported HMMER3 + subprograms are hmmscan, hmmsearch, and phmmer. + - hmmer2-text - HMMER2 regular text output format. Supported HMMER2 + subprograms are hmmpfam, hmmsearch. + - infernal-tab - Infernal tabular output. + - infernal-text - Infernal regular text output. Supported Infernal + subprograms are cmsearch and cmscan. + +Support for parsing: + + - hhsuite2-text - HHSUITE plain text output. + +Each of these formats have different keyword arguments available for use with +the main SearchIO functions. More details and examples are available in each +of the format's documentation. + +""" + +from Bio.File import as_handle +from Bio.SearchIO._model import Hit +from Bio.SearchIO._model import HSP +from Bio.SearchIO._model import HSPFragment +from Bio.SearchIO._model import QueryResult +from Bio.SearchIO._utils import get_processor + +__all__ = ("read", "parse", "to_dict", "index", "index_db", "write", "convert") + + +# dictionary of supported formats for parse() and read() +_ITERATOR_MAP = { + "blast-tab": ("BlastIO", "BlastTabParser"), + "blast-xml": ("BlastIO", "BlastXmlParser"), + "blat-psl": ("BlatIO", "BlatPslParser"), + "exonerate-cigar": ("ExonerateIO", "ExonerateCigarParser"), + "exonerate-text": ("ExonerateIO", "ExonerateTextParser"), + "exonerate-vulgar": ("ExonerateIO", "ExonerateVulgarParser"), + "fasta-m10": ("FastaIO", "FastaM10Parser"), + "hhsuite2-text": ("HHsuiteIO", "Hhsuite2TextParser"), + "hhsuite3-text": ("HHsuiteIO", "Hhsuite2TextParser"), + "hmmer2-text": ("HmmerIO", "Hmmer2TextParser"), + "hmmer3-text": ("HmmerIO", "Hmmer3TextParser"), + "hmmer3-tab": ("HmmerIO", "Hmmer3TabParser"), + # for hmmer3-domtab, the specific program is part of the format name + # as we need it distinguish hit / target coordinates + "hmmscan3-domtab": ("HmmerIO", "Hmmer3DomtabHmmhitParser"), + "hmmsearch3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryParser"), + "infernal-tab": ("InfernalIO", "InfernalTabParser"), + "infernal-text": ("InfernalIO", "InfernalTextParser"), + "interproscan-xml": ("InterproscanIO", "InterproscanXmlParser"), + "phmmer3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryParser"), +} + +# dictionary of supported formats for index() +_INDEXER_MAP = { + "blast-tab": ("BlastIO", "BlastTabIndexer"), + "blast-xml": ("BlastIO", "BlastXmlIndexer"), + "blat-psl": ("BlatIO", "BlatPslIndexer"), + "exonerate-cigar": ("ExonerateIO", "ExonerateCigarIndexer"), + "exonerate-text": ("ExonerateIO", "ExonerateTextIndexer"), + "exonerate-vulgar": ("ExonerateIO", "ExonerateVulgarIndexer"), + "fasta-m10": ("FastaIO", "FastaM10Indexer"), + "hmmer2-text": ("HmmerIO", "Hmmer2TextIndexer"), + "hmmer3-text": ("HmmerIO", "Hmmer3TextIndexer"), + "hmmer3-tab": ("HmmerIO", "Hmmer3TabIndexer"), + "hmmscan3-domtab": ("HmmerIO", "Hmmer3DomtabHmmhitIndexer"), + "hmmsearch3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryIndexer"), + "infernal-tab": ("InfernalIO", "InfernalTabIndexer"), + "infernal-text": ("InfernalIO", "InfernalTextIndexer"), + "phmmer3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryIndexer"), +} + +# dictionary of supported formats for write() +_WRITER_MAP = { + "blast-tab": ("BlastIO", "BlastTabWriter"), + "blast-xml": ("BlastIO", "BlastXmlWriter"), + "blat-psl": ("BlatIO", "BlatPslWriter"), + "hmmer3-tab": ("HmmerIO", "Hmmer3TabWriter"), + "hmmscan3-domtab": ("HmmerIO", "Hmmer3DomtabHmmhitWriter"), + "hmmsearch3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryWriter"), + "phmmer3-domtab": ("HmmerIO", "Hmmer3DomtabHmmqueryWriter"), +} + + +def parse(handle, format=None, **kwargs): + """Iterate over search tool output file as QueryResult objects. + + Arguments: + - handle - Handle to the file, or the filename as a string. + - format - Lower case string denoting one of the supported formats. + - kwargs - Format-specific keyword arguments. + + This function is used to iterate over each query in a given search output + file: + + >>> from Bio import SearchIO + >>> qresults = SearchIO.parse('Blast/mirna.xml', 'blast-xml') + >>> qresults + + >>> for qresult in qresults: + ... print("Search %s has %i hits" % (qresult.id, len(qresult))) + ... + Search 33211 has 100 hits + Search 33212 has 44 hits + Search 33213 has 95 hits + + Depending on the file format, ``parse`` may also accept additional keyword + argument(s) that modifies the behavior of the format parser. Here is a + simple example, where the keyword argument enables parsing of a commented + BLAST tabular output file: + + >>> from Bio import SearchIO + >>> for qresult in SearchIO.parse('Blast/mirna.tab', 'blast-tab', comments=True): + ... print("Search %s has %i hits" % (qresult.id, len(qresult))) + ... + Search 33211 has 100 hits + Search 33212 has 44 hits + Search 33213 has 95 hits + + """ + # get the iterator object and do error checking + iterator = get_processor(format, _ITERATOR_MAP) + + # HACK: force BLAST XML decoding to use utf-8 + handle_kwargs = {} + if format == "blast-xml": + handle_kwargs["encoding"] = "utf-8" + + # and start iterating + with as_handle(handle, **handle_kwargs) as source_file: + generator = iterator(source_file, **kwargs) + yield from generator + + +def read(handle, format=None, **kwargs): + """Turn a search output file containing one query into a single QueryResult. + + - handle - Handle to the file, or the filename as a string. + - format - Lower case string denoting one of the supported formats. + - kwargs - Format-specific keyword arguments. + + ``read`` is used for parsing search output files containing exactly one query: + + >>> from Bio import SearchIO + >>> qresult = SearchIO.read('Blast/xml_2226_blastp_004.xml', 'blast-xml') + >>> print("%s %s" % (qresult.id, qresult.description)) + ... + gi|11464971:4-101 pleckstrin [Mus musculus] + + If the given handle has no results, an exception will be raised: + + >>> from Bio import SearchIO + >>> qresult = SearchIO.read('Blast/tab_2226_tblastn_002.txt', 'blast-tab') + Traceback (most recent call last): + ... + ValueError: No query results found in handle + + Similarly, if the given handle has more than one result, an exception will + be raised: + + >>> from Bio import SearchIO + >>> qresult = SearchIO.read('Blast/tab_2226_tblastn_001.txt', 'blast-tab') + Traceback (most recent call last): + ... + ValueError: More than one query result found in handle + + Like ``parse``, ``read`` may also accept keyword argument(s) depending on the + search output file format. + + """ + query_results = parse(handle, format, **kwargs) + + try: + query_result = next(query_results) + except StopIteration: + raise ValueError("No query results found in handle") from None + try: + next(query_results) + raise ValueError("More than one query result found in handle") + except StopIteration: + pass + + return query_result + + +def to_dict(qresults, key_function=None): + """Turn a QueryResult iterator or list into a dictionary. + + - qresults - Iterable returning QueryResult objects. + - key_function - Optional callback function which when given a + QueryResult object should return a unique key for the + dictionary. Defaults to using .id of the result. + + This function enables access of QueryResult objects from a single search + output file using its identifier. + + >>> from Bio import SearchIO + >>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml') + >>> search_dict = SearchIO.to_dict(qresults) + >>> list(search_dict) + ['gi|195230749:301-1383', 'gi|325053704:108-1166', ..., 'gi|53729353:216-1313'] + >>> search_dict['gi|156630997:105-1160'] + QueryResult(id='gi|156630997:105-1160', 5 hits) + + By default, the dictionary key is the QueryResult's string ID. This may be + changed by supplying a callback function that returns the desired identifier. + Here is an example using a function that removes the 'gi|' part in the + beginning of the QueryResult ID. + + >>> from Bio import SearchIO + >>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml') + >>> key_func = lambda qresult: qresult.id.split('|')[1] + >>> search_dict = SearchIO.to_dict(qresults, key_func) + >>> list(search_dict) + ['195230749:301-1383', '325053704:108-1166', ..., '53729353:216-1313'] + >>> search_dict['156630997:105-1160'] + QueryResult(id='gi|156630997:105-1160', 5 hits) + + Note that the callback function does not change the QueryResult's ID value. + It only changes the key value used to retrieve the associated QueryResult. + + As this function loads all QueryResult objects into memory, it may be + unsuitable for dealing with files containing many queries. In that case, it + is recommended that you use either ``index`` or ``index_db``. + + Since Python 3.7, the default dict class maintains key order, meaning + this dictionary will reflect the order of records given to it. For + CPython and PyPy, this was already implemented for Python 3.6, so + effectively you can always assume the record order is preserved. + """ + + def _default_key_function(rec): + return rec.id + + if key_function is None: + key_function = _default_key_function + + qdict = {} + for qresult in qresults: + key = key_function(qresult) + if key in qdict: + raise ValueError("Duplicate key %r" % key) + qdict[key] = qresult + return qdict + + +def index(filename, format=None, key_function=None, **kwargs): + """Indexes a search output file and returns a dictionary-like object. + + - filename - string giving name of file to be indexed + - format - Lower case string denoting one of the supported formats. + - key_function - Optional callback function which when given a + QueryResult should return a unique key for the dictionary. + - kwargs - Format-specific keyword arguments. + + Index returns a pseudo-dictionary object with QueryResult objects as its + values and a string identifier as its keys. The function is mainly useful + for dealing with large search output files, as it enables access to any + given QueryResult object much faster than using parse or read. + + Index works by storing in-memory the start locations of all queries in a + file. When a user requests access to the query, this function will jump + to its start position, parse the whole query, and return it as a + QueryResult object: + + >>> from Bio import SearchIO + >>> search_idx = SearchIO.index('Blast/wnts.xml', 'blast-xml') + >>> search_idx + SearchIO.index('Blast/wnts.xml', 'blast-xml', key_function=None) + >>> sorted(search_idx) + ['gi|156630997:105-1160', 'gi|195230749:301-1383', ..., 'gi|53729353:216-1313'] + >>> search_idx['gi|195230749:301-1383'] + QueryResult(id='gi|195230749:301-1383', 5 hits) + >>> search_idx.close() + + If the file is BGZF compressed, this is detected automatically. Ordinary + GZIP files are not supported: + + >>> from Bio import SearchIO + >>> search_idx = SearchIO.index('Blast/wnts.xml.bgz', 'blast-xml') + >>> search_idx + SearchIO.index('Blast/wnts.xml.bgz', 'blast-xml', key_function=None) + >>> search_idx['gi|195230749:301-1383'] + QueryResult(id='gi|195230749:301-1383', 5 hits) + >>> search_idx.close() + + You can supply a custom callback function to alter the default identifier + string. This function should accept as its input the QueryResult ID string + and return a modified version of it. + + >>> from Bio import SearchIO + >>> key_func = lambda id: id.split('|')[1] + >>> search_idx = SearchIO.index('Blast/wnts.xml', 'blast-xml', key_func) + >>> search_idx + SearchIO.index('Blast/wnts.xml', 'blast-xml', key_function= at ...>) + >>> sorted(search_idx) + ['156630997:105-1160', ..., '371502086:108-1205', '53729353:216-1313'] + >>> search_idx['156630997:105-1160'] + QueryResult(id='gi|156630997:105-1160', 5 hits) + >>> search_idx.close() + + Note that the callback function does not change the QueryResult's ID value. + It only changes the key value used to retrieve the associated QueryResult. + + """ + if not isinstance(filename, str): + raise TypeError("Need a filename (not a handle)") + + from Bio.File import _IndexedSeqFileDict + + proxy_class = get_processor(format, _INDEXER_MAP) + repr = f"SearchIO.index({filename!r}, {format!r}, key_function={key_function!r})" + return _IndexedSeqFileDict( + proxy_class(filename, **kwargs), key_function, repr, "QueryResult" + ) + + +def index_db(index_filename, filenames=None, format=None, key_function=None, **kwargs): + """Indexes several search output files into an SQLite database. + + - index_filename - The SQLite filename. + - filenames - List of strings specifying file(s) to be indexed, or when + indexing a single file this can be given as a string. + (optional if reloading an existing index, but must match) + - format - Lower case string denoting one of the supported formats. + (optional if reloading an existing index, but must match) + - key_function - Optional callback function which when given a + QueryResult identifier string should return a unique + key for the dictionary. + - kwargs - Format-specific keyword arguments. + + The ``index_db`` function is similar to ``index`` in that it indexes the start + position of all queries from search output files. The main difference is + instead of storing these indices in-memory, they are written to disk as an + SQLite database file. This allows the indices to persist between Python + sessions. This enables access to any queries in the file without any + indexing overhead, provided it has been indexed at least once. + + >>> from Bio import SearchIO + >>> idx_filename = ":memory:" # Use a real filename, this is in RAM only! + >>> db_idx = SearchIO.index_db(idx_filename, 'Blast/mirna.xml', 'blast-xml') + >>> sorted(db_idx) + ['33211', '33212', '33213'] + >>> db_idx['33212'] + QueryResult(id='33212', 44 hits) + >>> db_idx.close() + + ``index_db`` can also index multiple files and store them in the same + database, making it easier to group multiple search files and access them + from a single interface. + + >>> from Bio import SearchIO + >>> idx_filename = ":memory:" # Use a real filename, this is in RAM only! + >>> files = ['Blast/mirna.xml', 'Blast/wnts.xml'] + >>> db_idx = SearchIO.index_db(idx_filename, files, 'blast-xml') + >>> sorted(db_idx) + ['33211', '33212', '33213', 'gi|156630997:105-1160', ..., 'gi|53729353:216-1313'] + >>> db_idx['33212'] + QueryResult(id='33212', 44 hits) + >>> db_idx.close() + + One common example where this is helpful is if you had a large set of + query sequences (say ten thousand) which you split into ten query files + of one thousand sequences each in order to run as ten separate BLAST jobs + on a cluster. You could use ``index_db`` to index the ten BLAST output + files together for seamless access to all the results as one dictionary. + + Note that ':memory:' rather than an index filename tells SQLite to hold + the index database in memory. This is useful for quick tests, but using + the Bio.SearchIO.index(...) function instead would use less memory. + + BGZF compressed files are supported, and detected automatically. Ordinary + GZIP compressed files are not supported. + + See also Bio.SearchIO.index(), Bio.SearchIO.to_dict(), and the Python module + glob which is useful for building lists of files. + """ + # cast filenames to list if it's a string + # (can we check if it's a string or a generator?) + if isinstance(filenames, str): + filenames = [filenames] + + from Bio.File import _SQLiteManySeqFilesDict + + repr = f"SearchIO.index_db({index_filename!r}, filenames={filenames!r}, {format!r}, key_function={key_function!r})" + + def proxy_factory(format, filename=None): + """Given a filename returns proxy object, else boolean if format OK.""" + if filename: + return get_processor(format, _INDEXER_MAP)(filename, **kwargs) + else: + return format in _INDEXER_MAP + + return _SQLiteManySeqFilesDict( + index_filename, filenames, proxy_factory, format, key_function, repr + ) + + +def write(qresults, handle, format=None, **kwargs): + """Write QueryResult objects to a file in the given format. + + - qresults - An iterator returning QueryResult objects or a single + QueryResult object. + - handle - Handle to the file, or the filename as a string. + - format - Lower case string denoting one of the supported formats. + - kwargs - Format-specific keyword arguments. + + The ``write`` function writes QueryResult object(s) into the given output + handle / filename. You can supply it with a single QueryResult object or an + iterable returning one or more QueryResult objects. In both cases, the + function will return a tuple of four values: the number of QueryResult, Hit, + HSP, and HSPFragment objects it writes to the output file:: + + from Bio import SearchIO + qresults = SearchIO.parse('Blast/mirna.xml', 'blast-xml') + SearchIO.write(qresults, 'results.tab', 'blast-tab') + (3, 239, 277, 277) + + The output of different formats may be adjusted using the format-specific + keyword arguments. Here is an example that writes BLAT PSL output file with + a header:: + + from Bio import SearchIO + qresults = SearchIO.parse('Blat/psl_34_001.psl', 'blat-psl') + SearchIO.write(qresults, 'results.tab', 'blat-psl', header=True) + (2, 13, 22, 26) + + """ + # turn qresults into an iterator if it's a single QueryResult object + if isinstance(qresults, QueryResult): + qresults = iter([qresults]) + else: + qresults = iter(qresults) + + # get the writer object and do error checking + writer_class = get_processor(format, _WRITER_MAP) + + # write to the handle + with as_handle(handle, "w") as target_file: + writer = writer_class(target_file, **kwargs) + # count how many qresults, hits, and hsps + qresult_count, hit_count, hsp_count, frag_count = writer.write_file(qresults) + + return qresult_count, hit_count, hsp_count, frag_count + + +def convert(in_file, in_format, out_file, out_format, in_kwargs=None, out_kwargs=None): + """Convert between two search output formats, return number of records. + + - in_file - Handle to the input file, or the filename as string. + - in_format - Lower case string denoting the format of the input file. + - out_file - Handle to the output file, or the filename as string. + - out_format - Lower case string denoting the format of the output file. + - in_kwargs - Dictionary of keyword arguments for the input function. + - out_kwargs - Dictionary of keyword arguments for the output function. + + The convert function is a shortcut function for ``parse`` and ``write``. It has + the same return type as ``write``. Format-specific arguments may be passed to + the convert function, but only as dictionaries. + + Here is an example of using ``convert`` to convert from a BLAST+ XML file + into a tabular file with comments:: + + from Bio import SearchIO + in_file = 'Blast/mirna.xml' + in_fmt = 'blast-xml' + out_file = 'results.tab' + out_fmt = 'blast-tab' + out_kwarg = {'comments': True} + SearchIO.convert(in_file, in_fmt, out_file, out_fmt, out_kwargs=out_kwarg) + (3, 239, 277, 277) + + Given that different search output file provide different statistics and + different level of details, the convert function is limited only to + converting formats that have the same statistics and for conversion to + formats with the same level of detail, or less. + + For example, converting from a BLAST+ XML output to a HMMER table file + is not possible, as these are two search programs with different kinds of + statistics. In theory, you may provide the necessary values required by the + HMMER table file (e.g. conditional e-values, envelope coordinates, etc). + However, these values are likely to hold little meaning as they are not true + HMMER-computed values. + + Another example is converting from BLAST+ XML to BLAST+ tabular file. This + is possible, as BLAST+ XML provide all the values necessary to create a + BLAST+ tabular file. However, the reverse conversion may not be possible. + There are more details covered in the XML file that are not found in a + tabular file (e.g. the lambda and kappa values) + + """ + if in_kwargs is None: + in_kwargs = {} + if out_kwargs is None: + out_kwargs = {} + + qresults = parse(in_file, in_format, **in_kwargs) + return write(qresults, out_file, out_format, **out_kwargs) + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_index.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_index.py new file mode 100644 index 0000000000000000000000000000000000000000..22f8576f8a97e5f80cc22a8fdf37ad2ce5de4423 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_index.py @@ -0,0 +1,35 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# Revisions copyright 2012-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Custom indexing for Bio.SearchIO objects.""" + +from io import StringIO + +from Bio.File import _IndexedSeqFileProxy +from Bio.File import _open_for_random_access + + +class SearchIndexer(_IndexedSeqFileProxy): + """Base class for file format specific random access. + + Subclasses for each file format should define '_parser' and optionally + 'get_raw' methods. + """ + + def __init__(self, filename, **kwargs): + """Initialize the class.""" + self._handle = _open_for_random_access(filename) + self._kwargs = kwargs + + def _parse(self, handle): + """Pass handle and arguments to the next iterable (PRIVATE).""" + return next(iter(self._parser(handle, **self._kwargs))) + + def get(self, offset): + """Get offset and convert it from bytes to string.""" + return self._parse(StringIO(self.get_raw(offset).decode())) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.__base.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.__base.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/.__base.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hit.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hit.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hit.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hsp.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hsp.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._hsp.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._query.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._query.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/._query.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa9ea76d2f72629f7f5319353f7364be707cd47 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/__init__.py @@ -0,0 +1,59 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO objects to model similarity search program outputs. + +The SearchIO object model consists of a hierarchy of four nested objects: + + * QueryResult, to represent a search query. + + This is the top-level object returned by the main SearchIO ``parse`` and + ``read`` functions. QueryResult objects may contain zero or more Hit + objects, each accessible by its ID string (like in Python dictionaries) + or integer index (like in Python lists). + + * Hit, to represent a database entry containing a full or partial sequence + match with the query sequence. + + Hit objects contain one or more HSP objects, each accessible by its integer + index. They behave very similar to a Python list. + + * HSP, to represent a region of significant alignment(s) between the query + and hit sequences. + + HSP objects contain one or more HSPFragment objects, each accessible by + its integer index. In most cases, the HSP objects are where the bulk of + search result statistics (e.g. e-value, bitscore) are stored. Like Hit + objects, HSPs also behave very similar to a Python list. + + * HSPFragment, to represent a single contiguous alignment between the query + and hit sequences. + + HSPFragment objects may store hit and query sequences resulting from the + sequence search. If present, these sequences are stored as SeqRecord + objects (see SeqRecord). If both of them are present, HSPFragment will + create a MultipleSeqAlignment object from both sequences. + + Most search programs only have HSPs with one HSPFragment in them, making + these two objects inseparable. However, there are programs (e.g. BLAT and + Exonerate) which may have more than one HSPFragment objects in any given + HSP. If you are not using these programs, you can safely consider HSP and + HSPFragment as a single union. + +""" + +from .hit import Hit +from .hsp import HSP +from .hsp import HSPFragment +from .query import QueryResult + +__all__ = ("QueryResult", "Hit", "HSP", "HSPFragment") + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/_base.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..02e8b28453f0b09cba7750d6f5b618f4005a60d4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/_base.py @@ -0,0 +1,69 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Abstract base classes for the SearchIO object model.""" + +from typing import Union + +from Bio.SearchIO._utils import getattr_str + + +class _BaseSearchObject: + """Abstract class for SearchIO objects.""" + + _NON_STICKY_ATTRS: tuple | tuple[str] = () + + def _transfer_attrs(self, obj): + """Transfer instance attributes to the given object (PRIVATE). + + This method is used to transfer attributes set externally (for example + using ``setattr``) to a new object created from this one (for example + from slicing). + + The reason this method is necessary is because different parsers will + set different attributes for each QueryResult, Hit, HSP, or HSPFragment + objects, depending on the attributes they found in the search output + file. Ideally, we want these attributes to 'stick' with any new instance + object created from the original one. + + """ + # list of attribute names we don't want to transfer + for attr in self.__dict__: + if attr not in self._NON_STICKY_ATTRS: + setattr(obj, attr, self.__dict__[attr]) + + +class _BaseHSP(_BaseSearchObject): + """Abstract base class for HSP objects.""" + + def _str_hsp_header(self): + """Print the alignment header info (PRIVATE).""" + lines = [] + # set query id line + qid_line = f" Query: {self.query_id} {self.query_description}" + qid_line = qid_line[:77] + "..." if len(qid_line) > 80 else qid_line + # set hit id line + hid_line = f" Hit: {self.hit_id} {self.hit_description}" + hid_line = hid_line[:77] + "..." if len(hid_line) > 80 else hid_line + lines.append(qid_line) + lines.append(hid_line) + + # coordinates + query_start = getattr_str(self, "query_start") + query_end = getattr_str(self, "query_end") + hit_start = getattr_str(self, "hit_start") + hit_end = getattr_str(self, "hit_end") + + # strands + try: + qstrand = self.query_strand + hstrand = self.hit_strand + except ValueError: + qstrand = self.query_strand_all[0] + hstrand = self.hit_strand_all[0] + lines.append(f"Query range: [{query_start}:{query_end}] ({qstrand!r})") + lines.append(f" Hit range: [{hit_start}:{hit_end}] ({hstrand!r})") + + return "\n".join(lines) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hit.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hit.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce53dd0789010359cb113c1f6e0e6a4d2fde200 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hit.py @@ -0,0 +1,464 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO object to model a single database hit.""" + +from itertools import chain + +from Bio.SearchIO._utils import allitems +from Bio.SearchIO._utils import getattr_str +from Bio.SearchIO._utils import optionalcascade + +from ._base import _BaseSearchObject +from .hsp import HSP + + +class Hit(_BaseSearchObject): + """Class representing a single database hit of a search result. + + Hit objects are the second-level container in the SearchIO module. They + are the objects contained within a QueryResult (see QueryResult). They + themselves are container for HSP objects and will contain at least one + HSP. + + To have a quick look at a Hit and its contents, invoke ``print`` on it:: + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> hit = qresult[3] + >>> print(hit) + Query: 33211 + mir_1 + Hit: gi|301171322|ref|NR_035857.1| (86) + Pan troglodytes microRNA mir-520c (MIR520C), microRNA + HSPs: ---- -------- --------- ------ --------------- --------------------- + # E-value Bit score Span Query range Hit range + ---- -------- --------- ------ --------------- --------------------- + 0 8.9e-20 100.47 60 [1:61] [13:73] + 1 3.3e-06 55.39 60 [0:60] [13:73] + + You can invoke ``len`` on a Hit object to see how many HSP objects it contains:: + + >>> len(hit) + 2 + + Hit objects behave very similar to Python lists. You can retrieve the HSP + object inside a Hit using the HSP's integer index. Hit objects can also be + sliced, which will return a new Hit objects containing only the sliced HSPs:: + + # HSP items inside the Hit can be retrieved using its integer index + >>> hit[0] + HSP(hit_id='gi|301171322|ref|NR_035857.1|', query_id='33211', 1 fragments) + + # slicing returns a new Hit + >>> hit + Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps) + >>> hit[:1] + Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 1 hsps) + >>> print(hit[1:]) + Query: 33211 + mir_1 + Hit: gi|301171322|ref|NR_035857.1| (86) + Pan troglodytes microRNA mir-520c (MIR520C), microRNA + HSPs: ---- -------- --------- ------ --------------- --------------------- + # E-value Bit score Span Query range Hit range + ---- -------- --------- ------ --------------- --------------------- + 0 3.3e-06 55.39 60 [0:60] [13:73] + + Hit objects provide ``filter`` and ``map`` methods, which are analogous to + Python's built-in ``filter`` and ``map`` except that they return a new Hit + object instead of a list. + + Here is an example of using ``filter`` to select for HSPs whose e-value is + less than 1e-10:: + + >>> evalue_filter = lambda hsp: hsp.evalue < 1e-10 + >>> filtered_hit = hit.filter(evalue_filter) + >>> len(hit) + 2 + >>> len(filtered_hit) + 1 + >>> print(filtered_hit) + Query: 33211 + mir_1 + Hit: gi|301171322|ref|NR_035857.1| (86) + Pan troglodytes microRNA mir-520c (MIR520C), microRNA + HSPs: ---- -------- --------- ------ --------------- --------------------- + # E-value Bit score Span Query range Hit range + ---- -------- --------- ------ --------------- --------------------- + 0 8.9e-20 100.47 60 [1:61] [13:73] + + There are also other methods which are counterparts of Python lists' methods + with the same names: ``append``, ``index``, ``pop``, and ``sort``. Consult their + respective documentations for more details and examples of their usage. + + """ + + # attributes we don't want to transfer when creating a new Hit class + # from this one + _NON_STICKY_ATTRS = ("_items",) + + def __init__(self, hsps=(), id=None, query_id=None): + """Initialize a Hit object. + + :param hsps: HSP objects contained in the Hit object + :type hsps: iterable yielding HSP + :param id: hit ID + :type id: string + :param query_id: query ID + :type query_id: string + + If multiple HSP objects are used for initialization, they must all + have the same ``query_id``, ``query_description``, ``hit_id``, and + ``hit_description`` properties. + """ + # default attribute values + self._id = id + self._id_alt = [] + self._query_id = query_id + self._description = None + self._description_alt = [] + self._query_description = None + self.attributes = {} + self.dbxrefs = [] + + # TODO - Move this into the for look below in case + # hsps is a single use iterator? + for attr in ("query_id", "query_description", "hit_id", "hit_description"): + # HACK: setting the if clause to '> 1' allows for empty hit objects. + # This makes it easier to work with file formats with unpredictable + # hit-hsp ordering. The empty hit object itself is nonfunctional, + # however, since all its cascading properties are empty. + if len({getattr(hsp, attr) for hsp in hsps}) > 1: + raise ValueError( + "Hit object can not contain HSPs with more than one %s." % attr + ) + + self._items = [] + for hsp in hsps: + # validate each HSP + self._validate_hsp(hsp) + # and store it them as an instance attribute + self.append(hsp) + + def __repr__(self): + """Return string representation of Hit object.""" + return f"Hit(id={self.id!r}, query_id={self.query_id!r}, {len(self)!r} hsps)" + + def __iter__(self): + """Iterate over hsps.""" + return iter(self.hsps) + + def __len__(self): + """Return number of hsps.""" + return len(self.hsps) + + def __bool__(self): + """Return True if there are hsps.""" + return bool(self.hsps) + + def __contains__(self, hsp): + """Return True if hsp in items.""" + return hsp in self._items + + def __str__(self): + """Return a human readable summary of the Hit object.""" + lines = [] + + # set query id line + qid_line = "Query: %s" % self.query_id + lines.append(qid_line) + if self.query_description: + line = " %s" % self.query_description + line = line[:77] + "..." if len(line) > 80 else line + lines.append(line) + + # set hit id line + hid_line = " Hit: %s" % self.id + try: + seq_len = self.seq_len + except AttributeError: + pass + else: + hid_line += " (%i)" % seq_len + lines.append(hid_line) + if self.description: + line = " %s" % self.description + line = line[:77] + "..." if len(line) > 80 else line + lines.append(line) + + # set attributes lines + for key, value in sorted(self.attributes.items()): + lines.append(f" {key}: {value}") + + # set dbxrefs line + if self.dbxrefs: + lines.append("Database cross-references: " + ", ".join(self.dbxrefs)) + + # set hsp line and table + if not self.hsps: + lines.append(" HSPs: ?") + else: + lines.append( + " HSPs: %s %s %s %s %s %s" + % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21) + ) + pattern = "%11s %8s %9s %6s %15s %21s" + lines.append( + pattern + % ("#", "E-value", "Bit score", "Span", "Query range", "Hit range") + ) + lines.append( + pattern % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21) + ) + for idx, hsp in enumerate(self.hsps): + # evalue + evalue = getattr_str(hsp, "evalue", fmt="%.2g") + # bitscore + bitscore = getattr_str(hsp, "bitscore", fmt="%.2f") + # alignment length + aln_span = getattr_str(hsp, "aln_span") + # query region + query_start = getattr_str(hsp, "query_start") + query_end = getattr_str(hsp, "query_end") + query_range = f"[{query_start}:{query_end}]" + # max column length is 18 + query_range = ( + query_range[:13] + "~]" if len(query_range) > 15 else query_range + ) + # hit region + hit_start = getattr_str(hsp, "hit_start") + hit_end = getattr_str(hsp, "hit_end") + hit_range = f"[{hit_start}:{hit_end}]" + hit_range = hit_range[:19] + "~]" if len(hit_range) > 21 else hit_range + # append the hsp row + lines.append( + pattern % (idx, evalue, bitscore, aln_span, query_range, hit_range) + ) + + return "\n".join(lines) + + def __getitem__(self, idx): + """Return the HSP object at the given index.""" + # if key is slice, return a new Hit instance + if isinstance(idx, slice): + obj = self.__class__(self.hsps[idx]) + self._transfer_attrs(obj) + return obj + return self._items[idx] + + def __setitem__(self, idx, hsps): + """Assign hsps to index idx.""" + # handle case if hsps is a list of hsp + if isinstance(hsps, (list, tuple)): + for hsp in hsps: + self._validate_hsp(hsp) + else: + self._validate_hsp(hsps) + + self._items[idx] = hsps + + def __delitem__(self, idx): + """Delete item of index idx.""" + del self._items[idx] + + # hsp properties # + def _validate_hsp(self, hsp): + """Validate an HSP object (PRIVATE). + + Valid HSP objects have the same hit_id as the Hit object ID and the + same query_id as the Hit object's query_id. + + """ + if not isinstance(hsp, HSP): + raise TypeError("Hit objects can only contain HSP objects.") + # HACK: to make validation during __init__ work + if self._items: + if self.id is not None: + if hsp.hit_id != self.id: + raise ValueError( + "Expected HSP with hit ID %r, found %r instead." + % (self.id, hsp.hit_id) + ) + else: + self.id = hsp.hit_id + + if self.description is not None: + if hsp.hit_description != self.description: + raise ValueError( + "Expected HSP with hit description %r, found %r instead." + % (self.description, hsp.hit_description) + ) + else: + self.description = hsp.hit_description + + if self.query_id is not None: + if hsp.query_id != self.query_id: + raise ValueError( + "Expected HSP with query ID %r, found %r instead." + % (self.query_id, hsp.query_id) + ) + else: + self.query_id = hsp.query_id + + if self.query_description is not None: + if hsp.query_description != self.query_description: + raise ValueError( + "Expected HSP with query description %r, found %r instead." + % (self.query_description, hsp.query_description) + ) + else: + self.query_description = hsp.query_description + + # properties # + description = optionalcascade( + "_description", "hit_description", """Hit description""" + ) + query_description = optionalcascade( + "_query_description", + "query_description", + """Description of the query that produced the hit""", + ) + id = optionalcascade("_id", "hit_id", """Hit ID string.""") + query_id = optionalcascade( + "_query_id", "query_id", """ID string of the query that produced the hit""" + ) + # returns all hsps + hsps = allitems(doc="""HSP objects contained in the Hit""") + + @property + def id_all(self): + """Alternative ID(s) of the Hit.""" + return [self.id] + self._id_alt + + @property + def description_all(self): + """Alternative descriptions of the Hit.""" + return [self.description] + self._description_alt + + @property + def fragments(self): + """Access the HSPFragment objects contained in the Hit.""" + return list(chain(*self._items)) + + # public methods # + def append(self, hsp): + """Add a HSP object to the end of Hit. + + Parameters + hsp -- HSP object to append. + + Any HSP object appended must have the same ``hit_id`` property as the + Hit object's ``id`` property and the same ``query_id`` property as the + Hit object's ``query_id`` property. + + """ + self._validate_hsp(hsp) + self._items.append(hsp) + + def filter(self, func=None): + """Create new Hit object whose HSP objects pass the filter function. + + :param func: function for filtering + :type func: callable, accepts HSP, returns bool + + ``filter`` is analogous to Python's built-in ``filter`` function, except + that instead of returning a list it returns a ``Hit`` object. Here is an + example of using ``filter`` to select for HSPs having bitscores bigger + than 60:: + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> hit = qresult[3] + >>> evalue_filter = lambda hsp: hsp.bitscore > 60 + >>> filtered_hit = hit.filter(evalue_filter) + >>> len(hit) + 2 + >>> len(filtered_hit) + 1 + >>> print(filtered_hit) + Query: 33211 + mir_1 + Hit: gi|301171322|ref|NR_035857.1| (86) + Pan troglodytes microRNA mir-520c (MIR520C), microRNA + HSPs: ---- -------- --------- ------ --------------- --------------------- + # E-value Bit score Span Query range Hit range + ---- -------- --------- ------ --------------- --------------------- + 0 8.9e-20 100.47 60 [1:61] [13:73] + + """ + hsps = list(filter(func, self.hsps)) + if hsps: + obj = self.__class__(hsps) + self._transfer_attrs(obj) + return obj + + def index(self, hsp): + """Return the index of a given HSP object, zero-based. + + :param hsp: object to look up + :type hsp: HSP + + """ + return self._items.index(hsp) + + def map(self, func=None): + """Create new Hit object, mapping the given function to its HSPs. + + :param func: function for mapping + :type func: callable, accepts HSP, returns HSP + + ``map`` is analogous to Python's built-in ``map`` function. It is applied to + all HSPs contained in the Hit object and returns a new Hit object. + + """ + if func is not None: + hsps = [func(x) for x in self.hsps[:]] # this creates a shallow copy + else: + hsps = self.hsps[:] + if hsps: + obj = self.__class__(hsps) + self._transfer_attrs(obj) + return obj + + def pop(self, index=-1): + """Remove and returns the HSP object at the specified index. + + :param index: index of HSP object to pop + :type index: int + + """ + return self._items.pop(index) + + def sort(self, key=None, reverse=False, in_place=True): + """Sort the HSP objects. + + :param key: sorting function + :type key: callable, accepts HSP, returns key for sorting + :param reverse: whether to reverse sorting results or no + :type reverse: bool + :param in_place: whether to do in-place sorting or no + :type in_place: bool + + ``sort`` defaults to sorting in-place, to mimic Python's ``list.sort`` + method. If you set the ``in_place`` argument to False, it will treat + return a new, sorted Hit object and keep the initial one unsorted + + """ + if in_place: + self._items.sort(key=key, reverse=reverse) + else: + hsps = self.hsps[:] + hsps.sort(key=key, reverse=reverse) + obj = self.__class__(hsps) + self._transfer_attrs(obj) + return obj + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hsp.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hsp.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a0ec021037c2b1804875feae0f7f2bed2a9f17 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/hsp.py @@ -0,0 +1,1228 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO objects to model high scoring regions between query and hit.""" + +import warnings +from operator import ge +from operator import le + +from Bio import BiopythonWarning +from Bio.Align import MultipleSeqAlignment +from Bio.SearchIO._utils import allitems +from Bio.SearchIO._utils import fragcascade +from Bio.SearchIO._utils import fullcascade +from Bio.SearchIO._utils import getattr_str +from Bio.SearchIO._utils import singleitem +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from ._base import _BaseHSP + + +class HSP(_BaseHSP): + """Class representing high-scoring region(s) between query and hit. + + HSP (high-scoring pair) objects are contained by Hit objects (see Hit). + In most cases, HSP objects store the bulk of the statistics and results + (e.g. e-value, bitscores, query sequence, etc.) produced by a search + program. + + Depending on the search output file format, a given HSP will contain one + or more HSPFragment object(s). Examples of search programs that produce HSP + with one HSPFragments are BLAST, HMMER, and FASTA. Other programs such as + BLAT or Exonerate may produce HSPs containing more than one HSPFragment. + However, their native terminologies may differ: in BLAT these fragments + are called 'blocks' while in Exonerate they are called exons or NER. + + Here are examples from each type of HSP. The first one comes from a BLAST + search:: + + >>> from Bio import SearchIO + >>> blast_qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> blast_hsp = blast_qresult[1][0] # the first HSP from the second hit + >>> blast_hsp + HSP(hit_id='gi|301171311|ref|NR_035856.1|', query_id='33211', 1 fragments) + >>> print(blast_hsp) + Query: 33211 mir_1 + Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ... + Query range: [1:61] (1) + Hit range: [0:60] (1) + Quick stats: evalue 1.7e-22; bitscore 109.49 + Fragments: 1 (60 columns) + Query - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG + |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| + Hit - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG + + For HSPs with a single HSPFragment, you can invoke ``print`` on it and see the + underlying sequence alignment, if it exists. This is not the case for HSPs + with more than one HSPFragment. Below is an example, using an HSP from a + BLAT search. Invoking ``print`` on these HSPs will instead show a table of the + HSPFragment objects it contains:: + + >>> blat_qresult = SearchIO.read('Blat/mirna.pslx', 'blat-psl', pslx=True) + >>> blat_hsp = blat_qresult[1][0] # the first HSP from the second hit + >>> blat_hsp + HSP(hit_id='chr11', query_id='blat_1', 2 fragments) + >>> print(blat_hsp) + Query: blat_1 + Hit: chr11 + Query range: [42:67] (-1) + Hit range: [59018929:59018955] (1) + Quick stats: evalue ?; bitscore ? + Fragments: --- -------------- ---------------------- ---------------------- + # Span Query range Hit range + --- -------------- ---------------------- ---------------------- + 0 6 [61:67] [59018929:59018935] + 1 16 [42:58] [59018939:59018955] + + Notice that in HSPs with more than one HSPFragments, the HSP's ``query_range`` + ``hit_range`` properties encompasses all fragments it contains. + + You can check whether an HSP has more than one HSPFragments or not using the + ``is_fragmented`` property:: + + >>> blast_hsp.is_fragmented + False + >>> blat_hsp.is_fragmented + True + + Since HSP objects are also containers similar to Python lists, you can + access a single fragment in an HSP using its integer index:: + + >>> blat_fragment = blat_hsp[0] + >>> print(blat_fragment) + Query: blat_1 + Hit: chr11 + Query range: [61:67] (-1) + Hit range: [59018929:59018935] (1) + Fragments: 1 (6 columns) + Query - tatagt + Hit - tatagt + + This applies to HSPs objects with a single fragment as well:: + + >>> blast_fragment = blast_hsp[0] + >>> print(blast_fragment) + Query: 33211 mir_1 + Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ... + Query range: [1:61] (1) + Hit range: [0:60] (1) + Fragments: 1 (60 columns) + Query - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG + |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| + Hit - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG + + Regardless of the search output file format, HSP objects provide the + properties listed below. These properties always return values in a list, + due to the HSP object itself being a list-like container. However, for + HSP objects with a single HSPFragment, shortcut properties that fetches + the item from the list are also provided. + + +----------------------+---------------------+-----------------------------+ + | Property | Shortcut | Value | + +======================+=====================+=============================+ + | aln_all | aln | HSP alignments as | + | | | MultipleSeqAlignment object | + +----------------------+---------------------+-----------------------------+ + | aln_annotation_all | aln_annotation | dictionary of annotation(s) | + | | | of all fragments' alignments| + +----------------------+---------------------+-----------------------------+ + | fragments | fragment | HSPFragment objects | + +----------------------+---------------------+-----------------------------+ + | hit_all | hit | hit sequence as SeqRecord | + | | | objects | + +----------------------+---------------------+-----------------------------+ + | hit_features_all | hit_features | SeqFeatures of all hit | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | hit_start_all | hit_start* | start coordinates of the | + | | | hit fragments | + +----------------------+---------------------+-----------------------------+ + | hit_end_all | hit_end* | end coordinates of the hit | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | hit_span_all | hit_span* | sizes of each hit fragments | + +----------------------+---------------------+-----------------------------+ + | hit_strand_all | hit_strand | strand orientations of the | + | | | hit fragments | + +----------------------+---------------------+-----------------------------+ + | hit_frame_all | hit_frame | reading frames of the hit | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | hit_range_all | hit_range | tuples of start and end | + | | | coordinates of each hit | + | | | fragment | + +----------------------+---------------------+-----------------------------+ + | query_all | query | query sequence as SeqRecord | + | | | object | + +----------------------+---------------------+-----------------------------+ + | query_features_all | query_features | SeqFeatures of all query | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | query_start_all | query_start* | start coordinates of the | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | query_end_all | query_end* | end coordinates of the | + | | | query fragments | + +----------------------+---------------------+-----------------------------+ + | query_span_all | query_span* | sizes of each query | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | query_strand_all | query_strand | strand orientations of the | + | | | query fragments | + +----------------------+---------------------+-----------------------------+ + | query_frame_all | query_frame | reading frames of the query | + | | | fragments | + +----------------------+---------------------+-----------------------------+ + | query_range_all | query_range | tuples of start and end | + | | | coordinates of each query | + | | | fragment | + +----------------------+---------------------+-----------------------------+ + + For all types of HSP objects, the property will return the values in a list. + Shortcuts are only applicable for HSPs with one fragment. Except the ones + noted, if they are used on an HSP with more than one fragments, an exception + will be raised. + + For properties that may be used in HSPs with multiple or single fragments + (``*_start``, ``*_end``, and ``*_span`` properties), their interpretation depends + on how many fragment the HSP has: + + +------------+---------------------------------------------------+ + | Property | Value | + +============+===================================================+ + | hit_start | smallest coordinate value of all hit fragments | + +------------+---------------------------------------------------+ + | hit_end | largest coordinate value of all hit fragments | + +------------+---------------------------------------------------+ + | hit_span | difference between ``hit_start`` and ``hit_end`` | + +------------+---------------------------------------------------+ + | query_start| smallest coordinate value of all query fragments | + +------------+---------------------------------------------------+ + | query_end | largest coordinate value of all query fragments | + +------------+---------------------------------------------------+ + | query_span | difference between ``query_start`` and | + | | ``query_end`` | + +------------+---------------------------------------------------+ + + In addition to the objects listed above, HSP objects also provide the + following properties and/or attributes: + + +--------------------+------------------------------------------------------+ + | Property | Value | + +====================+======================================================+ + | aln_span | total number of residues in all HSPFragment objects | + +--------------------+------------------------------------------------------+ + | molecule_type | molecule_type of the hit and query SeqRecord objects | + +--------------------+------------------------------------------------------+ + | is_fragmented | boolean, whether there are multiple fragments or not | + +--------------------+------------------------------------------------------+ + | hit_id | ID of the hit sequence | + +--------------------+------------------------------------------------------+ + | hit_description | description of the hit sequence | + +--------------------+------------------------------------------------------+ + | hit_inter_ranges | list of hit sequence coordinates of the regions | + | | between fragments | + +--------------------+------------------------------------------------------+ + | hit_inter_spans | list of lengths of the regions between hit fragments | + +--------------------+------------------------------------------------------+ + | output_index | 0-based index for storing the order by which the HSP | + | | appears in the output file (default: -1). | + +--------------------+------------------------------------------------------+ + | query_id | ID of the query sequence | + +--------------------+------------------------------------------------------+ + | query_description | description of the query sequence | + +--------------------+------------------------------------------------------+ + | query_inter_ranges | list of query sequence coordinates of the regions | + | | between fragments | + +--------------------+------------------------------------------------------+ + | query_inter_spans | list of lengths of the regions between query | + | | fragments | + +--------------------+------------------------------------------------------+ + + .. [1] may be used in HSPs with multiple fragments + + """ + + # attributes we don't want to transfer when creating a new Hit class + # from this one + _NON_STICKY_ATTRS = ("_items",) + + def __init__(self, fragments=(), output_index=-1): + """Initialize an HSP object. + + :param fragments: fragments contained in the HSP object + :type fragments: iterable yielding HSPFragment + :param output_index: optional index / ordering of the HSP fragment in + the original input file. + :type output_index: integer + + HSP objects must be initialized with a list containing at least one + HSPFragment object. If multiple HSPFragment objects are used for + initialization, they must all have the same ``query_id``, + ``query_description``, ``hit_id``, ``hit_description``, and + ``molecule_type`` properties. + + """ + if not fragments: + raise ValueError("HSP objects must have at least one HSPFragment object.") + # TODO - Move this into the for look in case hsps is a single use + # iterable? + # check that all fragments contain the same IDs, descriptions, + # molecule_type + for attr in ( + "query_id", + "query_description", + "hit_id", + "hit_description", + "molecule_type", + ): + if len({getattr(frag, attr) for frag in fragments}) != 1: + raise ValueError( + "HSP object can not contain fragments with more than one %s." % attr + ) + + self.output_index = output_index + self._items = [] + for fragment in fragments: + self._validate_fragment(fragment) + self._items.append(fragment) + + def __repr__(self): + """Return string representation of HSP object.""" + return "%s(hit_id=%r, query_id=%r, %r fragments)" % ( + self.__class__.__name__, + self.hit_id, + self.query_id, + len(self), + ) + + def __iter__(self): + """Iterate over HSP items.""" + return iter(self._items) + + def __contains__(self, fragment): + """Return True if HSPFragment is on HSP items.""" + return fragment in self._items + + def __len__(self): + """Return number of HSPs items.""" + return len(self._items) + + def __bool__(self): + """Return True if it has HSPs.""" + return bool(self._items) + + def __str__(self): + """Return a human readable summary of the HSP object.""" + lines = [] + # set hsp info line + statline = [] + # evalue + evalue = getattr_str(self, "evalue", fmt="%.2g") + statline.append("evalue " + evalue) + # bitscore + bitscore = getattr_str(self, "bitscore", fmt="%.2f") + statline.append("bitscore " + bitscore) + lines.append("Quick stats: " + "; ".join(statline)) + + if len(self.fragments) == 1: + return "\n".join( + [self._str_hsp_header(), "\n".join(lines), self.fragments[0]._str_aln()] + ) + else: + lines.append( + " Fragments: %s %s %s %s" % ("-" * 3, "-" * 14, "-" * 22, "-" * 22) + ) + pattern = "%16s %14s %22s %22s" + lines.append(pattern % ("#", "Span", "Query range", "Hit range")) + lines.append(pattern % ("-" * 3, "-" * 14, "-" * 22, "-" * 22)) + for idx, block in enumerate(self.fragments): + # set hsp line and table + # alignment span + aln_span = getattr_str(block, "aln_span") + # query region + query_start = getattr_str(block, "query_start") + query_end = getattr_str(block, "query_end") + query_range = "[%s:%s]" % (query_start, query_end) + # max column length is 20 + query_range = ( + query_range[:20] + "~]" if len(query_range) > 22 else query_range + ) + # hit region + hit_start = getattr_str(block, "hit_start") + hit_end = getattr_str(block, "hit_end") + hit_range = "[%s:%s]" % (hit_start, hit_end) + hit_range = hit_range[:20] + "~]" if len(hit_range) > 22 else hit_range + # append the hsp row + lines.append(pattern % (str(idx), aln_span, query_range, hit_range)) + + return self._str_hsp_header() + "\n" + "\n".join(lines) + + def __getitem__(self, idx): + """Return object of index idx.""" + # if key is slice, return a new HSP instance + if isinstance(idx, slice): + obj = self.__class__(self._items[idx]) + self._transfer_attrs(obj) + return obj + return self._items[idx] + + def __setitem__(self, idx, fragments): + """Set an item of index idx with the given fragments.""" + # handle case if hsps is a list of hsp + if isinstance(fragments, (list, tuple)): + for fragment in fragments: + self._validate_fragment(fragment) + else: + self._validate_fragment(fragments) + + self._items[idx] = fragments + + def __delitem__(self, idx): + """Delete item of index idx.""" + # note that this may result in an empty HSP object, which should be + # invalid + del self._items[idx] + + def _validate_fragment(self, fragment): + if not isinstance(fragment, HSPFragment): + raise TypeError("HSP objects can only contain HSPFragment objects.") + # HACK: to make validation during __init__ work + if self._items: + if fragment.hit_id != self.hit_id: + raise ValueError( + "Expected HSPFragment with hit ID %r, found %r instead." + % (self.id, fragment.hit_id) + ) + + if fragment.hit_description != self.hit_description: + raise ValueError( + "Expected HSPFragment with hit description %r, found %r instead." + % (self.description, fragment.hit_description) + ) + + if fragment.query_id != self.query_id: + raise ValueError( + "Expected HSPFragment with query ID %r, found %r instead." + % (self.query_id, fragment.query_id) + ) + + if fragment.query_description != self.query_description: + raise ValueError( + "Expected HSP with query description %r, found %r instead." + % (self.query_description, fragment.query_description) + ) + + def _aln_span_get(self): + # length of all alignments + # alignment span can be its own attribute, or computed from + # query / hit length + return sum(frg.aln_span for frg in self.fragments) + + aln_span = property( + fget=_aln_span_get, doc="Total number of columns in all HSPFragment objects." + ) + + # coordinate properties # + def _get_coords(self, seq_type, coord_type): + assert seq_type in ("hit", "query") + assert coord_type in ("start", "end") + coord_name = "%s_%s" % (seq_type, coord_type) + coords = [getattr(frag, coord_name) for frag in self.fragments] + if None in coords: + warnings.warn( + "'None' exist in %s coordinates; ignored" % (coord_name), + BiopythonWarning, + ) + return coords + + def _hit_start_get(self): + return min(self._get_coords("hit", "start")) + + hit_start = property( + fget=_hit_start_get, doc="Smallest coordinate value of all hit fragments." + ) + + def _query_start_get(self): + return min(self._get_coords("query", "start")) + + query_start = property( + fget=_query_start_get, doc="Smallest coordinate value of all query fragments." + ) + + def _hit_end_get(self): + return max(self._get_coords("hit", "end")) + + hit_end = property( + fget=_hit_end_get, doc="Largest coordinate value of all hit fragments." + ) + + def _query_end_get(self): + return max(self._get_coords("query", "end")) + + query_end = property( + fget=_query_end_get, doc="Largest coordinate value of all hit fragments." + ) + + # coordinate-dependent properties # + def _hit_span_get(self): + try: + return self.hit_end - self.hit_start + except TypeError: # triggered if any of the coordinates are None + return None + + hit_span = property( + fget=_hit_span_get, doc="The number of hit residues covered by the HSP." + ) + + def _query_span_get(self): + try: + return self.query_end - self.query_start + except TypeError: # triggered if any of the coordinates are None + return None + + query_span = property( + fget=_query_span_get, doc="The number of query residues covered by the HSP." + ) + + def _hit_range_get(self): + return (self.hit_start, self.hit_end) + + hit_range = property( + fget=_hit_range_get, doc="Tuple of HSP hit start and end coordinates." + ) + + def _query_range_get(self): + return (self.query_start, self.query_end) + + query_range = property( + fget=_query_range_get, doc="Tuple of HSP query start and end coordinates." + ) + + def _inter_ranges_get(self, seq_type): + # this property assumes that there are no mixed strands in a hit/query + assert seq_type in ("query", "hit") + strand = getattr(self, "%s_strand_all" % seq_type)[0] + coords = getattr(self, "%s_range_all" % seq_type) + # determine function used to set inter range + # start and end coordinates, given two pairs + # of fragment start and end coordinates + if strand == -1: + startfunc, endfunc = min, max + else: + startfunc, endfunc = max, min + inter_coords = [] + for idx, coord in enumerate(coords[:-1]): + start = startfunc(coords[idx]) + end = endfunc(coords[idx + 1]) + inter_coords.append((min(start, end), max(start, end))) + + return inter_coords + + def _hit_inter_ranges_get(self): + return self._inter_ranges_get("hit") + + hit_inter_ranges = property( + fget=_hit_inter_ranges_get, + doc="Hit sequence coordinates of the regions between fragments.", + ) + + def _query_inter_ranges_get(self): + return self._inter_ranges_get("query") + + query_inter_ranges = property( + fget=_query_inter_ranges_get, + doc="Query sequence coordinates of the regions between fragments.", + ) + + def _inter_spans_get(self, seq_type): + assert seq_type in ("query", "hit") + attr_name = "%s_inter_ranges" % seq_type + return [coord[1] - coord[0] for coord in getattr(self, attr_name)] + + def _hit_inter_spans_get(self): + return self._inter_spans_get("hit") + + hit_inter_spans = property( + fget=_hit_inter_spans_get, doc="Lengths of regions between hit fragments." + ) + + def _query_inter_spans_get(self): + return self._inter_spans_get("query") + + query_inter_spans = property( + fget=_query_inter_spans_get, doc="Lengths of regions between query fragments." + ) + + # shortcuts for fragments' properties # + + # bool check if there's more than one fragments + is_fragmented = property( + lambda self: len(self) > 1, + doc="Whether the HSP has more than one HSPFragment objects.", + ) + + # first item properties with setters + hit_description = fullcascade( + "hit_description", doc="Description of the hit sequence." + ) + + query_description = fullcascade( + "query_description", doc="Description of the query sequence." + ) + + hit_id = fullcascade("hit_id", doc="ID of the hit sequence.") + + query_id = fullcascade("query_id", doc="ID of the query sequence.") + + molecule_type = fullcascade( + "molecule_type", doc="molecule_type of the hit and query SeqRecord objects." + ) + + # properties for single-fragment HSPs + fragment = singleitem(doc="HSPFragment object, first fragment.") + + hit = singleitem("hit", doc="Hit sequence as a SeqRecord object, first fragment.") + + query = singleitem( + "query", doc="Query sequence as a SeqRecord object, first fragment." + ) + + aln = singleitem( + "aln", doc="Alignment of the first fragment as a MultipleSeqAlignment object." + ) + + aln_annotation = singleitem( + "aln_annotation", + doc="Dictionary of annotation(s) of the first fragment's alignment.", + ) + + hit_features = singleitem( + "hit_features", doc="Hit sequence features, first fragment." + ) + + query_features = singleitem( + "query_features", doc="Query sequence features, first fragment." + ) + + hit_strand = singleitem("hit_strand", doc="Hit strand orientation, first fragment.") + + query_strand = singleitem( + "query_strand", doc="Query strand orientation, first fragment." + ) + + hit_frame = singleitem( + "hit_frame", doc="Hit sequence reading frame, first fragment." + ) + + query_frame = singleitem( + "query_frame", doc="Query sequence reading frame, first fragment." + ) + + # properties for multi-fragment HSPs + fragments = allitems(doc="List of all HSPFragment objects.") + + hit_all = allitems( + "hit", doc="List of all fragments' hit sequences as SeqRecord objects." + ) + + query_all = allitems( + "query", doc="List of all fragments' query sequences as SeqRecord objects." + ) + + aln_all = allitems( + "aln", doc="List of all fragments' alignments as MultipleSeqAlignment objects." + ) + + aln_annotation_all = allitems( + "aln_annotation", + doc="Dictionary of annotation(s) of all fragments' alignments.", + ) + + hit_features_all = allitems( + "hit_features", doc="List of all hit sequence features." + ) + + query_features_all = allitems( + "query_features", doc="List of all query sequence features." + ) + + hit_strand_all = allitems( + "hit_strand", doc="List of all fragments' hit sequence strands." + ) + + query_strand_all = allitems( + "query_strand", doc="List of all fragments' query sequence strands" + ) + + hit_frame_all = allitems( + "hit_frame", doc="List of all fragments' hit sequence reading frames." + ) + + query_frame_all = allitems( + "query_frame", doc="List of all fragments' query sequence reading frames." + ) + + hit_start_all = allitems( + "hit_start", doc="List of all fragments' hit start coordinates." + ) + + query_start_all = allitems( + "query_start", doc="List of all fragments' query start coordinates." + ) + + hit_end_all = allitems("hit_end", doc="List of all fragments' hit end coordinates.") + + query_end_all = allitems( + "query_end", doc="List of all fragments' query end coordinates." + ) + + hit_span_all = allitems("hit_span", doc="List of all fragments' hit sequence size.") + + query_span_all = allitems( + "query_span", doc="List of all fragments' query sequence size." + ) + + hit_range_all = allitems( + "hit_range", doc="List of all fragments' hit start and end coordinates." + ) + + query_range_all = allitems( + "query_range", doc="List of all fragments' query start and end coordinates." + ) + + +class HSPFragment(_BaseHSP): + """Class representing a contiguous alignment of hit-query sequence. + + HSPFragment forms the core of any parsed search output file. Depending on + the search output file format, it may contain the actual query and/or hit + sequences that produces the search hits. These sequences are stored as + SeqRecord objects (see SeqRecord): + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> fragment = qresult[0][0][0] # first hit, first hsp, first fragment + >>> print(fragment) + Query: 33211 mir_1 + Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520... + Query range: [0:61] (1) + Hit range: [0:61] (1) + Fragments: 1 (61 columns) + Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG + ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| + Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG + + # the query sequence is a SeqRecord object + >>> fragment.query.__class__ + + >>> print(fragment.query) + ID: 33211 + Name: aligned query sequence + Description: mir_1 + Number of features: 0 + /molecule_type=DNA + Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG') + + # the hit sequence is a SeqRecord object as well + >>> fragment.hit.__class__ + + >>> print(fragment.hit) + ID: gi|262205317|ref|NR_030195.1| + Name: aligned hit sequence + Description: Homo sapiens microRNA 520b (MIR520B), microRNA + Number of features: 0 + /molecule_type=DNA + Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG') + + # when both query and hit are present, we get a MultipleSeqAlignment object + >>> fragment.aln.__class__ + + >>> print(fragment.aln) + Alignment with 2 rows and 61 columns + CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 33211 + CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1| + + """ + + def __init__( + self, + hit_id="", + query_id="", + hit=None, + query=None, + molecule_type=None, + ): + """Initialize the class.""" + self._molecule_type = molecule_type + self.aln_annotation = {} + + self._hit_id = hit_id + self._query_id = query_id + + for seq_type in ("query", "hit"): + # query or hit attributes default attributes + setattr(self, "_%s_description" % seq_type, "") + setattr(self, "_%s_features" % seq_type, []) + # query or hit attributes whose default attribute is None + for attr in ("strand", "frame", "start", "end"): + setattr(self, "%s_%s" % (seq_type, attr), None) + # self.query or self.hit + if eval(seq_type): + setattr(self, seq_type, eval(seq_type)) + else: + setattr(self, seq_type, None) + + def __repr__(self): + """Return HSPFragment info; hit id, query id, number of columns.""" + info = "hit_id=%r, query_id=%r" % (self.hit_id, self.query_id) + try: + info += ", %i columns" % len(self) + except AttributeError: + pass + return "%s(%s)" % (self.__class__.__name__, info) + + def __len__(self): + """Return alignment span.""" + return self.aln_span + + def __str__(self): + """Return string of HSP header and alignments.""" + return self._str_hsp_header() + "\n" + self._str_aln() + + def __getitem__(self, idx): + """Return object of index idx.""" + if self.aln is not None: + obj = self.__class__( + hit_id=self.hit_id, + query_id=self.query_id, + molecule_type=self.molecule_type, + ) + # transfer query and hit attributes + # let SeqRecord handle feature slicing, then retrieve the sliced + # features into the sliced HSPFragment + if self.query is not None: + obj.query = self.query[idx] + obj.query_features = obj.query.features + if self.hit is not None: + obj.hit = self.hit[idx] + obj.hit_features = obj.hit.features + # description, strand, frame + for attr in ("description", "strand", "frame"): + for seq_type in ("hit", "query"): + attr_name = "%s_%s" % (seq_type, attr) + self_val = getattr(self, attr_name) + setattr(obj, attr_name, self_val) + # alignment annotation should be transferred, since we can compute + # the resulting annotation + obj.aln_annotation = {} + for key, value in self.aln_annotation.items(): + assert len(value[idx]) == len(obj) + obj.aln_annotation[key] = value[idx] + return obj + else: + raise TypeError( + "Slicing for HSP objects without alignment is not supported." + ) + + def _str_aln(self): + lines = [] + # alignment length + aln_span = getattr_str(self, "aln_span") + lines.append(" Fragments: 1 (%s columns)" % aln_span) + # sequences + if self.query is not None and self.hit is not None: + try: + qseq = self.query.seq + except AttributeError: # query is None + qseq = "?" + try: + hseq = self.hit.seq + except AttributeError: # hit is None + hseq = "?" + + # similarity line + simil = "" + if "similarity" in self.aln_annotation and isinstance( + self.aln_annotation.get("similarity"), str + ): + simil = self.aln_annotation["similarity"] + + if self.aln_span <= 67: + lines.append("%10s - %s" % ("Query", qseq)) + if simil: + lines.append(" %s" % simil) + lines.append("%10s - %s" % ("Hit", hseq)) + else: + # adjust continuation character length, so we don't display + # the same residues twice + if self.aln_span - 66 > 3: + cont = "~" * 3 + else: + cont = "~" * (self.aln_span - 66) + lines.append("%10s - %s%s%s" % ("Query", qseq[:59], cont, qseq[-5:])) + if simil: + lines.append(" %s%s%s" % (simil[:59], cont, simil[-5:])) + lines.append("%10s - %s%s%s" % ("Hit", hseq[:59], cont, hseq[-5:])) + + return "\n".join(lines) + + # sequence properties # + def _set_seq(self, seq, seq_type): + """Check the given sequence for attribute setting (PRIVATE). + + :param seq: sequence to check + :type seq: string or SeqRecord + :param seq_type: sequence type + :type seq_type: string, choice of 'hit' or 'query' + + """ + assert seq_type in ("hit", "query") + if seq is None: + return seq # return immediately if seq is None + else: + if not isinstance(seq, (str, SeqRecord)): + raise TypeError( + "%s sequence must be a string or a SeqRecord object." % seq_type + ) + # check length if the opposite sequence is not None + opp_type = "hit" if seq_type == "query" else "query" + opp_seq = getattr(self, "_%s" % opp_type, None) + if opp_seq is not None: + if len(seq) != len(opp_seq): + raise ValueError( + "Sequence lengths do not match. Expected: %r (%s); found: %r (%s)." + % (len(opp_seq), opp_type, len(seq), seq_type) + ) + + seq_id = getattr(self, "%s_id" % seq_type) + seq_desc = getattr(self, "%s_description" % seq_type) + seq_feats = getattr(self, "%s_features" % seq_type) + seq_name = "aligned %s sequence" % seq_type + + if isinstance(seq, SeqRecord): + seq.id = seq_id + seq.description = seq_desc + seq.name = seq_name + seq.features = seq_feats + seq.annotations["molecule_type"] = self.molecule_type + elif isinstance(seq, str): + seq = SeqRecord( + Seq(seq), + id=seq_id, + name=seq_name, + description=seq_desc, + features=seq_feats, + annotations={"molecule_type": self.molecule_type}, + ) + + return seq + + def _hit_get(self): + return self._hit + + def _hit_set(self, value): + self._hit = self._set_seq(value, "hit") + + hit = property( + fget=_hit_get, + fset=_hit_set, + doc="Hit sequence as a SeqRecord object, defaults to None.", + ) + + def _query_get(self): + return self._query + + def _query_set(self, value): + self._query = self._set_seq(value, "query") + + query = property( + fget=_query_get, + fset=_query_set, + doc="Query sequence as a SeqRecord object, defaults to None.", + ) + + def _aln_get(self): + if self.query is None and self.hit is None: + return None + if self.hit is None: + msa = MultipleSeqAlignment([self.query]) + elif self.query is None: + msa = MultipleSeqAlignment([self.hit]) + else: + msa = MultipleSeqAlignment([self.query, self.hit]) + molecule_type = self.molecule_type + if molecule_type is not None: + msa.molecule_type = molecule_type + return msa + + aln = property( + fget=_aln_get, + doc="Query-hit alignment as a MultipleSeqAlignment object, defaults to None.", + ) + + def _molecule_type_get(self): + return self._molecule_type + + def _molecule_type_set(self, value): + self._molecule_type = value + try: + self.query.annotations["molecule_type"] = value + except AttributeError: + pass + try: + self.hit.annotations["molecule_type"] = value + except AttributeError: + pass + + molecule_type = property( + fget=_molecule_type_get, + fset=_molecule_type_set, + doc="molecule type used in the fragment's " + "sequence records and alignment, defaults to None.", + ) + + def _aln_span_get(self): + # length of alignment (gaps included) + # alignment span can be its own attribute, or computed from + # query / hit length + try: + self._aln_span + except AttributeError: + if self.query is not None: + self._aln_span = len(self.query) + elif self.hit is not None: + self._aln_span = len(self.hit) + + return self._aln_span + + def _aln_span_set(self, value): + self._aln_span = value + + aln_span = property( + fget=_aln_span_get, + fset=_aln_span_set, + doc="The number of alignment columns covered by the fragment.", + ) + + # id, description, and features properties # + hit_description = fragcascade("description", "hit", doc="Hit sequence description.") + + query_description = fragcascade( + "description", "query", doc="Query sequence description." + ) + + hit_id = fragcascade("id", "hit", doc="Hit sequence ID.") + + query_id = fragcascade("id", "query", doc="Query sequence ID.") + + hit_features = fragcascade("features", "hit", doc="Hit sequence features.") + + query_features = fragcascade("features", "query", doc="Query sequence features.") + + # strand properties # + def _prep_strand(self, strand): + # follow SeqFeature's convention + if strand not in (-1, 0, 1, None): + raise ValueError("Strand should be -1, 0, 1, or None; not %r" % strand) + return strand + + def _get_strand(self, seq_type): + assert seq_type in ("hit", "query") + strand = getattr(self, "_%s_strand" % seq_type) + + if strand is None: + # try to compute strand from frame + frame = getattr(self, "%s_frame" % seq_type) + if frame is not None: + try: + strand = frame // abs(frame) + except ZeroDivisionError: + strand = 0 + setattr(self, "%s_strand" % seq_type, strand) + + return strand + + def _hit_strand_get(self): + return self._get_strand("hit") + + def _hit_strand_set(self, value): + self._hit_strand = self._prep_strand(value) + + hit_strand = property( + fget=_hit_strand_get, + fset=_hit_strand_set, + doc="Hit sequence strand, defaults to None.", + ) + + def _query_strand_get(self): + return self._get_strand("query") + + def _query_strand_set(self, value): + self._query_strand = self._prep_strand(value) + + query_strand = property( + fget=_query_strand_get, + fset=_query_strand_set, + doc="Query sequence strand, defaults to None.", + ) + + # frame properties # + def _prep_frame(self, frame): + if frame not in (-3, -2, -1, 0, 1, 2, 3, None): + raise ValueError( + "Strand should be an integer between -3 and 3, or None; not %r" % frame + ) + return frame + + def _hit_frame_get(self): + return self._hit_frame + + def _hit_frame_set(self, value): + self._hit_frame = self._prep_frame(value) + + hit_frame = property( + fget=_hit_frame_get, + fset=_hit_frame_set, + doc="Hit sequence reading frame, defaults to None.", + ) + + def _query_frame_get(self): + """Get query sequence reading frame (PRIVATE).""" + return self._query_frame + + def _query_frame_set(self, value): + """Set query sequence reading frame (PRIVATE).""" + self._query_frame = self._prep_frame(value) + + query_frame = property( + fget=_query_frame_get, + fset=_query_frame_set, + doc="Query sequence reading frame, defaults to None.", + ) + + # coordinate properties # + def _prep_coord(self, coord, opp_coord_name, op): + # coord must either be None or int + if coord is None: + return coord + assert isinstance(coord, int) + # try to get opposite coordinate, if it's not present, return + try: + opp_coord = getattr(self, opp_coord_name) + except AttributeError: + return coord + # if opposite coordinate is None, return + if opp_coord is None: + return coord + # otherwise compare it to coord ('>=' or '<=') + else: + assert op(coord, opp_coord) + return coord + + def _hit_start_get(self): + """Get the sequence hit start coordinate (PRIVATE).""" + return self._hit_start + + def _hit_start_set(self, value): + """Set the sequence hit start coordinate (PRIVATE).""" + self._hit_start = self._prep_coord(value, "hit_end", le) + + hit_start = property( + fget=_hit_start_get, + fset=_hit_start_set, + doc="Hit sequence start coordinate, defaults to None.", + ) + + def _query_start_get(self): + """Get the query sequence start coordinate (PRIVATE).""" + return self._query_start + + def _query_start_set(self, value): + """Set the query sequence start coordinate (PRIVATE).""" + self._query_start = self._prep_coord(value, "query_end", le) + + query_start = property( + fget=_query_start_get, + fset=_query_start_set, + doc="Query sequence start coordinate, defaults to None.", + ) + + def _hit_end_get(self): + """Get the hit sequence end coordinate (PRIVATE).""" + return self._hit_end + + def _hit_end_set(self, value): + """Set the hit sequence end coordinate (PRIVATE).""" + self._hit_end = self._prep_coord(value, "hit_start", ge) + + hit_end = property( + fget=_hit_end_get, + fset=_hit_end_set, + doc="Hit sequence end coordinate, defaults to None.", + ) + + def _query_end_get(self): + """Get the query sequence end coordinate (PRIVATE).""" + return self._query_end + + def _query_end_set(self, value): + """Set the query sequence end coordinate (PRIVATE).""" + self._query_end = self._prep_coord(value, "query_start", ge) + + query_end = property( + fget=_query_end_get, + fset=_query_end_set, + doc="Query sequence end coordinate, defaults to None.", + ) + + # coordinate-dependent properties # + def _hit_span_get(self): + """Return the number of residues covered by the hit sequence (PRIVATE).""" + try: + return self.hit_end - self.hit_start + except TypeError: # triggered if any of the coordinates are None + return None + + hit_span = property( + fget=_hit_span_get, doc="The number of residues covered by the hit sequence." + ) + + def _query_span_get(self): + """Return the number or residues covered by the query (PRIVATE).""" + try: + return self.query_end - self.query_start + except TypeError: # triggered if any of the coordinates are None + return None + + query_span = property( + fget=_query_span_get, + doc="The number of residues covered by the query sequence.", + ) + + def _hit_range_get(self): + """Return the start and end of a hit (PRIVATE).""" + return (self.hit_start, self.hit_end) + + hit_range = property( + fget=_hit_range_get, doc="Tuple of hit start and end coordinates." + ) + + def _query_range_get(self): + """Return the start and end of a query (PRIVATE).""" + return (self.query_start, self.query_end) + + query_range = property( + fget=_query_range_get, doc="Tuple of query start and end coordinates." + ) + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/query.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/query.py new file mode 100644 index 0000000000000000000000000000000000000000..b5cc82b0721d661f1c809e2dddc94f3f7ec49196 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_model/query.py @@ -0,0 +1,737 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SearchIO object to model search results from a single query.""" + +from copy import deepcopy +from itertools import chain + +from Bio.SearchIO._utils import optionalcascade + +from ._base import _BaseSearchObject +from .hit import Hit + + +class QueryResult(_BaseSearchObject): + """Class representing search results from a single query. + + QueryResult is the container object that stores all search hits from a + single search query. It is the top-level object returned by SearchIO's two + main functions, ``read`` and ``parse``. Depending on the search results and + search output format, a QueryResult object will contain zero or more Hit + objects (see Hit). + + You can take a quick look at a QueryResult's contents and attributes by + invoking ``print`` on it:: + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> print(qresult) + Program: blastn (2.2.27+) + Query: 33211 (61) + mir_1 + Target: refseq_rna + Hits: ---- ----- ---------------------------------------------------------- + # # HSP ID + description + ---- ----- ---------------------------------------------------------- + 0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52... + 1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA... + 2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ... + 3 2 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA... + 4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA... + 5 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52... + 6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51... + 7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA... + 8 1 gi|262205451|ref|NR_030222.1| Homo sapiens microRNA 51... + 9 2 gi|301171447|ref|NR_035871.1| Pan troglodytes microRNA... + 10 1 gi|301171276|ref|NR_035852.1| Pan troglodytes microRNA... + 11 1 gi|262205290|ref|NR_030188.1| Homo sapiens microRNA 51... + ... + + If you just want to know how many hits a QueryResult has, you can invoke + ``len`` on it. Alternatively, you can simply type its name in the interpreter:: + + >>> len(qresult) + 100 + >>> qresult + QueryResult(id='33211', 100 hits) + + QueryResult behaves like a hybrid of Python's built-in list and dictionary. + You can retrieve its items (Hit objects) using the integer index of the + item, just like regular Python lists:: + + >>> first_hit = qresult[0] + >>> first_hit + Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps) + + You can slice QueryResult objects as well. Slicing will return a new + QueryResult object containing only the sliced hits:: + + >>> sliced_qresult = qresult[:3] # slice the first three hits + >>> len(qresult) + 100 + >>> len(sliced_qresult) + 3 + >>> print(sliced_qresult) + Program: blastn (2.2.27+) + Query: 33211 (61) + mir_1 + Target: refseq_rna + Hits: ---- ----- ---------------------------------------------------------- + # # HSP ID + description + ---- ----- ---------------------------------------------------------- + 0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52... + 1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA... + 2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ... + + Like Python dictionaries, you can also retrieve hits using the hit's ID. + This is useful for retrieving hits that you know should exist in a given + search:: + + >>> hit = qresult['gi|262205317|ref|NR_030195.1|'] + >>> hit + Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps) + + You can also replace a Hit in QueryResult with another Hit using either the + integer index or hit key string. Note that the replacing object must be a + Hit that has the same ``query_id`` property as the QueryResult object. + + If you're not sure whether a QueryResult contains a particular hit, you can + use the hit ID to check for membership first:: + + >>> 'gi|262205317|ref|NR_030195.1|' in qresult + True + >>> 'gi|262380031|ref|NR_023426.1|' in qresult + False + + Or, if you just want to know the rank / position of a given hit, you can + use the hit ID as an argument for the ``index`` method. Note that the values + returned will be zero-based. So zero (0) means the hit is the first in the + QueryResult, three (3) means the hit is the fourth item, and so on. If the + hit does not exist in the QueryResult, a ``ValueError`` will be raised. + + >>> qresult.index('gi|262205317|ref|NR_030195.1|') + 0 + >>> qresult.index('gi|262205330|ref|NR_030198.1|') + 5 + >>> qresult.index('gi|262380031|ref|NR_023426.1|') + Traceback (most recent call last): + ... + ValueError: ... + + To ease working with a large number of hits, QueryResult has several + ``filter`` and ``map`` methods, analogous to Python's built-in functions with + the same names. There are ``filter`` and ``map`` methods available for + operations over both Hit objects or HSP objects. As an example, here we are + using the ``hit_map`` method to rename all hit IDs within a QueryResult:: + + >>> def renamer(hit): + ... hit.id = hit.id.split('|')[3] + ... return hit + >>> mapped_qresult = qresult.hit_map(renamer) + >>> print(mapped_qresult) + Program: blastn (2.2.27+) + Query: 33211 (61) + mir_1 + Target: refseq_rna + Hits: ---- ----- ---------------------------------------------------------- + # # HSP ID + description + ---- ----- ---------------------------------------------------------- + 0 1 NR_030195.1 Homo sapiens microRNA 520b (MIR520B), micr... + 1 1 NR_035856.1 Pan troglodytes microRNA mir-520b (MIR520B... + 2 1 NR_032573.1 Macaca mulatta microRNA mir-519a (MIR519A)... + ... + + The principle for other ``map`` and ``filter`` methods are similar: they accept + a function, applies it, and returns a new QueryResult object. + + There are also other methods useful for working with list-like objects: + ``append``, ``pop``, and ``sort``. More details and examples are available in + their respective documentations. + + Finally, just like Python lists and dictionaries, QueryResult objects are + iterable. Iteration over QueryResults will yield Hit objects:: + + >>> for hit in qresult[:4]: # iterate over the first four items + ... hit + ... + Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps) + Hit(id='gi|301171311|ref|NR_035856.1|', query_id='33211', 1 hsps) + Hit(id='gi|270133242|ref|NR_032573.1|', query_id='33211', 1 hsps) + Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps) + + If you need access to all the hits in a QueryResult object, you can get + them in a list using the ``hits`` property. Similarly, access to all hit IDs is + available through the ``hit_keys`` property. + + >>> qresult.hits + [Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps), ...] + >>> qresult.hit_keys + ['gi|262205317|ref|NR_030195.1|', 'gi|301171311|ref|NR_035856.1|', ...] + + """ + + # attributes we don't want to transfer when creating a new QueryResult class + # from this one + _NON_STICKY_ATTRS = ("_items", "__alt_hit_ids") + + def __init__(self, hits=(), id=None, hit_key_function=None): + """Initialize a QueryResult object. + + :param id: query sequence ID + :type id: string + :param hits: iterator yielding Hit objects + :type hits: iterable + :param hit_key_function: function to define hit keys + :type hit_key_function: callable, accepts Hit objects, returns string + + """ + # default values + self._id = id + self._hit_key_function = hit_key_function or _hit_key_func + self._items = {} + self._description = None + self.__alt_hit_ids = {} + self.program = "" + self.target = "" + self.version = "" + + # validate Hit objects and fill up self._items + for hit in hits: + # validation is handled by __setitem__ + self.append(hit) + + def __iter__(self): + """Iterate over hits.""" + return iter(self.hits) + + @property + def hits(self): + """Hit objects contained in the QueryResult.""" + return list(self._items.values()) + + @property + def hit_keys(self): + """Hit IDs of the Hit objects contained in the QueryResult.""" + return list(self._items.keys()) + + @property + def items(self): + """List of tuples of Hit IDs and Hit objects.""" + return list(self._items.items()) + + def iterhits(self): + """Return an iterator over the Hit objects.""" + yield from self._items.values() + + def iterhit_keys(self): + """Return an iterator over the ID of the Hit objects.""" + yield from self._items + + def iteritems(self): + """Return an iterator yielding tuples of Hit ID and Hit objects.""" + yield from self._items.items() + + def __contains__(self, hit_key): + """Return True if hit key in items or alternative hit identifiers.""" + if isinstance(hit_key, Hit): + return self._hit_key_function(hit_key) in self._items + return hit_key in self._items or hit_key in self.__alt_hit_ids + + def __len__(self): + """Return the number of items.""" + return len(self._items) + + def __bool__(self): + """Return True if there are items.""" + return bool(self._items) + + def __repr__(self): + """Return string representation of the QueryResult object.""" + return "QueryResult(id=%r, %r hits)" % (self.id, len(self)) + + def __str__(self): + """Return a human readable summary of the QueryResult object.""" + lines = [] + + # set program and version line + lines.append("Program: %s (%s)" % (self.program, self.version)) + + # set query id line + qid_line = " Query: %s" % self.id + try: + seq_len = self.seq_len + except AttributeError: + pass + else: + qid_line += " (%i)" % seq_len + lines.append(qid_line) + if self.description: + line = " %s" % self.description + line = line[:77] + "..." if len(line) > 80 else line + lines.append(line) + + # set target line + lines.append(" Target: %s" % self.target) + + # set hit lines + if not self.hits: + lines.append(" Hits: 0") + else: + lines.append(" Hits: %s %s %s" % ("-" * 4, "-" * 5, "-" * 58)) + pattern = "%13s %5s %s" + lines.append(pattern % ("#", "# HSP", "ID + description")) + lines.append(pattern % ("-" * 4, "-" * 5, "-" * 58)) + for idx, hit in enumerate(self.hits): + if idx < 30: + hid_line = "%s %s" % (hit.id, hit.description) + if len(hid_line) > 58: + hid_line = hid_line[:55] + "..." + lines.append(pattern % (idx, len(hit), hid_line)) + elif idx > len(self.hits) - 4: + hid_line = "%s %s" % (hit.id, hit.description) + if len(hid_line) > 58: + hid_line = hid_line[:55] + "..." + lines.append(pattern % (idx, len(hit), hid_line)) + elif idx == 30: + lines.append("%14s" % "~~~") + + return "\n".join(lines) + + def __getitem__(self, hit_key): + """Return a QueryResult object that matches the hit_key.""" + # retrieval using slice objects returns another QueryResult object + if isinstance(hit_key, slice): + # should we return just a list of Hits instead of a full blown + # QueryResult object if it's a slice? + hits = list(self.hits)[hit_key] + obj = self.__class__(hits, self.id, self._hit_key_function) + self._transfer_attrs(obj) + return obj + + # if key is an int, then retrieve the Hit at the int index + elif isinstance(hit_key, int): + length = len(self) + if 0 <= hit_key < length: + for idx, item in enumerate(self.iterhits()): + if idx == hit_key: + return item + elif -1 * length <= hit_key < 0: + for idx, item in enumerate(self.iterhits()): + if length + hit_key == idx: + return item + raise IndexError("list index out of range") + + # if key is a string, then do a regular dictionary retrieval + # falling back on alternative hit IDs + try: + return self._items[hit_key] + except KeyError: + return self._items[self.__alt_hit_ids[hit_key]] + + def __setitem__(self, hit_key, hit): + """Add an item of key hit_key and value hit.""" + # only accept string keys + if not isinstance(hit_key, str): + raise TypeError("QueryResult object keys must be a string.") + # hit must be a Hit object + if not isinstance(hit, Hit): + raise TypeError("QueryResult objects can only contain Hit objects.") + qid = self.id + hqid = hit.query_id + # and it must have the same query ID as this object's ID + # unless it's the query ID is None (default for empty objects), in which + # case we want to use the hit's query ID as the query ID + if qid is not None: + if hqid != qid: + raise ValueError( + "Expected Hit with query ID %r, found %r instead." % (qid, hqid) + ) + else: + self.id = hqid + # same thing with descriptions + qdesc = self.description + hqdesc = hit.query_description + if qdesc is not None: + if hqdesc != qdesc: + raise ValueError( + "Expected Hit with query description %r, found %r instead." + % (qdesc, hqdesc) + ) + else: + self.description = hqdesc + + # remove existing alt_id references, if hit_key already exists + if hit_key in self._items: + for alt_key in self._items[hit_key].id_all[1:]: + del self.__alt_hit_ids[alt_key] + + # if hit_key is already present as an alternative ID + # delete it from the alternative ID dict + if hit_key in self.__alt_hit_ids: + del self.__alt_hit_ids[hit_key] + + self._items[hit_key] = hit + for alt_id in hit.id_all[1:]: + self.__alt_hit_ids[alt_id] = hit_key + + def __delitem__(self, hit_key): + """Delete item of key hit_key.""" + # if hit_key an integer or slice, get the corresponding key first + # and put it into a list + if isinstance(hit_key, int): + hit_keys = [list(self.hit_keys)[hit_key]] + # the same, if it's a slice + elif isinstance(hit_key, slice): + hit_keys = list(self.hit_keys)[hit_key] + # otherwise put it in a list + else: + hit_keys = [hit_key] + + for key in hit_keys: + deleted = False + if key in self._items: + del self._items[key] + deleted = True + if key in self.__alt_hit_ids: + del self._items[self.__alt_hit_ids[key]] + del self.__alt_hit_ids[key] + deleted = True + if not deleted: + raise KeyError(repr(key)) + + # properties # + id = optionalcascade("_id", "query_id", """QueryResult ID string""") + description = optionalcascade( + "_description", "query_description", """QueryResult description""" + ) + + @property + def hsps(self): + """Access the HSP objects contained in the QueryResult.""" + return sorted( + (hsp for hsp in chain(*self.hits)), key=lambda hsp: hsp.output_index + ) + + @property + def fragments(self): + """Access the HSPFragment objects contained in the QueryResult.""" + return list(chain(*self.hsps)) + + # public methods # + def absorb(self, hit): + """Add a Hit object to the end of QueryResult. + + If the QueryResult already has a Hit with the same ID, append the new + Hit's HSPs into the existing Hit. + + :param hit: object to absorb + :type hit: Hit + + This method is used for file formats that may output the same Hit in + separate places, such as BLAT or Exonerate. In both formats, Hit + with different strands are put in different places. However, SearchIO + considers them to be the same as a Hit object should be all database + entries with the same ID, regardless of strand orientation. + + """ + try: + self.append(hit) + except ValueError: + assert hit.id in self + for hsp in hit: + self[hit.id].append(hsp) + + def append(self, hit): + """Add a Hit object to the end of QueryResult. + + :param hit: object to append + :type hit: Hit + + Any Hit object appended must have the same ``query_id`` property as the + QueryResult's ``id`` property. If the hit key already exists, a + ``ValueError`` will be raised. + + """ + # if a custom hit_key_function is supplied, use it to define th hit key + if self._hit_key_function is not None: + hit_key = self._hit_key_function(hit) + else: + hit_key = hit.id + + if hit_key not in self and all(pid not in self for pid in hit.id_all[1:]): + self[hit_key] = hit + else: + raise ValueError( + "The ID or alternative IDs of Hit %r exists in this QueryResult." + % hit_key + ) + + def hit_filter(self, func=None): + """Create new QueryResult object whose Hit objects pass the filter function. + + :param func: filter function + :type func: callable, accepts Hit, returns bool + + Here is an example of using ``hit_filter`` to select Hits whose + description begins with the string 'Homo sapiens', case sensitive:: + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> def desc_filter(hit): + ... return hit.description.startswith('Homo sapiens') + ... + >>> len(qresult) + 100 + >>> filtered = qresult.hit_filter(desc_filter) + >>> len(filtered) + 39 + >>> print(filtered[:4]) + Program: blastn (2.2.27+) + Query: 33211 (61) + mir_1 + Target: refseq_rna + Hits: ---- ----- ---------------------------------------------------------- + # # HSP ID + description + ---- ----- ---------------------------------------------------------- + 0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52... + 1 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52... + 2 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51... + 3 1 gi|262205451|ref|NR_030222.1| Homo sapiens microRNA 51... + + Note that instance attributes (other than the hits) from the unfiltered + QueryResult are retained in the filtered object. + + >>> qresult.program == filtered.program + True + >>> qresult.target == filtered.target + True + + """ + hits = list(filter(func, self.hits)) + obj = self.__class__(hits, self.id, self._hit_key_function) + self._transfer_attrs(obj) + return obj + + def hit_map(self, func=None): + """Create new QueryResult object, mapping the given function to its Hits. + + :param func: map function + :type func: callable, accepts Hit, returns Hit + + Here is an example of using ``hit_map`` with a function that discards all + HSPs in a Hit except for the first one:: + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> print(qresult[:8]) + Program: blastn (2.2.27+) + Query: 33211 (61) + mir_1 + Target: refseq_rna + Hits: ---- ----- ---------------------------------------------------------- + # # HSP ID + description + ---- ----- ---------------------------------------------------------- + 0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52... + 1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA... + 2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ... + 3 2 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA... + 4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA... + 5 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52... + 6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51... + 7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA... + + >>> top_hsp = lambda hit: hit[:1] + >>> mapped_qresult = qresult.hit_map(top_hsp) + >>> print(mapped_qresult[:8]) + Program: blastn (2.2.27+) + Query: 33211 (61) + mir_1 + Target: refseq_rna + Hits: ---- ----- ---------------------------------------------------------- + # # HSP ID + description + ---- ----- ---------------------------------------------------------- + 0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52... + 1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA... + 2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ... + 3 1 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA... + 4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA... + 5 1 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52... + 6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51... + 7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA... + + """ + hits = [deepcopy(hit) for hit in self.hits] + if func is not None: + hits = [func(x) for x in hits] + obj = self.__class__(hits, self.id, self._hit_key_function) + self._transfer_attrs(obj) + return obj + + def hsp_filter(self, func=None): + """Create new QueryResult object whose HSP objects pass the filter function. + + ``hsp_filter`` is the same as ``hit_filter``, except that it filters + directly on each HSP object in every Hit. If the filtering removes + all HSP objects in a given Hit, the entire Hit will be discarded. This + will result in the QueryResult having less Hit after filtering. + """ + hits = [x for x in (hit.filter(func) for hit in self.hits) if x] + obj = self.__class__(hits, self.id, self._hit_key_function) + self._transfer_attrs(obj) + return obj + + def hsp_map(self, func=None): + """Create new QueryResult object, mapping the given function to its HSPs. + + ``hsp_map`` is the same as ``hit_map``, except that it applies the given + function to all HSP objects in every Hit, instead of the Hit objects. + """ + hits = [x for x in (hit.map(func) for hit in list(self.hits)[:]) if x] + obj = self.__class__(hits, self.id, self._hit_key_function) + self._transfer_attrs(obj) + return obj + + # marker for default self.pop() return value + # this method is adapted from Python's built in OrderedDict.pop + # implementation + __marker = object() + + def pop(self, hit_key=-1, default=__marker): + """Remove the specified hit key and return the Hit object. + + :param hit_key: key of the Hit object to return + :type hit_key: int or string + :param default: return value if no Hit exists with the given key + :type default: object + + By default, ``pop`` will remove and return the last Hit object in the + QueryResult object. To remove specific Hit objects, you can use its + integer index or hit key. + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> len(qresult) + 100 + >>> for hit in qresult[:5]: + ... print(hit.id) + ... + gi|262205317|ref|NR_030195.1| + gi|301171311|ref|NR_035856.1| + gi|270133242|ref|NR_032573.1| + gi|301171322|ref|NR_035857.1| + gi|301171267|ref|NR_035851.1| + + # remove the last hit + >>> qresult.pop() + Hit(id='gi|397513516|ref|XM_003827011.1|', query_id='33211', 1 hsps) + + # remove the first hit + >>> qresult.pop(0) + Hit(id='gi|262205317|ref|NR_030195.1|', query_id='33211', 1 hsps) + + # remove hit with the given ID + >>> qresult.pop('gi|301171322|ref|NR_035857.1|') + Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps) + + """ + # if key is an integer (index) + # get the ID for the Hit object at that index + if isinstance(hit_key, int): + # raise the appropriate error if there is no hit + if not self: + raise IndexError("pop from empty list") + hit_key = list(self.hit_keys)[hit_key] + + try: + hit = self._items.pop(hit_key) + # remove all alternative IDs of the popped hit + for alt_id in hit.id_all[1:]: + self.__alt_hit_ids.pop(alt_id, None) + except KeyError: + try: + hit = self.pop(self.__alt_hit_ids[hit_key]) + except KeyError: + # hit_key is not a valid id + # use the default if it has been set + if default is not self.__marker: + hit = default + else: + raise KeyError(hit_key) from None + return hit + + def index(self, hit_key): + """Return the index of a given hit key, zero-based. + + :param hit_key: hit ID + :type hit_key: string + + This method is useful for finding out the integer index (usually + correlated with search rank) of a given hit key. + + >>> from Bio import SearchIO + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> qresult.index('gi|301171259|ref|NR_035850.1|') + 7 + + """ + if isinstance(hit_key, Hit): + return list(self.hit_keys).index(hit_key.id) + try: + return list(self.hit_keys).index(hit_key) + except ValueError: + if hit_key in self.__alt_hit_ids: + return self.index(self.__alt_hit_ids[hit_key]) + raise + + def sort(self, key=None, reverse=False, in_place=True): + """Sort the Hit objects. + + :param key: sorting function + :type key: callable, accepts Hit, returns key for sorting + :param reverse: whether to reverse sorting results or no + :type reverse: bool + :param in_place: whether to do in-place sorting or no + :type in_place: bool + + ``sort`` defaults to sorting in-place, to mimic Python's ``list.sort`` + method. If you set the ``in_place`` argument to False, it will treat + return a new, sorted QueryResult object and keep the initial one + unsorted. + + """ + if key is None: + # if reverse is True, reverse the hits + if reverse: + sorted_hits = list(self.hits)[::-1] + # otherwise (default options) make a copy of the hits + else: + sorted_hits = list(self.hits)[:] + else: + sorted_hits = sorted(self.hits, key=key, reverse=reverse) + + # if sorting is in-place, don't create a new QueryResult object + if in_place: + self._items = {self._hit_key_function(hit): hit for hit in sorted_hits} + # otherwise, return a new sorted QueryResult object + else: + obj = self.__class__(sorted_hits, self.id, self._hit_key_function) + self._transfer_attrs(obj) + return obj + + +def _hit_key_func(hit): + """Map hit to its identifier (PRIVATE). + + Default hit key function for QueryResult.__init__ use. + """ + return hit.id + + +# if not used as a module, run the doctest +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_utils.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..83840426c768f65e2f7ded367d9d5f98fce97685 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SearchIO/_utils.py @@ -0,0 +1,169 @@ +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Common SearchIO utility functions.""" + +import sys + + +def getattr_str(obj, attr, fmt=None, fallback="?"): + """Return string of the given object's attribute. + + Defaults to the given fallback value if attribute is not present. + """ + try: + value = getattr(obj, attr) + except AttributeError: + return fallback + if fmt is None: + return str(value) + return fmt % value + + +def read_forward(handle): + """Read through whitespaces, return the first non-whitespace line.""" + while True: + line = handle.readline() + # if line is empty or line has characters and stripping does not remove + # them, return the line + if (not line) or (line and line.strip()): + return line + + +def get_processor(format, mapping): + """Return the object to process the given format according to the mapping. + + :param format: format name + :type format: string, lower case + :param mapping: mapping of format name and its processor object + :type mapping: dictionary {string: object} + + """ + # map file format to iterator name + try: + obj_info = mapping[format] + except KeyError: + # handle the errors with helpful messages + if format is None: + raise ValueError("Format required (lower case string)") from None + elif not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") from None + elif format != format.lower(): + raise ValueError("Format string %r should be lower case" % format) from None + else: + raise ValueError( + "Unknown format %r. Supported formats are %r" + % (format, "', '".join(mapping)) + ) from None + + mod_name, obj_name = obj_info + mod = __import__("Bio.SearchIO.%s" % mod_name, fromlist=[""]) + + return getattr(mod, obj_name) + + +def singleitem(attr=None, doc=""): + """Property for fetching attribute from first entry of container. + + Returns a property that fetches the given attribute from + the first item in a SearchIO container object. + """ + + def getter(self): + if len(self._items) > 1: + raise ValueError("More than one HSPFragment objects found in HSP") + if attr is None: + return self._items[0] + return getattr(self._items[0], attr) + + return property(fget=getter, doc=doc) + + +def allitems(attr=None, doc=""): + """Property for fetching attribute from all entries of container. + + Returns a property that fetches the given attributes from + all items in a SearchIO container object. + """ + + def getter(self): + if attr is None: + return self._items + return [getattr(frag, attr) for frag in self._items] + + return property(fget=getter, doc=doc) + + +def fullcascade(attr, doc=""): + """Return a getter property with a cascading setter. + + This is similar to ``optionalcascade``, but for SearchIO containers that have + at least one item (HSP). The getter always retrieves the attribute + value from the first item. If the items have more than one attribute values, + an error will be raised. The setter behaves like ``partialcascade``, except + that it only sets attributes to items in the object, not the object itself. + + """ + + def getter(self): + return getattr(self._items[0], attr) + + def setter(self, value): + for item in self: + setattr(item, attr, value) + + return property(fget=getter, fset=setter, doc=doc) + + +def optionalcascade(cont_attr, item_attr, doc=""): + """Return a getter property with a cascading setter. + + This is used for the ``id`` and ``description`` properties of the container + objects with zero or more items. These items have their own private + attributes that stores query and/or hit ID and description. When the + container has zero items, attribute values are always retrieved from the + container's attribute. Otherwise, the first item's attribute is used. + + To keep the container items' query and/or hit ID and description in-sync, + the setter cascades any new value given to the items' values. + + """ + + def getter(self): + if self._items: + # don't use self._items here, so QueryResult can use this property + # as well (the underlying dict is not integer-indexable) + return getattr(self[0], item_attr) + else: + return getattr(self, cont_attr) + + def setter(self, value): + setattr(self, cont_attr, value) + for item in self: + setattr(item, item_attr, value) + + return property(fget=getter, fset=setter, doc=doc) + + +def fragcascade(attr, seq_type, doc=""): + """Return a getter property with cascading setter, for HSPFragment objects. + + Similar to ``partialcascade``, but for HSPFragment objects and acts on ``query`` + or ``hit`` properties of the object if they are not None. + + """ + assert seq_type in ("hit", "query") + attr_name = f"_{seq_type}_{attr}" + + def getter(self): + return getattr(self, attr_name) + + def setter(self, value): + setattr(self, attr_name, value) + seq = getattr(self, seq_type) + if seq is not None: + setattr(seq, attr, value) + + return property(fget=getter, fset=setter, doc=doc) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Seq.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Seq.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7b78d1f681118326336ab5f2bfb8c498cb7f9f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Seq.py @@ -0,0 +1,3278 @@ +# Copyright 2000 Andrew Dalke. +# Copyright 2000-2002 Brad Chapman. +# Copyright 2004-2005, 2010 by M de Hoon. +# Copyright 2007-2023 by Peter Cock. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Provide objects to represent biological sequences. + +See also the Seq_ wiki and the chapter in our Tutorial_. + +.. _Seq: http://biopython.org/wiki/Seq +.. _Tutorial: https://biopython.org/docs/latest/Tutorial/index.html + +""" + +import collections +import numbers +import warnings +from abc import ABC +from abc import abstractmethod +from typing import Optional +from typing import overload +from typing import Union + +from Bio import BiopythonWarning +from Bio.Data import CodonTable +from Bio.Data import IUPACData + + +def _maketrans(complement_mapping): + """Make a python string translation table (PRIVATE). + + Arguments: + - complement_mapping - a dictionary such as ambiguous_dna_complement + and ambiguous_rna_complement from Data.IUPACData. + + Returns a translation table (a bytes object of length 256) for use with + the python string's translate method to use in a (reverse) complement. + + Compatible with lower case and upper case sequences. + + For internal use only. + """ + keys = "".join(complement_mapping.keys()).encode("ASCII") + values = "".join(complement_mapping.values()).encode("ASCII") + return bytes.maketrans(keys + keys.lower(), values + values.lower()) + + +ambiguous_dna_complement = dict(IUPACData.ambiguous_dna_complement) +ambiguous_dna_complement["U"] = ambiguous_dna_complement["T"] +_dna_complement_table = _maketrans(ambiguous_dna_complement) +del ambiguous_dna_complement +ambiguous_rna_complement = dict(IUPACData.ambiguous_rna_complement) +ambiguous_rna_complement["T"] = ambiguous_rna_complement["U"] +_rna_complement_table = _maketrans(ambiguous_rna_complement) +del ambiguous_rna_complement + + +class SequenceDataAbstractBaseClass(ABC): + """Abstract base class for sequence content providers. + + Most users will not need to use this class. It is used internally as a base + class for sequence content provider classes such as _UndefinedSequenceData + defined in this module, and _TwoBitSequenceData in Bio.SeqIO.TwoBitIO. + Instances of these classes can be used instead of a ``bytes`` object as the + data argument when creating a Seq object, and provide the sequence content + only when requested via ``__getitem__``. This allows lazy parsers to load + and parse sequence data from a file only for the requested sequence regions, + and _UndefinedSequenceData instances to raise an exception when undefined + sequence data are requested. + + Future implementations of lazy parsers that similarly provide on-demand + parsing of sequence data should use a subclass of this abstract class and + implement the abstract methods ``__len__`` and ``__getitem__``: + + * ``__len__`` must return the sequence length; + * ``__getitem__`` must return + + * a ``bytes`` object for the requested region; or + * a new instance of the subclass for the requested region; or + * raise an ``UndefinedSequenceError``. + + Calling ``__getitem__`` for a sequence region of size zero should always + return an empty ``bytes`` object. + Calling ``__getitem__`` for the full sequence (as in data[:]) should + either return a ``bytes`` object with the full sequence, or raise an + ``UndefinedSequenceError``. + + Subclasses of SequenceDataAbstractBaseClass must call ``super().__init__()`` + as part of their ``__init__`` method. + """ + + __slots__ = () + + def __init__(self): + """Check if ``__getitem__`` returns a bytes-like object.""" + assert self[:0] == b"" + + @abstractmethod + def __len__(self): + pass + + @abstractmethod + def __getitem__(self, key): + pass + + def __bytes__(self): + return self[:] + + def __hash__(self): + return hash(bytes(self)) + + def __eq__(self, other): + return bytes(self) == other + + def __lt__(self, other): + return bytes(self) < other + + def __le__(self, other): + return bytes(self) <= other + + def __gt__(self, other): + return bytes(self) > other + + def __ge__(self, other): + return bytes(self) >= other + + def __add__(self, other): + try: + return bytes(self) + bytes(other) + except UndefinedSequenceError: + return NotImplemented + # will be handled by _UndefinedSequenceData.__radd__ or + # by _PartiallyDefinedSequenceData.__radd__ + + def __radd__(self, other): + return other + bytes(self) + + def __mul__(self, other): + return other * bytes(self) + + def __contains__(self, item): + return bytes(self).__contains__(item) + + def decode(self, encoding="utf-8"): + """Decode the data as bytes using the codec registered for encoding. + + encoding + The encoding with which to decode the bytes. + """ + return bytes(self).decode(encoding) + + def count(self, sub, start=None, end=None): + """Return the number of non-overlapping occurrences of sub in data[start:end]. + + Optional arguments start and end are interpreted as in slice notation. + This method behaves as the count method of Python strings. + """ + return bytes(self).count(sub, start, end) + + def find(self, sub, start=None, end=None): + """Return the lowest index in data where subsection sub is found. + + Return the lowest index in data where subsection sub is found, + such that sub is contained within data[start,end]. Optional + arguments start and end are interpreted as in slice notation. + + Return -1 on failure. + """ + return bytes(self).find(sub, start, end) + + def rfind(self, sub, start=None, end=None): + """Return the highest index in data where subsection sub is found. + + Return the highest index in data where subsection sub is found, + such that sub is contained within data[start,end]. Optional + arguments start and end are interpreted as in slice notation. + + Return -1 on failure. + """ + return bytes(self).rfind(sub, start, end) + + def index(self, sub, start=None, end=None): + """Return the lowest index in data where subsection sub is found. + + Return the lowest index in data where subsection sub is found, + such that sub is contained within data[start,end]. Optional + arguments start and end are interpreted as in slice notation. + + Raises ValueError when the subsection is not found. + """ + return bytes(self).index(sub, start, end) + + def rindex(self, sub, start=None, end=None): + """Return the highest index in data where subsection sub is found. + + Return the highest index in data where subsection sub is found, + such that sub is contained within data[start,end]. Optional + arguments start and end are interpreted as in slice notation. + + Raise ValueError when the subsection is not found. + """ + return bytes(self).rindex(sub, start, end) + + def startswith(self, prefix, start=None, end=None): + """Return True if data starts with the specified prefix, False otherwise. + + With optional start, test data beginning at that position. + With optional end, stop comparing data at that position. + prefix can also be a tuple of bytes to try. + """ + return bytes(self).startswith(prefix, start, end) + + def endswith(self, suffix, start=None, end=None): + """Return True if data ends with the specified suffix, False otherwise. + + With optional start, test data beginning at that position. + With optional end, stop comparing data at that position. + suffix can also be a tuple of bytes to try. + """ + return bytes(self).endswith(suffix, start, end) + + def split(self, sep=None, maxsplit=-1): + """Return a list of the sections in the data, using sep as the delimiter. + + sep + The delimiter according which to split the data. + None (the default value) means split on ASCII whitespace characters + (space, tab, return, newline, formfeed, vertical tab). + maxsplit + Maximum number of splits to do. + -1 (the default value) means no limit. + """ + return bytes(self).split(sep, maxsplit) + + def rsplit(self, sep=None, maxsplit=-1): + """Return a list of the sections in the data, using sep as the delimiter. + + sep + The delimiter according which to split the data. + None (the default value) means split on ASCII whitespace characters + (space, tab, return, newline, formfeed, vertical tab). + maxsplit + Maximum number of splits to do. + -1 (the default value) means no limit. + + Splitting is done starting at the end of the data and working to the front. + """ + return bytes(self).rsplit(sep, maxsplit) + + def strip(self, chars=None): + """Strip leading and trailing characters contained in the argument. + + If the argument is omitted or None, strip leading and trailing ASCII whitespace. + """ + return bytes(self).strip(chars) + + def lstrip(self, chars=None): + """Strip leading characters contained in the argument. + + If the argument is omitted or None, strip leading ASCII whitespace. + """ + return bytes(self).lstrip(chars) + + def rstrip(self, chars=None): + """Strip trailing characters contained in the argument. + + If the argument is omitted or None, strip trailing ASCII whitespace. + """ + return bytes(self).rstrip(chars) + + def removeprefix(self, prefix): + """Remove the prefix if present.""" + # Want to do just this, but need Python 3.9+ + # return bytes(self).removeprefix(prefix) + data = bytes(self) + try: + return data.removeprefix(prefix) + except AttributeError: + if data.startswith(prefix): + return data[len(prefix) :] + else: + return data + + def removesuffix(self, suffix): + """Remove the suffix if present.""" + # Want to do just this, but need Python 3.9+ + # return bytes(self).removesuffix(suffix) + data = bytes(self) + try: + return data.removesuffix(suffix) + except AttributeError: + if data.startswith(suffix): + return data[: -len(suffix)] + else: + return data + + def upper(self): + """Return a copy of data with all ASCII characters converted to uppercase.""" + return bytes(self).upper() + + def lower(self): + """Return a copy of data with all ASCII characters converted to lowercase.""" + return bytes(self).lower() + + def isupper(self): + """Return True if all ASCII characters in data are uppercase. + + If there are no cased characters, the method returns False. + """ + return bytes(self).isupper() + + def islower(self): + """Return True if all ASCII characters in data are lowercase. + + If there are no cased characters, the method returns False. + """ + return bytes(self).islower() + + def replace(self, old, new): + """Return a copy with all occurrences of substring old replaced by new.""" + return bytes(self).replace(old, new) + + def translate(self, table, delete=b""): + """Return a copy with each character mapped by the given translation table. + + table + Translation table, which must be a bytes object of length 256. + + All characters occurring in the optional argument delete are removed. + The remaining characters are mapped through the given translation table. + """ + return bytes(self).translate(table, delete) + + @property + def defined(self): + """Return True if the sequence is defined, False if undefined or partially defined. + + Zero-length sequences are always considered to be defined. + """ + return True + + @property + def defined_ranges(self): + """Return a tuple of the ranges where the sequence contents is defined. + + The return value has the format ((start1, end1), (start2, end2), ...). + """ + length = len(self) + if length > 0: + return ((0, length),) + else: + return () + + +class _SeqAbstractBaseClass(ABC): + """Abstract base class for the Seq and MutableSeq classes (PRIVATE). + + Most users will not need to use this class. It is used internally as an + abstract base class for Seq and MutableSeq, as most of their methods are + identical. + """ + + __slots__ = ("_data",) + __array_ufunc__ = None # turn off numpy Ufuncs + + @abstractmethod + def __init__(self): + pass + + def __bytes__(self): + return bytes(self._data) + + def __repr__(self): + """Return (truncated) representation of the sequence.""" + data = self._data + if isinstance(data, _UndefinedSequenceData): + return f"Seq(None, length={len(self)})" + if isinstance(data, _PartiallyDefinedSequenceData): + d = {} + for position, seq in data._data.items(): + if len(seq) > 60: + start = seq[:54].decode("ASCII") + end = seq[-3:].decode("ASCII") + seq = f"{start}...{end}" + else: + seq = seq.decode("ASCII") + d[position] = seq + return "Seq(%r, length=%d)" % (d, len(self)) + if len(data) > 60: + # Shows the last three letters as it is often useful to see if + # there is a stop codon at the end of a sequence. + # Note total length is 54+3+3=60 + start = data[:54].decode("ASCII") + end = data[-3:].decode("ASCII") + return f"{self.__class__.__name__}('{start}...{end}')" + else: + data = data.decode("ASCII") + return f"{self.__class__.__name__}('{data}')" + + def __str__(self): + """Return the full sequence as a python string.""" + return self._data.decode("ASCII") + + def __eq__(self, other): + """Compare the sequence to another sequence or a string. + + Sequences are equal to each other if their sequence contents is + identical: + + >>> from Bio.Seq import Seq, MutableSeq + >>> seq1 = Seq("ACGT") + >>> seq2 = Seq("ACGT") + >>> mutable_seq = MutableSeq("ACGT") + >>> seq1 == seq2 + True + >>> seq1 == mutable_seq + True + >>> seq1 == "ACGT" + True + + Note that the sequence objects themselves are not identical to each + other: + + >>> id(seq1) == id(seq2) + False + >>> seq1 is seq2 + False + + Sequences can also be compared to strings, ``bytes``, and ``bytearray`` + objects: + + >>> seq1 == "ACGT" + True + >>> seq1 == b"ACGT" + True + >>> seq1 == bytearray(b"ACGT") + True + """ + if isinstance(other, _SeqAbstractBaseClass): + return self._data == other._data + elif isinstance(other, str): + return self._data == other.encode("ASCII") + else: + return self._data == other + + def __lt__(self, other): + """Implement the less-than operand.""" + if isinstance(other, _SeqAbstractBaseClass): + return self._data < other._data + elif isinstance(other, str): + return self._data < other.encode("ASCII") + else: + return self._data < other + + def __le__(self, other): + """Implement the less-than or equal operand.""" + if isinstance(other, _SeqAbstractBaseClass): + return self._data <= other._data + elif isinstance(other, str): + return self._data <= other.encode("ASCII") + else: + return self._data <= other + + def __gt__(self, other): + """Implement the greater-than operand.""" + if isinstance(other, _SeqAbstractBaseClass): + return self._data > other._data + elif isinstance(other, str): + return self._data > other.encode("ASCII") + else: + return self._data > other + + def __ge__(self, other): + """Implement the greater-than or equal operand.""" + if isinstance(other, _SeqAbstractBaseClass): + return self._data >= other._data + elif isinstance(other, str): + return self._data >= other.encode("ASCII") + else: + return self._data >= other + + def __len__(self): + """Return the length of the sequence.""" + return len(self._data) + + def __iter__(self): + """Return an iterable of the sequence.""" + return self._data.decode("ASCII").__iter__() + + @overload + def __getitem__(self, index: int) -> str: ... + + @overload + def __getitem__(self, index: slice) -> "Seq": ... + + def __getitem__(self, index): + """Return a subsequence as a single letter or as a sequence object. + + If the index is an integer, a single letter is returned as a Python + string: + + >>> seq = Seq('ACTCGACGTCG') + >>> seq[5] + 'A' + + Otherwise, a new sequence object of the same class is returned: + + >>> seq[5:8] + Seq('ACG') + >>> mutable_seq = MutableSeq('ACTCGACGTCG') + >>> mutable_seq[5:8] + MutableSeq('ACG') + """ + if isinstance(index, numbers.Integral): + # Return a single letter as a string + return chr(self._data[index]) + else: + # Return the (sub)sequence as another Seq/MutableSeq object + return self.__class__(self._data[index]) + + def __add__(self, other): + """Add a sequence or string to this sequence. + + >>> from Bio.Seq import Seq, MutableSeq + >>> Seq("MELKI") + "LV" + Seq('MELKILV') + >>> MutableSeq("MELKI") + "LV" + MutableSeq('MELKILV') + """ + if isinstance(other, _SeqAbstractBaseClass): + return self.__class__(self._data + other._data) + elif isinstance(other, str): + return self.__class__(self._data + other.encode("ASCII")) + else: + # If other is a SeqRecord, then SeqRecord's __radd__ will handle + # this. If not, returning NotImplemented will trigger a TypeError. + return NotImplemented + + def __radd__(self, other): + """Add a sequence string on the left. + + >>> from Bio.Seq import Seq, MutableSeq + >>> "LV" + Seq("MELKI") + Seq('LVMELKI') + >>> "LV" + MutableSeq("MELKI") + MutableSeq('LVMELKI') + + Adding two sequence objects is handled via the __add__ method. + """ + if isinstance(other, str): + return self.__class__(other.encode("ASCII") + self._data) + else: + return NotImplemented + + def __mul__(self, other): + """Multiply sequence by integer. + + >>> from Bio.Seq import Seq, MutableSeq + >>> Seq('ATG') * 2 + Seq('ATGATG') + >>> MutableSeq('ATG') * 2 + MutableSeq('ATGATG') + """ + if not isinstance(other, numbers.Integral): + raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type") + # we would like to simply write + # data = self._data * other + # here, but currently that causes a bug on PyPy if self._data is a + # bytearray and other is a numpy integer. Using this workaround: + data = self._data.__mul__(other) + return self.__class__(data) + + def __rmul__(self, other): + """Multiply integer by sequence. + + >>> from Bio.Seq import Seq + >>> 2 * Seq('ATG') + Seq('ATGATG') + """ + if not isinstance(other, numbers.Integral): + raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type") + # we would like to simply write + # data = self._data * other + # here, but currently that causes a bug on PyPy if self._data is a + # bytearray and other is a numpy integer. Using this workaround: + data = self._data.__mul__(other) + return self.__class__(data) + + def __imul__(self, other): + """Multiply the sequence object by other and assign. + + >>> from Bio.Seq import Seq + >>> seq = Seq('ATG') + >>> seq *= 2 + >>> seq + Seq('ATGATG') + + Note that this is different from in-place multiplication. The ``seq`` + variable is reassigned to the multiplication result, but any variable + pointing to ``seq`` will remain unchanged: + + >>> seq = Seq('ATG') + >>> seq2 = seq + >>> id(seq) == id(seq2) + True + >>> seq *= 2 + >>> seq + Seq('ATGATG') + >>> seq2 + Seq('ATG') + >>> id(seq) == id(seq2) + False + """ + if not isinstance(other, numbers.Integral): + raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type") + # we would like to simply write + # data = self._data * other + # here, but currently that causes a bug on PyPy if self._data is a + # bytearray and other is a numpy integer. Using this workaround: + data = self._data.__mul__(other) + return self.__class__(data) + + def count(self, sub, start=None, end=None): + """Return a non-overlapping count, like that of a python string. + + The number of occurrences of substring argument sub in the + (sub)sequence given by [start:end] is returned as an integer. + Optional arguments start and end are interpreted as in slice + notation. + + Arguments: + - sub - a string or another Seq object to look for + - start - optional integer, slice start + - end - optional integer, slice end + + e.g. + + >>> from Bio.Seq import Seq + >>> my_seq = Seq("AAAATGA") + >>> print(my_seq.count("A")) + 5 + >>> print(my_seq.count("ATG")) + 1 + >>> print(my_seq.count(Seq("AT"))) + 1 + >>> print(my_seq.count("AT", 2, -1)) + 1 + + HOWEVER, please note because the ``count`` method of Seq and MutableSeq + objects, like that of Python strings, do a non-overlapping search, this + may not give the answer you expect: + + >>> "AAAA".count("AA") + 2 + >>> print(Seq("AAAA").count("AA")) + 2 + + For an overlapping search, use the ``count_overlap`` method: + + >>> print(Seq("AAAA").count_overlap("AA")) + 3 + """ + if isinstance(sub, MutableSeq): + sub = sub._data + elif isinstance(sub, Seq): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, (bytes, bytearray)): + raise TypeError( + "a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % type(sub) + ) + return self._data.count(sub, start, end) + + def count_overlap(self, sub, start=None, end=None): + """Return an overlapping count. + + Returns an integer, the number of occurrences of substring + argument sub in the (sub)sequence given by [start:end]. + Optional arguments start and end are interpreted as in slice + notation. + + Arguments: + - sub - a string or another Seq object to look for + - start - optional integer, slice start + - end - optional integer, slice end + + e.g. + + >>> from Bio.Seq import Seq + >>> print(Seq("AAAA").count_overlap("AA")) + 3 + >>> print(Seq("ATATATATA").count_overlap("ATA")) + 4 + >>> print(Seq("ATATATATA").count_overlap("ATA", 3, -1)) + 1 + + For a non-overlapping search, use the ``count`` method: + + >>> print(Seq("AAAA").count("AA")) + 2 + + Where substrings do not overlap, ``count_overlap`` behaves the same as + the ``count`` method: + + >>> from Bio.Seq import Seq + >>> my_seq = Seq("AAAATGA") + >>> print(my_seq.count_overlap("A")) + 5 + >>> my_seq.count_overlap("A") == my_seq.count("A") + True + >>> print(my_seq.count_overlap("ATG")) + 1 + >>> my_seq.count_overlap("ATG") == my_seq.count("ATG") + True + >>> print(my_seq.count_overlap(Seq("AT"))) + 1 + >>> my_seq.count_overlap(Seq("AT")) == my_seq.count(Seq("AT")) + True + >>> print(my_seq.count_overlap("AT", 2, -1)) + 1 + >>> my_seq.count_overlap("AT", 2, -1) == my_seq.count("AT", 2, -1) + True + + HOWEVER, do not use this method for such cases because the + count() method is much for efficient. + """ + if isinstance(sub, MutableSeq): + sub = sub._data + elif isinstance(sub, Seq): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, (bytes, bytearray)): + raise TypeError( + "a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % type(sub) + ) + data = self._data + overlap_count = 0 + while True: + start = data.find(sub, start, end) + 1 + if start != 0: + overlap_count += 1 + else: + return overlap_count + + def __contains__(self, item): + """Return True if item is a subsequence of the sequence, and False otherwise. + + e.g. + + >>> from Bio.Seq import Seq, MutableSeq + >>> my_dna = Seq("ATATGAAATTTGAAAA") + >>> "AAA" in my_dna + True + >>> Seq("AAA") in my_dna + True + >>> MutableSeq("AAA") in my_dna + True + """ + if isinstance(item, _SeqAbstractBaseClass): + item = bytes(item) + elif isinstance(item, str): + item = item.encode("ASCII") + return item in self._data + + def find(self, sub, start=None, end=None): + """Return the lowest index in the sequence where subsequence sub is found. + + With optional arguments start and end, return the lowest index in the + sequence such that the subsequence sub is contained within the sequence + region [start:end]. + + Arguments: + - sub - a string or another Seq or MutableSeq object to search for + - start - optional integer, slice start + - end - optional integer, slice end + + Returns -1 if the subsequence is NOT found. + + e.g. Locating the first typical start codon, AUG, in an RNA sequence: + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_rna.find("AUG") + 3 + + The next typical start codon can then be found by starting the search + at position 4: + + >>> my_rna.find("AUG", 4) + 15 + + See the ``search`` method to find the locations of multiple subsequences + at the same time. + """ + if isinstance(sub, _SeqAbstractBaseClass): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, (bytes, bytearray)): + raise TypeError( + "a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % type(sub) + ) + return self._data.find(sub, start, end) + + def rfind(self, sub, start=None, end=None): + """Return the highest index in the sequence where subsequence sub is found. + + With optional arguments start and end, return the highest index in the + sequence such that the subsequence sub is contained within the sequence + region [start:end]. + + Arguments: + - sub - a string or another Seq or MutableSeq object to search for + - start - optional integer, slice start + - end - optional integer, slice end + + Returns -1 if the subsequence is NOT found. + + e.g. Locating the last typical start codon, AUG, in an RNA sequence: + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_rna.rfind("AUG") + 15 + + The location of the typical start codon before that can be found by + ending the search at position 15: + + >>> my_rna.rfind("AUG", end=15) + 3 + + See the ``search`` method to find the locations of multiple subsequences + at the same time. + """ + if isinstance(sub, _SeqAbstractBaseClass): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, (bytes, bytearray)): + raise TypeError( + "a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % type(sub) + ) + return self._data.rfind(sub, start, end) + + def index(self, sub, start=None, end=None): + """Return the lowest index in the sequence where subsequence sub is found. + + With optional arguments start and end, return the lowest index in the + sequence such that the subsequence sub is contained within the sequence + region [start:end]. + + Arguments: + - sub - a string or another Seq or MutableSeq object to search for + - start - optional integer, slice start + - end - optional integer, slice end + + Raises a ValueError if the subsequence is NOT found. + + e.g. Locating the first typical start codon, AUG, in an RNA sequence: + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_rna.index("AUG") + 3 + + The next typical start codon can then be found by starting the search + at position 4: + + >>> my_rna.index("AUG", 4) + 15 + + This method performs the same search as the ``find`` method. However, + if the subsequence is not found, ``find`` returns -1 while ``index`` + raises a ValueError: + + >>> my_rna.index("T") + Traceback (most recent call last): + ... + ValueError: ... + >>> my_rna.find("T") + -1 + + See the ``search`` method to find the locations of multiple subsequences + at the same time. + """ + if isinstance(sub, MutableSeq): + sub = sub._data + elif isinstance(sub, Seq): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, (bytes, bytearray)): + raise TypeError( + "a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % type(sub) + ) + return self._data.index(sub, start, end) + + def rindex(self, sub, start=None, end=None): + """Return the highest index in the sequence where subsequence sub is found. + + With optional arguments start and end, return the highest index in the + sequence such that the subsequence sub is contained within the sequence + region [start:end]. + + Arguments: + - sub - a string or another Seq or MutableSeq object to search for + - start - optional integer, slice start + - end - optional integer, slice end + + Returns -1 if the subsequence is NOT found. + + e.g. Locating the last typical start codon, AUG, in an RNA sequence: + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_rna.rindex("AUG") + 15 + + The location of the typical start codon before that can be found by + ending the search at position 15: + + >>> my_rna.rindex("AUG", end=15) + 3 + + This method performs the same search as the ``rfind`` method. However, + if the subsequence is not found, ``rfind`` returns -1 which ``rindex`` + raises a ValueError: + + >>> my_rna.rindex("T") + Traceback (most recent call last): + ... + ValueError: ... + >>> my_rna.rfind("T") + -1 + + See the ``search`` method to find the locations of multiple subsequences + at the same time. + """ + if isinstance(sub, MutableSeq): + sub = sub._data + elif isinstance(sub, Seq): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, (bytes, bytearray)): + raise TypeError( + "a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % type(sub) + ) + return self._data.rindex(sub, start, end) + + def search(self, subs): + """Search the substrings subs in self and yield the index and substring found. + + Arguments: + - subs - a list of strings, Seq, MutableSeq, bytes, or bytearray + objects containing the substrings to search for. + + >>> from Bio.Seq import Seq + >>> dna = Seq("GTCATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAGTTG") + >>> matches = dna.search(["CC", Seq("ATTG"), "ATTG", Seq("CCC")]) + >>> for index, substring in matches: + ... print(index, substring) + ... + 7 CC + 9 ATTG + 20 CC + 34 CC + 34 CCC + 35 CC + """ + subdict = collections.defaultdict(set) + for index, sub in enumerate(subs): + if isinstance(sub, (_SeqAbstractBaseClass, bytearray)): + sub = bytes(sub) + elif isinstance(sub, str): + sub = sub.encode("ASCII") + elif not isinstance(sub, bytes): + raise TypeError( + "subs[%d]: a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'" + % (index, type(sub)) + ) + length = len(sub) + subdict[length].add(sub) + for start in range(len(self) - 1): + for length, subs in subdict.items(): + stop = start + length + for sub in subs: + if self._data[start:stop] == sub: + yield (start, sub.decode()) + break + + def startswith(self, prefix, start=None, end=None): + """Return True if the sequence starts with the given prefix, False otherwise. + + Return True if the sequence starts with the specified prefix + (a string or another Seq object), False otherwise. + With optional start, test sequence beginning at that position. + With optional end, stop comparing sequence at that position. + prefix can also be a tuple of strings to try. e.g. + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_rna.startswith("GUC") + True + >>> my_rna.startswith("AUG") + False + >>> my_rna.startswith("AUG", 3) + True + >>> my_rna.startswith(("UCC", "UCA", "UCG"), 1) + True + """ + if isinstance(prefix, tuple): + prefix = tuple( + bytes(p) if isinstance(p, _SeqAbstractBaseClass) else p.encode("ASCII") + for p in prefix + ) + elif isinstance(prefix, _SeqAbstractBaseClass): + prefix = bytes(prefix) + elif isinstance(prefix, str): + prefix = prefix.encode("ASCII") + return self._data.startswith(prefix, start, end) + + def endswith(self, suffix, start=None, end=None): + """Return True if the sequence ends with the given suffix, False otherwise. + + Return True if the sequence ends with the specified suffix + (a string or another Seq object), False otherwise. + With optional start, test sequence beginning at that position. + With optional end, stop comparing sequence at that position. + suffix can also be a tuple of strings to try. e.g. + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_rna.endswith("UUG") + True + >>> my_rna.endswith("AUG") + False + >>> my_rna.endswith("AUG", 0, 18) + True + >>> my_rna.endswith(("UCC", "UCA", "UUG")) + True + """ + if isinstance(suffix, tuple): + suffix = tuple( + bytes(p) if isinstance(p, _SeqAbstractBaseClass) else p.encode("ASCII") + for p in suffix + ) + elif isinstance(suffix, _SeqAbstractBaseClass): + suffix = bytes(suffix) + elif isinstance(suffix, str): + suffix = suffix.encode("ASCII") + return self._data.endswith(suffix, start, end) + + def split(self, sep=None, maxsplit=-1): + """Return a list of subsequences when splitting the sequence by separator sep. + + Return a list of the subsequences in the sequence (as Seq objects), + using sep as the delimiter string. If maxsplit is given, at + most maxsplit splits are done. If maxsplit is omitted, all + splits are made. + + For consistency with the ``split`` method of Python strings, any + whitespace (tabs, spaces, newlines) is a separator if sep is None, the + default value + + e.g. + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_aa = my_rna.translate() + >>> my_aa + Seq('VMAIVMGR*KGAR*L') + >>> for pep in my_aa.split("*"): + ... pep + Seq('VMAIVMGR') + Seq('KGAR') + Seq('L') + >>> for pep in my_aa.split("*", 1): + ... pep + Seq('VMAIVMGR') + Seq('KGAR*L') + + See also the rsplit method, which splits the sequence starting from the + end: + + >>> for pep in my_aa.rsplit("*", 1): + ... pep + Seq('VMAIVMGR*KGAR') + Seq('L') + """ + if isinstance(sep, _SeqAbstractBaseClass): + sep = bytes(sep) + elif isinstance(sep, str): + sep = sep.encode("ASCII") + return [Seq(part) for part in self._data.split(sep, maxsplit)] + + def rsplit(self, sep=None, maxsplit=-1): + """Return a list of subsequences by splitting the sequence from the right. + + Return a list of the subsequences in the sequence (as Seq objects), + using sep as the delimiter string. If maxsplit is given, at + most maxsplit splits are done. If maxsplit is omitted, all + splits are made. + + For consistency with the ``rsplit`` method of Python strings, any + whitespace (tabs, spaces, newlines) is a separator if sep is None, the + default value + + e.g. + + >>> from Bio.Seq import Seq + >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG") + >>> my_aa = my_rna.translate() + >>> my_aa + Seq('VMAIVMGR*KGAR*L') + >>> for pep in my_aa.rsplit("*"): + ... pep + Seq('VMAIVMGR') + Seq('KGAR') + Seq('L') + >>> for pep in my_aa.rsplit("*", 1): + ... pep + Seq('VMAIVMGR*KGAR') + Seq('L') + + See also the split method, which splits the sequence starting from the + beginning: + + >>> for pep in my_aa.split("*", 1): + ... pep + Seq('VMAIVMGR') + Seq('KGAR*L') + """ + if isinstance(sep, _SeqAbstractBaseClass): + sep = bytes(sep) + elif isinstance(sep, str): + sep = sep.encode("ASCII") + return [Seq(part) for part in self._data.rsplit(sep, maxsplit)] + + def strip(self, chars=None, inplace=False): + """Return a sequence object with leading and trailing ends stripped. + + With default arguments, leading and trailing whitespace is removed: + + >>> seq = Seq(" ACGT ") + >>> seq.strip() + Seq('ACGT') + >>> seq + Seq(' ACGT ') + + If ``chars`` is given and not ``None``, remove characters in ``chars`` + instead. The order of the characters to be removed is not important: + + >>> Seq("ACGTACGT").strip("TGCA") + Seq('') + + A copy of the sequence is returned if ``inplace`` is ``False`` (the + default value). If ``inplace`` is ``True``, the sequence is stripped + in-place and returned. + + >>> seq = MutableSeq(" ACGT ") + >>> seq.strip() + MutableSeq('ACGT') + >>> seq + MutableSeq(' ACGT ') + >>> seq.strip(inplace=True) + MutableSeq('ACGT') + >>> seq + MutableSeq('ACGT') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if ``strip`` + is called on a ``Seq`` object with ``inplace=True``. + + See also the lstrip and rstrip methods. + """ + if isinstance(chars, _SeqAbstractBaseClass): + chars = bytes(chars) + elif isinstance(chars, str): + chars = chars.encode("ASCII") + try: + data = self._data.strip(chars) + except TypeError: + raise TypeError( + "argument must be None or a string, Seq, MutableSeq, or bytes-like object" + ) from None + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def lstrip(self, chars=None, inplace=False): + """Return a sequence object with leading and trailing ends stripped. + + With default arguments, leading whitespace is removed: + + >>> seq = Seq(" ACGT ") + >>> seq.lstrip() + Seq('ACGT ') + >>> seq + Seq(' ACGT ') + + If ``chars`` is given and not ``None``, remove characters in ``chars`` + from the leading end instead. The order of the characters to be removed + is not important: + + >>> Seq("ACGACGTTACG").lstrip("GCA") + Seq('TTACG') + + A copy of the sequence is returned if ``inplace`` is ``False`` (the + default value). If ``inplace`` is ``True``, the sequence is stripped + in-place and returned. + + >>> seq = MutableSeq(" ACGT ") + >>> seq.lstrip() + MutableSeq('ACGT ') + >>> seq + MutableSeq(' ACGT ') + >>> seq.lstrip(inplace=True) + MutableSeq('ACGT ') + >>> seq + MutableSeq('ACGT ') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``lstrip`` is called on a ``Seq`` object with ``inplace=True``. + + See also the strip and rstrip methods. + """ + if isinstance(chars, _SeqAbstractBaseClass): + chars = bytes(chars) + elif isinstance(chars, str): + chars = chars.encode("ASCII") + try: + data = self._data.lstrip(chars) + except TypeError: + raise TypeError( + "argument must be None or a string, Seq, MutableSeq, or bytes-like object" + ) from None + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def rstrip(self, chars=None, inplace=False): + """Return a sequence object with trailing ends stripped. + + With default arguments, trailing whitespace is removed: + + >>> seq = Seq(" ACGT ") + >>> seq.rstrip() + Seq(' ACGT') + >>> seq + Seq(' ACGT ') + + If ``chars`` is given and not ``None``, remove characters in ``chars`` + from the trailing end instead. The order of the characters to be + removed is not important: + + >>> Seq("ACGACGTTACG").rstrip("GCA") + Seq('ACGACGTT') + + A copy of the sequence is returned if ``inplace`` is ``False`` (the + default value). If ``inplace`` is ``True``, the sequence is stripped + in-place and returned. + + >>> seq = MutableSeq(" ACGT ") + >>> seq.rstrip() + MutableSeq(' ACGT') + >>> seq + MutableSeq(' ACGT ') + >>> seq.rstrip(inplace=True) + MutableSeq(' ACGT') + >>> seq + MutableSeq(' ACGT') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``rstrip`` is called on a ``Seq`` object with ``inplace=True``. + + See also the strip and lstrip methods. + """ + if isinstance(chars, _SeqAbstractBaseClass): + chars = bytes(chars) + elif isinstance(chars, str): + chars = chars.encode("ASCII") + try: + data = self._data.rstrip(chars) + except TypeError: + raise TypeError( + "argument must be None or a string, Seq, MutableSeq, or bytes-like object" + ) from None + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def removeprefix(self, prefix, inplace=False): + """Return a new Seq object with prefix (left) removed. + + This behaves like the python string method of the same name. + + e.g. Removing a start Codon: + + >>> from Bio.Seq import Seq + >>> my_seq = Seq("ATGGTGTGTGT") + >>> my_seq + Seq('ATGGTGTGTGT') + >>> my_seq.removeprefix('ATG') + Seq('GTGTGTGT') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``removeprefix`` is called on a ``Seq`` object with ``inplace=True``. + + See also the removesuffix method. + """ + if isinstance(prefix, _SeqAbstractBaseClass): + prefix = bytes(prefix) + elif isinstance(prefix, str): + prefix = prefix.encode("ASCII") + try: + data = self._data.removeprefix(prefix) + except TypeError: + raise TypeError( + "argument must be a string, Seq, MutableSeq, or bytes-like object" + ) from None + except AttributeError: + # Fall back for pre-Python 3.9 + data = self._data + if data.startswith(prefix): + data = data[len(prefix) :] + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def removesuffix(self, suffix, inplace=False): + """Return a new Seq object with suffix (right) removed. + + This behaves like the python string method of the same name. + + e.g. Removing a stop codon: + + >>> from Bio.Seq import Seq + >>> my_seq = Seq("GTGTGTGTTAG") + >>> my_seq + Seq('GTGTGTGTTAG') + >>> stop_codon = Seq("TAG") + >>> my_seq.removesuffix(stop_codon) + Seq('GTGTGTGT') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``removesuffix`` is called on a ``Seq`` object with ``inplace=True``. + + See also the removeprefix method. + """ + if isinstance(suffix, _SeqAbstractBaseClass): + suffix = bytes(suffix) + elif isinstance(suffix, str): + suffix = suffix.encode("ASCII") + try: + data = self._data.removesuffix(suffix) + except TypeError: + raise TypeError( + "argument must be a string, Seq, MutableSeq, or bytes-like object" + ) from None + except AttributeError: + # Fall back for pre-Python 3.9 + data = self._data + if data.endswith(suffix): + data = data[: -len(suffix)] + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def upper(self, inplace=False): + """Return the sequence in upper case. + + An upper-case copy of the sequence is returned if inplace is False, + the default value: + + >>> from Bio.Seq import Seq, MutableSeq + >>> my_seq = Seq("VHLTPeeK*") + >>> my_seq + Seq('VHLTPeeK*') + >>> my_seq.lower() + Seq('vhltpeek*') + >>> my_seq.upper() + Seq('VHLTPEEK*') + >>> my_seq + Seq('VHLTPeeK*') + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("VHLTPeeK*") + >>> my_seq + MutableSeq('VHLTPeeK*') + >>> my_seq.lower() + MutableSeq('vhltpeek*') + >>> my_seq.upper() + MutableSeq('VHLTPEEK*') + >>> my_seq + MutableSeq('VHLTPeeK*') + + >>> my_seq.lower(inplace=True) + MutableSeq('vhltpeek*') + >>> my_seq + MutableSeq('vhltpeek*') + >>> my_seq.upper(inplace=True) + MutableSeq('VHLTPEEK*') + >>> my_seq + MutableSeq('VHLTPEEK*') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``upper`` is called on a ``Seq`` object with ``inplace=True``. + + See also the ``lower`` method. + """ + data = self._data.upper() + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def lower(self, inplace=False): + """Return the sequence in lower case. + + An lower-case copy of the sequence is returned if inplace is False, + the default value: + + >>> from Bio.Seq import Seq, MutableSeq + >>> my_seq = Seq("VHLTPeeK*") + >>> my_seq + Seq('VHLTPeeK*') + >>> my_seq.lower() + Seq('vhltpeek*') + >>> my_seq.upper() + Seq('VHLTPEEK*') + >>> my_seq + Seq('VHLTPeeK*') + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("VHLTPeeK*") + >>> my_seq + MutableSeq('VHLTPeeK*') + >>> my_seq.lower() + MutableSeq('vhltpeek*') + >>> my_seq.upper() + MutableSeq('VHLTPEEK*') + >>> my_seq + MutableSeq('VHLTPeeK*') + + >>> my_seq.lower(inplace=True) + MutableSeq('vhltpeek*') + >>> my_seq + MutableSeq('vhltpeek*') + >>> my_seq.upper(inplace=True) + MutableSeq('VHLTPEEK*') + >>> my_seq + MutableSeq('VHLTPEEK*') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``lower`` is called on a ``Seq`` object with ``inplace=True``. + + See also the ``upper`` method. + """ + data = self._data.lower() + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + else: + return self.__class__(data) + + def isupper(self): + """Return True if all ASCII characters in data are uppercase. + + If there are no cased characters, the method returns False. + """ + return self._data.isupper() + + def islower(self): + """Return True if all ASCII characters in data are lowercase. + + If there are no cased characters, the method returns False. + """ + return self._data.islower() + + def translate( + self, table="Standard", stop_symbol="*", to_stop=False, cds=False, gap="-" + ): + """Turn a nucleotide sequence into a protein sequence by creating a new sequence object. + + This method will translate DNA or RNA sequences. It should not + be used on protein sequences as any result will be biologically + meaningless. + + Arguments: + - table - Which codon table to use? This can be either a name + (string), an NCBI identifier (integer), or a CodonTable + object (useful for non-standard genetic codes). This + defaults to the "Standard" table. + - stop_symbol - Single character string, what to use for + terminators. This defaults to the asterisk, "*". + - to_stop - Boolean, defaults to False meaning do a full + translation continuing on past any stop codons (translated as the + specified stop_symbol). If True, translation is terminated at + the first in frame stop codon (and the stop_symbol is not + appended to the returned protein sequence). + - cds - Boolean, indicates this is a complete CDS. If True, + this checks the sequence starts with a valid alternative start + codon (which will be translated as methionine, M), that the + sequence length is a multiple of three, and that there is a + single in frame stop codon at the end (this will be excluded + from the protein sequence, regardless of the to_stop option). + If these tests fail, an exception is raised. + - gap - Single character string to denote symbol used for gaps. + Defaults to the minus sign. + + A ``Seq`` object is returned if ``translate`` is called on a ``Seq`` + object; a ``MutableSeq`` object is returned if ``translate`` is called + pn a ``MutableSeq`` object. + + e.g. Using the standard table: + + >>> coding_dna = Seq("GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG") + >>> coding_dna.translate() + Seq('VAIVMGR*KGAR*') + >>> coding_dna.translate(stop_symbol="@") + Seq('VAIVMGR@KGAR@') + >>> coding_dna.translate(to_stop=True) + Seq('VAIVMGR') + + Now using NCBI table 2, where TGA is not a stop codon: + + >>> coding_dna.translate(table=2) + Seq('VAIVMGRWKGAR*') + >>> coding_dna.translate(table=2, to_stop=True) + Seq('VAIVMGRWKGAR') + + In fact, GTG is an alternative start codon under NCBI table 2, meaning + this sequence could be a complete CDS: + + >>> coding_dna.translate(table=2, cds=True) + Seq('MAIVMGRWKGAR') + + It isn't a valid CDS under NCBI table 1, due to both the start codon + and also the in frame stop codons: + + >>> coding_dna.translate(table=1, cds=True) + Traceback (most recent call last): + ... + Bio.Data.CodonTable.TranslationError: First codon 'GTG' is not a start codon + + If the sequence has no in-frame stop codon, then the to_stop argument + has no effect: + + >>> coding_dna2 = Seq("TTGGCCATTGTAATGGGCCGC") + >>> coding_dna2.translate() + Seq('LAIVMGR') + >>> coding_dna2.translate(to_stop=True) + Seq('LAIVMGR') + + NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid + or a stop codon. These are translated as "X". Any invalid codon + (e.g. "TA?" or "T-A") will throw a TranslationError. + + NOTE - This does NOT behave like the python string's translate + method. For that use str(my_seq).translate(...) instead + """ + try: + data = str(self) + except UndefinedSequenceError: + # translating an undefined sequence yields an undefined + # sequence with the length divided by 3 + n = len(self) + if n % 3 != 0: + warnings.warn( + "Partial codon, len(sequence) not a multiple of three. " + "This may become an error in future.", + BiopythonWarning, + ) + return Seq(None, n // 3) + + return self.__class__( + _translate_str(str(self), table, stop_symbol, to_stop, cds, gap=gap) + ) + + def complement(self, inplace=False): + """Return the complement as a DNA sequence. + + >>> Seq("CGA").complement() + Seq('GCT') + + Any U in the sequence is treated as a T: + + >>> Seq("CGAUT").complement() + Seq('GCTAA') + + In contrast, ``complement_rna`` returns an RNA sequence: + + >>> Seq("CGAUT").complement_rna() + Seq('GCUAA') + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> my_seq + MutableSeq('CGA') + >>> my_seq.complement() + MutableSeq('GCT') + >>> my_seq + MutableSeq('CGA') + + >>> my_seq.complement(inplace=True) + MutableSeq('GCT') + >>> my_seq + MutableSeq('GCT') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``complement_rna`` is called on a ``Seq`` object with ``inplace=True``. + """ + ttable = _dna_complement_table + try: + data = self._data.translate(ttable) + except UndefinedSequenceError: + # complement of an undefined sequence is an undefined sequence + # of the same length + return self + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + return self.__class__(data) + + def complement_rna(self, inplace=False): + """Return the complement as an RNA sequence. + + >>> Seq("CGA").complement_rna() + Seq('GCU') + + Any T in the sequence is treated as a U: + + >>> Seq("CGAUT").complement_rna() + Seq('GCUAA') + + In contrast, ``complement`` returns a DNA sequence by default: + + >>> Seq("CGA").complement() + Seq('GCT') + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> my_seq + MutableSeq('CGA') + >>> my_seq.complement_rna() + MutableSeq('GCU') + >>> my_seq + MutableSeq('CGA') + + >>> my_seq.complement_rna(inplace=True) + MutableSeq('GCU') + >>> my_seq + MutableSeq('GCU') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``complement_rna`` is called on a ``Seq`` object with ``inplace=True``. + """ + try: + data = self._data.translate(_rna_complement_table) + except UndefinedSequenceError: + # complement of an undefined sequence is an undefined sequence + # of the same length + return self + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + return self.__class__(data) + + def reverse_complement(self, inplace=False): + """Return the reverse complement as a DNA sequence. + + >>> Seq("CGA").reverse_complement() + Seq('TCG') + + Any U in the sequence is treated as a T: + + >>> Seq("CGAUT").reverse_complement() + Seq('AATCG') + + In contrast, ``reverse_complement_rna`` returns an RNA sequence: + + >>> Seq("CGA").reverse_complement_rna() + Seq('UCG') + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> my_seq + MutableSeq('CGA') + >>> my_seq.reverse_complement() + MutableSeq('TCG') + >>> my_seq + MutableSeq('CGA') + + >>> my_seq.reverse_complement(inplace=True) + MutableSeq('TCG') + >>> my_seq + MutableSeq('TCG') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``reverse_complement`` is called on a ``Seq`` object with + ``inplace=True``. + """ + try: + data = self._data.translate(_dna_complement_table) + except UndefinedSequenceError: + # reverse complement of an undefined sequence is an undefined sequence + # of the same length + return self + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[::-1] = data + return self + return self.__class__(data[::-1]) + + def reverse_complement_rna(self, inplace=False): + """Return the reverse complement as an RNA sequence. + + >>> Seq("CGA").reverse_complement_rna() + Seq('UCG') + + Any T in the sequence is treated as a U: + + >>> Seq("CGAUT").reverse_complement_rna() + Seq('AAUCG') + + In contrast, ``reverse_complement`` returns a DNA sequence: + + >>> Seq("CGA").reverse_complement() + Seq('TCG') + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> my_seq + MutableSeq('CGA') + >>> my_seq.reverse_complement_rna() + MutableSeq('UCG') + >>> my_seq + MutableSeq('CGA') + + >>> my_seq.reverse_complement_rna(inplace=True) + MutableSeq('UCG') + >>> my_seq + MutableSeq('UCG') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``reverse_complement_rna`` is called on a ``Seq`` object with + ``inplace=True``. + """ + try: + data = self._data.translate(_rna_complement_table) + except UndefinedSequenceError: + # reverse complement of an undefined sequence is an undefined sequence + # of the same length + return self + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[::-1] = data + return self + return self.__class__(data[::-1]) + + def transcribe(self, inplace=False): + """Transcribe a DNA sequence into RNA and return the RNA sequence as a new Seq object. + + Following the usual convention, the sequence is interpreted as the + coding strand of the DNA double helix, not the template strand. This + means we can get the RNA sequence just by switching T to U. + + >>> from Bio.Seq import Seq + >>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG") + >>> coding_dna + Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + >>> coding_dna.transcribe() + Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + + The sequence is modified in-place and returned if inplace is True: + + >>> sequence = MutableSeq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG") + >>> sequence + MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + >>> sequence.transcribe() + MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + >>> sequence + MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + + >>> sequence.transcribe(inplace=True) + MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + >>> sequence + MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``transcribe`` is called on a ``Seq`` object with ``inplace=True``. + + Trying to transcribe an RNA sequence has no effect. + If you have a nucleotide sequence which might be DNA or RNA + (or even a mixture), calling the transcribe method will ensure + any T becomes U. + + Trying to transcribe a protein sequence will replace any + T for Threonine with U for Selenocysteine, which has no + biologically plausible rational. + + >>> from Bio.Seq import Seq + >>> my_protein = Seq("MAIVMGRT") + >>> my_protein.transcribe() + Seq('MAIVMGRU') + """ + data = self._data.replace(b"T", b"U").replace(b"t", b"u") + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + return self.__class__(data) + + def back_transcribe(self, inplace=False): + """Return the DNA sequence from an RNA sequence by creating a new Seq object. + + >>> from Bio.Seq import Seq + >>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG") + >>> messenger_rna + Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + >>> messenger_rna.back_transcribe() + Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + + The sequence is modified in-place and returned if inplace is True: + + >>> sequence = MutableSeq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG") + >>> sequence + MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + >>> sequence.back_transcribe() + MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + >>> sequence + MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG') + + >>> sequence.back_transcribe(inplace=True) + MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + >>> sequence + MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``transcribe`` is called on a ``Seq`` object with ``inplace=True``. + + Trying to back-transcribe DNA has no effect, If you have a nucleotide + sequence which might be DNA or RNA (or even a mixture), calling the + back-transcribe method will ensure any U becomes T. + + Trying to back-transcribe a protein sequence will replace any U for + Selenocysteine with T for Threonine, which is biologically meaningless. + + >>> from Bio.Seq import Seq + >>> my_protein = Seq("MAIVMGRU") + >>> my_protein.back_transcribe() + Seq('MAIVMGRT') + """ + data = self._data.replace(b"U", b"T").replace(b"u", b"t") + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + return self.__class__(data) + + def join(self, other): + """Return a merge of the sequences in other, spaced by the sequence from self. + + Accepts a Seq object, MutableSeq object, or string (and iterates over + the letters), or an iterable containing Seq, MutableSeq, or string + objects. These arguments will be concatenated with the calling sequence + as the spacer: + + >>> concatenated = Seq('NNNNN').join([Seq("AAA"), Seq("TTT"), Seq("PPP")]) + >>> concatenated + Seq('AAANNNNNTTTNNNNNPPP') + + Joining the letters of a single sequence: + + >>> Seq('NNNNN').join(Seq("ACGT")) + Seq('ANNNNNCNNNNNGNNNNNT') + >>> Seq('NNNNN').join("ACGT") + Seq('ANNNNNCNNNNNGNNNNNT') + """ + if isinstance(other, _SeqAbstractBaseClass): + return self.__class__(str(self).join(str(other))) + elif isinstance(other, str): + return self.__class__(str(self).join(other)) + + from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports + + if isinstance(other, SeqRecord): + raise TypeError("Iterable cannot be a SeqRecord") + + for c in other: + if isinstance(c, SeqRecord): + raise TypeError("Iterable cannot contain SeqRecords") + elif not isinstance(c, (str, _SeqAbstractBaseClass)): + raise TypeError( + "Input must be an iterable of Seq objects, MutableSeq objects, or strings" + ) + return self.__class__(str(self).join([str(_) for _ in other])) + + def replace(self, old, new, inplace=False): + """Return a copy with all occurrences of subsequence old replaced by new. + + >>> s = Seq("ACGTAACCGGTT") + >>> t = s.replace("AC", "XYZ") + >>> s + Seq('ACGTAACCGGTT') + >>> t + Seq('XYZGTAXYZCGGTT') + + For mutable sequences, passing inplace=True will modify the sequence in place: + + >>> m = MutableSeq("ACGTAACCGGTT") + >>> t = m.replace("AC", "XYZ") + >>> m + MutableSeq('ACGTAACCGGTT') + >>> t + MutableSeq('XYZGTAXYZCGGTT') + + >>> m = MutableSeq("ACGTAACCGGTT") + >>> t = m.replace("AC", "XYZ", inplace=True) + >>> m + MutableSeq('XYZGTAXYZCGGTT') + >>> t + MutableSeq('XYZGTAXYZCGGTT') + + As ``Seq`` objects are immutable, a ``TypeError`` is raised if + ``replace`` is called on a ``Seq`` object with ``inplace=True``. + """ + if isinstance(old, _SeqAbstractBaseClass): + old = bytes(old) + elif isinstance(old, str): + old = old.encode("ASCII") + if isinstance(new, _SeqAbstractBaseClass): + new = bytes(new) + elif isinstance(new, str): + new = new.encode("ASCII") + data = self._data.replace(old, new) + if inplace: + if not isinstance(self._data, bytearray): + raise TypeError("Sequence is immutable") + self._data[:] = data + return self + return self.__class__(data) + + @property + def defined(self): + """Return True if the sequence is defined, False if undefined or partially defined. + + Zero-length sequences are always considered to be defined. + """ + if isinstance(self._data, (bytes, bytearray)): + return True + else: + return self._data.defined + + @property + def defined_ranges(self): + """Return a tuple of the ranges where the sequence contents is defined. + + The return value has the format ((start1, end1), (start2, end2), ...). + """ + if isinstance(self._data, (bytes, bytearray)): + length = len(self) + if length > 0: + return ((0, length),) + else: + return () + else: + return self._data.defined_ranges + + +class Seq(_SeqAbstractBaseClass): + """Read-only sequence object (essentially a string with biological methods). + + Like normal python strings, our basic sequence object is immutable. + This prevents you from doing my_seq[5] = "A" for example, but does allow + Seq objects to be used as dictionary keys. + + The Seq object provides a number of string like methods (such as count, + find, split and strip). + + The Seq object also provides some biological methods, such as complement, + reverse_complement, transcribe, back_transcribe and translate (which are + not applicable to protein sequences). + """ + + _data: bytes | SequenceDataAbstractBaseClass + + def __init__( + self, + data: ( + str + | bytes + | bytearray + | _SeqAbstractBaseClass + | SequenceDataAbstractBaseClass + | dict + | None + ), + length: int | None = None, + ): + """Create a Seq object. + + Arguments: + - data - Sequence, required (string) + - length - Sequence length, used only if data is None or a dictionary (integer) + + You will typically use Bio.SeqIO to read in sequences from files as + SeqRecord objects, whose sequence will be exposed as a Seq object via + the seq property. + + However, you can also create a Seq object directly: + + >>> from Bio.Seq import Seq + >>> my_seq = Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF") + >>> my_seq + Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF') + >>> print(my_seq) + MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF + + To create a Seq object with for a sequence of known length but + unknown sequence contents, use None for the data argument and pass + the sequence length for the length argument. Trying to access the + sequence contents of a Seq object created in this way will raise + an UndefinedSequenceError: + + >>> my_undefined_sequence = Seq(None, 20) + >>> my_undefined_sequence + Seq(None, length=20) + >>> len(my_undefined_sequence) + 20 + >>> print(my_undefined_sequence) + Traceback (most recent call last): + ... + Bio.Seq.UndefinedSequenceError: Sequence content is undefined + + If the sequence contents is known for parts of the sequence only, use + a dictionary for the data argument to pass the known sequence segments: + + >>> my_partially_defined_sequence = Seq({3: "ACGT"}, 10) + >>> my_partially_defined_sequence + Seq({3: 'ACGT'}, length=10) + >>> len(my_partially_defined_sequence) + 10 + >>> print(my_partially_defined_sequence) + Traceback (most recent call last): + ... + Bio.Seq.UndefinedSequenceError: Sequence content is only partially defined + >>> my_partially_defined_sequence[3:7] + Seq('ACGT') + >>> print(my_partially_defined_sequence[3:7]) + ACGT + """ + if data is None: + if length is None: + raise ValueError("length must not be None if data is None") + elif length == 0: + self._data = b"" + elif length < 0: + raise ValueError("length must not be negative.") + else: + self._data = _UndefinedSequenceData(length) + elif isinstance(data, (bytes, SequenceDataAbstractBaseClass)): + self._data = data + elif isinstance(data, (bytearray, _SeqAbstractBaseClass)): + self._data = bytes(data) + elif isinstance(data, str): + self._data = bytes(data, encoding="ASCII") + elif isinstance(data, dict): + if length is None: + raise ValueError("length must not be None if data is a dictionary") + elif length == 0: + self._data = b"" + elif length < 0: + raise ValueError("length must not be negative.") + else: + current = 0 # not needed here, but it keeps mypy happy + end = -1 + starts = sorted(data.keys()) + _data: dict[int, bytes] = {} + for start in starts: + seq = data[start] + if isinstance(seq, str): + seq = bytes(seq, encoding="ASCII") + else: + try: + seq = bytes(seq) + except Exception: + raise ValueError("Expected bytes-like objects or strings") + if start < end: + raise ValueError("Sequence data are overlapping.") + elif start == end: + _data[current] += seq # noqa: F821 + else: + _data[start] = seq + current = start + end = start + len(seq) + if end > length: + raise ValueError( + "Provided sequence data extend beyond sequence length." + ) + elif end == length and current == 0: + # sequence is fully defined + self._data = _data[current] + else: + self._data = _PartiallyDefinedSequenceData(length, _data) + else: + raise TypeError( + "data should be a string, bytes, bytearray, Seq, or MutableSeq object" + ) + + def __hash__(self): + """Hash of the sequence as a string for comparison. + + See Seq object comparison documentation (method ``__eq__`` in + particular) as this has changed in Biopython 1.65. Older versions + would hash on object identity. + """ + return hash(self._data) + + +class MutableSeq(_SeqAbstractBaseClass): + """An editable sequence object. + + Unlike normal python strings and our basic sequence object (the Seq class) + which are immutable, the MutableSeq lets you edit the sequence in place. + However, this means you cannot use a MutableSeq object as a dictionary key. + + >>> from Bio.Seq import MutableSeq + >>> my_seq = MutableSeq("ACTCGTCGTCG") + >>> my_seq + MutableSeq('ACTCGTCGTCG') + >>> my_seq[5] + 'T' + >>> my_seq[5] = "A" + >>> my_seq + MutableSeq('ACTCGACGTCG') + >>> my_seq[5] + 'A' + >>> my_seq[5:8] = "NNN" + >>> my_seq + MutableSeq('ACTCGNNNTCG') + >>> len(my_seq) + 11 + + Note that the MutableSeq object does not support as many string-like + or biological methods as the Seq object. + """ + + def __init__(self, data): + """Create a MutableSeq object.""" + if isinstance(data, bytearray): + self._data = data + elif isinstance(data, bytes): + self._data = bytearray(data) + elif isinstance(data, str): + self._data = bytearray(data, "ASCII") + elif isinstance(data, MutableSeq): + self._data = data._data[:] # Take a copy + elif isinstance(data, Seq): + # Make no assumptions about the Seq subclass internal storage + self._data = bytearray(bytes(data)) + else: + raise TypeError( + "data should be a string, bytearray object, Seq object, or a " + "MutableSeq object" + ) + + def __setitem__(self, index, value): + """Set a subsequence of single letter via value parameter. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> my_seq[0] = 'T' + >>> my_seq + MutableSeq('TCTCGACGTCG') + """ + if isinstance(index, numbers.Integral): + # Replacing a single letter with a new string + self._data[index] = ord(value) + else: + # Replacing a sub-sequence + if isinstance(value, MutableSeq): + self._data[index] = value._data + elif isinstance(value, Seq): + self._data[index] = bytes(value) + elif isinstance(value, str): + self._data[index] = value.encode("ASCII") + else: + raise TypeError(f"received unexpected type '{type(value).__name__}'") + + def __delitem__(self, index): + """Delete a subsequence of single letter. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> del my_seq[0] + >>> my_seq + MutableSeq('CTCGACGTCG') + """ + # Could be deleting a single letter, or a slice + del self._data[index] + + def append(self, c): + """Add a subsequence to the mutable sequence object. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> my_seq.append('A') + >>> my_seq + MutableSeq('ACTCGACGTCGA') + + No return value. + """ + self._data.append(ord(c.encode("ASCII"))) + + def insert(self, i, c): + """Add a subsequence to the mutable sequence object at a given index. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> my_seq.insert(0,'A') + >>> my_seq + MutableSeq('AACTCGACGTCG') + >>> my_seq.insert(8,'G') + >>> my_seq + MutableSeq('AACTCGACGGTCG') + + No return value. + """ + self._data.insert(i, ord(c.encode("ASCII"))) + + def pop(self, i=(-1)): + """Remove a subsequence of a single letter at given index. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> my_seq.pop() + 'G' + >>> my_seq + MutableSeq('ACTCGACGTC') + >>> my_seq.pop() + 'C' + >>> my_seq + MutableSeq('ACTCGACGT') + + Returns the last character of the sequence. + """ + c = self._data[i] + del self._data[i] + return chr(c) + + def remove(self, item): + """Remove a subsequence of a single letter from mutable sequence. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> my_seq.remove('C') + >>> my_seq + MutableSeq('ATCGACGTCG') + >>> my_seq.remove('A') + >>> my_seq + MutableSeq('TCGACGTCG') + + No return value. + """ + codepoint = ord(item) + try: + self._data.remove(codepoint) + except ValueError: + raise ValueError("value not found in MutableSeq") from None + + def reverse(self): + """Modify the mutable sequence to reverse itself. + + No return value. + """ + self._data.reverse() + + def extend(self, other): + """Add a sequence to the original mutable sequence object. + + >>> my_seq = MutableSeq('ACTCGACGTCG') + >>> my_seq.extend('A') + >>> my_seq + MutableSeq('ACTCGACGTCGA') + >>> my_seq.extend('TTT') + >>> my_seq + MutableSeq('ACTCGACGTCGATTT') + + No return value. + """ + if isinstance(other, MutableSeq): + self._data.extend(other._data) + elif isinstance(other, Seq): + self._data.extend(bytes(other)) + elif isinstance(other, str): + self._data.extend(other.encode("ASCII")) + else: + raise TypeError("expected a string, Seq or MutableSeq") + + +class UndefinedSequenceError(ValueError): + """Sequence contents is undefined.""" + + +class _UndefinedSequenceData(SequenceDataAbstractBaseClass): + """Stores the length of a sequence with an undefined sequence contents (PRIVATE). + + Objects of this class can be used to create a Seq object to represent + sequences with a known length, but an unknown sequence contents. + Calling __len__ returns the sequence length, calling __getitem__ raises an + UndefinedSequenceError except for requests of zero size, for which it + returns an empty bytes object. + """ + + __slots__ = ("_length",) + + def __init__(self, length): + """Initialize the object with the sequence length. + + The calling function is responsible for ensuring that the length is + greater than zero. + """ + self._length = length + super().__init__() + + def __getitem__(self, key: slice) -> Union[bytes, "_UndefinedSequenceData"]: + if isinstance(key, slice): + start, end, step = key.indices(self._length) + size = len(range(start, end, step)) + if size == 0: + return b"" + return _UndefinedSequenceData(size) + else: + raise UndefinedSequenceError("Sequence content is undefined") + + def __len__(self): + return self._length + + def __bytes__(self): + raise UndefinedSequenceError("Sequence content is undefined") + + def __add__(self, other): + length = len(self) + len(other) + try: + other = bytes(other) + except UndefinedSequenceError: + if isinstance(other, _UndefinedSequenceData): + return _UndefinedSequenceData(length) + else: + return NotImplemented + # _PartiallyDefinedSequenceData.__radd__ will handle this + else: + data = {len(self): other} + return _PartiallyDefinedSequenceData(length, data) + + def __radd__(self, other): + data = {0: bytes(other)} + length = len(other) + len(self) + return _PartiallyDefinedSequenceData(length, data) + + def upper(self): + """Return an upper case copy of the sequence.""" + # An upper case copy of an undefined sequence is an undefined + # sequence of the same length + return _UndefinedSequenceData(self._length) + + def lower(self): + """Return a lower case copy of the sequence.""" + # A lower case copy of an undefined sequence is an undefined + # sequence of the same length + return _UndefinedSequenceData(self._length) + + def isupper(self): + """Return True if all ASCII characters in data are uppercase. + + If there are no cased characters, the method returns False. + """ + # Character case is irrelevant for an undefined sequence + raise UndefinedSequenceError("Sequence content is undefined") + + def islower(self): + """Return True if all ASCII characters in data are lowercase. + + If there are no cased characters, the method returns False. + """ + # Character case is irrelevant for an undefined sequence + raise UndefinedSequenceError("Sequence content is undefined") + + def replace(self, old, new): + """Return a copy with all occurrences of substring old replaced by new.""" + # Replacing substring old by new in an undefined sequence will result + # in an undefined sequence of the same length, if old and new have the + # number of characters. + if len(old) != len(new): + raise UndefinedSequenceError("Sequence content is undefined") + return _UndefinedSequenceData(self._length) + + @property + def defined(self): + """Return False, as the sequence is not defined and has a non-zero length.""" + return False + + @property + def defined_ranges(self): + """Return a tuple of the ranges where the sequence contents is defined. + + As the sequence contents of an _UndefinedSequenceData object is fully + undefined, the return value is always an empty tuple. + """ + return () + + +class _PartiallyDefinedSequenceData(SequenceDataAbstractBaseClass): + """Stores the length of a sequence with an undefined sequence contents (PRIVATE). + + Objects of this class can be used to create a Seq object to represent + sequences with a known length, but with a sequence contents that is only + partially known. + Calling __len__ returns the sequence length, calling __getitem__ returns + the sequence contents if known, otherwise an UndefinedSequenceError is + raised. + """ + + __slots__ = ("_length", "_data") + + def __init__(self, length, data): + """Initialize with the sequence length and defined sequence segments. + + The calling function is responsible for ensuring that the length is + greater than zero. + """ + self._length = length + self._data = data + super().__init__() + + def __getitem__(self, key: slice | int) -> bytes | SequenceDataAbstractBaseClass: + if isinstance(key, slice): + start, end, step = key.indices(self._length) + size = len(range(start, end, step)) + if size == 0: + return b"" + data = {} + for s, d in self._data.items(): + indices = range(-s, -s + self._length)[key] + e: int | None = indices.stop + assert e is not None + if step > 0: + if e <= 0: + continue + if indices.start < 0: + s = indices.start % step + else: + s = indices.start + else: # step < 0 + if e < 0: + e = None + end = len(d) - 1 + if indices.start > end: + s = end + (indices.start - end) % step + else: + s = indices.start + if s < 0: + continue + start = (s - indices.start) // step + d = d[s:e:step] + if d: + data[start] = d + if len(data) == 0: # Fully undefined sequence + return _UndefinedSequenceData(size) + # merge adjacent sequence segments + end = -1 + previous = 0 # not needed here, but it keeps flake happy + items = data.items() + data = {} + for start, seq in items: + if end == start: + data[previous] += seq + else: + data[start] = seq + previous = start + end = start + len(seq) + if len(data) == 1: + seq = data.get(0) + if seq is not None and len(seq) == size: + return seq # Fully defined sequence; return bytes + if step < 0: + # use this after we drop Python 3.7: + # data = {start: data[start] for start in reversed(data)} + # use this as long as we support Python 3.7: + data = {start: data[start] for start in reversed(list(data.keys()))} + return _PartiallyDefinedSequenceData(size, data) + elif self._length <= key: + raise IndexError("sequence index out of range") + else: + for start, seq in self._data.items(): + if start <= key and key < start + len(seq): + return seq[key - start] + raise UndefinedSequenceError("Sequence at position %d is undefined" % key) + + def __len__(self): + return self._length + + def __bytes__(self): + raise UndefinedSequenceError("Sequence content is only partially defined") + + def __add__(self, other): + length = len(self) + len(other) + data = dict(self._data) + items = list(self._data.items()) + start, seq = items[-1] + end = start + len(seq) + try: + other = bytes(other) + except UndefinedSequenceError: + if isinstance(other, _UndefinedSequenceData): + pass + elif isinstance(other, _PartiallyDefinedSequenceData): + other_items = list(other._data.items()) + if end == len(self): + other_start, other_seq = other_items.pop(0) + if other_start == 0: + data[start] += other_seq + else: + data[len(self) + other_start] = other_seq + for other_start, other_seq in other_items: + data[len(self) + other_start] = other_seq + else: + if end == len(self): + data[start] += other + else: + data[len(self)] = other + return _PartiallyDefinedSequenceData(length, data) + + def __radd__(self, other): + length = len(other) + len(self) + try: + other = bytes(other) + except UndefinedSequenceError: + data = {len(other) + start: seq for start, seq in self._data.items()} + else: + data = {0: other} + items = list(self._data.items()) + start, seq = items.pop(0) + if start == 0: + data[0] += seq + else: + data[len(other) + start] = seq + for start, seq in items: + data[len(other) + start] = seq + return _PartiallyDefinedSequenceData(length, data) + + def __mul__(self, other): + length = self._length + items = self._data.items() + data = {} + end = -1 + previous = 0 # not needed here, but it keeps flake happy + for i in range(other): + for start, seq in items: + start += i * length + if end == start: + data[previous] += seq + else: + data[start] = seq + previous = start + end = start + len(seq) + return _PartiallyDefinedSequenceData(length * other, data) + + def upper(self): + """Return an upper case copy of the sequence.""" + data = {start: seq.upper() for start, seq in self._data.items()} + return _PartiallyDefinedSequenceData(self._length, data) + + def lower(self): + """Return a lower case copy of the sequence.""" + data = {start: seq.lower() for start, seq in self._data.items()} + return _PartiallyDefinedSequenceData(self._length, data) + + def isupper(self): + """Return True if all ASCII characters in data are uppercase. + + If there are no cased characters, the method returns False. + """ + # Character case is irrelevant for an undefined sequence + raise UndefinedSequenceError("Sequence content is only partially defined") + + def islower(self): + """Return True if all ASCII characters in data are lowercase. + + If there are no cased characters, the method returns False. + """ + # Character case is irrelevant for an undefined sequence + raise UndefinedSequenceError("Sequence content is only partially defined") + + def translate(self, table, delete=b""): + """Return a copy with each character mapped by the given translation table. + + table + Translation table, which must be a bytes object of length 256. + + All characters occurring in the optional argument delete are removed. + The remaining characters are mapped through the given translation table. + """ + items = self._data.items() + data = {start: seq.translate(table, delete) for start, seq in items} + return _PartiallyDefinedSequenceData(self._length, data) + + def replace(self, old, new): + """Return a copy with all occurrences of substring old replaced by new.""" + # Replacing substring old by new in the undefined sequence segments + # will result in an undefined sequence segment of the same length, if + # old and new have the number of characters. If not, an error is raised, + # as the correct start positions cannot be calculated reliably. + if len(old) != len(new): + raise UndefinedSequenceError( + "Sequence content is only partially defined; substring \n" + "replacement cannot be performed reliably" + ) + items = self._data.items() + data = {start: seq.replace(old, new) for start, seq in items} + return _PartiallyDefinedSequenceData(self._length, data) + + @property + def defined(self): + """Return False, as the sequence is not fully defined and has a non-zero length.""" + return False + + @property + def defined_ranges(self): + """Return a tuple of the ranges where the sequence contents is defined. + + The return value has the format ((start1, end1), (start2, end2), ...). + """ + return tuple((start, start + len(seq)) for start, seq in self._data.items()) + + +# The transcribe, backward_transcribe, and translate functions are +# user-friendly versions of the corresponding Seq/MutableSeq methods. +# The functions work both on Seq objects, and on strings. + + +def transcribe(dna): + """Transcribe a DNA sequence into RNA. + + Following the usual convention, the sequence is interpreted as the + coding strand of the DNA double helix, not the template strand. This + means we can get the RNA sequence just by switching T to U. + + If given a string, returns a new string object. + + Given a Seq or MutableSeq, returns a new Seq object. + + e.g. + + >>> transcribe("ACTGN") + 'ACUGN' + """ + if isinstance(dna, Seq): + return dna.transcribe() + elif isinstance(dna, MutableSeq): + return Seq(dna).transcribe() + else: + return dna.replace("T", "U").replace("t", "u") + + +def back_transcribe(rna): + """Return the RNA sequence back-transcribed into DNA. + + If given a string, returns a new string object. + + Given a Seq or MutableSeq, returns a new Seq object. + + e.g. + + >>> back_transcribe("ACUGN") + 'ACTGN' + """ + if isinstance(rna, Seq): + return rna.back_transcribe() + elif isinstance(rna, MutableSeq): + return Seq(rna).back_transcribe() + else: + return rna.replace("U", "T").replace("u", "t") + + +def _translate_str( + sequence, table, stop_symbol="*", to_stop=False, cds=False, pos_stop="X", gap=None +): + """Translate nucleotide string into a protein string (PRIVATE). + + Arguments: + - sequence - a string + - table - Which codon table to use? This can be either a name (string), + an NCBI identifier (integer), or a CodonTable object (useful for + non-standard genetic codes). This defaults to the "Standard" table. + - stop_symbol - a single character string, what to use for terminators. + - to_stop - boolean, should translation terminate at the first + in frame stop codon? If there is no in-frame stop codon + then translation continues to the end. + - pos_stop - a single character string for a possible stop codon + (e.g. TAN or NNN) + - cds - Boolean, indicates this is a complete CDS. If True, this + checks the sequence starts with a valid alternative start + codon (which will be translated as methionine, M), that the + sequence length is a multiple of three, and that there is a + single in frame stop codon at the end (this will be excluded + from the protein sequence, regardless of the to_stop option). + If these tests fail, an exception is raised. + - gap - Single character string to denote symbol used for gaps. + Defaults to None. + + Returns a string. + + e.g. + + >>> from Bio.Data import CodonTable + >>> table = CodonTable.ambiguous_dna_by_id[1] + >>> _translate_str("AAA", table) + 'K' + >>> _translate_str("TAR", table) + '*' + >>> _translate_str("TAN", table) + 'X' + >>> _translate_str("TAN", table, pos_stop="@") + '@' + >>> _translate_str("TA?", table) + Traceback (most recent call last): + ... + Bio.Data.CodonTable.TranslationError: Codon 'TA?' is invalid + + In a change to older versions of Biopython, partial codons are now + always regarded as an error (previously only checked if cds=True) + and will trigger a warning (likely to become an exception in a + future release). + + If **cds=True**, the start and stop codons are checked, and the start + codon will be translated at methionine. The sequence must be an + while number of codons. + + >>> _translate_str("ATGCCCTAG", table, cds=True) + 'MP' + >>> _translate_str("AAACCCTAG", table, cds=True) + Traceback (most recent call last): + ... + Bio.Data.CodonTable.TranslationError: First codon 'AAA' is not a start codon + >>> _translate_str("ATGCCCTAGCCCTAG", table, cds=True) + Traceback (most recent call last): + ... + Bio.Data.CodonTable.TranslationError: Extra in frame stop codon 'TAG' found. + """ + try: + table_id = int(table) + except ValueError: + # Assume it's a table name + # The same table can be used for RNA or DNA + try: + codon_table = CodonTable.ambiguous_generic_by_name[table] + except KeyError: + if isinstance(table, str): + raise ValueError( + "The Bio.Seq translate methods and function DO NOT " + "take a character string mapping table like the python " + "string object's translate method. " + "Use str(my_seq).translate(...) instead." + ) from None + else: + raise TypeError("table argument must be integer or string") from None + except (AttributeError, TypeError): + # Assume it's a CodonTable object + if isinstance(table, CodonTable.CodonTable): + codon_table = table + else: + raise ValueError("Bad table argument") from None + else: + # Assume it's a table ID + # The same table can be used for RNA or DNA + codon_table = CodonTable.ambiguous_generic_by_id[table_id] + sequence = sequence.upper() + amino_acids = [] + forward_table = codon_table.forward_table + stop_codons = codon_table.stop_codons + if codon_table.nucleotide_alphabet is not None: + valid_letters = set(codon_table.nucleotide_alphabet.upper()) + else: + # Assume the worst case, ambiguous DNA or RNA: + valid_letters = set( + IUPACData.ambiguous_dna_letters.upper() + + IUPACData.ambiguous_rna_letters.upper() + ) + n = len(sequence) + + # Check for tables with 'ambiguous' (dual-coding) stop codons: + dual_coding = [c for c in stop_codons if c in forward_table] + if dual_coding: + c = dual_coding[0] + if to_stop: + raise ValueError( + "You cannot use 'to_stop=True' with this table as it contains" + f" {len(dual_coding)} codon(s) which can be both STOP and an" + f" amino acid (e.g. '{c}' -> '{forward_table[c]}' or STOP)." + ) + warnings.warn( + f"This table contains {len(dual_coding)} codon(s) which code(s) for" + f" both STOP and an amino acid (e.g. '{c}' -> '{forward_table[c]}'" + " or STOP). Such codons will be translated as amino acid.", + BiopythonWarning, + ) + + if cds: + if str(sequence[:3]).upper() not in codon_table.start_codons: + raise CodonTable.TranslationError( + f"First codon '{sequence[:3]}' is not a start codon" + ) + if n % 3 != 0: + raise CodonTable.TranslationError( + f"Sequence length {n} is not a multiple of three" + ) + if str(sequence[-3:]).upper() not in stop_codons: + raise CodonTable.TranslationError( + f"Final codon '{sequence[-3:]}' is not a stop codon" + ) + # Don't translate the stop symbol, and manually translate the M + sequence = sequence[3:-3] + n -= 6 + amino_acids = ["M"] + elif n % 3 != 0: + warnings.warn( + "Partial codon, len(sequence) not a multiple of three. " + "Explicitly trim the sequence or add trailing N before " + "translation. This may become an error in future.", + BiopythonWarning, + ) + if gap is not None: + if not isinstance(gap, str): + raise TypeError("Gap character should be a single character string.") + elif len(gap) > 1: + raise ValueError("Gap character should be a single character string.") + + for i in range(0, n - n % 3, 3): + codon = sequence[i : i + 3] + try: + amino_acids.append(forward_table[codon]) + except (KeyError, CodonTable.TranslationError): + if codon in codon_table.stop_codons: + if cds: + raise CodonTable.TranslationError( + f"Extra in frame stop codon '{codon}' found." + ) from None + if to_stop: + break + amino_acids.append(stop_symbol) + elif valid_letters.issuperset(set(codon)): + # Possible stop codon (e.g. NNN or TAN) + amino_acids.append(pos_stop) + elif gap is not None and codon == gap * 3: + # Gapped translation + amino_acids.append(gap) + else: + raise CodonTable.TranslationError( + f"Codon '{codon}' is invalid" + ) from None + return "".join(amino_acids) + + +def translate( + sequence, table="Standard", stop_symbol="*", to_stop=False, cds=False, gap=None +): + """Translate a nucleotide sequence into amino acids. + + If given a string, returns a new string object. Given a Seq or + MutableSeq, returns a Seq object. + + Arguments: + - table - Which codon table to use? This can be either a name + (string), an NCBI identifier (integer), or a CodonTable object + (useful for non-standard genetic codes). Defaults to the "Standard" + table. + - stop_symbol - Single character string, what to use for any + terminators, defaults to the asterisk, "*". + - to_stop - Boolean, defaults to False meaning do a full + translation continuing on past any stop codons + (translated as the specified stop_symbol). If + True, translation is terminated at the first in + frame stop codon (and the stop_symbol is not + appended to the returned protein sequence). + - cds - Boolean, indicates this is a complete CDS. If True, this + checks the sequence starts with a valid alternative start + codon (which will be translated as methionine, M), that the + sequence length is a multiple of three, and that there is a + single in frame stop codon at the end (this will be excluded + from the protein sequence, regardless of the to_stop option). + If these tests fail, an exception is raised. + - gap - Single character string to denote symbol used for gaps. + Defaults to None. + + A simple string example using the default (standard) genetic code: + + >>> coding_dna = "GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG" + >>> translate(coding_dna) + 'VAIVMGR*KGAR*' + >>> translate(coding_dna, stop_symbol="@") + 'VAIVMGR@KGAR@' + >>> translate(coding_dna, to_stop=True) + 'VAIVMGR' + + Now using NCBI table 2, where TGA is not a stop codon: + + >>> translate(coding_dna, table=2) + 'VAIVMGRWKGAR*' + >>> translate(coding_dna, table=2, to_stop=True) + 'VAIVMGRWKGAR' + + In fact this example uses an alternative start codon valid under NCBI + table 2, GTG, which means this example is a complete valid CDS which + when translated should really start with methionine (not valine): + + >>> translate(coding_dna, table=2, cds=True) + 'MAIVMGRWKGAR' + + Note that if the sequence has no in-frame stop codon, then the to_stop + argument has no effect: + + >>> coding_dna2 = "GTGGCCATTGTAATGGGCCGC" + >>> translate(coding_dna2) + 'VAIVMGR' + >>> translate(coding_dna2, to_stop=True) + 'VAIVMGR' + + NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid + or a stop codon. These are translated as "X". Any invalid codon + (e.g. "TA?" or "T-A") will throw a TranslationError. + + It will however translate either DNA or RNA. + + NOTE - Since version 1.71 Biopython contains codon tables with 'ambiguous + stop codons'. These are stop codons with unambiguous sequence but which + have a context dependent coding as STOP or as amino acid. With these tables + 'to_stop' must be False (otherwise a ValueError is raised). The dual + coding codons will always be translated as amino acid, except for + 'cds=True', where the last codon will be translated as STOP. + + >>> coding_dna3 = "ATGGCACGGAAGTGA" + >>> translate(coding_dna3) + 'MARK*' + + >>> translate(coding_dna3, table=27) # Table 27: TGA -> STOP or W + 'MARKW' + + It will however raise a BiopythonWarning (not shown). + + >>> translate(coding_dna3, table=27, cds=True) + 'MARK' + + >>> translate(coding_dna3, table=27, to_stop=True) + Traceback (most recent call last): + ... + ValueError: You cannot use 'to_stop=True' with this table ... + """ + if isinstance(sequence, Seq): + return sequence.translate(table, stop_symbol, to_stop, cds) + elif isinstance(sequence, MutableSeq): + # Return a Seq object + return Seq(sequence).translate(table, stop_symbol, to_stop, cds) + else: + # Assume it's a string, return a string + return _translate_str(sequence, table, stop_symbol, to_stop, cds, gap=gap) + + +def reverse_complement(sequence, inplace=False): + """Return the reverse complement as a DNA sequence. + + If given a string, returns a new string object. + Given a Seq object, returns a new Seq object. + Given a MutableSeq, returns a new MutableSeq object. + Given a SeqRecord object, returns a new SeqRecord object. + + >>> my_seq = "CGA" + >>> reverse_complement(my_seq) + 'TCG' + >>> my_seq = Seq("CGA") + >>> reverse_complement(my_seq) + Seq('TCG') + >>> my_seq = MutableSeq("CGA") + >>> reverse_complement(my_seq) + MutableSeq('TCG') + >>> my_seq + MutableSeq('CGA') + + Any U in the sequence is treated as a T: + + >>> reverse_complement(Seq("CGAUT")) + Seq('AATCG') + + In contrast, ``reverse_complement_rna`` returns an RNA sequence: + + >>> reverse_complement_rna(Seq("CGAUT")) + Seq('AAUCG') + + Supports and lower- and upper-case characters, and unambiguous and + ambiguous nucleotides. All other characters are not converted: + + >>> reverse_complement("ACGTUacgtuXYZxyz") + 'zrxZRXaacgtAACGT' + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> reverse_complement(my_seq, inplace=True) + MutableSeq('TCG') + >>> my_seq + MutableSeq('TCG') + + As strings and ``Seq`` objects are immutable, a ``TypeError`` is + raised if ``reverse_complement`` is called on a ``Seq`` object with + ``inplace=True``. + """ + from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports + + if isinstance(sequence, (Seq, MutableSeq)): + return sequence.reverse_complement(inplace) + if isinstance(sequence, SeqRecord): + if inplace: + raise TypeError("SeqRecords are immutable") + return sequence.reverse_complement() + # Assume it's a string. + if inplace: + raise TypeError("strings are immutable") + sequence = sequence.encode("ASCII") + sequence = sequence.translate(_dna_complement_table) + sequence = sequence.decode("ASCII") + return sequence[::-1] + + +def reverse_complement_rna(sequence, inplace=False): + """Return the reverse complement as an RNA sequence. + + If given a string, returns a new string object. + Given a Seq object, returns a new Seq object. + Given a MutableSeq, returns a new MutableSeq object. + Given a SeqRecord object, returns a new SeqRecord object. + + >>> my_seq = "CGA" + >>> reverse_complement_rna(my_seq) + 'UCG' + >>> my_seq = Seq("CGA") + >>> reverse_complement_rna(my_seq) + Seq('UCG') + >>> my_seq = MutableSeq("CGA") + >>> reverse_complement_rna(my_seq) + MutableSeq('UCG') + >>> my_seq + MutableSeq('CGA') + + Any T in the sequence is treated as a U: + + >>> reverse_complement_rna(Seq("CGAUT")) + Seq('AAUCG') + + In contrast, ``reverse_complement`` returns a DNA sequence: + + >>> reverse_complement(Seq("CGAUT"), inplace=False) + Seq('AATCG') + + Supports and lower- and upper-case characters, and unambiguous and + ambiguous nucleotides. All other characters are not converted: + + >>> reverse_complement_rna("ACGTUacgtuXYZxyz") + 'zrxZRXaacguAACGU' + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> reverse_complement_rna(my_seq, inplace=True) + MutableSeq('UCG') + >>> my_seq + MutableSeq('UCG') + + As strings and ``Seq`` objects are immutable, a ``TypeError`` is + raised if ``reverse_complement`` is called on a ``Seq`` object with + ``inplace=True``. + """ + from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports + + if isinstance(sequence, (Seq, MutableSeq)): + return sequence.reverse_complement_rna(inplace) + if isinstance(sequence, SeqRecord): + if inplace: + raise TypeError("SeqRecords are immutable") + return sequence.reverse_complement_rna() + # Assume it's a string. + if inplace: + raise TypeError("strings are immutable") + sequence = sequence.encode("ASCII") + sequence = sequence.translate(_rna_complement_table) + sequence = sequence.decode("ASCII") + return sequence[::-1] + + +def complement(sequence, inplace=False): + """Return the complement as a DNA sequence. + + If given a string, returns a new string object. + Given a Seq object, returns a new Seq object. + Given a MutableSeq, returns a new MutableSeq object. + Given a SeqRecord object, returns a new SeqRecord object. + + >>> my_seq = "CGA" + >>> complement(my_seq) + 'GCT' + >>> my_seq = Seq("CGA") + >>> complement(my_seq) + Seq('GCT') + >>> my_seq = MutableSeq("CGA") + >>> complement(my_seq) + MutableSeq('GCT') + >>> my_seq + MutableSeq('CGA') + + Any U in the sequence is treated as a T: + + >>> complement(Seq("CGAUT")) + Seq('GCTAA') + + In contrast, ``complement_rna`` returns an RNA sequence: + + >>> complement_rna(Seq("CGAUT")) + Seq('GCUAA') + + Supports and lower- and upper-case characters, and unambiguous and + ambiguous nucleotides. All other characters are not converted: + + >>> complement("ACGTUacgtuXYZxyz") + 'TGCAAtgcaaXRZxrz' + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> complement(my_seq, inplace=True) + MutableSeq('GCT') + >>> my_seq + MutableSeq('GCT') + + As strings and ``Seq`` objects are immutable, a ``TypeError`` is + raised if ``reverse_complement`` is called on a ``Seq`` object with + ``inplace=True``. + """ + from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports + + if isinstance(sequence, (Seq, MutableSeq)): + return sequence.complement(inplace) + if isinstance(sequence, SeqRecord): + if inplace: + raise TypeError("SeqRecords are immutable") + return sequence.complement() + # Assume it's a string. + if inplace is True: + raise TypeError("strings are immutable") + sequence = sequence.encode("ASCII") + sequence = sequence.translate(_dna_complement_table) + return sequence.decode("ASCII") + + +def complement_rna(sequence, inplace=False): + """Return the complement as an RNA sequence. + + If given a string, returns a new string object. + Given a Seq object, returns a new Seq object. + Given a MutableSeq, returns a new MutableSeq object. + Given a SeqRecord object, returns a new SeqRecord object. + + >>> my_seq = "CGA" + >>> complement_rna(my_seq) + 'GCU' + >>> my_seq = Seq("CGA") + >>> complement_rna(my_seq) + Seq('GCU') + >>> my_seq = MutableSeq("CGA") + >>> complement_rna(my_seq) + MutableSeq('GCU') + >>> my_seq + MutableSeq('CGA') + + Any T in the sequence is treated as a U: + + >>> complement_rna(Seq("CGAUT")) + Seq('GCUAA') + + In contrast, ``complement`` returns a DNA sequence: + + >>> complement(Seq("CGAUT")) + Seq('GCTAA') + + Supports and lower- and upper-case characters, and unambiguous and + ambiguous nucleotides. All other characters are not converted: + + >>> complement_rna("ACGTUacgtuXYZxyz") + 'UGCAAugcaaXRZxrz' + + The sequence is modified in-place and returned if inplace is True: + + >>> my_seq = MutableSeq("CGA") + >>> complement(my_seq, inplace=True) + MutableSeq('GCT') + >>> my_seq + MutableSeq('GCT') + + As strings and ``Seq`` objects are immutable, a ``TypeError`` is + raised if ``reverse_complement`` is called on a ``Seq`` object with + ``inplace=True``. + """ + from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports + + if isinstance(sequence, (Seq, MutableSeq)): + return sequence.complement_rna(inplace) + if isinstance(sequence, SeqRecord): + if inplace: + raise TypeError("SeqRecords are immutable") + return sequence.complement_rna() + # Assume it's a string. + if inplace: + raise TypeError("strings are immutable") + sequence = sequence.encode("ASCII") + sequence = sequence.translate(_rna_complement_table) + return sequence.decode("ASCII") + + +if __name__ == "__main__": + from doctest import IGNORE_EXCEPTION_DETAIL + from Bio._utils import run_doctest + + run_doctest(optionflags=IGNORE_EXCEPTION_DETAIL) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca867bd82eb67c15caf8c3381b1de8f13e7e075 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py @@ -0,0 +1,2332 @@ +# Copyright 2000-2003 Jeff Chang. +# Copyright 2001-2008 Brad Chapman. +# Copyright 2005-2024 by Peter Cock. +# Copyright 2006-2009 Michiel de Hoon. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Represent a Sequence Feature holding info about a part of a sequence. + +This is heavily modeled after the Biocorba SeqFeature objects, and +may be pretty biased towards GenBank stuff since I'm writing it +for the GenBank parser output... + +What's here: + +Base class to hold a Feature +---------------------------- + +Classes: + - SeqFeature + +Hold information about a Reference +---------------------------------- + +This is an attempt to create a General class to hold Reference type +information. + +Classes: + - Reference + +Specify locations of a feature on a Sequence +-------------------------------------------- + +This aims to handle, in Ewan Birney's words, 'the dreaded fuzziness issue'. +This has the advantages of allowing us to handle fuzzy stuff in case anyone +needs it, and also be compatible with BioPerl etc and BioSQL. + +Classes: + - Location - abstract base class of SimpleLocation and CompoundLocation. + - SimpleLocation - Specify the start and end location of a feature. + - CompoundLocation - Collection of SimpleLocation objects (for joins etc). + - Position - abstract base class of ExactPosition, WithinPosition, + BetweenPosition, AfterPosition, OneOfPosition, UncertainPosition, and + UnknownPosition. + - ExactPosition - Specify the position as being exact. + - WithinPosition - Specify a position occurring within some range. + - BetweenPosition - Specify a position occurring between a range (OBSOLETE?). + - BeforePosition - Specify the position as being found before some base. + - AfterPosition - Specify the position as being found after some base. + - OneOfPosition - Specify a position consisting of multiple alternative positions. + - UncertainPosition - Specify a specific position which is uncertain. + - UnknownPosition - Represents missing information like '?' in UniProt. + + +Exceptions: + - LocationParserError - Exception indicating a failure to parse a location + string. + +""" + +import functools +import re +import warnings +from abc import ABC +from abc import abstractmethod + +from Bio import BiopythonParserWarning +from Bio.Seq import MutableSeq +from Bio.Seq import reverse_complement +from Bio.Seq import Seq + +# Regular expressions for location parsing + +_reference = r"(?:[a-zA-Z][a-zA-Z0-9_\.\|]*[a-zA-Z0-9]?\:)" +_oneof_position = r"one\-of\(\d+[,\d+]+\)" + +_oneof_location = rf"[<>]?(?:\d+|{_oneof_position})\.\.[<>]?(?:\d+|{_oneof_position})" + +_any_location = rf"({_reference}?{_oneof_location}|complement\({_oneof_location}\)|[^,]+|complement\([^,]+\))" + +_split = re.compile(_any_location).split + +assert _split("123..145")[1::2] == ["123..145"] +assert _split("123..145,200..209")[1::2] == ["123..145", "200..209"] +assert _split("one-of(200,203)..300")[1::2] == ["one-of(200,203)..300"] +assert _split("complement(123..145),200..209")[1::2] == [ + "complement(123..145)", + "200..209", +] +assert _split("123..145,one-of(200,203)..209")[1::2] == [ + "123..145", + "one-of(200,203)..209", +] +assert _split("123..145,one-of(200,203)..one-of(209,211),300")[1::2] == [ + "123..145", + "one-of(200,203)..one-of(209,211)", + "300", +] +assert _split("123..145,complement(one-of(200,203)..one-of(209,211)),300")[1::2] == [ + "123..145", + "complement(one-of(200,203)..one-of(209,211))", + "300", +] +assert _split("123..145,200..one-of(209,211),300")[1::2] == [ + "123..145", + "200..one-of(209,211)", + "300", +] +assert _split("123..145,200..one-of(209,211)")[1::2] == [ + "123..145", + "200..one-of(209,211)", +] +assert _split( + "complement(149815..150200),complement(293787..295573),NC_016402.1:6618..6676,181647..181905" +)[1::2] == [ + "complement(149815..150200)", + "complement(293787..295573)", + "NC_016402.1:6618..6676", + "181647..181905", +] + +_pair_location = r"[<>]?-?\d+\.\.[<>]?-?\d+" + +_between_location = r"\d+\^\d+" + +_within_position = r"\(\d+\.\d+\)" +_within_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" % ( + _within_position, + _within_position, +) +_within_position = r"\((\d+)\.(\d+)\)" +_re_within_position = re.compile(_within_position) +assert _re_within_position.match("(3.9)") + +_oneof_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" % (_oneof_position, _oneof_position) +_oneof_position = r"one\-of\((\d+[,\d+]+)\)" +_re_oneof_position = re.compile(_oneof_position) +assert _re_oneof_position.match("one-of(6,9)") +assert not _re_oneof_position.match("one-of(3)") +assert _re_oneof_position.match("one-of(3,6)") +assert _re_oneof_position.match("one-of(3,6,9)") + +_solo_location = r"[<>]?\d+" +_solo_bond = r"bond\(%s\)" % _solo_location + +_re_location_category = re.compile( + r"^(?P%s)|(?P%s)|(?P%s)|(?P%s)|(?P%s)|(?P%s)$" + % ( + _pair_location, + _between_location, + _within_location, + _oneof_location, + _solo_bond, + _solo_location, + ) +) + + +class LocationParserError(ValueError): + """Could not parse a feature location string.""" + + +class SeqFeature: + """Represent a Sequence Feature on an object. + + Attributes: + - location - the location of the feature on the sequence (SimpleLocation) + - type - the specified type of the feature (ie. CDS, exon, repeat...) + - id - A string identifier for the feature. + - qualifiers - A dictionary of qualifiers on the feature. These are + analogous to the qualifiers from a GenBank feature table. The keys of + the dictionary are qualifier names, the values are the qualifier + values. + + """ + + def __init__( + self, + location=None, + type="", + id="", + qualifiers=None, + sub_features=None, + ): + """Initialize a SeqFeature on a sequence. + + location can either be a SimpleLocation (with strand argument also + given if required), or None. + + e.g. With no strand, on the forward strand, and on the reverse strand: + + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> f1 = SeqFeature(SimpleLocation(5, 10), type="domain") + >>> f1.location.strand == None + True + >>> f2 = SeqFeature(SimpleLocation(7, 110, strand=1), type="CDS") + >>> f2.location.strand == +1 + True + >>> f3 = SeqFeature(SimpleLocation(9, 108, strand=-1), type="CDS") + >>> f3.location.strand == -1 + True + + For exact start/end positions, an integer can be used (as shown above) + as shorthand for the ExactPosition object. For non-exact locations, the + SimpleLocation must be specified via the appropriate position objects. + """ + if ( + location is not None + and not isinstance(location, SimpleLocation) + and not isinstance(location, CompoundLocation) + ): + raise TypeError( + "SimpleLocation, CompoundLocation (or None) required for the location" + ) + self.location = location + self.type = type + self.id = id + self.qualifiers = {} + if qualifiers is not None: + self.qualifiers.update(qualifiers) + if sub_features is not None: + raise TypeError("Rather than sub_features, use a CompoundLocation") + + def __eq__(self, other): + """Check if two SeqFeature objects should be considered equal.""" + return ( + isinstance(other, SeqFeature) + and self.id == other.id + and self.type == other.type + and self.location == other.location + and self.qualifiers == other.qualifiers + ) + + def __repr__(self): + """Represent the feature as a string for debugging.""" + answer = f"{self.__class__.__name__}({self.location!r}" + if self.type: + answer += f", type={self.type!r}" + if self.id and self.id != "": + answer += f", id={self.id!r}" + if self.qualifiers: + answer += ", qualifiers=..." + answer += ")" + return answer + + def __str__(self): + """Return the full feature as a python string.""" + out = f"type: {self.type}\n" + out += f"location: {self.location}\n" + if self.id and self.id != "": + out += f"id: {self.id}\n" + out += "qualifiers:\n" + for qual_key in sorted(self.qualifiers): + out += f" Key: {qual_key}, Value: {self.qualifiers[qual_key]}\n" + return out + + def _shift(self, offset): + """Return a copy of the feature with its location shifted (PRIVATE). + + The annotation qualifiers are copied. + """ + return SeqFeature( + location=self.location._shift(offset), + type=self.type, + id=self.id, + qualifiers=self.qualifiers.copy(), + ) + + def _flip(self, length): + """Return a copy of the feature with its location flipped (PRIVATE). + + The argument length gives the length of the parent sequence. For + example a location 0..20 (+1 strand) with parent length 30 becomes + after flipping 10..30 (-1 strand). Strandless (None) or unknown + strand (0) remain like that - just their end points are changed. + + The annotation qualifiers are copied. + """ + return SeqFeature( + location=self.location._flip(length), + type=self.type, + id=self.id, + qualifiers=self.qualifiers.copy(), + ) + + def extract(self, parent_sequence, references=None): + """Extract the feature's sequence from supplied parent sequence. + + The parent_sequence can be a Seq like object or a string, and will + generally return an object of the same type. The exception to this is + a MutableSeq as the parent sequence will return a Seq object. + + This should cope with complex locations including complements, joins + and fuzzy positions. Even mixed strand features should work! This + also covers features on protein sequences (e.g. domains), although + here reverse strand features are not permitted. If the + location refers to other records, they must be supplied in the + optional dictionary references. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL") + >>> f = SeqFeature(SimpleLocation(8, 15), type="domain") + >>> f.extract(seq) + Seq('VALIVIC') + + If the SimpleLocation is None, e.g. when parsing invalid locus + locations in the GenBank parser, extract() will raise a ValueError. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SeqFeature + >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL") + >>> f = SeqFeature(None, type="domain") + >>> f.extract(seq) + Traceback (most recent call last): + ... + ValueError: The feature's .location is None. Check the sequence file for a valid location. + + Note - currently only compound features of type "join" are supported. + """ + if self.location is None: + raise ValueError( + "The feature's .location is None. Check the " + "sequence file for a valid location." + ) + return self.location.extract(parent_sequence, references=references) + + def translate( + self, + parent_sequence, + table="Standard", + start_offset=None, + stop_symbol="*", + to_stop=False, + cds=None, + gap=None, + ): + """Get a translation of the feature's sequence. + + This method is intended for CDS or other features that code proteins + and is a shortcut that will both extract the feature and + translate it, taking into account the codon_start and transl_table + qualifiers, if they are present. If they are not present the + value of the arguments "table" and "start_offset" are used. + + The "cds" parameter is set to "True" if the feature is of type + "CDS" but can be overridden by giving an explicit argument. + + The arguments stop_symbol, to_stop and gap have the same meaning + as Seq.translate, refer to that documentation for further information. + + Arguments: + - parent_sequence - A DNA or RNA sequence. + - table - Which codon table to use if there is no transl_table + qualifier for this feature. This can be either a name + (string), an NCBI identifier (integer), or a CodonTable + object (useful for non-standard genetic codes). This + defaults to the "Standard" table. + - start_offset - offset at which the first complete codon of a + coding feature can be found, relative to the first base of + that feature. Has a valid value of 0, 1 or 2. NOTE: this + uses python's 0-based numbering whereas the codon_start + qualifier in files from NCBI use 1-based numbering. + Will override a codon_start qualifier + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> seq = Seq("GGTTACACTTACCGATAATGTCTCTGATGA") + >>> f = SeqFeature(SimpleLocation(0, 30), type="CDS") + >>> f.qualifiers['transl_table'] = [11] + + Note that features of type CDS are subject to the usual + checks at translation. But you can override this behavior + by giving explicit arguments: + + >>> f.translate(seq, cds=False) + Seq('GYTYR*CL**') + + Now use the start_offset argument to change the frame. Note + this uses python 0-based numbering. + + >>> f.translate(seq, start_offset=1, cds=False) + Seq('VTLTDNVSD') + + Alternatively use the codon_start qualifier to do the same + thing. Note: this uses 1-based numbering, which is found + in files from NCBI. + + >>> f.qualifiers['codon_start'] = [2] + >>> f.translate(seq, cds=False) + Seq('VTLTDNVSD') + """ + # see if this feature should be translated in a different + # frame using the "codon_start" qualifier + if start_offset is None: + try: + start_offset = int(self.qualifiers["codon_start"][0]) - 1 + except KeyError: + start_offset = 0 + + if start_offset not in [0, 1, 2]: + raise ValueError( + "The start_offset must be 0, 1, or 2. " + f"The supplied value is {start_offset}. " + "Check the value of either the codon_start qualifier " + "or the start_offset argument" + ) + + feat_seq = self.extract(parent_sequence)[start_offset:] + codon_table = self.qualifiers.get("transl_table", [table])[0] + + if cds is None: + cds = self.type == "CDS" + + return feat_seq.translate( + table=codon_table, + stop_symbol=stop_symbol, + to_stop=to_stop, + cds=cds, + gap=gap, + ) + + def __bool__(self): + """Boolean value of an instance of this class (True). + + This behavior is for backwards compatibility, since until the + __len__ method was added, a SeqFeature always evaluated as True. + + Note that in comparison, Seq objects, strings, lists, etc, will all + evaluate to False if they have length zero. + + WARNING: The SeqFeature may in future evaluate to False when its + length is zero (in order to better match normal python behavior)! + """ + return True + + def __len__(self): + """Return the length of the region where the feature is located. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL") + >>> f = SeqFeature(SimpleLocation(8, 15), type="domain") + >>> len(f) + 7 + >>> f.extract(seq) + Seq('VALIVIC') + >>> len(f.extract(seq)) + 7 + + This is a proxy for taking the length of the feature's location: + + >>> len(f.location) + 7 + + For simple features this is the same as the region spanned (end + position minus start position using Pythonic counting). However, for + a compound location (e.g. a CDS as the join of several exons) the + gaps are not counted (e.g. introns). This ensures that len(f) matches + len(f.extract(parent_seq)), and also makes sure things work properly + with features wrapping the origin etc. + """ + return len(self.location) + + def __iter__(self): + """Iterate over the parent positions within the feature. + + The iteration order is strand aware, and can be thought of as moving + along the feature using the parent sequence coordinates: + + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain") + >>> len(f) + 5 + >>> for i in f: print(i) + 9 + 8 + 7 + 6 + 5 + >>> list(f) + [9, 8, 7, 6, 5] + + This is a proxy for iterating over the location, + + >>> list(f.location) + [9, 8, 7, 6, 5] + """ + return iter(self.location) + + def __contains__(self, value): + """Check if an integer position is within the feature. + + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain") + >>> len(f) + 5 + >>> [i for i in range(15) if i in f] + [5, 6, 7, 8, 9] + + For example, to see which features include a SNP position, you could + use this: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("GenBank/NC_000932.gb", "gb") + >>> for f in record.features: + ... if 1750 in f: + ... print("%s %s" % (f.type, f.location)) + source [0:154478](+) + gene [1716:4347](-) + tRNA join{[4310:4347](-), [1716:1751](-)} + + Note that for a feature defined as a join of several subfeatures (e.g. + the union of several exons) the gaps are not checked (e.g. introns). + In this example, the tRNA location is defined in the GenBank file as + complement(join(1717..1751,4311..4347)), so that position 1760 falls + in the gap: + + >>> for f in record.features: + ... if 1760 in f: + ... print("%s %s" % (f.type, f.location)) + source [0:154478](+) + gene [1716:4347](-) + + Note that additional care may be required with fuzzy locations, for + example just before a BeforePosition: + + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> from Bio.SeqFeature import BeforePosition + >>> f = SeqFeature(SimpleLocation(BeforePosition(3), 8), type="domain") + >>> len(f) + 5 + >>> [i for i in range(10) if i in f] + [3, 4, 5, 6, 7] + + Note that is is a proxy for testing membership on the location. + + >>> [i for i in range(10) if i in f.location] + [3, 4, 5, 6, 7] + """ + return value in self.location + + +# --- References + + +# TODO -- Will this hold PubMed and Medline information decently? +class Reference: + """Represent a Generic Reference object. + + Attributes: + - location - A list of Location objects specifying regions of + the sequence that the references correspond to. If no locations are + specified, the entire sequence is assumed. + - authors - A big old string, or a list split by author, of authors + for the reference. + - title - The title of the reference. + - journal - Journal the reference was published in. + - medline_id - A medline reference for the article. + - pubmed_id - A pubmed reference for the article. + - comment - A place to stick any comments about the reference. + + """ + + def __init__(self): + """Initialize the class.""" + self.location = [] + self.authors = "" + self.consrtm = "" + self.title = "" + self.journal = "" + self.medline_id = "" + self.pubmed_id = "" + self.comment = "" + + def __str__(self): + """Return the full Reference object as a python string.""" + out = "" + for single_location in self.location: + out += f"location: {single_location}\n" + out += f"authors: {self.authors}\n" + if self.consrtm: + out += f"consrtm: {self.consrtm}\n" + out += f"title: {self.title}\n" + out += f"journal: {self.journal}\n" + out += f"medline id: {self.medline_id}\n" + out += f"pubmed id: {self.pubmed_id}\n" + out += f"comment: {self.comment}\n" + return out + + def __repr__(self): + """Represent the Reference object as a string for debugging.""" + # TODO - Update this is __init__ later accepts values + return f"{self.__class__.__name__}(title={self.title!r}, ...)" + + def __eq__(self, other): + """Check if two Reference objects should be considered equal. + + Note prior to Biopython 1.70 the location was not compared, as + until then __eq__ for the SimpleLocation class was not defined. + """ + return ( + self.authors == other.authors + and self.consrtm == other.consrtm + and self.title == other.title + and self.journal == other.journal + and self.medline_id == other.medline_id + and self.pubmed_id == other.pubmed_id + and self.comment == other.comment + and self.location == other.location + ) + + +# --- Handling feature locations + + +class Location(ABC): + """Abstract base class representing a location.""" + + @abstractmethod + def __repr__(self): + """Represent the Location object as a string for debugging.""" + return f"{self.__class__.__name__}(...)" + + @staticmethod + def fromstring(text, length=None, circular=False, stranded=True): + """Create a Location object from a string. + + This should accept any valid location string in the INSDC Feature Table + format (https://www.insdc.org/submitting-standards/feature-table/) as + used in GenBank, DDBJ and EMBL files. + + Simple examples: + + >>> Location.fromstring("123..456", 1000) + SimpleLocation(ExactPosition(122), ExactPosition(456), strand=1) + >>> Location.fromstring("complement(<123..>456)", 1000) + SimpleLocation(BeforePosition(122), AfterPosition(456), strand=-1) + + A more complex location using within positions, + + >>> Location.fromstring("(9.10)..(20.25)", 1000) + SimpleLocation(WithinPosition(8, left=8, right=9), WithinPosition(25, left=20, right=25), strand=1) + + Notice how that will act as though it has overall start 8 and end 25. + + Zero length between feature, + + >>> Location.fromstring("123^124", 1000) + SimpleLocation(ExactPosition(123), ExactPosition(123), strand=1) + + The expected sequence length is needed for a special case, a between + position at the start/end of a circular genome: + + >>> Location.fromstring("1000^1", 1000) + SimpleLocation(ExactPosition(1000), ExactPosition(1000), strand=1) + + Apart from this special case, between positions P^Q must have P+1==Q, + + >>> Location.fromstring("123^456", 1000) + Traceback (most recent call last): + ... + Bio.SeqFeature.LocationParserError: invalid feature location '123^456' + + You can optionally provide a reference name: + + >>> Location.fromstring("AL391218.9:105173..108462", 2000000) + SimpleLocation(ExactPosition(105172), ExactPosition(108462), strand=1, ref='AL391218.9') + + >>> Location.fromstring("<2644..159", 2868, "circular") + CompoundLocation([SimpleLocation(BeforePosition(2643), ExactPosition(2868), strand=1), SimpleLocation(ExactPosition(0), ExactPosition(159), strand=1)], 'join') + """ + if text.startswith("complement("): + if text[-1] != ")": + raise ValueError(f"closing bracket missing in '{text}'") + text = text[11:-1] + strand = -1 + elif stranded: + strand = 1 + else: + strand = None + + # Determine if we have a simple location or a compound location + if text.startswith("join("): + operator = "join" + parts = _split(text[5:-1])[1::2] + # assert parts[0] == "" and parts[-1] == "" + elif text.startswith("order("): + operator = "order" + parts = _split(text[6:-1])[1::2] + # assert parts[0] == "" and parts[-1] == "" + elif text.startswith("bond("): + operator = "bond" + parts = _split(text[5:-1])[1::2] + # assert parts[0] == "" and parts[-1] == "" + else: + loc = SimpleLocation.fromstring(text, length, circular) + loc.strand = strand + if strand == -1: + loc.parts.reverse() + return loc + locs = [] + for part in parts: + loc = SimpleLocation.fromstring(part, length, circular) + if loc is None: + break + if loc.strand == -1: + if strand == -1: + raise LocationParserError("double complement in '{text}'?") + else: + loc.strand = strand + locs.extend(loc.parts) + else: + if len(locs) == 1: + return loc + # Historically a join on the reverse strand has been represented + # in Biopython with both the parent SeqFeature and its children + # (the exons for a CDS) all given a strand of -1. Likewise, for + # a join feature on the forward strand they all have strand +1. + # However, we must also consider evil mixed strand examples like + # this, join(complement(69611..69724),139856..140087,140625..140650) + if strand == -1: + # Whole thing was wrapped in complement(...) + for loc in locs: + assert loc.strand == -1 + # Reverse the backwards order used in GenBank files + # with complement(join(...)) + locs = locs[::-1] + return CompoundLocation(locs, operator=operator) + # Not recognized + if "order" in text and "join" in text: + # See Bug 3197 + raise LocationParserError( + f"failed to parse feature location '{text}' containing a combination of 'join' and 'order' (nested operators) are illegal" + ) + + # See issue #937. Note that NCBI has already fixed this record. + if ",)" in text: + warnings.warn( + "Dropping trailing comma in malformed feature location", + BiopythonParserWarning, + ) + text = text.replace(",)", ")") + return Location.fromstring(text) + + raise LocationParserError(f"failed to parse feature location '{text}'") + + +class SimpleLocation(Location): + """Specify the location of a feature along a sequence. + + The SimpleLocation is used for simple continuous features, which can + be described as running from a start position to and end position + (optionally with a strand and reference information). More complex + locations made up from several non-continuous parts (e.g. a coding + sequence made up of several exons) are described using a SeqFeature + with a CompoundLocation. + + Note that the start and end location numbering follow Python's scheme, + thus a GenBank entry of 123..150 (one based counting) becomes a location + of [122:150] (zero based counting). + + >>> from Bio.SeqFeature import SimpleLocation + >>> f = SimpleLocation(122, 150) + >>> print(f) + [122:150] + >>> print(f.start) + 122 + >>> print(f.end) + 150 + >>> print(f.strand) + None + + Note the strand defaults to None. If you are working with nucleotide + sequences you'd want to be explicit if it is the forward strand: + + >>> from Bio.SeqFeature import SimpleLocation + >>> f = SimpleLocation(122, 150, strand=+1) + >>> print(f) + [122:150](+) + >>> print(f.strand) + 1 + + Note that for a parent sequence of length n, the SimpleLocation + start and end must satisfy the inequality 0 <= start <= end <= n. + This means even for features on the reverse strand of a nucleotide + sequence, we expect the 'start' coordinate to be less than the + 'end'. + + >>> from Bio.SeqFeature import SimpleLocation + >>> r = SimpleLocation(122, 150, strand=-1) + >>> print(r) + [122:150](-) + >>> print(r.start) + 122 + >>> print(r.end) + 150 + >>> print(r.strand) + -1 + + i.e. Rather than thinking of the 'start' and 'end' biologically in a + strand aware manner, think of them as the 'left most' or 'minimum' + boundary, and the 'right most' or 'maximum' boundary of the region + being described. This is particularly important with compound + locations describing non-continuous regions. + + In the example above we have used standard exact positions, but there + are also specialised position objects used to represent fuzzy positions + as well, for example a GenBank location like complement(<123..150) + would use a BeforePosition object for the start. + """ + + def __init__(self, start, end, strand=None, ref=None, ref_db=None): + """Initialize the class. + + start and end arguments specify the values where the feature begins + and ends. These can either by any of the ``*Position`` objects that + inherit from Position, or can just be integers specifying the position. + In the case of integers, the values are assumed to be exact and are + converted in ExactPosition arguments. This is meant to make it easy + to deal with non-fuzzy ends. + + i.e. Short form: + + >>> from Bio.SeqFeature import SimpleLocation + >>> loc = SimpleLocation(5, 10, strand=-1) + >>> print(loc) + [5:10](-) + + Explicit form: + + >>> from Bio.SeqFeature import SimpleLocation, ExactPosition + >>> loc = SimpleLocation(ExactPosition(5), ExactPosition(10), strand=-1) + >>> print(loc) + [5:10](-) + + Other fuzzy positions are used similarly, + + >>> from Bio.SeqFeature import SimpleLocation + >>> from Bio.SeqFeature import BeforePosition, AfterPosition + >>> loc2 = SimpleLocation(BeforePosition(5), AfterPosition(10), strand=-1) + >>> print(loc2) + [<5:>10](-) + + For nucleotide features you will also want to specify the strand, + use 1 for the forward (plus) strand, -1 for the reverse (negative) + strand, 0 for stranded but strand unknown (? in GFF3), or None for + when the strand does not apply (dot in GFF3), e.g. features on + proteins. + + >>> loc = SimpleLocation(5, 10, strand=+1) + >>> print(loc) + [5:10](+) + >>> print(loc.strand) + 1 + + Normally feature locations are given relative to the parent + sequence you are working with, but an explicit accession can + be given with the optional ref and db_ref strings: + + >>> loc = SimpleLocation(105172, 108462, ref="AL391218.9", strand=1) + >>> print(loc) + AL391218.9[105172:108462](+) + >>> print(loc.ref) + AL391218.9 + + """ + # TODO - Check 0 <= start <= end (<= length of reference) + if isinstance(start, Position): + self._start = start + elif isinstance(start, int): + self._start = ExactPosition(start) + else: + raise TypeError(f"start={start!r} {type(start)}") + if isinstance(end, Position): + self._end = end + elif isinstance(end, int): + self._end = ExactPosition(end) + else: + raise TypeError(f"end={end!r} {type(end)}") + if ( + isinstance(self.start, int) + and isinstance(self.end, int) + and self.start > self.end + ): + raise ValueError( + f"End location ({self.end}) must be greater than " + f"or equal to start location ({self.start})" + ) + self.strand = strand + self.ref = ref + self.ref_db = ref_db + + @staticmethod + def fromstring(text, length=None, circular=False): + """Create a SimpleLocation object from a string.""" + if text.startswith("complement("): + text = text[11:-1] + strand = -1 + else: + strand = None + # Try simple cases first for speed + try: + s, e = text.split("..") + s = int(s) - 1 + e = int(e) + except ValueError: + pass + else: + if 0 <= s < e: + return SimpleLocation(s, e, strand) + # Try general case + try: + ref, text = text.split(":") + except ValueError: + ref = None + m = _re_location_category.match(text) + if m is None: + raise LocationParserError(f"Could not parse feature location '{text}'") + for key, value in m.groupdict().items(): + if value is not None: + break + assert value == text + if key == "bond": + # e.g. bond(196) + warnings.warn( + "Dropping bond qualifier in feature location", + BiopythonParserWarning, + ) + text = text[5:-1] + s_pos = Position.fromstring(text, -1) + e_pos = Position.fromstring(text) + elif key == "solo": + # e.g. "123" + s_pos = Position.fromstring(text, -1) + e_pos = Position.fromstring(text) + elif key in ("pair", "within", "oneof"): + s, e = text.split("..") + # Attempt to fix features that span the origin + s_pos = Position.fromstring(s, -1) + e_pos = Position.fromstring(e) + # We have seen Ensembl data in "GenBank Format" with length zero in the LOCUS + # and variation features with s_pos >= e_pos - they are not origin wrapping! + if e_pos <= s_pos and length and s_pos < length: + # Assuming this is meant to be origin wrapping. + # Create a CompoundLocation of the wrapped feature, + # consisting of two SimpleLocation objects to extend to + # the list of feature locations. + if not circular: + raise LocationParserError( + f"it appears that '{text}' is a feature that spans the" + " origin, but the sequence topology is undefined" + ) + warnings.warn( + f"Attempting to fix invalid location {text!r} as it looks" + " like incorrect origin wrapping. Please fix input file," + " this could have unintended behavior.", + BiopythonParserWarning, + ) + + f1 = SimpleLocation(s_pos, length, strand) + f2 = SimpleLocation(0, e_pos, strand) + + if strand == -1: + # For complementary features spanning the origin + return f2 + f1 + else: + return f1 + f2 + elif key == "between": + # A between location like "67^68" (one based counting) is a + # special case (note it has zero length). In python slice + # notation this is 67:67, a zero length slice. See Bug 2622 + # Further more, on a circular genome of length N you can have + # a location N^1 meaning the junction at the origin. See Bug 3098. + # NOTE - We can imagine between locations like "2^4", but this + # is just "3". Similarly, "2^5" is just "3..4" + s, e = text.split("^") + s = int(s) + e = int(e) + if s + 1 == e or (s == length and e == 1): + s_pos = ExactPosition(s) + e_pos = s_pos + else: + raise LocationParserError(f"invalid feature location '{text}'") + if s_pos < 0: + raise LocationParserError( + f"negative starting position in feature location '{text}'" + ) + return SimpleLocation(s_pos, e_pos, strand, ref=ref) + + def _get_strand(self): + """Get function for the strand property (PRIVATE).""" + return self._strand + + def _set_strand(self, value): + """Set function for the strand property (PRIVATE).""" + if value not in [+1, -1, 0, None]: + raise ValueError(f"Strand should be +1, -1, 0 or None, not {value!r}") + self._strand = value + + strand = property( + fget=_get_strand, + fset=_set_strand, + doc="Strand of the location (+1, -1, 0 or None).", + ) + + def __str__(self): + """Return a representation of the SimpleLocation object (with python counting). + + For the simple case this uses the python splicing syntax, [122:150] + (zero based counting) which GenBank would call 123..150 (one based + counting). + """ + answer = f"[{self._start}:{self._end}]" + if self.ref and self.ref_db: + answer = f"{self.ref_db}:{self.ref}{answer}" + elif self.ref: + answer = self.ref + answer + # Is ref_db without ref meaningful? + if self.strand is None: + return answer + elif self.strand == +1: + return answer + "(+)" + elif self.strand == -1: + return answer + "(-)" + else: + # strand = 0, stranded but strand unknown, ? in GFF3 + return answer + "(?)" + + def __repr__(self): + """Represent the SimpleLocation object as a string for debugging.""" + optional = "" + if self.strand is not None: + optional += f", strand={self.strand!r}" + if self.ref is not None: + optional += f", ref={self.ref!r}" + if self.ref_db is not None: + optional += f", ref_db={self.ref_db!r}" + return f"{self.__class__.__name__}({self.start!r}, {self.end!r}{optional})" + + def __add__(self, other): + """Combine location with another SimpleLocation object, or shift it. + + You can add two feature locations to make a join CompoundLocation: + + >>> from Bio.SeqFeature import SimpleLocation + >>> f1 = SimpleLocation(5, 10) + >>> f2 = SimpleLocation(20, 30) + >>> combined = f1 + f2 + >>> print(combined) + join{[5:10], [20:30]} + + This is thus equivalent to: + + >>> from Bio.SeqFeature import CompoundLocation + >>> join = CompoundLocation([f1, f2]) + >>> print(join) + join{[5:10], [20:30]} + + You can also use sum(...) in this way: + + >>> join = sum([f1, f2]) + >>> print(join) + join{[5:10], [20:30]} + + Furthermore, you can combine a SimpleLocation with a CompoundLocation + in this way. + + Separately, adding an integer will give a new SimpleLocation with + its start and end offset by that amount. For example: + + >>> print(f1) + [5:10] + >>> print(f1 + 100) + [105:110] + >>> print(200 + f1) + [205:210] + + This can be useful when editing annotation. + """ + if isinstance(other, SimpleLocation): + return CompoundLocation([self, other]) + elif isinstance(other, int): + return self._shift(other) + else: + # This will allow CompoundLocation's __radd__ to be called: + return NotImplemented + + def __radd__(self, other): + """Return a SimpleLocation object by shifting the location by an integer amount.""" + if isinstance(other, int): + return self._shift(other) + else: + return NotImplemented + + def __sub__(self, other): + """Subtracting an integer will shift the start and end by that amount. + + >>> from Bio.SeqFeature import SimpleLocation + >>> f1 = SimpleLocation(105, 150) + >>> print(f1) + [105:150] + >>> print(f1 - 100) + [5:50] + + This can be useful when editing annotation. You can also add an integer + to a feature location (which shifts in the opposite direction). + """ + if isinstance(other, int): + return self._shift(-other) + else: + return NotImplemented + + def __nonzero__(self): + """Return True regardless of the length of the feature. + + This behavior is for backwards compatibility, since until the + __len__ method was added, a SimpleLocation always evaluated as True. + + Note that in comparison, Seq objects, strings, lists, etc, will all + evaluate to False if they have length zero. + + WARNING: The SimpleLocation may in future evaluate to False when its + length is zero (in order to better match normal python behavior)! + """ + return True + + def __len__(self): + """Return the length of the region described by the SimpleLocation object. + + Note that extra care may be needed for fuzzy locations, e.g. + + >>> from Bio.SeqFeature import SimpleLocation + >>> from Bio.SeqFeature import BeforePosition, AfterPosition + >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10)) + >>> len(loc) + 5 + """ + return int(self._end) - int(self._start) + + def __contains__(self, value): + """Check if an integer position is within the SimpleLocation object. + + Note that extra care may be needed for fuzzy locations, e.g. + + >>> from Bio.SeqFeature import SimpleLocation + >>> from Bio.SeqFeature import BeforePosition, AfterPosition + >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10)) + >>> len(loc) + 5 + >>> [i for i in range(15) if i in loc] + [5, 6, 7, 8, 9] + """ + if not isinstance(value, int): + raise ValueError( + "Currently we only support checking for integer " + "positions being within a SimpleLocation." + ) + if value < self._start or value >= self._end: + return False + else: + return True + + def __iter__(self): + """Iterate over the parent positions within the SimpleLocation object. + + >>> from Bio.SeqFeature import SimpleLocation + >>> from Bio.SeqFeature import BeforePosition, AfterPosition + >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10)) + >>> len(loc) + 5 + >>> for i in loc: print(i) + 5 + 6 + 7 + 8 + 9 + >>> list(loc) + [5, 6, 7, 8, 9] + >>> [i for i in range(15) if i in loc] + [5, 6, 7, 8, 9] + + Note this is strand aware: + + >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10), strand = -1) + >>> list(loc) + [9, 8, 7, 6, 5] + """ + if self.strand == -1: + yield from range(self._end - 1, self._start - 1, -1) + else: + yield from range(self._start, self._end) + + def __eq__(self, other): + """Implement equality by comparing all the location attributes.""" + if not isinstance(other, SimpleLocation): + return False + return ( + self._start == other.start + and self._end == other.end + and self._strand == other.strand + and self.ref == other.ref + and self.ref_db == other.ref_db + ) + + def _shift(self, offset): + """Return a copy of the SimpleLocation shifted by an offset (PRIVATE). + + Returns self when location is relative to an external reference. + """ + # TODO - What if offset is a fuzzy position? + if self.ref or self.ref_db: + return self + return SimpleLocation( + start=self._start + offset, + end=self._end + offset, + strand=self.strand, + ) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE). + + Returns self when location is relative to an external reference. + """ + if self.ref or self.ref_db: + return self + # Note this will flip the start and end too! + if self.strand == +1: + flip_strand = -1 + elif self.strand == -1: + flip_strand = +1 + else: + # 0 or None + flip_strand = self.strand + return SimpleLocation( + start=self._end._flip(length), + end=self._start._flip(length), + strand=flip_strand, + ) + + @property + def parts(self): + """Read only list of sections (always one, the SimpleLocation object). + + This is a convenience property allowing you to write code handling + both SimpleLocation objects (with one part) and more complex + CompoundLocation objects (with multiple parts) interchangeably. + """ + return [self] + + @property + def start(self): + """Start location - left most (minimum) value, regardless of strand. + + Read only, returns an integer like position object, possibly a fuzzy + position. + """ + return self._start + + @property + def end(self): + """End location - right most (maximum) value, regardless of strand. + + Read only, returns an integer like position object, possibly a fuzzy + position. + """ + return self._end + + def extract(self, parent_sequence, references=None): + """Extract the sequence from supplied parent sequence using the SimpleLocation object. + + The parent_sequence can be a Seq like object or a string, and will + generally return an object of the same type. The exception to this is + a MutableSeq as the parent sequence will return a Seq object. + If the location refers to other records, they must be supplied + in the optional dictionary references. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SimpleLocation + >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL") + >>> feature_loc = SimpleLocation(8, 15) + >>> feature_loc.extract(seq) + Seq('VALIVIC') + + """ + if self.ref or self.ref_db: + if not references: + raise ValueError( + f"Feature references another sequence ({self.ref})," + " references mandatory" + ) + elif self.ref not in references: + # KeyError? + raise ValueError( + f"Feature references another sequence ({self.ref})," + " not found in references" + ) + parent_sequence = references[self.ref] + f_seq = parent_sequence[int(self.start) : int(self.end)] + if isinstance(f_seq, MutableSeq): + f_seq = Seq(f_seq) + if self.strand == -1: + f_seq = reverse_complement(f_seq) + return f_seq + + +FeatureLocation = SimpleLocation # OBSOLETE; for backward compatibility only. + + +class CompoundLocation(Location): + """For handling joins etc where a feature location has several parts.""" + + def __init__(self, parts, operator="join"): + """Initialize the class. + + >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation + >>> f1 = SimpleLocation(10, 40, strand=+1) + >>> f2 = SimpleLocation(50, 59, strand=+1) + >>> f = CompoundLocation([f1, f2]) + >>> len(f) == len(f1) + len(f2) == 39 == len(list(f)) + True + >>> print(f.operator) + join + >>> 5 in f + False + >>> 15 in f + True + >>> f.strand + 1 + + Notice that the strand of the compound location is computed + automatically - in the case of mixed strands on the sub-locations + the overall strand is set to None. + + >>> f = CompoundLocation([SimpleLocation(3, 6, strand=+1), + ... SimpleLocation(10, 13, strand=-1)]) + >>> print(f.strand) + None + >>> len(f) + 6 + >>> list(f) + [3, 4, 5, 12, 11, 10] + + The example above doing list(f) iterates over the coordinates within the + feature. This allows you to use max and min on the location, to find the + range covered: + + >>> min(f) + 3 + >>> max(f) + 12 + + More generally, you can use the compound location's start and end which + give the full span covered, 0 <= start <= end <= full sequence length. + + >>> f.start == min(f) + True + >>> f.end == max(f) + 1 + True + + This is consistent with the behavior of the SimpleLocation for a single + region, where again the 'start' and 'end' do not necessarily give the + biological start and end, but rather the 'minimal' and 'maximal' + coordinate boundaries. + + Note that adding locations provides a more intuitive method of + construction: + + >>> f = SimpleLocation(3, 6, strand=+1) + SimpleLocation(10, 13, strand=-1) + >>> len(f) + 6 + >>> list(f) + [3, 4, 5, 12, 11, 10] + """ + self.operator = operator + self.parts = list(parts) + for loc in self.parts: + if not isinstance(loc, SimpleLocation): + raise ValueError( + "CompoundLocation should be given a list of " + "SimpleLocation objects, not %s" % loc.__class__ + ) + if len(parts) < 2: + raise ValueError( + f"CompoundLocation should have at least 2 parts, not {parts!r}" + ) + + def __str__(self): + """Return a representation of the CompoundLocation object (with python counting).""" + return "%s{%s}" % (self.operator, ", ".join(str(loc) for loc in self.parts)) + + def __repr__(self): + """Represent the CompoundLocation object as string for debugging.""" + return f"{self.__class__.__name__}({self.parts!r}, {self.operator!r})" + + def _get_strand(self): + """Get function for the strand property (PRIVATE).""" + # Historically a join on the reverse strand has been represented + # in Biopython with both the parent SeqFeature and its children + # (the exons for a CDS) all given a strand of -1. Likewise, for + # a join feature on the forward strand they all have strand +1. + # However, we must also consider evil mixed strand examples like + # this, join(complement(69611..69724),139856..140087,140625..140650) + if len({loc.strand for loc in self.parts}) == 1: + return self.parts[0].strand + else: + return None # i.e. mixed strands + + def _set_strand(self, value): + """Set function for the strand property (PRIVATE).""" + # Should this be allowed/encouraged? + for loc in self.parts: + loc.strand = value + + strand = property( + fget=_get_strand, + fset=_set_strand, + doc="""Overall strand of the compound location. + + If all the parts have the same strand, that is returned. Otherwise + for mixed strands, this returns None. + + >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation + >>> f1 = SimpleLocation(15, 17, strand=1) + >>> f2 = SimpleLocation(20, 30, strand=-1) + >>> f = f1 + f2 + >>> f1.strand + 1 + >>> f2.strand + -1 + >>> f.strand + >>> f.strand is None + True + + If you set the strand of a CompoundLocation, this is applied to + all the parts - use with caution: + + >>> f.strand = 1 + >>> f1.strand + 1 + >>> f2.strand + 1 + >>> f.strand + 1 + + """, + ) + + def __add__(self, other): + """Combine locations, or shift the location by an integer offset. + + >>> from Bio.SeqFeature import SimpleLocation + >>> f1 = SimpleLocation(15, 17) + SimpleLocation(20, 30) + >>> print(f1) + join{[15:17], [20:30]} + + You can add another SimpleLocation: + + >>> print(f1 + SimpleLocation(40, 50)) + join{[15:17], [20:30], [40:50]} + >>> print(SimpleLocation(5, 10) + f1) + join{[5:10], [15:17], [20:30]} + + You can also add another CompoundLocation: + + >>> f2 = SimpleLocation(40, 50) + SimpleLocation(60, 70) + >>> print(f2) + join{[40:50], [60:70]} + >>> print(f1 + f2) + join{[15:17], [20:30], [40:50], [60:70]} + + Also, as with the SimpleLocation, adding an integer shifts the + location's coordinates by that offset: + + >>> print(f1 + 100) + join{[115:117], [120:130]} + >>> print(200 + f1) + join{[215:217], [220:230]} + >>> print(f1 + (-5)) + join{[10:12], [15:25]} + """ + if isinstance(other, SimpleLocation): + return CompoundLocation(self.parts + [other], self.operator) + elif isinstance(other, CompoundLocation): + if self.operator != other.operator: + # Handle join+order -> order as a special case? + raise ValueError( + f"Mixed operators {self.operator} and {other.operator}" + ) + return CompoundLocation(self.parts + other.parts, self.operator) + elif isinstance(other, int): + return self._shift(other) + else: + raise NotImplementedError + + def __radd__(self, other): + """Add a feature to the left.""" + if isinstance(other, SimpleLocation): + return CompoundLocation([other] + self.parts, self.operator) + elif isinstance(other, int): + return self._shift(other) + else: + raise NotImplementedError + + def __contains__(self, value): + """Check if an integer position is within the CompoundLocation object.""" + for loc in self.parts: + if value in loc: + return True + return False + + def __nonzero__(self): + """Return True regardless of the length of the feature. + + This behavior is for backwards compatibility, since until the + __len__ method was added, a SimpleLocation always evaluated as True. + + Note that in comparison, Seq objects, strings, lists, etc, will all + evaluate to False if they have length zero. + + WARNING: The SimpleLocation may in future evaluate to False when its + length is zero (in order to better match normal python behavior)! + """ + return True + + def __len__(self): + """Return the length of the CompoundLocation object.""" + return sum(len(loc) for loc in self.parts) + + def __iter__(self): + """Iterate over the parent positions within the CompoundLocation object.""" + for loc in self.parts: + yield from loc + + def __eq__(self, other): + """Check if all parts of CompoundLocation are equal to all parts of other CompoundLocation.""" + if not isinstance(other, CompoundLocation): + return False + if len(self.parts) != len(other.parts): + return False + if self.operator != other.operator: + return False + for self_part, other_part in zip(self.parts, other.parts): + if self_part != other_part: + return False + return True + + def _shift(self, offset): + """Return a copy of the CompoundLocation shifted by an offset (PRIVATE).""" + return CompoundLocation( + [loc._shift(offset) for loc in self.parts], self.operator + ) + + def _flip(self, length): + """Return a copy of the locations after the parent is reversed (PRIVATE). + + Note that the order of the parts is NOT reversed unless all parts + have strand=None, since the order has meaning for stranded features. + Consider a CDS on the forward strand with exons small, medium + and large (in length). Once we change the frame of reference + to the reverse complement strand, the start codon is still part of + the small exon, and the stop codon still part of the large exon - + so the part order remains the same! + + Here is an artificial example, were the features map to the two upper + case regions and the lower case runs of n are not used: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SimpleLocation + >>> dna = Seq("nnnnnAGCATCCTGCTGTACnnnnnnnnGAGAMTGCCATGCCCCTGGAGTGAnnnnn") + >>> small = SimpleLocation(5, 20, strand=1) + >>> large = SimpleLocation(28, 52, strand=1) + >>> location = small + large + >>> print(small) + [5:20](+) + >>> print(large) + [28:52](+) + >>> print(location) + join{[5:20](+), [28:52](+)} + >>> for part in location.parts: + ... print(len(part)) + ... + 15 + 24 + + As you can see, this is a silly example where each "exon" is a word: + + >>> print(small.extract(dna).translate()) + SILLY + >>> print(large.extract(dna).translate()) + EXAMPLE* + >>> print(location.extract(dna).translate()) + SILLYEXAMPLE* + >>> for part in location.parts: + ... print(part.extract(dna).translate()) + ... + SILLY + EXAMPLE* + + Now, let's look at this from the reverse strand frame of reference: + + >>> flipped_dna = dna.reverse_complement() + >>> flipped_location = location._flip(len(dna)) + >>> print(flipped_location.extract(flipped_dna).translate()) + SILLYEXAMPLE* + >>> for part in flipped_location.parts: + ... print(part.extract(flipped_dna).translate()) + ... + SILLY + EXAMPLE* + + The key point here is the first part of the CompoundFeature is still the + small exon, while the second part is still the large exon: + + >>> for part in flipped_location.parts: + ... print(len(part)) + ... + 15 + 24 + >>> print(flipped_location) + join{[37:52](-), [5:29](-)} + + Notice the parts are not reversed. However, there was a bug here in older + versions of Biopython which would have given join{[5:29](-), [37:52](-)} + and the translation would have wrongly been "EXAMPLE*SILLY" instead. + + When all the parts have strand None, the order of the parts is reversed. + In principle this does not change the meaning of the location, but improves + the representation of feature locations spanning the origin in circular + molecules. + + >>> loc = SimpleLocation(4, 6, None) + SimpleLocation(0, 1, None) + >>> print(loc) + join{[4:6], [0:1]} + >>> print(loc._flip(6)) + join{[5:6], [0:2]} + + join{[0:2], [5:6]} would not be properly represented in SnapGene, Benchling, etc. + """ + if all(loc.strand is None for loc in self.parts): + return CompoundLocation( + [loc._flip(length) for loc in self.parts[::-1]], self.operator + ) + else: + return CompoundLocation( + [loc._flip(length) for loc in self.parts], self.operator + ) + + @property + def start(self): + """Start location - left most (minimum) value, regardless of strand. + + Read only, returns an integer like position object, possibly a fuzzy + position. + + For the special case of a CompoundLocation wrapping the origin of a + circular genome, this will return zero. + """ + return min(loc.start for loc in self.parts) + + @property + def end(self): + """End location - right most (maximum) value, regardless of strand. + + Read only, returns an integer like position object, possibly a fuzzy + position. + + For the special case of a CompoundLocation wrapping the origin of + a circular genome this will match the genome length. + """ + return max(loc.end for loc in self.parts) + + @property + def ref(self): + """Not present in CompoundLocation, dummy method for API compatibility.""" + return None + + @property + def ref_db(self): + """Not present in CompoundLocation, dummy method for API compatibility.""" + return None + + def extract(self, parent_sequence, references=None): + """Extract the sequence from supplied parent sequence using the CompoundLocation object. + + The parent_sequence can be a Seq like object or a string, and will + generally return an object of the same type. The exception to this is + a MutableSeq as the parent sequence will return a Seq object. + If the location refers to other records, they must be supplied + in the optional dictionary references. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation + >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL") + >>> fl1 = SimpleLocation(2, 8) + >>> fl2 = SimpleLocation(10, 15) + >>> fl3 = CompoundLocation([fl1,fl2]) + >>> fl3.extract(seq) + Seq('QHKAMILIVIC') + + """ + # This copes with mixed strand features & all on reverse: + parts = [ + loc.extract(parent_sequence, references=references) for loc in self.parts + ] + f_seq = functools.reduce(lambda x, y: x + y, parts) + return f_seq + + +class Position(ABC): + """Abstract base class representing a position.""" + + @abstractmethod + def __repr__(self): + """Represent the Position object as a string for debugging.""" + return f"{self.__class__.__name__}(...)" + + @staticmethod + def fromstring(text, offset=0): + """Build a Position object from the text string. + + For an end position, leave offset as zero (default): + + >>> Position.fromstring("5") + ExactPosition(5) + + For a start position, set offset to minus one (for Python counting): + + >>> Position.fromstring("5", -1) + ExactPosition(4) + + This also covers fuzzy positions: + + >>> p = Position.fromstring("<5") + >>> p + BeforePosition(5) + >>> print(p) + <5 + >>> int(p) + 5 + + >>> Position.fromstring(">5") + AfterPosition(5) + + By default assumes an end position, so note the integer behavior: + + >>> p = Position.fromstring("one-of(5,8,11)") + >>> p + OneOfPosition(11, choices=[ExactPosition(5), ExactPosition(8), ExactPosition(11)]) + >>> print(p) + one-of(5,8,11) + >>> int(p) + 11 + + >>> Position.fromstring("(8.10)") + WithinPosition(10, left=8, right=10) + + Fuzzy start positions: + + >>> p = Position.fromstring("<5", -1) + >>> p + BeforePosition(4) + >>> print(p) + <4 + >>> int(p) + 4 + + Notice how the integer behavior changes too! + + >>> p = Position.fromstring("one-of(5,8,11)", -1) + >>> p + OneOfPosition(4, choices=[ExactPosition(4), ExactPosition(7), ExactPosition(10)]) + >>> print(p) + one-of(4,7,10) + >>> int(p) + 4 + + """ + if offset != 0 and offset != -1: + raise ValueError( + "To convert one-based indices to zero-based indices, offset must be either 0 (for end positions) or -1 (for start positions)." + ) + if text == "?": + return UnknownPosition() + if text.startswith("?"): + return UncertainPosition(int(text[1:]) + offset) + if text.startswith("<"): + return BeforePosition(int(text[1:]) + offset) + if text.startswith(">"): + return AfterPosition(int(text[1:]) + offset) + m = _re_within_position.match(text) + if m is not None: + s, e = m.groups() + s = int(s) + offset + e = int(e) + offset + if offset == -1: + default = s + else: + default = e + return WithinPosition(default, left=s, right=e) + m = _re_oneof_position.match(text) + if m is not None: + positions = m.groups()[0] + parts = [ExactPosition(int(pos) + offset) for pos in positions.split(",")] + if offset == -1: + default = min(int(pos) for pos in parts) + else: + default = max(int(pos) for pos in parts) + return OneOfPosition(default, choices=parts) + return ExactPosition(int(text) + offset) + + +class ExactPosition(int, Position): + """Specify the specific position of a boundary. + + Arguments: + - position - The position of the boundary. + - extension - An optional argument which must be zero since we don't + have an extension. The argument is provided so that the same number + of arguments can be passed to all position types. + + In this case, there is no fuzziness associated with the position. + + >>> p = ExactPosition(5) + >>> p + ExactPosition(5) + >>> print(p) + 5 + + >>> isinstance(p, Position) + True + >>> isinstance(p, int) + True + + Integer comparisons and operations should work as expected: + + >>> p == 5 + True + >>> p < 6 + True + >>> p <= 5 + True + >>> p + 10 + ExactPosition(15) + + """ + + def __new__(cls, position, extension=0): + """Create an ExactPosition object.""" + if extension != 0: + raise AttributeError(f"Non-zero extension {extension} for exact position.") + return int.__new__(cls, position) + + # Must define this on Python 3.8 onwards because we redefine __repr__ + def __str__(self): + """Return a representation of the ExactPosition object (with python counting).""" + return str(int(self)) + + def __repr__(self): + """Represent the ExactPosition object as a string for debugging.""" + return "%s(%i)" % (self.__class__.__name__, int(self)) + + def __add__(self, offset): + """Return a copy of the position object with its location shifted (PRIVATE).""" + # By default preserve any subclass + return self.__class__(int(self) + offset) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + # By default preserve any subclass + return self.__class__(length - int(self)) + + +class UncertainPosition(ExactPosition): + """Specify a specific position which is uncertain. + + This is used in UniProt, e.g. ?222 for uncertain position 222, or in the + XML format explicitly marked as uncertain. Does not apply to GenBank/EMBL. + """ + + +class UnknownPosition(Position): + """Specify a specific position which is unknown (has no position). + + This is used in UniProt, e.g. ? or in the XML as unknown. + """ + + def __repr__(self): + """Represent the UnknownPosition object as a string for debugging.""" + return f"{self.__class__.__name__}()" + + def __hash__(self): + """Return the hash value of the UnknownPosition object.""" + return hash(None) + + def __add__(self, offset): + """Return a copy of the position object with its location shifted (PRIVATE).""" + return self + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + return self + + +class WithinPosition(int, Position): + """Specify the position of a boundary within some coordinates. + + Arguments: + - position - The default integer position + - left - The start (left) position of the boundary + - right - The end (right) position of the boundary + + This allows dealing with a location like ((11.14)..100). This + indicates that the start of the sequence is somewhere between 11 + and 14. Since this is a start coordinate, it should act like + it is at position 11 (or in Python counting, 10). + + >>> p = WithinPosition(10, 10, 13) + >>> p + WithinPosition(10, left=10, right=13) + >>> print(p) + (10.13) + >>> int(p) + 10 + + Basic integer comparisons and operations should work as though + this were a plain integer: + + >>> p == 10 + True + >>> p in [9, 10, 11] + True + >>> p < 11 + True + >>> p + 10 + WithinPosition(20, left=20, right=23) + + >>> isinstance(p, WithinPosition) + True + >>> isinstance(p, Position) + True + >>> isinstance(p, int) + True + + Note this also applies for comparison to other position objects, + where again the integer behavior is used: + + >>> p == 10 + True + >>> p == ExactPosition(10) + True + >>> p == BeforePosition(10) + True + >>> p == AfterPosition(10) + True + + If this were an end point, you would want the position to be 13 + (the right/larger value, not the left/smaller value as above): + + >>> p2 = WithinPosition(13, 10, 13) + >>> p2 + WithinPosition(13, left=10, right=13) + >>> print(p2) + (10.13) + >>> int(p2) + 13 + >>> p2 == 13 + True + >>> p2 == ExactPosition(13) + True + + """ + + def __new__(cls, position, left, right): + """Create a WithinPosition object.""" + if not (position == left or position == right): + raise RuntimeError( + "WithinPosition: %r should match left %r or " + "right %r" % (position, left, right) + ) + obj = int.__new__(cls, position) + obj._left = left + obj._right = right + return obj + + def __getnewargs__(self): + """Return the arguments accepted by __new__. + + Necessary to allow pickling and unpickling of class instances. + """ + return (int(self), self._left, self._right) + + def __repr__(self): + """Represent the WithinPosition object as a string for debugging.""" + return "%s(%i, left=%i, right=%i)" % ( + self.__class__.__name__, + int(self), + self._left, + self._right, + ) + + def __str__(self): + """Return a representation of the WithinPosition object (with python counting).""" + return f"({self._left}.{self._right})" + + def __add__(self, offset): + """Return a copy of the position object with its location shifted.""" + return self.__class__( + int(self) + offset, self._left + offset, self._right + offset + ) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + return self.__class__( + length - int(self), length - self._right, length - self._left + ) + + +class BetweenPosition(int, Position): + """Specify the position of a boundary between two coordinates (OBSOLETE?). + + Arguments: + - position - The default integer position + - left - The start (left) position of the boundary + - right - The end (right) position of the boundary + + This allows dealing with a position like 123^456. This + indicates that the start of the sequence is somewhere between + 123 and 456. It is up to the parser to set the position argument + to either boundary point (depending on if this is being used as + a start or end of the feature). For example as a feature end: + + >>> p = BetweenPosition(456, 123, 456) + >>> p + BetweenPosition(456, left=123, right=456) + >>> print(p) + (123^456) + >>> int(p) + 456 + + Integer equality and comparison use the given position, + + >>> p == 456 + True + >>> p in [455, 456, 457] + True + >>> p > 300 + True + + The old legacy properties of position and extension give the + starting/lower/left position as an integer, and the distance + to the ending/higher/right position as an integer. Note that + the position object will act like either the left or the right + end-point depending on how it was created: + + >>> p2 = BetweenPosition(123, left=123, right=456) + >>> int(p) == int(p2) + False + >>> p == 456 + True + >>> p2 == 123 + True + + Note this potentially surprising behavior: + + >>> BetweenPosition(123, left=123, right=456) == ExactPosition(123) + True + >>> BetweenPosition(123, left=123, right=456) == BeforePosition(123) + True + >>> BetweenPosition(123, left=123, right=456) == AfterPosition(123) + True + + i.e. For equality (and sorting) the position objects behave like + integers. + + """ + + def __new__(cls, position, left, right): + """Create a new instance in BetweenPosition object.""" + assert position == left or position == right + # TODO - public API for getting left/right, especially the unknown one + obj = int.__new__(cls, position) + obj._left = left + obj._right = right + return obj + + def __getnewargs__(self): + """Return the arguments accepted by __new__. + + Necessary to allow pickling and unpickling of class instances. + """ + return (int(self), self._left, self._right) + + def __repr__(self): + """Represent the BetweenPosition object as a string for debugging.""" + return "%s(%i, left=%i, right=%i)" % ( + self.__class__.__name__, + int(self), + self._left, + self._right, + ) + + def __str__(self): + """Return a representation of the BetweenPosition object (with python counting).""" + return f"({self._left}^{self._right})" + + def __add__(self, offset): + """Return a copy of the position object with its location shifted (PRIVATE).""" + return self.__class__( + int(self) + offset, self._left + offset, self._right + offset + ) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + return self.__class__( + length - int(self), length - self._right, length - self._left + ) + + +class BeforePosition(int, Position): + """Specify a position where the actual location occurs before it. + + Arguments: + - position - The upper boundary of where the location can occur. + - extension - An optional argument which must be zero since we don't + have an extension. The argument is provided so that the same number + of arguments can be passed to all position types. + + This is used to specify positions like (<10..100) where the location + occurs somewhere before position 10. + + >>> p = BeforePosition(5) + >>> p + BeforePosition(5) + >>> print(p) + <5 + >>> int(p) + 5 + >>> p + 10 + BeforePosition(15) + + Note this potentially surprising behavior: + + >>> p == ExactPosition(5) + True + >>> p == AfterPosition(5) + True + + Just remember that for equality and sorting the position objects act + like integers. + """ + + # Subclasses int so can't use __init__ + def __new__(cls, position, extension=0): + """Create a new instance in BeforePosition object.""" + if extension != 0: + raise AttributeError(f"Non-zero extension {extension} for exact position.") + return int.__new__(cls, position) + + def __repr__(self): + """Represent the location as a string for debugging.""" + return "%s(%i)" % (self.__class__.__name__, int(self)) + + def __str__(self): + """Return a representation of the BeforePosition object (with python counting).""" + return f"<{int(self)}" + + def __add__(self, offset): + """Return a copy of the position object with its location shifted (PRIVATE).""" + return self.__class__(int(self) + offset) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + return AfterPosition(length - int(self)) + + +class AfterPosition(int, Position): + """Specify a position where the actual location is found after it. + + Arguments: + - position - The lower boundary of where the location can occur. + - extension - An optional argument which must be zero since we don't + have an extension. The argument is provided so that the same number + of arguments can be passed to all position types. + + This is used to specify positions like (>10..100) where the location + occurs somewhere after position 10. + + >>> p = AfterPosition(7) + >>> p + AfterPosition(7) + >>> print(p) + >7 + >>> int(p) + 7 + >>> p + 10 + AfterPosition(17) + + >>> isinstance(p, AfterPosition) + True + >>> isinstance(p, Position) + True + >>> isinstance(p, int) + True + + Note this potentially surprising behavior: + + >>> p == ExactPosition(7) + True + >>> p == BeforePosition(7) + True + + Just remember that for equality and sorting the position objects act + like integers. + """ + + # Subclasses int so can't use __init__ + def __new__(cls, position, extension=0): + """Create a new instance of the AfterPosition object.""" + if extension != 0: + raise AttributeError(f"Non-zero extension {extension} for exact position.") + return int.__new__(cls, position) + + def __repr__(self): + """Represent the location as a string for debugging.""" + return "%s(%i)" % (self.__class__.__name__, int(self)) + + def __str__(self): + """Return a representation of the AfterPosition object (with python counting).""" + return f">{int(self)}" + + def __add__(self, offset): + """Return a copy of the position object with its location shifted (PRIVATE).""" + return self.__class__(int(self) + offset) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + return BeforePosition(length - int(self)) + + +class OneOfPosition(int, Position): + """Specify a position where the location can be multiple positions. + + This models the GenBank 'one-of(1888,1901)' function, and tries + to make this fit within the Biopython Position models. If this was + a start position it should act like 1888, but as an end position 1901. + + >>> p = OneOfPosition(1888, [ExactPosition(1888), ExactPosition(1901)]) + >>> p + OneOfPosition(1888, choices=[ExactPosition(1888), ExactPosition(1901)]) + >>> int(p) + 1888 + + Integer comparisons and operators act like using int(p), + + >>> p == 1888 + True + >>> p <= 1888 + True + >>> p > 1888 + False + >>> p + 100 + OneOfPosition(1988, choices=[ExactPosition(1988), ExactPosition(2001)]) + + >>> isinstance(p, OneOfPosition) + True + >>> isinstance(p, Position) + True + >>> isinstance(p, int) + True + + """ + + def __new__(cls, position, choices): + """Initialize with a set of possible positions. + + choices is a list of Position derived objects, specifying possible + locations. + + position is an integer specifying the default behavior. + """ + if position not in choices: + raise ValueError( + f"OneOfPosition: {position!r} should match one of {choices!r}" + ) + obj = int.__new__(cls, position) + obj.position_choices = choices + return obj + + def __getnewargs__(self): + """Return the arguments accepted by __new__. + + Necessary to allow pickling and unpickling of class instances. + """ + return (int(self), self.position_choices) + + def __repr__(self): + """Represent the OneOfPosition object as a string for debugging.""" + return "%s(%i, choices=%r)" % ( + self.__class__.__name__, + int(self), + self.position_choices, + ) + + def __str__(self): + """Return a representation of the OneOfPosition object (with python counting).""" + out = "one-of(" + for position in self.position_choices: + out += f"{position}," + # replace the last comma with the closing parenthesis + return out[:-1] + ")" + + def __add__(self, offset): + """Return a copy of the position object with its location shifted (PRIVATE).""" + return self.__class__( + int(self) + offset, [p + offset for p in self.position_choices] + ) + + def _flip(self, length): + """Return a copy of the location after the parent is reversed (PRIVATE).""" + return self.__class__( + length - int(self), [p._flip(length) for p in self.position_choices[::-1]] + ) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AbiIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AbiIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AbiIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AceIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AceIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._AceIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._FastaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._FastaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._FastaIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GckIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GckIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GckIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GfaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GfaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._GfaIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._IgIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._IgIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._IgIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._InsdcIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._InsdcIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._InsdcIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._Interfaces.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._Interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._Interfaces.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._NibIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._NibIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._NibIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PdbIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PdbIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PdbIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PhdIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PhdIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PhdIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PirIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PirIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._PirIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._QualityIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._QualityIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._QualityIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SeqXmlIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SeqXmlIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SeqXmlIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SffIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SffIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SffIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SnapGeneIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SnapGeneIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SnapGeneIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SwissIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SwissIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._SwissIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._TabIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._TabIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._TabIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._TwoBitIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._TwoBitIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._TwoBitIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._UniprotIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._UniprotIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._UniprotIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._XdnaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._XdnaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/._XdnaIO.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__index.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__index.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__index.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__twoBitIO.c b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__twoBitIO.c new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__twoBitIO.c differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__twoBitIO.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__twoBitIO.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/.__twoBitIO.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/AbiIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/AbiIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ad412efab03ad19b72393aa7a6b01be23a70eea4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/AbiIO.py @@ -0,0 +1,605 @@ +# Copyright 2011 by Wibowo Arindrarto (w.arindrarto@gmail.com) +# Revisions copyright 2011-2016 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO parser for the ABI format. + +ABI is the format used by Applied Biosystem's sequencing machines to store +sequencing results. + +For more details on the format specification, visit: +http://www6.appliedbiosystems.com/support/software_community/ABIF_File_Format.pdf + +""" + +import datetime +import io +import struct +import sys +from os.path import basename + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator + +# dictionary for determining which tags goes into SeqRecord annotation +# each key is tag_name + tag_number +# if a tag entry needs to be added, just add its key and its key +# for the annotations dictionary as the value +# dictionary for tags that require preprocessing before use in creating +# seqrecords +_EXTRACT = { + "TUBE1": "sample_well", + "DySN1": "dye", + "GTyp1": "polymer", + "MODL1": "machine_model", +} + + +# Complete data structure representing 98% of the API. The general section +# represents the part of the API that's common to ALL instruments, whereas the +# instrument specific sections are labelled as they are in the ABIF spec +# +# Keys don't seem to clash from machine to machine, so when we parse, we look +# for ANY key, and store that in the raw ABIF data structure attached to the +# annotations, with the assumption that anyone parsing the data can look up the +# spec themself +# +# Key definitions are retained in case end users want "nice" labels pre-made +# for them for all of the available fields. +_INSTRUMENT_SPECIFIC_TAGS = {} + +# fmt: off +_INSTRUMENT_SPECIFIC_TAGS["general"] = { + "APFN2": "Sequencing Analysis parameters file name", + "APXV1": "Analysis Protocol XML schema version", + "APrN1": "Analysis Protocol settings name", + "APrV1": "Analysis Protocol settings version", + "APrX1": "Analysis Protocol XML string", + "CMNT1": "Sample Comment", + "CTID1": "Container Identifier, a.k.a. plate barcode", + "CTNM1": "Container name, usually identical to CTID, but not necessarily so", + "CTTL1": "Comment Title", + "CpEP1": "Capillary type electrophoresis. 1 for a capillary based machine. 0 for a slab gel based machine.", + "DATA1": "Channel 1 raw data", + "DATA2": "Channel 2 raw data", + "DATA3": "Channel 3 raw data", + "DATA4": "Channel 4 raw data", + "DATA5": "Short Array holding measured volts/10 (EP voltage) during run", + "DATA6": "Short Array holding measured milliAmps trace (EP current) during run", + "DATA7": "Short Array holding measured milliWatts trace (Laser EP Power) during run", + "DATA8": "Short Array holding measured oven Temperature (polymer temperature) trace during run", + "DATA9": "Channel 9 processed data", + "DATA10": "Channel 10 processed data", + "DATA11": "Channel 11 processed data", + "DATA12": "Channel 12 processed data", + # Prism 3100/3100-Avant may provide DATA105 + # 3130/3130-XL may provide DATA105 + # 3530/3530-XL may provide DATA105-199, 9-12, 205-299 + "DSam1": "Downsampling factor", + "DySN1": "Dye set name", + "Dye#1": "Number of dyes", + "DyeN1": "Dye 1 name", + "DyeN2": "Dye 2 name", + "DyeN3": "Dye 3 name", + "DyeN4": "Dye 4 name", + "DyeW1": "Dye 1 wavelength", + "DyeW2": "Dye 2 wavelength", + "DyeW3": "Dye 3 wavelength", + "DyeW4": "Dye 4 wavelength", + # 'DyeN5-N': 'Dye 5-N Name', + # 'DyeW5-N': 'Dye 5-N Wavelength', + "EPVt1": "Electrophoresis voltage setting (volts)", + "EVNT1": "Start Run event", + "EVNT2": "Stop Run event", + "EVNT3": "Start Collection event", + "EVNT4": "Stop Collection event", + "FWO_1": 'Base Order. Sequencing Analysis Filter wheel order. Fixed for 3500 at "GATC"', + "GTyp1": "Gel or polymer Type", + "InSc1": "Injection time (seconds)", + "InVt1": "Injection voltage (volts)", + "LANE1": "Lane/Capillary", + "LIMS1": "Sample tracking ID", + "LNTD1": "Length to detector", + "LsrP1": "Laser Power setting (micro Watts)", + "MCHN1": "Instrument name and serial number", + "MODF1": "Data collection module file", + "MODL1": "Model number", + "NAVG1": "Pixels averaged per lane", + "NLNE1": "Number of capillaries", + "OfSc1": "List of scans that are marked off scale in Collection. (optional)", + # OvrI and OrvV are listed as "1-N", and "One for each dye (unanalyzed + # and/or analyzed data)" + "OvrI1": "List of scan number indexes that have values greater than 32767 but did not " + "saturate the camera. In Genemapper samples, this can have indexes with " + "values greater than 32000. In sequencing samples, this cannot have " + "indexes with values greater than 32000.", + "OvrI2": "List of scan number indexes that have values greater than 32767 but did not " + "saturate the camera. In Genemapper samples, this can have indexes with " + "values greater than 32000. In sequencing samples, this cannot have " + "indexes with values greater than 32000.", + "OvrI3": "List of scan number indexes that have values greater than 32767 but did not " + "saturate the camera. In Genemapper samples, this can have indexes with " + "values greater than 32000. In sequencing samples, this cannot have " + "indexes with values greater than 32000.", + "OvrI4": "List of scan number indexes that have values greater than 32767 but did not " + "saturate the camera. In Genemapper samples, this can have indexes with " + "values greater than 32000. In sequencing samples, this cannot have " + "indexes with values greater than 32000.", + "OvrV1": "List of color data values found at the locations listed in the OvrI tag. " + "There must be exactly as many numbers in this array as in the OvrI array.", + "OvrV2": "List of color data values found at the locations listed in the OvrI tag. " + "There must be exactly as many numbers in this array as in the OvrI array.", + "OvrV3": "List of color data values found at the locations listed in the OvrI tag. " + "There must be exactly as many numbers in this array as in the OvrI array.", + "OvrV4": "List of color data values found at the locations listed in the OvrI tag. " + "There must be exactly as many numbers in this array as in the OvrI array.", + "PDMF1": "Sequencing Analysis Mobility file name chosen in collection", + "RMXV1": "Run Module XML schema version", + "RMdN1": "Run Module name (same as MODF)", + "RMdX1": "Run Module XML string", + "RPrN1": "Run Protocol name", + "RPrV1": "Run Protocol version", + "RUND1": "Run Started Date", + "RUND2": "Run Stopped Date", + "RUND3": "Data Collection Started Date", + "RUND4": "Data Collection Stopped date", + "RUNT1": "Run Started Time", + "RUNT2": "Run Stopped Time", + "RUNT3": "Data Collection Started Time", + "RUNT4": "Data Collection Stopped Time", + "Rate1": "Scanning Rate. Milliseconds per frame.", + "RunN1": "Run Name", + "SCAN1": "Number of scans", + "SMED1": "Polymer lot expiration date", + "SMLt1": "Polymer lot number", + "SMPL1": "Sample name", + "SVER1": "Data collection software version", + "SVER3": "Data collection firmware version", + "Satd1": "Array of longs representing the scan numbers of data points, which are flagged as saturated by data collection (optional)", + "Scal1": "Rescaling divisor for color data", + "Scan1": "Number of scans (legacy - use SCAN)", + "TUBE1": "Well ID", + "Tmpr1": "Run temperature setting", + "User1": "Name of user who created the plate (optional)", +} + +# No instrument specific tags +# _INSTRUMENT_SPECIFIC_TAGS['abi_prism_3100/3100-Avant'] = { +# } + +_INSTRUMENT_SPECIFIC_TAGS["abi_3130/3130xl"] = { + "CTOw1": "Container owner", + "HCFG1": "Instrument Class", + "HCFG2": "Instrument Family", + "HCFG3": "Official Instrument Name", + "HCFG4": "Instrument Parameters", + "RMdVa1": "Run Module version", +} + +_INSTRUMENT_SPECIFIC_TAGS["abi_3530/3530xl"] = { + "AAct1": "Primary Analysis Audit Active indication. True if system auditing was enabled during the last write of this file, " + "false if system auditing was disabled.", + "ABED1": "Anode buffer expiration date using ISO 8601 format using the patterns YYYY-MM-DDTHH:MM:SS.ss+/-HH:MM. Hundredths of a second are optional.", + "ABID1": "Anode buffer tray first installed date", + "ABLt1": "Anode buffer lot number", + "ABRn1": "Number of runs (injections) processed with the current Anode Buffer (runs allowed - runs remaining)", + "ABTp1": "Anode buffer type", + "AEPt1": "Analysis Ending scan number for basecalling on initial analysis", + "AEPt2": "Analysis Ending scan number for basecalling on last analysis", + "APCN1": "Amplicon name", + "ARTN1": "Analysis Return code. Produced only by 5 Prime basecaller 1.0b3", + "ASPF1": "Flag to indicate whether adaptive processing worked or not", + "ASPt1": "Analysis Starting scan number for first analysis", + "ASPt2": "Analysis Starting scan number for last analysis", + "AUDT2": "Audit log used across 3500 software (optional)", + "AVld1": "Assay validation flag (true or false)", + "AmbT1": "Record of ambient temperature readings", + "AsyC1": "The assay contents (xml format)", + "AsyN1": "The assay name", + "AsyV1": "The assay version", + "B1Pt1": "Reference scan number for mobility and spacing curves for first analysis", + "B1Pt2": "Reference scan number for mobility and spacing curves for last analysis", + "BCTS1": "Basecaller timestamp. Time of completion of most recent analysis", + "BcRn1": "Basecalling qc code", + "BcRs1": "Basecalling warnings, a concatenated comma separated string", + "BcRs2": "Basecalling errors, a concatenated comma separated string", + "CAED1": "Capillary array expiration", + "CALt1": "Capillary array lot number", + "CARn1": "Number of injections processed (including the one of which this sample was a part) through the capillary array", + "CASN1": "Capillary array serial number", + "CBED1": "Cathode buffer expiration date", + "CBID1": "Cathode buffer tray first installed date", + "CBLt1": "Cathode buffer lot number", + "CBRn1": "Number of runs (injections) processed with the current Cathode Buffer (runs allowed - runs remaining)", + "CBTp1": "Cathode buffer type", + "CLRG1": "Start of the clear range (inclusive).", + "CLRG2": "Clear range length", + "CRLn1": "Contiguous read length", + "CRLn2": 'One of "Pass", "Fail", or "Check"', + "CTOw1": "The name entered as the Owner of a plate, in the plate editor", + "CkSm1": "File checksum", + "DCEv1": "A list of door-close events, separated by semicolon. Door open events are generally paired with door close events.", + "DCHT1": "Reserved for backward compatibility. The detection cell heater temperature setting from the Run Module. Not used for 3500.", + "DOEv1": "A list of door-open events, separated by semicolon. Door close events are generally paired with door open events.", + "ESig2": "Electronic signature record used across 3500 software", + "FTab1": "Feature table. Can be created by Nibbler for Clear Range.", + "FVoc1": "Feature table vocabulary. Can be created by Nibbler for Clear Range.", + "Feat1": "Features. Can be created by Nibbler for Clear Range.", + "HCFG1": "The Instrument Class. All upper case, no spaces. Initial valid value: CE", + "HCFG2": "The Instrument Family. All upper case, no spaces. Valid values: 31XX or 37XX for UDC, 35XX (for 3500)", + "HCFG3": "The official instrument name. Mixed case, minus any special formatting. Initial valid values: 3130, 3130xl, 3730, 3730xl, 3500, 3500xl.", + "HCFG4": "Instrument parameters. Contains key-value pairs of instrument configuration information, separated by semicolons. " + "Four parameters are included initially: UnitID=, CPUBoard=, " + "ArraySize=<# of capillaries>, SerialNumber=.", + "InjN1": "Injection name", + "LAST1": "Parameter settings information", + "NOIS1": "The estimate of rms baseline noise (S/N ratio) for each dye for a successfully analyzed sample. " + "Corresponds in order to the raw data in tags DATA 1-4. KB basecaller only.", + "P1AM1": "Amplitude of primary peak, which is not necessarily equal to corresponding signal strength at that position", + "P1RL1": "Deviation of primary peak position from (PLoc,2), times 100, rounded to integer", + "P1WD1": "Full-width Half-max of primary peak, times 100, rounded to integer. " + "Corresponding signal intensity is not necessarily equal to one half of primary peak amplitude", + "P2AM1": "Amplitude of secondary peak, which is not necessarily equal to corresponding signal strength at that position", + "P2BA1": "Base of secondary peak", + "P2RL1": "Deviation of secondary peak position from (PLoc,2), times 100, rounded to integer", + "PBAS1": "Array of sequence characters edited by user", + "PBAS2": "Array of sequence characters as called by Basecaller", + "PCON1": "Array of quality Values (0-255) as edited by user", + "PCON2": "Array of quality values (0-255) as called by Basecaller", + "PDMF2": "Mobility file name chosen in most recent analysis (identical to PDMF1)", + "PLOC1": "Array of peak locations edited by user", + "PLOC2": "Array of peak locations as called by Basecaller", + "PRJT1": "SeqScape 2.0 project template name", + "PROJ4": "SeqScape 2.0 project name", + "PSZE1": "Plate size. The number of sample positions in the container. Current allowed values: 96, 384.", + "PTYP1": "Plate type. Current allowed values: 96-Well, 384-Well.", + "PuSc1": "Median pupscore", + "QV201": "QV20+ value", + "QV202": 'One of "Pass", "Fail", or "Check"', + "QcPa1": "QC parameters", + "QcRn1": "Trimming and QC code", + "QcRs1": "QC warnings, a concatenated comma separated string", + "QcRs2": "QC errors, a concatenated comma separated string", + "RGOw1": "The name entered as the Owner of a Results Group, in the Results Group Editor. Implemented as the user name from the results group.", + "RInj1": "Reinjection number. The reinjection number that this sample belongs to. Not present if there was no reinjection.", + "RNmF1": "Raman normalization factor", + "RevC1": "for whether the sequence has been complemented", + "RunN1": "Run name (which, for 3500, is different from injection name)", + "S/N%1": "Signal strength for each dye", + "SMID1": "Polymer first installed date", + "SMRn1": "Number of runs (injections) processed with the current polymer (runs allowed - runs remaining)", + "SPAC1": "Average peak spacing used in last analysis", + "SPAC2": "Basecaller name - corresponds to name of bcp file.", + "SPAC3": "Average peak spacing last calculated by the Basecaller.", + "SPEC1": "Sequencing Analysis Specimen Name", + "SVER2": "Basecaller version number", + "SVER4": "Sample File Format Version String", + "ScPa1": "The parameter string of size caller", + "ScSt1": "Raw data start point. Set to 0 for 3500 data collection.", + "SpeN1": "Active spectral calibration name", + "TrPa1": "Trimming parameters", + "TrSc1": "Trace score.", + "TrSc2": 'One of "Pass", "Fail", or "Check"', + "phAR1": "Trace peak aria ratio", + "phCH1": 'Chemistry type ("term", "prim", "unknown"), based on DYE_1 information', + "phDY1": 'Dye ("big", "d-rhod", "unknown"), based on mob file information', + "phQL1": "Maximum Quality Value", + "phTR1": "Set Trim region", + "phTR2": "Trim probability", +} + +_INSTRUMENT_SPECIFIC_TAGS["abi_3730/3730xl"] = { + "BufT1": "Buffer tray heater temperature (degrees C)", +} +# fmt: on + +# dictionary for data unpacking format +_BYTEFMT = { + 1: "b", # byte + 2: "s", # char + 3: "H", # word + 4: "h", # short + 5: "i", # long + 6: "2i", # rational, legacy unsupported + 7: "f", # float + 8: "d", # double + 10: "h2B", # date + 11: "4B", # time + 12: "2i2b", # thumb + 13: "B", # bool + 14: "2h", # point, legacy unsupported + 15: "4h", # rect, legacy unsupported + 16: "2i", # vPoint, legacy unsupported + 17: "4i", # vRect, legacy unsupported + 18: "s", # pString + 19: "s", # cString + 20: "2i", # tag, legacy unsupported +} +# header data structure (excluding 4 byte ABIF marker) +_HEADFMT = ">H4sI2H3I" +# directory data structure +_DIRFMT = ">4sI2H4I" + +__global_tag_listing: list[str] = [] +for tag in _INSTRUMENT_SPECIFIC_TAGS.values(): + __global_tag_listing += tag.keys() + + +def _get_string_tag(opt_bytes_value, default=None): + """Return the string value of the given an optional raw bytes tag value. + + If the bytes value is None, return the given default value. + + """ + if opt_bytes_value is None: + return default + try: + return opt_bytes_value.decode() + except UnicodeDecodeError: + return opt_bytes_value.decode(encoding=sys.getdefaultencoding()) + + +class AbiIterator(SequenceIterator): + """Parser for Abi files.""" + + modes = "b" + + def __init__(self, source, trim=False): + """Return an iterator for the Abi file format.""" + super().__init__(source, fmt="ABI") + # check if input file is a valid Abi file + marker = self.stream.read(4) + if not marker: + # handle empty file gracefully + raise ValueError("Empty file.") + if marker != b"ABIF": + raise ValueError(f"File should start with ABIF, not {marker!r}") + self.trim = trim + + def __next__(self): + """Parse the file and generate SeqRecord objects.""" + stream = self.stream + # dirty hack for handling time information + times = {"RUND1": "", "RUND2": "", "RUNT1": "", "RUNT2": ""} + + # initialize annotations + annot = dict(zip(_EXTRACT.values(), [None] * len(_EXTRACT))) + + # parse header and extract data from directories + size = struct.calcsize(_HEADFMT) + data = stream.read(size) + if len(data) == 0: + raise StopIteration + elif len(data) < size: + raise ValueError("premature end of file") + header = struct.unpack(_HEADFMT, data) + + # Set default sample ID value, which we expect to be present in most + # cases in the SMPL1 tag, but may be missing. + sample_id = "" + + raw = {} + seq = qual = None + for tag_name, tag_number, tag_data in _abi_parse_header(header, stream): + key = tag_name + str(tag_number) + + raw[key] = tag_data + + # PBAS2 is base-called sequence, only available in 3530 + if key == "PBAS2": + seq = tag_data.decode() + # PCON2 is quality values of base-called sequence + elif key == "PCON2": + qual = [ord(val) for val in tag_data.decode()] + # SMPL1 is sample id entered before sequencing run, it must be + # a string. + elif key == "SMPL1": + sample_id = _get_string_tag(tag_data) + elif key in times: + times[key] = tag_data + else: + if key in _EXTRACT: + annot[_EXTRACT[key]] = tag_data + + # set time annotations + annot["run_start"] = f"{times['RUND1']} {times['RUNT1']}" + annot["run_finish"] = f"{times['RUND2']} {times['RUNT2']}" + + # raw data (for advanced end users benefit) + annot["abif_raw"] = raw + + # fsa check + is_fsa_file = all(tn not in raw for tn in ("PBAS1", "PBAS2")) + + if is_fsa_file: + try: + file_name = basename(stream.name).replace(".fsa", "") + except AttributeError: + file_name = "" + + sample_id = _get_string_tag(raw.get("LIMS1"), sample_id) + description = _get_string_tag(raw.get("CTID1"), "") + record = SeqRecord( + Seq(""), + id=sample_id, + name=file_name, + description=description, + annotations=annot, + ) + + else: + # use the file name as SeqRecord.name if available + try: + file_name = basename(stream.name).replace(".ab1", "") + except AttributeError: + file_name = "" + record = SeqRecord( + Seq(seq), + id=sample_id, + name=file_name, + description="", + annotations=annot, + ) + if qual: + # Expect this to be missing for FSA files. + record.letter_annotations["phred_quality"] = qual + elif not is_fsa_file and not qual and self.trim: + raise ValueError( + "The 'abi-trim' format can not be used for files without" + " quality values." + ) + + if self.trim and not is_fsa_file: + record = _abi_trim(record) + + record.annotations["molecule_type"] = "DNA" + # Move to the end of file to indicate that we finished reading + stream.seek(0, io.SEEK_END) + return record + + +def _AbiTrimIterator(stream): + """Return an iterator for the Abi file format that yields trimmed SeqRecord objects (PRIVATE).""" + return AbiIterator(stream, trim=True) + + +def _abi_parse_header(header, stream): + """Return directory contents (PRIVATE).""" + # header structure (after ABIF marker): + # file version, tag name, tag number, + # element type code, element size, number of elements + # data size, data offset, handle (not file handle) + head_elem_size = header[4] + head_elem_num = header[5] + head_offset = header[7] + + for index in range(head_elem_num): + start = head_offset + index * head_elem_size + # add directory offset to tuple + # to handle directories with data size <= 4 bytes + stream.seek(start) + dir_entry = struct.unpack(_DIRFMT, stream.read(struct.calcsize(_DIRFMT))) + ( + start, + ) + # only parse desired dirs + key = dir_entry[0].decode() + key += str(dir_entry[1]) + + tag_name = dir_entry[0].decode() + tag_number = dir_entry[1] + elem_code = dir_entry[2] + elem_num = dir_entry[4] + data_size = dir_entry[5] + data_offset = dir_entry[6] + tag_offset = dir_entry[8] + # if data size <= 4 bytes, data is stored inside tag + # so offset needs to be changed + if data_size <= 4: + data_offset = tag_offset + 20 + stream.seek(data_offset) + data = stream.read(data_size) + yield tag_name, tag_number, _parse_tag_data(elem_code, elem_num, data) + + +def _abi_trim(seq_record): + """Trims the sequence using Richard Mott's modified trimming algorithm (PRIVATE). + + Arguments: + - seq_record - SeqRecord object to be trimmed. + + Trimmed bases are determined from their segment score, which is a + cumulative sum of each base's score. Base scores are calculated from + their quality values. + + More about the trimming algorithm: + http://www.phrap.org/phredphrap/phred.html + http://resources.qiagenbioinformatics.com/manuals/clcgenomicsworkbench/650/Quality_trimming.html + """ + start = False # flag for starting position of trimmed sequence + segment = 20 # minimum sequence length + trim_start = 0 # init start index + cutoff = 0.05 # default cutoff value for calculating base score + + if len(seq_record) <= segment: + return seq_record + else: + # calculate base score + score_list = [ + cutoff - (10 ** (qual / -10.0)) + for qual in seq_record.letter_annotations["phred_quality"] + ] + + # calculate cumulative score + # if cumulative value < 0, set it to 0 + # first value is set to 0, because of the assumption that + # the first base will always be trimmed out + cummul_score = [0] + for i in range(1, len(score_list)): + score = cummul_score[-1] + score_list[i] + if score < 0: + cummul_score.append(0) + else: + cummul_score.append(score) + if not start: + # trim_start = value when cumulative score is first > 0 + trim_start = i + start = True + + # trim_finish = index of highest cumulative score, + # marking the end of sequence segment with highest cumulative score + trim_finish = cummul_score.index(max(cummul_score)) + + return seq_record[trim_start:trim_finish] + + +def _parse_tag_data(elem_code, elem_num, raw_data): + """Return single data value (PRIVATE). + + Arguments: + - elem_code - What kind of data + - elem_num - How many data points + - raw_data - abi file object from which the tags would be unpacked + + """ + if elem_code in _BYTEFMT: + # because '>1s' unpack differently from '>s' + if elem_num == 1: + num = "" + else: + num = str(elem_num) + fmt = ">" + num + _BYTEFMT[elem_code] + + assert len(raw_data) == struct.calcsize(fmt) + data = struct.unpack(fmt, raw_data) + + # no need to use tuple if len(data) == 1 + # also if data is date / time + if elem_code not in [10, 11] and len(data) == 1: + data = data[0] + + # account for different data types + if elem_code == 2: + return data + elif elem_code == 10: + return str(datetime.date(*data)) + elif elem_code == 11: + return str(datetime.time(*data[:3])) + elif elem_code == 13: + return bool(data) + elif elem_code == 18: + return data[1:] + elif elem_code == 19: + return data[:-1] + else: + return data + else: + return None + + +if __name__ == "__main__": + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/AceIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/AceIO.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cd9bd3c1f209f3712941e5ab5549e1ebbd6c97 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/AceIO.py @@ -0,0 +1,122 @@ +# Copyright 2008-2015 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "ace" file format. + +You are expected to use this module via the Bio.SeqIO functions. +See also the Bio.Sequencing.Ace module which offers more than just accessing +the contig consensus sequences in an ACE file as SeqRecord objects. +""" + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord +from Bio.Sequencing import Ace + +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator + + +class AceIterator(SequenceIterator): + """Return SeqRecord objects from an ACE file.""" + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + ) -> None: + """Iterate over SeqRecord objects read from an ACE file. + + Arguments: + - source - input stream opened in text mode, or a path to a file + + This uses the Bio.Sequencing.Ace module to do the hard work. Note that + by iterating over the file in a single pass, we are forced to ignore any + WA, CT, RT or WR footer tags. + + Ace files include the base quality for each position, which are taken to + be PHRED style scores. Just as if you had read in a FASTQ or QUAL file + using PHRED scores using Bio.SeqIO, these are stored in the SeqRecord's + letter_annotations dictionary under the "phred_quality" key. + + >>> from Bio import SeqIO + >>> with open("Ace/consed_sample.ace") as handle: + ... for record in SeqIO.parse(handle, "ace"): + ... print("%s %s... %i" % (record.id, record.seq[:10], len(record))) + ... print(max(record.letter_annotations["phred_quality"])) + Contig1 agccccgggc... 1475 + 90 + + However, ACE files do not include a base quality for any gaps in the + consensus sequence, and these are represented in Biopython with quality + of zero. Using zero is perhaps misleading as there may be very strong + evidence to support the gap in the consensus. Previous versions of + Biopython therefore used None instead, but this complicated usage, + and prevented output of the gapped sequence as FASTQ format. + + >>> from Bio import SeqIO + >>> with open("Ace/contig1.ace") as handle: + ... for record in SeqIO.parse(handle, "ace"): + ... print("%s ...%s..." % (record.id, record.seq[85:95])) + ... print(record.letter_annotations["phred_quality"][85:95]) + ... print(max(record.letter_annotations["phred_quality"])) + Contig1 ...AGAGG-ATGC... + [57, 57, 54, 57, 57, 0, 57, 72, 72, 72] + 90 + Contig2 ...GAATTACTAT... + [68, 68, 68, 68, 68, 68, 68, 68, 68, 68] + 90 + + """ + super().__init__(source, fmt="ACE") + self.ace_contigs = Ace.parse(self.stream) + + def __next__(self): + try: + ace_contig = next(self.ace_contigs) + except StopIteration: + raise StopIteration from None + # Convert the ACE contig record into a SeqRecord... + consensus_seq_str = ace_contig.sequence + if "*" in consensus_seq_str: + # For consistency with most other file formats, map + # any * gaps into - gaps. + assert "-" not in consensus_seq_str + consensus_seq = Seq(consensus_seq_str.replace("*", "-")) + else: + consensus_seq = Seq(consensus_seq_str) + + # TODO? - Base segments (BS lines) which indicates which read + # phrap has chosen to be the consensus at a particular position. + # Perhaps as SeqFeature objects? + + # TODO - Supporting reads (RD lines, plus perhaps QA and DS lines) + # Perhaps as SeqFeature objects? + + seq_record = SeqRecord(consensus_seq, id=ace_contig.name, name=ace_contig.name) + + # Consensus base quality (BQ lines). Note that any gaps (originally + # as * characters) in the consensus do not get a quality entry, so + # we assign a quality of None (zero would be misleading as there may + # be excellent support for having a gap here). + quals = [] + i = 0 + for base in consensus_seq: + if base == "-": + quals.append(0) + else: + quals.append(ace_contig.quality[i]) + i += 1 + assert i == len(ace_contig.quality) + seq_record.letter_annotations["phred_quality"] = quals + + return seq_record + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/FastaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/FastaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..dd665973202703cb125b6c07b17567caef4f1697 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/FastaIO.py @@ -0,0 +1,682 @@ +# Copyright 2006-2017,2020 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# This module is for reading and writing FASTA format files as SeqRecord +# objects. The code is partly inspired by earlier Biopython modules, +# Bio.Fasta.* and the now removed module Bio.SeqIO.FASTA +"""Bio.SeqIO support for the "fasta" (aka FastA or Pearson) file format. + +You are expected to use this module via the Bio.SeqIO functions. +""" + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord +from Bio import BiopythonDeprecationWarning + + +from .Interfaces import _clean +from .Interfaces import _get_seq_string +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +import warnings + + +def SimpleFastaParser(handle): + """Iterate over Fasta records as string tuples. + + Arguments: + - handle - input stream opened in text mode + + For each record a tuple of two strings is returned, the FASTA title + line (without the leading '>' character), and the sequence (with any + whitespace removed). The title line is not divided up into an + identifier (the first word) and comment or description. + + >>> with open("Fasta/dups.fasta") as handle: + ... for values in SimpleFastaParser(handle): + ... print(values) + ... + ('alpha', 'ACGTA') + ('beta', 'CGTC') + ('gamma', 'CCGCC') + ('alpha (again - this is a duplicate entry to test the indexing code)', 'ACGTA') + ('delta', 'CGCGC') + + """ + # Skip any text before the first record (e.g. blank lines, comments) + for line in handle: + if line[0] == ">": + title = line[1:].rstrip() + break + else: + # no break encountered - probably an empty file + return + + # Main logic + # Note, remove trailing whitespace, and any internal spaces + # (and any embedded \r which are possible in mangled files + # when not opened in universal read lines mode) + lines = [] + for line in handle: + if line[0] == ">": + yield title, "".join(lines).replace(" ", "").replace("\r", "") + lines = [] + title = line[1:].rstrip() + continue + lines.append(line.rstrip()) + + yield title, "".join(lines).replace(" ", "").replace("\r", "") + + +def FastaTwoLineParser(handle): + """Iterate over no-wrapping Fasta records as string tuples. + + Arguments: + - handle - input stream opened in text mode + + Functionally the same as SimpleFastaParser but with a strict + interpretation of the FASTA format as exactly two lines per + record, the greater-than-sign identifier with description, + and the sequence with no line wrapping. + + Any line wrapping will raise an exception, as will excess blank + lines (other than the special case of a zero-length sequence + as the second line of a record). + + Examples + -------- + This file uses two lines per FASTA record: + + >>> with open("Fasta/aster_no_wrap.pro") as handle: + ... for title, seq in FastaTwoLineParser(handle): + ... print("%s = %s..." % (title, seq[:3])) + ... + gi|3298468|dbj|BAA31520.1| SAMIPF = GGH... + + This equivalent file uses line wrapping: + + >>> with open("Fasta/aster.pro") as handle: + ... for title, seq in FastaTwoLineParser(handle): + ... print("%s = %s..." % (title, seq[:3])) + ... + Traceback (most recent call last): + ... + ValueError: Expected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: 'MTFGLVYTVYATAIDPKKGSLGTIAPIAIGFIVGANI' + + """ + idx = -1 # for empty file + for idx, line in enumerate(handle): + if idx % 2 == 0: # title line + if line[0] != ">": + raise ValueError( + "Expected FASTA record starting with '>' character. " + "Perhaps this file is using FASTA line wrapping? " + f"Got: '{line}'" + ) + title = line[1:].rstrip() + else: # sequence line + if line[0] == ">": + raise ValueError( + "Two '>' FASTA lines in a row. Missing sequence line " + "if this is strict two-line-per-record FASTA format. " + f"Have '>{title}' and '{line}'" + ) + yield title, line.strip() + + if idx == -1: + pass # empty file + elif idx % 2 == 0: # on a title line + raise ValueError( + "Missing sequence line at end of file if this is strict " + f"two-line-per-record FASTA format. Have title line '{line}'" + ) + else: + assert line[0] != ">", "line[0] == '>' ; this should be impossible!" + + +class FastaIterator(SequenceIterator): + """Parser for plain Fasta files without comments.""" + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ) -> None: + """Iterate over Fasta records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + - alphabet - optional alphabet, not used. Leave as None. + + This parser expects a plain Fasta format without comments or header + lines. + + By default this will act like calling Bio.SeqIO.parse(handle, "fasta") + with no custom handling of the title lines: + + >>> with open("Fasta/dups.fasta") as handle: + ... for record in FastaIterator(handle): + ... print(record.id) + ... + alpha + beta + gamma + alpha + delta + + If you want to modify the records before writing, for example to change + the ID of each record, you can use a generator function as follows: + + >>> def modify_records(records): + ... for record in records: + ... record.id = record.id.upper() + ... yield record + ... + >>> with open('Fasta/dups.fasta') as handle: + ... for record in modify_records(FastaIterator(handle)): + ... print(record.id) + ... + ALPHA + BETA + GAMMA + ALPHA + DELTA + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source, fmt="Fasta") + line = self.stream.readline() + if not line: + line = None + else: + if not line.startswith(">"): + raise ValueError( + """\ +This FASTA file contains comments at the beginning of the file, which are not +allowed by the 'fasta' parser. + +To parse this file, you have three options: + +(1) Modify your FASTA file to remove such comments at the beginning of the +file. + +(2) Use SeqIO.parse with the 'fasta-pearson' format instead of 'fasta'. This +format is consistent with the FASTA format defined by William Pearson's FASTA +aligner software. This format allows for comments before the first sequence; +lines starting with the ';' character anywhere in the file are also regarded +as comment lines and are ignored. + +(3) Use the 'fasta-blast' format. This format regards any lines "starting with +'!', '#', or ';' as comment lines. The 'fasta-blast' format may be safer than +the 'fasta-pearson' format, as it explicitly indicates which lines are comments. +""" + ) + self._line = line + + def __next__(self): + line = self._line + if line is None: + raise StopIteration + title = line[1:].rstrip() + # Main logic + # Note, remove trailing whitespace, and any internal spaces + # (and any embedded \r which are possible in mangled files + # when not opened in universal read lines mode) + lines = [] + for line in self.stream: + if line[0] == ">": + break + lines.append(line) + else: + line = None + self._line = line + sequence = "".join(lines).encode().translate(None, b" \t\r\n") + try: + first_word = title.split(None, 1)[0] + except IndexError: + assert not title, repr(title) + # Should we use SeqRecord default for no ID? + first_word = "" + return SeqRecord._from_validated( + Seq(sequence), id=first_word, name=first_word, description=title + ) + + +class FastaTwoLineIterator(SequenceIterator): + """Parser for Fasta files with exactly two lines per record.""" + + modes = "t" + + def __init__(self, source): + """Iterate over two-line Fasta records (as SeqRecord objects). + + Arguments: + - source - input stream opened in text mode, or a path to a file + + This uses a strict interpretation of the FASTA as requiring + exactly two lines per record (no line wrapping). + + Only the default title to ID/name/description parsing offered + by the relaxed FASTA parser is offered. + """ + super().__init__(source, fmt="FASTA") + self._data = FastaTwoLineParser(self.stream) + + def __next__(self): + try: + title, sequence = next(self._data) + except StopIteration: + raise StopIteration from None + try: + first_word = title.split(None, 1)[0] + except IndexError: + assert not title, repr(title) + # Should we use SeqRecord default for no ID? + first_word = "" + return SeqRecord( + Seq(sequence), id=first_word, name=first_word, description=title + ) + + +class FastaBlastIterator(SequenceIterator): + """Parser for Fasta files, allowing for comments as in BLAST.""" + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ) -> None: + """Iterate over Fasta records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + - alphabet - optional alphabet, not used. Leave as None. + + This parser expects the data to be in FASTA format. As in BLAST, lines + starting with '#', '!', or ';' are interpreted as comments and ignored. + + This iterator acts like calling Bio.SeqIO.parse(handle, "fasta-blast") + with no custom handling of the title lines: + + >>> with open("Fasta/dups.fasta") as handle: + ... for record in FastaIterator(handle): + ... print(record.id) + ... + alpha + beta + gamma + alpha + delta + + If you want to modify the records before writing, for example to change + the ID of each record, you can use a generator function as follows: + + >>> def modify_records(records): + ... for record in records: + ... record.id = record.id.upper() + ... yield record + ... + >>> with open('Fasta/dups.fasta') as handle: + ... for record in modify_records(FastaIterator(handle)): + ... print(record.id) + ... + ALPHA + BETA + GAMMA + ALPHA + DELTA + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source, fmt="FASTA") + for line in self.stream: + if line[0] not in "#!;": + if not line.startswith(">"): + raise ValueError( + "Expected FASTA record starting with '>' character.\n" + "If this line is a comment, please use '#', '!', or ';' as " + "the first character, or use the 'fasta-pearson' " + "format for parsing.\n" + f"Got: '{line}'" + ) + self._line = line + break + else: + self._line = None + + def __next__(self): + line = self._line + if line is None: + raise StopIteration + title = line[1:].rstrip() + lines = [] + for line in self.stream: + # Main logic + # Note, remove trailing whitespace, and any internal spaces + # (and any embedded \r which are possible in mangled files + # when not opened in universal read lines mode) + if line[0] in "#!;": + pass + elif line[0] == ">": + self_line = line + break + else: + lines.append(line.rstrip()) + else: + self._line = None + try: + first_word = title.split(None, 1)[0] + except IndexError: + first_word = "" + sequence = "".join(lines).replace(" ", "").replace("\r", "") + return SeqRecord( + Seq(sequence), id=first_word, name=first_word, description=title + ) + + +class FastaPearsonIterator(SequenceIterator): + """Parser for Fasta files, allowing for comments as in the FASTA aligner.""" + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ) -> None: + """Iterate over Fasta records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + - alphabet - optional alphabet, not used. Leave as None. + + This parser expects a Fasta format allowing for a header (before the + first sequence record) and comments (lines starting with ';') as in + William Pearson's FASTA aligner software. + + This iterator acts as calling Bio.SeqIO.parse(handle, "fasta-pearson") + with no custom handling of the title lines: + + >>> with open("Fasta/dups.fasta") as handle: + ... for record in FastaIterator(handle): + ... print(record.id) + ... + alpha + beta + gamma + alpha + delta + + If you want to modify the records before writing, for example to change + the ID of each record, you can use a generator function as follows: + + >>> def modify_records(records): + ... for record in records: + ... record.id = record.id.upper() + ... yield record + ... + >>> with open('Fasta/dups.fasta') as handle: + ... for record in modify_records(FastaIterator(handle)): + ... print(record.id) + ... + ALPHA + BETA + GAMMA + ALPHA + DELTA + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source, fmt="Fasta") + for line in self.stream: + if line.startswith(">"): + self._line = line + break + else: + self._line = None + + def __next__(self): + line = self._line + if line is None: + raise StopIteration + title = line[1:].rstrip() + lines = [] + for line in self.stream: + # Main logic + # Note, remove trailing whitespace, and any internal spaces + # (and any embedded \r which are possible in mangled files + # when not opened in universal read lines mode) + if line[0] == ";": + pass + elif line[0] == ">": + self._line = line + break + else: + lines.append(line.rstrip()) + else: + self._line = None + try: + first_word = title.split(None, 1)[0] + except IndexError: + first_word = "" + sequence = "".join(lines).replace(" ", "").replace("\r", "") + return SeqRecord( + Seq(sequence), id=first_word, name=first_word, description=title + ) + + +class FastaWriter(SequenceWriter): + """FASTA file writer.""" + + modes = "t" + + def __init__(self, target, wrap=60, record2title=None): + """Create a Fasta writer. + + Arguments: + - target - Output stream opened in text mode, or a path to a file. + - wrap - Optional line length used to wrap sequence lines. + Defaults to wrapping the sequence at 60 characters + Use zero (or None) for no wrapping, giving a single + long line for the sequence. + - record2title - Optional function to return the text to be + used for the title line of each record. By default + a combination of the record.id and record.description + is used. If the record.description starts with the + record.id, then just the record.description is used. + + You can either use:: + + handle = open(filename, "w") + writer = FastaWriter(handle) + writer.write_file(myRecords) + handle.close() + + Or, follow the sequential file writer system, for example:: + + handle = open(filename, "w") + writer = FastaWriter(handle) + ... + Multiple writer.write_record() and/or writer.write_records() calls + ... + handle.close() + + """ + super().__init__(target) + if wrap: + if wrap < 1: + raise ValueError + self.wrap = wrap + self.record2title = record2title + + @classmethod + def to_string(cls, record): + """Turn a SeqRecord into a FASTA formatted string, and return it.""" + id = _clean(record.id) + description = _clean(record.description) + if description and description.split(None, 1)[0] == id: + # The description includes the id at the start + title = description + elif description: + title = f"{id} {description}" + else: + title = id + assert "\n" not in title + assert "\r" not in title + lines = [f">{title}\n"] + + data = _get_seq_string(record) # Catches sequence being None + assert "\n" not in data + assert "\r" not in data + for i in range(0, len(data), 60): + lines.append(data[i : i + 60] + "\n") + + return "".join(lines) + + def write_record(self, record): + """Write a single Fasta record to the file.""" + if self.record2title: + title = self.clean(self.record2title(record)) + else: + id = self.clean(record.id) + description = self.clean(record.description) + if description and description.split(None, 1)[0] == id: + # The description includes the id at the start + title = description + elif description: + title = f"{id} {description}" + else: + title = id + + assert "\n" not in title + assert "\r" not in title + self.handle.write(f">{title}\n") + + data = _get_seq_string(record) # Catches sequence being None + + assert "\n" not in data + assert "\r" not in data + + if self.wrap: + for i in range(0, len(data), self.wrap): + self.handle.write(data[i : i + self.wrap] + "\n") + else: + self.handle.write(data + "\n") + + +class FastaTwoLineWriter(FastaWriter): + """Class to write 2-line per record Fasta format files. + + This means we write the sequence information without line + wrapping, and will always write a blank line for an empty + sequence. + """ + + def __init__(self, handle, record2title=None): + """Create a 2-line per record Fasta writer. + + Arguments: + - handle - Handle to an output file, e.g. as returned + by open(filename, "w") + - record2title - Optional function to return the text to be + used for the title line of each record. By default + a combination of the record.id and record.description + is used. If the record.description starts with the + record.id, then just the record.description is used. + + You can either use:: + + handle = open(filename, "w") + writer = FastaWriter(handle) + writer.write_file(myRecords) + handle.close() + + Or, follow the sequential file writer system, for example:: + + handle = open(filename, "w") + writer = FastaWriter(handle) + ... + Multiple writer.write_record() and/or writer.write_records() calls + ... + handle.close() + + """ + super().__init__(handle, wrap=None, record2title=record2title) + + @classmethod + def to_string(cls, record): + """Return a string in FASTA format with the sequence as one line.""" + id = _clean(record.id) + description = _clean(record.description) + if description and description.split(None, 1)[0] == id: + # The description includes the id at the start + title = description + elif description: + title = f"{id} {description}" + else: + title = id + assert "\n" not in title + assert "\r" not in title + + data = _get_seq_string(record) # Catches sequence being None + assert "\n" not in data + assert "\r" not in data + + return f">{title}\n{data}\n" + + +def as_fasta(record): + """Turn a SeqRecord into a FASTA formatted string.""" + warnings.warn( + """\ +FastaIO.as_fasta is deprecated. + +Instead of + +FastaIO.as_fasta(record) + +please use + +format(record, "fasta") +""", + DeprecationWarning, + ) + return FastaWriter.to_string(record) + + +def as_fasta_2line(record): + """Turn a SeqRecord into a two-line FASTA formatted string.""" + warnings.warn( + """\ +FastaIO.as_fasta_2line is deprecated. + +Instead of + +FastaIO.as_fasta_2line(record) + +please use + +format(record, "fasta-2line") +""", + DeprecationWarning, + ) + return FastaTwoLineWriter.to_string(record) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/GckIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/GckIO.py new file mode 100644 index 0000000000000000000000000000000000000000..118a1c0341231b98487a08fc873ec2c049d4f61a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/GckIO.py @@ -0,0 +1,244 @@ +# Copyright 2019 Damien Goutte-Gattat. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "gck" file format. + +The GCK binary format is generated by the Gene Construction Kit software +from Textco BioSoftware, Inc. +""" + +from struct import unpack + +from Bio.Seq import Seq +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator + + +def _read(stream, length): + """Read the specified number of bytes from the given stream.""" + data = stream.read(length) + if len(data) < length: + raise ValueError(f"Cannot read {length} bytes from stream") + return data + + +def _read_packet(stream): + """Read a length-prefixed packet. + + Parts of a GCK file are made of "packets" comprising of 4 bytes + giving the packet's size, followed by the packet's data. + + There is no type tag. The type of a packet, and thus the type of data + it contains, is solely indicated by the position of the packet within + the GCK file. + """ + length = stream.read(4) + if len(length) == 0: + return + if len(length) < 4: + raise ValueError("Cannot read packet size from stream") + length = unpack(">I", length)[0] + data = _read(stream, length) + return data + + +def _read_pstring(stream): + """Read a Pascal string. + + A Pascal string is one byte for length followed by the actual string. + """ + length = _read(stream, 1) + length = unpack(">B", length)[0] + data = _read(stream, length).decode("ASCII") + return data + + +def _read_p4string(stream): + """Read a 32-bit Pascal string. + + Similar to a Pascal string but length is encoded on 4 bytes. + """ + length = _read(stream, 4) + length = unpack(">I", length)[0] + data = _read(stream, length).decode("ASCII") + return data + + +class GckIterator(SequenceIterator): + """Parser for GCK files.""" + + modes = "b" + + def __init__(self, source): + """Break up a GCK file into SeqRecord objects. + + Note that a GCK file can only contain one sequence, so this + iterator will always return a single record. + """ + super().__init__(source, fmt="GCK") + # Skip file header + # GCK files start with a 24-bytes header. Bytes 4 and 8 seem to + # always be 12, maybe this could act as a magic cookie. Bytes + # 17-20 and 21-24 contain variable values of unknown meaning. + # check if file is empty + data = self.stream.read(24) + if not data: + raise ValueError("Empty file.") + if len(data) < 24: + raise ValueError("Improper header, cannot read 24 bytes from stream") + + def __next__(self): + stream = self.stream + # Read the actual sequence data + packet = _read_packet(stream) + if packet is None: + raise StopIteration + # The body of the sequence packet starts with a 32-bit integer + # representing the length of the sequence. + seq_length = unpack(">I", packet[:4])[0] + # This length should not be larger than the length of the + # sequence packet. + if seq_length > len(packet) - 4: + raise ValueError("Conflicting sequence length values") + sequence = packet[4:].decode("ASCII") + record = SeqRecord(Seq(sequence)) + + # Skip unknown packet + packet = _read_packet(stream) + if packet is None: + raise ValueError("Premature end of file") + + # Read features packet + packet = _read_packet(stream) + if packet is None: + raise ValueError("Premature end of file") + (seq_length, num_features) = unpack(">IH", packet[:6]) + # Check that length in the features packet matches the actual + # length of the sequence + if seq_length != len(sequence): + raise ValueError("Conflicting sequence length values") + # Each feature is stored in a 92-bytes structure. + if len(packet) - 6 != num_features * 92: + raise ValueError( + "Features packet size inconsistent with number of features" + ) + for i in range(num_features): + offset = 6 + i * 92 + feature_data = packet[offset : offset + 92] + + # There's probably more stuff to unpack in that structure, + # but those values are the only ones I understand. + (start, end, type, strand, has_name, has_comment, version) = unpack( + ">II6xH14xB17xII35xB", feature_data + ) + + if strand == 1: # Reverse strand + strand = -1 + else: + # Other possible values are 0 (no strand specified), + # 2 (forward strand), and 3 (both strands). All are + # treated as a forward strand. + strand = 1 + location = SimpleLocation(start, end, strand=strand) + + # It looks like any value > 0 indicates a CDS... + if type > 0: + type = "CDS" + else: + type = "misc_feature" + + # Each feature may have a name and a comment, which are then + # stored immediately after the features packet. Names are + # stored as Pascal strings (1 length byte followed by the + # string itself), comments are stored as "32-bit Pascal strings" + # (4 length bytes followed by the string). + qualifiers = {} + if has_name > 0: + name = _read_pstring(stream) + qualifiers["label"] = [name] + if has_comment > 0: + comment = _read_p4string(stream) + qualifiers["note"] = [comment] + + # Each feature may exist in several "versions". We keep only + # the most recent version. + if version > 0: + continue + + feature = SeqFeature(location, type=type, qualifiers=qualifiers) + record.features.append(feature) + + # Read restriction sites packet + # We are not interested in restriction sites, but we must still read + # that packet so that we can skip the names and comments for each + # site, which are stored after that packet in a similar way as for + # the features above. + packet = _read_packet(stream) + if packet is None: + raise ValueError("Premature end of file") + (seq_length, num_sites) = unpack(">IH", packet[:6]) + # Each site is stored in a 88-bytes structure + if len(packet) - 6 != num_sites * 88: + raise ValueError("Sites packet size inconsistent with number of sites") + for i in range(num_sites): + offset = 6 + i * 88 + site_data = packet[offset : offset + 88] + + (start, end, has_name, has_comment) = unpack(">II24xII48x", site_data) + + # Skip names and comments + if has_name: + _read_pstring(stream) + if has_comment: + _read_p4string(stream) + + # Skip unknown packet + packet = _read_packet(stream) + if packet is None: + raise ValueError("Premature end of file") + + # Next in the file are "version packets". + # However they are not properly formatted "packets" as they are not + # preceded by an integer giving their size. Instead we have a + # short integer indicating how many versions are there, and then + # as many 260-bytes block as we have versions. + num_versions = _read(stream, 2) + num_versions = unpack(">H", num_versions)[0] + versions = _read(stream, num_versions * 260) + for i in range(num_versions): + offset = i * 260 + version_data = versions[offset : offset + 260] + + # Each version may have a comment, which is then stored + # after all the "version packets". + has_comment = unpack(">I", version_data[-4:])[0] + if has_comment > 0: + _read_p4string(stream) + + # Skip unknown fixed-size block + # Whatever this block contains, it is not preceded by any length + # indicator, so I hope its size is indeed constant in all files... + _read(stream, 706) + + # Read the construct's name + name = _read_pstring(stream) + record.name = record.id = name.split(" ")[0] + record.description = name + + # Circularity byte + # There may be other flags in that block, but their meaning + # is unknown to me. + flags = _read(stream, 17) + circularity = unpack(">16xB", flags)[0] + if circularity > 0: + record.annotations["topology"] = "circular" + else: + record.annotations["topology"] = "linear" + + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/GfaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/GfaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..6098a8826bc2bde8fc7596bff096e7e483b93f8a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/GfaIO.py @@ -0,0 +1,213 @@ +"""Bio.SeqIO support for the Graphical Fragment Assembly format. + +This format is output by many assemblers and includes linkage information for +how the different sequences fit together, however, we just care about the +segment (sequence) information. + +Documentation: +- Version 1.x: https://gfa-spec.github.io/GFA-spec/GFA1.html +- Version 2.0: https://gfa-spec.github.io/GFA-spec/GFA2.html +""" + +import hashlib +import re +import warnings + +from Bio import BiopythonWarning +from Bio.Seq import _UndefinedSequenceData +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator + + +def _check_tags(seq, tags): + """Check a segment line's tags for inconsistencies (PRIVATE).""" + for tag in tags: + if tag[:2] == "LN": + # Sequence length + if len(seq) == 0: + # No sequence data, set the sequence length + seq._data = _UndefinedSequenceData(int(tag[5:])) + elif int(tag[5:]) != len(seq): + warnings.warn( + f"Segment line has incorrect length. Expected {tag[5:]} but got {len(seq)}.", + BiopythonWarning, + ) + elif tag[:2] == "SH": + # SHA256 checksum + checksum = hashlib.sha256(str(seq).encode()).hexdigest() + if checksum.upper() != tag[5:]: + warnings.warn( + f"Segment line has incorrect checksum. Expected {tag[5:]} but got {checksum}.", + BiopythonWarning, + ) + + +def _tags_to_annotations(tags): + """Build an annotations dictionary from a list of tags (PRIVATE).""" + annotations = {} + for tag in tags: + parts = tag.split(":") + if len(parts) < 3: + raise ValueError(f"Segment line has invalid tag: {tag}.") + if re.fullmatch(r"[A-Za-z][A-Za-z0-9]", parts[0]) is None: + warnings.warn( + f"Tag has invalid name: {parts[0]}. Are they tab delimited?", + BiopythonWarning, + ) + parts[2] = ":".join(parts[2:]) # tag value may contain : characters + annotations[parts[0]] = (parts[1], parts[2]) + + # Check type of the tag and raise warning on a mismatch. These RegExs + # are part of the 1.0 standard. + if parts[1] not in "AifZJHB": + warnings.warn(f"Tag has invalid type: {parts[1]}", BiopythonWarning) + elif parts[1] == "A" and re.fullmatch(r"[!-~]", parts[2]) is None: + warnings.warn( + f"Tag has incorrect type. Expected printable character, got {parts[2]}.", + BiopythonWarning, + ) + elif parts[1] == "i" and re.fullmatch(r"[-+]?[0-9]+", parts[2]) is None: + warnings.warn( + f"Tag has incorrect type. Expected signed integer, got {parts[2]}.", + BiopythonWarning, + ) + elif ( + parts[1] == "f" + and re.fullmatch(r"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?", parts[2]) + is None + ): + warnings.warn( + f"Tag has incorrect type. Expected float, got {parts[2]}.", + BiopythonWarning, + ) + elif parts[1] == "Z" and re.fullmatch(r"[ !-~]+", parts[2]) is None: + warnings.warn( + f"Tag has incorrect type. Expected printable string, got {parts[2]}.", + BiopythonWarning, + ) + elif parts[1] == "J" and re.fullmatch(r"[ !-~]+", parts[2]) is None: + warnings.warn( + f"Tag has incorrect type. Expected JSON excluding new-line and tab characters, got {parts[2]}.", + BiopythonWarning, + ) + elif parts[1] == "H" and re.fullmatch(r"[0-9A-F]+", parts[2]) is None: + warnings.warn( + f"Tag has incorrect type. Expected byte array in hex format, got {parts[2]}.", + BiopythonWarning, + ) + elif ( + parts[1] == "B" + and re.fullmatch( + r"[cCsSiIf](,[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+", parts[2] + ) + is None + ): + warnings.warn( + f"Tag has incorrect type. Expected array of integers or floats, got {parts[2]}.", + BiopythonWarning, + ) + return annotations + + +class Gfa1Iterator(SequenceIterator): + """Parser for GFA 1.x files. + + Documentation: https://gfa-spec.github.io/GFA-spec/GFA1.html + """ + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + ) -> None: + """Iterate over a GFA file as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + """ + super().__init__(source, fmt="GFA 1.0") + + def __next__(self): + for line in self.stream: + if line == "\n": + warnings.warn("GFA data has a blank line.", BiopythonWarning) + continue + + fields = line.strip("\n").split("\t") + if fields[0] == "S": + break + else: + raise StopIteration + if len(fields) < 3: + raise ValueError( + f"Segment line must have name and sequence fields: {line}." + ) + + if fields[2] == "*": + seq = Seq(None, length=0) + else: + seq = Seq(fields[2]) + + tags = fields[3:] + _check_tags(seq, tags) + annotations = _tags_to_annotations(tags) + + return SeqRecord(seq, id=fields[1], name=fields[1], annotations=annotations) + + +class Gfa2Iterator(SequenceIterator): + """Parser for GFA 2.0 files. + + Documentation for version 2: https://gfa-spec.github.io/GFA-spec/GFA2.html + """ + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + ) -> None: + """Iterate over a GFA file as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + """ + super().__init__(source, fmt="GFA 2.0") + + def __next__(self): + for line in self.stream: + if line == "\n": + warnings.warn("GFA data has a blank line.", BiopythonWarning) + continue + + fields = line.strip("\n").split("\t") + if fields[0] == "S": + break + else: + raise StopIteration + if len(fields) < 4: + raise ValueError( + f"Segment line must have name, length, and sequence fields: {line}." + ) + try: + int(fields[2]) + except ValueError: + raise ValueError( + f"Segment line must have an integer length: {line}." + ) from None + + if fields[3] == "*": + seq = Seq(None, length=0) + else: + seq = Seq(fields[3]) + + tags = fields[4:] + _check_tags(seq, tags) + annotations = _tags_to_annotations(tags) + + return SeqRecord(seq, id=fields[1], name=fields[1], annotations=annotations) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/IgIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/IgIO.py new file mode 100644 index 0000000000000000000000000000000000000000..91377565b5dd1bd7b37be40b04cad0dd8937ab47 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/IgIO.py @@ -0,0 +1,124 @@ +# Copyright 2008-2015 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "ig" (IntelliGenetics or MASE) file format. + +This module is for reading and writing IntelliGenetics format files as +SeqRecord objects. This file format appears to be the same as the MASE +multiple sequence alignment format. + +You are expected to use this module via the Bio.SeqIO functions. +""" + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator + + +class IgIterator(SequenceIterator): + """Parser for IntelliGenetics files.""" + + modes = "t" + + def __init__(self, source): + """Iterate over IntelliGenetics records (as SeqRecord objects). + + source - file-like object opened in text mode, or a path to a file + + The optional free format file header lines (which start with two + semi-colons) are ignored. + + The free format commentary lines at the start of each record (which + start with a semi-colon) are recorded as a single string with embedded + new line characters in the SeqRecord's annotations dictionary under the + key 'comment'. + + Examples + -------- + >>> with open("IntelliGenetics/TAT_mase_nuc.txt") as stream: + ... for record in IgIterator(stream): + ... print(f"{record.id} length {len(record)}") + ... + A_U455 length 303 + B_HXB2R length 306 + C_UG268A length 267 + D_ELI length 309 + F_BZ163A length 309 + O_ANT70 length 342 + O_MVP5180 length 348 + CPZGAB length 309 + CPZANT length 309 + A_ROD length 390 + B_EHOA length 420 + D_MM251 length 390 + STM_STM length 387 + VER_AGM3 length 354 + GRI_AGM677 length 264 + SAB_SAB1C length 219 + SYK_SYK length 330 + + """ + super().__init__(source, fmt="IntelliGenetics") + for line in self.stream: + if not line.startswith(";;"): + break + else: + # Empty file, or header only + line = None + self._line = line + + def __next__(self): + """Iterate over the records in the IntelliGenetics file.""" + line = self._line + if line is None: + raise StopIteration + if line[0] != ";": + raise ValueError(f"Records should start with ';' and not:\n{line!r}") + + stream = self.stream + # Try and agree with SeqRecord convention from the GenBank parser, + # (and followed in the SwissProt parser) which stores the comments + # as a long string with newlines under annotations key 'comment'. + + # Note some examples use "; ..." and others ";..." + comment_lines = [] + while line.startswith(";"): + # TODO - Extract identifier from lines like "LOCUS\tB_SF2"? + comment_lines.append(line[1:].strip()) + line = next(stream) + title = line.rstrip() + + seq_lines = [] + for line in stream: + if line[0] == ";": + break + # Remove trailing whitespace, and any internal spaces + seq_lines.append(line.rstrip().replace(" ", "")) + else: + line = None + seq_str = "".join(seq_lines) + if seq_str.endswith("1"): + # Remove the optional terminator (digit one) + seq_str = seq_str[:-1] + if "1" in seq_str: + raise ValueError("Potential terminator digit one found within sequence.") + + self._line = line + + # Return the record and then continue... + return SeqRecord( + Seq(seq_str), + id=title, + name=title, + annotations={"comment": "\n".join(comment_lines)}, + ) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/InsdcIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/InsdcIO.py new file mode 100644 index 0000000000000000000000000000000000000000..3ec2e115332fbd5b77f51f9fbbd0bd1b11ea46b1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/InsdcIO.py @@ -0,0 +1,1556 @@ +# Copyright 2007-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "genbank" and "embl" file formats. + +You are expected to use this module via the Bio.SeqIO functions. +Note that internally this module calls Bio.GenBank to do the actual +parsing of GenBank, EMBL and IMGT files. + +See Also: +International Nucleotide Sequence Database Collaboration +http://www.insdc.org/ + +GenBank +http://www.ncbi.nlm.nih.gov/Genbank/ + +EMBL Nucleotide Sequence Database +http://www.ebi.ac.uk/embl/ + +DDBJ (DNA Data Bank of Japan) +http://www.ddbj.nig.ac.jp/ + +IMGT (use a variant of EMBL format with longer feature indents) +http://imgt.cines.fr/download/LIGM-DB/userman_doc.html +http://imgt.cines.fr/download/LIGM-DB/ftable_doc.html +http://www.ebi.ac.uk/imgt/hla/docs/manual.html + +""" + +import warnings +from datetime import datetime, date as datetime_date +from string import ascii_letters +from string import digits + +from Bio import BiopythonWarning +from Bio import SeqFeature +from Bio import SeqIO +from Bio.GenBank.Scanner import _ImgtScanner +from Bio.GenBank.Scanner import EmblScanner +from Bio.GenBank.Scanner import GenBankScanner +from Bio.Seq import UndefinedSequenceError + +from .Interfaces import _get_seq_string +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +# Set containing all characters allowed in feature qualifier keys. See +# https://www.insdc.org/submitting-standards/feature-table/#3.1 +_allowed_table_component_name_chars = set(ascii_letters + digits + "_-'*") + +# NOTE +# ==== +# The "brains" for parsing GenBank, EMBL and IMGT files (and any +# other flat file variants from the INSDC in future) is in +# Bio.GenBank.Scanner (plus the _FeatureConsumer in Bio.GenBank) +# However, all the writing code is in this file. + + +class GenBankIterator(SequenceIterator): + """Parser for GenBank files.""" + + modes = "t" + + def __init__(self, source): + """Break up a Genbank file into SeqRecord objects. + + Argument source is a file-like object opened in text mode or a path to a file. + Every section from the LOCUS line to the terminating // becomes + a single SeqRecord with associated annotation and features. + + Note that for genomes or chromosomes, there is typically only + one record. + + This gets called internally by Bio.SeqIO for the GenBank file format: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("GenBank/cor6_6.gb", "gb"): + ... print(record.id) + ... + X55053.1 + X62281.1 + M81224.1 + AJ237582.1 + L31939.1 + AF297471.1 + + Equivalently, + + >>> with open("GenBank/cor6_6.gb") as handle: + ... for record in GenBankIterator(handle): + ... print(record.id) + ... + X55053.1 + X62281.1 + M81224.1 + AJ237582.1 + L31939.1 + AF297471.1 + + """ + super().__init__(source, fmt="GenBank") + self.records = GenBankScanner(debug=0).parse_records(self.stream) + + def __next__(self): + """Return the next SeqRecord.""" + return next(self.records) + + +class EmblIterator(SequenceIterator): + """Parser for EMBL files.""" + + modes = "t" + + def __init__(self, source): + """Break up an EMBL file into SeqRecord objects. + + Argument source is a file-like object opened in text mode or a path to a file. + Every section from the LOCUS line to the terminating // becomes + a single SeqRecord with associated annotation and features. + + Note that for genomes or chromosomes, there is typically only + one record. + + This gets called internally by Bio.SeqIO for the EMBL file format: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("EMBL/epo_prt_selection.embl", "embl"): + ... print(record.id) + ... + A00022.1 + A00028.1 + A00031.1 + A00034.1 + A00060.1 + A00071.1 + A00072.1 + A00078.1 + CQ797900.1 + + Equivalently, + + >>> with open("EMBL/epo_prt_selection.embl") as handle: + ... for record in EmblIterator(handle): + ... print(record.id) + ... + A00022.1 + A00028.1 + A00031.1 + A00034.1 + A00060.1 + A00071.1 + A00072.1 + A00078.1 + CQ797900.1 + + """ + super().__init__(source, fmt="EMBL") + self.records = EmblScanner(debug=0).parse_records(self.stream) + + def __next__(self): + """Return the next SeqRecord.""" + return next(self.records) + + +class ImgtIterator(SequenceIterator): + """Parser for IMGT files.""" + + modes = "t" + + def __init__(self, source): + """Break up an IMGT file into SeqRecord objects. + + Argument source is a file-like object opened in text mode or a path to a file. + Every section from the LOCUS line to the terminating // becomes + a single SeqRecord with associated annotation and features. + + Note that for genomes or chromosomes, there is typically only + one record. + """ + super().__init__(source, fmt="IMGT") + self.records = _ImgtScanner(debug=0).parse_records(self.stream) + + def __next__(self): + """Return the next SeqRecord.""" + return next(self.records) + + +class GenBankCdsFeatureIterator(SequenceIterator): + """Parser for GenBank files, creating a SeqRecord for each CDS feature.""" + + modes = "t" + + def __init__(self, source): + """Break up a Genbank file into SeqRecord objects for each CDS feature. + + Argument source is a file-like object opened in text mode or a path to a file. + + Every section from the LOCUS line to the terminating // can contain + many CDS features. These are returned as with the stated amino acid + translation sequence (if given). + """ + super().__init__(source, fmt="GenBank") + self.records = GenBankScanner(debug=0).parse_cds_features(self.stream) + + def __next__(self): + """Return the next SeqRecord.""" + return next(self.records) + + +class EmblCdsFeatureIterator(SequenceIterator): + """Parser for EMBL files, creating a SeqRecord for each CDS feature.""" + + modes = "t" + + def __init__(self, source): + """Break up a EMBL file into SeqRecord objects for each CDS feature. + + Argument source is a file-like object opened in text mode or a path to a file. + + Every section from the LOCUS line to the terminating // can contain + many CDS features. These are returned as with the stated amino acid + translation sequence (if given). + """ + super().__init__(source, fmt="EMBL") + self.records = EmblScanner(debug=0).parse_cds_features(self.stream) + + def __next__(self): + """Return the next SeqRecord.""" + return next(self.records) + + +def _insdc_feature_position_string(pos, offset=0): + """Build a GenBank/EMBL position string (PRIVATE). + + Use offset=1 to add one to convert a start position from python counting. + """ + if isinstance(pos, SeqFeature.ExactPosition): + return "%i" % (pos + offset) + elif isinstance(pos, SeqFeature.WithinPosition): + # TODO - avoid private variables + return "(%i.%i)" % ( + pos._left + offset, + pos._right + offset, + ) + elif isinstance(pos, SeqFeature.BetweenPosition): + # TODO - avoid private variables + return "(%i^%i)" % ( + pos._left + offset, + pos._right + offset, + ) + elif isinstance(pos, SeqFeature.BeforePosition): + return "<%i" % (pos + offset) + elif isinstance(pos, SeqFeature.AfterPosition): + return ">%i" % (pos + offset) + elif isinstance(pos, SeqFeature.OneOfPosition): + return "one-of(%s)" % ",".join( + _insdc_feature_position_string(p, offset) for p in pos.position_choices + ) + elif isinstance(pos, SeqFeature.Position): + raise NotImplementedError("Please report this as a bug in Biopython.") + else: + raise ValueError("Expected a SeqFeature position object.") + + +def _insdc_location_string_ignoring_strand_and_subfeatures(location, rec_length): + if location.ref: + ref = f"{location.ref}:" + else: + ref = "" + assert not location.ref_db + if ( + isinstance(location.start, SeqFeature.ExactPosition) + and isinstance(location.end, SeqFeature.ExactPosition) + and location.start == location.end + ): + # Special case, for 12:12 return 12^13 + # (a zero length slice, meaning the point between two letters) + if location.end == rec_length: + # Very special case, for a between position at the end of a + # sequence (used on some circular genomes, Bug 3098) we have + # N:N so return N^1 + return "%s%i^1" % (ref, rec_length) + else: + return "%s%i^%i" % (ref, location.end, location.end + 1) + if ( + isinstance(location.start, SeqFeature.ExactPosition) + and isinstance(location.end, SeqFeature.ExactPosition) + and location.start + 1 == location.end + ): + # Special case, for 11:12 return 12 rather than 12..12 + # (a length one slice, meaning a single letter) + return "%s%i" % (ref, location.end) + elif isinstance(location.start, SeqFeature.UnknownPosition) or isinstance( + location.end, SeqFeature.UnknownPosition + ): + # Special case for features from SwissProt/UniProt files + if isinstance(location.start, SeqFeature.UnknownPosition) and isinstance( + location.end, SeqFeature.UnknownPosition + ): + # warnings.warn("Feature with unknown location", BiopythonWarning) + # return "?" + raise ValueError("Feature with unknown location") + elif isinstance(location.start, SeqFeature.UnknownPosition): + # Treat the unknown start position as a BeforePosition + return "%s<%i..%s" % ( + ref, + location.end, + _insdc_feature_position_string(location.end), + ) + else: + # Treat the unknown end position as an AfterPosition + return "%s%s..>%i" % ( + ref, + _insdc_feature_position_string(location.start, +1), + location.start + 1, + ) + else: + # Typical case, e.g. 12..15 gets mapped to 11:15 + return ( + ref + + _insdc_feature_position_string(location.start, +1) + + ".." + + _insdc_feature_position_string(location.end) + ) + + +def _insdc_location_string(location, rec_length): + """Build a GenBank/EMBL location from a (Compound) SimpleLocation (PRIVATE). + + There is a choice of how to show joins on the reverse complement strand, + GenBank used "complement(join(1,10),(20,100))" while EMBL used to use + "join(complement(20,100),complement(1,10))" instead (but appears to have + now adopted the GenBank convention). Notice that the order of the entries + is reversed! This function therefore uses the first form. In this situation + we expect the CompoundLocation and its parts to all be marked as + strand == -1, and to be in the order 19:100 then 0:10. + """ + try: + parts = location.parts + # CompoundLocation + if location.strand == -1: + # Special case, put complement outside the join/order/... and reverse order + return "complement(%s(%s))" % ( + location.operator, + ",".join( + _insdc_location_string_ignoring_strand_and_subfeatures( + p, rec_length + ) + for p in parts[::-1] + ), + ) + else: + return "%s(%s)" % ( + location.operator, + ",".join(_insdc_location_string(p, rec_length) for p in parts), + ) + except AttributeError: + # SimpleLocation + loc = _insdc_location_string_ignoring_strand_and_subfeatures( + location, rec_length + ) + if location.strand == -1: + return f"complement({loc})" + else: + return loc + + +class _InsdcWriter(SequenceWriter): + """Base class for GenBank and EMBL writers (PRIVATE).""" + + MAX_WIDTH = 80 + QUALIFIER_INDENT = 21 + QUALIFIER_INDENT_STR = " " * QUALIFIER_INDENT + QUALIFIER_INDENT_TMP = " %s " # 21 if %s is empty + FTQUAL_NO_QUOTE = ( + "anticodon", + "citation", + "codon_start", + "compare", + "direction", + "estimated_length", + "mod_base", + "number", + "rpt_type", + "rpt_unit_range", + "tag_peptide", + "transl_except", + "transl_table", + ) + + modes = "t" + + def _write_feature_qualifier(self, key, value=None, quote=None): + if not _allowed_table_component_name_chars.issuperset(key): + warnings.warn( + f"Feature qualifier key '{key}' contains characters not" + " allowed by standard.", + BiopythonWarning, + ) + if len(key) > 20: + warnings.warn( + f"Feature qualifier key '{key}' is longer than maximum length" + " specified by standard (20 characters).", + BiopythonWarning, + ) + + if value is None: + # Value-less entry like /pseudo + self.handle.write(f"{self.QUALIFIER_INDENT_STR}/{key}\n") + return + + if isinstance(value, str): + value = value.replace( + '"', '""' + ) # NCBI says escape " as "" in qualifier values + + # Quick hack with no line wrapping, may be useful for testing: + # self.handle.write('%s/%s="%s"\n' % (self.QUALIFIER_INDENT_STR, key, value)) + if quote is None: + # Try to mimic unwritten rules about when quotes can be left out: + if isinstance(value, int) or key in self.FTQUAL_NO_QUOTE: + quote = False + else: + quote = True + if quote: + line = f'{self.QUALIFIER_INDENT_STR}/{key}="{value}"' + else: + line = f"{self.QUALIFIER_INDENT_STR}/{key}={value}" + if len(line) <= self.MAX_WIDTH: + self.handle.write(line + "\n") + return + while line.lstrip(): + if len(line) <= self.MAX_WIDTH: + self.handle.write(line + "\n") + return + # Insert line break... + for index in range( + min(len(line) - 1, self.MAX_WIDTH), self.QUALIFIER_INDENT + 1, -1 + ): + if line[index] == " ": + break + if line[index] != " ": + # No nice place to break... + index = self.MAX_WIDTH + assert index <= self.MAX_WIDTH + self.handle.write(line[:index] + "\n") + line = self.QUALIFIER_INDENT_STR + line[index:].lstrip() + + def _wrap_location(self, location): + """Split a feature location into lines (break at commas) (PRIVATE).""" + # TODO - Rewrite this not to recurse! + length = self.MAX_WIDTH - self.QUALIFIER_INDENT + if len(location) <= length: + return location + index = location[:length].rfind(",") + if index == -1: + # No good place to split (!) + warnings.warn(f"Couldn't split location:\n{location}", BiopythonWarning) + return location + return ( + location[: index + 1] + + "\n" + + self.QUALIFIER_INDENT_STR + + self._wrap_location(location[index + 1 :]) + ) + + def _write_feature(self, feature, record_length): + """Write a single SeqFeature object to features table (PRIVATE).""" + assert feature.type, feature + + f_type = feature.type.replace(" ", "_") + if not _allowed_table_component_name_chars.issuperset(f_type): + warnings.warn( + f"Feature key '{f_type}' contains characters not allowed by standard.", + BiopythonWarning, + ) + if len(f_type) > 15: + warnings.warn( + f"Feature key '{f_type}' is longer than maximum length" + " specified by standard (15 characters).", + BiopythonWarning, + ) + + location = _insdc_location_string(feature.location, record_length) + line = ( + (self.QUALIFIER_INDENT_TMP % f_type)[: self.QUALIFIER_INDENT] + + self._wrap_location(location) + + "\n" + ) + self.handle.write(line) + # Now the qualifiers... + # Note as of Biopython 1.69, this is an ordered-dict, don't sort it: + for key, values in feature.qualifiers.items(): + if isinstance(values, (list, tuple)): + for value in values: + self._write_feature_qualifier(key, value) + else: + # String, int, etc - or None for a /pseudo tpy entry + self._write_feature_qualifier(key, values) + + @staticmethod + def _get_annotation_str(record, key, default=".", just_first=False): + """Get an annotation dictionary entry (as a string) (PRIVATE). + + Some entries are lists, in which case if just_first=True the first entry + is returned. If just_first=False (default) this verifies there is only + one entry before returning it. + """ + try: + answer = record.annotations[key] + except KeyError: + return default + if isinstance(answer, list): + if not just_first: + assert len(answer) == 1 + return str(answer[0]) + else: + return str(answer) + + @staticmethod + def _split_multi_line(text, max_len): + """Return a list of strings (PRIVATE). + + Any single words which are too long get returned as a whole line + (e.g. URLs) without an exception or warning. + """ + # TODO - Do the line splitting while preserving white space? + text = text.strip() + if len(text) <= max_len: + return [text] + + words = text.split() + text = "" + while words and len(text) + 1 + len(words[0]) <= max_len: + text += " " + words.pop(0) + text = text.strip() + # assert len(text) <= max_len + answer = [text] + while words: + text = words.pop(0) + while words and len(text) + 1 + len(words[0]) <= max_len: + text += " " + words.pop(0) + text = text.strip() + # assert len(text) <= max_len + answer.append(text) + assert not words + return answer + + def _split_contig(self, record, max_len): + """Return a list of strings, splits on commas (PRIVATE).""" + # TODO - Merge this with _write_multi_line method? + # It would need the addition of the comma splitting logic... + # are there any other cases where that would be sensible? + contig = record.annotations.get("contig", "") + if isinstance(contig, (list, tuple)): + contig = "".join(contig) + contig = self.clean(contig) + answer = [] + while contig: + if len(contig) > max_len: + # Split lines at the commas + pos = contig[: max_len - 1].rfind(",") + if pos == -1: + raise ValueError("Could not break up CONTIG") + text, contig = contig[: pos + 1], contig[pos + 1 :] + else: + text, contig = contig, "" + answer.append(text) + return answer + + +class GenBankWriter(_InsdcWriter): + """GenBank writer.""" + + HEADER_WIDTH = 12 + QUALIFIER_INDENT = 21 + STRUCTURED_COMMENT_START = "-START##" + STRUCTURED_COMMENT_END = "-END##" + STRUCTURED_COMMENT_DELIM = " :: " + LETTERS_PER_LINE = 60 + SEQUENCE_INDENT = 9 + + def _write_single_line(self, tag, text): + """Write single line in each GenBank record (PRIVATE). + + Used in the 'header' of each GenBank record. + """ + assert len(tag) < self.HEADER_WIDTH + if len(text) > self.MAX_WIDTH - self.HEADER_WIDTH: + if tag: + warnings.warn( + f"Annotation {text!r} too long for {tag!r} line", BiopythonWarning + ) + else: + # Can't give such a precise warning + warnings.warn(f"Annotation {text!r} too long", BiopythonWarning) + self.handle.write( + "%s%s\n" % (tag.ljust(self.HEADER_WIDTH), text.replace("\n", " ")) + ) + + def _write_multi_line(self, tag, text): + """Write multiple lines in each GenBank record (PRIVATE). + + Used in the 'header' of each GenBank record. + """ + # TODO - Do the line splitting while preserving white space? + max_len = self.MAX_WIDTH - self.HEADER_WIDTH + lines = self._split_multi_line(text, max_len) + self._write_single_line(tag, lines[0]) + for line in lines[1:]: + self._write_single_line("", line) + + def _write_multi_entries(self, tag, text_list): + # used for DBLINK and any similar later line types. + # If the list of strings is empty, nothing is written. + for i, text in enumerate(text_list): + if i == 0: + self._write_single_line(tag, text) + else: + self._write_single_line("", text) + + @staticmethod + def _get_date(record): + default = "01-JAN-1980" + try: + date = record.annotations["date"] + except KeyError: + return default + # Cope with a list of one string: + if isinstance(date, list) and len(date) == 1: + date = date[0] + months = [ + "JAN", + "FEB", + "MAR", + "APR", + "MAY", + "JUN", + "JUL", + "AUG", + "SEP", + "OCT", + "NOV", + "DEC", + ] + if isinstance(date, datetime_date): + date = f"{date.day:02d}-{months[date.month - 1]}-{date.year}" + if not isinstance(date, str) or len(date) != 11: + warnings.warn( + f"Invalid date format provided {record.annotations['date']!r}, using default {default!r}", + BiopythonWarning, + ) + return default + try: + datetime(int(date[-4:]), months.index(date[3:6]) + 1, int(date[0:2])) + except ValueError: + warnings.warn( + f"Invalid date provided {record.annotations['date']!r}, using default {default!r}", + BiopythonWarning, + ) + date = default + return date + + @staticmethod + def _get_data_division(record): + try: + division = record.annotations["data_file_division"] + except KeyError: + division = "UNK" + if division in [ + "PRI", + "ROD", + "MAM", + "VRT", + "INV", + "PLN", + "BCT", + "VRL", + "PHG", + "SYN", + "UNA", + "EST", + "PAT", + "STS", + "GSS", + "HTG", + "HTC", + "ENV", + "CON", + "TSA", + ]: + # Good, already GenBank style + # PRI - primate sequences + # ROD - rodent sequences + # MAM - other mammalian sequences + # VRT - other vertebrate sequences + # INV - invertebrate sequences + # PLN - plant, fungal, and algal sequences + # BCT - bacterial sequences [plus archaea] + # VRL - viral sequences + # PHG - bacteriophage sequences + # SYN - synthetic sequences + # UNA - unannotated sequences + # EST - EST sequences (expressed sequence tags) + # PAT - patent sequences + # STS - STS sequences (sequence tagged sites) + # GSS - GSS sequences (genome survey sequences) + # HTG - HTGS sequences (high throughput genomic sequences) + # HTC - HTC sequences (high throughput cDNA sequences) + # ENV - Environmental sampling sequences + # CON - Constructed sequences + # TSA - Transcriptome Shotgun Assembly + # + # (plus UNK for unknown) + pass + else: + # See if this is in EMBL style: + # Division Code + # ----------------- ---- + # Bacteriophage PHG - common + # Environmental Sample ENV - common + # Fungal FUN - map to PLN (plants + fungal) + # Human HUM - map to PRI (primates) + # Invertebrate INV - common + # Other Mammal MAM - common + # Other Vertebrate VRT - common + # Mus musculus MUS - map to ROD (rodent) + # Plant PLN - common + # Prokaryote PRO - map to BCT (poor name) + # Other Rodent ROD - common + # Synthetic SYN - common + # Transgenic TGN - ??? map to SYN ??? + # Unclassified UNC - map to UNK + # Viral VRL - common + # + # (plus XXX for submitting which we can map to UNK) + embl_to_gbk = { + "FUN": "PLN", + "HUM": "PRI", + "MUS": "ROD", + "PRO": "BCT", + "UNC": "UNK", + "XXX": "UNK", + } + try: + division = embl_to_gbk[division] + except KeyError: + division = "UNK" + assert len(division) == 3 + return division + + def _get_topology(self, record): + """Set the topology to 'circular', 'linear' if defined (PRIVATE).""" + max_topology_len = len("circular") + + topology = self._get_annotation_str(record, "topology", default="") + if topology and len(topology) <= max_topology_len: + return topology.ljust(max_topology_len) + else: + return " " * max_topology_len + + def _write_the_first_line(self, record): + """Write the LOCUS line (PRIVATE).""" + locus = record.name + if not locus or locus == "": + locus = record.id + if not locus or locus == "": + locus = self._get_annotation_str(record, "accession", just_first=True) + if len(locus) > 16: + if len(locus) + 1 + len(str(len(record))) > 28: + # Locus name and record length to long to squeeze in. + # Per updated GenBank standard (Dec 15, 2018) 229.0 + # the Locus identifier can be any length, and a space + # is added after the identifier to keep the identifier + # and length fields separated + warnings.warn( + "Increasing length of locus line to allow " + "long name. This will result in fields that " + "are not in usual positions.", + BiopythonWarning, + ) + + if len(locus.split()) > 1: + raise ValueError(f"Invalid whitespace in {locus!r} for LOCUS line") + if len(record) > 99999999999: + # As of the GenBank release notes 229.0, the locus line can be + # any length. However, long locus lines may not be compatible + # with all software. + warnings.warn( + "The sequence length is very long. The LOCUS " + "line will be increased in length to compensate. " + "This may cause unexpected behavior.", + BiopythonWarning, + ) + + # Get the molecule type + mol_type = self._get_annotation_str(record, "molecule_type", None) + if mol_type is None: + raise ValueError("missing molecule_type in annotations") + if mol_type and len(mol_type) > 7: + # Deal with common cases from EMBL to GenBank + mol_type = mol_type.replace("unassigned ", "").replace("genomic ", "") + if len(mol_type) > 7: + warnings.warn(f"Molecule type {mol_type!r} too long", BiopythonWarning) + mol_type = "DNA" + if mol_type in ["protein", "PROTEIN"]: + mol_type = "" + + if mol_type == "": + units = "aa" + else: + units = "bp" + + topology = self._get_topology(record) + + division = self._get_data_division(record) + + # Accommodate longer header, with long accessions and lengths + if len(locus) > 16 and len(str(len(record))) > (11 - (len(locus) - 16)): + name_length = locus + " " + str(len(record)) + + # This is the older, standard 80 position header + else: + name_length = str(len(record)).rjust(28) + name_length = locus + name_length[len(locus) :] + assert len(name_length) == 28, name_length + assert " " in name_length, name_length + + assert len(units) == 2 + assert len(division) == 3 + line = "LOCUS %s %s %s %s %s %s\n" % ( + name_length, + units, + mol_type.ljust(7), + topology, + division, + self._get_date(record), + ) + # Extra long header + if len(line) > 80: + splitline = line.split() + if splitline[3] not in ["bp", "aa"]: + raise ValueError( + "LOCUS line does not contain size units at " + "expected position:\n" + line + ) + + if not ( + splitline[3].strip() == "aa" + or "DNA" in splitline[4].strip().upper() + or "RNA" in splitline[4].strip().upper() + ): + raise ValueError( + "LOCUS line does not contain valid " + "sequence type (DNA, RNA, ...):\n" + line + ) + + self.handle.write(line) + + # 80 position header + else: + assert len(line) == 79 + 1, repr(line) # plus one for new line + + # We're bending the rules to allow an identifier over 16 characters + # if we can steal spaces from the length field: + # assert line[12:28].rstrip() == locus, \ + # 'LOCUS line does not contain the locus at the expected position:\n' + line + # assert line[28:29] == " " + # assert line[29:40].lstrip() == str(len(record)), \ + # 'LOCUS line does not contain the length at the expected position:\n' + line + assert line[12:40].split() == [locus, str(len(record))], line + + # Tests copied from Bio.GenBank.Scanner + if line[40:44] not in [" bp ", " aa "]: + raise ValueError( + "LOCUS line does not contain size units at " + "expected position:\n" + line + ) + if line[44:47] not in [" ", "ss-", "ds-", "ms-"]: + raise ValueError( + "LOCUS line does not have valid strand " + "type (Single stranded, ...):\n" + line + ) + if not ( + line[47:54].strip() == "" + or "DNA" in line[47:54].strip().upper() + or "RNA" in line[47:54].strip().upper() + ): + raise ValueError( + "LOCUS line does not contain valid " + "sequence type (DNA, RNA, ...):\n" + line + ) + if line[54:55] != " ": + raise ValueError( + "LOCUS line does not contain space at position 55:\n" + line + ) + if line[55:63].strip() not in ["", "linear", "circular"]: + raise ValueError( + "LOCUS line does not contain valid " + "entry (linear, circular, ...):\n" + line + ) + if line[63:64] != " ": + raise ValueError( + "LOCUS line does not contain space at position 64:\n" + line + ) + if line[67:68] != " ": + raise ValueError( + "LOCUS line does not contain space at position 68:\n" + line + ) + if line[70:71] != "-": + raise ValueError( + "LOCUS line does not contain - at position 71 in date:\n" + line + ) + if line[74:75] != "-": + raise ValueError( + "LOCUS line does not contain - at position 75 in date:\n" + line + ) + + self.handle.write(line) + + def _write_references(self, record): + number = 0 + for ref in record.annotations["references"]: + if not isinstance(ref, SeqFeature.Reference): + continue + number += 1 + data = str(number) + # TODO - support more complex record reference locations? + if ref.location and len(ref.location) == 1: + molecule_type = record.annotations.get("molecule_type") + if molecule_type and "protein" in molecule_type: + units = "residues" + else: + units = "bases" + data += " (%s %i to %i)" % ( + units, + ref.location[0].start + 1, + ref.location[0].end, + ) + self._write_single_line("REFERENCE", data) + if ref.authors: + # We store the AUTHORS data as a single string + self._write_multi_line(" AUTHORS", ref.authors) + if ref.consrtm: + # We store the consortium as a single string + self._write_multi_line(" CONSRTM", ref.consrtm) + if ref.title: + # We store the title as a single string + self._write_multi_line(" TITLE", ref.title) + if ref.journal: + # We store this as a single string - holds the journal name, + # volume, year, and page numbers of the citation + self._write_multi_line(" JOURNAL", ref.journal) + if ref.medline_id: + # This line type is obsolete and was removed from the GenBank + # flatfile format in April 2005. Should we write it? + # Note this has a two space indent: + self._write_multi_line(" MEDLINE", ref.medline_id) + if ref.pubmed_id: + # Note this has a THREE space indent: + self._write_multi_line(" PUBMED", ref.pubmed_id) + if ref.comment: + self._write_multi_line(" REMARK", ref.comment) + + def _write_comment(self, record): + # This is a bit complicated due to the range of possible + # ways people might have done their annotation... + # Currently the parser uses a single string with newlines. + # A list of lines is also reasonable. + # A single (long) string is perhaps the most natural of all. + # This means we may need to deal with line wrapping. + lines = [] + if "structured_comment" in record.annotations: + comment = record.annotations["structured_comment"] + # Find max length of keys for equal padded printing + padding = 0 + for key, data in comment.items(): + for subkey, subdata in data.items(): + padding = len(subkey) if len(subkey) > padding else padding + # Construct output + for key, data in comment.items(): + lines.append(f"##{key}{self.STRUCTURED_COMMENT_START}") + for subkey, subdata in data.items(): + spaces = " " * (padding - len(subkey)) + lines.append( + f"{subkey}{spaces}{self.STRUCTURED_COMMENT_DELIM}{subdata}" + ) + lines.append(f"##{key}{self.STRUCTURED_COMMENT_END}") + if "comment" in record.annotations: + comment = record.annotations["comment"] + if isinstance(comment, str): + lines += comment.split("\n") + elif isinstance(comment, (list, tuple)): + lines += list(comment) + else: + raise ValueError("Could not understand comment annotation") + self._write_multi_line("COMMENT", lines[0]) + for line in lines[1:]: + self._write_multi_line("", line) + + def _write_contig(self, record): + max_len = self.MAX_WIDTH - self.HEADER_WIDTH + lines = self._split_contig(record, max_len) + self._write_single_line("CONTIG", lines[0]) + for text in lines[1:]: + self._write_single_line("", text) + + def _write_sequence(self, record): + # Loosely based on code from Howard Salis + # TODO - Force lower case? + + try: + data = _get_seq_string(record) + except UndefinedSequenceError: + # We have already recorded the length, and there is no need + # to record a long sequence of NNNNNNN...NNN or whatever. + if "contig" in record.annotations: + self._write_contig(record) + else: + self.handle.write("ORIGIN\n") + return + + # Catches sequence being None: + data = data.lower() + seq_len = len(data) + self.handle.write("ORIGIN\n") + for line_number in range(0, seq_len, self.LETTERS_PER_LINE): + self.handle.write(str(line_number + 1).rjust(self.SEQUENCE_INDENT)) + for words in range( + line_number, min(line_number + self.LETTERS_PER_LINE, seq_len), 10 + ): + self.handle.write(f" {data[words : words + 10]}") + self.handle.write("\n") + + def write_record(self, record): + """Write a single record to the output file.""" + handle = self.handle + self._write_the_first_line(record) + + default = record.id + if default.count(".") == 1 and default[default.index(".") + 1 :].isdigit(): + # Good, looks like accession.version and not something + # else like identifier.start-end + default = record.id.split(".", 1)[0] + accession = self._get_annotation_str( + record, "accession", default, just_first=True + ) + acc_with_version = accession + if record.id.startswith(accession + "."): + try: + acc_with_version = "%s.%i" % ( + accession, + int(record.id.split(".", 1)[1]), + ) + except ValueError: + pass + gi = self._get_annotation_str(record, "gi", just_first=True) + + descr = record.description + if descr == "": + descr = "" # Trailing dot will be added later + + # The DEFINITION field must end with a period + # see ftp://ftp.ncbi.nih.gov/genbank/gbrel.txt [3.4.5] + # and discussion https://github.com/biopython/biopython/pull/616 + # So let's add a period + descr += "." + self._write_multi_line("DEFINITION", descr) + + self._write_single_line("ACCESSION", accession) + if gi != ".": + self._write_single_line("VERSION", f"{acc_with_version} GI:{gi}") + else: + self._write_single_line("VERSION", acc_with_version) + + # The NCBI initially expected two types of link, + # e.g. "Project:28471" and "Trace Assembly Archive:123456" + # + # This changed and at some point the formatting switched to + # include a space after the colon, e.g. + # + # LOCUS NC_000011 1606 bp DNA linear CON 06-JUN-2016 + # DEFINITION Homo sapiens chromosome 11, GRCh38.p7 Primary Assembly. + # ACCESSION NC_000011 REGION: complement(5225466..5227071) GPC_000001303 + # VERSION NC_000011.10 GI:568815587 + # DBLINK BioProject: PRJNA168 + # Assembly: GCF_000001405.33 + # ... + # + # Or, + # + # LOCUS JU120277 1044 bp mRNA linear TSA 27-NOV-2012 + # DEFINITION TSA: Tupaia chinensis tbc000002.Tuchadli mRNA sequence. + # ACCESSION JU120277 + # VERSION JU120277.1 GI:379775257 + # DBLINK BioProject: PRJNA87013 + # Sequence Read Archive: SRR433859 + # ... + dbxrefs_with_space = [] + for x in record.dbxrefs: + if ": " not in x: + x = x.replace(":", ": ") + dbxrefs_with_space.append(x) + self._write_multi_entries("DBLINK", dbxrefs_with_space) + del dbxrefs_with_space + + try: + # List of strings + # Keywords should be given separated with semi colons, + keywords = "; ".join(record.annotations["keywords"]) + # with a trailing period: + if not keywords.endswith("."): + keywords += "." + except KeyError: + # If no keywords, there should be just a period: + keywords = "." + self._write_multi_line("KEYWORDS", keywords) + + if "segment" in record.annotations: + # Deal with SEGMENT line found only in segmented records, + # e.g. AH000819 + segment = record.annotations["segment"] + if isinstance(segment, list): + assert len(segment) == 1, segment + segment = segment[0] + self._write_single_line("SEGMENT", segment) + + self._write_multi_line("SOURCE", self._get_annotation_str(record, "source")) + # The ORGANISM line MUST be a single line, as any continuation is the taxonomy + org = self._get_annotation_str(record, "organism") + if len(org) > self.MAX_WIDTH - self.HEADER_WIDTH: + org = org[: self.MAX_WIDTH - self.HEADER_WIDTH - 4] + "..." + self._write_single_line(" ORGANISM", org) + try: + # List of strings + # Taxonomy should be given separated with semi colons, + taxonomy = "; ".join(record.annotations["taxonomy"]) + # with a trailing period: + if not taxonomy.endswith("."): + taxonomy += "." + except KeyError: + taxonomy = "." + self._write_multi_line("", taxonomy) + + if "db_source" in record.annotations: + # Hack around the issue of BioSQL loading a list for the db_source + db_source = record.annotations["db_source"] + if isinstance(db_source, list): + db_source = db_source[0] + self._write_single_line("DBSOURCE", db_source) + + if "references" in record.annotations: + self._write_references(record) + + if ( + "comment" in record.annotations + or "structured_comment" in record.annotations + ): + self._write_comment(record) + + handle.write("FEATURES Location/Qualifiers\n") + rec_length = len(record) + for feature in record.features: + self._write_feature(feature, rec_length) + self._write_sequence(record) + handle.write("//\n") + + +class EmblWriter(_InsdcWriter): + """EMBL writer.""" + + HEADER_WIDTH = 5 + QUALIFIER_INDENT = 21 + QUALIFIER_INDENT_STR = "FT" + " " * (QUALIFIER_INDENT - 2) + QUALIFIER_INDENT_TMP = "FT %s " # 21 if %s is empty + # Note second spacer line of just FH is expected: + FEATURE_HEADER = "FH Key Location/Qualifiers\nFH\n" + + LETTERS_PER_BLOCK = 10 + BLOCKS_PER_LINE = 6 + LETTERS_PER_LINE = LETTERS_PER_BLOCK * BLOCKS_PER_LINE + POSITION_PADDING = 10 + + def _write_contig(self, record): + max_len = self.MAX_WIDTH - self.HEADER_WIDTH + lines = self._split_contig(record, max_len) + for text in lines: + self._write_single_line("CO", text) + + def _write_sequence(self, record): + handle = self.handle # save looking up this multiple times + + try: + data = _get_seq_string(record) + except UndefinedSequenceError: + # We have already recorded the length, and there is no need + # to record a long sequence of NNNNNNN...NNN or whatever. + if "contig" in record.annotations: + self._write_contig(record) + else: + # TODO - Can the sequence just be left out as in GenBank files? + handle.write("SQ \n") + return + + # Catches sequence being None + data = data.lower() + seq_len = len(data) + + molecule_type = record.annotations.get("molecule_type") + if molecule_type is not None and "DNA" in molecule_type: + # TODO - What if we have RNA? + a_count = data.count("A") + data.count("a") + c_count = data.count("C") + data.count("c") + g_count = data.count("G") + data.count("g") + t_count = data.count("T") + data.count("t") + other = seq_len - (a_count + c_count + g_count + t_count) + handle.write( + "SQ Sequence %i BP; %i A; %i C; %i G; %i T; %i other;\n" + % (seq_len, a_count, c_count, g_count, t_count, other) + ) + else: + handle.write("SQ \n") + + for line_number in range(seq_len // self.LETTERS_PER_LINE): + handle.write(" ") # Just four, not five + for block in range(self.BLOCKS_PER_LINE): + index = ( + self.LETTERS_PER_LINE * line_number + self.LETTERS_PER_BLOCK * block + ) + handle.write(f" {data[index : index + self.LETTERS_PER_BLOCK]}") + handle.write( + str((line_number + 1) * self.LETTERS_PER_LINE).rjust( + self.POSITION_PADDING + ) + ) + handle.write("\n") + if seq_len % self.LETTERS_PER_LINE: + # Final (partial) line + line_number = seq_len // self.LETTERS_PER_LINE + handle.write(" ") # Just four, not five + for block in range(self.BLOCKS_PER_LINE): + index = ( + self.LETTERS_PER_LINE * line_number + self.LETTERS_PER_BLOCK * block + ) + handle.write( + f" {data[index : index + self.LETTERS_PER_BLOCK]}".ljust(11) + ) + handle.write(str(seq_len).rjust(self.POSITION_PADDING)) + handle.write("\n") + + def _write_single_line(self, tag, text): + assert len(tag) == 2 + line = tag + " " + text + if len(text) > self.MAX_WIDTH: + warnings.warn(f"Line {line!r} too long", BiopythonWarning) + self.handle.write(line + "\n") + + def _write_multi_line(self, tag, text): + max_len = self.MAX_WIDTH - self.HEADER_WIDTH + lines = self._split_multi_line(text, max_len) + for line in lines: + self._write_single_line(tag, line) + + def _write_the_first_lines(self, record): + """Write the ID and AC lines (PRIVATE).""" + if "." in record.id and record.id.rsplit(".", 1)[1].isdigit(): + version = "SV " + record.id.rsplit(".", 1)[1] + accession = self._get_annotation_str( + record, "accession", record.id.rsplit(".", 1)[0], just_first=True + ) + else: + version = "" + accession = self._get_annotation_str( + record, "accession", record.id, just_first=True + ) + + if ";" in accession: + raise ValueError(f"Cannot have semi-colon in EMBL accession, '{accession}'") + if " " in accession: + # This is out of practicality... might it be allowed? + raise ValueError(f"Cannot have spaces in EMBL accession, '{accession}'") + + topology = self._get_annotation_str(record, "topology", default="") + + # Get the molecule type + # TODO - record this explicitly in the parser? + # Note often get RNA vs DNA discrepancy in real EMBL/NCBI files + mol_type = record.annotations.get("molecule_type") + if mol_type is None: + raise ValueError("missing molecule_type in annotations") + if mol_type not in ( + "DNA", + "genomic DNA", + "unassigned DNA", + "mRNA", + "RNA", + "protein", + ): + warnings.warn(f"Non-standard molecule type: {mol_type}", BiopythonWarning) + mol_type_upper = mol_type.upper() + if "DNA" in mol_type_upper: + units = "BP" + elif "RNA" in mol_type_upper: + units = "BP" + elif "PROTEIN" in mol_type_upper: + mol_type = "PROTEIN" + units = "AA" + else: + raise ValueError(f"failed to understand molecule_type '{mol_type}'") + + # Get the taxonomy division + division = self._get_data_division(record) + + # TODO - Full ID line + handle = self.handle + # ID <1>; SV <2>; <3>; <4>; <5>; <6>; <7> BP. + # 1. Primary accession number + # 2. Sequence version number + # 3. Topology: 'circular' or 'linear' + # 4. Molecule type + # 5. Data class + # 6. Taxonomic division + # 7. Sequence length + self._write_single_line( + "ID", + "%s; %s; %s; %s; ; %s; %i %s." + % (accession, version, topology, mol_type, division, len(record), units), + ) + handle.write("XX\n") + self._write_single_line("AC", accession + ";") + handle.write("XX\n") + + @staticmethod + def _get_data_division(record): + try: + division = record.annotations["data_file_division"] + except KeyError: + division = "UNC" + if division in [ + "PHG", + "ENV", + "FUN", + "HUM", + "INV", + "MAM", + "VRT", + "MUS", + "PLN", + "PRO", + "ROD", + "SYN", + "TGN", + "UNC", + "VRL", + "XXX", + ]: + # Good, already EMBL style + # Division Code + # ----------------- ---- + # Bacteriophage PHG + # Environmental Sample ENV + # Fungal FUN + # Human HUM + # Invertebrate INV + # Other Mammal MAM + # Other Vertebrate VRT + # Mus musculus MUS + # Plant PLN + # Prokaryote PRO + # Other Rodent ROD + # Synthetic SYN + # Transgenic TGN + # Unclassified UNC (i.e. unknown) + # Viral VRL + # + # (plus XXX used for submitting data to EMBL) + pass + else: + # See if this is in GenBank style & can be converted. + # Generally a problem as the GenBank groups are wider + # than those of EMBL. Note that GenBank use "BCT" for + # both bacteria and archaea thus this maps to EMBL's + # "PRO" nicely. + gbk_to_embl = {"BCT": "PRO", "UNK": "UNC"} + try: + division = gbk_to_embl[division] + except KeyError: + division = "UNC" + assert len(division) == 3 + return division + + def _write_keywords(self, record): + # Put the keywords right after DE line. + # Each 'keyword' can have multiple words and spaces, but we + # must not split any 'keyword' between lines. + # TODO - Combine short keywords onto one line + for keyword in record.annotations["keywords"]: + self._write_single_line("KW", keyword) + self.handle.write("XX\n") + + def _write_references(self, record): + # The order should be RN, RC, RP, RX, RG, RA, RT, RL + number = 0 + for ref in record.annotations["references"]: + if not isinstance(ref, SeqFeature.Reference): + continue + number += 1 + self._write_single_line("RN", "[%i]" % number) + # TODO - support for RC line (needed in parser too) + # TODO - support more complex record reference locations? + if ref.location and len(ref.location) == 1: + self._write_single_line( + "RP", + "%i-%i" % (ref.location[0].start + 1, ref.location[0].end), + ) + # TODO - record any DOI or AGRICOLA identifier in the reference object? + if ref.pubmed_id: + self._write_single_line("RX", f"PUBMED; {ref.pubmed_id}.") + if ref.consrtm: + self._write_single_line("RG", f"{ref.consrtm}") + if ref.authors: + # We store the AUTHORS data as a single string + self._write_multi_line("RA", ref.authors + ";") + if ref.title: + # We store the title as a single string + self._write_multi_line("RT", f'"{ref.title}";') + if ref.journal: + # We store this as a single string - holds the journal name, + # volume, year, and page numbers of the citation + self._write_multi_line("RL", ref.journal) + self.handle.write("XX\n") + + def _write_comment(self, record): + # This is a bit complicated due to the range of possible + # ways people might have done their annotation... + # Currently the parser uses a single string with newlines. + # A list of lines is also reasonable. + # A single (long) string is perhaps the most natural of all. + # This means we may need to deal with line wrapping. + comment = record.annotations["comment"] + if isinstance(comment, str): + lines = comment.split("\n") + elif isinstance(comment, (list, tuple)): + lines = comment + else: + raise ValueError("Could not understand comment annotation") + # TODO - Merge this with the GenBank comment code? + if not lines: + return + for line in lines: + self._write_multi_line("CC", line) + self.handle.write("XX\n") + + def write_record(self, record): + """Write a single record to the output file.""" + handle = self.handle + self._write_the_first_lines(record) + + # PR line (0 or 1 lines only), project identifier + # + # Assuming can't use 2 lines, we should prefer newer GenBank + # DBLINK BioProject:... entries over the older GenBank DBLINK + # Project:... lines. + # + # In either case, seems EMBL uses just "PR Project:..." + # regardless of the type of ID (old numeric only, or new + # with alpha prefix), e.g. for CP002497 NCBI now uses: + # + # DBLINK BioProject: PRJNA60715 + # BioSample: SAMN03081426 + # + # While EMBL uses: + # + # XX + # PR Project:PRJNA60715; + # XX + # + # Sorting ensures (new) BioProject:... is before old Project:... + for xref in sorted(record.dbxrefs): + if xref.startswith("BioProject:"): + self._write_single_line("PR", xref[3:] + ";") + handle.write("XX\n") + break + if xref.startswith("Project:"): + self._write_single_line("PR", xref + ";") + handle.write("XX\n") + break + + # TODO - DT lines (date) + + descr = record.description + if descr == "": + descr = "." + self._write_multi_line("DE", descr) + handle.write("XX\n") + + if "keywords" in record.annotations: + self._write_keywords(record) + + # Should this be "source" or "organism"? + self._write_multi_line("OS", self._get_annotation_str(record, "organism")) + try: + # List of strings + taxonomy = "; ".join(record.annotations["taxonomy"]) + "." + except KeyError: + taxonomy = "." + self._write_multi_line("OC", taxonomy) + handle.write("XX\n") + + if "references" in record.annotations: + self._write_references(record) + + if "comment" in record.annotations: + self._write_comment(record) + + handle.write(self.FEATURE_HEADER) + rec_length = len(record) + for feature in record.features: + self._write_feature(feature, rec_length) + handle.write("XX\n") + + self._write_sequence(record) + handle.write("//\n") + + +class ImgtWriter(EmblWriter): + """IMGT writer (EMBL format variant).""" + + HEADER_WIDTH = 5 + QUALIFIER_INDENT = 25 # Not 21 as in EMBL + QUALIFIER_INDENT_STR = "FT" + " " * (QUALIFIER_INDENT - 2) + QUALIFIER_INDENT_TMP = "FT %s " # 25 if %s is empty + FEATURE_HEADER = "FH Key Location/Qualifiers\nFH\n" + + +def _genbank_convert_fasta(in_file, out_file): + """Fast GenBank to FASTA (PRIVATE).""" + # We don't need to parse the features... + records = GenBankScanner().parse_records(in_file, do_features=False) + return SeqIO.write(records, out_file, "fasta") + + +def _embl_convert_fasta(in_file, out_file): + """Fast EMBL to FASTA (PRIVATE).""" + # We don't need to parse the features... + records = EmblScanner().parse_records(in_file, do_features=False) + return SeqIO.write(records, out_file, "fasta") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/Interfaces.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/Interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..b613ba3160ccbb693f5a3a3719be8737be28d516 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/Interfaces.py @@ -0,0 +1,247 @@ +# Copyright 2006-2021 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support module (not for general use). + +Unless you are writing a new parser or writer for Bio.SeqIO, you should not +use this module. It provides base classes to try and simplify things. +""" + +from abc import ABC +from abc import abstractmethod +from io import StringIO +from os import PathLike +from typing import AnyStr +from typing import Generic +from typing import IO +from typing import Optional +from typing import Union + +from Bio import StreamModeError +from Bio.Seq import MutableSeq +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +# https://docs.python.org/3/glossary.html#term-path-like-object +_PathLikeTypes = (PathLike, str, bytes) +_IOSource = IO[AnyStr] | PathLike | str | bytes +_TextIOSource = _IOSource[str] +_BytesIOSource = _IOSource[bytes] + + +class SequenceIterator(ABC, Generic[AnyStr]): + """Base class for building SeqRecord iterators. + + You should write a __next__ method that returns the next SeqRecord. You + may wish to redefine the __init__ method as well. + You must also create a class property `modes` specifying the allowable + file stream modes. + """ + + @property + @abstractmethod + def modes(self): + """File modes (binary or text) that the parser can handle. + + This property must be "t" (for text mode only), "b" (for binary mode + only), "tb" (if both text and binary mode are accepted, but text mode + is preferred), or "bt" (if both text and binary mode are accepted, but + binary mode is preferred). + """ + pass + + def __init__( + self, + source: _IOSource, + alphabet: None = None, + fmt: str | None = None, + ) -> None: + """Create a SequenceIterator object. + + Arguments: + - source - input file stream, or path to input file + - alphabet - no longer used, should be None + - fmt - string, mixed case format name for in error messages + + This method MAY be overridden by any subclass. + + Note when subclassing: + - there should be a single non-optional argument, the source. + - you do not have to require an alphabet. + - you can add additional optional arguments. + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + modes = self.modes + self.source = source + if isinstance(source, _PathLikeTypes): + mode = modes[0] + self.stream = open(source, "r" + mode) + else: + value = source.read(0) + if value == "": + if modes == "b": + raise StreamModeError( + f"{fmt} files must be opened in binary mode." + ) from None + mode = "t" + elif value == b"": + if modes == "t": + raise StreamModeError( + f"{fmt} files must be opened in text mode." + ) from None + mode = "b" + else: + raise RuntimeError("Failed to read from input data") from None + self.stream = source + self.mode = mode + + @abstractmethod + def __next__(self): + """Return the next SeqRecord. + + This method must be implemented by the subclass. + """ + + def __iter__(self): + """Iterate over the entries as a SeqRecord objects. + + Example usage for Fasta files:: + + with open("example.fasta","r") as myFile: + myFastaReader = FastaIterator(myFile) + for record in myFastaReader: + print(record.id) + print(record.seq) + + This method SHOULD NOT be overridden by any subclass. + """ + return self + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_traceback): + try: + stream = self.stream + except AttributeError: + return + if self.stream is not self.source: + self.stream.close() + del self.stream + return False + + +def _get_seq_string(record: SeqRecord) -> str: + """Use this to catch errors like the sequence being None (PRIVATE).""" + if not isinstance(record, SeqRecord): + raise TypeError("Expected a SeqRecord object") + if record.seq is None: + raise TypeError(f"SeqRecord (id={record.id}) has None for its sequence.") + elif not isinstance(record.seq, (Seq, MutableSeq)): + raise TypeError(f"SeqRecord (id={record.id}) has an invalid sequence.") + return str(record.seq) + + +# Function variant of the SequenceWriter method. +def _clean(text: str) -> str: + """Use this to avoid getting newlines in the output (PRIVATE).""" + return text.replace("\n", " ").replace("\r", " ") + + +class SequenceWriter(ABC, Generic[AnyStr]): + """Base class for sequence writers. This class should be subclassed. + + The user may call the write_file() method to write a complete + file containing the sequences. + + Most subclasses will only need to implement the write_record method. + Subclasses must implement the write_records method to include a file + header or footer, for file formats that only allow one record, or for + file formats that cannot be written sequentially. + """ + + @property + @abstractmethod + def modes(self): + """File modes (binary or text) that the writer can handle. + + This property must be "t" (for text mode only), "b" (for binary mode + only), "tb" (if both text and binary mode are accepted, but text mode + is preferred), or "bt" (if both text and binary mode are accepted, but + binary mode is preferred). + """ + pass + + def __init__(self, target: _IOSource) -> None: + """Create the writer object.""" + if isinstance(target, _PathLikeTypes): + mode = self.modes[0] + stream = open(target, "w" + mode) + else: + stream = target + modes = "tb" + values = ("", b"") + for mode, value in zip(modes, values): + try: + stream.write(value) + except TypeError: + continue + else: + break + else: + raise RuntimeError("Failed to read from input data") from None + if mode not in self.modes: + if mode == "t": + # target was opened in text mode + raise StreamModeError("File must be opened in binary mode.") + elif mode == "b": + # target was opened in binary mode + raise StreamModeError("File must be opened in text mode.") + self.target = target + self.handle = stream + + def clean(self, text: str) -> str: + """Use this to avoid getting newlines in the output.""" + return text.replace("\n", " ").replace("\r", " ") + + @classmethod + def to_string(cls, record): + """Format the record and return the string.""" + handle = StringIO() + writer = cls(handle) + records = [record] + writer.write_file(records) + return handle.getvalue() + + def write_record(self, record): + """Write a single record to the output file. + + record - a SeqRecord object + """ + + def write_records(self, records): + """Write records to the output file, and return the number of records. + + records - A list or iterator returning SeqRecord objects + """ + count = 0 + for record in records: + self.write_record(record) + count += 1 + return count + + def write_file(self, records): + """Write a complete file with the records, and return the number of records. + + records - A list or iterator returning SeqRecord objects + """ + try: + count = self.write_records(records) + finally: + if self.handle is not self.target: + self.handle.close() + return count diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/NibIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/NibIO.py new file mode 100644 index 0000000000000000000000000000000000000000..3e99cb6a990cb856439fa9539ccaeb37c96a4c96 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/NibIO.py @@ -0,0 +1,175 @@ +# Copyright 2019 by Michiel de Hoon. All rights reserved. +# Based on code contributed and copyright 2016 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the UCSC nib file format. + +Nib stands for nibble (4 bit) representation of nucleotide sequences. +The two nibbles in a byte each store one nucleotide, represented numerically +as follows: + + - ``0`` - T + - ``1`` - C + - ``2`` - A + - ``3`` - G + - ``4`` - N (unknown) + +As the first bit in a nibble is set if the nucleotide is soft-masked, we +additionally have: + + - ``8`` - t + - ``9`` - c + - ``a`` - a + - ``b`` - g + - ``c`` - n (unknown) + +A nib file contains only one sequence record. +You are expected to use this module via the Bio.SeqIO functions under +the format name "nib": + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Nib/test_even_bigendian.nib", "nib") + >>> print("%i %s..." % (len(record), record.seq[:20])) + 50 nAGAAGagccgcNGgCActt... + +For detailed information on the file format, please see the UCSC +description at https://genome.ucsc.edu/FAQ/FAQformat.html. +""" + +import binascii +import struct +import sys + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + + +class NibIterator(SequenceIterator): + """Parser for nib files.""" + + modes = "b" + + def __init__(self, source): + """Iterate over a nib file and yield a SeqRecord. + + - source - a file-like object or a path to a file in the nib file + format as defined by UCSC; the file must be opened in binary mode. + + Note that a nib file always contains only one sequence record. + The sequence of the resulting SeqRecord object should match the sequence + generated by Jim Kent's nibFrag utility run with the -masked option. + + This function is used internally via the Bio.SeqIO functions: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Nib/test_even_bigendian.nib", "nib") + >>> print("%s %i" % (record.seq, len(record))) + nAGAAGagccgcNGgCActtGAnTAtCGTCgcCacCaGncGncTtGNtGG 50 + + You can also call it directly: + + >>> with open("Nib/test_even_bigendian.nib", "rb") as handle: + ... for record in NibIterator(handle): + ... print("%s %i" % (record.seq, len(record))) + ... + nAGAAGagccgcNGgCActtGAnTAtCGTCgcCacCaGncGncTtGNtGG 50 + + """ + super().__init__(source, fmt="Nib") + word = self.stream.read(4) + if not word: + raise ValueError("Empty file.") + signature = word.hex() + if signature == "3a3de96b": + self.byteorder = "little" # little-endian + elif signature == "6be93d3a": + self.byteorder = "big" # big-endian + else: + raise ValueError("unexpected signature in nib header") + + def __next__(self): + """Iterate over the records in the nib file.""" + stream = self.stream + byteorder = self.byteorder + number = stream.read(4) + if not number: + raise StopIteration + length = int.from_bytes(number, byteorder) + data = stream.read() + indices = binascii.hexlify(data) + if length % 2 == 0: + if len(indices) != length: + raise ValueError("Unexpected file size") + elif length % 2 == 1: + if len(indices) != length + 1: + raise ValueError("Unexpected file size") + indices = indices[:length] + if not set(indices).issubset(b"0123489abc"): + raise ValueError("Unexpected sequence data found in file") + table = bytes.maketrans(b"0123489abc", b"TCAGNtcagn") + nucleotides = indices.translate(table) + sequence = Seq(nucleotides) + record = SeqRecord(sequence) + return record + + +class NibWriter(SequenceWriter): + """Nib file writer.""" + + modes = "b" + + def write_header(self): + """Write the file header.""" + handle = self.handle + byteorder = sys.byteorder + if byteorder == "little": # little-endian + signature = "3a3de96b" + elif byteorder == "big": # big-endian + signature = "6be93d3a" + else: + raise RuntimeError(f"unexpected system byte order {byteorder}") + handle.write(bytes.fromhex(signature)) + + def write_record(self, record): + """Write a single record to the output file.""" + handle = self.handle + sequence = record.seq + nucleotides = bytes(sequence) + length = len(sequence) + handle.write(struct.pack("i", length)) + table = bytes.maketrans(b"TCAGNtcagn", b"0123489abc") + padding = length % 2 + suffix = padding * b"T" + nucleotides += suffix + if not set(nucleotides).issubset(b"ACGTNacgtn"): + raise ValueError("Sequence should contain A,C,G,T,N,a,c,g,t,n only") + indices = nucleotides.translate(table) + handle.write(binascii.unhexlify(indices)) + + def write_records(self, records): + """Write records to the output file, and return the number of records. + + records - A list or iterator returning SeqRecord objects + """ + self.write_header() + count = 0 + for record in records: + if count == 1: + raise ValueError("More than one sequence found") + self.write_record(record) + count += 1 + if count != 1: + raise ValueError("Must have one sequence") + return count + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PdbIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PdbIO.py new file mode 100644 index 0000000000000000000000000000000000000000..40bafea0184679c4b8a369fa7788ae1d467816f4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PdbIO.py @@ -0,0 +1,574 @@ +# Copyright 2012 by Eric Talevich. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for accessing sequences in PDB and mmCIF files.""" + +import collections +import warnings + +from Bio import BiopythonParserWarning +from Bio.Data.PDBData import protein_letters_3to1 +from Bio.Data.PDBData import protein_letters_3to1_extended +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator + +_aa3to1_dict = {} +_aa3to1_dict.update(protein_letters_3to1) +_aa3to1_dict.update(protein_letters_3to1_extended) + + +def _res2aacode(residue, undef_code="X"): + """Return the one-letter amino acid code from the residue name. + + Non-amino acid are returned as "X". + """ + if isinstance(residue, str): + return _aa3to1_dict.get(residue, undef_code) + + return _aa3to1_dict.get(residue.resname, undef_code) + + +def AtomIterator(pdb_id, structure): + """Return SeqRecords from Structure objects. + + Base function for sequence parsers that read structures Bio.PDB parsers. + + Once a parser from Bio.PDB has been used to load a structure into a + Bio.PDB.Structure.Structure object, there is no difference in how the + sequence parser interprets the residue sequence. The functions in this + module may be used by SeqIO modules wishing to parse sequences from lists + of residues. + + Calling functions must pass a Bio.PDB.Structure.Structure object. + + + See Bio.SeqIO.PdbIO.PdbAtomIterator and Bio.SeqIO.PdbIO.CifAtomIterator for + details. + """ + model = structure[0] + for chn_id, chain in sorted(model.child_dict.items()): + # HETATM mod. res. policy: remove mod if in sequence, else discard + residues = [ + res + for res in chain.get_unpacked_list() + if _res2aacode(res.get_resname().upper()) != "X" + ] + if not residues: + continue + # Identify missing residues in the structure + # (fill the sequence with 'X' residues in these regions) + gaps = [] + rnumbers = [r.id[1] for r in residues] + for i, rnum in enumerate(rnumbers[:-1]): + if rnumbers[i + 1] != rnum + 1 and rnumbers[i + 1] != rnum: + # It's a gap! + gaps.append((i + 1, rnum, rnumbers[i + 1])) + if gaps: + res_out = [] + prev_idx = 0 + for i, pregap, postgap in gaps: + if postgap > pregap: + gapsize = postgap - pregap - 1 + res_out.extend(_res2aacode(x) for x in residues[prev_idx:i]) + prev_idx = i + res_out.append("X" * gapsize) + else: + warnings.warn( + "Ignoring out-of-order residues after a gap", + BiopythonParserWarning, + ) + # Keep the normal part, drop the out-of-order segment + # (presumably modified or hetatm residues, e.g. 3BEG) + res_out.extend(_res2aacode(x) for x in residues[prev_idx:i]) + break + else: + # Last segment + res_out.extend(_res2aacode(x) for x in residues[prev_idx:]) + else: + # No gaps + res_out = [_res2aacode(x) for x in residues] + record_id = f"{pdb_id}:{chn_id}" + # ENH - model number in SeqRecord id if multiple models? + # id = "Chain%s" % str(chain.id) + # if len(structure) > 1 : + # id = ("Model%s|" % str(model.id)) + id + + record = SeqRecord(Seq("".join(res_out)), id=record_id, description=record_id) + # TODO: Test PDB files with DNA and RNA too: + record.annotations["molecule_type"] = "protein" + + record.annotations["model"] = model.id + record.annotations["chain"] = chain.id + + record.annotations["start"] = int(rnumbers[0]) + record.annotations["end"] = int(rnumbers[-1]) + yield record + + +class PdbSeqresIterator(SequenceIterator): + """Parser for PDB files.""" + + modes = "t" + + def __init__(self, source: _TextIOSource) -> None: + """Iterate over chains in a PDB file as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + + The sequences are derived from the SEQRES lines in the + PDB file header, not the atoms of the 3D structure. + + Specifically, these PDB records are handled: DBREF, DBREF1, DBREF2, SEQADV, SEQRES, MODRES + + See: http://www.wwpdb.org/documentation/format23/sect3.html + + This gets called internally via Bio.SeqIO for the SEQRES based interpretation + of the PDB file format: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-seqres"): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... print(record.dbxrefs) + ... + Record id 1A8O:A, chain A + ['UNP:P12497', 'UNP:POL_HV1N5'] + + Equivalently, + + >>> with open("PDB/1A8O.pdb") as handle: + ... for record in PdbSeqresIterator(handle): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... print(record.dbxrefs) + ... + Record id 1A8O:A, chain A + ['UNP:P12497', 'UNP:POL_HV1N5'] + + Note the chain is recorded in the annotations dictionary, and any PDB DBREF + lines are recorded in the database cross-references list. + """ + super().__init__(source, fmt="PDB") + self.cache = None + + def __next__(self): + """Iterate over the records in the PDB file.""" + if self.cache is None: + chains = collections.defaultdict(list) + metadata = collections.defaultdict(list) + + rec_name = None + for line in self.stream: + rec_name = line[0:6].strip() + if rec_name == "SEQRES": + # NB: We only actually need chain ID and the residues here; + # commented bits are placeholders from the wwPDB spec. + # Serial number of the SEQRES record for the current chain. + # Starts at 1 and increments by one each line. + # Reset to 1 for each chain. + # ser_num = int(line[8:10]) + # Chain identifier. This may be any single legal character, + # including a blank which is used if there is only one + # chain. + chn_id = line[11] + # Number of residues in the chain (repeated on every record) + # num_res = int(line[13:17]) + residues = [_res2aacode(res) for res in line[19:].split()] + chains[chn_id].extend(residues) + elif rec_name == "DBREF": + # ID code of this entry (PDB ID) + pdb_id = line[7:11] + # Chain identifier. + chn_id = line[12] + # Initial sequence number of the PDB sequence segment. + # seq_begin = int(line[14:18]) + # Initial insertion code of the PDB sequence segment. + # icode_begin = line[18] + # Ending sequence number of the PDB sequence segment. + # seq_end = int(line[20:24]) + # Ending insertion code of the PDB sequence segment. + # icode_end = line[24] + # Sequence database name. + database = line[26:32].strip() + # Sequence database accession code. + db_acc = line[33:41].strip() + # Sequence database identification code. + db_id_code = line[42:54].strip() + # Initial sequence number of the database seqment. + # db_seq_begin = int(line[55:60]) + # Insertion code of initial residue of the segment, if PDB + # is the reference. + # db_icode_begin = line[60] + # Ending sequence number of the database segment. + # db_seq_end = int(line[62:67]) + # Insertion code of the ending residue of the segment, if + # PDB is the reference. + # db_icode_end = line[67] + metadata[chn_id].append( + { + "pdb_id": pdb_id, + "database": database, + "db_acc": db_acc, + "db_id_code": db_id_code, + } + ) + elif rec_name == "DBREF1": + # ID code of this entry (PDB ID) + pdb_id = line[7:11] + # Chain identifier. + chn_id = line[12] + # Sequence database name. + database = line[26:32].strip() + # Sequence database identification code. + db_id_code = line[47:67].strip() + elif rec_name == "DBREF2": + # Ensure ID code and chain are consistent: + if pdb_id != line[7:11] or chn_id != line[12]: + raise ValueError("DBREF2 identifiers do not match") + # Sequence database accession code. + db_acc = line[18:40].strip() + metadata[chn_id].append( + { + "pdb_id": pdb_id, + "database": database, + "db_acc": db_acc, + "db_id_code": db_id_code, + } + ) + # ENH: 'SEQADV' 'MODRES' + + if rec_name is None: + raise ValueError("Empty file.") + + self.cache = [] + for chn_id, residues in sorted(chains.items()): + record = SeqRecord(Seq("".join(residues))) + record.annotations = {"chain": chn_id} + # TODO: Test PDB files with DNA and RNA too: + record.annotations["molecule_type"] = "protein" + if chn_id in metadata: + m = metadata[chn_id][0] + record.id = record.name = f"{m['pdb_id']}:{chn_id}" + record.description = ( + f"{m['database']}:{m['db_acc']} {m['db_id_code']}" + ) + for melem in metadata[chn_id]: + record.dbxrefs.extend( + [ + f"{melem['database']}:{melem['db_acc']}", + f"{melem['database']}:{melem['db_id_code']}", + ] + ) + else: + record.id = chn_id + self.cache.append(record) + try: + record = self.cache.pop(0) + except IndexError: + raise StopIteration + else: + return record + + +class PdbAtomIterator(SequenceIterator): + """Parser for structures in a PDB files.""" + + modes = "t" + + def __init__(self, source: _TextIOSource) -> None: + """Iterate over structures in a PDB file as SeqRecord objects. + + Argument source is a file-like object or a path to a file. + + The sequences are derived from the 3D structure (ATOM records), not the + SEQRES lines in the PDB file header. + + Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM + entries are converted to "X" in the sequence. + + In addition to information from the PDB header (which is the same for + all records), the following chain specific information is placed in the + annotation: + + record.annotations["residues"] = List of residue ID strings + record.annotations["chain"] = Chain ID (typically A, B ,...) + record.annotations["model"] = Model ID (typically zero) + + Where amino acids are missing from the structure, as indicated by + residue numbering, the sequence is filled in with 'X' characters to + match the size of the missing region, and None is included as the + corresponding entry in the list record.annotations["residues"]. + + This function uses the Bio.PDB module to do most of the hard work. The + annotation information could be improved but this extra parsing should + be done in parse_pdb_header, not this module. + + This gets called internally via Bio.SeqIO for the atom based + interpretation of the PDB file format: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-atom"): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... + Record id 1A8O:A, chain A + + Equivalently, + + >>> with open("PDB/1A8O.pdb") as handle: + ... for record in PdbAtomIterator(handle): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... + Record id 1A8O:A, chain A + + """ + # TODO - Add record.annotations to the doctest, esp the residues (not working?) + + # Only import PDB when needed, to avoid/delay NumPy dependency in SeqIO + from Bio.PDB.PDBParser import PDBParser + + structure = PDBParser().get_structure(None, source) + pdb_id = structure.header["idcode"] + if not pdb_id: + warnings.warn( + "'HEADER' line not found; can't determine PDB ID.", + BiopythonParserWarning, + ) + pdb_id = "????" + + records = [] + for record in AtomIterator(pdb_id, structure): + # The PDB header was loaded as a dictionary, so let's reuse it all + record.annotations.update(structure.header) + + # ENH - add letter annotations -- per-residue info, e.g. numbers + + records.append(record) + + self.records = iter(records) + + def __next__(self): + return next(self.records) + + +PDBX_POLY_SEQ_SCHEME_FIELDS = ( + "_pdbx_poly_seq_scheme.asym_id", # Chain ID + "_pdbx_poly_seq_scheme.mon_id", # Residue type +) + +STRUCT_REF_FIELDS = ( + "_struct_ref.id", # ID of this reference + "_struct_ref.db_name", # Name of the database + "_struct_ref.db_code", # Code for this entity + "_struct_ref.pdbx_db_accession", # DB accession ID of ref +) + +STRUCT_REF_SEQ_FIELDS = ( + "_struct_ref_seq.ref_id", # Pointer to _struct_ref + "_struct_ref_seq.pdbx_PDB_id_code", # PDB ID of this structure + "_struct_ref_seq.pdbx_strand_id", # Chain ID of the reference +) + + +class CifSeqresIterator(SequenceIterator): + """Parser for chains in an mmCIF files.""" + + modes = "t" + + def __init__(self, source: _TextIOSource) -> None: + """Iterate over chains in an mmCIF file as SeqRecord objects. + + Argument source is a file-like object or a path to a file. + + The sequences are derived from the _entity_poly_seq entries in the + mmCIF file, not the atoms of the 3D structure. + + Specifically, these mmCIF records are handled: _pdbx_poly_seq_scheme + and _struct_ref_seq. The _pdbx_poly_seq records contain sequence + information, and the _struct_ref_seq records contain database + cross-references. + + See: + http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v40.dic/Categories/pdbx_poly_seq_scheme.html + and + http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v50.dic/Categories/struct_ref_seq.html + + This gets called internally via Bio.SeqIO for the sequence-based + interpretation of the mmCIF file format: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("PDB/1A8O.cif", "cif-seqres"): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... print(record.dbxrefs) + ... + Record id 1A8O:A, chain A + ['UNP:P12497', 'UNP:POL_HV1N5'] + + Equivalently, + + >>> with open("PDB/1A8O.cif") as handle: + ... for record in CifSeqresIterator(handle): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... print(record.dbxrefs) + ... + Record id 1A8O:A, chain A + ['UNP:P12497', 'UNP:POL_HV1N5'] + + Note the chain is recorded in the annotations dictionary, and any mmCIF + _struct_ref_seq entries are recorded in the database cross-references + list. + """ + + # Only import PDB when needed, to avoid/delay NumPy dependency in SeqIO + from Bio.PDB.MMCIF2Dict import MMCIF2Dict + + chains = collections.defaultdict(list) + metadata = collections.defaultdict(list) + records = MMCIF2Dict(source) + + # Explicitly convert records to list (See #1533). + # If an item is not present, use an empty list + for field in ( + PDBX_POLY_SEQ_SCHEME_FIELDS + STRUCT_REF_SEQ_FIELDS + STRUCT_REF_FIELDS + ): + if field not in records: + records[field] = [] + elif not isinstance(records[field], list): + records[field] = [records[field]] + + for asym_id, mon_id in zip( + records["_pdbx_poly_seq_scheme.asym_id"], + records["_pdbx_poly_seq_scheme.mon_id"], + ): + mon_id_1l = _res2aacode(mon_id) + chains[asym_id].append(mon_id_1l) + + # Build a dict of _struct_ref records, indexed by the id field: + struct_refs = {} + for ref_id, db_name, db_code, db_acc in zip( + records["_struct_ref.id"], + records["_struct_ref.db_name"], + records["_struct_ref.db_code"], + records["_struct_ref.pdbx_db_accession"], + ): + struct_refs[ref_id] = { + "database": db_name, + "db_id_code": db_code, + "db_acc": db_acc, + } + + # Look through _struct_ref_seq records, look up the corresponding + # _struct_ref and add an entry to the metadata list for this chain. + for ref_id, pdb_id, chain_id in zip( + records["_struct_ref_seq.ref_id"], + records["_struct_ref_seq.pdbx_PDB_id_code"], + records["_struct_ref_seq.pdbx_strand_id"], + ): + struct_ref = struct_refs[ref_id] + + # The names here mirror those in PdbIO + metadata[chain_id].append({"pdb_id": pdb_id}) + metadata[chain_id][-1].update(struct_ref) + + records = [] # type: ignore + for chn_id, residues in sorted(chains.items()): + record = SeqRecord(Seq("".join(residues))) + record.annotations = {"chain": chn_id} + # TODO: Test PDB files with DNA and RNA too: + record.annotations["molecule_type"] = "protein" + if chn_id in metadata: + m = metadata[chn_id][0] + record.id = record.name = f"{m['pdb_id']}:{chn_id}" + record.description = f"{m['database']}:{m['db_acc']} {m['db_id_code']}" + for melem in metadata[chn_id]: + record.dbxrefs.extend( + [ + f"{melem['database']}:{melem['db_acc']}", + f"{melem['database']}:{melem['db_id_code']}", + ] + ) + else: + record.id = chn_id + records.append(record) # type: ignore + + self.records = iter(records) + + def __next__(self): + return next(self.records) + + +class CifAtomIterator(SequenceIterator): + """Parser for structures in an mmCIF files.""" + + modes = "t" + + def __init__(self, source: _TextIOSource) -> None: + """Iterate over structures in an mmCIF file as SeqRecord objects. + + Argument source is a file-like object or a path to a file. + + The sequences are derived from the 3D structure (_atom_site.* fields) + in the mmCIF file. + + Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM + entries are converted to "X" in the sequence. + + In addition to information from the PDB header (which is the same for + all records), the following chain specific information is placed in the + annotation: + + record.annotations["residues"] = List of residue ID strings + record.annotations["chain"] = Chain ID (typically A, B ,...) + record.annotations["model"] = Model ID (typically zero) + + Where amino acids are missing from the structure, as indicated by + residue numbering, the sequence is filled in with 'X' characters to + match the size of the missing region, and None is included as the + corresponding entry in the list record.annotations["residues"]. + + This function uses the Bio.PDB module to do most of the hard work. The + annotation information could be improved but this extra parsing should + be done in parse_pdb_header, not this module. + + This gets called internally via Bio.SeqIO for the atom based + interpretation of the PDB file format: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("PDB/1A8O.cif", "cif-atom"): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... + Record id 1A8O:A, chain A + + Equivalently, + + >>> with open("PDB/1A8O.cif") as handle: + ... for record in CifAtomIterator(handle): + ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) + ... + Record id 1A8O:A, chain A + + """ + # TODO - Add record.annotations to the doctest, esp the residues (not working?) + + # Only import parser when needed, to avoid/delay NumPy dependency in SeqIO + from Bio.PDB.MMCIFParser import MMCIFParser + + structure = MMCIFParser().get_structure(None, source) + pdb_id = structure.header["idcode"] + if not pdb_id: + warnings.warn("Could not determine the PDB ID.", BiopythonParserWarning) + pdb_id = "????" + self.records = AtomIterator(pdb_id, structure) + + def __next__(self): + return next(self.records) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PhdIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PhdIO.py new file mode 100644 index 0000000000000000000000000000000000000000..cedb43f395892a0c41a5ebcc8793acfca776b3c3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PhdIO.py @@ -0,0 +1,169 @@ +# Copyright 2008-2016 by Peter Cock. All rights reserved. +# Revisions copyright 2009 by Cymon J. Cox. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "phd" file format. + +PHD files are output by PHRED and used by PHRAP and CONSED. + +You are expected to use this module via the Bio.SeqIO functions, under the +format name "phd". See also the underlying Bio.Sequencing.Phd module. + +For example, using Bio.SeqIO we can read in one of the example PHRED files +from the Biopython unit tests: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("Phd/phd1", "phd"): + ... print(record.id) + ... print("%s..." % record.seq[:10]) + ... print("%s..." % record.letter_annotations["phred_quality"][:10]) + 34_222_(80-A03-19).b.ab1 + ctccgtcgga... + [9, 9, 10, 19, 22, 37, 28, 28, 24, 22]... + 425_103_(81-A03-19).g.ab1 + cgggatccca... + [14, 17, 22, 10, 10, 10, 15, 8, 8, 9]... + 425_7_(71-A03-19).b.ab1 + acataaatca... + [10, 10, 10, 10, 8, 8, 6, 6, 6, 6]... + +Since PHRED files contain quality scores, you can save them as FASTQ or as +QUAL files, for example using Bio.SeqIO.write(...), or simply with the format +method of the SeqRecord object: + + >>> print(record[:50].format("fastq")) + @425_7_(71-A03-19).b.ab1 + acataaatcaaattactnaccaacacacaaaccngtctcgcgtagtggag + + + ++++))'''')(''')$!$''')''''(+.''$!$))))+)))''''''' + + +Or, + + >>> print(record[:50].format("qual")) + >425_7_(71-A03-19).b.ab1 + 10 10 10 10 8 8 6 6 6 6 8 7 6 6 6 8 3 0 3 6 6 6 8 6 6 6 6 7 + 10 13 6 6 3 0 3 8 8 8 8 10 8 8 8 6 6 6 6 6 6 6 + + +Note these examples only show the first 50 bases to keep the output short. +""" + +from collections.abc import Iterator + +from Bio.SeqRecord import SeqRecord +from Bio.Sequencing import Phd + +from .Interfaces import _IOSource +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter +from .QualityIO import _get_phred_quality + + +class PhdIterator(SequenceIterator): + """Parser for PHD files.""" + + modes = "t" + + def __init__(self, source: _TextIOSource) -> None: + """Return SeqRecord objects from a PHD file. + + Arguments: + - source - input stream opened in text mode, or a path to a file + + This uses the Bio.Sequencing.Phd module to do the hard work. + """ + super().__init__(source, fmt="PHD") + + def __next__(self): + phd_record = Phd._read(self.stream) + if phd_record is None: + raise StopIteration + # Convert the PHY record into a SeqRecord... + # The "filename" can contain spaces, e.g. 'HWI-EAS94_4_1_1_602_99 1' + # from unit test example file phd_solexa. + # This will cause problems if used as the record identifier + # (e.g. output for FASTQ format). + name = phd_record.file_name.split(None, 1)[0] + seq_record = SeqRecord( + phd_record.seq, id=name, name=name, description=phd_record.file_name + ) + # Just reuse the comments dictionary as the SeqRecord's annotations + seq_record.annotations = phd_record.comments + seq_record.annotations["molecule_type"] = "DNA" + # And store the qualities and peak locations as per-letter-annotation + seq_record.letter_annotations["phred_quality"] = [ + int(site[1]) for site in phd_record.sites + ] + try: + seq_record.letter_annotations["peak_location"] = [ + int(site[2]) for site in phd_record.sites + ] + except IndexError: + # peak locations are not always there according to + # David Gordon (the Consed author) + pass + return seq_record + + +class PhdWriter(SequenceWriter): + """Class to write Phd format files.""" + + modes = "t" + + def write_record(self, record): + """Write a single Phd record to the file.""" + assert record.seq, "No sequence present in SeqRecord" + # This method returns the 'phred_quality' scores or converted + # 'solexa_quality' scores if present, else raises a value error + phred_qualities = _get_phred_quality(record) + peak_locations = record.letter_annotations.get("peak_location") + if len(record.seq) != len(phred_qualities): + raise ValueError( + "Number of phd quality scores does not match length of sequence" + ) + if peak_locations: + if len(record.seq) != len(peak_locations): + raise ValueError( + "Number of peak location scores does not match length of sequence" + ) + if None in phred_qualities: + raise ValueError("A quality value of None was found") + if record.description.startswith(f"{record.id} "): + title = record.description + else: + title = f"{record.id} {record.description}" + self.handle.write(f"BEGIN_SEQUENCE {self.clean(title)}\nBEGIN_COMMENT\n") + for annot in [k.lower() for k in Phd.CKEYWORDS]: + value = None + if annot == "trim": + if record.annotations.get("trim"): + value = "%s %s %.4f" % record.annotations["trim"] + elif annot == "trace_peak_area_ratio": + if record.annotations.get("trace_peak_area_ratio"): + value = f"{record.annotations['trace_peak_area_ratio']:.4f}" + else: + value = record.annotations.get(annot) + if value or value == 0: + self.handle.write(f"{annot.upper()}: {value}\n") + + self.handle.write("END_COMMENT\nBEGIN_DNA\n") + for i, site in enumerate(record.seq): + if peak_locations: + self.handle.write( + "%s %i %i\n" % (site, round(phred_qualities[i]), peak_locations[i]) + ) + else: + self.handle.write("%s %i\n" % (site, round(phred_qualities[i]))) + + self.handle.write("END_DNA\nEND_SEQUENCE\n") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PirIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PirIO.py new file mode 100644 index 0000000000000000000000000000000000000000..0cbce3c38b0e084a5dff3e4cd6e491624a5782db --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/PirIO.py @@ -0,0 +1,292 @@ +# Copyright 2008-2015 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "pir" (aka PIR or NBRF) file format. + +This module is for reading and writing PIR or NBRF format files as +SeqRecord objects. + +You are expected to use this module via the Bio.SeqIO functions, or if +the file contains a sequence alignment, optionally via Bio.AlignIO instead. + +This format was introduced for the Protein Information Resource (PIR), a +project of the National Biomedical Research Foundation (NBRF). The PIR +database itself is now part of UniProt. + +The file format is described online at: +http://www.ebi.ac.uk/help/pir_frame.html +http://www.cmbi.kun.nl/bioinf/tools/crab_pir.html (currently down) + +An example file in this format would be:: + + >P1;CRAB_ANAPL + ALPHA CRYSTALLIN B CHAIN (ALPHA(B)-CRYSTALLIN). + MDITIHNPLI RRPLFSWLAP SRIFDQIFGE HLQESELLPA SPSLSPFLMR + SPIFRMPSWL ETGLSEMRLE KDKFSVNLDV KHFSPEELKV KVLGDMVEIH + GKHEERQDEH GFIAREFNRK YRIPADVDPL TITSSLSLDG VLTVSAPRKQ + SDVPERSIPI TREEKPAIAG AQRK* + + >P1;CRAB_BOVIN + ALPHA CRYSTALLIN B CHAIN (ALPHA(B)-CRYSTALLIN). + MDIAIHHPWI RRPFFPFHSP SRLFDQFFGE HLLESDLFPA STSLSPFYLR + PPSFLRAPSW IDTGLSEMRL EKDRFSVNLD VKHFSPEELK VKVLGDVIEV + HGKHEERQDE HGFISREFHR KYRIPADVDP LAITSSLSSD GVLTVNGPRK + QASGPERTIP ITREEKPAVT AAPKK* + +Or, an example of a multiple sequence alignment:: + + >P1;S27231 + rhodopsin - northern leopard frog + MNGTEGPNFY IPMSNKTGVV RSPFDYPQYY LAEPWKYSVL AAYMFLLILL GLPINFMTLY + VTIQHKKLRT PLNYILLNLG VCNHFMVLCG FTITMYTSLH GYFVFGQTGC YFEGFFATLG + GEIALWSLVV LAIERYIVVC KPMSNFRFGE NHAMMGVAFT WIMALACAVP PLFGWSRYIP + EGMQCSCGVD YYTLKPEVNN ESFVIYMFVV HFLIPLIIIS FCYGRLVCTV KEAAAQQQES + ATTQKAEKEV TRMVIIMVIF FLICWVPYAY VAFYIFTHQG SEFGPIFMTV PAFFAKSSAI + YNPVIYIMLN KQFRNCMITT LCCGKNPFGD DDASSAATSK TEATSVSTSQ VSPA* + + >P1;I51200 + rhodopsin - African clawed frog + MNGTEGPNFY VPMSNKTGVV RSPFDYPQYY LAEPWQYSAL AAYMFLLILL GLPINFMTLF + VTIQHKKLRT PLNYILLNLV FANHFMVLCG FTVTMYTSMH GYFIFGPTGC YIEGFFATLG + GEVALWSLVV LAVERYIVVC KPMANFRFGE NHAIMGVAFT WIMALSCAAP PLFGWSRYIP + EGMQCSCGVD YYTLKPEVNN ESFVIYMFIV HFTIPLIVIF FCYGRLLCTV KEAAAQQQES + LTTQKAEKEV TRMVVIMVVF FLICWVPYAY VAFYIFTHQG SNFGPVFMTV PAFFAKSSAI + YNPVIYIVLN KQFRNCLITT LCCGKNPFGD EDGSSAATSK TEASSVSSSQ VSPA* + + >P1;JN0120 + rhodopsin - Japanese lamprey + MNGTEGDNFY VPFSNKTGLA RSPYEYPQYY LAEPWKYSAL AAYMFFLILV GFPVNFLTLF + VTVQHKKLRT PLNYILLNLA MANLFMVLFG FTVTMYTSMN GYFVFGPTMC SIEGFFATLG + GEVALWSLVV LAIERYIVIC KPMGNFRFGN THAIMGVAFT WIMALACAAP PLVGWSRYIP + EGMQCSCGPD YYTLNPNFNN ESYVVYMFVV HFLVPFVIIF FCYGRLLCTV KEAAAAQQES + ASTQKAEKEV TRMVVLMVIG FLVCWVPYAS VAFYIFTHQG SDFGATFMTL PAFFAKSSAL + YNPVIYILMN KQFRNCMITT LCCGKNPLGD DE-SGASTSKT EVSSVSTSPV SPA* + + +As with the FASTA format, each record starts with a line beginning with ">" +character. There is then a two letter sequence type (P1, F1, DL, DC, RL, +RC, or XX), a semi colon, and the identification code. The second like is +free text description. The remaining lines contain the sequence itself, +terminating in an asterisk. Space separated blocks of ten letters as shown +above are typical. + +Sequence codes and their meanings: + - P1 - Protein (complete) + - F1 - Protein (fragment) + - D1 - DNA (e.g. EMBOSS seqret output) + - DL - DNA (linear) + - DC - DNA (circular) + - RL - RNA (linear) + - RC - RNA (circular) + - N3 - tRNA + - N1 - Other functional RNA + - XX - Unknown + +""" + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import _get_seq_string +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +_pir_mol_type = { + "P1": "protein", + "F1": "protein", + "D1": "DNA", + "DL": "DNA", + "DC": "DNA", + "RL": "RNA", + "RC": "RNA", + "N3": "RNA", + "XX": None, +} + + +class PirIterator(SequenceIterator): + """Parser for PIR files.""" + + modes = "t" + + def __init__(self, source): + """Iterate over a PIR file and yield SeqRecord objects. + + source - file-like object or a path to a file. + + Examples + -------- + >>> with open("NBRF/DMB_prot.pir") as handle: + ... for record in PirIterator(handle): + ... print("%s length %i" % (record.id, len(record))) + HLA:HLA00489 length 263 + HLA:HLA00490 length 94 + HLA:HLA00491 length 94 + HLA:HLA00492 length 80 + HLA:HLA00493 length 175 + HLA:HLA01083 length 188 + + """ + super().__init__(source, fmt="Pir") + # Skip any text before the first record (e.g. blank lines, comments) + for line in self.stream: + if line[0] == ">": + self._line = line + break + else: + self._line = None # Premature end of file, or just empty? + + def __next__(self): + """Iterate over the records in the PIR file.""" + line = self._line + if line is None: + raise StopIteration + + pir_type = line[1:3] + if pir_type not in _pir_mol_type or line[3] != ";": + raise ValueError( + "Records should start with '>XX;' where XX is a valid sequence type" + ) + + identifier = line[4:].strip() + description = self.stream.readline() + if description == "": + raise StopIteration + else: + description = description.strip() + + lines = [] + for line in self.stream: + if line[0] == ">": + self._line = line + break + # Remove trailing whitespace, and any internal spaces + lines.append(line.rstrip().replace(" ", "")) + else: + self._line = None + seq = "".join(lines) + if seq[-1] != "*": + # Note the * terminator is present on nucleotide sequences too, + # it is not a stop codon! + raise ValueError("Sequences in PIR files should include a * terminator!") + + # Return the record and then continue... + record = SeqRecord( + Seq(seq[:-1]), id=identifier, name=identifier, description=description + ) + record.annotations["PIR-type"] = pir_type + if _pir_mol_type[pir_type]: + record.annotations["molecule_type"] = _pir_mol_type[pir_type] + return record + + +class PirWriter(SequenceWriter): + """Class to write PIR format files.""" + + modes = "t" + + def __init__(self, handle, wrap=60, record2title=None, code=None): + """Create a PIR writer. + + Arguments: + - handle - Handle to an output file, e.g. as returned + by open(filename, "w") + - wrap - Optional line length used to wrap sequence lines. + Defaults to wrapping the sequence at 60 characters + Use zero (or None) for no wrapping, giving a single + long line for the sequence. + - record2title - Optional function to return the text to be + used for the title line of each record. By default + a combination of the record.id, record.name and + record.description is used. + - code - Optional sequence code must be one of P1, F1, + D1, DL, DC, RL, RC, N3 and XX. By default None is used, + which means auto detection based on the molecule type + in the record annotation. + + You can either use:: + + handle = open(filename, "w") + writer = PirWriter(handle) + writer.write_file(myRecords) + handle.close() + + Or, follow the sequential file writer system, for example:: + + handle = open(filename, "w") + writer = PirWriter(handle) + ... + Multiple writer.write_record() and/or writer.write_records() calls + ... + handle.close() + + """ + super().__init__(handle) + self.wrap = None + if wrap: + if wrap < 1: + raise ValueError("wrap should be None, 0, or a positive integer") + self.wrap = wrap + self.record2title = record2title + self.code = code + + def write_record(self, record): + """Write a single PIR record to the file.""" + if self.record2title: + title = self.clean(self.record2title(record)) + else: + title = self.clean(record.id) + + if record.name and record.description: + description = self.clean(record.name + " - " + record.description) + elif record.name and not record.description: + description = self.clean(record.name) + else: + description = self.clean(record.description) + + if self.code: + code = self.code + else: + molecule_type = record.annotations.get("molecule_type") + if molecule_type is None: + code = "XX" + elif "DNA" in molecule_type: + code = "D1" + elif "RNA" in molecule_type: + code = "RL" + elif "protein" in molecule_type: + code = "P1" + else: + code = "XX" + + if code not in _pir_mol_type: + raise TypeError( + "Sequence code must be one of " + _pir_mol_type.keys() + "." + ) + assert "\n" not in title + assert "\r" not in description + + self.handle.write(f">{code};{title}\n{description}\n") + + data = _get_seq_string(record) # Catches sequence being None + + assert "\n" not in data + assert "\r" not in data + + if self.wrap: + line = "" + for i in range(0, len(data), self.wrap): + line += data[i : i + self.wrap] + "\n" + line = line[:-1] + "*\n" + self.handle.write(line) + else: + self.handle.write(data + "*\n") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/QualityIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/QualityIO.py new file mode 100644 index 0000000000000000000000000000000000000000..511979a324bf70df5b982845a2b2eedf54a63d53 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/QualityIO.py @@ -0,0 +1,2524 @@ +# Copyright 2009-2020 by Peter Cock. All rights reserved. +# Copyright 2020 by Michael R. Crusoe +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the FASTQ and QUAL file formats. + +Note that you are expected to use this code via the Bio.SeqIO interface, as +shown below. + +The FASTQ file format is used frequently at the Wellcome Trust Sanger Institute +to bundle a FASTA sequence and its PHRED quality data (integers between 0 and +90). Rather than using a single FASTQ file, often paired FASTA and QUAL files +are used containing the sequence and the quality information separately. + +The PHRED software reads DNA sequencing trace files, calls bases, and +assigns a non-negative quality value to each called base using a logged +transformation of the error probability, Q = -10 log10( Pe ), for example:: + + Pe = 1.0, Q = 0 + Pe = 0.1, Q = 10 + Pe = 0.01, Q = 20 + ... + Pe = 0.00000001, Q = 80 + Pe = 0.000000001, Q = 90 + +In typical raw sequence reads, the PHRED quality valuea will be from 0 to 40. +In the QUAL format these quality values are held as space separated text in +a FASTA like file format. In the FASTQ format, each quality values is encoded +with a single ASCI character using chr(Q+33), meaning zero maps to the +character "!" and for example 80 maps to "q". For the Sanger FASTQ standard +the allowed range of PHRED scores is 0 to 93 inclusive. The sequences and +quality are then stored in pairs in a FASTA like format. + +Unfortunately there is no official document describing the FASTQ file format, +and worse, several related but different variants exist. For more details, +please read this open access publication:: + + The Sanger FASTQ file format for sequences with quality scores, and the + Solexa/Illumina FASTQ variants. + P.J.A.Cock (Biopython), C.J.Fields (BioPerl), N.Goto (BioRuby), + M.L.Heuer (BioJava) and P.M. Rice (EMBOSS). + Nucleic Acids Research 2010 38(6):1767-1771 + https://doi.org/10.1093/nar/gkp1137 + +The good news is that Roche 454 sequencers can output files in the QUAL format, +and sensibly they use PHREP style scores like Sanger. Converting a pair of +FASTA and QUAL files into a Sanger style FASTQ file is easy. To extract QUAL +files from a Roche 454 SFF binary file, use the Roche off instrument command +line tool "sffinfo" with the -q or -qual argument. You can extract a matching +FASTA file using the -s or -seq argument instead. + +The bad news is that Solexa/Illumina did things differently - they have their +own scoring system AND their own incompatible versions of the FASTQ format. +Solexa/Illumina quality scores use Q = - 10 log10 ( Pe / (1-Pe) ), which can +be negative. PHRED scores and Solexa scores are NOT interchangeable (but a +reasonable mapping can be achieved between them, and they are approximately +equal for higher quality reads). + +Confusingly early Solexa pipelines produced a FASTQ like file but using their +own score mapping and an ASCII offset of 64. To make things worse, for the +Solexa/Illumina pipeline 1.3 onwards, they introduced a third variant of the +FASTQ file format, this time using PHRED scores (which is more consistent) but +with an ASCII offset of 64. + +i.e. There are at least THREE different and INCOMPATIBLE variants of the FASTQ +file format: The original Sanger PHRED standard, and two from Solexa/Illumina. + +The good news is that as of CASAVA version 1.8, Illumina sequencers will +produce FASTQ files using the standard Sanger encoding. + +You are expected to use this module via the Bio.SeqIO functions, with the +following format names: + + - "qual" means simple quality files using PHRED scores (e.g. from Roche 454) + - "fastq" means Sanger style FASTQ files using PHRED scores and an ASCII + offset of 33 (e.g. from the NCBI Short Read Archive and Illumina 1.8+). + These can potentially hold PHRED scores from 0 to 93. + - "fastq-sanger" is an alias for "fastq". + - "fastq-solexa" means old Solexa (and also very early Illumina) style FASTQ + files, using Solexa scores with an ASCII offset 64. These can hold Solexa + scores from -5 to 62. + - "fastq-illumina" means newer Illumina 1.3 to 1.7 style FASTQ files, using + PHRED scores but with an ASCII offset 64, allowing PHRED scores from 0 + to 62. + +We could potentially add support for "qual-solexa" meaning QUAL files which +contain Solexa scores, but thus far there isn't any reason to use such files. + +For example, consider the following short FASTQ file:: + + @EAS54_6_R1_2_1_413_324 + CCCTTCTTGTCTTCAGCGTTTCTCC + + + ;;3;;;;;;;;;;;;7;;;;;;;88 + @EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + + + ;;;;;;;;;;;7;;;;;-;;;3;83 + @EAS54_6_R1_2_1_443_348 + GTTGCTTCTGGCGTGGGTGGGGGGG + + + ;;;;;;;;;;;9;7;;.7;393333 + +This contains three reads of length 25. From the read length these were +probably originally from an early Solexa/Illumina sequencer but this file +follows the Sanger FASTQ convention (PHRED style qualities with an ASCII +offset of 33). This means we can parse this file using Bio.SeqIO using +"fastq" as the format name: + +>>> from Bio import SeqIO +>>> for record in SeqIO.parse("Quality/example.fastq", "fastq"): +... print("%s %s" % (record.id, record.seq)) +EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC +EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA +EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + +The qualities are held as a list of integers in each record's annotation: + +>>> print(record) +ID: EAS54_6_R1_2_1_443_348 +Name: EAS54_6_R1_2_1_443_348 +Description: EAS54_6_R1_2_1_443_348 +Number of features: 0 +Per letter annotation for: phred_quality +Seq('GTTGCTTCTGGCGTGGGTGGGGGGG') +>>> print(record.letter_annotations["phred_quality"]) +[26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] + +You can use the SeqRecord format method to show this in the QUAL format: + +>>> print(record.format("qual")) +>EAS54_6_R1_2_1_443_348 +26 26 26 26 26 26 26 26 26 26 26 24 26 22 26 26 13 22 26 18 +24 18 18 18 18 + + +Or go back to the FASTQ format, use "fastq" (or "fastq-sanger"): + +>>> print(record.format("fastq")) +@EAS54_6_R1_2_1_443_348 +GTTGCTTCTGGCGTGGGTGGGGGGG ++ +;;;;;;;;;;;9;7;;.7;393333 + + +Or, using the Illumina 1.3+ FASTQ encoding (PHRED values with an ASCII offset +of 64): + +>>> print(record.format("fastq-illumina")) +@EAS54_6_R1_2_1_443_348 +GTTGCTTCTGGCGTGGGTGGGGGGG ++ +ZZZZZZZZZZZXZVZZMVZRXRRRR + + +You can also get Biopython to convert the scores and show a Solexa style +FASTQ file: + +>>> print(record.format("fastq-solexa")) +@EAS54_6_R1_2_1_443_348 +GTTGCTTCTGGCGTGGGTGGGGGGG ++ +ZZZZZZZZZZZXZVZZMVZRXRRRR + + +Notice that this is actually the same output as above using "fastq-illumina" +as the format! The reason for this is all these scores are high enough that +the PHRED and Solexa scores are almost equal. The differences become apparent +for poor quality reads. See the functions solexa_quality_from_phred and +phred_quality_from_solexa for more details. + +If you wanted to trim your sequences (perhaps to remove low quality regions, +or to remove a primer sequence), try slicing the SeqRecord objects. e.g. + +>>> sub_rec = record[5:15] +>>> print(sub_rec) +ID: EAS54_6_R1_2_1_443_348 +Name: EAS54_6_R1_2_1_443_348 +Description: EAS54_6_R1_2_1_443_348 +Number of features: 0 +Per letter annotation for: phred_quality +Seq('TTCTGGCGTG') +>>> print(sub_rec.letter_annotations["phred_quality"]) +[26, 26, 26, 26, 26, 26, 24, 26, 22, 26] +>>> print(sub_rec.format("fastq")) +@EAS54_6_R1_2_1_443_348 +TTCTGGCGTG ++ +;;;;;;9;7; + + +If you wanted to, you could read in this FASTQ file, and save it as a QUAL file: + +>>> from Bio import SeqIO +>>> record_iterator = SeqIO.parse("Quality/example.fastq", "fastq") +>>> with open("Quality/temp.qual", "w") as out_handle: +... SeqIO.write(record_iterator, out_handle, "qual") +3 + +You can of course read in a QUAL file, such as the one we just created: + +>>> from Bio import SeqIO +>>> for record in SeqIO.parse("Quality/temp.qual", "qual"): +... print("%s read of length %d" % (record.id, len(record.seq))) +EAS54_6_R1_2_1_413_324 read of length 25 +EAS54_6_R1_2_1_540_792 read of length 25 +EAS54_6_R1_2_1_443_348 read of length 25 + +Notice that QUAL files don't have a proper sequence present! But the quality +information is there: + +>>> print(record) +ID: EAS54_6_R1_2_1_443_348 +Name: EAS54_6_R1_2_1_443_348 +Description: EAS54_6_R1_2_1_443_348 +Number of features: 0 +Per letter annotation for: phred_quality +Undefined sequence of length 25 +>>> print(record.letter_annotations["phred_quality"]) +[26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] + +Just to keep things tidy, if you are following this example yourself, you can +delete this temporary file now: + +>>> import os +>>> os.remove("Quality/temp.qual") + +Sometimes you won't have a FASTQ file, but rather just a pair of FASTA and QUAL +files. Because the Bio.SeqIO system is designed for reading single files, you +would have to read the two in separately and then combine the data. However, +since this is such a common thing to want to do, there is a helper iterator +defined in this module that does this for you - PairedFastaQualIterator. + +Alternatively, if you have enough RAM to hold all the records in memory at once, +then a simple dictionary approach would work: + +>>> from Bio import SeqIO +>>> reads = SeqIO.to_dict(SeqIO.parse("Quality/example.fasta", "fasta")) +>>> for rec in SeqIO.parse("Quality/example.qual", "qual"): +... reads[rec.id].letter_annotations["phred_quality"]=rec.letter_annotations["phred_quality"] + +You can then access any record by its key, and get both the sequence and the +quality scores. + +>>> print(reads["EAS54_6_R1_2_1_540_792"].format("fastq")) +@EAS54_6_R1_2_1_540_792 +TTGGCAGGCCAAGGCCGATGGATCA ++ +;;;;;;;;;;;7;;;;;-;;;3;83 + + +It is important that you explicitly tell Bio.SeqIO which FASTQ variant you are +using ("fastq" or "fastq-sanger" for the Sanger standard using PHRED values, +"fastq-solexa" for the original Solexa/Illumina variant, or "fastq-illumina" +for the more recent variant), as this cannot be detected reliably +automatically. + +To illustrate this problem, let's consider an artificial example: + +>>> from Bio.Seq import Seq +>>> from Bio.SeqRecord import SeqRecord +>>> test = SeqRecord(Seq("NACGTACGTA"), id="Test", description="Made up!") +>>> print(test.format("fasta")) +>Test Made up! +NACGTACGTA + +>>> print(test.format("fastq")) +Traceback (most recent call last): + ... +ValueError: No suitable quality scores found in letter_annotations of SeqRecord (id=Test). + +We created a sample SeqRecord, and can show it in FASTA format - but for QUAL +or FASTQ format we need to provide some quality scores. These are held as a +list of integers (one for each base) in the letter_annotations dictionary: + +>>> test.letter_annotations["phred_quality"] = [0, 1, 2, 3, 4, 5, 10, 20, 30, 40] +>>> print(test.format("qual")) +>Test Made up! +0 1 2 3 4 5 10 20 30 40 + +>>> print(test.format("fastq")) +@Test Made up! +NACGTACGTA ++ +!"#$%&+5?I + + +We can check this FASTQ encoding - the first PHRED quality was zero, and this +mapped to a exclamation mark, while the final score was 40 and this mapped to +the letter "I": + +>>> ord('!') - 33 +0 +>>> ord('I') - 33 +40 +>>> [ord(letter)-33 for letter in '!"#$%&+5?I'] +[0, 1, 2, 3, 4, 5, 10, 20, 30, 40] + +Similarly, we could produce an Illumina 1.3 to 1.7 style FASTQ file using PHRED +scores with an offset of 64: + +>>> print(test.format("fastq-illumina")) +@Test Made up! +NACGTACGTA ++ +@ABCDEJT^h + + +And we can check this too - the first PHRED score was zero, and this mapped to +"@", while the final score was 40 and this mapped to "h": + +>>> ord("@") - 64 +0 +>>> ord("h") - 64 +40 +>>> [ord(letter)-64 for letter in "@ABCDEJT^h"] +[0, 1, 2, 3, 4, 5, 10, 20, 30, 40] + +Notice how different the standard Sanger FASTQ and the Illumina 1.3 to 1.7 style +FASTQ files look for the same data! Then we have the older Solexa/Illumina +format to consider which encodes Solexa scores instead of PHRED scores. + +First let's see what Biopython says if we convert the PHRED scores into Solexa +scores (rounding to one decimal place): + +>>> for q in [0, 1, 2, 3, 4, 5, 10, 20, 30, 40]: +... print("PHRED %i maps to Solexa %0.1f" % (q, solexa_quality_from_phred(q))) +PHRED 0 maps to Solexa -5.0 +PHRED 1 maps to Solexa -5.0 +PHRED 2 maps to Solexa -2.3 +PHRED 3 maps to Solexa -0.0 +PHRED 4 maps to Solexa 1.8 +PHRED 5 maps to Solexa 3.3 +PHRED 10 maps to Solexa 9.5 +PHRED 20 maps to Solexa 20.0 +PHRED 30 maps to Solexa 30.0 +PHRED 40 maps to Solexa 40.0 + +Now here is the record using the old Solexa style FASTQ file: + +>>> print(test.format("fastq-solexa")) +@Test Made up! +NACGTACGTA ++ +;;>@BCJT^h + + +Again, this is using an ASCII offset of 64, so we can check the Solexa scores: + +>>> [ord(letter)-64 for letter in ";;>@BCJT^h"] +[-5, -5, -2, 0, 2, 3, 10, 20, 30, 40] + +This explains why the last few letters of this FASTQ output matched that using +the Illumina 1.3 to 1.7 format - high quality PHRED scores and Solexa scores +are approximately equal. + +""" + +import warnings +from math import log +from abc import abstractmethod +from typing import Any +from collections.abc import Callable +from typing import IO +from collections.abc import Iterator +from collections.abc import Mapping +from typing import Optional +from collections.abc import Sequence +from typing import Union +from collections.abc import Iterable +import array +from dataclasses import dataclass + +from Bio import BiopythonParserWarning +from Bio import BiopythonWarning +from Bio import BiopythonDeprecationWarning +from Bio import StreamModeError +from Bio.File import as_handle +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import _clean +from .Interfaces import _get_seq_string +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +# define score offsets. See discussion for differences between Sanger and +# Solexa offsets. +SANGER_SCORE_OFFSET = 33 +SOLEXA_SCORE_OFFSET = 64 +INVALID_CHAR_CODE = 200 +INVALID_CHAR = bytes((INVALID_CHAR_CODE,)) + + +def solexa_quality_from_phred(phred_quality: float) -> float: + """Convert a PHRED quality (range 0 to about 90) to a Solexa quality. + + PHRED and Solexa quality scores are both log transformations of a + probality of error (high score = low probability of error). This function + takes a PHRED score, transforms it back to a probability of error, and + then re-expresses it as a Solexa score. This assumes the error estimates + are equivalent. + + How does this work exactly? Well the PHRED quality is minus ten times the + base ten logarithm of the probability of error:: + + phred_quality = -10*log(error,10) + + Therefore, turning this round:: + + error = 10 ** (- phred_quality / 10) + + Now, Solexa qualities use a different log transformation:: + + solexa_quality = -10*log(error/(1-error),10) + + After substitution and a little manipulation we get:: + + solexa_quality = 10*log(10**(phred_quality/10.0) - 1, 10) + + However, real Solexa files use a minimum quality of -5. This does have a + good reason - a random base call would be correct 25% of the time, + and thus have a probability of error of 0.75, which gives 1.25 as the PHRED + quality, or -4.77 as the Solexa quality. Thus (after rounding), a random + nucleotide read would have a PHRED quality of 1, or a Solexa quality of -5. + + Taken literally, this logarithic formula would map a PHRED quality of zero + to a Solexa quality of minus infinity. Of course, taken literally, a PHRED + score of zero means a probability of error of one (i.e. the base call is + definitely wrong), which is worse than random! In practice, a PHRED quality + of zero usually means a default value, or perhaps random - and therefore + mapping it to the minimum Solexa score of -5 is reasonable. + + In conclusion, we follow EMBOSS, and take this logarithmic formula but also + apply a minimum value of -5.0 for the Solexa quality, and also map a PHRED + quality of zero to -5.0 as well. + + Note this function will return a floating point number, it is up to you to + round this to the nearest integer if appropriate. e.g. + + >>> print("%0.2f" % round(solexa_quality_from_phred(80), 2)) + 80.00 + >>> print("%0.2f" % round(solexa_quality_from_phred(50), 2)) + 50.00 + >>> print("%0.2f" % round(solexa_quality_from_phred(20), 2)) + 19.96 + >>> print("%0.2f" % round(solexa_quality_from_phred(10), 2)) + 9.54 + >>> print("%0.2f" % round(solexa_quality_from_phred(5), 2)) + 3.35 + >>> print("%0.2f" % round(solexa_quality_from_phred(4), 2)) + 1.80 + >>> print("%0.2f" % round(solexa_quality_from_phred(3), 2)) + -0.02 + >>> print("%0.2f" % round(solexa_quality_from_phred(2), 2)) + -2.33 + >>> print("%0.2f" % round(solexa_quality_from_phred(1), 2)) + -5.00 + >>> print("%0.2f" % round(solexa_quality_from_phred(0), 2)) + -5.00 + + Notice that for high quality reads PHRED and Solexa scores are numerically + equal. The differences are important for poor quality reads, where PHRED + has a minimum of zero but Solexa scores can be negative. + + Finally, as a special case where None is used for a "missing value", None + is returned: + + >>> print(solexa_quality_from_phred(None)) + None + """ + if phred_quality is None: + # Assume None is used as some kind of NULL or NA value; return None + # e.g. Bio.SeqIO gives Ace contig gaps a quality of None. + return None + elif phred_quality > 0: + # Solexa uses a minimum value of -5, which after rounding matches a + # random nucleotide base call. + return max(-5.0, 10 * log(10 ** (phred_quality / 10.0) - 1, 10)) + elif phred_quality == 0: + # Special case, map to -5 as discussed in the docstring + return -5.0 + else: + raise ValueError( + f"PHRED qualities must be positive (or zero), not {phred_quality!r}" + ) + + +def phred_quality_from_solexa(solexa_quality: float) -> float: + """Convert a Solexa quality (which can be negative) to a PHRED quality. + + PHRED and Solexa quality scores are both log transformations of a + probality of error (high score = low probability of error). This function + takes a Solexa score, transforms it back to a probability of error, and + then re-expresses it as a PHRED score. This assumes the error estimates + are equivalent. + + The underlying formulas are given in the documentation for the sister + function solexa_quality_from_phred, in this case the operation is:: + + phred_quality = 10*log(10**(solexa_quality/10.0) + 1, 10) + + This will return a floating point number, it is up to you to round this to + the nearest integer if appropriate. e.g. + + >>> print("%0.2f" % round(phred_quality_from_solexa(80), 2)) + 80.00 + >>> print("%0.2f" % round(phred_quality_from_solexa(20), 2)) + 20.04 + >>> print("%0.2f" % round(phred_quality_from_solexa(10), 2)) + 10.41 + >>> print("%0.2f" % round(phred_quality_from_solexa(0), 2)) + 3.01 + >>> print("%0.2f" % round(phred_quality_from_solexa(-5), 2)) + 1.19 + + Note that a solexa_quality less then -5 is not expected, will trigger a + warning, but will still be converted as per the logarithmic mapping + (giving a number between 0 and 1.19 back). + + As a special case where None is used for a "missing value", None is + returned: + + >>> print(phred_quality_from_solexa(None)) + None + """ + if solexa_quality is None: + # Assume None is used as some kind of NULL or NA value; return None + return None + if solexa_quality < -5: + warnings.warn( + f"Solexa quality less than -5 passed, {solexa_quality!r}", BiopythonWarning + ) + return 10 * log(10 ** (solexa_quality / 10.0) + 1, 10) + + +def _get_phred_quality(record: SeqRecord) -> list[float] | list[int]: + """Extract PHRED qualities from a SeqRecord's letter_annotations (PRIVATE). + + If there are no PHRED qualities, but there are Solexa qualities, those are + used instead after conversion. + """ + try: + return record.letter_annotations["phred_quality"] # type: ignore + except KeyError: + pass + try: + return [ + phred_quality_from_solexa(q) + for q in record.letter_annotations["solexa_quality"] + ] + except KeyError: + raise ValueError( + "No suitable quality scores found in " + "letter_annotations of SeqRecord (id=%s)." % record.id + ) from None + + +# Only map 0 to 93, we need to give a warning on truncating at 93 +_phred_to_sanger_quality_str = { + qp: chr(min(126, qp + SANGER_SCORE_OFFSET)) for qp in range(93 + 1) +} +# Only map -5 to 93, we need to give a warning on truncating at 93 +_solexa_to_sanger_quality_str = { + qs: chr(min(126, int(round(phred_quality_from_solexa(qs)) + SANGER_SCORE_OFFSET))) + for qs in range(-5, 93 + 1) +} + + +def _get_sanger_quality_str(record: SeqRecord) -> str: + """Return a Sanger FASTQ encoded quality string (PRIVATE). + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> r = SeqRecord(Seq("ACGTAN"), id="Test", + ... letter_annotations = {"phred_quality":[50, 40, 30, 20, 10, 0]}) + >>> _get_sanger_quality_str(r) + 'SI?5+!' + + If as in the above example (or indeed a SeqRecord parser with Bio.SeqIO), + the PHRED qualities are integers, this function is able to use a very fast + pre-cached mapping. However, if they are floats which differ slightly, then + it has to do the appropriate rounding - which is slower: + + >>> r2 = SeqRecord(Seq("ACGTAN"), id="Test2", + ... letter_annotations = {"phred_quality":[50.0, 40.05, 29.99, 20, 9.55, 0.01]}) + >>> _get_sanger_quality_str(r2) + 'SI?5+!' + + If your scores include a None value, this raises an exception: + + >>> r3 = SeqRecord(Seq("ACGTAN"), id="Test3", + ... letter_annotations = {"phred_quality":[50, 40, 30, 20, 10, None]}) + >>> _get_sanger_quality_str(r3) + Traceback (most recent call last): + ... + TypeError: A quality value of None was found + + If (strangely) your record has both PHRED and Solexa scores, then the PHRED + scores are used in preference: + + >>> r4 = SeqRecord(Seq("ACGTAN"), id="Test4", + ... letter_annotations = {"phred_quality":[50, 40, 30, 20, 10, 0], + ... "solexa_quality":[-5, -4, 0, None, 0, 40]}) + >>> _get_sanger_quality_str(r4) + 'SI?5+!' + + If there are no PHRED scores, but there are Solexa scores, these are used + instead (after the appropriate conversion): + + >>> r5 = SeqRecord(Seq("ACGTAN"), id="Test5", + ... letter_annotations = {"solexa_quality":[40, 30, 20, 10, 0, -5]}) + >>> _get_sanger_quality_str(r5) + 'I?5+$"' + + Again, integer Solexa scores can be looked up in a pre-cached mapping making + this very fast. You can still use approximate floating point scores: + + >>> r6 = SeqRecord(Seq("ACGTAN"), id="Test6", + ... letter_annotations = {"solexa_quality":[40.1, 29.7, 20.01, 10, 0.0, -4.9]}) + >>> _get_sanger_quality_str(r6) + 'I?5+$"' + + Notice that due to the limited range of printable ASCII characters, a + PHRED quality of 93 is the maximum that can be held in an Illumina FASTQ + file (using ASCII 126, the tilde). This function will issue a warning + in this situation. + """ + # TODO - This functions works and is fast, but it is also ugly + # and there is considerable repetition of code for the other + # two FASTQ variants. + try: + # These take priority (in case both Solexa and PHRED scores found) + qualities = record.letter_annotations["phred_quality"] + except KeyError: + # Fall back on solexa scores... + pass + else: + # Try and use the precomputed mapping: + try: + return "".join(_phred_to_sanger_quality_str[qp] for qp in qualities) + except KeyError: + # Could be a float, or a None in the list, or a high value. + pass + if None in qualities: + raise TypeError("A quality value of None was found") + if max(qualities) >= 93.5: + warnings.warn( + "Data loss - max PHRED quality 93 in Sanger FASTQ", BiopythonWarning + ) + # This will apply the truncation at 93, giving max ASCII 126 + return "".join( + chr(min(126, int(round(qp)) + SANGER_SCORE_OFFSET)) for qp in qualities + ) + # Fall back on the Solexa scores... + try: + qualities = record.letter_annotations["solexa_quality"] + except KeyError: + raise ValueError( + "No suitable quality scores found in " + "letter_annotations of SeqRecord (id=%s)." % record.id + ) from None + # Try and use the precomputed mapping: + try: + return "".join(_solexa_to_sanger_quality_str[qs] for qs in qualities) + except KeyError: + # Either no PHRED scores, or something odd like a float or None + pass + if None in qualities: + raise TypeError("A quality value of None was found") + # Must do this the slow way, first converting the PHRED scores into + # Solexa scores: + if max(qualities) >= 93.5: + warnings.warn( + "Data loss - max PHRED quality 93 in Sanger FASTQ", BiopythonWarning + ) + # This will apply the truncation at 93, giving max ASCII 126 + return "".join( + chr(min(126, int(round(phred_quality_from_solexa(qs))) + SANGER_SCORE_OFFSET)) + for qs in qualities + ) + + +# Only map 0 to 62, we need to give a warning on truncating at 62 +assert 62 + SOLEXA_SCORE_OFFSET == 126 +_phred_to_illumina_quality_str = { + qp: chr(qp + SOLEXA_SCORE_OFFSET) for qp in range(62 + 1) +} +# Only map -5 to 62, we need to give a warning on truncating at 62 +_solexa_to_illumina_quality_str = { + qs: chr(int(round(phred_quality_from_solexa(qs))) + SOLEXA_SCORE_OFFSET) + for qs in range(-5, 62 + 1) +} + + +def _get_illumina_quality_str(record: SeqRecord) -> str: + """Return an Illumina 1.3 to 1.7 FASTQ encoded quality string (PRIVATE). + + Notice that due to the limited range of printable ASCII characters, a + PHRED quality of 62 is the maximum that can be held in an Illumina FASTQ + file (using ASCII 126, the tilde). This function will issue a warning + in this situation. + """ + # TODO - This functions works and is fast, but it is also ugly + # and there is considerable repetition of code for the other + # two FASTQ variants. + try: + # These take priority (in case both Solexa and PHRED scores found) + qualities = record.letter_annotations["phred_quality"] + except KeyError: + # Fall back on solexa scores... + pass + else: + # Try and use the precomputed mapping: + try: + return "".join(_phred_to_illumina_quality_str[qp] for qp in qualities) + except KeyError: + # Could be a float, or a None in the list, or a high value. + pass + if None in qualities: + raise TypeError("A quality value of None was found") + if max(qualities) >= 62.5: + warnings.warn( + "Data loss - max PHRED quality 62 in Illumina FASTQ", BiopythonWarning + ) + # This will apply the truncation at 62, giving max ASCII 126 + return "".join( + chr(min(126, int(round(qp)) + SOLEXA_SCORE_OFFSET)) for qp in qualities + ) + # Fall back on the Solexa scores... + try: + qualities = record.letter_annotations["solexa_quality"] + except KeyError: + raise ValueError( + "No suitable quality scores found in " + "letter_annotations of SeqRecord (id=%s)." % record.id + ) from None + # Try and use the precomputed mapping: + try: + return "".join(_solexa_to_illumina_quality_str[qs] for qs in qualities) + except KeyError: + # Either no PHRED scores, or something odd like a float or None + pass + if None in qualities: + raise TypeError("A quality value of None was found") + # Must do this the slow way, first converting the PHRED scores into + # Solexa scores: + if max(qualities) >= 62.5: + warnings.warn( + "Data loss - max PHRED quality 62 in Illumina FASTQ", BiopythonWarning + ) + # This will apply the truncation at 62, giving max ASCII 126 + return "".join( + chr(min(126, int(round(phred_quality_from_solexa(qs))) + SOLEXA_SCORE_OFFSET)) + for qs in qualities + ) + + +# Only map 0 to 62, we need to give a warning on truncating at 62 +assert 62 + SOLEXA_SCORE_OFFSET == 126 +_solexa_to_solexa_quality_str = { + qs: chr(min(126, qs + SOLEXA_SCORE_OFFSET)) for qs in range(-5, 62 + 1) +} +# Only map -5 to 62, we need to give a warning on truncating at 62 +_phred_to_solexa_quality_str = { + qp: chr(min(126, int(round(solexa_quality_from_phred(qp))) + SOLEXA_SCORE_OFFSET)) + for qp in range(62 + 1) +} + + +def _get_solexa_quality_str(record: SeqRecord) -> str: + """Return a Solexa FASTQ encoded quality string (PRIVATE). + + Notice that due to the limited range of printable ASCII characters, a + Solexa quality of 62 is the maximum that can be held in a Solexa FASTQ + file (using ASCII 126, the tilde). This function will issue a warning + in this situation. + """ + # TODO - This functions works and is fast, but it is also ugly + # and there is considerable repetition of code for the other + # two FASTQ variants. + try: + # These take priority (in case both Solexa and PHRED scores found) + qualities = record.letter_annotations["solexa_quality"] + except KeyError: + # Fall back on PHRED scores... + pass + else: + # Try and use the precomputed mapping: + try: + return "".join(_solexa_to_solexa_quality_str[qs] for qs in qualities) + except KeyError: + # Could be a float, or a None in the list, or a high value. + pass + if None in qualities: + raise TypeError("A quality value of None was found") + if max(qualities) >= 62.5: + warnings.warn( + "Data loss - max Solexa quality 62 in Solexa FASTQ", BiopythonWarning + ) + # This will apply the truncation at 62, giving max ASCII 126 + return "".join( + chr(min(126, int(round(qs)) + SOLEXA_SCORE_OFFSET)) for qs in qualities + ) + # Fall back on the PHRED scores... + try: + qualities = record.letter_annotations["phred_quality"] + except KeyError: + raise ValueError( + "No suitable quality scores found in " + "letter_annotations of SeqRecord (id=%s)." % record.id + ) from None + # Try and use the precomputed mapping: + try: + return "".join(_phred_to_solexa_quality_str[qp] for qp in qualities) + except KeyError: + # Either no PHRED scores, or something odd like a float or None + # or too big to be in the cache + pass + if None in qualities: + raise TypeError("A quality value of None was found") + # Must do this the slow way, first converting the PHRED scores into + # Solexa scores: + if max(qualities) >= 62.5: + warnings.warn( + "Data loss - max Solexa quality 62 in Solexa FASTQ", BiopythonWarning + ) + return "".join( + chr(min(126, int(round(solexa_quality_from_phred(qp))) + SOLEXA_SCORE_OFFSET)) + for qp in qualities + ) + + +# TODO - Default to nucleotide or even DNA? +def FastqGeneralIterator(source: _TextIOSource) -> Iterator[tuple[str, str, str]]: + """Iterate over Fastq records as string tuples (not as SeqRecord objects). + + Arguments: + - source - input stream opened in text mode, or a path to a file + + This code does not try to interpret the quality string numerically. It + just returns tuples of the title, sequence and quality as strings. For + the sequence and quality, any whitespace (such as new lines) is removed. + + Our SeqRecord based FASTQ iterators call this function internally, and then + turn the strings into a SeqRecord objects, mapping the quality string into + a list of numerical scores. If you want to do a custom quality mapping, + then you might consider calling this function directly. + + For parsing FASTQ files, the title string from the "@" line at the start + of each record can optionally be omitted on the "+" lines. If it is + repeated, it must be identical. + + The sequence string and the quality string can optionally be split over + multiple lines, although several sources discourage this. In comparison, + for the FASTA file format line breaks between 60 and 80 characters are + the norm. + + **WARNING** - Because the "@" character can appear in the quality string, + this can cause problems as this is also the marker for the start of + a new sequence. In fact, the "+" sign can also appear as well. Some + sources recommended having no line breaks in the quality to avoid this, + but even that is not enough, consider this example:: + + @071113_EAS56_0053:1:1:998:236 + TTTCTTGCCCCCATAGACTGAGACCTTCCCTAAATA + +071113_EAS56_0053:1:1:998:236 + IIIIIIIIIIIIIIIIIIIIIIIIIIIIICII+III + @071113_EAS56_0053:1:1:182:712 + ACCCAGCTAATTTTTGTATTTTTGTTAGAGACAGTG + + + @IIIIIIIIIIIIIIICDIIIII<%<6&-*).(*%+ + @071113_EAS56_0053:1:1:153:10 + TGTTCTGAAGGAAGGTGTGCGTGCGTGTGTGTGTGT + + + IIIIIIIIIIIICIIGIIIII>IAIIIE65I=II:6 + @071113_EAS56_0053:1:3:990:501 + TGGGAGGTTTTATGTGGA + AAGCAGCAATGTACAAGA + + + IIIIIII.IIIIII1@44 + @-7.%<&+/$/%4(++(% + + This is four PHRED encoded FASTQ entries originally from an NCBI source + (given the read length of 36, these are probably Solexa Illumina reads where + the quality has been mapped onto the PHRED values). + + This example has been edited to illustrate some of the nasty things allowed + in the FASTQ format. Firstly, on the "+" lines most but not all of the + (redundant) identifiers are omitted. In real files it is likely that all or + none of these extra identifiers will be present. + + Secondly, while the first three sequences have been shown without line + breaks, the last has been split over multiple lines. In real files any line + breaks are likely to be consistent. + + Thirdly, some of the quality string lines start with an "@" character. For + the second record this is unavoidable. However for the fourth sequence this + only happens because its quality string is split over two lines. A naive + parser could wrongly treat any line starting with an "@" as the beginning of + a new sequence! This code copes with this possible ambiguity by keeping + track of the length of the sequence which gives the expected length of the + quality string. + + Using this tricky example file as input, this short bit of code demonstrates + what this parsing function would return: + + >>> with open("Quality/tricky.fastq") as handle: + ... for (title, sequence, quality) in FastqGeneralIterator(handle): + ... print(title) + ... print("%s %s" % (sequence, quality)) + ... + 071113_EAS56_0053:1:1:998:236 + TTTCTTGCCCCCATAGACTGAGACCTTCCCTAAATA IIIIIIIIIIIIIIIIIIIIIIIIIIIIICII+III + 071113_EAS56_0053:1:1:182:712 + ACCCAGCTAATTTTTGTATTTTTGTTAGAGACAGTG @IIIIIIIIIIIIIIICDIIIII<%<6&-*).(*%+ + 071113_EAS56_0053:1:1:153:10 + TGTTCTGAAGGAAGGTGTGCGTGCGTGTGTGTGTGT IIIIIIIIIIIICIIGIIIII>IAIIIE65I=II:6 + 071113_EAS56_0053:1:3:990:501 + TGGGAGGTTTTATGTGGAAAGCAGCAATGTACAAGA IIIIIII.IIIIII1@44@-7.%<&+/$/%4(++(% + + Finally we note that some sources state that the quality string should + start with "!" (which using the PHRED mapping means the first letter always + has a quality score of zero). This rather restrictive rule is not widely + observed, so is therefore ignored here. One plus point about this "!" rule + is that (provided there are no line breaks in the quality sequence) it + would prevent the above problem with the "@" character. + """ + with as_handle(source) as handle: + if handle.read(0) != "": + raise StreamModeError("Fastq files must be opened in text mode") from None + + line = handle.readline() + if line == "": + return # Premature end of file, or just empty? + + while True: + if line[0] != "@": + raise ValueError( + "Records in Fastq files should start with '@' character" + ) + title_line = line[1:].rstrip() + seq_string = "" + # There will now be one or more sequence lines; keep going until we + # find the "+" marking the quality line: + for line in handle: + if line[0] == "+": + break + seq_string += line.rstrip() + else: + if seq_string: + raise ValueError("End of file without quality information.") + else: + raise ValueError("Unexpected end of file") + # The title here is optional, but if present must match! + second_title = line[1:].rstrip() + if second_title and second_title != title_line: + raise ValueError("Sequence and quality captions differ.") + # This is going to slow things down a little, but assuming + # this isn't allowed we should try and catch it here: + if " " in seq_string or "\t" in seq_string: + raise ValueError("Whitespace is not allowed in the sequence.") + seq_len = len(seq_string) + + # There will now be at least one line of quality data, followed by + # another sequence, or EOF + line = None + quality_string = "" + for line in handle: + if line[0] == "@": + # This COULD be the start of a new sequence. However, it MAY just + # be a line of quality data which starts with a "@" character. We + # should be able to check this by looking at the sequence length + # and the amount of quality data found so far. + if len(quality_string) >= seq_len: + # We expect it to be equal if this is the start of a new record. + # If the quality data is longer, we'll raise an error below. + break + # Continue - its just some (more) quality data. + quality_string += line.rstrip() + else: + if line is None: + raise ValueError("Unexpected end of file") + line = None + + if seq_len != len(quality_string): + raise ValueError( + "Lengths of sequence and quality values differs for %s (%i and %i)." + % (title_line, seq_len, len(quality_string)) + ) + + # Return the record and then continue... + yield (title_line, seq_string, quality_string) + + if line is None: + break + + +class FastqIteratorAbstractBaseClass(SequenceIterator[str]): + """Abstract base class for FASTQ file parsers.""" + + modes = "t" + + @property + @abstractmethod + def q_mapping(self): + """Dictionary that maps letters in the quality string to quality values.""" + pass + + @property + @abstractmethod + def q_key(self): + """Key name (string) of the quality values in record.letter_annotations.""" + pass + + def __init__(self, source): + """Iterate over FASTQ records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + + The quality values are stored in the `letter_annotations` dictionary + attribute under the key `q_key`. + """ + super().__init__(source, fmt="Fastq") + self.line = None + + def __next__(self) -> SeqRecord: + """Parse the file and generate SeqRecord objects.""" + + line = self.line + if line is None: + line = self.stream.readline() + if not line: + raise StopIteration + if line[0] != "@": + raise ValueError("Records in Fastq files should start with '@' character") + title_line = line[1:].rstrip() + seq_string = "" + # There will now be one or more sequence lines; keep going until we + # find the "+" marking the quality line: + for line in self.stream: + if line[0] == "+": + break + seq_string += line.rstrip() + else: + if seq_string: + raise ValueError("End of file without quality information.") + else: + raise ValueError("Unexpected end of file") + seq_len = len(seq_string) + # The title here is optional, but if present must match! + second_title = line[1:].rstrip() + if second_title and second_title != title_line: + raise ValueError("Sequence and quality captions differ.") + + # Note: str.isprintable is False for ASCII characters 0-32 and 127 + if not seq_string.isprintable() or " " in seq_string: # type: ignore + # first printable character + raise ValueError("Whitespace is not allowed in the sequence.") + + # There will now be at least one line of quality data, followed by + # another sequence, or EOF + line = None + quality_string = "" + for line in self.stream: + if line[0] == "@": + # This COULD be the start of a new sequence. However, it MAY just + # be a line of quality data which starts with a "@" character. We + # should be able to check this by looking at the sequence length + # and the amount of quality data found so far. + if len(quality_string) >= seq_len: + # We expect it to be equal if this is the start of a new record. + # If the quality data is longer, we'll raise an error below. + self.line = line + break + # Continue - its just some (more) quality data. + quality_string += line.rstrip() + else: + if line is None: + raise ValueError("Unexpected end of file") + self.line = None + + descr = title_line + id = descr.split()[0] + name = id + + if not quality_string.isascii(): + # Look for invalid non-ascii characters + index = _find_index_where(quality_string, lambda c: not c.isascii()) + assert index >= 0, "Non-ascii char in qualities not found. Biopython bug?" + + details = "is not an ASCII character" + raise InvalidCharError(quality_string, index, details) + + if len(quality_string) != seq_len: + # This should happen after ascii check, because non-ascii characters will often trigger this + raise ValueError( + f"Lengths of sequence and quality values differs for {title_line} ({seq_len} and {len(quality_string)})." + ) + + byte_scores = quality_string.encode().translate(self.q_mapping) + + if INVALID_CHAR in byte_scores: + # Look for invalid but still ascii characters + invalid_index = byte_scores.find(INVALID_CHAR_CODE) + + details = "not in correct range (are you sure you're using the right QualityIO parser?)" + raise InvalidCharError(quality_string, invalid_index, details) + + # Pass through (standard library) array to handle negative scores from old quality formats + qualities = array.array("b", byte_scores).tolist() + + # SeqRecord._from_validated avoids length/type checking + # .encode isn't strictly necessary (Seq init can handle a string), but it is faster to pre-encode + record = SeqRecord._from_validated( + Seq(seq_string.encode()), + id=id, + name=name, + description=descr, + letter_annotations={self.q_key: qualities}, + ) + return record + + +class FastqPhredIterator(FastqIteratorAbstractBaseClass): + """Parser for FASTQ files.""" + + assert SANGER_SCORE_OFFSET == ord("!") + # Originally, I used a list expression for each record: + # + # qualities = [ord(letter)-SANGER_SCORE_OFFSET for letter in quality_string] + # + # Precomputing is faster, perhaps partly by avoiding the subtractions. + q_mapping = bytes( + ( + letter - SANGER_SCORE_OFFSET + if SANGER_SCORE_OFFSET <= letter < 94 + SANGER_SCORE_OFFSET + else INVALID_CHAR_CODE + ) + for letter in range(256) + ) + + q_key = "phred_quality" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ): + """Iterate over FASTQ records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + - alphabet - optional alphabet, no longer used. Leave as None. + + For each sequence in a (Sanger style) FASTQ file there is a matching string + encoding the PHRED qualities (integers between 0 and about 90) using ASCII + values with an offset of 33. + + For example, consider a file containing three short reads:: + + @EAS54_6_R1_2_1_413_324 + CCCTTCTTGTCTTCAGCGTTTCTCC + + + ;;3;;;;;;;;;;;;7;;;;;;;88 + @EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + + + ;;;;;;;;;;;7;;;;;-;;;3;83 + @EAS54_6_R1_2_1_443_348 + GTTGCTTCTGGCGTGGGTGGGGGGG + + + ;;;;;;;;;;;9;7;;.7;393333 + + For each sequence (e.g. "CCCTTCTTGTCTTCAGCGTTTCTCC") there is a matching + string encoding the PHRED qualities using a ASCII values with an offset of + 33 (e.g. ";;3;;;;;;;;;;;;7;;;;;;;88"). + + Using this module directly you might run: + + >>> with open("Quality/example.fastq") as handle: + ... for record in FastqPhredIterator(handle): + ... print("%s %s" % (record.id, record.seq)) + EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC + EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA + EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + + Typically however, you would call this via Bio.SeqIO instead with "fastq" + (or "fastq-sanger") as the format: + + >>> from Bio import SeqIO + >>> with open("Quality/example.fastq") as handle: + ... for record in SeqIO.parse(handle, "fastq"): + ... print("%s %s" % (record.id, record.seq)) + EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC + EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA + EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + + If you want to look at the qualities, they are record in each record's + per-letter-annotation dictionary as a simple list of integers: + + >>> print(record.letter_annotations["phred_quality"]) + [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] + + To modify the records returned by the parser, you can use a generator + function. For example, to store the mean PHRED quality in the record + description, use + + >>> from statistics import mean + >>> def modify_records(records): + ... for record in records: + ... record.description = mean(record.letter_annotations['phred_quality']) + ... yield record + ... + >>> with open('Quality/example.fastq') as handle: + ... for record in modify_records(FastqPhredIterator(handle)): + ... print(record.id, record.description) + ... + EAS54_6_R1_2_1_413_324 25.28 + EAS54_6_R1_2_1_540_792 24.52 + EAS54_6_R1_2_1_443_348 23.4 + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source) + + +class FastqSolexaIterator(FastqIteratorAbstractBaseClass): + """Parser for old Solexa/Illumina FASTQ like files. + + These files differ in the quality mapping. + """ + + # For negative numbers, will need to interpret as a signed integer byte + q_mapping = bytes( + ( + (letter - SOLEXA_SCORE_OFFSET) % 256 + if SOLEXA_SCORE_OFFSET - 5 <= letter < 63 + SOLEXA_SCORE_OFFSET + else INVALID_CHAR_CODE + ) + for letter in range(256) + ) + + q_key = "solexa_quality" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ): + r"""Iterate over FASTQ records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + - alphabet - optional alphabet, no longer used. Leave as None. + + For each sequence in Solexa/Illumina FASTQ files there is a matching + string encoding the Solexa integer qualities using ASCII values with an + offset of 64. Solexa scores are scaled differently to PHRED scores, + and Biopython will NOT perform any automatic conversion when loading. + + NOTE - This file format is used by the OLD versions of the Solexa/ + Illumina pipeline. See also the FastqIlluminaIterator function for the + NEW version. + + For example, consider a file containing these five records:: + + @SLXA-B3_649_FC8437_R1_1_1_610_79 + GATGTGCAATACCTTTGTAGAGGAA + +SLXA-B3_649_FC8437_R1_1_1_610_79 + YYYYYYYYYYYYYYYYYYWYWYYSU + @SLXA-B3_649_FC8437_R1_1_1_397_389 + GGTTTGAGAAAGAGAAATGAGATAA + +SLXA-B3_649_FC8437_R1_1_1_397_389 + YYYYYYYYYWYYYYWWYYYWYWYWW + @SLXA-B3_649_FC8437_R1_1_1_850_123 + GAGGGTGTTGATCATGATGATGGCG + +SLXA-B3_649_FC8437_R1_1_1_850_123 + YYYYYYYYYYYYYWYYWYYSYYYSY + @SLXA-B3_649_FC8437_R1_1_1_362_549 + GGAAACAAAGTTTTTCTCAACATAG + +SLXA-B3_649_FC8437_R1_1_1_362_549 + YYYYYYYYYYYYYYYYYYWWWWYWY + @SLXA-B3_649_FC8437_R1_1_1_183_714 + GTATTATTTAATGGCATACACTCAA + +SLXA-B3_649_FC8437_R1_1_1_183_714 + YYYYYYYYYYWYYYYWYWWUWWWQQ + + Using this module directly you might run: + + >>> with open("Quality/solexa_example.fastq") as handle: + ... for record in FastqSolexaIterator(handle): + ... print("%s %s" % (record.id, record.seq)) + SLXA-B3_649_FC8437_R1_1_1_610_79 GATGTGCAATACCTTTGTAGAGGAA + SLXA-B3_649_FC8437_R1_1_1_397_389 GGTTTGAGAAAGAGAAATGAGATAA + SLXA-B3_649_FC8437_R1_1_1_850_123 GAGGGTGTTGATCATGATGATGGCG + SLXA-B3_649_FC8437_R1_1_1_362_549 GGAAACAAAGTTTTTCTCAACATAG + SLXA-B3_649_FC8437_R1_1_1_183_714 GTATTATTTAATGGCATACACTCAA + + Typically however, you would call this via Bio.SeqIO instead with + "fastq-solexa" as the format: + + >>> from Bio import SeqIO + >>> with open("Quality/solexa_example.fastq") as handle: + ... for record in SeqIO.parse(handle, "fastq-solexa"): + ... print("%s %s" % (record.id, record.seq)) + SLXA-B3_649_FC8437_R1_1_1_610_79 GATGTGCAATACCTTTGTAGAGGAA + SLXA-B3_649_FC8437_R1_1_1_397_389 GGTTTGAGAAAGAGAAATGAGATAA + SLXA-B3_649_FC8437_R1_1_1_850_123 GAGGGTGTTGATCATGATGATGGCG + SLXA-B3_649_FC8437_R1_1_1_362_549 GGAAACAAAGTTTTTCTCAACATAG + SLXA-B3_649_FC8437_R1_1_1_183_714 GTATTATTTAATGGCATACACTCAA + + The qualities are recorded in each record's per-letter-annotation + dictionary as a simple list of integers: + + >>> print(record.letter_annotations["solexa_quality"]) + [25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 25, 25, 25, 23, 25, 23, 23, 21, 23, 23, 23, 17, 17] + + These scores aren't very good, but they are high enough that they map + almost exactly onto PHRED scores: + + >>> print("%0.2f" % phred_quality_from_solexa(25)) + 25.01 + + Let's look at faked example read which is even worse, where there are + more noticeable differences between the Solexa and PHRED scores:: + + @slxa_0001_1_0001_01 + ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + +slxa_0001_1_0001_01 + hgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<; + + Again, you would typically use Bio.SeqIO to read this file in (rather + than calling the Bio.SeqIO.QualtityIO module directly). Most FASTQ + files will contain thousands of reads, so you would normally use + Bio.SeqIO.parse() as shown above. This example has only as one entry, + so instead we can use the Bio.SeqIO.read() function: + + >>> from Bio import SeqIO + >>> with open("Quality/solexa_faked.fastq") as handle: + ... record = SeqIO.read(handle, "fastq-solexa") + >>> print("%s %s" % (record.id, record.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(record.letter_annotations["solexa_quality"]) + [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] + + These quality scores are so low that when converted from the Solexa + scheme into PHRED scores they look quite different: + + >>> print("%0.2f" % phred_quality_from_solexa(-1)) + 2.54 + >>> print("%0.2f" % phred_quality_from_solexa(-5)) + 1.19 + + Note you can use the Bio.SeqIO.write() function or the SeqRecord's + format method to output the record(s): + + >>> print(record.format("fastq-solexa")) + @slxa_0001_1_0001_01 + ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + + + hgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<; + + + Note this output is slightly different from the input file as Biopython + has left out the optional repetition of the sequence identifier on the + "+" line. If you want the to use PHRED scores, use "fastq" or "qual" + as the output format instead, and Biopython will do the conversion for + you: + + >>> print(record.format("fastq")) + @slxa_0001_1_0001_01 + ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + + + IHGFEDCBA@?>=<;:9876543210/.-,++*)('&&%%$$##"" + + + >>> print(record.format("qual")) + >slxa_0001_1_0001_01 + 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 + 20 19 18 17 16 15 14 13 12 11 10 10 9 8 7 6 5 5 4 4 3 3 2 2 + 1 1 + + + As shown above, the poor quality Solexa reads have been mapped to the + equivalent PHRED score (e.g. -5 to 1 as shown earlier). + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source) + + +class FastqIlluminaIterator(FastqIteratorAbstractBaseClass): + """Parser for Illumina 1.3 to 1.7 FASTQ like files. + + These files differ in the quality mapping. + """ + + q_mapping = bytes( + ( + letter - SOLEXA_SCORE_OFFSET + if SOLEXA_SCORE_OFFSET <= letter < 63 + SOLEXA_SCORE_OFFSET + else INVALID_CHAR_CODE + ) + for letter in range(256) + ) + + q_key = "phred_quality" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ): + """Iterate over FASTQ records as SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + - alphabet - optional alphabet, no longer used. Leave as None. + + For each sequence in Illumina 1.3+ FASTQ files there is a matching + string encoding PHRED integer qualities using ASCII values with an + offset of 64. + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Quality/illumina_faked.fastq", "fastq-illumina") + >>> print("%s %s" % (record.id, record.seq)) + Test ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTN + >>> max(record.letter_annotations["phred_quality"]) + 40 + >>> min(record.letter_annotations["phred_quality"]) + 0 + + NOTE - Older versions of the Solexa/Illumina pipeline encoded Solexa + scores with an ASCII offset of 64. They are approximately equal but + only for high quality reads. If you have an old Solexa/Illumina file + with negative Solexa scores, and try and read this as an Illumina 1.3+ + file it will fail: + + >>> record2 = SeqIO.read("Quality/solexa_faked.fastq", "fastq-illumina") + Traceback (most recent call last): + ... + Bio.SeqIO.QualityIO.InvalidCharError: Invalid character (?) or (0x3f) in quality string not in correct range (are you sure you're using the right QualityIO parser?) with context: [...BA@?>=<...] + + NOTE - True Sanger style FASTQ files use PHRED scores with an offset + of 33. + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source) + + +class QualPhredIterator(SequenceIterator): + """Parser for QUAL files with PHRED quality scores but no sequence.""" + + modes = "t" + + def __init__( + self, + source: _TextIOSource, + alphabet: None = None, + ) -> None: + """For QUAL files which include PHRED quality scores, but no sequence. + + For example, consider this short QUAL file:: + + >EAS54_6_R1_2_1_413_324 + 26 26 18 26 26 26 26 26 26 26 26 26 26 26 26 22 26 26 26 26 + 26 26 26 23 23 + >EAS54_6_R1_2_1_540_792 + 26 26 26 26 26 26 26 26 26 26 26 22 26 26 26 26 26 12 26 26 + 26 18 26 23 18 + >EAS54_6_R1_2_1_443_348 + 26 26 26 26 26 26 26 26 26 26 26 24 26 22 26 26 13 22 26 18 + 24 18 18 18 18 + + Using this module directly you might run: + + >>> with open("Quality/example.qual") as handle: + ... for record in QualPhredIterator(handle): + ... print("%s read of length %d" % (record.id, len(record.seq))) + EAS54_6_R1_2_1_413_324 read of length 25 + EAS54_6_R1_2_1_540_792 read of length 25 + EAS54_6_R1_2_1_443_348 read of length 25 + + Typically however, you would call this via Bio.SeqIO instead with "qual" + as the format: + + >>> from Bio import SeqIO + >>> with open("Quality/example.qual") as handle: + ... for record in SeqIO.parse(handle, "qual"): + ... print("%s read of length %d" % (record.id, len(record.seq))) + EAS54_6_R1_2_1_413_324 read of length 25 + EAS54_6_R1_2_1_540_792 read of length 25 + EAS54_6_R1_2_1_443_348 read of length 25 + + Only the sequence length is known, as the QUAL file does not contain + the sequence string itself. + + The quality scores themselves are available as a list of integers + in each record's per-letter-annotation: + + >>> print(record.letter_annotations["phred_quality"]) + [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] + + You can still slice one of these SeqRecord objects: + + >>> sub_record = record[5:10] + >>> print("%s %s" % (sub_record.id, sub_record.letter_annotations["phred_quality"])) + EAS54_6_R1_2_1_443_348 [26, 26, 26, 26, 26] + + As of Biopython 1.59, this parser will accept files with negatives quality + scores but will replace them with the lowest possible PHRED score of zero. + This will trigger a warning, previously it raised a ValueError exception. + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source, fmt="QUAL") + # Skip any text before the first record (e.g. blank lines, comments) + for line in self.stream: + if line[0] == ">": + break + else: + line = None + self._line = line + + def __next__(self) -> SeqRecord: + """Parse the file and generate SeqRecord objects.""" + + line = self._line + if line is None: + raise StopIteration + while True: + descr = line[1:].rstrip() + id = descr.split()[0] + name = id + + qualities: list[int] = [] + for line in self.stream: + if line[0] == ">": + break + qualities.extend(int(word) for word in line.split()) + else: + line = None + self._line = line + + if qualities and min(qualities) < 0: + warnings.warn( + "Negative quality score %i found, substituting PHRED zero instead." + % min(qualities), + BiopythonParserWarning, + ) + qualities = [max(0, q) for q in qualities] + + # Return the record and then continue... + sequence = Seq(None, length=len(qualities)) + + # Avoid unnecessary length/type checks + record = SeqRecord._from_validated( + sequence, + id=id, + name=name, + description=descr, + letter_annotations={"phred_quality": qualities}, + ) + return record + + +assert SANGER_SCORE_OFFSET == ord("!") + + +class FastqPhredWriter(SequenceWriter): + """Class to write standard FASTQ format files (using PHRED quality scores). + + Although you can use this class directly, you are strongly encouraged + to use the top level ``Bio.SeqIO.write()`` function instead via the format + name "fastq" or the alias "fastq-sanger". + + For example, this code reads in a standard Sanger style FASTQ file + (using PHRED scores) and re-saves it as another Sanger style FASTQ file: + + >>> from Bio import SeqIO + >>> record_iterator = SeqIO.parse("Quality/example.fastq", "fastq") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "fastq") + 3 + + You might want to do this if the original file included extra line breaks, + which while valid may not be supported by all tools. The output file from + Biopython will have each sequence on a single line, and each quality + string on a single line (which is considered desirable for maximum + compatibility). + + In this next example, an old style Solexa/Illumina FASTQ file (using Solexa + quality scores) is converted into a standard Sanger style FASTQ file using + PHRED qualities: + + >>> from Bio import SeqIO + >>> record_iterator = SeqIO.parse("Quality/solexa_example.fastq", "fastq-solexa") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "fastq") + 5 + + This code is also called if you use the .format("fastq") method of a + SeqRecord, or .format("fastq-sanger") if you prefer that alias. + + Note that Sanger FASTQ files have an upper limit of PHRED quality 93, which is + encoded as ASCII 126, the tilde. If your quality scores are truncated to fit, a + warning is issued. + + P.S. To avoid cluttering up your working directory, you can delete this + temporary file now: + + >>> import os + >>> os.remove("Quality/temp.fastq") + """ + + modes = "t" + + @classmethod + def to_string(cls, record): + """Turn a SeqRecord into a Sanger FASTQ formatted string, and return it.""" + # TODO - Is an empty sequence allowed in FASTQ format? + seq_str = _get_seq_string(record) + qualities_str = _get_sanger_quality_str(record) + if len(qualities_str) != len(seq_str): + raise ValueError( + "Record %s has sequence length %i but %i quality scores" + % (record.id, len(seq_str), len(qualities_str)) + ) + id_ = _clean(record.id) if record.id else "" + description = _clean(record.description) + if description and description.split(None, 1)[0] == id_: + title = description + elif description: + title = f"{id_} {description}" + else: + title = id_ + return f"@{title}\n{seq_str}\n+\n{qualities_str}\n" + + def write_record(self, record: SeqRecord) -> None: + """Write a single FASTQ record to the file.""" + self.handle.write(self.to_string(record)) + + +def as_fastq(record: SeqRecord) -> str: + """Turn a SeqRecord into a Sanger FASTQ formatted string, and return it.""" + warnings.warn( + """\ +QualityIO.as_fastq is deprecated. + +Instead of + +QualityIO.as_fastq(record) + +please use + +format(record, "fastq") +""", + DeprecationWarning, + ) + return FastqPhredWriter.to_string(record) + + +class QualPhredWriter(SequenceWriter): + """Class to write QUAL format files (using PHRED quality scores). + + Although you can use this class directly, you are strongly encouraged + to use the top level ``Bio.SeqIO.write()`` function instead. + + For example, this code reads in a FASTQ file and saves the quality scores + into a QUAL file: + + >>> from Bio import SeqIO + >>> record_iterator = SeqIO.parse("Quality/example.fastq", "fastq") + >>> with open("Quality/temp.qual", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "qual") + 3 + + This code is also called if you use the .format("qual") method of a + SeqRecord. + + P.S. Don't forget to clean up the temp file if you don't need it anymore: + + >>> import os + >>> os.remove("Quality/temp.qual") + """ + + modes = "t" + + def __init__( + self, + handle: _TextIOSource, + wrap: int = 60, + record2title: Callable[[SeqRecord], str] | None = None, + ) -> None: + """Create a QUAL writer. + + Arguments: + - handle - Handle to an output file, e.g. as returned + by open(filename, "w") + - wrap - Optional line length used to wrap sequence lines. + Defaults to wrapping the sequence at 60 characters. Use + zero (or None) for no wrapping, giving a single long line + for the sequence. + - record2title - Optional function to return the text to be + used for the title line of each record. By default a + combination of the record.id and record.description is + used. If the record.description starts with the record.id, + then just the record.description is used. + + The record2title argument is present for consistency with the + Bio.SeqIO.FastaIO writer class. + """ + super().__init__(handle) + # self.handle = handle + self.wrap: int | None = None + if wrap: + if wrap < 1: + raise ValueError + self.wrap = wrap + self.record2title = record2title + + @classmethod + def to_string(cls, record: SeqRecord) -> str: + """Turn a SeqRecord into a QUAL formatted string.""" + id_ = _clean(record.id) if record.id else "" + description = _clean(record.description) + if description and description.split(None, 1)[0] == id_: + title = description + elif description: + title = f"{id_} {description}" + else: + title = id_ + lines = [f">{title}\n"] + + qualities = _get_phred_quality(record) + try: + # This rounds to the nearest integer. + # TODO - can we record a float in a qual file? + qualities_strs = [("%i" % round(q, 0)) for q in qualities] + except TypeError: + if None in qualities: + raise TypeError("A quality value of None was found") from None + else: + raise + + # Safe wrapping + while qualities_strs: + line = qualities_strs.pop(0) + while qualities_strs and len(line) + 1 + len(qualities_strs[0]) < 60: + line += " " + qualities_strs.pop(0) + lines.append(line + "\n") + return "".join(lines) + + def write_record(self, record: SeqRecord) -> None: + """Write a single QUAL record to the file.""" + handle = self.handle + wrap = self.wrap + + if self.record2title: + title = self.clean(self.record2title(record)) + else: + id_ = self.clean(record.id) if record.id else "" + description = self.clean(record.description) + if description and description.split(None, 1)[0] == id_: + # The description includes the id at the start + title = description + elif description: + title = f"{id_} {description}" + else: + title = id_ + handle.write(f">{title}\n") + + qualities = _get_phred_quality(record) + try: + # This rounds to the nearest integer. + # TODO - can we record a float in a qual file? + qualities_strs = [("%i" % round(q, 0)) for q in qualities] + except TypeError: + if None in qualities: + raise TypeError("A quality value of None was found") from None + else: + raise + + if wrap is not None and wrap > 5: + # Fast wrapping + data = " ".join(qualities_strs) + while True: + if len(data) <= wrap: + self.handle.write(data + "\n") + break + else: + # By construction there must be spaces in the first X chars + # (unless we have X digit or higher quality scores!) + i = data.rfind(" ", 0, wrap) + handle.write(data[:i] + "\n") + data = data[i + 1 :] + elif wrap: + # Safe wrapping + while qualities_strs: + line = qualities_strs.pop(0) + while qualities_strs and len(line) + 1 + len(qualities_strs[0]) < wrap: + line += " " + qualities_strs.pop(0) + handle.write(line + "\n") + else: + # No wrapping + data = " ".join(qualities_strs) + handle.write(data + "\n") + + +def as_qual(record: SeqRecord) -> str: + """Turn a SeqRecord into a QUAL formatted string.""" + warnings.warn( + """\ +QualityIO.as_qual is deprecated. + +Instead of + +QualityIO.as_qual(record) + +please use + +format(record, "qual") +""", + DeprecationWarning, + ) + return QualPhredWriter.to_string(record) + + +class FastqSolexaWriter(SequenceWriter): + r"""Write old style Solexa/Illumina FASTQ format files (with Solexa qualities). + + This outputs FASTQ files like those from the early Solexa/Illumina + pipeline, using Solexa scores and an ASCII offset of 64. These are + NOT compatible with the standard Sanger style PHRED FASTQ files. + + If your records contain a "solexa_quality" entry under letter_annotations, + this is used, otherwise any "phred_quality" entry will be used after + conversion using the solexa_quality_from_phred function. If neither style + of quality scores are present, an exception is raised. + + Although you can use this class directly, you are strongly encouraged + to use the ``as_fastq_solexa`` function, or top-level ``Bio.SeqIO.write()`` + function instead. For example, this code reads in a FASTQ file and re-saves + it as another FASTQ file: + + >>> from Bio import SeqIO + >>> record_iterator = SeqIO.parse("Quality/solexa_example.fastq", "fastq-solexa") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "fastq-solexa") + 5 + + You might want to do this if the original file included extra line breaks, + which (while valid) may not be supported by all tools. The output file + from Biopython will have each sequence on a single line, and each quality + string on a single line (which is considered desirable for maximum + compatibility). + + This code is also called if you use the .format("fastq-solexa") method of + a SeqRecord. For example, + + >>> record = SeqIO.read("Quality/sanger_faked.fastq", "fastq-sanger") + >>> print(record.format("fastq-solexa")) + @Test PHRED qualities from 40 to 0 inclusive + ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTN + + + hgfedcba`_^]\[ZYXWVUTSRQPONMLKJHGFECB@>;; + + + Note that Solexa FASTQ files have an upper limit of Solexa quality 62, which is + encoded as ASCII 126, the tilde. If your quality scores must be truncated to fit, + a warning is issued. + + P.S. Don't forget to delete the temp file if you don't need it anymore: + + >>> import os + >>> os.remove("Quality/temp.fastq") + """ + + modes = "t" + + @classmethod + def to_string(cls, record: SeqRecord) -> str: + """Turn a SeqRecord into a Solexa FASTQ formatted string. + + This is used internally by the SeqRecord's .format("fastq-solexa") + method and by the SeqIO.write(..., ..., "fastq-solexa") function. + """ + # TODO - Is an empty sequence allowed in FASTQ format? + seq_str = _get_seq_string(record) + qualities_str = _get_solexa_quality_str(record) + if len(qualities_str) != len(seq_str): + raise ValueError( + "Record %s has sequence length %i but %i quality scores" + % (record.id, len(seq_str), len(qualities_str)) + ) + id_ = _clean(record.id) if record.id else "" + description = _clean(record.description) + if description and description.split(None, 1)[0] == id_: + # The description includes the id at the start + title = description + elif description: + title = f"{id_} {description}" + else: + title = id_ + return f"@{title}\n{seq_str}\n+\n{qualities_str}\n" + + def write_record(self, record: SeqRecord) -> None: + """Write a single FASTQ record to the file.""" + self.handle.write(self.to_string(record)) + + +def as_fastq_solexa(record: SeqRecord) -> str: + """Turn a SeqRecord into a Solexa FASTQ formatted string.""" + warnings.warn( + """\ +QualityIO.as_fastq_solexa is deprecated. + +Instead of + +QualityIO.as_fastq_solexa(record) + +please use + +format(record, "fastq-solexa") +""", + DeprecationWarning, + ) + return FastqSolexaWriter.to_string(record) + + +class FastqIlluminaWriter(SequenceWriter): + r"""Write Illumina 1.3+ FASTQ format files (with PHRED quality scores). + + This outputs FASTQ files like those from the Solexa/Illumina 1.3+ pipeline, + using PHRED scores and an ASCII offset of 64. Note these files are NOT + compatible with the standard Sanger style PHRED FASTQ files which use an + ASCII offset of 32. + + Although you can use this class directly, you are strongly encouraged to + use the ``as_fastq_illumina`` or top-level ``Bio.SeqIO.write()`` function + with format name "fastq-illumina" instead. This code is also called if you + use the .format("fastq-illumina") method of a SeqRecord. For example, + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Quality/sanger_faked.fastq", "fastq-sanger") + >>> print(record.format("fastq-illumina")) + @Test PHRED qualities from 40 to 0 inclusive + ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTN + + + hgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@ + + + Note that Illumina FASTQ files have an upper limit of PHRED quality 62, which is + encoded as ASCII 126, the tilde. If your quality scores are truncated to fit, a + warning is issued. + """ + + modes = "t" + + @classmethod + def to_string(cls, record: SeqRecord) -> str: + """Turn a SeqRecord into an Illumina FASTQ formatted string. + + This is used internally by the SeqRecord's .format("fastq-illumina") + method and by the SeqIO.write(..., ..., "fastq-illumina") function. + """ + # TODO - Is an empty sequence allowed in FASTQ format? + seq_str = _get_seq_string(record) + qualities_str = _get_illumina_quality_str(record) + if len(qualities_str) != len(seq_str): + raise ValueError( + "Record %s has sequence length %i but %i quality scores" + % (record.id, len(seq_str), len(qualities_str)) + ) + id_ = _clean(record.id) if record.id else "" + description = _clean(record.description) + if description and description.split(None, 1)[0] == id_: + title = description + elif description: + title = f"{id_} {description}" + else: + title = id_ + return f"@{title}\n{seq_str}\n+\n{qualities_str}\n" + + def write_record(self, record: SeqRecord) -> None: + """Write a single FASTQ record to the file.""" + self.handle.write(self.to_string(record)) + + +def as_fastq_illumina(record: SeqRecord) -> str: + """Turn a SeqRecord into an Illumina FASTQ formatted string.""" + warnings.warn( + """\ +QualityIO.as_fastq_illumina is deprecated. + +Instead of + +QualityIO.as_fastq_illumina(record) + +please use + +format(record, "fastq-illumina") +""", + DeprecationWarning, + ) + return FastqIlluminaWriter.to_string(record) + + +def PairedFastaQualIterator( + fasta_source: _TextIOSource, + qual_source: _TextIOSource, + alphabet: None = None, +) -> Iterator[SeqRecord]: + """Iterate over matched FASTA and QUAL files as SeqRecord objects. + + For example, consider this short QUAL file with PHRED quality scores:: + + >EAS54_6_R1_2_1_413_324 + 26 26 18 26 26 26 26 26 26 26 26 26 26 26 26 22 26 26 26 26 + 26 26 26 23 23 + >EAS54_6_R1_2_1_540_792 + 26 26 26 26 26 26 26 26 26 26 26 22 26 26 26 26 26 12 26 26 + 26 18 26 23 18 + >EAS54_6_R1_2_1_443_348 + 26 26 26 26 26 26 26 26 26 26 26 24 26 22 26 26 13 22 26 18 + 24 18 18 18 18 + + And a matching FASTA file:: + + >EAS54_6_R1_2_1_413_324 + CCCTTCTTGTCTTCAGCGTTTCTCC + >EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + >EAS54_6_R1_2_1_443_348 + GTTGCTTCTGGCGTGGGTGGGGGGG + + You can parse these separately using Bio.SeqIO with the "qual" and + "fasta" formats, but then you'll get a group of SeqRecord objects with + no sequence, and a matching group with the sequence but not the + qualities. Because it only deals with one input file handle, Bio.SeqIO + can't be used to read the two files together - but this function can! + For example, + + >>> with open("Quality/example.fasta") as f: + ... with open("Quality/example.qual") as q: + ... for record in PairedFastaQualIterator(f, q): + ... print("%s %s" % (record.id, record.seq)) + ... + EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC + EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA + EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + + As with the FASTQ or QUAL parsers, if you want to look at the qualities, + they are in each record's per-letter-annotation dictionary as a simple + list of integers: + + >>> print(record.letter_annotations["phred_quality"]) + [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] + + If you have access to data as a FASTQ format file, using that directly + would be simpler and more straight forward. Note that you can easily use + this function to convert paired FASTA and QUAL files into FASTQ files: + + >>> from Bio import SeqIO + >>> with open("Quality/example.fasta") as f: + ... with open("Quality/example.qual") as q: + ... SeqIO.write(PairedFastaQualIterator(f, q), "Quality/temp.fastq", "fastq") + ... + 3 + + And don't forget to clean up the temp file if you don't need it anymore: + + >>> import os + >>> os.remove("Quality/temp.fastq") + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + + from Bio.SeqIO.FastaIO import FastaIterator + + fasta_iter = FastaIterator(fasta_source) + qual_iter = QualPhredIterator(qual_source) + + # Using zip wouldn't load everything into memory, but also would not catch + # any extra records found in only one file. + while True: + try: + f_rec = next(fasta_iter) + except StopIteration: + f_rec = None + try: + q_rec = next(qual_iter) + except StopIteration: + q_rec = None + if f_rec is None and q_rec is None: + # End of both files + break + if f_rec is None: + raise ValueError("FASTA file has more entries than the QUAL file.") + if q_rec is None: + raise ValueError("QUAL file has more entries than the FASTA file.") + if f_rec.id != q_rec.id: + raise ValueError( + f"FASTA and QUAL entries do not match ({f_rec.id} vs {q_rec.id})." + ) + if len(f_rec) != len(q_rec.letter_annotations["phred_quality"]): + raise ValueError( + f"Sequence length and number of quality scores disagree for {f_rec.id}" + ) + # Merge the data.... + f_rec.letter_annotations["phred_quality"] = q_rec.letter_annotations[ + "phred_quality" + ] + yield f_rec + # Done + + +def _fastq_generic( + in_file: _TextIOSource, + out_file: _TextIOSource, + mapping: Sequence[str] | Mapping[int, str | int | None], +) -> int: + """FASTQ helper function where can't have data loss by truncation (PRIVATE).""" + # For real speed, don't even make SeqRecord and Seq objects! + count = 0 + null = chr(0) + with as_handle(out_file, "w") as out_handle: + for title, seq, old_qual in FastqGeneralIterator(in_file): + count += 1 + # map the qual... + qual = old_qual.translate(mapping) + if null in qual: + invalid_index = qual.find(null) + raise InvalidCharError( + old_qual, + invalid_index, + details="not in correct range (are you sure you're using the right QualityIO parser?)", + ) + + out_handle.write(f"@{title}\n{seq}\n+\n{qual}\n") + return count + + +def _fastq_generic2( + in_file: _TextIOSource, + out_file: _TextIOSource, + mapping: Sequence[str] | Mapping[int, str | int | None], + truncate_char: str, + truncate_msg: str, +) -> int: + """FASTQ helper function where there could be data loss by truncation (PRIVATE).""" + # For real speed, don't even make SeqRecord and Seq objects! + count = 0 + null = chr(0) + with as_handle(out_file, "w") as out_handle: + for title, seq, old_qual in FastqGeneralIterator(in_file): + count += 1 + # map the qual... + qual = old_qual.translate(mapping) + if null in qual: + invalid_index = qual.find(null) + raise InvalidCharError( + old_qual, + invalid_index, + details="not in correct range (are you sure you're using the right QualityIO parser?)", + ) + if truncate_char in qual: + qual = qual.replace(truncate_char, chr(126)) + warnings.warn(truncate_msg, BiopythonWarning) + out_handle.write(f"@{title}\n{seq}\n+\n{qual}\n") + return count + + +def _fastq_sanger_convert_fastq_sanger( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Sanger FASTQ to Sanger FASTQ conversion (PRIVATE). + + Useful for removing line wrapping and the redundant second identifier + on the plus lines. Will check also check the quality string is valid. + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(33)] + + [chr(ascii) for ascii in range(33, 127)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_solexa_convert_fastq_solexa( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Solexa FASTQ to Solexa FASTQ conversion (PRIVATE). + + Useful for removing line wrapping and the redundant second identifier + on the plus lines. Will check also check the quality string is valid. + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(59)] + + [chr(ascii) for ascii in range(59, 127)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_illumina_convert_fastq_illumina( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Illumina 1.3+ FASTQ to Illumina 1.3+ FASTQ conversion (PRIVATE). + + Useful for removing line wrapping and the redundant second identifier + on the plus lines. Will check also check the quality string is valid. + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(64)] + + [chr(ascii) for ascii in range(64, 127)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_illumina_convert_fastq_sanger( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Illumina 1.3+ FASTQ to Sanger FASTQ conversion (PRIVATE). + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(64)] + + [chr(33 + q) for q in range(62 + 1)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_sanger_convert_fastq_illumina( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Sanger FASTQ to Illumina 1.3+ FASTQ conversion (PRIVATE). + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. Will issue a warning if the scores had to be truncated at 62 + (maximum possible in the Illumina 1.3+ FASTQ format) + """ + # Map unexpected chars to null + trunc_char = chr(1) + mapping = "".join( + [chr(0) for ascii in range(33)] + + [chr(64 + q) for q in range(62 + 1)] + + [trunc_char for ascii in range(96, 127)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic2( + in_file, + out_file, + mapping, + trunc_char, + "Data loss - max PHRED quality 62 in Illumina 1.3+ FASTQ", + ) + + +def _fastq_solexa_convert_fastq_sanger( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Solexa FASTQ to Sanger FASTQ conversion (PRIVATE). + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(59)] + + [ + chr(33 + int(round(phred_quality_from_solexa(q)))) + for q in range(-5, 62 + 1) + ] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_sanger_convert_fastq_solexa( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Sanger FASTQ to Solexa FASTQ conversion (PRIVATE). + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. Will issue a warning if the scores had to be truncated at 62 + (maximum possible in the Solexa FASTQ format) + """ + # Map unexpected chars to null + trunc_char = chr(1) + mapping = "".join( + [chr(0) for ascii in range(33)] + + [chr(64 + int(round(solexa_quality_from_phred(q)))) for q in range(62 + 1)] + + [trunc_char for ascii in range(96, 127)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic2( + in_file, + out_file, + mapping, + trunc_char, + "Data loss - max Solexa quality 62 in Solexa FASTQ", + ) + + +def _fastq_solexa_convert_fastq_illumina( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Solexa FASTQ to Illumina 1.3+ FASTQ conversion (PRIVATE). + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(59)] + + [ + chr(64 + int(round(phred_quality_from_solexa(q)))) + for q in range(-5, 62 + 1) + ] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_illumina_convert_fastq_solexa( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Illumina 1.3+ FASTQ to Solexa FASTQ conversion (PRIVATE). + + Avoids creating SeqRecord and Seq objects in order to speed up this + conversion. + """ + # Map unexpected chars to null + mapping = "".join( + [chr(0) for ascii in range(64)] + + [chr(64 + int(round(solexa_quality_from_phred(q)))) for q in range(62 + 1)] + + [chr(0) for ascii in range(127, 256)] + ) + assert len(mapping) == 256 + return _fastq_generic(in_file, out_file, mapping) + + +def _fastq_convert_fasta(in_file: _TextIOSource, out_file: _TextIOSource) -> int: + """Fast FASTQ to FASTA conversion (PRIVATE). + + Avoids dealing with the FASTQ quality encoding, and creating SeqRecord and + Seq objects in order to speed up this conversion. + + NOTE - This does NOT check the characters used in the FASTQ quality string + are valid! + """ + # For real speed, don't even make SeqRecord and Seq objects! + count = 0 + with as_handle(out_file, "w") as out_handle: + for title, seq, qual in FastqGeneralIterator(in_file): + count += 1 + out_handle.write(f">{title}\n") + # Do line wrapping + for i in range(0, len(seq), 60): + out_handle.write(seq[i : i + 60] + "\n") + return count + + +def _fastq_convert_tab(in_file: _TextIOSource, out_file: _TextIOSource) -> int: + """Fast FASTQ to simple tabbed conversion (PRIVATE). + + Avoids dealing with the FASTQ quality encoding, and creating SeqRecord and + Seq objects in order to speed up this conversion. + + NOTE - This does NOT check the characters used in the FASTQ quality string + are valid! + """ + # For real speed, don't even make SeqRecord and Seq objects! + count = 0 + with as_handle(out_file, "w") as out_handle: + for title, seq, qual in FastqGeneralIterator(in_file): + count += 1 + out_handle.write(f"{title.split(None, 1)[0]}\t{seq}\n") + return count + + +def _fastq_convert_qual( + in_file: _TextIOSource, + out_file: _TextIOSource, + mapping: Mapping[str, str], +) -> int: + """FASTQ helper function for QUAL output (PRIVATE). + + Mapping should be a dictionary mapping expected ASCII characters from the + FASTQ quality string to PHRED quality scores (as strings). + """ + # For real speed, don't even make SeqRecord and Seq objects! + count = 0 + with as_handle(out_file, "w") as out_handle: + for title, seq, qual in FastqGeneralIterator(in_file): + count += 1 + out_handle.write(f">{title}\n") + # map the qual... note even with Sanger encoding max 2 digits + try: + qualities_strs = [mapping[ascii_] for ascii_ in qual] + except KeyError: + invalid_index = _find_index_where(qual, lambda x: x not in mapping) + assert invalid_index >= 0, "Invalid char not in mapping not found!" + raise InvalidCharError( + qual, + invalid_index, + details="not in correct range (are you sure you're using the right QualityIO parser?)", + ) from None + data = " ".join(qualities_strs) + while len(data) > 60: + # Know quality scores are either 1 or 2 digits, so there + # must be a space in any three consecutive characters. + if data[60] == " ": + out_handle.write(data[:60] + "\n") + data = data[61:] + elif data[59] == " ": + out_handle.write(data[:59] + "\n") + data = data[60:] + else: + assert data[58] == " ", "Internal logic failure in wrapping" + out_handle.write(data[:58] + "\n") + data = data[59:] + out_handle.write(data + "\n") + return count + + +def _fastq_sanger_convert_qual(in_file: _TextIOSource, out_file: _TextIOSource) -> int: + """Fast Sanger FASTQ to QUAL conversion (PRIVATE).""" + mapping = {chr(q + 33): str(q) for q in range(93 + 1)} + return _fastq_convert_qual(in_file, out_file, mapping) + + +def _fastq_solexa_convert_qual(in_file: _TextIOSource, out_file: _TextIOSource) -> int: + """Fast Solexa FASTQ to QUAL conversion (PRIVATE).""" + mapping = { + chr(q + 64): str(int(round(phred_quality_from_solexa(q)))) + for q in range(-5, 62 + 1) + } + return _fastq_convert_qual(in_file, out_file, mapping) + + +def _fastq_illumina_convert_qual( + in_file: _TextIOSource, out_file: _TextIOSource +) -> int: + """Fast Illumina 1.3+ FASTQ to QUAL conversion (PRIVATE).""" + mapping = {chr(q + 64): str(q) for q in range(62 + 1)} + return _fastq_convert_qual(in_file, out_file, mapping) + + +@dataclass +class InvalidCharError(ValueError): + """ + Custom error for strings that have a character that is invalid for whatever reason (eg: non-ascii, invalid range) + + Main attributes: + - full_string - the string which contains the invalid character (str) + - index - position of the invalid character in full_string (int) + - details - additional information to add to the error message. Like: 'not in correct range' (str) + - r - how many characters on each side of the invalid character to include in the error message (int) + """ + + full_string: str + index: int + details: str + r: int = 3 + + def __str__(self) -> str: + char = self.full_string[self.index] + + surrounding_characters = self.full_string[ + max(self.index - self.r, 0) : self.index + self.r + 1 + ] + left_complete = self.index - self.r < 0 + prefix = "" if left_complete else "..." + right_complete = self.index + self.r + 1 >= len(self.full_string) + suffix = "" if right_complete else "..." + + return f"Invalid character ({char}) or (0x{char.encode().hex()}) in quality string {self.details} with context: [{prefix}{surrounding_characters}{suffix}]" + + +def _find_index_where(iterable: Iterable, predicate: Callable[[Any], bool]) -> int: + for i, x in enumerate(iterable): + if predicate(x) is True: + return i + + return -1 + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SeqXmlIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SeqXmlIO.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf28b7342f991d15364841d814ba4110db8b551 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SeqXmlIO.py @@ -0,0 +1,727 @@ +# Copyright 2010 by Thomas Schmitt. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "seqxml" file format, SeqXML. + +This module is for reading and writing SeqXML format files as +SeqRecord objects, and is expected to be used via the Bio.SeqIO API. + +SeqXML is a lightweight XML format which is supposed be an alternative for +FASTA files. For more Information see http://www.seqXML.org and Schmitt et al +(2011), https://doi.org/10.1093/bib/bbr025 +""" + +from xml import sax +from xml.sax import handler +from xml.sax.saxutils import XMLGenerator +from xml.sax.xmlreader import AttributesImpl + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + + +class ContentHandler(handler.ContentHandler): + """Handles XML events generated by the parser (PRIVATE).""" + + def __init__(self): + """Create a handler to handle XML events.""" + super().__init__() + self.source = None + self.sourceVersion = None + self.seqXMLversion = None + self.ncbiTaxID = None + self.speciesName = None + self.startElementNS = None + self.data = None + self.records = [] + + def startDocument(self): + """Set XML handlers when an XML declaration is found.""" + self.startElementNS = self.startSeqXMLElement + + def startSeqXMLElement(self, name, qname, attrs): + """Handle start of a seqXML element.""" + if name != (None, "seqXML"): + raise ValueError("Failed to find the start of seqXML element") + if qname is not None: + raise RuntimeError("Unexpected qname for seqXML element") + schema = None + for key, value in attrs.items(): + namespace, localname = key + if namespace is None: + if localname == "source": + self.source = value + elif localname == "sourceVersion": + self.sourceVersion = value + elif localname == "seqXMLversion": + self.seqXMLversion = value + elif localname == "ncbiTaxID": + # check if it is an integer, but store as string + number = int(value) + self.ncbiTaxID = value + elif localname == "speciesName": + self.speciesName = value + else: + raise ValueError("Unexpected attribute for XML Schema") + elif namespace == "http://www.w3.org/2001/XMLSchema-instance": + if localname == "noNamespaceSchemaLocation": + schema = value + else: + raise ValueError("Unexpected attribute for XML Schema in namespace") + else: + raise ValueError( + f"Unexpected namespace '{namespace}' for seqXML attribute" + ) + if self.seqXMLversion is None: + raise ValueError("Failed to find seqXMLversion") + elif self.seqXMLversion not in ("0.1", "0.2", "0.3", "0.4"): + raise ValueError("Unsupported seqXMLversion") + url = f"http://www.seqxml.org/{self.seqXMLversion}/seqxml.xsd" + if schema is not None and schema != url: + raise ValueError( + "XML Schema '%s' found not consistent with reported seqXML version %s" + % (schema, self.seqXMLversion) + ) + # speciesName and ncbiTaxID attributes on the root are only supported + # in 0.4 + if self.speciesName and self.seqXMLversion != "0.4": + raise ValueError( + "Attribute 'speciesName' on root is only supported in version 0.4" + ) + if self.ncbiTaxID and self.seqXMLversion != "0.4": + raise ValueError( + "Attribute 'ncbiTaxID' on root is only supported in version 0.4" + ) + self.endElementNS = self.endSeqXMLElement + self.startElementNS = self.startEntryElement + + def endSeqXMLElement(self, name, qname): + """Handle end of the seqXML element.""" + namespace, localname = name + if namespace is not None: + raise RuntimeError(f"Unexpected namespace '{namespace}' for seqXML end") + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for seqXML end") + if localname != "seqXML": + raise RuntimeError("Failed to find end of seqXML element") + self.startElementNS = None + self.endElementNS = None + + def startEntryElement(self, name, qname, attrs): + """Set new entry with id and the optional entry source (PRIVATE).""" + if name != (None, "entry"): + raise ValueError("Expected to find the start of an entry element") + if qname is not None: + raise RuntimeError("Unexpected qname for entry element") + record = SeqRecord(None, id=None) + if self.speciesName is not None: + record.annotations["organism"] = self.speciesName + if self.ncbiTaxID is not None: + record.annotations["ncbi_taxid"] = self.ncbiTaxID + record.annotations["source"] = self.source + for key, value in attrs.items(): + namespace, localname = key + if namespace is None: + if localname == "id": + record.id = value + elif localname == "source" and ( + self.seqXMLversion == "0.3" or self.seqXMLversion == "0.4" + ): + record.annotations["source"] = value + else: + raise ValueError( + f"Unexpected attribute {localname} in entry element" + ) + else: + raise ValueError( + f"Unexpected namespace '{namespace}' for entry attribute" + ) + if record.id is None: + raise ValueError("Failed to find entry ID") + self.records.append(record) + if self.seqXMLversion == "0.1": + self.startElementNS = self.startEntryFieldElementVersion01 + else: + self.startElementNS = self.startEntryFieldElement + self.endElementNS = self.endEntryElement + + def endEntryElement(self, name, qname): + """Handle end of an entry element.""" + if name != (None, "entry"): + raise ValueError("Expected to find the end of an entry element") + if qname is not None: + raise RuntimeError("Unexpected qname for entry element") + if self.records[-1].seq is None: + raise ValueError("Failed to find a sequence for entry element") + self.startElementNS = self.startEntryElement + self.endElementNS = self.endSeqXMLElement + + def startEntryFieldElementVersion01(self, name, qname, attrs): + """Receive a field of an entry element and forward it for version 0.1.""" + namespace, localname = name + if namespace is not None: + raise ValueError( + f"Unexpected namespace '{namespace}' for {localname} element" + ) + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for {localname} element") + if localname == "species": + return self.startSpeciesElement(attrs) + if localname == "description": + return self.startDescriptionElement(attrs) + if localname in ("dnaSeq", "rnaSeq", "aaSeq"): + return self.startSequenceElement(attrs) + if localname == "alternativeID": + return self.startDBRefElement(attrs) + if localname == "property": + return self.startPropertyElement(attrs) + raise ValueError(f"Unexpected field {localname} in entry") + + def startEntryFieldElement(self, name, qname, attrs): + """Receive a field of an entry element and forward it for versions >=0.2.""" + namespace, localname = name + if namespace is not None: + raise ValueError( + f"Unexpected namespace '{namespace}' for {localname} element" + ) + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for {localname} element") + if localname == "species": + return self.startSpeciesElement(attrs) + if localname == "description": + return self.startDescriptionElement(attrs) + if localname in ("DNAseq", "RNAseq", "AAseq"): + return self.startSequenceElement(attrs) + if localname == "DBRef": + return self.startDBRefElement(attrs) + if localname == "property": + return self.startPropertyElement(attrs) + raise ValueError(f"Unexpected field {localname} in entry") + + def startSpeciesElement(self, attrs): + """Parse the species information.""" + name = None + ncbiTaxID = None + for key, value in attrs.items(): + namespace, localname = key + if namespace is None: + if localname == "name": + name = value + elif localname == "ncbiTaxID": + # check if it is an integer, but store as string + number = int(value) + ncbiTaxID = value + else: + raise ValueError( + f"Unexpected attribute '{key}' found in species tag" + ) + else: + raise ValueError( + f"Unexpected namespace '{namespace}' for species attribute" + ) + # The attributes "name" and "ncbiTaxID" are required: + if name is None: + raise ValueError("Failed to find species name") + if ncbiTaxID is None: + raise ValueError("Failed to find ncbiTaxId") + record = self.records[-1] + # The keywords for the species annotation are taken from SwissIO + record.annotations["organism"] = name + # TODO - Should have been a list to match SwissProt parser: + record.annotations["ncbi_taxid"] = ncbiTaxID + self.endElementNS = self.endSpeciesElement + + def endSpeciesElement(self, name, qname): + """Handle end of a species element.""" + namespace, localname = name + if namespace is not None: + raise RuntimeError(f"Unexpected namespace '{namespace}' for species end") + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for species end") + if localname != "species": + raise RuntimeError("Failed to find end of species element") + self.endElementNS = self.endEntryElement + + def startDescriptionElement(self, attrs): + """Parse the description.""" + if attrs: + raise ValueError("Unexpected attributes found in description element") + if self.data is not None: + raise RuntimeError(f"Unexpected data found: '{self.data}'") + self.data = "" + self.endElementNS = self.endDescriptionElement + + def endDescriptionElement(self, name, qname): + """Handle the end of a description element.""" + namespace, localname = name + if namespace is not None: + raise RuntimeError( + f"Unexpected namespace '{namespace}' for description end" + ) + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for description end") + if localname != "description": + raise RuntimeError("Failed to find end of description element") + record = self.records[-1] + description = self.data + if description: # ignore if empty string + record.description = description + self.data = None + self.endElementNS = self.endEntryElement + + def startSequenceElement(self, attrs): + """Parse DNA, RNA, or protein sequence.""" + if attrs: + raise ValueError("Unexpected attributes found in sequence element") + if self.data is not None: + raise RuntimeError(f"Unexpected data found: '{self.data}'") + self.data = "" + self.endElementNS = self.endSequenceElement + + def endSequenceElement(self, name, qname): + """Handle the end of a sequence element.""" + namespace, localname = name + if namespace is not None: + raise RuntimeError(f"Unexpected namespace '{namespace}' for sequence end") + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for sequence end") + record = self.records[-1] + if (localname == "DNAseq" and self.seqXMLversion != "0.1") or ( + localname == "dnaSeq" and self.seqXMLversion == "0.1" + ): + record.annotations["molecule_type"] = "DNA" + elif (localname == "RNAseq" and self.seqXMLversion != "0.1") or ( + localname == "rnaSeq" and self.seqXMLversion == "0.1" + ): + record.annotations["molecule_type"] = "RNA" + elif (localname == "AAseq" and self.seqXMLversion >= "0.1") or ( + localname == "aaSeq" and self.seqXMLversion == "0.1" + ): + record.annotations["molecule_type"] = "protein" + else: + raise RuntimeError( + f"Failed to find end of sequence (localname = {localname})" + ) + record.seq = Seq(self.data) + self.data = None + self.endElementNS = self.endEntryElement + + def startDBRefElement(self, attrs): + """Parse a database cross reference.""" + TYPE = None + source = None + ID = None + for key, value in attrs.items(): + namespace, localname = key + if namespace is None: + if localname == "type": + TYPE = value + elif localname == "source": + source = value + elif localname == "id": + ID = value + else: + raise ValueError( + f"Unexpected attribute '{key}' found for DBRef element" + ) + else: + raise ValueError( + f"Unexpected namespace '{namespace}' for DBRef attribute" + ) + # The attributes "source" and "id" are required, and "type" in versions + # 0.2-0.3: + if source is None: + raise ValueError("Failed to find source for DBRef element") + if ID is None: + raise ValueError("Failed to find id for DBRef element") + if TYPE is None and ( + self.seqXMLversion == "0.2" or self.seqXMLversion == "0.3" + ): + raise ValueError("Failed to find type for DBRef element") + if self.data is not None: + raise RuntimeError(f"Unexpected data found: '{self.data}'") + self.data = "" + record = self.records[-1] + dbxref = f"{source}:{ID}" + if dbxref not in record.dbxrefs: + record.dbxrefs.append(dbxref) + self.endElementNS = self.endDBRefElement + + def endDBRefElement(self, name, qname): + """Handle the end of a DBRef element.""" + namespace, localname = name + if namespace is not None: + raise RuntimeError(f"Unexpected namespace '{namespace}' for DBRef element") + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for DBRef element") + if (localname != "DBRef" and self.seqXMLversion != "0.1") or ( + localname != "alternativeID" and self.seqXMLversion == "0.1" + ): + raise RuntimeError(f"Unexpected localname '{localname}' for DBRef element") + if self.data: + raise RuntimeError( + f"Unexpected data received for DBRef element: '{self.data}'" + ) + self.data = None + self.endElementNS = self.endEntryElement + + def startPropertyElement(self, attrs): + """Handle the start of a property element.""" + property_name = None + property_value = None + for key, value in attrs.items(): + namespace, localname = key + if namespace is None: + if localname == "name": + property_name = value + elif localname == "value": + property_value = value + else: + raise ValueError( + "Unexpected attribute '%s' found for property element", key + ) + else: + raise ValueError( + f"Unexpected namespace '{namespace}' for property attribute" + ) + # The attribute "name" is required: + if property_name is None: + raise ValueError("Failed to find name for property element") + record = self.records[-1] + if property_name == "molecule_type": + # At this point, record.annotations["molecule_type"] is either + # "DNA", "RNA", or "protein"; property_value may be a more detailed + # description such as "mRNA" or "genomic DNA". + assert record.annotations[property_name] in property_value + record.annotations[property_name] = property_value + else: + if property_name not in record.annotations: + record.annotations[property_name] = [] + record.annotations[property_name].append(property_value) + self.endElementNS = self.endPropertyElement + + def endPropertyElement(self, name, qname): + """Handle the end of a property element.""" + namespace, localname = name + if namespace is not None: + raise RuntimeError( + f"Unexpected namespace '{namespace}' for property element" + ) + if qname is not None: + raise RuntimeError(f"Unexpected qname '{qname}' for property element") + if localname != "property": + raise RuntimeError( + f"Unexpected localname '{localname}' for property element" + ) + self.endElementNS = self.endEntryElement + + def characters(self, data): + """Handle character data.""" + if self.data is not None: + self.data += data + + +class SeqXmlIterator(SequenceIterator): + """Parser for seqXML files. + + Parses seqXML files and creates SeqRecords. + Assumes valid seqXML please validate beforehand. + It is assumed that all information for one record can be found within a + record element or above. Two types of methods are called when the start + tag of an element is reached. To receive only the attributes of an + element before its end tag is reached implement _attr_TAGNAME. + To get an element and its children as a DOM tree implement _elem_TAGNAME. + Everything that is part of the DOM tree will not trigger any further + method calls. + """ + + modes = "b" + + # Small block size can be a problem with libexpat 2.6.0 onwards: + BLOCK = 1024 + + def __init__(self, stream_or_path, namespace=None): + """Create the object and initialize the XML parser.""" + # Make sure we got a binary handle. If we got a text handle, then + # the parser will still run but unicode characters will be garbled + # if the text handle was opened with a different encoding than the + # one specified in the XML file. With a binary handle, the correct + # encoding is picked up by the parser from the XML file. + super().__init__(stream_or_path, fmt="SeqXML") + stream = self.stream + parser = sax.make_parser() + content_handler = ContentHandler() + parser.setContentHandler(content_handler) + parser.setFeature(handler.feature_namespaces, True) + self.parser = parser + BLOCK = self.BLOCK + while True: + # Read in another block of the file... + text = stream.read(BLOCK) + if not text: + if content_handler.startElementNS is None: + raise ValueError("Empty file.") + else: + raise ValueError("XML file contains no data.") + parser.feed(text) + seqXMLversion = content_handler.seqXMLversion + if seqXMLversion is not None: + break + self.seqXMLversion = seqXMLversion + self.source = content_handler.source + self.sourceVersion = content_handler.sourceVersion + self.ncbiTaxID = content_handler.ncbiTaxID + self.speciesName = content_handler.speciesName + + def __next__(self): + """Return the next entry.""" + parser = self.parser + content_handler = parser.getContentHandler() + records = content_handler.records + if records is None: + raise StopIteration + stream = self.stream + BLOCK = self.BLOCK + while True: + if len(records) > 1: + # Then at least the first record is finished + record = records.pop(0) + return record + # Read in another block of the file... + text = stream.read(BLOCK) + if not text: + # Closing the parser ensures that all XML data fed + # into it are processed + parser.close() + break + parser.feed(text) + # We have reached the end of the XML file; + # send out the remaining records + try: + record = records.pop(0) + except IndexError: + self.records = None + raise StopIteration + else: + return record + + +class SeqXmlWriter(SequenceWriter): + """Writes SeqRecords into seqXML file. + + SeqXML requires the SeqRecord annotations to specify the molecule_type; + the molecule type is required to contain the term "DNA", "RNA", or + "protein". + """ + + modes = "b" + + def __init__( + self, target, source=None, source_version=None, species=None, ncbiTaxId=None + ): + """Create Object and start the xml generator. + + Arguments: + - target - Output stream opened in binary mode, or a path to a file. + - source - The source program/database of the file, for example + UniProt. + - source_version - The version or release number of the source + program or database from which the data originated. + - species - The scientific name of the species of origin of all + entries in the file. + - ncbiTaxId - The NCBI taxonomy identifier of the species of origin. + + """ + super().__init__(target) + handle = self.handle + self.xml_generator = XMLGenerator(handle, "utf-8") + self.xml_generator.startDocument() + self.source = source + self.source_version = source_version + self.species = species + self.ncbiTaxId = ncbiTaxId + + def write_records(self, records): + """Write records to the output file, and return the number of records. + + records - A list or iterator returning SeqRecord objects + """ + self.write_header() + count = super().write_records(records) + self.write_footer() + return count + + def write_header(self): + """Write root node with document metadata.""" + attrs = { + "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", + "xsi:noNamespaceSchemaLocation": "http://www.seqxml.org/0.4/seqxml.xsd", + "seqXMLversion": "0.4", + } + + if self.source is not None: + attrs["source"] = self.source + if self.source_version is not None: + attrs["sourceVersion"] = self.source_version + if self.species is not None: + if not isinstance(self.species, str): + raise TypeError("species should be of type string") + attrs["speciesName"] = self.species + if self.ncbiTaxId is not None: + if not isinstance(self.ncbiTaxId, (str, int)): + raise TypeError("ncbiTaxID should be of type string or int") + attrs["ncbiTaxID"] = self.ncbiTaxId + + self.xml_generator.startElement("seqXML", AttributesImpl(attrs)) + + def write_record(self, record): + """Write one record.""" + if not record.id or record.id == "": + raise ValueError("SeqXML requires identifier") + + if not isinstance(record.id, str): + raise TypeError("Identifier should be of type string") + + attrb = {"id": record.id} + + if ( + "source" in record.annotations + and self.source != record.annotations["source"] + ): + if not isinstance(record.annotations["source"], str): + raise TypeError("source should be of type string") + attrb["source"] = record.annotations["source"] + + self.xml_generator.startElement("entry", AttributesImpl(attrb)) + self._write_species(record) + self._write_description(record) + self._write_seq(record) + self._write_dbxrefs(record) + self._write_properties(record) + self.xml_generator.endElement("entry") + + def write_footer(self): + """Close the root node and finish the XML document.""" + self.xml_generator.endElement("seqXML") + self.xml_generator.endDocument() + + def _write_species(self, record): + """Write the species if given (PRIVATE).""" + local_ncbi_taxid = None + if "ncbi_taxid" in record.annotations: + local_ncbi_taxid = record.annotations["ncbi_taxid"] + if isinstance(local_ncbi_taxid, list): + # SwissProt parser uses a list (which could cope with chimeras) + if len(local_ncbi_taxid) == 1: + local_ncbi_taxid = local_ncbi_taxid[0] + elif len(local_ncbi_taxid) == 0: + local_ncbi_taxid = None + else: + raise ValueError( + "Multiple entries for record.annotations['ncbi_taxid'], %r" + % local_ncbi_taxid + ) + if "organism" in record.annotations and local_ncbi_taxid: + local_org = record.annotations["organism"] + + if not isinstance(local_org, str): + raise TypeError("organism should be of type string") + + if not isinstance(local_ncbi_taxid, (str, int)): + raise TypeError("ncbiTaxID should be of type string or int") + + # The local species definition is only written if it differs from the global species definition + if local_org != self.species or local_ncbi_taxid != self.ncbiTaxId: + attr = {"name": local_org, "ncbiTaxID": str(local_ncbi_taxid)} + self.xml_generator.startElement("species", AttributesImpl(attr)) + self.xml_generator.endElement("species") + + def _write_description(self, record): + """Write the description if given (PRIVATE).""" + if record.description: + if not isinstance(record.description, str): + raise TypeError("Description should be of type string") + + description = record.description + if description == "": + description = "" + + if len(record.description) > 0: + self.xml_generator.startElement("description", AttributesImpl({})) + self.xml_generator.characters(description) + self.xml_generator.endElement("description") + + def _write_seq(self, record): + """Write the sequence (PRIVATE). + + Note that SeqXML requires the molecule type to contain the term + "DNA", "RNA", or "protein". + """ + seq = bytes(record.seq) + + if not len(seq) > 0: + raise ValueError("The sequence length should be greater than 0") + + molecule_type = record.annotations.get("molecule_type") + if molecule_type is None: + raise ValueError("molecule_type is not defined") + elif "DNA" in molecule_type: + seqElem = "DNAseq" + elif "RNA" in molecule_type: + seqElem = "RNAseq" + elif "protein" in molecule_type: + seqElem = "AAseq" + else: + raise ValueError(f"unknown molecule_type '{molecule_type}'") + + self.xml_generator.startElement(seqElem, AttributesImpl({})) + self.xml_generator.characters(seq) + self.xml_generator.endElement(seqElem) + + def _write_dbxrefs(self, record): + """Write all database cross references (PRIVATE).""" + if record.dbxrefs is not None: + for dbxref in record.dbxrefs: + if not isinstance(dbxref, str): + raise TypeError("dbxrefs should be of type list of string") + if dbxref.find(":") < 1: + raise ValueError( + "dbxrefs should be in the form ['source:id', 'source:id' ]" + ) + + dbsource, dbid = dbxref.split(":", 1) + + attr = {"source": dbsource, "id": dbid} + self.xml_generator.startElement("DBRef", AttributesImpl(attr)) + self.xml_generator.endElement("DBRef") + + def _write_properties(self, record): + """Write all annotations that are key value pairs with values of a primitive type or list of primitive types (PRIVATE).""" + for key, value in record.annotations.items(): + if key not in ("organism", "ncbi_taxid", "source"): + if value is None: + attr = {"name": key} + self.xml_generator.startElement("property", AttributesImpl(attr)) + self.xml_generator.endElement("property") + + elif isinstance(value, list): + for v in value: + if v is None: + attr = {"name": key} + else: + attr = {"name": key, "value": str(v)} + self.xml_generator.startElement( + "property", AttributesImpl(attr) + ) + self.xml_generator.endElement("property") + + elif isinstance(value, (int, float, str)): + attr = {"name": key, "value": str(value)} + self.xml_generator.startElement("property", AttributesImpl(attr)) + self.xml_generator.endElement("property") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SffIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SffIO.py new file mode 100644 index 0000000000000000000000000000000000000000..21f0134eaed8696f34637102cb9db85fdb52a6ae --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SffIO.py @@ -0,0 +1,1478 @@ +# Copyright 2009-2020 by Peter Cock. All rights reserved. +# Based on code contributed and copyright 2009 by Jose Blanca (COMAV-UPV). +# +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Bio.SeqIO support for the binary Standard Flowgram Format (SFF) file format. + +SFF was designed by 454 Life Sciences (Roche), the Whitehead Institute for +Biomedical Research and the Wellcome Trust Sanger Institute. SFF was also used +as the native output format from early versions of Ion Torrent's PGM platform +as well. You are expected to use this module via the Bio.SeqIO functions under +the format name "sff" (or "sff-trim" as described below). + +For example, to iterate over the records in an SFF file, + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff"): + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) + ... + E3MFGYR02JWQ7T 265 tcagGGTCTACATGTTGGTT... + E3MFGYR02JA6IL 271 tcagTTTTTTTTGGAAAGGA... + E3MFGYR02JHD4H 310 tcagAAAGACAAGTGGTATC... + E3MFGYR02GFKUC 299 tcagCGGCCGGGCCTCTCAT... + E3MFGYR02FTGED 281 tcagTGGTAATGGGGGGAAA... + E3MFGYR02FR9G7 261 tcagCTCCGTAAGAAGGTGC... + E3MFGYR02GAZMS 278 tcagAAAGAAGTAAGGTAAA... + E3MFGYR02HHZ8O 221 tcagACTTTCTTCTTTACCG... + E3MFGYR02GPGB1 269 tcagAAGCAGTGGTATCAAC... + E3MFGYR02F7Z7G 219 tcagAATCATCCACTTTTTA... + +Each SeqRecord object will contain all the annotation from the SFF file, +including the PHRED quality scores. + + >>> print("%s %i" % (record.id, len(record))) + E3MFGYR02F7Z7G 219 + >>> print("%s..." % record.seq[:10]) + tcagAATCAT... + >>> print("%r..." % (record.letter_annotations["phred_quality"][:10])) + [22, 21, 23, 28, 26, 15, 12, 21, 28, 21]... + +Notice that the sequence is given in mixed case, the central upper case region +corresponds to the trimmed sequence. This matches the output of the Roche +tools (and the 3rd party tool sff_extract) for SFF to FASTA. + + >>> print(record.annotations["clip_qual_left"]) + 4 + >>> print(record.annotations["clip_qual_right"]) + 134 + >>> print(record.seq[:4]) + tcag + >>> print("%s...%s" % (record.seq[4:20], record.seq[120:134])) + AATCATCCACTTTTTA...CAAAACACAAACAG + >>> print(record.seq[134:]) + atcttatcaacaaaactcaaagttcctaactgagacacgcaacaggggataagacaaggcacacaggggataggnnnnnnnnnnn + +The annotations dictionary also contains any adapter clip positions +(usually zero), and information about the flows. e.g. + + >>> len(record.annotations) + 12 + >>> print(record.annotations["flow_key"]) + TCAG + >>> print(record.annotations["flow_values"][:10]) + (83, 1, 128, 7, 4, 84, 6, 106, 3, 172) + >>> print(len(record.annotations["flow_values"])) + 400 + >>> print(record.annotations["flow_index"][:10]) + (1, 2, 3, 2, 2, 0, 3, 2, 3, 3) + >>> print(len(record.annotations["flow_index"])) + 219 + +Note that to convert from a raw reading in flow_values to the corresponding +homopolymer stretch estimate, the value should be rounded to the nearest 100: + + >>> print("%r..." % [int(round(value, -2)) // 100 + ... for value in record.annotations["flow_values"][:10]]) + ... + [1, 0, 1, 0, 0, 1, 0, 1, 0, 2]... + +If a read name is exactly 14 alphanumeric characters, the annotations +dictionary will also contain meta-data about the read extracted by +interpreting the name as a 454 Sequencing System "Universal" Accession +Number. Note that if a read name happens to be exactly 14 alphanumeric +characters but was not generated automatically, these annotation records +will contain nonsense information. + + >>> print(record.annotations["region"]) + 2 + >>> print(record.annotations["time"]) + [2008, 1, 9, 16, 16, 0] + >>> print(record.annotations["coords"]) + (2434, 1658) + +As a convenience method, you can read the file with SeqIO format name "sff-trim" +instead of "sff" to get just the trimmed sequences (without any annotation +except for the PHRED quality scores and anything encoded in the read names): + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff-trim"): + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) + ... + E3MFGYR02JWQ7T 260 GGTCTACATGTTGGTTAACC... + E3MFGYR02JA6IL 265 TTTTTTTTGGAAAGGAAAAC... + E3MFGYR02JHD4H 292 AAAGACAAGTGGTATCAACG... + E3MFGYR02GFKUC 295 CGGCCGGGCCTCTCATCGGT... + E3MFGYR02FTGED 277 TGGTAATGGGGGGAAATTTA... + E3MFGYR02FR9G7 256 CTCCGTAAGAAGGTGCTGCC... + E3MFGYR02GAZMS 271 AAAGAAGTAAGGTAAATAAC... + E3MFGYR02HHZ8O 150 ACTTTCTTCTTTACCGTAAC... + E3MFGYR02GPGB1 221 AAGCAGTGGTATCAACGCAG... + E3MFGYR02F7Z7G 130 AATCATCCACTTTTTAACGT... + +Looking at the final record in more detail, note how this differs to the +example above: + + >>> print("%s %i" % (record.id, len(record))) + E3MFGYR02F7Z7G 130 + >>> print("%s..." % record.seq[:10]) + AATCATCCAC... + >>> print("%r..." % record.letter_annotations["phred_quality"][:10]) + [26, 15, 12, 21, 28, 21, 36, 28, 27, 27]... + >>> len(record.annotations) + 4 + >>> print(record.annotations["region"]) + 2 + >>> print(record.annotations["coords"]) + (2434, 1658) + >>> print(record.annotations["time"]) + [2008, 1, 9, 16, 16, 0] + >>> print(record.annotations["molecule_type"]) + DNA + +You might use the Bio.SeqIO.convert() function to convert the (trimmed) SFF +reads into a FASTQ file (or a FASTA file and a QUAL file), e.g. + + >>> from Bio import SeqIO + >>> from io import StringIO + >>> out_handle = StringIO() + >>> count = SeqIO.convert("Roche/E3MFGYR02_random_10_reads.sff", "sff", + ... out_handle, "fastq") + ... + >>> print("Converted %i records" % count) + Converted 10 records + +The output FASTQ file would start like this: + + >>> print("%s..." % out_handle.getvalue()[:50]) + @E3MFGYR02JWQ7T + tcagGGTCTACATGTTGGTTAACCCGTACTGATT... + +Bio.SeqIO.index() provides memory efficient random access to the reads in an +SFF file by name. SFF files can include an index within the file, which can +be read in making this very fast. If the index is missing (or in a format not +yet supported in Biopython) the file is indexed by scanning all the reads - +which is a little slower. For example, + + >>> from Bio import SeqIO + >>> reads = SeqIO.index("Roche/E3MFGYR02_random_10_reads.sff", "sff") + >>> record = reads["E3MFGYR02JHD4H"] + >>> print("%s %i %s..." % (record.id, len(record), record.seq[:20])) + E3MFGYR02JHD4H 310 tcagAAAGACAAGTGGTATC... + >>> reads.close() + +Or, using the trimmed reads: + + >>> from Bio import SeqIO + >>> reads = SeqIO.index("Roche/E3MFGYR02_random_10_reads.sff", "sff-trim") + >>> record = reads["E3MFGYR02JHD4H"] + >>> print("%s %i %s..." % (record.id, len(record), record.seq[:20])) + E3MFGYR02JHD4H 292 AAAGACAAGTGGTATCAACG... + >>> reads.close() + +You can also use the Bio.SeqIO.write() function with the "sff" format. Note +that this requires all the flow information etc, and thus is probably only +useful for SeqRecord objects originally from reading another SFF file (and +not the trimmed SeqRecord objects from parsing an SFF file as "sff-trim"). + +As an example, let's pretend this example SFF file represents some DNA which +was pre-amplified with a PCR primers AAAGANNNNN. The following script would +produce a sub-file containing all those reads whose post-quality clipping +region (i.e. the sequence after trimming) starts with AAAGA exactly (the non- +degenerate bit of this pretend primer): + + >>> from Bio import SeqIO + >>> records = (record for record in + ... SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff") + ... if record.seq[record.annotations["clip_qual_left"]:].startswith("AAAGA")) + ... + >>> count = SeqIO.write(records, "temp_filtered.sff", "sff") + >>> print("Selected %i records" % count) + Selected 2 records + +Of course, for an assembly you would probably want to remove these primers. +If you want FASTA or FASTQ output, you could just slice the SeqRecord. However, +if you want SFF output we have to preserve all the flow information - the trick +is just to adjust the left clip position! + + >>> from Bio import SeqIO + >>> def filter_and_trim(records, primer): + ... for record in records: + ... if record.seq[record.annotations["clip_qual_left"]:].startswith(primer): + ... record.annotations["clip_qual_left"] += len(primer) + ... yield record + ... + >>> records = SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff") + >>> count = SeqIO.write(filter_and_trim(records, "AAAGA"), + ... "temp_filtered.sff", "sff") + ... + >>> print("Selected %i records" % count) + Selected 2 records + +We can check the results, note the lower case clipped region now includes the "AAAGA" +sequence: + + >>> for record in SeqIO.parse("temp_filtered.sff", "sff"): + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) + ... + E3MFGYR02JHD4H 310 tcagaaagaCAAGTGGTATC... + E3MFGYR02GAZMS 278 tcagaaagaAGTAAGGTAAA... + >>> for record in SeqIO.parse("temp_filtered.sff", "sff-trim"): + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) + ... + E3MFGYR02JHD4H 287 CAAGTGGTATCAACGCAGAG... + E3MFGYR02GAZMS 266 AGTAAGGTAAATAACAAACG... + >>> import os + >>> os.remove("temp_filtered.sff") + +For a description of the file format, please see the Roche manuals and: +http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?cmd=show&f=formats&m=doc&s=formats + +""" + +import re +import struct + +from Bio import StreamModeError +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +_null = b"\0" +_sff = b".sff" +_hsh = b".hsh" +_srt = b".srt" +_mft = b".mft" +_flag = b"\xff" + + +def _sff_file_header(handle): + """Read in an SFF file header (PRIVATE). + + Assumes the handle is at the start of the file, will read forwards + though the header and leave the handle pointing at the first record. + Returns a tuple of values from the header (header_length, index_offset, + index_length, number_of_reads, flows_per_read, flow_chars, key_sequence) + + >>> with open("Roche/greek.sff", "rb") as handle: + ... values = _sff_file_header(handle) + ... + >>> print(values[0]) + 840 + >>> print(values[1]) + 65040 + >>> print(values[2]) + 256 + >>> print(values[3]) + 24 + >>> print(values[4]) + 800 + >>> values[-1] + 'TCAG' + + """ + # file header (part one) + # use big endian encoding > + # magic_number I + # version 4B + # index_offset Q + # index_length I + # number_of_reads I + # header_length H + # key_length H + # number_of_flows_per_read H + # flowgram_format_code B + # [rest of file header depends on the number of flows and how many keys] + fmt = ">4s4BQIIHHHB" + assert 31 == struct.calcsize(fmt) + data = handle.read(31) + if not data: + raise ValueError("Empty file.") + elif len(data) < 31: + raise ValueError("File too small to hold a valid SFF header.") + try: + ( + magic_number, + ver0, + ver1, + ver2, + ver3, + index_offset, + index_length, + number_of_reads, + header_length, + key_length, + number_of_flows_per_read, + flowgram_format, + ) = struct.unpack(fmt, data) + except TypeError: + raise StreamModeError("SFF files must be opened in binary mode.") from None + if magic_number in [_hsh, _srt, _mft]: + # Probably user error, calling Bio.SeqIO.parse() twice! + raise ValueError("Handle seems to be at SFF index block, not start") + if magic_number != _sff: # 779314790 + raise ValueError(f"SFF file did not start '.sff', but {magic_number!r}") + if (ver0, ver1, ver2, ver3) != (0, 0, 0, 1): + raise ValueError( + "Unsupported SFF version in header, %i.%i.%i.%i" % (ver0, ver1, ver2, ver3) + ) + if flowgram_format != 1: + raise ValueError("Flowgram format code %i not supported" % flowgram_format) + if (index_offset != 0) ^ (index_length != 0): + raise ValueError( + "Index offset %i but index length %i" % (index_offset, index_length) + ) + flow_chars = handle.read(number_of_flows_per_read).decode("ASCII") + key_sequence = handle.read(key_length).decode("ASCII") + # According to the spec, the header_length field should be the total number + # of bytes required by this set of header fields, and should be equal to + # "31 + number_of_flows_per_read + key_length" rounded up to the next value + # divisible by 8. + assert header_length % 8 == 0 + padding = header_length - number_of_flows_per_read - key_length - 31 + assert 0 <= padding < 8, padding + if handle.read(padding).count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post header %i byte " + "null padding region contained data." % padding, + BiopythonParserWarning, + ) + return ( + header_length, + index_offset, + index_length, + number_of_reads, + number_of_flows_per_read, + flow_chars, + key_sequence, + ) + + +def _sff_do_slow_index(handle): + """Generate an index by scanning though all the reads in an SFF file (PRIVATE). + + This is a slow but generic approach if we can't parse the provided index + (if present). + + Will use the handle seek/tell functions. + """ + handle.seek(0) + ( + header_length, + index_offset, + index_length, + number_of_reads, + number_of_flows_per_read, + flow_chars, + key_sequence, + ) = _sff_file_header(handle) + # Now on to the reads... + read_header_fmt = ">2HI4H" + read_header_size = struct.calcsize(read_header_fmt) + # NOTE - assuming flowgram_format==1, which means struct type H + read_flow_fmt = ">%iH" % number_of_flows_per_read + read_flow_size = struct.calcsize(read_flow_fmt) + assert 1 == struct.calcsize(">B") + assert 1 == struct.calcsize(">s") + assert 1 == struct.calcsize(">c") + assert read_header_size % 8 == 0 # Important for padding calc later! + for read in range(number_of_reads): + record_offset = handle.tell() + if record_offset == index_offset: + # Found index block within reads, ignore it: + offset = index_offset + index_length + if offset % 8: + offset += 8 - (offset % 8) + assert offset % 8 == 0 + handle.seek(offset) + record_offset = offset + # assert record_offset%8 == 0 # Worth checking, but slow + # First the fixed header + data = handle.read(read_header_size) + ( + read_header_length, + name_length, + seq_len, + clip_qual_left, + clip_qual_right, + clip_adapter_left, + clip_adapter_right, + ) = struct.unpack(read_header_fmt, data) + if read_header_length < 10 or read_header_length % 8 != 0: + raise ValueError( + "Malformed read header, says length is %i:\n%r" + % (read_header_length, data) + ) + # now the name and any padding (remainder of header) + name = handle.read(name_length).decode() + padding = read_header_length - read_header_size - name_length + if handle.read(padding).count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post name %i byte " + "padding region contained data" % padding, + BiopythonParserWarning, + ) + assert record_offset + read_header_length == handle.tell() + # now the flowgram values, flowgram index, bases and qualities + size = read_flow_size + 3 * seq_len + handle.seek(size, 1) + # now any padding... + padding = size % 8 + if padding: + padding = 8 - padding + if handle.read(padding).count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post quality %i " + "byte padding region contained data" % padding, + BiopythonParserWarning, + ) + yield name, record_offset + if handle.tell() % 8 != 0: + raise ValueError("After scanning reads, did not end on a multiple of 8") + + +def _sff_find_roche_index(handle): + """Locate any existing Roche style XML meta data and read index (PRIVATE). + + Makes a number of hard coded assumptions based on reverse engineered SFF + files from Roche 454 machines. + + Returns a tuple of read count, SFF "index" offset and size, XML offset + and size, and the actual read index offset and size. + + Raises a ValueError for unsupported or non-Roche index blocks. + """ + handle.seek(0) + ( + header_length, + index_offset, + index_length, + number_of_reads, + number_of_flows_per_read, + flow_chars, + key_sequence, + ) = _sff_file_header(handle) + assert handle.tell() == header_length + if not index_offset or not index_length: + raise ValueError("No index present in this SFF file") + # Now jump to the header... + handle.seek(index_offset) + fmt = ">4s4B" + fmt_size = struct.calcsize(fmt) + data = handle.read(fmt_size) + if not data: + raise ValueError( + "Premature end of file? Expected index of size %i at offset %i, found nothing" + % (index_length, index_offset) + ) + if len(data) < fmt_size: + raise ValueError( + "Premature end of file? Expected index of size %i at offset %i, found %r" + % (index_length, index_offset, data) + ) + magic_number, ver0, ver1, ver2, ver3 = struct.unpack(fmt, data) + if magic_number == _mft: # 778921588 + # Roche 454 manifest index + # This is typical from raw Roche 454 SFF files (2009), and includes + # both an XML manifest and the sorted index. + if (ver0, ver1, ver2, ver3) != (49, 46, 48, 48): + # This is "1.00" as a string + raise ValueError( + "Unsupported version in .mft index header, %i.%i.%i.%i" + % (ver0, ver1, ver2, ver3) + ) + fmt2 = ">LL" + fmt2_size = struct.calcsize(fmt2) + xml_size, data_size = struct.unpack(fmt2, handle.read(fmt2_size)) + if index_length != fmt_size + fmt2_size + xml_size + data_size: + raise ValueError( + "Problem understanding .mft index header, %i != %i + %i + %i + %i" + % (index_length, fmt_size, fmt2_size, xml_size, data_size) + ) + return ( + number_of_reads, + header_length, + index_offset, + index_length, + index_offset + fmt_size + fmt2_size, + xml_size, + index_offset + fmt_size + fmt2_size + xml_size, + data_size, + ) + elif magic_number == _srt: # 779317876 + # Roche 454 sorted index + # I've had this from Roche tool sfffile when the read identifiers + # had nonstandard lengths and there was no XML manifest. + if (ver0, ver1, ver2, ver3) != (49, 46, 48, 48): + # This is "1.00" as a string + raise ValueError( + "Unsupported version in .srt index header, %i.%i.%i.%i" + % (ver0, ver1, ver2, ver3) + ) + data = handle.read(4) + if data != _null * 4: + raise ValueError("Did not find expected null four bytes in .srt index") + return ( + number_of_reads, + header_length, + index_offset, + index_length, + 0, + 0, + index_offset + fmt_size + 4, + index_length - fmt_size - 4, + ) + elif magic_number == _hsh: + raise ValueError( + "Hash table style indexes (.hsh) in SFF files are not (yet) supported" + ) + else: + raise ValueError( + f"Unknown magic number {magic_number!r} in SFF index header:\n{data!r}" + ) + + +def ReadRocheXmlManifest(handle): + """Read any Roche style XML manifest data in the SFF "index". + + The SFF file format allows for multiple different index blocks, and Roche + took advantage of this to define their own index block which also embeds + an XML manifest string. This is not a publicly documented extension to + the SFF file format, this was reverse engineered. + + The handle should be to an SFF file opened in binary mode. This function + will use the handle seek/tell functions and leave the handle in an + arbitrary location. + + Any XML manifest found is returned as a Python string, which you can then + parse as appropriate, or reuse when writing out SFF files with the + SffWriter class. + + Returns a string, or raises a ValueError if an Roche manifest could not be + found. + """ + ( + number_of_reads, + header_length, + index_offset, + index_length, + xml_offset, + xml_size, + read_index_offset, + read_index_size, + ) = _sff_find_roche_index(handle) + if not xml_offset or not xml_size: + raise ValueError("No XML manifest found") + handle.seek(xml_offset) + return handle.read(xml_size).decode() + + +# This is a generator function! +def _sff_read_roche_index(handle): + """Read any existing Roche style read index provided in the SFF file (PRIVATE). + + Will use the handle seek/tell functions. + + This works on ".srt1.00" and ".mft1.00" style Roche SFF index blocks. + + Roche SFF indices use base 255 not 256, meaning we see bytes in range the + range 0 to 254 only. This appears to be so that byte 0xFF (character 255) + can be used as a marker character to separate entries (required if the + read name lengths vary). + + Note that since only four bytes are used for the read offset, this is + limited to 255^4 bytes (nearly 4GB). If you try to use the Roche sfffile + tool to combine SFF files beyond this limit, they issue a warning and + omit the index (and manifest). + """ + ( + number_of_reads, + header_length, + index_offset, + index_length, + xml_offset, + xml_size, + read_index_offset, + read_index_size, + ) = _sff_find_roche_index(handle) + # Now parse the read index... + handle.seek(read_index_offset) + fmt = ">5B" + for read in range(number_of_reads): + # TODO - Be more aware of when the index should end? + data = handle.read(6) + while True: + more = handle.read(1) + if not more: + raise ValueError("Premature end of file!") + data += more + if more == _flag: + break + assert data[-1:] == _flag, data[-1:] + name = data[:-6].decode() + off4, off3, off2, off1, off0 = struct.unpack(fmt, data[-6:-1]) + offset = off0 + 255 * off1 + 65025 * off2 + 16581375 * off3 + if off4: + # Could in theory be used as a fifth piece of offset information, + # i.e. offset =+ 4228250625L*off4, but testing the Roche tools this + # is not the case. They simple don't support such large indexes. + raise ValueError("Expected a null terminator to the read name.") + yield name, offset + if handle.tell() != read_index_offset + read_index_size: + raise ValueError( + "Problem with index length? %i vs %i" + % (handle.tell(), read_index_offset + read_index_size) + ) + + +_valid_UAN_read_name = re.compile(r"^[a-zA-Z0-9]{14}$") + + +def _string_as_base_36(string): + """Interpret a string as a base-36 number as per 454 manual (PRIVATE).""" + total = 0 + for c, power in zip(string[::-1], _powers_of_36): + # For reference: ord('0') = 48, ord('9') = 57 + # For reference: ord('A') = 65, ord('Z') = 90 + # For reference: ord('a') = 97, ord('z') = 122 + if 48 <= ord(c) <= 57: + val = ord(c) - 22 # equivalent to: - ord('0') + 26 + elif 65 <= ord(c) <= 90: + val = ord(c) - 65 + elif 97 <= ord(c) <= 122: + val = ord(c) - 97 + else: + # Invalid character + val = 0 + total += val * power + return total + + +def _get_read_xy(read_name): + """Extract coordinates from last 5 characters of read name (PRIVATE).""" + number = _string_as_base_36(read_name[9:]) + return divmod(number, 4096) + + +_time_denominators = [ + 13 * 32 * 24 * 60 * 60, + 32 * 24 * 60 * 60, + 24 * 60 * 60, + 60 * 60, + 60, +] + + +def _get_read_time(read_name): + """Extract time from first 6 characters of read name (PRIVATE).""" + time_list = [] + remainder = _string_as_base_36(read_name[:6]) + for denominator in _time_denominators: + this_term, remainder = divmod(remainder, denominator) + time_list.append(this_term) + time_list.append(remainder) + time_list[0] += 2000 + return time_list + + +def _get_read_region(read_name): + """Extract region from read name (PRIVATE).""" + return int(read_name[8]) + + +def _sff_read_raw_record(handle, number_of_flows_per_read): + """Extract the next read in the file as a raw (bytes) string (PRIVATE).""" + read_header_fmt = ">2HI" + read_header_size = struct.calcsize(read_header_fmt) + read_flow_fmt = ">%iH" % number_of_flows_per_read + read_flow_size = struct.calcsize(read_flow_fmt) + + raw = handle.read(read_header_size) + read_header_length, name_length, seq_len = struct.unpack(read_header_fmt, raw) + if read_header_length < 10 or read_header_length % 8 != 0: + raise ValueError( + "Malformed read header, says length is %i" % read_header_length + ) + # now the four clip values (4H = 8 bytes), and read name + raw += handle.read(8 + name_length) + # and any padding (remainder of header) + padding = read_header_length - read_header_size - 8 - name_length + pad = handle.read(padding) + if pad.count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post name %i " + "byte padding region contained data" % padding, + BiopythonParserWarning, + ) + raw += pad + # now the flowgram values, flowgram index, bases and qualities + raw += handle.read(read_flow_size + seq_len * 3) + padding = (read_flow_size + seq_len * 3) % 8 + # now any padding... + if padding: + padding = 8 - padding + pad = handle.read(padding) + if pad.count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post quality %i " + "byte padding region contained data" % padding, + BiopythonParserWarning, + ) + raw += pad + # Return the raw bytes + return raw + + +class SffIterator(SequenceIterator): + """Parser for Standard Flowgram Format (SFF) files.""" + + modes = "b" + + # the read header format (fixed part): + # read_header_length H + # name_length H + # seq_len I + # clip_qual_left H + # clip_qual_right H + # clip_adapter_left H + # clip_adapter_right H + # [rest of read header depends on the name length etc] + read_header_fmt = ">2HI4H" + read_header_size = struct.calcsize(read_header_fmt) + assert read_header_size % 8 == 0 # Important for padding calc later! + + def __init__(self, source, alphabet=None, trim=False): + """Iterate over Standard Flowgram Format (SFF) reads (as SeqRecord objects). + + - source - path to an SFF file, e.g. from Roche 454 sequencing, + or a file-like object opened in binary mode. + - alphabet - optional alphabet, unused. Leave as None. + - trim - should the sequences be trimmed? + + The resulting SeqRecord objects should match those from a paired FASTA + and QUAL file converted from the SFF file using the Roche 454 tool + ssfinfo. i.e. The sequence will be mixed case, with the trim regions + shown in lower case. + + This function is used internally via the Bio.SeqIO functions: + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff"): + ... print("%s %i" % (record.id, len(record))) + ... + E3MFGYR02JWQ7T 265 + E3MFGYR02JA6IL 271 + E3MFGYR02JHD4H 310 + E3MFGYR02GFKUC 299 + E3MFGYR02FTGED 281 + E3MFGYR02FR9G7 261 + E3MFGYR02GAZMS 278 + E3MFGYR02HHZ8O 221 + E3MFGYR02GPGB1 269 + E3MFGYR02F7Z7G 219 + + You can also call it directly: + + >>> with open("Roche/E3MFGYR02_random_10_reads.sff", "rb") as handle: + ... for record in SffIterator(handle): + ... print("%s %i" % (record.id, len(record))) + ... + E3MFGYR02JWQ7T 265 + E3MFGYR02JA6IL 271 + E3MFGYR02JHD4H 310 + E3MFGYR02GFKUC 299 + E3MFGYR02FTGED 281 + E3MFGYR02FR9G7 261 + E3MFGYR02GAZMS 278 + E3MFGYR02HHZ8O 221 + E3MFGYR02GPGB1 269 + E3MFGYR02F7Z7G 219 + + Or, with the trim option: + + >>> with open("Roche/E3MFGYR02_random_10_reads.sff", "rb") as handle: + ... for record in SffIterator(handle, trim=True): + ... print("%s %i" % (record.id, len(record))) + ... + E3MFGYR02JWQ7T 260 + E3MFGYR02JA6IL 265 + E3MFGYR02JHD4H 292 + E3MFGYR02GFKUC 295 + E3MFGYR02FTGED 277 + E3MFGYR02FR9G7 256 + E3MFGYR02GAZMS 271 + E3MFGYR02HHZ8O 150 + E3MFGYR02GPGB1 221 + E3MFGYR02F7Z7G 130 + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source, fmt="SFF") + self.trim = trim + stream = self.stream + ( + self._offset, + self.index_offset, + self.index_length, + self.number_of_reads, + number_of_flows_per_read, + self.flow_chars, + self.key_sequence, + ) = _sff_file_header(stream) + # Now on to the reads... + self.read_flow_fmt = ">%iH" % number_of_flows_per_read + self.read_flow_size = struct.calcsize(self.read_flow_fmt) + self._read_counter = 0 + + def __next__(self): + stream = self.stream + if self._read_counter == self.number_of_reads: + self._read_counter = None # check EOF only once + self._check_eof(stream) + raise StopIteration + elif self._read_counter is None: + raise StopIteration + # The spec allows for the index block to be before or even in the middle + # of the reads. We can check that if we keep track of our position + # in the file... + index_offset = self.index_offset + if self._offset == index_offset: + index_length = self.index_length + offset = index_offset + index_length + if offset % 8: + offset += 8 - (offset % 8) + assert offset % 8 == 0 + stream.seek(offset) + self._offset = offset + record = self._sff_read_seq_record(self.stream) + self._read_counter += 1 + return record + + def _sff_read_seq_record(self, stream): + """Parse the next read in the file, return data as a SeqRecord (PRIVATE).""" + # Now on to the reads... + # the read header format (fixed part): + # read_header_length H + # name_length H + # seq_len I + # clip_qual_left H + # clip_qual_right H + # clip_adapter_left H + # clip_adapter_right H + # [rest of read header depends on the name length etc] + read_header_fmt = SffIterator.read_header_fmt + read_header_size = SffIterator.read_header_size + ( + read_header_length, + name_length, + seq_len, + clip_qual_left, + clip_qual_right, + clip_adapter_left, + clip_adapter_right, + ) = struct.unpack(read_header_fmt, stream.read(read_header_size)) + if clip_qual_left: + clip_qual_left -= 1 # python counting + if clip_adapter_left: + clip_adapter_left -= 1 # python counting + if read_header_length < 10 or read_header_length % 8 != 0: + raise ValueError( + "Malformed read header, says length is %i" % read_header_length + ) + # now the name and any padding (remainder of header) + name = stream.read(name_length).decode() + padding = read_header_length - read_header_size - name_length + if stream.read(padding).count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post name %i " + "byte padding region contained data" % padding, + BiopythonParserWarning, + ) + self._offset += read_header_length + # now the flowgram values, flowgram index, bases and qualities + # NOTE - assuming flowgram_format==1, which means struct type H + flow_values = stream.read(self.read_flow_size) # unpack later if needed + temp_fmt = ">%iB" % seq_len # used for flow index and quals + flow_index = stream.read(seq_len) # unpack later if needed + seq = stream.read(seq_len) # Leave as bytes for Seq object + quals = list(struct.unpack(temp_fmt, stream.read(seq_len))) + self._offset += self.read_flow_size + seq_len * 3 + # now any padding... + padding = (self.read_flow_size + seq_len * 3) % 8 + if padding: + padding = 8 - padding + if stream.read(padding).count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post quality %i " + "byte padding region contained data" % padding, + BiopythonParserWarning, + ) + self._offset += padding + # Follow Roche and apply most aggressive of qual and adapter clipping. + # Note Roche seems to ignore adapter clip fields when writing SFF, + # and uses just the quality clipping values for any clipping. + clip_left = max(clip_qual_left, clip_adapter_left) + # Right clipping of zero means no clipping + if clip_qual_right: + if clip_adapter_right: + clip_right = min(clip_qual_right, clip_adapter_right) + else: + # Typical case with Roche SFF files + clip_right = clip_qual_right + elif clip_adapter_right: + clip_right = clip_adapter_right + else: + clip_right = seq_len + # Now build a SeqRecord + if self.trim: + if clip_left >= clip_right: + # Raise an error? + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Overlapping clip values in SFF record, trimmed to nothing", + BiopythonParserWarning, + ) + seq = "" + quals = [] + else: + seq = seq[clip_left:clip_right].upper() + quals = quals[clip_left:clip_right] + # Don't record the clipping values, flow etc, they make no sense now: + annotations = {} + else: + if clip_left >= clip_right: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Overlapping clip values in SFF record", BiopythonParserWarning + ) + seq = seq.lower() + else: + # This use of mixed case mimics the Roche SFF tool's FASTA output + seq = ( + seq[:clip_left].lower() + + seq[clip_left:clip_right].upper() + + seq[clip_right:].lower() + ) + annotations = { + "flow_values": struct.unpack(self.read_flow_fmt, flow_values), + "flow_index": struct.unpack(temp_fmt, flow_index), + "flow_chars": self.flow_chars, + "flow_key": self.key_sequence, + "clip_qual_left": clip_qual_left, + "clip_qual_right": clip_qual_right, + "clip_adapter_left": clip_adapter_left, + "clip_adapter_right": clip_adapter_right, + } + if re.match(_valid_UAN_read_name, name): + annotations["time"] = _get_read_time(name) + annotations["region"] = _get_read_region(name) + annotations["coords"] = _get_read_xy(name) + annotations["molecule_type"] = "DNA" + # Avoids type and length checks + record = SeqRecord._from_validated( + Seq(seq), + id=name, + name=name, + description="", + annotations=annotations, + letter_annotations={"phred_quality": quals}, + ) + # Return the record and then continue... + return record + + def _check_eof(self, stream): + """Check final padding is OK (8 byte alignment) and file ends (PRIVATE). + + Will attempt to spot apparent SFF file concatenation and give an error. + + Will not attempt to seek, only moves the stream forward. + """ + offset = self._offset + extra = b"" + padding = 0 + + index_offset = self.index_offset + index_length = self.index_length + if index_offset and offset <= index_offset: + # Index block then end of file... + if offset < index_offset: + raise ValueError( + "Gap of %i bytes after final record end %i, " + "before %i where index starts?" + % (index_offset - offset, offset, index_offset) + ) + # Doing read to jump the index rather than a seek + # in case this is a network handle or similar + stream.read(index_length) + self._offset += index_length + offset = index_offset + index_length + if offset != self._offset: + raise ValueError( + "Wanted %i, got %i, index is %i to %i" + % (offset, stream.tell(), index_offset, index_offset + index_length) + ) + + if offset % 8: + padding = 8 - (offset % 8) + extra = stream.read(padding) + self._offset += padding + + if padding >= 4 and extra[-4:] == _sff: + # Seen this in one user supplied file, should have been + # four bytes of null padding but was actually .sff and + # the start of a new concatenated SFF file! + raise ValueError( + "Your SFF file is invalid, post index %i byte " + "null padding region ended '.sff' which could " + "be the start of a concatenated SFF file? " + "See offset %i" % (padding, offset) + ) + if padding and not extra: + # TODO - Is this error harmless enough to just ignore? + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is technically invalid as it is missing " + "a terminal %i byte null padding region." % padding, + BiopythonParserWarning, + ) + return + if extra.count(_null) != padding: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "Your SFF file is invalid, post index %i byte " + "null padding region contained data: %r" % (padding, extra), + BiopythonParserWarning, + ) + + offset = self._offset + if offset % 8 != 0: + raise ValueError( + "Wanted offset %i %% 8 = %i to be zero" % (offset, offset % 8) + ) + # Should now be at the end of the file... + extra = stream.read(4) + self._offset += 4 + if extra == _sff: + raise ValueError( + "Additional data at end of SFF file, " + "perhaps multiple SFF files concatenated? " + "See offset %i" % offset + ) + elif extra: + raise ValueError( + "Additional data at end of SFF file, see offset %i" % offset + ) + + +_powers_of_36 = [36**i for i in range(6)] + + +class _SffTrimIterator(SffIterator): + """Iterate over SFF reads (as SeqRecord objects) with trimming (PRIVATE).""" + + def __init__(self, source): + super().__init__(source, trim=True) + + +class SffWriter(SequenceWriter): + """SFF file writer.""" + + modes = "b" + + def __init__(self, target, index=True, xml=None): + """Initialize an SFF writer object. + + Arguments: + - target - Output stream opened in binary mode, or a path to a file. + - index - Boolean argument, should we try and write an index? + - xml - Optional string argument, xml manifest to be recorded + in the index block (see function ReadRocheXmlManifest for + reading this data). + + """ + super().__init__(target) + self._xml = xml + if index: + self._index = [] + else: + self._index = None + + def write_records(self, records): + """Write records to the output file, and return the number of records. + + records - A list or iterator returning SeqRecord objects + """ + try: + self._number_of_reads = len(records) + except TypeError: + self._number_of_reads = 0 # dummy value + if not hasattr(self.handle, "seek") or not hasattr(self.handle, "tell"): + raise ValueError( + "A handle with a seek/tell methods is required in order " + "to record the total record count in the file header " + "(once it is known at the end)." + ) from None + if self._index is not None and not ( + hasattr(self.handle, "seek") and hasattr(self.handle, "tell") + ): + import warnings + + warnings.warn( + "A handle with a seek/tell methods is required in " + "order to record an SFF index." + ) + self._index = None + self._index_start = 0 + self._index_length = 0 + if not hasattr(records, "next"): + records = iter(records) + # Get the first record in order to find the flow information + # we will need for the header. + try: + record = next(records) + except StopIteration: + record = None + if record is None: + # No records -> empty SFF file (or an error)? + # We can't write a header without the flow information. + # return 0 + raise ValueError("Must have at least one sequence") + try: + self._key_sequence = record.annotations["flow_key"].encode("ASCII") + self._flow_chars = record.annotations["flow_chars"].encode("ASCII") + self._number_of_flows_per_read = len(self._flow_chars) + except KeyError: + raise ValueError("Missing SFF flow information") from None + self.write_header() + self.write_record(record) + count = 1 + for record in records: + self.write_record(record) + count += 1 + if self._number_of_reads == 0: + # Must go back and record the record count... + offset = self.handle.tell() + self.handle.seek(0) + self._number_of_reads = count + self.write_header() + self.handle.seek(offset) # not essential? + else: + assert count == self._number_of_reads + if self._index is not None: + self._write_index() + return count + + def _write_index(self): + assert len(self._index) == self._number_of_reads + handle = self.handle + self._index.sort() + self._index_start = handle.tell() # need for header + # XML... + if self._xml is not None: + xml = self._xml.encode() + else: + from Bio import __version__ + + xml = f"\n" + xml += ( + "\n" + ) + xml += "\n" + xml = xml.encode() + xml_len = len(xml) + # Write to the file... + fmt = ">I4BLL" + fmt_size = struct.calcsize(fmt) + handle.write(_null * fmt_size + xml) # fill this later + fmt2 = ">6B" + assert 6 == struct.calcsize(fmt2) + self._index.sort() + index_len = 0 # don't know yet! + for name, offset in self._index: + # Roche files record the offsets using base 255 not 256. + # See comments for parsing the index block. There may be a faster + # way to code this, but we can't easily use shifts due to odd base + off3 = offset + off0 = off3 % 255 + off3 -= off0 + off1 = off3 % 65025 + off3 -= off1 + off2 = off3 % 16581375 + off3 -= off2 + if offset != off0 + off1 + off2 + off3: + raise RuntimeError( + "%i -> %i %i %i %i" % (offset, off0, off1, off2, off3) + ) + off3, off2, off1, off0 = ( + off3 // 16581375, + off2 // 65025, + off1 // 255, + off0, + ) + if not (off0 < 255 and off1 < 255 and off2 < 255 and off3 < 255): + raise RuntimeError( + "%i -> %i %i %i %i" % (offset, off0, off1, off2, off3) + ) + handle.write(name + struct.pack(fmt2, 0, off3, off2, off1, off0, 255)) + index_len += len(name) + 6 + # Note any padding in not included: + self._index_length = fmt_size + xml_len + index_len # need for header + # Pad out to an 8 byte boundary (although I have noticed some + # real Roche SFF files neglect to do this depsite their manual + # suggesting this padding should be there): + if self._index_length % 8: + padding = 8 - (self._index_length % 8) + handle.write(_null * padding) + else: + padding = 0 + offset = handle.tell() + if offset != self._index_start + self._index_length + padding: + raise RuntimeError( + "%i vs %i + %i + %i" + % (offset, self._index_start, self._index_length, padding) + ) + # Must now go back and update the index header with index size... + handle.seek(self._index_start) + handle.write( + struct.pack( + fmt, + 778921588, # magic number + 49, + 46, + 48, + 48, # Roche index version, "1.00" + xml_len, + index_len, + ) + + xml + ) + # Must now go back and update the header... + handle.seek(0) + self.write_header() + handle.seek(offset) # not essential? + + def write_header(self): + """Write the SFF file header.""" + # Do header... + key_length = len(self._key_sequence) + # file header (part one) + # use big endiean encdoing > + # magic_number I + # version 4B + # index_offset Q + # index_length I + # number_of_reads I + # header_length H + # key_length H + # number_of_flows_per_read H + # flowgram_format_code B + # [rest of file header depends on the number of flows and how many keys] + fmt = ">I4BQIIHHHB%is%is" % (self._number_of_flows_per_read, key_length) + # According to the spec, the header_length field should be the total + # number of bytes required by this set of header fields, and should be + # equal to "31 + number_of_flows_per_read + key_length" rounded up to + # the next value divisible by 8. + if struct.calcsize(fmt) % 8 == 0: + padding = 0 + else: + padding = 8 - (struct.calcsize(fmt) % 8) + header_length = struct.calcsize(fmt) + padding + assert header_length % 8 == 0 + header = struct.pack( + fmt, + 779314790, # magic number 0x2E736666 + 0, + 0, + 0, + 1, # version + self._index_start, + self._index_length, + self._number_of_reads, + header_length, + key_length, + self._number_of_flows_per_read, + 1, # the only flowgram format code we support + self._flow_chars, + self._key_sequence, + ) + self.handle.write(header + _null * padding) + + def write_record(self, record): + """Write a single additional record to the output file. + + This assumes the header has been done. + """ + # Basics + name = record.id.encode() + name_len = len(name) + seq = bytes(record.seq).upper() + seq_len = len(seq) + # Qualities + try: + quals = record.letter_annotations["phred_quality"] + except KeyError: + raise ValueError( + f"Missing PHRED qualities information for {record.id}" + ) from None + # Flow + try: + flow_values = record.annotations["flow_values"] + flow_index = record.annotations["flow_index"] + if ( + self._key_sequence != record.annotations["flow_key"].encode() + or self._flow_chars != record.annotations["flow_chars"].encode() + ): + raise ValueError("Records have inconsistent SFF flow data") + except KeyError: + raise ValueError(f"Missing SFF flow information for {record.id}") from None + except AttributeError: + raise ValueError("Header not written yet?") from None + # Clipping + try: + clip_qual_left = record.annotations["clip_qual_left"] + if clip_qual_left < 0: + raise ValueError(f"Negative SFF clip_qual_left value for {record.id}") + if clip_qual_left: + clip_qual_left += 1 + clip_qual_right = record.annotations["clip_qual_right"] + if clip_qual_right < 0: + raise ValueError(f"Negative SFF clip_qual_right value for {record.id}") + clip_adapter_left = record.annotations["clip_adapter_left"] + if clip_adapter_left < 0: + raise ValueError( + f"Negative SFF clip_adapter_left value for {record.id}" + ) + if clip_adapter_left: + clip_adapter_left += 1 + clip_adapter_right = record.annotations["clip_adapter_right"] + if clip_adapter_right < 0: + raise ValueError( + f"Negative SFF clip_adapter_right value for {record.id}" + ) + except KeyError: + raise ValueError( + f"Missing SFF clipping information for {record.id}" + ) from None + + # Capture information for index + if self._index is not None: + offset = self.handle.tell() + # Check the position of the final record (before sort by name) + # Using a four-digit base 255 number, so the upper bound is + # 254*(1)+254*(255)+254*(255**2)+254*(255**3) = 4228250624 + # or equivalently it overflows at 255**4 = 4228250625 + if offset > 4228250624: + import warnings + + warnings.warn( + "Read %s has file offset %i, which is too large " + "to store in the Roche SFF index structure. No " + "index block will be recorded." % (name, offset) + ) + # No point recoring the offsets now + self._index = None + else: + self._index.append((name, self.handle.tell())) + + # the read header format (fixed part): + # read_header_length H + # name_length H + # seq_len I + # clip_qual_left H + # clip_qual_right H + # clip_adapter_left H + # clip_adapter_right H + # [rest of read header depends on the name length etc] + # name + # flow values + # flow index + # sequence + # padding + read_header_fmt = ">2HI4H%is" % name_len + if struct.calcsize(read_header_fmt) % 8 == 0: + padding = 0 + else: + padding = 8 - (struct.calcsize(read_header_fmt) % 8) + read_header_length = struct.calcsize(read_header_fmt) + padding + assert read_header_length % 8 == 0 + data = ( + struct.pack( + read_header_fmt, + read_header_length, + name_len, + seq_len, + clip_qual_left, + clip_qual_right, + clip_adapter_left, + clip_adapter_right, + name, + ) + + _null * padding + ) + assert len(data) == read_header_length + # now the flowgram values, flowgram index, bases and qualities + # NOTE - assuming flowgram_format==1, which means struct type H + read_flow_fmt = ">%iH" % self._number_of_flows_per_read + read_flow_size = struct.calcsize(read_flow_fmt) + temp_fmt = ">%iB" % seq_len # used for flow index and quals + data += ( + struct.pack(read_flow_fmt, *flow_values) + + struct.pack(temp_fmt, *flow_index) + + seq + + struct.pack(temp_fmt, *quals) + ) + # now any final padding... + padding = (read_flow_size + seq_len * 3) % 8 + if padding: + padding = 8 - padding + self.handle.write(data + _null * padding) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SnapGeneIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SnapGeneIO.py new file mode 100644 index 0000000000000000000000000000000000000000..4da6d3c7673a85619930be3dd89ee008d81818bf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SnapGeneIO.py @@ -0,0 +1,355 @@ +# Copyright 2017-2019 Damien Goutte-Gattat. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the SnapGene file format. + +The SnapGene binary format is the native format used by the SnapGene program +from GSL Biotech LLC. +""" + +from datetime import datetime +from re import sub +from struct import unpack +from xml.dom.minidom import parseString + +from Bio.Seq import Seq +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator + + +def _iterate(handle): + """Iterate over the packets of a SnapGene file. + + A SnapGene file is made of packets, each packet being a TLV-like + structure comprising: + + - 1 single byte indicating the packet's type; + - 1 big-endian long integer (4 bytes) indicating the length of the + packet's data; + - the actual data. + """ + while True: + packet_type = handle.read(1) + if len(packet_type) < 1: # No more packet + return + packet_type = unpack(">B", packet_type)[0] + + length = handle.read(4) + if len(length) < 4: + raise ValueError("Unexpected end of packet") + length = unpack(">I", length)[0] + + data = handle.read(length) + if len(data) < length: + raise ValueError("Unexpected end of packet") + + yield (packet_type, length, data) + + +def _parse_dna_packet(length, data, record): + """Parse a DNA sequence packet. + + A DNA sequence packet contains a single byte flag followed by the + sequence itself. + """ + if record.seq: + raise ValueError("The file contains more than one DNA packet") + + flags, sequence = unpack(">B%ds" % (length - 1), data) + record.seq = Seq(sequence.decode("ASCII")) + record.annotations["molecule_type"] = "DNA" + if flags & 0x01: + record.annotations["topology"] = "circular" + else: + record.annotations["topology"] = "linear" + + +def _parse_notes_packet(length, data, record): + """Parse a 'Notes' packet. + + This type of packet contains some metadata about the sequence. They + are stored as a XML string with a 'Notes' root node. + """ + xml = parseString(data.decode("UTF-8")) + type = _get_child_value(xml, "Type") + if type == "Synthetic": + record.annotations["data_file_division"] = "SYN" + else: + record.annotations["data_file_division"] = "UNC" + + date = _get_child_value(xml, "LastModified") + if date: + record.annotations["date"] = datetime.strptime(date, "%Y.%m.%d") + + acc = _get_child_value(xml, "AccessionNumber") + if acc: + record.id = acc + + comment = _get_child_value(xml, "Comments") + if comment: + record.name = comment.split(" ", 1)[0] + record.description = comment + if not acc: + record.id = record.name + + +def _parse_cookie_packet(length, data): + """Parse a SnapGene cookie packet. + + Every SnapGene file starts with a packet of this type. It acts as + a magic cookie identifying the file as a SnapGene file. + """ + cookie, seq_type, exp_version, imp_version = unpack(">8sHHH", data) + if cookie.decode("ASCII") != "SnapGene": + raise ValueError("The file is not a valid SnapGene file") + + +def _parse_location(rangespec, strand, record, is_primer=False): + start, end = (int(x) for x in rangespec.split("-")) + # Account for SnapGene's 1-based coordinates + start = start - 1 + if is_primer: + # Primers' coordinates in SnapGene files are shifted by -1 + # for some reasons + start += 1 + end += 1 + if start >= end: + # Range wrapping the end of the sequence + l1 = SimpleLocation(start, len(record), strand=strand) + l2 = SimpleLocation(0, end, strand=strand) + location = l1 + l2 + else: + location = SimpleLocation(start, end, strand=strand) + return location + + +def _parse_features_packet(length, data, record): + """Parse a sequence features packet. + + This packet stores sequence features (except primer binding sites, + which are in a dedicated Primers packet). The data is a XML string + starting with a 'Features' root node. + """ + xml = parseString(data.decode("UTF-8")) + for feature in xml.getElementsByTagName("Feature"): + quals = {} + + type = _get_attribute_value(feature, "type", default="misc_feature") + + strand = +1 + directionality = int( + _get_attribute_value(feature, "directionality", default="1") + ) + if directionality == 2: + strand = -1 + + location = None + subparts = [] + n_parts = 0 + for segment in feature.getElementsByTagName("Segment"): + if _get_attribute_value(segment, "type", "standard") == "gap": + continue + rng = _get_attribute_value(segment, "range") + n_parts += 1 + next_location = _parse_location(rng, strand, record) + if location is None: + location = next_location + elif strand == -1: + # Reverse segments order for reverse-strand features + location = next_location + location + else: + location = location + next_location + + name = _get_attribute_value(segment, "name") + if name: + subparts.append([n_parts, name]) + + if len(subparts) > 0: + # Add a "parts" qualifiers to represent "named subfeatures" + if strand == -1: + # Reverse segment indexes and order for reverse-strand features + subparts = reversed([[n_parts - i + 1, name] for i, name in subparts]) + quals["parts"] = [";".join(f"{i}:{name}" for i, name in subparts)] + + if not location: + raise ValueError("Missing feature location") + + for qualifier in feature.getElementsByTagName("Q"): + qname = _get_attribute_value( + qualifier, "name", error="Missing qualifier name" + ) + qvalues = [] + for value in qualifier.getElementsByTagName("V"): + if value.hasAttribute("text"): + qvalues.append(_decode(value.attributes["text"].value)) + elif value.hasAttribute("predef"): + qvalues.append(_decode(value.attributes["predef"].value)) + elif value.hasAttribute("int"): + qvalues.append(int(value.attributes["int"].value)) + # Remove linebreaks that may mess up formatting to GenBank + qvalues = [ + sub(r"\r\n|\r|\n", " ", v).strip() if isinstance(v, str) else v + for v in qvalues + ] + quals[qname] = qvalues + + name = _get_attribute_value(feature, "name") + if name: + if "label" not in quals: + # No explicit label attribute, use the SnapGene name + quals["label"] = [name] + elif name not in quals["label"]: + # The SnapGene name is different from the label, + # add a specific attribute to represent it + quals["name"] = [name] + + feature = SeqFeature(location, type=type, qualifiers=quals) + record.features.append(feature) + + +def _parse_primers_packet(length, data, record): + """Parse a Primers packet. + + A Primers packet is similar to a Features packet but specifically + stores primer binding features. The data is a XML string starting + with a 'Primers' root node. + + Within the Primers packet, a primer can have multiple BindingSite + elements. However, not all of them are shown to the user when the file is + opened SnapGene. This seems to depend on the HybridizationParams element, which + stores a minimal hybridization length and Tm. When a SnapGene file is parsed, + `primer_bind` features that do not meet the hybridization parameters are dropped, + since they are not shown to the user when the file is opened in SnapGene. + For more details, see #5053. + """ + xml = parseString(data.decode("UTF-8")) + min_match_length = 0 + min_melting_temp = 0 + for param in xml.getElementsByTagName("HybridizationParams"): + min_match_length = int( + _get_attribute_value(param, "minContinuousMatchLen", default="0") + ) + min_melting_temp = int( + _get_attribute_value(param, "minMeltingTemperature", default="0") + ) + for primer in xml.getElementsByTagName("Primer"): + quals = {} + + name = _get_attribute_value(primer, "name") + if name: + quals["label"] = [name] + + locations = [] + for site in primer.getElementsByTagName("BindingSite"): + rng = _get_attribute_value( + site, "location", error="Missing binding site location" + ) + strand = int(_get_attribute_value(site, "boundStrand", default="0")) + if strand == 1: + strand = -1 + else: + strand = +1 + + location = _parse_location(rng, strand, record, is_primer=True) + simplified = int(_get_attribute_value(site, "simplified", default="0")) == 1 + if simplified and location in locations: + # Duplicate "simplified" binding site, ignore + continue + annealed = _get_attribute_value(site, "annealedBases") + if annealed is not None and len(annealed) < min_match_length: + continue + melting_temp = _get_attribute_value(site, "meltingTemperature") + if melting_temp is not None and int(melting_temp) < min_melting_temp: + continue + + locations.append(location) + feature = SeqFeature( + location, + type="primer_bind", + qualifiers=quals, + ) + record.features.append(feature) + + +_packet_handlers = { + 0x00: _parse_dna_packet, + 0x05: _parse_primers_packet, + 0x06: _parse_notes_packet, + 0x0A: _parse_features_packet, +} + +# Helper functions to process the XML data in +# some of the segments + + +def _decode(text): + # Get rid of HTML tags in some values + return sub("<[^>]+>", "", text) + + +def _get_attribute_value(node, name, default=None, error=None): + if node.hasAttribute(name): + return _decode(node.attributes[name].value) + elif error: + raise ValueError(error) + else: + return default + + +def _get_child_value(node, name, default=None, error=None): + children = node.getElementsByTagName(name) + if ( + children + and children[0].childNodes + and children[0].firstChild.nodeType == node.TEXT_NODE + ): + return _decode(children[0].firstChild.data) + elif error: + raise ValueError(error) + else: + return default + + +class SnapGeneIterator(SequenceIterator): + """Parser for SnapGene files.""" + + modes = "b" + + def __init__(self, source): + """Parse a SnapGene file and return a SeqRecord object. + + Argument source is a file-like object or a path to a file. + + Note that a SnapGene file can only contain one sequence, so this + iterator will always return a single record. + """ + super().__init__(source, fmt="SnapGene") + self.packets = _iterate(self.stream) + try: + packet_type, length, data = next(self.packets) + except StopIteration: + raise ValueError("Empty file.") from None + if packet_type != 0x09: + raise ValueError("The file does not start with a SnapGene cookie packet") + _parse_cookie_packet(length, data) + + def __next__(self): + packets = self.packets + if packets is None: + raise StopIteration + record = SeqRecord(None) + for packet in packets: + packet_type, length, data = packet + handler = _packet_handlers.get(packet_type) + if handler is not None: + handler(length, data, record) + if not record.seq: + raise ValueError("No DNA packet in file") + self.packets = None # A SnapGene file contains only one sequence + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SwissIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SwissIO.py new file mode 100644 index 0000000000000000000000000000000000000000..b432b70dddc215f2910e685f93a477de4fdb0c36 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/SwissIO.py @@ -0,0 +1,123 @@ +# Copyright 2006-2013,2020 by Peter Cock. +# Revisions copyright 2008-2009 by Michiel de Hoon. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "swiss" (aka SwissProt/UniProt) file format. + +You are expected to use this module via the Bio.SeqIO functions. +See also the Bio.SwissProt module which offers more than just accessing +the sequences as SeqRecord objects. + +See also Bio.SeqIO.UniprotIO.py which supports the "uniprot-xml" format. +""" + +from Bio import SeqFeature +from Bio import SwissProt +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import _TextIOSource +from .Interfaces import SequenceIterator + + +class SwissIterator(SequenceIterator): + """Parser to break up a Swiss-Prot/UniProt file into SeqRecord objects.""" + + modes = "t" + + def __init__(self, source: _TextIOSource) -> None: + """Iterate over a Swiss-Prot file and return SeqRecord objects. + + Arguments: + - source - input stream opened in text mode, or a path to a file + + Every section from the ID line to the terminating // becomes + a single SeqRecord with associated annotation and features. + + This parser is for the flat file "swiss" format as used by: + - Swiss-Prot aka SwissProt + - TrEMBL + - UniProtKB aka UniProt Knowledgebase + + For consistency with BioPerl and EMBOSS we call this the "swiss" + format. See also the SeqIO support for "uniprot-xml" format. + + Rather than calling it directly, you are expected to use this + parser via Bio.SeqIO.parse(..., format="swiss") instead. + """ + super().__init__(source, fmt="SwissProt") + + def __next__(self): + swiss_record = SwissProt._read(self.stream) + if swiss_record is None: + raise StopIteration + # Convert the SwissProt record to a SeqRecord + record = SeqRecord( + Seq(swiss_record.sequence), + id=swiss_record.accessions[0], + name=swiss_record.entry_name, + description=swiss_record.description, + features=swiss_record.features, + ) + for cross_reference in swiss_record.cross_references: + if len(cross_reference) < 2: + continue + database, accession = cross_reference[:2] + dbxref = f"{database}:{accession}" + if dbxref not in record.dbxrefs: + record.dbxrefs.append(dbxref) + annotations = record.annotations + annotations["molecule_type"] = "protein" + annotations["accessions"] = swiss_record.accessions + if swiss_record.protein_existence: + annotations["protein_existence"] = swiss_record.protein_existence + if swiss_record.created: + date, version = swiss_record.created + annotations["date"] = date + annotations["sequence_version"] = version + if swiss_record.sequence_update: + date, version = swiss_record.sequence_update + annotations["date_last_sequence_update"] = date + annotations["sequence_version"] = version + if swiss_record.annotation_update: + date, version = swiss_record.annotation_update + annotations["date_last_annotation_update"] = date + annotations["entry_version"] = version + if swiss_record.gene_name: + annotations["gene_name"] = swiss_record.gene_name + annotations["organism"] = swiss_record.organism.rstrip(".") + annotations["taxonomy"] = swiss_record.organism_classification + annotations["ncbi_taxid"] = swiss_record.taxonomy_id + if swiss_record.host_organism: + annotations["organism_host"] = swiss_record.host_organism + if swiss_record.host_taxonomy_id: + annotations["host_ncbi_taxid"] = swiss_record.host_taxonomy_id + if swiss_record.comments: + annotations["comment"] = "\n".join(swiss_record.comments) + if swiss_record.references: + annotations["references"] = [] + for reference in swiss_record.references: + feature = SeqFeature.Reference() + feature.comment = " ".join("%s=%s;" % k_v for k_v in reference.comments) + for key, value in reference.references: + if key == "PubMed": + feature.pubmed_id = value + elif key == "MEDLINE": + feature.medline_id = value + elif key == "DOI": + pass + elif key == "AGRICOLA": + pass + else: + raise ValueError(f"Unknown key {key} found in references") + feature.authors = reference.authors + feature.title = reference.title + feature.journal = reference.location + annotations["references"].append(feature) + if swiss_record.keywords: + record.annotations["keywords"] = swiss_record.keywords + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/TabIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/TabIO.py new file mode 100644 index 0000000000000000000000000000000000000000..5bebc94b573b53285bdbffc86cb8b19900359312 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/TabIO.py @@ -0,0 +1,157 @@ +# Copyright 2008-2017,2020 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "tab" (simple tab separated) file format. + +You are expected to use this module via the Bio.SeqIO functions. + +The "tab" format is an ad-hoc plain text file format where each sequence is +on one (long) line. Each line contains the identifier/description, followed +by a tab, followed by the sequence. For example, consider the following +short FASTA format file:: + + >ID123456 possible binding site? + CATCNAGATGACACTACGACTACGACTCAGACTAC + >ID123457 random sequence + ACACTACGACTACGACTCAGACTACAAN + +Apart from the descriptions, this can be represented in the simple two column +tab separated format as follows:: + + ID123456(tab)CATCNAGATGACACTACGACTACGACTCAGACTAC + ID123457(tab)ACACTACGACTACGACTCAGACTACAAN + +When reading this file, "ID123456" or "ID123457" will be taken as the record's +.id and .name property. There is no other information to record. + +Similarly, when writing to this format, Biopython will ONLY record the record's +.id and .seq (and not the description or any other information) as in the +example above. +""" + +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord +from Bio import BiopythonDeprecationWarning + +from .Interfaces import _clean +from .Interfaces import _get_seq_string +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +import warnings + + +class TabIterator(SequenceIterator): + """Parser for tab-delimited files.""" + + modes = "t" + + def __init__(self, source): + """Iterate over tab separated lines as SeqRecord objects. + + Each line of the file should contain one tab only, dividing the line + into an identifier and the full sequence. + + Arguments: + - source - file-like object opened in text mode, or a path to a file + + The first field is taken as the record's .id and .name (regardless of + any spaces within the text) and the second field is the sequence. + + Any blank lines are ignored. + + Examples + -------- + >>> with open("GenBank/NC_005816.tsv") as handle: + ... for record in TabIterator(handle): + ... print("%s length %i" % (record.id, len(record))) + gi|45478712|ref|NP_995567.1| length 340 + gi|45478713|ref|NP_995568.1| length 260 + gi|45478714|ref|NP_995569.1| length 64 + gi|45478715|ref|NP_995570.1| length 123 + gi|45478716|ref|NP_995571.1| length 145 + gi|45478717|ref|NP_995572.1| length 357 + gi|45478718|ref|NP_995573.1| length 138 + gi|45478719|ref|NP_995574.1| length 312 + gi|45478720|ref|NP_995575.1| length 99 + gi|45478721|ref|NP_995576.1| length 90 + + """ + super().__init__(source, fmt="Tab-separated plain-text") + + def __next__(self): + for line in self.stream: + try: + title, seq = line.split("\t") # will fail if more than one tab! + except ValueError: + if line.strip() == "": + # It's a blank line, ignore it + continue + raise ValueError( + "Each line should have one tab separating the" + + " title and sequence, this line has %i tabs: %r" + % (line.count("\t"), line) + ) from None + title = title.strip() + seq = seq.strip() # removes the trailing new line + return SeqRecord(Seq(seq), id=title, name=title, description="") + raise StopIteration + + +class TabWriter(SequenceWriter): + """Class to write simple tab separated format files. + + Each line consists of "id(tab)sequence" only. + + Any description, name or other annotation is not recorded. + + This class is not intended to be used directly. Instead, please use + the top level ``Bio.SeqIO.write()`` function with ``format="tab"``. + """ + + modes = "t" + + @classmethod + def to_string(cls, record): + """Return record as tab separated (id(tab)seq) string.""" + title = _clean(record.id) + seq = _get_seq_string(record) # Catches sequence being None + assert "\t" not in title + assert "\n" not in title + assert "\r" not in title + assert "\t" not in seq + assert "\n" not in seq + assert "\r" not in seq + return f"{title}\t{seq}\n" + + def write_record(self, record): + """Write a single tab line to the file.""" + self.handle.write(self.to_string(record)) + + +def as_tab(record): + """Return record as tab separated (id(tab)seq) string.""" + warnings.warn( + """\ +TabIO.as_tab is deprecated. + +Instead of + +TabIO.as_tab(record) + +please use + +format(record, "tab") +""", + DeprecationWarning, + ) + return TabWriter.to_string(record) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/TwoBitIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/TwoBitIO.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1727ce38c1bc3674a837dbaa4838d4af597aa0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/TwoBitIO.py @@ -0,0 +1,263 @@ +# Copyright 2020 by Michiel de Hoon +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for UCSC's "twoBit" (.2bit) file format. + +This parser reads the index stored in the twoBit file, as well as the masked +regions and the N's for each sequence. It also creates sequence data objects +(_TwoBitSequenceData objects), which support only two methods: __len__ and +__getitem__. The former will return the length of the sequence, while the +latter returns the sequence (as a bytes object) for the requested region. + +Using the information in the index, the __getitem__ method calculates the file +position at which the requested region starts, and only reads the requested +sequence region. Note that the full sequence of a record is loaded only if +specifically requested, making the parser memory-efficient. + +The TwoBitIterator object implements the __getitem__, keys, and __len__ +methods that allow it to be used as a dictionary. +""" + +# The .2bit file format is defined by UCSC as follows +# (see http://genome.ucsc.edu/FAQ/FAQformat.html#format7): +# +# +# A .2bit file stores multiple DNA sequences (up to 4 Gb total) in a compact +# randomly-accessible format. The file contains masking information as well +# as the DNA itself. +# +# The file begins with a 16-byte header containing the following fields: +# +# signature - the number 0x1A412743 in the architecture of the machine that +# created the file +# version - zero for now. Readers should abort if they see a version number +# higher than 0 +# sequenceCount - the number of sequences in the file +# reserved - always zero for now +# +# All fields are 32 bits unless noted. If the signature value is not as +# given, the reader program should byte-swap the signature and check if the +# swapped version matches. If so, all multiple-byte entities in the file +# will have to be byte-swapped. This enables these binary files to be used +# unchanged on different architectures. +# +# The header is followed by a file index, which contains one entry for each +# sequence. Each index entry contains three fields: +# +# nameSize - a byte containing the length of the name field +# name - the sequence name itself (in ASCII-compatible byte string), of +# variable length depending on nameSize +# offset - the 32-bit offset of the sequence data relative to the start of +# the file, not aligned to any 4-byte padding boundary +# +# The index is followed by the sequence records, which contain nine fields: +# +# dnaSize - number of bases of DNA in the sequence +# nBlockCount - the number of blocks of Ns in the file (representing unknown +# sequence) +# nBlockStarts - an array of length nBlockCount of 32 bit integers +# indicating the (0-based) starting position of a block of Ns +# nBlockSizes - an array of length nBlockCount of 32 bit integers indicating +# the length of a block of Ns +# maskBlockCount - the number of masked (lower-case) blocks +# maskBlockStarts - an array of length maskBlockCount of 32 bit integers +# indicating the (0-based) starting position of a masked block +# maskBlockSizes - an array of length maskBlockCount of 32 bit integers +# indicating the length of a masked block +# reserved - always zero for now +# packedDna - the DNA packed to two bits per base, represented as so: +# T - 00, C - 01, A - 10, G - 11. The first base is in the most +# significant 2-bit byte; the last base is in the least significant +# 2 bits. For example, the sequence TCAG is represented as 00011011. +try: + import numpy as np +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install NumPy if you want to use Bio.SeqIO with TwoBit files." + "See http://www.numpy.org/" + ) from None + +from Bio.Seq import Seq +from Bio.Seq import SequenceDataAbstractBaseClass +from Bio.SeqRecord import SeqRecord + +from . import _twoBitIO # type: ignore +from .Interfaces import SequenceIterator + + +class _TwoBitSequenceData(SequenceDataAbstractBaseClass): + """Stores information needed to retrieve sequence data from a .2bit file (PRIVATE). + + Objects of this class store the file position at which the sequence data + start, the sequence length, and the start and end position of unknown (N) + and masked (lowercase) letters in the sequence. + + Only two methods are provided: __len__ and __getitem__. The former will + return the length of the sequence, while the latter returns the sequence + (as a bytes object) for the requested region. The full sequence of a record + is loaded only if explicitly requested. + """ + + __slots__ = ("stream", "offset", "length", "nBlocks", "maskBlocks") + + def __init__(self, stream, offset, length): + """Initialize the file stream and file position of the sequence data.""" + self.stream = stream + self.offset = offset + self.length = length + super().__init__() + + def __getitem__(self, key): + """Return the sequence contents (as a bytes object) for the requested region.""" + length = self.length + if isinstance(key, slice): + start, end, step = key.indices(length) + size = len(range(start, end, step)) + if size == 0: + return b"" + else: + if key < 0: + key += length + if key < 0: + raise IndexError("index out of range") + start = key + end = key + 1 + step = 1 + size = 1 + byteStart = start // 4 + byteEnd = (end + 3) // 4 + byteSize = byteEnd - byteStart + stream = self.stream + try: + stream.seek(self.offset + byteStart) + except ValueError as exception: + if str(exception) == "seek of closed file": + raise ValueError("cannot retrieve sequence: file is closed") from None + raise + data = np.fromfile(stream, dtype="uint8", count=byteSize) + sequence = _twoBitIO.convert( + data, start, end, step, self.nBlocks, self.maskBlocks + ) + if isinstance(key, slice): + return sequence + else: # single nucleotide + return ord(sequence) + + def __len__(self): + """Get the sequence length.""" + return self.length + + def upper(self): + """Remove the sequence mask.""" + data = _TwoBitSequenceData(self.stream, self.offset, self.length) + data.nBlocks = self.nBlocks[:, :] + data.maskBlocks = np.empty((0, 2), dtype="uint32") + return data + + def lower(self): + """Extend the sequence mask to the full sequence.""" + data = _TwoBitSequenceData(self.stream, self.offset, self.length) + data.nBlocks = self.nBlocks[:, :] + data.maskBlocks = np.array([[0, self.length]], dtype="uint32") + return data + + +class TwoBitIterator(SequenceIterator): + """Parser for UCSC twoBit (.2bit) files.""" + + modes = "b" + + def __init__(self, source): + """Read the file index.""" + super().__init__(source, fmt="twoBit") + stream = self.stream + data = stream.read(4) + if not data: + raise ValueError("Empty file.") + byteorders = ("little", "big") + dtypes = ("u4") + for byteorder, dtype in zip(byteorders, dtypes): + signature = int.from_bytes(data, byteorder) + if signature == 0x1A412743: + break + else: + raise ValueError("Unknown signature") + self.byteorder = byteorder + data = stream.read(4) + version = int.from_bytes(data, byteorder, signed=False) + if version == 1: + raise ValueError( + "version-1 twoBit files with 64-bit offsets for index are currently not supported" + ) + if version != 0: + raise ValueError("Found unexpected file version %u; aborting" % version) + data = stream.read(4) + sequenceCount = int.from_bytes(data, byteorder, signed=False) + data = stream.read(4) + reserved = int.from_bytes(data, byteorder, signed=False) + if reserved != 0: + raise ValueError("Found non-zero reserved field; aborting") + sequences = {} + for i in range(sequenceCount): + data = stream.read(1) + nameSize = int.from_bytes(data, byteorder, signed=False) + data = stream.read(nameSize) + name = data.decode("ASCII") + data = stream.read(4) + offset = int.from_bytes(data, byteorder, signed=False) + sequences[name] = (stream, offset) + self.sequences = sequences + for name, (stream, offset) in sequences.items(): + stream.seek(offset) + data = stream.read(4) + dnaSize = int.from_bytes(data, byteorder, signed=False) + sequence = _TwoBitSequenceData(stream, offset, dnaSize) + data = stream.read(4) + nBlockCount = int.from_bytes(data, byteorder, signed=False) + nBlockStarts = np.fromfile(stream, dtype=dtype, count=nBlockCount) + nBlockSizes = np.fromfile(stream, dtype=dtype, count=nBlockCount) + sequence.nBlocks = np.empty((nBlockCount, 2), dtype="uint32") + sequence.nBlocks[:, 0] = nBlockStarts + sequence.nBlocks[:, 1] = nBlockStarts + nBlockSizes + data = stream.read(4) + maskBlockCount = int.from_bytes(data, byteorder, signed=False) + maskBlockStarts = np.fromfile(stream, dtype=dtype, count=maskBlockCount) + maskBlockSizes = np.fromfile(stream, dtype=dtype, count=maskBlockCount) + sequence.maskBlocks = np.empty((maskBlockCount, 2), dtype="uint32") + sequence.maskBlocks[:, 0] = maskBlockStarts + sequence.maskBlocks[:, 1] = maskBlockStarts + maskBlockSizes + data = stream.read(4) + reserved = int.from_bytes(data, byteorder, signed=False) + if reserved != 0: + raise ValueError("Found non-zero reserved field %u" % reserved) + sequence.offset = stream.tell() + sequence = Seq(sequence) + sequences[name] = sequence + self._names = iter(self.sequences) + + def __next__(self): + """Return the next entry.""" + name = next(self._names) + sequence = self.sequences[name] + return SeqRecord(sequence, id=name) + + def __getitem__(self, name): + """Return sequence associated with given name as a SeqRecord object.""" + try: + sequence = self.sequences[name] + except ValueError: + raise KeyError(name) from None + return SeqRecord(sequence, id=name) + + def keys(self): + """Return a list with the names of the sequences in the file.""" + return self.sequences.keys() + + def __len__(self): + """Return number of sequences.""" + return len(self.sequences) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/UniprotIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/UniprotIO.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc18467fde0a5e47dc1ab04ced9bc7745509872 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/UniprotIO.py @@ -0,0 +1,570 @@ +# Copyright 2010 by Andrea Pierleoni +# Revisions copyright 2010, 2016 by Peter Cock +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "uniprot-xml" file format. + +See Also: +http://www.uniprot.org + +The UniProt XML format essentially replaces the old plain text file format +originally introduced by SwissProt ("swiss" format in Bio.SeqIO). + +""" + +import warnings +from xml.etree import ElementTree +from xml.parsers.expat import errors + +from Bio import SeqFeature +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator, _BytesIOSource + +NS = "{http://uniprot.org/uniprot}" +REFERENCE_JOURNAL = "%(name)s %(volume)s:%(first)s-%(last)s(%(pub_date)s)" + + +class UniprotIterator(SequenceIterator): + """Parser for UniProt XML files, returning SeqRecord objects.""" + + modes = "b" + + def __init__( + self, + source: _BytesIOSource, + alphabet: None = None, + return_raw_comments: bool = False, + ) -> None: + """Iterate over UniProt XML as SeqRecord objects. + + parses an XML entry at a time from any UniProt XML file + returns a SeqRecord for each iteration + + Arguments: + - source - input stream opened in binary mode, or a path to a file + - alphabet - optional alphabet, not used. Leave as None. + - return_raw_comments - if True, return comment fields as complete XML + to allow further processing. + + This generator can be used in Bio.SeqIO. + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + super().__init__(source, fmt="UniProt XML") + self.return_raw_comments = return_raw_comments + self._data = ElementTree.iterparse( + self.stream, events=("start", "start-ns", "end") + ) + + def __next__(self): + try: + for event, elem in self._data: + if event == "start-ns" and not ( + elem[1].startswith("http://www.w3.org/") or NS == f"{{{elem[1]}}}" + ): + raise ValueError( + f"SeqIO format 'uniprot-xml' only parses xml with namespace: {NS} but xml has namespace: {{{elem[1]}}}" + ) + if event == "end" and elem.tag == NS + "entry": + record = self._create_record(elem) + elem.clear() + return record + raise StopIteration + except ElementTree.ParseError as exception: + if errors.messages[exception.code] == errors.XML_ERROR_NO_ELEMENTS: + assert exception.position == (1, 0) # line 1, column 0 + raise ValueError("Empty file.") from None + else: + raise + + def _parse_name(self, element): + self._record.name = element.text + self._record.dbxrefs.append(self._dbname + ":" + element.text) + + def _parse_protein(self, element): + """Parse protein names (PRIVATE).""" + descr_set = False + for protein_element in element: + if protein_element.tag in [ + NS + "recommendedName", + NS + "submittedName", + NS + "alternativeName", + ]: # recommendedName tag are parsed before + # use protein fields for name and description + for rec_name in protein_element: + ann_key = "%s_%s" % ( + protein_element.tag.replace(NS, ""), + rec_name.tag.replace(NS, ""), + ) + self._append_to_annotations(ann_key, rec_name.text) + if (rec_name.tag == NS + "fullName") and not descr_set: + self._record.description = rec_name.text + descr_set = True + elif protein_element.tag == NS + "component": + pass # not parsed + elif protein_element.tag == NS + "domain": + pass # not parsed + + def _append_to_annotations(self, key, value): + annotations = self._record.annotations + if key not in annotations: + annotations[key] = [] + if value not in annotations[key]: + annotations[key].append(value) + + def _parse_accession(self, element): + self._append_to_annotations( + "accessions", element.text + ) # to cope with SwissProt plain text parser + self._record.dbxrefs.append(self._dbname + ":" + element.text) + + def _parse_gene(self, element): + for genename_element in element: + if "type" in genename_element.attrib: + ann_key = "gene_%s_%s" % ( + genename_element.tag.replace(NS, ""), + genename_element.attrib["type"], + ) + if genename_element.attrib["type"] == "primary": + self._record.annotations[ann_key] = genename_element.text + else: + self._append_to_annotations(ann_key, genename_element.text) + + def _parse_organism(self, element): + organism_name = com_name = sci_name = "" + for organism_element in element: + if organism_element.tag == NS + "name": + if organism_element.text: + if organism_element.attrib["type"] == "scientific": + sci_name = organism_element.text + elif organism_element.attrib["type"] == "common": + com_name = organism_element.text + else: + # e.g. synonym + self._append_to_annotations( + "organism_name", organism_element.text + ) + elif organism_element.tag == NS + "dbReference": + self._record.dbxrefs.append( + organism_element.attrib["type"] + + ":" + + organism_element.attrib["id"] + ) + elif organism_element.tag == NS + "lineage": + for taxon_element in organism_element: + if taxon_element.tag == NS + "taxon": + self._append_to_annotations("taxonomy", taxon_element.text) + if sci_name and com_name: + organism_name = f"{sci_name} ({com_name})" + elif sci_name: + organism_name = sci_name + elif com_name: + organism_name = com_name + self._record.annotations["organism"] = organism_name + + def _parse_reference(self, element): + reference = SeqFeature.Reference() + authors = [] + scopes = [] + tissues = [] + journal_name = "" + pub_type = "" + pub_date = "" + for ref_element in element: + if ref_element.tag == NS + "citation": + pub_type = ref_element.attrib["type"] + if pub_type == "submission": + pub_type += " to the " + ref_element.attrib["db"] + if "name" in ref_element.attrib: + journal_name = ref_element.attrib["name"] + pub_date = ref_element.attrib.get("date", "") + j_volume = ref_element.attrib.get("volume", "") + j_first = ref_element.attrib.get("first", "") + j_last = ref_element.attrib.get("last", "") + for cit_element in ref_element: + if cit_element.tag == NS + "title": + reference.title = cit_element.text + elif cit_element.tag == NS + "authorList": + for person_element in cit_element: + authors.append(person_element.attrib["name"]) + elif cit_element.tag == NS + "dbReference": + self._record.dbxrefs.append( + cit_element.attrib["type"] + ":" + cit_element.attrib["id"] + ) + if cit_element.attrib["type"] == "PubMed": + reference.pubmed_id = cit_element.attrib["id"] + elif ref_element.attrib["type"] == "MEDLINE": + reference.medline_id = cit_element.attrib["id"] + elif ref_element.tag == NS + "scope": + scopes.append(ref_element.text) + elif ref_element.tag == NS + "source": + for source_element in ref_element: + if source_element.tag == NS + "tissue": + tissues.append(source_element.text) + if scopes: + scopes_str = "Scope: " + ", ".join(scopes) + else: + scopes_str = "" + if tissues: + tissues_str = "Tissue: " + ", ".join(tissues) + else: + tissues_str = "" + + # locations cannot be parsed since they are actually written in + # free text inside scopes so all the references are put in the + # annotation. + reference.location = [] + reference.authors = ", ".join(authors) + if journal_name: + if pub_date and j_volume and j_first and j_last: + reference.journal = REFERENCE_JOURNAL % { + "name": journal_name, + "volume": j_volume, + "first": j_first, + "last": j_last, + "pub_date": pub_date, + } + else: + reference.journal = journal_name + reference.comment = " | ".join((pub_type, pub_date, scopes_str, tissues_str)) + self._append_to_annotations("references", reference) + + def _parse_comment(self, element): + """Parse comments (PRIVATE). + + Comment fields are very heterogeneus. each type has his own (frequently mutated) schema. + To store all the contained data, more complex data structures are needed, such as + annotated dictionaries. This is left to end user, by optionally setting: + + return_raw_comments=True + + The original XML is returned in the annotation fields. + + Available comment types at december 2009: + - "allergen" + - "alternative products" + - "biotechnology" + - "biophysicochemical properties" + - "catalytic activity" + - "caution" + - "cofactor" + - "developmental stage" + - "disease" + - "domain" + - "disruption phenotype" + - "enzyme regulation" + - "function" + - "induction" + - "miscellaneous" + - "pathway" + - "pharmaceutical" + - "polymorphism" + - "PTM" + - "RNA editing" + - "similarity" + - "subcellular location" + - "sequence caution" + - "subunit" + - "tissue specificity" + - "toxic dose" + - "online information" + - "mass spectrometry" + - "interaction" + + """ + simple_comments = [ + "allergen", + "biotechnology", + "biophysicochemical properties", + "catalytic activity", + "caution", + "cofactor", + "developmental stage", + "disease", + "domain", + "disruption phenotype", + "enzyme regulation", + "function", + "induction", + "miscellaneous", + "pathway", + "pharmaceutical", + "polymorphism", + "PTM", + "RNA editing", # positions not parsed + "similarity", + "subunit", + "tissue specificity", + "toxic dose", + ] + + if element.attrib["type"] in simple_comments: + ann_key = f"comment_{element.attrib['type'].replace(' ', '')}" + for text_element in element.iter(NS + "text"): + if text_element.text: + self._append_to_annotations(ann_key, text_element.text) + elif element.attrib["type"] == "subcellular location": + for subloc_element in element.iter(NS + "subcellularLocation"): + for el in subloc_element: + if el.text: + ann_key = "comment_%s_%s" % ( + element.attrib["type"].replace(" ", ""), + el.tag.replace(NS, ""), + ) + self._append_to_annotations(ann_key, el.text) + elif element.attrib["type"] == "interaction": + for interact_element in element.iter(NS + "interactant"): + ann_key = f"comment_{element.attrib['type']}_intactId" + self._append_to_annotations( + ann_key, interact_element.attrib["intactId"] + ) + elif element.attrib["type"] == "alternative products": + for alt_element in element.iter(NS + "isoform"): + ann_key = "comment_%s_isoform" % element.attrib["type"].replace(" ", "") + for id_element in alt_element.iter(NS + "id"): + self._append_to_annotations(ann_key, id_element.text) + elif element.attrib["type"] == "mass spectrometry": + ann_key = f"comment_{element.attrib['type'].replace(' ', '')}" + start = end = 0 + for el in element.iter(NS + "location"): + pos_els = list(el.iter(NS + "position")) + # this try should be avoided, maybe it is safer to skip position parsing for mass spectrometry + try: + if pos_els: + end = int(pos_els[0].attrib["position"]) + start = end - 1 + else: + start = int(next(el.iter(NS + "begin")).attrib["position"]) + start -= 1 + end = int(next(el.iter(NS + "end")).attrib["position"]) + except (ValueError, KeyError): + # undefined positions or erroneously mapped + pass + mass = element.attrib["mass"] + method = element.attrib["method"] + if start == end == 0: + self._append_to_annotations(ann_key, f"undefined:{mass}|{method}") + else: + self._append_to_annotations(ann_key, f"{start}..{end}:{mass}|{method}") + elif element.attrib["type"] == "sequence caution": + pass # not parsed: few information, complex structure + elif element.attrib["type"] == "online information": + for link_element in element.iter(NS + "link"): + ann_key = f"comment_{element.attrib['type'].replace(' ', '')}" + for id_element in link_element.iter(NS + "link"): + self._append_to_annotations( + ann_key, + f"{element.attrib['name']}@{link_element.attrib['uri']}", + ) + + # return raw XML comments if needed + if self.return_raw_comments: + ann_key = f"comment_{element.attrib['type'].replace(' ', '')}_xml" + self._append_to_annotations(ann_key, ElementTree.tostring(element)) + + def _parse_dbReference(self, element): + self._record.dbxrefs.append(element.attrib["type"] + ":" + element.attrib["id"]) + # e.g. + # + # + # + # + # + if "type" in element.attrib: + if element.attrib["type"] == "PDB": + method = "" + resolution = "" + for ref_element in element: + if ref_element.tag == NS + "property": + dat_type = ref_element.attrib["type"] + if dat_type == "method": + method = ref_element.attrib["value"] + if dat_type == "resolution": + resolution = ref_element.attrib["value"] + if dat_type == "chains": + pairs = ref_element.attrib["value"].split(",") + for elem in pairs: + pair = elem.strip().split("=") + if pair[1] != "-": + # TODO - How best to store these, do SeqFeatures make sense? + feature = SeqFeature.SeqFeature() + feature.type = element.attrib["type"] + feature.qualifiers["name"] = element.attrib["id"] + feature.qualifiers["method"] = method + feature.qualifiers["resolution"] = resolution + feature.qualifiers["chains"] = pair[0].split("/") + start = int(pair[1].split("-")[0]) - 1 + end = int(pair[1].split("-")[1]) + feature.location = SeqFeature.SimpleLocation( + start, end + ) + # self._record.features.append(feature) + + for ref_element in element: + if ref_element.tag == NS + "property": + pass # this data cannot be fitted in a seqrecord object with a simple list. however at least ensembl and EMBL parsing can be improved to add entries in dbxrefs + + def _parse_proteinExistence(self, element): + self._append_to_annotations("proteinExistence", element.attrib["type"]) + + def _parse_keyword(self, element): + self._append_to_annotations("keywords", element.text) + + def _parse_position(self, element, offset=0): + try: + position = int(element.attrib["position"]) + offset + except KeyError: + position = None + status = element.attrib.get("status", "") + if status == "unknown": + assert position is None + return SeqFeature.UnknownPosition() + elif not status: + return SeqFeature.ExactPosition(position) + elif status == "greater than": + return SeqFeature.AfterPosition(position) + elif status == "less than": + return SeqFeature.BeforePosition(position) + elif status == "uncertain": + return SeqFeature.UncertainPosition(position) + else: + raise NotImplementedError(f"Position status {status!r}") + + def _parse_feature(self, element): + feature = SeqFeature.SeqFeature() + for k, v in element.attrib.items(): + feature.qualifiers[k] = v + feature.type = element.attrib.get("type", "") + if "id" in element.attrib: + feature.id = element.attrib["id"] + for feature_element in element: + if feature_element.tag == NS + "location": + position_elements = feature_element.findall(NS + "position") + if position_elements: + element = position_elements[0] + start_position = self._parse_position(element, -1) + end_position = self._parse_position(element) + else: + element = feature_element.findall(NS + "begin")[0] + start_position = self._parse_position(element, -1) + element = feature_element.findall(NS + "end")[0] + end_position = self._parse_position(element) + feature.location = SeqFeature.SimpleLocation( + start_position, end_position + ) + elif feature_element.tag == NS + "ligand": + # Support multiple ligand entries per feature + name = None + db_ref = None + for child in feature_element: + if child.tag == NS + "name": + name = child.text.strip() if child.text else None + elif child.tag == NS + "dbReference": + db_ref = child.attrib.get("id") + # Append to a list of ligands in qualifiers + lig_list = feature.qualifiers.setdefault("ligands", []) + lig_list.append({"name": name, "db_ref": db_ref}) + continue + else: + try: + feature.qualifiers[feature_element.tag.replace(NS, "")] = ( + feature_element.text + ) + except Exception: # TODO - Which exceptions? + pass # skip unparsable tag + self._record.features.append(feature) + + def _parse_evidence(self, element): + for k, v in element.attrib.items(): + ann_key = k + self._append_to_annotations(ann_key, v) + + def _parse_sequence(self, element): + record = self._record + for k, v in element.attrib.items(): + if k in ("length", "mass", "version"): + record.annotations[f"sequence_{k}"] = int(v) + else: + record.annotations[f"sequence_{k}"] = v + record.seq = Seq("".join(element.text.split())) + record.annotations["molecule_type"] = "protein" + + def _parse_organismHost(self, element): + for organism_element in element: + if organism_element.tag == NS + "name": + self._append_to_annotations("organism_host", organism_element.text) + + def _parse_geneLocation(self, element): + self._append_to_annotations("geneLocation", element.attrib["type"]) + + def _create_record(self, entry): + assert entry.tag == NS + "entry" + # ============================================# + # Initialize SeqRecord + record = SeqRecord(None, id="") + self._record = record + + # Entry attribs parsing + # Unknown dataset should not happen! + self._dbname = entry.attrib.get("dataset", "UnknownDataset") + # add attribs to annotations + for k, v in entry.attrib.items(): + if k in ("version"): + # original + # self.ParsedSeqRecord.annotations["entry_%s" % k] = int(v) + # To cope with swissProt plain text parser. this can cause errors + # if the attrib has the same name of an other annotation + record.annotations[k] = int(v) + else: + # record.annotations["entry_%s" % k] = v + # to cope with swissProt plain text parser: + record.annotations[k] = v + + # Top-to-bottom entry children parsing + for element in entry: + if element.tag == NS + "name": + self._parse_name(element) + elif element.tag == NS + "accession": + self._parse_accession(element) + elif element.tag == NS + "protein": + self._parse_protein(element) + elif element.tag == NS + "gene": + self._parse_gene(element) + elif element.tag == NS + "geneLocation": + self._parse_geneLocation(element) + elif element.tag == NS + "organism": + self._parse_organism(element) + elif element.tag == NS + "organismHost": + self._parse_organismHost(element) + elif element.tag == NS + "keyword": + self._parse_keyword(element) + elif element.tag == NS + "comment": + self._parse_comment(element) + elif element.tag == NS + "dbReference": + self._parse_dbReference(element) + elif element.tag == NS + "reference": + self._parse_reference(element) + elif element.tag == NS + "feature": + self._parse_feature(element) + elif element.tag == NS + "proteinExistence": + self._parse_proteinExistence(element) + elif element.tag == NS + "evidence": + self._parse_evidence(element) + elif element.tag == NS + "sequence": + self._parse_sequence(element) + else: + pass + + # remove duplicate dbxrefs + record.dbxrefs = sorted(set(record.dbxrefs)) + + # use first accession as id + if not record.id: + record.id = record.annotations["accessions"][0] + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/XdnaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/XdnaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..666e9b194e9abaa4ec2ef4de3265afcebf9b0e2d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/XdnaIO.py @@ -0,0 +1,364 @@ +# Copyright 2017-2019 Damien Goutte-Gattat. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.SeqIO support for the "xdna" file format. + +The Xdna binary format is generated by Christian Marck's DNA Strider program +and also used by Serial Cloner. +""" + +import warnings +from re import match +from struct import pack +from struct import unpack + +from Bio import BiopythonWarning +from Bio.Seq import Seq +from Bio.SeqFeature import ExactPosition +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequenceIterator +from .Interfaces import SequenceWriter + +_seq_types = { + 0: None, + 1: "DNA", + 2: "DNA", + 3: "RNA", + 4: "protein", +} + +_seq_topologies = {0: "linear", 1: "circular"} + + +def _read(handle, length): + """Read the specified number of bytes from the given handle.""" + data = handle.read(length) + if len(data) < length: + raise ValueError("Cannot read %d bytes from handle" % length) + return data + + +def _read_pstring(handle): + """Read a Pascal string. + + A Pascal string comprises a single byte giving the length of the string + followed by as many bytes. + """ + length = unpack(">B", _read(handle, 1))[0] + return unpack("%ds" % length, _read(handle, length))[0].decode("ASCII") + + +def _read_pstring_as_integer(handle): + return int(_read_pstring(handle)) + + +def _read_overhang(handle): + """Read an overhang specification. + + An overhang is represented in a XDNA file as: + - a Pascal string containing the text representation of the overhang + length, which also indicates the nature of the overhang: + - a length of zero means no overhang, + - a negative length means a 3' overhang, + - a positive length means a 5' overhang; + - the actual overhang sequence. + + Examples: + - 0x01 0x30: no overhang ("0", as a P-string) + - 0x01 0x32 0x41 0x41: 5' AA overhang (P-string "2", then "AA") + - 0x02 0x2D 0x31 0x43: 3' C overhang (P-string "-1", then "C") + + Returns a tuple (length, sequence). + + """ + length = _read_pstring_as_integer(handle) + if length != 0: + overhang = _read(handle, abs(length)) + return (length, overhang) + else: + return (None, None) + + +def _parse_feature_description(desc, qualifiers): + """Parse the description field of a Xdna feature. + + The 'description' field of a feature sometimes contains several + GenBank-like qualifiers, separated by carriage returns (CR, 0x0D). + """ + # Split the field's value in CR-separated lines, skipping empty lines + for line in [x for x in desc.split("\x0d") if len(x) > 0]: + # Is it a qualifier="value" line? + m = match('^([^=]+)="([^"]+)"?$', line) + if m: + # Store the qualifier as provided + qual, value = m.groups() + qualifiers[qual] = [value] + elif '"' not in line: # Reject ill-formed qualifiers + # Store the entire line as a generic note qualifier + qualifiers["note"] = [line] + + +def _read_feature(handle, record): + """Read a single sequence feature.""" + name = _read_pstring(handle) + desc = _read_pstring(handle) + type = _read_pstring(handle) or "misc_feature" + start = _read_pstring_as_integer(handle) + end = _read_pstring_as_integer(handle) + + # Feature flags (4 bytes): + # byte 1 is the strand (0: reverse strand, 1: forward strand); + # byte 2 tells whether to display the feature; + # byte 4 tells whether to draw an arrow when displaying the feature; + # meaning of byte 3 is unknown. + (forward, display, arrow) = unpack(">BBxB", _read(handle, 4)) + if forward: + strand = 1 + else: + strand = -1 + start, end = end, start + + # The last field is a Pascal string usually containing a + # comma-separated triplet of numbers ranging from 0 to 255. + # I suspect this represents the RGB color to use when displaying + # the feature. Skip it as we have no need for it. + _read_pstring(handle) + + # Assemble the feature + # Shift start by -1 as XDNA feature coordinates are 1-based + # while Biopython uses 0-based counting. + location = SimpleLocation(start - 1, end, strand=strand) + qualifiers = {} + if name: + qualifiers["label"] = [name] + _parse_feature_description(desc, qualifiers) + feature = SeqFeature(location, type=type, qualifiers=qualifiers) + record.features.append(feature) + + +class XdnaIterator(SequenceIterator): + """Parser for Xdna files.""" + + modes = "b" + + def __init__(self, source): + """Parse a Xdna file and return a SeqRecord object. + + Argument source is a file-like object in binary mode or a path to a file. + + Note that this is an "iterator" in name only since an Xdna file always + contain a single sequence. + + """ + super().__init__(source, fmt="Xdna") + header = self.stream.read(112) + if not header: + raise ValueError("Empty file.") + if len(header) < 112: + raise ValueError("Improper header, cannot read 112 bytes from stream") + self._header = header + + def __next__(self): + if self._header is None: + raise StopIteration + stream = self.stream + # Parse fixed-size header and do some rudimentary checks + # + # The "neg_length" value is the length of the part of the sequence + # before the nucleotide considered as the "origin" (nucleotide number 1, + # which in DNA Strider is not always the first nucleotide). + # Biopython's SeqRecord has no such concept of a sequence origin as far + # as I know, so we ignore that value. SerialCloner has no such concept + # either and always generates files with a neg_length of zero. + (version, seq_type, topology, length, neg_length, com_length) = unpack( + ">BBB25xII60xI12x", self._header + ) + if version != 0: + raise ValueError("Unsupported XDNA version") + # Read actual sequence and comment found in all XDNA files + sequence = _read(stream, length).decode("ASCII") + comment = _read(stream, com_length).decode("ASCII") + + # Try to derive a name from the first "word" of the comment + name = comment.split(" ")[0] + + # Create record object + record = SeqRecord(Seq(sequence), description=comment, name=name, id=name) + try: + molecule_type = _seq_types[seq_type] + except KeyError: + raise ValueError("Unknown sequence type") from None + else: + record.annotations["molecule_type"] = molecule_type + try: + topology = _seq_topologies[topology] + except KeyError: + pass + else: + record.annotations["topology"] = topology + + if len(stream.read(1)) == 1: + # This is an XDNA file with an optional annotation section. + + # Skip the overhangs as I don't know how to represent + # them in the SeqRecord model. + _read_overhang(stream) # right-side overhang + _read_overhang(stream) # left-side overhang + + # Read the features + num_features = unpack(">B", _read(stream, 1))[0] + while num_features > 0: + _read_feature(stream, record) + num_features -= 1 + + self._header = None + return record + + +class XdnaWriter(SequenceWriter): + """Write files in the Xdna format.""" + + modes = "b" + + def write_records(self, records): + """Write the specified record to a Xdna file. + + Note that the function expects a list (or iterable) of records + as per the SequenceWriter interface, but the list should contain + only one record as the Xdna format is a mono-record format. + """ + records = iter(records) + + try: + record = next(records) + except StopIteration: + raise ValueError("Must have one sequence") from None + + try: + next(records) + raise ValueError("More than one sequence found") + except StopIteration: + pass + + self._has_truncated_strings = False + + molecule_type = record.annotations.get("molecule_type") + if molecule_type is None: + seqtype = 0 + elif "DNA" in molecule_type: + seqtype = 1 + elif "RNA" in molecule_type: + seqtype = 3 + elif "protein" in molecule_type: + seqtype = 4 + else: + seqtype = 0 + + if record.annotations.get("topology", "linear") == "circular": + topology = 1 + else: + topology = 0 + + # We store the record's id and description in the comment field. + # Make sure to avoid duplicating the id if it is already + # contained in the description. + if record.description.startswith(record.id): + comment = record.description + else: + comment = f"{record.id} {record.description}" + + # Write header + self.handle.write( + pack( + ">BBB25xII60xI11xB", + 0, # version + seqtype, + topology, + len(record), + 0, # negative length + len(comment), + 255, # end of header + ) + ) + + # Actual sequence and comment + self.handle.write(bytes(record.seq)) + self.handle.write(comment.encode("ASCII")) + + self.handle.write(pack(">B", 0)) # Annotation section marker + self._write_pstring("0") # right-side overhang + self._write_pstring("0") # left-side overhand + + # Write features + # We must skip features with fuzzy locations as they cannot be + # represented in the Xdna format + features = [ + f + for f in record.features + if isinstance(f.location.start, ExactPosition) + and isinstance(f.location.end, ExactPosition) + ] + drop = len(record.features) - len(features) + if drop > 0: + warnings.warn( + f"Dropping {drop} features with fuzzy locations", BiopythonWarning + ) + + # We also cannot store more than 255 features as the number of + # features is stored on a single byte... + if len(features) > 255: + drop = len(features) - 255 + warnings.warn( + f"Too many features, dropping the last {drop}", BiopythonWarning + ) + features = features[:255] + + self.handle.write(pack(">B", len(features))) + for feature in features: + self._write_pstring(feature.qualifiers.get("label", [""])[0]) + + description = "" + for qname in feature.qualifiers: + if qname in ("label", "translation"): + continue + + for val in feature.qualifiers[qname]: + if len(description) > 0: + description = description + "\x0d" + description = description + f'{qname}="{val}"' + self._write_pstring(description) + + self._write_pstring(feature.type) + + start = int(feature.location.start) + 1 # 1-based coordinates + end = int(feature.location.end) + strand = 1 + if feature.location.strand == -1: + start, end = end, start + strand = 0 + self._write_pstring(str(start)) + self._write_pstring(str(end)) + + self.handle.write(pack(">BBBB", strand, 1, 0, 1)) + self._write_pstring("127,127,127") + + if self._has_truncated_strings: + warnings.warn( + "Some annotations were truncated to 255 characters", BiopythonWarning + ) + + return 1 + + def _write_pstring(self, s): + """Write the given string as a Pascal string.""" + if len(s) > 255: + self._has_truncated_strings = True + s = s[:255] + self.handle.write(pack(">B", len(s))) + self.handle.write(s.encode("ASCII")) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..edac0e85d64830afec6f3edfbdc54b85e5fdac8e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/__init__.py @@ -0,0 +1,1171 @@ +# Copyright 2006-2024 by Peter Cock. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +r"""Sequence input/output as SeqRecord objects. + +Bio.SeqIO is also documented at SeqIO_ and by a whole chapter in our Tutorial_: + +.. _SeqIO: http://biopython.org/wiki/SeqIO +.. _Tutorial: https://biopython.org/docs/latest/Tutorial/index.html + +Input +----- +The main function is Bio.SeqIO.parse(...) which takes an input file handle +(or in recent versions of Biopython alternatively a filename as a string), +and format string. This returns an iterator giving SeqRecord objects: + +>>> from Bio import SeqIO +>>> for record in SeqIO.parse("Fasta/f002", "fasta"): +... print("%s %i" % (record.id, len(record))) +gi|1348912|gb|G26680|G26680 633 +gi|1348917|gb|G26685|G26685 413 +gi|1592936|gb|G29385|G29385 471 + +Note that the parse() function will invoke the relevant parser for the +format with its default settings. You may want more control, in which case +you need to create a format specific sequence iterator directly. + +Some of these parsers are wrappers around low-level parsers which build up +SeqRecord objects for the consistent SeqIO interface. In cases where the +run-time is critical, such as large FASTA or FASTQ files, calling these +underlying parsers will be much faster - in this case these generator +functions which return tuples of strings: + +>>> from Bio.SeqIO.FastaIO import SimpleFastaParser +>>> from Bio.SeqIO.QualityIO import FastqGeneralIterator + + +Input - Single Records +---------------------- +If you expect your file to contain one-and-only-one record, then we provide +the following 'helper' function which will return a single SeqRecord, or +raise an exception if there are no records or more than one record: + +>>> from Bio import SeqIO +>>> record = SeqIO.read("Fasta/f001", "fasta") +>>> print("%s %i" % (record.id, len(record))) +gi|3318709|pdb|1A91| 79 + +This style is useful when you expect a single record only (and would +consider multiple records an error). For example, when dealing with GenBank +files for bacterial genomes or chromosomes, there is normally only a single +record. Alternatively, use this with a handle when downloading a single +record from the internet. + +However, if you just want the first record from a file containing multiple +record, use the next() function on the iterator: + +>>> from Bio import SeqIO +>>> record = next(SeqIO.parse("Fasta/f002", "fasta")) +>>> print("%s %i" % (record.id, len(record))) +gi|1348912|gb|G26680|G26680 633 + +The above code will work as long as the file contains at least one record. +Note that if there is more than one record, the remaining records will be +silently ignored. + + +Input - Multiple Records +------------------------ +For non-interlaced files (e.g. Fasta, GenBank, EMBL) with multiple records +using a sequence iterator can save you a lot of memory (RAM). There is +less benefit for interlaced file formats (e.g. most multiple alignment file +formats). However, an iterator only lets you access the records one by one. + +If you want random access to the records by number, turn this into a list: + +>>> from Bio import SeqIO +>>> records = list(SeqIO.parse("Fasta/f002", "fasta")) +>>> len(records) +3 +>>> print(records[1].id) +gi|1348917|gb|G26685|G26685 + +If you want random access to the records by a key such as the record id, +turn the iterator into a dictionary: + +>>> from Bio import SeqIO +>>> record_dict = SeqIO.to_dict(SeqIO.parse("Fasta/f002", "fasta")) +>>> len(record_dict) +3 +>>> print(len(record_dict["gi|1348917|gb|G26685|G26685"])) +413 + +However, using list() or the to_dict() function will load all the records +into memory at once, and therefore is not possible on very large files. +Instead, for *some* file formats Bio.SeqIO provides an indexing approach +providing dictionary like access to any record. For example, + +>>> from Bio import SeqIO +>>> record_dict = SeqIO.index("Fasta/f002", "fasta") +>>> len(record_dict) +3 +>>> print(len(record_dict["gi|1348917|gb|G26685|G26685"])) +413 +>>> record_dict.close() + +Many but not all of the supported input file formats can be indexed like +this. For example "fasta", "fastq", "qual" and even the binary format "sff" +work, but alignment formats like "phylip", "clustalw" and "nexus" will not. + +In most cases you can also use SeqIO.index to get the record from the file +as a raw string (not a SeqRecord). This can be useful for example to extract +a sub-set of records from a file where SeqIO cannot output the file format +(e.g. the plain text SwissProt format, "swiss") or where it is important to +keep the output 100% identical to the input). For example, + +>>> from Bio import SeqIO +>>> record_dict = SeqIO.index("Fasta/f002", "fasta") +>>> len(record_dict) +3 +>>> print(record_dict.get_raw("gi|1348917|gb|G26685|G26685").decode()) +>gi|1348917|gb|G26685|G26685 human STS STS_D11734. +CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATCTTACTCTTTC +ATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTTTACAGATGTGAAACTTTCAA +GAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAAACCTGATGCTTTTATAAGCCATTGTGATTA +GGATGACTGTTACAGGCTTAGCTTTGTGTGAAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGT +TCATATTACTNTAAGTTCTATAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGG +AATTGNTTTGCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA + +>>> print(record_dict["gi|1348917|gb|G26685|G26685"].format("fasta")) +>gi|1348917|gb|G26685|G26685 human STS STS_D11734. +CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATC +TTACTCTTTCATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTT +TACAGATGTGAAACTTTCAAGAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAA +ACCTGATGCTTTTATAAGCCATTGTGATTAGGATGACTGTTACAGGCTTAGCTTTGTGTG +AAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGTTCATATTACTNTAAGTTCTA +TAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGGAATTGNTTTG +CCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA + +>>> record_dict.close() + +Here the original file and what Biopython would output differ in the line +wrapping. Also note that the get_raw method will return a bytes object, +hence the use of decode to turn it into a string. + +Also note that the get_raw method will preserve the newline endings. This +example FASTQ file uses Unix style endings (b"\n" only), + +>>> from Bio import SeqIO +>>> fastq_dict = SeqIO.index("Quality/example.fastq", "fastq") +>>> len(fastq_dict) +3 +>>> raw = fastq_dict.get_raw("EAS54_6_R1_2_1_540_792") +>>> raw.count(b"\n") +4 +>>> raw.count(b"\r\n") +0 +>>> b"\r" in raw +False +>>> len(raw) +78 +>>> fastq_dict.close() + +Here is the same file but using DOS/Windows new lines (b"\r\n" instead), + +>>> from Bio import SeqIO +>>> fastq_dict = SeqIO.index("Quality/example_dos.fastq", "fastq") +>>> len(fastq_dict) +3 +>>> raw = fastq_dict.get_raw("EAS54_6_R1_2_1_540_792") +>>> raw.count(b"\n") +4 +>>> raw.count(b"\r\n") +4 +>>> b"\r\n" in raw +True +>>> len(raw) +82 +>>> fastq_dict.close() + +Because this uses two bytes for each new line, the file is longer than +the Unix equivalent with only one byte. + + +Input - Alignments +------------------ +You can read in alignment files as alignment objects using Bio.AlignIO. +Alternatively, reading in an alignment file format via Bio.SeqIO will give +you a SeqRecord for each row of each alignment: + +>>> from Bio import SeqIO +>>> for record in SeqIO.parse("Clustalw/hedgehog.aln", "clustal"): +... print("%s %i" % (record.id, len(record))) +gi|167877390|gb|EDS40773.1| 447 +gi|167234445|ref|NP_001107837. 447 +gi|74100009|gb|AAZ99217.1| 447 +gi|13990994|dbj|BAA33523.2| 447 +gi|56122354|gb|AAV74328.1| 447 + + +Output +------ +Use the function Bio.SeqIO.write(...), which takes a complete set of +SeqRecord objects (either as a list, or an iterator), an output file handle +(or in recent versions of Biopython an output filename as a string) and of +course the file format:: + + from Bio import SeqIO + records = ... + SeqIO.write(records, "example.faa", "fasta") + +Or, using a handle:: + + from Bio import SeqIO + records = ... + with open("example.faa", "w") as handle: + SeqIO.write(records, handle, "fasta") + +You are expected to call this function once (with all your records) and if +using a handle, make sure you close it to flush the data to the hard disk. + + +Output - Advanced +----------------- +The effect of calling write() multiple times on a single file will vary +depending on the file format, and is best avoided unless you have a strong +reason to do so. + +If you give a filename, then each time you call write() the existing file +will be overwritten. For sequential files formats (e.g. fasta, genbank) each +"record block" holds a single sequence. For these files it would probably +be safe to call write() multiple times by re-using the same handle. + +However, trying this for certain alignment formats (e.g. phylip, clustal, +stockholm) would have the effect of concatenating several multiple sequence +alignments together. Such files are created by the PHYLIP suite of programs +for bootstrap analysis, but it is clearer to do this via Bio.AlignIO instead. + +Worse, many fileformats have an explicit header and/or footer structure +(e.g. any XMl format, and most binary file formats like SFF). Here making +multiple calls to write() will result in an invalid file. + + +Conversion +---------- +The Bio.SeqIO.convert(...) function allows an easy interface for simple +file format conversions. Additionally, it may use file format specific +optimisations so this should be the fastest way too. + +In general however, you can combine the Bio.SeqIO.parse(...) function with +the Bio.SeqIO.write(...) function for sequence file conversion. Using +generator expressions or generator functions provides a memory efficient way +to perform filtering or other extra operations as part of the process. + + +File Formats +------------ +When specifying the file format, use lowercase strings. The same format +names are also used in Bio.AlignIO and include the following: + + - abi - Applied Biosystem's sequencing trace format + - abi-trim - Same as "abi" but with quality trimming with Mott's algorithm + - ace - Reads the contig sequences from an ACE assembly file. + - cif-atom - Uses Bio.PDB.MMCIFParser to determine the (partial) protein + sequence as it appears in the structure based on the atomic coordinates. + - cif-seqres - Reads a macromolecular Crystallographic Information File + (mmCIF) file to determine the complete protein sequence as defined by the + _pdbx_poly_seq_scheme records. + - embl - The EMBL flat file format. Uses Bio.GenBank internally. + - fasta - The generic sequence file format where each record starts with + an identifier line starting with a ">" character, followed by + lines of sequence. + - fasta-2line - Stricter interpretation of the FASTA format using exactly + two lines per record (no line wrapping). + - fastq - A "FASTA like" format used by Sanger which also stores PHRED + sequence quality values (with an ASCII offset of 33). + - fastq-sanger - An alias for "fastq" for consistency with BioPerl and EMBOSS + - fastq-solexa - Original Solexa/Illumnia variant of the FASTQ format which + encodes Solexa quality scores (not PHRED quality scores) with an + ASCII offset of 64. + - fastq-illumina - Solexa/Illumina 1.3 to 1.7 variant of the FASTQ format + which encodes PHRED quality scores with an ASCII offset of 64 + (not 33). Note as of version 1.8 of the CASAVA pipeline Illumina + will produce FASTQ files using the standard Sanger encoding. + - gck - Gene Construction Kit's format. + - genbank - The GenBank or GenPept flat file format. + - gb - An alias for "genbank", for consistency with NCBI Entrez Utilities + - gfa1 - Graphical Fragment Assemblyv versions 1.x. Only segment lines + are parsed and all linkage information is ignored. + - gfa2 - Graphical Fragment Assembly version 2.0. Only segment lines are + parsed and all linkage information is ignored. + - ig - The IntelliGenetics file format, apparently the same as the + MASE alignment format. + - imgt - An EMBL like format from IMGT where the feature tables are more + indented to allow for longer feature types. + - nib - UCSC's nib file format for nucleotide sequences, which uses one + nibble (4 bits) to represent each nucleotide, and stores two nucleotides in + one byte. + - pdb-seqres - Reads a Protein Data Bank (PDB) file to determine the + complete protein sequence as it appears in the header (no dependencies). + - pdb-atom - Uses Bio.PDB to determine the (partial) protein sequence as + it appears in the structure based on the atom coordinate section of the + file (requires NumPy for Bio.PDB). + - phd - Output from PHRED, used by PHRAP and CONSED for input. + - pir - A "FASTA like" format introduced by the National Biomedical + Research Foundation (NBRF) for the Protein Information Resource + (PIR) database, now part of UniProt. + - seqxml - SeqXML, simple XML format described in Schmitt et al (2011). + - sff - Standard Flowgram Format (SFF), typical output from Roche 454. + - sff-trim - Standard Flowgram Format (SFF) with given trimming applied. + - snapgene - SnapGene's native format. + - swiss - Plain text Swiss-Prot aka UniProt format. + - tab - Simple two column tab separated sequence files, where each + line holds a record's identifier and sequence. For example, + this is used as by Aligent's eArray software when saving + microarray probes in a minimal tab delimited text file. + - qual - A "FASTA like" format holding PHRED quality values from + sequencing DNA, but no actual sequences (usually provided + in separate FASTA files). + - uniprot-xml - The UniProt XML format (replacement for the SwissProt plain + text format which we call "swiss") + - xdna - DNA Strider's and SerialCloner's native format. + +Note that while Bio.SeqIO can read all the above file formats, it cannot +write to all of them. + +You can also use any file format supported by Bio.AlignIO, such as "nexus", +"phylip" and "stockholm", which gives you access to the individual sequences +making up each alignment as SeqRecords. +""" +# TODO +# - define policy on reading aligned sequences with more than +# one gap character (see also AlignIO) +# +# - How best to handle unique/non unique record.id when writing. +# For most file formats reading such files is fine; The stockholm +# parser would fail. +# +# - MSF multiple alignment format, aka GCG, aka PileUp format (*.msf) +# http://www.bioperl.org/wiki/MSF_multiple_alignment_format +# +# FAO BioPython Developers +# ------------------------ +# The way I envision this SeqIO system working as that for any sequence file +# format we have an iterator that returns SeqRecord objects. +# +# This also applies to interlaced file formats (like clustal - although that +# is now handled via Bio.AlignIO instead) where the file cannot be read record +# by record. You should still return an iterator, even if the implementation +# could just as easily return a list. +# +# These file format specific sequence iterators may be implemented as: +# - Classes which take a handle for __init__ and provide the __iter__ method +# - Functions that take a handle, and return an iterator object +# - Generator functions that take a handle, and yield SeqRecord objects +# +# It is then trivial to turn this iterator into a list of SeqRecord objects, +# an in memory dictionary, or a multiple sequence alignment object. +# +# For building the dictionary by default the id property of each SeqRecord is +# used as the key. You should always populate the id property, and it should +# be unique in most cases. For some file formats the accession number is a good +# choice. If the file itself contains ambiguous identifiers, don't try and +# dis-ambiguate them - return them as is. +# +# When adding a new file format, please use the same lower case format name +# as BioPerl, or if they have not defined one, try the names used by EMBOSS. +# +# See also http://biopython.org/wiki/SeqIO_dev +# +# --Peter + +from abc import ABC, abstractmethod +from collections.abc import Callable +from collections.abc import Iterable +from typing import Union + +from Bio import AlignIO +from Bio.SeqIO import AbiIO +from Bio.SeqIO import AceIO +from Bio.SeqIO import FastaIO +from Bio.SeqIO import GckIO +from Bio.SeqIO import GfaIO +from Bio.SeqIO import IgIO # IntelliGenetics or MASE format +from Bio.SeqIO import InsdcIO # EMBL and GenBank +from Bio.SeqIO import NibIO +from Bio.SeqIO import PdbIO +from Bio.SeqIO import PhdIO +from Bio.SeqIO import PirIO +from Bio.SeqIO import QualityIO # FastQ and qual files +from Bio.SeqIO import SeqXmlIO +from Bio.SeqIO import SffIO +from Bio.SeqIO import SnapGeneIO +from Bio.SeqIO import SwissIO +from Bio.SeqIO import TabIO +from Bio.SeqIO import TwoBitIO +from Bio.SeqIO import UniprotIO +from Bio.SeqIO import XdnaIO +from Bio.SeqRecord import SeqRecord + +from .Interfaces import _IOSource, _TextIOSource, SequenceIterator, SequenceWriter + +# Convention for format names is "mainname-subtype" in lower case. +# Please use the same names as BioPerl or EMBOSS where possible. +# +# Note that this simple system copes with defining +# multiple possible iterators for a given format/extension +# with the -subtype suffix +# +# Most alignment file formats will be handled via Bio.AlignIO + +_FormatToIterator = { + "abi": AbiIO.AbiIterator, + "abi-trim": AbiIO._AbiTrimIterator, + "ace": AceIO.AceIterator, + "fasta": FastaIO.FastaIterator, + "fasta-2line": FastaIO.FastaTwoLineIterator, + "fasta-blast": FastaIO.FastaBlastIterator, + "fasta-pearson": FastaIO.FastaPearsonIterator, + "ig": IgIO.IgIterator, + "embl": InsdcIO.EmblIterator, + "embl-cds": InsdcIO.EmblCdsFeatureIterator, + "gb": InsdcIO.GenBankIterator, + "gck": GckIO.GckIterator, + "genbank": InsdcIO.GenBankIterator, + "genbank-cds": InsdcIO.GenBankCdsFeatureIterator, + "gfa1": GfaIO.Gfa1Iterator, + "gfa2": GfaIO.Gfa2Iterator, + "imgt": InsdcIO.ImgtIterator, + "nib": NibIO.NibIterator, + "cif-seqres": PdbIO.CifSeqresIterator, + "cif-atom": PdbIO.CifAtomIterator, + "pdb-atom": PdbIO.PdbAtomIterator, + "pdb-seqres": PdbIO.PdbSeqresIterator, + "phd": PhdIO.PhdIterator, + "pir": PirIO.PirIterator, + "fastq": QualityIO.FastqPhredIterator, + "fastq-sanger": QualityIO.FastqPhredIterator, + "fastq-solexa": QualityIO.FastqSolexaIterator, + "fastq-illumina": QualityIO.FastqIlluminaIterator, + "qual": QualityIO.QualPhredIterator, + "seqxml": SeqXmlIO.SeqXmlIterator, + "sff": SffIO.SffIterator, + "snapgene": SnapGeneIO.SnapGeneIterator, + "sff-trim": SffIO._SffTrimIterator, # Not sure about this in the long run + "swiss": SwissIO.SwissIterator, + "tab": TabIO.TabIterator, + "twobit": TwoBitIO.TwoBitIterator, + "uniprot-xml": UniprotIO.UniprotIterator, + "xdna": XdnaIO.XdnaIterator, +} + +# Right now used in the unit tests as proxy for all supported outputs... +_FormatToWriter = { + "fasta": FastaIO.FastaWriter, + "fasta-2line": FastaIO.FastaTwoLineWriter, + "gb": InsdcIO.GenBankWriter, + "genbank": InsdcIO.GenBankWriter, + "embl": InsdcIO.EmblWriter, + "imgt": InsdcIO.ImgtWriter, + "nib": NibIO.NibWriter, + "phd": PhdIO.PhdWriter, + "pir": PirIO.PirWriter, + "fastq": QualityIO.FastqPhredWriter, + "fastq-sanger": QualityIO.FastqPhredWriter, + "fastq-solexa": QualityIO.FastqSolexaWriter, + "fastq-illumina": QualityIO.FastqIlluminaWriter, + "qual": QualityIO.QualPhredWriter, + "seqxml": SeqXmlIO.SeqXmlWriter, + "sff": SffIO.SffWriter, + "tab": TabIO.TabWriter, + "xdna": XdnaIO.XdnaWriter, +} + + +class AlignmentSequenceIterator(SequenceIterator): + """Pareses an alignment file and yields sequence records.""" + + modes = "t" + + @property + @abstractmethod + def fmt(self): + """Alignment file format name.""" + + @property + @abstractmethod + def _alignment_iterator_class(self): + """Alignment iterator class.""" + + def __init__(self, source: _IOSource) -> None: + """Initialize the iterator.""" + super().__init__(source, fmt=self.fmt) + # We need type(self) here, because _alignment_iterator_class is + # actually a function instead of a class for some formats in + # Bio.AlignIO, and Python will turn the function into a bound method + # with self as the first argument. + alignment_iterator_class = type(self)._alignment_iterator_class + alignments = alignment_iterator_class(self.stream, None) # type: ignore + self.iterator = (record for alignment in alignments for record in alignment) + + def __next__(self): + return next(self.iterator) + + +for fmt, alignment_iterator_class in AlignIO._FormatToIterator.items(): + name = fmt.replace("-", " ").title().replace(" ", "") + "AlignmentSequenceIterator" + cls = type( + name, + (AlignmentSequenceIterator,), + { + "fmt": fmt, + "_alignment_iterator_class": alignment_iterator_class, + }, + ) + _FormatToIterator[fmt] = cls + + +class AlignmentSequenceWriter(SequenceWriter): + """Writes sequences as an alignment.""" + + modes = "t" + + @property + @abstractmethod + def _alignment_writer_class(self): + """Alignment writer class.""" + + def write_records(self, records): + """Write records to the output file, and return the number of records. + + records - A list or iterator returning SeqRecord objects + """ + from Bio.Align import MultipleSeqAlignment + + alignment = MultipleSeqAlignment(records) + alignment_writer_class = self._alignment_writer_class + alignment_writer = alignment_writer_class(self.handle) + alignment_count = alignment_writer.write_file([alignment]) + if alignment_count != 1: + raise RuntimeError( + "Internal error - the underlying writer " + "should have returned 1, not %r" % alignment_count + ) + count = len(alignment) + return count + + +for fmt, alignment_writer_class in AlignIO._FormatToWriter.items(): + name = fmt.replace("-", " ").title().replace(" ", "") + "AlignmentSequenceWriter" + cls = type( + name, + (AlignmentSequenceWriter,), + {"_alignment_writer_class": alignment_writer_class}, + ) + _FormatToWriter[fmt] = cls # type: ignore + + +del AlignIO + + +def write( + sequences: Iterable[SeqRecord] | SeqRecord, + handle: _TextIOSource, + format: str, +) -> int: + """Write complete set of sequences to a file. + + Arguments: + - sequences - A list (or iterator) of SeqRecord objects, or a single + SeqRecord. + - handle - File handle object to write to, or filename as string. + - format - lower case string describing the file format to write. + + Note if providing a file handle, your code should close the handle + after calling this function (to ensure the data gets flushed to disk). + + Returns the number of records written (as an integer). + """ + from Bio import AlignIO + + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if not format.islower(): + raise ValueError(f"Format string '{format}' should be lower case") + + if isinstance(handle, SeqRecord): + raise TypeError("Check arguments, handle should NOT be a SeqRecord") + if isinstance(handle, list): + # e.g. list of SeqRecord objects + raise TypeError("Check arguments, handle should NOT be a list") + + if isinstance(sequences, SeqRecord): + # This raised an exception in older versions of Biopython + sequences = [sequences] + + writer_class = _FormatToWriter.get(format) + if writer_class is not None: + count = writer_class(handle).write_file(sequences) + if not isinstance(count, int): + raise RuntimeError( + "Internal error - the underlying %s writer " + "should have returned the record count, not %r" % (format, count) + ) + return count + + if format in _FormatToIterator: + raise ValueError(f"Reading format '{format}' is supported, but not writing") + + raise ValueError(f"Unknown format '{format}'") + + +def parse(handle, format, alphabet=None): + r"""Turn a sequence file into an iterator returning SeqRecords. + + Arguments: + - handle - handle to the file, or the filename as a string + - format - lower case string describing the file format. + - alphabet - no longer used, should be None. + + Typical usage, opening a file to read in, and looping over the record(s): + + >>> from Bio import SeqIO + >>> filename = "Fasta/sweetpea.nu" + >>> for record in SeqIO.parse(filename, "fasta"): + ... print("ID %s" % record.id) + ... print("Sequence length %i" % len(record)) + ID gi|3176602|gb|U78617.1|LOU78617 + Sequence length 309 + + For lazy-loading file formats such as twobit, for which the file contents + is read on demand only, ensure that the file remains open while extracting + sequence data. + + If you have a string 'data' containing the file contents, you must + first turn this into a handle in order to parse it: + + >>> data = ">Alpha\nACCGGATGTA\n>Beta\nAGGCTCGGTTA\n" + >>> from Bio import SeqIO + >>> from io import StringIO + >>> for record in SeqIO.parse(StringIO(data), "fasta"): + ... print("%s %s" % (record.id, record.seq)) + Alpha ACCGGATGTA + Beta AGGCTCGGTTA + + Use the Bio.SeqIO.read(...) function when you expect a single record + only. + """ + # NOTE - The above docstring has some raw \n characters needed + # for the StringIO example, hence the whole docstring is in raw + # string mode (see the leading r before the opening quote). + + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if not format.islower(): + raise ValueError(f"Format string '{format}' should be lower case") + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + + iterator_generator = _FormatToIterator.get(format) + if iterator_generator: + return iterator_generator(handle) + + raise ValueError(f"Unknown format '{format}'") + + +def read(handle, format, alphabet=None): + """Turn a sequence file into a single SeqRecord. + + Arguments: + - handle - handle to the file, or the filename as a string + (note older versions of Biopython only took a handle). + - format - string describing the file format. + - alphabet - no longer used, should be None. + + This function is for use parsing sequence files containing + exactly one record. For example, reading a GenBank file: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("GenBank/arab1.gb", "genbank") + >>> print("ID %s" % record.id) + ID AC007323.5 + >>> print("Sequence length %i" % len(record)) + Sequence length 86436 + + If the handle contains no records, or more than one record, + an exception is raised. For example: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("GenBank/cor6_6.gb", "genbank") + Traceback (most recent call last): + ... + ValueError: More than one record found in handle + + If however you want the first record from a file containing + multiple records this function would raise an exception (as + shown in the example above). Instead use: + + >>> from Bio import SeqIO + >>> record = next(SeqIO.parse("GenBank/cor6_6.gb", "genbank")) + >>> print("First record's ID %s" % record.id) + First record's ID X55053.1 + + Use the Bio.SeqIO.parse(handle, format) function if you want + to read multiple records from the handle. + """ + with parse(handle, format, alphabet) as records: + try: + record = next(records) + except StopIteration: + raise ValueError("No records found in handle") from None + try: + next(records) + raise ValueError("More than one record found in handle") + except StopIteration: + pass + return record + + +def to_dict(sequences, key_function=None): + """Turn a sequence iterator or list into a dictionary. + + Arguments: + - sequences - An iterator that returns SeqRecord objects, + or simply a list of SeqRecord objects. + - key_function - Optional callback function which when given a + SeqRecord should return a unique key for the dictionary. + + e.g. key_function = lambda rec : rec.name + or, key_function = lambda rec : rec.description.split()[0] + + If key_function is omitted then record.id is used, on the assumption + that the records objects returned are SeqRecords with a unique id. + + If there are duplicate keys, an error is raised. + + Since Python 3.7, the default dict class maintains key order, meaning + this dictionary will reflect the order of records given to it. For + CPython and PyPy, this was already implemented for Python 3.6, so + effectively you can always assume the record order is preserved. + + Example usage, defaulting to using the record.id as key: + + >>> from Bio import SeqIO + >>> filename = "GenBank/cor6_6.gb" + >>> format = "genbank" + >>> id_dict = SeqIO.to_dict(SeqIO.parse(filename, format)) + >>> print(list(id_dict)) + ['X55053.1', 'X62281.1', 'M81224.1', 'AJ237582.1', 'L31939.1', 'AF297471.1'] + >>> print(id_dict["L31939.1"].description) + Brassica rapa (clone bif72) kin mRNA, complete cds + + A more complex example, using the key_function argument in order to + use a sequence checksum as the dictionary key: + + >>> from Bio import SeqIO + >>> from Bio.SeqUtils.CheckSum import seguid + >>> filename = "GenBank/cor6_6.gb" + >>> format = "genbank" + >>> seguid_dict = SeqIO.to_dict(SeqIO.parse(filename, format), + ... key_function = lambda rec : seguid(rec.seq)) + >>> for key, record in sorted(seguid_dict.items()): + ... print("%s %s" % (key, record.id)) + /wQvmrl87QWcm9llO4/efg23Vgg AJ237582.1 + BUg6YxXSKWEcFFH0L08JzaLGhQs L31939.1 + SabZaA4V2eLE9/2Fm5FnyYy07J4 X55053.1 + TtWsXo45S3ZclIBy4X/WJc39+CY M81224.1 + l7gjJFE6W/S1jJn5+1ASrUKW/FA X62281.1 + uVEYeAQSV5EDQOnFoeMmVea+Oow AF297471.1 + + This approach is not suitable for very large sets of sequences, as all + the SeqRecord objects are held in memory. Instead, consider using the + Bio.SeqIO.index() function (if it supports your particular file format). + + This dictionary will reflect the order of records given to it. + """ + # This is to avoid a lambda function: + + def _default_key_function(rec): + return rec.id + + if key_function is None: + key_function = _default_key_function + + d = {} + for record in sequences: + key = key_function(record) + if key in d: + raise ValueError(f"Duplicate key '{key}'") + d[key] = record + return d + + +def index(filename, format, alphabet=None, key_function=None): + """Indexes a sequence file and returns a dictionary like object. + + Arguments: + - filename - string giving name of file to be indexed + - format - lower case string describing the file format + - alphabet - no longer used, leave as None + - key_function - Optional callback function which when given a + SeqRecord identifier string should return a unique key for the + dictionary. + + This indexing function will return a dictionary like object, giving the + SeqRecord objects as values. + + As of Biopython 1.69, this will preserve the ordering of the records in + file when iterating over the entries. + + >>> from Bio import SeqIO + >>> records = SeqIO.index("Quality/example.fastq", "fastq") + >>> len(records) + 3 + >>> list(records) # make a list of the keys + ['EAS54_6_R1_2_1_413_324', 'EAS54_6_R1_2_1_540_792', 'EAS54_6_R1_2_1_443_348'] + >>> print(records["EAS54_6_R1_2_1_540_792"].format("fasta")) + >EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + + >>> "EAS54_6_R1_2_1_540_792" in records + True + >>> print(records.get("Missing", None)) + None + >>> records.close() + + If the file is BGZF compressed, this is detected automatically. Ordinary + GZIP files are not supported: + + >>> from Bio import SeqIO + >>> records = SeqIO.index("Quality/example.fastq.bgz", "fastq") + >>> len(records) + 3 + >>> print(records["EAS54_6_R1_2_1_540_792"].seq) + TTGGCAGGCCAAGGCCGATGGATCA + >>> records.close() + + When you call the index function, it will scan through the file, noting + the location of each record. When you access a particular record via the + dictionary methods, the code will jump to the appropriate part of the + file and then parse that section into a SeqRecord. + + Note that not all the input formats supported by Bio.SeqIO can be used + with this index function. It is designed to work only with sequential + file formats (e.g. "fasta", "gb", "fastq") and is not suitable for any + interlaced file format (e.g. alignment formats such as "clustal"). + + For small files, it may be more efficient to use an in memory Python + dictionary, e.g. + + >>> from Bio import SeqIO + >>> records = SeqIO.to_dict(SeqIO.parse("Quality/example.fastq", "fastq")) + >>> len(records) + 3 + >>> list(records) # make a list of the keys + ['EAS54_6_R1_2_1_413_324', 'EAS54_6_R1_2_1_540_792', 'EAS54_6_R1_2_1_443_348'] + >>> print(records["EAS54_6_R1_2_1_540_792"].format("fasta")) + >EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + + + As with the to_dict() function, by default the id string of each record + is used as the key. You can specify a callback function to transform + this (the record identifier string) into your preferred key. For example: + + >>> from Bio import SeqIO + >>> def make_tuple(identifier): + ... parts = identifier.split("_") + ... return int(parts[-2]), int(parts[-1]) + >>> records = SeqIO.index("Quality/example.fastq", "fastq", + ... key_function=make_tuple) + >>> len(records) + 3 + >>> list(records) # make a list of the keys + [(413, 324), (540, 792), (443, 348)] + >>> print(records[(540, 792)].format("fasta")) + >EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + + >>> (540, 792) in records + True + >>> "EAS54_6_R1_2_1_540_792" in records + False + >>> print(records.get("Missing", None)) + None + >>> records.close() + + Another common use case would be indexing an NCBI style FASTA file, + where you might want to extract the GI number from the FASTA identifier + to use as the dictionary key. + + Notice that unlike the to_dict() function, here the key_function does + not get given the full SeqRecord to use to generate the key. Doing so + would impose a severe performance penalty as it would require the file + to be completely parsed while building the index. Right now this is + usually avoided. + + See Also: Bio.SeqIO.index_db() and Bio.SeqIO.to_dict() + + """ + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if not format.islower(): + raise ValueError(f"Format string '{format}' should be lower case") + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + + # Map the file format to a sequence iterator: + from Bio.File import _IndexedSeqFileDict + + from ._index import _FormatToRandomAccess # Lazy import + + try: + proxy_class = _FormatToRandomAccess[format] + except KeyError: + raise ValueError(f"Unsupported format {format!r}") from None + repr = "SeqIO.index(%r, %r, alphabet=%r, key_function=%r)" % ( + filename, + format, + alphabet, + key_function, + ) + + try: + random_access_proxy = proxy_class(filename, format) + except TypeError: + raise TypeError( + "Need a string or path-like object for the filename (not a handle)" + ) from None + + return _IndexedSeqFileDict(random_access_proxy, key_function, repr, "SeqRecord") + + +def index_db( + index_filename, filenames=None, format=None, alphabet=None, key_function=None +): + """Index several sequence files and return a dictionary like object. + + The index is stored in an SQLite database rather than in memory (as in the + Bio.SeqIO.index(...) function). + + Arguments: + - index_filename - Where to store the SQLite index + - filenames - list of strings specifying file(s) to be indexed, or when + indexing a single file this can be given as a string. + (optional if reloading an existing index, but must match) + - format - lower case string describing the file format + (optional if reloading an existing index, but must match) + - alphabet - no longer used, leave as None. + - key_function - Optional callback function which when given a + SeqRecord identifier string should return a unique + key for the dictionary. + + This indexing function will return a dictionary like object, giving the + SeqRecord objects as values: + + >>> from Bio import SeqIO + >>> files = ["GenBank/NC_000932.faa", "GenBank/NC_005816.faa"] + >>> def get_gi(name): + ... parts = name.split("|") + ... i = parts.index("gi") + ... assert i != -1 + ... return parts[i+1] + >>> idx_name = ":memory:" #use an in memory SQLite DB for this test + >>> records = SeqIO.index_db(idx_name, files, "fasta", key_function=get_gi) + >>> len(records) + 95 + >>> records["7525076"].description + 'gi|7525076|ref|NP_051101.1| Ycf2 [Arabidopsis thaliana]' + >>> records["45478717"].description + 'gi|45478717|ref|NP_995572.1| pesticin [Yersinia pestis biovar Microtus str. 91001]' + >>> records.close() + + In this example the two files contain 85 and 10 records respectively. + + BGZF compressed files are supported, and detected automatically. Ordinary + GZIP compressed files are not supported. + + See Also: Bio.SeqIO.index() and Bio.SeqIO.to_dict(), and the Python module + glob which is useful for building lists of files. + + """ + from os import fspath + + def is_pathlike(obj): + """Test if the given object can be accepted as a path.""" + try: + fspath(obj) + return True + except TypeError: + return False + + # Try and give helpful error messages: + if not is_pathlike(index_filename): + raise TypeError("Need a string or path-like object for filename (not a handle)") + if is_pathlike(filenames): + # Make the API a little more friendly, and more similar + # to Bio.SeqIO.index(...) for indexing just one file. + filenames = [filenames] + if filenames is not None and not isinstance(filenames, list): + raise TypeError( + "Need a list of filenames (as strings or path-like " + "objects), or one filename" + ) + if format is not None and not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if format and not format.islower(): + raise ValueError(f"Format string '{format}' should be lower case") + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + + # Map the file format to a sequence iterator: + from Bio.File import _SQLiteManySeqFilesDict + + from ._index import _FormatToRandomAccess # Lazy import + + repr = "SeqIO.index_db(%r, filenames=%r, format=%r, key_function=%r)" % ( + index_filename, + filenames, + format, + key_function, + ) + + def proxy_factory(format, filename=None): + """Given a filename returns proxy object, else boolean if format OK.""" + if filename: + return _FormatToRandomAccess[format](filename, format) + else: + return format in _FormatToRandomAccess + + return _SQLiteManySeqFilesDict( + index_filename, filenames, proxy_factory, format, key_function, repr + ) + + +# TODO? - Handling aliases explicitly would let us shorten this list: +_converter = { + ("genbank", "fasta"): InsdcIO._genbank_convert_fasta, + ("gb", "fasta"): InsdcIO._genbank_convert_fasta, + ("embl", "fasta"): InsdcIO._embl_convert_fasta, + ("fastq", "fasta"): QualityIO._fastq_convert_fasta, + ("fastq-sanger", "fasta"): QualityIO._fastq_convert_fasta, + ("fastq-solexa", "fasta"): QualityIO._fastq_convert_fasta, + ("fastq-illumina", "fasta"): QualityIO._fastq_convert_fasta, + ("fastq", "tab"): QualityIO._fastq_convert_tab, + ("fastq-sanger", "tab"): QualityIO._fastq_convert_tab, + ("fastq-solexa", "tab"): QualityIO._fastq_convert_tab, + ("fastq-illumina", "tab"): QualityIO._fastq_convert_tab, + ("fastq", "fastq"): QualityIO._fastq_sanger_convert_fastq_sanger, + ("fastq-sanger", "fastq"): QualityIO._fastq_sanger_convert_fastq_sanger, + ("fastq-solexa", "fastq"): QualityIO._fastq_solexa_convert_fastq_sanger, + ("fastq-illumina", "fastq"): QualityIO._fastq_illumina_convert_fastq_sanger, + ("fastq", "fastq-sanger"): QualityIO._fastq_sanger_convert_fastq_sanger, + ("fastq-sanger", "fastq-sanger"): QualityIO._fastq_sanger_convert_fastq_sanger, + ("fastq-solexa", "fastq-sanger"): QualityIO._fastq_solexa_convert_fastq_sanger, + ("fastq-illumina", "fastq-sanger"): QualityIO._fastq_illumina_convert_fastq_sanger, + ("fastq", "fastq-solexa"): QualityIO._fastq_sanger_convert_fastq_solexa, + ("fastq-sanger", "fastq-solexa"): QualityIO._fastq_sanger_convert_fastq_solexa, + ("fastq-solexa", "fastq-solexa"): QualityIO._fastq_solexa_convert_fastq_solexa, + ("fastq-illumina", "fastq-solexa"): QualityIO._fastq_illumina_convert_fastq_solexa, + ("fastq", "fastq-illumina"): QualityIO._fastq_sanger_convert_fastq_illumina, + ("fastq-sanger", "fastq-illumina"): QualityIO._fastq_sanger_convert_fastq_illumina, + ("fastq-solexa", "fastq-illumina"): QualityIO._fastq_solexa_convert_fastq_illumina, + ( + "fastq-illumina", + "fastq-illumina", + ): QualityIO._fastq_illumina_convert_fastq_illumina, + ("fastq", "qual"): QualityIO._fastq_sanger_convert_qual, + ("fastq-sanger", "qual"): QualityIO._fastq_sanger_convert_qual, + ("fastq-solexa", "qual"): QualityIO._fastq_solexa_convert_qual, + ("fastq-illumina", "qual"): QualityIO._fastq_illumina_convert_qual, +} + + +def convert(in_file, in_format, out_file, out_format, molecule_type=None): + """Convert between two sequence file formats, return number of records. + + Arguments: + - in_file - an input handle or filename + - in_format - input file format, lower case string + - out_file - an output handle or filename + - out_format - output file format, lower case string + - molecule_type - optional molecule type to apply, string containing + "DNA", "RNA" or "protein". + + **NOTE** - If you provide an output filename, it will be opened which will + overwrite any existing file without warning. + + The idea here is that while doing this will work:: + + from Bio import SeqIO + records = SeqIO.parse(in_handle, in_format) + count = SeqIO.write(records, out_handle, out_format) + + it is shorter to write:: + + from Bio import SeqIO + count = SeqIO.convert(in_handle, in_format, out_handle, out_format) + + Also, Bio.SeqIO.convert is faster for some conversions as it can make some + optimisations. + + For example, going from a filename to a handle: + + >>> from Bio import SeqIO + >>> from io import StringIO + >>> handle = StringIO("") + >>> SeqIO.convert("Quality/example.fastq", "fastq", handle, "fasta") + 3 + >>> print(handle.getvalue()) + >EAS54_6_R1_2_1_413_324 + CCCTTCTTGTCTTCAGCGTTTCTCC + >EAS54_6_R1_2_1_540_792 + TTGGCAGGCCAAGGCCGATGGATCA + >EAS54_6_R1_2_1_443_348 + GTTGCTTCTGGCGTGGGTGGGGGGG + + + Note some formats like SeqXML require you to specify the molecule type + when it cannot be determined by the parser: + + >>> from Bio import SeqIO + >>> from io import BytesIO + >>> handle = BytesIO() + >>> SeqIO.convert("Quality/example.fastq", "fastq", handle, "seqxml", "DNA") + 3 + """ + if molecule_type: + if not isinstance(molecule_type, str): + raise TypeError(f"Molecule type should be a string, not {molecule_type!r}") + elif ( + "DNA" in molecule_type + or "RNA" in molecule_type + or "protein" in molecule_type + ): + pass + else: + raise ValueError(f"Unexpected molecule type, {molecule_type!r}") + f = _converter.get((in_format, out_format)) + if f: + count = f(in_file, out_file) + else: + records = parse(in_file, in_format) + if molecule_type: + # Edit the records on the fly to set molecule type + + def over_ride(record): + """Over-ride molecule in-place.""" + record.annotations["molecule_type"] = molecule_type + return record + + records = (over_ride(_) for _ in records) + count = write(records, out_file, out_format) + return count + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_index.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_index.py new file mode 100644 index 0000000000000000000000000000000000000000..052151752effbbb8aeb6e6b213b962dc82c15049 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_index.py @@ -0,0 +1,718 @@ +# Copyright 2009-2011 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Dictionary like indexing of sequence files (PRIVATE). + +You are not expected to access this module, or any of its code, directly. This +is all handled internally by the Bio.SeqIO.index(...) and index_db(...) +functions which are the public interface for this functionality. + +The basic idea is that we scan over a sequence file, looking for new record +markers. We then try to extract the string that Bio.SeqIO.parse/read would +use as the record id, ideally without actually parsing the full record. We +then use a subclassed Python dictionary to record the file offset for the +record start against the record id. + +Note that this means full parsing is on demand, so any invalid or problem +record may not trigger an exception until it is accessed. This is by design. + +This means our dictionary like objects have in memory ALL the keys (all the +record identifiers), which shouldn't be a problem even with second generation +sequencing. If memory is an issue, the index_db(...) interface stores the +keys and offsets in an SQLite database - which can be re-used to avoid +re-indexing the file for use another time. +""" + +import re +import struct +from io import BytesIO +from io import StringIO + +from Bio import SeqIO +from Bio.File import _IndexedSeqFileProxy +from Bio.File import _open_for_random_access + + +class SeqFileRandomAccess(_IndexedSeqFileProxy): + """Base class for defining random access to sequence files.""" + + def __init__(self, filename, format): + """Initialize the class.""" + self._handle = _open_for_random_access(filename) + self._format = format + # Load the parser class/function once an avoid the dict lookup in each + # __getitem__ call: + self._iterator = SeqIO._FormatToIterator[format] + + def get(self, offset): + """Return SeqRecord.""" + # Should be overridden for binary file formats etc: + return next(self._iterator(StringIO(self.get_raw(offset).decode()))) + + +#################### +# Special indexers # +#################### +# Anything where the records cannot be read simply by parsing from +# the record start. For example, anything requiring information from +# a file header - e.g. SFF files where we would need to know the +# number of flows. +class SffRandomAccess(SeqFileRandomAccess): + """Random access to a Standard Flowgram Format (SFF) file.""" + + def __init__(self, filename, format): + """Initialize the class.""" + SeqFileRandomAccess.__init__(self, filename, format) + ( + header_length, + self.index_offset, + self.index_length, + number_of_reads, + self.number_of_flows_per_read, + self.flow_chars, + self.key_sequence, + ) = SeqIO.SffIO._sff_file_header(self._handle) + # Now on to the reads... + self.read_flow_fmt = ">%iH" % self.number_of_flows_per_read + self.read_flow_size = struct.calcsize(self.read_flow_fmt) + + def __iter__(self): + """Load any index block in the file, or build it the slow way (PRIVATE).""" + handle = self._handle + handle.seek(0) + # Already did this in __init__ but need handle in right place + ( + header_length, + index_offset, + index_length, + number_of_reads, + self.number_of_flows_per_read, + self.flow_chars, + self.key_sequence, + ) = SeqIO.SffIO._sff_file_header(handle) + if index_offset and index_length: + # There is an index provided, try this the fast way: + count = 0 + max_offset = 0 + try: + for name, offset in SeqIO.SffIO._sff_read_roche_index(handle): + max_offset = max(max_offset, offset) + yield name, offset, 0 + count += 1 + if count != number_of_reads: + raise ValueError( + "Indexed %i records, expected %i" % (count, number_of_reads) + ) + # If that worked, call _check_eof ... + except ValueError as err: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + f"Could not parse the SFF index: {err}", BiopythonParserWarning + ) + assert count == 0, "Partially populated index" + handle.seek(0) + # Drop out to the slow way... + else: + # Fast way worked, check EOF + if index_offset + index_length <= max_offset: + # Can have an index at start (or mid-file) + handle.seek(max_offset) + # Parse the final read, + SeqIO.SffIO._sff_read_raw_record( + handle, self.number_of_flows_per_read + ) + # Should now be at the end of the file! + self._offset = handle.tell() + SeqIO.SffIO.SffIterator._check_eof(self, handle) + return + # We used to give a warning in this case, but Ion Torrent's + # SFF files don't have an index so that would be annoying. + # Fall back on the slow way! + count = 0 + for name, offset in SeqIO.SffIO._sff_do_slow_index(handle): + yield name, offset, 0 + count += 1 + if count != number_of_reads: + raise ValueError( + "Indexed %i records, expected %i" % (count, number_of_reads) + ) + self._offset = handle.tell() + SeqIO.SffIO.SffIterator._check_eof(self, handle) + + def get(self, offset): + """Return the SeqRecord starting at the given offset.""" + handle = self._handle + handle.seek(offset) + self._offset = offset + self.trim = False + return SeqIO.SffIO.SffIterator._sff_read_seq_record(self, handle) + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + handle = self._handle + handle.seek(offset) + self.stream = handle + return SeqIO.SffIO._sff_read_raw_record(handle, self.number_of_flows_per_read) + + +class SffTrimedRandomAccess(SffRandomAccess): + """Random access to an SFF file with defined trimming applied to each sequence.""" + + def get(self, offset): + """Return the SeqRecord starting at the given offset.""" + handle = self._handle + handle.seek(offset) + self._offset = offset + self.trim = True + return SeqIO.SffIO.SffIterator._sff_read_seq_record(self, handle) + + +################### +# Simple indexers # +################### + + +class SequentialSeqFileRandomAccess(SeqFileRandomAccess): + """Random access to a simple sequential sequence file.""" + + def __init__(self, filename, format): + """Initialize the class.""" + SeqFileRandomAccess.__init__(self, filename, format) + marker = { + "ace": b"CO ", + "embl": b"ID ", + "fasta": b">", + "genbank": b"LOCUS ", + "gb": b"LOCUS ", + "imgt": b"ID ", + "phd": b"BEGIN_SEQUENCE", + "pir": b">..;", + "qual": b">", + "swiss": b"ID ", + "uniprot-xml": b" end of this record + break + lines.append(line) + return b"".join(lines) + + +####################################### +# Fiddly indexers: GenBank, EMBL, ... # +####################################### + + +class GenBankRandomAccess(SequentialSeqFileRandomAccess): + """Indexed dictionary like access to a GenBank file.""" + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + marker_re = self._marker_re + accession_marker = b"ACCESSION " + version_marker = b"VERSION " + # Skip and header before first record + while True: + start_offset = handle.tell() + line = handle.readline() + if marker_re.match(line) or not line: + break + # Should now be at the start of a record, or end of the file + while marker_re.match(line): + # We cannot assume the record.id is the first word after LOCUS, + # normally the first entry on the VERSION or ACCESSION line is used. + # However if both missing, GenBank parser falls back on LOCUS entry. + try: + key = line[5:].split(None, 1)[0] + except ValueError: + # Warning? + # No content in LOCUS line + key = None + length = len(line) + while True: + end_offset = handle.tell() + line = handle.readline() + if marker_re.match(line) or not line: + if not key: + raise ValueError( + "Did not find usable ACCESSION/VERSION/LOCUS lines" + ) + yield key.decode(), start_offset, length + start_offset = end_offset + break + elif line.startswith(accession_marker): + try: + key = line.rstrip().split()[1] + except IndexError: + # No content in ACCESSION line + pass + elif line.startswith(version_marker): + try: + version_id = line.rstrip().split()[1] + if ( + version_id.count(b".") == 1 + and version_id.split(b".")[1].isdigit() + ): + # This should mimic the GenBank parser... + key = version_id + except IndexError: + # No content in VERSION line + pass + + length += len(line) + assert not line, repr(line) + + +class EmblRandomAccess(SequentialSeqFileRandomAccess): + """Indexed dictionary like access to an EMBL file.""" + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + marker_re = self._marker_re + sv_marker = b"SV " + ac_marker = b"AC " + # Skip any header before first record + while True: + start_offset = handle.tell() + line = handle.readline() + if marker_re.match(line) or not line: + break + # Should now be at the start of a record, or end of the file + while marker_re.match(line): + # We cannot assume the record.id is the first word after ID, + # normally the SV line is used. + setbysv = False # resets sv as false + length = len(line) + if line[2:].count(b";") in [5, 6]: + # Looks like the semi colon separated style introduced in 2006 + # Or style from IPD-IMGT/HLA after their v3.16.0 release + parts = line[3:].rstrip().split(b";") + if parts[1].strip().startswith(sv_marker): + # The SV bit gives the version + key = parts[0].strip() + b"." + parts[1].strip().split()[1] + setbysv = True + else: + key = parts[0].strip() + elif line[2:].count(b";") in [2, 3]: + # Looks like the pre 2006 style, take first word only + # Or, with two colons, the KIPO patent variation + key = line[3:].strip().split(None, 1)[0] + if key.endswith(b";"): + key = key[:-1] + else: + raise ValueError(f"Did not recognise the ID line layout:\n{line!r}") + while True: + line = handle.readline() + if marker_re.match(line) or not line: + end_offset = handle.tell() - len(line) + yield key.decode(), start_offset, length + start_offset = end_offset + break + elif line.startswith(ac_marker) and not setbysv: + key = line.rstrip().split()[1] + if key.endswith(b";"): + key = key[:-1] + elif line.startswith(sv_marker): + key = line.rstrip().split()[1] + setbysv = True + length += len(line) + assert not line, repr(line) + + +class SwissRandomAccess(SequentialSeqFileRandomAccess): + """Random access to a SwissProt file.""" + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + marker_re = self._marker_re + # Skip any header before first record + while True: + start_offset = handle.tell() + line = handle.readline() + if marker_re.match(line) or not line: + break + # Should now be at the start of a record, or end of the file + while marker_re.match(line): + length = len(line) + # We cannot assume the record.id is the first word after ID, + # normally the following AC line is used. + line = handle.readline() + length += len(line) + assert line.startswith(b"AC ") + key = line[3:].strip().split(b";")[0].strip() + while True: + end_offset = handle.tell() + line = handle.readline() + if marker_re.match(line) or not line: + yield key.decode(), start_offset, length + start_offset = end_offset + break + length += len(line) + assert not line, repr(line) + + +class UniprotRandomAccess(SequentialSeqFileRandomAccess): + """Random access to a UniProt XML file.""" + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + marker_re = self._marker_re + start_acc_marker = b"" + end_acc_marker = b"" + end_entry_marker = b"" + # Skip any header before first record + while True: + start_offset = handle.tell() + line = handle.readline() + if marker_re.match(line) or not line: + break + # Should now be at the start of a record, or end of the file + while marker_re.match(line): + length = len(line) + # We expect the next line to be xxx + # (possibly with leading spaces) + # but allow it to be later on within the + key = None + while True: + line = handle.readline() + if key is None and start_acc_marker in line: + assert end_acc_marker in line, line + key = line[line.find(start_acc_marker) + 11 :].split(b"<", 1)[0] + length += len(line) + elif end_entry_marker in line: + length += line.find(end_entry_marker) + 8 + end_offset = ( + handle.tell() - len(line) + line.find(end_entry_marker) + 8 + ) + assert start_offset + length == end_offset + break + elif marker_re.match(line) or not line: + # Start of next record or end of file + raise ValueError("Didn't find end of record") + else: + length += len(line) + if not key: + raise ValueError( + "Did not find line in bytes %i to %i" + % (start_offset, start_offset + length) + ) + yield key.decode(), start_offset, length + # Find start of next record + while not marker_re.match(line) and line: + start_offset = handle.tell() + line = handle.readline() + assert not line, repr(line) + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + handle = self._handle + marker_re = self._marker_re + end_entry_marker = b"" + handle.seek(offset) + data = [handle.readline()] + while True: + line = handle.readline() + i = line.find(end_entry_marker) + if i != -1: + data.append(line[: i + 8]) + break + if marker_re.match(line) or not line: + # End of file, or start of next record + raise ValueError("Didn't find end of record") + data.append(line) + return b"".join(data) + + def get(self, offset): + """Return the SeqRecord starting at the given offset.""" + # TODO - Can we handle this directly in the parser? + # This is a hack - use get_raw for ... and wrap it with + # the apparently required XML header and footer. + data = ( + b""" + + """ + + self.get_raw(offset) + + b"" + ) + return next(SeqIO.UniprotIO.UniprotIterator(BytesIO(data))) + + +class IntelliGeneticsRandomAccess(SeqFileRandomAccess): + """Random access to a IntelliGenetics file.""" + + def __init__(self, filename, format): + """Initialize the class.""" + SeqFileRandomAccess.__init__(self, filename, format) + self._marker_re = re.compile(b"^;") + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + # Skip any header + offset = 0 + line = "" + while True: + offset += len(line) + line = handle.readline() + if not line: + break # Premature end of file, or just empty? + if not line.startswith(b";;"): + break + while line: + length = 0 + assert offset + len(line) == handle.tell() + if not line.startswith(b";"): + raise ValueError(f"Records should start with ';' and not:\n{line!r}") + while line.startswith(b";"): + length += len(line) + line = handle.readline() + key = line.rstrip() + # Now look for the first line which starts ";" + while line and not line.startswith(b";"): + length += len(line) + line = handle.readline() + yield key.decode(), offset, length + offset += length + assert offset + len(line) == handle.tell() + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + handle = self._handle + handle.seek(offset) + marker_re = self._marker_re + lines = [] + line = handle.readline() + while line.startswith(b";"): + lines.append(line) + line = handle.readline() + while line and not line.startswith(b";"): + lines.append(line) + line = handle.readline() + return b"".join(lines) + + +class TabRandomAccess(SeqFileRandomAccess): + """Random access to a simple tabbed file.""" + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + tab_char = b"\t" + while True: + start_offset = handle.tell() + line = handle.readline() + if not line: + break # End of file + try: + key = line.split(tab_char)[0] + except ValueError: + if not line.strip(): + # Ignore blank lines + continue + else: + raise + else: + yield key.decode(), start_offset, len(line) + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + handle = self._handle + handle.seek(offset) + return handle.readline() + + +########################## +# Now the FASTQ indexers # +########################## + + +class FastqRandomAccess(SeqFileRandomAccess): + """Random access to a FASTQ file (any supported variant). + + With FASTQ the records all start with a "@" line, but so can quality lines. + Note this will cope with line-wrapped FASTQ files. + """ + + def __iter__(self): + """Iterate over the sequence records in the file.""" + handle = self._handle + handle.seek(0) + id = None + start_offset = handle.tell() + line = handle.readline() + if not line: + # Empty file! + return + if line[0:1] != b"@": + raise ValueError(f"Problem with FASTQ @ line:\n{line!r}") + while line: + # assert line[0]=="@" + # This record seems OK (so far) + id = line[1:].rstrip().split(None, 1)[0] + # Find the seq line(s) + seq_len = 0 + length = len(line) + while line: + line = handle.readline() + length += len(line) + if line.startswith(b"+"): + break + seq_len += len(line.strip()) + if not line: + raise ValueError("Premature end of file in seq section") + # assert line[0]=="+" + # Find the qual line(s) + qual_len = 0 + while line: + if seq_len == qual_len: + if seq_len == 0: + # Special case, quality line should be just "\n" + line = handle.readline() + if line.strip(): + raise ValueError( + f"Expected blank quality line, not {line!r}" + ) + length += len(line) # Need to include the blank ling + # Should be end of record... + end_offset = handle.tell() + line = handle.readline() + if line and line[0:1] != b"@": + raise ValueError(f"Problem with line {line!r}") + break + else: + line = handle.readline() + qual_len += len(line.strip()) + length += len(line) + if seq_len != qual_len: + raise ValueError("Problem with quality section") + yield id.decode(), start_offset, length + start_offset = end_offset + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string.""" + # TODO - Refactor this and the __init__ method to reduce code duplication? + handle = self._handle + handle.seek(offset) + line = handle.readline() + data = line + if line[0:1] != b"@": + raise ValueError(f"Problem with FASTQ @ line:\n{line!r}") + # Find the seq line(s) + seq_len = 0 + while line: + line = handle.readline() + data += line + if line.startswith(b"+"): + break + seq_len += len(line.strip()) + if not line: + raise ValueError("Premature end of file in seq section") + assert line[0:1] == b"+" + # Find the qual line(s) + qual_len = 0 + while line: + if seq_len == qual_len: + if seq_len == 0: + # Special case, quality line should be just "\n" + line = handle.readline() + if line.strip(): + raise ValueError(f"Expected blank quality line, not {line!r}") + data += line + # Should be end of record... + line = handle.readline() + if line and line[0:1] != b"@": + raise ValueError(f"Problem with line {line!r}") + break + else: + line = handle.readline() + data += line + qual_len += len(line.strip()) + if seq_len != qual_len: + raise ValueError("Problem with quality section") + return data + + +############################################################################### + +_FormatToRandomAccess = { + "ace": SequentialSeqFileRandomAccess, + "embl": EmblRandomAccess, + "fasta": SequentialSeqFileRandomAccess, + "fastq": FastqRandomAccess, # Class handles all three variants + "fastq-sanger": FastqRandomAccess, # alias of the above + "fastq-solexa": FastqRandomAccess, + "fastq-illumina": FastqRandomAccess, + "genbank": GenBankRandomAccess, + "gb": GenBankRandomAccess, # alias of the above + "ig": IntelliGeneticsRandomAccess, + "imgt": EmblRandomAccess, + "phd": SequentialSeqFileRandomAccess, + "pir": SequentialSeqFileRandomAccess, + "sff": SffRandomAccess, + "sff-trim": SffTrimedRandomAccess, + "swiss": SwissRandomAccess, + "tab": TabRandomAccess, + "qual": SequentialSeqFileRandomAccess, + "uniprot-xml": UniprotRandomAccess, +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_twoBitIO.c b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_twoBitIO.c new file mode 100644 index 0000000000000000000000000000000000000000..149db94e13d0cbeb01d135e9a07869d66b1fa1df --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_twoBitIO.c @@ -0,0 +1,482 @@ +#define PY_SSIZE_T_CLEAN +#include "Python.h" + + +static const char bases[][4] = {"TTTT", /* 00 00 00 00 */ + "TTTC", /* 00 00 00 01 */ + "TTTA", /* 00 00 00 10 */ + "TTTG", /* 00 00 00 11 */ + "TTCT", /* 00 00 01 00 */ + "TTCC", /* 00 00 01 01 */ + "TTCA", /* 00 00 01 10 */ + "TTCG", /* 00 00 01 11 */ + "TTAT", /* 00 00 10 00 */ + "TTAC", /* 00 00 10 01 */ + "TTAA", /* 00 00 10 10 */ + "TTAG", /* 00 00 10 11 */ + "TTGT", /* 00 00 11 00 */ + "TTGC", /* 00 00 11 01 */ + "TTGA", /* 00 00 11 10 */ + "TTGG", /* 00 00 11 11 */ + "TCTT", /* 00 01 00 00 */ + "TCTC", /* 00 01 00 01 */ + "TCTA", /* 00 01 00 10 */ + "TCTG", /* 00 01 00 11 */ + "TCCT", /* 00 01 01 00 */ + "TCCC", /* 00 01 01 01 */ + "TCCA", /* 00 01 01 10 */ + "TCCG", /* 00 01 01 11 */ + "TCAT", /* 00 01 10 00 */ + "TCAC", /* 00 01 10 01 */ + "TCAA", /* 00 01 10 10 */ + "TCAG", /* 00 01 10 11 */ + "TCGT", /* 00 01 11 00 */ + "TCGC", /* 00 01 11 01 */ + "TCGA", /* 00 01 11 10 */ + "TCGG", /* 00 01 11 11 */ + "TATT", /* 00 10 00 00 */ + "TATC", /* 00 10 00 01 */ + "TATA", /* 00 10 00 10 */ + "TATG", /* 00 10 00 11 */ + "TACT", /* 00 10 01 00 */ + "TACC", /* 00 10 01 01 */ + "TACA", /* 00 10 01 10 */ + "TACG", /* 00 10 01 11 */ + "TAAT", /* 00 10 10 00 */ + "TAAC", /* 00 10 10 01 */ + "TAAA", /* 00 10 10 10 */ + "TAAG", /* 00 10 10 11 */ + "TAGT", /* 00 10 11 00 */ + "TAGC", /* 00 10 11 01 */ + "TAGA", /* 00 10 11 10 */ + "TAGG", /* 00 10 11 11 */ + "TGTT", /* 00 11 00 00 */ + "TGTC", /* 00 11 00 01 */ + "TGTA", /* 00 11 00 10 */ + "TGTG", /* 00 11 00 11 */ + "TGCT", /* 00 11 01 00 */ + "TGCC", /* 00 11 01 01 */ + "TGCA", /* 00 11 01 10 */ + "TGCG", /* 00 11 01 11 */ + "TGAT", /* 00 11 10 00 */ + "TGAC", /* 00 11 10 01 */ + "TGAA", /* 00 11 10 10 */ + "TGAG", /* 00 11 10 11 */ + "TGGT", /* 00 11 11 00 */ + "TGGC", /* 00 11 11 01 */ + "TGGA", /* 00 11 11 10 */ + "TGGG", /* 00 11 11 11 */ + "CTTT", /* 01 00 00 00 */ + "CTTC", /* 01 00 00 01 */ + "CTTA", /* 01 00 00 10 */ + "CTTG", /* 01 00 00 11 */ + "CTCT", /* 01 00 01 00 */ + "CTCC", /* 01 00 01 01 */ + "CTCA", /* 01 00 01 10 */ + "CTCG", /* 01 00 01 11 */ + "CTAT", /* 01 00 10 00 */ + "CTAC", /* 01 00 10 01 */ + "CTAA", /* 01 00 10 10 */ + "CTAG", /* 01 00 10 11 */ + "CTGT", /* 01 00 11 00 */ + "CTGC", /* 01 00 11 01 */ + "CTGA", /* 01 00 11 10 */ + "CTGG", /* 01 00 11 11 */ + "CCTT", /* 01 01 00 00 */ + "CCTC", /* 01 01 00 01 */ + "CCTA", /* 01 01 00 10 */ + "CCTG", /* 01 01 00 11 */ + "CCCT", /* 01 01 01 00 */ + "CCCC", /* 01 01 01 01 */ + "CCCA", /* 01 01 01 10 */ + "CCCG", /* 01 01 01 11 */ + "CCAT", /* 01 01 10 00 */ + "CCAC", /* 01 01 10 01 */ + "CCAA", /* 01 01 10 10 */ + "CCAG", /* 01 01 10 11 */ + "CCGT", /* 01 01 11 00 */ + "CCGC", /* 01 01 11 01 */ + "CCGA", /* 01 01 11 10 */ + "CCGG", /* 01 01 11 11 */ + "CATT", /* 01 10 00 00 */ + "CATC", /* 01 10 00 01 */ + "CATA", /* 01 10 00 10 */ + "CATG", /* 01 10 00 11 */ + "CACT", /* 01 10 01 00 */ + "CACC", /* 01 10 01 01 */ + "CACA", /* 01 10 01 10 */ + "CACG", /* 01 10 01 11 */ + "CAAT", /* 01 10 10 00 */ + "CAAC", /* 01 10 10 01 */ + "CAAA", /* 01 10 10 10 */ + "CAAG", /* 01 10 10 11 */ + "CAGT", /* 01 10 11 00 */ + "CAGC", /* 01 10 11 01 */ + "CAGA", /* 01 10 11 10 */ + "CAGG", /* 01 10 11 11 */ + "CGTT", /* 01 11 00 00 */ + "CGTC", /* 01 11 00 01 */ + "CGTA", /* 01 11 00 10 */ + "CGTG", /* 01 11 00 11 */ + "CGCT", /* 01 11 01 00 */ + "CGCC", /* 01 11 01 01 */ + "CGCA", /* 01 11 01 10 */ + "CGCG", /* 01 11 01 11 */ + "CGAT", /* 01 11 10 00 */ + "CGAC", /* 01 11 10 01 */ + "CGAA", /* 01 11 10 10 */ + "CGAG", /* 01 11 10 11 */ + "CGGT", /* 01 11 11 00 */ + "CGGC", /* 01 11 11 01 */ + "CGGA", /* 01 11 11 10 */ + "CGGG", /* 01 11 11 11 */ + "ATTT", /* 10 00 00 00 */ + "ATTC", /* 10 00 00 01 */ + "ATTA", /* 10 00 00 10 */ + "ATTG", /* 10 00 00 11 */ + "ATCT", /* 10 00 01 00 */ + "ATCC", /* 10 00 01 01 */ + "ATCA", /* 10 00 01 10 */ + "ATCG", /* 10 00 01 11 */ + "ATAT", /* 10 00 10 00 */ + "ATAC", /* 10 00 10 01 */ + "ATAA", /* 10 00 10 10 */ + "ATAG", /* 10 00 10 11 */ + "ATGT", /* 10 00 11 00 */ + "ATGC", /* 10 00 11 01 */ + "ATGA", /* 10 00 11 10 */ + "ATGG", /* 10 00 11 11 */ + "ACTT", /* 10 01 00 00 */ + "ACTC", /* 10 01 00 01 */ + "ACTA", /* 10 01 00 10 */ + "ACTG", /* 10 01 00 11 */ + "ACCT", /* 10 01 01 00 */ + "ACCC", /* 10 01 01 01 */ + "ACCA", /* 10 01 01 10 */ + "ACCG", /* 10 01 01 11 */ + "ACAT", /* 10 01 10 00 */ + "ACAC", /* 10 01 10 01 */ + "ACAA", /* 10 01 10 10 */ + "ACAG", /* 10 01 10 11 */ + "ACGT", /* 10 01 11 00 */ + "ACGC", /* 10 01 11 01 */ + "ACGA", /* 10 01 11 10 */ + "ACGG", /* 10 01 11 11 */ + "AATT", /* 10 10 00 00 */ + "AATC", /* 10 10 00 01 */ + "AATA", /* 10 10 00 10 */ + "AATG", /* 10 10 00 11 */ + "AACT", /* 10 10 01 00 */ + "AACC", /* 10 10 01 01 */ + "AACA", /* 10 10 01 10 */ + "AACG", /* 10 10 01 11 */ + "AAAT", /* 10 10 10 00 */ + "AAAC", /* 10 10 10 01 */ + "AAAA", /* 10 10 10 10 */ + "AAAG", /* 10 10 10 11 */ + "AAGT", /* 10 10 11 00 */ + "AAGC", /* 10 10 11 01 */ + "AAGA", /* 10 10 11 10 */ + "AAGG", /* 10 10 11 11 */ + "AGTT", /* 10 11 00 00 */ + "AGTC", /* 10 11 00 01 */ + "AGTA", /* 10 11 00 10 */ + "AGTG", /* 10 11 00 11 */ + "AGCT", /* 10 11 01 00 */ + "AGCC", /* 10 11 01 01 */ + "AGCA", /* 10 11 01 10 */ + "AGCG", /* 10 11 01 11 */ + "AGAT", /* 10 11 10 00 */ + "AGAC", /* 10 11 10 01 */ + "AGAA", /* 10 11 10 10 */ + "AGAG", /* 10 11 10 11 */ + "AGGT", /* 10 11 11 00 */ + "AGGC", /* 10 11 11 01 */ + "AGGA", /* 10 11 11 10 */ + "AGGG", /* 10 11 11 11 */ + "GTTT", /* 11 00 00 00 */ + "GTTC", /* 11 00 00 01 */ + "GTTA", /* 11 00 00 10 */ + "GTTG", /* 11 00 00 11 */ + "GTCT", /* 11 00 01 00 */ + "GTCC", /* 11 00 01 01 */ + "GTCA", /* 11 00 01 10 */ + "GTCG", /* 11 00 01 11 */ + "GTAT", /* 11 00 10 00 */ + "GTAC", /* 11 00 10 01 */ + "GTAA", /* 11 00 10 10 */ + "GTAG", /* 11 00 10 11 */ + "GTGT", /* 11 00 11 00 */ + "GTGC", /* 11 00 11 01 */ + "GTGA", /* 11 00 11 10 */ + "GTGG", /* 11 00 11 11 */ + "GCTT", /* 11 01 00 00 */ + "GCTC", /* 11 01 00 01 */ + "GCTA", /* 11 01 00 10 */ + "GCTG", /* 11 01 00 11 */ + "GCCT", /* 11 01 01 00 */ + "GCCC", /* 11 01 01 01 */ + "GCCA", /* 11 01 01 10 */ + "GCCG", /* 11 01 01 11 */ + "GCAT", /* 11 01 10 00 */ + "GCAC", /* 11 01 10 01 */ + "GCAA", /* 11 01 10 10 */ + "GCAG", /* 11 01 10 11 */ + "GCGT", /* 11 01 11 00 */ + "GCGC", /* 11 01 11 01 */ + "GCGA", /* 11 01 11 10 */ + "GCGG", /* 11 01 11 11 */ + "GATT", /* 11 10 00 00 */ + "GATC", /* 11 10 00 01 */ + "GATA", /* 11 10 00 10 */ + "GATG", /* 11 10 00 11 */ + "GACT", /* 11 10 01 00 */ + "GACC", /* 11 10 01 01 */ + "GACA", /* 11 10 01 10 */ + "GACG", /* 11 10 01 11 */ + "GAAT", /* 11 10 10 00 */ + "GAAC", /* 11 10 10 01 */ + "GAAA", /* 11 10 10 10 */ + "GAAG", /* 11 10 10 11 */ + "GAGT", /* 11 10 11 00 */ + "GAGC", /* 11 10 11 01 */ + "GAGA", /* 11 10 11 10 */ + "GAGG", /* 11 10 11 11 */ + "GGTT", /* 11 11 00 00 */ + "GGTC", /* 11 11 00 01 */ + "GGTA", /* 11 11 00 10 */ + "GGTG", /* 11 11 00 11 */ + "GGCT", /* 11 11 01 00 */ + "GGCC", /* 11 11 01 01 */ + "GGCA", /* 11 11 01 10 */ + "GGCG", /* 11 11 01 11 */ + "GGAT", /* 11 11 10 00 */ + "GGAC", /* 11 11 10 01 */ + "GGAA", /* 11 11 10 10 */ + "GGAG", /* 11 11 10 11 */ + "GGGT", /* 11 11 11 00 */ + "GGGC", /* 11 11 11 01 */ + "GGGA", /* 11 11 11 10 */ + "GGGG", /* 11 11 11 11 */ + }; + +static int +extract(const unsigned char* bytes, Py_ssize_t byteSize, + Py_ssize_t start, Py_ssize_t end, char sequence[]) { + Py_ssize_t i; + const Py_ssize_t size = end - start; + const Py_ssize_t byteStart = start / 4; + const Py_ssize_t byteEnd = (end + 3) / 4; + + if (byteSize != byteEnd - byteStart) { + PyErr_Format(PyExc_RuntimeError, + "unexpected number of bytes %u (expected %u)", + byteSize, byteEnd - byteStart); + return -1; + } + + start -= byteStart * 4; + if (byteStart + 1 == byteEnd) { + /* one byte only */ + memcpy(sequence, &(bases[*bytes][start]), size); + } + else { + end -= byteEnd * 4; + /* end is now a negative number equal to the distance to the byte end */ + memcpy(sequence, &(bases[*bytes][start]), 4 - start); + bytes++; + sequence += (4 - start); + for (i = byteStart+1; i < byteEnd-1; i++, bytes++, sequence += 4) + memcpy(sequence, bases[*bytes], 4); + memcpy(sequence, bases[*bytes], end + 4); + bytes++; + bytes -= byteSize; + } + return 0; +} + +static void +applyNs(char sequence[], Py_ssize_t start, Py_ssize_t end, Py_buffer *nBlocks) +{ + const Py_ssize_t nBlockCount = nBlocks->shape[0]; + const uint32_t* const nBlockPositions = nBlocks->buf; + + Py_ssize_t i; + for (i = 0; i < nBlockCount; i++) { + Py_ssize_t nBlockStart = nBlockPositions[2*i]; + Py_ssize_t nBlockEnd = nBlockPositions[2*i+1]; + if (nBlockEnd < start) continue; + if (end < nBlockStart) break; + if (nBlockStart < start) nBlockStart = start; + if (end < nBlockEnd) nBlockEnd = end; + memset(sequence + nBlockStart - start, 'N', nBlockEnd - nBlockStart); + } +} + +static void +applyMask(char sequence[], Py_ssize_t start, Py_ssize_t end, + Py_buffer* maskBlocks) +{ + const Py_ssize_t maskBlockCount = maskBlocks->shape[0]; + const uint32_t* const maskBlockPositions = maskBlocks->buf; + const char diff = 'a' - 'A'; + + Py_ssize_t i; + for (i = 0; i < maskBlockCount; i++) { + Py_ssize_t j; + Py_ssize_t maskBlockStart = maskBlockPositions[2*i]; + Py_ssize_t maskBlockEnd = maskBlockPositions[2*i+1]; + if (maskBlockEnd < start) continue; + if (end < maskBlockStart) break; + if (maskBlockStart < start) maskBlockStart = start; + if (end < maskBlockEnd) maskBlockEnd = end; + for (j = maskBlockStart - start; j < maskBlockEnd - start; j++) + sequence[j] += diff; + } +} + +static int +blocks_converter(PyObject* object, void* pointer) +{ + const int flag = PyBUF_ND | PyBUF_FORMAT; + Py_buffer *view = pointer; + + if (object == NULL) goto exit; + + if (PyObject_GetBuffer(object, view, flag) == -1) { + PyErr_SetString(PyExc_RuntimeError, "blocks have unexpected format."); + return 0; + } + + if (view->itemsize != sizeof(uint32_t) + || (strcmp(view->format, "I") != 0 && strcmp(view->format, "L") != 0 )) { + PyErr_Format(PyExc_RuntimeError, + "blocks have incorrect data type (itemsize %zd, format %s)", + view->itemsize, view->format); + goto exit; + } + if (view->ndim != 2) { + PyErr_Format(PyExc_RuntimeError, + "blocks have incorrect rank %d (expected 2)", view->ndim); + goto exit; + } + if (view->shape[1] != 2) { + PyErr_Format(PyExc_RuntimeError, + "blocks should have two columns (found %zd)", + view->shape[1]); + goto exit; + } + return Py_CLEANUP_SUPPORTED; + +exit: + PyBuffer_Release(view); + return 0; +} + +static char TwoBit_convert__doc__[] = "convert twoBit data to the DNA sequence, apply blocks of N's (representing unknown sequences) and masked (lower case) blocks, and return the sequence as a bytes object"; + +static PyObject* +TwoBit_convert(PyObject* self, PyObject* args, PyObject* keywords) +{ + const unsigned char *data; + Py_ssize_t start; + Py_ssize_t end; + Py_ssize_t step; + Py_ssize_t size; + Py_ssize_t length; + Py_buffer nBlocks; + Py_buffer maskBlocks; + PyObject *object; + char *sequence; + + static char* kwlist[] = {"data", "start", "end", "step", + "nBlocks", "maskBlocks", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, keywords, "y#nnnO&O&", kwlist, + &data, &length, &start, &end, &step, + &blocks_converter, &nBlocks, + &blocks_converter, &maskBlocks)) + return NULL; + + size = (end - start) / step; + object = PyBytes_FromStringAndSize(NULL, size); + if (!object) goto exit; + + sequence = PyBytes_AS_STRING(object); + + if (step == 1) { + if (extract(data, length, start, end, sequence) < 0) { + Py_DECREF(object); + object = NULL; + goto exit; + } + applyNs(sequence, start, end, &nBlocks); + applyMask(sequence, start, end, &maskBlocks); + } + else { + Py_ssize_t current, i; + Py_ssize_t full_start, full_end; + char* full_sequence; + if (start <= end) { + full_start = start; + full_end = end; + current = 0; /* first position in sequence */ + } + else { + full_start = end + 1; + full_end = start + 1; + current = start - end - 1; /* last position in sequence */ + } + full_sequence = PyMem_Malloc((full_end-full_start+1)*sizeof(char)); + full_sequence[full_end-full_start] = '\0'; + if (!full_sequence) { + Py_DECREF(object); + object = NULL; + goto exit; + } + if (extract(data, length, full_start, full_end, full_sequence) < 0) { + PyMem_Free(full_sequence); + Py_DECREF(object); + object = NULL; + goto exit; + } + applyNs(full_sequence, full_start, full_end, &nBlocks); + applyMask(full_sequence, full_start, full_end, &maskBlocks); + for (i = 0; i < size; current += step, i++) + sequence[i] = full_sequence[current]; + PyMem_Free(full_sequence); + } + +exit: + blocks_converter(NULL, &nBlocks); + blocks_converter(NULL, &maskBlocks); + return object; +} + +static struct PyMethodDef _twoBitIO_methods[] = { + {"convert", + (PyCFunction)TwoBit_convert, + METH_VARARGS | METH_KEYWORDS, + TwoBit_convert__doc__ + }, + {NULL, NULL, 0, NULL} /* sentinel */ +}; + + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "_twoBitIO", + "Parser for DNA sequence data in 2bit format", + -1, + _twoBitIO_methods, + NULL, + NULL, + NULL, + NULL +}; + +PyObject * +PyInit__twoBitIO(void) +{ + return PyModule_Create(&moduledef); +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_twoBitIO.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_twoBitIO.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..85de809f07d05340ad50bdda027b6d26ed99009c Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqIO/_twoBitIO.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqRecord.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqRecord.py new file mode 100644 index 0000000000000000000000000000000000000000..621e83c424f7e594091c220c3a58b088f8e5f788 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqRecord.py @@ -0,0 +1,1541 @@ +# Copyright 2000-2002 Andrew Dalke. All rights reserved. +# Copyright 2002-2004 Brad Chapman. All rights reserved. +# Copyright 2006-2023 by Peter Cock. All rights reserved. +# Copyright 2020 by Michael R. Crusoe +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Represent a Sequence Record, a sequence with annotation.""" + +# NEEDS TO BE SYNCH WITH THE REST OF BIOPYTHON AND BIOPERL +# In particular, the SeqRecord and BioSQL.BioSeq.DBSeqRecord classes +# need to be in sync (this is the BioSQL "Database SeqRecord"). +import numbers +from typing import Any +from typing import cast +from collections.abc import Iterator +from typing import NoReturn +from typing import Optional +from typing import overload +from collections.abc import Sequence +from typing import TYPE_CHECKING +from typing import Union + +from Bio import StreamModeError +from Bio.Seq import MutableSeq +from Bio.Seq import Seq +from Bio.Seq import UndefinedSequenceError + +if TYPE_CHECKING: + from Bio.SeqFeature import SeqFeature + +_NO_SEQRECORD_COMPARISON = "SeqRecord comparison is deliberately not implemented. Explicitly compare the attributes of interest." + + +class _RestrictedDict(dict[str, Sequence[Any]]): + """Dict which only allows sequences of given length as values (PRIVATE). + + This simple subclass of the Python dictionary is used in the SeqRecord + object for holding per-letter-annotations. This class is intended to + prevent simple errors by only allowing python sequences (e.g. lists, + strings and tuples) to be stored, and only if their length matches that + expected (the length of the SeqRecord's seq object). It cannot however + prevent the entries being edited in situ (for example appending entries + to a list). + + >>> x = _RestrictedDict(5) + >>> x["test"] = "hello" + >>> x + {'test': 'hello'} + + Adding entries which don't have the expected length are blocked: + + >>> x["test"] = "hello world" + Traceback (most recent call last): + ... + TypeError: Any per-letter annotation should be a Python sequence (list, tuple or string) of the same length as the biological sequence, here 5. + + The expected length is stored as a private attribute, + + >>> x._length + 5 + + In order that the SeqRecord (and other objects using this class) can be + pickled, for example for use in the multiprocessing library, we need to + be able to pickle the restricted dictionary objects. + + Using the default protocol, which is 3 on Python 3, + + >>> import pickle + >>> y = pickle.loads(pickle.dumps(x)) + >>> y + {'test': 'hello'} + >>> y._length + 5 + + Using the highest protocol, which is 4 on Python 3, + + >>> import pickle + >>> z = pickle.loads(pickle.dumps(x, pickle.HIGHEST_PROTOCOL)) + >>> z + {'test': 'hello'} + >>> z._length + 5 + """ + + def __init__(self, length: int) -> None: + """Create an EMPTY restricted dictionary.""" + dict.__init__(self) + self._length = int(length) + + def __setitem__(self, key: str, value: Sequence[Any]) -> None: + # The check hasattr(self, "_length") is to cope with pickle protocol 2 + # I couldn't seem to avoid this with __getstate__ and __setstate__ + if ( + not hasattr(value, "__len__") + or not hasattr(value, "__getitem__") + or (hasattr(self, "_length") and len(value) != self._length) + ): + raise TypeError( + "Any per-letter annotation should be a Python sequence " + "(list, tuple or string) of the same length as the " + f"biological sequence, here {self._length}." + ) + dict.__setitem__(self, key, value) + + def update(self, new_dict): + # Force this to go via our strict __setitem__ method + for key, value in new_dict.items(): + self[key] = value + + +class SeqRecord: + """A SeqRecord object holds a sequence and information about it. + + Main attributes: + - id - Identifier such as a locus tag (string) + - seq - The sequence itself (Seq object or similar) + + Additional attributes: + - name - Sequence name, e.g. gene name (string) + - description - Additional text (string) + - dbxrefs - List of database cross references (list of strings) + - features - Any (sub)features defined (list of SeqFeature objects) + - annotations - Further information about the whole sequence (dictionary). + Most entries are strings, or lists of strings. + - letter_annotations - Per letter/symbol annotation (restricted + dictionary). This holds Python sequences (lists, strings + or tuples) whose length matches that of the sequence. + A typical use would be to hold a list of integers + representing sequencing quality scores, or a string + representing the secondary structure. + + You will typically use Bio.SeqIO to read in sequences from files as + SeqRecord objects. However, you may want to create your own SeqRecord + objects directly (see the __init__ method for further details): + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"), + ... id="YP_025292.1", name="HokC", + ... description="toxic membrane protein") + >>> print(record) + ID: YP_025292.1 + Name: HokC + Description: toxic membrane protein + Number of features: 0 + Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF') + + If you want to save SeqRecord objects to a sequence file, use Bio.SeqIO + for this. For the special case where you want the SeqRecord turned into + a string in a particular file format there is a format method which uses + Bio.SeqIO internally: + + >>> print(record.format("fasta")) + >YP_025292.1 toxic membrane protein + MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF + + + You can also do things like slicing a SeqRecord, checking its length, etc + + >>> len(record) + 44 + >>> edited = record[:10] + record[11:] + >>> print(edited.seq) + MKQHKAMIVAIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF + >>> print(record.seq) + MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF + + """ + + _AnnotationsDictValue = str | int + _AnnotationsDict = dict[str, _AnnotationsDictValue] + + annotations: _AnnotationsDict + dbxrefs: list[str] + _per_letter_annotations: _RestrictedDict | None + + def __init__( + self, + seq: Union["Seq", "MutableSeq"] | None, + id: str | None = "", + name: str = "", + description: str = "", + dbxrefs: list[str] | None = None, + features: list["SeqFeature"] | None = None, + annotations: _AnnotationsDict | None = None, + letter_annotations: dict[str, Sequence[Any]] | None = None, + ) -> None: + """Create a SeqRecord. + + Arguments: + - seq - Sequence, required (Seq or MutableSeq) + - id - Sequence identifier, recommended (string) + - name - Sequence name, optional (string) + - description - Sequence description, optional (string) + - dbxrefs - Database cross references, optional (list of strings) + - features - Any (sub)features, optional (list of SeqFeature objects) + - annotations - Dictionary of annotations for the whole sequence + - letter_annotations - Dictionary of per-letter-annotations, values + should be strings, list or tuples of the same length as the full + sequence. + + You will typically use Bio.SeqIO to read in sequences from files as + SeqRecord objects. However, you may want to create your own SeqRecord + objects directly. + + Note that while an id is optional, we strongly recommend you supply a + unique id string for each record. This is especially important + if you wish to write your sequences to a file. + + You can create a 'blank' SeqRecord object, and then populate the + attributes later. + """ + if seq is not None and not isinstance(seq, (Seq, MutableSeq)): + raise TypeError("seq argument should be a Seq or MutableSeq object") + if id is not None and not isinstance(id, str): + # Lots of existing code uses id=None... this may be a bad idea. + raise TypeError("id argument should be a string") + if not isinstance(name, str): + raise TypeError("name argument should be a string") + if not isinstance(description, str): + raise TypeError("description argument should be a string") + + self._seq = seq + self.id = id + self.name = name + self.description = description + + # database cross references (for the whole sequence) + if dbxrefs is None: + dbxrefs = [] + elif not isinstance(dbxrefs, list): + raise TypeError("dbxrefs argument should be a list (of strings)") + self.dbxrefs = dbxrefs + + # annotations about the whole sequence + if annotations is None: + annotations = {} + elif not isinstance(annotations, dict): + raise TypeError("annotations argument must be a dict or None") + self.annotations = annotations + + self._per_letter_annotations = None + if letter_annotations is not None: + # This will be handled via the property set function, which will + # turn this into a _RestrictedDict and thus ensure all the values + # in the dict are the right length + self.letter_annotations = letter_annotations + + # annotations about parts of the sequence + if features is None: + features = [] + elif not isinstance(features, list): + raise TypeError( + "features argument should be a list (of SeqFeature objects)" + ) + self.features = features + + @property + def letter_annotations(self) -> dict[str, Sequence[Any]]: + """Dictionary of per-letter-annotation for the sequence. + + For example, this can hold quality scores used in FASTQ or QUAL files. + Consider this example using Bio.SeqIO to read in an example Solexa + variant FASTQ file as a SeqRecord: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") + >>> print("%s %s" % (record.id, record.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(list(record.letter_annotations)) + ['solexa_quality'] + >>> print(record.letter_annotations["solexa_quality"]) + [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] + + The letter_annotations get sliced automatically if you slice the + parent SeqRecord, for example taking the last ten bases: + + >>> sub_record = record[-10:] + >>> print("%s %s" % (sub_record.id, sub_record.seq)) + slxa_0001_1_0001_01 ACGTNNNNNN + >>> print(sub_record.letter_annotations["solexa_quality"]) + [4, 3, 2, 1, 0, -1, -2, -3, -4, -5] + + Any python sequence (i.e. list, tuple or string) can be recorded in + the SeqRecord's letter_annotations dictionary as long as the length + matches that of the SeqRecord's sequence. e.g. + + >>> len(sub_record.letter_annotations) + 1 + >>> sub_record.letter_annotations["dummy"] = "abcdefghij" + >>> len(sub_record.letter_annotations) + 2 + + You can delete entries from the letter_annotations dictionary as usual: + + >>> del sub_record.letter_annotations["solexa_quality"] + >>> sub_record.letter_annotations + {'dummy': 'abcdefghij'} + + You can completely clear the dictionary easily as follows: + + >>> sub_record.letter_annotations = {} + >>> sub_record.letter_annotations + {} + + Note that if replacing the record's sequence with a sequence of a + different length you must first clear the letter_annotations dict. + """ + if self._per_letter_annotations is None: + length = 0 if self.seq is None else len(self.seq) + self._per_letter_annotations = _RestrictedDict(length=length) + return self._per_letter_annotations + + # TODO - Just make this a read only property? + @letter_annotations.setter + def letter_annotations(self, value: dict[str, Sequence[Any]]) -> None: + if not isinstance(value, dict): + raise TypeError( + "The per-letter-annotations should be a (restricted) dictionary." + ) + # Turn this into a restricted-dictionary (and check the entries) + length = 0 if self.seq is None else len(self.seq) + if any(len(val) != length for val in value.values()): + raise ValueError( + f"The per-letter-annotations have the same length as the sequence, but found: \n {','.join([f'{key}={val}' for key, val in value.items() if len(val) != length])}" + ) + if self._per_letter_annotations is None: + self._per_letter_annotations = _RestrictedDict(length=length) + else: + self._per_letter_annotations.clear() + dict.update(self._per_letter_annotations, value) # type: ignore + + @property + def seq(self) -> Union["Seq", "MutableSeq"] | None: + """The sequence itself, as a Seq or MutableSeq object.""" + return self._seq + + @seq.setter + def seq(self, value: Union["Seq", "MutableSeq"]) -> None: + # Adding this here for users who are not type-checking their code. + if value is not None and not isinstance(value, (Seq, MutableSeq)): + raise TypeError("seq must be a Seq or MutableSeq object") + # TODO - Add a deprecation warning that the seq should be write only? + if self._per_letter_annotations: + if len(self) != len(value): + # TODO - Make this a warning? Silently empty the dictionary? + raise ValueError("You must empty the letter annotations first!") + else: + # Leave the existing per letter annotations unchanged: + self._seq = value + else: + self._seq = value + # Reset the (empty) letter annotations dict with new length: + length = 0 if self.seq is None else len(self.seq) + self._per_letter_annotations = _RestrictedDict(length=length) + + @classmethod + def _from_validated( + cls, + seq: Seq | MutableSeq | None, + id: str | None = "", + name: str = "", + description: str = "", + dbxrefs: list[str] | None = None, + features: list["SeqFeature"] | None = None, + annotations: dict[str, str | int] | None = None, + letter_annotations: dict[str, Sequence] | None = None, + ) -> "SeqRecord": + """Faster constructor for post-validated data like copies or validated parsed data""" + + if cls is not SeqRecord: + # If we subclassed, we'll default to that class's initializer just to be careful + return cls( + seq, + id, + name, + description, + dbxrefs, + features, + annotations, + letter_annotations, + ) + + inst = cls.__new__(cls) + + inst._seq = seq + inst.id = id + inst.name = name + inst.description = description + if dbxrefs is None: + dbxrefs = [] + inst.dbxrefs = dbxrefs + if features is None: + features = [] + inst.features = features + if annotations is None: + annotations = {} + inst.annotations = annotations + + inst._per_letter_annotations = None + if letter_annotations is not None: + length = 0 if seq is None else len(seq) + inst._per_letter_annotations = _RestrictedDict(length=length) + dict.update(inst._per_letter_annotations, letter_annotations) # type: ignore + return inst + + @overload + def __getitem__(self, index: int) -> str: ... + + @overload + def __getitem__(self, index: slice) -> "SeqRecord": ... + + def __getitem__(self, index): + """Return a sub-sequence or an individual letter. + + Slicing, e.g. my_record[5:10], returns a new SeqRecord for + that sub-sequence with some annotation preserved as follows: + + * The name, id and description are kept as-is. + * Any per-letter-annotations are sliced to match the requested + sub-sequence. + * Unless a stride is used, all those features which fall fully + within the subsequence are included (with their locations + adjusted accordingly). If you want to preserve any truncated + features (e.g. GenBank/EMBL source features), you must + explicitly add them to the new SeqRecord yourself. + * With the exception of any molecule type, the annotations + dictionary and the dbxrefs list are not used for the new + SeqRecord, as in general they may not apply to the + subsequence. If you want to preserve them, you must explicitly + copy them to the new SeqRecord yourself. + + Using an integer index, e.g. my_record[5] is shorthand for + extracting that letter from the sequence, my_record.seq[5]. + + For example, consider this short protein and its secondary + structure as encoded by the PDB (e.g. H for alpha helices), + plus a simple feature for its histidine self phosphorylation + site: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.SeqFeature import SeqFeature, SimpleLocation + >>> rec = SeqRecord(Seq("MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLAT" + ... "EMMSEQDGYLAESINKDIEECNAIIEQFIDYLR"), + ... id="1JOY", name="EnvZ", + ... description="Homodimeric domain of EnvZ from E. coli") + >>> rec.letter_annotations["secondary_structure"] = " S SSSSSSHHHHHTTTHHHHHHHHHHHHHHHHHHHHHHTHHHHHHHHHHHHHHHHHHHHHTT " + >>> rec.features.append(SeqFeature(SimpleLocation(20, 21), + ... type = "Site")) + + Now let's have a quick look at the full record, + + >>> print(rec) + ID: 1JOY + Name: EnvZ + Description: Homodimeric domain of EnvZ from E. coli + Number of features: 1 + Per letter annotation for: secondary_structure + Seq('MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLATEMMSEQDGYLAESINKDIEE...YLR') + >>> rec.letter_annotations["secondary_structure"] + ' S SSSSSSHHHHHTTTHHHHHHHHHHHHHHHHHHHHHHTHHHHHHHHHHHHHHHHHHHHHTT ' + >>> print(rec.features[0].location) + [20:21] + + Now let's take a sub sequence, here chosen as the first (fractured) + alpha helix which includes the histidine phosphorylation site: + + >>> sub = rec[11:41] + >>> print(sub) + ID: 1JOY + Name: EnvZ + Description: Homodimeric domain of EnvZ from E. coli + Number of features: 1 + Per letter annotation for: secondary_structure + Seq('RTLLMAGVSHDLRTPLTRIRLATEMMSEQD') + >>> sub.letter_annotations["secondary_structure"] + 'HHHHHTTTHHHHHHHHHHHHHHHHHHHHHH' + >>> print(sub.features[0].location) + [9:10] + + You can also of course omit the start or end values, for + example to get the first ten letters only: + + >>> print(rec[:10]) + ID: 1JOY + Name: EnvZ + Description: Homodimeric domain of EnvZ from E. coli + Number of features: 0 + Per letter annotation for: secondary_structure + Seq('MAAGVKQLAD') + + Or for the last ten letters: + + >>> print(rec[-10:]) + ID: 1JOY + Name: EnvZ + Description: Homodimeric domain of EnvZ from E. coli + Number of features: 0 + Per letter annotation for: secondary_structure + Seq('IIEQFIDYLR') + + If you omit both, then you get a copy of the original record (although + lacking the annotations and dbxrefs): + + >>> print(rec[:]) + ID: 1JOY + Name: EnvZ + Description: Homodimeric domain of EnvZ from E. coli + Number of features: 1 + Per letter annotation for: secondary_structure + Seq('MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLATEMMSEQDGYLAESINKDIEE...YLR') + + Finally, indexing with a simple integer is shorthand for pulling out + that letter from the sequence directly: + + >>> rec[5] + 'K' + >>> rec.seq[5] + 'K' + """ + if isinstance(index, numbers.Integral): + # NOTE - The sequence level annotation like the id, name, etc + # do not really apply to a single character. However, should + # we try and expose any per-letter-annotation here? If so how? + if self.seq is None: + raise ValueError( + "Seq in SeqRecord is None, it doesn't support indexing" + ) + return self.seq[index] + elif isinstance(index, slice): + if self.seq is None: + raise ValueError("Seq in SeqRecord is None, we cannot slice it") + parent_length = len(self) + try: + from BioSQL.BioSeq import DBSeqRecord + + biosql_available = True + except ImportError: + biosql_available = False + + if biosql_available and isinstance(self, DBSeqRecord): + answer = SeqRecord._from_validated( + self.seq[index], + id=self.id, + name=self.name, + description=self.description, + ) + else: + answer = self._from_validated( + self.seq[index], + id=self.id, + name=self.name, + description=self.description, + ) + # TODO - The description may no longer apply. + # It would be safer to change it to something + # generic like "edited" or the default value. + + # Don't copy the annotation dict and dbxefs list, + # they may not apply to a subsequence. + # answer.annotations = dict(self.annotations.items()) + # answer.dbxrefs = self.dbxrefs[:] + # TODO - Review this in light of adding SeqRecord objects? + + if "molecule_type" in self.annotations: + # This will still apply, and we need it for GenBank/EMBL etc output + answer.annotations["molecule_type"] = self.annotations["molecule_type"] + + # TODO - Cope with strides by generating ambiguous locations? + start, stop, step = index.indices(parent_length) + if step == 1: + # Select relevant features, add them with shifted locations + # assert str(self.seq)[index] == str(self.seq)[start:stop] + for f in self.features: + if f.location.ref or f.location.ref_db: + # TODO - Implement this (with lots of tests)? + import warnings + + warnings.warn( + "When slicing SeqRecord objects, any " + "SeqFeature referencing other sequences (e.g. " + "from segmented GenBank records) are ignored." + ) + continue + try: + if start <= f.location.start and f.location.end <= stop: + answer.features.append(f._shift(-start)) + except TypeError: + # Will fail on UnknownPosition + pass + + # Slice all the values to match the sliced sequence + # (this should also work with strides, even negative strides): + for key, value in self.letter_annotations.items(): + answer.letter_annotations[key] = value[index] + + return answer + raise ValueError("Invalid index") + + def __iter__(self) -> Iterator[str]: + """Iterate over the letters in the sequence. + + For example, using Bio.SeqIO to read in a protein FASTA file: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Fasta/loveliesbleeding.pro", "fasta") + >>> for amino in record: + ... print(amino) + ... if amino == "L": break + X + A + G + L + >>> print(record.seq[3]) + L + + This is just a shortcut for iterating over the sequence directly: + + >>> for amino in record.seq: + ... print(amino) + ... if amino == "L": break + X + A + G + L + >>> print(record.seq[3]) + L + + Note that this does not facilitate iteration together with any + per-letter-annotation. However, you can achieve that using the + python zip function on the record (or its sequence) and the relevant + per-letter-annotation: + + >>> from Bio import SeqIO + >>> rec = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") + >>> print("%s %s" % (rec.id, rec.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(list(rec.letter_annotations)) + ['solexa_quality'] + >>> for nuc, qual in zip(rec, rec.letter_annotations["solexa_quality"]): + ... if qual > 35: + ... print("%s %i" % (nuc, qual)) + A 40 + C 39 + G 38 + T 37 + A 36 + + You may agree that using zip(rec.seq, ...) is more explicit than using + zip(rec, ...) as shown above. + """ + if self._seq is None: + raise ValueError("Seq in SeqRecord is None, can't iterate over it") + return iter(self._seq) + + def __contains__(self, char: str) -> bool: + """Implement the 'in' keyword, searches the sequence. + + e.g. + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Fasta/sweetpea.nu", "fasta") + >>> "GAATTC" in record + False + >>> "AAA" in record + True + + This essentially acts as a proxy for using "in" on the sequence: + + >>> "GAATTC" in record.seq + False + >>> "AAA" in record.seq + True + + Note that you can also use Seq objects as the query, + + >>> from Bio.Seq import Seq + >>> Seq("AAA") in record + True + + See also the Seq object's __contains__ method. + """ + if self._seq is None: + raise ValueError("Seq in SeqRecord is None, can't convert to bytes") + return char in self._seq + + def __bytes__(self) -> bytes: + if self._seq is None: + raise ValueError("Seq in SeqRecord is None, can't convert to bytes") + return bytes(self._seq) + + def __str__(self) -> str: + """Return a human readable summary of the record and its annotation (string). + + The python built in function str works by calling the object's __str__ + method. e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"), + ... id="YP_025292.1", name="HokC", + ... description="toxic membrane protein, small") + >>> print(str(record)) + ID: YP_025292.1 + Name: HokC + Description: toxic membrane protein, small + Number of features: 0 + Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF') + + In this example you don't actually need to call str explicitly, as the + print command does this automatically: + + >>> print(record) + ID: YP_025292.1 + Name: HokC + Description: toxic membrane protein, small + Number of features: 0 + Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF') + + Note that long sequences are shown truncated. + """ + lines: list[str] = [] + if self.id: + lines.append(f"ID: {self.id}") + if self.name: + lines.append(f"Name: {self.name}") + if self.description: + lines.append(f"Description: {self.description}") + if self.dbxrefs: + lines.append("Database cross-references: " + ", ".join(self.dbxrefs)) + lines.append(f"Number of features: {len(self.features)}") + for a in self.annotations: + lines.append(f"/{a}={self.annotations[a]!s}") + if self.letter_annotations: + lines.append( + "Per letter annotation for: " + ", ".join(self.letter_annotations) + ) + if self.seq is not None: + try: + bytes(self.seq) + except UndefinedSequenceError: + lines.append(f"Undefined sequence of length {len(self.seq)}") + else: + # Don't want to include the entire sequence + seq = repr(self.seq) + lines.append(seq) + else: + lines.append("Missing Sequence (None)") + + return "\n".join(lines) + + def __repr__(self) -> str: + """Return a concise summary of the record for debugging (string). + + The python built in function repr works by calling the object's __repr__ + method. e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> rec = SeqRecord(Seq("MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKAT" + ... "GEMKEQTEWHRVVLFGKLAEVASEYLRKGSQVYIEGQLRTRKWTDQ" + ... "SGQDRYTTEVVVNVGGTMQMLGGRQGGGAPAGGNIGGGQPQGGWGQ" + ... "PQQPQGGNQFSGGAQSRPQQSAPAAPSNEPPMDFDDDIPF"), + ... id="NP_418483.1", name="b4059", + ... description="ssDNA-binding protein", + ... dbxrefs=["ASAP:13298", "GI:16131885", "GeneID:948570"]) + >>> print(repr(rec)) + SeqRecord(seq=Seq('MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKATGEMKEQTE...IPF'), id='NP_418483.1', name='b4059', description='ssDNA-binding protein', dbxrefs=['ASAP:13298', 'GI:16131885', 'GeneID:948570']) + + At the python prompt you can also use this shorthand: + + >>> rec + SeqRecord(seq=Seq('MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKATGEMKEQTE...IPF'), id='NP_418483.1', name='b4059', description='ssDNA-binding protein', dbxrefs=['ASAP:13298', 'GI:16131885', 'GeneID:948570']) + + Note that long sequences are shown truncated. Also note that any + annotations, letter_annotations and features are not shown (as they + would lead to a very long string). + """ + return ( + f"{self.__class__.__name__}(seq={self.seq!r}, id={self.id!r}," + f" name={self.name!r}, description={self.description!r}," + f" dbxrefs={self.dbxrefs!r})" + ) + + def format(self, format: str) -> str: + r"""Return the record as a string in the specified file format. + + The format should be a lower case string supported as an output + format by Bio.SeqIO, which is used to turn the SeqRecord into a + string. e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"), + ... id="YP_025292.1", name="HokC", + ... description="toxic membrane protein") + >>> record.format("fasta") + '>YP_025292.1 toxic membrane protein\nMKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF\n' + >>> print(record.format("fasta")) + >YP_025292.1 toxic membrane protein + MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF + + + The Python print function automatically appends a new line, meaning + in this example a blank line is shown. If you look at the string + representation you can see there is a trailing new line (shown as + slash n) which is important when writing to a file or if + concatenating multiple sequence strings together. + + Note that this method will NOT work on every possible file format + supported by Bio.SeqIO (e.g. some are for multiple sequences only, + and binary formats are not supported). + """ + # See also the __format__ method + return self.__format__(format) + + def __format__(self, format_spec: str) -> str: + r"""Return the record as a string in the specified file format. + + This method supports the Python format() function and f-strings. + The format_spec should be a lower case string supported by + Bio.SeqIO as a text output file format. Requesting a binary file + format raises a ValueError. e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"), + ... id="YP_025292.1", name="HokC", + ... description="toxic membrane protein") + ... + >>> format(record, "fasta") + '>YP_025292.1 toxic membrane protein\nMKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF\n' + >>> print(f"Here is {record.id} in FASTA format:\n{record:fasta}") + Here is YP_025292.1 in FASTA format: + >YP_025292.1 toxic membrane protein + MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF + + + See also the SeqRecord's format() method. + """ + if not format_spec: + # Follow python convention and default to using __str__ + return str(self) + from Bio import SeqIO + + cls = SeqIO._FormatToWriter[format_spec] + try: + return cls.to_string(self) # type: ignore + except StreamModeError: + raise ValueError( + "Binary format %s cannot be used with SeqRecord format method" + % format_spec + ) from None + + def __len__(self) -> int: + """Return the length of the sequence. + + For example, using Bio.SeqIO to read in a FASTA nucleotide file: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Fasta/sweetpea.nu", "fasta") + >>> len(record) + 309 + >>> len(record.seq) + 309 + """ + return len(self._seq) if self._seq is not None else 0 + + def __lt__(self, other: Any) -> NoReturn: + """Define the less-than operand (not implemented).""" + raise NotImplementedError(_NO_SEQRECORD_COMPARISON) + + def __le__(self, other: Any) -> NoReturn: + """Define the less-than-or-equal-to operand (not implemented).""" + raise NotImplementedError(_NO_SEQRECORD_COMPARISON) + + def __eq__(self, other: object) -> NoReturn: + """Define the equal-to operand (not implemented).""" + raise NotImplementedError(_NO_SEQRECORD_COMPARISON) + + def __ne__(self, other: object) -> NoReturn: + """Define the not-equal-to operand (not implemented).""" + raise NotImplementedError(_NO_SEQRECORD_COMPARISON) + + def __gt__(self, other: Any) -> NoReturn: + """Define the greater-than operand (not implemented).""" + raise NotImplementedError(_NO_SEQRECORD_COMPARISON) + + def __ge__(self, other: Any) -> NoReturn: + """Define the greater-than-or-equal-to operand (not implemented).""" + raise NotImplementedError(_NO_SEQRECORD_COMPARISON) + + def __bool__(self) -> bool: + """Boolean value of an instance of this class (True). + + This behaviour is for backwards compatibility, since until the + __len__ method was added, a SeqRecord always evaluated as True. + + Note that in comparison, a Seq object will evaluate to False if it + has a zero length sequence. + + WARNING: The SeqRecord may in future evaluate to False when its + sequence is of zero length (in order to better match the Seq + object behaviour)! + """ + return True + + def __add__( + self, other: Union["SeqRecord", "Seq", "MutableSeq", str] + ) -> "SeqRecord": + """Add another sequence or string to this sequence. + + The other sequence can be a SeqRecord object, a Seq object (or + similar, e.g. a MutableSeq) or a plain Python string. If you add + a plain string or a Seq (like) object, the new SeqRecord will simply + have this appended to the existing data. However, any per letter + annotation will be lost: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") + >>> print("%s %s" % (record.id, record.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(list(record.letter_annotations)) + ['solexa_quality'] + + >>> new = record + "ACT" + >>> print("%s %s" % (new.id, new.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNNACT + >>> print(list(new.letter_annotations)) + [] + + The new record will attempt to combine the annotation, but for any + ambiguities (e.g. different names) it defaults to omitting that + annotation. + + >>> from Bio import SeqIO + >>> with open("GenBank/pBAD30.gb") as handle: + ... plasmid = SeqIO.read(handle, "gb") + >>> print("%s %i" % (plasmid.id, len(plasmid))) + pBAD30 4923 + + Now let's cut the plasmid into two pieces, and join them back up the + other way round (i.e. shift the starting point on this plasmid, have + a look at the annotated features in the original file to see why this + particular split point might make sense): + + >>> left = plasmid[:3765] + >>> right = plasmid[3765:] + >>> new = right + left + >>> print("%s %i" % (new.id, len(new))) + pBAD30 4923 + >>> str(new.seq) == str(right.seq + left.seq) + True + >>> len(new.features) == len(left.features) + len(right.features) + True + + When we add the left and right SeqRecord objects, their annotation + is all consistent, so it is all conserved in the new SeqRecord: + + >>> new.id == left.id == right.id == plasmid.id + True + >>> new.name == left.name == right.name == plasmid.name + True + >>> new.description == plasmid.description + True + >>> new.annotations == left.annotations == right.annotations + True + >>> new.letter_annotations == plasmid.letter_annotations + True + >>> new.dbxrefs == left.dbxrefs == right.dbxrefs + True + + However, we should point out that when we sliced the SeqRecord, + any annotations dictionary or dbxrefs list entries were lost. + You can explicitly copy them like this: + + >>> new.annotations = plasmid.annotations.copy() + >>> new.dbxrefs = plasmid.dbxrefs[:] + """ + + if self._seq is None: + raise ValueError("Left operand seq=None, can't add") + + if not isinstance(other, SeqRecord): + # Assume it is a string or a Seq. + # Note can't transfer any per-letter-annotations + return type(self)( + self._seq + other, + id=self.id, + name=self.name, + description=self.description, + features=self.features[:], + annotations=self.annotations.copy(), + dbxrefs=self.dbxrefs[:], + ) + + if other._seq is None: + raise ValueError("Right SeqRecord has seq=None, can't add") + + # Adding two SeqRecord objects... must merge annotation + answer = self._from_validated( + self._seq + other._seq, features=self.features[:], dbxrefs=self.dbxrefs[:] + ) + # Will take all the features and all the db cross refs, + length = len(self) + for f in other.features: + answer.features.append(f._shift(length)) + del length + for ref in other.dbxrefs: + if ref not in answer.dbxrefs: + answer.dbxrefs.append(ref) + + # Take common id/name/description/annotation + if self.id == other.id: + answer.id = self.id + if self.name == other.name: + answer.name = self.name + if self.description == other.description: + answer.description = self.description + for k, v in self.annotations.items(): + if k in other.annotations and other.annotations[k] == v: + answer.annotations[k] = v + # Can append matching per-letter-annotation + try: + # To make this type safe, we would need to make sure the types are compatible, eg: no adding tuples and str + for k, v in self.letter_annotations.items(): # type: ignore + if k in other.letter_annotations: + # avoid length checks, but otherwise equivalent to answer.letter_annotations[k] = v + other.letter_annotations[k] + dict.__setitem__( + answer.letter_annotations, + k, + v + other.letter_annotations[k], # type: ignore + ) + except TypeError: + print("Failed while try to concatenate letter annotations") + raise + + return answer + + def __radd__(self, other: Union["Seq", "MutableSeq", str]) -> "SeqRecord": + """Add another sequence or string to this sequence (from the left). + + This method handles adding a Seq object (or similar, e.g. MutableSeq) + or a plain Python string (on the left) to a SeqRecord (on the right). + See the __add__ method for more details, but for example: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") + >>> print("%s %s" % (record.id, record.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(list(record.letter_annotations)) + ['solexa_quality'] + + >>> new = "ACT" + record + >>> print("%s %s" % (new.id, new.seq)) + slxa_0001_1_0001_01 ACTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(list(new.letter_annotations)) + [] + """ + if isinstance(other, SeqRecord): + raise RuntimeError( + "This should have happened via the __add__ of " + "the other SeqRecord being added!" + ) + if self.seq is None: + raise TypeError("Can't add (right hand side) SeqRecord with seq = None") + # Assume it is a string or a Seq. + # Note can't transfer any per-letter-annotations + offset = len(other) + return type(self)( + cast(Seq | MutableSeq, other + self.seq), + id=self.id, + name=self.name, + description=self.description, + features=[f._shift(offset) for f in self.features], + annotations=self.annotations.copy(), + dbxrefs=self.dbxrefs[:], + ) + + def count(self, sub, start=None, end=None): + """Return the number of non-overlapping occurrences of sub in seq[start:end]. + + Optional arguments start and end are interpreted as in slice notation. + This method behaves as the count method of Python strings. + """ + if self._seq is None: + raise ValueError( + "seq is SeqRecord is None, assign it a sequence before applying count" + ) + return self.seq.count(sub, start, end) + + def upper(self) -> "SeqRecord": + """Return a copy of the record with an upper case sequence. + + All the annotation is preserved unchanged. e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> record = SeqRecord(Seq("acgtACGT"), id="Test", + ... description = "Made up for this example") + >>> record.letter_annotations["phred_quality"] = [1, 2, 3, 4, 5, 6, 7, 8] + >>> print(record.upper().format("fastq")) + @Test Made up for this example + ACGTACGT + + + "#$%&'() + + + Naturally, there is a matching lower method: + + >>> print(record.lower().format("fastq")) + @Test Made up for this example + acgtacgt + + + "#$%&'() + + """ + if self.seq is None: + raise ValueError( + "seq is SeqRecord is None, assign it a sequence before applying upper" + ) + return self._from_validated( + self.seq.upper(), + id=self.id, + name=self.name, + description=self.description, + dbxrefs=self.dbxrefs[:], + features=self.features[:], + annotations=self.annotations.copy(), + letter_annotations=( + None + if self._per_letter_annotations is None + else self.letter_annotations.copy() + ), + ) + + def lower(self) -> "SeqRecord": + """Return a copy of the record with a lower case sequence. + + All the annotation is preserved unchanged. e.g. + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Fasta/aster.pro", "fasta") + >>> print(record.format("fasta")) + >gi|3298468|dbj|BAA31520.1| SAMIPF + GGHVNPAVTFGAFVGGNITLLRGIVYIIAQLLGSTVACLLLKFVTNDMAVGVFSLSAGVG + VTNALVFEIVMTFGLVYTVYATAIDPKKGSLGTIAPIAIGFIVGANI + + >>> print(record.lower().format("fasta")) + >gi|3298468|dbj|BAA31520.1| SAMIPF + gghvnpavtfgafvggnitllrgivyiiaqllgstvaclllkfvtndmavgvfslsagvg + vtnalvfeivmtfglvytvyataidpkkgslgtiapiaigfivgani + + + To take a more annotation rich example, + + >>> from Bio import SeqIO + >>> old = SeqIO.read("EMBL/TRBG361.embl", "embl") + >>> len(old.features) + 3 + >>> new = old.lower() + >>> len(old.features) == len(new.features) + True + >>> old.annotations["organism"] == new.annotations["organism"] + True + >>> old.dbxrefs == new.dbxrefs + True + """ + if self.seq is None: + raise ValueError( + "seq is SeqRecord is None, assign it a sequence before applying lower" + ) + return self._from_validated( + self.seq.lower(), + id=self.id, + name=self.name, + description=self.description, + dbxrefs=self.dbxrefs[:], + features=self.features[:], + annotations=self.annotations.copy(), + letter_annotations=( + None + if self._per_letter_annotations is None + else self.letter_annotations.copy() + ), + ) + + def isupper(self): + """Return True if all ASCII characters in the record's sequence are uppercase. + + If there are no cased characters, the method returns False. + """ + return self.seq.isupper() + + def islower(self): + """Return True if all ASCII characters in the record's sequence are lowercase. + + If there are no cased characters, the method returns False. + """ + return self.seq.islower() + + def reverse_complement( + self, + id: bool = False, + name: bool = False, + description: bool = False, + features: bool = True, + annotations: bool = False, + letter_annotations: bool = True, + dbxrefs: bool = False, + ) -> "SeqRecord": + """Return new SeqRecord with reverse complement sequence. + + By default the new record does NOT preserve the sequence identifier, + name, description, general annotation or database cross-references - + these are unlikely to apply to the reversed sequence. + + You can specify the returned record's id, name and description as + strings, or True to keep that of the parent, or False for a default. + + You can specify the returned record's features with a list of + SeqFeature objects, or True to keep that of the parent, or False to + omit them. The default is to keep the original features (with the + strand and locations adjusted). + + You can also specify both the returned record's annotations and + letter_annotations as dictionaries, True to keep that of the parent, + or False to omit them. The default is to keep the original + annotations (with the letter annotations reversed). + + To show what happens to the pre-letter annotations, consider an + example Solexa variant FASTQ file with a single entry, which we'll + read in as a SeqRecord: + + >>> from Bio import SeqIO + >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") + >>> print("%s %s" % (record.id, record.seq)) + slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + >>> print(list(record.letter_annotations)) + ['solexa_quality'] + >>> print(record.letter_annotations["solexa_quality"]) + [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] + + Now take the reverse complement, here we explicitly give a new + identifier (the old identifier with a suffix): + + >>> rc_record = record.reverse_complement(id=record.id + "_rc") + >>> print("%s %s" % (rc_record.id, rc_record.seq)) + slxa_0001_1_0001_01_rc NNNNNNACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT + + Notice that the per-letter-annotations have also been reversed, + although this may not be appropriate for all cases. + + >>> print(rc_record.letter_annotations["solexa_quality"]) + [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] + + Now for the features, we need a different example. Parsing a GenBank + file is probably the easiest way to get an nice example with features + in it... + + >>> from Bio import SeqIO + >>> with open("GenBank/pBAD30.gb") as handle: + ... plasmid = SeqIO.read(handle, "gb") + >>> print("%s %i" % (plasmid.id, len(plasmid))) + pBAD30 4923 + >>> plasmid.seq + Seq('GCTAGCGGAGTGTATACTGGCTTACTATGTTGGCACTGATGAGGGTGTCAGTGA...ATG') + >>> len(plasmid.features) + 13 + + Now, let's take the reverse complement of this whole plasmid: + + >>> rc_plasmid = plasmid.reverse_complement(id=plasmid.id+"_rc") + >>> print("%s %i" % (rc_plasmid.id, len(rc_plasmid))) + pBAD30_rc 4923 + >>> rc_plasmid.seq + Seq('CATGGGCAAATATTATACGCAAGGCGACAAGGTGCTGATGCCGCTGGCGATTCA...AGC') + >>> len(rc_plasmid.features) + 13 + + Let's compare the first CDS feature - it has gone from being the + second feature (index 1) to the second last feature (index -2), its + strand has changed, and the location switched round. + + >>> print(plasmid.features[1]) + type: CDS + location: [1081:1960](-) + qualifiers: + Key: label, Value: ['araC'] + Key: note, Value: ['araC regulator of the arabinose BAD promoter'] + Key: vntifkey, Value: ['4'] + + >>> print(rc_plasmid.features[-2]) + type: CDS + location: [2963:3842](+) + qualifiers: + Key: label, Value: ['araC'] + Key: note, Value: ['araC regulator of the arabinose BAD promoter'] + Key: vntifkey, Value: ['4'] + + + You can check this new location, based on the length of the plasmid: + + >>> len(plasmid) - 1081 + 3842 + >>> len(plasmid) - 1960 + 2963 + + Note that if the SeqFeature annotation includes any strand specific + information (e.g. base changes for a SNP), this information is not + amended, and would need correction after the reverse complement. + + Note trying to reverse complement a protein SeqRecord raises an + exception: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> protein_rec = SeqRecord(Seq("MAIVMGR"), id="Test", + ... annotations={"molecule_type": "protein"}) + >>> protein_rec.reverse_complement() + Traceback (most recent call last): + ... + ValueError: Proteins do not have complements! + + If you have RNA without any U bases, it must be annotated as RNA + otherwise it will be treated as DNA by default with A mapped to T: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> rna1 = SeqRecord(Seq("ACG"), id="Test") + >>> rna2 = SeqRecord(Seq("ACG"), id="Test", annotations={"molecule_type": "RNA"}) + >>> print(rna1.reverse_complement(id="RC", description="unk").format("fasta")) + >RC unk + CGT + + >>> print(rna2.reverse_complement(id="RC", description="RNA").format("fasta")) + >RC RNA + CGU + + + Also note you can reverse complement a SeqRecord using a MutableSeq: + + >>> from Bio.Seq import MutableSeq + >>> from Bio.SeqRecord import SeqRecord + >>> rec = SeqRecord(MutableSeq("ACGT"), id="Test") + >>> rec.seq[0] = "T" + >>> print("%s %s" % (rec.id, rec.seq)) + Test TCGT + >>> rc = rec.reverse_complement(id=True) + >>> print("%s %s" % (rc.id, rc.seq)) + Test ACGA + """ + + if self.seq is None: + raise ValueError( + "Seq in SeqRecord is None, so can't construct the reverse_complement. Please assign it a sequence first" + ) + + if "protein" in cast(str, self.annotations.get("molecule_type", "")): + raise ValueError("Proteins do not have complements!") + if "RNA" in cast(str, self.annotations.get("molecule_type", "")): + seq = self.seq.reverse_complement_rna() + else: + # Default to DNA + seq = self.seq.reverse_complement() + if isinstance(self.seq, MutableSeq): + seq = Seq(seq) + answer = self._from_validated(seq) + if isinstance(id, str): + answer.id = id + elif id: + answer.id = self.id + if isinstance(name, str): + answer.name = name + elif name: + answer.name = self.name + if isinstance(description, str): + answer.description = description + elif description: + answer.description = self.description + if isinstance(dbxrefs, list): + answer.dbxrefs = dbxrefs + elif dbxrefs: + # Copy the old dbxrefs + answer.dbxrefs = self.dbxrefs[:] + if isinstance(features, list): + answer.features = features + elif features: + # Copy the old features, adjusting location and string + length = len(answer) + answer.features = [f._flip(length) for f in self.features] + + # The old list should have been sorted by start location, + # reversing it will leave it sorted by what is now the end position, + # so we need to resort in case of overlapping features. + # NOTE - In the common case of gene before CDS (and similar) with + # the exact same locations, this will still maintain gene before CDS + + def key_fun(f): + """Sort on start position.""" + try: + return int(f.location.start) + except TypeError: # Expected for UnknownPosition + return None + + answer.features.sort(key=key_fun) + if isinstance(annotations, dict): + answer.annotations = annotations + elif annotations: + # Copy the old annotations, + answer.annotations = self.annotations.copy() + if self._per_letter_annotations is not None: + if isinstance(letter_annotations, dict): + answer.letter_annotations = letter_annotations + elif letter_annotations: + # Copy the old per letter annotations, reversing them + for key, value in self.letter_annotations.items(): + answer.letter_annotations[key] = value[::-1] + return answer + + def translate( + self, + # Seq translation arguments: + table: str = "Standard", + stop_symbol: str = "*", + to_stop: bool = False, + cds: bool = False, + gap: str | None = None, + # SeqRecord annotation arguments: + id: bool = False, + name: bool = False, + description: bool = False, + features: bool = False, + annotations: bool = False, + letter_annotations: bool = False, + dbxrefs: bool = False, + ) -> "SeqRecord": + """Return new SeqRecord with translated sequence. + + This calls the record's .seq.translate() method (which describes + the translation related arguments, like table for the genetic code), + + By default the new record does NOT preserve the sequence identifier, + name, description, general annotation or database cross-references - + these are unlikely to apply to the translated sequence. + + You can specify the returned record's id, name and description as + strings, or True to keep that of the parent, or False for a default. + + You can specify the returned record's features with a list of + SeqFeature objects, or False (default) to omit them. + + You can also specify both the returned record's annotations and + letter_annotations as dictionaries, True to keep that of the parent + (annotations only), or False (default) to omit them. + + e.g. Loading a FASTA gene and translating it, + + >>> from Bio import SeqIO + >>> gene_record = SeqIO.read("Fasta/sweetpea.nu", "fasta") + >>> print(gene_record.format("fasta")) + >gi|3176602|gb|U78617.1|LOU78617 Lathyrus odoratus phytochrome A (PHYA) gene, partial cds + CAGGCTGCGCGGTTTCTATTTATGAAGAACAAGGTCCGTATGATAGTTGATTGTCATGCA + AAACATGTGAAGGTTCTTCAAGACGAAAAACTCCCATTTGATTTGACTCTGTGCGGTTCG + ACCTTAAGAGCTCCACATAGTTGCCATTTGCAGTACATGGCTAACATGGATTCAATTGCT + TCATTGGTTATGGCAGTGGTCGTCAATGACAGCGATGAAGATGGAGATAGCCGTGACGCA + GTTCTACCACAAAAGAAAAAGAGACTTTGGGGTTTGGTAGTTTGTCATAACACTACTCCG + AGGTTTGTT + + + And now translating the record, specifying the new ID and description: + + >>> protein_record = gene_record.translate(table=11, + ... id="phya", + ... description="translation") + >>> print(protein_record.format("fasta")) + >phya translation + QAARFLFMKNKVRMIVDCHAKHVKVLQDEKLPFDLTLCGSTLRAPHSCHLQYMANMDSIA + SLVMAVVVNDSDEDGDSRDAVLPQKKKRLWGLVVCHNTTPRFV + + + """ + if "protein" == self.annotations.get("molecule_type", ""): + raise ValueError("Proteins cannot be translated!") + + if self.seq is None: + raise ValueError("Seq in SeqRecord is None, can't be translated") + + answer = SeqRecord( + self.seq.translate( + table=table, stop_symbol=stop_symbol, to_stop=to_stop, cds=cds, gap=gap + ) + ) + if isinstance(id, str): + answer.id = id + elif id: + answer.id = self.id + if isinstance(name, str): + answer.name = name + elif name: + answer.name = self.name + if isinstance(description, str): + answer.description = description + elif description: + answer.description = self.description + if isinstance(dbxrefs, list): + answer.dbxrefs = dbxrefs + elif dbxrefs: + # Copy the old dbxrefs + answer.dbxrefs = self.dbxrefs[:] + if isinstance(features, list): + answer.features = features + elif features: + # Does not make sense to copy old features as locations wrong + raise TypeError(f"Unexpected features argument {features!r}") + if isinstance(annotations, dict): + answer.annotations = annotations + elif annotations: + # Copy the old annotations + answer.annotations = self.annotations.copy() + # Set/update to protein: + answer.annotations["molecule_type"] = "protein" + if self._per_letter_annotations is not None: + if isinstance(letter_annotations, dict): + answer.letter_annotations = letter_annotations + elif letter_annotations: + # Does not make sense to copy these as length now wrong + raise TypeError( + f"Unexpected letter_annotations argument {letter_annotations!r}" + ) + return answer + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._CheckSum.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._CheckSum.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._CheckSum.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._IsoelectricPoint.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._IsoelectricPoint.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._IsoelectricPoint.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._MeltingTemp.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._MeltingTemp.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._MeltingTemp.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._ProtParam.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._ProtParam.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._ProtParam.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._ProtParamData.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._ProtParamData.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._ProtParamData.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._lcc.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._lcc.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/._lcc.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/CheckSum.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/CheckSum.py new file mode 100644 index 0000000000000000000000000000000000000000..5a078f33f9fc3f91f8e19fffd3b02a55b2b151b9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/CheckSum.py @@ -0,0 +1,144 @@ +# Copyright 2002 by Yves Bastide and Brad Chapman. +# Copyright 2007 by Sebastian Bassi +# All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Functions to calculate assorted sequence checksums.""" + +# crc32, crc64, gcg, and seguid +# crc64 is adapted from BioPerl + +import binascii + + +def crc32(seq): + """Return the crc32 checksum for a sequence (string or Seq object). + + Note that the case is important: + + >>> crc32("ACGTACGTACGT") + 20049947 + >>> crc32("acgtACGTacgt") + 1688586483 + + """ + try: + # Assume it's a Seq object + s = bytes(seq) + except TypeError: + # Assume it's a string + s = seq.encode() + return binascii.crc32(s) + + +def _init_table_h(): + _table_h = [] + for i in range(256): + part_l = i + part_h = 0 + for j in range(8): + rflag = part_l & 1 + part_l >>= 1 + if part_h & 1: + part_l |= 1 << 31 + part_h >>= 1 + if rflag: + part_h ^= 0xD8000000 + _table_h.append(part_h) + return _table_h + + +# Initialisation +_table_h = _init_table_h() + + +def crc64(s): + """Return the crc64 checksum for a sequence (string or Seq object). + + Note that the case is important: + + >>> crc64("ACGTACGTACGT") + 'CRC-C4FBB762C4A87EBD' + >>> crc64("acgtACGTacgt") + 'CRC-DA4509DC64A87EBD' + + """ + crcl = 0 + crch = 0 + for c in s: + shr = (crch & 0xFF) << 24 + temp1h = crch >> 8 + temp1l = (crcl >> 8) | shr + idx = (crcl ^ ord(c)) & 0xFF + crch = temp1h ^ _table_h[idx] + crcl = temp1l + + return f"CRC-{crch:08X}{crcl:08X}" + + +def gcg(seq): + """Return the GCG checksum (int) for a sequence (string or Seq object). + + Given a nucleotide or amino-acid sequence (or any string), + returns the GCG checksum (int). Checksum used by GCG program. + seq type = str. + + Based on BioPerl GCG_checksum. Adapted by Sebastian Bassi + with the help of John Lenton, Pablo Ziliani, and Gabriel Genellina. + + All sequences are converted to uppercase. + + >>> gcg("ACGTACGTACGT") + 5688 + >>> gcg("acgtACGTacgt") + 5688 + + """ + index = checksum = 0 + for char in seq: + index += 1 + checksum += index * ord(char.upper()) + if index == 57: + index = 0 + return checksum % 10000 + + +def seguid(seq): + """Return the SEGUID (string) for a sequence (string or Seq object). + + Given a nucleotide or amino-acid sequence (or any string), + returns the SEGUID string (A SEquence Globally Unique IDentifier). + seq type = str. + + Note that the case is not important: + + >>> seguid("ACGTACGTACGT") + 'If6HIvcnRSQDVNiAoefAzySc6i4' + >>> seguid("acgtACGTacgt") + 'If6HIvcnRSQDVNiAoefAzySc6i4' + + For more information about SEGUID, see: + http://bioinformatics.anl.gov/seguid/ + https://doi.org/10.1002/pmic.200600032 + """ + import base64 + import hashlib + + m = hashlib.sha1() + try: + # Assume it's a Seq object + seq = bytes(seq) + except TypeError: + # Assume it's a string + seq = seq.encode() + m.update(seq.upper()) + tmp = base64.encodebytes(m.digest()) + return tmp.decode().replace("\n", "").rstrip("=") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/IsoelectricPoint.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/IsoelectricPoint.py new file mode 100644 index 0000000000000000000000000000000000000000..c98bc12bd5ebebd837f2734001522f282efad1ff --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/IsoelectricPoint.py @@ -0,0 +1,167 @@ +# Copyright 2003 Yair Benita. All rights reserved. +# Revisions copyright 2020 by Tianyi Shi. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Calculate isoelectric points of polypeptides using methods of Bjellqvist. + +pK values and the methods are taken from:: + + * Bjellqvist, B.,Hughes, G.J., Pasquali, Ch., Paquet, N., Ravier, F., + Sanchez, J.-Ch., Frutiger, S. & Hochstrasser, D.F. + The focusing positions of polypeptides in immobilized pH gradients can be + predicted from their amino acid sequences. Electrophoresis 1993, 14, + 1023-1031. + + * Bjellqvist, B., Basse, B., Olsen, E. and Celis, J.E. + Reference points for comparisons of two-dimensional maps of proteins from + different human cell types defined in a pH scale where isoelectric points + correlate with polypeptide compositions. Electrophoresis 1994, 15, 529-539. + +I designed the algorithm according to a note by David L. Tabb, available at: +http://fields.scripps.edu/DTASelect/20010710-pI-Algorithm.pdf +""" + +positive_pKs = {"Nterm": 7.5, "K": 10.0, "R": 12.0, "H": 5.98} +negative_pKs = {"Cterm": 3.55, "D": 4.05, "E": 4.45, "C": 9.0, "Y": 10.0} +pKcterminal = {"D": 4.55, "E": 4.75} +pKnterminal = { + "A": 7.59, + "M": 7.0, + "S": 6.93, + "P": 8.36, + "T": 6.82, + "V": 7.44, + "E": 7.7, +} +charged_aas = ("K", "R", "H", "D", "E", "C", "Y") + + +class IsoelectricPoint: + """A class for calculating the IEP or charge at given pH of a protein. + + Parameters + ---------- + :protein_sequence: A ``Bio.Seq`` or string object containing a protein + sequence. + :aa_content: A dictionary with amino acid letters as keys and its + occurrences as integers, e.g. ``{"A": 3, "C": 0, ...}``. + Default: ``None``. If ``None``, the dic will be calculated + from the given sequence. + + Methods + ------- + :charge_at_pH(pH): Calculates the charge of the protein for a given pH + :pi(): Calculates the isoelectric point + + + Examples + -------- + The methods of this class can either be accessed from the class itself + or from a ``ProtParam.ProteinAnalysis`` object (with partially different + names): + + >>> from Bio.SeqUtils.IsoelectricPoint import IsoelectricPoint as IP + >>> protein = IP("INGAR") + >>> print(f"IEP of peptide {protein.sequence} is {protein.pi():.2f}") + IEP of peptide INGAR is 9.75 + >>> print(f"Its charge at pH 7 is {protein.charge_at_pH(7.0):.2f}") + Its charge at pH 7 is 0.76 + + + >>> from Bio.SeqUtils.ProtParam import ProteinAnalysis as PA + >>> protein = PA("PETER") + >>> print(f"IEP of {protein.sequence}: {protein.isoelectric_point():.2f}") + IEP of PETER: 4.53 + >>> print(f"Charge at pH 4.53: {protein.charge_at_pH(4.53):.2f}") + Charge at pH 4.53: 0.00 + + """ + + def __init__(self, protein_sequence, aa_content=None): + """Initialize the class.""" + self.sequence = protein_sequence.upper() + if not aa_content: + from Bio.SeqUtils.ProtParam import ProteinAnalysis as _PA + + aa_content = _PA(self.sequence).count_amino_acids() + self.charged_aas_content = self._select_charged(aa_content) + + self.pos_pKs, self.neg_pKs = self._update_pKs_tables() + + # This function creates a dictionary with the contents of each charged aa, + # plus Cterm and Nterm. + def _select_charged(self, aa_content): + charged = {} + for aa in charged_aas: + charged[aa] = float(aa_content[aa]) + charged["Nterm"] = 1.0 + charged["Cterm"] = 1.0 + return charged + + def _update_pKs_tables(self): + """Update pKs tables with seq specific values for N- and C-termini.""" + pos_pKs = positive_pKs.copy() + neg_pKs = negative_pKs.copy() + nterm, cterm = self.sequence[0], self.sequence[-1] + if nterm in pKnterminal: + pos_pKs["Nterm"] = pKnterminal[nterm] + if cterm in pKcterminal: + neg_pKs["Cterm"] = pKcterminal[cterm] + return pos_pKs, neg_pKs + + def charge_at_pH(self, pH): + """Calculate the charge of a protein at given pH.""" + # derivation: + # Henderson Hasselbalch equation: pH = pKa + log([A-]/[HA]) + # Rearranging: [HA]/[A-] = 10 ** (pKa - pH) + # partial_charge = + # [A-]/[A]total = [A-]/([A-] + [HA]) = 1 / { ([A-] + [HA])/[A-] } = + # 1 / (1 + [HA]/[A-]) = 1 / (1 + 10 ** (pKa - pH)) for acidic residues; + # 1 / (1 + 10 ** (pH - pKa)) for basic residues + positive_charge = 0.0 + for aa, pK in self.pos_pKs.items(): + partial_charge = 1.0 / (10 ** (pH - pK) + 1.0) + positive_charge += self.charged_aas_content[aa] * partial_charge + + negative_charge = 0.0 + for aa, pK in self.neg_pKs.items(): + partial_charge = 1.0 / (10 ** (pK - pH) + 1.0) + negative_charge += self.charged_aas_content[aa] * partial_charge + + return positive_charge - negative_charge + + # This is the action function, it tries different pH until the charge of + # the protein is 0 (or close). + def pi(self, pH=7.775, min_=4.05, max_=12): + r"""Calculate and return the isoelectric point as float. + + This is a recursive function that uses bisection method. + Wiki on bisection: https://en.wikipedia.org/wiki/Bisection_method + + Arguments: + - pH: the pH at which the current charge of the protein is computed. + This pH lies at the centre of the interval (mean of `min_` and `max_`). + - min\_: the minimum of the interval. Initial value defaults to 4.05, + which is below the theoretical minimum, when the protein is composed + exclusively of aspartate. + - max\_: the maximum of the the interval. Initial value defaults to 12, + which is above the theoretical maximum, when the protein is composed + exclusively of arginine. + """ + charge = self.charge_at_pH(pH) + if max_ - min_ > 0.0001: + if charge > 0.0: + min_ = pH + else: + max_ = pH + next_pH = (min_ + max_) / 2 + return self.pi(next_pH, min_, max_) + return pH + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/MeltingTemp.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/MeltingTemp.py new file mode 100644 index 0000000000000000000000000000000000000000..cf27bd8113333380c4643cbd820aa005e5e45c19 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/MeltingTemp.py @@ -0,0 +1,1076 @@ +# Copyright 2004-2008 by Sebastian Bassi. +# Copyright 2013-2018 by Markus Piotrowski. +# All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Calculate the melting temperature of nucleotide sequences. + +This module contains three different methods to calculate the melting +temperature of oligonucleotides: + +1. Tm_Wallace: 'Rule of thumb' +2. Tm_GC: Empirical formulas based on GC content. Salt and mismatch corrections + can be included. +3. Tm_NN: Calculation based on nearest neighbor thermodynamics. Several tables + for DNA/DNA, DNA/RNA and RNA/RNA hybridizations are included. + Correction for mismatches, dangling ends, salt concentration and other + additives are available. + +General parameters for most Tm methods: + - seq -- A Biopython sequence object or a string. + - check -- Checks if the sequence is valid for the given method (default= + True). In general, whitespaces and non-base characters are removed and + characters are converted to uppercase. RNA will be backtranscribed. + - strict -- Do not allow base characters or neighbor duplex keys (e.g. + 'AT/NA') that could not or not unambiguously be evaluated for the respective + method (default=True). Note that W (= A or T) and S (= C or G) are not + ambiguous for Tm_Wallace and Tm_GC. If 'False', average values (if + applicable) will be used. + +This module is not able to detect self-complementary and it will not use +alignment tools to align an oligonucleotide sequence to its target sequence. +Thus it can not detect dangling-ends and mismatches by itself (don't even think +about bulbs and loops). These parameters have to be handed over to the +respective method. + +Other public methods of this module: + - make_table : To create a table with thermodynamic data. + - salt_correction: To adjust Tm to a given salt concentration by different + formulas. This method is called from Tm_GC and Tm_NN but may + also be accessed 'manually'. It returns a correction term, not + a corrected Tm! + - chem_correction: To adjust Tm regarding the chemical additives DMSO and + formaldehyde. The method returns a corrected Tm. Chemical + correction is not an integral part of the Tm methods and must + be called additionally. + +For example: + + >>> from Bio.SeqUtils import MeltingTemp as mt + >>> from Bio.Seq import Seq + >>> mystring = 'CGTTCCAAAGATGTGGGCATGAGCTTAC' + >>> myseq = Seq(mystring) + >>> print('%0.2f' % mt.Tm_Wallace(mystring)) + 84.00 + >>> print('%0.2f' % mt.Tm_Wallace(myseq)) + 84.00 + >>> print('%0.2f' % mt.Tm_GC(myseq)) + 58.97 + >>> print('%0.2f' % mt.Tm_NN(myseq)) + 60.32 + +Using different thermodynamic tables, e.g. from Breslauer '86 or Sugimoto '96: + + >>> print('%0.2f' % mt.Tm_NN(myseq, nn_table=mt.DNA_NN1)) # Breslauer '86 + 72.19 + >>> print('%0.2f' % mt.Tm_NN(myseq, nn_table=mt.DNA_NN2)) # Sugimoto '96 + 65.47 + +Tables for RNA and RNA/DNA hybrids are included: + + >>> print('%0.2f' % mt.Tm_NN(myseq, nn_table=mt.RNA_NN1)) # Freier '86 + 73.35 + >>> print('%0.2f' % mt.Tm_NN(myseq, nn_table=mt.R_DNA_NN1)) # Sugimoto '95 + 58.45 + +Several types of salc correction (for Tm_NN and Tm_GC): + + >>> for i in range(1, 8): + ... print("Type: %d, Tm: %0.2f" % (i, Tm_NN(myseq, saltcorr=i))) + ... + Type: 1, Tm: 54.27 + Type: 2, Tm: 54.02 + Type: 3, Tm: 59.60 + Type: 4, Tm: 60.64 + Type: 5, Tm: 60.32 + Type: 6, Tm: 59.78 + Type: 7, Tm: 59.78 + +Correction for other monovalent cations (K+, Tris), Mg2+ and dNTPs according +to von Ahsen et al. (2001) or Owczarzy et al. (2008) (for Tm_NN and Tm_GC): + + >>> print('%0.2f' % mt.Tm_NN(myseq, Na=50, Tris=10)) + 60.79 + >>> print('%0.2f' % mt.Tm_NN(myseq, Na=50, Tris=10, Mg=1.5)) + 67.39 + >>> print('%0.2f' % mt.Tm_NN(myseq, Na=50, Tris=10, Mg=1.5, saltcorr=7)) + 66.81 + >>> print('%0.2f' % mt.Tm_NN(myseq, Na=50, Tris=10, Mg=1.5, dNTPs=0.6, + ... saltcorr=7)) + 66.04 + +Dangling ends and mismatches, e.g.:: + + Oligo: CGTTCCaAAGATGTGGGCATGAGCTTAC CGTTCCaAAGATGTGGGCATGAGCTTAC + ::::::X::::::::::::::::::::: or ::::::X::::::::::::::::::::: + Template: GCAAGGcTTCTACACCCGTACTCGAATG TGCAAGGcTTCTACACCCGTACTCGAATGC + +Here: + + >>> print('%0.2f' % mt.Tm_NN('CGTTCCAAAGATGTGGGCATGAGCTTAC')) + 60.32 + >>> print('%0.2f' % mt.Tm_NN('CGTTCCAAAGATGTGGGCATGAGCTTAC', + ... c_seq='GCAAGGcTTCTACACCCGTACTCGAATG')) + 55.39 + >>> print('%0.2f' % mt.Tm_NN('CGTTCCAAAGATGTGGGCATGAGCTTAC', shift=1, + ... c_seq='TGCAAGGcTTCTACACCCGTACTCGAATGC')) + 55.69 + +The same for RNA: + + >>> print('%0.2f' % mt.Tm_NN('CGUUCCAAAGAUGUGGGCAUGAGCUUAC', + ... c_seq='UGCAAGGcUUCUACACCCGUACUCGAAUGC', + ... shift=1, nn_table=mt.RNA_NN3, + ... de_table=mt.RNA_DE1)) + 73.00 + +Note, that thermodynamic data are not available for all kind of mismatches, +e.g. most double mismatches or terminal mismatches combined with dangling ends: + + >>> print('%0.2f' % mt.Tm_NN('CGTTCCAAAGATGTGGGCATGAGCTTAC', + ... c_seq='TtCAAGGcTTCTACACCCGTACTCGAATGC', + ... shift=1)) + Traceback (most recent call last): + ValueError: no thermodynamic data for neighbors '.C/TT' available + +Make your own tables, or update/extend existing tables. E.g., add values for +locked nucleotides. Here, 'locked A' (and its complement) should be represented +by '1': + + >>> mytable = mt.make_table(oldtable=mt.DNA_NN3, + ... values={'A1/T1':(-6.608, -17.235), + ... '1A/1T':(-6.893, -15.923)}) + >>> print('%0.2f' % mt.Tm_NN('CGTTCCAAAGATGTGGGCATGAGCTTAC')) + 60.32 + >>> print('%0.2f' % mt.Tm_NN('CGTTCCA1AGATGTGGGCATGAGCTTAC', + ... nn_table=mytable, check=False)) + ... # 'check' must be False, otherwise '1' would be discarded + 62.53 + +""" + +import math +import warnings + +from Bio import BiopythonWarning +from Bio import Seq +from Bio import SeqUtils + +# Thermodynamic lookup tables (dictionaries): +# Enthalpy (dH) and entropy (dS) values for nearest neighbors and initiation +# process. Calculation of duplex initiation is quite different in several +# papers; to allow for a general calculation, all different initiation +# parameters are included in all tables and non-applicable parameters are set +# to zero. +# The key is either an initiation type (e.g., 'init_A/T') or a nearest neighbor +# duplex sequence (e.g., GT/CA, to read 5'GT3'-3'CA5'). The values are tuples +# of dH (kcal/mol), dS (cal/mol K). + +# Turn black code style off +# fmt: off + +# DNA/DNA +# Breslauer et al. (1986), Proc Natl Acad Sci USA 83: 3746-3750 +DNA_NN1 = { + "init": (0, 0), "init_A/T": (0, 0), "init_G/C": (0, 0), + "init_oneG/C": (0, -16.8), "init_allA/T": (0, -20.1), "init_5T/A": (0, 0), + "sym": (0, -1.3), + "AA/TT": (-9.1, -24.0), "AT/TA": (-8.6, -23.9), "TA/AT": (-6.0, -16.9), + "CA/GT": (-5.8, -12.9), "GT/CA": (-6.5, -17.3), "CT/GA": (-7.8, -20.8), + "GA/CT": (-5.6, -13.5), "CG/GC": (-11.9, -27.8), "GC/CG": (-11.1, -26.7), + "GG/CC": (-11.0, -26.6)} + +# Sugimoto et al. (1996), Nuc Acids Res 24 : 4501-4505 +DNA_NN2 = { + "init": (0.6, -9.0), "init_A/T": (0, 0), "init_G/C": (0, 0), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, -1.4), + "AA/TT": (-8.0, -21.9), "AT/TA": (-5.6, -15.2), "TA/AT": (-6.6, -18.4), + "CA/GT": (-8.2, -21.0), "GT/CA": (-9.4, -25.5), "CT/GA": (-6.6, -16.4), + "GA/CT": (-8.8, -23.5), "CG/GC": (-11.8, -29.0), "GC/CG": (-10.5, -26.4), + "GG/CC": (-10.9, -28.4)} + +# Allawi and SantaLucia (1997), Biochemistry 36: 10581-10594 +DNA_NN3 = { + "init": (0, 0), "init_A/T": (2.3, 4.1), "init_G/C": (0.1, -2.8), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, -1.4), + "AA/TT": (-7.9, -22.2), "AT/TA": (-7.2, -20.4), "TA/AT": (-7.2, -21.3), + "CA/GT": (-8.5, -22.7), "GT/CA": (-8.4, -22.4), "CT/GA": (-7.8, -21.0), + "GA/CT": (-8.2, -22.2), "CG/GC": (-10.6, -27.2), "GC/CG": (-9.8, -24.4), + "GG/CC": (-8.0, -19.9)} + +# SantaLucia & Hicks (2004), Annu. Rev. Biophys. Biomol. Struct 33: 415-440 +DNA_NN4 = { + "init": (0.2, -5.7), "init_A/T": (2.2, 6.9), "init_G/C": (0, 0), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, -1.4), + "AA/TT": (-7.6, -21.3), "AT/TA": (-7.2, -20.4), "TA/AT": (-7.2, -21.3), + "CA/GT": (-8.5, -22.7), "GT/CA": (-8.4, -22.4), "CT/GA": (-7.8, -21.0), + "GA/CT": (-8.2, -22.2), "CG/GC": (-10.6, -27.2), "GC/CG": (-9.8, -24.4), + "GG/CC": (-8.0, -19.9)} + +# RNA/RNA +# Freier et al. (1986), Proc Natl Acad Sci USA 83: 9373-9377 +RNA_NN1 = { + "init": (0, -10.8), "init_A/T": (0, 0), "init_G/C": (0, 0), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, -1.4), + "AA/TT": (-6.6, -18.4), "AT/TA": (-5.7, -15.5), "TA/AT": (-8.1, -22.6), + "CA/GT": (-10.5, -27.8), "GT/CA": (-10.2, -26.2), "CT/GA": (-7.6, -19.2), + "GA/CT": (-13.3, -35.5), "CG/GC": (-8.0, -19.4), "GC/CG": (-14.2, -34.9), + "GG/CC": (-12.2, -29.7)} + +# Xia et al (1998), Biochemistry 37: 14719-14735 +RNA_NN2 = { + "init": (3.61, -1.5), "init_A/T": (3.72, 10.5), "init_G/C": (0, 0), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, -1.4), + "AA/TT": (-6.82, -19.0), "AT/TA": (-9.38, -26.7), "TA/AT": (-7.69, -20.5), + "CA/GT": (-10.44, -26.9), "GT/CA": (-11.40, -29.5), + "CT/GA": (-10.48, -27.1), "GA/CT": (-12.44, -32.5), + "CG/GC": (-10.64, -26.7), "GC/CG": (-14.88, -36.9), + "GG/CC": (-13.39, -32.7)} + +# Chen et al. (2012), Biochemistry 51: 3508-3522 +RNA_NN3 = { + "init": (6.40, 6.99), "init_A/T": (3.85, 11.04), "init_G/C": (0, 0), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, -1.4), + "AA/TT": (-7.09, -19.8), "AT/TA": (-9.11, -25.8), "TA/AT": (-8.50, -22.9), + "CA/GT": (-11.03, -28.8), "GT/CA": (-11.98, -31.3), + "CT/GA": (-10.90, -28.5), "GA/CT": (-13.21, -34.9), + "CG/GC": (-10.88, -27.4), "GC/CG": (-16.04, -40.6), + "GG/CC": (-14.18, -35.0), "GT/TG": (-13.83, -46.9), + "GG/TT": (-17.82, -56.7), "AG/TT": (-3.96, -11.6), + "TG/AT": (-0.96, -1.8), "TT/AG": (-10.38, -31.8), "TG/GT": (-12.64, -38.9), + "AT/TG": (-7.39, -21.0), "CG/GT": (-5.56, -13.9), "CT/GG": (-9.44, -24.7), + "GG/CT": (-7.03, -16.8), "GT/CG": (-11.09, -28.8)} + +# RNA/DNA +# Sugimoto et al. (1995), Biochemistry 34: 11211-11216 +R_DNA_NN1 = { + "init": (1.9, -3.9), "init_A/T": (0, 0), "init_G/C": (0, 0), + "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), + "sym": (0, 0), + "TT/AA": (-11.5, -36.4), "GT/CA": (-7.8, -21.6), "CT/GA": (-7.0, -19.7), + "AT/TA": (-8.3, -23.9), "TG/AC": (-10.4, -28.4), "GG/CC": (-12.8, -31.9), + "CG/GC": (-16.3, -47.1), "AG/TC": (-9.1, -23.5), "TC/AG": (-8.6, -22.9), + "GC/CG": (-8.0, -17.1), "CC/GG": (-9.3, -23.2), "AC/TG": (-5.9, -12.3), + "TA/AT": (-7.8, -23.2), "GA/CT": (-5.5, -13.5), "CA/GT": (-9.0, -26.1), + "AA/TT": (-7.8, -21.9)} + +# Internal mismatch and inosine table (DNA) +# Allawi & SantaLucia (1997), Biochemistry 36: 10581-10594 +# Allawi & SantaLucia (1998), Biochemistry 37: 9435-9444 +# Allawi & SantaLucia (1998), Biochemistry 37: 2170-2179 +# Allawi & SantaLucia (1998), Nucl Acids Res 26: 2694-2701 +# Peyret et al. (1999), Biochemistry 38: 3468-3477 +# Watkins & SantaLucia (2005), Nucl Acids Res 33: 6258-6267 +DNA_IMM1 = { + "AG/TT": (1.0, 0.9), "AT/TG": (-2.5, -8.3), "CG/GT": (-4.1, -11.7), + "CT/GG": (-2.8, -8.0), "GG/CT": (3.3, 10.4), "GG/TT": (5.8, 16.3), + "GT/CG": (-4.4, -12.3), "GT/TG": (4.1, 9.5), "TG/AT": (-0.1, -1.7), + "TG/GT": (-1.4, -6.2), "TT/AG": (-1.3, -5.3), "AA/TG": (-0.6, -2.3), + "AG/TA": (-0.7, -2.3), "CA/GG": (-0.7, -2.3), "CG/GA": (-4.0, -13.2), + "GA/CG": (-0.6, -1.0), "GG/CA": (0.5, 3.2), "TA/AG": (0.7, 0.7), + "TG/AA": (3.0, 7.4), + "AC/TT": (0.7, 0.2), "AT/TC": (-1.2, -6.2), "CC/GT": (-0.8, -4.5), + "CT/GC": (-1.5, -6.1), "GC/CT": (2.3, 5.4), "GT/CC": (5.2, 13.5), + "TC/AT": (1.2, 0.7), "TT/AC": (1.0, 0.7), + "AA/TC": (2.3, 4.6), "AC/TA": (5.3, 14.6), "CA/GC": (1.9, 3.7), + "CC/GA": (0.6, -0.6), "GA/CC": (5.2, 14.2), "GC/CA": (-0.7, -3.8), + "TA/AC": (3.4, 8.0), "TC/AA": (7.6, 20.2), + "AA/TA": (1.2, 1.7), "CA/GA": (-0.9, -4.2), "GA/CA": (-2.9, -9.8), + "TA/AA": (4.7, 12.9), "AC/TC": (0.0, -4.4), "CC/GC": (-1.5, -7.2), + "GC/CC": (3.6, 8.9), "TC/AC": (6.1, 16.4), "AG/TG": (-3.1, -9.5), + "CG/GG": (-4.9, -15.3), "GG/CG": (-6.0, -15.8), "TG/AG": (1.6, 3.6), + "AT/TT": (-2.7, -10.8), "CT/GT": (-5.0, -15.8), "GT/CT": (-2.2, -8.4), + "TT/AT": (0.2, -1.5), + "AI/TC": (-8.9, -25.5), "TI/AC": (-5.9, -17.4), "AC/TI": (-8.8, -25.4), + "TC/AI": (-4.9, -13.9), "CI/GC": (-5.4, -13.7), "GI/CC": (-6.8, -19.1), + "CC/GI": (-8.3, -23.8), "GC/CI": (-5.0, -12.6), + "AI/TA": (-8.3, -25.0), "TI/AA": (-3.4, -11.2), "AA/TI": (-0.7, -2.6), + "TA/AI": (-1.3, -4.6), "CI/GA": (2.6, 8.9), "GI/CA": (-7.8, -21.1), + "CA/GI": (-7.0, -20.0), "GA/CI": (-7.6, -20.2), + "AI/TT": (0.49, -0.7), "TI/AT": (-6.5, -22.0), "AT/TI": (-5.6, -18.7), + "TT/AI": (-0.8, -4.3), "CI/GT": (-1.0, -2.4), "GI/CT": (-3.5, -10.6), + "CT/GI": (0.1, -1.0), "GT/CI": (-4.3, -12.1), + "AI/TG": (-4.9, -15.8), "TI/AG": (-1.9, -8.5), "AG/TI": (0.1, -1.8), + "TG/AI": (1.0, 1.0), "CI/GG": (7.1, 21.3), "GI/CG": (-1.1, -3.2), + "CG/GI": (5.8, 16.9), "GG/CI": (-7.6, -22.0), + "AI/TI": (-3.3, -11.9), "TI/AI": (0.1, -2.3), "CI/GI": (1.3, 3.0), + "GI/CI": (-0.5, -1.3)} + +# Terminal mismatch table (DNA) +# SantaLucia & Peyret (2001) Patent Application WO 01/94611 +DNA_TMM1 = { + "AA/TA": (-3.1, -7.8), "TA/AA": (-2.5, -6.3), "CA/GA": (-4.3, -10.7), + "GA/CA": (-8.0, -22.5), + "AC/TC": (-0.1, 0.5), "TC/AC": (-0.7, -1.3), "CC/GC": (-2.1, -5.1), + "GC/CC": (-3.9, -10.6), + "AG/TG": (-1.1, -2.1), "TG/AG": (-1.1, -2.7), "CG/GG": (-3.8, -9.5), + "GG/CG": (-0.7, -19.2), + "AT/TT": (-2.4, -6.5), "TT/AT": (-3.2, -8.9), "CT/GT": (-6.1, -16.9), + "GT/CT": (-7.4, -21.2), + "AA/TC": (-1.6, -4.0), "AC/TA": (-1.8, -3.8), "CA/GC": (-2.6, -5.9), + "CC/GA": (-2.7, -6.0), "GA/CC": (-5.0, -13.8), "GC/CA": (-3.2, -7.1), + "TA/AC": (-2.3, -5.9), "TC/AA": (-2.7, -7.0), + "AC/TT": (-0.9, -1.7), "AT/TC": (-2.3, -6.3), "CC/GT": (-3.2, -8.0), + "CT/GC": (-3.9, -10.6), "GC/CT": (-4.9, -13.5), "GT/CC": (-3.0, -7.8), + "TC/AT": (-2.5, -6.3), "TT/AC": (-0.7, -1.2), + "AA/TG": (-1.9, -4.4), "AG/TA": (-2.5, -5.9), "CA/GG": (-3.9, -9.6), + "CG/GA": (-6.0, -15.5), "GA/CG": (-4.3, -11.1), "GG/CA": (-4.6, -11.4), + "TA/AG": (-2.0, -4.7), "TG/AA": (-2.4, -5.8), + "AG/TT": (-3.2, -8.7), "AT/TG": (-3.5, -9.4), "CG/GT": (-3.8, -9.0), + "CT/GG": (-6.6, -18.7), "GG/CT": (-5.7, -15.9), "GT/CG": (-5.9, -16.1), + "TG/AT": (-3.9, -10.5), "TT/AG": (-3.6, -9.8)} + +# Dangling ends table (DNA) +# Bommarito et al. (2000), Nucl Acids Res 28: 1929-1934 +DNA_DE1 = { + "AA/.T": (0.2, 2.3), "AC/.G": (-6.3, -17.1), "AG/.C": (-3.7, -10.0), + "AT/.A": (-2.9, -7.6), "CA/.T": (0.6, 3.3), "CC/.G": (-4.4, -12.6), + "CG/.C": (-4.0, -11.9), "CT/.A": (-4.1, -13.0), "GA/.T": (-1.1, -1.6), + "GC/.G": (-5.1, -14.0), "GG/.C": (-3.9, -10.9), "GT/.A": (-4.2, -15.0), + "TA/.T": (-6.9, -20.0), "TC/.G": (-4.0, -10.9), "TG/.C": (-4.9, -13.8), + "TT/.A": (-0.2, -0.5), + ".A/AT": (-0.7, -0.8), ".C/AG": (-2.1, -3.9), ".G/AC": (-5.9, -16.5), + ".T/AA": (-0.5, -1.1), ".A/CT": (4.4, 14.9), ".C/CG": (-0.2, -0.1), + ".G/CC": (-2.6, -7.4), ".T/CA": (4.7, 14.2), ".A/GT": (-1.6, -3.6), + ".C/GG": (-3.9, -11.2), ".G/GC": (-3.2, -10.4), ".T/GA": (-4.1, -13.1), + ".A/TT": (2.9, 10.4), ".C/TG": (-4.4, -13.1), ".G/TC": (-5.2, -15.0), + ".T/TA": (-3.8, -12.6)} + +# Dangling ends table (RNA) +# Turner & Mathews (2010), Nucl Acids Res 38: D280-D282 +RNA_DE1 = { + ".T/AA": (-4.9, -13.2), ".T/CA": (-0.9, -1.3), ".T/GA": (-5.5, -15.1), + ".T/TA": (-2.3, -5.5), + ".G/AC": (-9.0, -23.5), ".G/CC": (-4.1, -10.6), ".G/GC": (-8.6, -22.2), + ".G/TC": (-7.5, -20.31), + ".C/AG": (-7.4, -20.3), ".C/CG": (-2.8, -7.7), ".C/GG": (-6.4, -16.4), + ".C/TG": (-3.6, -9.7), + ".T/AG": (-4.9, -13.2), ".T/CG": (-0.9, -1.3), ".T/GG": (-5.5, -15.1), + ".T/TG": (-2.3, -5.5), + ".A/AT": (-5.7, -16.1), ".A/CT": (-0.7, -1.9), ".A/GT": (-5.8, -16.4), + ".A/TT": (-2.2, -6.8), + ".G/AT": (-5.7, -16.1), ".G/CT": (-0.7, -1.9), ".G/GT": (-5.8, -16.4), + ".G/TT": (-2.2, -6.8), + "AT/.A": (-0.5, -0.6), "CT/.A": (6.9, 22.6), "GT/.A": (0.6, 2.6), + "TT/.A": (0.6, 2.6), + "AG/.C": (-1.6, -4.5), "CG/.C": (0.7, 3.2), "GG/.C": (-4.6, -14.8), + "TG/.C": (-0.4, -1.3), + "AC/.G": (-2.4, -6.1), "CC/.G": (3.3, 11.6), "GC/.G": (0.8, 3.2), + "TC/.G": (-1.4, -4.2), + "AT/.G": (-0.5, -0.6), "CT/.G": (6.9, 22.6), "GT/.G": (0.6, 2.6), + "TT/.G": (0.6, 2.6), + "AA/.T": (1.6, 6.1), "CA/.T": (2.2, 8.1), "GA/.T": (0.7, 3.5), + "TA/.T": (3.1, 10.6), + "AG/.T": (1.6, 6.1), "CG/.T": (2.2, 8.1), "GG/.T": (0.7, 3.5), + "TG/.T": (3.1, 10.6)} + +# Turn black code style on +# fmt: on + + +def make_table(oldtable=None, values=None): + """Return a table with thermodynamic parameters (as dictionary). + + Arguments: + - oldtable: An existing dictionary with thermodynamic parameters. + - values: A dictionary with new or updated values. + + E.g., to replace the initiation parameters in the Sugimoto '96 dataset with + the initiation parameters from Allawi & SantaLucia '97: + + >>> from Bio.SeqUtils.MeltingTemp import make_table, DNA_NN2 + >>> table = DNA_NN2 # Sugimoto '96 + >>> table['init_A/T'] + (0, 0) + >>> newtable = make_table(oldtable=DNA_NN2, values={'init': (0, 0), + ... 'init_A/T': (2.3, 4.1), + ... 'init_G/C': (0.1, -2.8)}) + >>> print("%0.1f, %0.1f" % newtable['init_A/T']) + 2.3, 4.1 + + """ + if oldtable is None: + table = { + "init": (0, 0), + "init_A/T": (0, 0), + "init_G/C": (0, 0), + "init_oneG/C": (0, 0), + "init_allA/T": (0, 0), + "init_5T/A": (0, 0), + "sym": (0, 0), + "AA/TT": (0, 0), + "AT/TA": (0, 0), + "TA/AT": (0, 0), + "CA/GT": (0, 0), + "GT/CA": (0, 0), + "CT/GA": (0, 0), + "GA/CT": (0, 0), + "CG/GC": (0, 0), + "GC/CG": (0, 0), + "GG/CC": (0, 0), + } + else: + table = oldtable.copy() + if values: + table.update(values) + return table + + +def _check(seq, method): + """Return a sequence which fulfills the requirements of the given method (PRIVATE). + + All Tm methods in this package require the sequence in uppercase format. + Most methods make use of the length of the sequence (directly or + indirectly), which can only be expressed as len(seq) if the sequence does + not contain whitespaces and other non-base characters. RNA sequences are + backtranscribed to DNA. This method is PRIVATE. + + Arguments: + - seq: The sequence as given by the user (passed as string). + - method: Tm_Wallace, Tm_GC or Tm_NN. + + >>> from Bio.SeqUtils import MeltingTemp as mt + >>> mt._check('10 ACGTTGCAAG tccatggtac', 'Tm_NN') + 'ACGTTGCAAGTCCATGGTAC' + + """ + seq = "".join(seq.split()).upper() + seq = str(Seq.Seq(seq).back_transcribe()) + if method == "Tm_Wallace": + return seq + if method == "Tm_GC": + baseset = ( + "A", + "B", + "C", + "D", + "G", + "H", + "I", + "K", + "M", + "N", + "R", + "S", + "T", + "V", + "W", + "X", + "Y", + ) + if method == "Tm_NN": + baseset = ("A", "C", "G", "T", "I") + seq = "".join([base for base in seq if base in baseset]) + return seq + + +def salt_correction(Na=0, K=0, Tris=0, Mg=0, dNTPs=0, method=1, seq=None): + """Calculate a term to correct Tm for salt ions. + + Depending on the Tm calculation, the term will correct Tm or entropy. To + calculate corrected Tm values, different operations need to be applied: + + - methods 1-4: Tm(new) = Tm(old) + corr + - method 5: deltaS(new) = deltaS(old) + corr + - methods 6+7: Tm(new) = 1/(1/Tm(old) + corr) + + Arguments: + - Na, K, Tris, Mg, dNTPS: Millimolar concentration of respective ion. To + have a simple 'salt correction', just pass Na. If any of K, Tris, Mg and + dNTPS is non-zero, a 'sodium-equivalent' concentration is calculated + according to von Ahsen et al. (2001, Clin Chem 47: 1956-1961): + [Na_eq] = [Na+] + [K+] + [Tris]/2 + 120*([Mg2+] - [dNTPs])^0.5 + If [dNTPs] >= [Mg2+]: [Na_eq] = [Na+] + [K+] + [Tris]/2 + - method: Which method to be applied. Methods 1-4 correct Tm, method 5 + corrects deltaS, methods 6 and 7 correct 1/Tm. The methods are: + + 1. 16.6 x log[Na+] + (Schildkraut & Lifson (1965), Biopolymers 3: 195-208) + 2. 16.6 x log([Na+]/(1.0 + 0.7*[Na+])) + (Wetmur (1991), Crit Rev Biochem Mol Biol 126: 227-259) + 3. 12.5 x log(Na+] + (SantaLucia et al. (1996), Biochemistry 35: 3555-3562 + 4. 11.7 x log[Na+] + (SantaLucia (1998), Proc Natl Acad Sci USA 95: 1460-1465 + 5. Correction for deltaS: 0.368 x (N-1) x ln[Na+] + (SantaLucia (1998), Proc Natl Acad Sci USA 95: 1460-1465) + 6. (4.29(%GC)-3.95)x1e-5 x ln[Na+] + 9.40e-6 x ln[Na+]^2 + (Owczarzy et al. (2004), Biochemistry 43: 3537-3554) + 7. Complex formula with decision tree and 7 empirical constants. + Mg2+ is corrected for dNTPs binding (if present) + (Owczarzy et al. (2008), Biochemistry 47: 5336-5353) + + Examples + -------- + >>> from Bio.SeqUtils.MeltingTemp import salt_correction + >>> print('%0.2f' % salt_correction(Na=50, method=1)) + -21.60 + >>> print('%0.2f' % salt_correction(Na=50, method=2)) + -21.85 + >>> print('%0.2f' % salt_correction(Na=100, Tris=20, method=2)) + -16.45 + >>> print('%0.2f' % salt_correction(Na=100, Tris=20, Mg=1.5, method=2)) + -10.99 + + """ + if method in (5, 6, 7) and not seq: + raise ValueError( + "sequence is missing (is needed to calculate GC content or sequence length)." + ) + corr = 0 + if not method: + return corr + Mon = Na + K + Tris / 2.0 # Note: all these values are millimolar + mg = Mg * 1e-3 # Lowercase ions (mg, mon, dntps) are molar + # Na equivalent according to von Ahsen et al. (2001): + if sum((K, Mg, Tris, dNTPs)) > 0 and method != 7 and dNTPs < Mg: + # dNTPs bind Mg2+ strongly. If [dNTPs] is larger or equal than + # [Mg2+], free Mg2+ is considered not to be relevant. + Mon += 120 * math.sqrt(Mg - dNTPs) + mon = Mon * 1e-3 + # Note: math.log = ln(), math.log10 = log() + if method in range(1, 7) and not mon: + raise ValueError( + "Total ion concentration of zero is not allowed in this method." + ) + if method == 1: + corr = 16.6 * math.log10(mon) + if method == 2: + corr = 16.6 * math.log10((mon) / (1.0 + 0.7 * (mon))) + if method == 3: + corr = 12.5 * math.log10(mon) + if method == 4: + corr = 11.7 * math.log10(mon) + if method == 5: + corr = 0.368 * (len(seq) - 1) * math.log(mon) + if method == 6: + corr = ( + (4.29 * SeqUtils.gc_fraction(seq, "ignore") - 3.95) * 1e-5 * math.log(mon) + ) + 9.40e-6 * math.log(mon) ** 2 + # Turn black code style off + # fmt: off + if method == 7: + a, b, c, d = 3.92, -0.911, 6.26, 1.42 + e, f, g = -48.2, 52.5, 8.31 + if dNTPs > 0: + dntps = dNTPs * 1e-3 + ka = 3e4 # Dissociation constant for Mg:dNTP + # Free Mg2+ calculation: + mg = (-(ka * dntps - ka * mg + 1.0) + + math.sqrt((ka * dntps - ka * mg + 1.0) ** 2 + + 4.0 * ka * mg)) / (2.0 * ka) + if Mon > 0: + R = math.sqrt(mg) / mon + if R < 0.22: + corr = (4.29 * SeqUtils.gc_fraction(seq, "ignore") - 3.95) * \ + 1e-5 * math.log(mon) + 9.40e-6 * math.log(mon) ** 2 + return corr + elif R < 6.0: + a = 3.92 * (0.843 - 0.352 * math.sqrt(mon) * math.log(mon)) + d = 1.42 * (1.279 - 4.03e-3 * math.log(mon) + - 8.03e-3 * math.log(mon) ** 2) + g = 8.31 * (0.486 - 0.258 * math.log(mon) + + 5.25e-3 * math.log(mon) ** 3) + corr = (a + b * math.log(mg) + (SeqUtils.gc_fraction(seq, "ignore")) + * (c + d * math.log(mg)) + (1 / (2.0 * (len(seq) - 1))) + * (e + f * math.log(mg) + g * math.log(mg) ** 2)) * 1e-5 + # Turn black code style on + # fmt: on + if method > 7: + raise ValueError("Allowed values for parameter 'method' are 1-7.") + return corr + + +def chem_correction( + melting_temp, DMSO=0, fmd=0, DMSOfactor=0.75, fmdfactor=0.65, fmdmethod=1, GC=None +): + """Correct a given Tm for DMSO and formamide. + + Please note that these corrections are +/- rough approximations. + + Arguments: + - melting_temp: Melting temperature. + - DMSO: Percent DMSO. + - fmd: Formamide concentration in %(fmdmethod=1) or molar (fmdmethod=2). + - DMSOfactor: How much should Tm decreases per percent DMSO. Default=0.65 + (von Ahsen et al. 2001). Other published values are 0.5, 0.6 and 0.675. + - fmdfactor: How much should Tm decrease per percent formamide. + Default=0.65. Several papers report factors between 0.6 and 0.72. + - fmdmethod: + + 1. Tm = Tm - factor(%formamide) (Default) + 2. Tm = Tm + (0.453(f(GC)) - 2.88) x [formamide] + + Here f(GC) is fraction of GC. + Note (again) that in fmdmethod=1 formamide concentration is given in %, + while in fmdmethod=2 it is given in molar. + - GC: GC content in percent. + + Examples: + >>> from Bio.SeqUtils import MeltingTemp as mt + >>> mt.chem_correction(70) + 70 + >>> print('%0.2f' % mt.chem_correction(70, DMSO=3)) + 67.75 + >>> print('%0.2f' % mt.chem_correction(70, fmd=5)) + 66.75 + >>> print('%0.2f' % mt.chem_correction(70, fmdmethod=2, fmd=1.25, + ... GC=50)) + 66.68 + + """ + if DMSO: + melting_temp -= DMSOfactor * DMSO + if fmd: + # McConaughy et al. (1969), Biochemistry 8: 3289-3295 + if fmdmethod == 1: + # Note: Here fmd is given in percent + melting_temp -= fmdfactor * fmd + # Blake & Delcourt (1996), Nucl Acids Res 11: 2095-2103 + if fmdmethod == 2: + if GC is None or GC < 0: + raise ValueError("'GC' is missing or negative") + # Note: Here fmd is given in molar + melting_temp += (0.453 * (GC / 100.0) - 2.88) * fmd + if fmdmethod not in (1, 2): + raise ValueError("'fmdmethod' must be 1 or 2") + return melting_temp + + +def Tm_Wallace(seq, check=True, strict=True): + """Calculate and return the Tm using the 'Wallace rule'. + + Tm = 4 degC * (G + C) + 2 degC * (A+T) + + The Wallace rule (Thein & Wallace 1986, in Human genetic diseases: a + practical approach, 33-50) is often used as rule of thumb for approximate + Tm calculations for primers of 14 to 20 nt length. + + Non-DNA characters (e.g., E, F, J, !, 1, etc) are ignored by this method. + + Examples: + >>> from Bio.SeqUtils import MeltingTemp as mt + >>> mt.Tm_Wallace('ACGTTGCAATGCCGTA') + 48.0 + >>> mt.Tm_Wallace('ACGT TGCA ATGC CGTA') + 48.0 + >>> mt.Tm_Wallace('1ACGT2TGCA3ATGC4CGTA') + 48.0 + + """ + seq = str(seq) + if check: + seq = _check(seq, "Tm_Wallace") + + melting_temp = 2 * (sum(map(seq.count, ("A", "T", "W")))) + 4 * ( + sum(map(seq.count, ("C", "G", "S"))) + ) + + # Intermediate values for ambiguous positions: + tmp = ( + 3 * (sum(map(seq.count, ("K", "M", "N", "R", "Y")))) + + 10 / 3.0 * (sum(map(seq.count, ("B", "V")))) + + 8 / 3.0 * (sum(map(seq.count, ("D", "H")))) + ) + if strict and tmp: + raise ValueError( + "ambiguous bases B, D, H, K, M, N, R, V, Y not allowed when strict=True" + ) + else: + melting_temp += tmp + return melting_temp + + +def Tm_GC( + seq, + check=True, + strict=True, + valueset=7, + userset=None, + Na=50, + K=0, + Tris=0, + Mg=0, + dNTPs=0, + saltcorr=0, + mismatch=True, +): + """Return the Tm using empirical formulas based on GC content. + + General format: Tm = A + B(%GC) - C/N + salt correction - D(%mismatch) + + A, B, C, D: empirical constants, N: primer length + D (amount of decrease in Tm per % mismatch) is often 1, but sometimes other + values have been used (0.6-1.5). Use 'X' to indicate the mismatch position + in the sequence. Note that this mismatch correction is a rough estimate. + + >>> from Bio.SeqUtils import MeltingTemp as mt + >>> print("%0.2f" % mt.Tm_GC('CTGCTGATXGCACGAGGTTATGG', valueset=2)) + 69.20 + + Arguments: + - valueset: A few often cited variants are included: + + 1. Tm = 69.3 + 0.41(%GC) - 650/N + (Marmur & Doty 1962, J Mol Biol 5: 109-118; Chester & Marshak 1993), + Anal Biochem 209: 284-290) + 2. Tm = 81.5 + 0.41(%GC) - 675/N - %mismatch + 'QuikChange' formula. Recommended (by the manufacturer) for the + design of primers for QuikChange mutagenesis. + 3. Tm = 81.5 + 0.41(%GC) - 675/N + 16.6 x log[Na+] + (Marmur & Doty 1962, J Mol Biol 5: 109-118; Schildkraut & Lifson + 1965, Biopolymers 3: 195-208) + 4. Tm = 81.5 + 0.41(%GC) - 500/N + 16.6 x log([Na+]/(1.0 + 0.7 x + [Na+])) - %mismatch + (Wetmur 1991, Crit Rev Biochem Mol Biol 126: 227-259). This is the + standard formula in approximative mode of MELTING 4.3. + 5. Tm = 78 + 0.7(%GC) - 500/N + 16.6 x log([Na+]/(1.0 + 0.7 x [Na+])) + - %mismatch + (Wetmur 1991, Crit Rev Biochem Mol Biol 126: 227-259). For RNA. + 6. Tm = 67 + 0.8(%GC) - 500/N + 16.6 x log([Na+]/(1.0 + 0.7 x [Na+])) + - %mismatch + (Wetmur 1991, Crit Rev Biochem Mol Biol 126: 227-259). For RNA/DNA + hybrids. + 7. Tm = 81.5 + 0.41(%GC) - 600/N + 16.6 x log[Na+] + Used by Primer3Plus to calculate the product Tm. Default set. + 8. Tm = 77.1 + 0.41(%GC) - 528/N + 11.7 x log[Na+] + (von Ahsen et al. 2001, Clin Chem 47: 1956-1961). Recommended 'as a + tradeoff between accuracy and ease of use'. + + - userset: Tuple of four values for A, B, C, and D. Usersets override + valuesets. + - Na, K, Tris, Mg, dNTPs: Concentration of the respective ions [mM]. If + any of K, Tris, Mg and dNTPS is non-zero, a 'sodium-equivalent' + concentration is calculated and used for salt correction (von Ahsen et + al., 2001). + - saltcorr: Type of salt correction (see method salt_correction). + Default=0. 0 or None means no salt correction. + - mismatch: If 'True' (default) every 'X' in the sequence is counted as + mismatch. + + """ + if saltcorr == 5: + raise ValueError("salt-correction method 5 not applicable to Tm_GC") + seq = str(seq) + if check: + seq = _check(seq, "Tm_GC") + + if strict and any(x in seq for x in "KMNRYBVDH"): + raise ValueError( + "ambiguous bases B, D, H, K, M, N, R, V, Y not allowed when 'strict=True'" + ) + + # Ambiguous bases: add 0.5, 0.67 or 0.33% depending on G+C probability: + percent_gc = SeqUtils.gc_fraction(seq, "weighted") * 100 + + # gc_fraction counts X as 0.5 + if mismatch: + percent_gc -= seq.count("X") * 50.0 / len(seq) + + if userset: + A, B, C, D = userset + else: + if valueset == 1: + A, B, C, D = (69.3, 0.41, 650, 1) + saltcorr = 0 + if valueset == 2: + A, B, C, D = (81.5, 0.41, 675, 1) + saltcorr = 0 + if valueset == 3: + A, B, C, D = (81.5, 0.41, 675, 1) + saltcorr = 1 + if valueset == 4: + A, B, C, D = (81.5, 0.41, 500, 1) + saltcorr = 2 + if valueset == 5: + A, B, C, D = (78.0, 0.7, 500, 1) + saltcorr = 2 + if valueset == 6: + A, B, C, D = (67.0, 0.8, 500, 1) + saltcorr = 2 + if valueset == 7: + A, B, C, D = (81.5, 0.41, 600, 1) + saltcorr = 1 + if valueset == 8: + A, B, C, D = (77.1, 0.41, 528, 1) + saltcorr = 4 + if valueset > 8: + raise ValueError("allowed values for parameter 'valueset' are 0-8.") + + melting_temp = A + B * percent_gc - C / len(seq) + if saltcorr: + melting_temp += salt_correction( + Na=Na, K=K, Tris=Tris, Mg=Mg, dNTPs=dNTPs, seq=seq, method=saltcorr + ) + if mismatch: + melting_temp -= D * (seq.count("X") * 100.0 / len(seq)) + return melting_temp + + +def _key_error(neighbors, strict): + """Throw an error or a warning if there is no data for the neighbors (PRIVATE).""" + # We haven't found the key in the tables + if strict: + raise ValueError(f"no thermodynamic data for neighbors {neighbors!r} available") + else: + warnings.warn( + "no themodynamic data for neighbors %r available. " + "Calculation will be wrong" % neighbors, + BiopythonWarning, + ) + + +def Tm_NN( + seq, + check=True, + strict=True, + c_seq=None, + shift=0, + nn_table=None, + tmm_table=None, + imm_table=None, + de_table=None, + dnac1=25, + dnac2=25, + selfcomp=False, + Na=50, + K=0, + Tris=0, + Mg=0, + dNTPs=0, + saltcorr=5, +): + """Return the Tm using nearest neighbor thermodynamics. + + Arguments: + - seq: The primer/probe sequence as string or Biopython sequence object. + For RNA/DNA hybridizations seq must be the RNA sequence. + - c_seq: Complementary sequence. The sequence of the template/target in + 3'->5' direction. c_seq is necessary for mismatch correction and + dangling-ends correction. Both corrections will automatically be + applied if mismatches or dangling ends are present. Default=None. + - shift: Shift of the primer/probe sequence on the template/target + sequence, e.g.:: + + shift=0 shift=1 shift= -1 + Primer (seq): 5' ATGC... 5' ATGC... 5' ATGC... + Template (c_seq): 3' TACG... 3' CTACG... 3' ACG... + + The shift parameter is necessary to align seq and c_seq if they have + different lengths or if they should have dangling ends. Default=0 + - table: Thermodynamic NN values, eight tables are implemented: + For DNA/DNA hybridizations: + + - DNA_NN1: values from Breslauer et al. (1986) + - DNA_NN2: values from Sugimoto et al. (1996) + - DNA_NN3: values from Allawi & SantaLucia (1997) (default) + - DNA_NN4: values from SantaLucia & Hicks (2004) + + For RNA/RNA hybridizations: + + - RNA_NN1: values from Freier et al. (1986) + - RNA_NN2: values from Xia et al. (1998) + - RNA_NN3: values from Chen et al. (2012) + + For RNA/DNA hybridizations: + + - R_DNA_NN1: values from Sugimoto et al. (1995) + Note that ``seq`` must be the RNA sequence. + + Use the module's maketable method to make a new table or to update one + one of the implemented tables. + - tmm_table: Thermodynamic values for terminal mismatches. + Default: DNA_TMM1 (SantaLucia & Peyret, 2001) + - imm_table: Thermodynamic values for internal mismatches, may include + insosine mismatches. Default: DNA_IMM1 (Allawi & SantaLucia, 1997-1998; + Peyret et al., 1999; Watkins & SantaLucia, 2005) + - de_table: Thermodynamic values for dangling ends: + + - DNA_DE1: for DNA. Values from Bommarito et al. (2000) (default) + - RNA_DE1: for RNA. Values from Turner & Mathews (2010) + + - dnac1: Concentration of the higher concentrated strand [nM]. Typically + this will be the primer (for PCR) or the probe. Default=25. + - dnac2: Concentration of the lower concentrated strand [nM]. In PCR this + is the template strand which concentration is typically very low and may + be ignored (dnac2=0). In oligo/oligo hybridization experiments, dnac1 + equals dnac1. Default=25. + MELTING and Primer3Plus use k = [Oligo(Total)]/4 by default. To mimic + this behaviour, you have to divide [Oligo(Total)] by 2 and assign this + concentration to dnac1 and dnac2. E.g., Total oligo concentration of + 50 nM in Primer3Plus means dnac1=25, dnac2=25. + - selfcomp: Is the sequence self-complementary? Default=False. If 'True' + the primer is thought binding to itself, thus dnac2 is not considered. + - Na, K, Tris, Mg, dNTPs: See method 'Tm_GC' for details. Defaults: Na=50, + K=0, Tris=0, Mg=0, dNTPs=0. + - saltcorr: See method 'Tm_GC'. Default=5. 0 means no salt correction. + + """ + # Set defaults + if not nn_table: + nn_table = DNA_NN3 + if not tmm_table: + tmm_table = DNA_TMM1 + if not imm_table: + imm_table = DNA_IMM1 + if not de_table: + de_table = DNA_DE1 + + seq = str(seq) + if not c_seq: + # c_seq must be provided by user if dangling ends or mismatches should + # be taken into account. Otherwise take perfect complement. + c_seq = Seq.Seq(seq).complement() + c_seq = str(c_seq) + if check: + seq = _check(seq, "Tm_NN") + c_seq = _check(c_seq, "Tm_NN") + tmp_seq = seq + tmp_cseq = c_seq + delta_h = 0 + delta_s = 0 + d_h = 0 # Names for indexes + d_s = 1 # 0 and 1 + + # Dangling ends? + if shift or len(seq) != len(c_seq): + # Align both sequences using the shift parameter + if shift > 0: + tmp_seq = "." * shift + seq + if shift < 0: + tmp_cseq = "." * abs(shift) + c_seq + if len(tmp_cseq) > len(tmp_seq): + tmp_seq += (len(tmp_cseq) - len(tmp_seq)) * "." + if len(tmp_cseq) < len(tmp_seq): + tmp_cseq += (len(tmp_seq) - len(tmp_cseq)) * "." + # Remove 'over-dangling' ends + while tmp_seq.startswith("..") or tmp_cseq.startswith(".."): + tmp_seq = tmp_seq[1:] + tmp_cseq = tmp_cseq[1:] + while tmp_seq.endswith("..") or tmp_cseq.endswith(".."): + tmp_seq = tmp_seq[:-1] + tmp_cseq = tmp_cseq[:-1] + # Now for the dangling ends + if tmp_seq.startswith(".") or tmp_cseq.startswith("."): + left_de = tmp_seq[:2] + "/" + tmp_cseq[:2] + try: + delta_h += de_table[left_de][d_h] + delta_s += de_table[left_de][d_s] + except KeyError: + _key_error(left_de, strict) + tmp_seq = tmp_seq[1:] + tmp_cseq = tmp_cseq[1:] + if tmp_seq.endswith(".") or tmp_cseq.endswith("."): + right_de = tmp_cseq[-2:][::-1] + "/" + tmp_seq[-2:][::-1] + try: + delta_h += de_table[right_de][d_h] + delta_s += de_table[right_de][d_s] + except KeyError: + _key_error(right_de, strict) + tmp_seq = tmp_seq[:-1] + tmp_cseq = tmp_cseq[:-1] + + # Now for terminal mismatches + left_tmm = tmp_cseq[:2][::-1] + "/" + tmp_seq[:2][::-1] + if left_tmm in tmm_table: + delta_h += tmm_table[left_tmm][d_h] + delta_s += tmm_table[left_tmm][d_s] + tmp_seq = tmp_seq[1:] + tmp_cseq = tmp_cseq[1:] + right_tmm = tmp_seq[-2:] + "/" + tmp_cseq[-2:] + if right_tmm in tmm_table: + delta_h += tmm_table[right_tmm][d_h] + delta_s += tmm_table[right_tmm][d_s] + tmp_seq = tmp_seq[:-1] + tmp_cseq = tmp_cseq[:-1] + + # Now everything 'unusual' at the ends is handled and removed and we can + # look at the initiation. + # One or several of the following initiation types may apply: + + # Type: General initiation value + delta_h += nn_table["init"][d_h] + delta_s += nn_table["init"][d_s] + + # Type: Duplex with no (allA/T) or at least one (oneG/C) GC pair + if SeqUtils.gc_fraction(seq, "ignore") == 0: + delta_h += nn_table["init_allA/T"][d_h] + delta_s += nn_table["init_allA/T"][d_s] + else: + delta_h += nn_table["init_oneG/C"][d_h] + delta_s += nn_table["init_oneG/C"][d_s] + + # Type: Penalty if 5' end is T + if seq.startswith("T"): + delta_h += nn_table["init_5T/A"][d_h] + delta_s += nn_table["init_5T/A"][d_s] + if seq.endswith("A"): + delta_h += nn_table["init_5T/A"][d_h] + delta_s += nn_table["init_5T/A"][d_s] + + # Type: Different values for G/C or A/T terminal basepairs + ends = seq[0] + seq[-1] + AT = ends.count("A") + ends.count("T") + GC = ends.count("G") + ends.count("C") + delta_h += nn_table["init_A/T"][d_h] * AT + delta_s += nn_table["init_A/T"][d_s] * AT + delta_h += nn_table["init_G/C"][d_h] * GC + delta_s += nn_table["init_G/C"][d_s] * GC + + # Finally, the 'zipping' + for basenumber in range(len(tmp_seq) - 1): + neighbors = ( + tmp_seq[basenumber : basenumber + 2] + + "/" + + tmp_cseq[basenumber : basenumber + 2] + ) + if neighbors in imm_table: + delta_h += imm_table[neighbors][d_h] + delta_s += imm_table[neighbors][d_s] + elif neighbors[::-1] in imm_table: + delta_h += imm_table[neighbors[::-1]][d_h] + delta_s += imm_table[neighbors[::-1]][d_s] + elif neighbors in nn_table: + delta_h += nn_table[neighbors][d_h] + delta_s += nn_table[neighbors][d_s] + elif neighbors[::-1] in nn_table: + delta_h += nn_table[neighbors[::-1]][d_h] + delta_s += nn_table[neighbors[::-1]][d_s] + else: + # We haven't found the key... + _key_error(neighbors, strict) + + k = (dnac1 - (dnac2 / 2.0)) * 1e-9 + if selfcomp: + k = dnac1 * 1e-9 + delta_h += nn_table["sym"][d_h] + delta_s += nn_table["sym"][d_s] + R = 1.987 # universal gas constant in Cal/degrees C*Mol + if saltcorr: + corr = salt_correction( + Na=Na, K=K, Tris=Tris, Mg=Mg, dNTPs=dNTPs, method=saltcorr, seq=seq + ) + if saltcorr == 5: + delta_s += corr + melting_temp = (1000 * delta_h) / (delta_s + (R * (math.log(k)))) - 273.15 + if saltcorr in (1, 2, 3, 4): + melting_temp += corr + if saltcorr in (6, 7): + # Tm = 1/(1/Tm + corr) + melting_temp = 1 / (1 / (melting_temp + 273.15) + corr) - 273.15 + + return melting_temp + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/ProtParam.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/ProtParam.py new file mode 100644 index 0000000000000000000000000000000000000000..cac523b4ce1470b5b5694cb6b99ba5d27656a1fa --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/ProtParam.py @@ -0,0 +1,350 @@ +# Copyright 2003 Yair Benita. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Simple protein analysis. + +Examples +-------- +>>> from Bio.SeqUtils.ProtParam import ProteinAnalysis +>>> X = ProteinAnalysis("MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNGGHFLRILPDGTVDGT" +... "RDRSDQHIQLQLSAESVGEVYIKSTETGQYLAMDTSGLLYGSQTPSEEC" +... "LFLERLEENHYNTYTSKKHAEKNWFVGLKKNGSCKRGPRTHYGQKAILF" +... "LPLPV") +>>> print(X.count_amino_acids()['A']) +6 +>>> print(X.count_amino_acids()['E']) +12 +>>> print("%0.2f" % X.amino_acids_percent['A']) +3.95 +>>> print("%0.2f" % X.amino_acids_percent['L']) +11.84 +>>> print("%0.2f" % X.molecular_weight()) +17103.16 +>>> print("%0.2f" % X.aromaticity()) +0.10 +>>> print("%0.2f" % X.instability_index()) +41.98 +>>> print("%0.2f" % X.isoelectric_point()) +7.72 +>>> sec_struc = X.secondary_structure_fraction() # [helix, turn, sheet] +>>> print("%0.2f" % sec_struc[0]) # helix +0.33 +>>> print("%0.2f" % sec_struc[1]) # turn +0.29 +>>> print("%0.2f" % sec_struc[2]) # sheet +0.37 +>>> epsilon_prot = X.molar_extinction_coefficient() # [reduced, oxidized] +>>> print(epsilon_prot[0]) # with reduced cysteines +17420 +>>> print(epsilon_prot[1]) # with disulfid bridges +17545 + +Other public methods are: + - gravy + - protein_scale + - flexibility + - charge_at_pH + +""" + +import functools +import sys + +from Bio.Data import IUPACData +from Bio.Seq import Seq +from Bio.SeqUtils import IsoelectricPoint # Local +from Bio.SeqUtils import molecular_weight +from Bio.SeqUtils import ProtParamData # Local + + +class ProteinAnalysis: + """Class containing methods for protein analysis. + + The constructor takes two arguments. + The first is the protein sequence as a string or a Seq object. + + The second argument is optional. If set to True, the weight of the amino + acids will be calculated using their monoisotopic mass (the weight of the + most abundant isotopes for each element), instead of the average molecular + mass (the averaged weight of all stable isotopes for each element). + If set to false (the default value) or left out, the IUPAC average + molecular mass will be used for the calculation. + + """ + + def __init__(self, prot_sequence, monoisotopic=False): + """Initialize the class.""" + self.sequence = prot_sequence.upper() + self.amino_acids_content = None + self.length = len(self.sequence) + self.monoisotopic = monoisotopic + + def count_amino_acids(self): + """Count standard amino acids, return a dict. + + Counts the number times each amino acid is in the protein + sequence. Returns a dictionary {AminoAcid:Number}. + + The return value is cached in self.amino_acids_content. + It is not recalculated upon subsequent calls. + """ + if self.amino_acids_content is None: + prot_dic = dict.fromkeys(IUPACData.protein_letters, 0) + for aa in prot_dic: + prot_dic[aa] = self.sequence.count(aa) + + self.amino_acids_content = prot_dic + + return self.amino_acids_content + + @functools.cached_property + def amino_acids_percent(self): + """Get the amino acid content in percentages. + + The same as count_amino_acids, but returns the number as a percentage + of the sequence length. Returns a dictionary of {AminoAcid:percentage}, + where the percentage is in the range 0-100. + """ + aa_counts = self.count_amino_acids() + percentages = { + aa: (count * 100 / self.length) for aa, count in aa_counts.items() + } + + return percentages + + def molecular_weight(self): + """Calculate MW from Protein sequence.""" + return molecular_weight( + self.sequence, seq_type="protein", monoisotopic=self.monoisotopic + ) + + def aromaticity(self): + """Calculate the aromaticity according to Lobry, 1994. + + Calculates the aromaticity value of a protein according to Lobry, 1994. + It is simply the relative frequency of Phe+Trp+Tyr. + """ + aromatic_aas = "YWF" + aa_percentages = self.amino_acids_percent + + aromaticity = sum(aa_percentages[aa] / 100 for aa in aromatic_aas) + + return aromaticity + + def instability_index(self): + """Calculate the instability index according to Guruprasad et al 1990. + + Implementation of the method of Guruprasad et al. 1990 to test a + protein for stability. Any value above 40 means the protein is unstable + (has a short half life). + + See: Guruprasad K., Reddy B.V.B., Pandit M.W. + Protein Engineering 4:155-161(1990). + """ + index = ProtParamData.DIWV + score = 0.0 + + for i in range(self.length - 1): + this, next = self.sequence[i : i + 2] + dipeptide_value = index[this][next] + score += dipeptide_value + + return (10.0 / self.length) * score + + def flexibility(self): + """Calculate the flexibility according to Vihinen, 1994. + + No argument to change window size because parameters are specific for + a window=9. The parameters used are optimized for determining the + flexibility. + """ + flexibilities = ProtParamData.Flex + window_size = 9 + weights = [0.25, 0.4375, 0.625, 0.8125, 1] + scores = [] + + for i in range(self.length - window_size): + subsequence = self.sequence[i : i + window_size] + score = 0.0 + + for j in range(window_size // 2): + front = subsequence[j] + back = subsequence[window_size - j - 1] + score += (flexibilities[front] + flexibilities[back]) * weights[j] + + middle = subsequence[window_size // 2 + 1] + score += flexibilities[middle] + + scores.append(score / 5.25) + + return scores + + def gravy(self, scale="KyteDoolitle"): + """Calculate the GRAVY (Grand Average of Hydropathy) according to Kyte and Doolitle, 1982. + + Utilizes the given Hydrophobicity scale, by default uses the original + proposed by Kyte and Doolittle (KyteDoolitle). Other options are: + Aboderin, AbrahamLeo, Argos, BlackMould, BullBreese, Casari, Cid, + Cowan3.4, Cowan7.5, Eisenberg, Engelman, Fasman, Fauchere, GoldSack, + Guy, Jones, Juretic, Kidera, Miyazawa, Parker,Ponnuswamy, Rose, + Roseman, Sweet, Tanford, Wilson and Zimmerman. + + New scales can be added in ProtParamData. + """ + selected_scale = ProtParamData.gravy_scales.get(scale, -1) + + if selected_scale == -1: + raise ValueError(f"scale: {scale} not known") + + total_gravy = sum(selected_scale[aa] for aa in self.sequence) + + return total_gravy / self.length + + def _weight_list(self, window, edge): + """Make list of relative weight of window edges (PRIVATE). + + The relative weight of window edges are compared to the window + center. The weights are linear. It actually generates half a list. + For a window of size 9 and edge 0.4 you get a list of + [0.4, 0.55, 0.7, 0.85]. + """ + unit = 2 * (1.0 - edge) / (window - 1) + weights = [0.0] * (window // 2) + + for i in range(window // 2): + weights[i] = edge + unit * i + + return weights + + def protein_scale(self, param_dict, window, edge=1.0): + """Compute a profile by any amino acid scale. + + An amino acid scale is defined by a numerical value assigned to each + type of amino acid. The most frequently used scales are the + hydrophobicity or hydrophilicity scales and the secondary structure + conformational parameters scales, but many other scales exist which + are based on different chemical and physical properties of the + amino acids. You can set several parameters that control the + computation of a scale profile, such as the window size and the window + edge relative weight value. + + WindowSize: The window size is the length of the interval to use for + the profile computation. For a window size n, we use the i-(n-1)/2 + neighboring residues on each side to compute the score for residue i. + The score for residue i is the sum of the scaled values for these + amino acids, optionally weighted according to their position in the + window. + + Edge: The central amino acid of the window always has a weight of 1. + By default, the amino acids at the remaining window positions have the + same weight, but you can make the residue at the center of the window + have a larger weight than the others by setting the edge value for the + residues at the beginning and end of the interval to a value between + 0 and 1. For instance, for Edge=0.4 and a window size of 5 the weights + will be: 0.4, 0.7, 1.0, 0.7, 0.4. + + The method returns a list of values which can be plotted to view the + change along a protein sequence. Many scales exist. Just add your + favorites to the ProtParamData modules. + + Similar to expasy's ProtScale: + http://www.expasy.org/cgi-bin/protscale.pl + """ + # generate the weights + # _weight_list returns only one tail. If the list should be + # [0.4,0.7,1.0,0.7,0.4] what you actually get from _weights_list + # is [0.4,0.7]. The correct calculation is done in the loop. + weights = self._weight_list(window, edge) + scores = [] + + # the score in each Window is divided by the sum of weights + # (* 2 + 1) since the weight list is one sided: + sum_of_weights = sum(weights) * 2 + 1 + + for i in range(self.length - window + 1): + subsequence = self.sequence[i : i + window] + score = 0.0 + + for j in range(window // 2): + # walk from the outside of the Window towards the middle. + # Iddo: try/except clauses added to avoid raising an exception + # on a non-standard amino acid + try: + front = param_dict[subsequence[j]] + back = param_dict[subsequence[window - j - 1]] + score += weights[j] * front + weights[j] * back + except KeyError: + sys.stderr.write( + "warning: %s or %s is not a standard " + "amino acid.\n" % (subsequence[j], subsequence[window - j - 1]) + ) + + # Now add the middle value, which always has a weight of 1. + middle = subsequence[window // 2] + if middle in param_dict: + score += param_dict[middle] + else: + sys.stderr.write(f"warning: {middle} is not a standard amino acid.\n") + + scores.append(score / sum_of_weights) + + return scores + + def isoelectric_point(self): + """Calculate the isoelectric point. + + Uses the module IsoelectricPoint to calculate the pI of a protein. + """ + aa_content = self.count_amino_acids() + + ie_point = IsoelectricPoint.IsoelectricPoint(self.sequence, aa_content) + return ie_point.pi() + + def charge_at_pH(self, pH): + """Calculate the charge of a protein at given pH.""" + aa_content = self.count_amino_acids() + charge = IsoelectricPoint.IsoelectricPoint(self.sequence, aa_content) + return charge.charge_at_pH(pH) + + def secondary_structure_fraction(self): + """Calculate fraction of helix, turn and sheet. + + Returns a list of the fraction of amino acids which tend + to be in Helix, Turn or Sheet, according to Haimov and Srebnik, 2016; + Hutchinson and Thornton, 1994; and Kim and Berg, 1993, respectively. + + Amino acids in helix: E, M, A, L, K. + Amino acids in turn: N, P, G, S, D. + Amino acids in sheet: V, I, Y, F, W, L, T. + + Note that, prior to v1.82, this method wrongly returned + (Sheet, Turn, Helix) while claiming to return (Helix, Turn, Sheet). + + Returns a tuple of three floats (Helix, Turn, Sheet). + """ + aa_percentages = self.amino_acids_percent + + helix = sum(aa_percentages[r] / 100 for r in "EMALK") + turn = sum(aa_percentages[r] / 100 for r in "NPGSD") + sheet = sum(aa_percentages[r] / 100 for r in "VIYFWLT") + + return helix, turn, sheet + + def molar_extinction_coefficient(self): + """Calculate the molar extinction coefficient. + + Calculates the molar extinction coefficient assuming cysteines + (reduced) and cystines residues (Cys-Cys-bond) + """ + num_aa = self.count_amino_acids() + mec_reduced = num_aa["W"] * 5500 + num_aa["Y"] * 1490 + mec_cystines = mec_reduced + (num_aa["C"] // 2) * 125 + return (mec_reduced, mec_cystines) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/ProtParamData.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/ProtParamData.py new file mode 100644 index 0000000000000000000000000000000000000000..59f9ce8354d8418ff96aec826a8e0ff5714e0df5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/ProtParamData.py @@ -0,0 +1,390 @@ +# Copyright 2003 Yair Benita. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Indices to be used with ProtParam.""" + +# Turn black code style off +# fmt: off + +# Hydrophobicity + +# Kyte & Doolittle index of hydrophobicity +# J. Mol. Biol. 157:105-132(1982). +# "KyteDoolittle" +kd = {"A": 1.8, "R": -4.5, "N": -3.5, "D": -3.5, "C": 2.5, + "Q": -3.5, "E": -3.5, "G": -0.4, "H": -3.2, "I": 4.5, + "L": 3.8, "K": -3.9, "M": 1.9, "F": 2.8, "P": -1.6, + "S": -0.8, "T": -0.7, "W": -0.9, "Y": -1.3, "V": 4.2} + +# Aboderin hydrophobicity index +# International J. of Biochemistry, 2(11), 537-544. +# "Aboderin" +ab = {"A": 5.1, "R": 2.0, "N": 0.6, "D": 0.7, "C": 0.0, + "Q": 1.4, "E": 1.8, "G": 4.1, "H": 1.6, "I": 9.3, + "L": 10.0, "K": 1.3, "M": 8.7, "F": 9.6, "P": 4.9, + "S": 3.1, "T": 3.5, "W": 9.2, "Y": 8.0, "V": 8.5} + +# Abraham & Leo hydrophobicity index +# Proteins: Structure, Function and Genetics 2:130-152(1987). +# "AbrahamLeo" +al = {"A": 0.44, "R": -2.42, "N": -1.32, "D": -0.31, "C": 0.58, + "Q": -0.71, "E": -0.34, "G": 0.0, "H": -0.01, "I": 2.46, + "L": 2.46, "K": -2.45, "M": 1.1, "F": 2.54, "P": 1.29, + "S": -0.84, "T": -0.41, "W": 2.56, "Y": 1.63, "V": 1.73} + +# Argos hydrophobicity index +# European Journal of Biochemistry, 128(2-3), 565-575. +# "Argos" +ag = {"A": 0.61, "R": 0.6, "N": 0.06, "D": 0.46, "C": 1.07, + "Q": 0.0, "E": 0.47, "G": 0.07, "H": 0.61, "I": 2.22, + "L": 1.53, "K": 1.15, "M": 1.18, "F": 2.02, "P": 1.95, + "S": 0.05, "T": 0.05, "W": 2.65, "Y": 1.88, "V": 1.32} + +# Black & Mould hydrophobicity index +# Anal. Biochem. 193:72-82(1991). +# "BlackMould" +bm = {"A": 0.616, "R": 0.0, "N": 0.236, "D": 0.028, "C": 0.68, + "Q": 0.251, "E": 0.043, "G": 0.501, "H": 0.165, "I": 0.943, + "L": 0.943, "K": 0.283, "M": 0.738, "F": 1.0, "P": 0.711, + "S": 0.359, "T": 0.45, "W": 0.878, "Y": 0.88, "V": 0.825} + +# Bull & Breese hydrophobicity index +# Arch. Biochem. Biophys. 161:665-670(1974) +# "BullBreese" +bb = {"A": 0.61, "R": 0.69, "N": 0.89, "D": 0.61, "C": 0.36, + "Q": 0.97, "E": 0.51, "G": 0.81, "H": 0.69, "I": -1.45, + "L": -1.65, "K": 0.46, "M": -0.66, "F": -1.52, "P": -0.17, + "S": 0.42, "T": 0.29, "W": -1.2, "Y": -1.43, "V": -0.75} + +# Casari & Sippl hydrophobic potential +# Journal of molecular biology, 224(3), 725-732. +# "Casari" +cs = {"A": 0.2, "R": -0.7, "N": -0.5, "D": -1.4, "C": 1.9, + "Q": -1.1, "E": -1.3, "G": -0.1, "H": 0.4, "I": 1.4, + "L": 0.5, "K": -1.6, "M": 0.5, "F": 1.0, "P": -1.0, + "S": -0.7, "T": -0.4, "W": 1.6, "Y": 0.5, "V": 0.7} + +# Cid hydrophobicity index +# Protein engineering, 5(5), 373-375. +# "Cid" +ci = {"A": 0.02, "R": -0.42, "N": -0.77, "D": -1.04, "C": 0.77, + "Q": -1.1, "E": -1.14, "G": -0.8, "H": 0.26, "I": 1.81, + "L": 1.14, "K": -0.41, "M": 1.0, "F": 1.35, "P": -0.09, + "S": -0.97, "T": -0.77, "W": 1.71, "Y": 1.11, "V": 1.13} + +# Cowan hydrophobicity indices at ph 3.4 and 7.5 +# Peptide Research 3:75-80(1990). +# "Cowan3.4" "Conwan7.5" +cw = {3.4 : {"A": 0.42, "R": -1.56, "N": -1.03, "D": -0.51, "C": 0.84, + "Q": -0.96, "E": -0.37, "G": 0.0, "H": -2.28, "I": 1.81, + "L": 1.8, "K": -2.03, "M": 1.18, "F": 1.74, "P": 0.86, + "S": -0.64, "T": -0.26, "W": 1.46, "Y": 0.51, "V": 1.34}, + 7.5 : {"A": 0.35, "R": -1.5, "N": -0.99, "D": -2.15, "C": 0.76, + "Q": -0.93, "E": -1.95, "G": 0.0, "H": -0.65, "I": 1.83, + "L": 1.8, "K": -1.54, "M": 1.1, "F": 1.69, "P": 0.84, + "S": -0.63, "T": -0.27, "W": 1.35, "Y": 0.39, "V": 1.32} + } + +# Eisenberg Normalized consensus hydrophobicity scale +# J. Mol. Biol. 179:125-142(1984) +# "Eisenberg" +es = {"A": 0.62, "R": -2.53, "N": -0.78, "D": -0.9, "C": 0.29, + "Q": -0.85, "E": -0.74, "G": 0.48, "H": -0.4, "I": 1.38, + "L": 1.06, "K": -1.5, "M": 0.64, "F": 1.19, "P": 0.12, + "S": -0.18, "T": -0.05, "W": 0.81, "Y": 0.26, "V": 1.08} + +# Engelman Hydrophobic Transfer Free Energies +# Annual review of biophysics and biophysical chemistry, 15(1), 321-353. +# "Engelman" +eg = {"A": -1.6, "R": 12.3, "N": 4.8, "D": 9.2, "C": -2, + "Q": 4.1, "E": 8.2, "G": -1, "H": 3, "I": -3.1, + "L": -2.8, "K": 8.8, "M": -3.4, "F": -3.7, "P": 0.2, + "S": -0.6, "T": -1.2, "W": -1.9, "Y": 0.7, "V": -2.6} + +# Fasman hydrophobicity index +# (1989). Prediction of protein structure and the principles of protein conformation. Springer. +# "Fasman" +fs = {"A": -0.21, "R": 2.11, "N": 0.96, "D": 1.36, "C": -6.04, + "Q": 1.52, "E": 2.3, "G": 0, "H": -1.23, "I": -4.81, + "L": -4.68, "K": 3.88, "M": -3.66, "F": -4.65, "P": 0.75, + "S": 1.74, "T": 0.78, "W": -3.32, "Y": -1.01, "V": -3.5} + +# Fauchere Hydrophobicity scale +# Eur. J. Med. Chem. 18:369-375(1983). +# "Fauchere" +fc = {"A": 0.31, "R": -1.01, "N": -0.6, "D": -0.77, "C": 1.54, + "Q": -0.22, "E": -0.64, "G": 0, "H": 0.13, "I": 1.8, + "L": 1.7, "K": -0.99, "M": 1.23, "F": 1.79, "P": 0.72, + "S": -0.04, "T": 0.26, "W": 2.25, "Y": 0.96, "V": 1.22} + +# Goldsack & Chalifoux Free Energy of Mixing of the Hydrophobic Side Chains +# Journal of theoretical biology, 39(3), 645-651. +# "Goldsack" +gd = {"A": 0.75, "R": 0.75, "N": 0.69, "D": 0, "C": 1, + "Q": 0.59, "E": 0, "G": 0, "H": 0, "I": 2.95, + "L": 2.4, "K": 1.5, "M": 1.3, "F": 2.65, "P": 2.6, + "S": 0, "T": 0.45, "W": 3, "Y": 2.85, "V": 1.7} + +# Guy Hydrophobicity scale based on free energy of transfer (kcal/mole). +# Biophys J. 47:61-70(1985) +# "Guy" +gy = {"A": 0.1, "R": 1.91, "N": 0.48, "D": 0.78, "C": -1.42, + "Q": 0.95, "E": 0.83, "G": 0.33, "H": -0.5, "I": -1.13, + "L": -1.18, "K": 1.4, "M": -1.59, "F": -2.12, "P": 0.73, + "S": 0.52, "T": 0.07, "W": -0.51, "Y": -0.21, "V": -1.27} + +# Jones Hydrophobicity scale +# Journal of theoretical biology, 50(1), 167-183. +# "Jones" +jo = {"A": 0.87, "R": 0.85, "N": 0.09, "D": 0.66, "C": 1.52, + "Q": 0, "E": 0.67, "G": 0.1, "H": 0.87, "I": 3.15, + "L": 2.17, "K": 1.64, "M": 1.67, "F": 2.87, "P": 2.77, + "S": 0.07, "T": 0.07, "W": 3.77, "Y": 2.67, "V": 1.87} + +# Juretic Hydrophobicity scale +# Theoretical and computational chemistry, 5, 405-445. +# "Juretic" +ju = {"A": 1.1, "R": -5.1, "N": -3.5, "D": -3.6, "C": 2.5, + "Q": -3.68, "E": -3.2, "G": -0.64, "H": -3.2, "I": 4.5, + "L": 3.8, "K": -4.11, "M": 1.9, "F": 2.8, "P": -1.9, + "S": -0.5, "T": -0.7, "W": -0.46, "Y": -1.3, "V": 4.2} + +# Kidera Hydrophobicity Factors +# Journal of Protein Chemistry, 4(1), 23-55. +# "Kidera" +ki = {"A": -0.27, "R": 1.87, "N": 0.81, "D": 0.81, "C": -1.05, + "Q": 1.1, "E": 1.17, "G": -0.16, "H": 0.28, "I": -0.77, + "L": -1.1, "K": 1.7, "M": -0.73, "F": -1.43, "P": -0.75, + "S": 0.42, "T": 0.63, "W": -1.57, "Y": -0.56, "V": -0.4} + +# Miyazawa Hydrophobicity scale (contact energy derived from 3D data) +# Macromolecules 18:534-552(1985) +# "Miyazawa" +mi = {"A": 5.33, "R": 4.18, "N": 3.71, "D": 3.59, "C": 7.93, + "Q": 3.87, "E": 3.65, "G": 4.48, "H": 5.1, "I": 8.83, + "L": 8.47, "K": 2.95, "M": 8.95, "F": 9.03, "P": 3.87, + "S": 4.09, "T": 4.49, "W": 7.66, "Y": 5.89, "V": 7.63} + +# Parker Hydrophilicity scale derived from HPLC peptide retention times +# Biochemistry 25:5425-5431(1986) +# "Parker" +pa = {"A": 2.1, "R": 4.2, "N": 7, "D": 10, "C": 1.4, + "Q": 6, "E": 7.8, "G": 5.7, "H": 2.1, "I": -8, + "L": -9.2, "K": 5.7, "M": -4.2, "F": -9.2, "P": 2.1, + "S": 6.5, "T": 5.2, "W": -10, "Y": -1.9, "V": -3.7} + +# Ponnuswamy Hydrophobic characteristics of folded proteins +# Progress in biophysics and molecular biology, 59(1), 57-103. +# "Ponnuswamy" +po = {"A": 0.85, "R": 0.2, "N": -0.48, "D": -1.1, "C": 2.1, + "Q": -0.42, "E": -0.79, "G": 0, "H": 0.22, "I": 3.14, + "L": 1.99, "K": -1.19, "M": 1.42, "F": 1.69, "P": -1.14, + "S": -0.52, "T": -0.08, "W": 1.76, "Y": 1.37, "V": 2.53} + +# Rose Hydrophobicity scale +# Science 229:834-838(1985) +# "Rose" +ro = {"A": 0.74, "R": 0.64, "N": 0.63, "D": 0.62, "C": 0.91, + "Q": 0.62, "E": 0.62, "G": 0.72, "H": 0.78, "I": 0.88, + "L": 0.85, "K": 0.52, "M": 0.85, "F": 0.88, "P": 0.64, + "S": 0.66, "T": 0.7, "W": 0.85, "Y": 0.76, "V": 0.86} + +# Roseman Hydrophobicity scale +# J. Mol. Biol. 200:513-522(1988) +# "Roseman" +rm = {"A": 0.39, "R": -3.95, "N": -1.91, "D": -3.81, "C": 0.25, + "Q": -1.3, "E": -2.91, "G": 0, "H": -0.64, "I": 1.82, + "L": 1.82, "K": -2.77, "M": 0.96, "F": 2.27, "P": 0.99, + "S": -1.24, "T": -1, "W": 2.13, "Y": 1.47, "V": 1.3} + +# Sweet Optimized Matchig Hydrophobicity (OMH) +# J. Mol. Biol. 171:479-488(1983). +# "Sweet +sw = {"A": -0.4, "R": -0.59, "N": -0.92, "D": -1.31, "C": 0.17, + "Q": -0.91, "E": -1.22, "G": -0.67, "H": -0.64, "I": 1.25, + "L": 1.22, "K": -0.67, "M": 1.02, "F": 1.92, "P": -0.49, + "S": -0.55, "T": -0.28, "W": 0.5, "Y": 1.67, "V": 0.91} + +# Tanford Hydrophobicity scale +# J. Am. Chem. Soc. 84:4240-4274(1962) +# "Tanford" +ta = {"A": 0.62, "R": -2.53, "N": -0.78, "D": -0.09, "C": 0.29, + "Q": -0.85, "E": -0.74, "G": 0.48, "H": -0.4, "I": 1.38, + "L": 1.53, "K": -1.5, "M": 0.64, "F": 1.19, "P": 0.12, + "S": -0.18, "T": -0.05, "W": 0.81, "Y": 0.26, "V": 1.8} + +# Wilson Hydrophobic constants derived from HPLC peptide retention times +# Biochem. J. 199:31-41(1981) +# "Wilson" +wi = {"A": -0.3, "R": -1.1, "N": -0.2, "D": -1.4, "C": 6.3, + "Q": -0.2, "E": 0, "G": 1.2, "H": -1.3, "I": 4.3, + "L": 6.6, "K": -3.6, "M": 2.5, "F": 7.5, "P": 2.2, + "S": -0.6, "T": -2.2, "W": 7.9, "Y": 7.1, "V": 5.9} + +# Zimmerman Hydrophobicity scale +# Journal of theoretical biology, 21(2), 170-201. +# "Zimmerman" +zi = {"A": 0.83, "R": 0.83, "N": 0.09, "D": 0.64, "C": 1.48, + "Q": 0, "E": 0.65, "G": 0.1, "H": 1.1, "I": 3.07, + "L": 2.52, "K": 1.6, "M": 1.4, "F": 2.75, "P": 2.7, + "S": 0.14, "T": 0.54, "W": 0.31, "Y": 2.97, "V": 1.79} + +gravy_scales = {"KyteDoolitle": kd, "Aboderin": ab, + "AbrahamLeo": al, "Argos": ag, + "BlackMould": bm, "BullBreese": bb, + "Casari": cs, "Cid": ci, + "Cowan3.4": cw[3.4], "Cowan7.5": cw[7.5], + "Eisenberg": es, "Engelman": eg, + "Fasman": fs, "Fauchere": fc, + "GoldSack": gd, "Guy": gy, + "Jones": jo, "Juretic": ju, + "Kidera": ki, "Miyazawa": mi, + "Parker": pa, "Ponnuswamy": po, + "Rose": ro, "Roseman": rm, + "Sweet": sw, "Tanford": ta, + "Wilson": wi, "Zimmerman": zi} + + +# Flexibility +# Normalized flexibility parameters (B-values), average +# Vihinen M., Torkkila E., Riikonen P. Proteins. 19(2):141-9(1994). +Flex = {"A": 0.984, "C": 0.906, "E": 1.094, "D": 1.068, + "G": 1.031, "F": 0.915, "I": 0.927, "H": 0.950, + "K": 1.102, "M": 0.952, "L": 0.935, "N": 1.048, + "Q": 1.037, "P": 1.049, "S": 1.046, "R": 1.008, + "T": 0.997, "W": 0.904, "V": 0.931, "Y": 0.929} + +# Hydrophilicity +# 1 Hopp & Wood +# Proc. Natl. Acad. Sci. U.S.A. 78:3824-3828(1981). +hw = {"A": -0.5, "R": 3.0, "N": 0.2, "D": 3.0, "C": -1.0, + "Q": 0.2, "E": 3.0, "G": 0.0, "H": -0.5, "I": -1.8, + "L": -1.8, "K": 3.0, "M": -1.3, "F": -2.5, "P": 0.0, + "S": 0.3, "T": -0.4, "W": -3.4, "Y": -2.3, "V": -1.5} + +# Surface accessibility +# Vergoten G & Theophanides T, Biomolecular Structure and Dynamics, +# pg.138 (1997). +# 1 Emini Surface fractional probability +em = {"A": 0.815, "R": 1.475, "N": 1.296, "D": 1.283, "C": 0.394, + "Q": 1.348, "E": 1.445, "G": 0.714, "H": 1.180, "I": 0.603, + "L": 0.603, "K": 1.545, "M": 0.714, "F": 0.695, "P": 1.236, + "S": 1.115, "T": 1.184, "W": 0.808, "Y": 1.089, "V": 0.606} + +# 2 Janin Interior to surface transfer energy scale +ja = {"A": 0.28, "R": -1.14, "N": -0.55, "D": -0.52, "C": 0.97, + "Q": -0.69, "E": -1.01, "G": 0.43, "H": -0.31, "I": 0.60, + "L": 0.60, "K": -1.62, "M": 0.43, "F": 0.46, "P": -0.42, + "S": -0.19, "T": -0.32, "W": 0.29, "Y": -0.15, "V": 0.60} + + +# A two dimensional dictionary for calculating the instability index. +# Guruprasad K., Reddy B.V.B., Pandit M.W. Protein Engineering 4:155-161(1990). +# It is based on dipeptide values; therefore, the value for the dipeptide DG +# is DIWV['D']['G']. +DIWV = {"A": {"A": 1.0, "C": 44.94, "E": 1.0, "D": -7.49, + "G": 1.0, "F": 1.0, "I": 1.0, "H": -7.49, + "K": 1.0, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 1.0, "P": 20.26, "S": 1.0, "R": 1.0, + "T": 1.0, "W": 1.0, "V": 1.0, "Y": 1.0}, + "C": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 20.26, + "G": 1.0, "F": 1.0, "I": 1.0, "H": 33.60, + "K": 1.0, "M": 33.60, "L": 20.26, "N": 1.0, + "Q": -6.54, "P": 20.26, "S": 1.0, "R": 1.0, + "T": 33.60, "W": 24.68, "V": -6.54, "Y": 1.0}, + "E": {"A": 1.0, "C": 44.94, "E": 33.60, "D": 20.26, + "G": 1.0, "F": 1.0, "I": 20.26, "H": -6.54, + "K": 1.0, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 20.26, "P": 20.26, "S": 20.26, "R": 1.0, + "T": 1.0, "W": -14.03, "V": 1.0, "Y": 1.0}, + "D": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 1.0, + "G": 1.0, "F": -6.54, "I": 1.0, "H": 1.0, + "K": -7.49, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 1.0, "P": 1.0, "S": 20.26, "R": -6.54, + "T": -14.03, "W": 1.0, "V": 1.0, "Y": 1.0}, + "G": {"A": -7.49, "C": 1.0, "E": -6.54, "D": 1.0, + "G": 13.34, "F": 1.0, "I": -7.49, "H": 1.0, + "K": -7.49, "M": 1.0, "L": 1.0, "N": -7.49, + "Q": 1.0, "P": 1.0, "S": 1.0, "R": 1.0, + "T": -7.49, "W": 13.34, "V": 1.0, "Y": -7.49}, + "F": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 13.34, + "G": 1.0, "F": 1.0, "I": 1.0, "H": 1.0, + "K": -14.03, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 1.0, "P": 20.26, "S": 1.0, "R": 1.0, + "T": 1.0, "W": 1.0, "V": 1.0, "Y": 33.601}, + "I": {"A": 1.0, "C": 1.0, "E": 44.94, "D": 1.0, + "G": 1.0, "F": 1.0, "I": 1.0, "H": 13.34, + "K": -7.49, "M": 1.0, "L": 20.26, "N": 1.0, + "Q": 1.0, "P": -1.88, "S": 1.0, "R": 1.0, + "T": 1.0, "W": 1.0, "V": -7.49, "Y": 1.0}, + "H": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 1.0, + "G": -9.37, "F": -9.37, "I": 44.94, "H": 1.0, + "K": 24.68, "M": 1.0, "L": 1.0, "N": 24.68, + "Q": 1.0, "P": -1.88, "S": 1.0, "R": 1.0, + "T": -6.54, "W": -1.88, "V": 1.0, "Y": 44.94}, + "K": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 1.0, + "G": -7.49, "F": 1.0, "I": -7.49, "H": 1.0, + "K": 1.0, "M": 33.60, "L": -7.49, "N": 1.0, + "Q": 24.64, "P": -6.54, "S": 1.0, "R": 33.60, + "T": 1.0, "W": 1.0, "V": -7.49, "Y": 1.0}, + "M": {"A": 13.34, "C": 1.0, "E": 1.0, "D": 1.0, + "G": 1.0, "F": 1.0, "I": 1.0, "H": 58.28, + "K": 1.0, "M": -1.88, "L": 1.0, "N": 1.0, + "Q": -6.54, "P": 44.94, "S": 44.94, "R": -6.54, + "T": -1.88, "W": 1.0, "V": 1.0, "Y": 24.68}, + "L": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 1.0, + "G": 1.0, "F": 1.0, "I": 1.0, "H": 1.0, + "K": -7.49, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 33.60, "P": 20.26, "S": 1.0, "R": 20.26, + "T": 1.0, "W": 24.68, "V": 1.0, "Y": 1.0}, + "N": {"A": 1.0, "C": -1.88, "E": 1.0, "D": 1.0, + "G": -14.03, "F": -14.03, "I": 44.94, "H": 1.0, + "K": 24.68, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": -6.54, "P": -1.88, "S": 1.0, "R": 1.0, + "T": -7.49, "W": -9.37, "V": 1.0, "Y": 1.0}, + "Q": {"A": 1.0, "C": -6.54, "E": 20.26, "D": 20.26, + "G": 1.0, "F": -6.54, "I": 1.0, "H": 1.0, + "K": 1.0, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 20.26, "P": 20.26, "S": 44.94, "R": 1.0, + "T": 1.0, "W": 1.0, "V": -6.54, "Y": -6.54}, + "P": {"A": 20.26, "C": -6.54, "E": 18.38, "D": -6.54, + "G": 1.0, "F": 20.26, "I": 1.0, "H": 1.0, + "K": 1.0, "M": -6.54, "L": 1.0, "N": 1.0, + "Q": 20.26, "P": 20.26, "S": 20.26, "R": -6.54, + "T": 1.0, "W": -1.88, "V": 20.26, "Y": 1.0}, + "S": {"A": 1.0, "C": 33.60, "E": 20.26, "D": 1.0, + "G": 1.0, "F": 1.0, "I": 1.0, "H": 1.0, + "K": 1.0, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 20.26, "P": 44.94, "S": 20.26, "R": 20.26, + "T": 1.0, "W": 1.0, "V": 1.0, "Y": 1.0}, + "R": {"A": 1.0, "C": 1.0, "E": 1.0, "D": 1.0, + "G": -7.49, "F": 1.0, "I": 1.0, "H": 20.26, + "K": 1.0, "M": 1.0, "L": 1.0, "N": 13.34, + "Q": 20.26, "P": 20.26, "S": 44.94, "R": 58.28, + "T": 1.0, "W": 58.28, "V": 1.0, "Y": -6.54}, + "T": {"A": 1.0, "C": 1.0, "E": 20.26, "D": 1.0, + "G": -7.49, "F": 13.34, "I": 1.0, "H": 1.0, + "K": 1.0, "M": 1.0, "L": 1.0, "N": -14.03, + "Q": -6.54, "P": 1.0, "S": 1.0, "R": 1.0, + "T": 1.0, "W": -14.03, "V": 1.0, "Y": 1.0}, + "W": {"A": -14.03, "C": 1.0, "E": 1.0, "D": 1.0, + "G": -9.37, "F": 1.0, "I": 1.0, "H": 24.68, + "K": 1.0, "M": 24.68, "L": 13.34, "N": 13.34, + "Q": 1.0, "P": 1.0, "S": 1.0, "R": 1.0, + "T": -14.03, "W": 1.0, "V": -7.49, "Y": 1.0}, + "V": {"A": 1.0, "C": 1.0, "E": 1.0, "D": -14.03, + "G": -7.49, "F": 1.0, "I": 1.0, "H": 1.0, + "K": -1.88, "M": 1.0, "L": 1.0, "N": 1.0, + "Q": 1.0, "P": 20.26, "S": 1.0, "R": 1.0, + "T": -7.49, "W": 1.0, "V": 1.0, "Y": -6.54}, + "Y": {"A": 24.68, "C": 1.0, "E": -6.54, "D": 24.68, + "G": -7.49, "F": 1.0, "I": 1.0, "H": 13.34, + "K": 1.0, "M": 44.94, "L": 1.0, "N": 1.0, + "Q": 1.0, "P": 13.34, "S": 1.0, "R": -15.91, + "T": -7.49, "W": -9.37, "V": 1.0, "Y": 13.34}, + } + +# Turn black code style on +# fmt: on diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..30425692616195fe12103cab217b39ddee3f88c1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/__init__.py @@ -0,0 +1,732 @@ +#!/usr/bin/env python +# Copyright 2002 by Thomas Sicheritz-Ponten and Cecilia Alsmark. +# Copyright 2003 Yair Benita. +# Revisions copyright 2014 by Markus Piotrowski. +# Revisions copyright 2014-2016 by Peter Cock. +# All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Miscellaneous functions for dealing with sequences.""" + +import re +from math import cos +from math import exp +from math import log +from math import pi +from math import sin + +from Bio.Data import IUPACData +from Bio.Data.CodonTable import standard_dna_table +from Bio.Seq import complement +from Bio.Seq import complement_rna +from Bio.Seq import Seq +from Bio.Seq import translate + +###################################### +# DNA +###################### +# { + +_gc_values = { + "G": 1.000, + "C": 1.000, + "A": 0.000, + "T": 0.000, + "U": 0.000, + "S": 1.000, # Strong interaction (3 H bonds) (G or C) + "W": 0.000, # Weak interaction (2 H bonds) (A or T) + "M": 0.500, # Amino (A or C) + "R": 0.500, # Purine (A or G) + "Y": 0.500, # Pyrimidine (T or C) + "K": 0.500, # Keto (G or T) + "V": 2 / 3, # Not T or U (A or C or G) + "B": 2 / 3, # Not A (C or G or T) + "H": 1 / 3, # Not G (A or C or T) + "D": 1 / 3, # Not C (A or G or T) + "X": 0.500, # Any nucleotide (A or C or G or T) + "N": 0.500, # Any nucleotide (A or C or G or T) +} + + +def gc_fraction(seq, ambiguous="remove"): + """Calculate G+C percentage in seq (float between 0 and 1). + + Copes with mixed case sequences. Ambiguous Nucleotides in this context are + those different from ATCGSWU (S is G or C, and W is A or T). + + If ambiguous equals "remove" (default), will only count GCS and will only + include ACTGSWU when calculating the sequence length. Equivalent to removing + all characters in the set BDHKMNRVXY before calculating the GC content, as + each of these ambiguous nucleotides can either be in (A,T) or in (C,G). + + If ambiguous equals "ignore", it will treat only unambiguous nucleotides (GCS) + as counting towards the GC percentage, but will include all ambiguous and + unambiguous nucleotides when calculating the sequence length. + + If ambiguous equals "weighted", will use a "mean" value when counting the + ambiguous characters, for example, G and C will be counted as 1, N and X will + be counted as 0.5, D will be counted as 0.33 etc. See Bio.SeqUtils._gc_values + for a full list. + + Will raise a ValueError for any other value of the ambiguous parameter. + + + >>> from Bio.SeqUtils import gc_fraction + >>> seq = "ACTG" + >>> print(f"GC content of {seq} : {gc_fraction(seq):.2f}") + GC content of ACTG : 0.50 + + Example with an RNA sequence: + + >>> seq = "GGAUCUUCGGAUCU" + >>> print(f"GC content of {seq} : {gc_fraction(seq):.2f}") + GC content of GGAUCUUCGGAUCU : 0.50 + + S and W are ambiguous for the purposes of calculating the GC content. + + >>> seq = "ACTGSSSS" + >>> gc = gc_fraction(seq, "remove") + >>> print(f"GC content of {seq} : {gc:.2f}") + GC content of ACTGSSSS : 0.75 + >>> gc = gc_fraction(seq, "ignore") + >>> print(f"GC content of {seq} : {gc:.2f}") + GC content of ACTGSSSS : 0.75 + >>> gc = gc_fraction(seq, "weighted") + >>> print(f"GC content with ambiguous counting: {gc:.2f}") + GC content with ambiguous counting: 0.75 + + Some examples with ambiguous nucleotides. + + >>> seq = "ACTGN" + >>> gc = gc_fraction(seq, "ignore") + >>> print(f"GC content of {seq} : {gc:.2f}") + GC content of ACTGN : 0.40 + >>> gc = gc_fraction(seq, "weighted") + >>> print(f"GC content with ambiguous counting: {gc:.2f}") + GC content with ambiguous counting: 0.50 + >>> gc = gc_fraction(seq, "remove") + >>> print(f"GC content with ambiguous removing: {gc:.2f}") + GC content with ambiguous removing: 0.50 + + Ambiguous nucleotides are also removed from the length of the sequence. + + >>> seq = "GDVV" + >>> gc = gc_fraction(seq, "ignore") + >>> print(f"GC content of {seq} : {gc:.2f}") + GC content of GDVV : 0.25 + >>> gc = gc_fraction(seq, "weighted") + >>> print(f"GC content with ambiguous counting: {gc:.4f}") + GC content with ambiguous counting: 0.6667 + >>> gc = gc_fraction(seq, "remove") + >>> print(f"GC content with ambiguous removing: {gc:.2f}") + GC content with ambiguous removing: 1.00 + + + Note that this will return zero for an empty sequence. + """ + if ambiguous not in ("weighted", "remove", "ignore"): + raise ValueError(f"ambiguous value '{ambiguous}' not recognized") + + gc = sum(seq.count(x) for x in "CGScgs") + + if ambiguous == "remove": + length = gc + sum(seq.count(x) for x in "ATWUatwu") + else: + length = len(seq) + + if ambiguous == "weighted": + gc += sum( + (seq.count(x) + seq.count(x.lower())) * _gc_values[x] for x in "BDHKMNRVXY" + ) + + if length == 0: + return 0 + + return gc / length + + +def GC123(seq): + """Calculate G+C content: total, for first, second and third positions. + + Returns a tuple of four floats (percentages between 0 and 100) for the + entire sequence, and the three codon positions. e.g. + + >>> from Bio.SeqUtils import GC123 + >>> GC123("ACTGTN") + (40.0, 50.0, 50.0, 0.0) + + Copes with mixed case sequences, but does NOT deal with ambiguous + nucleotides. + """ + d = {} + for nt in ["A", "T", "G", "C"]: + d[nt] = [0, 0, 0] + + for i in range(0, len(seq), 3): + codon = seq[i : i + 3] + if len(codon) < 3: + codon += " " + for pos in range(3): + for nt in ["A", "T", "G", "C"]: + if codon[pos] == nt or codon[pos] == nt.lower(): + d[nt][pos] += 1 + gc = {} + gcall = 0 + nall = 0 + for i in range(3): + try: + n = d["G"][i] + d["C"][i] + d["T"][i] + d["A"][i] + gc[i] = (d["G"][i] + d["C"][i]) * 100.0 / n + except Exception: # TODO - ValueError? + gc[i] = 0 + + gcall = gcall + d["G"][i] + d["C"][i] + nall = nall + n + + gcall = 100.0 * gcall / nall + return gcall, gc[0], gc[1], gc[2] + + +def GC_skew(seq, window=100): + """Calculate GC skew (G-C)/(G+C) for multiple windows along the sequence. + + Returns a list of ratios (floats), controlled by the length of the sequence + and the size of the window. + + Returns 0 for windows without any G/C by handling zero division errors. + + Does NOT look at any ambiguous nucleotides. + """ + # 8/19/03: Iddo: added lowercase + values = [] + for i in range(0, len(seq), window): + s = seq[i : i + window] + g = s.count("G") + s.count("g") + c = s.count("C") + s.count("c") + try: + skew = (g - c) / (g + c) + except ZeroDivisionError: + skew = 0.0 + values.append(skew) + return values + + +def xGC_skew(seq, window=1000, zoom=100, r=300, px=100, py=100): + """Calculate and plot normal and accumulated GC skew (GRAPHICS !!!).""" + import tkinter + + yscroll = tkinter.Scrollbar(orient=tkinter.VERTICAL) + xscroll = tkinter.Scrollbar(orient=tkinter.HORIZONTAL) + canvas = tkinter.Canvas( + yscrollcommand=yscroll.set, xscrollcommand=xscroll.set, background="white" + ) + win = canvas.winfo_toplevel() + win.geometry("700x700") + + yscroll.config(command=canvas.yview) + xscroll.config(command=canvas.xview) + yscroll.pack(side=tkinter.RIGHT, fill=tkinter.Y) + xscroll.pack(side=tkinter.BOTTOM, fill=tkinter.X) + canvas.pack(fill=tkinter.BOTH, side=tkinter.LEFT, expand=1) + canvas.update() + + X0, Y0 = r + px, r + py + x1, x2, y1, y2 = X0 - r, X0 + r, Y0 - r, Y0 + r + + ty = Y0 + canvas.create_text(X0, ty, text="%s...%s (%d nt)" % (seq[:7], seq[-7:], len(seq))) + ty += 20 + canvas.create_text(X0, ty, text=f"GC {gc_fraction(seq):3.2f}%") + ty += 20 + canvas.create_text(X0, ty, text="GC Skew", fill="blue") + ty += 20 + canvas.create_text(X0, ty, text="Accumulated GC Skew", fill="magenta") + ty += 20 + canvas.create_oval(x1, y1, x2, y2) + + acc = 0 + start = 0 + for gc in GC_skew(seq, window): + r1 = r + acc += gc + # GC skew + alpha = pi - (2 * pi * start) / len(seq) + r2 = r1 - gc * zoom + x1 = X0 + r1 * sin(alpha) + y1 = Y0 + r1 * cos(alpha) + x2 = X0 + r2 * sin(alpha) + y2 = Y0 + r2 * cos(alpha) + canvas.create_line(x1, y1, x2, y2, fill="blue") + # accumulated GC skew + r1 = r - 50 + r2 = r1 - acc + x1 = X0 + r1 * sin(alpha) + y1 = Y0 + r1 * cos(alpha) + x2 = X0 + r2 * sin(alpha) + y2 = Y0 + r2 * cos(alpha) + canvas.create_line(x1, y1, x2, y2, fill="magenta") + + canvas.update() + start += window + + canvas.configure(scrollregion=canvas.bbox(tkinter.ALL)) + + +def nt_search(seq, subseq): + """Search for a DNA subseq in seq, return list of [subseq, positions]. + + Use ambiguous values (like N = A or T or C or G, R = A or G etc.), + searches only on forward strand. + """ + pattern = "" + for nt in subseq: + value = IUPACData.ambiguous_dna_values[nt] + if len(value) == 1: + pattern += value + else: + pattern += f"[{value}]" + + pos = -1 + result = [pattern] + while True: + pos += 1 + s = seq[pos:] + m = re.search(pattern, s) + if not m: + break + pos += int(m.start(0)) + result.append(pos) + return result + + +###################################### +# Protein +###################### + + +def seq3(seq, custom_map=None, undef_code="Xaa"): + """Convert protein sequence from one-letter to three-letter code. + + The single required input argument 'seq' should be a protein sequence using + single letter codes, either as a Python string or as a Seq or MutableSeq + object. + + This function returns the amino acid sequence as a string using the three + letter amino acid codes. Output follows the IUPAC standard (including + ambiguous characters B for "Asx", J for "Xle" and X for "Xaa", and also U + for "Sel" and O for "Pyl") plus "Ter" for a terminator given as an + asterisk. Any unknown character (including possible gap characters), + is changed into 'Xaa' by default. + + e.g. + + >>> from Bio.SeqUtils import seq3 + >>> seq3("MAIVMGRWKGAR*") + 'MetAlaIleValMetGlyArgTrpLysGlyAlaArgTer' + + You can set a custom translation of the codon termination code using the + dictionary "custom_map" argument (which defaults to {'*': 'Ter'}), e.g. + + >>> seq3("MAIVMGRWKGAR*", custom_map={"*": "***"}) + 'MetAlaIleValMetGlyArgTrpLysGlyAlaArg***' + + You can also set a custom translation for non-amino acid characters, such + as '-', using the "undef_code" argument, e.g. + + >>> seq3("MAIVMGRWKGA--R*", undef_code='---') + 'MetAlaIleValMetGlyArgTrpLysGlyAla------ArgTer' + + If not given, "undef_code" defaults to "Xaa", e.g. + + >>> seq3("MAIVMGRWKGA--R*") + 'MetAlaIleValMetGlyArgTrpLysGlyAlaXaaXaaArgTer' + + This function was inspired by BioPerl's seq3. + """ + if custom_map is None: + custom_map = {"*": "Ter"} + # not doing .update() on IUPACData dict with custom_map dict + # to preserve its initial state (may be imported in other modules) + threecode = dict( + list(IUPACData.protein_letters_1to3_extended.items()) + list(custom_map.items()) + ) + # We use a default of 'Xaa' for undefined letters + # Note this will map '-' to 'Xaa' which may be undesirable! + return "".join(threecode.get(aa, undef_code) for aa in seq) + + +def seq1(seq, custom_map=None, undef_code="X"): + """Convert protein sequence from three-letter to one-letter code. + + The single required input argument 'seq' should be a protein sequence + using three-letter codes, either as a Python string or as a Seq or + MutableSeq object. + + This function returns the amino acid sequence as a string using the one + letter amino acid codes. Output follows the IUPAC standard (including + ambiguous characters "B" for "Asx", "J" for "Xle", "X" for "Xaa", "U" for + "Sel", and "O" for "Pyl") plus "*" for a terminator given the "Ter" code. + Any unknown character (including possible gap characters), is changed + into '-' by default. + + e.g. + + >>> from Bio.SeqUtils import seq1 + >>> seq1("MetAlaIleValMetGlyArgTrpLysGlyAlaArgTer") + 'MAIVMGRWKGAR*' + + The input is case insensitive, e.g. + + >>> from Bio.SeqUtils import seq1 + >>> seq1("METalaIlEValMetGLYArgtRplysGlyAlaARGTer") + 'MAIVMGRWKGAR*' + + You can set a custom translation of the codon termination code using the + dictionary "custom_map" argument (defaulting to {'Ter': '*'}), e.g. + + >>> seq1("MetAlaIleValMetGlyArgTrpLysGlyAla***", custom_map={"***": "*"}) + 'MAIVMGRWKGA*' + + You can also set a custom translation for non-amino acid characters, such + as '-', using the "undef_code" argument, e.g. + + >>> seq1("MetAlaIleValMetGlyArgTrpLysGlyAla------ArgTer", undef_code='?') + 'MAIVMGRWKGA??R*' + + If not given, "undef_code" defaults to "X", e.g. + + >>> seq1("MetAlaIleValMetGlyArgTrpLysGlyAla------ArgTer") + 'MAIVMGRWKGAXXR*' + + """ + if custom_map is None: + custom_map = {"Ter": "*"} + # reverse map of threecode + # upper() on all keys to enable caps-insensitive input seq handling + onecode = {k.upper(): v for k, v in IUPACData.protein_letters_3to1_extended.items()} + # add the given termination codon code and custom maps + onecode.update((k.upper(), v) for k, v in custom_map.items()) + seqlist = [seq[3 * i : 3 * (i + 1)] for i in range(len(seq) // 3)] + return "".join(onecode.get(aa.upper(), undef_code) for aa in seqlist) + + +###################################### +# Mixed ??? +###################### + + +def molecular_weight( + seq, seq_type="DNA", double_stranded=False, circular=False, monoisotopic=False +): + """Calculate the molecular mass of DNA, RNA or protein sequences as float. + + Only unambiguous letters are allowed. Nucleotide sequences are assumed to + have a 5' phosphate. + + Arguments: + - seq: string, Seq, or SeqRecord object. + - seq_type: The default is to assume DNA; override this with a string + "DNA", "RNA", or "protein". + - double_stranded: Calculate the mass for the double stranded molecule? + - circular: Is the molecule circular (has no ends)? + - monoisotopic: Use the monoisotopic mass tables? + + >>> print("%0.2f" % molecular_weight("AGC")) + 949.61 + >>> print("%0.2f" % molecular_weight(Seq("AGC"))) + 949.61 + + However, it is better to be explicit - for example with strings: + + >>> print("%0.2f" % molecular_weight("AGC", "DNA")) + 949.61 + >>> print("%0.2f" % molecular_weight("AGC", "RNA")) + 997.61 + >>> print("%0.2f" % molecular_weight("AGC", "protein")) + 249.29 + + """ + try: + seq = seq.seq + except AttributeError: # not a SeqRecord object + pass + seq = "".join(str(seq).split()).upper() # Do the minimum formatting + + if seq_type == "DNA": + if monoisotopic: + weight_table = IUPACData.monoisotopic_unambiguous_dna_weights + else: + weight_table = IUPACData.unambiguous_dna_weights + elif seq_type == "RNA": + if monoisotopic: + weight_table = IUPACData.monoisotopic_unambiguous_rna_weights + else: + weight_table = IUPACData.unambiguous_rna_weights + elif seq_type == "protein": + if monoisotopic: + weight_table = IUPACData.monoisotopic_protein_weights + else: + weight_table = IUPACData.protein_weights + else: + raise ValueError(f"Allowed seq_types are DNA, RNA or protein, not {seq_type!r}") + + if monoisotopic: + water = 18.010565 + else: + water = 18.0153 + + try: + weight = sum(weight_table[x] for x in seq) - (len(seq) - 1) * water + if circular: + weight -= water + except KeyError as e: + raise ValueError( + f"'{e}' is not a valid unambiguous letter for {seq_type}" + ) from None + + if double_stranded: + if seq_type == "protein": + raise ValueError("protein sequences cannot be double-stranded") + elif seq_type == "DNA": + seq = complement(seq) + elif seq_type == "RNA": + seq = complement_rna(seq) + weight += sum(weight_table[x] for x in seq) - (len(seq) - 1) * water + if circular: + weight -= water + + return weight + + +def six_frame_translations(seq, genetic_code=1): + """Return pretty string showing the 6 frame translations and GC content. + + Nice looking 6 frame translation with GC content - code from xbbtools + similar to DNA Striders six-frame translation + + >>> from Bio.SeqUtils import six_frame_translations + >>> print(six_frame_translations("AUGGCCAUUGUAAUGGGCCGCUGA")) + GC_Frame: a:5 t:0 g:8 c:5 + Sequence: auggccauug ... gggccgcuga, 24 nt, 54.17 %GC + + + 1/1 + G H C N G P L + W P L * W A A + M A I V M G R * + auggccauuguaaugggccgcuga 54 % + uaccgguaacauuacccggcgacu + A M T I P R Q + H G N Y H A A S + P W Q L P G S + + + + """ # noqa for pep8 W291 trailing whitespace + from Bio.Seq import reverse_complement + from Bio.Seq import reverse_complement_rna + + if "u" in seq.lower(): + anti = reverse_complement_rna(seq) + else: + anti = reverse_complement(seq) + comp = anti[::-1] + length = len(seq) + frames = {} + for i in range(3): + fragment_length = 3 * ((length - i) // 3) + frames[i + 1] = translate(seq[i : i + fragment_length], genetic_code) + frames[-(i + 1)] = translate(anti[i : i + fragment_length], genetic_code)[::-1] + + # create header + if length > 20: + short = f"{seq[:10]} ... {seq[-10:]}" + else: + short = seq + header = "GC_Frame:" + for nt in ["a", "t", "g", "c"]: + header += " %s:%d" % (nt, seq.count(nt.upper())) + + gc = 100 * gc_fraction(seq, ambiguous="ignore") + header += "\nSequence: %s, %d nt, %0.2f %%GC\n\n\n" % ( + short.lower(), + length, + gc, + ) + res = header + + for i in range(0, length, 60): + subseq = seq[i : i + 60] + csubseq = comp[i : i + 60] + p = i // 3 + res += "%d/%d\n" % (i + 1, i / 3 + 1) + res += " " + " ".join(frames[3][p : p + 20]) + "\n" + res += " " + " ".join(frames[2][p : p + 20]) + "\n" + res += " ".join(frames[1][p : p + 20]) + "\n" + # seq + res += subseq.lower() + "%5d %%\n" % int(gc) + res += csubseq.lower() + "\n" + # - frames + res += " ".join(frames[-2][p : p + 20]) + "\n" + res += " " + " ".join(frames[-1][p : p + 20]) + "\n" + res += " " + " ".join(frames[-3][p : p + 20]) + "\n\n" + return res + + +class CodonAdaptationIndex(dict): + """A codon adaptation index (CAI) implementation. + + Implements the codon adaptation index (CAI) described by Sharp and + Li (Nucleic Acids Res. 1987 Feb 11;15(3):1281-95). + """ + + def __init__(self, sequences, table=standard_dna_table): + """Generate a codon adaptiveness table from the coding DNA sequences. + + This calculates the relative adaptiveness of each codon (w_ij) as + defined by Sharp & Li (Nucleic Acids Research 15(3): 1281-1295 (1987)) + from the provided codon DNA sequences. + + Arguments: + - sequences: An iterable over DNA sequences, which may be plain + strings, Seq objects, MutableSeq objects, or SeqRecord + objects. + - table: A Bio.Data.CodonTable.CodonTable object defining the + genetic code. By default, the standard genetic code is + used. + """ + self._table = table + codons = {aminoacid: [] for aminoacid in table.protein_alphabet} + for codon, aminoacid in table.forward_table.items(): + codons[aminoacid].append(codon) + synonymous_codons = tuple(list(codons.values()) + [table.stop_codons]) + + # count codon occurrences in the sequences. + counts = {c1 + c2 + c3: 0 for c1 in "ACGT" for c2 in "ACGT" for c3 in "ACGT"} + self.update(counts) # just to ensure that the dictionary is sorted + + # iterate over sequence and count the codons + for sequence in sequences: + try: # SeqRecord + name = sequence.id + sequence = sequence.seq + except AttributeError: # str, Seq, or MutableSeq + name = None + sequence = sequence.upper() + for i in range(0, len(sequence), 3): + codon = sequence[i : i + 3] + try: + counts[codon] += 1 + except KeyError: + if name is None: + message = f"illegal codon '{codon}'" + else: + message = f"illegal codon '{codon}' in gene {name}" + raise ValueError(message) from None + + # Following the description in the original paper, we use a value + # of 0.5 for codons that do not appear in the reference sequences. + for codon, count in counts.items(): + if count == 0: + counts[codon] = 0.5 + + for codons in synonymous_codons: + denominator = max(counts[codon] for codon in codons) + for codon in codons: + self[codon] = counts[codon] / denominator + + def calculate(self, sequence): + """Calculate and return the CAI (float) for the provided DNA sequence.""" + cai_value, cai_length = 0, 0 + + try: + sequence = sequence.seq # SeqRecord + except AttributeError: + pass # str, Seq, or MutableSeq + sequence = sequence.upper() + + for i in range(0, len(sequence), 3): + codon = sequence[i : i + 3] + if codon in ["ATG", "TGG"]: + # Exclude these two codons as their index is always one. + continue + try: + cai_value += log(self[codon]) + except KeyError: + if codon in ["TGA", "TAA", "TAG"]: + # Stop codon, which is valid but may be missing from the index. + continue + raise TypeError(f"illegal codon in sequence: {codon}") from None + else: + cai_length += 1 + + return exp(cai_value / cai_length) + + def optimize(self, sequence, seq_type="DNA", strict=True): + """Return a new DNA sequence with preferred codons only. + + Uses the codon adaptiveness table defined by the CodonAdaptationIndex + object to generate DNA sequences with only preferred codons. + May be useful when designing DNA sequences for transgenic protein + expression or codon-optimized proteins like fluorophores. + + Arguments: + - sequence: DNA, RNA, or protein sequence to codon-optimize. + Supplied as a str, Seq, or SeqRecord object. + - seq_type: String specifying type of sequence provided. + Options are "DNA", "RNA", and "protein". Default is "DNA". + - strict: Determines whether an exception should be raised when + two codons are equally preferred for a given amino acid. + Returns: + Seq object with DNA encoding the same protein as the sequence argument, + but using only preferred codons as defined by the codon adaptation index. + If multiple codons are equally preferred, a warning is issued + and one codon is chosen for use in the optimized sequence. + """ + try: # If seq record is provided, convert to sequence + sequence = sequence.seq + except AttributeError: # not a SeqRecord object + pass + seq = sequence.upper() + # Make dict with amino acids referencing preferred codons + pref_codons = {} + for codon, aminoacid in self._table.forward_table.items(): + if self[codon] == 1.0: + if aminoacid in pref_codons: + msg = f"{pref_codons[aminoacid]} and {codon} are equally preferred." + if strict: + raise ValueError(msg) + pref_codons[aminoacid] = codon + for codon in self._table.stop_codons: + if self[codon] == 1.0: + pref_codons["*"] = codon + # Create amino acid sequence if DNA was provided + if seq_type == "DNA" or seq_type == "RNA": + aa_seq = translate(seq) + elif seq_type == "protein": + aa_seq = seq + else: + raise ValueError( + f"Allowed seq_types are DNA, RNA or protein, not {seq_type!r}" + ) + # Un-translate in loop using only preferred codons + try: + optimized = "".join(pref_codons[aa] for aa in aa_seq) + except KeyError as ex: + raise KeyError(f"Unrecognized amino acid: {ex}") from None + return Seq(optimized) + + def __str__(self): + lines = [] + for codon, value in self.items(): + line = f"{codon}\t{value:.3f}" + lines.append(line) + return "\n".join(lines) + "\n" + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/lcc.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/lcc.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4a0a51fe6cf1fca660a62498c42855bf761a2d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SeqUtils/lcc.py @@ -0,0 +1,152 @@ +# Copyright 2003, 2007 by Sebastian Bassi. sbassi@genesdigitales.com +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Local Composition Complexity.""" + +import math + + +def lcc_mult(seq, wsize): + """Calculate Local Composition Complexity (LCC) values over sliding window. + + Returns a list of floats, the LCC values for a sliding window over + the sequence. + + seq - an unambiguous DNA sequence (a string or Seq object) + wsize - window size, integer + + The result is the same as applying lcc_simp multiple times, but this + version is optimized for speed. The optimization works by using the + value of previous window as a base to compute the next one. + """ + l4 = math.log(4) + seq = seq.upper() + tamseq = len(seq) + compone = [0] + lccsal = [] + for i in range(wsize): + compone.append(((i + 1) / wsize) * math.log((i + 1) / wsize) / l4) + window = seq[0:wsize] + cant_a = window.count("A") + cant_c = window.count("C") + cant_t = window.count("T") + cant_g = window.count("G") + term_a = compone[cant_a] + term_c = compone[cant_c] + term_t = compone[cant_t] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + tail = seq[0] + for x in range(tamseq - wsize): + window = seq[x + 1 : wsize + x + 1] + if tail == window[-1]: + lccsal.append(lccsal[-1]) + elif tail == "A": + cant_a -= 1 + if window.endswith("C"): + cant_c += 1 + term_a = compone[cant_a] + term_c = compone[cant_c] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("T"): + cant_t += 1 + term_a = compone[cant_a] + term_t = compone[cant_t] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("G"): + cant_g += 1 + term_a = compone[cant_a] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif tail == "C": + cant_c -= 1 + if window.endswith("A"): + cant_a += 1 + term_a = compone[cant_a] + term_c = compone[cant_c] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("T"): + cant_t += 1 + term_c = compone[cant_c] + term_t = compone[cant_t] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("G"): + cant_g += 1 + term_c = compone[cant_c] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif tail == "T": + cant_t -= 1 + if window.endswith("A"): + cant_a += 1 + term_a = compone[cant_a] + term_t = compone[cant_t] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("C"): + cant_c += 1 + term_c = compone[cant_c] + term_t = compone[cant_t] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("G"): + cant_g += 1 + term_t = compone[cant_t] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif tail == "G": + cant_g -= 1 + if window.endswith("A"): + cant_a += 1 + term_a = compone[cant_a] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("C"): + cant_c += 1 + term_c = compone[cant_c] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + elif window.endswith("T"): + cant_t += 1 + term_t = compone[cant_t] + term_g = compone[cant_g] + lccsal.append(-(term_a + term_c + term_t + term_g)) + tail = window[0] + return lccsal + + +def lcc_simp(seq): + """Calculate Local Composition Complexity (LCC) for a sequence. + + seq - an unambiguous DNA sequence (a string or Seq object) + + Returns the Local Composition Complexity (LCC) value for the entire + sequence (as a float). + + Reference: + Andrzej K Konopka (2005) Sequence Complexity and Composition + https://doi.org/10.1038/npg.els.0005260 + """ + wsize = len(seq) + seq = seq.upper() + l4 = math.log(4) + # Check to avoid calculating the log of 0. + if "A" not in seq: + term_a = 0 + else: + term_a = (seq.count("A") / wsize) * math.log(seq.count("A") / wsize) / l4 + if "C" not in seq: + term_c = 0 + else: + term_c = (seq.count("C") / wsize) * math.log(seq.count("C") / wsize) / l4 + if "T" not in seq: + term_t = 0 + else: + term_t = (seq.count("T") / wsize) * math.log(seq.count("T") / wsize) / l4 + if "G" not in seq: + term_g = 0 + else: + term_g = (seq.count("G") / wsize) * math.log(seq.count("G") / wsize) / l4 + return -(term_a + term_c + term_t + term_g) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/._Ace.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/._Ace.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/._Ace.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/._Phd.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/._Phd.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/._Phd.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/Ace.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/Ace.py new file mode 100644 index 0000000000000000000000000000000000000000..19d03981f21abc1ce4653ea2404b12f7f8bec484 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/Ace.py @@ -0,0 +1,605 @@ +# Copyright 2004 by Frank Kauff and Cymon J. Cox. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Parser for ACE files output by PHRAP. + +Written by Frank Kauff (fkauff@duke.edu) and +Cymon J. Cox (cymon@duke.edu) + +Usage: + +There are two ways of reading an ace file: + +1. The function 'read' reads the whole file at once; +2. The function 'parse' reads the file contig after contig. + +First option, parse whole ace file at once:: + + from Bio.Sequencing import Ace + acefilerecord = Ace.read(open('my_ace_file.ace')) + +This gives you: + - acefilerecord.ncontigs (the number of contigs in the ace file) + - acefilerecord.nreads (the number of reads in the ace file) + - acefilerecord.contigs[] (one instance of the Contig class for each contig) + +The Contig class holds the info of the CO tag, CT and WA tags, and all the reads used +for this contig in a list of instances of the Read class, e.g.:: + + contig3 = acefilerecord.contigs[2] + read4 = contig3.reads[3] + RD_of_read4 = read4.rd + DS_of_read4 = read4.ds + +CT, WA, RT tags from the end of the file can appear anywhere are automatically +sorted into the right place. + +see _RecordConsumer for details. + +The second option is to iterate over the contigs of an ace file one by one +in the usual way:: + + from Bio.Sequencing import Ace + contigs = Ace.parse(open('my_ace_file.ace')) + for contig in contigs: + print(contig.name) + ... + +Please note that for memory efficiency, when using the iterator approach, only one +contig is kept in memory at once. However, there can be a footer to the ACE file +containing WA, CT, RT or WR tags which contain additional meta-data on the contigs. +Because the parser doesn't see this data until the final record, it cannot be added to +the appropriate records. Instead these tags will be returned with the last contig record. +Thus an ace file does not entirerly suit the concept of iterating. If WA, CT, RT, WR tags +are needed, the 'read' function rather than the 'parse' function might be more appropriate. +""" + + +class rd: + """RD (reads), store a read with its name, sequence etc. + + The location and strand each read is mapped to is held in the AF lines. + """ + + def __init__(self): + """Initialize the class.""" + self.name = "" + self.padded_bases = None + self.info_items = None + self.read_tags = None + self.sequence = "" + + +class qa: + """QA (read quality), including which part if any was used as the consensus.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.qual_clipping_start = None + self.qual_clipping_end = None + self.align_clipping_start = None + self.align_clipping_end = None + if line: + header = line.split() + self.qual_clipping_start = int(header[1]) + self.qual_clipping_end = int(header[2]) + self.align_clipping_start = int(header[3]) + self.align_clipping_end = int(header[4]) + + +class ds: + """DS lines, include file name of a read's chromatogram file.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.chromat_file = "" + self.phd_file = "" + self.time = "" + self.chem = "" + self.dye = "" + self.template = "" + self.direction = "" + if line: + tags = [ + "CHROMAT_FILE", + "PHD_FILE", + "TIME", + "CHEM", + "DYE", + "TEMPLATE", + "DIRECTION", + ] + poss = [line.find(x) for x in tags] + tagpos = dict(zip(poss, tags)) + if -1 in tagpos: + del tagpos[-1] + ps = sorted(tagpos) # the keys + for p1, p2 in zip(ps, ps[1:] + [len(line) + 1]): + setattr( + self, + tagpos[p1].lower(), + line[p1 + len(tagpos[p1]) + 1 : p2].strip(), + ) + + +class af: + """AF lines, define the location of the read within the contig. + + Note attribute coru is short for complemented (C) or uncomplemented (U), + since the strand information is stored in an ACE file using either the + C or U character. + """ + + def __init__(self, line=None): + """Initialize the class.""" + self.name = "" + self.coru = None + self.padded_start = None + if line: + header = line.split() + self.name = header[1] + self.coru = header[2] + self.padded_start = int(header[3]) + + +class bs: + """BS (base segment), which read was chosen as the consensus at each position.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.name = "" + self.padded_start = None + self.padded_end = None + if line: + header = line.split() + self.padded_start = int(header[1]) + self.padded_end = int(header[2]) + self.name = header[3] + + +class rt: + """RT (transient read tags), generated by crossmatch and phrap.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.name = "" + self.tag_type = "" + self.program = "" + self.padded_start = None + self.padded_end = None + self.date = "" + self.comment = [] + if line: + header = line.split() + self.name = header[0] + self.tag_type = header[1] + self.program = header[2] + self.padded_start = int(header[3]) + self.padded_end = int(header[4]) + self.date = header[5] + + +class ct: + """CT (consensus tags).""" + + def __init__(self, line=None): + """Initialize the class.""" + self.name = "" + self.tag_type = "" + self.program = "" + self.padded_start = None + self.padded_end = None + self.date = "" + self.notrans = "" + self.info = [] + self.comment = [] + if line: + header = line.split() + self.name = header[0] + self.tag_type = header[1] + self.program = header[2] + self.padded_start = int(header[3]) + self.padded_end = int(header[4]) + self.date = header[5] + if len(header) == 7: + self.notrans = header[6] + + +class wa: + """WA (whole assembly tag), holds the assembly program name, version, etc.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.tag_type = "" + self.program = "" + self.date = "" + self.info = [] + if line: + header = line.split() + self.tag_type = header[0] + self.program = header[1] + self.date = header[2] + + +class wr: + """WR lines.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.name = "" + self.aligned = "" + self.program = "" + self.date = [] + if line: + header = line.split() + self.name = header[0] + self.aligned = header[1] + self.program = header[2] + self.date = header[3] + + +class Reads: + """Holds information about a read supporting an ACE contig.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.rd = None # one per read + self.qa = None # one per read + self.ds = None # none or one per read + self.rt = None # none or many per read + self.wr = None # none or many per read + if line: + self.rd = rd() + header = line.split() + self.rd.name = header[1] + self.rd.padded_bases = int(header[2]) + self.rd.info_items = int(header[3]) + self.rd.read_tags = int(header[4]) + + +class Contig: + """Holds information about a contig from an ACE record.""" + + def __init__(self, line=None): + """Initialize the class.""" + self.name = "" + self.nbases = None + self.nreads = None + self.nsegments = None + self.uorc = None + self.sequence = "" + self.quality = [] + self.af = [] + self.bs = [] + self.reads = [] + self.ct = None # none or many + self.wa = None # none or many + if line: + header = line.split() + self.name = header[1] + self.nbases = int(header[2]) + self.nreads = int(header[3]) + self.nsegments = int(header[4]) + self.uorc = header[5] + + +def _parse(stream): + """Iterate of ACE file contig by contig by reading from a file-like object. + + Argument stream is a file-like object. + + This is a private function for internal purposes only. The public function + ``parse`` (without a leading underscore) takes care of opening the file, + calling ``_parse`` to read from it, and closing the file if appropriate. + """ + + line = "" + while True: + # at beginning, skip the AS and look for first CO command + try: + while True: + if line.startswith("CO"): + break + line = next(stream) + except StopIteration: + return + + record = Contig(line) + + for line in stream: + line = line.strip() + if not line: + break + record.sequence += line + + for line in stream: + if line.strip(): + break + if not line.startswith("BQ"): + raise ValueError("Failed to find BQ line") + + for line in stream: + if not line.strip(): + break + record.quality.extend(int(x) for x in line.split()) + + for line in stream: + if line.strip(): + break + + while True: + if not line.startswith("AF "): + break + record.af.append(af(line)) + try: + line = next(stream) + except StopIteration: + raise ValueError("Unexpected end of AF block") from None + + while True: + if line.strip(): + break + try: + line = next(stream) + except StopIteration: + raise ValueError("Unexpected end of file") from None + + while True: + if not line.startswith("BS "): + break + record.bs.append(bs(line)) + try: + line = next(stream) + except StopIteration: + raise ValueError("Failed to find end of BS block") from None + + # now read all the read data + # it starts with a 'RD', and then a mandatory QA + # then follows an optional DS + # CT,RT,WA,WR may or may not be there in unlimited quantity. + # They might refer to the actual read or contig, or, if + # encountered at the end of file, to any previous read or contig. + # The sort() method deals with that later. + while True: + # each read must have a rd and qa + try: + while True: + # If I've met the condition, then stop reading the line. + if line.startswith("RD "): + break + line = next(stream) + except StopIteration: + raise ValueError("Failed to find RD line") from None + + record.reads.append(Reads(line)) + + for line in stream: + line = line.strip() + if not line: + break + record.reads[-1].rd.sequence += line + + for line in stream: + if line.strip(): + break + if not line.startswith("QA "): + raise ValueError("Failed to find QA line") + record.reads[-1].qa = qa(line) + + # now one ds can follow + for line in stream: + if line.strip(): + break + else: + break + + if line.startswith("DS "): + record.reads[-1].ds = ds(line) + line = "" + # the file could just end, or there's some more stuff. + # In ace files, anything can happen. + # the following tags are interspersed between reads and can appear multiple times. + while True: + # something left + try: + while True: + if line.strip(): + break + line = next(stream) + except StopIteration: + # file ends here + break + if line.startswith("RT{"): + # now if we're at the end of the file, this rt could + # belong to a previous read, not the actual one. + # we store it here were it appears, the user can sort later. + if record.reads[-1].rt is None: + record.reads[-1].rt = [] + for line in stream: + line = line.strip() + # if line=="COMMENT{": + if line.startswith("COMMENT{"): + if line[8:].strip(): + # MIRA 3.0.5 would miss the new line out :( + record.reads[-1].rt[-1].comment.append(line[8:]) + for line in stream: + line = line.strip() + if line.endswith("C}"): + break + record.reads[-1].rt[-1].comment.append(line) + elif line == "}": + break + else: + record.reads[-1].rt.append(rt(line)) + line = "" + elif line.startswith("WR{"): + if record.reads[-1].wr is None: + record.reads[-1].wr = [] + for line in stream: + line = line.strip() + if line == "}": + break + record.reads[-1].wr.append(wr(line)) + line = "" + elif line.startswith("WA{"): + if record.wa is None: + record.wa = [] + try: + line = next(stream) + except StopIteration: + raise ValueError("Failed to read WA block") from None + record.wa.append(wa(line)) + for line in stream: + line = line.strip() + if line == "}": + break + record.wa[-1].info.append(line) + line = "" + elif line.startswith("CT{"): + if record.ct is None: + record.ct = [] + try: + line = next(stream) + except StopIteration: + raise ValueError("Failed to read CT block") from None + record.ct.append(ct(line)) + for line in stream: + line = line.strip() + if line == "COMMENT{": + for line in stream: + line = line.strip() + if line.endswith("C}"): + break + record.ct[-1].comment.append(line) + elif line == "}": + break + else: + record.ct[-1].info.append(line) + line = "" + else: + break + + if not line.startswith("RD"): # another read? + break + + yield record + + +def parse(source): + """Iterate of ACE file contig by contig. + + Argument source is a file-like object or a path to a file. + + This function returns an iterator that allows you to iterate + over the ACE file record by record:: + + records = parse(source) + for record in records: + # do something with the record + + where each record is a Contig object. + """ + try: + handle = open(source) + except TypeError: + handle = source + if handle.read(0) != "": + raise ValueError("Ace files must be opened in text mode.") from None + + try: + yield from _parse(handle) + finally: + if handle is not source: + handle.close() + + +class ACEFileRecord: + """Holds data of an ACE file.""" + + def __init__(self): + """Initialize the class.""" + self.ncontigs = None + self.nreads = None + self.contigs = [] + self.wa = None # none or many + + def sort(self): + """Sorts wr, rt and ct tags into the appropriate contig / read instance, if possible.""" + ct = [] + rt = [] + wr = [] + # search for tags that aren't in the right position + for i, c in enumerate(self.contigs): + if c.wa: + if not self.wa: + self.wa = [] + self.wa.extend(c.wa) + if c.ct: + newcts = [ct_tag for ct_tag in c.ct if ct_tag.name != c.name] + for x in newcts: + self.contigs[i].ct.remove(x) + ct.extend(newcts) + for j, r in enumerate(c.reads): + if r.rt: + newrts = [rt_tag for rt_tag in r.rt if rt_tag.name != r.rd.name] + for x in newrts: + self.contigs[i].reads[j].rt.remove(x) + rt.extend(newrts) + if r.wr: + newwrs = [wr_tag for wr_tag in r.wr if wr_tag.name != r.rd.name] + for x in newwrs: + self.contigs[i].reads[j].wr.remove(x) + wr.extend(newwrs) + # now sort them into their proper place + for i, c in enumerate(self.contigs): + for ct_tag in ct: + if ct_tag.name == c.name: + if self.contigs[i].ct is None: + self.contigs[i].ct = [] + self.contigs[i].ct.append(ct_tag) + if rt or wr: + for j, r in enumerate(c.reads): + for rt_tag in rt: + if rt_tag.name == r.rd.name: + if self.contigs[i].reads[j].rt is None: + self.contigs[i].reads[j].rt = [] + self.contigs[i].reads[j].rt.append(rt_tag) + for wr_tag in wr: + if wr_tag.name == r.rd.name: + if self.contigs[i].reads[j].wr is None: + self.contigs[i].reads[j].wr = [] + self.contigs[i].reads[j].wr.append(wr_tag) + + +def read(handle): + """Parse a full ACE file into a list of contigs.""" + handle = iter(handle) + + record = ACEFileRecord() + + try: + line = next(handle) + except StopIteration: + raise ValueError("Premature end of file") from None + + # check if the file starts correctly + if not line.startswith("AS"): + raise ValueError("File does not start with 'AS'.") + + words = line.split() + record.ncontigs = int(words[1]) + record.nreads = int(words[2]) + + # now read all the records + record.contigs = list(parse(handle)) + # wa, ct, rt rags are usually at the end of the file, but not necessarily (correct?). + # If the iterator is used, the tags are returned with the contig or the read after which they appear, + # if all tags are at the end, they are read with the last contig. The concept of an + # iterator leaves no other choice. But if the user uses the ACEParser, we can check + # them and put them into the appropriate contig/read instance. + # Conclusion: An ACE file is not a filetype for which iteration is 100% suitable... + record.sort() + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/Phd.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/Phd.py new file mode 100644 index 0000000000000000000000000000000000000000..d78e60ae6d8c486c095fdba32714746d3b218b61 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/Phd.py @@ -0,0 +1,204 @@ +# Copyright 2004 by Cymon J. Cox and Frank Kauff. All rights reserved. +# Copyright 2008 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2009 by Cymon J. Cox. All rights reserved. +# Revisions copyright 2009 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Parser for PHD files output by PHRED and used by PHRAP and CONSED. + +This module can be used directly, which will return Record objects +containing all the original data in the file. + +Alternatively, using Bio.SeqIO with the "phd" format will call this module +internally. This will give SeqRecord objects for each contig sequence. +""" + +from Bio import Seq + +CKEYWORDS = [ + "CHROMAT_FILE", + "ABI_THUMBPRINT", + "PHRED_VERSION", + "CALL_METHOD", + "QUALITY_LEVELS", + "TIME", + "TRACE_ARRAY_MIN_INDEX", + "TRACE_ARRAY_MAX_INDEX", + "TRIM", + "TRACE_PEAK_AREA_RATIO", + "CHEM", + "DYE", +] + + +class Record: + """Hold information from a PHD file.""" + + def __init__(self): + """Initialize the class.""" + self.file_name = "" + self.comments = {} + for kw in CKEYWORDS: + self.comments[kw.lower()] = None + self.sites = [] + self.seq = "" + self.seq_trimmed = "" + + +def read(source): + """Read one PHD record from the file and return it as a Record object. + + Argument source is a file-like object opened in text mode, or a path + to a file. + + This function reads PHD file data line by line from the source, and + returns a single Record object. A ValueError is raised if more than + one record is found in the file. + """ + handle = _open(source) + try: + record = _read(handle) + try: + next(handle) + except StopIteration: + return record + else: + raise ValueError("More than one PHD record found") + finally: + if handle is not source: + handle.close() + + +def parse(source): + """Iterate over a file yielding multiple PHD records. + + Argument source is a file-like object opened in text mode, or a path + to a file. + + The data is read line by line from the source. + + Typical usage:: + + records = parse(handle) + for record in records: + # do something with the record object + + """ + handle = _open(source) + try: + while True: + record = _read(handle) + if not record: + return + yield record + finally: + if handle is not source: + handle.close() + + +# Everything below is considered private + + +def _open(source): + try: + handle = open(source) + except TypeError: + handle = source + if handle.read(0) != "": + raise ValueError("PHD files must be opened in text mode.") from None + return handle + + +def _read(handle): + for line in handle: + if line.startswith("BEGIN_SEQUENCE"): + record = Record() + record.file_name = line[15:].rstrip() + break + else: + return # No record found + + for line in handle: + if line.startswith("BEGIN_COMMENT"): + break + else: + raise ValueError("Failed to find BEGIN_COMMENT line") + + for line in handle: + line = line.strip() + if not line: + continue + if line == "END_COMMENT": + break + keyword, value = line.split(":", 1) + keyword = keyword.lower() + value = value.strip() + if keyword in ( + "chromat_file", + "phred_version", + "call_method", + "chem", + "dye", + "time", + "basecaller_version", + "trace_processor_version", + ): + record.comments[keyword] = value + elif keyword in ( + "abi_thumbprint", + "quality_levels", + "trace_array_min_index", + "trace_array_max_index", + ): + record.comments[keyword] = int(value) + elif keyword == "trace_peak_area_ratio": + record.comments[keyword] = float(value) + elif keyword == "trim": + first, last, prob = value.split() + record.comments[keyword] = (int(first), int(last), float(prob)) + else: + raise ValueError("Failed to find END_COMMENT line") + + for line in handle: + if line.startswith("BEGIN_DNA"): + break + else: + raise ValueError("Failed to find BEGIN_DNA line") + + for line in handle: + if line.startswith("END_DNA"): + break + else: + # Line is: "site quality peak_location" + # Peak location is optional according to + # David Gordon (the Consed author) + parts = line.split() + if len(parts) in [2, 3]: + record.sites.append(tuple(parts)) + else: + raise ValueError( + "DNA line must contain a base and quality " + "score, and optionally a peak location." + ) + + for line in handle: + if line.startswith("END_SEQUENCE"): + break + else: + raise ValueError("Failed to find END_SEQUENCE line") + + record.seq = Seq.Seq("".join(n[0] for n in record.sites)) + if record.comments["trim"] is not None: + first, last = record.comments["trim"][:2] + record.seq_trimmed = record.seq[first:last] + + return record + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..927b866b3724739e4ba402a4816b7238196dd19b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Sequencing/__init__.py @@ -0,0 +1,12 @@ +# Copyright 2004 Frank Kauff. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code to deal with various programs for sequencing and assembly. + +This code deals with programs such as Phred, Phrap and Consed -- which provide +utilities for calling bases from sequencing reads, and assembling sequences +into contigs. +""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/._KeyWList.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/._KeyWList.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/._KeyWList.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/KeyWList.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/KeyWList.py new file mode 100644 index 0000000000000000000000000000000000000000..381741c25ca5dd932305846b875553eba8cd28cc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/KeyWList.py @@ -0,0 +1,90 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code to parse the keywlist.txt file from SwissProt/UniProt. + +See: + - https://www.uniprot.org/docs/keywlist.txt + +Classes: + - Record Stores the information about one keyword or one category + in the keywlist.txt file. + +Functions: + - parse Parses the keywlist.txt file and returns an iterator to + the records it contains. + +""" + + +class Record(dict): + """Store information of one keyword or category from the keywords list. + + This record stores the information of one keyword or category in the + keywlist.txt as a Python dictionary. The keys in this dictionary are + the line codes that can appear in the keywlist.txt file:: + + --------- --------------------------- ---------------------- + Line code Content Occurrence in an entry + --------- --------------------------- ---------------------- + ID Identifier (keyword) Once; starts a keyword entry + IC Identifier (category) Once; starts a category entry + AC Accession (KW-xxxx) Once + DE Definition Once or more + SY Synonyms Optional; once or more + GO Gene ontology (GO) mapping Optional; once or more + HI Hierarchy Optional; once or more + WW Relevant WWW site Optional; once or more + CA Category Once per keyword entry; absent + in category entries + + """ + + def __init__(self): + """Initialize the class.""" + dict.__init__(self) + for keyword in ("DE", "SY", "GO", "HI", "WW"): + self[keyword] = [] + + +def parse(handle): + """Parse the keyword list from file handle. + + Returns a generator object which yields keyword entries as + Bio.SwissProt.KeyWList.Record() object. + """ + record = Record() + # First, skip the header - look for start of a record + for line in handle: + if line.startswith("ID "): + # Looks like there was no header + record["ID"] = line[5:].strip() + break + if line.startswith("IC "): + # Looks like there was no header + record["IC"] = line[5:].strip() + break + # Now parse the records + for line in handle: + if line.startswith("-------------------------------------"): + # We have reached the footer + break + key = line[:2] + if key == "//": + record["DE"] = " ".join(record["DE"]) + record["SY"] = " ".join(record["SY"]) + yield record + record = Record() + elif line[2:5] == " ": + value = line[5:].strip() + if key in ("ID", "IC", "AC", "CA"): + record[key] = value + elif key in ("DE", "SY", "GO", "HI", "WW"): + record[key].append(value) + else: + raise ValueError(f"Cannot parse line '{line.strip()}'") + # Read the footer and throw it away + for line in handle: + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7700e7e119d55b1bdc0fb4fc05b978babaf0e35 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/SwissProt/__init__.py @@ -0,0 +1,849 @@ +# Copyright 2007 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Code to work with the sprotXX.dat file from SwissProt. + +https://web.expasy.org/docs/userman.html + +Classes: + - Record Holds SwissProt data. + - Reference Holds reference data from a SwissProt record. + +Functions: + - read Read one SwissProt record + - parse Read multiple SwissProt records + +""" + +import io +import re + +from Bio.SeqFeature import Position +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation + + +class SwissProtParserError(ValueError): + """An error occurred while parsing a SwissProt file.""" + + def __init__(self, *args, line=None): + """Create a SwissProtParserError object with the offending line.""" + super().__init__(*args) + self.line = line + + +class Record: + """Holds information from a SwissProt record. + + Attributes: + - entry_name Name of this entry, e.g. RL1_ECOLI. + - data_class Either 'STANDARD' or 'PRELIMINARY'. + - molecule_type Type of molecule, 'PRT', + - sequence_length Number of residues. + - accessions List of the accession numbers, e.g. ['P00321'] + - created A tuple of (date, release). + - sequence_update A tuple of (date, release). + - annotation_update A tuple of (date, release). + - description Free-format description. + - gene_name A list of dictionaries with keys 'Name', 'Synonyms', + 'OrderedLocusNames' and 'ORFNames'. + - organism The source of the sequence. + - organelle The origin of the sequence. + - organism_classification The taxonomy classification. List of strings. + (http://www.ncbi.nlm.nih.gov/Taxonomy/) + - taxonomy_id A list of NCBI taxonomy id's. + - host_organism A list of names of the hosts of a virus, if any. + - host_taxonomy_id A list of NCBI taxonomy id's of the hosts, if any. + - references List of Reference objects. + - comments List of strings. + - cross_references List of tuples (db, id1[, id2][, id3]). See the docs. + - keywords List of the keywords. + - features List of tuples (key name, from, to, description). + from and to can be either integers for the residue + numbers, '<', '>', or '?' + - protein_existence Numerical value describing the evidence for the existence of the protein. + - seqinfo tuple of (length, molecular weight, CRC32 value) + - sequence The sequence. + + Examples + -------- + >>> from Bio import SwissProt + >>> example_filename = "SwissProt/P68308.txt" + >>> with open(example_filename) as handle: + ... records = SwissProt.parse(handle) + ... for record in records: + ... print(record.entry_name) + ... print(record.accessions) + ... print(record.keywords) + ... print(record.organism) + ... print(record.sequence[:20] + "...") + ... + NU3M_BALPH + ['P68308', 'P24973'] + ['Electron transport', 'Membrane', 'Mitochondrion', 'Mitochondrion inner membrane', 'NAD', 'Respiratory chain', 'Translocase', 'Transmembrane', 'Transmembrane helix', 'Transport', 'Ubiquinone'] + Balaenoptera physalus (Fin whale) (Balaena physalus). + MNLLLTLLTNTTLALLLVFI... + + """ + + def __init__(self): + """Initialize the class.""" + self.entry_name = None + self.data_class = None + self.molecule_type = None + self.sequence_length = None + + self.accessions = [] + self.created = None + self.sequence_update = None + self.annotation_update = None + + self.description = [] + self.gene_name = [] + self.organism = [] + self.organelle = "" + self.organism_classification = [] + self.taxonomy_id = [] + self.host_organism = [] + self.host_taxonomy_id = [] + self.references = [] + self.comments = [] + self.cross_references = [] + self.keywords = [] + self.features = [] + self.protein_existence = "" + + self.seqinfo = None + self.sequence = "" + + +class Reference: + """Holds information from one reference in a SwissProt entry. + + Attributes: + - number Number of reference in an entry. + - evidence Evidence code. List of strings. + - positions Describes extent of work. List of strings. + - comments Comments. List of (token, text). + - references References. List of (dbname, identifier). + - authors The authors of the work. + - title Title of the work. + - location A citation for the work. + + """ + + def __init__(self): + """Initialize the class.""" + self.number = None + self.positions = [] + self.comments = [] + self.references = [] + self.authors = [] + self.title = [] + self.location = [] + + +class FeatureTable(SeqFeature): + """Stores feature annotations for specific regions of the sequence. + + This is a subclass of SeqFeature, defined in Bio.SeqFeature, where the + attributes are used as follows: + + - ``location``: location of the feature on the canonical or isoform + sequence; the location is stored as an instance of SimpleLocation, + defined in Bio.SeqFeature, with the ref attribute set to the isoform + ID referring to the canonical or isoform sequence on which the feature + is defined + - ``id``: unique and stable identifier (FTId), only provided for features + belonging to the types CARBOHYD, CHAIN, PEPTIDE, PROPEP, VARIANT, or + VAR_SEQ + - ``type``: indicates the type of feature, as defined by the UniProt + Knowledgebase documentation: + + - ACT_SITE: amino acid(s) involved in the activity of an enzyme + - BINDING: binding site for any chemical group + - CARBOHYD: glycosylation site; an FTId identifier to the GlyConnect + database is provided if annotated there + - CA_BIND: calcium-binding region + - CHAIN: polypeptide chain in the mature protein + - COILED: coiled-coil region + - COMPBIAS: compositionally biased region + - CONFLICT: different sources report differing sequences + - CROSSLNK: posttransationally formed amino acid bond + - DISULFID: disulfide bond + - DNA_BIND: DNA-binding region + - DOMAIN: domain, defined as a specific combination of secondary + structures organized into a characteristic three-dimensional + structure or fold + - INIT_MET: initiator methionine + - INTRAMEM: region located in a membrane without crossing it + - HELIX: alpha-, 3(10)-, or pi-helix secondary structure + - LIPID: covalent binding of a lipid moiety + - METAL: binding site for a metal ion + - MOD_RES: posttranslational modification (PTM) of a residue, + annotated by the controlled vocabulary defined by the ptmlist.txt + document on the UniProt website + - MOTIF: short sequence motif of biological interest + - MUTAGEN: site experimentally altered by mutagenesis + - NON_CONS: non-consecutive residues + - NON_STD: non-standard amino acid + - NON_TER: the residue at an extremity of the sequence is not the + terminal residue + - NP_BIND: nucleotide phosphate-binding region + - PEPTIDE: released active mature polypeptide + - PROPEP: any processed propeptide + - REGION: region of interest in the sequence + - REPEAT: internal sequence repetition + - SIGNAL: signal sequence (prepeptide) + - SITE: amino-acid site of interest not represented by another + feature key + - STRAND: beta-strand secondary structure; either a hydrogen-bonded + extended beta strand or a residue in an isolated beta-bridge + - TOPO_DOM: topological domain + - TRANSIT: transit peptide (mitochondrion, chloroplast, thylakoid, + cyanelle, peroxisome, etc.) + - TRANSMEM: transmembrane region + - TURN: H-bonded turn (3-, 4-, or 5-turn) + - UNSURE: uncertainties in the sequence + - VARIANT: sequence variant; an FTId is provided for protein sequence + variants of Hominidae (great apes and humans) + - VAR_SEQ: sequence variant produced by alternative splicing, + alternative promoter usage, alternative initiation, or ribosomal + frameshifting + - ZN_FING: zinc finger region + + - ``qualifiers``: a dictionary of additional information, which may include + the feature evidence and free-text notes. While SwissProt includes the + feature identifier code (FTId) as a qualifier, it is stored as the + attribute ID of the FeatureTable object. + + """ + + +def parse(source): + """Read multiple SwissProt records from file. + + Argument source is a file-like object or a path to a file. + + Returns a generator object which yields Bio.SwissProt.Record() objects. + """ + handle = _open(source) + try: + while True: + record = _read(handle) + if not record: + return + yield record + finally: + if handle is not source: + handle.close() + + +def read(source): + """Read one SwissProt record from file. + + Argument source is a file-like object or a path to a file. + + Returns a Record() object. + """ + handle = _open(source) + try: + record = _read(handle) + if not record: + raise ValueError("No SwissProt record found") + # We should have reached the end of the record by now. + # Try to read one more line to be sure: + try: + next(handle) + except StopIteration: + return record + raise ValueError("More than one SwissProt record found") + finally: + if handle is not source: + handle.close() + + +# Everything below is considered private + + +def _open(source): + try: + handle = open(source) + return handle + except TypeError: + handle = source + if handle.read(0) == "": + # handle is text; assume the encoding is compatible with ASCII + return handle + # handle is binary; SwissProt encoding is always ASCII + return io.TextIOWrapper(handle, encoding="ASCII") + + +def _read(handle): + record = None + unread = "" + try: + line = next(handle) + except StopIteration: + return record + key, value = line[:2], line[5:].rstrip() + if key != "ID": + raise SwissProtParserError("Failed to find ID in first line", line=line) + record = Record() + _read_id(record, line) + _sequence_lines = [] + for line in handle: + key, value = line[:2], line[5:].rstrip() + if unread: + value = unread + " " + value + unread = "" + if key == "AC": + accessions = value.rstrip(";").split("; ") + record.accessions.extend(accessions) + elif key == "DT": + _read_dt(record, line) + elif key == "DE": + record.description.append(value.strip()) + elif key == "GN": + if value == "and": + record.gene_name.append("") + else: + if len(record.gene_name) == 0: + record.gene_name.append("") + record.gene_name[-1] += value + " " + elif key == "OS": + record.organism.append(value) + elif key == "OG": + record.organelle += line[5:] + elif key == "OC": + cols = value.rstrip(";.").split("; ") + record.organism_classification.extend(cols) + elif key == "OX": + _read_ox(record, line) + elif key == "OH": + _read_oh(record, line) + elif key == "RN": + reference = Reference() + _read_rn(reference, value) + record.references.append(reference) + elif key == "RP": + assert record.references, "RP: missing RN" + record.references[-1].positions.append(value) + elif key == "RC": + assert record.references, "RC: missing RN" + reference = record.references[-1] + unread = _read_rc(reference, value) + elif key == "RX": + assert record.references, "RX: missing RN" + reference = record.references[-1] + _read_rx(reference, value) + elif key == "RL": + assert record.references, "RL: missing RN" + reference = record.references[-1] + reference.location.append(value) + # In UniProt release 1.12 of 6/21/04, there is a new RG + # (Reference Group) line, which references a group instead of + # an author. Each block must have at least 1 RA or RG line. + elif key == "RA": + assert record.references, "RA: missing RN" + reference = record.references[-1] + reference.authors.append(value) + elif key == "RG": + assert record.references, "RG: missing RN" + reference = record.references[-1] + reference.authors.append(value) + elif key == "RT": + assert record.references, "RT: missing RN" + reference = record.references[-1] + reference.title.append(value) + elif key == "CC": + _read_cc(record, line) + elif key == "DR": + _read_dr(record, value) + elif key == "PE": + _read_pe(record, value) + elif key == "KW": + _read_kw(record, value) + elif key == "FT": + _read_ft(record, line) + elif key == "SQ": + cols = value.split() + assert len(cols) == 7, f"I don't understand SQ line {line}" + # Do more checking here? + record.seqinfo = int(cols[1]), int(cols[3]), cols[5] + elif key == " ": + _sequence_lines.append(value.replace(" ", "").rstrip()) + elif key == "//": + _read_gn(record) + # Join multiline data into one string + record.description = " ".join(record.description) + record.organism = " ".join(record.organism) + record.organelle = record.organelle.rstrip() + for reference in record.references: + reference.authors = " ".join(reference.authors).rstrip(";") + if reference.title: + title = reference.title[0] + for fragment in reference.title[1:]: + if not title.endswith("-"): + title += " " + title += fragment + title = title.rstrip(";") + if title.startswith('"') and title.endswith('"'): + title = title[1:-1] # remove quotes + else: + title = "" + reference.title = title + reference.location = " ".join(reference.location) + record.sequence = "".join(_sequence_lines) + return record + elif key == "**": + # Do this one last, as it will almost never occur. + # See Bug 2353, some files from the EBI have extra lines + # starting "**" (two asterisks/stars). They appear + # to be unofficial automated annotations. e.g. + # ** + # ** ################# INTERNAL SECTION ################## + # **HA SAM; Annotated by PicoHamap 1.88; MF_01138.1; 09-NOV-2003. + pass + else: + raise SwissProtParserError(f"Unknown keyword {key!r} found", line=line) + if record: + raise ValueError("Unexpected end of stream.") + + +def _read_gn(record): + for i, text in enumerate(record.gene_name): + tokens = text.rstrip("; ").split("; ") + gene_name = {} + for token in tokens: + # value may include an equals sign, e.g. + # GN Name=Lacc1=POX4 {ECO:0000313|EMBL:KDQ27217.1}; + key, value = token.strip().split("=", 1) + if key == "Name": + gene_name["Name"] = value + else: + assert key in ("Synonyms", "OrderedLocusNames", "ORFNames") + gene_name[key] = value.split(", ") + record.gene_name[i] = gene_name + + +def _read_id(record, line): + cols = line[5:].split() + # Prior to release 51, included with MoleculeType: + # ID EntryName DataClass; MoleculeType; SequenceLength AA. + # + # Newer files lack the MoleculeType: + # ID EntryName DataClass; SequenceLength AA. + if len(cols) == 5: + record.entry_name = cols[0] + record.data_class = cols[1].rstrip(";") + record.molecule_type = cols[2].rstrip(";") + record.sequence_length = int(cols[3]) + elif len(cols) == 4: + record.entry_name = cols[0] + record.data_class = cols[1].rstrip(";") + record.molecule_type = None + record.sequence_length = int(cols[2]) + else: + raise SwissProtParserError("ID line has unrecognised format", line=line) + # check if the data class is one of the allowed values + allowed = ("STANDARD", "PRELIMINARY", "IPI", "Reviewed", "Unreviewed") + if record.data_class not in allowed: + message = f"Unrecognized data class {record.data_class!r}" + raise SwissProtParserError(message, line=line) + + # molecule_type should be 'PRT' for PRoTein + # Note that has been removed in recent releases (set to None) + if record.molecule_type not in (None, "PRT"): + message = f"Unrecognized molecule type {record.molecule_type!r}" + raise SwissProtParserError(message, line=line) + + +def _read_dt(record, line): + value = line[5:] + uprline = value.upper() + cols = value.rstrip().split() + if ( + "CREATED" in uprline + or "LAST SEQUENCE UPDATE" in uprline + or "LAST ANNOTATION UPDATE" in uprline + ): + # Old style DT line + # ================= + # e.g. + # DT 01-FEB-1995 (Rel. 31, Created) + # DT 01-FEB-1995 (Rel. 31, Last sequence update) + # DT 01-OCT-2000 (Rel. 40, Last annotation update) + # + # or: + # DT 08-JAN-2002 (IPI Human rel. 2.3, Created) + # ... + + # find where the version information will be located + # This is needed for when you have cases like IPI where + # the release version is in a different spot: + # DT 08-JAN-2002 (IPI Human rel. 2.3, Created) + uprcols = uprline.split() + rel_index = -1 + for index in range(len(uprcols)): + if "REL." in uprcols[index]: + rel_index = index + assert rel_index >= 0, f"Could not find Rel. in DT line: {line}" + version_index = rel_index + 1 + # get the version information + str_version = cols[version_index].rstrip(",") + # no version number + if str_version == "": + version = 0 + # dot versioned + elif "." in str_version: + version = str_version + # integer versioned + else: + version = int(str_version) + date = cols[0] + + if "CREATED" in uprline: + record.created = date, version + elif "LAST SEQUENCE UPDATE" in uprline: + record.sequence_update = date, version + elif "LAST ANNOTATION UPDATE" in uprline: + record.annotation_update = date, version + else: + raise SwissProtParserError("Unrecognised DT (DaTe) line", line=line) + elif ( + "INTEGRATED INTO" in uprline + or "SEQUENCE VERSION" in uprline + or "ENTRY VERSION" in uprline + ): + # New style DT line + # ================= + # As of UniProt Knowledgebase release 7.0 (including + # Swiss-Prot release 49.0 and TrEMBL release 32.0) the + # format of the DT lines and the version information + # in them was changed - the release number was dropped. + # + # For more information see bug 1948 and + # http://ca.expasy.org/sprot/relnotes/sp_news.html#rel7.0 + # + # e.g. + # DT 01-JAN-1998, integrated into UniProtKB/Swiss-Prot. + # DT 15-OCT-2001, sequence version 3. + # DT 01-APR-2004, entry version 14. + # + # This is a new style DT line... + + # The date should be in string cols[1] + # Get the version number if there is one. + # For the three DT lines above: 0, 3, 14 + try: + version = 0 + for s in cols[-1].split("."): + if s.isdigit(): + version = int(s) + except ValueError: + version = 0 + date = cols[0].rstrip(",") + + # Reuse the historical property names, even though + # the meaning has changed slightly: + if "INTEGRATED" in uprline: + record.created = date, version + elif "SEQUENCE VERSION" in uprline: + record.sequence_update = date, version + elif "ENTRY VERSION" in uprline: + record.annotation_update = date, version + else: + raise SwissProtParserError("Unrecognised DT (DaTe) line", line=line) + else: + raise SwissProtParserError("Failed to parse DT (DaTe) line", line=line) + + +def _read_ox(record, line): + # The OX line used to be in the simple format: + # OX DESCRIPTION=ID[, ID]...; + # If there are too many id's to fit onto a line, then the ID's + # continue directly onto the next line, e.g. + # OX DESCRIPTION=ID[, ID]... + # OX ID[, ID]...; + # Currently, the description is always "NCBI_TaxID". + # To parse this, I need to check to see whether I'm at the + # first line. If I am, grab the description and make sure + # it's an NCBI ID. Then, grab all the id's. + # + # As of the 2014-10-01 release, there may be an evidence code, e.g. + # OX NCBI_TaxID=418404 {ECO:0000313|EMBL:AEX14553.1}; + # In the short term, we will ignore any evidence codes: + line = line.split("{")[0] + if record.taxonomy_id: + ids = line[5:].rstrip().rstrip(";") + else: + descr, ids = line[5:].rstrip().rstrip(";").split("=") + assert descr == "NCBI_TaxID", f"Unexpected taxonomy type {descr}" + record.taxonomy_id.extend(ids.split(", ")) + + +def _read_oh(record, line): + # Line type OH (Organism Host) for viral hosts + assert line[5:].startswith("NCBI_TaxID="), f"Unexpected {line}" + line = line[16:].rstrip() + assert line[-1] == "." and line.count(";") == 1, line + taxid, name = line[:-1].split(";") + record.host_taxonomy_id.append(taxid.strip()) + record.host_organism.append(name.strip()) + + +def _read_rn(reference, rn): + # This used to be a very simple line with a reference number, e.g. + # RN [1] + # As of the 2014-10-01 release, there may be an evidence code, e.g. + # RN [1] {ECO:0000313|EMBL:AEX14553.1} + words = rn.split(None, 1) + number = words[0] + assert number.startswith("[") and number.endswith("]"), f"Missing brackets {number}" + reference.number = int(number[1:-1]) + if len(words) > 1: + evidence = words[1] + assert evidence.startswith("{") and evidence.endswith( + "}" + ), f"Missing braces {evidence}" + reference.evidence = evidence[1:-1].split("|") + + +def _read_rc(reference, value): + cols = value.split(";") + if value[-1] == ";": + unread = "" + else: + cols, unread = cols[:-1], cols[-1] + for col in cols: + if not col: # last column will be the empty string + return + # The token is everything before the first '=' character. + i = col.find("=") + if i >= 0: + token, text = col[:i], col[i + 1 :] + comment = token.lstrip(), text + reference.comments.append(comment) + else: + comment = reference.comments[-1] + comment = f"{comment} {col}" + reference.comments[-1] = comment + return unread + + +def _read_rx(reference, value): + # The basic (older?) RX line is of the form: + # RX MEDLINE; 85132727. + # but there are variants of this that need to be dealt with (see below) + + # CLD1_HUMAN in Release 39 and DADR_DIDMA in Release 33 + # have extraneous information in the RX line. Check for + # this and chop it out of the line. + # (noticed by katel@worldpath.net) + value = value.replace(" [NCBI, ExPASy, Israel, Japan]", "") + + # RX lines can also be used of the form + # RX PubMed=9603189; + # reported by edvard@farmasi.uit.no + # and these can be more complicated like: + # RX MEDLINE=95385798; PubMed=7656980; + # RX PubMed=15060122; DOI=10.1136/jmg 2003.012781; + # We look for these cases first and deal with them + warn = False + if "=" in value: + cols = value.split("; ") + cols = [x.strip() for x in cols] + cols = [x for x in cols if x] + for col in cols: + x = col.split("=") + if len(x) != 2 or x == ("DOI", "DOI"): + warn = True + break + assert len(x) == 2, f"I don't understand RX line {value}" + reference.references.append((x[0], x[1].rstrip(";"))) + # otherwise we assume we have the type 'RX MEDLINE; 85132727.' + else: + cols = value.split("; ") + # normally we split into the three parts + if len(cols) != 2: + warn = True + else: + reference.references.append((cols[0].rstrip(";"), cols[1].rstrip("."))) + if warn: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn(f"Possibly corrupt RX line {value!r}", BiopythonParserWarning) + + +def _read_cc(record, line): + key, value = line[5:8], line[9:].rstrip() + if key == "-!-": # Make a new comment + record.comments.append(value) + elif key == " ": # add to the previous comment + if not record.comments: + # TCMO_STRGA in Release 37 has comment with no topic + record.comments.append(value) + else: + record.comments[-1] += " " + value + + +def _read_dr(record, value): + cols = value.rstrip(".").split("; ") + record.cross_references.append(tuple(cols)) + + +def _read_pe(record, value): + pe = value.split(":") + record.protein_existence = int(pe[0]) + + +def _read_kw(record, value): + # Old style - semi-colon separated, multi-line. e.g. Q13639.txt + # KW Alternative splicing; Cell membrane; Complete proteome; + # KW Disulfide bond; Endosome; G-protein coupled receptor; Glycoprotein; + # KW Lipoprotein; Membrane; Palmitate; Polymorphism; Receptor; Transducer; + # KW Transmembrane. + # + # New style as of 2014-10-01 release with evidence codes, e.g. H2CNN8.txt + # KW Monooxygenase {ECO:0000313|EMBL:AEX14553.1}; + # KW Oxidoreductase {ECO:0000313|EMBL:AEX14553.1}. + # For now to match the XML parser, drop the evidence codes. + for val in value.rstrip(";.").split("; "): + if val.endswith("}"): + # Discard the evidence code + val = val.rsplit("{", 1)[0] + record.keywords.append(val.strip()) + + +def _read_ft(record, line): + name = line[5:13].rstrip() + if name: + if line[13:21] == " ": # new-style FT line + location = line[21:80].rstrip() + try: + isoform_id, location = location.split(":") + except ValueError: + isoform_id = None + try: + from_res, to_res = location.split("..") + except ValueError: + from_res = location + to_res = "" + qualifiers = {} + else: # old-style FT line + from_res = line[14:20].lstrip() + to_res = line[21:27].lstrip() + isoform_id = None + description = line[34:75].rstrip() + qualifiers = {"description": description} + from_res = Position.fromstring(from_res, -1) + if to_res == "": + to_res = from_res + 1 + else: + to_res = Position.fromstring(to_res) + location = SimpleLocation(from_res, to_res, ref=isoform_id) + feature = FeatureTable( + location=location, type=name, id=None, qualifiers=qualifiers + ) + record.features.append(feature) + return + # this line is a continuation of the previous feature + feature = record.features[-1] + if line[5:34] == " ": # old-style FT line + description = line[34:75].rstrip() + if description.startswith("/FTId="): + # store the FTId as the feature ID + feature.id = description[6:].rstrip(".") + return + # this line is a continuation of the description of the previous feature + old_description = feature.qualifiers["description"] + if old_description.endswith("-"): + description = f"{old_description}{description}" + else: + description = f"{old_description} {description}" + + if feature.type in ("VARSPLIC", "VAR_SEQ"): # special case + # Remove unwanted spaces in sequences. + # During line carryover, the sequences in VARSPLIC/VAR_SEQ can get + # mangled with unwanted spaces like: + # 'DISSTKLQALPSHGLESIQT -> PCRATGWSPFRRSSPC LPTH' + # We want to check for this case and correct it as it happens. + try: + first_seq, second_seq = description.split(" -> ") + except ValueError: + pass + else: + extra_info = "" + # we might have more information at the end of the + # second sequence, which should be in parenthesis + extra_info_pos = second_seq.find(" (") + if extra_info_pos != -1: + extra_info = second_seq[extra_info_pos:] + second_seq = second_seq[:extra_info_pos] + # now clean spaces out of the first and second string + first_seq = first_seq.replace(" ", "") + second_seq = second_seq.replace(" ", "") + # reassemble the description + description = first_seq + " -> " + second_seq + extra_info + feature.qualifiers["description"] = description + else: # new-style FT line + value = line[21:].rstrip() + match = re.match(r"^/([a-z_]+)=", value) + if match: + qualifier_type = match.group(1) + value = value[len(match.group(0)) :] + if not value.startswith('"'): + raise ValueError("Missing starting quote in feature") + if qualifier_type == "id": + if not value.endswith('"'): + raise ValueError("Missing closing quote for id") + feature.id = value[1:-1] + else: + if value.endswith('"'): + value = value[1:-1] + else: # continues on the next line + value = value[1:] + if qualifier_type in feature.qualifiers: + raise ValueError( + f"Feature qualifier {qualifier_type!r} already exists for feature" + ) + feature.qualifiers[qualifier_type] = value + return + # this line is a continuation of the description of the previous feature + keys = list(feature.qualifiers.keys()) + key = keys[-1] + description = value.rstrip('"') + old_description = feature.qualifiers[key] + if key == "evidence" or old_description.endswith("-"): + description = f"{old_description}{description}" + else: + description = f"{old_description} {description}" + if feature.type == "VAR_SEQ": # see VARSPLIC above + try: + first_seq, second_seq = description.split(" -> ") + except ValueError: + pass + else: + extra_info = "" + # we might have more information at the end of the + # second sequence, which should be in parenthesis + extra_info_pos = second_seq.find(" (") + if extra_info_pos != -1: + extra_info = second_seq[extra_info_pos:] + second_seq = second_seq[:extra_info_pos] + # now clean spaces out of the first and second string + first_seq = first_seq.replace(" ", "") + second_seq = second_seq.replace(" ", "") + # reassemble the description + description = first_seq + " -> " + second_seq + extra_info + feature.qualifiers[key] = description + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2669d8c5f92125f095560d3d2f8c1d2c13317a0c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/TogoWS/__init__.py @@ -0,0 +1,374 @@ +# Copyright 2010-2011, 2013-2014, 2016-2018 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Provides code to access the TogoWS integrated websevices of DBCLS, Japan. + +This module aims to make the TogoWS (from DBCLS, Japan) easier to use. See: +http://togows.dbcls.jp/ + +The TogoWS REST service provides simple access to a range of databases, acting +as a proxy to shield you from all the different provider APIs. This works using +simple URLs (which this module will construct for you). For more details, see +http://togows.dbcls.jp/site/en/rest.html + +The functionality is somewhat similar to Biopython's Bio.Entrez module which +provides access to the NCBI's Entrez Utilities (E-Utils) which also covers a +wide range of databases. + +Currently TogoWS does not provide any usage guidelines (unlike the NCBI whose +requirements are reasonably clear). To avoid risking overloading the service, +Biopython will only allow three calls per second. + +The TogoWS SOAP service offers a more complex API for calling web services +(essentially calling remote functions) provided by DDBJ, KEGG and PDBj. For +example, this allows you to run a remote BLAST search at the DDBJ. This is +not yet covered by this module, however there are lots of Python examples +on the TogoWS website using the SOAPpy python library. See: +http://togows.dbcls.jp/site/en/soap.html +http://soapy.sourceforge.net/ +""" + +import io +import time +from urllib.parse import quote +from urllib.request import urlopen + +from Bio._utils import function_with_previous + +# Constant +_BASE_URL = "http://togows.dbcls.jp" + +# Caches: +_search_db_names = None +_entry_db_names = None +_entry_db_fields: dict[str, str] = {} +_entry_db_formats: dict[str, str] = {} +_convert_formats: list[str] = [] + + +def _get_fields(url): + """Query a TogoWS URL for a plain text list of values (PRIVATE).""" + handle = _open(url) + fields = handle.read().strip().split() + handle.close() + return fields + + +def _get_entry_dbs(): + return _get_fields(_BASE_URL + "/entry") + + +def _get_entry_fields(db): + return _get_fields(_BASE_URL + f"/entry/{db}?fields") + + +def _get_entry_formats(db): + return _get_fields(_BASE_URL + f"/entry/{db}?formats") + + +def _get_convert_formats(): + return [pair.split(".") for pair in _get_fields(_BASE_URL + "/convert/")] + + +def entry(db, id, format=None, field=None): + """Call TogoWS 'entry' to fetch a record. + + Arguments: + - db - database (string), see list below. + - id - identifier (string) or a list of identifiers (either as a list of + strings or a single string with comma separators). + - format - return data file format (string), options depend on the database + e.g. "xml", "json", "gff", "fasta", "ttl" (RDF Turtle) + - field - specific field from within the database record (string) + e.g. "au" or "authors" for pubmed. + + At the time of writing, this includes the following:: + + KEGG: compound, drug, enzyme, genes, glycan, orthology, reaction, + module, pathway + DDBj: ddbj, dad, pdb + NCBI: nuccore, nucest, nucgss, nucleotide, protein, gene, onim, + homologue, snp, mesh, pubmed + EBI: embl, uniprot, uniparc, uniref100, uniref90, uniref50 + + For the current list, please see http://togows.dbcls.jp/entry/ + + This function is essentially equivalent to the NCBI Entrez service + EFetch, available in Biopython as Bio.Entrez.efetch(...), but that + does not offer field extraction. + """ + global _entry_db_names + if _entry_db_names is None: + _entry_db_names = _get_entry_dbs() + if db not in _entry_db_names: + raise ValueError( + f"TogoWS entry fetch does not officially support database '{db}'." + ) + if field: + try: + fields = _entry_db_fields[db] + except KeyError: + fields = _get_entry_fields(db) + _entry_db_fields[db] = fields + if db == "pubmed" and field == "ti" and "title" in fields: + # Backwards compatibility fix for TogoWS change Nov/Dec 2013 + field = "title" + import warnings + + warnings.warn( + "TogoWS dropped 'pubmed' field alias 'ti', please use 'title' instead." + ) + if field not in fields: + raise ValueError( + "TogoWS entry fetch does not explicitly support " + "field '%s' for database '%s'. Only: %s" + % (field, db, ", ".join(sorted(fields))) + ) + if format: + try: + formats = _entry_db_formats[db] + except KeyError: + formats = _get_entry_formats(db) + _entry_db_formats[db] = formats + if format not in formats: + raise ValueError( + "TogoWS entry fetch does not explicitly support " + "format '%s' for database '%s'. Only: %s" + % (format, db, ", ".join(sorted(formats))) + ) + + if isinstance(id, list): + id = ",".join(id) + url = _BASE_URL + f"/entry/{db}/{quote(id)}" + if field: + url += "/" + field + if format: + url += "." + format + return _open(url) + + +def search_count(db, query): + """Call TogoWS search count to see how many matches a search gives. + + Arguments: + - db - database (string), see http://togows.dbcls.jp/search + - query - search term (string) + + You could then use the count to download a large set of search results in + batches using the offset and limit options to Bio.TogoWS.search(). In + general however the Bio.TogoWS.search_iter() function is simpler to use. + """ + global _search_db_names + if _search_db_names is None: + _search_db_names = _get_fields(_BASE_URL + "/search") + if db not in _search_db_names: + # TODO - Make this a ValueError? Right now despite the HTML website + # claiming to, the "gene" or "ncbi-gene" don't work and are not listed. + import warnings + + warnings.warn( + "TogoWS search does not officially support database '%s'. " + "See %s/search/ for options." % (db, _BASE_URL) + ) + url = _BASE_URL + f"/search/{db}/{quote(query)}/count" + handle = _open(url) + data = handle.read() + handle.close() + if not data: + raise ValueError(f"TogoWS returned no data from URL {url}") + try: + return int(data.strip()) + except ValueError: + raise ValueError(f"Expected an integer from URL {url}, got: {data!r}") from None + + +def search_iter(db, query, limit=None, batch=100): + """Call TogoWS search iterating over the results (generator function). + + Arguments: + - db - database (string), see http://togows.dbcls.jp/search + - query - search term (string) + - limit - optional upper bound on number of search results + - batch - number of search results to pull back each time talk to + TogoWS (currently limited to 100). + + You would use this function within a for loop, e.g. + + >>> from Bio import TogoWS + >>> for id in TogoWS.search_iter("pubmed", "diabetes+human", limit=10): + ... print("PubMed ID: %s" %id) # maybe fetch data with entry? + PubMed ID: ... + + Internally this first calls the Bio.TogoWS.search_count() and then + uses Bio.TogoWS.search() to get the results in batches. + """ + count = search_count(db, query) + if not count: + return + # NOTE - We leave it to TogoWS to enforce any upper bound on each + # batch, they currently return an HTTP 400 Bad Request if above 100. + remain = count + if limit is not None: + remain = min(remain, limit) + offset = 1 # They don't use zero based counting + prev_ids = [] # Just cache the last batch for error checking + while remain: + batch = min(batch, remain) + # print("%r left, asking for %r" % (remain, batch)) + ids = search(db, query, offset, batch).read().strip().split() + assert len(ids) == batch, "Got %i, expected %i" % (len(ids), batch) + # print("offset %i, %s ... %s" % (offset, ids[0], ids[-1])) + if ids == prev_ids: + raise RuntimeError("Same search results for previous offset") + for identifier in ids: + if identifier in prev_ids: + raise RuntimeError(f"Result {identifier} was in previous batch") + yield identifier + offset += batch + remain -= batch + prev_ids = ids + + +def search(db, query, offset=None, limit=None, format=None): + """Call TogoWS search. + + This is a low level wrapper for the TogoWS search function, which + can return results in a several formats. In general, the search_iter + function is more suitable for end users. + + Arguments: + - db - database (string), see http://togows.dbcls.jp/search/ + - query - search term (string) + - offset, limit - optional integers specifying which result to start from + (1 based) and the number of results to return. + - format - return data file format (string), e.g. "json", "ttl" (RDF) + By default plain text is returned, one result per line. + + At the time of writing, TogoWS applies a default count limit of 100 + search results, and this is an upper bound. To access more results, + use the offset argument or the search_iter(...) function. + + TogoWS supports a long list of databases, including many from the NCBI + (e.g. "ncbi-pubmed" or "pubmed", "ncbi-genbank" or "genbank", and + "ncbi-taxonomy"), EBI (e.g. "ebi-ebml" or "embl", "ebi-uniprot" or + "uniprot, "ebi-go"), and KEGG (e.g. "kegg-compound" or "compound"). + For the current list, see http://togows.dbcls.jp/search/ + + The NCBI provide the Entrez Search service (ESearch) which is similar, + available in Biopython as the Bio.Entrez.esearch() function. + + See also the function Bio.TogoWS.search_count() which returns the number + of matches found, and the Bio.TogoWS.search_iter() function which allows + you to iterate over the search results (taking care of batching for you). + """ + global _search_db_names + if _search_db_names is None: + _search_db_names = _get_fields(_BASE_URL + "/search") + if db not in _search_db_names: + # TODO - Make this a ValueError? Right now despite the HTML website + # claiming to, the "gene" or "ncbi-gene" don't work and are not listed. + import warnings + + warnings.warn( + "TogoWS search does not explicitly support database '%s'. " + "See %s/search/ for options." % (db, _BASE_URL) + ) + url = _BASE_URL + f"/search/{db}/{quote(query)}" + if offset is not None and limit is not None: + try: + offset = int(offset) + except ValueError: + raise ValueError( + f"Offset should be an integer (at least one), not {offset!r}" + ) from None + try: + limit = int(limit) + except ValueError: + raise ValueError( + f"Limit should be an integer (at least one), not {limit!r}" + ) from None + if offset <= 0: + raise ValueError("Offset should be at least one, not %i" % offset) + if limit <= 0: + raise ValueError("Count should be at least one, not %i" % limit) + url += "/%i,%i" % (offset, limit) + elif offset is not None or limit is not None: + raise ValueError("Expect BOTH offset AND limit to be provided (or neither)") + if format: + url += "." + format + # print(url) + return _open(url) + + +def convert(data, in_format, out_format): + """Call TogoWS for file format conversion. + + Arguments: + - data - string or handle containing input record(s) + - in_format - string describing the input file format (e.g. "genbank") + - out_format - string describing the requested output format (e.g. "fasta") + + For a list of supported conversions (e.g. "genbank" to "fasta"), see + http://togows.dbcls.jp/convert/ + + Note that Biopython has built in support for conversion of sequence and + alignnent file formats (functions Bio.SeqIO.convert and Bio.AlignIO.convert) + """ + global _convert_formats + if not _convert_formats: + _convert_formats = _get_convert_formats() + if [in_format, out_format] not in _convert_formats: + msg = "\n".join("%s -> %s" % tuple(pair) for pair in _convert_formats) + raise ValueError(f"Unsupported conversion. Choose from:\n{msg}") + url = _BASE_URL + f"/convert/{in_format}.{out_format}" + # TODO - Should we just accept a string not a handle? What about a filename? + try: + # Handle + data = data.read() + except AttributeError: + # String + pass + return _open(url, post=data) + + +@function_with_previous +def _open(url, post=None): + """Build the URL and open a handle to it (PRIVATE). + + Open a handle to TogoWS, will raise an IOError if it encounters an error. + + In the absence of clear guidelines, this function enforces a limit of + "up to three queries per second" to avoid abusing the TogoWS servers. + """ + delay = 0.333333333 # one third of a second + current = time.time() + wait = _open.previous + delay - current + if wait > 0: + time.sleep(wait) + _open.previous = current + wait + else: + _open.previous = current + + if post: + handle = urlopen(url, post.encode()) + else: + handle = urlopen(url) + + # We now trust TogoWS to have set an HTTP error code, that + # suffices for my current unit tests. Previously we would + # examine the start of the data returned back. + text_handle = io.TextIOWrapper(handle, encoding="UTF-8") + text_handle.url = handle.url + return text_handle + + +_open.previous = 0 + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6333dc494439d0a77d5cfe53acb0543255569b1e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/UniGene/__init__.py @@ -0,0 +1,335 @@ +# Copyright 2006 by Sean Davis, National Cancer Institute, NIH. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Parse Unigene flat file format files such as the Hs.data file. + +Here is an overview of the flat file format that this parser deals with: + + Line types/qualifiers:: + + ID UniGene cluster ID + TITLE Title for the cluster + GENE Gene symbol + CYTOBAND Cytological band + EXPRESS Tissues of origin for ESTs in cluster + RESTR_EXPR Single tissue or development stage contributes + more than half the total EST frequency for this gene. + GNM_TERMINUS genomic confirmation of presence of a 3' terminus; + T if a non-templated polyA tail is found among + a cluster's sequences; else + I if templated As are found in genomic sequence or + S if a canonical polyA signal is found on + the genomic sequence + GENE_ID Entrez gene identifier associated with at least one + sequence in this cluster; + to be used instead of LocusLink. + LOCUSLINK LocusLink identifier associated with at least one + sequence in this cluster; + deprecated in favor of GENE_ID + HOMOL Homology; + CHROMOSOME Chromosome. For plants, CHROMOSOME refers to mapping + on the arabidopsis genome. + STS STS + ACC= GenBank/EMBL/DDBJ accession number of STS + [optional field] + UNISTS= identifier in NCBI's UNISTS database + TXMAP Transcript map interval + MARKER= Marker found on at least one sequence in this + cluster + RHPANEL= Radiation Hybrid panel used to place marker + PROTSIM Protein Similarity data for the sequence with + highest-scoring protein similarity in this cluster + ORG= Organism + PROTGI= Sequence GI of protein + PROTID= Sequence ID of protein + PCT= Percent alignment + ALN= length of aligned region (aa) + SCOUNT Number of sequences in the cluster + SEQUENCE Sequence + ACC= GenBank/EMBL/DDBJ accession number of sequence + NID= Unique nucleotide sequence identifier (gi) + PID= Unique protein sequence identifier (used for + non-ESTs) + CLONE= Clone identifier (used for ESTs only) + END= End (5'/3') of clone insert read (used for + ESTs only) + LID= Library ID; see Hs.lib.info for library name + and tissue + MGC= 5' CDS-completeness indicator; if present, the + clone associated with this sequence is believed + CDS-complete. A value greater than 511 is the gi + of the CDS-complete mRNA matched by the EST, + otherwise the value is an indicator of the + reliability of the test indicating CDS + completeness; higher values indicate more + reliable CDS-completeness predictions. + SEQTYPE= Description of the nucleotide sequence. + Possible values are mRNA, EST and HTC. + TRACE= The Trace ID of the EST sequence, as provided by + NCBI Trace Archive + +""" + + +class SequenceLine: + """Store the information for one SEQUENCE line from a Unigene file. + + Initialize with the text part of the SEQUENCE line, or nothing. + + Attributes and descriptions (access as LOWER CASE): + - ACC= GenBank/EMBL/DDBJ accession number of sequence + - NID= Unique nucleotide sequence identifier (gi) + - PID= Unique protein sequence identifier (used for non-ESTs) + - CLONE= Clone identifier (used for ESTs only) + - END= End (5'/3') of clone insert read (used for ESTs only) + - LID= Library ID; see Hs.lib.info for library name and tissue + - MGC= 5' CDS-completeness indicator; if present, + the clone associated with this sequence + is believed CDS-complete. A value greater than 511 + is the gi of the CDS-complete mRNA matched by the EST, + otherwise the value is an indicator of the reliability + of the test indicating CDS completeness; + higher values indicate more reliable CDS-completeness + predictions. + - SEQTYPE= Description of the nucleotide sequence. Possible values + are mRNA, EST and HTC. + - TRACE= The Trace ID of the EST sequence, as provided by NCBI + Trace Archive + + """ + + def __init__(self, text=None): + """Initialize the class.""" + self.acc = "" + self.nid = "" + self.lid = "" + self.pid = "" + self.clone = "" + self.image = "" + self.is_image = False + self.end = "" + self.mgc = "" + self.seqtype = "" + self.trace = "" + if text is not None: + self.text = text + self._init_from_text(text) + + def _init_from_text(self, text): + parts = text.split("; ") + for part in parts: + key, val = part.split("=") + if key == "CLONE": + if val[:5] == "IMAGE": + self.is_image = True + self.image = val[6:] + setattr(self, key.lower(), val) + + def __repr__(self): + """Return UniGene SequenceLine object as a string.""" + return self.text + + +class ProtsimLine: + """Store the information for one PROTSIM line from a Unigene file. + + Initialize with the text part of the PROTSIM line, or nothing. + + Attributes and descriptions (access as LOWER CASE) + ORG= Organism + PROTGI= Sequence GI of protein + PROTID= Sequence ID of protein + PCT= Percent alignment + ALN= length of aligned region (aa) + """ + + def __init__(self, text=None): + """Initialize the class.""" + self.org = "" + self.protgi = "" + self.protid = "" + self.pct = "" + self.aln = "" + if text is not None: + self.text = text + self._init_from_text(text) + + def _init_from_text(self, text): + parts = text.split("; ") + + for part in parts: + key, val = part.split("=") + setattr(self, key.lower(), val) + + def __repr__(self): + """Return UniGene ProtsimLine object as a string.""" + return self.text + + +class STSLine: + """Store the information for one STS line from a Unigene file. + + Initialize with the text part of the STS line, or nothing. + + Attributes and descriptions (access as LOWER CASE) + + ACC= GenBank/EMBL/DDBJ accession number of STS [optional field] + UNISTS= identifier in NCBI's UNISTS database + """ + + def __init__(self, text=None): + """Initialize the class.""" + self.acc = "" + self.unists = "" + if text is not None: + self.text = text + self._init_from_text(text) + + def _init_from_text(self, text): + parts = text.split(" ") + + for part in parts: + key, val = part.split("=") + setattr(self, key.lower(), val) + + def __repr__(self): + """Return UniGene STSLine object as a string.""" + return self.text + + +class Record: + """Store a Unigene record. + + Here is what is stored:: + + self.ID = '' # ID line + self.species = '' # Hs, Bt, etc. + self.title = '' # TITLE line + self.symbol = '' # GENE line + self.cytoband = '' # CYTOBAND line + self.express = [] # EXPRESS line, parsed on ';' + # Will be an array of strings + self.restr_expr = '' # RESTR_EXPR line + self.gnm_terminus = '' # GNM_TERMINUS line + self.gene_id = '' # GENE_ID line + self.locuslink = '' # LOCUSLINK line + self.homol = '' # HOMOL line + self.chromosome = '' # CHROMOSOME line + self.protsim = [] # PROTSIM entries, array of Protsims + # Type ProtsimLine + self.sequence = [] # SEQUENCE entries, array of Sequence entries + # Type SequenceLine + self.sts = [] # STS entries, array of STS entries + # Type STSLine + self.txmap = [] # TXMAP entries, array of TXMap entries + + """ + + def __init__(self): + """Initialize the class.""" + self.ID = "" # ID line + self.species = "" # Hs, Bt, etc. + self.title = "" # TITLE line + self.symbol = "" # GENE line + self.cytoband = "" # CYTOBAND line + self.express = [] # EXPRESS line, parsed on ';' + self.restr_expr = "" # RESTR_EXPR line + self.gnm_terminus = "" # GNM_TERMINUS line + self.gene_id = "" # GENE_ID line + self.locuslink = "" # LOCUSLINK line + self.homol = "" # HOMOL line + self.chromosome = "" # CHROMOSOME line + self.protsim = [] # PROTSIM entries, array of Protsims + self.sequence = [] # SEQUENCE entries, array of Sequence entries + self.sts = [] # STS entries, array of STS entries + self.txmap = [] # TXMAP entries, array of TXMap entries + + def __repr__(self): + """Represent the UniGene Record object as a string for debugging.""" + return f"<{self.__class__.__name__}> {self.ID} {self.symbol} {self.title}" + + +def parse(handle): + """Read and load a UniGene records, for files containing multiple records.""" + while True: + record = _read(handle) + if not record: + return + yield record + + +def read(handle): + """Read and load a UniGene record, one record per file.""" + record = _read(handle) + if not record: + raise ValueError("No SwissProt record found") + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one SwissProt record found") + return record + + +# Everything below is private + + +def _read(handle): + UG_INDENT = 12 + record = None + for line in handle: + tag, value = line[:UG_INDENT].rstrip(), line[UG_INDENT:].rstrip() + line = line.rstrip() + if tag == "ID": + record = Record() + record.ID = value + record.species = record.ID.split(".")[0] + elif tag == "TITLE": + record.title = value + elif tag == "GENE": + record.symbol = value + elif tag == "GENE_ID": + record.gene_id = value + elif tag == "LOCUSLINK": + record.locuslink = value + elif tag == "HOMOL": + if value == "YES": + record.homol = True + elif value == "NO": + record.homol = True + else: + raise ValueError(f"Cannot parse HOMOL line {line}") + elif tag == "EXPRESS": + record.express = [word.strip() for word in value.split("|")] + elif tag == "RESTR_EXPR": + record.restr_expr = [word.strip() for word in value.split("|")] + elif tag == "CHROMOSOME": + record.chromosome = value + elif tag == "CYTOBAND": + record.cytoband = value + elif tag == "PROTSIM": + protsim = ProtsimLine(value) + record.protsim.append(protsim) + elif tag == "SCOUNT": + scount = int(value) + elif tag == "SEQUENCE": + sequence = SequenceLine(value) + record.sequence.append(sequence) + elif tag == "STS": + sts = STSLine(value) + record.sts.append(sts) + elif tag == "//": + if len(record.sequence) != scount: + raise ValueError( + "The number of sequences specified in the record " + "(%d) does not agree with the number of sequences found (%d)" + % (scount, len(record.sequence)) + ) + return record + else: + raise ValueError(f"Unknown tag {tag}") + if record: + raise ValueError("Unexpected end of stream.") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/._GOA.py b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/._GOA.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/._GOA.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/GOA.py b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/GOA.py new file mode 100644 index 0000000000000000000000000000000000000000..27087cd70a9ef75e96edb470c63aa69eb81bf935 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/GOA.py @@ -0,0 +1,509 @@ +#!/usr/bin/env python +# Copyright 2013, 2016 by Iddo Friedberg idoerg@gmail.com. All rights reserved. +# Copyright 2020 by Sergio Valqui. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Parsers for the GAF, GPA and GPI formats from UniProt-GOA. + +Uniprot-GOA README + GAF format description: +ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/UNIPROT/README + +Gene Association File, GAF formats: +http://geneontology.org/docs/go-annotation-file-gaf-format-2.2/ +http://geneontology.org/docs/go-annotation-file-gaf-format-2.1/ +http://geneontology.org/docs/go-annotation-file-gaf-format-2.0/ + +Gene Product Association Data (GPA format) README: +http://geneontology.org/docs/gene-product-association-data-gpad-format/ + +Gene Product Information (GPI format) README: +http://geneontology.org/docs/gene-product-information-gpi-format/ + +Go Annotation files are located here: +ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/ +""" + +import copy + +# GAF: GO Annotation Format +# +# GAF version 2.0 + +GAF20FIELDS = [ + "DB", + "DB_Object_ID", + "DB_Object_Symbol", + "Qualifier", + "GO_ID", + "DB:Reference", + "Evidence", + "With", + "Aspect", + "DB_Object_Name", + "Synonym", + "DB_Object_Type", + "Taxon_ID", + "Date", + "Assigned_By", + "Annotation_Extension", + "Gene_Product_Form_ID", +] + +# GAF version 1.0 +GAF10FIELDS = [ + "DB", + "DB_Object_ID", + "DB_Object_Symbol", + "Qualifier", + "GO_ID", + "DB:Reference", + "Evidence", + "With", + "Aspect", + "DB_Object_Name", + "Synonym", + "DB_Object_Type", + "Taxon_ID", + "Date", + "Assigned_By", +] + +# GPA version 1.0 +GPA10FIELDS = [ + "DB", + "DB_Object_ID", + "Qualifier", + "GO_ID", + "DB:Reference", + "Evidence code", + "With", + "Interacting_taxon_ID", + "Date", + "Assigned_by", + "Annotation_Extension", + "Spliceform_ID", +] + +# GPA version 1.1 +GPA11FIELDS = [ + "DB", + "DB_Object_ID", + "Qualifier", + "GO_ID", + "DB:Reference", + "ECO_Evidence_code", + "With", + "Interacting_taxon_ID", + "Date", + "Assigned_by", + "Annotation Extension", + "Annotation_Properties", +] + +# GPI version 1.0 +GPI10FIELDS = [ + "DB", + "DB_subset", + "DB_Object_ID", + "DB_Object_Symbol", + "DB_Object_Name", + "DB_Object_Synonym", + "DB_Object_Type", + "Taxon", + "Annotation_Target_Set", + "Annotation_Completed", + "Parent_Object_ID", +] + +# GPI version 1.1 +GPI11FIELDS = [ + "DB_Object_ID", + "DB_Object_Symbol", + "DB_Object_Name", + "DB_Object_Synonym", + "DB_Object_Type", + "Taxon", + "Parent_Object_ID", + "DB_Xref", + "Gene_Product_Properties", +] + +# GPI version 1.2 +GPI12FIELDS = [ + "DB", + "DB_Object_ID", + "DB_Object_Symbol", + "DB_Object_Name", + "DB_Object_Synonym", + "DB_Object_Type", + "Taxon", + "Parent_Object_ID", + "DB_Xref", + "Gene_Product_Properties", +] + + +def _gpi10iterator(handle): + """Read GPI 1.0 format files (PRIVATE). + + This iterator is used to read a gp_information.goa_uniprot + file which is in the GPI 1.0 format. + """ + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[5] = inrec[5].split("|") # DB_Object_Synonym(s) + inrec[8] = inrec[8].split("|") # Annotation_Target_Set + yield dict(zip(GPI10FIELDS, inrec)) + + +def _gpi11iterator(handle): + """Read GPI 1.1 format files (PRIVATE). + + This iterator is used to read a gp_information.goa_uniprot + file which is in the GPI 1.1 format. + """ + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[2] = inrec[2].split("|") # DB_Object_Name + inrec[3] = inrec[3].split("|") # DB_Object_Synonym(s) + inrec[7] = inrec[7].split("|") # DB_Xref(s) + inrec[8] = inrec[8].split("|") # Properties + yield dict(zip(GPI11FIELDS, inrec)) + + +def _gpi12iterator(handle): + """Read GPI 1.2 format files (PRIVATE). + + This iterator is used to read a gp_information.goa_uniprot + file which is in the GPI 1.2 format. + """ + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[3] = inrec[3].split("|") # DB_Object_Name + inrec[4] = inrec[4].split("|") # DB_Object_Synonym(s) + inrec[8] = inrec[8].split("|") # DB_Xref(s) + inrec[9] = inrec[9].split("|") # Properties + yield dict(zip(GPI12FIELDS, inrec)) + + +def gpi_iterator(handle): + """Read GPI format files. + + This function should be called to read a + gp_information.goa_uniprot file. At the moment, there is + only one format, but this may change, so + this function is a placeholder a future wrapper. + """ + inline = handle.readline() + if inline.strip() == "!gpi-version: 1.2": + return _gpi12iterator(handle) + elif inline.strip() == "!gpi-version: 1.1": + # sys.stderr.write("gpi 1.1\n") + return _gpi11iterator(handle) + elif inline.strip() == "!gpi-version: 1.0": + # sys.stderr.write("gpi 1.0\n") + return _gpi10iterator(handle) + elif inline.strip() == "!gpi-version: 2.1": + # sys.stderr.write("gpi 2.1\n") + # return _gpi20iterator(handle) + raise NotImplementedError("Sorry, parsing GPI version 2 not implemented yet.") + else: + raise ValueError(f"Unknown GPI version {inline}\n") + + +def _gpa10iterator(handle): + """Read GPA 1.0 format files (PRIVATE). + + This iterator is used to read a gp_association.* + file which is in the GPA 1.0 format. Do not call directly. Rather, + use the gpaiterator function. + """ + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[2] = inrec[2].split("|") # Qualifier + inrec[4] = inrec[4].split("|") # DB:Reference(s) + inrec[6] = inrec[6].split("|") # With + inrec[10] = inrec[10].split("|") # Annotation extension + yield dict(zip(GPA10FIELDS, inrec)) + + +def _gpa11iterator(handle): + """Read GPA 1.1 format files (PRIVATE). + + This iterator is used to read a gp_association.goa_uniprot + file which is in the GPA 1.1 format. Do not call directly. Rather + use the gpa_iterator function + """ + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[2] = inrec[2].split("|") # Qualifier + inrec[4] = inrec[4].split("|") # DB:Reference(s) + inrec[6] = inrec[6].split("|") # With + inrec[10] = inrec[10].split("|") # Annotation extension + yield dict(zip(GPA11FIELDS, inrec)) + + +def gpa_iterator(handle): + """Read GPA format files. + + This function should be called to read a + gene_association.goa_uniprot file. Reads the first record and + returns a gpa 1.1 or a gpa 1.0 iterator as needed + """ + inline = handle.readline() + if inline.strip() == "!gpa-version: 1.1": + # sys.stderr.write("gpa 1.1\n") + return _gpa11iterator(handle) + elif inline.strip() == "!gpa-version: 1.0": + # sys.stderr.write("gpa 1.0\n") + return _gpa10iterator(handle) + else: + raise ValueError(f"Unknown GPA version {inline}\n") + + +def _gaf20iterator(handle): + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[3] = inrec[3].split("|") # Qualifier + inrec[5] = inrec[5].split("|") # DB:reference(s) + inrec[7] = inrec[7].split("|") # With || From + inrec[10] = inrec[10].split("|") # Synonym + inrec[12] = inrec[12].split("|") # Taxon + yield dict(zip(GAF20FIELDS, inrec)) + + +def _gaf10iterator(handle): + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[3] = inrec[3].split("|") # Qualifier + inrec[5] = inrec[5].split("|") # DB:reference(s) + inrec[7] = inrec[7].split("|") # With || From + inrec[10] = inrec[10].split("|") # Synonym + inrec[12] = inrec[12].split("|") # Taxon + yield dict(zip(GAF10FIELDS, inrec)) + + +def _gaf10byproteiniterator(handle): + cur_id = None + id_rec_list = [] + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[3] = inrec[3].split("|") # Qualifier + inrec[5] = inrec[5].split("|") # DB:reference(s) + inrec[7] = inrec[7].split("|") # With || From + inrec[10] = inrec[10].split("|") # Synonym + inrec[12] = inrec[12].split("|") # Taxon + cur_rec = dict(zip(GAF10FIELDS, inrec)) + if cur_rec["DB_Object_ID"] != cur_id and cur_id: + ret_list = copy.copy(id_rec_list) + id_rec_list = [cur_rec] + cur_id = cur_rec["DB_Object_ID"] + yield ret_list + else: + cur_id = cur_rec["DB_Object_ID"] + id_rec_list.append(cur_rec) + + +def _gaf20byproteiniterator(handle): + cur_id = None + id_rec_list = [] + for inline in handle: + if inline[0] == "!": + continue + inrec = inline.rstrip("\n").split("\t") + if len(inrec) == 1: + continue + inrec[3] = inrec[3].split("|") # Qualifier + inrec[5] = inrec[5].split("|") # DB:reference(s) + inrec[7] = inrec[7].split("|") # With || From + inrec[10] = inrec[10].split("|") # Synonym + inrec[12] = inrec[12].split("|") # Taxon + cur_rec = dict(zip(GAF20FIELDS, inrec)) + if cur_rec["DB_Object_ID"] != cur_id and cur_id: + ret_list = copy.copy(id_rec_list) + id_rec_list = [cur_rec] + cur_id = cur_rec["DB_Object_ID"] + yield ret_list + else: + cur_id = cur_rec["DB_Object_ID"] + id_rec_list.append(cur_rec) + + +def gafbyproteiniterator(handle): + """Iterate over records in a gene association file. + + Returns a list of all consecutive records with the same DB_Object_ID + This function should be called to read a + gene_association.goa_uniprot file. Reads the first record and + returns a gaf 2.0 or a gaf 1.0 iterator as needed + 2016-04-09: added GAF 2.1 iterator & fixed bug in iterator assignment + In the meantime GAF 2.1 uses the GAF 2.0 iterator + """ + inline = handle.readline() + if inline.strip() == "!gaf-version: 2.0": + # sys.stderr.write("gaf 2.0\n") + return _gaf20byproteiniterator(handle) + elif inline.strip() == "!gaf-version: 1.0": + # sys.stderr.write("gaf 1.0\n") + return _gaf10byproteiniterator(handle) + elif inline.strip() == "!gaf-version: 2.1": + # Handle GAF 2.1 as GAF 2.0 for now TODO: fix + # sys.stderr.write("gaf 2.1\n") + return _gaf20byproteiniterator(handle) + elif inline.strip() == "!gaf-version: 2.2": + # Handle GAF 2.2 as GAF 2.0 for now. Change from + # 2.1 to 2.2 is that Qualifier field is no longer optional. + # As this type of checks has not been done before, we can + # continue to use the gaf2.0 parser + return _gaf20byproteiniterator(handle) + else: + raise ValueError(f"Unknown GAF version {inline}\n") + + +def gafiterator(handle): + """Iterate over a GAF 1.0 or 2.x file. + + This function should be called to read a + gene_association.goa_uniprot file. Reads the first record and + returns a gaf 2.x or a gaf 1.0 iterator as needed + + Example: open, read, interat and filter results. + + Original data file has been trimmed to ~600 rows. + + Original source ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/YEAST/goa_yeast.gaf.gz + + >>> from Bio.UniProt.GOA import gafiterator, record_has + >>> Evidence = {'Evidence': set(['ND'])} + >>> Synonym = {'Synonym': set(['YA19A_YEAST', 'YAL019W-A'])} + >>> Taxon_ID = {'Taxon_ID': set(['taxon:559292'])} + >>> with open('UniProt/goa_yeast.gaf', 'r') as handle: + ... for rec in gafiterator(handle): + ... if record_has(rec, Taxon_ID) and record_has(rec, Evidence) and record_has(rec, Synonym): + ... for key in ('DB_Object_Name', 'Evidence', 'Synonym', 'Taxon_ID'): + ... print(rec[key]) + ... + Putative uncharacterized protein YAL019W-A + ND + ['YA19A_YEAST', 'YAL019W-A'] + ['taxon:559292'] + Putative uncharacterized protein YAL019W-A + ND + ['YA19A_YEAST', 'YAL019W-A'] + ['taxon:559292'] + Putative uncharacterized protein YAL019W-A + ND + ['YA19A_YEAST', 'YAL019W-A'] + ['taxon:559292'] + + """ + inline = handle.readline() + if inline.strip() == "!gaf-version: 2.0": + # sys.stderr.write("gaf 2.0\n") + return _gaf20iterator(handle) + elif inline.strip() == "!gaf-version: 2.1": + # sys.stderr.write("gaf 2.1\n") + # Handle GAF 2.1 as GAF 2.0 for now. TODO: fix + return _gaf20iterator(handle) + elif inline.strip() == "!gaf-version: 2.2": + # Handle GAF 2.2 as GAF 2.0 for now. Change from + # 2.1 to 2.2 is that Qualifier field is no longer optional. + # As this type of checks has not been done before, we can + # continue to use the gaf2.0 parser + return _gaf20iterator(handle) + elif inline.strip() == "!gaf-version: 1.0": + # sys.stderr.write("gaf 1.0\n") + return _gaf10iterator(handle) + else: + raise ValueError(f"Unknown GAF version {inline}\n") + + +def writerec(outrec, handle, fields=GAF20FIELDS): + """Write a single UniProt-GOA record to an output stream. + + Caller should know the format version. Default: gaf-2.0 + If header has a value, then it is assumed this is the first record, + a header is written. + """ + outstr = "" + for field in fields[:-1]: + if isinstance(outrec[field], list): + for subfield in outrec[field]: + outstr += subfield + "|" + outstr = outstr[:-1] + "\t" + else: + outstr += outrec[field] + "\t" + outstr += outrec[fields[-1]] + "\n" + handle.write(outstr) + + +def writebyproteinrec(outprotrec, handle, fields=GAF20FIELDS): + """Write a list of GAF records to an output stream. + + Caller should know the format version. Default: gaf-2.0 + If header has a value, then it is assumed this is the first record, + a header is written. Typically the list is the one read by fafbyproteinrec, which + contains all consecutive lines with the same DB_Object_ID + """ + for outrec in outprotrec: + writerec(outrec, handle, fields=fields) + + +def record_has(inrec, fieldvals): + """Accept a record, and a dictionary of field values. + + The format is {'field_name': set([val1, val2])}. + If any field in the record has a matching value, the function returns + True. Otherwise, returns False. + """ + retval = False + for field in fieldvals: + if isinstance(inrec[field], str): + set1 = {inrec[field]} + else: + set1 = set(inrec[field]) + if set1 & fieldvals[field]: + retval = True + break + return retval + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47341be0e3b6b5f8f94b9c2584fbce8a8042e772 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/UniProt/__init__.py @@ -0,0 +1,156 @@ +# Copyright 2013 by Iddo Friedberg idoerg@gmail.com +# Revision copyright 2013 by Peter Cock. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code for dealing with assorted UniProt file formats and interacting with the UniProt database. + +This currently include parsers for the GAF, GPA and GPI formats +from UniProt-GOA as the module Bio.UniProt.GOA. + +See also Bio.SwissProt and the "swiss" support in Bio.SeqIO for +the legacy plain text sequence format still used in UniProt. + +See also Bio.SeqIO.SwissIO for the "uniprot-xml" support in +Bio.SeqIO. +""" + +import json +import re +import urllib.parse +from http.client import HTTPResponse +from typing import Optional +from urllib.request import urlopen + +_re_next_link = re.compile(r'<(.+)>; rel="next"') + + +def _get_next_link(response: HTTPResponse) -> str | None: + headers = response.headers + + if "Link" in headers and headers["Link"]: + match = _re_next_link.match(headers["Link"]) + if match: + return match.group(1) + + return None + + +def _get_results(response: HTTPResponse) -> list[dict]: + return json.loads(response.read().decode())["results"] + + +def _get_search_result_count(response: HTTPResponse) -> int: + headers = response.headers + + if "x-total-results" in headers and headers["x-total-results"]: + return int(headers["x-total-results"]) + else: + return 0 + + +class _UniProtSearchResults: + """A sequence over the results of a UniProt search. + + Do not use this class directly. Instead, use the :meth:`UniProt.search` method. + """ + + def _fetch_next_batch(self) -> HTTPResponse: + assert self.next_url is not None # type: ignore + with urlopen(self.next_url) as response: # type: ignore + self.results_cache += _get_results(response) + self.next_url = _get_next_link(response) + return response + + def __init__(self, first_url: str): + self.next_url = first_url + self.results_cache: list[dict] = [] + self.next_result_index = 0 + response = self._fetch_next_batch() + self.search_result_count = _get_search_result_count(response) + + def __iter__(self): + return self + + def __len__(self) -> int: + """Return the total number of search results, regardless of the batch size.""" + return self.search_result_count + + def _fetch_for(self, index: int) -> None: + """Fetch batches until the given index is in the cache.""" + assert index in range(len(self)) + while index >= len(self.results_cache): + self._fetch_next_batch() + + def __next__(self) -> dict: + if self.next_result_index < len(self): + self._fetch_for(self.next_result_index) + try: + next_result = self.results_cache[self.next_result_index] + self.next_result_index += 1 + return next_result + except IndexError: + raise StopIteration + else: + raise StopIteration + + def __getitem__(self, index): + if isinstance(index, slice): + start, stop, step = index.indices(len(self)) + # The assertions below should be guaranteed by the indices method + assert 0 <= start < len(self) and 0 <= stop <= len(self) + if step > 0: + if start <= stop and stop > 0: + self._fetch_for(stop - 1) + else: + # If start is 0 and step is negative, the slice is empty + if start >= stop and start > 0: + self._fetch_for(start) + elif isinstance(index, int): + if index not in range(-len(self), len(self)): + raise IndexError("Index out of bounds.") + self._fetch_for(index % len(self)) + return self.results_cache[index] + + +def search( + query: str, fields: list[str] | None = None, batch_size: int = 500 +) -> _UniProtSearchResults: + """Search the UniProt database. + + Consider using `query syntax `_ and + `query fields `_ to refine your search. + + See the API details `here `_. + + >>> from Bio import UniProt + >>> from itertools import islice + >>> # Get the first 10 results + >>> results = UniProt.search("(organism_id:2697049) AND (reviewed:true)")[:10] + + :param query: The query string to search UniProt with + :type query: str + :param fields: The columns to retrieve in the results, defaults to all fields + :type fields: List[str], optional + :param batch_size: The number of results to retrieve in each batch, defaults to 500 + :type batch_size: int + :return: An iterator over the search results + :rtype: _UniProtSearchResults + """ + parameters = { + "query": query, + "size": batch_size, + "format": "json", + } + if fields: + parameters["fields"] = ",".join(fields) + url = f"https://rest.uniprot.org/uniprotkb/search?{urllib.parse.urlencode(parameters)}" + + return _UniProtSearchResults(url) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e916c4fe6f2510ffa6dabbff0345851469f59a85 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/__init__.py @@ -0,0 +1,147 @@ +# Copyright 1999-2003 by Jeffrey Chang. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Collection of modules for dealing with biological data in Python. + +The Biopython Project is an international association of developers +of freely available Python tools for computational molecular biology. + +https://biopython.org +""" + +import os +import warnings + +__version__ = "1.87" + + +class MissingExternalDependencyError(Exception): + """Missing an external dependency. + + Used for things like missing command line tools. Important for our unit + tests to allow skipping tests with missing external dependencies. + """ + + +class MissingPythonDependencyError(MissingExternalDependencyError, ImportError): + """Missing an external python dependency (subclass of ImportError). + + Used for missing Python modules (rather than just a typical ImportError). + Important for our unit tests to allow skipping tests with missing external + python dependencies, while also allowing the exception to be caught as an + ImportError. + """ + + +class StreamModeError(ValueError): + """Incorrect stream mode (text vs binary). + + This error should be raised when a stream (file or file-like object) + argument is in text mode while the receiving function expects binary mode, + or vice versa. + """ + + +class BiopythonWarning(Warning): + """Biopython warning. + + Biopython should use this warning (or subclasses of it), making it easy to + silence all our warning messages should you wish to: + + >>> import warnings + >>> from Bio import BiopythonWarning + >>> warnings.simplefilter('ignore', BiopythonWarning) + + Consult the warnings module documentation for more details. + """ + + +class BiopythonParserWarning(BiopythonWarning): + """Biopython parser warning. + + Some in-valid data files cannot be parsed and will trigger an exception. + Where a reasonable interpretation is possible, Biopython will issue this + warning to indicate a potential problem. To silence these warnings, use: + + >>> import warnings + >>> from Bio import BiopythonParserWarning + >>> warnings.simplefilter('ignore', BiopythonParserWarning) + + Consult the warnings module documentation for more details. + """ + + +class BiopythonDeprecationWarning(BiopythonWarning): + """Biopython deprecation warning. + + Biopython uses this warning instead of the built in DeprecationWarning + since those are ignored by default since Python 2.7. + + To silence all our deprecation warning messages, use: + + >>> import warnings + >>> from Bio import BiopythonDeprecationWarning + >>> warnings.simplefilter('ignore', BiopythonDeprecationWarning) + + Code marked as deprecated is likely to be removed in a future version + of Biopython. To avoid removal of this code, please contact the Biopython + developers via the mailing list or GitHub. + """ + + +class BiopythonExperimentalWarning(BiopythonWarning): + """Biopython experimental code warning. + + Biopython uses this warning for experimental code ('alpha' or 'beta' + level code) which is released as part of the standard releases to mark + sub-modules or functions for early adopters to test & give feedback. + + Code issuing this warning is likely to change (or even be removed) in + a subsequent release of Biopython. Such code should NOT be used for + production/stable code. It should only be used if: + + - You are running the latest release of Biopython, or ideally the + latest code from our repository. + - You are subscribed to the biopython-dev mailing list to provide + feedback on this code, and to be alerted of changes to it. + + If all goes well, experimental code would be promoted to stable in + a subsequent release, and this warning removed from it. + """ + + +_parent_dir = os.path.dirname(os.path.dirname(__file__)) +if os.path.exists(os.path.join(_parent_dir, "pyproject.toml")): + # Looks like we are running from our source directory, + # a bad idea except if installed in development mode. + # + # See https://setuptools.readthedocs.io/en/latest/userguide/development_mode.html + # Do we have .../site-packages/biopython.egg-link present? + # + # Note "pip install -e ." currently calls setuptools internally + import site + + _dev_mode = False + for _p in site.getsitepackages(): + if os.path.isfile(os.path.join(_p, "biopython.egg-link")): + _dev_mode = True + break + # Also check the user specific site packages + if not _dev_mode and os.path.isfile( + os.path.join(site.getusersitepackages(), "biopython.egg-link") + ): + _dev_mode = True + if not _dev_mode: + warnings.warn( + "You may be importing Biopython from inside the source tree." + " This is bad practice and might lead to downstream issues." + " In particular, you might encounter ImportErrors due to" + " missing compiled C extensions. We recommend that you" + " try running your code from outside the source tree." + " If you are outside the source tree then you have a" + " pyproject.toml file in an unexpected directory: " + _parent_dir, + BiopythonWarning, + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/_utils.py b/.venv_haddock/lib/python3.12/site-packages/Bio/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6512b0670e7ad64420e051ecd53a3f43cc557fac --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/_utils.py @@ -0,0 +1,92 @@ +# Copyright 2010 by Eric Talevich. All rights reserved. +# Copyright 2012 by Wibowo Arindrarto. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Common utility functions for various Bio submodules.""" + +import os +from typing import Any +from collections.abc import Callable +from typing import cast +from typing import Optional +from typing import Protocol +from typing import TypeVar + +# workaround type checking method attributes from https://github.com/python/mypy/issues/2087#issuecomment-587741762 + +F = TypeVar("F", bound=Callable[..., object]) + + +class _FunctionWithPrevious(Protocol[F]): + previous: int | None + __call__: F + + +def function_with_previous(func: F) -> _FunctionWithPrevious[F]: + """Decorate a function as having an attribute named 'previous'.""" + function_with_previous = cast(_FunctionWithPrevious[F], func) + # Make sure the cast isn't a lie. + function_with_previous.previous = None + return function_with_previous + + +def find_test_dir(start_dir: str | None = None) -> str: + """Find the absolute path of Biopython's Tests directory. + + Arguments: + start_dir -- Initial directory to begin lookup (default to current dir) + + If the directory is not found up the filesystem's root directory, an + exception will be raised. + + """ + if not start_dir: + # no callbacks in function signatures! + # defaults to the current directory + # (using __file__ would give the installed Biopython) + start_dir = "." + + target = os.path.abspath(start_dir) + while True: + if os.path.isdir(os.path.join(target, "Bio")) and os.path.isdir( + os.path.join(target, "Tests") + ): + # Good, we're in the Biopython root now + return os.path.abspath(os.path.join(target, "Tests")) + # Recurse up the tree + # TODO - Test this on Windows + new, tmp = os.path.split(target) + if target == new: + # Reached root + break + target = new + raise ValueError( + f"Not within Biopython source tree: {os.path.abspath(start_dir)!r}" + ) + + +def run_doctest(target_dir: str | None = None, *args: Any, **kwargs: Any) -> None: + """Run doctest for the importing module.""" + import doctest + + # default doctest options + doctest_attributes: dict[str, Any] = {"optionflags": doctest.ELLIPSIS} + doctest_attributes.update(kwargs) + + cur_dir = os.path.abspath(os.curdir) + + print("Running doctests...") + try: + os.chdir(find_test_dir(target_dir)) + doctest.testmod(*args, **doctest_attributes) + finally: + # and revert back to initial directory + os.chdir(cur_dir) + print("Done") + + +if __name__ == "__main__": + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/bgzf.py b/.venv_haddock/lib/python3.12/site-packages/Bio/bgzf.py new file mode 100644 index 0000000000000000000000000000000000000000..8041dd5918bcffa81ad91f9c1108a84b006b0d8e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/bgzf.py @@ -0,0 +1,960 @@ +#!/usr/bin/env python +# Copyright 2010-2018 by Peter Cock. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +r"""Read and write BGZF compressed files (the GZIP variant used in BAM). + +The SAM/BAM file format (Sequence Alignment/Map) comes in a plain text +format (SAM), and a compressed binary format (BAM). The latter uses a +modified form of gzip compression called BGZF (Blocked GNU Zip Format), +which can be applied to any file format to provide compression with +efficient random access. BGZF is described together with the SAM/BAM +file format at https://samtools.sourceforge.net/SAM1.pdf + +Please read the text below about 'virtual offsets' before using BGZF +files for random access. + +Aim of this module +------------------ +The Python gzip library can be used to read BGZF files, since for +decompression they are just (specialised) gzip files. What this +module aims to facilitate is random access to BGZF files (using the +'virtual offset' idea), and writing BGZF files (which means using +suitably sized gzip blocks and writing the extra 'BC' field in the +gzip headers). As in the gzip library, the zlib library is used +internally. + +In addition to being required for random access to and writing of +BAM files, the BGZF format can also be used on other sequential +data (in the sense of one record after another), such as most of +the sequence data formats supported in Bio.SeqIO (like FASTA, +FASTQ, GenBank, etc) or large MAF alignments. + +The Bio.SeqIO indexing functions use this module to support BGZF files. + +Technical Introduction to BGZF +------------------------------ +The gzip file format allows multiple compressed blocks, each of which +could be a stand alone gzip file. As an interesting bonus, this means +you can use Unix ``cat`` to combine two or more gzip files into one by +concatenating them. Also, each block can have one of several compression +levels (including uncompressed, which actually takes up a little bit +more space due to the gzip header). + +What the BAM designers realised was that while random access to data +stored in traditional gzip files was slow, breaking the file into +gzip blocks would allow fast random access to each block. To access +a particular piece of the decompressed data, you just need to know +which block it starts in (the offset of the gzip block start), and +how far into the (decompressed) contents of the block you need to +read. + +One problem with this is finding the gzip block sizes efficiently. +You can do it with a standard gzip file, but it requires every block +to be decompressed -- and that would be rather slow. Additionally +typical gzip files may use very large blocks. + +All that differs in BGZF is that compressed size of each gzip block +is limited to 2^16 bytes, and an extra 'BC' field in the gzip header +records this size. Traditional decompression tools can ignore this, +and unzip the file just like any other gzip file. + +The point of this is you can look at the first BGZF block, find out +how big it is from this 'BC' header, and thus seek immediately to +the second block, and so on. + +The BAM indexing scheme records read positions using a 64 bit +'virtual offset', comprising ``coffset << 16 | uoffset``, where ``coffset`` +is the file offset of the BGZF block containing the start of the read +(unsigned integer using up to 64-16 = 48 bits), and ``uoffset`` is the +offset within the (decompressed) block (unsigned 16 bit integer). + +This limits you to BAM files where the last block starts by 2^48 +bytes, or 256 petabytes, and the decompressed size of each block +is at most 2^16 bytes, or 64kb. Note that this matches the BGZF +'BC' field size which limits the compressed size of each block to +2^16 bytes, allowing for BAM files to use BGZF with no gzip +compression (useful for intermediate files in memory to reduce +CPU load). + +Warning about namespaces +------------------------ +It is considered a bad idea to use "from XXX import ``*``" in Python, because +it pollutes the namespace. This is a real issue with Bio.bgzf (and the +standard Python library gzip) because they contain a function called open +i.e. Suppose you do this: + +>>> from Bio.bgzf import * +>>> print(open.__module__) +Bio.bgzf + +Or, + +>>> from gzip import * +>>> print(open.__module__) +gzip + +Notice that the open function has been replaced. You can "fix" this if you +need to by importing the built-in open function: + +>>> from builtins import open + +However, what we recommend instead is to use the explicit namespace, e.g. + +>>> from Bio import bgzf +>>> print(bgzf.open.__module__) +Bio.bgzf + + +Examples +-------- +This is an ordinary GenBank file compressed using BGZF, so it can +be decompressed using gzip, + +>>> import gzip +>>> handle = gzip.open("GenBank/NC_000932.gb.bgz", "r") +>>> assert 0 == handle.tell() +>>> line = handle.readline() +>>> assert 80 == handle.tell() +>>> line = handle.readline() +>>> assert 143 == handle.tell() +>>> data = handle.read(70000) +>>> assert 70143 == handle.tell() +>>> handle.close() + +We can also access the file using the BGZF reader - but pay +attention to the file offsets which will be explained below: + +>>> handle = BgzfReader("GenBank/NC_000932.gb.bgz", "r") +>>> assert 0 == handle.tell() +>>> print(handle.readline().rstrip()) +LOCUS NC_000932 154478 bp DNA circular PLN 15-APR-2009 +>>> assert 80 == handle.tell() +>>> print(handle.readline().rstrip()) +DEFINITION Arabidopsis thaliana chloroplast, complete genome. +>>> assert 143 == handle.tell() +>>> data = handle.read(70000) +>>> assert 987828735 == handle.tell() +>>> print(handle.readline().rstrip()) +f="GeneID:844718" +>>> print(handle.readline().rstrip()) + CDS complement(join(84337..84771,85454..85843)) +>>> offset = handle.seek(make_virtual_offset(55074, 126)) +>>> print(handle.readline().rstrip()) + 68521 tatgtcattc gaaattgtat aaagacaact cctatttaat agagctattt gtgcaagtat +>>> handle.close() + +Notice the handle's offset looks different as a BGZF file. This +brings us to the key point about BGZF, which is the block structure: + +>>> handle = open("GenBank/NC_000932.gb.bgz", "rb") +>>> for values in BgzfBlocks(handle): +... print("Raw start %i, raw length %i; data start %i, data length %i" % values) +Raw start 0, raw length 15073; data start 0, data length 65536 +Raw start 15073, raw length 17857; data start 65536, data length 65536 +Raw start 32930, raw length 22144; data start 131072, data length 65536 +Raw start 55074, raw length 22230; data start 196608, data length 65536 +Raw start 77304, raw length 14939; data start 262144, data length 43478 +Raw start 92243, raw length 28; data start 305622, data length 0 +>>> handle.close() + +In this example the first three blocks are 'full' and hold 65536 bytes +of uncompressed data. The fourth block isn't full and holds 43478 bytes. +Finally there is a special empty fifth block which takes 28 bytes on +disk and serves as an 'end of file' (EOF) marker. If this is missing, +it is possible your BGZF file is incomplete. + +By reading ahead 70,000 bytes we moved into the second BGZF block, +and at that point the BGZF virtual offsets start to look different +to a simple offset into the decompressed data as exposed by the gzip +library. + +As an example, consider seeking to the decompressed position 196734. +Since 196734 = 65536 + 65536 + 65536 + 126 = 65536*3 + 126, this +is equivalent to jumping the first three blocks (which in this +specific example are all size 65536 after decompression - which +does not always hold) and starting at byte 126 of the fourth block +(after decompression). For BGZF, we need to know the fourth block's +offset of 55074 and the offset within the block of 126 to get the +BGZF virtual offset. + +>>> print(55074 << 16 | 126) +3609329790 +>>> print(bgzf.make_virtual_offset(55074, 126)) +3609329790 + +Thus for this BGZF file, decompressed position 196734 corresponds +to the virtual offset 3609329790. However, another BGZF file with +different contents would have compressed more or less efficiently, +so the compressed blocks would be different sizes. What this means +is the mapping between the uncompressed offset and the compressed +virtual offset depends on the BGZF file you are using. + +If you are accessing a BGZF file via this module, just use the +handle.tell() method to note the virtual offset of a position you +may later want to return to using handle.seek(). + +The catch with BGZF virtual offsets is while they can be compared +(which offset comes first in the file), you cannot safely subtract +them to get the size of the data between them, nor add/subtract +a relative offset. + +Of course you can parse this file with Bio.SeqIO using BgzfReader, +although there isn't any benefit over using gzip.open(...), unless +you want to index BGZF compressed sequence files: + +>>> from Bio import SeqIO +>>> handle = BgzfReader("GenBank/NC_000932.gb.bgz") +>>> record = SeqIO.read(handle, "genbank") +>>> handle.close() +>>> print(record.id) +NC_000932.1 + +Text Mode +--------- + +Like the standard library gzip.open(...), the BGZF code defaults to opening +files in binary mode. + +You can request the file be opened in text mode, but beware that this is hard +coded to the simple "latin1" (aka "iso-8859-1") encoding (which includes all +the ASCII characters), which works well with most Western European languages. +However, it is not fully compatible with the more widely used UTF-8 encoding. + +In variable width encodings like UTF-8, some single characters in the unicode +text output are represented by multiple bytes in the raw binary form. This is +problematic with BGZF, as we cannot always decode each block in isolation - a +single unicode character could be split over two blocks. This can even happen +with fixed width unicode encodings, as the BGZF block size is not fixed. + +Therefore, this module is currently restricted to only support single byte +unicode encodings, such as ASCII, "latin1" (which is a superset of ASCII), or +potentially other character maps (not implemented). + +Furthermore, unlike the default text mode on Python 3, we do not attempt to +implement universal new line mode. This transforms the various operating system +new line conventions like Windows (CR LF or "\r\n"), Unix (just LF, "\n"), or +old Macs (just CR, "\r"), into just LF ("\n"). Here we have the same problem - +is "\r" at the end of a block an incomplete Windows style new line? + +Instead, you will get the CR ("\r") and LF ("\n") characters as is. + +If your data is in UTF-8 or any other incompatible encoding, you must use +binary mode, and decode the appropriate fragments yourself. +""" + +import io +import struct +import sys +import zlib +from builtins import open as _open + +_bgzf_magic = b"\x1f\x8b\x08\x04" +_bgzf_header = b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00\x42\x43\x02\x00" +_bgzf_eof = b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00" +_bytes_BC = b"BC" + + +def open(filename, mode="rb"): + r"""Open a BGZF file for reading, writing or appending. + + If text mode is requested, in order to avoid multi-byte characters, this is + hard coded to use the "latin1" encoding, and "\r" and "\n" are passed as is + (without implementing universal new line mode). + + If your data is in UTF-8 or any other incompatible encoding, you must use + binary mode, and decode the appropriate fragments yourself. + """ + if "r" in mode.lower(): + return BgzfReader(filename, mode) + elif "w" in mode.lower() or "a" in mode.lower(): + return BgzfWriter(filename, mode) + else: + raise ValueError(f"Bad mode {mode!r}") + + +def make_virtual_offset(block_start_offset, within_block_offset): + """Compute a BGZF virtual offset from block start and within block offsets. + + The BAM indexing scheme records read positions using a 64 bit + 'virtual offset', comprising in C terms: + + block_start_offset << 16 | within_block_offset + + Here block_start_offset is the file offset of the BGZF block + start (unsigned integer using up to 64-16 = 48 bits), and + within_block_offset within the (decompressed) block (unsigned + 16 bit integer). + + >>> make_virtual_offset(0, 0) + 0 + >>> make_virtual_offset(0, 1) + 1 + >>> make_virtual_offset(0, 2**16 - 1) + 65535 + >>> make_virtual_offset(0, 2**16) + Traceback (most recent call last): + ... + ValueError: Require 0 <= within_block_offset < 2**16, got 65536 + + >>> 65536 == make_virtual_offset(1, 0) + True + >>> 65537 == make_virtual_offset(1, 1) + True + >>> 131071 == make_virtual_offset(1, 2**16 - 1) + True + + >>> 6553600000 == make_virtual_offset(100000, 0) + True + >>> 6553600001 == make_virtual_offset(100000, 1) + True + >>> 6553600010 == make_virtual_offset(100000, 10) + True + + >>> make_virtual_offset(2**48, 0) + Traceback (most recent call last): + ... + ValueError: Require 0 <= block_start_offset < 2**48, got 281474976710656 + + """ + if within_block_offset < 0 or within_block_offset >= 65536: + raise ValueError( + "Require 0 <= within_block_offset < 2**16, got %i" % within_block_offset + ) + if block_start_offset < 0 or block_start_offset >= 281474976710656: + raise ValueError( + "Require 0 <= block_start_offset < 2**48, got %i" % block_start_offset + ) + return (block_start_offset << 16) | within_block_offset + + +def split_virtual_offset(virtual_offset): + """Divides a 64-bit BGZF virtual offset into block start & within block offsets. + + >>> (100000, 0) == split_virtual_offset(6553600000) + True + >>> (100000, 10) == split_virtual_offset(6553600010) + True + + """ + start = virtual_offset >> 16 + return start, virtual_offset ^ (start << 16) + + +def BgzfBlocks(handle): + """Low level debugging function to inspect BGZF blocks. + + Expects a BGZF compressed file opened in binary read mode using + the builtin open function. Do not use a handle from this bgzf + module or the gzip module's open function which will decompress + the file. + + Returns the block start offset (see virtual offsets), the block + length (add these for the start of the next block), and the + decompressed length of the blocks contents (limited to 65536 in + BGZF), as an iterator - one tuple per BGZF block. + + >>> from builtins import open + >>> handle = open("SamBam/ex1.bam", "rb") + >>> for values in BgzfBlocks(handle): + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) + Raw start 0, raw length 18239; data start 0, data length 65536 + Raw start 18239, raw length 18223; data start 65536, data length 65536 + Raw start 36462, raw length 18017; data start 131072, data length 65536 + Raw start 54479, raw length 17342; data start 196608, data length 65536 + Raw start 71821, raw length 17715; data start 262144, data length 65536 + Raw start 89536, raw length 17728; data start 327680, data length 65536 + Raw start 107264, raw length 17292; data start 393216, data length 63398 + Raw start 124556, raw length 28; data start 456614, data length 0 + >>> handle.close() + + Indirectly we can tell this file came from an old version of + samtools because all the blocks (except the final one and the + dummy empty EOF marker block) are 65536 bytes. Later versions + avoid splitting a read between two blocks, and give the header + its own block (useful to speed up replacing the header). You + can see this in ex1_refresh.bam created using samtools 0.1.18: + + samtools view -b ex1.bam > ex1_refresh.bam + + >>> handle = open("SamBam/ex1_refresh.bam", "rb") + >>> for values in BgzfBlocks(handle): + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) + Raw start 0, raw length 53; data start 0, data length 38 + Raw start 53, raw length 18195; data start 38, data length 65434 + Raw start 18248, raw length 18190; data start 65472, data length 65409 + Raw start 36438, raw length 18004; data start 130881, data length 65483 + Raw start 54442, raw length 17353; data start 196364, data length 65519 + Raw start 71795, raw length 17708; data start 261883, data length 65411 + Raw start 89503, raw length 17709; data start 327294, data length 65466 + Raw start 107212, raw length 17390; data start 392760, data length 63854 + Raw start 124602, raw length 28; data start 456614, data length 0 + >>> handle.close() + + The above example has no embedded SAM header (thus the first block + is very small at just 38 bytes of decompressed data), while the next + example does (a larger block of 103 bytes). Notice that the rest of + the blocks show the same sizes (they contain the same read data): + + >>> handle = open("SamBam/ex1_header.bam", "rb") + >>> for values in BgzfBlocks(handle): + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) + Raw start 0, raw length 104; data start 0, data length 103 + Raw start 104, raw length 18195; data start 103, data length 65434 + Raw start 18299, raw length 18190; data start 65537, data length 65409 + Raw start 36489, raw length 18004; data start 130946, data length 65483 + Raw start 54493, raw length 17353; data start 196429, data length 65519 + Raw start 71846, raw length 17708; data start 261948, data length 65411 + Raw start 89554, raw length 17709; data start 327359, data length 65466 + Raw start 107263, raw length 17390; data start 392825, data length 63854 + Raw start 124653, raw length 28; data start 456679, data length 0 + >>> handle.close() + + """ + if isinstance(handle, BgzfReader): + raise TypeError("Function BgzfBlocks expects a binary handle") + data_start = 0 + while True: + start_offset = handle.tell() + try: + block_length, data = _load_bgzf_block(handle) + except StopIteration: + break + data_len = len(data) + yield start_offset, block_length, data_start, data_len + data_start += data_len + + +def _load_bgzf_block(handle, text_mode=False): + """Load the next BGZF block of compressed data (PRIVATE). + + Returns a tuple (block size and data), or at end of file + will raise StopIteration. + """ + magic = handle.read(4) + if not magic: + # End of file - should we signal this differently now? + # See https://www.python.org/dev/peps/pep-0479/ + raise StopIteration + if magic != _bgzf_magic: + raise ValueError( + r"A BGZF block should start with %r, not %r; handle.tell() now says %r" + % (_bgzf_magic, magic, handle.tell()) + ) + gzip_mod_time, gzip_extra_flags, gzip_os, extra_len = struct.unpack( + ">> from builtins import open + >>> handle = open("SamBam/ex1.bam", "rb") + >>> for values in BgzfBlocks(handle): + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) + Raw start 0, raw length 18239; data start 0, data length 65536 + Raw start 18239, raw length 18223; data start 65536, data length 65536 + Raw start 36462, raw length 18017; data start 131072, data length 65536 + Raw start 54479, raw length 17342; data start 196608, data length 65536 + Raw start 71821, raw length 17715; data start 262144, data length 65536 + Raw start 89536, raw length 17728; data start 327680, data length 65536 + Raw start 107264, raw length 17292; data start 393216, data length 63398 + Raw start 124556, raw length 28; data start 456614, data length 0 + >>> handle.close() + + Now let's see how to use this block information to jump to + specific parts of the decompressed BAM file: + + >>> handle = BgzfReader("SamBam/ex1.bam", "rb") + >>> assert 0 == handle.tell() + >>> magic = handle.read(4) + >>> assert 4 == handle.tell() + + So far nothing so strange, we got the magic marker used at the + start of a decompressed BAM file, and the handle position makes + sense. Now however, let's jump to the end of this block and 4 + bytes into the next block by reading 65536 bytes, + + >>> data = handle.read(65536) + >>> len(data) + 65536 + >>> assert 1195311108 == handle.tell() + + Expecting 4 + 65536 = 65540 were you? Well this is a BGZF 64-bit + virtual offset, which means: + + >>> split_virtual_offset(1195311108) + (18239, 4) + + You should spot 18239 as the start of the second BGZF block, while + the 4 is the offset into this block. See also make_virtual_offset, + + >>> make_virtual_offset(18239, 4) + 1195311108 + + Let's jump back to almost the start of the file, + + >>> make_virtual_offset(0, 2) + 2 + >>> handle.seek(2) + 2 + >>> handle.close() + + Note that you can use the max_cache argument to limit the number of + BGZF blocks cached in memory. The default is 100, and since each + block can be up to 64kb, the default cache could take up to 6MB of + RAM. The cache is not important for reading through the file in one + pass, but is important for improving performance of random access. + """ + + def __init__(self, filename=None, mode="r", fileobj=None, max_cache=100): + r"""Initialize the class for reading a BGZF file. + + You would typically use the top level ``bgzf.open(...)`` function + which will call this class internally. Direct use is discouraged. + + Either the ``filename`` (string) or ``fileobj`` (input file object in + binary mode) arguments must be supplied, but not both. + + Argument ``mode`` controls if the data will be returned as strings in + text mode ("rt", "tr", or default "r"), or bytes binary mode ("rb" + or "br"). The argument name matches the built-in ``open(...)`` and + standard library ``gzip.open(...)`` function. + + If text mode is requested, in order to avoid multi-byte characters, + this is hard coded to use the "latin1" encoding, and "\r" and "\n" + are passed as is (without implementing universal new line mode). There + is no ``encoding`` argument. + + If your data is in UTF-8 or any other incompatible encoding, you must + use binary mode, and decode the appropriate fragments yourself. + + Argument ``max_cache`` controls the maximum number of BGZF blocks to + cache in memory. Each can be up to 64kb thus the default of 100 blocks + could take up to 6MB of RAM. This is important for efficient random + access, a small value is fine for reading the file in one pass. + """ + # TODO - Assuming we can seek, check for 28 bytes EOF empty block + # and if missing warn about possible truncation (as in samtools)? + if max_cache < 1: + raise ValueError("Use max_cache with a minimum of 1") + # Must open the BGZF file in binary mode, but we may want to + # treat the contents as either text or binary (unicode or + # bytes under Python 3) + if filename and fileobj: + raise ValueError("Supply either filename or fileobj, not both") + # Want to reject output modes like w, a, x, + + if mode.lower() not in ("r", "tr", "rt", "rb", "br"): + raise ValueError( + "Must use a read mode like 'r' (default), 'rt', or 'rb' for binary" + ) + # If an open file was passed, make sure it was opened in binary mode. + if fileobj: + if fileobj.read(0) != b"": + raise ValueError("fileobj not opened in binary mode") + handle = fileobj + else: + handle = _open(filename, "rb") + self._text = "b" not in mode.lower() + if self._text: + self._newline = "\n" + else: + self._newline = b"\n" + self._handle = handle + self.max_cache = max_cache + self._buffers = {} + self._block_start_offset = None + self._block_raw_length = None + self._load_block(handle.tell()) + + def _load_block(self, start_offset=None): + if start_offset is None: + # If the file is being read sequentially, then _handle.tell() + # should be pointing at the start of the next block. + # However, if seek has been used, we can't assume that. + start_offset = self._block_start_offset + self._block_raw_length + if start_offset == self._block_start_offset: + self._within_block_offset = 0 + return + elif start_offset in self._buffers: + # Already in cache + self._buffer, self._block_raw_length = self._buffers[start_offset] + self._within_block_offset = 0 + self._block_start_offset = start_offset + return + # Must hit the disk... first check cache limits, + while len(self._buffers) >= self.max_cache: + # TODO - Implement LRU cache removal? + self._buffers.popitem() + # Now load the block + handle = self._handle + if start_offset is not None: + handle.seek(start_offset) + self._block_start_offset = handle.tell() + try: + block_size, self._buffer = _load_bgzf_block(handle, self._text) + except StopIteration: + # EOF + block_size = 0 + if self._text: + self._buffer = "" + else: + self._buffer = b"" + self._within_block_offset = 0 + self._block_raw_length = block_size + # Finally save the block in our cache, + self._buffers[self._block_start_offset] = self._buffer, block_size + + def tell(self): + """Return a 64-bit unsigned BGZF virtual offset.""" + if 0 < self._within_block_offset and self._within_block_offset == len( + self._buffer + ): + # Special case where we're right at the end of a (non empty) block. + # For non-maximal blocks could give two possible virtual offsets, + # but for a maximal block can't use 65536 as the within block + # offset. Therefore for consistency, use the next block and a + # within block offset of zero. + return (self._block_start_offset + self._block_raw_length) << 16 + else: + # return make_virtual_offset(self._block_start_offset, + # self._within_block_offset) + # TODO - Include bounds checking as in make_virtual_offset? + return (self._block_start_offset << 16) | self._within_block_offset + + def seek(self, virtual_offset): + """Seek to a 64-bit unsigned BGZF virtual offset.""" + # Do this inline to avoid a function call, + # start_offset, within_block = split_virtual_offset(virtual_offset) + start_offset = virtual_offset >> 16 + within_block = virtual_offset ^ (start_offset << 16) + if start_offset != self._block_start_offset: + # Don't need to load the block if already there + # (this avoids a function call since _load_block would do nothing) + self._load_block(start_offset) + if start_offset != self._block_start_offset: + raise ValueError("start_offset not loaded correctly") + if within_block > len(self._buffer): + if not (within_block == 0 and len(self._buffer) == 0): + raise ValueError( + "Within offset %i but block size only %i" + % (within_block, len(self._buffer)) + ) + self._within_block_offset = within_block + # assert virtual_offset == self.tell(), \ + # "Did seek to %i (%i, %i), but tell says %i (%i, %i)" \ + # % (virtual_offset, start_offset, within_block, + # self.tell(), self._block_start_offset, + # self._within_block_offset) + return virtual_offset + + def read(self, size=-1): + """Read method for the BGZF module.""" + if size < 0: + raise NotImplementedError("Don't be greedy, that could be massive!") + + result = "" if self._text else b"" + while size and self._block_raw_length: + if self._within_block_offset + size <= len(self._buffer): + # This may leave us right at the end of a block + # (lazy loading, don't load the next block unless we have too) + data = self._buffer[ + self._within_block_offset : self._within_block_offset + size + ] + self._within_block_offset += size + if not data: + raise ValueError("Must be at least 1 byte") + result += data + break + else: + data = self._buffer[self._within_block_offset :] + size -= len(data) + self._load_block() # will reset offsets + result += data + + return result + + def readline(self): + """Read a single line for the BGZF file.""" + result = "" if self._text else b"" + while self._block_raw_length: + i = self._buffer.find(self._newline, self._within_block_offset) + # Three cases to consider, + if i == -1: + # No newline, need to read in more data + data = self._buffer[self._within_block_offset :] + self._load_block() # will reset offsets + result += data + elif i + 1 == len(self._buffer): + # Found new line, but right at end of block (SPECIAL) + data = self._buffer[self._within_block_offset :] + # Must now load the next block to ensure tell() works + self._load_block() # will reset offsets + if not data: + raise ValueError("Must be at least 1 byte") + result += data + break + else: + # Found new line, not at end of block (easy case, no IO) + data = self._buffer[self._within_block_offset : i + 1] + self._within_block_offset = i + 1 + # assert data.endswith(self._newline) + result += data + break + + return result + + def __next__(self): + """Return the next line.""" + line = self.readline() + if not line: + raise StopIteration + return line + + def __iter__(self): + """Iterate over the lines in the BGZF file.""" + return self + + def close(self): + """Close BGZF file.""" + self._handle.close() + self._buffer = None + self._block_start_offset = None + self._buffers = None + + def seekable(self): + """Return True indicating the BGZF supports random access.""" + return True + + def isatty(self): + """Return True if connected to a TTY device.""" + return False + + def fileno(self): + """Return integer file descriptor.""" + return self._handle.fileno() + + def __enter__(self): + """Open a file operable with WITH statement.""" + return self + + def __exit__(self, type, value, traceback): + """Close a file with WITH statement.""" + self.close() + + +class BgzfWriter: + """Define a BGZFWriter object.""" + + def __init__(self, filename=None, mode="w", fileobj=None, compresslevel=6): + """Initialize the class.""" + if filename and fileobj: + raise ValueError("Supply either filename or fileobj, not both") + if fileobj: + # If an open file was passed, make sure it was opened in binary mode. + # This is a courtesy -- we can't detect mode for all file-like objects. + # Notably, `StringIO` does not have a `mode` attribute but plain files *do*. + if isinstance(fileobj, io.StringIO) or "b" not in getattr( + fileobj, "mode", "wb" + ): + raise ValueError("fileobj not opened in binary mode") + handle = fileobj + else: + if "w" not in mode.lower() and "a" not in mode.lower(): + raise ValueError(f"Must use write or append mode, not {mode!r}") + if "a" in mode.lower(): + handle = _open(filename, "ab") + else: + handle = _open(filename, "wb") + self._text = "b" not in mode.lower() + self._handle = handle + self._buffer = b"" + self.compresslevel = compresslevel + + def _write_block(self, block): + """Write provided data to file as a single BGZF compressed block (PRIVATE).""" + # print("Saving %i bytes" % len(block)) + if len(block) > 65536: + raise ValueError(f"{len(block)} Block length > 65536") + # Giving a negative window bits means no gzip/zlib headers, + # -15 used in samtools + c = zlib.compressobj( + self.compresslevel, zlib.DEFLATED, -15, zlib.DEF_MEM_LEVEL, 0 + ) + compressed = c.compress(block) + c.flush() + del c + if len(compressed) > 65536: + raise RuntimeError( + "TODO - Didn't compress enough, try less data in this block" + ) + crc = zlib.crc32(block) + # Should cope with a mix of Python platforms... + if crc < 0: + crc = struct.pack("= 65536: + self._write_block(self._buffer[:65536]) + self._buffer = self._buffer[65536:] + + def flush(self): + """Flush data explicitally.""" + while len(self._buffer) >= 65536: + self._write_block(self._buffer[:65535]) + self._buffer = self._buffer[65535:] + self._write_block(self._buffer) + self._buffer = b"" + self._handle.flush() + + def close(self): + """Flush data, write 28 bytes BGZF EOF marker, and close BGZF file. + + samtools will look for a magic EOF marker, just a 28 byte empty BGZF + block, and if it is missing warns the BAM file may be truncated. In + addition to samtools writing this block, so too does bgzip - so this + implementation does too. + """ + if self._buffer: + self.flush() + self._handle.write(_bgzf_eof) + self._handle.flush() + self._handle.close() + + def tell(self): + """Return a BGZF 64-bit virtual offset.""" + return make_virtual_offset(self._handle.tell(), len(self._buffer)) + + def seekable(self): + """Return True indicating the BGZF supports random access.""" + # Not seekable, but we do support tell... + return False + + def isatty(self): + """Return True if connected to a TTY device.""" + return False + + def fileno(self): + """Return integer file descriptor.""" + return self._handle.fileno() + + def __enter__(self): + """Open a file operable with WITH statement.""" + return self + + def __exit__(self, type, value, traceback): + """Close a file with WITH statement.""" + self.close() + + +if __name__ == "__main__": + if len(sys.argv) > 1: + print("Call this with no arguments and pipe uncompressed data in on stdin") + print("and it will produce BGZF compressed data on stdout. e.g.") + print("") + print("./bgzf.py < example.fastq > example.fastq.bgz") + print("") + print("The extension convention of *.bgz is to distinugish these from *.gz") + print("used for standard gzipped files without the block structure of BGZF.") + print("You can use the standard gunzip command to decompress BGZF files,") + print("if it complains about the extension try something like this:") + print("") + print("cat example.fastq.bgz | gunzip > example.fastq") + print("") + print("See also the tool bgzip that comes with samtools") + sys.exit(0) + + # Ensure we have binary mode handles + # (leave stderr as default text mode) + stdin = sys.stdin.buffer + stdout = sys.stdout.buffer + + sys.stderr.write("Producing BGZF output from stdin...\n") + w = BgzfWriter(fileobj=stdout) + while True: + data = stdin.read(65536) + w.write(data) + if not data: + break + # Doing close will write an empty BGZF block as EOF marker: + w.close() + sys.stderr.write("BGZF data produced\n") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/._codonalignment.py b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/._codonalignment.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/._codonalignment.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/._codonseq.py b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/._codonseq.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/._codonseq.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb416d772ceef3d2c329a1aeddcaa881b7031fcc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/__init__.py @@ -0,0 +1,808 @@ +# Copyright 2013 by Zheng Ruan (zruan1991@gmail.com). All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code for dealing with Codon Alignments.""" + +import warnings +from collections.abc import Iterable +from collections.abc import Mapping + +from Bio import BiopythonExperimentalWarning +from Bio import BiopythonWarning +from Bio.codonalign.codonalignment import CodonAlignment +from Bio.codonalign.codonalignment import mktest +from Bio.codonalign.codonseq import CodonSeq +from Bio.Data import CodonTable +from Bio.SeqRecord import SeqRecord + +warnings.warn( + "Bio.codonalign is an experimental module which may undergo " + "significant changes prior to its future official release.", + BiopythonExperimentalWarning, +) + + +def build( + pro_align, + nucl_seqs, + corr_dict=None, + gap_char="-", + unknown="X", + codon_table=None, + complete_protein=False, + anchor_len=10, + max_score=10, +): + """Build a codon alignment from protein alignment and corresponding nucleotides. + + Arguments: + - pro_align - a protein MultipleSeqAlignment object + - nucl_seqs - an object returned by SeqIO.parse or SeqIO.index + or a collection of SeqRecord. + - corr_dict - a dict that maps protein id to nucleotide id + - complete_protein - whether the sequence begins with a start + codon + + Return a CodonAlignment object. + + The example below answers this Biostars question: https://www.biostars.org/p/89741/ + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> from Bio.codonalign import build + >>> seq1 = SeqRecord(Seq('ATGTCTCGT'), id='pro1') + >>> seq2 = SeqRecord(Seq('ATGCGT'), id='pro2') + >>> pro1 = SeqRecord(Seq('MSR'), id='pro1') + >>> pro2 = SeqRecord(Seq('M-R'), id='pro2') + >>> aln = MultipleSeqAlignment([pro1, pro2]) + >>> codon_aln = build(aln, [seq1, seq2]) + >>> print(codon_aln) + CodonAlignment with 2 rows and 9 columns (3 codons) + ATGTCTCGT pro1 + ATG---CGT pro2 + + """ + # TODO + # add an option to allow the user to specify the returned object? + + from Bio.Align import MultipleSeqAlignment + + # check the type of object of pro_align + if not isinstance(pro_align, MultipleSeqAlignment): + raise TypeError("the first argument should be a MultipleSeqAlignment object") + # check whether the number of seqs in pro_align and nucl_seqs is + # the same + pro_num = len(pro_align) + if corr_dict is None: + try: + nucl_num = len(nucl_seqs) + except TypeError: + # nucl_seqs will be an iterator if returned by SeqIO.parse() + nucl_seqs = tuple(nucl_seqs) + nucl_num = len(nucl_seqs) + if pro_num > nucl_num: + raise ValueError( + f"Higher Number of SeqRecords in Protein Alignment ({pro_num}) " + f"than the Number of Nucleotide SeqRecords ({nucl_num}) are found!" + ) + + # Determine the protein sequences and nucl sequences + # correspondence. If nucl_seqs is a list, tuple or read by + # SeqIO.parse(), we assume the order of sequences in pro_align + # and nucl_seqs are the same. If nucl_seqs is a dict or read by + # SeqIO.index(), we match seqs in pro_align and those in + # nucl_seq by their id. + if isinstance(nucl_seqs, Mapping): + corr_method = 1 + elif isinstance(nucl_seqs, Iterable): + corr_method = 0 + else: + raise TypeError( + "Nucl Sequences Error, Unknown type to assign correspondence method" + ) + else: + if not isinstance(corr_dict, dict): + raise TypeError( + "corr_dict should be a dict that corresponds " + "protein id to nucleotide id!" + ) + if len(corr_dict) >= pro_num: + if isinstance(nucl_seqs, Mapping): + pass + else: + d = {} + for record in nucl_seqs: + key = record.id + if key in d: + raise ValueError(f"Duplicate key '{key}'") + d[key] = record + nucl_seqs = d + corr_method = 2 + else: + raise RuntimeError( + f"Number of items in corr_dict ({len(corr_dict)}) " + f"is less than number of protein records ({pro_num})" + ) + + # set up pro-nucl correspondence based on corr_method + # corr_method = 0, consecutive pairing + if corr_method == 0: + pro_nucl_pair = zip(pro_align, nucl_seqs) + # corr_method = 1, keyword pairing + elif corr_method == 1: + nucl_id = set(nucl_seqs.keys()) + pro_id = {i.id for i in pro_align} + # check if there is pro_id that does not have a nucleotide match + if pro_id - nucl_id: + diff = pro_id - nucl_id + raise ValueError( + f"Protein Record {', '.join(diff)} cannot find a " + "nucleotide sequence match, please check the id" + ) + else: + pro_nucl_pair = [] + for pro_rec in pro_align: + pro_nucl_pair.append((pro_rec, nucl_seqs[pro_rec.id])) + # corr_method = 2, dict pairing + elif corr_method == 2: + pro_nucl_pair = [] + for pro_rec in pro_align: + try: + nucl_id = corr_dict[pro_rec.id] + except KeyError: + print(f"Protein record ({pro_rec.id}) is not in corr_dict!") + exit(1) + pro_nucl_pair.append((pro_rec, nucl_seqs[nucl_id])) + + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + + codon_aln = [] + shift = False + for pair in pro_nucl_pair: + # Beware that the following span corresponds to an ungapped + # nucleotide sequence. + corr_span = _check_corr( + pair[0], + pair[1], + gap_char=gap_char, + codon_table=codon_table, + complete_protein=complete_protein, + anchor_len=anchor_len, + ) + if not corr_span: + raise ValueError( + f"Protein Record {pair[0].id} and " + f"Nucleotide Record {pair[1].id} do not match!" + ) + else: + codon_rec = _get_codon_rec( + pair[0], + pair[1], + corr_span, + gap_char=gap_char, + complete_protein=complete_protein, + codon_table=codon_table, + max_score=max_score, + ) + codon_aln.append(codon_rec) + if corr_span[1] == 2: + shift = True + if shift: + return CodonAlignment(_align_shift_recs(codon_aln)) + else: + return CodonAlignment(codon_aln) + + +def _codons2re(codons): + """Generate regular expression based on a given list of codons (PRIVATE).""" + reg = "" + for i in zip(*codons): + if len(set(i)) == 1: + reg += "".join(set(i)) + else: + reg += "[" + "".join(set(i)) + "]" + return reg + + +def _get_aa_regex(codon_table, stop="*", unknown="X"): + """Set up the regular expression of a given CodonTable (PRIVATE). + + >>> from Bio.Data.CodonTable import generic_by_id + >>> p = generic_by_id[1] + >>> t = _get_aa_regex(p) + >>> print(t['A'][0]) + G + >>> print(t['A'][1]) + C + >>> print(sorted(list(t['A'][2:]))) + ['A', 'C', 'G', 'T', 'U', '[', ']'] + >>> print(sorted(list(t['L'][:5]))) + ['C', 'T', 'U', '[', ']'] + >>> print(sorted(list(t['L'][5:9]))) + ['T', 'U', '[', ']'] + >>> print(sorted(list(t['L'][9:]))) + ['A', 'C', 'G', 'T', 'U', '[', ']'] + + """ + from Bio.Data.CodonTable import CodonTable + + if not isinstance(codon_table, CodonTable): + raise TypeError("Input table is not a instance of Bio.Data.CodonTable object") + aa2codon = {} + for codon, aa in codon_table.forward_table.items(): + aa2codon.setdefault(aa, []).append(codon) + for aa, codons in aa2codon.items(): + aa2codon[aa] = _codons2re(codons) + aa2codon[stop] = _codons2re(codon_table.stop_codons) + aa2codon[unknown] = "..." + return aa2codon + + +def _check_corr( + pro, nucl, gap_char, codon_table, complete_protein=False, anchor_len=10 +): + """Check if the nucleotide can be translated into the protein (PRIVATE). + + Expects two SeqRecord objects. + """ + import re + + if not isinstance(pro, SeqRecord) or not isinstance(nucl, SeqRecord): + raise TypeError( + "_check_corr accepts two SeqRecord object. Please check your input." + ) + + aa2re = _get_aa_regex(codon_table) + pro_re = "" + for aa in pro.seq: + if aa != gap_char: + pro_re += aa2re[aa] + + nucl_seq = str(nucl.seq.upper().replace(gap_char, "")) + match = re.search(pro_re, nucl_seq) + if match: + # mode = 0, direct match + return (match.span(), 0) + else: + # Might caused by mismatches or frameshift, using anchors to + # have a try + # anchor_len = 10 # adjust this value to test performance + pro_seq = str(pro.seq).replace(gap_char, "") + anchors = [ + pro_seq[i : (i + anchor_len)] for i in range(0, len(pro_seq), anchor_len) + ] + # if the last anchor is less than the specified anchor + # size, we combine the penultimate and the last anchor + # together as the last one. + # TODO: modify this to deal with short sequence with only + # one anchor. + if len(anchors[-1]) < anchor_len: + anchors[-1] = anchors[-2] + anchors[-1] + + pro_re = [] + anchor_distance = 0 + anchor_pos = [] + for i, anchor in enumerate(anchors): + this_anchor_len = len(anchor) + qcodon = "" + fncodon = "" + # dirty code to deal with the last anchor + # as the last anchor is combined in the steps + # above, we need to get the true last anchor to + # pro_re + if this_anchor_len == anchor_len: + for aa in anchor: + if complete_protein and i == 0: + qcodon += _codons2re(codon_table.start_codons) + fncodon += aa2re["X"] + continue + qcodon += aa2re[aa] + fncodon += aa2re["X"] + match = re.search(qcodon, nucl_seq) + elif this_anchor_len > anchor_len: + last_qcodon = "" + last_fcodon = "" + for j in range(anchor_len, len(anchor)): + last_qcodon += aa2re[anchor[j]] + last_fcodon += aa2re["X"] + match = re.search(last_qcodon, nucl_seq) + # build full_pro_re from anchors + if match: + anchor_pos.append((match.start(), match.end(), i)) + if this_anchor_len == anchor_len: + pro_re.append(qcodon) + else: + pro_re.append(last_qcodon) + else: + if this_anchor_len == anchor_len: + pro_re.append(fncodon) + else: + pro_re.append(last_fcodon) + full_pro_re = "".join(pro_re) + match = re.search(full_pro_re, nucl_seq) + if match: + # mode = 1, mismatch + return (match.span(), 1) + else: + # check frames of anchors + # ten frameshift events are allowed in a sequence + first_anchor = True + shift_id_pos = 0 + # check the first anchor + if first_anchor and anchor_pos[0][2] != 0: + shift_val_lst = [1, 2, 3 * anchor_len - 2, 3 * anchor_len - 1, 0] + sh_anc = anchors[0] + for shift_val in shift_val_lst: + if shift_val == 0: + qcodon = None + break + if shift_val in (1, 2): + sh_nuc_len = anchor_len * 3 + shift_val + elif shift_val in (3 * anchor_len - 2, 3 * anchor_len - 1): + sh_nuc_len = anchor_len * 3 - (3 * anchor_len - shift_val) + if anchor_pos[0][0] >= sh_nuc_len: + sh_nuc = nucl_seq[ + anchor_pos[0][0] - sh_nuc_len : anchor_pos[0][0] + ] + else: + # this is unlikely to produce the correct output + sh_nuc = nucl_seq[: anchor_pos[0][0]] + qcodon, shift_id_pos = _get_shift_anchor_re( + sh_anc, sh_nuc, shift_val, aa2re, anchor_len, shift_id_pos + ) + if qcodon is not None and qcodon != -1: + # pro_re[0] should be '.'*anchor_len, therefore I + # replace it. + pro_re[0] = qcodon + break + if qcodon == -1: + warnings.warn( + f"first frameshift detection failed for {nucl.id}", + BiopythonWarning, + ) + # check anchors in the middle + for i in range(len(anchor_pos) - 1): + shift_val = (anchor_pos[i + 1][0] - anchor_pos[i][0]) % (3 * anchor_len) + sh_anc = "".join(anchors[anchor_pos[i][2] : anchor_pos[i + 1][2]]) + sh_nuc = nucl_seq[anchor_pos[i][0] : anchor_pos[i + 1][0]] + qcodon = None + if shift_val != 0: + qcodon, shift_id_pos = _get_shift_anchor_re( + sh_anc, sh_nuc, shift_val, aa2re, anchor_len, shift_id_pos + ) + if qcodon is not None and qcodon != -1: + pro_re[anchor_pos[i][2] : anchor_pos[i + 1][2]] = [qcodon] + qcodon = None + elif qcodon == -1: + warnings.warn( + f"middle frameshift detection failed for {nucl.id}", + BiopythonWarning, + ) + # check the last anchor + if anchor_pos[-1][2] + 1 == len(anchors) - 1: + sh_anc = anchors[-1] + this_anchor_len = len(sh_anc) + shift_val_lst = [ + 1, + 2, + 3 * this_anchor_len - 2, + 3 * this_anchor_len - 1, + 0, + ] + for shift_val in shift_val_lst: + if shift_val == 0: + qcodon = None + break + if shift_val in (1, 2): + sh_nuc_len = this_anchor_len * 3 + shift_val + elif shift_val in ( + 3 * this_anchor_len - 2, + 3 * this_anchor_len - 1, + ): + sh_nuc_len = this_anchor_len * 3 - ( + 3 * this_anchor_len - shift_val + ) + if len(nucl_seq) - anchor_pos[-1][0] >= sh_nuc_len: + sh_nuc = nucl_seq[ + anchor_pos[-1][0] : anchor_pos[-1][0] + sh_nuc_len + ] + else: + # this is unlikely to produce the correct output + sh_nuc = nucl_seq[anchor_pos[-1][0] :] + qcodon, shift_id_pos = _get_shift_anchor_re( + sh_anc, sh_nuc, shift_val, aa2re, this_anchor_len, shift_id_pos + ) + if qcodon is not None and qcodon != -1: + pro_re.pop() + pro_re[-1] = qcodon + break + if qcodon == -1: + warnings.warn( + f"last frameshift detection failed for {nucl.id}", + BiopythonWarning, + ) + # try global match + full_pro_re = "".join(pro_re) + match = re.search(full_pro_re, nucl_seq) + if match: + return (match.span(), 2, match) + else: + raise RuntimeError( + f"Protein SeqRecord ({pro.id}) and " + f"Nucleotide SeqRecord ({nucl.id}) do not match!" + ) + + +def _get_shift_anchor_re(sh_anc, sh_nuc, shift_val, aa2re, anchor_len, shift_id_pos): + """Find a regular expression matching a potentially shifted anchor (PRIVATE). + + Arguments: + - sh_anc - shifted anchor sequence + - sh_nuc - potentially corresponding nucleotide sequence + of sh_anc + - shift_val - 1 or 2 indicates forward frame shift, whereas + 3*anchor_len-1 or 3*anchor_len-2 indicates + backward shift + - aa2re - aa to codon re dict + - anchor_len - length of the anchor + - shift_id_pos - specify current shift name we are at + + """ + import re + + shift_id = [chr(i) for i in range(97, 107)] + if 0 < shift_val < 3 * anchor_len - 2: + # if shift_val in (1, 2): + for j in range(len(sh_anc)): + qcodon = "^" + for k, aa in enumerate(sh_anc): + if k == j: + qcodon += aa2re[aa] + "(?P<" + shift_id[shift_id_pos] + ">..*)" + else: + qcodon += aa2re[aa] + qcodon += "$" + match = re.search(qcodon, sh_nuc) + if match: + qcodon = qcodon.replace("^", "").replace("$", "") + shift_id_pos += 1 + return qcodon, shift_id_pos + if not match: + # failed to find a match (frameshift) + return -1, shift_id_pos + elif shift_val in (3 * anchor_len - 1, 3 * anchor_len - 2): + shift_val = 3 * anchor_len - shift_val + # obtain shifted anchor and corresponding nucl + # first check if the shifted pos is just at the end of the + # previous anchor. + for j in range(1, len(sh_anc)): + qcodon = "^" + for k, aa in enumerate(sh_anc): + if k == j - 1: + # will be considered in the next step + pass + elif k == j: + qcodon += _merge_aa2re( + sh_anc[j - 1], + sh_anc[j], + shift_val, + aa2re, + shift_id[shift_id_pos].upper(), + ) + else: + qcodon += aa2re[aa] + qcodon += "$" + match = re.search(qcodon, sh_nuc) + if match: + qcodon = qcodon.replace("^", "").replace("$", "") + shift_id_pos += 1 + return qcodon, shift_id_pos + if not match: + # failed to find a match (frameshift) + return -1, shift_id_pos + + +def _merge_aa2re(aa1, aa2, shift_val, aa2re, reid): + """Merge two amino acids based on detected frame shift value (PRIVATE).""" + + def get_aa_from_codonre(re_aa): + aas = [] + m = 0 + for i in re_aa: + if i == "[": + m = -1 + aas.append("") + elif i == "]": + m = 0 + continue + elif m == -1: + aas[-1] = aas[-1] + i + elif m == 0: + aas.append(i) + return aas + + scodon = list(map(get_aa_from_codonre, (aa2re[aa1], aa2re[aa2]))) + if shift_val == 1: + intersect = "".join(set(scodon[0][2]) & set(scodon[1][0])) + scodonre = "(?P<" + reid + ">" + scodonre += ( + "[" + + scodon[0][0] + + "]" + + "[" + + scodon[0][1] + + "]" + + "[" + + intersect + + "]" + + "[" + + scodon[1][1] + + "]" + + "[" + + scodon[1][2] + + "]" + ) + elif shift_val == 2: + intersect1 = "".join(set(scodon[0][1]) & set(scodon[1][0])) + intersect2 = "".join(set(scodon[0][2]) & set(scodon[1][1])) + scodonre = "(?P<" + reid + ">" + scodonre += ( + "[" + + scodon[0][0] + + "]" + + "[" + + intersect1 + + "]" + + "[" + + intersect2 + + "]" + + "[" + + scodon[1][2] + + "]" + ) + scodonre += ")" + return scodonre + + +def _get_codon_rec( + pro, nucl, span_mode, gap_char, codon_table, complete_protein=False, max_score=10 +): + """Generate codon alignment based on regular re match (PRIVATE). + + span_mode is a tuple returned by _check_corr. The first element + is the span of a re search, and the second element is the mode + for the match. + + mode + - 0: direct match + - 1: mismatch (no indels) + - 2: frameshift + + """ + import re + + from Bio.Seq import Seq + + nucl_seq = nucl.seq.replace(gap_char, "") + span = span_mode[0] + mode = span_mode[1] + aa2re = _get_aa_regex(codon_table) + if mode in (0, 1): + if len(pro.seq.replace(gap_char, "")) * 3 != (span[1] - span[0]): + raise ValueError( + f"Protein Record {pro.id} and Nucleotide Record {nucl.id} do not match!" + ) + aa_num = 0 + codon_seq = CodonSeq() + for aa in pro.seq: + if aa == "-": + codon_seq += "---" + elif complete_protein and aa_num == 0: + this_codon = nucl_seq[span[0] : span[0] + 3] + if not re.search( + _codons2re(codon_table.start_codons), str(this_codon.upper()) + ): + max_score -= 1 + warnings.warn( + f"start codon of {pro.id} ({aa} {aa_num}) does not " + f"correspond to {nucl.id} ({this_codon})", + BiopythonWarning, + ) + if max_score == 0: + raise RuntimeError( + f"max_score reached for {nucl.id}! Please raise up " + "the tolerance to get an alignment in anyway" + ) + codon_seq += this_codon + aa_num += 1 + else: + this_codon = nucl_seq[span[0] + 3 * aa_num : span[0] + 3 * (aa_num + 1)] + if this_codon.upper().translate(table=codon_table) != aa: + max_score -= 1 + warnings.warn( + "%s(%s %d) does not correspond to %s(%s)" + % (pro.id, aa, aa_num, nucl.id, this_codon), + BiopythonWarning, + ) + if max_score == 0: + raise RuntimeError( + f"max_score reached for {nucl.id}! Please raise up " + "the tolerance to get an alignment in anyway" + ) + codon_seq += this_codon + aa_num += 1 + return SeqRecord(codon_seq, id=nucl.id) + elif mode == 2: + from collections import deque + + shift_pos = deque([]) + shift_start = [] + match = span_mode[2] + m_groupdict = list(match.groupdict().keys()) + # backward frameshift + for i in m_groupdict: + shift_pos.append(match.span(i)) + shift_start.append(match.start(i)) + rf_table = [] + i = match.start() + while True: + rf_table.append(i) + i += 3 + if i in shift_start and m_groupdict[shift_start.index(i)].isupper(): + shift_index = shift_start.index(i) + shift_val = 6 - (shift_pos[shift_index][1] - shift_pos[shift_index][0]) + rf_table.append(i) + rf_table.append(i + 3 - shift_val) + i = shift_pos[shift_index][1] + elif i in shift_start and m_groupdict[shift_start.index(i)].islower(): + i = shift_pos[shift_start.index(i)][1] + if i >= match.end(): + break + codon_seq = CodonSeq() + aa_num = 0 + for aa in pro.seq: + if aa == "-": + codon_seq += "---" + elif complete_protein and aa_num == 0: + this_codon = nucl_seq[rf_table[0] : rf_table[0] + 3] + if not re.search( + _codons2re(codon_table.start_codons), str(this_codon.upper()) + ): + max_score -= 1 + warnings.warn( + f"start codon of {pro.id}({aa} {aa_num}) does not " + f"correspond to {nucl.id}({this_codon})", + BiopythonWarning, + ) + codon_seq += this_codon + aa_num += 1 + else: + if ( + aa_num < len(pro.seq.replace("-", "")) - 1 + and rf_table[aa_num + 1] - rf_table[aa_num] - 3 < 0 + ): + max_score -= 1 + start = rf_table[aa_num] + end = start + (3 - shift_val) + ngap = shift_val + this_codon = nucl_seq[start:end] + "-" * ngap + elif rf_table[aa_num] - rf_table[aa_num - 1] - 3 > 0: + max_score -= 1 + start = rf_table[aa_num - 1] + 3 + end = rf_table[aa_num] + ngap = 3 - (rf_table[aa_num] - rf_table[aa_num - 1] - 3) + this_codon = ( + nucl_seq[start:end] + + "-" * ngap + + nucl_seq[rf_table[aa_num] : rf_table[aa_num] + 3] + ) + else: + start = rf_table[aa_num] + end = start + 3 + this_codon = nucl_seq[start:end] + if this_codon.upper().translate(table=codon_table) != aa: + max_score -= 1 + warnings.warn( + f"Codon of {pro.id}({aa} {aa_num}) does not " + f"correspond to {nucl.id}({this_codon})", + BiopythonWarning, + ) + if max_score == 0: + raise RuntimeError( + f"max_score reached for {nucl.id}! Please raise up " + "the tolerance to get an alignment in anyway" + ) + codon_seq += this_codon + aa_num += 1 + codon_seq.rf_table = rf_table + return SeqRecord(codon_seq, id=nucl.id) + + +def _align_shift_recs(recs): + """Build alignment according to the frameshift detected by _check_corr (PRIVATE). + + Argument: + - recs - a list of SeqRecords containing a CodonSeq dictated + by a rf_table (with frameshift in some of them). + + """ + + def find_next_int(k, lst): + idx = lst.index(k) + p = 0 + while True: + if isinstance(lst[idx + p], int): + return lst[idx + p], p + p += 1 + + full_rf_table_lst = [rec.seq.get_full_rf_table() for rec in recs] + rf_num = [0] * len(recs) + for k, rec in enumerate(recs): + for i in rec.seq.get_full_rf_table(): + if isinstance(i, int): + rf_num[k] += 1 + # isinstance(i, float) should be True + elif rec.seq[int(i) : int(i) + 3] == "---": + rf_num[k] += 1 + if len(set(rf_num)) != 1: + raise RuntimeError("Number of alignable codons unequal in given records") + i = 0 + rec_num = len(recs) + while True: + add_lst = [] + try: + col_rf_lst = [k[i] for k in full_rf_table_lst] + except IndexError: + # we probably reached the last codon + break + for j, k in enumerate(col_rf_lst): + add_lst.append((j, int(k))) + if isinstance(k, float) and recs[j].seq[int(k) : int(k) + 3] != "---": + m, p = find_next_int(k, full_rf_table_lst[j]) + if (m - k) % 3 != 0: + gap_num = 3 - (m - k) % 3 + else: + gap_num = 0 + if gap_num != 0: + gaps = "-" * int(gap_num) + seq = CodonSeq(rf_table=recs[j].seq.rf_table) + seq += recs[j].seq[: int(k)] + gaps + recs[j].seq[int(k) :] + full_rf_table = full_rf_table_lst[j] + bp = full_rf_table.index(k) + full_rf_table = full_rf_table[:bp] + [ + v + int(gap_num) for v in full_rf_table[bp + 1 :] + ] + full_rf_table_lst[j] = full_rf_table + recs[j].seq = seq + add_lst.pop() + gap_num += m - k + i += p - 1 + if len(add_lst) != rec_num: + for j, k in add_lst: + seq = CodonSeq(rf_table=recs[j].seq.rf_table) + gaps = "-" * int(gap_num) + seq += recs[j].seq[: int(k)] + gaps + recs[j].seq[int(k) :] + full_rf_table = full_rf_table_lst[j] + bp = full_rf_table.index(k) + inter_rf = [] + for t in range(0, len(gaps), 3): + inter_rf.append(k + t + 3.0) + full_rf_table = ( + full_rf_table[:bp] + + inter_rf + + [v + int(gap_num) for v in full_rf_table[bp:]] + ) + full_rf_table_lst[j] = full_rf_table + recs[j].seq = seq + i += 1 + return recs + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/codonalignment.py b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/codonalignment.py new file mode 100644 index 0000000000000000000000000000000000000000..9b2d38de867e45f0fe00b5199110540a329062e4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/codonalignment.py @@ -0,0 +1,517 @@ +# Copyright 2013 by Zheng Ruan (zruan1991@gmail.com). All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code for dealing with Codon Alignment. + +CodonAlignment class is inherited from MultipleSeqAlignment class. This is +the core class to deal with codon alignment in biopython. +""" + +import warnings +from math import erfc +from math import sqrt + +from Bio import BiopythonWarning +from Bio.Align import MultipleSeqAlignment +from Bio.codonalign.codonseq import _get_codon_list +from Bio.codonalign.codonseq import cal_dn_ds +from Bio.codonalign.codonseq import CodonSeq +from Bio.Data import CodonTable +from Bio.SeqRecord import SeqRecord + + +class CodonAlignment(MultipleSeqAlignment): + """Codon Alignment class that inherits from MultipleSeqAlignment. + + >>> from Bio.SeqRecord import SeqRecord + >>> a = SeqRecord(CodonSeq("AAAACGTCG"), id="Alpha") + >>> b = SeqRecord(CodonSeq("AAA---TCG"), id="Beta") + >>> c = SeqRecord(CodonSeq("AAAAGGTGG"), id="Gamma") + >>> print(CodonAlignment([a, b, c])) + CodonAlignment with 3 rows and 9 columns (3 codons) + AAAACGTCG Alpha + AAA---TCG Beta + AAAAGGTGG Gamma + + """ + + def __init__(self, records="", name=None): + """Initialize the class.""" + MultipleSeqAlignment.__init__(self, records) + + # check the type of the alignment to be nucleotide + for rec in self: + if not isinstance(rec.seq, CodonSeq): + raise TypeError( + "CodonSeq objects are expected in each SeqRecord in CodonAlignment" + ) + + if self.get_alignment_length() % 3 != 0: + raise ValueError( + "Alignment length is not a multiple of " + "three (i.e. a whole number of codons)" + ) + + def __str__(self): + """Return a multi-line string summary of the alignment. + + This output is indicated to be readable, but large alignment + is shown truncated. A maximum of 20 rows (sequences) and + 60 columns (20 codons) are shown, with the record identifiers. + This should fit nicely on a single screen. e.g. + + """ + rows = len(self._records) + lines = [ + "CodonAlignment with %i rows and %i columns (%i codons)" + % (rows, self.get_alignment_length(), self.get_aln_length()) + ] + + if rows <= 60: + lines.extend([self._str_line(rec, length=60) for rec in self._records]) + else: + lines.extend([self._str_line(rec, length=60) for rec in self._records[:18]]) + lines.append("...") + lines.append(self._str_line(self._records[-1], length=60)) + return "\n".join(lines) + + def __getitem__(self, index): + """Return a CodonAlignment object for single indexing.""" + if isinstance(index, int): + return self._records[index] + elif isinstance(index, slice): + return CodonAlignment(self._records[index]) + elif len(index) != 2: + raise TypeError("Invalid index type.") + # Handle double indexing + row_index, col_index = index + if isinstance(row_index, int): + return self._records[row_index][col_index] + elif isinstance(col_index, int): + return "".join(str(rec[col_index]) for rec in self._records[row_index]) + else: + return MultipleSeqAlignment( + rec[col_index] for rec in self._records[row_index] + ) + + def __add__(self, other): + """Combine two codonalignments with the same number of rows by adding them. + + The method also allows to combine a CodonAlignment object with a + MultipleSeqAlignment object. The following rules apply: + + * CodonAlignment + CodonAlignment -> CodonAlignment + * CodonAlignment + MultipleSeqAlignment -> MultipleSeqAlignment + """ + if isinstance(other, CodonAlignment): + if len(self) != len(other): + raise ValueError( + "When adding two alignments they must have the same length" + " (i.e. same number or rows)" + ) + warnings.warn( + "Please make sure the two CodonAlignment objects are sharing the same codon table. This is not checked by Biopython.", + BiopythonWarning, + ) + merged = ( + SeqRecord(seq=CodonSeq(left.seq + right.seq)) + for left, right in zip(self, other) + ) + return CodonAlignment(merged) + elif isinstance(other, MultipleSeqAlignment): + if len(self) != len(other): + raise ValueError( + "When adding two alignments they must have the same length" + " (i.e. same number or rows)" + ) + return self.toMultipleSeqAlignment() + other + else: + raise TypeError( + "Only CodonAlignment or MultipleSeqAlignment object can be" + f" added with a CodonAlignment object. {object(other)} detected." + ) + + def get_aln_length(self): + """Get alignment length.""" + return self.get_alignment_length() // 3 + + def toMultipleSeqAlignment(self): + """Convert the CodonAlignment to a MultipleSeqAlignment. + + Return a MultipleSeqAlignment containing all the + SeqRecord in the CodonAlignment using Seq to store + sequences + """ + alignments = [SeqRecord(rec.seq.toSeq(), id=rec.id) for rec in self._records] + return MultipleSeqAlignment(alignments) + + def get_dn_ds_matrix(self, method="NG86", codon_table=None): + """Available methods include NG86, LWL85, YN00 and ML. + + Argument: + - method - Available methods include NG86, LWL85, YN00 and ML. + - codon_table - Codon table to use for forward translation. + + """ + from Bio.Phylo.TreeConstruction import DistanceMatrix as DM + + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + names = [i.id for i in self._records] + size = len(self._records) + dn_matrix = [] + ds_matrix = [] + for i in range(size): + dn_matrix.append([]) + ds_matrix.append([]) + for j in range(i + 1): + if i != j: + dn, ds = cal_dn_ds( + self._records[i], + self._records[j], + method=method, + codon_table=codon_table, + ) + dn_matrix[i].append(dn) + ds_matrix[i].append(ds) + else: + dn_matrix[i].append(0.0) + ds_matrix[i].append(0.0) + dn_dm = DM(names, matrix=dn_matrix) + ds_dm = DM(names, matrix=ds_matrix) + return dn_dm, ds_dm + + def get_dn_ds_tree( + self, dn_ds_method="NG86", tree_method="UPGMA", codon_table=None + ): + """Construct dn tree and ds tree. + + Argument: + - dn_ds_method - Available methods include NG86, LWL85, YN00 and ML. + - tree_method - Available methods include UPGMA and NJ. + + """ + from Bio.Phylo.TreeConstruction import DistanceTreeConstructor + + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + dn_dm, ds_dm = self.get_dn_ds_matrix( + method=dn_ds_method, codon_table=codon_table + ) + dn_constructor = DistanceTreeConstructor() + ds_constructor = DistanceTreeConstructor() + if tree_method == "UPGMA": + dn_tree = dn_constructor.upgma(dn_dm) + ds_tree = ds_constructor.upgma(ds_dm) + elif tree_method == "NJ": + dn_tree = dn_constructor.nj(dn_dm) + ds_tree = ds_constructor.nj(ds_dm) + else: + raise RuntimeError( + f"Unknown tree method ({tree_method}). Only NJ and UPGMA are accepted." + ) + return dn_tree, ds_tree + + @classmethod + def from_msa(cls, align): + """Convert a MultipleSeqAlignment to CodonAlignment. + + Function to convert a MultipleSeqAlignment to CodonAlignment. + It is the user's responsibility to ensure all the requirement + needed by CodonAlignment is met. + """ + rec = [SeqRecord(CodonSeq(str(i.seq)), id=i.id) for i in align._records] + return cls(rec) + + +def mktest(codon_alns, codon_table=None, alpha=0.05): + """McDonald-Kreitman test for neutrality. + + Implement the McDonald-Kreitman test for neutrality (PMID: 1904993) + This method counts changes rather than sites + (http://mkt.uab.es/mkt/help_mkt.asp). + + Arguments: + - codon_alns - list of CodonAlignment to compare (each + CodonAlignment object corresponds to gene sampled from a species) + + Return the p-value of test result. + """ + import copy + + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + if not all(isinstance(i, CodonAlignment) for i in codon_alns): + raise TypeError("mktest accepts CodonAlignment list.") + codon_aln_len = [i.get_alignment_length() for i in codon_alns] + if len(set(codon_aln_len)) != 1: + raise RuntimeError( + "CodonAlignment object for mktest should be of equal length." + ) + codon_num = codon_aln_len[0] // 3 + # prepare codon_dict (taking stop codon as an extra amino acid) + codon_dict = copy.deepcopy(codon_table.forward_table) + for stop in codon_table.stop_codons: + codon_dict[stop] = "stop" + # prepare codon_lst + codon_lst = [] + for codon_aln in codon_alns: + codon_lst.append([]) + for i in codon_aln: + codon_lst[-1].append(_get_codon_list(i.seq)) + codon_set = [] + for i in range(codon_num): + uniq_codons = [] + for j in codon_lst: + uniq_codon = {k[i] for k in j} + uniq_codons.append(uniq_codon) + codon_set.append(uniq_codons) + syn_fix, nonsyn_fix, syn_poly, nonsyn_poly = 0, 0, 0, 0 + G, nonsyn_G = _get_codon2codon_matrix(codon_table=codon_table) + for i in codon_set: + all_codon = i[0].union(*i[1:]) + if "-" in all_codon or len(all_codon) == 1: + continue + fix_or_not = all(len(k) == 1 for k in i) + if fix_or_not: + # fixed + nonsyn_subgraph = _get_subgraph(all_codon, nonsyn_G) + subgraph = _get_subgraph(all_codon, G) + this_non = _count_replacement(all_codon, nonsyn_subgraph) + this_syn = _count_replacement(all_codon, subgraph) - this_non + nonsyn_fix += this_non + syn_fix += this_syn + else: + # not fixed + nonsyn_subgraph = _get_subgraph(all_codon, nonsyn_G) + subgraph = _get_subgraph(all_codon, G) + this_non = _count_replacement(all_codon, nonsyn_subgraph) + this_syn = _count_replacement(all_codon, subgraph) - this_non + nonsyn_poly += this_non + syn_poly += this_syn + return _G_test([syn_fix, nonsyn_fix, syn_poly, nonsyn_poly]) + + +def _get_codon2codon_matrix(codon_table): + """Get codon codon substitution matrix (PRIVATE). + + Elements in the matrix are number of synonymous and nonsynonymous + substitutions required for the substitution. + """ + import copy + + base_tuple = ("A", "T", "C", "G") + codons = [ + i + for i in list(codon_table.forward_table.keys()) + codon_table.stop_codons + if "U" not in i + ] + # set up codon_dict considering stop codons + codon_dict = copy.deepcopy(codon_table.forward_table) + for stop in codon_table.stop_codons: + codon_dict[stop] = "stop" + # count site + num = len(codons) + G = {} # graph for substitution + nonsyn_G = {} # graph for nonsynonymous substitution + graph = {} + graph_nonsyn = {} + for i, codon in enumerate(codons): + graph[codon] = {} + graph_nonsyn[codon] = {} + for p, b in enumerate(codon): + for j in base_tuple: + tmp_codon = codon[0:p] + j + codon[p + 1 :] + if codon_dict[codon] != codon_dict[tmp_codon]: + graph_nonsyn[codon][tmp_codon] = 1 + graph[codon][tmp_codon] = 1 + else: + if codon != tmp_codon: + graph_nonsyn[codon][tmp_codon] = 0.1 + graph[codon][tmp_codon] = 1 + for codon1 in codons: + nonsyn_G[codon1] = {} + G[codon1] = {} + for codon2 in codons: + if codon1 == codon2: + nonsyn_G[codon1][codon2] = 0 + G[codon1][codon2] = 0 + else: + nonsyn_G[codon1][codon2] = _dijkstra(graph_nonsyn, codon1, codon2) + G[codon1][codon2] = _dijkstra(graph, codon1, codon2) + return G, nonsyn_G + + +def _dijkstra(graph, start, end): + """Dijkstra's algorithm Python implementation (PRIVATE). + + Algorithm adapted from + http://thomas.pelletier.im/2010/02/dijkstras-algorithm-python-implementation/. + However, an obvious bug in:: + + if D[child_node] >(<) D[node] + child_value: + + is fixed. + This function will return the distance between start and end. + + Arguments: + - graph: Dictionary of dictionary (keys are vertices). + - start: Start vertex. + - end: End vertex. + + Output: + List of vertices from the beginning to the end. + + """ + D = {} # Final distances dict + P = {} # Predecessor dict + # Fill the dicts with default values + for node in graph.keys(): + D[node] = 100 # Vertices are unreachable + P[node] = "" # Vertices have no predecessors + D[start] = 0 # The start vertex needs no move + unseen_nodes = list(graph.keys()) # All nodes are unseen + while len(unseen_nodes) > 0: + # Select the node with the lowest value in D (final distance) + shortest = None + node = "" + for temp_node in unseen_nodes: + if shortest is None: + shortest = D[temp_node] + node = temp_node + elif D[temp_node] < shortest: + shortest = D[temp_node] + node = temp_node + # Remove the selected node from unseen_nodes + unseen_nodes.remove(node) + # For each child (ie: connected vertex) of the current node + for child_node, child_value in graph[node].items(): + if D[child_node] > D[node] + child_value: + D[child_node] = D[node] + child_value + # To go to child_node, you have to go through node + P[child_node] = node + if node == end: + break + # Set a clean path + path = [] + # We begin from the end + node = end + distance = 0 + # While we are not arrived at the beginning + while node != start: + if path.count(node) == 0: + path.insert(0, node) # Insert the predecessor of the current node + node = P[node] # The current node becomes its predecessor + else: + break + path.insert(0, start) # Finally, insert the start vertex + for i in range(len(path) - 1): + distance += graph[path[i]][path[i + 1]] + return distance + + +def _count_replacement(codon_set, G): + """Count replacement needed for a given codon_set (PRIVATE).""" + from math import floor + + if len(codon_set) == 1: + return 0, 0 + elif len(codon_set) == 2: + codons = list(codon_set) + return floor(G[codons[0]][codons[1]]) + else: + codons = list(codon_set) + return _prim(G) + + +def _prim(G): + """Prim's algorithm to find minimum spanning tree (PRIVATE). + + Code is adapted from + http://programmingpraxis.com/2010/04/09/minimum-spanning-tree-prims-algorithm/ + """ + from collections import defaultdict + from heapq import heapify + from heapq import heappop + from heapq import heappush + from math import floor + + nodes = [] + edges = [] + for i in G.keys(): + nodes.append(i) + for j in G[i]: + if (i, j, G[i][j]) not in edges and (j, i, G[i][j]) not in edges: + edges.append((i, j, G[i][j])) + conn = defaultdict(list) + for n1, n2, c in edges: + conn[n1].append((c, n1, n2)) + conn[n2].append((c, n2, n1)) + mst = [] # minimum spanning tree + used = set(nodes[0]) + usable_edges = conn[nodes[0]][:] + heapify(usable_edges) + while usable_edges: + cost, n1, n2 = heappop(usable_edges) + if n2 not in used: + used.add(n2) + mst.append((n1, n2, cost)) + for e in conn[n2]: + if e[2] not in used: + heappush(usable_edges, e) + length = 0 + for p in mst: + length += floor(p[2]) + return length + + +def _get_subgraph(codons, G): + """Get the subgraph that contains all codons in list (PRIVATE).""" + subgraph = {} + for i in codons: + subgraph[i] = {} + for j in codons: + if i != j: + subgraph[i][j] = G[i][j] + return subgraph + + +def _G_test(site_counts): + """G test for 2x2 contingency table (PRIVATE). + + Arguments: + - site_counts - [syn_fix, nonsyn_fix, syn_poly, nonsyn_poly] + + >>> print("%0.6f" % _G_test([17, 7, 42, 2])) + 0.004924 + """ + # TODO: + # Apply continuity correction for Chi-square test. + from math import log + + G = 0 + tot = sum(site_counts) + tot_syn = site_counts[0] + site_counts[2] + tot_non = site_counts[1] + site_counts[3] + tot_fix = sum(site_counts[:2]) + tot_poly = sum(site_counts[2:]) + exp = [ + tot_fix * tot_syn / tot, + tot_fix * tot_non / tot, + tot_poly * tot_syn / tot, + tot_poly * tot_non / tot, + ] + for obs, ex in zip(site_counts, exp): + G += obs * log(obs / ex) + # with only 1 degree of freedom for a 2x2 table, + # the cumulative chi-square distribution reduces to a simple form: + return erfc(sqrt(G)) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/codonseq.py b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/codonseq.py new file mode 100644 index 0000000000000000000000000000000000000000..faf5de82559867a4c4c82fa650411ca6b2eac920 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/codonalign/codonseq.py @@ -0,0 +1,1319 @@ +# Copyright 2013 by Zheng Ruan (zruan1991@gmail.com). All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code for dealing with coding sequence. + +CodonSeq class is inherited from Seq class. This is the core class to +deal with sequences in CodonAlignment in biopython. + +""" + +from itertools import permutations +from math import log + +from Bio.Data import CodonTable +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class CodonSeq(Seq): + """CodonSeq is designed to be within the SeqRecords of a CodonAlignment class. + + CodonSeq is useful as it allows the user to specify + reading frame when translate CodonSeq + + CodonSeq also accepts codon style slice by calling + get_codon() method. + + **Important:** Ungapped CodonSeq can be any length if you + specify the rf_table. Gapped CodonSeq should be a + multiple of three. + + >>> codonseq = CodonSeq("AAATTTGGGCCAAATTT", rf_table=(0,3,6,8,11,14)) + >>> print(codonseq.translate()) + KFGAKF + + test get_full_rf_table method + + >>> p = CodonSeq('AAATTTCCCGG-TGGGTTTAA', rf_table=(0, 3, 6, 9, 11, 14, 17)) + >>> full_rf_table = p.get_full_rf_table() + >>> print(full_rf_table) + [0, 3, 6, 9, 12, 15, 18] + >>> print(p.translate(rf_table=full_rf_table, ungap_seq=False)) + KFPPWV* + >>> p = CodonSeq('AAATTTCCCGGGAA-TTTTAA', rf_table=(0, 3, 6, 9, 14, 17)) + >>> print(p.get_full_rf_table()) + [0, 3, 6, 9, 12.0, 15, 18] + >>> p = CodonSeq('AAA------------TAA', rf_table=(0, 3)) + >>> print(p.get_full_rf_table()) + [0, 3.0, 6.0, 9.0, 12.0, 15] + + """ + + def __init__(self, data="", gap_char="-", rf_table=None): + """Initialize the class.""" + # rf_table should be a tuple or list indicating the every + # codon position along the sequence. For example: + # sequence = 'AAATTTGGGCCAAATTT' + # rf_table = (0, 3, 6, 8, 11, 14) + # the translated protein sequences will be + # AAA TTT GGG GCC AAA TTT + # K F G A K F + # Notice: rf_table applies to ungapped sequence. If there + # are gaps in the sequence, they will be discarded. This + # feature ensures the rf_table is independent of where the + # codon sequence appears in the alignment + + Seq.__init__(self, data.upper()) + self.gap_char = gap_char + + # check the length of the alignment to be a triple + if rf_table is None: + length = len(self) + if length % 3 != 0: + raise ValueError( + "Sequence length is not a multiple of " + "three (i.e. a whole number of codons)" + ) + self.rf_table = list(range(0, length - self.count(gap_char), 3)) + else: + # if gap_char in self: + # assert len(self) % 3 == 0, \ + # "Gapped sequence length is not a triple number" + if not isinstance(rf_table, (tuple, list)): + raise TypeError("rf_table should be a tuple or list object") + if not all(isinstance(i, int) for i in rf_table): + raise TypeError( + "Elements in rf_table should be int " + "that specify the codon positions of " + "the sequence" + ) + self.rf_table = rf_table + + def get_codon(self, index): + """Get the index codon from the sequence.""" + if len({i % 3 for i in self.rf_table}) != 1: + raise RuntimeError( + "frameshift detected. CodonSeq object is not able to deal with " + "codon sequence with frameshift. Please use normal slice option." + ) + if isinstance(index, int): + if index != -1: + return str(self[index * 3 : (index + 1) * 3]) + else: + return str(self[index * 3 :]) + else: + # This slice ensures that codon will always be the unit + # in slicing (it won't change to other codon if you are + # using reverse slicing such as [::-1]). + # The idea of the code below is to first map the slice + # to amino acid sequence and then transform it into + # codon sequence. + aa_index = range(len(self) // 3) + + def cslice(p): + aa_slice = aa_index[p] + codon_slice = "" + for i in aa_slice: + codon_slice += self[i * 3 : i * 3 + 3] + return str(codon_slice) + + codon_slice = cslice(index) + return CodonSeq(codon_slice) + + def get_codon_num(self): + """Return the number of codons in the CodonSeq.""" + return len(self.rf_table) + + def translate( + self, codon_table=None, stop_symbol="*", rf_table=None, ungap_seq=True + ): + """Translate the CodonSeq based on the reading frame in rf_table. + + It is possible for the user to specify + a rf_table at this point. If you want to include + gaps in the translated sequence, this is the only + way. ungap_seq should be set to true for this + purpose. + """ + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + amino_acids = [] + if ungap_seq: + tr_seq = str(self).replace(self.gap_char, "") + else: + tr_seq = str(self) + if rf_table is None: + rf_table = self.rf_table + p = -1 # initiation + for i in rf_table: + if isinstance(i, float): + amino_acids.append("-") + continue + # elif '---' == tr_seq[i:i+3]: + # amino_acids.append('-') + # continue + elif "-" in tr_seq[i : i + 3]: + # considering two types of frameshift + if p == -1 or p - i == 3: + p = i + codon = tr_seq[i : i + 6].replace("-", "")[:3] + elif p - i > 3: + codon = tr_seq[i : i + 3] + p = i + else: + # normal condition without gaps + codon = tr_seq[i : i + 3] + p = i + if codon in codon_table.stop_codons: + amino_acids.append(stop_symbol) + continue + try: + amino_acids.append(codon_table.forward_table[codon]) + except KeyError: + raise RuntimeError( + f"Unknown codon detected ({codon}). Did you" + " forget to specify the ungap_seq argument?" + ) + return "".join(amino_acids) + + def toSeq(self): + """Convert DNA to seq object.""" + return Seq(str(self)) + + def get_full_rf_table(self): + """Return full rf_table of the CodonSeq records. + + A full rf_table is different from a normal rf_table in that + it translate gaps in CodonSeq. It is helpful to construct + alignment containing frameshift. + """ + ungap_seq = str(self).replace("-", "") + relative_pos = [self.rf_table[0]] + for i in range(1, len(self.rf_table[1:]) + 1): + relative_pos.append(self.rf_table[i] - self.rf_table[i - 1]) + full_rf_table = [] + codon_num = 0 + for i in range(0, len(self), 3): + if self[i : i + 3] == self.gap_char * 3: + full_rf_table.append(i + 0.0) + elif relative_pos[codon_num] == 0: + full_rf_table.append(i) + codon_num += 1 + elif relative_pos[codon_num] in (-1, -2): + # check the gap status of previous codon + gap_stat = 3 - self.count("-", i - 3, i) + if gap_stat == 3: + full_rf_table.append(i + relative_pos[codon_num]) + elif gap_stat == 2: + full_rf_table.append(i + 1 + relative_pos[codon_num]) + elif gap_stat == 1: + full_rf_table.append(i + 2 + relative_pos[codon_num]) + codon_num += 1 + elif relative_pos[codon_num] > 0: + full_rf_table.append(i + 0.0) + try: + this_len = 3 - self.count("-", i, i + 3) + relative_pos[codon_num] -= this_len + except Exception: # TODO: IndexError? + # we probably reached the last codon + pass + return full_rf_table + + def full_translate(self, codon_table=None, stop_symbol="*"): + """Apply full translation with gaps considered.""" + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + full_rf_table = self.get_full_rf_table() + return self.translate( + codon_table=codon_table, + stop_symbol=stop_symbol, + rf_table=full_rf_table, + ungap_seq=False, + ) + + def ungap(self, gap="-"): + """Return a copy of the sequence without the gap character(s).""" + if len(gap) != 1 or not isinstance(gap, str): + raise ValueError(f"Unexpected gap character, {gap!r}") + return CodonSeq(str(self).replace(gap, ""), rf_table=self.rf_table) + + @classmethod + def from_seq(cls, seq, rf_table=None): + """Get codon sequence from sequence data.""" + if rf_table is None: + return cls(str(seq)) + else: + return cls(str(seq), rf_table=rf_table) + + +def _get_codon_list(codonseq): + """List of codons according to full_rf_table for counting (PRIVATE).""" + # if not isinstance(codonseq, CodonSeq): + # raise TypeError("_get_codon_list accept a CodonSeq object " + # "({0} detected)".format(type(codonseq))) + full_rf_table = codonseq.get_full_rf_table() + codon_lst = [] + for i, k in enumerate(full_rf_table): + if isinstance(k, int): + start = k + try: + end = int(full_rf_table[i + 1]) + except IndexError: + end = start + 3 + this_codon = str(codonseq[start:end]) + if len(this_codon) == 3: + codon_lst.append(this_codon) + else: + codon_lst.append(str(this_codon.ungap())) + elif str(codonseq[int(k) : int(k) + 3]) == "---": + codon_lst.append("---") + else: + # this may be problematic, as normally no codon should + # fall into this condition + codon_lst.append(codonseq[int(k) : int(k) + 3]) + return codon_lst + + +def cal_dn_ds(codon_seq1, codon_seq2, method="NG86", codon_table=None, k=1, cfreq=None): + """Calculate dN and dS of the given two sequences. + + Available methods: + - NG86 - `Nei and Gojobori (1986)`_ (PMID 3444411). + - LWL85 - `Li et al. (1985)`_ (PMID 3916709). + - ML - `Goldman and Yang (1994)`_ (PMID 7968486). + - YN00 - `Yang and Nielsen (2000)`_ (PMID 10666704). + + .. _`Nei and Gojobori (1986)`: http://www.ncbi.nlm.nih.gov/pubmed/3444411 + .. _`Li et al. (1985)`: http://www.ncbi.nlm.nih.gov/pubmed/3916709 + .. _`Goldman and Yang (1994)`: http://mbe.oxfordjournals.org/content/11/5/725 + .. _`Yang and Nielsen (2000)`: https://doi.org/10.1093/oxfordjournals.molbev.a026236 + + Arguments: + - codon_seq1 - CodonSeq or or SeqRecord that contains a CodonSeq + - codon_seq2 - CodonSeq or or SeqRecord that contains a CodonSeq + - w - transition/transversion ratio + - cfreq - Current codon frequency vector can only be specified + when you are using ML method. Possible ways of + getting cfreq are: F1x4, F3x4 and F61. + + """ + if isinstance(codon_seq1, CodonSeq) and isinstance(codon_seq2, CodonSeq): + pass + elif isinstance(codon_seq1, SeqRecord) and isinstance(codon_seq2, SeqRecord): + codon_seq1 = codon_seq1.seq + codon_seq2 = codon_seq2.seq + else: + raise TypeError( + "cal_dn_ds accepts two CodonSeq objects or SeqRecord " + "that contains CodonSeq as its seq!" + ) + if len(codon_seq1.get_full_rf_table()) != len(codon_seq2.get_full_rf_table()): + raise RuntimeError( + f"full_rf_table length of seq1 ({len(codon_seq1.get_full_rf_table())})" + f" and seq2 ({len(codon_seq2.get_full_rf_table())}) are not the same" + ) + if cfreq is None: + cfreq = "F3x4" + elif cfreq is not None and method != "ML": + raise RuntimeError("cfreq can only be specified when you are using ML method") + if cfreq not in ("F1x4", "F3x4", "F61"): + import warnings + + warnings.warn( + f"Unknown cfreq ({cfreq}). " + "Only F1x4, F3x4 and F61 are acceptable. Used F3x4 in the following." + ) + cfreq = "F3x4" + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + seq1_codon_lst = _get_codon_list(codon_seq1) + seq2_codon_lst = _get_codon_list(codon_seq2) + # remove gaps in seq_codon_lst + seq1 = [] + seq2 = [] + for i, j in zip(seq1_codon_lst, seq2_codon_lst): + if ("-" not in i) and ("-" not in j): + seq1.append(i) + seq2.append(j) + dnds_func = {"ML": _ml, "NG86": _ng86, "LWL85": _lwl85, "YN00": _yn00} + if method == "ML": + return dnds_func[method](seq1, seq2, cfreq, codon_table) + else: + return dnds_func[method](seq1, seq2, k, codon_table) + + +################################################################# +# private functions for NG86 method +################################################################# + + +def _ng86(seq1, seq2, k, codon_table): + """NG86 method main function (PRIVATE).""" + S_sites1, N_sites1 = _count_site_NG86(seq1, codon_table=codon_table, k=k) + S_sites2, N_sites2 = _count_site_NG86(seq2, codon_table=codon_table, k=k) + S_sites = (S_sites1 + S_sites2) / 2.0 + N_sites = (N_sites1 + N_sites2) / 2.0 + SN = [0, 0] + for i, j in zip(seq1, seq2): + SN = [ + m + n for m, n in zip(SN, _count_diff_NG86(i, j, codon_table=codon_table)) + ] + + ps = SN[0] / S_sites + pn = SN[1] / N_sites + if ps < 3 / 4: + dS = abs(-3.0 / 4 * log(1 - 4.0 / 3 * ps)) + else: + dS = -1 + if pn < 3 / 4: + dN = abs(-3.0 / 4 * log(1 - 4.0 / 3 * pn)) + else: + dN = -1 + return dN, dS + + +def _count_site_NG86(codon_lst, codon_table, k=1): + """Count synonymous and non-synonymous sites of a list of codons (PRIVATE). + + Arguments: + - codon_lst - A three letter codon list from a CodonSeq object. + This can be returned from _get_codon_list method. + - k - transition/transversion rate ratio. + + """ + S_site = 0 # synonymous sites + N_site = 0 # non-synonymous sites + purine = ("A", "G") + pyrimidine = ("T", "C") + base_tuple = ("A", "T", "C", "G") + for codon in codon_lst: + neighbor_codon = {"transition": [], "transversion": []} + # classify neighbor codons + codon = codon.replace("U", "T") + if codon == "---": + continue + for n, i in enumerate(codon): + for j in base_tuple: + if i == j: + pass + elif i in purine and j in purine: + codon_chars = list(codon) + codon_chars[n] = j + this_codon = "".join(codon_chars) + neighbor_codon["transition"].append(this_codon) + elif i in pyrimidine and j in pyrimidine: + codon_chars = list(codon) + codon_chars[n] = j + this_codon = "".join(codon_chars) + neighbor_codon["transition"].append(this_codon) + else: + codon_chars = list(codon) + codon_chars[n] = j + this_codon = "".join(codon_chars) + neighbor_codon["transversion"].append(this_codon) + # count synonymous and non-synonymous sites + aa = codon_table.forward_table[codon] + this_codon_N_site = this_codon_S_site = 0 + for neighbor in neighbor_codon["transition"]: + if neighbor in codon_table.stop_codons: + this_codon_N_site += k + elif codon_table.forward_table[neighbor] == aa: + this_codon_S_site += k + else: + this_codon_N_site += k + for neighbor in neighbor_codon["transversion"]: + if neighbor in codon_table.stop_codons: + this_codon_N_site += 1 + elif codon_table.forward_table[neighbor] == aa: + this_codon_S_site += 1 + else: + this_codon_N_site += 1 + norm_const = (this_codon_N_site + this_codon_S_site) / 3 + S_site += this_codon_S_site / norm_const + N_site += this_codon_N_site / norm_const + return (S_site, N_site) + + +def _count_diff_NG86(codon1, codon2, codon_table): + """Count differences between two codons, three-letter string (PRIVATE). + + The function will take multiple pathways from codon1 to codon2 + into account. + """ + if not isinstance(codon1, str) or not isinstance(codon2, str): + raise TypeError( + "_count_diff_NG86 accepts string object to represent codon" + f" ({type(codon1)}, {type(codon2)} detected)" + ) + if len(codon1) != 3 or len(codon2) != 3: + raise RuntimeError( + "codon should be three letter string" + f" ({len(codon1)}, {len(codon2)} detected)" + ) + SN = [0, 0] # synonymous and nonsynonymous counts + if codon1 == "---" or codon2 == "---": + return SN + base_tuple = ("A", "C", "G", "T") + if not all(i in base_tuple for i in codon1): + raise RuntimeError( + f"Unrecognized character detected in codon1 {codon1}" + " (Codons consist of A, T, C or G)" + ) + if not all(i in base_tuple for i in codon2): + raise RuntimeError( + f"Unrecognized character detected in codon2 {codon2}" + " (Codons consist of A, T, C or G)" + ) + if codon1 == codon2: + return SN + else: + diff_pos = [] + for i, k in enumerate(zip(codon1, codon2)): + if k[0] != k[1]: + diff_pos.append(i) + + def compare_codon(codon1, codon2, codon_table, weight=1): + """Compare two codon accounting for different pathways.""" + sd = nd = 0 + if len(set(map(codon_table.forward_table.get, [codon1, codon2]))) == 1: + sd += weight + else: + nd += weight + return (sd, nd) + + if len(diff_pos) == 1: + SN = [ + i + j + for i, j in zip( + SN, compare_codon(codon1, codon2, codon_table=codon_table) + ) + ] + elif len(diff_pos) == 2: + for i in diff_pos: + temp_codon = codon1[:i] + codon2[i] + codon1[i + 1 :] + SN = [ + i + j + for i, j in zip( + SN, + compare_codon( + codon1, temp_codon, codon_table=codon_table, weight=0.5 + ), + ) + ] + SN = [ + i + j + for i, j in zip( + SN, + compare_codon( + temp_codon, codon2, codon_table=codon_table, weight=0.5 + ), + ) + ] + elif len(diff_pos) == 3: + paths = list(permutations([0, 1, 2], 3)) + tmp_codon = [] + for p in paths: + tmp1 = codon1[: p[0]] + codon2[p[0]] + codon1[p[0] + 1 :] + tmp2 = tmp1[: p[1]] + codon2[p[1]] + tmp1[p[1] + 1 :] + tmp_codon.append((tmp1, tmp2)) + SN = [ + i + j + for i, j in zip( + SN, compare_codon(codon1, tmp1, codon_table, weight=0.5 / 3) + ) + ] + SN = [ + i + j + for i, j in zip( + SN, compare_codon(tmp1, tmp2, codon_table, weight=0.5 / 3) + ) + ] + SN = [ + i + j + for i, j in zip( + SN, compare_codon(tmp2, codon2, codon_table, weight=0.5 / 3) + ) + ] + return SN + + +################################################################# +# private functions for LWL85 method +################################################################# + + +def _lwl85(seq1, seq2, k, codon_table): + """LWL85 method main function (PRIVATE). + + Nomenclature is according to Li et al. (1985), PMID 3916709. + """ + codon_fold_dict = _get_codon_fold(codon_table) + # count number of sites in different degenerate classes + fold0 = [0, 0] + fold2 = [0, 0] + fold4 = [0, 0] + for codon in seq1 + seq2: + fold_num = codon_fold_dict[codon] + for f in fold_num: + if f == "0": + fold0[0] += 1 + elif f == "2": + fold2[0] += 1 + elif f == "4": + fold4[0] += 1 + L = [sum(fold0) / 2.0, sum(fold2) / 2.0, sum(fold4) / 2.0] + # count number of differences in different degenerate classes + PQ = [0] * 6 # with P0, P2, P4, Q0, Q2, Q4 in each position + for codon1, codon2 in zip(seq1, seq2): + if (codon1 == "---" or codon2 == "---") or codon1 == codon2: + continue + else: + PQ = [ + i + j + for i, j in zip( + PQ, _diff_codon(codon1, codon2, fold_dict=codon_fold_dict) + ) + ] + PQ = [i / j for i, j in zip(PQ, L * 2)] + P = PQ[:3] + Q = PQ[3:] + A = [ + (1.0 / 2) * log(1.0 / (1 - 2 * i - j)) - (1.0 / 4) * log(1.0 / (1 - 2 * j)) + for i, j in zip(P, Q) + ] + B = [(1.0 / 2) * log(1.0 / (1 - 2 * i)) for i in Q] + dS = 3 * (L[2] * A[1] + L[2] * (A[2] + B[2])) / (L[1] + 3 * L[2]) + dN = 3 * (L[2] * B[1] + L[0] * (A[0] + B[0])) / (2 * L[1] + 3 * L[0]) + return dN, dS + + +def _get_codon_fold(codon_table): + """Classify different position in a codon into different folds (PRIVATE).""" + + def find_fold_class(codon, forward_table): + base = {"A", "T", "C", "G"} + fold = "" + codon_base_lst = list(codon) + for i, b in enumerate(codon_base_lst): + other_base = base - set(b) + aa = [] + for j in other_base: + codon_base_lst[i] = j + try: + aa.append(forward_table["".join(codon_base_lst)]) + except KeyError: + aa.append("stop") + if aa.count(forward_table[codon]) == 0: + fold += "0" + elif aa.count(forward_table[codon]) in (1, 2): + fold += "2" + elif aa.count(forward_table[codon]) == 3: + fold += "4" + else: + raise RuntimeError( + "Unknown Error, cannot assign the position to a fold" + ) + codon_base_lst[i] = b + return fold + + fold_table = {} + for codon in codon_table.forward_table: + if "U" not in codon: + fold_table[codon] = find_fold_class(codon, codon_table.forward_table) + fold_table["---"] = "---" + return fold_table + + +def _diff_codon(codon1, codon2, fold_dict): + """Count number of different substitution types between two codons (PRIVATE). + + returns tuple (P0, P2, P4, Q0, Q2, Q4) + + Nomenclature is according to Li et al. (1958), PMID 3916709. + """ + P0 = P2 = P4 = Q0 = Q2 = Q4 = 0 + fold_num = fold_dict[codon1] + purine = ("A", "G") + pyrimidine = ("T", "C") + for n, (i, j) in enumerate(zip(codon1, codon2)): + if i != j and (i in purine and j in purine): + if fold_num[n] == "0": + P0 += 1 + elif fold_num[n] == "2": + P2 += 1 + elif fold_num[n] == "4": + P4 += 1 + else: + raise RuntimeError("Unexpected fold_num %d" % fold_num[n]) + if i != j and (i in pyrimidine and j in pyrimidine): + if fold_num[n] == "0": + P0 += 1 + elif fold_num[n] == "2": + P2 += 1 + elif fold_num[n] == "4": + P4 += 1 + else: + raise RuntimeError("Unexpected fold_num %d" % fold_num[n]) + if i != j and ( + (i in purine and j in pyrimidine) or (i in pyrimidine and j in purine) + ): + if fold_num[n] == "0": + Q0 += 1 + elif fold_num[n] == "2": + Q2 += 1 + elif fold_num[n] == "4": + Q4 += 1 + else: + raise RuntimeError("Unexpected fold_num %d" % fold_num[n]) + return (P0, P2, P4, Q0, Q2, Q4) + + +################################################################# +# private functions for YN00 method +################################################################# + + +def _yn00(seq1, seq2, k, codon_table): + """YN00 method main function (PRIVATE). + + Nomenclature is according to Yang and Nielsen (2000), PMID 10666704. + """ + from collections import defaultdict + + from scipy.linalg import expm + + fcodon = [ + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + ] + codon_fold_dict = _get_codon_fold(codon_table) + fold0_cnt = defaultdict(int) + fold4_cnt = defaultdict(int) + for codon in seq1 + seq2: + # count sites at different codon position + if codon != "---": + fcodon[0][codon[0]] += 1 + fcodon[1][codon[1]] += 1 + fcodon[2][codon[2]] += 1 + # count sites in different degenerate fold class + fold_num = codon_fold_dict[codon] + for i, f in enumerate(fold_num): + if f == "0": + fold0_cnt[codon[i]] += 1 + elif f == "4": + fold4_cnt[codon[i]] += 1 + f0_total = sum(fold0_cnt.values()) + f4_total = sum(fold4_cnt.values()) + for i, j in zip(fold0_cnt, fold4_cnt): + fold0_cnt[i] = fold0_cnt[i] / f0_total + fold4_cnt[i] = fold4_cnt[i] / f4_total + # TODO: + # the initial kappa is different from what yn00 gives, + # try to find the problem. + TV = _get_TV(seq1, seq2, codon_table=codon_table) + k04 = (_get_kappa_t(fold0_cnt, TV), _get_kappa_t(fold4_cnt, TV)) + kappa = (f0_total * k04[0] + f4_total * k04[1]) / (f0_total + f4_total) + # kappa = 2.4285 + # count synonymous sites and non-synonymous sites + for i in range(3): + tot = sum(fcodon[i].values()) + fcodon[i] = {j: k / tot for j, k in fcodon[i].items()} + pi = defaultdict(int) + for i in list(codon_table.forward_table.keys()) + codon_table.stop_codons: + if "U" not in i: + pi[i] = 0 + for i in seq1 + seq2: + pi[i] += 1 + S_sites1, N_sites1, bfreqSN1 = _count_site_YN00( + seq1, seq2, pi, k=kappa, codon_table=codon_table + ) + S_sites2, N_sites2, bfreqSN2 = _count_site_YN00( + seq2, seq1, pi, k=kappa, codon_table=codon_table + ) + N_sites = (N_sites1 + N_sites2) / 2 + S_sites = (S_sites1 + S_sites2) / 2 + bfreqSN = [{"A": 0, "T": 0, "C": 0, "G": 0}, {"A": 0, "T": 0, "C": 0, "G": 0}] + for i in range(2): + for b in ("A", "T", "C", "G"): + bfreqSN[i][b] = (bfreqSN1[i][b] + bfreqSN2[i][b]) / 2 + # use NG86 method to get initial t and w + SN = [0, 0] + for i, j in zip(seq1, seq2): + SN = [ + m + n for m, n in zip(SN, _count_diff_NG86(i, j, codon_table=codon_table)) + ] + ps = SN[0] / S_sites + pn = SN[1] / N_sites + p = sum(SN) / (S_sites + N_sites) + w = log(1 - 4.0 / 3 * pn) / log(1 - 4.0 / 3 * ps) + t = -3 / 4 * log(1 - 4 / 3 * p) + tolerance = 1e-5 + dSdN_pre = [0, 0] + for temp in range(20): + # count synonymous and nonsynonymous differences under kappa, w, t + codon_lst = [ + i + for i in list(codon_table.forward_table.keys()) + codon_table.stop_codons + if "U" not in i + ] + Q = _get_Q(pi, kappa, w, codon_lst, codon_table) + P = expm(Q * t) + TV = [0, 0, 0, 0] # synonymous/nonsynonymous transition/transversion + codon_npath = {} + for i, j in zip(seq1, seq2): + if i != "---" and j != "---": + codon_npath.setdefault((i, j), 0) + codon_npath[(i, j)] += 1 + for i in codon_npath: + tv = _count_diff_YN00(i[0], i[1], P, codon_lst, codon_table) + TV = [m + n * codon_npath[i] for m, n in zip(TV, tv)] + TV = (TV[0] / S_sites, TV[1] / S_sites), (TV[2] / N_sites, TV[3] / N_sites) + # according to the DistanceF84() function of yn00.c in paml, + # the t (e.q. 10) appears in PMID: 10666704 is dS and dN + dSdN = [] + for f, tv in zip(bfreqSN, TV): + dSdN.append(_get_kappa_t(f, tv, t=True)) + t = dSdN[0] * 3 * S_sites / (S_sites + N_sites) + dSdN[1] * 3 * N_sites / ( + S_sites + N_sites + ) + w = dSdN[1] / dSdN[0] + if all(abs(i - j) < tolerance for i, j in zip(dSdN, dSdN_pre)): + return dSdN[1], dSdN[0] # dN, dS + dSdN_pre = dSdN + + +def _get_TV(codon_lst1, codon_lst2, codon_table): + """Get TV (PRIVATE). + + Arguments: + - T - proportions of transitional differences + - V - proportions of transversional differences + + """ + purine = ("A", "G") + pyrimidine = ("C", "T") + TV = [0, 0] + sites = 0 + for codon1, codon2 in zip(codon_lst1, codon_lst2): + if "---" not in (codon1, codon2): + for i, j in zip(codon1, codon2): + if i == j: + pass + elif i in purine and j in purine: + TV[0] += 1 + elif i in pyrimidine and j in pyrimidine: + TV[0] += 1 + else: + TV[1] += 1 + sites += 1 + return (TV[0] / sites, TV[1] / sites) + # return (TV[0], TV[1]) + + +def _get_kappa_t(pi, TV, t=False): + """Calculate kappa (PRIVATE). + + The following formula and variable names are according to PMID: 10666704 + """ + pi["Y"] = pi["T"] + pi["C"] + pi["R"] = pi["A"] + pi["G"] + A = ( + 2 * (pi["T"] * pi["C"] + pi["A"] * pi["G"]) + + 2 + * ( + pi["T"] * pi["C"] * pi["R"] / pi["Y"] + + pi["A"] * pi["G"] * pi["Y"] / pi["R"] + ) + * (1 - TV[1] / (2 * pi["Y"] * pi["R"])) + - TV[0] + ) / (2 * (pi["T"] * pi["C"] / pi["Y"] + pi["A"] * pi["G"] / pi["R"])) + B = 1 - TV[1] / (2 * pi["Y"] * pi["R"]) + a = -0.5 * log(A) # this seems to be an error in YANG's original paper + b = -0.5 * log(B) + kappaF84 = a / b - 1 + if t is False: + kappaHKY85 = 1 + ( + pi["T"] * pi["C"] / pi["Y"] + pi["A"] * pi["G"] / pi["R"] + ) * kappaF84 / (pi["T"] * pi["C"] + pi["A"] * pi["G"]) + return kappaHKY85 + else: + t = ( + 4 * pi["T"] * pi["C"] * (1 + kappaF84 / pi["Y"]) + + 4 * pi["A"] * pi["G"] * (1 + kappaF84 / pi["R"]) + + 4 * pi["Y"] * pi["R"] + ) * b + return t + + +def _count_site_YN00(codon_lst1, codon_lst2, pi, k, codon_table): + """Site counting method from Ina / Yang and Nielsen (PRIVATE). + + Method from `Ina (1995)`_ as modified by `Yang and Nielsen (2000)`_. + This will return the total number of synonymous and nonsynonymous sites + and base frequencies in each category. The function is equivalent to + the ``CountSites()`` function in ``yn00.c`` of PAML. + + .. _`Ina (1995)`: https://doi.org/10.1007/BF00167113 + .. _`Yang and Nielsen (2000)`: https://doi.org/10.1093/oxfordjournals.molbev.a026236 + + """ + if len(codon_lst1) != len(codon_lst2): + raise RuntimeError( + "Length of two codon_lst should be the same (%d and %d detected)" + % (len(codon_lst1), len(codon_lst2)) + ) + else: + length = len(codon_lst1) + purine = ("A", "G") + pyrimidine = ("T", "C") + base_tuple = ("A", "T", "C", "G") + codon_dict = codon_table.forward_table + stop = codon_table.stop_codons + codon_npath = {} + for i, j in zip(codon_lst1, codon_lst2): + if i != "---" and j != "---": + codon_npath.setdefault((i, j), 0) + codon_npath[(i, j)] += 1 + S_sites = N_sites = 0 + freqSN = [ + {"A": 0, "T": 0, "C": 0, "G": 0}, # synonymous + {"A": 0, "T": 0, "C": 0, "G": 0}, + ] # nonsynonymous + for codon_pair, npath in codon_npath.items(): + codon = codon_pair[0] + S = N = 0 + for pos in range(3): + for base in base_tuple: + if codon[pos] == base: + continue + neighbor_codon = codon[:pos] + base + codon[pos + 1 :] + if neighbor_codon in stop: + continue + weight = pi[neighbor_codon] + if codon[pos] in pyrimidine and base in pyrimidine: + weight *= k + elif codon[pos] in purine and base in purine: + weight *= k + if codon_dict[codon] == codon_dict[neighbor_codon]: + S += weight + freqSN[0][base] += weight * npath + else: + N += weight + freqSN[1][base] += weight * npath + S_sites += S * npath + N_sites += N * npath + norm_const = 3 * length / (S_sites + N_sites) + S_sites *= norm_const + N_sites *= norm_const + for i in freqSN: + norm_const = sum(i.values()) + for b in i: + i[b] /= norm_const + return S_sites, N_sites, freqSN + + +def _count_diff_YN00(codon1, codon2, P, codon_lst, codon_table): + """Count differences between two codons (three-letter string; PRIVATE). + + The function will weighted multiple pathways from codon1 to codon2 + according to P matrix of codon substitution. The proportion + of transition and transversion (TV) will also be calculated in + the function. + """ + if not isinstance(codon1, str) or not isinstance(codon2, str): + raise TypeError( + "_count_diff_YN00 accepts string object to represent codon" + f" ({type(codon1)}, {type(codon2)} detected)" + ) + if len(codon1) != 3 or len(codon2) != 3: + raise RuntimeError( + "codon should be three letter string" + f" ({len(codon1)}, {len(codon2)} detected)" + ) + TV = [ + 0, + 0, + 0, + 0, + ] # transition and transversion counts (synonymous and nonsynonymous) + if codon1 == "---" or codon2 == "---": + return TV + base_tuple = ("A", "C", "G", "T") + if not all(i in base_tuple for i in codon1): + raise RuntimeError( + f"Unrecognized character detected in codon1 {codon1}" + " (Codons consist of A, T, C or G)" + ) + if not all(i in base_tuple for i in codon2): + raise RuntimeError( + f"Unrecognized character detected in codon2 {codon2}" + " (Codons consist of A, T, C or G)" + ) + if codon1 == codon2: + return TV + else: + diff_pos = [] + for i, k in enumerate(zip(codon1, codon2)): + if k[0] != k[1]: + diff_pos.append(i) + + def count_TV(codon1, codon2, diff, codon_table, weight=1): + purine = ("A", "G") + pyrimidine = ("T", "C") + dic = codon_table.forward_table + stop = codon_table.stop_codons + if codon1 in stop or codon2 in stop: + # stop codon is always considered as nonsynonymous + if codon1[diff] in purine and codon2[diff] in purine: + return [0, 0, weight, 0] + elif codon1[diff] in pyrimidine and codon2[diff] in pyrimidine: + return [0, 0, weight, 0] + else: + return [0, 0, 0, weight] + elif dic[codon1] == dic[codon2]: + if codon1[diff] in purine and codon2[diff] in purine: + return [weight, 0, 0, 0] + elif codon1[diff] in pyrimidine and codon2[diff] in pyrimidine: + return [weight, 0, 0, 0] + else: + return [0, weight, 0, 0] + else: + if codon1[diff] in purine and codon2[diff] in purine: + return [0, 0, weight, 0] + elif codon1[diff] in pyrimidine and codon2[diff] in pyrimidine: + return [0, 0, weight, 0] + else: + return [0, 0, 0, weight] + + if len(diff_pos) == 1: + TV = [ + p + q + for p, q in zip(TV, count_TV(codon1, codon2, diff_pos[0], codon_table)) + ] + elif len(diff_pos) == 2: + tmp_codon = [codon1[:i] + codon2[i] + codon1[i + 1 :] for i in diff_pos] + path_prob = [] + for i in tmp_codon: + codon_idx = list(map(codon_lst.index, [codon1, i, codon2])) + prob = (P[codon_idx[0], codon_idx[1]], P[codon_idx[1], codon_idx[2]]) + path_prob.append(prob[0] * prob[1]) + path_prob = [2 * i / sum(path_prob) for i in path_prob] + for n, i in enumerate(diff_pos): + temp_codon = codon1[:i] + codon2[i] + codon1[i + 1 :] + TV = [ + p + q + for p, q in zip( + TV, + count_TV( + codon1, temp_codon, i, codon_table, weight=path_prob[n] / 2 + ), + ) + ] + TV = [ + p + q + for p, q in zip( + TV, + count_TV( + codon1, temp_codon, i, codon_table, weight=path_prob[n] / 2 + ), + ) + ] + elif len(diff_pos) == 3: + paths = list(permutations([0, 1, 2], 3)) + path_prob = [] + tmp_codon = [] + for p in paths: + tmp1 = codon1[: p[0]] + codon2[p[0]] + codon1[p[0] + 1 :] + tmp2 = tmp1[: p[1]] + codon2[p[1]] + tmp1[p[1] + 1 :] + tmp_codon.append((tmp1, tmp2)) + codon_idx = list(map(codon_lst.index, [codon1, tmp1, tmp2, codon2])) + prob = ( + P[codon_idx[0], codon_idx[1]], + P[codon_idx[1], codon_idx[2]], + P[codon_idx[2], codon_idx[3]], + ) + path_prob.append(prob[0] * prob[1] * prob[2]) + path_prob = [3 * i / sum(path_prob) for i in path_prob] + for i, j, k in zip(tmp_codon, path_prob, paths): + TV = [ + p + q + for p, q in zip( + TV, count_TV(codon1, i[0], k[0], codon_table, weight=j / 3) + ) + ] + TV = [ + p + q + for p, q in zip( + TV, count_TV(i[0], i[1], k[1], codon_table, weight=j / 3) + ) + ] + TV = [ + p + q + for p, q in zip( + TV, count_TV(i[1], codon2, k[1], codon_table, weight=j / 3) + ) + ] + return TV + + +################################################################# +# private functions for Maximum Likelihood method +################################################################# + + +def _ml(seq1, seq2, cmethod, codon_table): + """ML method main function (PRIVATE).""" + from collections import Counter + + from scipy.optimize import minimize + + codon_cnt = Counter() + pi = _get_pi(seq1, seq2, cmethod, codon_table=codon_table) + for i, j in zip(seq1, seq2): + # if i != j and ('---' not in (i, j)): + if "---" not in (i, j): + codon_cnt[(i, j)] += 1 + codon_lst = [ + i + for i in list(codon_table.forward_table.keys()) + codon_table.stop_codons + if "U" not in i + ] + + # apply optimization + def func( + params, pi=pi, codon_cnt=codon_cnt, codon_lst=codon_lst, codon_table=codon_table + ): + """Temporary function, params = [t, k, w].""" + return -_likelihood_func( + params[0], + params[1], + params[2], + pi, + codon_cnt, + codon_lst=codon_lst, + codon_table=codon_table, + ) + + # count sites + opt_res = minimize( + func, + [1, 0.1, 2], + method="L-BFGS-B", + bounds=((1e-10, 20), (1e-10, 20), (1e-10, 10)), + tol=1e-5, + ) + t, k, w = opt_res.x + Q = _get_Q(pi, k, w, codon_lst, codon_table) + Sd = Nd = 0 + for i, c1 in enumerate(codon_lst): + for j, c2 in enumerate(codon_lst): + if i != j: + try: + if codon_table.forward_table[c1] == codon_table.forward_table[c2]: + # synonymous count + Sd += pi[c1] * Q[i, j] + else: + # nonsynonymous count + Nd += pi[c1] * Q[i, j] + except KeyError: + # This is probably due to stop codons + pass + Sd *= t + Nd *= t + + # count differences (with w fixed to 1) + def func_w1( + params, pi=pi, codon_cnt=codon_cnt, codon_lst=codon_lst, codon_table=codon_table + ): + """Temporary function, params = [t, k]. w is fixed to 1.""" + return -_likelihood_func( + params[0], + params[1], + 1.0, + pi, + codon_cnt, + codon_lst=codon_lst, + codon_table=codon_table, + ) + + opt_res = minimize( + func_w1, + [1, 0.1], + method="L-BFGS-B", + bounds=((1e-10, 20), (1e-10, 20)), + tol=1e-5, + ) + t, k = opt_res.x + w = 1.0 + Q = _get_Q(pi, k, w, codon_lst, codon_table) + rhoS = rhoN = 0 + for i, c1 in enumerate(codon_lst): + for j, c2 in enumerate(codon_lst): + if i != j: + try: + if codon_table.forward_table[c1] == codon_table.forward_table[c2]: + # synonymous count + rhoS += pi[c1] * Q[i, j] + else: + # nonsynonymous count + rhoN += pi[c1] * Q[i, j] + except KeyError: + # This is probably due to stop codons + pass + rhoS *= 3 + rhoN *= 3 + dN = Nd / rhoN + dS = Sd / rhoS + return dN, dS + + +def _get_pi(seq1, seq2, cmethod, codon_table): + """Obtain codon frequency dict (pi) from two codon list (PRIVATE). + + This function is designed for ML method. Available counting methods + (cfreq) are F1x4, F3x4 and F64. + """ + # TODO: + # Stop codon should not be allowed according to Yang. + # Try to modify this! + pi = {} + if cmethod == "F1x4": + fcodon = {"A": 0, "G": 0, "C": 0, "T": 0} + for i in seq1 + seq2: + if i != "---": + for c in i: + fcodon[c] += 1 + tot = sum(fcodon.values()) + fcodon = {j: k / tot for j, k in fcodon.items()} + for i in codon_table.forward_table.keys() + codon_table.stop_codons: + if "U" not in i: + pi[i] = fcodon[i[0]] * fcodon[i[1]] * fcodon[i[2]] + elif cmethod == "F3x4": + # three codon position + fcodon = [ + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + ] + for i in seq1 + seq2: + if i != "---": + fcodon[0][i[0]] += 1 + fcodon[1][i[1]] += 1 + fcodon[2][i[2]] += 1 + for i in range(3): + tot = sum(fcodon[i].values()) + fcodon[i] = {j: k / tot for j, k in fcodon[i].items()} + for i in list(codon_table.forward_table.keys()) + codon_table.stop_codons: + if "U" not in i: + pi[i] = fcodon[0][i[0]] * fcodon[1][i[1]] * fcodon[2][i[2]] + elif cmethod == "F61": + for i in codon_table.forward_table.keys() + codon_table.stop_codons: + if "U" not in i: + pi[i] = 0.1 + for i in seq1 + seq2: + if i != "---": + pi[i] += 1 + tot = sum(pi.values()) + pi = {j: k / tot for j, k in pi.items()} + return pi + + +def _q(i, j, pi, k, w, codon_table): + """Q matrix for codon substitution (PRIVATE). + + Arguments: + - i, j : three letter codon string + - pi : expected codon frequency + - k : transition/transversion ratio + - w : nonsynonymous/synonymous rate ratio + - codon_table: Bio.Data.CodonTable object + + """ + if i == j: + # diagonal elements is the sum of all other elements + return 0 + if i in codon_table.stop_codons or j in codon_table.stop_codons: + return 0 + if (i not in pi) or (j not in pi): + return 0 + purine = ("A", "G") + pyrimidine = ("T", "C") + diff = [] + for n, (c1, c2) in enumerate(zip(i, j)): + if c1 != c2: + diff.append((n, c1, c2)) + if len(diff) >= 2: + return 0 + if codon_table.forward_table[i] == codon_table.forward_table[j]: + # synonymous substitution + if diff[0][1] in purine and diff[0][2] in purine: + # transition + return k * pi[j] + elif diff[0][1] in pyrimidine and diff[0][2] in pyrimidine: + # transition + return k * pi[j] + else: + # transversion + return pi[j] + else: + # nonsynonymous substitution + if diff[0][1] in purine and diff[0][2] in purine: + # transition + return w * k * pi[j] + elif diff[0][1] in pyrimidine and diff[0][2] in pyrimidine: + # transition + return w * k * pi[j] + else: + # transversion + return w * pi[j] + + +def _get_Q(pi, k, w, codon_lst, codon_table): + """Q matrix for codon substitution (PRIVATE).""" + import numpy as np + + codon_num = len(codon_lst) + Q = np.zeros((codon_num, codon_num)) + for i in range(codon_num): + for j in range(codon_num): + if i != j: + Q[i, j] = _q( + codon_lst[i], codon_lst[j], pi, k, w, codon_table=codon_table + ) + nucl_substitutions = 0 + for i in range(codon_num): + Q[i, i] = -sum(Q[i, :]) + try: + nucl_substitutions += pi[codon_lst[i]] * (-Q[i, i]) + except KeyError: + pass + Q = Q / nucl_substitutions + return Q + + +def _likelihood_func(t, k, w, pi, codon_cnt, codon_lst, codon_table): + """Likelihood function for ML method (PRIVATE).""" + from scipy.linalg import expm + + Q = _get_Q(pi, k, w, codon_lst, codon_table) + P = expm(Q * t) + likelihood = 0 + for i, c1 in enumerate(codon_lst): + for j, c2 in enumerate(codon_lst): + if (c1, c2) in codon_cnt: + if P[i, j] * pi[c1] <= 0: + likelihood += codon_cnt[(c1, c2)] * 0 + else: + likelihood += codon_cnt[(c1, c2)] * log(pi[c1] * P[i, j]) + return likelihood + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..1409c4aa2f3b7434f34d0ae856080b296bc8d99d Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2module.c b/.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2module.c new file mode 100644 index 0000000000000000000000000000000000000000..1b6fa90e9c1c962311cfe702d4194a6ee9aa4df8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2module.c @@ -0,0 +1,479 @@ +/* Copyright 2002 by Jeffrey Chang. + * Copyright 2016, 2019 by Markus Piotrowski. + * All rights reserved. + * + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + * + * cpairwise2module.c + * Created 30 Sep 2001 + * + * Optimized C routines that complement pairwise2.py. + */ + +#include "Python.h" + + +#define _PRECISION 1000 +#define rint(x) (int)((x)*_PRECISION+0.5) + +/* Functions in this module. */ + +static double calc_affine_penalty(int length, double open, double extend, + int penalize_extend_when_opening) +{ + double penalty; + + if(length <= 0) + return 0.0; + penalty = open + extend * length; + if(!penalize_extend_when_opening) + penalty -= extend; + return penalty; +} + +static double _get_match_score(PyObject *py_sequenceA, PyObject *py_sequenceB, + PyObject *py_match_fn, int i, int j, + char *sequenceA, char *sequenceB, + int use_sequence_cstring, + double match, double mismatch, + int use_match_mismatch_scores) +{ + PyObject *py_A=NULL, *py_B=NULL; + PyObject *py_arglist=NULL, *py_result=NULL; + double score = 0; + + if(use_sequence_cstring && use_match_mismatch_scores) { + score = (sequenceA[i] == sequenceB[j]) ? match : mismatch; + return score; + } + /* Calculate the match score. */ + if(!(py_A = PySequence_GetItem(py_sequenceA, i))) + goto _get_match_score_cleanup; + if(!(py_B = PySequence_GetItem(py_sequenceB, j))) + goto _get_match_score_cleanup; + if(!(py_arglist = Py_BuildValue("(OO)", py_A, py_B))) + goto _get_match_score_cleanup; + + if(!(py_result = PyObject_CallObject(py_match_fn, py_arglist))) + goto _get_match_score_cleanup; + score = PyFloat_AsDouble(py_result); + + _get_match_score_cleanup: + if(py_A) { + Py_DECREF(py_A); + } + if(py_B) { + Py_DECREF(py_B); + } + if(py_arglist) { + Py_DECREF(py_arglist); + } + if(py_result) { + Py_DECREF(py_result); + } + return score; +} + +#if PY_MAJOR_VERSION >= 3 +static PyObject* _create_bytes_object(PyObject* o) +{ + PyObject* b; + if (PyBytes_Check(o)) { + return o; + } + if (!PyUnicode_Check(o)) { + return NULL; + } + b = PyUnicode_AsASCIIString(o); + if (!b) { + PyErr_Clear(); + return NULL; + } + return b; +} +#endif + +/* This function is a more-or-less straightforward port of the + * equivalent function in pairwise2. Please see there for algorithm + * documentation. + */ +static PyObject *cpairwise2__make_score_matrix_fast(PyObject *self, + PyObject *args) +{ + int i; + int row, col; + PyObject *py_sequenceA, *py_sequenceB, *py_match_fn; +#if PY_MAJOR_VERSION >= 3 + PyObject *py_bytesA, *py_bytesB; +#endif + char *sequenceA=NULL, *sequenceB=NULL; + int use_sequence_cstring; + double open_A, extend_A, open_B, extend_B; + int penalize_extend_when_opening, penalize_end_gaps_A, penalize_end_gaps_B; + int align_globally, score_only; + + PyObject *py_match=NULL, *py_mismatch=NULL; + double first_A_gap, first_B_gap; + double match, mismatch; + double score; + double best_score = 0; + double local_max_score = 0; + int use_match_mismatch_scores; + int lenA, lenB; + double *score_matrix = NULL; + unsigned char *trace_matrix = NULL; + PyObject *py_score_matrix=NULL, *py_trace_matrix=NULL; + + double *col_cache_score = NULL; + PyObject *py_retval = NULL; + + if(!PyArg_ParseTuple(args, "OOOddddi(ii)ii", &py_sequenceA, &py_sequenceB, + &py_match_fn, &open_A, &extend_A, &open_B, &extend_B, + &penalize_extend_when_opening, + &penalize_end_gaps_A, &penalize_end_gaps_B, + &align_globally, &score_only)) + return NULL; + if(!PySequence_Check(py_sequenceA) || !PySequence_Check(py_sequenceB)) { + PyErr_SetString(PyExc_TypeError, + "py_sequenceA and py_sequenceB should be sequences."); + return NULL; + } + + /* Optimize for the common case. Check to see if py_sequenceA and + py_sequenceB are strings. If they are, use the c string + representation. */ +#if PY_MAJOR_VERSION < 3 + use_sequence_cstring = 0; + if(PyString_Check(py_sequenceA) && PyString_Check(py_sequenceB)) { + sequenceA = PyString_AS_STRING(py_sequenceA); + sequenceB = PyString_AS_STRING(py_sequenceB); + use_sequence_cstring = 1; + } +#else + py_bytesA = _create_bytes_object(py_sequenceA); + py_bytesB = _create_bytes_object(py_sequenceB); + if (py_bytesA && py_bytesB) { + sequenceA = PyBytes_AS_STRING(py_bytesA); + sequenceB = PyBytes_AS_STRING(py_bytesB); + use_sequence_cstring = 1; + } + else { + Py_XDECREF(py_bytesA); + Py_XDECREF(py_bytesB); + use_sequence_cstring = 0; + } +#endif + + if(!PyCallable_Check(py_match_fn)) { + PyErr_SetString(PyExc_TypeError, "py_match_fn must be callable."); + return NULL; + } + /* Optimize for the common case. Check to see if py_match_fn is + an identity_match. If so, pull out the match and mismatch + member variables and calculate the scores myself. */ + match = mismatch = 0; + use_match_mismatch_scores = 0; + if(!(py_match = PyObject_GetAttrString(py_match_fn, "match"))) + goto cleanup_after_py_match_fn; + match = PyFloat_AsDouble(py_match); + if(match==-1.0 && PyErr_Occurred()) + goto cleanup_after_py_match_fn; + if(!(py_mismatch = PyObject_GetAttrString(py_match_fn, "mismatch"))) + goto cleanup_after_py_match_fn; + mismatch = PyFloat_AsDouble(py_mismatch); + if(mismatch==-1.0 && PyErr_Occurred()) + goto cleanup_after_py_match_fn; + use_match_mismatch_scores = 1; + + cleanup_after_py_match_fn: + if(PyErr_Occurred()) + PyErr_Clear(); + if(py_match) { + Py_DECREF(py_match); + } + if(py_mismatch) { + Py_DECREF(py_mismatch); + } + /* Cache some commonly used gap penalties */ + first_A_gap = calc_affine_penalty(1, open_A, extend_A, + penalize_extend_when_opening); + first_B_gap = calc_affine_penalty(1, open_B, extend_B, + penalize_extend_when_opening); + + /* Allocate matrices for storing the results and initialize first row and col. */ + lenA = PySequence_Length(py_sequenceA); + lenB = PySequence_Length(py_sequenceB); + score_matrix = malloc((lenA+1)*(lenB+1)*sizeof(*score_matrix)); + if(!score_matrix) { + PyErr_SetString(PyExc_MemoryError, "Out of memory"); + goto _cleanup_make_score_matrix_fast; + } + for(i=0; i<(lenB+1); i++) + score_matrix[i] = 0; + for(i=0; i<(lenA+1)*(lenB+1); i += (lenB+1)) + score_matrix[i] = 0; + /* If we only want the score, we don't need the trace matrix. */ + if (!score_only){ + trace_matrix = malloc((lenA+1)*(lenB+1)*sizeof(*trace_matrix)); + if(!trace_matrix) { + PyErr_SetString(PyExc_MemoryError, "Out of memory"); + goto _cleanup_make_score_matrix_fast; + } + for(i=0; i<(lenB+1); i++) + trace_matrix[i] = 0; + for(i=0; i<(lenA+1)*(lenB+1); i += (lenB+1)) + trace_matrix[i] = 0; + } + else + trace_matrix = malloc(1); + + /* Initialize the first row and col of the score matrix. */ + for(i=0; i<=lenA; i++) { + if(penalize_end_gaps_B) + score = calc_affine_penalty(i, open_B, extend_B, + penalize_extend_when_opening); + else + score = 0; + score_matrix[i*(lenB+1)] = score; + } + for(i=0; i<=lenB; i++) { + if(penalize_end_gaps_A) + score = calc_affine_penalty(i, open_A, extend_A, + penalize_extend_when_opening); + else + score = 0; + score_matrix[i] = score; + } + + /* Now initialize the col cache. */ + col_cache_score = malloc((lenB+1)*sizeof(*col_cache_score)); + memset((void *)col_cache_score, 0, (lenB+1)*sizeof(*col_cache_score)); + for(i=0; i<=lenB; i++) { + col_cache_score[i] = calc_affine_penalty(i, (2*open_B), extend_B, + penalize_extend_when_opening); + } + + /* Fill in the score matrix. The row cache is calculated on the fly.*/ + for(row=1; row<=lenA; row++) { + double row_cache_score = calc_affine_penalty(row, (2*open_A), extend_A, + penalize_extend_when_opening); + for(col=1; col<=lenB; col++) { + double match_score, nogap_score; + double row_open, row_extend, col_open, col_extend; + int best_score_rint, row_score_rint, col_score_rint; + unsigned char row_trace_score, col_trace_score, trace_score; + + /* Calculate the best score. */ + match_score = _get_match_score(py_sequenceA, py_sequenceB, + py_match_fn, row-1, col-1, + sequenceA, sequenceB, + use_sequence_cstring, + match, mismatch, + use_match_mismatch_scores); + if(match_score==-1.0 && PyErr_Occurred()) + goto _cleanup_make_score_matrix_fast; + nogap_score = score_matrix[(row-1)*(lenB+1)+col-1] + match_score; + + if (!penalize_end_gaps_A && row==lenA) { + row_open = score_matrix[(row)*(lenB+1)+col-1]; + row_extend = row_cache_score; + } + else { + row_open = score_matrix[(row)*(lenB+1)+col-1] + first_A_gap; + row_extend = row_cache_score + extend_A; + } + row_cache_score = (row_open > row_extend) ? row_open : row_extend; + + if (!penalize_end_gaps_B && col==lenB){ + col_open = score_matrix[(row-1)*(lenB+1)+col]; + col_extend = col_cache_score[col]; + } + else { + col_open = score_matrix[(row-1)*(lenB+1)+col] + first_B_gap; + col_extend = col_cache_score[col] + extend_B; + } + col_cache_score[col] = (col_open > col_extend) ? col_open : col_extend; + + best_score = (row_cache_score > col_cache_score[col]) ? row_cache_score : col_cache_score[col]; + if(nogap_score > best_score) + best_score = nogap_score; + + if (best_score > local_max_score) + local_max_score = best_score; + + if(!align_globally && best_score < 0) + score_matrix[row*(lenB+1)+col] = 0; + else + score_matrix[row*(lenB+1)+col] = best_score; + + if (!score_only) { + row_score_rint = rint(row_cache_score); + col_score_rint = rint(col_cache_score[col]); + row_trace_score = 0; + col_trace_score = 0; + if (rint(row_open) == row_score_rint) + row_trace_score = row_trace_score|1; + if (rint(row_extend) == row_score_rint) + row_trace_score = row_trace_score|8; + if (rint(col_open) == col_score_rint) + col_trace_score = col_trace_score|4; + if (rint(col_extend) == col_score_rint) + col_trace_score = col_trace_score|16; + + trace_score = 0; + best_score_rint = rint(best_score); + if (rint(nogap_score) == best_score_rint) + trace_score = trace_score|2; + if (row_score_rint == best_score_rint) + trace_score += row_trace_score; + if (col_score_rint == best_score_rint) + trace_score += col_trace_score; + trace_matrix[row*(lenB+1)+col] = trace_score; + } + } + } + + if (!align_globally) + best_score = local_max_score; + + /* Save the score and traceback matrices into real python objects. */ + if(!score_only) { + if(!(py_score_matrix = PyList_New(lenA+1))) + goto _cleanup_make_score_matrix_fast; + if(!(py_trace_matrix = PyList_New(lenA+1))) + goto _cleanup_make_score_matrix_fast; + + for(row=0; row<=lenA; row++) { + PyObject *py_score_row, *py_trace_row; + if(!(py_score_row = PyList_New(lenB+1))) + goto _cleanup_make_score_matrix_fast; + PyList_SET_ITEM(py_score_matrix, row, py_score_row); + if(!(py_trace_row = PyList_New(lenB+1))) + goto _cleanup_make_score_matrix_fast; + PyList_SET_ITEM(py_trace_matrix, row, py_trace_row); + + for(col=0; col<=lenB; col++) { + PyObject *py_score, *py_trace; + int offset = row*(lenB+1) + col; + + /* Set py_score_matrix[row][col] to the score. */ + if(!(py_score = PyFloat_FromDouble(score_matrix[offset]))) + goto _cleanup_make_score_matrix_fast; + PyList_SET_ITEM(py_score_row, col, py_score); + + /* Set py_trace_matrix[row][col] to a list of indexes. On + the edges of the matrix (row or column is 0), the + matrix should be [None]. */ + if(!row || !col) { + if(!(py_trace = Py_BuildValue("B", 1))) + goto _cleanup_make_score_matrix_fast; + Py_INCREF(Py_None); + PyList_SET_ITEM(py_trace_row, col, Py_None); + } + else { + if(!(py_trace = Py_BuildValue("B", trace_matrix[offset]))) + goto _cleanup_make_score_matrix_fast; + PyList_SET_ITEM(py_trace_row, col, py_trace); + + } + } + } + } + else { + py_score_matrix = PyList_New(1); + py_trace_matrix = PyList_New(1); + } + py_retval = Py_BuildValue("(OOd)", py_score_matrix, py_trace_matrix, best_score); + + _cleanup_make_score_matrix_fast: + if(score_matrix) + free(score_matrix); + if(trace_matrix) + free(trace_matrix); + if(col_cache_score) + free(col_cache_score); + if(py_score_matrix){ + Py_DECREF(py_score_matrix); + } + if(py_trace_matrix){ + Py_DECREF(py_trace_matrix); + } + +#if PY_MAJOR_VERSION >= 3 + if (py_bytesA != NULL && py_bytesA != py_sequenceA) Py_DECREF(py_bytesA); + if (py_bytesB != NULL && py_bytesB != py_sequenceB) Py_DECREF(py_bytesB); +#endif + + return py_retval; +} + +static PyObject *cpairwise2_rint(PyObject *self, PyObject *args, + PyObject *keywds) +{ + double x; + int precision = _PRECISION; + int rint_x; + + static char *kwlist[] = {"x", "precision", NULL}; + + if(!PyArg_ParseTupleAndKeywords(args, keywds, "d|l", kwlist, + &x, &precision)) + return NULL; + rint_x = (int)(x * precision + 0.5); +#if PY_MAJOR_VERSION >= 3 + return PyLong_FromLong((long)rint_x); +#else + return PyInt_FromLong((long)rint_x); +#endif +} + +/* Module definition stuff */ + +static PyMethodDef cpairwise2Methods[] = { + {"_make_score_matrix_fast", + (PyCFunction)cpairwise2__make_score_matrix_fast, METH_VARARGS, ""}, + {"rint", (PyCFunction)cpairwise2_rint, METH_VARARGS|METH_KEYWORDS, ""}, + {NULL, NULL, 0, NULL} +}; + +static char cpairwise2__doc__[] = +"Optimized C routines that complement pairwise2.py. These are called from within pairwise2.py.\n\ +\n\ +"; + +#if PY_MAJOR_VERSION >= 3 + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "cpairwise2", + cpairwise2__doc__, + -1, + cpairwise2Methods, + NULL, + NULL, + NULL, + NULL +}; + +PyObject * +PyInit_cpairwise2(void) + +#else + +void +/* for Windows: _declspec(dllexport) initcpairwise2(void) */ +initcpairwise2(void) +#endif + +{ +#if PY_MAJOR_VERSION >= 3 + PyObject* module = PyModule_Create(&moduledef); + if (module==NULL) return NULL; + return module; +#else + (void) Py_InitModule3("cpairwise2", cpairwise2Methods, cpairwise2__doc__); +#endif +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.__pwm.c b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.__pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.__pwm.c differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.__pwm.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.__pwm.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/.__pwm.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._alignace.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._alignace.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._alignace.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._clusterbuster.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._clusterbuster.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._clusterbuster.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._jaspar b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._jaspar new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._jaspar differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._mast.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._mast.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._mast.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._matrix.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._matrix.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._meme.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._meme.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._meme.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._minimal.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._minimal.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._pfm.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._pfm.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._pfm.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._thresholds.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._thresholds.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._thresholds.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._transfac.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._transfac.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._transfac.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._xms.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._xms.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/._xms.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59535db70adfe4047695a9d7346714242b4bf14b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/__init__.py @@ -0,0 +1,645 @@ +# Copyright 2003-2009 by Bartek Wilczynski. All rights reserved. +# Copyright 2012-2013 by Michiel JL de Hoon. All rights reserved. +# Revisions copyright 2019 by Victor Lin. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Tools for sequence motif analysis. + +Bio.motifs contains the core Motif class containing various I/O methods +as well as methods for motif comparisons and motif searching in sequences. +It also includes functionality for parsing output from the AlignACE, MEME, +and MAST programs, as well as files in the TRANSFAC format. +""" + +from urllib.parse import urlencode +from urllib.request import Request +from urllib.request import urlopen + +try: + import numpy as np +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install NumPy if you want to use Bio.motifs." + ) from None + +from Bio.Align import Alignment + + +def create(instances, alphabet="ACGT"): + """Create a Motif object.""" + alignment = Alignment(instances) + return Motif(alignment=alignment, alphabet=alphabet) + + +def parse(handle, fmt, strict=True): + """Parse an output file from a motif finding program. + + Currently supported formats (case is ignored): + - AlignAce: AlignAce output file format + - ClusterBuster: Cluster Buster position frequency matrix format + - XMS: XMS matrix format + - MEME: MEME output file motif + - MINIMAL: MINIMAL MEME output file motif + - MAST: MAST output file motif + - TRANSFAC: TRANSFAC database file format + - pfm-four-columns: Generic position-frequency matrix format with four columns. (CIS-BP, HOMER, HOCOMOCO, Neph, Tiffin) + - pfm-four-rows: Generic position-frequency matrix format with four row. (ScerTF, YeTFaSCo, hDPI, iDMMPMM, FlyFactorSurvey, Cys2His2 Zinc Finger Proteins PWM Predictor) + - pfm: JASPAR-style position-frequency matrix + - jaspar: JASPAR-style multiple PFM format + - sites: JASPAR-style sites file + + As files in the pfm and sites formats contain only a single motif, + it is easier to use Bio.motifs.read() instead of Bio.motifs.parse() + for those. + + For example: + + >>> from Bio import motifs + >>> with open("motifs/alignace.out") as handle: + ... for m in motifs.parse(handle, "AlignAce"): + ... print(m.consensus) + ... + TCTACGATTGAG + CTGCACCTAGCTACGAGTGAG + GTGCCCTAAGCATACTAGGCG + GCCACTAGCAGAGCAGGGGGC + CGACTCAGAGGTT + CCACGCTAAGAGAAGTGCCGGAG + GCACGTCCCTGAGCA + GTCCATCGCAAAGCGTGGGGC + GAGATCAGAGGGCCG + TGGACGCGGGG + GACCAGAGCCTCGCATGGGGG + AGCGCGCGTG + GCCGGTTGCTGTTCATTAGG + ACCGACGGCAGCTAAAAGGG + GACGCCGGGGAT + CGACTCGCGCTTACAAGG + + If strict is True (default), the parser will raise a ValueError if the + file contents does not strictly comply with the specified file format. + """ + fmt = fmt.lower() + if fmt == "alignace": + from Bio.motifs import alignace + + return alignace.read(handle) + elif fmt == "meme": + from Bio.motifs import meme + + return meme.read(handle) + elif fmt == "minimal": + from Bio.motifs import minimal + + return minimal.read(handle) + elif fmt == "clusterbuster": + from Bio.motifs import clusterbuster + + return clusterbuster.read(handle) + elif fmt in ("pfm-four-columns", "pfm-four-rows"): + from Bio.motifs import pfm + + return pfm.read(handle, fmt) + elif fmt == "xms": + from Bio.motifs import xms + + return xms.read(handle) + elif fmt == "mast": + from Bio.motifs import mast + + return mast.read(handle) + elif fmt == "transfac": + from Bio.motifs import transfac + + return transfac.read(handle, strict) + elif fmt in ("pfm", "sites", "jaspar"): + from Bio.motifs import jaspar + + return jaspar.read(handle, fmt) + else: + raise ValueError("Unknown format %s" % fmt) + + +def read(handle, fmt, strict=True): + """Read a motif from a handle using the specified file-format. + + This supports the same formats as Bio.motifs.parse(), but + only for files containing exactly one motif. For example, + reading a JASPAR-style pfm file: + + >>> from Bio import motifs + >>> with open("motifs/SRF.pfm") as handle: + ... m = motifs.read(handle, "pfm") + >>> m.consensus + Seq('GCCCATATATGG') + + Or a single-motif MEME file, + + >>> from Bio import motifs + >>> with open("motifs/meme.psp_test.classic.zoops.xml") as handle: + ... m = motifs.read(handle, "meme") + >>> m.consensus + Seq('GCTTATGTAA') + + If the handle contains no records, or more than one record, + an exception is raised: + + >>> from Bio import motifs + >>> with open("motifs/alignace.out") as handle: + ... motif = motifs.read(handle, "AlignAce") + Traceback (most recent call last): + ... + ValueError: More than one motif found in handle + + If however you want the first motif from a file containing + multiple motifs this function would raise an exception (as + shown in the example above). Instead use: + + >>> from Bio import motifs + >>> with open("motifs/alignace.out") as handle: + ... record = motifs.parse(handle, "alignace") + >>> motif = record[0] + >>> motif.consensus + Seq('TCTACGATTGAG') + + Use the Bio.motifs.parse(handle, fmt) function if you want + to read multiple records from the handle. + + If strict is True (default), the parser will raise a ValueError if the + file contents does not strictly comply with the specified file format. + """ + fmt = fmt.lower() + motifs = parse(handle, fmt, strict) + if len(motifs) == 0: + raise ValueError("No motifs found in handle") + if len(motifs) > 1: + raise ValueError("More than one motif found in handle") + motif = motifs[0] + return motif + + +class Motif: + """A class representing sequence motifs.""" + + def __init__(self, alphabet="ACGT", alignment=None, counts=None): + """Initialize the class.""" + from . import matrix + + self.name = "" + if counts is not None and alignment is not None: + raise Exception( + ValueError, "Specify either counts or an alignment, don't specify both" + ) + elif counts is not None: + self.alignment = None + self.counts = matrix.FrequencyPositionMatrix(alphabet, counts) + self.length = self.counts.length + elif alignment is not None: + length = alignment.length + frequencies = alignment.frequencies + for letter in alphabet: + if letter not in frequencies: + frequencies[letter] = np.zeros(length, int) + self.counts = matrix.FrequencyPositionMatrix(alphabet, frequencies) + self.alignment = alignment + self.length = length + else: + self.counts = None + self.alignment = None + self.length = None + self.alphabet = alphabet + self.pseudocounts = None + self.background = None + self.mask = None + + def __get_mask(self): + return self.__mask + + def __set_mask(self, mask): + if self.length is None: + self.__mask = () + elif mask is None: + self.__mask = (1,) * self.length + elif len(mask) != self.length: + raise ValueError( + "The length (%d) of the mask is inconsistent with the length (%d) of the motif" + % (len(mask), self.length), + ) + elif isinstance(mask, str): + self.__mask = [] + for char in mask: + if char == "*": + self.__mask.append(1) + elif char == " ": + self.__mask.append(0) + else: + raise ValueError( + "Mask should contain only '*' or ' ' and not a '%s'" % char + ) + self.__mask = tuple(self.__mask) + else: + self.__mask = tuple(int(bool(c)) for c in mask) + + mask = property(__get_mask, __set_mask) + del __get_mask + del __set_mask + + def __get_pseudocounts(self): + return self._pseudocounts + + def __set_pseudocounts(self, value): + self._pseudocounts = {} + if isinstance(value, dict): + self._pseudocounts = {letter: value[letter] for letter in self.alphabet} + else: + if value is None: + value = 0.0 + self._pseudocounts = dict.fromkeys(self.alphabet, value) + + pseudocounts = property(__get_pseudocounts, __set_pseudocounts) + del __get_pseudocounts + del __set_pseudocounts + + def __get_background(self): + return self._background + + def __set_background(self, value): + if isinstance(value, dict): + self._background = {letter: value[letter] for letter in self.alphabet} + elif value is None: + self._background = dict.fromkeys(self.alphabet, 1.0) + else: + if not self._has_dna_alphabet() and not self._has_rna_alphabet(): + raise ValueError( + "Setting the background to a single value only works for DNA and RNA" + "motifs (in which case the value is interpreted as the GC content)" + ) + T_or_U = "T" if self._has_dna_alphabet() else "U" + self._background["A"] = (1.0 - value) / 2.0 + self._background["C"] = value / 2.0 + self._background["G"] = value / 2.0 + self._background[T_or_U] = (1.0 - value) / 2.0 + total = sum(self._background.values()) + for letter in self.alphabet: + self._background[letter] /= total + + background = property(__get_background, __set_background) + del __get_background + del __set_background + + def __getitem__(self, key): + """Return a new Motif object for the positions included in key. + + >>> from Bio import motifs + >>> motif = motifs.create(["AACGCCA", "ACCGCCC", "AACTCCG"]) + >>> print(motif) + AACGCCA + ACCGCCC + AACTCCG + >>> print(motif[:-1]) + AACGCC + ACCGCC + AACTCC + """ + if not isinstance(key, slice): + raise TypeError("motif indices must be slices") + alphabet = self.alphabet + if self.alignment is None: + alignment = None + if self.counts is None: + counts = None + else: + counts = {letter: self.counts[letter][key] for letter in alphabet} + else: + alignment = self.alignment[:, key] + counts = None + motif = Motif(alphabet=alphabet, alignment=alignment, counts=counts) + motif.mask = self.mask[key] + if alignment is None and counts is None: + try: + length = self.length + except AttributeError: + pass + else: + motif.length = len(range(*key.indices(length))) + motif.pseudocounts = self.pseudocounts.copy() + motif.background = self.background.copy() + return motif + + @property + def pwm(self): + """Calculate and return the position weight matrix for this motif.""" + return self.counts.normalize(self._pseudocounts) + + @property + def pssm(self): + """Calculate and return the position specific scoring matrix for this motif.""" + return self.pwm.log_odds(self._background) + + def __str__(self, masked=False): + """Return string representation of a motif.""" + text = "" + if self.alignment is not None: + text += "\n".join(self.alignment) + + if masked: + for i in range(self.length): + if self.__mask[i]: + text += "*" + else: + text += " " + text += "\n" + return text + + def __len__(self): + """Return the length of a motif. + + Please use this method (i.e. invoke len(m)) instead of referring to m.length directly. + """ + if self.length is None: + return 0 + else: + return self.length + + def _has_dna_alphabet(self): + return sorted(self.alphabet) == ["A", "C", "G", "T"] + + def _has_rna_alphabet(self): + return sorted(self.alphabet) == ["A", "C", "G", "U"] + + def reverse_complement(self): + """Return the reverse complement of the motif as a new motif.""" + alphabet = self.alphabet + if not self._has_dna_alphabet() and not self._has_rna_alphabet(): + raise ValueError( + "Calculating reverse complement only works for DNA and RNA motifs" + ) + T_or_U = "T" if self._has_dna_alphabet() else "U" + if self.alignment is not None: + alignment = self.alignment.reverse_complement() + if T_or_U == "U": + alignment.sequences = [s.replace("T", "U") for s in alignment.sequences] + res = Motif(alphabet=alphabet, alignment=alignment) + else: # has counts + counts = { + "A": self.counts[T_or_U][::-1], + "C": self.counts["G"][::-1], + "G": self.counts["C"][::-1], + T_or_U: self.counts["A"][::-1], + } + res = Motif(alphabet=alphabet, counts=counts) + res.__mask = self.__mask[::-1] + res.background = { + "A": self.background[T_or_U], + "C": self.background["G"], + "G": self.background["C"], + T_or_U: self.background["A"], + } + res.pseudocounts = { + "A": self.pseudocounts[T_or_U], + "C": self.pseudocounts["G"], + "G": self.pseudocounts["C"], + T_or_U: self.pseudocounts["A"], + } + return res + + @property + def consensus(self): + """Return the consensus sequence.""" + return self.counts.consensus + + @property + def anticonsensus(self): + """Return the least probable pattern to be generated from this motif.""" + return self.counts.anticonsensus + + @property + def degenerate_consensus(self): + """Return the degenerate consensus sequence. + + Following the rules adapted from + D. R. Cavener: "Comparison of the consensus sequence flanking + translational start sites in Drosophila and vertebrates." + Nucleic Acids Research 15(4): 1353-1361. (1987). + + The same rules are used by TRANSFAC. + """ + return self.counts.degenerate_consensus + + @property + def relative_entropy(self): + """Return an array with the relative entropy for each column of the motif.""" + background = self.background + pseudocounts = self.pseudocounts + alphabet = self.alphabet + counts = self.counts + length = self.length + values = np.zeros(length) + if self.alignment is None: + total = np.array( + [ + sum(counts[c][i] + pseudocounts[c] for c in alphabet) + for i in range(length) + ] + ) + for letter, frequencies in counts.items(): + frequencies = np.array(frequencies) + pseudocounts[letter] + mask = frequencies > 0 + frequencies = frequencies[mask] / total[mask] + values[mask] += frequencies * np.log2(frequencies / background[letter]) + else: + total = np.zeros(length) + for letter, frequencies in counts.items(): + total += np.array(frequencies) + pseudocounts[letter] + for letter, frequencies in counts.items(): + frequencies = np.array(frequencies) + pseudocounts[letter] + mask = frequencies > 0 + frequencies = frequencies[mask] / total[mask] + values[mask] += frequencies * np.log2(frequencies / background[letter]) + return values + + def weblogo(self, fname, fmt="PNG", **kwds): + """Download and save a weblogo using the Berkeley weblogo service. + + Requires an internet connection. + + The parameters from ``**kwds`` are passed directly to the weblogo server. + + Currently, this method uses WebLogo version 3.3. + These are the arguments and their default values passed to + WebLogo 3.3; see their website at http://weblogo.threeplusone.com + for more information:: + + 'stack_width' : 'medium', + 'stacks_per_line' : '40', + 'alphabet' : 'alphabet_dna', + 'ignore_lower_case' : True, + 'unit_name' : "bits", + 'first_index' : '1', + 'logo_start' : '1', + 'logo_end': str(self.length), + 'composition' : "comp_auto", + 'percentCG' : '', + 'scale_width' : True, + 'show_errorbars' : True, + 'logo_title' : '', + 'logo_label' : '', + 'show_xaxis': True, + 'xaxis_label': '', + 'show_yaxis': True, + 'yaxis_label': '', + 'yaxis_scale': 'auto', + 'yaxis_tic_interval' : '1.0', + 'show_ends' : True, + 'show_fineprint' : True, + 'color_scheme': 'color_auto', + 'symbols0': '', + 'symbols1': '', + 'symbols2': '', + 'symbols3': '', + 'symbols4': '', + 'color0': '', + 'color1': '', + 'color2': '', + 'color3': '', + 'color4': '', + + """ + if set(self.alphabet) == set("ACDEFGHIKLMNPQRSTVWY"): + alpha = "alphabet_protein" + elif set(self.alphabet) == set("ACGU"): + alpha = "alphabet_rna" + elif set(self.alphabet) == set("ACGT"): + alpha = "alphabet_dna" + else: + alpha = "auto" + + frequencies = format(self, "transfac") + url = "https://weblogo.threeplusone.com/create.cgi" + values = { + "sequences": frequencies, + "format": fmt.lower(), + "stack_width": "medium", + "stacks_per_line": "40", + "alphabet": alpha, + "ignore_lower_case": True, + "unit_name": "bits", + "first_index": "1", + "logo_start": "1", + "logo_end": str(self.length), + "composition": "comp_auto", + "percentCG": "", + "scale_width": True, + "show_errorbars": True, + "logo_title": "", + "logo_label": "", + "show_xaxis": True, + "xaxis_label": "", + "show_yaxis": True, + "yaxis_label": "", + "yaxis_scale": "auto", + "yaxis_tic_interval": "1.0", + "show_ends": True, + "show_fineprint": True, + "color_scheme": "color_auto", + "symbols0": "", + "symbols1": "", + "symbols2": "", + "symbols3": "", + "symbols4": "", + "color0": "", + "color1": "", + "color2": "", + "color3": "", + "color4": "", + } + + values.update({k: "" if v is False else str(v) for k, v in kwds.items()}) + data = urlencode(values).encode("utf-8") + req = Request(url, data) + response = urlopen(req) + with open(fname, "wb") as f: + im = response.read() + f.write(im) + + def __format__(self, format_spec, **kwargs): + """Return a string representation of the Motif in the given format. + + Currently supported formats: + - clusterbuster: Cluster Buster position frequency matrix format + - pfm : JASPAR single Position Frequency Matrix + - jaspar : JASPAR multiple Position Frequency Matrix + - transfac : TRANSFAC like files + + """ + if format_spec in ("pfm", "jaspar"): + from Bio.motifs import jaspar + + motifs = [self] + return jaspar.write(motifs, format_spec) + elif format_spec == "transfac": + from Bio.motifs import transfac + + motifs = [self] + return transfac.write(motifs) + elif format_spec == "clusterbuster": + from Bio.motifs import clusterbuster + + motifs = [self] + return clusterbuster.write(motifs, **kwargs) + elif not format_spec: + # Follow python convention and default to using __str__ + return str(self) + else: + raise ValueError("Unknown format type %s" % format_spec) + + def format(self, format_spec): + """Return a string representation of the Motif in the given format. + + Currently supported formats: + - clusterbuster: Cluster Buster position frequency matrix format + - pfm : JASPAR single Position Frequency Matrix + - jaspar : JASPAR multiple Position Frequency Matrix + - transfac : TRANSFAC like files + + """ + return self.__format__(format_spec) + + +def write(motifs, fmt, **kwargs): + """Return a string representation of motifs in the given format. + + Currently supported formats (case is ignored): + - clusterbuster: Cluster Buster position frequency matrix format + - pfm : JASPAR simple single Position Frequency Matrix + - jaspar : JASPAR multiple PFM format + - transfac : TRANSFAC like files + + """ + fmt = fmt.lower() + if fmt in ("pfm", "jaspar"): + from Bio.motifs import jaspar + + return jaspar.write(motifs, fmt) + elif fmt == "transfac": + from Bio.motifs import transfac + + return transfac.write(motifs) + elif fmt == "clusterbuster": + from Bio.motifs import clusterbuster + + return clusterbuster.write(motifs, **kwargs) + else: + raise ValueError("Unknown format type %s" % fmt) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/_pwm.c b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..5ef5c0bdcb42bea0c960225d971eacfe3a5c7c73 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/_pwm.c @@ -0,0 +1,216 @@ +/* Copyright 2009-2020 by Michiel de Hoon. All rights reserved. + * + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + */ + +#define PY_SSIZE_T_CLEAN +#include +#include + + +static void +calculate(const char sequence[], Py_ssize_t m, double* matrix, Py_ssize_t n, + float* scores) +{ + Py_ssize_t i, j; + char c; + double score; + int ok; + float* p = scores; +#ifndef NAN + float NAN = 0.0; + NAN /= NAN; +#endif + + for (i = 0; i < n; i++) + { + score = 0.0; + ok = 1; + for (j = 0; j < m; j++) + { + c = sequence[i+j]; + switch (c) + { + /* Handling mixed case input here rather than converting it to + uppercase in Python code first, since doing so could use too + much memory if sequence is too long (e.g. chromosome or + plasmid). */ + case 'A': + case 'a': + score += matrix[j*4+0]; break; + case 'C': + case 'c': + score += matrix[j*4+1]; break; + case 'G': + case 'g': + score += matrix[j*4+2]; break; + case 'T': + case 't': + score += matrix[j*4+3]; break; + default: + ok = 0; + } + } + if (ok) *p = (float)score; + else *p = NAN; + p++; + } +} + +static int +matrix_converter(PyObject* object, void* address) +{ + const int flags = PyBUF_C_CONTIGUOUS | PyBUF_FORMAT; + char datatype; + Py_buffer* view = address; + + if (object == NULL) goto exit; + if (PyObject_GetBuffer(object, view, flags) == -1) { + PyErr_SetString(PyExc_RuntimeError, + "position-weight matrix is not an array"); + return 0; + } + datatype = view->format[0]; + switch (datatype) { + case '@': + case '=': + case '<': + case '>': + case '!': datatype = view->format[1]; break; + default: break; + } + if (datatype != 'd') { + PyErr_Format(PyExc_RuntimeError, + "position-weight matrix data format incorrect " + "('%c', expected 'd')", datatype); + goto exit; + } + if (view->ndim != 2) { + PyErr_Format(PyExc_RuntimeError, + "position-weight matrix has incorrect rank (%d expected 2)", + view->ndim); + goto exit; + } + if (view->shape[1] != 4) { + PyErr_Format(PyExc_RuntimeError, + "position-weight matrix should have four columns " + "(%zd columns found)", view->shape[1]); + goto exit; + } + return Py_CLEANUP_SUPPORTED; + +exit: + PyBuffer_Release(view); + return 0; +} + +static int +scores_converter(PyObject* object, void* address) +{ + const int flags = PyBUF_C_CONTIGUOUS | PyBUF_FORMAT; + char datatype; + Py_buffer* view = address; + + if (object == NULL) goto exit; + if (PyObject_GetBuffer(object, view, flags) == -1) return 0; + datatype = view->format[0]; + switch (datatype) { + case '@': + case '=': + case '<': + case '>': + case '!': datatype = view->format[1]; break; + default: break; + } + if (datatype != 'f') { + PyErr_Format(PyExc_RuntimeError, + "scores array has incorrect data format ('%c', expected 'f')", + datatype); + goto exit; + } + if (view->ndim != 1) { + PyErr_Format(PyExc_ValueError, + "scores array has incorrect rank (%d expected 1)", + view->ndim); + goto exit; + } + return Py_CLEANUP_SUPPORTED; + +exit: + PyBuffer_Release(view); + return 0; +} + +static char calculate__doc__[] = +" calculate(sequence, pwm, scores)\n" +"\n" +"This function calculates the position-weight matrix scores for all\n" +"positions along the sequence for position-weight matrix pwm, and stores\n" +"them in the provided numpy array scores.\n"; + +static PyObject* +py_calculate(PyObject* self, PyObject* args, PyObject* keywords) +{ + const char* sequence; + static char* kwlist[] = {"sequence", "matrix", "scores", NULL}; + Py_ssize_t m; + Py_ssize_t n; + Py_ssize_t s; + PyObject* result = NULL; + Py_buffer scores; + Py_buffer matrix; + + matrix.obj = NULL; + scores.obj = NULL; + if (!PyArg_ParseTupleAndKeywords(args, keywords, "y#O&O&", kwlist, + &sequence, &s, + matrix_converter, &matrix, + scores_converter, &scores)) return NULL; + m = matrix.shape[0]; + n = scores.shape[0]; + if (n == s - m + 1) { + calculate(sequence, m, matrix.buf, n, scores.buf); + Py_INCREF(Py_None); + result = Py_None; + } + else { + PyErr_Format(PyExc_RuntimeError, + "size of scores array is inconsistent " + "(sequence length is %zd, " + "motif length is %zd, scores length is %zd", s, m, n); + } + + matrix_converter(NULL, &matrix); + scores_converter(NULL, &scores); + return result; +} + +static struct PyMethodDef methods[] = { + {"calculate", + (PyCFunction)py_calculate, + METH_VARARGS | METH_KEYWORDS, + PyDoc_STR(calculate__doc__), + }, + {NULL, NULL, 0, NULL} /* sentinel */ +}; + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "_pwm", + PyDoc_STR("Fast calculations involving position-weight matrices"), + -1, + methods, + NULL, + NULL, + NULL, + NULL +}; + +PyObject* +PyInit__pwm(void) +{ + return PyModule_Create(&moduledef); +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/_pwm.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/_pwm.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..543387439e68ad85465f2976780c99b8ffc988b7 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/_pwm.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/alignace.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/alignace.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a9dcb8fe1cccb6b8e9d2af3b72a7aee1fbdb75 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/alignace.py @@ -0,0 +1,68 @@ +# Copyright 2003 by Bartek Wilczynski. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Parsing AlignACE output files.""" + +from Bio.Align import Alignment +from Bio.motifs import Motif +from Bio.Seq import Seq + + +class Record(list): + """AlignACE record (subclass of Python list).""" + + def __init__(self): + """Initialize the class.""" + self.parameters = None + + +def read(handle): + """Parse an AlignACE format handle as a Record object.""" + record = Record() + line = next(handle) + record.version = line.strip() + line = next(handle) + record.command = line.strip() + mask = None + number = None + for line in handle: + line = line.strip() + if line == "": + pass + elif line[:4] == "Para": + record.parameters = {} + elif line[0] == "#": + seq_name = line.split("\t")[1] + record.sequences.append(seq_name) + elif "=" in line: + par_name, par_value = line.split("=") + par_name = par_name.strip() + par_value = par_value.strip() + record.parameters[par_name] = par_value + elif line[:5] == "Input": + record.sequences = [] + elif line[:5] == "Motif": + words = line.split() + assert words[0] == "Motif" + number = int(words[1]) + instances = [] + elif line[:3] == "MAP": + alphabet = "ACGT" + alignment = Alignment(instances) + motif = Motif(alphabet, alignment) + motif.score = float(line.split()[-1]) + motif.number = number + motif.mask = mask + record.append(motif) + elif len(line.split("\t")) == 4: + seq = Seq(line.split("\t")[0]) + instances.append(seq) + elif "*" in line: + mask = line.strip("\r\n") + else: + raise ValueError(line) + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/clusterbuster.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/clusterbuster.py new file mode 100644 index 0000000000000000000000000000000000000000..baf8f07c2625976ab40d70ce56b3fabf5c364c23 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/clusterbuster.py @@ -0,0 +1,117 @@ +# Copyright 2015 by Gert Hulselmans. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Parse Cluster Buster position frequency matrix files.""" + +from Bio import motifs + + +class Record(list): + """Class to store the information in a Cluster Buster matrix table. + + The record inherits from a list containing the individual motifs. + """ + + def __str__(self): + """Return a string representation of the motifs in the Record object.""" + return "\n".join(str(motif) for motif in self) + + +def read(handle): + """Read motifs in Cluster Buster position frequency matrix format from a file handle. + + Cluster Buster motif format: https://bu.wenglab.org/cluster-buster/help/cis-format.html + """ + motif_nbr = 0 + record = Record() + nucleotide_counts = {"A": [], "C": [], "G": [], "T": []} + motif_name = "" + motif_gap = None + motif_weight = None + + for line in handle: + line = line.strip() + if line: + if line.startswith(">"): + if motif_nbr != 0: + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name + motif.gap = motif_gap + motif.weight = motif_weight + record.append(motif) + + motif_name = line[1:].strip() + nucleotide_counts = {"A": [], "C": [], "G": [], "T": []} + motif_gap = None + motif_weight = None + motif_nbr += 1 + else: + if line.startswith("# GAP"): + motif_gap = float(line.split()[2]) + continue + elif line.startswith("# WEIGHT"): + motif_weight = float(line.split()[2]) + continue + elif line.startswith("#"): + continue + + matrix_columns = line.split() + + if len(matrix_columns) == 4: + [ + nucleotide_counts[nucleotide].append(float(nucleotide_count)) + for nucleotide, nucleotide_count in zip( + ["A", "C", "G", "T"], matrix_columns + ) + ] + + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name + motif.gap = motif_gap + motif.weight = motif_weight + record.append(motif) + + return record + + +def write(motifs, precision=0): + """Return the representation of motifs in Cluster Buster position frequency matrix format. + + By default (`precision=0`) Cluster Buster position frequency matrices will be written + with integer values. + If a higher precision value is set, Cluster Buster position frequency matrices will be + written as floats with `x` decimal places. + """ + lines = [] + for m in motifs: + lines.append(f">{m.name}\n") + try: + weight = m.weight + except AttributeError: + pass + else: + if weight: + lines.append(f"# WEIGHT: {weight}\n") + try: + gap = m.gap + except AttributeError: + pass + else: + if gap: + lines.append(f"# GAP: {gap}\n") + for ACGT_counts in zip( + m.counts["A"], m.counts["C"], m.counts["G"], m.counts["T"] + ): + lines.append( + "{:0.0f}\t{:0.0f}\t{:0.0f}\t{:0.0f}\n".replace( + "0f", str(int(precision)) + "f" + ).format(*ACGT_counts) + ) + + # Finished; glue the lines together. + text = "".join(lines) + + return text diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/._db.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/._db.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/._db.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..060f400ebba72c93940031764bf347e60381ae07 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/__init__.py @@ -0,0 +1,374 @@ +# Copyright 2013 by Anthony Mathelier and David Arenillas. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""JASPAR2014 module.""" + +import math +import re + +from Bio import Align +from Bio import motifs +from Bio.Seq import Seq + + +class Motif(motifs.Motif): + """A subclass of Bio.motifs.Motif used to represent a JASPAR profile. + + Additional metadata information are stored if available. The metadata + availability depends on the source of the JASPAR motif (a 'pfm' format + file, a 'jaspar' format file or a JASPAR database). + """ + + def __init__( + self, + matrix_id, + name, + alphabet="ACGT", + alignment=None, + counts=None, + collection=None, + tf_class=None, + tf_family=None, + species=None, + tax_group=None, + acc=None, + data_type=None, + medline=None, + pazar_id=None, + comment=None, + ): + """Construct a JASPAR Motif instance.""" + motifs.Motif.__init__(self, alphabet, alignment, counts) + self.name = name + self.matrix_id = matrix_id + self.collection = collection + self.tf_class = tf_class + self.tf_family = tf_family + # May have multiple so species is a list. + # The species are actually specified as + # taxonomy IDs. + self.species = species + self.tax_group = tax_group + self.acc = acc # May have multiple so acc is a list. + self.data_type = data_type + self.medline = medline + self.pazar_id = pazar_id + self.comment = comment + + @property + def base_id(self): + """Return the JASPAR base matrix ID.""" + (base_id, __) = split_jaspar_id(self.matrix_id) + return base_id + + @property + def version(self): + """Return the JASPAR matrix version.""" + (__, version) = split_jaspar_id(self.matrix_id) + return version + + def __str__(self): + """Return a string representation of the JASPAR profile. + + We choose to provide only the filled metadata information. + """ + tf_name_str = f"TF name\t{self.name}\n" + matrix_id_str = f"Matrix ID\t{self.matrix_id}\n" + the_string = "".join([tf_name_str, matrix_id_str]) + if self.collection: + collection_str = f"Collection\t{self.collection}\n" + the_string = "".join([the_string, collection_str]) + if self.tf_class: + tf_class_str = f"TF class\t{self.tf_class}\n" + the_string = "".join([the_string, tf_class_str]) + if self.tf_family: + tf_family_str = f"TF family\t{self.tf_family}\n" + the_string = "".join([the_string, tf_family_str]) + if self.species: + species_str = f"Species\t{','.join(self.species)}\n" + the_string = "".join([the_string, species_str]) + if self.tax_group: + tax_group_str = f"Taxonomic group\t{self.tax_group}\n" + the_string = "".join([the_string, tax_group_str]) + if self.acc: + acc_str = f"Accession\t{self.acc}\n" + the_string = "".join([the_string, acc_str]) + if self.data_type: + data_type_str = f"Data type used\t{self.data_type}\n" + the_string = "".join([the_string, data_type_str]) + if self.medline: + medline_str = f"Medline\t{self.medline}\n" + the_string = "".join([the_string, medline_str]) + if self.pazar_id: + pazar_id_str = f"PAZAR ID\t{self.pazar_id}\n" + the_string = "".join([the_string, pazar_id_str]) + if self.comment: + comment_str = f"Comments\t{self.comment}\n" + the_string = "".join([the_string, comment_str]) + matrix_str = f"Matrix:\n{self.counts}\n\n" + the_string = "".join([the_string, matrix_str]) + return the_string + + def __hash__(self): + """Return the hash key corresponding to the JASPAR profile. + + :note: We assume the unicity of matrix IDs + + """ + return self.matrix_id.__hash__() + + def __eq__(self, other): + """Return True if matrix IDs are the same.""" + return self.matrix_id == other.matrix_id + + +class Record(list): + """Represent a list of jaspar motifs. + + Attributes: + - version: The JASPAR version used + + """ + + def __init__(self): + """Initialize the class.""" + self.version = None + + def __str__(self): + """Return a string of all motifs in the Record.""" + return "\n".join(str(the_motif) for the_motif in self) + + def to_dict(self): + """Return the list of matrices as a dictionary of matrices.""" + dic = {} + for motif in self: + dic[motif.matrix_id] = motif + return dic + + +def read(handle, format): + """Read motif(s) from a file in one of several different JASPAR formats. + + Return the record of PFM(s). + Call the appropriate routine based on the format passed. + """ + format = format.lower() + if format == "pfm": + record = _read_pfm(handle) + return record + elif format == "sites": + record = _read_sites(handle) + return record + elif format == "jaspar": + record = _read_jaspar(handle) + return record + else: + raise ValueError("Unknown JASPAR format %s" % format) + + +def write(motifs, format): + """Return the representation of motifs in "pfm" or "jaspar" format.""" + letters = "ACGT" + lines = [] + if format == "pfm": + motif = motifs[0] + counts = motif.counts + for letter in letters: + terms = [f"{value:6.2f}" for value in counts[letter]] + line = f"{' '.join(terms)}\n" + lines.append(line) + elif format == "jaspar": + for m in motifs: + counts = m.counts + try: + matrix_id = m.matrix_id + except AttributeError: + matrix_id = None + line = f">{matrix_id} {m.name}\n" + lines.append(line) + for letter in letters: + terms = [f"{value:6.2f}" for value in counts[letter]] + line = f"{letter} [{' '.join(terms)}]\n" + lines.append(line) + else: + raise ValueError("Unknown JASPAR format %s" % format) + + # Finished; glue the lines together + text = "".join(lines) + + return text + + +def _read_pfm(handle): + """Read the motif from a JASPAR .pfm file (PRIVATE).""" + alphabet = "ACGT" + counts = {} + + for letter, line in zip(alphabet, handle): + words = line.split() + # if there is a letter in the beginning, ignore it + if words[0] == letter: + words = words[1:] + counts[letter] = [float(x) for x in words] + + motif = Motif(matrix_id=None, name=None, alphabet=alphabet, counts=counts) + motif.mask = "*" * motif.length + record = Record() + record.append(motif) + + return record + + +def _read_sites(handle): + """Read the motif from JASPAR .sites file (PRIVATE).""" + alphabet = "ACGT" + instances = [] + + for line in handle: + if not line.startswith(">"): + break + # line contains the header ">...." + # now read the actual sequence + line = next(handle) + instance = "" + for c in line.strip(): + if c.isupper(): + instance += c + instance = Seq(instance) + instances.append(instance) + + alignment = Align.Alignment(instances) + motif = Motif(matrix_id=None, name=None, alphabet=alphabet, alignment=alignment) + motif.mask = "*" * motif.length + record = Record() + record.append(motif) + + return record + + +def _read_jaspar(handle): + """Read motifs from a JASPAR formatted file (PRIVATE). + + Format is one or more records of the form, e.g.:: + + - JASPAR 2010 matrix_only format:: + + >MA0001.1 AGL3 + A [ 0 3 79 40 66 48 65 11 65 0 ] + C [94 75 4 3 1 2 5 2 3 3 ] + G [ 1 0 3 4 1 0 5 3 28 88 ] + T [ 2 19 11 50 29 47 22 81 1 6 ] + + - JASPAR 2010-2014 PFMs format:: + + >MA0001.1 AGL3 + 0 3 79 40 66 48 65 11 65 0 + 94 75 4 3 1 2 5 2 3 3 + 1 0 3 4 1 0 5 3 28 88 + 2 19 11 50 29 47 22 81 1 6 + + """ + alphabet = "ACGT" + counts = {} + + record = Record() + + head_pat = re.compile(r"^>\s*(\S+)(\s+(\S+))?") + row_pat_long = re.compile(r"\s*([ACGT])\s*\[\s*(.*)\s*\]") + row_pat_short = re.compile(r"\s*(.+)\s*") + + identifier = None + name = None + row_count = 0 + nucleotides = ["A", "C", "G", "T"] + for line in handle: + line = line.strip() + + head_match = head_pat.match(line) + row_match_long = row_pat_long.match(line) + row_match_short = row_pat_short.match(line) + + if head_match: + identifier = head_match.group(1) + if head_match.group(3): + name = head_match.group(3) + else: + name = identifier + elif row_match_long: + (letter, counts_str) = row_match_long.group(1, 2) + words = counts_str.split() + counts[letter] = [float(x) for x in words] + row_count += 1 + if row_count == 4: + record.append(Motif(identifier, name, alphabet=alphabet, counts=counts)) + identifier = None + name = None + counts = {} + row_count = 0 + elif row_match_short: + words = row_match_short.group(1).split() + counts[nucleotides[row_count]] = [float(x) for x in words] + row_count += 1 + if row_count == 4: + record.append(Motif(identifier, name, alphabet=alphabet, counts=counts)) + identifier = None + name = None + counts = {} + row_count = 0 + + return record + + +def calculate_pseudocounts(motif): + """Calculate pseudocounts. + + Computes the root square of the total number of sequences multiplied by + the background nucleotide. + """ + alphabet = motif.alphabet + background = motif.background + + # It is possible to have unequal column sums so use the average + # number of instances. + total = 0 + for i in range(motif.length): + total += sum(motif.counts[letter][i] for letter in alphabet) + + avg_nb_instances = total / motif.length + sq_nb_instances = math.sqrt(avg_nb_instances) + + if background: + background = dict(background) + else: + background = dict.fromkeys(sorted(alphabet), 1.0) + + total = sum(background.values()) + pseudocounts = {} + + for letter in alphabet: + background[letter] /= total + pseudocounts[letter] = sq_nb_instances * background[letter] + + return pseudocounts + + +def split_jaspar_id(id): + """Split a JASPAR matrix ID into its component. + + Components are base ID and version number, e.g. 'MA0047.2' is returned as + ('MA0047', 2). + """ + id_split = id.split(".") + + base_id = None + version = None + if len(id_split) == 2: + base_id = id_split[0] + version = id_split[1] + else: + base_id = id + + return (base_id, version) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/db.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/db.py new file mode 100644 index 0000000000000000000000000000000000000000..92f7e8f641d1f1f9e3b5c983994613037ad08d5a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/jaspar/db.py @@ -0,0 +1,784 @@ +# Copyright 2013 by David Arenillas and Anthony Mathelier. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Provides read access to a JASPAR5 formatted database. + +This modules requires MySQLdb to be installed. + +Example, substitute the your database credentials as +appropriate:: + + from Bio.motifs.jaspar.db import JASPAR5 + JASPAR_DB_HOST = "hostname.example.org" + JASPAR_DB_NAME = "JASPAR2018" + JASPAR_DB_USER = "guest" + JASPAR_DB_PASS = "guest" + + jdb = JASPAR5( + host=JASPAR_DB_HOST, + name=JASPAR_DB_NAME, + user=JASPAR_DB_USER, + password=JASPAR_DB_PASS + ) + ets1 = jdb.fetch_motif_by_id('MA0098') + print(ets1) + TF name ETS1 + Matrix ID MA0098.3 + Collection CORE + TF class ['Tryptophan cluster factors'] + TF family ['Ets-related factors'] + Species 9606 + Taxonomic group vertebrates + Accession ['P14921'] + Data type used HT-SELEX + Medline 20517297 + PAZAR ID TF0000070 + Comments Data is from Taipale HTSELEX DBD (2013) + Matrix: + 0 1 2 3 4 5 6 7 8 9 + A: 2683.00 180.00 425.00 0.00 0.00 2683.00 2683.00 1102.00 89.00 803.00 + C: 210.00 2683.00 2683.00 21.00 0.00 0.00 9.00 21.00 712.00 401.00 + G: 640.00 297.00 7.00 2683.00 2683.00 0.00 31.00 1580.00 124.00 1083.00 + T: 241.00 22.00 0.00 0.00 12.00 0.00 909.00 12.00 1970.00 396.00 + + motifs = jdb.fetch_motifs( + collection = 'CORE', + tax_group = ['vertebrates', 'insects'], + tf_class = 'Homeo domain factors', + tf_family = ['TALE-type homeo domain factors', 'POU domain factors'], + min_ic = 12 + ) + for motif in motifs: + pass # do something with the motif +""" + +import warnings + +from Bio import BiopythonWarning +from Bio import MissingPythonDependencyError + +try: + import MySQLdb as mdb +except ImportError: + raise MissingPythonDependencyError( + "Install MySQLdb if you want to use Bio.motifs.jaspar.db" + ) + +from Bio.motifs import jaspar +from Bio.motifs import matrix + +JASPAR_DFLT_COLLECTION = "CORE" + + +class JASPAR5: + """Class representing a JASPAR5 database. + + Class representing a JASPAR5 DB. The methods within are loosely based + on the perl TFBS::DB::JASPAR5 module. + + Note: We will only implement reading of JASPAR motifs from the DB. + Unlike the perl module, we will not attempt to implement any methods to + store JASPAR motifs or create a new DB at this time. + """ + + def __init__(self, host=None, name=None, user=None, password=None): + """Construct a JASPAR5 instance and connect to specified DB. + + Arguments: + - host - host name of the the JASPAR DB server + - name - name of the JASPAR database + - user - user name to connect to the JASPAR DB + - password - JASPAR DB password + + """ + self.name = name + self.host = host + self.user = user + self.password = password + + self.dbh = mdb.connect(host, user, password, name) + + def __str__(self): + """Return a string representation of the JASPAR5 DB connection.""" + return rf"{self.user}\@{self.host}:{self.name}" + + def fetch_motif_by_id(self, id): + """Fetch a single JASPAR motif from the DB by its JASPAR matrix ID. + + Example id 'MA0001.1'. + + Arguments: + - id - JASPAR matrix ID. This may be a fully specified ID including + the version number (e.g. MA0049.2) or just the base ID (e.g. + MA0049). If only a base ID is provided, the latest version is + returned. + + Returns: + - A Bio.motifs.jaspar.Motif object + + **NOTE:** The perl TFBS module allows you to specify the type of matrix + to return (PFM, PWM, ICM) but matrices are always stored in JASPAR as + PFMs so this does not really belong here. Once a PFM is fetched the + pwm() and pssm() methods can be called to return the normalized and + log-odds matrices. + + """ + # separate stable ID and version number + (base_id, version) = jaspar.split_jaspar_id(id) + if not version: + # if ID contains no version portion, fetch the latest version + version = self._fetch_latest_version(base_id) + + # fetch internal JASPAR matrix ID - also a check for validity + int_id = None + if version: + int_id = self._fetch_internal_id(base_id, version) + + # fetch JASPAR motif using internal ID + motif = None + if int_id: + motif = self._fetch_motif_by_internal_id(int_id) + + return motif + + def fetch_motifs_by_name(self, name): + """Fetch a list of JASPAR motifs from a JASPAR DB by the given TF name(s). + + Arguments: + name - a single name or list of names + Returns: + A list of Bio.motifs.jaspar.Motif objects + + Notes: + Names are not guaranteed to be unique. There may be more than one + motif with the same name. Therefore even if name specifies a single + name, a list of motifs is returned. This just calls + self.fetch_motifs(collection = None, tf_name = name). + + This behaviour is different from the TFBS perl module's + get_Matrix_by_name() method which always returns a single matrix, + issuing a warning message and returning the first matrix retrieved + in the case where multiple matrices have the same name. + + """ + return self.fetch_motifs(collection=None, tf_name=name) + + def fetch_motifs( + self, + collection=JASPAR_DFLT_COLLECTION, + tf_name=None, + tf_class=None, + tf_family=None, + matrix_id=None, + tax_group=None, + species=None, + pazar_id=None, + data_type=None, + medline=None, + min_ic=0, + min_length=0, + min_sites=0, + all=False, + all_versions=False, + ): + """Fetch jaspar.Record (list) of motifs using selection criteria. + + Arguments:: + + Except where obvious, all selection criteria arguments may be + specified as a single value or a list of values. Motifs must + meet ALL the specified selection criteria to be returned with + the precedent exceptions noted below. + + all - Takes precedent of all other selection criteria. + Every motif is returned. If 'all_versions' is also + specified, all versions of every motif are returned, + otherwise just the latest version of every motif is + returned. + matrix_id - Takes precedence over all other selection criteria + except 'all'. Only motifs with the given JASPAR + matrix ID(s) are returned. A matrix ID may be + specified as just a base ID or full JASPAR IDs + including version number. If only a base ID is + provided for specific motif(s), then just the latest + version of those motif(s) are returned unless + 'all_versions' is also specified. + collection - Only motifs from the specified JASPAR collection(s) + are returned. NOTE - if not specified, the collection + defaults to CORE for all other selection criteria + except 'all' and 'matrix_id'. To apply the other + selection criteria across all JASPAR collections, + explicitly set collection=None. + tf_name - Only motifs with the given name(s) are returned. + tf_class - Only motifs of the given TF class(es) are returned. + tf_family - Only motifs from the given TF families are returned. + tax_group - Only motifs belonging to the given taxonomic + supergroups are returned (e.g. 'vertebrates', + 'insects', 'nematodes' etc.) + species - Only motifs derived from the given species are + returned. Species are specified as taxonomy IDs. + data_type - Only motifs generated with the given data type (e.g. + ('ChIP-seq', 'PBM', 'SELEX' etc.) are returned. + NOTE - must match exactly as stored in the database. + pazar_id - Only motifs with the given PAZAR TF ID are returned. + medline - Only motifs with the given medline (PubmMed IDs) are + returned. + min_ic - Only motifs whose profile matrices have at least this + information content (specificty) are returned. + min_length - Only motifs whose profiles are of at least this + length are returned. + min_sites - Only motifs compiled from at least these many binding + sites are returned. + all_versions- Unless specified, just the latest version of motifs + determined by the other selection criteria are + returned. Otherwise all versions of the selected + motifs are returned. + + Returns: + - A Bio.motifs.jaspar.Record (list) of motifs. + + """ + # Fetch the internal IDs of the motifs using the criteria provided + int_ids = self._fetch_internal_id_list( + collection=collection, + tf_name=tf_name, + tf_class=tf_class, + tf_family=tf_family, + matrix_id=matrix_id, + tax_group=tax_group, + species=species, + pazar_id=pazar_id, + data_type=data_type, + medline=medline, + all=all, + all_versions=all_versions, + ) + + record = jaspar.Record() + + """ + Now further filter motifs returned above based on any specified + matrix specific criteria. + """ + for int_id in int_ids: + motif = self._fetch_motif_by_internal_id(int_id) + + # Filter motifs to those with matrix IC greater than min_ic + if min_ic: + if motif.pssm.mean() < min_ic: + continue + + # Filter motifs to those with minimum length of min_length + if min_length: + if motif.length < min_length: + continue + + # XXX We could also supply a max_length filter. + + """ + Filter motifs to those composed of at least this many sites. + The perl TFBS module assumes column sums may be different but + this should be strictly enforced here we will ignore this and + just use the first column sum. + """ + if min_sites: + num_sites = sum(motif.counts[nt][0] for nt in motif.alphabet) + if num_sites < min_sites: + continue + + record.append(motif) + + return record + + def _fetch_latest_version(self, base_id): + """Get the latest version number for the given base_id (PRIVATE).""" + cur = self.dbh.cursor() + cur.execute( + "select VERSION from MATRIX where BASE_id = %s order by VERSION" + " desc limit 1", + (base_id,), + ) + + row = cur.fetchone() + + latest = None + if row: + latest = row[0] + else: + warnings.warn( + "Failed to fetch latest version number for JASPAR motif" + f" with base ID '{base_id}'. No JASPAR motif with this" + " base ID appears to exist in the database.", + BiopythonWarning, + ) + + return latest + + def _fetch_internal_id(self, base_id, version): + """Fetch the internal id for a base id + version (PRIVATE). + + Also checks if this combo exists or not. + """ + cur = self.dbh.cursor() + cur.execute( + "select id from MATRIX where BASE_id = %s and VERSION = %s", + (base_id, version), + ) + + row = cur.fetchone() + + int_id = None + if row: + int_id = row[0] + else: + warnings.warn( + "Failed to fetch internal database ID for JASPAR motif" + f" with matrix ID '{base_id}.{version}'. No JASPAR motif" + " with this matrix ID appears to exist.", + BiopythonWarning, + ) + + return int_id + + def _fetch_motif_by_internal_id(self, int_id): + """Fetch basic motif information (PRIVATE).""" + cur = self.dbh.cursor() + cur.execute( + "select BASE_ID, VERSION, COLLECTION, NAME from MATRIX where id = %s", + (int_id,), + ) + + row = cur.fetchone() + + # This should never happen as it is an internal method. If it does + # we should probably raise an exception + if not row: + warnings.warn( + f"Could not fetch JASPAR motif with internal ID = {int_id}", + BiopythonWarning, + ) + return None + + base_id = row[0] + version = row[1] + collection = row[2] + name = row[3] + + matrix_id = "".join([base_id, ".", str(version)]) + + # fetch the counts matrix + counts = self._fetch_counts_matrix(int_id) + + # Create new JASPAR motif + motif = jaspar.Motif(matrix_id, name, collection=collection, counts=counts) + + # fetch species + cur.execute("select TAX_ID from MATRIX_SPECIES where id = %s", (int_id,)) + tax_ids = [] + rows = cur.fetchall() + for row in rows: + tax_ids.append(row[0]) + + # Many JASPAR motifs (especially those not in the CORE collection) + # do not have taxonomy IDs. So this warning would get annoying. + # if not tax_ids: + # warnings.warn("Could not fetch any taxonomy IDs for JASPAR motif" + # " {0}".format(motif.matrix_id), BiopythonWarning) + + motif.species = tax_ids + + # fetch protein accession numbers + cur.execute("select ACC FROM MATRIX_PROTEIN where id = %s", (int_id,)) + accs = [] + rows = cur.fetchall() + for row in rows: + accs.append(row[0]) + + # Similarly as for taxonomy IDs, it would get annoying to print + # warnings for JASPAR motifs which do not have accession numbers. + + motif.acc = accs + + # fetch remaining annotation as tags from the ANNOTATION table + cur.execute("select TAG, VAL from MATRIX_ANNOTATION where id = %s", (int_id,)) + rows = cur.fetchall() + + # Since JASPAR 2018 tf_family and tf_class are return as array. + tf_family = [] + tf_class = [] + + for row in rows: + attr = row[0] + val = row[1] + if attr == "class": + tf_class.append(val) + elif attr == "family": + tf_family.append(val) + elif attr == "tax_group": + motif.tax_group = val + elif attr == "type": + motif.data_type = val + elif attr == "pazar_tf_id": + motif.pazar_id = val + elif attr == "medline": + motif.medline = val + elif attr == "comment": + motif.comment = val + else: + # TODO If we were to implement additional arbitrary tags + # motif.tag(attr, val) + pass + + motif.tf_family = tf_family + motif.tf_class = tf_class + + return motif + + def _fetch_counts_matrix(self, int_id): + """Fetch the counts matrix from the JASPAR DB by the internal ID (PRIVATE). + + Returns a Bio.motifs.matrix.GenericPositionMatrix + """ + counts = {} + cur = self.dbh.cursor() + + for base in "ACGT": + base_counts = [] + + cur.execute( + "select val from MATRIX_DATA where ID = %s and row = %s order by col", + (int_id, base), + ) + + rows = cur.fetchall() + for row in rows: + base_counts.append(row[0]) + + counts[base] = [float(x) for x in base_counts] + + return matrix.GenericPositionMatrix("ACGT", counts) + + def _fetch_internal_id_list( + self, + collection=JASPAR_DFLT_COLLECTION, + tf_name=None, + tf_class=None, + tf_family=None, + matrix_id=None, + tax_group=None, + species=None, + pazar_id=None, + data_type=None, + medline=None, + all=False, + all_versions=False, + ): + """Fetch list of internal JASPAR motif IDs. + + Fetch a list of internal JASPAR motif IDs based on various passed + parameters which may then be used to fetch the rest of the motif data. + + Caller: + fetch_motifs() + + Arguments: + See arguments sections of fetch_motifs() + + Returns: + A list of internal JASPAR motif IDs which match the given + selection criteria arguments. + + + Build an SQL query based on the selection arguments provided. + + 1: First add table joins and sub-clauses for criteria corresponding to + named fields from the MATRIX and MATRIX_SPECIES tables such as + collection, matrix ID, name, species etc. + + 2: Then add joins/sub-clauses for tag/value parameters from the + MATRIX_ANNOTATION table. + + For the surviving matrices, the responsibility to do matrix-based + feature filtering such as ic, number of sites etc, fall on the + calling fetch_motifs() method. + + """ + int_ids = [] + + cur = self.dbh.cursor() + + """ + Special case 1: fetch ALL motifs. Highest priority. + Ignore all other selection arguments. + """ + if all: + cur.execute("select ID from MATRIX") + rows = cur.fetchall() + + for row in rows: + int_ids.append(row[0]) + + return int_ids + + """ + Special case 2: fetch specific motifs by their JASPAR IDs. This + has higher priority than any other except the above 'all' case. + Ignore all other selection arguments. + """ + if matrix_id: + """ + These might be either stable IDs or stable_ID.version. + If just stable ID and if all_versions == 1, return all versions, + otherwise just the latest + """ + if all_versions: + for id in matrix_id: + # ignore version here, this is a stupidity filter + (base_id, version) = jaspar.split_jaspar_id(id) + cur.execute("select ID from MATRIX where BASE_ID = %s", (base_id,)) + + rows = cur.fetchall() + for row in rows: + int_ids.append(row[0]) + else: + # only the latest version, or the requested version + for id in matrix_id: + (base_id, version) = jaspar.split_jaspar_id(id) + + if not version: + version = self._fetch_latest_version(base_id) + + int_id = None + if version: + int_id = self._fetch_internal_id(base_id, version) + + if int_id: + int_ids.append(int_id) + + return int_ids + + tables = ["MATRIX m"] + where_clauses = [] + + # Select by MATRIX.COLLECTION + if collection: + if isinstance(collection, list): + # Multiple collections passed in as a list + clause = "m.COLLECTION in ('" + clause = "".join([clause, "','".join(collection)]) + clause = "".join([clause, "')"]) + else: + # A single collection - typical usage + clause = "m.COLLECTION = '%s'" % collection + + where_clauses.append(clause) + + # Select by MATRIX.NAME + if tf_name: + if isinstance(tf_name, list): + # Multiple names passed in as a list + clause = "m.NAME in ('" + clause = "".join([clause, "','".join(tf_name)]) + clause = "".join([clause, "')"]) + else: + # A single name + clause = "m.NAME = '%s'" % tf_name + + where_clauses.append(clause) + + # Select by MATRIX_SPECIES.TAX_ID + if species: + tables.append("MATRIX_SPECIES ms") + where_clauses.append("m.ID = ms.ID") + + """ + NOTE: species are numeric taxonomy IDs but stored as varchars + in the DB. + """ + if isinstance(species, list): + # Multiple tax IDs passed in as a list + clause = "ms.TAX_ID in ('" + clause = "".join([clause, "','".join(str(s) for s in species)]) + clause = "".join([clause, "')"]) + else: + # A single tax ID + clause = "ms.TAX_ID = '%s'" % species + + where_clauses.append(clause) + + """ + Tag based selection from MATRIX_ANNOTATION + Differs from perl TFBS module in that the matrix class explicitly + has a tag attribute corresponding to the tags in the database. This + provides tremendous flexibility in adding new tags to the DB and + being able to select based on those tags with out adding new code. + In the JASPAR Motif class we have elected to use specific attributes + for the most commonly used tags and here correspondingly only allow + selection on these attributes. + + The attributes corresponding to the tags for which selection is + provided are: + + Attribute Tag + tf_class class + tf_family family + pazar_id pazar_tf_id + medline medline + data_type type + tax_group tax_group + """ + + # Select by TF class(es) (MATRIX_ANNOTATION.TAG="class") + if tf_class: + tables.append("MATRIX_ANNOTATION ma1") + where_clauses.append("m.ID = ma1.ID") + + clause = "ma1.TAG = 'class'" + if isinstance(tf_class, list): + # A list of TF classes + clause = "".join([clause, " and ma1.VAL in ('"]) + clause = "".join([clause, "','".join(tf_class)]) + clause = "".join([clause, "')"]) + else: + # A single TF class + clause = "".join([clause, " and ma1.VAL = '%s' " % tf_class]) + + where_clauses.append(clause) + + # Select by TF families (MATRIX_ANNOTATION.TAG="family") + if tf_family: + tables.append("MATRIX_ANNOTATION ma2") + where_clauses.append("m.ID = ma2.ID") + + clause = "ma2.TAG = 'family'" + if isinstance(tf_family, list): + # A list of TF families + clause = "".join([clause, " and ma2.VAL in ('"]) + clause = "".join([clause, "','".join(tf_family)]) + clause = "".join([clause, "')"]) + else: + # A single TF family + clause = "".join([clause, " and ma2.VAL = '%s' " % tf_family]) + + where_clauses.append(clause) + + # Select by PAZAR TF ID(s) (MATRIX_ANNOTATION.TAG="pazar_tf_id") + if pazar_id: + tables.append("MATRIX_ANNOTATION ma3") + where_clauses.append("m.ID = ma3.ID") + + clause = "ma3.TAG = 'pazar_tf_id'" + if isinstance(pazar_id, list): + # A list of PAZAR IDs + clause = "".join([clause, " and ma3.VAL in ('"]) + clause = "".join([clause, "','".join(pazar_id)]) + clause = "".join([clause, "')"]) + else: + # A single PAZAR ID + clause = "".join([" and ma3.VAL = '%s' " % pazar_id]) + + where_clauses.append(clause) + + # Select by PubMed ID(s) (MATRIX_ANNOTATION.TAG="medline") + if medline: + tables.append("MATRIX_ANNOTATION ma4") + where_clauses.append("m.ID = ma4.ID") + + clause = "ma4.TAG = 'medline'" + if isinstance(medline, list): + # A list of PubMed IDs + clause = "".join([clause, " and ma4.VAL in ('"]) + clause = "".join([clause, "','".join(medline)]) + clause = "".join([clause, "')"]) + else: + # A single PubMed ID + clause = "".join([" and ma4.VAL = '%s' " % medline]) + + where_clauses.append(clause) + + # Select by data type(s) used to compile the matrix + # (MATRIX_ANNOTATION.TAG="type") + if data_type: + tables.append("MATRIX_ANNOTATION ma5") + where_clauses.append("m.ID = ma5.ID") + + clause = "ma5.TAG = 'type'" + if isinstance(data_type, list): + # A list of data types + clause = "".join([clause, " and ma5.VAL in ('"]) + clause = "".join([clause, "','".join(data_type)]) + clause = "".join([clause, "')"]) + else: + # A single data type + clause = "".join([" and ma5.VAL = '%s' " % data_type]) + + where_clauses.append(clause) + + # Select by taxonomic supergroup(s) (MATRIX_ANNOTATION.TAG="tax_group") + if tax_group: + tables.append("MATRIX_ANNOTATION ma6") + where_clauses.append("m.ID = ma6.ID") + + clause = "ma6.TAG = 'tax_group'" + if isinstance(tax_group, list): + # A list of tax IDs + clause = "".join([clause, " and ma6.VAL in ('"]) + clause = "".join([clause, "','".join(tax_group)]) + clause = "".join([clause, "')"]) + else: + # A single tax ID + clause = "".join([clause, " and ma6.VAL = '%s' " % tax_group]) + + where_clauses.append(clause) + + sql = "".join(["select distinct(m.ID) from ", ", ".join(tables)]) + + if where_clauses: + sql = "".join([sql, " where ", " and ".join(where_clauses)]) + + cur.execute(sql) + rows = cur.fetchall() + + for row in rows: + id = row[0] + if all_versions: + int_ids.append(id) + else: + # is the latest version? + if self._is_latest_version(id): + int_ids.append(id) + + if len(int_ids) < 1: + warnings.warn( + "Zero motifs returned with current select criteria", BiopythonWarning + ) + + return int_ids + + def _is_latest_version(self, int_id): + """Check if the internal ID represents the latest JASPAR matrix (PRIVATE). + + Does this internal ID represent the latest version of the JASPAR + matrix (collapse on base ids) + """ + cur = self.dbh.cursor() + + cur.execute( + "select count(*) from MATRIX where " + "BASE_ID = (select BASE_ID from MATRIX where ID = %s) " + "and VERSION > (select VERSION from MATRIX where ID = %s)", + (int_id, int_id), + ) + + row = cur.fetchone() + + count = row[0] + + if count == 0: + # no matrices with higher version ID and same base id + return True + + return False diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/mast.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/mast.py new file mode 100644 index 0000000000000000000000000000000000000000..3fec6c19ebabe1bf56039f6df65cd8734406e333 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/mast.py @@ -0,0 +1,139 @@ +# Copyright 2008 by Bartek Wilczynski. +# Adapted from Bio.MEME.Parser by Jason A. Hackney. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Module for the support of Motif Alignment and Search Tool (MAST).""" + +import xml.etree.ElementTree as ET + +from Bio.motifs import meme + + +class Record(list): + """The class for holding the results from a MAST run. + + A mast.Record holds data about matches between motifs and sequences. + The motifs held by the Record are objects of the class meme.Motif. + + The mast.Record class inherits from list, so you can access individual + motifs in the record by their index. Alternatively, you can find a motif + by its name: + + >>> from Bio import motifs + >>> with open("motifs/mast.crp0.de.oops.txt.xml") as f: + ... record = motifs.parse(f, 'MAST') + >>> motif = record[0] + >>> print(motif.name) + 1 + >>> motif = record['1'] + >>> print(motif.name) + 1 + """ + + def __init__(self): + """Initialize the class.""" + self.sequences = [] + self.version = "" + self.database = "" + self.diagrams = {} + self.alphabet = None + self.strand_handling = "" + + def __getitem__(self, key): + """Return the motif of index key.""" + if isinstance(key, str): + for motif in self: + if motif.name == key: + return motif + else: + return list.__getitem__(self, key) + + +def read(handle): + """Parse a MAST XML format handle as a Record object.""" + record = Record() + try: + xml_tree = ET.parse(handle) + except ET.ParseError: + raise ValueError( + "Improper MAST XML input file. XML root tag should start with maximum: + maximum = count + sequence_letter = letter + sequence += sequence_letter + return Seq(sequence) + + @property + def anticonsensus(self): + """Return the anticonsensus sequence.""" + sequence = "" + for i in range(self.length): + minimum = math.inf + for letter in self.alphabet: + count = self[letter][i] + if count < minimum: + minimum = count + sequence_letter = letter + sequence += sequence_letter + return Seq(sequence) + + @property + def degenerate_consensus(self): + """Return the degenerate consensus sequence.""" + # Following the rules adapted from + # D. R. Cavener: "Comparison of the consensus sequence flanking + # translational start sites in Drosophila and vertebrates." + # Nucleic Acids Research 15(4): 1353-1361. (1987). + # The same rules are used by TRANSFAC. + degenerate_nucleotide = { + "A": "A", + "C": "C", + "G": "G", + "T": "T", + "U": "U", + "AC": "M", + "AG": "R", + "AT": "W", + "AU": "W", + "CG": "S", + "CT": "Y", + "CU": "Y", + "GT": "K", + "GU": "K", + "ACG": "V", + "ACT": "H", + "ACU": "H", + "AGT": "D", + "AGU": "D", + "CGT": "B", + "CGU": "B", + "ACGT": "N", + "ACGU": "N", + } + sequence = "" + for i in range(self.length): + + def get(nucleotide): + return self[nucleotide][i] # noqa: B023 + + nucleotides = sorted(self, key=get, reverse=True) + counts = [self[c][i] for c in nucleotides] + # Follow the Cavener rules: + if counts[0] > sum(counts[1:]) and counts[0] > 2 * counts[1]: + key = nucleotides[0] + elif 4 * sum(counts[:2]) > 3 * sum(counts): + key = "".join(sorted(nucleotides[:2])) + elif counts[3] == 0: + key = "".join(sorted(nucleotides[:3])) + else: + key = "ACGT" + nucleotide = degenerate_nucleotide.get(key, key) + sequence += nucleotide + return Seq(sequence) + + def calculate_consensus( + self, substitution_matrix=None, plurality=None, identity=0, setcase=None + ): + """Return the consensus sequence (as a string) for the given parameters. + + This function largely follows the conventions of the EMBOSS `cons` tool. + + Arguments: + - substitution_matrix - the scoring matrix used when comparing + sequences. By default, it is None, in which case we simply count the + frequency of each letter. + Instead of the default value, you can use the substitution matrices + available in Bio.Align.substitution_matrices. Common choices are + BLOSUM62 (also known as EBLOSUM62) for protein, and NUC.4.4 (also + known as EDNAFULL) for nucleotides. NOTE: This has not yet been + implemented. + - plurality - threshold value for the number of positive + matches, divided by the total count in a column, required to reach + consensus. If substitution_matrix is None, then this argument must + be None, and is ignored; a ValueError is raised otherwise. If + substitution_matrix is not None, then the default value of the + plurality is 0.5. + - identity - number of identities, divided by the total + count in a column, required to define a consensus value. If the + number of identities is less than identity * total count in a column, + then the undefined character ('N' for nucleotides and 'X' for amino + acid sequences) is used in the consensus sequence. If identity is + 1.0, then only columns of identical letters contribute to the + consensus. Default value is zero. + - setcase - threshold for the positive matches, divided by + the total count in a column, above which the consensus is in + upper-case and below which the consensus is in lower-case. By + default, this is equal to 0.5. + """ + alphabet = self.alphabet + if set(alphabet).union("ACGTUN-") == set("ACGTUN-"): + undefined = "N" + else: + undefined = "X" + if substitution_matrix is None: + if plurality is not None: + raise ValueError( + "plurality must be None if substitution_matrix is None" + ) + sequence = "" + for i in range(self.length): + maximum = 0 + total = 0 + for letter in alphabet: + count = self[letter][i] + total += count + if count > maximum: + maximum = count + consensus_letter = letter + if maximum < identity * total: + consensus_letter = undefined + else: + if setcase is None: + setcase_threshold = total / 2 + else: + setcase_threshold = setcase * total + if maximum <= setcase_threshold: + consensus_letter = consensus_letter.lower() + sequence += consensus_letter + else: + raise NotImplementedError( + "calculate_consensus currently only supports substitution_matrix=None" + ) + return sequence + + @property + def gc_content(self): + """Compute the fraction GC content.""" + alphabet = self.alphabet + gc_total = 0.0 + total = 0.0 + for i in range(self.length): + for letter in alphabet: + if letter in "CG": + gc_total += self[letter][i] + total += self[letter][i] + return gc_total / total + + def reverse_complement(self): + """Compute reverse complement.""" + values = {} + if self.alphabet == "ACGU": + values["A"] = self["U"][::-1] + values["U"] = self["A"][::-1] + else: + values["A"] = self["T"][::-1] + values["T"] = self["A"][::-1] + values["G"] = self["C"][::-1] + values["C"] = self["G"][::-1] + alphabet = self.alphabet + return self.__class__(alphabet, values) + + +class FrequencyPositionMatrix(GenericPositionMatrix): + """Class for the support of frequency calculations on the Position Matrix.""" + + def normalize(self, pseudocounts=None): + """Create and return a position-weight matrix by normalizing the counts matrix. + + If pseudocounts is None (default), no pseudocounts are added + to the counts. + + If pseudocounts is a number, it is added to the counts before + calculating the position-weight matrix. + + Alternatively, the pseudocounts can be a dictionary with a key + for each letter in the alphabet associated with the motif. + """ + counts = {} + if pseudocounts is None: + for letter in self.alphabet: + counts[letter] = [0.0] * self.length + elif isinstance(pseudocounts, dict): + for letter in self.alphabet: + counts[letter] = [float(pseudocounts[letter])] * self.length + else: + for letter in self.alphabet: + counts[letter] = [float(pseudocounts)] * self.length + for i in range(self.length): + for letter in self.alphabet: + counts[letter][i] += self[letter][i] + # Actual normalization is done in the PositionWeightMatrix initializer + return PositionWeightMatrix(self.alphabet, counts) + + +class PositionWeightMatrix(GenericPositionMatrix): + """Class for the support of weight calculations on the Position Matrix.""" + + def __init__(self, alphabet, counts): + """Initialize the class.""" + GenericPositionMatrix.__init__(self, alphabet, counts) + for i in range(self.length): + total = sum(self[letter][i] for letter in alphabet) + for letter in alphabet: + self[letter][i] /= total + for letter in alphabet: + self[letter] = tuple(self[letter]) + + def log_odds(self, background=None): + """Return the Position-Specific Scoring Matrix. + + The Position-Specific Scoring Matrix (PSSM) contains the log-odds + scores computed from the probability matrix and the background + probabilities. If the background is None, a uniform background + distribution is assumed. + """ + values = {} + alphabet = self.alphabet + if background is None: + background = dict.fromkeys(self.alphabet, 1.0) + else: + background = dict(background) + total = sum(background.values()) + for letter in alphabet: + background[letter] /= total + values[letter] = [] + for i in range(self.length): + for letter in alphabet: + b = background[letter] + if b > 0: + p = self[letter][i] + if p > 0: + logodds = math.log(p / b, 2) + else: + logodds = -math.inf + else: + p = self[letter][i] + if p > 0: + logodds = math.inf + else: + logodds = math.nan + values[letter].append(logodds) + pssm = PositionSpecificScoringMatrix(alphabet, values) + return pssm + + +class PositionSpecificScoringMatrix(GenericPositionMatrix): + """Class for the support of Position Specific Scoring Matrix calculations.""" + + def calculate(self, sequence): + """Return the PWM score for a given sequence for all positions. + + Notes: + - the sequence can only be a DNA sequence + - the search is performed only on one strand + - if the sequence and the motif have the same length, a single + number is returned + - otherwise, the result is a one-dimensional numpy array + + """ + # TODO - Code itself tolerates ambiguous bases (as NaN). + if sorted(self.alphabet) != ["A", "C", "G", "T"]: + raise ValueError( + "PSSM has wrong alphabet: %s - Use only with DNA motifs" % self.alphabet + ) + + # NOTE: The C code handles mixed case input as this could be large + # (e.g. contig or chromosome), so requiring it be all upper or lower + # case would impose an overhead to allocate the extra memory. + try: + sequence = bytes(sequence) + except TypeError: # str + try: + sequence = bytes(sequence, "ASCII") + except TypeError: + raise ValueError( + "sequence should be a Seq, MutableSeq, string, or bytes-like object" + ) from None + except UnicodeEncodeError: + raise ValueError( + "sequence should contain ASCII characters only" + ) from None + except Exception: + raise ValueError( + "sequence should be a Seq, MutableSeq, string, or bytes-like object" + ) from None + + n = len(sequence) + m = self.length + # Create the numpy arrays here; the C module then does not rely on numpy + # Use a float32 for the scores array to save space + scores = np.empty(n - m + 1, np.float32) + logodds = np.array( + [[self[letter][i] for letter in "ACGT"] for i in range(m)], float + ) + _pwm.calculate(sequence, logodds, scores) + + if len(scores) == 1: + return scores[0] + else: + return scores + + def search(self, sequence, threshold=0.0, both=True, chunksize=10**6): + """Find hits with PWM score above given threshold. + + A generator function, returning found hits in the given sequence + with the pwm score higher than the threshold. + """ + sequence = sequence.upper() + seq_len = len(sequence) + motif_l = self.length + chunk_starts = np.arange(0, seq_len, chunksize) + if both: + rc = self.reverse_complement() + for chunk_start in chunk_starts: + subseq = sequence[chunk_start : chunk_start + chunksize + motif_l - 1] + pos_scores = self.calculate(subseq) + pos_ind = pos_scores >= threshold + pos_positions = np.where(pos_ind)[0] + chunk_start + pos_scores = pos_scores[pos_ind] + if both: + neg_scores = rc.calculate(subseq) + neg_ind = neg_scores >= threshold + neg_positions = np.where(neg_ind)[0] + chunk_start + neg_scores = neg_scores[neg_ind] + else: + neg_positions = np.empty((0), dtype=int) + neg_scores = np.empty((0), dtype=int) + chunk_positions = np.append(pos_positions, neg_positions - seq_len) + chunk_scores = np.append(pos_scores, neg_scores) + order = np.argsort(np.append(pos_positions, neg_positions)) + chunk_positions = chunk_positions[order] + chunk_scores = chunk_scores[order] + yield from zip(chunk_positions, chunk_scores) + + @property + def max(self): + """Maximal possible score for this motif. + + returns the score computed for the consensus sequence. + """ + score = 0.0 + letters = self.alphabet + for position in range(self.length): + score += max(self[letter][position] for letter in letters) + return score + + @property + def min(self): + """Minimal possible score for this motif. + + returns the score computed for the anticonsensus sequence. + """ + score = 0.0 + letters = self.alphabet + for position in range(self.length): + score += min(self[letter][position] for letter in letters) + return score + + @property + def gc_content(self): + """Compute the GC-ratio.""" + raise Exception("Cannot compute the %GC composition of a PSSM") + + def mean(self, background=None): + """Return expected value of the score of a motif.""" + if background is None: + background = dict.fromkeys(self.alphabet, 1.0) + else: + background = dict(background) + total = sum(background.values()) + for letter in self.alphabet: + background[letter] /= total + sx = 0.0 + for i in range(self.length): + for letter in self.alphabet: + logodds = self[letter, i] + if math.isnan(logodds): + continue + if math.isinf(logodds) and logodds < 0: + continue + b = background[letter] + p = b * math.pow(2, logodds) + sx += p * logodds + return sx + + def std(self, background=None): + """Return standard deviation of the score of a motif.""" + if background is None: + background = dict.fromkeys(self.alphabet, 1.0) + else: + background = dict(background) + total = sum(background.values()) + for letter in self.alphabet: + background[letter] /= total + variance = 0.0 + for i in range(self.length): + sx = 0.0 + sxx = 0.0 + for letter in self.alphabet: + logodds = self[letter, i] + if math.isnan(logodds): + continue + if math.isinf(logodds) and logodds < 0: + continue + b = background[letter] + p = b * math.pow(2, logodds) + sx += p * logodds + sxx += p * logodds * logodds + sxx -= sx * sx + variance += sxx + variance = max(variance, 0) # to avoid roundoff problems + return math.sqrt(variance) + + def dist_pearson(self, other): + """Return the similarity score based on pearson correlation for the given motif against self. + + We use the Pearson's correlation of the respective probabilities. + """ + if self.alphabet != other.alphabet: + raise ValueError("Cannot compare motifs with different alphabets") + + max_p = -2 + for offset in range(-self.length + 1, other.length): + if offset < 0: + p = self.dist_pearson_at(other, -offset) + else: # offset>=0 + p = other.dist_pearson_at(self, offset) + if max_p < p: + max_p = p + max_o = -offset + return 1 - max_p, max_o + + def dist_pearson_at(self, other, offset): + """Return the similarity score based on pearson correlation at the given offset.""" + letters = self.alphabet + sx = 0.0 # \sum x + sy = 0.0 # \sum y + sxx = 0.0 # \sum x^2 + sxy = 0.0 # \sum x \cdot y + syy = 0.0 # \sum y^2 + norm = max(self.length, offset + other.length) * len(letters) + for pos in range(min(self.length - offset, other.length)): + xi = [self[letter, pos + offset] for letter in letters] + yi = [other[letter, pos] for letter in letters] + sx += sum(xi) + sy += sum(yi) + sxx += sum(x * x for x in xi) + sxy += sum(x * y for x, y in zip(xi, yi)) + syy += sum(y * y for y in yi) + sx /= norm + sy /= norm + sxx /= norm + sxy /= norm + syy /= norm + numerator = sxy - sx * sy + denominator = math.sqrt((sxx - sx * sx) * (syy - sy * sy)) + return numerator / denominator + + def distribution(self, background=None, precision=10**3): + """Calculate the distribution of the scores at the given precision.""" + from .thresholds import ScoreDistribution + + if background is None: + background = dict.fromkeys(self.alphabet, 1.0) + else: + background = dict(background) + total = sum(background.values()) + for letter in self.alphabet: + background[letter] /= total + return ScoreDistribution(precision=precision, pssm=self, background=background) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/meme.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/meme.py new file mode 100644 index 0000000000000000000000000000000000000000..35c8b929087af742735874746e7e77da4865a2e6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/meme.py @@ -0,0 +1,187 @@ +# Copyright 2008 by Bartek Wilczynski. +# Revisions copyright 2019 by Victor Lin. +# Adapted from Bio.MEME.Parser by Jason A. Hackney. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Module for the support of MEME motif format.""" + +import xml.etree.ElementTree as ET + +from Bio import Align +from Bio import motifs +from Bio.Seq import Seq + + +def read(handle): + """Parse the text output of the MEME program into a meme.Record object. + + Examples + -------- + >>> from Bio.motifs import meme + >>> with open("motifs/meme.INO_up800.classic.oops.xml") as f: + ... record = meme.read(f) + >>> for motif in record: + ... for sequence in motif.alignment.sequences: + ... print(sequence.motif_name, sequence.sequence_name, sequence.sequence_id, sequence.strand, sequence.pvalue) + GSKGCATGTGAAA INO1 sequence_5 + 1.21e-08 + GSKGCATGTGAAA FAS1 sequence_2 - 1.87e-08 + GSKGCATGTGAAA ACC1 sequence_4 - 6.62e-08 + GSKGCATGTGAAA CHO2 sequence_1 - 1.05e-07 + GSKGCATGTGAAA CHO1 sequence_0 - 1.69e-07 + GSKGCATGTGAAA FAS2 sequence_3 - 5.62e-07 + GSKGCATGTGAAA OPI3 sequence_6 + 1.08e-06 + TTGACWCYTGCYCWG CHO2 sequence_1 + 7.2e-10 + TTGACWCYTGCYCWG OPI3 sequence_6 - 2.56e-08 + TTGACWCYTGCYCWG ACC1 sequence_4 - 1.59e-07 + TTGACWCYTGCYCWG CHO1 sequence_0 + 2.05e-07 + TTGACWCYTGCYCWG FAS1 sequence_2 + 3.85e-07 + TTGACWCYTGCYCWG FAS2 sequence_3 - 5.11e-07 + TTGACWCYTGCYCWG INO1 sequence_5 + 8.01e-07 + + """ + record = Record() + try: + xml_tree = ET.parse(handle) + except ET.ParseError: + raise ValueError( + "Improper MEME XML input file. XML root tag should start with >> from Bio import motifs + >>> with open("motifs/meme.INO_up800.classic.oops.xml") as f: + ... record = motifs.parse(f, 'MEME') + >>> motif = record[0] + >>> print(motif.name) + GSKGCATGTGAAA + >>> motif = record['GSKGCATGTGAAA'] + >>> print(motif.name) + GSKGCATGTGAAA + """ + + def __init__(self): + """Initialize the class.""" + self.version = "" + self.datafile = "" + self.command = "" + self.alphabet = "" + self.sequences = [] + + def __getitem__(self, key): + """Return the motif of index key.""" + if isinstance(key, str): + for motif in self: + if motif.name == key: + return motif + else: + return list.__getitem__(self, key) + + +# Everything below is private + + +def __read_metadata(record, xml_tree): + record.version = xml_tree.getroot().get("version") + record.datafile = xml_tree.find("training_set").get("primary_sequences") + record.command = xml_tree.find("model").find("command_line").text + # TODO - background_frequencies, other metadata under model + + +def __read_alphabet(record, xml_tree): + alphabet_tree = ( + xml_tree.find("training_set").find("letter_frequencies").find("alphabet_array") + ) + for value in alphabet_tree.findall("value"): + record.alphabet += value.get("letter_id") + + +def __get_sequence_id_name_map(xml_tree): + return { + sequence_tree.get("id"): sequence_tree.get("name") + for sequence_tree in xml_tree.find("training_set").findall("sequence") + } + + +def __read_motifs(record, xml_tree, sequence_id_name_map): + for motif_tree in xml_tree.find("motifs").findall("motif"): + instances = [] + for site_tree in motif_tree.find("contributing_sites").findall( + "contributing_site" + ): + letters = [ + letter_ref.get("letter_id") + for letter_ref in site_tree.find("site").findall("letter_ref") + ] + sequence = "".join(letters) + instance = Seq(sequence) + instance.motif_name = motif_tree.get("name") + instance.sequence_id = site_tree.get("sequence_id") + instance.sequence_name = sequence_id_name_map[instance.sequence_id] + # TODO - left flank, right flank + instance.start = int(site_tree.get("position")) + 1 + instance.pvalue = float(site_tree.get("pvalue")) + instance.strand = __convert_strand(site_tree.get("strand")) + instance.length = len(sequence) + instances.append(instance) + alignment = Align.Alignment(instances) + motif = Motif(record.alphabet, alignment) + motif.id = motif_tree.get("id") + motif.name = motif_tree.get("name") + motif.alt_id = motif_tree.get("alt") + motif.length = int(motif_tree.get("width")) + motif.num_occurrences = int(motif_tree.get("sites")) + motif.evalue = float(motif_tree.get("e_value")) + # TODO - ic, re, llr, pvalue, bayes_threshold, elapsed_time + record.append(motif) + + +def __convert_strand(strand): + """Convert strand (+/-) from XML if present. + + Default: + + """ + if strand == "minus": + return "-" + if strand == "plus" or strand == "none": + return "+" + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/minimal.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5b035de88f44f3668ac06fbde13b8cdd3459a8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/minimal.py @@ -0,0 +1,221 @@ +# Copyright 2018 by Ariel Aptekmann. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Module for the support of MEME minimal motif format.""" + +from Bio import motifs + + +def read(handle): + """Parse the text output of the MEME program into a meme.Record object. + + Examples + -------- + >>> from Bio.motifs import minimal + >>> with open("motifs/meme.out") as f: + ... record = minimal.read(f) + ... + >>> for motif in record: + ... print(motif.name, motif.evalue) + ... + 1 1.1e-22 + + You can access individual motifs in the record by their index or find a motif + by its name: + + >>> from Bio import motifs + >>> with open("motifs/minimal_test.meme") as f: + ... record = motifs.parse(f, 'minimal') + ... + >>> motif = record[0] + >>> print(motif.name) + KRP + >>> motif = record['IFXA'] + >>> print(motif.name) + IFXA + + This function won't retrieve instances, as there are none in minimal meme format. + + """ + motif_number = 0 + record = Record() + _read_version(record, handle) + _read_alphabet(record, handle) + _read_background(record, handle) + + while True: + for line in handle: + if line.startswith("MOTIF"): + break + else: + return record + name = line.split()[1] + motif_number += 1 + length, num_occurrences, evalue = _read_motif_statistics(handle) + counts = _read_lpm(record, handle, length, num_occurrences) + # {'A': 0.25, 'C': 0.25, 'T': 0.25, 'G': 0.25} + motif = motifs.Motif(alphabet=record.alphabet, counts=counts) + motif.background = record.background + motif.length = motif.counts.length + motif.num_occurrences = num_occurrences + motif.evalue = evalue + motif.name = name + record.append(motif) + assert len(record) == motif_number + return record + + +class Record(list): + """Class for holding the results of a minimal MEME run.""" + + def __init__(self): + """Initialize record class values.""" + self.version = "" + self.datafile = "" + self.command = "" + self.alphabet = None + self.background = {} + self.sequences = [] + + def __getitem__(self, key): + """Return the motif of index key.""" + if isinstance(key, str): + for motif in self: + if motif.name == key: + return motif + else: + return list.__getitem__(self, key) + + +# Everything below is private + + +def _read_background(record, handle): + """Read background letter frequencies (PRIVATE).""" + for line in handle: + if line.startswith("Background letter frequencies"): + background_freqs = [] + for line in handle: + line = line.rstrip() + if line: + background_freqs.extend( + [ + float(freq) + for i, freq in enumerate(line.split(" ")) + if i % 2 == 1 + ] + ) + else: + break + if not background_freqs: + raise ValueError( + "Unexpected end of stream: Expected to find line starting background frequencies." + ) + break + else: + raise ValueError( + "Improper input file. File should contain a line starting background frequencies." + ) + record.background = dict(zip(record.alphabet, background_freqs)) + + +def _read_version(record, handle): + """Read MEME version (PRIVATE).""" + for line in handle: + if line.startswith("MEME version"): + break + else: + raise ValueError( + "Improper input file. File should contain a line starting MEME version." + ) + line = line.strip() + ls = line.split() + record.version = ls[2] + + +def _read_alphabet(record, handle): + """Read alphabet (PRIVATE).""" + for line in handle: + if line.startswith("ALPHABET"): + break + else: + raise ValueError( + "Unexpected end of stream: Expected to find line starting with 'ALPHABET'" + ) + if not line.startswith("ALPHABET= "): + raise ValueError("Line does not start with 'ALPHABET':\n%s" % line) + line = line.strip().replace("ALPHABET= ", "") + if line == "ACGT": + al = "ACGT" + elif line == "ACGU": + al = "ACGU" + else: + # al = "ACDEFGHIKLMNPQRSTVWY" + raise ValueError("Only parsing of DNA and RNA motifs is implemented") + record.alphabet = al + + +def _read_lpm(record, handle, length, num_occurrences): + """Read letter probability matrix (PRIVATE).""" + counts = [[], [], [], []] + for line in handle: + freqs = line.split() + if len(freqs) != 4: + break + counts[0].append(round(float(freqs[0]) * num_occurrences)) + counts[1].append(round(float(freqs[1]) * num_occurrences)) + counts[2].append(round(float(freqs[2]) * num_occurrences)) + counts[3].append(round(float(freqs[3]) * num_occurrences)) + if length and len(counts[0]) == length: + break + c = dict(zip(record.alphabet, counts)) + return c + + +def _read_motif_statistics(handle): + """Read motif statistics (PRIVATE).""" + # minimal MEME motif format letter-probability matrix line: + # letter-probability matrix: alength= 4 w= 19 nsites= 17 E= 4.1e-009 + # + # All the "key= value" pairs after the "letter-probability matrix:" text are optional. + # The "alength= alphabet length" and "w= motif length" can be derived from the matrix + # if they are not specified, provided there is an empty line following the letter + # probability matrix. + # The "nsites= source sites" will default to 20 if it is not provided and the + # "E= source E-value" will default to zero. + for line in handle: + if line.startswith("letter-probability matrix:"): + break + + # The "nsites= source sites" will default to 20 if it is not provided. + num_occurrences = ( + int(line.split("nsites=")[1].split()[0]) if line.find("nsites=") != -1 else 20 + ) + # Length can be infered later if it is not provided. + length = int(line.split("w=")[1].split()[0]) if line.find("w=") != -1 else None + # E-value will default to zero if it is not provided. + evalue = float(line.split("E=")[1].split()[0]) if line.find("E=") != -1 else 0.0 + return length, num_occurrences, evalue + + +def _read_motif_name(handle): + """Read motif name (PRIVATE).""" + for line in handle: + if "sorted by position p-value" in line: + break + else: + raise ValueError("Unexpected end of stream: Failed to find motif name") + line = line.strip() + words = line.split() + name = " ".join(words[0:2]) + return name + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/pfm.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/pfm.py new file mode 100644 index 0000000000000000000000000000000000000000..bede681091c8e297be5619acaa345bb3cb31a0bf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/pfm.py @@ -0,0 +1,423 @@ +# Copyright 2015 by Gert Hulselmans. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Parse various position frequency matrix format files.""" + +import re + +from Bio import motifs + + +class Record(list): + """Class to store the information in a position frequency matrix table. + + The record inherits from a list containing the individual motifs. + """ + + def __str__(self): + """Return a string representation of the motifs in the Record object.""" + return "\n".join(str(motif) for motif in self) + + +def read(handle, pfm_format): + """Read motif(s) from a file in various position frequency matrix formats. + + Return the record of PFM(s). + Call the appropriate routine based on the format passed. + """ + # Supporting underscores here for backward compatibility + pfm_format = pfm_format.lower().replace("_", "-") + if pfm_format == "pfm-four-columns": + record = _read_pfm_four_columns(handle) + return record + elif pfm_format == "pfm-four-rows": + record = _read_pfm_four_rows(handle) + return record + else: + raise ValueError("Unknown Position Frequency matrix format '%s'" % pfm_format) + + +def _read_pfm_four_columns(handle): + """Read motifs in position frequency matrix format (4 columns) from a file handle. + + # CIS-BP + Pos A C G T + 1 0.00961538461538462 0.00961538461538462 0.00961538461538462 0.971153846153846 + 2 0.00961538461538462 0.00961538461538462 0.00961538461538462 0.971153846153846 + 3 0.971153846153846 0.00961538461538462 0.00961538461538462 0.00961538461538462 + 4 0.00961538461538462 0.00961538461538462 0.00961538461538462 0.971153846153846 + 5 0.00961538461538462 0.971153846153846 0.00961538461538462 0.00961538461538462 + 6 0.971153846153846 0.00961538461538462 0.00961538461538462 0.00961538461538462 + 7 0.00961538461538462 0.971153846153846 0.00961538461538462 0.00961538461538462 + 8 0.00961538461538462 0.00961538461538462 0.00961538461538462 0.971153846153846 + + # C2H2-ZFs + Gene ENSG00000197372 + Pos A C G T + 1 0.341303 0.132427 0.117054 0.409215 + 2 0.283785 0.077066 0.364552 0.274597 + 3 0.491055 0.078208 0.310520 0.120217 + 4 0.492621 0.076117 0.131007 0.300256 + 5 0.250645 0.361464 0.176504 0.211387 + 6 0.276694 0.498070 0.197793 0.027444 + 7 0.056317 0.014631 0.926202 0.002850 + 8 0.004470 0.007769 0.983797 0.003964 + 9 0.936213 0.058787 0.002387 0.002613 + 10 0.004352 0.004030 0.002418 0.989200 + 11 0.013277 0.008165 0.001991 0.976567 + 12 0.968132 0.002263 0.002868 0.026737 + 13 0.397623 0.052017 0.350783 0.199577 + 14 0.000000 0.000000 1.000000 0.000000 + 15 1.000000 0.000000 0.000000 0.000000 + 16 0.000000 0.000000 1.000000 0.000000 + 17 0.000000 0.000000 1.000000 0.000000 + 18 1.000000 0.000000 0.000000 0.000000 + 19 0.000000 1.000000 0.000000 0.000000 + 20 1.000000 0.000000 0.000000 0.000000 + + # C2H2-ZFs + Gene FBgn0000210 + Motif M1734_0.90 + Pos A C G T + 1 0.25 0.0833333 0.0833333 0.583333 + 2 0.75 0.166667 0.0833333 0 + 3 0.833333 0 0 0.166667 + 4 1 0 0 0 + 5 0 0.833333 0.0833333 0.0833333 + 6 0.333333 0 0 0.666667 + 7 0.833333 0 0 0.166667 + 8 0.5 0 0.333333 0.166667 + 9 0.5 0.0833333 0.166667 0.25 + 10 0.333333 0.25 0.166667 0.25 + 11 0.166667 0.25 0.416667 0.166667 + + # FlyFactorSurvey (Cluster Buster) + >AbdA_Cell_FBgn0000014 + 1 3 0 14 + 0 0 0 18 + 16 0 0 2 + 18 0 0 0 + 1 0 0 17 + 0 0 6 12 + 15 1 2 0 + + # HOMER + >ATGACTCATC AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer 6.049537 -1.782996e+03 0 9805.3,5781.0,3085.1,2715.0,0.00e+00 + 0.419 0.275 0.277 0.028 + 0.001 0.001 0.001 0.997 + 0.010 0.002 0.965 0.023 + 0.984 0.003 0.001 0.012 + 0.062 0.579 0.305 0.054 + 0.026 0.001 0.001 0.972 + 0.043 0.943 0.001 0.012 + 0.980 0.005 0.001 0.014 + 0.050 0.172 0.307 0.471 + 0.149 0.444 0.211 0.195 + + # HOCOMOCO + > AHR_si + 40.51343240527031 18.259112547756697 56.41253757072521 38.77363485291994 + 10.877470982533044 11.870876719950774 34.66312982331297 96.54723985087516 + 21.7165707818416 43.883079837598544 20.706746561638717 67.6523201955933 + 2.5465132509466635 1.3171620263517245 145.8637051322628 4.231336967110781 + 0.0 150.35847450464382 1.4927836298652875 2.1074592421627525 + 3.441039751299748 0.7902972158110341 149.37613720253387 0.3512432070271259 + 0.0 3.441039751299748 0.7024864140542533 149.81519121131782 + 0.0 0.0 153.95871737667187 0.0 + 43.07922333291745 66.87558226865211 16.159862546986584 27.844049228115868 + + # Neph + UW.Motif.0001 atgactca + 0.772949 0.089579 0.098612 0.038860 + 0.026652 0.004653 0.025056 0.943639 + 0.017663 0.023344 0.918728 0.040264 + 0.919596 0.025414 0.029759 0.025231 + 0.060312 0.772259 0.104968 0.062462 + 0.037406 0.020643 0.006667 0.935284 + 0.047316 0.899024 0.026928 0.026732 + 0.948639 0.019497 0.005737 0.026128 + + # Tiffin + T A G C + 30 0 28 40 + 0 0 0 99 + 0 55 14 29 + 0 99 0 0 + 20 78 0 0 + 0 52 7 39 + 19 46 11 22 + 0 60 38 0 + 0 33 0 66 + 73 0 25 0 + 99 0 0 0 + """ + record = Record() + + motif_name = None + motif_nbr = 0 + motif_nbr_added = 0 + + default_nucleotide_order = ["A", "C", "G", "T"] + nucleotide_order = default_nucleotide_order + nucleotide_counts = {"A": [], "C": [], "G": [], "T": []} + + for line in handle: + line = line.strip() + + if line: + columns = line.split() + nbr_columns = len(columns) + + if line.startswith("#"): + # Skip comment lines. + continue + elif line.startswith(">"): + # Parse ">AbdA_Cell_FBgn0000014" and "> AHR_si" like lines and put the part after ">" as motif name. + if motif_nbr != 0 and motif_nbr_added != motif_nbr: + # Add the previous motif to the record. + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name if motif_name else "" + record.append(motif) + motif_nbr_added = motif_nbr + + # Reinitialize variables for the new motif. + motif_name = line[1:].strip() + nucleotide_order = default_nucleotide_order + elif columns[0] == "Gene": + # Parse "Gene ENSG00000197372" like lines and put the gene name as motif name. + if motif_nbr != 0 and motif_nbr_added != motif_nbr: + # Add the previous motif to the record. + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name if motif_name else "" + record.append(motif) + motif_nbr_added = motif_nbr + + # Reinitialize variables for the new motif. + motif_name = columns[1] + nucleotide_order = default_nucleotide_order + elif columns[0] == "Motif": + # Parse "Motif M1734_0.90" like lines. + if motif_nbr != 0 and motif_nbr_added != motif_nbr: + # Add the previous motif to the record. + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name if motif_name else "" + record.append(motif) + motif_nbr_added = motif_nbr + + # Reinitialize variables for the new motif. + motif_name = columns[1] + nucleotide_order = default_nucleotide_order + elif columns[0] == "Pos": + # Parse "Pos A C G T" like lines and change nucleotide order if necessary. + if nbr_columns == 5: + # If the previous line was not a "Gene ENSG00000197372" like line, a new motif starts here. + if motif_nbr != 0 and motif_nbr_added != motif_nbr: + # Add the previous motif to the record. + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name if motif_name else "" + record.append(motif) + motif_nbr_added = motif_nbr + + nucleotide_order = default_nucleotide_order + + if set(columns[1:]) == set(default_nucleotide_order): + nucleotide_order = columns[1:] + elif columns[0] in default_nucleotide_order: + # Parse "A C G T" like lines and change nucleotide order if necessary. + if nbr_columns == 4: + nucleotide_order = default_nucleotide_order + if set(columns) == set(default_nucleotide_order): + nucleotide_order = columns + else: + # Parse matrix columns lines and use the correct nucleotide order. + if nbr_columns == 4: + matrix_columns = columns + elif nbr_columns == 5: + matrix_columns = columns[1:] + else: + continue + + if motif_nbr == motif_nbr_added: + # A new motif matrix starts here, so reinitialize variables for the new motif. + nucleotide_counts = {"A": [], "C": [], "G": [], "T": []} + motif_nbr += 1 + + [ + nucleotide_counts[nucleotide].append(float(nucleotide_count)) + for nucleotide, nucleotide_count in zip( + nucleotide_order, matrix_columns + ) + ] + else: + # Empty lines can be separators between motifs. + if motif_nbr != 0 and motif_nbr_added != motif_nbr: + # Add the previous motif to the record. + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name if motif_name else "" + record.append(motif) + motif_nbr_added = motif_nbr + + # Reinitialize variables for the new motif. + motif_name = None + nucleotide_order = default_nucleotide_order + + if motif_nbr != 0 and motif_nbr_added != motif_nbr: + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name if motif_name else "" + record.append(motif) + + return record + + +def _read_pfm_four_rows(handle): + """Read motifs in position frequency matrix format (4 rows) from a file handle. + + # hDPI + A 0 5 6 5 1 0 + C 1 1 0 0 0 4 + G 5 0 0 0 3 0 + T 0 0 0 1 2 2 + + # YeTFaSCo + A 0.5 0.0 0.0 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.5 0.0 0.0833333334583333 + T 0.0 0.0 0.0 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.0 0.0 0.0833333334583333 + G 0.0 1.0 0.0 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.0 1.0 0.249999999875 + C 0.5 0.0 1.0 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.5 0.0 0.583333333208333 + + # FlyFactorSurvey ZFP finger + A | 92 106 231 135 0 1 780 28 0 700 739 94 60 127 130 + C | 138 82 129 81 774 1 3 1 0 6 17 49 193 122 148 + G | 270 398 54 164 7 659 1 750 755 65 1 41 202 234 205 + T | 290 204 375 411 9 127 6 11 36 20 31 605 335 307 308 + + # ScerTF pcm + A | 9 1 1 97 1 94 + T | 80 1 97 1 1 2 + C | 9 97 1 1 1 2 + G | 2 1 1 1 97 2 + + # ScerTF pfm + A | 0.090 0.010 0.010 0.970 0.010 0.940 + C | 0.090 0.970 0.010 0.010 0.010 0.020 + G | 0.020 0.010 0.010 0.010 0.970 0.020 + T | 0.800 0.010 0.970 0.010 0.010 0.020 + + # iDMMPMM + > abd-A + 0.218451749734889 0.0230646871686108 0.656680805938494 0.898197242841994 0.040694591728526 0.132953340402969 0.74907211028632 0.628313891834571 + 0.0896076352067868 0.317338282078473 0.321580063626723 0.0461293743372216 0.0502386002120891 0.040694591728526 0.0284994697773065 0.0339342523860021 + 0.455991516436904 0.0691940615058324 0.0108695652173913 0.0217391304347826 0.0284994697773065 0.0284994697773065 0.016304347826087 0.160127253446448 + 0.235949098621421 0.590402969247084 0.0108695652173913 0.0339342523860021 0.880567338282079 0.797852598091198 0.206124072110286 0.17762460233298 + + # JASPAR + >MA0001.1 AGL3 + A [ 0 3 79 40 66 48 65 11 65 0 ] + C [94 75 4 3 1 2 5 2 3 3 ] + G [ 1 0 3 4 1 0 5 3 28 88 ] + T [ 2 19 11 50 29 47 22 81 1 6 ] + + or:: + + >MA0001.1 AGL3 + 0 3 79 40 66 48 65 11 65 0 + 94 75 4 3 1 2 5 2 3 3 + 1 0 3 4 1 0 5 3 28 88 + 2 19 11 50 29 47 22 81 1 6 + + # Cys2His2 Zinc Finger Proteins PWM Predictor + base 1 2 3 4 5 6 7 8 9 + a 0.116 0.974 0.444 0.116 0.974 0.444 0.667 0.939 0.068 # noqa: RST301 + c 0.718 0.006 0.214 0.718 0.006 0.214 0.143 0.006 0.107 # noqa: RST301 + g 0.016 0.020 0.028 0.016 0.020 0.028 0.047 0.045 0.216 # noqa: RST301 + t 0.150 0.001 0.314 0.150 0.001 0.314 0.143 0.009 0.609 # noqa: RST301 + + Ent= 1.210 0.202 1.665 1.210 0.202 1.665 1.399 0.396 1.521 + """ + record = Record() + + name_pattern = re.compile(r"^>\s*(.+)\s*") + row_pattern_with_nucleotide_letter = re.compile( + r"\s*([ACGTacgt])\s*[\[|]*\s*([0-9.\-eE\s]+)\s*\]*\s*" + ) + row_pattern_without_nucleotide_letter = re.compile(r"\s*([0-9.\-eE\s]+)\s*") + + motif_name = None + nucleotide_counts = {} + row_count = 0 + nucleotides = ["A", "C", "G", "T"] + + for line in handle: + line = line.strip() + + if line.startswith("Ent="): + continue + + name_match = name_pattern.match(line) + row_match_with_nucleotide_letter = row_pattern_with_nucleotide_letter.match( + line + ) + row_match_without_nucleotide_letter = ( + row_pattern_without_nucleotide_letter.match(line) + ) + + if name_match: + motif_name = name_match.group(1) + elif row_match_with_nucleotide_letter: + (nucleotide, counts_str) = row_match_with_nucleotide_letter.group(1, 2) + current_nucleotide_counts = counts_str.split() + nucleotide_counts[nucleotide.upper()] = [ + float(current_nucleotide_count) + for current_nucleotide_count in current_nucleotide_counts + ] + row_count += 1 + if row_count == 4: + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + + motif.name = motif_name if motif_name else "" + + record.append(motif) + + motif_name = None + nucleotide_counts = {} + row_count = 0 + elif row_match_without_nucleotide_letter: + current_nucleotide_counts = row_match_without_nucleotide_letter.group( + 1 + ).split() + nucleotide_counts[nucleotides[row_count]] = [ + float(current_nucleotide_count) + for current_nucleotide_count in current_nucleotide_counts + ] + row_count += 1 + if row_count == 4: + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + + motif.name = motif_name if motif_name else "" + + record.append(motif) + + motif_name = None + nucleotide_counts = {} + row_count = 0 + + return record + + +def write(motifs): + """Return the representation of motifs in Cluster Buster position frequency matrix format.""" + lines = [] + for m in motifs: + line = f">{m.name}\n" + lines.append(line) + for ACGT_counts in zip( + m.counts["A"], m.counts["C"], m.counts["G"], m.counts["T"] + ): + lines.append("{:0.0f}\t{:0.0f}\t{:0.0f}\t{:0.0f}\n".format(*ACGT_counts)) + + # Finished; glue the lines together. + text = "".join(lines) + + return text diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/thresholds.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/thresholds.py new file mode 100644 index 0000000000000000000000000000000000000000..f94423ba6c7e95cc4e36ccc2c7dd80485890ecf4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/thresholds.py @@ -0,0 +1,109 @@ +# Copyright 2008 by Norbert Dojer. All rights reserved. +# Adapted by Bartek Wilczynski. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Approximate calculation of appropriate thresholds for motif finding.""" + + +class ScoreDistribution: + """Class representing approximate score distribution for a given motif. + + Utilizes a dynamic programming approach to calculate the distribution of + scores with a predefined precision. Provides a number of methods for calculating + thresholds for motif occurrences. + """ + + def __init__(self, motif=None, precision=10**3, pssm=None, background=None): + """Initialize the class.""" + if pssm is None: + self.min_score = min(0.0, motif.min_score()) + self.interval = max(0.0, motif.max_score()) - self.min_score + self.n_points = precision * motif.length + self.ic = motif.ic() + else: + self.min_score = min(0.0, pssm.min) + self.interval = max(0.0, pssm.max) - self.min_score + self.n_points = precision * pssm.length + self.ic = pssm.mean(background) + self.step = self.interval / (self.n_points - 1) + self.mo_density = [0.0] * self.n_points + self.mo_density[-self._index_diff(self.min_score)] = 1.0 + self.bg_density = [0.0] * self.n_points + self.bg_density[-self._index_diff(self.min_score)] = 1.0 + if pssm is None: + for lo, mo in zip(motif.log_odds(), motif.pwm()): + self.modify(lo, mo, motif.background) + else: + for position in range(pssm.length): + mo_new = [0.0] * self.n_points + bg_new = [0.0] * self.n_points + lo = pssm[:, position] + for letter, score in lo.items(): + bg = background[letter] + mo = pow(2, pssm[letter, position]) * bg + d = self._index_diff(score) + for i in range(self.n_points): + mo_new[self._add(i, d)] += self.mo_density[i] * mo + bg_new[self._add(i, d)] += self.bg_density[i] * bg + self.mo_density = mo_new + self.bg_density = bg_new + + def _index_diff(self, x, y=0.0): + return int((x - y + 0.5 * self.step) // self.step) + + def _add(self, i, j): + return max(0, min(self.n_points - 1, i + j)) + + def modify(self, scores, mo_probs, bg_probs): + """Modify motifs and background density.""" + mo_new = [0.0] * self.n_points + bg_new = [0.0] * self.n_points + for k, v in scores.items(): + d = self._index_diff(v) + for i in range(self.n_points): + mo_new[self._add(i, d)] += self.mo_density[i] * mo_probs[k] + bg_new[self._add(i, d)] += self.bg_density[i] * bg_probs[k] + self.mo_density = mo_new + self.bg_density = bg_new + + def threshold_fpr(self, fpr): + """Approximate the log-odds threshold which makes the type I error (false positive rate).""" + i = self.n_points + prob = 0.0 + while prob < fpr: + i -= 1 + prob += self.bg_density[i] + return self.min_score + i * self.step + + def threshold_fnr(self, fnr): + """Approximate the log-odds threshold which makes the type II error (false negative rate).""" + i = -1 + prob = 0.0 + while prob < fnr: + i += 1 + prob += self.mo_density[i] + return self.min_score + i * self.step + + def threshold_balanced(self, rate_proportion=1.0, return_rate=False): + """Approximate log-odds threshold making FNR equal to FPR times rate_proportion.""" + i = self.n_points + fpr = 0.0 + fnr = 1.0 + while fpr * rate_proportion < fnr: + i -= 1 + fpr += self.bg_density[i] + fnr -= self.mo_density[i] + if return_rate: + return self.min_score + i * self.step, fpr + else: + return self.min_score + i * self.step + + def threshold_patser(self): + """Threshold selection mimicking the behaviour of patser (Hertz, Stormo 1999) software. + + It selects such a threshold that the log(fpr)=-ic(M) + note: the actual patser software uses natural logarithms instead of log_2, so the numbers + are not directly comparable. + """ + return self.threshold_fpr(fpr=2**-self.ic) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/transfac.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/transfac.py new file mode 100644 index 0000000000000000000000000000000000000000..141a1d27f7b309a4893ffdec7738f3627efd5d9d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/transfac.py @@ -0,0 +1,331 @@ +# Copyright 2003 by Bartek Wilczynski. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Parsing TRANSFAC files.""" + +from Bio import motifs + + +class Motif(motifs.Motif, dict): + """Store the information for one TRANSFAC motif. + + This class inherits from the Bio.motifs.Motif base class, as well + as from a Python dictionary. All motif information found by the parser + is stored as attributes of the base class when possible; see the + Bio.motifs.Motif base class for a description of these attributes. All + other information associated with the motif is stored as (key, value) + pairs in the dictionary, where the key is the two-letter fields as found + in the TRANSFAC file. References are an exception: These are stored in + the .references attribute. + + These fields are commonly found in TRANSFAC files:: + + AC: Accession number + AS: Accession numbers, secondary + BA: Statistical basis + BF: Binding factors + BS: Factor binding sites underlying the matrix + [sequence; SITE accession number; start position for matrix + sequence; length of sequence used; number of gaps inserted; + strand orientation.] + CC: Comments + CO: Copyright notice + DE: Short factor description + DR: External databases + [database name: database accession number] + DT: Date created/updated + HC: Subfamilies + HP: Superfamilies + ID: Identifier + NA: Name of the binding factor + OC: Taxonomic classification + OS: Species/Taxon + OV: Older version + PV: Preferred version + TY: Type + XX: Empty line; these are not stored in the Record. + + References are stored in an .references attribute, which is a list of + dictionaries with the following keys:: + + RN: Reference number + RA: Reference authors + RL: Reference data + RT: Reference title + RX: PubMed ID + + For more information, see the TRANSFAC documentation. + """ + + multiple_value_keys = {"BF", "OV", "HP", "BS", "HC", "DT", "DR", "CC"} + # These keys can occur multiple times for one motif + + reference_keys = {"RX", "RA", "RT", "RL"} + # These keys occur for references + + def __getitem__(self, key): + try: + value = super().__getitem__(key) # motifs.Motif + except TypeError: + value = super(motifs.Motif, self).__getitem__(key) # dict + return value + + +class Record(list): + """Store the information in a TRANSFAC matrix table. + + The record inherits from a list containing the individual motifs. + + Attributes: + - version - The version number, corresponding to the 'VV' field + in the TRANSFAC file; + + """ + + def __init__(self): + """Initialize the class.""" + self.version = None + + def __str__(self): + """Turn the TRANSFAC matrix into a string.""" + return write(self) + + +def read(handle, strict=True): + """Parse a transfac format handle into a Record object.""" + annotations = {} + references = [] + counts = None + record = Record() + for line in handle: + line = line.strip() + if not line: + continue + key_value = line.split(None, 1) + key = key_value[0].strip() + if strict: + if len(key) != 2: + raise ValueError( + "The key value of a TRANSFAC motif line should have 2 characters:" + f'"{line}"' + ) + if len(key_value) == 2: + value = key_value[1].strip() + if strict: + if not line.partition(" ")[1]: + raise ValueError( + "A TRANSFAC motif line should have 2 " + "spaces between key and value columns: " + f'"{line}"' + ) + if key == "VV": + record.version = value + elif key in ("P0", "PO"): # Old TRANSFAC files use PO instead of P0 + counts = {} + if value.split()[:4] != ["A", "C", "G", "T"]: + raise ValueError( + f'A TRANSFAC matrix "{key}" line should be ' + f'followed by "A C G T": {line}' + ) + length = 0 + for c in "ACGT": + counts[c] = [] + for line in handle: + line = line.strip() + key_value = line.split(None, 1) + key = key_value[0].strip() + if len(key_value) == 2: + value = key_value[1].strip() + if strict: + if not line.partition(" ")[1]: + raise ValueError( + "A TRANSFAC motif line should have 2 spaces" + f' between key and value columns: "{line}"' + ) + try: + i = int(key) + except ValueError: + break + if length == 0 and i == 0: + if strict: + raise ValueError( + 'A TRANSFAC matrix should start with "01" as first row' + f' of the matrix, but this matrix uses "00": "{line}' + ) + else: + length += 1 + if i != length: + raise ValueError( + "The TRANSFAC matrix row number does not match the position" + f' in the matrix: "{line}"' + ) + if strict: + if len(key) == 1: + raise ValueError( + "A TRANSFAC matrix line should have a 2 digit" + f' key at the start of the line ("{i:02d}"),' + f' but this matrix uses "{i:d}": "{line:s}".' + ) + if len(key_value) != 2: + raise ValueError( + "A TRANSFAC matrix line should have a key and a" + f' value: "{line}"' + ) + values = value.split()[:4] + if len(values) != 4: + raise ValueError( + "A TRANSFAC matrix line should have a value for each" + f' nucleotide (A, C, G and T): "{line}"' + ) + for c, v in zip("ACGT", values): + counts[c].append(float(v)) + if line == "XX": + pass + elif key == "RN": + index, separator, accession = value.partition(";") + if index[0] != "[": + raise ValueError( + f'The index "{index}" in a TRANSFAC RN line should start' + f' with a "[": "{line}"' + ) + if index[-1] != "]": + raise ValueError( + f'The index "{index}" in a TRANSFAC RN line should end' + f' with a "]": "{line}"' + ) + index = int(index[1:-1]) + if len(references) != index - 1: + raise ValueError( + f'The index "{index:d}" of the TRANSFAC RN line does not ' + "match the current number of seen references " + f'"{len(references) + 1:d}": "{line:s}"' + ) + reference = {key: value} + references.append(reference) + elif key == "//": + if counts is not None: + motif = Motif(alphabet="ACGT", counts=counts) + motif.update(annotations) + motif.references = references + record.append(motif) + annotations = {} + references = [] + elif key in Motif.reference_keys: + reference[key] = value + elif key in Motif.multiple_value_keys: + if key not in annotations: + annotations[key] = [] + annotations[key].append(value) + else: + annotations[key] = value + return record + + +def write(motifs): + """Write the representation of a motif in TRANSFAC format.""" + blocks = [] + try: + version = motifs.version + except AttributeError: + pass + else: + if version is not None: + block = ( + """\ +VV %s +XX +// +""" + % version + ) + blocks.append(block) + multiple_value_keys = Motif.multiple_value_keys + sections = ( + ("AC", "AS"), # Accession + ("ID",), # ID + ("DT", "CO"), # Date, copyright + ("NA",), # Name + ("DE",), # Short factor description + ("TY",), # Type + ("OS", "OC"), # Organism + ("HP", "HC"), # Superfamilies, subfamilies + ("BF",), # Binding factors + ("P0",), # Frequency matrix + ("BA",), # Statistical basis + ("BS",), # Factor binding sites + ("CC",), # Comments + ("DR",), # External databases + ("OV", "PV"), # Versions + ) + for motif in motifs: + lines = [] + for section in sections: + blank = False + for key in section: + if key == "P0": + # Frequency matrix + length = motif.length + if length == 0: + continue + sequence = motif.degenerate_consensus + letters = sorted(motif.alphabet) + line = " ".join(["P0"] + letters) + + lines.append(line) + for i in range(length): + line = ( + " ".join(["%02.d"] + ["%6.20g" for _ in letters]) + + " %s" + ) + line = line % tuple( + [i + 1] + + [motif.counts[_][i] for _ in letters] + + [sequence[i]] + ) + lines.append(line) + blank = True + else: + try: + value = motif.get(key) + except AttributeError: + value = None + if value is not None: + if key in multiple_value_keys: + for v in value: + line = f"{key} {v}" + lines.append(line) + else: + line = f"{key} {value}" + lines.append(line) + blank = True + if key == "PV": + # References + try: + references = motif.references + except AttributeError: + pass + else: + keys = ("RN", "RX", "RA", "RT", "RL") + for reference in references: + for key in keys: + value = reference.get(key) + if value is None: + continue + line = f"{key} {value}" + lines.append(line) + blank = True + if blank: + line = "XX" + lines.append(line) + # Finished this motif; glue the lines together + line = "//" + lines.append(line) + block = "\n".join(lines) + "\n" + blocks.append(block) + # Finished all motifs; glue the blocks together + text = "".join(blocks) + return text diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/xms.py b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/xms.py new file mode 100644 index 0000000000000000000000000000000000000000..0d39d8f8b125cc717630d3ac51bfca98c553c0dd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/motifs/xms.py @@ -0,0 +1,106 @@ +# Copyright 2015 by Gert Hulselmans. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Parse XMS motif files.""" + +import re +from xml.dom import minidom +from xml.dom import Node + +from Bio import motifs + + +class XMSScanner: + """Class for scanning XMS XML file.""" + + def __init__(self, doc): + """Generate motif Record from xms document, an XML-like motif pfm file.""" + self.record = Record() + for child in doc.getElementsByTagName("motif"): + if child.nodeType == Node.ELEMENT_NODE: + self.handle_motif(child) + + def handle_motif(self, node): + """Read the motif's name and column from the node and add the motif record.""" + motif_name = self.get_text(node.getElementsByTagName("name")) + nucleotide_counts = {"A": [], "C": [], "G": [], "T": []} + + for column in node.getElementsByTagName("column"): + [ + nucleotide_counts[nucleotide].append(float(nucleotide_count)) + for nucleotide, nucleotide_count in zip( + ["A", "C", "G", "T"], self.get_acgt(column) + ) + ] + + motif = motifs.Motif(alphabet="GATC", counts=nucleotide_counts) + motif.name = motif_name + + self.record.append(motif) + + def get_property_value(self, node, key_name): + """Extract the value of the motif's property named key_name from node.""" + for cur_property in node.getElementsByTagName("prop"): + right_property = False + cur_value = None + for child in cur_property.childNodes: + if child.nodeType != Node.ELEMENT_NODE: + continue + if child.tagName == "key" and self.get_text([child]) == key_name: + right_property = True + if child.tagName == "value": + cur_value = self.get_text([child]) + if right_property: + return cur_value + return None + + def get_acgt(self, node): + """Get and return the motif's weights of A, C, G, T.""" + a, c, g, t = 0.0, 0.0, 0.0, 0.0 + for weight in node.getElementsByTagName("weight"): + if weight.getAttribute("symbol") == "adenine": + a = float(self.get_text([weight])) + elif weight.getAttribute("symbol") == "cytosine": + c = float(self.get_text([weight])) + elif weight.getAttribute("symbol") == "guanine": + g = float(self.get_text([weight])) + elif weight.getAttribute("symbol") == "thymine": + t = float(self.get_text([weight])) + return a, c, g, t + + def get_text(self, nodelist): + """Return a string representation of the motif's properties listed on nodelist .""" + retlist = [] + for node in nodelist: + if node.nodeType == Node.TEXT_NODE: + retlist.append(node.wholeText) + elif node.hasChildNodes: + retlist.append(self.get_text(node.childNodes)) + + return re.sub(r"\s+", " ", "".join(retlist)) + + +class Record(list): + """Class to store the information in a XMS matrix table. + + The record inherits from a list containing the individual motifs. + """ + + def __str__(self): + """Return a string representation of the motifs in the Record object.""" + return "\n".join(str(motif) for motif in self) + + +def read(handle): + """Read motifs in XMS matrix format from a file handle. + + XMS is an XML format for describing regulatory motifs and PSSMs. + This format was defined by Thomas Down, and used in the NestedMICA and MotifExplorer programs. + """ + xms_doc = minidom.parse(handle) + record = XMSScanner(xms_doc).record + + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/pairwise2.py b/.venv_haddock/lib/python3.12/site-packages/Bio/pairwise2.py new file mode 100644 index 0000000000000000000000000000000000000000..e6aa80271e3cfcdfa31bb07932ad0c80658752ac --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/pairwise2.py @@ -0,0 +1,1441 @@ +# Copyright 2002 by Jeffrey Chang. +# Copyright 2016, 2019, 2020 by Markus Piotrowski. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Pairwise sequence alignment using a dynamic programming algorithm. + +This provides functions to get global and local alignments between two +sequences. A global alignment finds the best concordance between all +characters in two sequences. A local alignment finds just the +subsequences that align the best. Local alignments must have a positive +score to be reported and they will not be extended for 'zero counting' +matches. This means a local alignment will always start and end with +a positive counting match. + +When doing alignments, you can specify the match score and gap +penalties. The match score indicates the compatibility between an +alignment of two characters in the sequences. Highly compatible +characters should be given positive scores, and incompatible ones +should be given negative scores or 0. The gap penalties should be +negative. + +The names of the alignment functions in this module follow the +convention +XX +where is either "global" or "local" and XX is a 2 +character code indicating the parameters it takes. The first +character indicates the parameters for matches (and mismatches), and +the second indicates the parameters for gap penalties. + +The match parameters are:: + + CODE DESCRIPTION & OPTIONAL KEYWORDS + x No parameters. Identical characters have score of 1, otherwise 0. + m A match score is the score of identical chars, otherwise mismatch + score. Keywords ``match``, ``mismatch``. + d A dictionary returns the score of any pair of characters. + Keyword ``match_dict``. + c A callback function returns scores. Keyword ``match_fn``. + +The gap penalty parameters are:: + + CODE DESCRIPTION & OPTIONAL KEYWORDS + x No gap penalties. + s Same open and extend gap penalties for both sequences. + Keywords ``open``, ``extend``. + d The sequences have different open and extend gap penalties. + Keywords ``openA``, ``extendA``, ``openB``, ``extendB``. + c A callback function returns the gap penalties. + Keywords ``gap_A_fn``, ``gap_B_fn``. + +All the different alignment functions are contained in an object +``align``. For example: + + >>> from Bio import pairwise2 + >>> alignments = pairwise2.align.globalxx("ACCGT", "ACG") + +For better readability, the required arguments can be used with optional keywords: + + >>> alignments = pairwise2.align.globalxx(sequenceA="ACCGT", sequenceB="ACG") + +The result is a list of the alignments between the two strings. Each alignment +is a named tuple consisting of the two aligned sequences, the score and the +start and end positions of the alignment: + + >>> print(alignments) + [Alignment(seqA='ACCGT', seqB='A-CG-', score=3.0, start=0, end=5), ... + +You can access each element of an alignment by index or name: + + >>> alignments[0][2] + 3.0 + >>> alignments[0].score + 3.0 + +For a nice printout of an alignment, use the ``format_alignment`` method of +the module: + + >>> from Bio.pairwise2 import format_alignment + >>> print(format_alignment(*alignments[0])) + ACCGT + | || + A-CG- + Score=3 + + +All alignment functions have the following arguments: + +- Two sequences: strings, Biopython sequence objects or lists. + Lists are useful for supplying sequences which contain residues that are + encoded by more than one letter. + +- ``penalize_extend_when_opening``: boolean (default: False). + Whether to count an extension penalty when opening a gap. If false, a gap of + 1 is only penalized an "open" penalty, otherwise it is penalized + "open+extend". + +- ``penalize_end_gaps``: boolean. + Whether to count the gaps at the ends of an alignment. By default, they are + counted for global alignments but not for local ones. Setting + ``penalize_end_gaps`` to (boolean, boolean) allows you to specify for the + two sequences separately whether gaps at the end of the alignment should be + counted. + +- ``gap_char``: string (default: ``'-'``). + Which character to use as a gap character in the alignment returned. If your + input sequences are lists, you must change this to ``['-']``. + +- ``force_generic``: boolean (default: False). + Always use the generic, non-cached, dynamic programming function (slow!). + For debugging. + +- ``score_only``: boolean (default: False). + Only get the best score, don't recover any alignments. The return value of + the function is the score. Faster and uses less memory. + +- ``one_alignment_only``: boolean (default: False). + Only recover one alignment. + +The other parameters of the alignment function depend on the function called. +Some examples: + +- Find the best global alignment between the two sequences. Identical + characters are given 1 point. No points are deducted for mismatches or gaps. + + >>> for a in pairwise2.align.globalxx("ACCGT", "ACG"): + ... print(format_alignment(*a)) + ACCGT + | || + A-CG- + Score=3 + + ACCGT + || | + AC-G- + Score=3 + + +- Same thing as before, but with a local alignment. Note that + ``format_alignment`` will only show the aligned parts of the sequences, + together with the starting positions. + + >>> for a in pairwise2.align.localxx("ACCGT", "ACG"): + ... print(format_alignment(*a)) + 1 ACCG + | || + 1 A-CG + Score=3 + + 1 ACCG + || | + 1 AC-G + Score=3 + + + To restore the 'historic' behaviour of ``format_alignemt``, i.e., showing + also the un-aligned parts of both sequences, use the new keyword parameter + ``full_sequences``: + + >>> for a in pairwise2.align.localxx("ACCGT", "ACG"): + ... print(format_alignment(*a, full_sequences=True)) + ACCGT + | || + A-CG- + Score=3 + + ACCGT + || | + AC-G- + Score=3 + + + +- Do a global alignment. Identical characters are given 2 points, 1 point is + deducted for each non-identical character. Don't penalize gaps. + + >>> for a in pairwise2.align.globalmx("ACCGT", "ACG", 2, -1): + ... print(format_alignment(*a)) + ACCGT + | || + A-CG- + Score=6 + + ACCGT + || | + AC-G- + Score=6 + + +- Same as above, except now 0.5 points are deducted when opening a gap, and + 0.1 points are deducted when extending it. + + >>> for a in pairwise2.align.globalms("ACCGT", "ACG", 2, -1, -.5, -.1): + ... print(format_alignment(*a)) + ACCGT + | || + A-CG- + Score=5 + + ACCGT + || | + AC-G- + Score=5 + + +- Note that you can use keywords to increase the readability, e.g.: + + >>> a = pairwise2.align.globalms("ACGT", "ACG", match=2, mismatch=-1, open=-.5, + ... extend=-.1) + +- Depending on the penalties, a gap in one sequence may be followed by a gap in + the other sequence.If you don't like this behaviour, increase the gap-open + penalty: + + >>> for a in pairwise2.align.globalms("A", "T", 5, -4, -1, -.1): + ... print(format_alignment(*a)) + A- + + -T + Score=-2 + + >>> for a in pairwise2.align.globalms("A", "T", 5, -4, -3, -.1): + ... print(format_alignment(*a)) + A + . + T + Score=-4 + + +- The alignment function can also use known matrices already included in + Biopython (in ``Bio.Align.substitution_matrices``): + + >>> from Bio.Align import substitution_matrices + >>> matrix = substitution_matrices.load("BLOSUM62") + >>> for a in pairwise2.align.globaldx("KEVLA", "EVL", matrix): + ... print(format_alignment(*a)) + KEVLA + ||| + -EVL- + Score=13 + + +- With the parameter ``c`` you can define your own match- and gap functions. + E.g. to define an affine logarithmic gap function and using it: + + >>> from math import log + >>> def gap_function(x, y): # x is gap position in seq, y is gap length + ... if y == 0: # No gap + ... return 0 + ... elif y == 1: # Gap open penalty + ... return -2 + ... return - (2 + y/4.0 + log(y)/2.0) + ... + >>> alignment = pairwise2.align.globalmc("ACCCCCGT", "ACG", 5, -4, + ... gap_function, gap_function) + + You can define different gap functions for each sequence. + Self-defined match functions must take the two residues to be compared and + return a score. + +To see a description of the parameters for a function, please look at +the docstring for the function via the help function, e.g. +type ``help(pairwise2.align.localds)`` at the Python prompt. + +""" # noqa: W291 + +import warnings +from collections import namedtuple + +from Bio import BiopythonDeprecationWarning +from Bio import BiopythonWarning +from Bio.Align import substitution_matrices + +warnings.warn( + "Bio.pairwise2 has been deprecated, and we intend to remove it in a " + "future release of Biopython. As an alternative, please consider using " + "Bio.Align.PairwiseAligner as a replacement, and contact the " + "Biopython developers if you still need the Bio.pairwise2 module.", + BiopythonDeprecationWarning, +) + + +MAX_ALIGNMENTS = 1000 # maximum alignments recovered in traceback + +Alignment = namedtuple("Alignment", ("seqA, seqB, score, start, end")) + + +class align: + """Provide functions that do alignments. + + Alignment functions are called as: + + pairwise2.align.globalXX + + or + + pairwise2.align.localXX + + Where XX is a 2 character code indicating the match/mismatch parameters + (first character, either x, m, d or c) and the gap penalty parameters + (second character, either x, s, d, or c). + + For a detailed description read the main module's docstring (e.g., + type ``help(pairwise2)``). + To see a description of the parameters for a function, please + look at the docstring for the function, e.g. type + ``help(pairwise2.align.localds)`` at the Python prompt. + """ + + class alignment_function: + """Callable class which impersonates an alignment function. + + The constructor takes the name of the function. This class + will decode the name of the function to figure out how to + interpret the parameters. + """ + + # match code -> tuple of (parameters, docstring) + match2args = { + "x": ([], ""), + "m": ( + ["match", "mismatch"], + "match is the score to given to identical characters.\n" + "mismatch is the score given to non-identical ones.", + ), + "d": ( + ["match_dict"], + "match_dict is a dictionary where the keys are tuples\n" + "of pairs of characters and the values are the scores,\n" + "e.g. ('A', 'C') : 2.5.", + ), + "c": ( + ["match_fn"], + "match_fn is a callback function that takes two " + "characters and returns the score between them.", + ), + } + # penalty code -> tuple of (parameters, docstring) + penalty2args = { + "x": ([], ""), + "s": ( + ["open", "extend"], + "open and extend are the gap penalties when a gap is\n" + "opened and extended. They should be negative.", + ), + "d": ( + ["openA", "extendA", "openB", "extendB"], + "openA and extendA are the gap penalties for sequenceA,\n" + "and openB and extendB for sequenceB. The penalties\n" + "should be negative.", + ), + "c": ( + ["gap_A_fn", "gap_B_fn"], + "gap_A_fn and gap_B_fn are callback functions that takes\n" + "(1) the index where the gap is opened, and (2) the length\n" + "of the gap. They should return a gap penalty.", + ), + } + + def __init__(self, name): + """Check to make sure the name of the function is reasonable.""" + if name.startswith("global"): + if len(name) != 8: + raise AttributeError("function should be globalXX") + elif name.startswith("local"): + if len(name) != 7: + raise AttributeError("function should be localXX") + else: + raise AttributeError(name) + align_type, match_type, penalty_type = name[:-2], name[-2], name[-1] + try: + match_args, match_doc = self.match2args[match_type] + except KeyError: + raise AttributeError(f"unknown match type {match_type!r}") + try: + penalty_args, penalty_doc = self.penalty2args[penalty_type] + except KeyError: + raise AttributeError(f"unknown penalty type {penalty_type!r}") + + # Now get the names of the parameters to this function. + param_names = ["sequenceA", "sequenceB"] + param_names.extend(match_args) + param_names.extend(penalty_args) + self.function_name = name + self.align_type = align_type + self.param_names = param_names + + self.__name__ = self.function_name + # Set the doc string. + doc = f"{self.__name__}({', '.join(self.param_names)}) -> alignments\n" + doc += """\ +\nThe following parameters can also be used with optional +keywords of the same name.\n\n +sequenceA and sequenceB must be of the same type, either +strings, lists or Biopython sequence objects.\n +""" + if match_doc: + doc += f"\n{match_doc}\n" + if penalty_doc: + doc += f"\n{penalty_doc}\n" + doc += """\ +\nalignments is a list of named tuples (seqA, seqB, score, +begin, end). seqA and seqB are strings showing the alignment +between the sequences. score is the score of the alignment. +begin and end are indexes of seqA and seqB that indicate +where the alignment occurs. +""" + self.__doc__ = doc + + def decode(self, *args, **keywds): + """Decode the arguments for the _align function. + + keywds will get passed to it, so translate the arguments + to this function into forms appropriate for _align. + """ + keywds = keywds.copy() + + # Replace possible "keywords" with arguments: + args += (len(self.param_names) - len(args)) * (None,) + for key in keywds.copy(): + if key in self.param_names: + _index = self.param_names.index(key) + args = args[:_index] + (keywds[key],) + args[_index:] + del keywds[key] + args = tuple(arg for arg in args if arg is not None) + + if len(args) != len(self.param_names): + raise TypeError( + "%s takes exactly %d argument (%d given)" + % (self.function_name, len(self.param_names), len(args)) + ) + + i = 0 + while i < len(self.param_names): + if self.param_names[i] in [ + "sequenceA", + "sequenceB", + "gap_A_fn", + "gap_B_fn", + "match_fn", + ]: + keywds[self.param_names[i]] = args[i] + i += 1 + elif self.param_names[i] == "match": + assert self.param_names[i + 1] == "mismatch" + match, mismatch = args[i], args[i + 1] + keywds["match_fn"] = identity_match(match, mismatch) + i += 2 + elif self.param_names[i] == "match_dict": + keywds["match_fn"] = dictionary_match(args[i]) + i += 1 + elif self.param_names[i] == "open": + assert self.param_names[i + 1] == "extend" + open, extend = args[i], args[i + 1] + pe = keywds.get("penalize_extend_when_opening", 0) + keywds["gap_A_fn"] = affine_penalty(open, extend, pe) + keywds["gap_B_fn"] = affine_penalty(open, extend, pe) + i += 2 + elif self.param_names[i] == "openA": + assert self.param_names[i + 3] == "extendB" + openA, extendA, openB, extendB = args[i : i + 4] + pe = keywds.get("penalize_extend_when_opening", 0) + keywds["gap_A_fn"] = affine_penalty(openA, extendA, pe) + keywds["gap_B_fn"] = affine_penalty(openB, extendB, pe) + i += 4 + else: + raise ValueError(f"unknown parameter {self.param_names[i]!r}") + + # Here are the default parameters for _align. Assign + # these to keywds, unless already specified. + pe = keywds.get("penalize_extend_when_opening", 0) + default_params = [ + ("match_fn", identity_match(1, 0)), + ("gap_A_fn", affine_penalty(0, 0, pe)), + ("gap_B_fn", affine_penalty(0, 0, pe)), + ("penalize_extend_when_opening", 0), + ("penalize_end_gaps", self.align_type == "global"), + ("align_globally", self.align_type == "global"), + ("gap_char", "-"), + ("force_generic", 0), + ("score_only", 0), + ("one_alignment_only", 0), + ] + for name, default in default_params: + keywds[name] = keywds.get(name, default) + value = keywds["penalize_end_gaps"] + try: + n = len(value) + except TypeError: + keywds["penalize_end_gaps"] = tuple([value] * 2) + else: + assert n == 2 + return keywds + + def __call__(self, *args, **keywds): + """Call the alignment instance already created.""" + keywds = self.decode(*args, **keywds) + return _align(**keywds) + + def __getattr__(self, attr): + """Call alignment_function() to check and decode the attributes.""" + # The following 'magic' is needed to rewrite the class docstring + # dynamically: + wrapper = self.alignment_function(attr) + wrapper_type = type(wrapper) + wrapper_dict = wrapper_type.__dict__.copy() + wrapper_dict["__doc__"] = wrapper.__doc__ + new_alignment_function = type("alignment_function", (object,), wrapper_dict) + + return new_alignment_function(attr) + + +align = align() + + +def _align( + sequenceA, + sequenceB, + match_fn, + gap_A_fn, + gap_B_fn, + penalize_extend_when_opening, + penalize_end_gaps, + align_globally, + gap_char, + force_generic, + score_only, + one_alignment_only, +): + """Return optimal alignments between two sequences (PRIVATE). + + This method either returns a list of optimal alignments (with the same + score) or just the optimal score. + """ + if not sequenceA or not sequenceB: + return [] + try: + sequenceA + gap_char + sequenceB + gap_char + except TypeError: + raise TypeError( + "both sequences must be of the same type, either " + "string/sequence object or list. Gap character must " + "fit the sequence type (string or list)" + ) + + if not isinstance(sequenceA, list): + sequenceA = str(sequenceA) + if not isinstance(sequenceB, list): + sequenceB = str(sequenceB) + if not align_globally and (penalize_end_gaps[0] or penalize_end_gaps[1]): + warnings.warn( + '"penalize_end_gaps" should not be used in local ' + "alignments. The resulting score may be wrong.", + BiopythonWarning, + ) + + if ( + (not force_generic) + and isinstance(gap_A_fn, affine_penalty) + and isinstance(gap_B_fn, affine_penalty) + ): + open_A, extend_A = gap_A_fn.open, gap_A_fn.extend + open_B, extend_B = gap_B_fn.open, gap_B_fn.extend + matrices = _make_score_matrix_fast( + sequenceA, + sequenceB, + match_fn, + open_A, + extend_A, + open_B, + extend_B, + penalize_extend_when_opening, + penalize_end_gaps, + align_globally, + score_only, + ) + else: + matrices = _make_score_matrix_generic( + sequenceA, + sequenceB, + match_fn, + gap_A_fn, + gap_B_fn, + penalize_end_gaps, + align_globally, + score_only, + ) + + score_matrix, trace_matrix, best_score = matrices + + # print("SCORE %s" % print_matrix(score_matrix)) + # print("TRACEBACK %s" % print_matrix(trace_matrix)) + + # If they only want the score, then return it. + if score_only: + return best_score + + starts = _find_start(score_matrix, best_score, align_globally) + + # Recover the alignments and return them. + alignments = _recover_alignments( + sequenceA, + sequenceB, + starts, + best_score, + score_matrix, + trace_matrix, + align_globally, + gap_char, + one_alignment_only, + gap_A_fn, + gap_B_fn, + ) + if not alignments: + # This may happen, see recover_alignments for explanation + score_matrix, trace_matrix = _reverse_matrices(score_matrix, trace_matrix) + starts = [(z, (y, x)) for z, (x, y) in starts] + alignments = _recover_alignments( + sequenceB, + sequenceA, + starts, + best_score, + score_matrix, + trace_matrix, + align_globally, + gap_char, + one_alignment_only, + gap_B_fn, + gap_A_fn, + reverse=True, + ) + return alignments + + +def _make_score_matrix_generic( + sequenceA, + sequenceB, + match_fn, + gap_A_fn, + gap_B_fn, + penalize_end_gaps, + align_globally, + score_only, +): + """Generate a score and traceback matrix (PRIVATE). + + This implementation according to Needleman-Wunsch allows the usage of + general gap functions and is rather slow. It is automatically called if + you define your own gap functions. You can force the usage of this method + with ``force_generic=True``. + """ + local_max_score = 0 + # Create the score and traceback matrices. These should be in the + # shape: + # sequenceA (down) x sequenceB (across) + lenA, lenB = len(sequenceA), len(sequenceB) + score_matrix, trace_matrix = [], [] + for i in range(lenA + 1): + score_matrix.append([None] * (lenB + 1)) + if not score_only: + trace_matrix.append([None] * (lenB + 1)) + + # Initialize first row and column with gap scores. This is like opening up + # i gaps at the beginning of sequence A or B. + for i in range(lenA + 1): + if penalize_end_gaps[1]: # [1]:gap in sequence B + score = gap_B_fn(0, i) + else: + score = 0.0 + score_matrix[i][0] = score + for i in range(lenB + 1): + if penalize_end_gaps[0]: # [0]:gap in sequence A + score = gap_A_fn(0, i) + else: + score = 0.0 + score_matrix[0][i] = score + + # Fill in the score matrix. Each position in the matrix + # represents an alignment between a character from sequence A to + # one in sequence B. As I iterate through the matrix, find the + # alignment by choose the best of: + # 1) extending a previous alignment without gaps + # 2) adding a gap in sequenceA + # 3) adding a gap in sequenceB + for row in range(1, lenA + 1): + for col in range(1, lenB + 1): + # First, calculate the score that would occur by extending + # the alignment without gaps. + # fmt: off + nogap_score = ( + score_matrix[row - 1][col - 1] + + match_fn(sequenceA[row - 1], sequenceB[col - 1]) + ) + + # fmt: on + # Try to find a better score by opening gaps in sequenceA. + # Do this by checking alignments from each column in the row. + # Each column represents a different character to align from, + # and thus a different length gap. + # Although the gap function does not distinguish between opening + # and extending a gap, we distinguish them for the backtrace. + if not penalize_end_gaps[0] and row == lenA: + row_open = score_matrix[row][col - 1] + row_extend = max(score_matrix[row][x] for x in range(col)) + else: + row_open = score_matrix[row][col - 1] + gap_A_fn(row, 1) + row_extend = max( + score_matrix[row][x] + gap_A_fn(row, col - x) for x in range(col) + ) + + # Try to find a better score by opening gaps in sequenceB. + if not penalize_end_gaps[1] and col == lenB: + col_open = score_matrix[row - 1][col] + col_extend = max(score_matrix[x][col] for x in range(row)) + else: + col_open = score_matrix[row - 1][col] + gap_B_fn(col, 1) + col_extend = max( + score_matrix[x][col] + gap_B_fn(col, row - x) for x in range(row) + ) + + best_score = max(nogap_score, row_open, row_extend, col_open, col_extend) + local_max_score = max(local_max_score, best_score) + if not align_globally and best_score < 0: + score_matrix[row][col] = 0.0 + else: + score_matrix[row][col] = best_score + + # The backtrace is encoded binary. See _make_score_matrix_fast + # for details. + if not score_only: + trace_score = 0 + if rint(nogap_score) == rint(best_score): + trace_score += 2 + if rint(row_open) == rint(best_score): + trace_score += 1 + if rint(row_extend) == rint(best_score): + trace_score += 8 + if rint(col_open) == rint(best_score): + trace_score += 4 + if rint(col_extend) == rint(best_score): + trace_score += 16 + trace_matrix[row][col] = trace_score + + if not align_globally: + best_score = local_max_score + + return score_matrix, trace_matrix, best_score + + +def _make_score_matrix_fast( + sequenceA, + sequenceB, + match_fn, + open_A, + extend_A, + open_B, + extend_B, + penalize_extend_when_opening, + penalize_end_gaps, + align_globally, + score_only, +): + """Generate a score and traceback matrix according to Gotoh (PRIVATE). + + This is an implementation of the Needleman-Wunsch dynamic programming + algorithm as modified by Gotoh, implementing affine gap penalties. + In short, we have three matrices, holding scores for alignments ending + in (1) a match/mismatch, (2) a gap in sequence A, and (3) a gap in + sequence B, respectively. However, we can combine them in one matrix, + which holds the best scores, and store only those values from the + other matrices that are actually used for the next step of calculation. + The traceback matrix holds the positions for backtracing the alignment. + """ + first_A_gap = calc_affine_penalty(1, open_A, extend_A, penalize_extend_when_opening) + first_B_gap = calc_affine_penalty(1, open_B, extend_B, penalize_extend_when_opening) + local_max_score = 0 + + # Create the score and traceback matrices. These should be in the + # shape: + # sequenceA (down) x sequenceB (across) + lenA, lenB = len(sequenceA), len(sequenceB) + score_matrix, trace_matrix = [], [] + for i in range(lenA + 1): + score_matrix.append([None] * (lenB + 1)) + if not score_only: + trace_matrix.append([None] * (lenB + 1)) + + # Initialize first row and column with gap scores. This is like opening up + # i gaps at the beginning of sequence A or B. + for i in range(lenA + 1): + if penalize_end_gaps[1]: # [1]:gap in sequence B + score = calc_affine_penalty( + i, open_B, extend_B, penalize_extend_when_opening + ) + else: + score = 0 + score_matrix[i][0] = score + for i in range(lenB + 1): + if penalize_end_gaps[0]: # [0]:gap in sequence A + score = calc_affine_penalty( + i, open_A, extend_A, penalize_extend_when_opening + ) + else: + score = 0 + score_matrix[0][i] = score + + # Now initialize the col 'matrix'. Actually this is only a one dimensional + # list, since we only need the col scores from the last row. + col_score = [0] # Best score, if actual alignment ends with gap in seqB + for i in range(1, lenB + 1): + col_score.append( + calc_affine_penalty(i, 2 * open_B, extend_B, penalize_extend_when_opening) + ) + + # The row 'matrix' is calculated on the fly. Here we only need the actual + # score. + # Now, filling up the score and traceback matrices: + for row in range(1, lenA + 1): + row_score = calc_affine_penalty( + row, 2 * open_A, extend_A, penalize_extend_when_opening + ) + for col in range(1, lenB + 1): + # Calculate the score that would occur by extending the + # alignment without gaps. + # fmt: off + nogap_score = ( + score_matrix[row - 1][col - 1] + + match_fn(sequenceA[row - 1], sequenceB[col - 1]) + ) + # fmt: on + # Check the score that would occur if there were a gap in + # sequence A. This could come from opening a new gap or + # extending an existing one. + # A gap in sequence A can also be opened if it follows a gap in + # sequence B: A- + # -B + if not penalize_end_gaps[0] and row == lenA: + row_open = score_matrix[row][col - 1] + row_extend = row_score + else: + row_open = score_matrix[row][col - 1] + first_A_gap + row_extend = row_score + extend_A + row_score = max(row_open, row_extend) + + # The same for sequence B: + if not penalize_end_gaps[1] and col == lenB: + col_open = score_matrix[row - 1][col] + col_extend = col_score[col] + else: + col_open = score_matrix[row - 1][col] + first_B_gap + col_extend = col_score[col] + extend_B + col_score[col] = max(col_open, col_extend) + + best_score = max(nogap_score, col_score[col], row_score) + local_max_score = max(local_max_score, best_score) + if not align_globally and best_score < 0: + score_matrix[row][col] = 0 + else: + score_matrix[row][col] = best_score + + # Now the trace_matrix. The edges of the backtrace are encoded + # binary: 1 = open gap in seqA, 2 = match/mismatch of seqA and + # seqB, 4 = open gap in seqB, 8 = extend gap in seqA, and + # 16 = extend gap in seqB. This values can be summed up. + # Thus, the trace score 7 means that the best score can either + # come from opening a gap in seqA (=1), pairing two characters + # of seqA and seqB (+2=3) or opening a gap in seqB (+4=7). + # However, if we only want the score we don't care about the trace. + if not score_only: + row_score_rint = rint(row_score) + col_score_rint = rint(col_score[col]) + row_trace_score = 0 + col_trace_score = 0 + if rint(row_open) == row_score_rint: + row_trace_score += 1 # Open gap in seqA + if rint(row_extend) == row_score_rint: + row_trace_score += 8 # Extend gap in seqA + if rint(col_open) == col_score_rint: + col_trace_score += 4 # Open gap in seqB + if rint(col_extend) == col_score_rint: + col_trace_score += 16 # Extend gap in seqB + + trace_score = 0 + best_score_rint = rint(best_score) + if rint(nogap_score) == best_score_rint: + trace_score += 2 # Align seqA with seqB + if row_score_rint == best_score_rint: + trace_score += row_trace_score + if col_score_rint == best_score_rint: + trace_score += col_trace_score + trace_matrix[row][col] = trace_score + + if not align_globally: + best_score = local_max_score + + return score_matrix, trace_matrix, best_score + + +def _recover_alignments( + sequenceA, + sequenceB, + starts, + best_score, + score_matrix, + trace_matrix, + align_globally, + gap_char, + one_alignment_only, + gap_A_fn, + gap_B_fn, + reverse=False, +): + """Do the backtracing and return a list of alignments (PRIVATE). + + Recover the alignments by following the traceback matrix. This + is a recursive procedure, but it's implemented here iteratively + with a stack. + + sequenceA and sequenceB may be sequences, including strings, + lists, or list-like objects. In order to preserve the type of + the object, we need to use slices on the sequences instead of + indexes. For example, sequenceA[row] may return a type that's + not compatible with sequenceA, e.g. if sequenceA is a list and + sequenceA[row] is a string. Thus, avoid using indexes and use + slices, e.g. sequenceA[row:row+1]. Assume that client-defined + sequence classes preserve these semantics. + """ + lenA, lenB = len(sequenceA), len(sequenceB) + ali_seqA, ali_seqB = sequenceA[0:0], sequenceB[0:0] + tracebacks = [] + in_process = [] + + for start in starts: + score, (row, col) = start + begin = 0 + if align_globally: + end = None + else: + # If this start is a zero-extension: don't start here! + if (score, (row - 1, col - 1)) in starts: + continue + # Local alignments should start with a positive score! + if score <= 0: + continue + # Local alignments should not end with a gap!: + trace = trace_matrix[row][col] + if (trace - trace % 2) % 4 == 2: # Trace contains 'nogap', fine! + trace_matrix[row][col] = 2 + # If not, don't start here! + else: + continue + end = -max(lenA - row, lenB - col) + if not end: + end = None + col_distance = lenB - col + row_distance = lenA - row + + # fmt: off + ali_seqA = ( + (col_distance - row_distance) * gap_char + + sequenceA[lenA - 1 : row - 1 : -1] + ) + ali_seqB = ( + (row_distance - col_distance) * gap_char + + sequenceB[lenB - 1 : col - 1 : -1] + ) + # fmt: on + in_process += [ + (ali_seqA, ali_seqB, end, row, col, False, trace_matrix[row][col]) + ] + while in_process and len(tracebacks) < MAX_ALIGNMENTS: + # Although we allow a gap in seqB to be followed by a gap in seqA, + # we don't want to allow it the other way round, since this would + # give redundant alignments of type: A- vs. -A + # -B B- + # Thus we need to keep track if a gap in seqA was opened (col_gap) + # and stop the backtrace (dead_end) if a gap in seqB follows. + # + # Attention: This may fail, if the gap-penalties for both strands are + # different. In this case the second alignment may be the only optimal + # alignment. Thus it can happen that no alignment is returned. For + # this case a workaround was implemented, which reverses the input and + # the matrices (this happens in _reverse_matrices) and repeats the + # backtrace. The variable 'reverse' keeps track of this. + dead_end = False + ali_seqA, ali_seqB, end, row, col, col_gap, trace = in_process.pop() + + while (row > 0 or col > 0) and not dead_end: + cache = (ali_seqA[:], ali_seqB[:], end, row, col, col_gap) + + # If trace is empty we have reached at least one border of the + # matrix or the end of a local alignment. Just add the rest of + # the sequence(s) and fill with gaps if necessary. + if not trace: + if col and col_gap: + dead_end = True + else: + ali_seqA, ali_seqB = _finish_backtrace( + sequenceA, sequenceB, ali_seqA, ali_seqB, row, col, gap_char + ) + break + elif trace % 2 == 1: # = row open = open gap in seqA + trace -= 1 + if col_gap: + dead_end = True + else: + col -= 1 + ali_seqA += gap_char + ali_seqB += sequenceB[col : col + 1] + col_gap = False + elif trace % 4 == 2: # = match/mismatch of seqA with seqB + trace -= 2 + row -= 1 + col -= 1 + ali_seqA += sequenceA[row : row + 1] + ali_seqB += sequenceB[col : col + 1] + col_gap = False + elif trace % 8 == 4: # = col open = open gap in seqB + trace -= 4 + row -= 1 + ali_seqA += sequenceA[row : row + 1] + ali_seqB += gap_char + col_gap = True + elif trace in (8, 24): # = row extend = extend gap in seqA + trace -= 8 + if col_gap: + dead_end = True + else: + col_gap = False + # We need to find the starting point of the extended gap + x = _find_gap_open( + sequenceA, + sequenceB, + ali_seqA, + ali_seqB, + end, + row, + col, + col_gap, + gap_char, + score_matrix, + trace_matrix, + in_process, + gap_A_fn, + col, + row, + "col", + best_score, + align_globally, + ) + ali_seqA, ali_seqB, row, col, in_process, dead_end = x + elif trace == 16: # = col extend = extend gap in seqB + trace -= 16 + col_gap = True + x = _find_gap_open( + sequenceA, + sequenceB, + ali_seqA, + ali_seqB, + end, + row, + col, + col_gap, + gap_char, + score_matrix, + trace_matrix, + in_process, + gap_B_fn, + row, + col, + "row", + best_score, + align_globally, + ) + ali_seqA, ali_seqB, row, col, in_process, dead_end = x + + if trace: # There is another path to follow... + cache += (trace,) + in_process.append(cache) + trace = trace_matrix[row][col] + if not align_globally: + if score_matrix[row][col] == best_score: + # We have gone through a 'zero-score' extension, discard it + dead_end = True + elif score_matrix[row][col] <= 0: + # We have reached the end of the backtrace + begin = max(row, col) + trace = 0 + if not dead_end: + if not reverse: + tracebacks.append((ali_seqA[::-1], ali_seqB[::-1], score, begin, end)) + else: + tracebacks.append((ali_seqB[::-1], ali_seqA[::-1], score, begin, end)) + if one_alignment_only: + break + return _clean_alignments(tracebacks) + + +def _find_start(score_matrix, best_score, align_globally): + """Return a list of starting points (score, (row, col)) (PRIVATE). + + Indicating every possible place to start the tracebacks. + """ + nrows, ncols = len(score_matrix), len(score_matrix[0]) + # In this implementation of the global algorithm, the start will always be + # the bottom right corner of the matrix. + if align_globally: + starts = [(best_score, (nrows - 1, ncols - 1))] + else: + # For local alignments, there may be many different start points. + starts = [] + tolerance = 0 # XXX do anything with this? + # Now find all the positions within some tolerance of the best + # score. + for row in range(nrows): + for col in range(ncols): + score = score_matrix[row][col] + if rint(abs(score - best_score)) <= rint(tolerance): + starts.append((score, (row, col))) + return starts + + +def _reverse_matrices(score_matrix, trace_matrix): + """Reverse score and trace matrices (PRIVATE).""" + reverse_score_matrix = [] + reverse_trace_matrix = [] + # fmt: off + reverse_trace = { + 1: 4, 2: 2, 3: 6, 4: 1, 5: 5, 6: 3, 7: 7, 8: 16, 9: 20, 10: 18, 11: 22, 12: 17, + 13: 21, 14: 19, 15: 23, 16: 8, 17: 12, 18: 10, 19: 14, 20: 9, 21: 13, 22: 11, + 23: 15, 24: 24, 25: 28, 26: 26, 27: 30, 28: 25, 29: 29, 30: 27, 31: 31, + None: None, + } + # fmt: on + for col in range(len(score_matrix[0])): + new_score_row = [] + new_trace_row = [] + for row in range(len(score_matrix)): + new_score_row.append(score_matrix[row][col]) + new_trace_row.append(reverse_trace[trace_matrix[row][col]]) + reverse_score_matrix.append(new_score_row) + reverse_trace_matrix.append(new_trace_row) + return reverse_score_matrix, reverse_trace_matrix + + +def _clean_alignments(alignments): + """Take a list of alignments and return a cleaned version (PRIVATE). + + Remove duplicates, make sure begin and end are set correctly, remove + empty alignments. + """ + unique_alignments = [] + for align in alignments: + if align not in unique_alignments: + unique_alignments.append(align) + i = 0 + while i < len(unique_alignments): + seqA, seqB, score, begin, end = unique_alignments[i] + # Make sure end is set reasonably. + if end is None: # global alignment + end = len(seqA) + elif end < 0: + end = end + len(seqA) + # If there's no alignment here, get rid of it. + if begin >= end: + del unique_alignments[i] + continue + unique_alignments[i] = Alignment(seqA, seqB, score, begin, end) + i += 1 + return unique_alignments + + +def _finish_backtrace(sequenceA, sequenceB, ali_seqA, ali_seqB, row, col, gap_char): + """Add remaining sequences and fill with gaps if necessary (PRIVATE).""" + if row: + ali_seqA += sequenceA[row - 1 :: -1] + if col: + ali_seqB += sequenceB[col - 1 :: -1] + if row > col: + ali_seqB += gap_char * (len(ali_seqA) - len(ali_seqB)) + elif col > row: + ali_seqA += gap_char * (len(ali_seqB) - len(ali_seqA)) + return ali_seqA, ali_seqB + + +def _find_gap_open( + sequenceA, + sequenceB, + ali_seqA, + ali_seqB, + end, + row, + col, + col_gap, + gap_char, + score_matrix, + trace_matrix, + in_process, + gap_fn, + target, + index, + direction, + best_score, + align_globally, +): + """Find the starting point(s) of the extended gap (PRIVATE).""" + dead_end = False + target_score = score_matrix[row][col] + for n in range(target): + if direction == "col": + col -= 1 + ali_seqA += gap_char + ali_seqB += sequenceB[col : col + 1] + else: + row -= 1 + ali_seqA += sequenceA[row : row + 1] + ali_seqB += gap_char + actual_score = score_matrix[row][col] + gap_fn(index, n + 1) + if not align_globally and score_matrix[row][col] == best_score: + # We have run through a 'zero-score' extension and discard it + dead_end = True + break + if rint(actual_score) == rint(target_score) and n > 0: + if not trace_matrix[row][col]: + break + else: + in_process.append( + ( + ali_seqA[:], + ali_seqB[:], + end, + row, + col, + col_gap, + trace_matrix[row][col], + ) + ) + if not trace_matrix[row][col]: + dead_end = True + return ali_seqA, ali_seqB, row, col, in_process, dead_end + + +_PRECISION = 1000 + + +def rint(x, precision=_PRECISION): + """Print number with declared precision.""" + return int(x * precision + 0.5) + + +class identity_match: + """Create a match function for use in an alignment. + + match and mismatch are the scores to give when two residues are equal + or unequal. By default, match is 1 and mismatch is 0. + """ + + def __init__(self, match=1, mismatch=0): + """Initialize the class.""" + self.match = match + self.mismatch = mismatch + + def __call__(self, charA, charB): + """Call a match function instance already created.""" + if charA == charB: + return self.match + return self.mismatch + + +class dictionary_match: + """Create a match function for use in an alignment. + + Attributes: + - score_dict - A dictionary where the keys are tuples (residue 1, + residue 2) and the values are the match scores between those residues. + - symmetric - A flag that indicates whether the scores are symmetric. + + """ + + def __init__(self, score_dict, symmetric=1): + """Initialize the class.""" + if isinstance(score_dict, substitution_matrices.Array): + score_dict = dict(score_dict) # Access to dict is much faster + self.score_dict = score_dict + self.symmetric = symmetric + + def __call__(self, charA, charB): + """Call a dictionary match instance already created.""" + if self.symmetric and (charA, charB) not in self.score_dict: + # If the score dictionary is symmetric, then look up the + # score both ways. + charB, charA = charA, charB + return self.score_dict[(charA, charB)] + + +class affine_penalty: + """Create a gap function for use in an alignment.""" + + def __init__(self, open, extend, penalize_extend_when_opening=0): + """Initialize the class.""" + if open > 0 or extend > 0: + raise ValueError("Gap penalties should be non-positive.") + if not penalize_extend_when_opening and (extend < open): + raise ValueError( + "Gap opening penalty should be higher than " + "gap extension penalty (or equal)" + ) + self.open, self.extend = open, extend + self.penalize_extend_when_opening = penalize_extend_when_opening + + def __call__(self, index, length): + """Call a gap function instance already created.""" + return calc_affine_penalty( + length, self.open, self.extend, self.penalize_extend_when_opening + ) + + +def calc_affine_penalty(length, open, extend, penalize_extend_when_opening): + """Calculate a penalty score for the gap function.""" + if length <= 0: + return 0.0 + penalty = open + extend * length + if not penalize_extend_when_opening: + penalty -= extend + return penalty + + +def print_matrix(matrix): + """Print out a matrix for debugging purposes.""" + # Transpose the matrix and get the length of the values in each column. + matrixT = [[] for x in range(len(matrix[0]))] + for i in range(len(matrix)): + for j in range(len(matrix[i])): + matrixT[j].append(len(str(matrix[i][j]))) + ndigits = [max(x) for x in matrixT] + for i in range(len(matrix)): + # Using string formatting trick to add leading spaces, + print( + " ".join("%*s " % (ndigits[j], matrix[i][j]) for j in range(len(matrix[i]))) + ) + + +def format_alignment(align1, align2, score, begin, end, full_sequences=False): + """Format the alignment prettily into a string. + + IMPORTANT: Gap symbol must be "-" (or ['-'] for lists)! + + Since Biopython 1.71 identical matches are shown with a pipe + character, mismatches as a dot, and gaps as a space. + + Prior releases just used the pipe character to indicate the + aligned region (matches, mismatches and gaps). + + Also, in local alignments, if the alignment does not include + the whole sequences, now only the aligned part is shown, + together with the start positions of the aligned subsequences. + The start positions are 1-based; so start position n is the + n-th base/amino acid in the *un-aligned* sequence. + + NOTE: This is different to the alignment's begin/end values, + which give the Python indices (0-based) of the bases/amino acids + in the *aligned* sequences. + + If you want to restore the 'historic' behaviour, that means + displaying the whole sequences (including the non-aligned parts), + use ``full_sequences=True``. In this case, the non-aligned leading + and trailing parts are also indicated by spaces in the match-line. + """ + align_begin = begin + align_end = end + start1 = start2 = "" + start_m = begin # Begin of match line (how many spaces to include) + # For local alignments: + if not full_sequences and (begin != 0 or end != len(align1)): + # Calculate the actual start positions in the un-aligned sequences + # This will only work if the gap symbol is '-' or ['-']! + start1 = str(len(align1[:begin]) - align1[:begin].count("-") + 1) + " " + start2 = str(len(align2[:begin]) - align2[:begin].count("-") + 1) + " " + start_m = max(len(start1), len(start2)) + elif full_sequences: + start_m = 0 + begin = 0 + end = len(align1) + + if isinstance(align1, list): + # List elements will be separated by spaces, since they can be + # of different lengths + align1 = [a + " " for a in align1] + align2 = [a + " " for a in align2] + + s1_line = ["{:>{width}}".format(start1, width=start_m)] # seq1 line + m_line = [" " * start_m] # match line + s2_line = ["{:>{width}}".format(start2, width=start_m)] # seq2 line + + for n, (a, b) in enumerate(zip(align1[begin:end], align2[begin:end])): + # Since list elements can be of different length, we center them, + # using the maximum length of the two compared elements as width + m_len = max(len(a), len(b)) + s1_line.append("{:^{width}}".format(a, width=m_len)) + s2_line.append("{:^{width}}".format(b, width=m_len)) + if full_sequences and (n < align_begin or n >= align_end): + m_line.append("{:^{width}}".format(" ", width=m_len)) # space + continue + if a == b: + m_line.append("{:^{width}}".format("|", width=m_len)) # match + elif a.strip() == "-" or b.strip() == "-": + m_line.append("{:^{width}}".format(" ", width=m_len)) # gap + else: + m_line.append("{:^{width}}".format(".", width=m_len)) # mismatch + + s2_line.append(f"\n Score={score:g}\n") + return "\n".join(["".join(s1_line), "".join(m_line), "".join(s2_line)]) + + +# Try and load C implementations of functions. If I can't, +# then throw a warning and use the pure Python implementations. +# The redefinition is deliberate, thus the no quality assurance +# flag for when using flake8. +# Before, we secure access to the pure Python functions (for testing purposes): + +_python_make_score_matrix_fast = _make_score_matrix_fast +_python_rint = rint + +try: + from .cpairwise2 import rint, _make_score_matrix_fast # noqa +except ImportError: + warnings.warn( + "Import of C module failed. Falling back to pure Python " + "implementation. This may be slooow...", + BiopythonWarning, + ) + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/._phen_micro.py b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/._phen_micro.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/._phen_micro.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/._pm_fitting.py b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/._pm_fitting.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/._pm_fitting.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c652f736c3c0ac3ddf25c304035a4eebb2308a3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/__init__.py @@ -0,0 +1,244 @@ +# Copyright 2014-2016 by Marco Galardini. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +r"""phenotype data input/output. + +Input +===== +The main function is Bio.phenotype.parse(...) which takes an input file, +and format string. This returns an iterator giving PlateRecord objects: + + >>> from Bio import phenotype + >>> for record in phenotype.parse("phenotype/Plates.csv", "pm-csv"): + ... print("%s %i" % (record.id, len(record))) + ... + PM01 96 + PM09 96 + +Note that the parse() function will invoke the relevant parser for the +format with its default settings. You may want more control, in which case +you need to create a format specific sequence iterator directly. + +Input - Single Records +====================== +If you expect your file to contain one-and-only-one record, then we provide +the following 'helper' function which will return a single PlateRecord, or +raise an exception if there are no records or more than one record: + + >>> from Bio import phenotype + >>> record = phenotype.read("phenotype/Plate.json", "pm-json") + >>> print("%s %i" % (record.id, len(record))) + PM01 96 + +This style is useful when you expect a single record only (and would +consider multiple records an error). For example, when dealing with PM +JSON files saved by the opm library. + +However, if you just want the first record from a file containing multiple +record, use the next() function on the iterator: + + >>> from Bio import phenotype + >>> record = next(phenotype.parse("phenotype/Plates.csv", "pm-csv")) + >>> print("%s %i" % (record.id, len(record))) + PM01 96 + +The above code will work as long as the file contains at least one record. +Note that if there is more than one record, the remaining records will be +silently ignored. + +Output +====== +Use the function Bio.phenotype.write(...), which takes a complete set of +PlateRecord objects (either as a list, or an iterator), an output file handle +(or in recent versions of Biopython an output filename as a string) and of +course the file format:: + + from Bio import phenotype + records = ... + phenotype.write(records, "example.json", "pm-json") + +Or, using a handle:: + + from Bio import phenotype + records = ... + with open("example.json", "w") as handle: + phenotype.write(records, handle, "pm-json") + +You are expected to call this function once (with all your records) and if +using a handle, make sure you close it to flush the data to the hard disk. + + +File Formats +============ +When specifying the file format, use lowercase strings. + + - pm-json - Phenotype Microarray plates in JSON format. + - pm-csv - Phenotype Microarray plates in CSV format, which is the + machine vendor format + +Note that while Bio.phenotype can read the above file formats, it can only +write in JSON format. +""" + +try: + # Both phen_micro.py and pm_fitting require NumPy, so require NumPy here + import numpy as np +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Please install NumPy if you want to use Bio.phenotype. " + "See http://www.numpy.org/" + ) from None + +from Bio.File import as_handle +from Bio.phenotype import phen_micro + +# Convention for format names is "mainname-format" in lower case. + +_FormatToIterator = { + "pm-csv": phen_micro.CsvIterator, + "pm-json": phen_micro.JsonIterator, +} + +_FormatToWriter = {"pm-json": phen_micro.JsonWriter} + + +def write(plates, handle, format): + """Write complete set of PlateRecords to a file. + + - plates - A list (or iterator) of PlateRecord objects. + - handle - File handle object to write to, or filename as string + (note older versions of Biopython only took a handle). + - format - lower case string describing the file format to write. + + You should close the handle after calling this function. + + Returns the number of records written (as an integer). + """ + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if format != format.lower(): + raise ValueError(f"Format string '{format}' should be lower case") + + if isinstance(plates, phen_micro.PlateRecord): + plates = [plates] + + with as_handle(handle, "w") as fp: + # Map the file format to a writer class + if format in _FormatToWriter: + writer_class = _FormatToWriter[format] + count = writer_class(plates).write(fp) + else: + raise ValueError(f"Unknown format '{format}'") + + if not isinstance(count, int): + raise TypeError( + "Internal error - the underlying %s " + "writer should have returned the record count, not %r" % (format, count) + ) + + return count + + +def parse(handle, format): + """Turn a phenotype file into an iterator returning PlateRecords. + + - handle - handle to the file, or the filename as a string + (note older versions of Biopython only took a handle). + - format - lower case string describing the file format. + + Typical usage, opening a file to read in, and looping over the record(s): + + >>> from Bio import phenotype + >>> filename = "phenotype/Plates.csv" + >>> for record in phenotype.parse(filename, "pm-csv"): + ... print("ID %s" % record.id) + ... print("Number of wells %i" % len(record)) + ... + ID PM01 + Number of wells 96 + ID PM09 + Number of wells 96 + + Use the Bio.phenotype.read(...) function when you expect a single record + only. + """ + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if format != format.lower(): + raise ValueError(f"Format string '{format}' should be lower case") + if format not in _FormatToIterator: + raise ValueError(f"Unknown format '{format}'") + + with as_handle(handle) as fp: + yield from _FormatToIterator[format](fp) + + +def read(handle, format): + """Turn a phenotype file into a single PlateRecord. + + - handle - handle to the file, or the filename as a string + (note older versions of Biopython only took a handle). + - format - string describing the file format. + + This function is for use parsing phenotype files containing + exactly one record. For example, reading a PM JSON file: + + >>> from Bio import phenotype + >>> record = phenotype.read("phenotype/Plate.json", "pm-json") + >>> print("ID %s" % record.id) + ID PM01 + >>> print("Number of wells %i" % len(record)) + Number of wells 96 + + If the handle contains no records, or more than one record, + an exception is raised. For example:: + + from Bio import phenotype + record = phenotype.read("plates.csv", "pm-csv") + Traceback (most recent call last): + ... + ValueError: More than one record found in handle + + If however you want the first record from a file containing + multiple records this function would raise an exception (as + shown in the example above). Instead use: + + >>> from Bio import phenotype + >>> record = next(phenotype.parse("phenotype/Plates.csv", "pm-csv")) + >>> print("First record's ID %s" % record.id) + First record's ID PM01 + + Use the Bio.phenotype.parse(handle, format) function if you want + to read multiple records from the handle. + """ + iterator = parse(handle, format) + try: + first = next(iterator) + except StopIteration: + first = None + if first is None: + raise ValueError("No records found in handle") + try: + second = next(iterator) + except StopIteration: + second = None + if second is not None: + raise ValueError("More than one record found in handle") + return first + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/phen_micro.py b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/phen_micro.py new file mode 100644 index 0000000000000000000000000000000000000000..7a01c76ecef2ab1fddb503442e7a718b16bf88a5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/phen_micro.py @@ -0,0 +1,1209 @@ +# Copyright 2014-2016 by Marco Galardini. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Classes to work with Phenotype Microarray data. + +More information on the single plates can be found here: http://www.biolog.com/ + +Classes: + - PlateRecord - Object that contain time course data on each well of the + plate, as well as metadata (if any). + - WellRecord - Object that contains the time course data of a single well + - JsonWriter - Writer of PlateRecord objects in JSON format. + +Functions: + - JsonIterator - Incremental PM JSON parser, this is an iterator that returns + PlateRecord objects. + - CsvIterator - Incremental PM CSV parser, this is an iterator that returns + PlateRecord objects. + - _toOPM - Used internally by JsonWriter, converts PlateRecord objects in + dictionaries ready to be serialized in JSON format. + +""" + +import csv +import json +import warnings + +import numpy as np + +from Bio import BiopythonParserWarning + +# Private csv headers - hardcoded because this are supposedly never changed +_datafile = "Data File" +_plate = "Plate Type" +_strainType = "Strain Type" +_sample = "Sample Number" +_strainName = "Strain Name" +_strainNumber = "Strain Number" +_other = "Other" +_hour = "Hour" +_file = "File" +_position = "Position" +_setupTime = "Setup Time" + +_platesPrefix = "PM" +_platesPrefixMammalian = "PM-M" +# + +# Json identifiers - hardcoded as they are set by the creators of opm +_csvData = "csv_data" +_measurements = "measurements" +# + + +class PlateRecord: + """PlateRecord object for storing Phenotype Microarray plates data. + + A PlateRecord stores all the wells of a particular phenotype + Microarray plate, along with metadata (if any). The single wells can be + accessed calling their id as an index or iterating on the PlateRecord: + + >>> from Bio import phenotype + >>> plate = phenotype.read("phenotype/Plate.json", "pm-json") + >>> well = plate['A05'] + >>> for well in plate: + ... print(well.id) + ... + A01 + ... + + The plate rows and columns can be queried with an indexing system similar + to NumPy and other matrices: + + >>> print(plate[1]) + Plate ID: PM01 + Well: 12 + Rows: 1 + Columns: 12 + PlateRecord('WellRecord['B01'], WellRecord['B02'], WellRecord['B03'], ..., WellRecord['B12']') + + >>> print(plate[:,1]) + Plate ID: PM01 + Well: 8 + Rows: 8 + Columns: 1 + PlateRecord('WellRecord['A02'], WellRecord['B02'], WellRecord['C02'], ..., WellRecord['H02']') + + Single WellRecord objects can be accessed using this indexing system: + + >>> print(plate[1,2]) + Plate ID: PM01 + Well ID: B03 + Time points: 384 + Minum signal 0.00 at time 11.00 + Maximum signal 76.25 at time 18.00 + WellRecord('(0.0, 11.0), (0.25, 11.0), (0.5, 11.0), (0.75, 11.0), (1.0, 11.0), ..., (95.75, 11.0)') + + The presence of a particular well can be inspected with the "in" keyword: + >>> 'A01' in plate + True + + All the wells belonging to a "row" (identified by the first character of + the well id) in the plate can be obtained: + + >>> for well in plate.get_row('H'): + ... print(well.id) + ... + H01 + H02 + H03 + ... + + All the wells belonging to a "column" (identified by the number of the well) + in the plate can be obtained: + + >>> for well in plate.get_column(12): + ... print(well.id) + ... + A12 + B12 + C12 + ... + + Two PlateRecord objects can be compared: if all their wells are equal the + two plates are considered equal: + + >>> plate2 = phenotype.read("phenotype/Plate.json", "pm-json") + >>> plate == plate2 + True + + Two PlateRecord object can be summed up or subtracted from each other: the + the signals of each well will be summed up or subtracted. The id of the + left operand will be kept: + + >>> plate3 = plate + plate2 + >>> print(plate3.id) + PM01 + + Many Phenotype Microarray plate have a "negative control" well, which can + be subtracted to all wells: + + >>> subplate = plate.subtract_control() + + """ + + def __init__(self, plateid, wells=None): + """Initialize the class.""" + self.id = plateid + + if wells is None: + wells = [] + + # Similar behaviour as GenBank + # Contains all the attributes + self.qualifiers = {} + + # Well_id --> WellRecord objects + self._wells = {} + try: + for w in wells: + self._is_well(w) + self[w.id] = w + except TypeError: + raise TypeError( + "You must provide an iterator-like object containing the single wells" + ) + + self._update() + + def _update(self): + """Update the rows and columns string identifiers (PRIVATE).""" + self._rows = sorted({x[0] for x in self._wells}) + self._columns = sorted({x[1:] for x in self._wells}) + + def _is_well(self, obj): + """Check if the given object is a WellRecord object (PRIVATE). + + Used both for the class constructor and the __setitem__ method + """ + # Value should be of WellRecord type + if not isinstance(obj, WellRecord): + raise ValueError( + f"A WellRecord type object is needed as value (got {type(obj)})" + ) + + def __getitem__(self, index): + """Access part of the plate. + + Depending on the indices, you can get a WellRecord object + (representing a single well of the plate), + or another plate + (representing some part or all of the original plate). + + plate[wid] gives a WellRecord (if wid is a WellRecord id) + plate[r,c] gives a WellRecord + plate[r] gives a row as a PlateRecord + plate[r,:] gives a row as a PlateRecord + plate[:,c] gives a column as a PlateRecord + + plate[:] and plate[:,:] give a copy of the plate + + Anything else gives a subset of the original plate, e.g. + plate[0:2] or plate[0:2,:] uses only row 0 and 1 + plate[:,1:3] uses only columns 1 and 2 + plate[0:2,1:3] uses only rows 0 & 1 and only cols 1 & 2 + + >>> from Bio import phenotype + >>> plate = phenotype.read("phenotype/Plate.json", "pm-json") + + You can access a well of the plate, using its id. + + >>> w = plate['A01'] + + You can access a row of the plate as a PlateRecord using an integer + index: + + >>> first_row = plate[0] + >>> print(first_row) + Plate ID: PM01 + Well: 12 + Rows: 1 + Columns: 12 + PlateRecord('WellRecord['A01'], WellRecord['A02'], WellRecord['A03'], ..., WellRecord['A12']') + >>> last_row = plate[-1] + >>> print(last_row) + Plate ID: PM01 + Well: 12 + Rows: 1 + Columns: 12 + PlateRecord('WellRecord['H01'], WellRecord['H02'], WellRecord['H03'], ..., WellRecord['H12']') + + You can also access use python's slice notation to sub-plates + containing only some of the plate rows: + + >>> sub_plate = plate[2:5] + >>> print(sub_plate) + Plate ID: PM01 + Well: 36 + Rows: 3 + Columns: 12 + PlateRecord('WellRecord['C01'], WellRecord['C02'], WellRecord['C03'], ..., WellRecord['E12']') + + This includes support for a step, i.e. plate[start:end:step], which + can be used to select every second row: + + >>> sub_plate = plate[::2] + + You can also use two indices to specify both rows and columns. + Using simple integers gives you the single wells. e.g. + + >>> w = plate[3, 4] + >>> print(w.id) + D05 + + To get a single column use this syntax: + + >>> sub_plate = plate[:, 4] + >>> print(sub_plate) + Plate ID: PM01 + Well: 8 + Rows: 8 + Columns: 1 + PlateRecord('WellRecord['A05'], WellRecord['B05'], WellRecord['C05'], ..., WellRecord['H05']') + + Or, to get part of a column, + + >>> sub_plate = plate[1:3, 4] + >>> print(sub_plate) + Plate ID: PM01 + Well: 2 + Rows: 2 + Columns: 1 + PlateRecord(WellRecord['B05'], WellRecord['C05']) + + However, in general you get a sub-plate, + + >>> print(plate[1:5, 3:6]) + Plate ID: PM01 + Well: 12 + Rows: 4 + Columns: 3 + PlateRecord('WellRecord['B04'], WellRecord['B05'], WellRecord['B06'], ..., WellRecord['E06']') + + This should all seem familiar to anyone who has used the NumPy + array or matrix objects. + """ + # Well identifier access + if isinstance(index, str): + try: + return self._wells[index] + except KeyError: + raise KeyError(f"Well {index} not found!") + + # Integer index + elif isinstance(index, int): + try: + row = self._rows[index] + except IndexError: + raise IndexError("Row %d not found!" % index) + return PlateRecord( + self.id, filter(lambda x: x.id.startswith(row), self._wells.values()) + ) + + # Slice + elif isinstance(index, slice): + rows = self._rows[index] + return PlateRecord( + self.id, filter(lambda x: x.id[0] in rows, self._wells.values()) + ) + + # Other access + elif len(index) != 2: + raise TypeError("Invalid index type.") + + row_index, col_index = index + if isinstance(row_index, int) and isinstance(col_index, int): + # Return a single WellRecord + try: + row = self._rows[row_index] + except IndexError: + raise IndexError("Row %d not found!" % row_index) + try: + col = self._columns[col_index] + except IndexError: + raise IndexError("Column %d not found!" % col_index) + + return self._wells[row + col] + + elif isinstance(row_index, int): + try: + row = self._rows[row_index] + except IndexError: + raise IndexError("Row %d not found!" % row_index) + cols = self._columns[col_index] + + return PlateRecord( + self.id, + filter( + lambda x: x.id.startswith(row) and x.id[1:] in cols, + self._wells.values(), + ), + ) + + elif isinstance(col_index, int): + try: + col = self._columns[col_index] + except IndexError: + raise IndexError("Columns %d not found!" % col_index) + rows = self._rows[row_index] + + return PlateRecord( + self.id, + filter( + lambda x: x.id.endswith(col) and x.id[0] in rows, + self._wells.values(), + ), + ) + + else: + rows = self._rows[row_index] + cols = self._columns[col_index] + + return PlateRecord( + self.id, + filter( + lambda x: x.id[0] in rows and x.id[1:] in cols, self._wells.values() + ), + ) + + def __setitem__(self, key, value): + if not isinstance(key, str): + raise ValueError("Well identifier should be string-like") + self._is_well(value) + # Provided key and well ID should be the same + if value.id != key: + raise ValueError( + "WellRecord ID and provided key are different (got '%s' and '%s')" + % (type(value.id), type(key)) + ) + self._wells[key] = value + + self._update() + + def __delitem__(self, key): + if not isinstance(key, str): + raise ValueError("Well identifier should be string-like") + del self._wells[key] + + self._update() + + def __iter__(self): + for well in sorted(self._wells): + yield self._wells[well] + + def __contains__(self, wellid): + if wellid in self._wells: + return True + return False + + def __len__(self): + """Return the number of wells in this plate.""" + return len(self._wells) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self._wells == other._wells + else: + return False + + def __add__(self, plate): + """Add another PlateRecord object. + + The wells in both plates must be the same + + A new PlateRecord object is returned, having the same id as the + left operand. + """ + if not isinstance(plate, PlateRecord): + raise TypeError("Expecting a PlateRecord object") + + if {x.id for x in self} != {x.id for x in plate}: + raise ValueError("The two plates have different wells") + + wells = [] + + for w in self: + wells.append(w + plate[w.id]) + + newp = PlateRecord(self.id, wells=wells) + + return newp + + def __sub__(self, plate): + """Subtract another PlateRecord object. + + The wells in both plates must be the same + + A new PlateRecord object is returned, having the same id as the + left operand. + """ + if not isinstance(plate, PlateRecord): + raise TypeError("Expecting a PlateRecord object") + + if {x.id for x in self} != {x.id for x in plate}: + raise ValueError("The two plates have different wells") + + wells = [] + + for w in self: + wells.append(w - plate[w.id]) + + newp = PlateRecord(self.id, wells=wells) + + return newp + + def get_row(self, row): + """Get all the wells of a given row. + + A row is identified with a letter (e.g. 'A') + """ + # Key is casted to str implicitly + try: + row = str(row) + except Exception: + # Is it even possible to get an exception here? + raise ValueError("Row identifier should be string-like") + if len(row) > 1: + raise ValueError("Row identifier must be of maximum one letter") + + for w in sorted(filter(lambda x: x.startswith(row), self._wells)): + yield self._wells[w] + + def get_column(self, column): + """Get all the wells of a given column. + + A column is identified with a number (e.g. '6') + """ + # Column is casted to int implicitly + try: + column = int(column) + except Exception: + raise ValueError("Column identifier should be a number") + + # A 96-well plate has well numbers in two digits + for w in sorted(filter(lambda x: x.endswith("%02d" % column), self._wells)): + yield self._wells[w] + + def subtract_control(self, control="A01", wells=None): + """Subtract a 'control' well from the other plates wells. + + By default the control is subtracted to all wells, unless + a list of well ID is provided + + The control well should belong to the plate + A new PlateRecord object is returned + """ + if control not in self: + raise ValueError("Control well not present in plate") + wcontrol = self[control] + + if wells is None: + wells = self._wells.keys() + + missing = {w for w in wells if w not in self} + if missing: + raise ValueError("Some wells to be subtracted are not present") + + nwells = [] + + for w in self: + if w.id in wells: + nwells.append(w - wcontrol) + else: + nwells.append(w) + + newp = PlateRecord(self.id, wells=nwells) + + return newp + + def __repr__(self): + """Return a (truncated) representation of the plate for debugging.""" + if len(self._wells) > 4: + # Show the last well and the first three + return "%s('%s, ..., %s')" % ( + self.__class__.__name__, + ", ".join( + [ + "%s['%s']" % (self[x].__class__.__name__, self[x].id) + for x in sorted(self._wells.keys())[:3] + ] + ), + "%s['%s']" + % ( + self[sorted(self._wells.keys())[-1]].__class__.__name__, + self[sorted(self._wells.keys())[-1]].id, + ), + ) + else: + return "%s(%s)" % ( + self.__class__.__name__, + ", ".join( + [ + "%s['%s']" % (self[x].__class__.__name__, self[x].id) + for x in sorted(self._wells.keys()) + ] + ), + ) + + def __str__(self): + """Return a human readable summary of the record (string). + + The python built in function str works by calling the object's __str__ + method. e.g. + + >>> from Bio import phenotype + >>> record = next(phenotype.parse("phenotype/Plates.csv", "pm-csv")) + >>> print(record) + Plate ID: PM01 + Well: 96 + Rows: 8 + Columns: 12 + PlateRecord('WellRecord['A01'], WellRecord['A02'], WellRecord['A03'], ..., WellRecord['H12']') + + Note that long well lists are shown truncated. + """ + lines = [] + if self.id: + lines.append(f"Plate ID: {self.id}") + lines.append("Well: %i" % len(self)) + # Here we assume that all well ID start with a char + lines.append("Rows: %d" % len({x.id[0] for x in self})) + # Here we assume that well number is a two-digit number + lines.append("Columns: %d" % len({x.id[1:3] for x in self})) + lines.append(repr(self)) + return "\n".join(lines) + + +class WellRecord: + """WellRecord stores all time course signals of a phenotype Microarray well. + + The single time points and signals can be accessed iterating on the + WellRecord or using lists indexes or slices: + + >>> from Bio import phenotype + >>> plate = phenotype.read("phenotype/Plate.json", "pm-json") + >>> well = plate['A05'] + >>> for time, signal in well: + ... print("Time: %f, Signal: %f" % (time, signal)) # doctest:+ELLIPSIS + ... + Time: 0.000000, Signal: 14.000000 + Time: 0.250000, Signal: 13.000000 + Time: 0.500000, Signal: 15.000000 + Time: 0.750000, Signal: 15.000000 + ... + >>> well[1] + 16.0 + >>> well[1:5] + [16.0, 20.0, 18.0, 15.0] + >>> well[1:5:0.5] + [16.0, 19.0, 20.0, 18.0, 18.0, 18.0, 15.0, 18.0] + + If a time point was not present in the input file but it's between the + minimum and maximum time point, the interpolated signal is returned, + otherwise a nan value: + + >>> well[1.3] + 19.0 + >>> well[1250] + nan + + Two WellRecord objects can be compared: if their input time/signal pairs + are exactly the same, the two records are considered equal: + + >>> well2 = plate['H12'] + >>> well == well2 + False + + Two WellRecord objects can be summed up or subtracted from each other: a new + WellRecord object is returned, having the left operand id. + + >>> well1 = plate['A05'] + >>> well2 = well + well1 + >>> print(well2.id) + A05 + + If SciPy is installed, a sigmoid function can be fitted to the PM curve, + in order to extract some parameters; three sigmoid functions are available: + * gompertz + * logistic + * richards + The functions are described in Zwietering et al., 1990 (PMID: 16348228) + + For example:: + + well.fit() + print(well.slope, well.model) + (61.853516785566917, 'logistic') + + If not sigmoid function is specified, the first one that is successfully + fitted is used. The user can also specify a specific function. + + To specify gompertz:: + + well.fit('gompertz') + print(well.slope, well.model) + (127.94630059171354, 'gompertz') + + If no function can be fitted, the parameters are left as None, except for + the max, min, average_height and area. + """ + + def __init__(self, wellid, plate=None, signals=None): + """Initialize the class.""" + if plate is None: + self.plate = PlateRecord(None) + else: + self.plate = plate + + self.id = wellid + + # Curve parameters (to be calculated with the "fit" function) + # Parameters that don't need scipy + self.max = None + self.min = None + self.average_height = None + + # Parameters that need scipy + self.area = None + self.plateau = None + self.slope = None + self.lag = None + self.v = None + self.y0 = None + self.model = None + + # Original signals (private) + if signals is None: + self._signals = {} + else: + self._signals = signals + + def _interpolate(self, time): + """Linear interpolation of the signals at certain time points (PRIVATE).""" + times = sorted(self._signals.keys()) + + return np.interp( + time, times, [self._signals[x] for x in times], left=np.nan, right=np.nan + ) + + def __setitem__(self, time, signal): + """Assign a signal at a certain time point.""" + try: + time = float(time) + except ValueError: + raise ValueError("Time point should be a number") + try: + signal = float(signal) + except ValueError: + raise ValueError("Signal should be a number") + + self._signals[time] = signal + + def __getitem__(self, time): + """Return a subset of signals or a single signal.""" + if isinstance(time, slice): + # Fix the missing values in the slice + if time.start is None: + start = 0 + else: + start = time.start + + if time.stop is None: + stop = max(self.get_times()) + else: + stop = time.stop + + time = np.arange(start, stop, time.step) + return [float(value) for value in self._interpolate(time)] + + elif isinstance(time, (float, int)): + return float(self._interpolate(time)) + + raise ValueError("Invalid index") + + def __iter__(self): + for time in sorted(self._signals.keys()): + yield time, self._signals[time] + + def __eq__(self, other): + if isinstance(other, self.__class__): + if list(self._signals.keys()) != list(other._signals.keys()): + return False + # Account for the presence of NaNs + for k in self._signals: + if np.isnan(self[k]) and np.isnan(other[k]): + continue + elif self[k] != other[k]: + return False + return True + else: + return False + + def __add__(self, well): + """Add another WellRecord object. + + A new WellRecord object is returned, having the same id as the + left operand + """ + if not isinstance(well, WellRecord): + raise TypeError("Expecting a WellRecord object") + + signals = {} + + times = set(self._signals.keys()).union(set(well._signals.keys())) + for t in sorted(times): + signals[t] = self[t] + well[t] + + neww = WellRecord(self.id, signals=signals) + + return neww + + def __sub__(self, well): + """Subtract another WellRecord object. + + A new WellRecord object is returned, having the same id as the + left operand + """ + if not isinstance(well, WellRecord): + raise TypeError("Expecting a WellRecord object") + + signals = {} + + times = set(self._signals.keys()).union(set(well._signals.keys())) + for t in sorted(times): + signals[t] = self[t] - well[t] + + neww = WellRecord(self.id, signals=signals) + + return neww + + def __len__(self): + """Return the number of time points sampled.""" + return len(self._signals) + + def __repr__(self): + """Return a (truncated) representation of the signals for debugging.""" + if len(self) > 7: + # Shows the last time point and the first five + return "%s('%s, ..., %s')" % ( + self.__class__.__name__, + ", ".join([str(x) for x in self.get_raw()[:5]]), + str(self.get_raw()[-1]), + ) + else: + return "%s(%s)" % ( + self.__class__.__name__, + ", ".join([str(x) for x in self.get_raw()]), + ) + + def __str__(self): + """Return a human readable summary of the record (string). + + The python built-in function str works by calling the object's __str__ + method. e.g. + + >>> from Bio import phenotype + >>> plate = phenotype.read("phenotype/Plate.json", "pm-json") + >>> record = plate['A05'] + >>> print(record) + Plate ID: PM01 + Well ID: A05 + Time points: 384 + Minum signal 0.25 at time 13.00 + Maximum signal 19.50 at time 23.00 + WellRecord('(0.0, 14.0), (0.25, 13.0), (0.5, 15.0), (0.75, 15.0), (1.0, 16.0), ..., (95.75, 16.0)') + + Note that long time spans are shown truncated. + """ + lines = [] + if self.plate and self.plate.id: + lines.append(f"Plate ID: {self.plate.id}") + if self.id: + lines.append(f"Well ID: {self.id}") + lines.append("Time points: %i" % len(self)) + lines.append("Minum signal %.2f at time %.2f" % min(self, key=lambda x: x[1])) + lines.append("Maximum signal %.2f at time %.2f" % max(self, key=lambda x: x[1])) + lines.append(repr(self)) + return "\n".join(lines) + + def get_raw(self): + """Get a list of time/signal pairs.""" + return [(t, self._signals[t]) for t in sorted(self._signals.keys())] + + def get_times(self): + """Get a list of the recorded time points.""" + return sorted(self._signals.keys()) + + def get_signals(self): + """Get a list of the recorded signals (ordered by collection time).""" + return [self._signals[t] for t in sorted(self._signals.keys())] + + def fit(self, function=("gompertz", "logistic", "richards")): + """Fit a sigmoid function to this well and extract curve parameters. + + If function is None or an empty tuple/list, then no fitting is done. + Only the object's ``.min``, ``.max`` and ``.average_height`` are + calculated. + + By default the following fitting functions will be used in order: + - gompertz + - logistic + - richards + + The first function that is successfully fitted to the signals will + be used to extract the curve parameters and update ``.area`` and + ``.model``. If no function can be fitted an exception is raised. + + The function argument should be a tuple or list of any of these three + function names as strings. + + There is no return value. + """ + avail_func = ("gompertz", "logistic", "richards") + + # Parameters not dependent on curve fitting + self.max = max(self, key=lambda x: x[1])[1] + self.min = min(self, key=lambda x: x[1])[1] + + self.average_height = np.array(self.get_signals()).mean() + + if not function: + self.area = None + self.model = None + return + for sigmoid_func in function: + if sigmoid_func not in avail_func: + raise ValueError(f"Fitting function {sigmoid_func!r} not supported") + + # Parameters that depend on scipy curve_fit + from .pm_fitting import fit + from .pm_fitting import get_area + from .pm_fitting import gompertz + from .pm_fitting import logistic + from .pm_fitting import richards + + function_map = { + "logistic": logistic, + "gompertz": gompertz, + "richards": richards, + } + + self.area = get_area(self.get_signals(), self.get_times()) + + self.model = None + for sigmoid_func in function: + func = function_map[sigmoid_func] + try: + (self.plateau, self.slope, self.lag, self.v, self.y0), pcov = fit( + func, self.get_times(), self.get_signals() + ) + + self.model = sigmoid_func + return + except RuntimeError: + continue + raise RuntimeError("Could not fit any sigmoid function") + + +def JsonIterator(handle): + """Iterate over PM json records as PlateRecord objects. + + Arguments: + - handle - input file + + """ + try: + data = json.load(handle) + except ValueError: + raise ValueError("Could not parse JSON file") + + # We can have one single plate or several + # we need to discriminate + if hasattr(data, "keys"): + data = [data] + + for pobj in data: + try: + plateID = pobj[_csvData][_plate] + except TypeError: + raise TypeError("Malformed JSON input") + except KeyError: + raise KeyError("Could not retrieve plate id") + + # Parse also non-standard plate IDs + if not plateID.startswith(_platesPrefix) and not plateID.startswith( + _platesPrefixMammalian + ): + warnings.warn( + f"Non-standard plate ID found ({plateID})", BiopythonParserWarning + ) + else: + # Simplify the plates IDs, removing letters, as opm does + if plateID.startswith(_platesPrefixMammalian): + pID = plateID[len(_platesPrefixMammalian) :] + else: + pID = plateID[len(_platesPrefix) :] + while len(pID) > 0: + try: + int(pID) + break + except ValueError: + pID = pID[:-1] + + # No luck + if len(pID) == 0: + warnings.warn( + f"Non-standard plate ID found ({plateID})", BiopythonParserWarning + ) + elif int(pID) < 0: + warnings.warn( + f"Non-standard plate ID found ({plateID}), using {_platesPrefix}{abs(int(pID))}" + ) + plateID = _platesPrefix + str(abs(int(pID))) + else: + if plateID.startswith(_platesPrefixMammalian): + plateID = _platesPrefixMammalian + "%02d" % int(pID) + else: + plateID = _platesPrefix + "%02d" % int(pID) + + try: + times = pobj[_measurements][_hour] + except KeyError: + raise KeyError("Could not retrieve the time points") + + plate = PlateRecord(plateID) + + for k in pobj[_measurements]: + # Skip the time points + if k == _hour: + continue + + plate[k] = WellRecord( + k, + plate=plate, + signals={ + times[i]: pobj[_measurements][k][i] for i in range(len(times)) + }, + ) + + # Remove the measurements and assign the other qualifiers + del pobj["measurements"] + plate.qualifiers = pobj + + yield plate + + +def CsvIterator(handle): + """Iterate over PM csv records as PlateRecord objects. + + Arguments: + - handle - input file + + """ + plate = None + data = False + qualifiers = {} + idx = {} + wells = {} + + tblreader = csv.reader(handle, delimiter=",", quotechar='"') + for line in tblreader: + if len(line) < 2: + continue + + elif _datafile in line[0].strip(): + # Do we have a previous plate? + if plate is not None: + qualifiers[_csvData][_datafile] = line[1].strip() + plate = PlateRecord(plate.id) + for k, v in wells.items(): + plate[k] = WellRecord(k, plate, v) + plate.qualifiers = qualifiers + yield plate + plate = PlateRecord(None) + data = False + qualifiers[_csvData] = {} + idx = {} + wells = {} + + elif _plate in line[0].strip(): + plateID = line[1].strip() + + qualifiers[_csvData][_plate] = plateID + + # Parse also non-standard plate IDs + if not plateID.startswith(_platesPrefix) and not plateID.startswith( + _platesPrefixMammalian + ): + warnings.warn( + f"Non-standard plate ID found ({plateID})", BiopythonParserWarning + ) + else: + # Simplify the plates IDs, removing letters, as opm does + if plateID.startswith(_platesPrefixMammalian): + pID = plateID[len(_platesPrefixMammalian) :] + else: + pID = plateID[len(_platesPrefix) :] + while len(pID) > 0: + try: + int(pID) + break + except ValueError: + pID = pID[:-1] + + # No luck + if len(pID) == 0: + warnings.warn( + f"Non-standard plate ID found ({plateID})", + BiopythonParserWarning, + ) + elif int(pID) < 0: + warnings.warn( + f"Non-standard plate ID found ({plateID}), using {_platesPrefix}{abs(int(pID))}" + ) + plateID = _platesPrefix + str(abs(int(pID))) + else: + if plateID.startswith(_platesPrefixMammalian): + plateID = _platesPrefixMammalian + "%02d" % int(pID) + else: + plateID = _platesPrefix + "%02d" % int(pID) + + plate.id = plateID + + elif _strainType in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_strainType] = line[1].strip() + + elif _sample in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_sample] = line[1].strip() + + elif _strainNumber in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_strainNumber] = line[1].strip() + + elif _strainName in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_strainName] = line[1].strip() + + elif _other in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_other] = line[1].strip() + + elif _file in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_file] = line[1].strip() + + elif _position in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_position] = line[1].strip() + + elif _setupTime in line[0].strip(): + if plate is None: + continue + qualifiers[_csvData][_setupTime] = line[1].strip() + + elif _hour in line[0].strip(): + if plate is None: + continue + data = True + for i in range(1, len(line)): + x = line[i] + if x == "": + continue + wells[x.strip()] = {} + idx[i] = x.strip() + + elif data: + if plate is None: + continue + + # Workaround for bad-formatted files + try: + float(line[0]) + except ValueError: + continue + + time = float(line[0]) + + for i in range(1, len(line)): + x = line[i] + + try: + signal = float(x) + except ValueError: + continue + + well = idx[i] + wells[well][time] = signal + + if plate is not None and plate.id is not None: + plate = PlateRecord(plate.id) + for k, v in wells.items(): + plate[k] = WellRecord(k, plate, v) + plate.qualifiers = qualifiers + yield plate + + +def _toOPM(plate): + """Transform a PlateRecord object into a dictionary (PRIVATE).""" + d = dict(plate.qualifiers.items()) + + d[_csvData] = {} + d[_csvData][_plate] = plate.id + d[_measurements] = {} + d[_measurements][_hour] = [] + times = set() + for wid, w in plate._wells.items(): + d[_measurements][wid] = [] + for hour in w._signals: + times.add(hour) + + for hour in sorted(times): + d[_measurements][_hour].append(hour) + for wid, w in plate._wells.items(): + if hour in w._signals: + d[_measurements][wid].append(w[hour]) + # This shouldn't happen + else: + d[_measurements][wid].append(float("nan")) + + return d + + +class JsonWriter: + """Class to write PM Json format files.""" + + def __init__(self, plates): + """Initialize the class.""" + self.plates = plates + + def write(self, handle): + """Write this instance's plates to a file handle.""" + out = [] + for plate in self.plates: + try: + out.append(_toOPM(plate)) + except ValueError: + raise ValueError("Could not export plate(s) in JSON format") + + handle.write(json.dumps(out) + "\n") + + return len(out) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/pm_fitting.py b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/pm_fitting.py new file mode 100644 index 0000000000000000000000000000000000000000..1d3a1f6b5b1861db1328cbaee859d1050c42fa26 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/phenotype/pm_fitting.py @@ -0,0 +1,151 @@ +# Copyright 2014-2016 by Marco Galardini. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Growth curves fitting and parameters extraction for phenotype data. + +This module provides functions to perform sigmoid functions fitting to +Phenotype Microarray data. This module depends on scipy curve_fit function. +If not available, a warning is raised. + +Functions: +logistic Logistic growth model. +gompertz Gompertz growth model. +richards Richards growth model. +guess_plateau Guess the plateau point to improve sigmoid fitting. +guess_lag Guess the lag point to improve sigmoid fitting. +fit Sigmoid functions fit. +get_area Calculate the area under the PM curve. +""" + +import numpy as np + +try: + from scipy.optimize.minpack import curve_fit +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError("Install scipy to extract curve parameters.") + +try: + from scipy.integrate import trapezoid +except ImportError: + # Assume this is prior to scipy 1.12.0 and try old name: + from scipy.integrate import trapz as trapezoid + + +def logistic(x, A, u, d, v, y0): + """Logistic growth model. + + Proposed in Zwietering et al., 1990 (PMID: 16348228) + """ + y = (A / (1 + np.exp((((4 * u) / A) * (d - x)) + 2))) + y0 + return y + + +def gompertz(x, A, u, d, v, y0): + """Gompertz growth model. + + Proposed in Zwietering et al., 1990 (PMID: 16348228) + """ + y = (A * np.exp(-np.exp((((u * np.e) / A) * (d - x)) + 1))) + y0 + return y + + +def richards(x, A, u, d, v, y0): + """Richards growth model (equivalent to Stannard). + + Proposed in Zwietering et al., 1990 (PMID: 16348228) + """ + y = ( + A + * pow( + 1 + + ( + v + + (np.exp(1 + v) * np.exp((u / A) * (1 + v) * (1 + (1 / v)) * (d - x))) + ), + -(1 / v), + ) + ) + y0 + return y + + +def guess_lag(x, y): + """Given two axes returns a guess of the lag point. + + The lag point is defined as the x point where the difference in y + with the next point is higher then the mean differences between + the points plus one standard deviation. If such point is not found + or x and y have different lengths the function returns zero. + """ + if len(x) != len(y): + return 0 + + diffs = [] + indexes = range(len(x)) + + for i in indexes: + if i + 1 not in indexes: + continue + diffs.append(y[i + 1] - y[i]) + diffs = np.array(diffs) + + flex = x[-1] + for i in indexes: + if i + 1 not in indexes: + continue + if (y[i + 1] - y[i]) > (diffs.mean() + (diffs.std())): + flex = x[i] + break + + return flex + + +def guess_plateau(x, y): + """Given two axes returns a guess of the plateau point. + + The plateau point is defined as the x point where the y point + is near one standard deviation of the differences between the y points to + the maximum y value. If such point is not found or x and y have + different lengths the function returns zero. + """ + if len(x) != len(y): + return 0 + + diffs = [] + indexes = range(len(y)) + + for i in indexes: + if i + 1 not in indexes: + continue + diffs.append(y[i + 1] - y[i]) + diffs = np.array(diffs) + + ymax = y[-1] + for i in indexes: + if y[i] > (ymax - diffs.std()) and y[i] < (ymax + diffs.std()): + ymax = y[i] + break + + return ymax + + +def fit(function, x, y): + """Fit the provided function to the x and y values. + + The function parameters and the parameters covariance. + """ + # Compute guesses for the parameters + # This is necessary to get significant fits + p0 = [guess_plateau(x, y), 4.0, guess_lag(x, y), 0.1, min(y)] + + params, pcov = curve_fit(function, x, y, p0=p0) + return params, pcov + + +def get_area(y, x): + """Get the area under the curve.""" + return trapezoid(y=y, x=x) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/py.typed b/.venv_haddock/lib/python3.12/site-packages/Bio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/._BioSeq.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._BioSeq.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._BioSeq.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/._BioSeqDatabase.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._BioSeqDatabase.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._BioSeqDatabase.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/._DBUtils.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._DBUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._DBUtils.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/._Loader.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._Loader.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._Loader.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/._py.typed b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._py.typed new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/BioSQL/._py.typed differ diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeq.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeq.py new file mode 100644 index 0000000000000000000000000000000000000000..23319e2c388cc460b93addacd024fbbc7dac20e1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeq.py @@ -0,0 +1,592 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2016 copyright by Peter Cock. All rights reserved. +# Revisions 2008-2009 copyright by Cymon J. Cox. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Implementations of Biopython-like Seq objects on top of BioSQL. + +This allows retrieval of items stored in a BioSQL database using +a biopython-like SeqRecord and Seq interface. + +Note: Currently we do not support recording per-letter-annotations +(like quality scores) in BioSQL. +""" + +from Bio import SeqFeature +from Bio.Seq import Seq +from Bio.Seq import SequenceDataAbstractBaseClass +from Bio.SeqRecord import _RestrictedDict +from Bio.SeqRecord import SeqRecord + + +class _BioSQLSequenceData(SequenceDataAbstractBaseClass): + """Retrieves sequence data from a BioSQL database (PRIVATE).""" + + __slots__ = ("primary_id", "adaptor", "_length", "start") + + def __init__(self, primary_id, adaptor, start=0, length=0): + """Create a new _BioSQLSequenceData object referring to a BioSQL entry. + + You wouldn't normally create a _BioSQLSequenceData object yourself, + this is done for you when retrieving a DBSeqRecord object from the + database, which creates a Seq object using a _BioSQLSequenceData + instance as the data provider. + """ + self.primary_id = primary_id + self.adaptor = adaptor + self._length = length + self.start = start + super().__init__() + + def __len__(self): + """Return the length of the sequence.""" + return self._length + + def __getitem__(self, key): + """Return a subsequence as a bytes or a _BioSQLSequenceData object.""" + if isinstance(key, slice): + start, end, step = key.indices(self._length) + size = len(range(start, end, step)) + if size == 0: + return b"" + else: + # Return a single letter as an integer (consistent with bytes) + i = key + if i < 0: + i += self._length + if i < 0: + raise IndexError(key) + elif i >= self._length: + raise IndexError(key) + c = self.adaptor.get_subseq_as_string( + self.primary_id, self.start + i, self.start + i + 1 + ) + return ord(c) + + if step == 1: + if start == 0 and size == self._length: + # Return the full sequence as bytes + sequence = self.adaptor.get_subseq_as_string( + self.primary_id, self.start, self.start + self._length + ) + return sequence.encode("ASCII") + else: + # Return a _BioSQLSequenceData with the start and end adjusted + return _BioSQLSequenceData( + self.primary_id, self.adaptor, self.start + start, size + ) + else: + # Will have to extract the sequence because of the stride + full = self.adaptor.get_subseq_as_string( + self.primary_id, self.start + start, self.start + end + ) + return full[::step].encode("ASCII") + + +def _retrieve_seq_len(adaptor, primary_id): + # The database schema ensures there will be only one matching row + seqs = adaptor.execute_and_fetchall( + "SELECT length FROM biosequence WHERE bioentry_id = %s", (primary_id,) + ) + if not seqs: + return None + if len(seqs) != 1: + raise ValueError(f"Expected 1 response, got {len(seqs)}.") + (given_length,) = seqs[0] + return int(given_length) + + +def _retrieve_seq(adaptor, primary_id): + # The database schema ensures there will be only one matching + # row in the table. + + # If an undefined sequence was recorded, seq will be NULL, + # but length will be populated. This means length(seq) + # will return None. + seqs = adaptor.execute_and_fetchall( + "SELECT alphabet, length, length(seq) FROM biosequence WHERE bioentry_id = %s", + (primary_id,), + ) + if not seqs: + return + if len(seqs) != 1: + raise ValueError(f"Expected 1 response, got {len(seqs)}.") + moltype, given_length, length = seqs[0] + + try: + length = int(length) + given_length = int(given_length) + if length != given_length: + raise ValueError( + f"'length' differs from sequence length, {given_length}, {length}" + ) + have_seq = True + except TypeError: + if length is not None: + raise ValueError(f"Expected 'length' to be 'None', got {length}.") + seqs = adaptor.execute_and_fetchall( + "SELECT alphabet, length, seq FROM biosequence WHERE bioentry_id = %s", + (primary_id,), + ) + if len(seqs) != 1: + raise ValueError(f"Expected 1 response, got {len(seqs)}.") + moltype, given_length, seq = seqs[0] + if seq: + raise ValueError(f"Expected 'seq' to have a falsy value, got {seq}.") + length = int(given_length) + have_seq = False + del seq + del given_length + + if have_seq: + data = _BioSQLSequenceData(primary_id, adaptor, start=0, length=length) + return Seq(data) + else: + return Seq(None, length=length) + + +def _retrieve_dbxrefs(adaptor, primary_id): + """Retrieve the database cross references for the sequence (PRIVATE).""" + _dbxrefs = [] + dbxrefs = adaptor.execute_and_fetchall( + "SELECT dbname, accession, version" + " FROM bioentry_dbxref join dbxref using (dbxref_id)" + " WHERE bioentry_id = %s" + ' ORDER BY "rank"', + (primary_id,), + ) + for dbname, accession, version in dbxrefs: + if version and version != "0": + v = f"{accession}.{version}" + else: + v = accession + _dbxrefs.append(f"{dbname}:{v}") + return _dbxrefs + + +def _retrieve_features(adaptor, primary_id): + sql = ( + 'SELECT seqfeature_id, type.name, "rank"' + " FROM seqfeature join term type on (type_term_id = type.term_id)" + " WHERE bioentry_id = %s" + ' ORDER BY "rank"' + ) + results = adaptor.execute_and_fetchall(sql, (primary_id,)) + seq_feature_list = [] + for seqfeature_id, seqfeature_type, seqfeature_rank in results: + # Get qualifiers [except for db_xref which is stored separately] + qvs = adaptor.execute_and_fetchall( + "SELECT name, value" + " FROM seqfeature_qualifier_value join term using (term_id)" + " WHERE seqfeature_id = %s" + ' ORDER BY "rank"', + (seqfeature_id,), + ) + qualifiers = {} + for qv_name, qv_value in qvs: + qualifiers.setdefault(qv_name, []).append(qv_value) + # Get db_xrefs [special case of qualifiers] + qvs = adaptor.execute_and_fetchall( + "SELECT dbxref.dbname, dbxref.accession" + " FROM dbxref join seqfeature_dbxref using (dbxref_id)" + " WHERE seqfeature_dbxref.seqfeature_id = %s" + ' ORDER BY "rank"', + (seqfeature_id,), + ) + for qv_name, qv_value in qvs: + value = f"{qv_name}:{qv_value}" + qualifiers.setdefault("db_xref", []).append(value) + # Get locations + results = adaptor.execute_and_fetchall( + "SELECT location_id, start_pos, end_pos, strand" + " FROM location" + " WHERE seqfeature_id = %s" + ' ORDER BY "rank"', + (seqfeature_id,), + ) + locations = [] + # convert to Python standard form + # Convert strand = 0 to strand = None + # re: comment in Loader.py: + # Biopython uses None when we don't know strand information but + # BioSQL requires something (non null) and sets this as zero + # So we'll use the strand or 0 if Biopython spits out None + for location_id, start, end, strand in results: + if start: + start -= 1 + if strand == 0: + strand = None + if strand not in (+1, -1, None): + raise ValueError( + "Invalid strand %s found in database for " + "seqfeature_id %s" % (strand, seqfeature_id) + ) + if start is not None and end is not None and end < start: + import warnings + + from Bio import BiopythonWarning + + warnings.warn( + "Inverted location start/end (%i and %i) for " + "seqfeature_id %s" % (start, end, seqfeature_id), + BiopythonWarning, + ) + + # For SwissProt unknown positions (?) + if start is None: + start = SeqFeature.UnknownPosition() + if end is None: + end = SeqFeature.UnknownPosition() + + locations.append((location_id, start, end, strand)) + # Get possible remote reference information + remote_results = adaptor.execute_and_fetchall( + "SELECT location_id, dbname, accession, version" + " FROM location join dbxref using (dbxref_id)" + " WHERE seqfeature_id = %s", + (seqfeature_id,), + ) + lookup = {} + for location_id, dbname, accession, version in remote_results: + if version and version != "0": + v = f"{accession}.{version}" + else: + v = accession + # subfeature remote location db_ref are stored as a empty string + # when not present + if dbname == "": + dbname = None + lookup[location_id] = (dbname, v) + + feature = SeqFeature.SeqFeature(type=seqfeature_type) + # Store the key as a private property + feature._seqfeature_id = seqfeature_id + feature.qualifiers = qualifiers + if len(locations) == 0: + pass + elif len(locations) == 1: + location_id, start, end, strand = locations[0] + # See Bug 2677, we currently don't record the location_operator + # For consistency with older versions Biopython, default to "". + feature.location_operator = _retrieve_location_qualifier_value( + adaptor, location_id + ) + dbname, version = lookup.get(location_id, (None, None)) + feature.location = SeqFeature.SimpleLocation(start, end) + feature.location.strand = strand + feature.location.ref_db = dbname + feature.location.ref = version + else: + locs = [] + for location in locations: + location_id, start, end, strand = location + dbname, version = lookup.get(location_id, (None, None)) + locs.append( + SeqFeature.SimpleLocation( + start, end, strand=strand, ref=version, ref_db=dbname + ) + ) + # Locations are typically in biological in order (see negative + # strands below), but because of remote locations for + # sub-features they are not necessarily in numerical order: + strands = {_.strand for _ in locs} + if len(strands) == 1 and -1 in strands: + # Evil hack time for backwards compatibility + # TODO - Check if BioPerl and (old) Biopython did the same, + # we may have an existing incompatibility lurking here... + locs = locs[::-1] + feature.location = SeqFeature.CompoundLocation(locs, "join") + # TODO - See Bug 2677 - we don't yet record location operator, + # so for consistency with older versions of Biopython default + # to assuming its a join. + seq_feature_list.append(feature) + return seq_feature_list + + +def _retrieve_location_qualifier_value(adaptor, location_id): + value = adaptor.execute_and_fetch_col0( + "SELECT value FROM location_qualifier_value WHERE location_id = %s", + (location_id,), + ) + try: + return value[0] + except IndexError: + return "" + + +def _retrieve_annotations(adaptor, primary_id, taxon_id): + annotations = {} + annotations.update(_retrieve_alphabet(adaptor, primary_id)) + annotations.update(_retrieve_qualifier_value(adaptor, primary_id)) + annotations.update(_retrieve_reference(adaptor, primary_id)) + annotations.update(_retrieve_taxon(adaptor, primary_id, taxon_id)) + annotations.update(_retrieve_comment(adaptor, primary_id)) + return annotations + + +def _retrieve_alphabet(adaptor, primary_id): + results = adaptor.execute_and_fetchall( + "SELECT alphabet FROM biosequence WHERE bioentry_id = %s", (primary_id,) + ) + if len(results) != 1: + raise ValueError(f"Expected 1 response, got {len(results)}.") + alphabets = results[0] + if len(alphabets) != 1: + raise ValueError(f"Expected 1 alphabet in response, got {len(alphabets)}.") + alphabet = alphabets[0] + if alphabet == "dna": + molecule_type = "DNA" + elif alphabet == "rna": + molecule_type = "RNA" + elif alphabet == "protein": + molecule_type = "protein" + else: + molecule_type = None + if molecule_type is not None: + return {"molecule_type": molecule_type} + else: + return {} + + +def _retrieve_qualifier_value(adaptor, primary_id): + qvs = adaptor.execute_and_fetchall( + "SELECT name, value" + " FROM bioentry_qualifier_value JOIN term USING (term_id)" + " WHERE bioentry_id = %s" + ' ORDER BY "rank"', + (primary_id,), + ) + qualifiers = {} + for name, value in qvs: + if name == "keyword": + name = "keywords" + # See handling of "date" in Loader.py + elif name == "date_changed": + name = "date" + elif name == "secondary_accession": + name = "accessions" + qualifiers.setdefault(name, []).append(value) + return qualifiers + + +def _retrieve_reference(adaptor, primary_id): + # XXX dbxref_qualifier_value + + refs = adaptor.execute_and_fetchall( + "SELECT start_pos, end_pos, " + " location, title, authors," + " dbname, accession" + " FROM bioentry_reference" + " JOIN reference USING (reference_id)" + " LEFT JOIN dbxref USING (dbxref_id)" + " WHERE bioentry_id = %s" + ' ORDER BY "rank"', + (primary_id,), + ) + references = [] + for start, end, location, title, authors, dbname, accession in refs: + reference = SeqFeature.Reference() + # If the start/end are missing, reference.location is an empty list + if (start is not None) or (end is not None): + if start is not None: + start -= 1 # python counting + reference.location = [SeqFeature.SimpleLocation(start, end)] + # Don't replace the default "" with None. + if authors: + reference.authors = authors + if title: + reference.title = title + reference.journal = location + if dbname == "PUBMED": + reference.pubmed_id = accession + elif dbname == "MEDLINE": + reference.medline_id = accession + references.append(reference) + if references: + return {"references": references} + else: + return {} + + +def _retrieve_taxon(adaptor, primary_id, taxon_id): + a = {} + common_names = adaptor.execute_and_fetch_col0( + "SELECT name FROM taxon_name WHERE taxon_id = %s" + " AND name_class = 'genbank common name'", + (taxon_id,), + ) + if common_names: + a["source"] = common_names[0] + scientific_names = adaptor.execute_and_fetch_col0( + "SELECT name FROM taxon_name WHERE taxon_id = %s" + " AND name_class = 'scientific name'", + (taxon_id,), + ) + if scientific_names: + a["organism"] = scientific_names[0] + ncbi_taxids = adaptor.execute_and_fetch_col0( + "SELECT ncbi_taxon_id FROM taxon WHERE taxon_id = %s", (taxon_id,) + ) + if ncbi_taxids and ncbi_taxids[0] and ncbi_taxids[0] != "0": + a["ncbi_taxid"] = ncbi_taxids[0] + + # Old code used the left/right values in the taxon table to get the + # taxonomy lineage in one SQL command. This was actually very slow, + # and would fail if the (optional) left/right values were missing. + # + # The following code is based on a contribution from Eric Gibert, and + # relies on the taxon table's parent_taxon_id field only (ignoring the + # optional left/right values). This means that it has to make a + # separate SQL query for each entry in the lineage, but it does still + # appear to be *much* faster. See Bug 2494. + taxonomy = [] + while taxon_id: + name, rank, parent_taxon_id = adaptor.execute_one( + "SELECT taxon_name.name, taxon.node_rank, taxon.parent_taxon_id" + " FROM taxon, taxon_name" + " WHERE taxon.taxon_id=taxon_name.taxon_id" + " AND taxon_name.name_class='scientific name'" + " AND taxon.taxon_id = %s", + (taxon_id,), + ) + if taxon_id == parent_taxon_id: + # If the taxon table has been populated by the BioSQL script + # load_ncbi_taxonomy.pl this is how top parent nodes are stored. + # Personally, I would have used a NULL parent_taxon_id here. + break + + taxonomy.insert(0, name) + taxon_id = parent_taxon_id + + if taxonomy: + a["taxonomy"] = taxonomy + return a + + +def _retrieve_comment(adaptor, primary_id): + qvs = adaptor.execute_and_fetchall( + 'SELECT comment_text FROM comment WHERE bioentry_id=%s ORDER BY "rank"', + (primary_id,), + ) + comments = [comm[0] for comm in qvs] + # Don't want to add an empty list... + if comments: + return {"comment": comments} + else: + return {} + + +class DBSeqRecord(SeqRecord): + """BioSQL equivalent of the Biopython SeqRecord object.""" + + def __init__(self, adaptor, primary_id): + """Create a DBSeqRecord object. + + Arguments: + - adaptor - A BioSQL.BioSeqDatabase.Adaptor object + - primary_id - An internal integer ID used by BioSQL + + You wouldn't normally create a DBSeqRecord object yourself, + this is done for you when using a BioSeqDatabase object + """ + self._adaptor = adaptor + self._primary_id = primary_id + + ( + self._biodatabase_id, + self._taxon_id, + self.name, + accession, + version, + self._identifier, + self._division, + self.description, + ) = self._adaptor.execute_one( + "SELECT biodatabase_id, taxon_id, name, accession, version," + " identifier, division, description" + " FROM bioentry" + " WHERE bioentry_id = %s", + (self._primary_id,), + ) + if version and version != "0": + self.id = f"{accession}.{version}" + else: + self.id = accession + # We don't yet record any per-letter-annotations in the + # BioSQL database, but we should set this property up + # for completeness (and the __str__ method). + # We do NOT want to load the sequence from the DB here! + length = _retrieve_seq_len(adaptor, primary_id) + self._per_letter_annotations = _RestrictedDict(length=length) + + def __get_seq(self): + if not hasattr(self, "_seq"): + self._seq = _retrieve_seq(self._adaptor, self._primary_id) + return self._seq + + def __set_seq(self, seq): + # TODO - Check consistent with self._per_letter_annotations + self._seq = seq + + def __del_seq(self): + del self._seq + + seq = property(__get_seq, __set_seq, __del_seq, "Seq object") # type: ignore + + @property + def dbxrefs(self) -> list[str]: + """Database cross references.""" + if not hasattr(self, "_dbxrefs"): + self._dbxrefs = _retrieve_dbxrefs(self._adaptor, self._primary_id) + return self._dbxrefs + + @dbxrefs.setter + def dbxrefs(self, value: list[str]) -> None: + self._dbxrefs = value + + @dbxrefs.deleter + def dbxrefs(self) -> None: + del self._dbxrefs + + def __get_features(self): + if not hasattr(self, "_features"): + self._features = _retrieve_features(self._adaptor, self._primary_id) + return self._features + + def __set_features(self, features): + self._features = features + + def __del_features(self): + del self._features + + features = property(__get_features, __set_features, __del_features, "Features") + + @property + def annotations(self) -> SeqRecord._AnnotationsDict: + """Annotations.""" + if not hasattr(self, "_annotations"): + self._annotations = _retrieve_annotations( + self._adaptor, self._primary_id, self._taxon_id + ) + if self._identifier: + self._annotations["gi"] = self._identifier + if self._division: + self._annotations["data_file_division"] = self._division + return self._annotations + + @annotations.setter + def annotations(self, value: SeqRecord._AnnotationsDict | None) -> None: + if value: + self._annotations = value + else: + self._annotations = {} + + @annotations.deleter + def annotations(self) -> None: + del self._annotations diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeqDatabase.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeqDatabase.py new file mode 100644 index 0000000000000000000000000000000000000000..32cbd85aae7d67f82e647b09c2a1c40e37b2310f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeqDatabase.py @@ -0,0 +1,841 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2016 copyright by Peter Cock. All rights reserved. +# Revisions 2009 copyright by Cymon J. Cox. All rights reserved. +# Revisions 2013-2014 copyright by Tiago Antao. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Connect with a BioSQL database and load Biopython like objects from it. + +This provides interfaces for loading biological objects from a relational +database, and is compatible with the BioSQL standards. +""" + +import os + +from . import BioSeq +from . import DBUtils +from . import Loader + +_POSTGRES_RULES_PRESENT = False # Hack for BioSQL Bug 2839 + + +def open_database(driver="MySQLdb", **kwargs): + """Load an existing BioSQL-style database. + + This function is the easiest way to retrieve a connection to a + database, doing something like:: + + from BioSQL import BioSeqDatabase + server = BioSeqDatabase.open_database(user="root", db="minidb") + + Arguments: + - driver - The name of the database driver to use for connecting. The + driver should implement the python DB API. By default, the MySQLdb + driver is used. + - user -the username to connect to the database with. + - password, passwd - the password to connect with + - host - the hostname of the database + - database or db - the name of the database + + """ + if driver == "psycopg": + raise ValueError( + "Using BioSQL with psycopg (version one) is no " + "longer supported. Use psycopg2 instead." + ) + + if os.name == "java": + from com.ziclix.python.sql import zxJDBC + + module = zxJDBC + if driver in ["MySQLdb"]: + jdbc_driver = "com.mysql.jdbc.Driver" + url_pref = "jdbc:mysql://" + kwargs["host"] + "/" + elif driver in ["psycopg2"]: + jdbc_driver = "org.postgresql.Driver" + url_pref = "jdbc:postgresql://" + kwargs["host"] + "/" + + else: + module = __import__(driver, fromlist=["connect"]) + connect = module.connect + + # Different drivers use different keywords... + kw = kwargs.copy() + if driver in ["MySQLdb", "mysql.connector"] and os.name != "java": + if "database" in kw: + kw["db"] = kw["database"] + del kw["database"] + if "password" in kw: + kw["passwd"] = kw["password"] + del kw["password"] + # kw["charset"] = "utf8" + # kw["use_unicode"] = True + else: + # DB-API recommendations + if "db" in kw: + kw["database"] = kw["db"] + del kw["db"] + if "passwd" in kw: + kw["password"] = kw["passwd"] + del kw["passwd"] + if driver in ["psycopg2", "pgdb"] and not kw.get("database"): + kw["database"] = "template1" + # SQLite connect takes the database name as input + if os.name == "java": + if driver in ["MySQLdb"]: + conn = connect( + url_pref + kw.get("database", "mysql"), + kw["user"], + kw["password"], + jdbc_driver, + ) + elif driver in ["psycopg2"]: + conn = connect( + url_pref + kw.get("database", "postgresql") + "?stringtype=unspecified", + kw["user"], + kw["password"], + jdbc_driver, + ) + elif driver in ["sqlite3"]: + conn = connect(kw["database"]) + else: + conn = connect(**kw) + + if os.name == "java": + server = DBServer(conn, module, driver) + else: + server = DBServer(conn, module) + + # Sets MySQL to allow double quotes, rather than only backticks + if driver in ["MySQLdb", "mysql.connector"]: + server.adaptor.execute("SET sql_mode='ANSI_QUOTES';") + + # TODO - Remove the following once BioSQL Bug 2839 is fixed. + # Test for RULES in PostgreSQL schema, see also Bug 2833. + if driver in ["psycopg2", "pgdb"]: + sql = ( + "SELECT ev_class FROM pg_rewrite WHERE " + "rulename='rule_bioentry_i1' OR " + "rulename='rule_bioentry_i2';" + ) + if server.adaptor.execute_and_fetchall(sql): + import warnings + + from Bio import BiopythonWarning + + warnings.warn( + "Your BioSQL PostgreSQL schema includes some rules " + "currently required for bioperl-db but which may" + "cause problems loading data using Biopython (see " + "BioSQL's RedMine Bug 2839 aka GitHub Issue 4 " + "https://github.com/biosql/biosql/issues/4). " + "If you do not use BioPerl, please remove these " + "rules. Biopython should cope with the rules " + "present, but with a performance penalty when " + "loading new records.", + BiopythonWarning, + ) + global _POSTGRES_RULES_PRESENT + _POSTGRES_RULES_PRESENT = True + + elif driver == "sqlite3": + # Tell SQLite that we want to use foreign keys + # https://www.sqlite.org/foreignkeys.html#fk_enable + server.adaptor.execute("PRAGMA foreign_keys = ON") + + return server + + +class DBServer: + """Represents a BioSQL database containing namespaces (sub-databases). + + This acts like a Python dictionary, giving access to each namespace + (defined by a row in the biodatabase table) as a BioSeqDatabase object. + """ + + def __init__(self, conn, module, module_name=None): + """Create a DBServer object. + + Arguments: + - conn - A database connection object + - module - The module used to create the database connection + - module_name - Optionally, the name of the module. Default: module.__name__ + + Normally you would not want to create a DBServer object yourself. + Instead use the open_database function, which returns an instance of DBServer. + """ + self.module = module + if module_name is None: + module_name = module.__name__ + if module_name == "mysql.connector": + wrap_cursor = True + else: + wrap_cursor = False + # Get module specific Adaptor or the base (general) Adaptor + Adapt = _interface_specific_adaptors.get(module_name, Adaptor) + self.adaptor = Adapt( + conn, DBUtils.get_dbutils(module_name), wrap_cursor=wrap_cursor + ) + self.module_name = module_name + + def __repr__(self): + """Return a short description of the class name and database connection.""" + return f"{self.__class__.__name__}({self.adaptor.conn!r})" + + def __getitem__(self, name): + """Return a BioSeqDatabase object. + + Arguments: + - name - The name of the BioSeqDatabase + + """ + return BioSeqDatabase(self.adaptor, name) + + def __len__(self): + """Return number of namespaces (sub-databases) in this database.""" + sql = "SELECT COUNT(name) FROM biodatabase;" + return int(self.adaptor.execute_and_fetch_col0(sql)[0]) + + def __contains__(self, value): + """Check if a namespace (sub-database) in this database.""" + sql = "SELECT COUNT(name) FROM biodatabase WHERE name=%s;" + return bool(self.adaptor.execute_and_fetch_col0(sql, (value,))[0]) + + def __iter__(self): + """Iterate over namespaces (sub-databases) in the database.""" + # TODO - Iterate over the cursor, much more efficient + return iter(self.adaptor.list_biodatabase_names()) + + def keys(self): + """Iterate over namespaces (sub-databases) in the database.""" + return iter(self) + + def values(self): + """Iterate over BioSeqDatabase objects in the database.""" + for key in self: + yield self[key] + + def items(self): + """Iterate over (namespace, BioSeqDatabase) in the database.""" + for key in self: + yield key, self[key] + + def __delitem__(self, name): + """Remove a namespace and all its entries.""" + if name not in self: + raise KeyError(name) + db_id = self.adaptor.fetch_dbid_by_dbname(name) + remover = Loader.DatabaseRemover(self.adaptor, db_id) + remover.remove() + + def new_database(self, db_name, authority=None, description=None): + """Add a new database to the server and return it.""" + # make the database + sql = ( + "INSERT INTO biodatabase (name, authority, description) VALUES (%s, %s, %s)" + ) + self.adaptor.execute(sql, (db_name, authority, description)) + return BioSeqDatabase(self.adaptor, db_name) + + def load_database_sql(self, sql_file): + """Load a database schema into the given database. + + This is used to create tables, etc when a database is first created. + sql_file should specify the complete path to a file containing + SQL entries for building the tables. + """ + # Not sophisticated enough for PG schema. Is it needed by MySQL? + # Looks like we need this more complicated way for both. Leaving it + # the default and removing the simple-minded approach. + + # read the file with all comment lines removed + sql = "" + with open(sql_file) as sql_handle: + for line in sql_handle: + if line.startswith("--"): # don't include comment lines + pass + elif line.startswith("#"): # ditto for MySQL comments + pass + elif line.strip(): # only include non-blank lines + sql += line.strip() + " " + + # two ways to load the SQL + # 1. PostgreSQL can load it all at once and actually needs to + # due to FUNCTION defines at the end of the SQL which mess up + # the splitting by semicolons + if self.module_name in ["psycopg2", "pgdb"]: + self.adaptor.cursor.execute(sql) + # 2. MySQL needs the database loading split up into single lines of + # SQL executed one at a time + elif self.module_name in ["mysql.connector", "MySQLdb", "sqlite3"]: + sql_parts = sql.split(";") # one line per sql command + # don't use the last item, it's blank + for sql_line in sql_parts[:-1]: + self.adaptor.cursor.execute(sql_line) + else: + raise ValueError(f"Module {self.module_name} not supported by the loader.") + + def commit(self): + """Commit the current transaction to the database.""" + return self.adaptor.commit() + + def rollback(self): + """Roll-back the current transaction.""" + return self.adaptor.rollback() + + def close(self): + """Close the connection. No further activity possible.""" + return self.adaptor.close() + + +class _CursorWrapper: + """A wrapper for mysql.connector resolving bytestring representations.""" + + def __init__(self, real_cursor): + self.real_cursor = real_cursor + + def execute(self, operation, params=None, multi=False): + """Execute a sql statement.""" + self.real_cursor.execute(operation, params, multi) + + def executemany(self, operation, params): + """Execute many sql statements.""" + self.real_cursor.executemany(operation, params) + + def _convert_tuple(self, tuple_): + """Decode any bytestrings present in the row (PRIVATE).""" + tuple_list = list(tuple_) + for i, elem in enumerate(tuple_list): + if isinstance(elem, bytes): + tuple_list[i] = elem.decode("utf-8") + return tuple(tuple_list) + + def _convert_list(self, lst): + ret_lst = [] + for tuple_ in lst: + new_tuple = self._convert_tuple(tuple_) + ret_lst.append(new_tuple) + return ret_lst + + def fetchall(self): + rv = self.real_cursor.fetchall() + return self._convert_list(rv) + + def fetchone(self): + tuple_ = self.real_cursor.fetchone() + return self._convert_tuple(tuple_) + + +class Adaptor: + """High level wrapper for a database connection and cursor. + + Most database calls in BioSQL are done indirectly though this adaptor + class. This provides helper methods for fetching data and executing + sql. + """ + + def __init__(self, conn, dbutils, wrap_cursor=False): + """Create an Adaptor object. + + Arguments: + - conn - A database connection + - dbutils - A BioSQL.DBUtils object + - wrap_cursor - Optional, whether to wrap the cursor object + + """ + self.conn = conn + if wrap_cursor: + self.cursor = _CursorWrapper(conn.cursor()) + else: + self.cursor = conn.cursor() + self.dbutils = dbutils + + def last_id(self, table): + """Return the last row id for the selected table.""" + return self.dbutils.last_id(self.cursor, table) + + def autocommit(self, y=True): + """Set the autocommit mode. True values enable; False value disable.""" + return self.dbutils.autocommit(self.conn, y) + + def commit(self): + """Commit the current transaction.""" + return self.conn.commit() + + def rollback(self): + """Roll-back the current transaction.""" + return self.conn.rollback() + + def close(self): + """Close the connection. No further activity possible.""" + return self.conn.close() + + def fetch_dbid_by_dbname(self, dbname): + """Return the internal id for the sub-database using its name.""" + self.execute( + "select biodatabase_id from biodatabase where name = %s", (dbname,) + ) + rv = self.cursor.fetchall() + if not rv: + raise KeyError(f"Cannot find biodatabase with name {dbname!r}") + return rv[0][0] + + def fetch_seqid_by_display_id(self, dbid, name): + """Return the internal id for a sequence using its display id. + + Arguments: + - dbid - the internal id for the sub-database + - name - the name of the sequence. Corresponds to the + name column of the bioentry table of the SQL schema + + """ + sql = "select bioentry_id from bioentry where name = %s" + fields = [name] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find display id {name!r}") + if len(rv) > 1: + raise IndexError(f"More than one entry with display id {name!r}") + return rv[0][0] + + def fetch_seqid_by_accession(self, dbid, name): + """Return the internal id for a sequence using its accession. + + Arguments: + - dbid - the internal id for the sub-database + - name - the accession of the sequence. Corresponds to the + accession column of the bioentry table of the SQL schema + + """ + sql = "select bioentry_id from bioentry where accession = %s" + fields = [name] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find accession {name!r}") + if len(rv) > 1: + raise IndexError(f"More than one entry with accession {name!r}") + return rv[0][0] + + def fetch_seqids_by_accession(self, dbid, name): + """Return a list internal ids using an accession. + + Arguments: + - dbid - the internal id for the sub-database + - name - the accession of the sequence. Corresponds to the + accession column of the bioentry table of the SQL schema + + """ + sql = "select bioentry_id from bioentry where accession = %s" + fields = [name] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + return self.execute_and_fetch_col0(sql, fields) + + def fetch_seqid_by_version(self, dbid, name): + """Return the internal id for a sequence using its accession and version. + + Arguments: + - dbid - the internal id for the sub-database + - name - the accession of the sequence containing a version number. + Must correspond to . + + """ + acc_version = name.split(".") + if len(acc_version) > 2: + raise IndexError(f"Bad version {name!r}") + acc = acc_version[0] + if len(acc_version) == 2: + version = acc_version[1] + else: + version = "0" + sql = "SELECT bioentry_id FROM bioentry WHERE accession = %s AND version = %s" + fields = [acc, version] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find version {name!r}") + if len(rv) > 1: + raise IndexError(f"More than one entry with version {name!r}") + return rv[0][0] + + def fetch_seqid_by_identifier(self, dbid, identifier): + """Return the internal id for a sequence using its identifier. + + Arguments: + - dbid - the internal id for the sub-database + - identifier - the identifier of the sequence. Corresponds to + the identifier column of the bioentry table in the SQL schema. + + """ + # YB: was fetch_seqid_by_seqid + sql = "SELECT bioentry_id FROM bioentry WHERE identifier = %s" + fields = [identifier] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find display id {identifier!r}") + return rv[0][0] + + def list_biodatabase_names(self): + """Return a list of all of the sub-databases.""" + return self.execute_and_fetch_col0("SELECT name FROM biodatabase") + + def list_bioentry_ids(self, dbid): + """Return a list of internal ids for all of the sequences in a sub-databae. + + Arguments: + - dbid - The internal id for a sub-database + + """ + return self.execute_and_fetch_col0( + "SELECT bioentry_id FROM bioentry WHERE biodatabase_id = %s", (dbid,) + ) + + def list_bioentry_display_ids(self, dbid): + """Return a list of all sequence names in a sub-databae. + + Arguments: + - dbid - The internal id for a sub-database + + """ + return self.execute_and_fetch_col0( + "SELECT name FROM bioentry WHERE biodatabase_id = %s", (dbid,) + ) + + def list_any_ids(self, sql, args): + """Return ids given a SQL statement to select for them. + + This assumes that the given SQL does a SELECT statement that + returns a list of items. This parses them out of the 2D list + they come as and just returns them in a list. + """ + return self.execute_and_fetch_col0(sql, args) + + def execute_one(self, sql, args=None): + """Execute sql that returns 1 record, and return the record.""" + self.execute(sql, args or ()) + rv = self.cursor.fetchall() + if len(rv) != 1: + raise ValueError(f"Expected 1 response, got {len(rv)}.") + return rv[0] + + def execute(self, sql, args=None): + """Just execute an sql command.""" + if os.name == "java": + sql = sql.replace("%s", "?") + self.dbutils.execute(self.cursor, sql, args) + + def executemany(self, sql, args): + """Execute many sql commands.""" + if os.name == "java": + sql = sql.replace("%s", "?") + self.dbutils.executemany(self.cursor, sql, args) + + def get_subseq_as_string(self, seqid, start, end): + """Return a substring of a sequence. + + Arguments: + - seqid - The internal id for the sequence + - start - The start position of the sequence; 0-indexed + - end - The end position of the sequence + + """ + length = end - start + # XXX Check this on MySQL and PostgreSQL. substr should be general, + # does it need dbutils? + # return self.execute_one( + # """select SUBSTRING(seq FROM %s FOR %s) + # from biosequence where bioentry_id = %s""", + # (start+1, length, seqid))[0] + return self.execute_one( + "SELECT SUBSTR(seq, %s, %s) FROM biosequence WHERE bioentry_id = %s", + (start + 1, length, seqid), + )[0] + + def execute_and_fetch_col0(self, sql, args=None): + """Return a list of values from the first column in the row.""" + self.execute(sql, args or ()) + return [field[0] for field in self.cursor.fetchall()] + + def execute_and_fetchall(self, sql, args=None): + """Return a list of tuples of all rows.""" + self.execute(sql, args or ()) + return self.cursor.fetchall() + + +class MysqlConnectorAdaptor(Adaptor): + """A BioSQL Adaptor class with fixes for the MySQL interface. + + BioSQL was failing due to returns of bytearray objects from + the mysql-connector-python database connector. This adaptor + class scrubs returns of bytearrays and of byte strings converting + them to string objects instead. This adaptor class was made in + response to backwards incompatible changes added to + mysql-connector-python in release 2.0.0 of the package. + """ + + @staticmethod + def _bytearray_to_str(s): + """If s is bytes or bytearray, convert to a string (PRIVATE).""" + if isinstance(s, (bytes, bytearray)): + return s.decode() + return s + + def execute_one(self, sql, args=None): + """Execute sql that returns 1 record, and return the record.""" + out = super().execute_one(sql, args) + return tuple(self._bytearray_to_str(v) for v in out) + + def execute_and_fetch_col0(self, sql, args=None): + """Return a list of values from the first column in the row.""" + out = super().execute_and_fetch_col0(sql, args) + return [self._bytearray_to_str(column) for column in out] + + def execute_and_fetchall(self, sql, args=None): + """Return a list of tuples of all rows.""" + out = super().execute_and_fetchall(sql, args) + return [tuple(self._bytearray_to_str(v) for v in o) for o in out] + + +_interface_specific_adaptors = { + # If SQL interfaces require a specific adaptor, use this to map the adaptor + "mysql.connector": MysqlConnectorAdaptor, + "MySQLdb": MysqlConnectorAdaptor, +} + +_allowed_lookups = { + # Lookup name / function name to get id, function to list all ids + "primary_id": "fetch_seqid_by_identifier", + "gi": "fetch_seqid_by_identifier", + "display_id": "fetch_seqid_by_display_id", + "name": "fetch_seqid_by_display_id", + "accession": "fetch_seqid_by_accession", + "version": "fetch_seqid_by_version", +} + + +class BioSeqDatabase: + """Represents a namespace (sub-database) within the BioSQL database. + + i.e. One row in the biodatabase table, and all all rows in the bioentry + table associated with it. + """ + + def __init__(self, adaptor, name): + """Create a BioDatabase object. + + Arguments: + - adaptor - A BioSQL.Adaptor object + - name - The name of the sub-database (namespace) + + """ + self.adaptor = adaptor + self.name = name + self.dbid = self.adaptor.fetch_dbid_by_dbname(name) + + def __repr__(self): + """Return a short summary of the BioSeqDatabase.""" + return f"BioSeqDatabase({self.adaptor!r}, {self.name!r})" + + def get_Seq_by_id(self, name): + """Get a DBSeqRecord object by its name. + + Example: seq_rec = db.get_Seq_by_id('ROA1_HUMAN') + + The name of this method is misleading since it returns a DBSeqRecord + rather than a Seq object, and presumably was to mirror BioPerl. + """ + seqid = self.adaptor.fetch_seqid_by_display_id(self.dbid, name) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def get_Seq_by_acc(self, name): + """Get a DBSeqRecord object by accession number. + + Example: seq_rec = db.get_Seq_by_acc('X77802') + + The name of this method is misleading since it returns a DBSeqRecord + rather than a Seq object, and presumably was to mirror BioPerl. + """ + seqid = self.adaptor.fetch_seqid_by_accession(self.dbid, name) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def get_Seq_by_ver(self, name): + """Get a DBSeqRecord object by version number. + + Example: seq_rec = db.get_Seq_by_ver('X77802.1') + + The name of this method is misleading since it returns a DBSeqRecord + rather than a Seq object, and presumably was to mirror BioPerl. + """ + seqid = self.adaptor.fetch_seqid_by_version(self.dbid, name) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def get_Seqs_by_acc(self, name): + """Get a list of DBSeqRecord objects by accession number. + + Example: seq_recs = db.get_Seq_by_acc('X77802') + + The name of this method is misleading since it returns a list of + DBSeqRecord objects rather than a list of Seq objects, and presumably + was to mirror BioPerl. + """ + seqids = self.adaptor.fetch_seqids_by_accession(self.dbid, name) + return [BioSeq.DBSeqRecord(self.adaptor, seqid) for seqid in seqids] + + def __getitem__(self, key): + """Return a DBSeqRecord for one of the sequences in the sub-database. + + Arguments: + - key - The internal id for the sequence + + """ + record = BioSeq.DBSeqRecord(self.adaptor, key) + if record._biodatabase_id != self.dbid: + raise KeyError(f"Entry {key!r} does exist, but not in current name space") + return record + + def __delitem__(self, key): + """Remove an entry and all its annotation.""" + if key not in self: + raise KeyError( + f"Entry {key!r} cannot be deleted. It was not found or is invalid" + ) + # Assuming this will automatically cascade to the other tables... + sql = "DELETE FROM bioentry WHERE biodatabase_id=%s AND bioentry_id=%s;" + self.adaptor.execute(sql, (self.dbid, key)) + + def __len__(self): + """Return number of records in this namespace (sub database).""" + sql = "SELECT COUNT(bioentry_id) FROM bioentry WHERE biodatabase_id=%s;" + return int(self.adaptor.execute_and_fetch_col0(sql, (self.dbid,))[0]) + + def __contains__(self, value): + """Check if a primary (internal) id is this namespace (sub database).""" + sql = ( + "SELECT COUNT(bioentry_id) FROM bioentry " + "WHERE biodatabase_id=%s AND bioentry_id=%s;" + ) + # The bioentry_id field is an integer in the schema. + # PostgreSQL will throw an error if we use a non integer in the query. + try: + bioentry_id = int(value) + except ValueError: + return False + return bool( + self.adaptor.execute_and_fetch_col0(sql, (self.dbid, bioentry_id))[0] + ) + + def __iter__(self): + """Iterate over ids (which may not be meaningful outside this database).""" + # TODO - Iterate over the cursor, much more efficient + return iter(self.adaptor.list_bioentry_ids(self.dbid)) + + def keys(self): + """Iterate over ids (which may not be meaningful outside this database).""" + return iter(self) + + def values(self): + """Iterate over DBSeqRecord objects in the namespace (sub database).""" + for key in self: + yield self[key] + + def items(self): + """Iterate over (id, DBSeqRecord) for the namespace (sub database).""" + for key in self: + yield key, self[key] + + def lookup(self, **kwargs): + """Return a DBSeqRecord using an acceptable identifier. + + Arguments: + - kwargs - A single key-value pair where the key is one + of primary_id, gi, display_id, name, accession, version + + """ + if len(kwargs) != 1: + raise TypeError("single key/value parameter expected") + k, v = list(kwargs.items())[0] + if k not in _allowed_lookups: + raise TypeError( + f"lookup() expects one of {list(_allowed_lookups.keys())!r}, not {k!r}" + ) + lookup_name = _allowed_lookups[k] + lookup_func = getattr(self.adaptor, lookup_name) + seqid = lookup_func(self.dbid, v) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def load(self, record_iterator, fetch_NCBI_taxonomy=False): + """Load a set of SeqRecords into the BioSQL database. + + record_iterator is either a list of SeqRecord objects, or an + Iterator object that returns SeqRecord objects (such as the + output from the Bio.SeqIO.parse() function), which will be + used to populate the database. + + fetch_NCBI_taxonomy is boolean flag allowing or preventing + connection to the taxonomic database on the NCBI server + (via Bio.Entrez) to fetch a detailed taxonomy for each + SeqRecord. + + Example:: + + from Bio import SeqIO + count = db.load(SeqIO.parse(open(filename), format)) + + Returns the number of records loaded. + """ + db_loader = Loader.DatabaseLoader(self.adaptor, self.dbid, fetch_NCBI_taxonomy) + num_records = 0 + for cur_record in record_iterator: + num_records += 1 + # Hack to work around BioSQL Bug 2839 - If using PostgreSQL and + # the RULES are present check for a duplicate record before loading + if _POSTGRES_RULES_PRESENT: + # Recreate what the Loader's _load_bioentry_table will do: + if cur_record.id.count(".") == 1: + accession, version = cur_record.id.split(".") + try: + version = int(version) + except ValueError: + accession = cur_record.id + version = 0 + else: + accession = cur_record.id + version = 0 + gi = cur_record.annotations.get("gi") + sql = ( + "SELECT bioentry_id FROM bioentry " + "WHERE (identifier = '%s' AND biodatabase_id = '%s') " + "OR (accession = '%s' AND version = '%s' AND biodatabase_id = '%s')" + ) + self.adaptor.execute( + sql % (gi, self.dbid, accession, version, self.dbid) + ) + if self.adaptor.cursor.fetchone(): + raise self.adaptor.conn.IntegrityError( + "Duplicate record detected: record has not been inserted" + ) + # End of hack + db_loader.load_seqrecord(cur_record) + return num_records diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/DBUtils.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/DBUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..7552b983fb1faf765304cf14210c9c0324511a25 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/DBUtils.py @@ -0,0 +1,153 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2010 copyright by Peter Cock. All rights reserved. +# Revisions 2009 copyright by Brad Chapman. All rights reserved. +# Revisions 2013 copyright by Tiago Antao. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Helper code for Biopython's BioSQL code (for internal use).""" + +import os + +_dbutils: dict[str, type["Generic_dbutils"]] = {} + + +class Generic_dbutils: + """Default database utilities.""" + + def __init__(self): + """Create a Generic_dbutils object.""" + + def tname(self, table): + """Return the name of the table.""" + if table != "biosequence": + return table + else: + return "bioentry" + + def last_id(self, cursor, table): + """Return the last used id for a table.""" + # XXX: Unsafe without transactions isolation + table = self.tname(table) + sql = f"select max({table}_id) from {table}" + cursor.execute(sql) + rv = cursor.fetchone() + return rv[0] + + def execute(self, cursor, sql, args=None): + """Just execute an sql command.""" + cursor.execute(sql, args or ()) + + def executemany(self, cursor, sql, seq): + """Execute many sql commands.""" + cursor.executemany(sql, seq) + + def autocommit(self, conn, y=1): + """Set autocommit on the database connection.""" + # Let's hope it was not really needed + + +class Sqlite_dbutils(Generic_dbutils): + """Custom database utilities for SQLite.""" + + def _sub_placeholder(self, sql): + """Format the argument placeholders for sqlite (PRIVATE).""" + return sql.replace("%s", "?") + + def execute(self, cursor, sql, args=None): + """Execute SQL command. + + Replaces %s with ? for variable substitution in sqlite3. + """ + sql = self._sub_placeholder(sql) + cursor.execute(sql, args or ()) + + def executemany(self, cursor, sql, seq): + """Execute many sql statements.""" + sql = self._sub_placeholder(sql) + cursor.executemany(sql, seq) + + +_dbutils["sqlite3"] = Sqlite_dbutils + + +class Mysql_dbutils(Generic_dbutils): + """Custom database utilities for MySQL.""" + + def last_id(self, cursor, table): + """Return the last used id for a table.""" + if os.name == "java": + return Generic_dbutils.last_id(self, cursor, table) + try: + # This worked on older versions of MySQL + return cursor.insert_id() + except AttributeError: + # See bug 2390 + # Google suggests this is the new way, + # same fix also suggested by Eric Gibert: + return cursor.lastrowid + + +_dbutils["MySQLdb"] = Mysql_dbutils + + +class _PostgreSQL_dbutils(Generic_dbutils): + """Base class for any PostgreSQL adaptor.""" + + def next_id(self, cursor, table): + table = self.tname(table) + sql = f"SELECT nextval('{table}_pk_seq')" + cursor.execute(sql) + rv = cursor.fetchone() + return rv[0] + + def last_id(self, cursor, table): + table = self.tname(table) + sql = f"SELECT currval('{table}_pk_seq')" + cursor.execute(sql) + rv = cursor.fetchone() + return rv[0] + + +class Psycopg2_dbutils(_PostgreSQL_dbutils): + """Custom database utilities for Psycopg2 (PostgreSQL).""" + + def autocommit(self, conn, y=True): + """Set autocommit on the database connection.""" + if y: + if os.name == "java": + conn.autocommit = 1 + else: + conn.set_isolation_level(0) + else: + if os.name == "java": + conn.autocommit = 0 + else: + conn.set_isolation_level(1) + + +_dbutils["psycopg2"] = Psycopg2_dbutils + + +class Pgdb_dbutils(_PostgreSQL_dbutils): + """Custom database utilities for Pgdb (aka PyGreSQL, for PostgreSQL).""" + + def autocommit(self, conn, y=True): + """Set autocommit on the database connection. Currently not implemented.""" + raise NotImplementedError("pgdb does not support this!") + + +_dbutils["pgdb"] = Pgdb_dbutils + + +def get_dbutils(module_name): + """Return the correct dbutils object for the database driver.""" + try: + return _dbutils[module_name]() + except KeyError: + return Generic_dbutils() diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/Loader.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/Loader.py new file mode 100644 index 0000000000000000000000000000000000000000..888ce686c9087d9579a90eb816d191712e89cfd3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/Loader.py @@ -0,0 +1,1260 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2016 copyright by Peter Cock. All rights reserved. +# Revisions 2008 copyright by Cymon J. Cox. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org + +"""Load biopython objects into a BioSQL database for persistent storage. + +This code makes it possible to store biopython objects in a relational +database and then retrieve them back. You shouldn't use any of the +classes in this module directly. Rather, call the load() method on +a database object. +""" + +# standard modules +from time import gmtime +from time import strftime + +from Bio import Entrez +from Bio.Seq import UndefinedSequenceError +from Bio.SeqFeature import UnknownPosition + +# biopython +from Bio.SeqUtils.CheckSum import crc64 + + +class DatabaseLoader: + """Object used to load SeqRecord objects into a BioSQL database.""" + + def __init__(self, adaptor, dbid, fetch_NCBI_taxonomy=False): + """Initialize with connection information for the database. + + Creating a DatabaseLoader object is normally handled via the + BioSeqDatabase DBServer object, for example:: + + from BioSQL import BioSeqDatabase + server = BioSeqDatabase.open_database(driver="MySQLdb", + user="gbrowse", + passwd="biosql", + host="localhost", + db="test_biosql") + try: + db = server["test"] + except KeyError: + db = server.new_database("test", + description="For testing GBrowse") + + """ + self.adaptor = adaptor + self.dbid = dbid + self.fetch_NCBI_taxonomy = fetch_NCBI_taxonomy + + def load_seqrecord(self, record): + """Load a Biopython SeqRecord into the database.""" + bioentry_id = self._load_bioentry_table(record) + self._load_bioentry_date(record, bioentry_id) + self._load_biosequence(record, bioentry_id) + self._load_comment(record, bioentry_id) + self._load_dbxrefs(record, bioentry_id) + references = record.annotations.get("references", ()) + for reference, rank in zip(references, list(range(len(references)))): + self._load_reference(reference, rank, bioentry_id) + self._load_annotations(record, bioentry_id) + for seq_feature_num in range(len(record.features)): + seq_feature = record.features[seq_feature_num] + self._load_seqfeature(seq_feature, seq_feature_num, bioentry_id) + + def _get_ontology_id(self, name, definition=None): + """Return identifier for the named ontology (PRIVATE). + + This looks through the onotology table for a the given entry name. + If it is not found, a row is added for this ontology (using the + definition if supplied). In either case, the id corresponding to + the provided name is returned, so that you can reference it in + another table. + """ + oids = self.adaptor.execute_and_fetch_col0( + "SELECT ontology_id FROM ontology WHERE name = %s", (name,) + ) + if oids: + return oids[0] + self.adaptor.execute( + "INSERT INTO ontology(name, definition) VALUES (%s, %s)", (name, definition) + ) + return self.adaptor.last_id("ontology") + + def _get_term_id(self, name, ontology_id=None, definition=None, identifier=None): + """Get the id that corresponds to a term (PRIVATE). + + This looks through the term table for a the given term. If it + is not found, a new id corresponding to this term is created. + In either case, the id corresponding to that term is returned, so + that you can reference it in another table. + + The ontology_id should be used to disambiguate the term. + """ + # try to get the term id + sql = "SELECT term_id FROM term WHERE name = %s" + fields = [name] + if ontology_id: + sql += " AND ontology_id = %s" + fields.append(ontology_id) + id_results = self.adaptor.execute_and_fetchall(sql, fields) + # something is wrong + if len(id_results) > 1: + raise ValueError(f"Multiple term ids for {name}: {id_results!r}") + elif len(id_results) == 1: + return id_results[0][0] + else: + sql = ( + "INSERT INTO term (name, definition," + " identifier, ontology_id)" + " VALUES (%s, %s, %s, %s)" + ) + self.adaptor.execute(sql, (name, definition, identifier, ontology_id)) + return self.adaptor.last_id("term") + + def _add_dbxref(self, dbname, accession, version): + """Insert a dbxref and return its id (PRIVATE).""" + self.adaptor.execute( + "INSERT INTO dbxref(dbname, accession, version) VALUES (%s, %s, %s)", + (dbname, accession, version), + ) + return self.adaptor.last_id("dbxref") + + def _get_taxon_id(self, record): + """Get the taxon id for this record (PRIVATE). + + Arguments: + - record - a SeqRecord object + + This searches the taxon/taxon_name tables using the + NCBI taxon ID, scientific name and common name to find + the matching taxon table entry's id. + + If the species isn't in the taxon table, and we have at + least the NCBI taxon ID, scientific name or common name, + at least a minimal stub entry is created in the table. + + Returns the taxon id (database key for the taxon table, + not an NCBI taxon ID), or None if the taxonomy information + is missing. + + See also the BioSQL script load_ncbi_taxonomy.pl which + will populate and update the taxon/taxon_name tables + with the latest information from the NCBI. + """ + # To find the NCBI taxid, first check for a top level annotation + ncbi_taxon_id = None + if "ncbi_taxid" in record.annotations: + # Could be a list of IDs. + if isinstance(record.annotations["ncbi_taxid"], list): + if len(record.annotations["ncbi_taxid"]) == 1: + ncbi_taxon_id = record.annotations["ncbi_taxid"][0] + else: + ncbi_taxon_id = record.annotations["ncbi_taxid"] + if not ncbi_taxon_id: + # Secondly, look for a source feature + for f in record.features: + if f.type == "source": + quals = getattr(f, "qualifiers", {}) + if "db_xref" in quals: + for db_xref in f.qualifiers["db_xref"]: + if db_xref.startswith("taxon:"): + ncbi_taxon_id = int(db_xref[6:]) + break + if ncbi_taxon_id: + break + + try: + scientific_name = record.annotations["organism"][:255] + except KeyError: + scientific_name = None + try: + common_name = record.annotations["source"][:255] + except KeyError: + common_name = None + # Note: The maximum length for taxon names in the schema is 255. + # Cropping it now should help in getting a match when searching, + # and avoids an error if we try and add these to the database. + + if ncbi_taxon_id: + # Good, we have the NCBI taxon to go on - this is unambiguous :) + # Note that the scientific name and common name will only be + # used if we have to record a stub entry. + return self._get_taxon_id_from_ncbi_taxon_id( + ncbi_taxon_id, scientific_name, common_name + ) + + if not common_name and not scientific_name: + # Nothing to go on... and there is no point adding + # a new entry to the database. We'll just leave this + # sequence's taxon as a NULL in the database. + return None + + # Next, we'll try to find a match based on the species name + # (stored in GenBank files as the organism and/or the source). + if scientific_name: + taxa = self.adaptor.execute_and_fetch_col0( + "SELECT taxon_id FROM taxon_name" + " WHERE name_class = 'scientific name' AND name = %s", + (scientific_name,), + ) + if taxa: + # Good, mapped the scientific name to a taxon table entry + return taxa[0] + + # Last chance... + if common_name: + taxa = self.adaptor.execute_and_fetch_col0( + "SELECT DISTINCT taxon_id FROM taxon_name WHERE name = %s", + (common_name,), + ) + # Its natural that several distinct taxa will have the same common + # name - in which case we can't resolve the taxon uniquely. + if len(taxa) > 1: + raise ValueError( + "Taxa: %d species have name %r" % (len(taxa), common_name) + ) + if taxa: + # Good, mapped the common name to a taxon table entry + return taxa[0] + + # At this point, as far as we can tell, this species isn't + # in the taxon table already. So we'll have to add it. + # We don't have an NCBI taxonomy ID, so if we do record just + # a stub entry, there is no simple way to fix this later. + # + # TODO - Should we try searching the NCBI taxonomy using the + # species name? + # + # OK, let's try inserting the species. + # Chances are we don't have enough information ... + # Furthermore, it won't be in the hierarchy. + + lineage = [] + for c in record.annotations.get("taxonomy", []): + lineage.append([None, None, c]) + if lineage: + lineage[-1][1] = "genus" + lineage.append([None, "species", record.annotations["organism"]]) + # XXX do we have them? + if "subspecies" in record.annotations: + lineage.append([None, "subspecies", record.annotations["subspecies"]]) + if "variant" in record.annotations: + lineage.append([None, "varietas", record.annotations["variant"]]) + lineage[-1][0] = ncbi_taxon_id + + left_value = self.adaptor.execute_one("SELECT MAX(left_value) FROM taxon")[0] + if not left_value: + left_value = 0 + left_value += 1 + + # XXX -- Brad: Fixing this for now in an ugly way because + # I am getting overlaps for right_values. I need to dig into this + # more to actually understand how it works. I'm not sure it is + # actually working right anyhow. + right_start_value = self.adaptor.execute_one( + "SELECT MAX(right_value) FROM taxon" + )[0] + if not right_start_value: + right_start_value = 0 + right_value = right_start_value + 2 * len(lineage) - 1 + + parent_taxon_id = None + for taxon in lineage: + self.adaptor.execute( + "INSERT INTO taxon(parent_taxon_id, ncbi_taxon_id, node_rank," + " left_value, right_value)" + " VALUES (%s, %s, %s, %s, %s)", + (parent_taxon_id, taxon[0], taxon[1], left_value, right_value), + ) + taxon_id = self.adaptor.last_id("taxon") + self.adaptor.execute( + "INSERT INTO taxon_name(taxon_id, name, name_class)" + "VALUES (%s, %s, 'scientific name')", + (taxon_id, taxon[2][:255]), + ) + # Note the name field is limited to 255, some SwissProt files + # have a multi-species name which can be longer. So truncate this. + left_value += 1 + right_value -= 1 + parent_taxon_id = taxon_id + if common_name: + self.adaptor.execute( + "INSERT INTO taxon_name(taxon_id, name, name_class)" + "VALUES (%s, %s, 'common name')", + (taxon_id, common_name), + ) + + return taxon_id + + def _fix_name_class(self, entrez_name): + """Map Entrez name terms to those used in taxdump (PRIVATE). + + We need to make this conversion to match the taxon_name.name_class + values used by the BioSQL load_ncbi_taxonomy.pl script. + + e.g.:: + + "ScientificName" -> "scientific name", + "EquivalentName" -> "equivalent name", + "Synonym" -> "synonym", + + """ + # Add any special cases here: + # + # known = {} + # try: + # return known[entrez_name] + # except KeyError: + # pass + + # Try automatically by adding spaces before each capital + def add_space(letter): + """Add a space before a capital letter.""" + if letter.isupper(): + return " " + letter.lower() + else: + return letter + + answer = "".join(add_space(letter) for letter in entrez_name).strip() + if answer != answer.lower(): + raise ValueError( + f"Expected processed entrez_name, '{answer}' to only have lower case letters." + ) + return answer + + def _update_left_right_taxon_values(self, left_value): + """Update the left and right taxon values in the table (PRIVATE).""" + if not left_value: + return + # Due to the UNIQUE constraint on the left and right values in the taxon + # table we cannot simply update them through an SQL statement as we risk + # colliding values. Instead we must select all of the rows that we want to + # update, modify the values in python and then update the rows + # self.adaptor.execute("UPDATE taxon SET right_value = right_value + 2 " + # "WHERE right_value >= %s", (left_value,)) + # self.adaptor.execute("UPDATE taxon SET left_value = left_value + 2 " + # "WHERE left_value > %s", (left_value,)) + + rows = self.adaptor.execute_and_fetchall( + "SELECT left_value, right_value, taxon_id FROM taxon " + "WHERE right_value >= %s or left_value > %s", + (left_value, left_value), + ) + + right_rows = [] + left_rows = [] + for row in rows: + new_right = row[1] + new_left = row[0] + if new_right >= left_value: + new_right += 2 + + if new_left > left_value: + new_left += 2 + right_rows.append((new_right, row[2])) + left_rows.append((new_left, row[2])) + + # sort the rows based on the value from largest to smallest + # should ensure no overlaps + right_rows = sorted(right_rows, key=lambda x: x[0], reverse=True) + left_rows = sorted(left_rows, key=lambda x: x[0], reverse=True) + + self.adaptor.executemany( + "UPDATE taxon SET left_value = %s WHERE taxon_id = %s", left_rows + ) + self.adaptor.executemany( + "UPDATE taxon SET right_value = %s WHERE taxon_id = %s", right_rows + ) + + def _get_taxon_id_from_ncbi_taxon_id( + self, ncbi_taxon_id, scientific_name=None, common_name=None + ): + """Get the taxon id for record from NCBI taxon ID (PRIVATE). + + Arguments: + - ncbi_taxon_id - string containing an NCBI taxon id + - scientific_name - string, used if a stub entry is recorded + - common_name - string, used if a stub entry is recorded + + This searches the taxon table using ONLY the NCBI taxon ID + to find the matching taxon table entry's ID (database key). + + If the species isn't in the taxon table, and the fetch_NCBI_taxonomy + flag is true, Biopython will attempt to go online using Bio.Entrez + to fetch the official NCBI lineage, recursing up the tree until an + existing entry is found in the database or the full lineage has been + fetched. + + Otherwise the NCBI taxon ID, scientific name and common name are + recorded as a minimal stub entry in the taxon and taxon_name tables. + Any partial information about the lineage from the SeqRecord is NOT + recorded. This should mean that (re)running the BioSQL script + load_ncbi_taxonomy.pl can fill in the taxonomy lineage. + + Returns the taxon id (database key for the taxon table, not + an NCBI taxon ID). + """ + if not ncbi_taxon_id: + raise ValueError("Expected a non-empty value for ncbi_taxon_id.") + + taxon_id = self.adaptor.execute_and_fetch_col0( + "SELECT taxon_id FROM taxon WHERE ncbi_taxon_id = %s", (int(ncbi_taxon_id),) + ) + if taxon_id: + # Good, we have mapped the NCBI taxid to a taxon table entry + return taxon_id[0] + + # At this point, as far as we can tell, this species isn't + # in the taxon table already. So we'll have to add it. + + parent_taxon_id = None + rank = "species" + genetic_code = None + mito_genetic_code = None + parent_left_value = None + parent_right_value = None + left_value = None + right_value = None + species_names = [] + if scientific_name: + species_names.append(("scientific name", scientific_name)) + if common_name: + species_names.append(("common name", common_name)) + + if self.fetch_NCBI_taxonomy: + # Go online to get the parent taxon ID! + handle = Entrez.efetch(db="taxonomy", id=ncbi_taxon_id, retmode="XML") + taxonomic_record = Entrez.read(handle) + if len(taxonomic_record) == 1: + if taxonomic_record[0]["TaxId"] != str(ncbi_taxon_id): + raise ValueError( + f"ncbi_taxon_id different from parent taxon id. {ncbi_taxon_id} versus {taxonomic_record[0]['TaxId']}" + ) + + ( + parent_taxon_id, + parent_left_value, + parent_right_value, + ) = self._get_taxon_id_from_ncbi_lineage( + taxonomic_record[0]["LineageEx"] + ) + + left_value = parent_right_value + right_value = parent_right_value + 1 + + rank = str(taxonomic_record[0]["Rank"]) + + genetic_code = int(taxonomic_record[0]["GeneticCode"]["GCId"]) + + mito_genetic_code = int(taxonomic_record[0]["MitoGeneticCode"]["MGCId"]) + + species_names = [ + ("scientific name", str(taxonomic_record[0]["ScientificName"])) + ] + try: + for name_class, names in taxonomic_record[0]["OtherNames"].items(): + name_class = self._fix_name_class(name_class) + if not isinstance(names, list): + # The Entrez parser seems to return single entry + # lists as just a string which is annoying. + names = [names] + for name in names: + # Want to ignore complex things like ClassCDE + # entries + if isinstance(name, str): + species_names.append((name_class, name)) + except KeyError: + # OtherNames isn't always present, + # e.g. NCBI taxon 41205, Bromheadia finlaysoniana + pass + else: + pass + # If we are not allowed to go online, we will record the bare minimum; + # as long as the NCBI taxon id is present, then (re)running + # load_ncbi_taxonomy.pl should fill in the taxonomomy lineage + # (and update the species names). + # + # I am NOT going to try and record the lineage, even if it + # is in the record annotation as a list of names, as we won't + # know the NCBI taxon IDs for these parent nodes. + + self._update_left_right_taxon_values(left_value) + + self.adaptor.execute( + "INSERT INTO taxon(parent_taxon_id, ncbi_taxon_id, node_rank," + " genetic_code, mito_genetic_code, left_value, right_value)" + " VALUES (%s, %s, %s, %s, %s, %s, %s)", + ( + parent_taxon_id, + ncbi_taxon_id, + rank, + genetic_code, + mito_genetic_code, + left_value, + right_value, + ), + ) + + taxon_id = self.adaptor.last_id("taxon") + + # Record the scientific name, common name, etc + for name_class, name in species_names: + self.adaptor.execute( + "INSERT INTO taxon_name(taxon_id, name, name_class)" + " VALUES (%s, %s, %s)", + (taxon_id, name[:255], name_class), + ) + return taxon_id + + def _get_taxon_id_from_ncbi_lineage(self, taxonomic_lineage): + """Recursive method to get taxon ID from NCBI lineage (PRIVATE). + + Arguments: + - taxonomic_lineage - list of taxonomy dictionaries from Bio.Entrez + + First dictionary in list is the taxonomy root, highest would be + the species. Each dictionary includes: + + - TaxID (string, NCBI taxon id) + - Rank (string, e.g. "species", "genus", ..., "phylum", ...) + - ScientificName (string) + + (and that is all at the time of writing) + + This method will record all the lineage given, returning the taxon id + (database key, not NCBI taxon id) of the final entry (the species). + """ + ncbi_taxon_id = int(taxonomic_lineage[-1]["TaxId"]) + left_value = None + right_value = None + parent_left_value = None + parent_right_value = None + # Is this in the database already? Check the taxon table... + rows = self.adaptor.execute_and_fetchall( + "SELECT taxon_id, left_value, right_value FROM taxon" + " WHERE ncbi_taxon_id=%s" % ncbi_taxon_id + ) + if rows: + # we could verify that the Scientific Name etc in the database + # is the same and update it or print a warning if not... + if len(rows) != 1: + raise ValueError(f"Expected 1 response, got {len(rows)}") + return rows[0] + + # We have to record this. + if len(taxonomic_lineage) > 1: + # Use recursion to find out the taxon id (database key) of the + # parent. + ( + parent_taxon_id, + parent_left_value, + parent_right_value, + ) = self._get_taxon_id_from_ncbi_lineage(taxonomic_lineage[:-1]) + left_value = parent_right_value + right_value = parent_right_value + 1 + if not isinstance(parent_taxon_id, int): + raise ValueError( + f"Expected parent_taxon_id to be an int, got {parent_taxon_id}" + ) + else: + # we have reached the top of the lineage but no current taxonomy + # id has been found + parent_taxon_id = None + left_value = self.adaptor.execute_one("SELECT MAX(left_value) FROM taxon")[ + 0 + ] + if not left_value: + left_value = 0 + + right_value = left_value + 1 + + self._update_left_right_taxon_values(left_value) + + # INSERT new taxon + rank = str(taxonomic_lineage[-1].get("Rank")) + self.adaptor.execute( + "INSERT INTO taxon(ncbi_taxon_id, parent_taxon_id, node_rank, " + "left_value, right_value) VALUES (%s, %s, %s, %s, %s)", + (ncbi_taxon_id, parent_taxon_id, rank, left_value, right_value), + ) + + taxon_id = self.adaptor.last_id("taxon") + # assert isinstance(taxon_id, int), repr(taxon_id) + # ... and its name in taxon_name + scientific_name = taxonomic_lineage[-1].get("ScientificName") + if scientific_name: + self.adaptor.execute( + "INSERT INTO taxon_name(taxon_id, name, name_class) " + "VALUES (%s, %s, 'scientific name')", + (taxon_id, scientific_name[:255]), + ) + return taxon_id, left_value, right_value + + def _load_bioentry_table(self, record): + """Fill the bioentry table with sequence information (PRIVATE). + + Arguments: + - record - SeqRecord object to add to the database. + + """ + # get the pertinent info and insert it + + if record.id.count(".") == 1: # try to get a version from the id + # This assumes the string is something like "XXXXXXXX.123" + accession, version = record.id.split(".") + try: + version = int(version) + except ValueError: + accession = record.id + version = 0 + else: # otherwise just use a version of 0 + accession = record.id + version = 0 + + if ( + "accessions" in record.annotations + and isinstance(record.annotations["accessions"], list) + and record.annotations["accessions"] + ): + # Take the first accession (one if there is more than one) + accession = record.annotations["accessions"][0] + + # Find the taxon id (this is not just the NCBI Taxon ID) + # NOTE - If the species isn't defined in the taxon table, + # a new minimal entry is created. + taxon_id = self._get_taxon_id(record) + + if "gi" in record.annotations: + identifier = record.annotations["gi"] + else: + identifier = record.id + + # Allow description and division to default to NULL as in BioPerl. + description = getattr(record, "description", None) + division = record.annotations.get("data_file_division") + + sql = """ + INSERT INTO bioentry ( + biodatabase_id, + taxon_id, + name, + accession, + identifier, + division, + description, + version) + VALUES ( + %s, + %s, + %s, + %s, + %s, + %s, + %s, + %s)""" + # print(self.dbid, taxon_id, record.name, accession, identifier, \ + # division, description, version) + self.adaptor.execute( + sql, + ( + self.dbid, + taxon_id, + record.name, + accession, + identifier, + division, + description, + version, + ), + ) + # now retrieve the id for the bioentry + return self.adaptor.last_id("bioentry") + + def _load_bioentry_date(self, record, bioentry_id): + """Add the effective date of the entry into the database (PRIVATE). + + record - a SeqRecord object with an annotated date + bioentry_id - corresponding database identifier + """ + # dates are GenBank style, like: + # 14-SEP-2000 + date = record.annotations.get("date", strftime("%d-%b-%Y", gmtime()).upper()) + if isinstance(date, list): + date = date[0] + annotation_tags_id = self._get_ontology_id("Annotation Tags") + date_id = self._get_term_id("date_changed", annotation_tags_id) + sql = ( + "INSERT INTO bioentry_qualifier_value" + ' (bioentry_id, term_id, value, "rank")' + " VALUES (%s, %s, %s, 1)" + ) + self.adaptor.execute(sql, (bioentry_id, date_id, date)) + + def _load_biosequence(self, record, bioentry_id): + """Record SeqRecord's sequence and alphabet in DB (PRIVATE). + + Arguments: + - record - a SeqRecord object with a seq property + - bioentry_id - corresponding database identifier + + """ + if record.seq is None: + # The biosequence table entry is optional, so if we haven't + # got a sequence, we don't need to write to the table. + return + + molecule_type = record.annotations.get("molecule_type", "") + if "DNA" in molecule_type: + alphabet = "dna" + elif "RNA" in molecule_type: + alphabet = "rna" + elif "protein" in molecule_type: + alphabet = "protein" + else: + alphabet = "unknown" + + try: + seq_str = str(record.seq) + except UndefinedSequenceError: + seq_str = None + + sql = ( + "INSERT INTO biosequence (bioentry_id, version, " + "length, seq, alphabet) " + "VALUES (%s, 0, %s, %s, %s)" + ) + self.adaptor.execute(sql, (bioentry_id, len(record.seq), seq_str, alphabet)) + + def _load_comment(self, record, bioentry_id): + """Record a SeqRecord's annotated comment in the database (PRIVATE). + + Arguments: + - record - a SeqRecord object with an annotated comment + - bioentry_id - corresponding database identifier + + """ + comments = record.annotations.get("comment") + if not comments: + return + if not isinstance(comments, list): + # It should be a string then... + comments = [comments] + + for index, comment in enumerate(comments): + comment = comment.replace("\n", " ") + # TODO - Store each line as a separate entry? This would preserve + # the newlines, but we should check BioPerl etc to be consistent. + sql = ( + 'INSERT INTO comment (bioentry_id, comment_text, "rank")' + " VALUES (%s, %s, %s)" + ) + self.adaptor.execute(sql, (bioentry_id, comment, index + 1)) + + def _load_annotations(self, record, bioentry_id): + """Record a SeqRecord's misc annotations in the database (PRIVATE). + + The annotation strings are recorded in the bioentry_qualifier_value + table, except for special cases like the reference, comment and + taxonomy which are handled with their own tables. + + Arguments: + - record - a SeqRecord object with an annotations dictionary + - bioentry_id - corresponding database identifier + + """ + mono_sql = ( + "INSERT INTO bioentry_qualifier_value" + "(bioentry_id, term_id, value)" + " VALUES (%s, %s, %s)" + ) + many_sql = ( + "INSERT INTO bioentry_qualifier_value" + '(bioentry_id, term_id, value, "rank")' + " VALUES (%s, %s, %s, %s)" + ) + tag_ontology_id = self._get_ontology_id("Annotation Tags") + for key, value in record.annotations.items(): + if key in ["molecule_type", "references", "comment", "ncbi_taxid", "date"]: + # Handled separately + continue + term_id = self._get_term_id(key, ontology_id=tag_ontology_id) + if isinstance(value, (list, tuple)): + rank = 0 + for entry in value: + if isinstance(entry, (str, int)): + # Easy case + rank += 1 + self.adaptor.execute( + many_sql, (bioentry_id, term_id, str(entry), rank) + ) + else: + pass + elif isinstance(value, (str, int)): + # Have a simple single entry, leave rank as the DB default + self.adaptor.execute(mono_sql, (bioentry_id, term_id, str(value))) + else: + pass + # print("Ignoring annotation '%s' entry of type '%s'" \ + # % (key, type(value))) + + def _load_reference(self, reference, rank, bioentry_id): + """Record SeqRecord's annotated references in the database (PRIVATE). + + Arguments: + - record - a SeqRecord object with annotated references + - bioentry_id - corresponding database identifier + + """ + refs = None + if reference.medline_id: + refs = self.adaptor.execute_and_fetch_col0( + "SELECT reference_id" + " FROM reference JOIN dbxref USING (dbxref_id)" + " WHERE dbname = 'MEDLINE' AND accession = %s", + (reference.medline_id,), + ) + if not refs and reference.pubmed_id: + refs = self.adaptor.execute_and_fetch_col0( + "SELECT reference_id" + " FROM reference JOIN dbxref USING (dbxref_id)" + " WHERE dbname = 'PUBMED' AND accession = %s", + (reference.pubmed_id,), + ) + if not refs: + s = [] + for f in reference.authors, reference.title, reference.journal: + s.append(f or "") + crc = crc64("".join(s)) + refs = self.adaptor.execute_and_fetch_col0( + "SELECT reference_id FROM reference WHERE crc = %s", (crc,) + ) + if not refs: + if reference.medline_id: + dbxref_id = self._add_dbxref("MEDLINE", reference.medline_id, 0) + elif reference.pubmed_id: + dbxref_id = self._add_dbxref("PUBMED", reference.pubmed_id, 0) + else: + dbxref_id = None + authors = reference.authors or None + title = reference.title or None + # The location/journal field cannot be Null, so default + # to an empty string rather than None: + journal = reference.journal or "" + self.adaptor.execute( + "INSERT INTO reference (dbxref_id, location," + " title, authors, crc)" + " VALUES (%s, %s, %s, %s, %s)", + (dbxref_id, journal, title, authors, crc), + ) + reference_id = self.adaptor.last_id("reference") + else: + reference_id = refs[0] + + if reference.location: + start = 1 + int(str(reference.location[0].start)) + end = int(str(reference.location[0].end)) + else: + start = None + end = None + + sql = ( + "INSERT INTO bioentry_reference (bioentry_id, reference_id," + ' start_pos, end_pos, "rank") VALUES (%s, %s, %s, %s, %s)' + ) + self.adaptor.execute(sql, (bioentry_id, reference_id, start, end, rank + 1)) + + def _load_seqfeature(self, feature, feature_rank, bioentry_id): + """Load a biopython SeqFeature into the database (PRIVATE).""" + # records loaded from a gff file using BCBio.GFF will contain value + # of 2nd column of the gff as a feature qualifier. The BioSQL wiki + # suggests that the source should not go in with the other feature + # mappings but instead be put in the term table + # (http://www.biosql.org/wiki/Annotation_Mapping) + try: + source = feature.qualifiers["source"] + if isinstance(source, list): + source = source[0] + seqfeature_id = self._load_seqfeature_basic( + feature.type, feature_rank, bioentry_id, source=source + ) + except KeyError: + seqfeature_id = self._load_seqfeature_basic( + feature.type, feature_rank, bioentry_id + ) + + self._load_seqfeature_locations(feature, seqfeature_id) + self._load_seqfeature_qualifiers(feature.qualifiers, seqfeature_id) + + def _load_seqfeature_basic( + self, feature_type, feature_rank, bioentry_id, source="EMBL/GenBank/SwissProt" + ): + """Load the first tables of a seqfeature and returns the id (PRIVATE). + + This loads the "key" of the seqfeature (ie. CDS, gene) and + the basic seqfeature table itself. + """ + ontology_id = self._get_ontology_id("SeqFeature Keys") + seqfeature_key_id = self._get_term_id(feature_type, ontology_id=ontology_id) + source_cat_id = self._get_ontology_id("SeqFeature Sources") + source_term_id = self._get_term_id(source, ontology_id=source_cat_id) + + sql = ( + "INSERT INTO seqfeature (bioentry_id, type_term_id, " + 'source_term_id, "rank") VALUES (%s, %s, %s, %s)' + ) + self.adaptor.execute( + sql, (bioentry_id, seqfeature_key_id, source_term_id, feature_rank + 1) + ) + return self.adaptor.last_id("seqfeature") + + def _load_seqfeature_locations(self, feature, seqfeature_id): + """Load all of the locations for a SeqFeature into tables (PRIVATE). + + This adds the locations related to the SeqFeature into the + seqfeature_location table. Fuzzies are not handled right now. + For a simple location, ie (1..2), we have a single table row + with seq_start = 1, seq_end = 2, location_rank = 1. + + For split locations, ie (1..2, 3..4, 5..6) we would have three + row tables with:: + + start = 1, end = 2, rank = 1 + start = 3, end = 4, rank = 2 + start = 5, end = 6, rank = 3 + + """ + # TODO - Record an ontology for the locations (using location.term_id) + # which for now as in BioPerl we leave defaulting to NULL. + try: + if feature.location.operator != "join": + # e.g. order locations... we don't record "order" so it + # will become a "join" on reloading. What does BioPerl do? + import warnings + + from Bio import BiopythonWarning + + warnings.warn( + "%s location operators are not fully supported" + % feature.location_operator, + BiopythonWarning, + ) + except AttributeError: + pass + # This will be a list of length one for a SimpleLocation: + parts = feature.location.parts + if parts and {loc.strand for loc in parts} == {-1}: + # To mimic prior behaviour of Biopython+BioSQL, reverse order + parts = parts[::-1] + # TODO - Check what BioPerl does; see also BioSeq.py code + for rank, loc in enumerate(parts): + self._insert_location(loc, rank + 1, seqfeature_id) + + def _insert_location(self, location, rank, seqfeature_id): + """Add SeqFeature location to seqfeature_location table (PRIVATE). + + TODO - Add location operator to location_qualifier_value? + """ + # convert biopython locations to the 1-based location system + # used in bioSQL + # XXX This could also handle fuzzies + + try: + start = int(location.start) + 1 + except TypeError: + # Handle SwissProt unknown position (?) + if isinstance(location.start, UnknownPosition): + start = None + else: + raise + + try: + end = int(location.end) + except TypeError: + # Handle SwissProt unknown position (?) + if isinstance(location.end, UnknownPosition): + end = None + else: + raise + + # Biopython uses None when we don't know strand information but + # BioSQL requires something (non null) and sets this as zero + # So we'll use the strand or 0 if Biopython spits out None + strand = location.strand or 0 + + # TODO - Record an ontology term for the location (location.term_id) + # which for now like BioPerl we'll leave as NULL. + # This might allow us to record "between" positions properly, but I + # don't really see how it could work for before/after fuzzy positions + loc_term_id = None + + if location.ref: + # sub_feature remote locations when they are in the same db as the + # current record do not have a value for ref_db, which SeqFeature + # object stores as None. BioSQL schema requires a varchar and is + # not NULL + dbxref_id = self._get_dbxref_id(location.ref_db or "", location.ref) + else: + dbxref_id = None + + sql = ( + "INSERT INTO location (seqfeature_id, dbxref_id, term_id," + 'start_pos, end_pos, strand, "rank") ' + "VALUES (%s, %s, %s, %s, %s, %s, %s)" + ) + self.adaptor.execute( + sql, (seqfeature_id, dbxref_id, loc_term_id, start, end, strand, rank) + ) + + """ + # See Bug 2677 + # TODO - Record the location_operator (e.g. "join" or "order") + # using the location_qualifier_value table (which we and BioPerl + # have historically left empty). + # Note this will need an ontology term for the location qualifier + # (location_qualifier_value.term_id) for which oddly the schema + # does not allow NULL. + if feature.location_operator: + #e.g. "join" (common), + #or "order" (see Tests/GenBank/protein_refseq2.gb) + location_id = self.adaptor.last_id('location') + loc_qual_term_id = None # Not allowed in BioSQL v1.0.1 + sql = ("INSERT INTO location_qualifier_value" + "(location_id, term_id, value) " + "VALUES (%s, %s, %s)") + self.adaptor.execute(sql, (location_id, loc_qual_term_id, + feature.location_operator)) + """ + + def _load_seqfeature_qualifiers(self, qualifiers, seqfeature_id): + """Insert feature's (key, value) pair qualifiers (PRIVATE). + + Qualifiers should be a dictionary of the form:: + + {key : [value1, value2]} + + """ + tag_ontology_id = self._get_ontology_id("Annotation Tags") + for qualifier_key in qualifiers: + # Treat db_xref qualifiers differently to sequence annotation + # qualifiers by populating the seqfeature_dbxref and dbxref + # tables. Other qualifiers go into the seqfeature_qualifier_value + # and (if new) term tables. + if qualifier_key != "db_xref": + qualifier_key_id = self._get_term_id( + qualifier_key, ontology_id=tag_ontology_id + ) + # now add all of the values to their table + entries = qualifiers[qualifier_key] + if not isinstance(entries, list): + # Could be a plain string, or an int or a float. + # However, we exect a list of strings here. + entries = [entries] + for qual_value_rank in range(len(entries)): + qualifier_value = entries[qual_value_rank] + sql = ( + "INSERT INTO seqfeature_qualifier_value " + ' (seqfeature_id, term_id, "rank", value) VALUES' + " (%s, %s, %s, %s)" + ) + self.adaptor.execute( + sql, + ( + seqfeature_id, + qualifier_key_id, + qual_value_rank + 1, + qualifier_value, + ), + ) + else: + # The dbxref_id qualifier/value sets go into the dbxref table + # as dbname, accession, version tuples, with dbxref.dbxref_id + # being automatically assigned, and into the seqfeature_dbxref + # table as seqfeature_id, dbxref_id, and rank tuples + self._load_seqfeature_dbxref(qualifiers[qualifier_key], seqfeature_id) + + def _load_seqfeature_dbxref(self, dbxrefs, seqfeature_id): + """Add SeqFeature's DB cross-references to the database (PRIVATE). + + Arguments: + - dbxrefs - List, dbxref data from the source file in the + format : + - seqfeature_id - Int, the identifier for the seqfeature in the + seqfeature table + + Insert dbxref qualifier data for a seqfeature into the + seqfeature_dbxref and, if required, dbxref tables. + The dbxref_id qualifier/value sets go into the dbxref table + as dbname, accession, version tuples, with dbxref.dbxref_id + being automatically assigned, and into the seqfeature_dbxref + table as seqfeature_id, dbxref_id, and rank tuples. + """ + # NOTE - In older versions of Biopython, we would map the GenBank + # db_xref "name", for example "GI" to "GeneIndex", and give a warning + # for any unknown terms. This was a long term maintenance problem, + # and differed from BioPerl and BioJava's implementation. See bug 2405 + for rank, value in enumerate(dbxrefs): + # Split the DB:accession format string at colons. We have to + # account for multiple-line and multiple-accession entries + try: + dbxref_data = value.replace(" ", "").replace("\n", "").split(":") + db = dbxref_data[0] + accessions = dbxref_data[1:] + except Exception: + raise ValueError(f"Parsing of db_xref failed: '{value}'") from None + # Loop over all the grabbed accessions, and attempt to fill the + # table + for accession in accessions: + # Get the dbxref_id value for the dbxref data + dbxref_id = self._get_dbxref_id(db, accession) + # Insert the seqfeature_dbxref data + self._get_seqfeature_dbxref(seqfeature_id, dbxref_id, rank + 1) + + def _get_dbxref_id(self, db, accession): + """Get DB cross-reference for accession (PRIVATE). + + Arguments: + - db - String, the name of the external database containing + the accession number + - accession - String, the accession of the dbxref data + + Finds and returns the dbxref_id for the passed data. The method + attempts to find an existing record first, and inserts the data + if there is no record. + """ + # Check for an existing record + sql = "SELECT dbxref_id FROM dbxref WHERE dbname = %s AND accession = %s" + dbxref_id = self.adaptor.execute_and_fetch_col0(sql, (db, accession)) + # If there was a record, return the dbxref_id, else create the + # record and return the created dbxref_id + if dbxref_id: + return dbxref_id[0] + return self._add_dbxref(db, accession, 0) + + def _get_seqfeature_dbxref(self, seqfeature_id, dbxref_id, rank): + """Get DB cross-reference, creating it if needed (PRIVATE). + + Check for a pre-existing seqfeature_dbxref entry with the passed + seqfeature_id and dbxref_id. If one does not exist, insert new + data. + """ + # Check for an existing record + sql = ( + "SELECT seqfeature_id, dbxref_id FROM seqfeature_dbxref " + "WHERE seqfeature_id = %s AND dbxref_id = %s" + ) + result = self.adaptor.execute_and_fetch_col0(sql, (seqfeature_id, dbxref_id)) + # If there was a record, return without executing anything, else create + # the record and return + if result: + return result + return self._add_seqfeature_dbxref(seqfeature_id, dbxref_id, rank) + + def _add_seqfeature_dbxref(self, seqfeature_id, dbxref_id, rank): + """Add DB cross-reference (PRIVATE). + + Insert a seqfeature_dbxref row and return the seqfeature_id and + dbxref_id + """ + sql = ( + "INSERT INTO seqfeature_dbxref " + '(seqfeature_id, dbxref_id, "rank") VALUES' + "(%s, %s, %s)" + ) + self.adaptor.execute(sql, (seqfeature_id, dbxref_id, rank)) + return (seqfeature_id, dbxref_id) + + def _load_dbxrefs(self, record, bioentry_id): + """Load any sequence level cross references into the database (PRIVATE). + + See table bioentry_dbxref. + """ + for rank, value in enumerate(record.dbxrefs): + # Split the DB:accession string at first colon. + # We have to cope with things like: + # "MGD:MGI:892" (db="MGD", accession="MGI:892") + # "GO:GO:123" (db="GO", accession="GO:123") + # + # Annoyingly I have seen the NCBI use both the style + # "GO:GO:123" and "GO:123" in different vintages. + newline_escape_count = value.count("\n") + if newline_escape_count != 0: + raise ValueError( + "Expected a single line in value, got {newline_escape_count}" + ) + try: + db, accession = value.split(":", 1) + db = db.strip() + accession = accession.strip() + except Exception: + raise ValueError(f"Parsing of dbxrefs list failed: '{value}'") from None + # Get the dbxref_id value for the dbxref data + dbxref_id = self._get_dbxref_id(db, accession) + # Insert the bioentry_dbxref data + self._get_bioentry_dbxref(bioentry_id, dbxref_id, rank + 1) + + def _get_bioentry_dbxref(self, bioentry_id, dbxref_id, rank): + """Get pre-existing db-xref, or create and return it (PRIVATE). + + Check for a pre-existing bioentry_dbxref entry with the passed + seqfeature_id and dbxref_id. If one does not exist, insert new + data + """ + # Check for an existing record + sql = ( + "SELECT bioentry_id, dbxref_id FROM bioentry_dbxref " + "WHERE bioentry_id = %s AND dbxref_id = %s" + ) + result = self.adaptor.execute_and_fetch_col0(sql, (bioentry_id, dbxref_id)) + # If there was a record, return without executing anything, else create + # the record and return + if result: + return result + return self._add_bioentry_dbxref(bioentry_id, dbxref_id, rank) + + def _add_bioentry_dbxref(self, bioentry_id, dbxref_id, rank): + """Insert a bioentry_dbxref row (PRIVATE). + + Returns the seqfeature_id and dbxref_id (PRIVATE). + """ + sql = ( + "INSERT INTO bioentry_dbxref " + '(bioentry_id,dbxref_id,"rank") VALUES ' + "(%s, %s, %s)" + ) + self.adaptor.execute(sql, (bioentry_id, dbxref_id, rank)) + return (bioentry_id, dbxref_id) + + +class DatabaseRemover: + """Complement the Loader functionality by fully removing a database. + + This probably isn't really useful for normal purposes, since you + can just do a:: + + DROP DATABASE db_name + + and then recreate the database. But, it's really useful for testing + purposes. + """ + + def __init__(self, adaptor, dbid): + """Initialize with a database id and adaptor connection.""" + self.adaptor = adaptor + self.dbid = dbid + + def remove(self): + """Remove everything related to the given database id.""" + sql = "DELETE FROM bioentry WHERE biodatabase_id = %s" + self.adaptor.execute(sql, (self.dbid,)) + sql = "DELETE FROM biodatabase WHERE biodatabase_id = %s" + self.adaptor.execute(sql, (self.dbid,)) diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/__init__.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8f079d70ededef41ad81cdfefa7ebf05ce2e7b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2008 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Storing and retrieve biological sequences in a BioSQL relational database. + +See: + +- http://biopython.org/wiki/BioSQL +- http://www.biosql.org/ + +""" diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/py.typed b/.venv_haddock/lib/python3.12/site-packages/BioSQL/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/._override.py b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/._override.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/._override.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94f71b99ecefd27e6cf3fd06fc3c0eef5fd73910 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/__init__.py @@ -0,0 +1,239 @@ +# don't import any costly modules +import os +import sys + +report_url = ( + "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml" +) + + +def warn_distutils_present(): + if 'distutils' not in sys.modules: + return + import warnings + + warnings.warn( + "Distutils was imported before Setuptools, but importing Setuptools " + "also replaces the `distutils` module in `sys.modules`. This may lead " + "to undesirable behaviors or errors. To avoid these issues, avoid " + "using distutils directly, ensure that setuptools is installed in the " + "traditional way (e.g. not an editable install), and/or make sure " + "that setuptools is always imported before distutils." + ) + + +def clear_distutils(): + if 'distutils' not in sys.modules: + return + import warnings + + warnings.warn( + "Setuptools is replacing distutils. Support for replacing " + "an already imported distutils is deprecated. In the future, " + "this condition will fail. " + f"Register concerns at {report_url}" + ) + mods = [ + name + for name in sys.modules + if name == "distutils" or name.startswith("distutils.") + ] + for name in mods: + del sys.modules[name] + + +def enabled(): + """ + Allow selection of distutils by environment variable. + """ + which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local') + if which == 'stdlib': + import warnings + + warnings.warn( + "Reliance on distutils from stdlib is deprecated. Users " + "must rely on setuptools to provide the distutils module. " + "Avoid importing distutils or import setuptools first, " + "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. " + f"Register concerns at {report_url}" + ) + return which == 'local' + + +def ensure_local_distutils(): + import importlib + + clear_distutils() + + # With the DistutilsMetaFinder in place, + # perform an import to cause distutils to be + # loaded from setuptools._distutils. Ref #2906. + with shim(): + importlib.import_module('distutils') + + # check that submodules load as expected + core = importlib.import_module('distutils.core') + assert '_distutils' in core.__file__, core.__file__ + assert 'setuptools._distutils.log' not in sys.modules + + +def do_override(): + """ + Ensure that the local copy of distutils is preferred over stdlib. + + See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 + for more motivation. + """ + if enabled(): + warn_distutils_present() + ensure_local_distutils() + + +class _TrivialRe: + def __init__(self, *patterns) -> None: + self._patterns = patterns + + def match(self, string): + return all(pat in string for pat in self._patterns) + + +class DistutilsMetaFinder: + def find_spec(self, fullname, path, target=None): + # optimization: only consider top level modules and those + # found in the CPython test suite. + if path is not None and not fullname.startswith('test.'): + return None + + method_name = 'spec_for_{fullname}'.format(**locals()) + method = getattr(self, method_name, lambda: None) + return method() + + def spec_for_distutils(self): + if self.is_cpython(): + return None + + import importlib + import importlib.abc + import importlib.util + + try: + mod = importlib.import_module('setuptools._distutils') + except Exception: + # There are a couple of cases where setuptools._distutils + # may not be present: + # - An older Setuptools without a local distutils is + # taking precedence. Ref #2957. + # - Path manipulation during sitecustomize removes + # setuptools from the path but only after the hook + # has been loaded. Ref #2980. + # In either case, fall back to stdlib behavior. + return None + + class DistutilsLoader(importlib.abc.Loader): + def create_module(self, spec): + mod.__name__ = 'distutils' + return mod + + def exec_module(self, module): + pass + + return importlib.util.spec_from_loader( + 'distutils', DistutilsLoader(), origin=mod.__file__ + ) + + @staticmethod + def is_cpython(): + """ + Suppress supplying distutils for CPython (build and tests). + Ref #2965 and #3007. + """ + return os.path.isfile('pybuilddir.txt') + + def spec_for_pip(self): + """ + Ensure stdlib distutils when running under pip. + See pypa/pip#8761 for rationale. + """ + if sys.version_info >= (3, 12) or self.pip_imported_during_build(): + return + clear_distutils() + self.spec_for_distutils = lambda: None + + @classmethod + def pip_imported_during_build(cls): + """ + Detect if pip is being imported in a build script. Ref #2355. + """ + import traceback + + return any( + cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None) + ) + + @staticmethod + def frame_file_is_setup(frame): + """ + Return True if the indicated frame suggests a setup.py file. + """ + # some frames may not have __file__ (#2940) + return frame.f_globals.get('__file__', '').endswith('setup.py') + + def spec_for_sensitive_tests(self): + """ + Ensure stdlib distutils when running select tests under CPython. + + python/cpython#91169 + """ + clear_distutils() + self.spec_for_distutils = lambda: None + + sensitive_tests = ( + [ + 'test.test_distutils', + 'test.test_peg_generator', + 'test.test_importlib', + ] + if sys.version_info < (3, 10) + else [ + 'test.test_distutils', + ] + ) + + +for name in DistutilsMetaFinder.sensitive_tests: + setattr( + DistutilsMetaFinder, + f'spec_for_{name}', + DistutilsMetaFinder.spec_for_sensitive_tests, + ) + + +DISTUTILS_FINDER = DistutilsMetaFinder() + + +def add_shim(): + DISTUTILS_FINDER in sys.meta_path or insert_shim() + + +class shim: + def __enter__(self) -> None: + insert_shim() + + def __exit__(self, exc: object, value: object, tb: object) -> None: + _remove_shim() + + +def insert_shim(): + sys.meta_path.insert(0, DISTUTILS_FINDER) + + +def _remove_shim(): + try: + sys.meta_path.remove(DISTUTILS_FINDER) + except ValueError: + pass + + +if sys.version_info < (3, 12): + # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632) + remove_shim = _remove_shim diff --git a/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/override.py b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/override.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc433a4a55e3b41fa31089918fb62096092f89f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_distutils_hack/override.py @@ -0,0 +1 @@ +__import__('_distutils_hack').do_override() diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._basevalidators.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._basevalidators.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._basevalidators.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._colors b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._colors new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._colors differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._data_utils.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._data_utils.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._exceptions.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._exceptions.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._files.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._files.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._files.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._importers.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._importers.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._importers.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._optional_imports.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._optional_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._optional_imports.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._png.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._png.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._png.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._utils.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/._utils.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/basevalidators.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/basevalidators.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7849cc931c24f9741bf1256a28f05fe14d1693 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/basevalidators.py @@ -0,0 +1,2754 @@ +import base64 +import numbers +import textwrap +import uuid +from importlib import import_module +import copy +import io +import re +import sys +import narwhals.stable.v1 as nw + +from _plotly_utils.optional_imports import get_module + + +# back-port of fullmatch from Py3.4+ +def fullmatch(regex, string, flags=0): + """Emulate python-3.4 re.fullmatch().""" + if "pattern" in dir(regex): + regex_string = regex.pattern + else: + regex_string = regex + return re.match("(?:" + regex_string + r")\Z", string, flags=flags) + + +def to_non_numpy_type(np, v): + """ + Convert a numpy scalar value to a native Python type. + Calling .item() on a datetime64[ns] value returns an integer, since + Python datetimes only support microsecond precision. So we cast + datetime64[ns] to datetime64[us] to ensure it remains a datetime. + + Should only be used in contexts where we already know `np` is defined. + """ + if hasattr(v, "dtype") and v.dtype == np.dtype("datetime64[ns]"): + return v.astype("datetime64[us]").item() + return v.item() + + +# Utility functions +# ----------------- +def to_scalar_or_list(v): + # Handle the case where 'v' is a non-native scalar-like type, + # such as numpy.float32. Without this case, the object might be + # considered numpy-convertable and therefore promoted to a + # 0-dimensional array, but we instead want it converted to a + # Python native scalar type ('float' in the example above). + # We explicitly check if is has the 'item' method, which conventionally + # converts these types to native scalars. + np = get_module("numpy", should_load=False) + pd = get_module("pandas", should_load=False) + if np and np.isscalar(v) and hasattr(v, "item"): + return to_non_numpy_type(np, v) + if isinstance(v, (list, tuple)): + return [to_scalar_or_list(e) for e in v] + elif np and isinstance(v, np.ndarray): + if v.ndim == 0: + return to_non_numpy_type(np, v) + return [to_scalar_or_list(e) for e in v] + elif pd and isinstance(v, (pd.Series, pd.Index)): + return [to_scalar_or_list(e) for e in v] + elif is_numpy_convertable(v): + return to_scalar_or_list(np.array(v)) + else: + return v + + +def copy_to_readonly_numpy_array(v, kind=None, force_numeric=False): + """ + Convert an array-like value into a read-only numpy array + + Parameters + ---------- + v : array like + Array like value (list, tuple, numpy array, pandas series, etc.) + kind : str or tuple of str + If specified, the numpy dtype kind (or kinds) that the array should + have, or be converted to if possible. + If not specified then let numpy infer the datatype + force_numeric : bool + If true, raise an exception if the resulting numpy array does not + have a numeric dtype (i.e. dtype.kind not in ['u', 'i', 'f']) + Returns + ------- + np.ndarray + Numpy array with the 'WRITEABLE' flag set to False + """ + np = get_module("numpy") + + assert np is not None + + # ### Process kind ### + if not kind: + kind = () + elif isinstance(kind, str): + kind = (kind,) + + first_kind = kind[0] if kind else None + + # u: unsigned int, i: signed int, f: float + numeric_kinds = {"u", "i", "f"} + kind_default_dtypes = { + "u": "uint32", + "i": "int32", + "f": "float64", + "O": "object", + } + + # With `pass_through=True`, the original object will be returned if unable to convert + # to a Narwhals DataFrame or Series. + v = nw.from_native(v, allow_series=True, pass_through=True) + + if isinstance(v, nw.Series): + if v.dtype == nw.Datetime and v.dtype.time_zone is not None: + # Remove time zone so that local time is displayed + v = v.dt.replace_time_zone(None).to_numpy() + else: + v = v.to_numpy() + elif isinstance(v, nw.DataFrame): + schema = v.schema + overrides = {} + for key, val in schema.items(): + if val == nw.Datetime and val.time_zone is not None: + # Remove time zone so that local time is displayed + overrides[key] = nw.col(key).dt.replace_time_zone(None) + if overrides: + v = v.with_columns(**overrides) + v = v.to_numpy() + + if not isinstance(v, np.ndarray): + # v has its own logic on how to convert itself into a numpy array + if is_numpy_convertable(v): + return copy_to_readonly_numpy_array( + np.array(v), kind=kind, force_numeric=force_numeric + ) + else: + # v is not homogenous array + v_list = [to_scalar_or_list(e) for e in v] + + # Lookup dtype for requested kind, if any + dtype = kind_default_dtypes.get(first_kind, None) + + # construct new array from list + new_v = np.array(v_list, order="C", dtype=dtype) + elif v.dtype.kind in numeric_kinds: + # v is a homogenous numeric array + if kind and v.dtype.kind not in kind: + # Kind(s) were specified and this array doesn't match + # Convert to the default dtype for the first kind + dtype = kind_default_dtypes.get(first_kind, None) + new_v = np.ascontiguousarray(v.astype(dtype)) + else: + # Either no kind was requested or requested kind is satisfied + new_v = np.ascontiguousarray(v.copy()) + else: + # v is a non-numeric homogenous array + new_v = v.copy() + + # Handle force numeric param + # -------------------------- + if force_numeric and new_v.dtype.kind not in numeric_kinds: + raise ValueError( + "Input value is not numeric and force_numeric parameter set to True" + ) + + if "U" not in kind: + # Force non-numeric arrays to have object type + # -------------------------------------------- + # Here we make sure that non-numeric arrays have the object + # datatype. This works around cases like np.array([1, 2, '3']) where + # numpy converts the integers to strings and returns array of dtype + # ' 'x' for anchor-style + # enumeration properties + self.regex_replacements = [] + + # Loop over enumeration values + # ---------------------------- + # Look for regular expressions + for v in self.values: + if v and isinstance(v, str) and v[0] == "/" and v[-1] == "/" and len(v) > 1: + # String is a regex with leading and trailing '/' character + regex_str = v[1:-1] + self.val_regexs.append(re.compile(regex_str)) + self.regex_replacements.append( + EnumeratedValidator.build_regex_replacement(regex_str) + ) + else: + self.val_regexs.append(None) + self.regex_replacements.append(None) + + def __deepcopy__(self, memodict={}): + """ + A custom deepcopy method is needed here because compiled regex + objects don't support deepcopy + """ + cls = self.__class__ + return cls(self.plotly_name, self.parent_name, values=self.values) + + @staticmethod + def build_regex_replacement(regex_str): + # Example: regex_str == r"^y([2-9]|[1-9][0-9]+)?$" + # + # When we see a regular expression like the one above, we want to + # build regular expression replacement params that will remove a + # suffix of 1 from the input string ('y1' -> 'y' in this example) + # + # Why?: Regular expressions like this one are used in enumeration + # properties that refer to subplotids (e.g. layout.annotation.xref) + # The regular expressions forbid suffixes of 1, like 'x1'. But we + # want to accept 'x1' and coerce it into 'x' + # + # To be cautious, we only perform this conversion for enumerated + # values that match the anchor-style regex + match = re.match( + r"\^(\w)\(\[2\-9\]\|\[1\-9\]\[0\-9\]\+\)\?\( domain\)\?\$", regex_str + ) + + if match: + anchor_char = match.group(1) + return "^" + anchor_char + "1$", anchor_char + else: + return None + + def perform_replacemenet(self, v): + """ + Return v with any applicable regex replacements applied + """ + if isinstance(v, str): + for repl_args in self.regex_replacements: + if repl_args: + v = re.sub(repl_args[0], repl_args[1], v) + + return v + + def description(self): + # Separate regular values from regular expressions + enum_vals = [] + enum_regexs = [] + for v, regex in zip(self.values, self.val_regexs): + if regex is not None: + enum_regexs.append(regex.pattern) + else: + enum_vals.append(v) + desc = """\ + The '{name}' property is an enumeration that may be specified as:""".format( + name=self.plotly_name + ) + + if enum_vals: + enum_vals_str = "\n".join( + textwrap.wrap( + repr(enum_vals), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + ) + ) + + desc = ( + desc + + """ + - One of the following enumeration values: +{enum_vals_str}""".format(enum_vals_str=enum_vals_str) + ) + + if enum_regexs: + enum_regexs_str = "\n".join( + textwrap.wrap( + repr(enum_regexs), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + ) + ) + + desc = ( + desc + + """ + - A string that matches one of the following regular expressions: +{enum_regexs_str}""".format(enum_regexs_str=enum_regexs_str) + ) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def in_values(self, e): + """ + Return whether a value matches one of the enumeration options + """ + is_str = isinstance(e, str) + for v, regex in zip(self.values, self.val_regexs): + if is_str and regex: + in_values = fullmatch(regex, e) is not None + # in_values = regex.fullmatch(e) is not None + else: + in_values = e == v + + if in_values: + return True + + return False + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_array(v): + v_replaced = [self.perform_replacemenet(v_el) for v_el in v] + + invalid_els = [e for e in v_replaced if (not self.in_values(e))] + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + if is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(v) + else: + v = to_scalar_or_list(v) + else: + v = self.perform_replacemenet(v) + if not self.in_values(v): + self.raise_invalid_val(v) + return v + + +class BooleanValidator(BaseValidator): + """ + "boolean": { + "description": "A boolean (true/false) value.", + "requiredOpts": [], + "otherOpts": [ + "arrayOk", + "dflt" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, array_ok=False, **kwargs): + super(BooleanValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a boolean and must be specified as: + - A boolean value: True or False""".format(plotly_name=self.plotly_name) + if self.array_ok: + desc += """ + - A tuple or list of the above""" + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_simple_array(v): + invalid_els = [e for e in v if not isinstance(e, bool)] + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + v = to_scalar_or_list(v) + elif not isinstance(v, bool): + self.raise_invalid_val(v) + + return v + + +class SrcValidator(BaseValidator): + def __init__(self, plotly_name, parent_name, **kwargs): + super(SrcValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.chart_studio = get_module("chart_studio") + + def description(self): + return """\ + The '{plotly_name}' property must be specified as a string or + as a plotly.grid_objs.Column object""".format(plotly_name=self.plotly_name) + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif isinstance(v, str): + pass + elif self.chart_studio and isinstance(v, self.chart_studio.grid_objs.Column): + # Convert to id string + v = v.id + else: + self.raise_invalid_val(v) + + return v + + +class NumberValidator(BaseValidator): + """ + "number": { + "description": "A number or a numeric value (e.g. a number + inside a string). When applicable, values + greater (less) than `max` (`min`) are coerced to + the `dflt`.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "min", + "max", + "arrayOk" + ] + }, + """ + + def __init__( + self, plotly_name, parent_name, min=None, max=None, array_ok=False, **kwargs + ): + super(NumberValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Handle min + if min is None and max is not None: + # Max was specified, so make min -inf + self.min_val = float("-inf") + else: + self.min_val = min + + # Handle max + if max is None and min is not None: + # Min was specified, so make min inf + self.max_val = float("inf") + else: + self.max_val = max + + if min is not None or max is not None: + self.has_min_max = True + else: + self.has_min_max = False + + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a number and may be specified as:""".format( + plotly_name=self.plotly_name + ) + + if not self.has_min_max: + desc = ( + desc + + """ + - An int or float""" + ) + + else: + desc = ( + desc + + """ + - An int or float in the interval [{min_val}, {max_val}]""".format( + min_val=self.min_val, max_val=self.max_val + ) + ) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + np = get_module("numpy") + try: + v_array = copy_to_readonly_numpy_array(v, force_numeric=True) + except (ValueError, TypeError, OverflowError): + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + v_valid = np.logical_and( + self.min_val <= v_array, v_array <= self.max_val + ) + + if not np.all(v_valid): + # Grab up to the first 10 invalid values + v_invalid = np.logical_not(v_valid) + some_invalid_els = np.array(v, dtype="object")[v_invalid][ + :10 + ].tolist() + + self.raise_invalid_elements(some_invalid_els) + + v = v_array # Always numeric numpy array + elif self.array_ok and is_simple_array(v): + # Check numeric + invalid_els = [e for e in v if not isinstance(e, numbers.Number)] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + # Check min/max + if self.has_min_max: + invalid_els = [e for e in v if not (self.min_val <= e <= self.max_val)] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + v = to_scalar_or_list(v) + else: + # Check numeric + if not isinstance(v, numbers.Number): + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + if not (self.min_val <= v <= self.max_val): + self.raise_invalid_val(v) + return v + + +class IntegerValidator(BaseValidator): + """ + "integer": { + "description": "An integer or an integer inside a string. When + applicable, values greater (less) than `max` + (`min`) are coerced to the `dflt`.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "min", + "max", + "extras", + "arrayOk" + ] + }, + """ + + def __init__( + self, + plotly_name, + parent_name, + min=None, + max=None, + extras=None, + array_ok=False, + **kwargs, + ): + super(IntegerValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Handle min + if min is None and max is not None: + # Max was specified, so make min -inf + self.min_val = -sys.maxsize - 1 + else: + self.min_val = min + + # Handle max + if max is None and min is not None: + # Min was specified, so make min inf + self.max_val = sys.maxsize + else: + self.max_val = max + + if min is not None or max is not None: + self.has_min_max = True + else: + self.has_min_max = False + + self.extras = extras if extras is not None else [] + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a integer and may be specified as:""".format( + plotly_name=self.plotly_name + ) + + if not self.has_min_max: + desc = ( + desc + + """ + - An int (or float that will be cast to an int)""" + ) + else: + desc = desc + ( + """ + - An int (or float that will be cast to an int) + in the interval [{min_val}, {max_val}]""".format( + min_val=self.min_val, max_val=self.max_val + ) + ) + + # Extras + if self.extras: + desc = desc + ( + """ + OR exactly one of {extras} (e.g. '{eg_extra}')""" + ).format(extras=self.extras, eg_extra=self.extras[-1]) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif v in self.extras: + return v + elif self.array_ok and is_homogeneous_array(v): + np = get_module("numpy") + v_array = copy_to_readonly_numpy_array( + v, kind=("i", "u"), force_numeric=True + ) + + if v_array.dtype.kind not in ["i", "u"]: + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + v_valid = np.logical_and( + self.min_val <= v_array, v_array <= self.max_val + ) + + if not np.all(v_valid): + # Grab up to the first 10 invalid values + v_invalid = np.logical_not(v_valid) + some_invalid_els = np.array(v, dtype="object")[v_invalid][ + :10 + ].tolist() + self.raise_invalid_elements(some_invalid_els) + + v = v_array + elif self.array_ok and is_simple_array(v): + # Check integer type + invalid_els = [ + e for e in v if not isinstance(e, int) and e not in self.extras + ] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + # Check min/max + if self.has_min_max: + invalid_els = [ + e + for e in v + if not (isinstance(e, int) and self.min_val <= e <= self.max_val) + and e not in self.extras + ] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + v = to_scalar_or_list(v) + else: + # Check int + if not isinstance(v, int): + # don't let int() cast strings to ints + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + if not (self.min_val <= v <= self.max_val): + self.raise_invalid_val(v) + + return v + + +class StringValidator(BaseValidator): + """ + "string": { + "description": "A string value. Numbers are converted to strings + except for attributes with `strict` set to true.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "noBlank", + "strict", + "arrayOk", + "values" + ] + }, + """ + + def __init__( + self, + plotly_name, + parent_name, + no_blank=False, + strict=False, + array_ok=False, + values=None, + **kwargs, + ): + super(StringValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.no_blank = no_blank + self.strict = strict + self.array_ok = array_ok + self.values = values + + @staticmethod + def to_str_or_unicode_or_none(v): + """ + Convert a value to a string if it's not None, a string, + or a unicode (on Python 2). + """ + if v is None or isinstance(v, str): + return v + else: + return str(v) + + def description(self): + desc = """\ + The '{plotly_name}' property is a string and must be specified as:""".format( + plotly_name=self.plotly_name + ) + + if self.no_blank: + desc = ( + desc + + """ + - A non-empty string""" + ) + elif self.values: + valid_str = "\n".join( + textwrap.wrap( + repr(self.values), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + ) + ) + + desc = ( + desc + + """ + - One of the following strings: +{valid_str}""".format(valid_str=valid_str) + ) + else: + desc = ( + desc + + """ + - A string""" + ) + + if not self.strict: + desc = ( + desc + + """ + - A number that will be converted to a string""" + ) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_array(v): + # If strict, make sure all elements are strings. + if self.strict: + invalid_els = [e for e in v if not isinstance(e, str)] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + if is_homogeneous_array(v): + np = get_module("numpy") + + # If not strict, let numpy cast elements to strings + v = copy_to_readonly_numpy_array(v, kind="U") + + # Check no_blank + if self.no_blank: + invalid_els = v[v == ""][:10].tolist() + if invalid_els: + self.raise_invalid_elements(invalid_els) + + # Check values + if self.values: + invalid_inds = np.logical_not(np.isin(v, self.values)) + invalid_els = v[invalid_inds][:10].tolist() + if invalid_els: + self.raise_invalid_elements(invalid_els) + elif is_simple_array(v): + if not self.strict: + v = [StringValidator.to_str_or_unicode_or_none(e) for e in v] + + # Check no_blank + if self.no_blank: + invalid_els = [e for e in v if e == ""] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + # Check values + if self.values: + invalid_els = [e for e in v if v not in self.values] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(v) + + else: + if self.strict: + if not isinstance(v, str): + self.raise_invalid_val(v) + else: + if isinstance(v, str): + pass + elif isinstance(v, (int, float)): + # Convert value to a string + v = str(v) + else: + self.raise_invalid_val(v) + + if self.no_blank and len(v) == 0: + self.raise_invalid_val(v) + + if self.values and v not in self.values: + self.raise_invalid_val(v) + + return v + + +class ColorValidator(BaseValidator): + """ + "color": { + "description": "A string describing color. Supported formats: + - hex (e.g. '#d3d3d3') + - rgb (e.g. 'rgb(255, 0, 0)') + - rgba (e.g. 'rgb(255, 0, 0, 0.5)') + - hsl (e.g. 'hsl(0, 100%, 50%)') + - hsv (e.g. 'hsv(0, 100%, 100%)') + - named colors(full list: + http://www.w3.org/TR/css3-color/#svg-color)", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "arrayOk" + ] + }, + """ + + re_hex = re.compile(r"#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})") + re_rgb_etc = re.compile(r"(rgb|hsl|hsv)a?\([\d.]+%?(,[\d.]+%?){2,3}\)") + re_ddk = re.compile(r"var\(\-\-.*\)") + + named_colors = [ + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgrey", + "darkgreen", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "grey", + "green", + "greenyellow", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgrey", + "lightgreen", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "red", + "rosybrown", + "royalblue", + "rebeccapurple", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen", + ] + + def __init__( + self, plotly_name, parent_name, array_ok=False, colorscale_path=None, **kwargs + ): + super(ColorValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.array_ok = array_ok + + # colorscale_path is the path to the colorscale associated with this + # color property, or None if no such colorscale exists. Only colors + # with an associated colorscale may take on numeric values + self.colorscale_path = colorscale_path + + def numbers_allowed(self): + return self.colorscale_path is not None + + def description(self): + valid_color_description = """\ + The '{plotly_name}' property is a color and may be specified as: + - A hex string (e.g. '#ff0000') + - An rgb/rgba string (e.g. 'rgb(255,0,0)') + - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') + - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') + - A named CSS color: see https://plotly.com/python/css-colors/ for a list""".format( + plotly_name=self.plotly_name + ) + + if self.colorscale_path: + valid_color_description = ( + valid_color_description + + """ + - A number that will be interpreted as a color + according to {colorscale_path}""".format(colorscale_path=self.colorscale_path) + ) + + if self.array_ok: + valid_color_description = ( + valid_color_description + + """ + - A list or array of any of the above""" + ) + + return valid_color_description + + def validate_coerce(self, v, should_raise=True): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(v) + if self.numbers_allowed() and v.dtype.kind in ["u", "i", "f"]: + # Numbers are allowed and we have an array of numbers. + # All good + pass + else: + validated_v = [self.validate_coerce(e, should_raise=False) for e in v] + + invalid_els = self.find_invalid_els(v, validated_v) + + if invalid_els and should_raise: + self.raise_invalid_elements(invalid_els) + + # ### Check that elements have valid colors types ### + elif self.numbers_allowed() or invalid_els: + v = copy_to_readonly_numpy_array(validated_v, kind="O") + else: + v = copy_to_readonly_numpy_array(validated_v, kind="U") + elif self.array_ok and is_simple_array(v): + validated_v = [self.validate_coerce(e, should_raise=False) for e in v] + + invalid_els = self.find_invalid_els(v, validated_v) + + if invalid_els and should_raise: + self.raise_invalid_elements(invalid_els) + else: + v = validated_v + else: + # Validate scalar color + validated_v = self.vc_scalar(v) + if validated_v is None and should_raise: + self.raise_invalid_val(v) + + v = validated_v + + return v + + def find_invalid_els(self, orig, validated, invalid_els=None): + """ + Helper method to find invalid elements in orig array. + Elements are invalid if their corresponding element in + the validated array is None. + + This method handles deeply nested list structures + """ + if invalid_els is None: + invalid_els = [] + + for orig_el, validated_el in zip(orig, validated): + if is_array(orig_el): + self.find_invalid_els(orig_el, validated_el, invalid_els) + else: + if validated_el is None: + invalid_els.append(orig_el) + + return invalid_els + + def vc_scalar(self, v): + """Helper to validate/coerce a scalar color""" + return ColorValidator.perform_validate_coerce( + v, allow_number=self.numbers_allowed() + ) + + @staticmethod + def perform_validate_coerce(v, allow_number=None): + """ + Validate, coerce, and return a single color value. If input cannot be + coerced to a valid color then return None. + + Parameters + ---------- + v : number or str + Candidate color value + + allow_number : bool + True if numbers are allowed as colors + + Returns + ------- + number or str or None + """ + + if isinstance(v, numbers.Number) and allow_number: + # If allow_numbers then any number is ok + return v + elif not isinstance(v, str): + # If not allow_numbers then value must be a string + return None + else: + # Remove spaces so regexes don't need to bother with them. + v_normalized = v.replace(" ", "").lower() + + # if ColorValidator.re_hex.fullmatch(v_normalized): + if fullmatch(ColorValidator.re_hex, v_normalized): + # valid hex color (e.g. #f34ab3) + return v + elif fullmatch(ColorValidator.re_rgb_etc, v_normalized): + # elif ColorValidator.re_rgb_etc.fullmatch(v_normalized): + # Valid rgb(a), hsl(a), hsv(a) color + # (e.g. rgba(10, 234, 200, 50%) + return v + elif fullmatch(ColorValidator.re_ddk, v_normalized): + # Valid var(--*) DDK theme variable, inspired by CSS syntax + # (e.g. var(--accent) ) + # DDK will crawl & eval var(-- colors for Graph theming + return v + elif v_normalized in ColorValidator.named_colors: + # Valid named color (e.g. 'coral') + return v + else: + # Not a valid color + return None + + +class ColorlistValidator(BaseValidator): + """ + "colorlist": { + "description": "A list of colors. Must be an {array} containing + valid colors.", + "requiredOpts": [], + "otherOpts": [ + "dflt" + ] + } + """ + + def __init__(self, plotly_name, parent_name, **kwargs): + super(ColorlistValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + def description(self): + return """\ + The '{plotly_name}' property is a colorlist that may be specified + as a tuple, list, one-dimensional numpy array, or pandas Series of valid + color strings""".format(plotly_name=self.plotly_name) + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif is_array(v): + validated_v = [ + ColorValidator.perform_validate_coerce(e, allow_number=False) for e in v + ] + + invalid_els = [ + el for el, validated_el in zip(v, validated_v) if validated_el is None + ] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(v) + else: + self.raise_invalid_val(v) + return v + + +class ColorscaleValidator(BaseValidator): + """ + "colorscale": { + "description": "A Plotly colorscale either picked by a name: + (any of Greys, YlGnBu, Greens, YlOrRd, Bluered, + RdBu, Reds, Blues, Picnic, Rainbow, Portland, + Jet, Hot, Blackbody, Earth, Electric, Viridis) + customized as an {array} of 2-element {arrays} + where the first element is the normalized color + level value (starting at *0* and ending at *1*), + and the second item is a valid color string.", + "requiredOpts": [], + "otherOpts": [ + "dflt" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, **kwargs): + super(ColorscaleValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # named colorscales initialized on first use + self._named_colorscales = None + + @property + def named_colorscales(self): + if self._named_colorscales is None: + import inspect + import itertools + from plotly import colors + + colorscale_members = itertools.chain( + inspect.getmembers(colors.sequential), + inspect.getmembers(colors.diverging), + inspect.getmembers(colors.cyclical), + ) + + self._named_colorscales = { + c[0].lower(): c[1] + for c in colorscale_members + if isinstance(c, tuple) + and len(c) == 2 + and isinstance(c[0], str) + and isinstance(c[1], list) + and not c[0].endswith("_r") + and not c[0].startswith("_") + } + + return self._named_colorscales + + def description(self): + colorscales_str = "\n".join( + textwrap.wrap( + repr(sorted(list(self.named_colorscales))), + initial_indent=" " * 12, + subsequent_indent=" " * 13, + break_on_hyphens=False, + width=80, + ) + ) + + desc = """\ + The '{plotly_name}' property is a colorscale and may be + specified as: + - A list of colors that will be spaced evenly to create the colorscale. + Many predefined colorscale lists are included in the sequential, diverging, + and cyclical modules in the plotly.colors package. + - A list of 2-element lists where the first element is the + normalized color level value (starting at 0 and ending at 1), + and the second item is a valid color string. + (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) + - One of the following named colorscales: +{colorscales_str}. + Appending '_r' to a named colorscale reverses it. +""".format(plotly_name=self.plotly_name, colorscales_str=colorscales_str) + + return desc + + def validate_coerce(self, v): + v_valid = False + + if v is None: + v_valid = True + elif isinstance(v, str): + v_lower = v.lower() + if v_lower in self.named_colorscales: + # Convert to color list + v = self.named_colorscales[v_lower] + v_valid = True + elif v_lower.endswith("_r") and v_lower[:-2] in self.named_colorscales: + v = self.named_colorscales[v_lower[:-2]][::-1] + v_valid = True + # + if v_valid: + # Convert to list of lists colorscale + d = len(v) - 1 + v = [[(1.0 * i) / (1.0 * d), x] for i, x in enumerate(v)] + + elif is_array(v) and len(v) > 0: + # If firset element is a string, treat as colorsequence + if isinstance(v[0], str): + invalid_els = [ + e for e in v if ColorValidator.perform_validate_coerce(e) is None + ] + + if len(invalid_els) == 0: + v_valid = True + + # Convert to list of lists colorscale + d = len(v) - 1 + v = [[(1.0 * i) / (1.0 * d), x] for i, x in enumerate(v)] + else: + invalid_els = [ + e + for e in v + if ( + not is_array(e) + or len(e) != 2 + or not isinstance(e[0], numbers.Number) + or not (0 <= e[0] <= 1) + or not isinstance(e[1], str) + or ColorValidator.perform_validate_coerce(e[1]) is None + ) + ] + + if len(invalid_els) == 0: + v_valid = True + + # Convert to list of lists + v = [ + [e[0], ColorValidator.perform_validate_coerce(e[1])] for e in v + ] + + if not v_valid: + self.raise_invalid_val(v) + + return v + + def present(self, v): + # Return-type must be immutable + if v is None: + return None + elif isinstance(v, str): + return v + else: + return tuple([tuple(e) for e in v]) + + +class AngleValidator(BaseValidator): + """ + "angle": { + "description": "A number (in degree) between -180 and 180.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "arrayOk" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, array_ok=False, **kwargs): + super(AngleValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a angle (in degrees) that may be + specified as a number between -180 and 180{array_ok}. + Numeric values outside this range are converted to the equivalent value + (e.g. 270 is converted to -90). + """.format( + plotly_name=self.plotly_name, + array_ok=( + ", or a list, numpy array or other iterable thereof" + if self.array_ok + else "" + ), + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + try: + v_array = copy_to_readonly_numpy_array(v, force_numeric=True) + except (ValueError, TypeError, OverflowError): + self.raise_invalid_val(v) + v = v_array # Always numeric numpy array + # Normalize v onto the interval [-180, 180) + v = (v + 180) % 360 - 180 + elif self.array_ok and is_simple_array(v): + # Check numeric + invalid_els = [e for e in v if not isinstance(e, numbers.Number)] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + v = [(x + 180) % 360 - 180 for x in to_scalar_or_list(v)] + elif not isinstance(v, numbers.Number): + self.raise_invalid_val(v) + else: + # Normalize v onto the interval [-180, 180) + v = (v + 180) % 360 - 180 + + return v + + +class SubplotidValidator(BaseValidator): + """ + "subplotid": { + "description": "An id string of a subplot type (given by dflt), + optionally followed by an integer >1. e.g. if + dflt='geo', we can have 'geo', 'geo2', 'geo3', + ...", + "requiredOpts": [ + "dflt" + ], + "otherOpts": [ + "arrayOk", + "regex" + ] + } + """ + + def __init__( + self, plotly_name, parent_name, dflt=None, regex=None, array_ok=False, **kwargs + ): + if dflt is None and regex is None: + raise ValueError("One or both of regex and deflt must be specified") + + super(SubplotidValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + if dflt is not None: + self.base = dflt + else: + # e.g. regex == '/^y([2-9]|[1-9][0-9]+)?$/' + self.base = re.match(r"/\^(\w+)", regex).group(1) + + self.regex = self.base + r"(\d*)" + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is an identifier of a particular + subplot, of type '{base}', that may be specified as: + - the string '{base}' optionally followed by an integer >= 1 + (e.g. '{base}', '{base}1', '{base}2', '{base}3', etc.)""".format( + plotly_name=self.plotly_name, base=self.base + ) + if self.array_ok: + desc += """ + - A tuple or list of the above""" + return desc + + def validate_coerce(self, v): + def coerce(value): + if not isinstance(value, str): + return value, False + match = fullmatch(self.regex, value) + if not match: + return value, False + else: + digit_str = match.group(1) + if len(digit_str) > 0 and int(digit_str) == 0: + return value, False + elif len(digit_str) > 0 and int(digit_str) == 1: + return self.base, True + else: + return value, True + + if v is None: + pass + elif self.array_ok and is_simple_array(v): + values = [] + invalid_els = [] + for e in v: + coerced_e, success = coerce(e) + values.append(coerced_e) + if not success: + invalid_els.append(coerced_e) + if len(invalid_els) > 0: + self.raise_invalid_elements(invalid_els[:10]) + return values + else: + v, success = coerce(v) + if not success: + self.raise_invalid_val(self.base) + return v + + +class FlaglistValidator(BaseValidator): + """ + "flaglist": { + "description": "A string representing a combination of flags + (order does not matter here). Combine any of the + available `flags` with *+*. + (e.g. ('lines+markers')). Values in `extras` + cannot be combined.", + "requiredOpts": [ + "flags" + ], + "otherOpts": [ + "dflt", + "extras", + "arrayOk" + ] + }, + """ + + def __init__( + self, plotly_name, parent_name, flags, extras=None, array_ok=False, **kwargs + ): + super(FlaglistValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.flags = flags + self.extras = extras if extras is not None else [] + self.array_ok = array_ok + + def description(self): + desc = ( + """\ + The '{plotly_name}' property is a flaglist and may be specified + as a string containing:""" + ).format(plotly_name=self.plotly_name) + + # Flags + desc = desc + ( + """ + - Any combination of {flags} joined with '+' characters + (e.g. '{eg_flag}')""" + ).format(flags=self.flags, eg_flag="+".join(self.flags[:2])) + + # Extras + if self.extras: + desc = desc + ( + """ + OR exactly one of {extras} (e.g. '{eg_extra}')""" + ).format(extras=self.extras, eg_extra=self.extras[-1]) + + if self.array_ok: + desc = ( + desc + + """ + - A list or array of the above""" + ) + + return desc + + def vc_scalar(self, v): + if isinstance(v, str): + v = v.strip() + + if v in self.extras: + return v + + if not isinstance(v, str): + return None + + # To be generous we accept flags separated on plus ('+'), + # or comma (',') and we accept whitespace around the flags + split_vals = [e.strip() for e in re.split("[,+]", v)] + + # Are all flags valid names? + if all(f in self.flags for f in split_vals): + return "+".join(split_vals) + else: + return None + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_array(v): + # Coerce individual strings + validated_v = [self.vc_scalar(e) for e in v] + + invalid_els = [ + el for el, validated_el in zip(v, validated_v) if validated_el is None + ] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + if is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(validated_v, kind="U") + else: + v = to_scalar_or_list(v) + else: + validated_v = self.vc_scalar(v) + if validated_v is None: + self.raise_invalid_val(v) + + v = validated_v + + return v + + +class AnyValidator(BaseValidator): + """ + "any": { + "description": "Any type.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "values", + "arrayOk" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, values=None, array_ok=False, **kwargs): + super(AnyValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.values = values + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property accepts values of any type + """.format(plotly_name=self.plotly_name) + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(v, kind="O") + elif self.array_ok and is_simple_array(v): + v = to_scalar_or_list(v) + return v + + +class InfoArrayValidator(BaseValidator): + """ + "info_array": { + "description": "An {array} of plot information.", + "requiredOpts": [ + "items" + ], + "otherOpts": [ + "dflt", + "freeLength", + "dimensions" + ] + } + """ + + def __init__( + self, + plotly_name, + parent_name, + items, + free_length=None, + dimensions=None, + **kwargs, + ): + super(InfoArrayValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.items = items + self.dimensions = dimensions if dimensions else 1 + self.free_length = free_length + + # Instantiate validators for each info array element + self.item_validators = [] + info_array_items = self.items if isinstance(self.items, list) else [self.items] + + for i, item in enumerate(info_array_items): + element_name = "{name}[{i}]".format(name=plotly_name, i=i) + item_validator = InfoArrayValidator.build_validator( + item, element_name, parent_name + ) + self.item_validators.append(item_validator) + + def description(self): + # Cases + # 1) self.items is array, self.dimensions is 1 + # a) free_length=True + # b) free_length=False + # 2) self.items is array, self.dimensions is 2 + # (requires free_length=True) + # 3) self.items is scalar (requires free_length=True) + # a) dimensions=1 + # b) dimensions=2 + # + # dimensions can be set to '1-2' to indicate the both are accepted + # + desc = """\ + The '{plotly_name}' property is an info array that may be specified as:\ +""".format(plotly_name=self.plotly_name) + + if isinstance(self.items, list): + # ### Case 1 ### + if self.dimensions in (1, "1-2"): + upto = " up to" if self.free_length and self.dimensions == 1 else "" + desc += """ + + * a list or tuple of{upto} {N} elements where:\ +""".format(upto=upto, N=len(self.item_validators)) + + for i, item_validator in enumerate(self.item_validators): + el_desc = item_validator.description().strip() + desc = ( + desc + + """ +({i}) {el_desc}""".format(i=i, el_desc=el_desc) + ) + + # ### Case 2 ### + if self.dimensions in ("1-2", 2): + assert self.free_length + + desc += """ + + * a 2D list where:""" + for i, item_validator in enumerate(self.item_validators): + # Update name for 2d + orig_name = item_validator.plotly_name + item_validator.plotly_name = "{name}[i][{i}]".format( + name=self.plotly_name, i=i + ) + + el_desc = item_validator.description().strip() + desc = ( + desc + + """ +({i}) {el_desc}""".format(i=i, el_desc=el_desc) + ) + item_validator.plotly_name = orig_name + else: + # ### Case 3 ### + assert self.free_length + item_validator = self.item_validators[0] + orig_name = item_validator.plotly_name + + if self.dimensions in (1, "1-2"): + item_validator.plotly_name = "{name}[i]".format(name=self.plotly_name) + + el_desc = item_validator.description().strip() + + desc += """ + * a list of elements where: + {el_desc} +""".format(el_desc=el_desc) + + if self.dimensions in ("1-2", 2): + item_validator.plotly_name = "{name}[i][j]".format( + name=self.plotly_name + ) + + el_desc = item_validator.description().strip() + desc += """ + * a 2D list where: + {el_desc} +""".format(el_desc=el_desc) + + item_validator.plotly_name = orig_name + + return desc + + @staticmethod + def build_validator(validator_info, plotly_name, parent_name): + datatype = validator_info["valType"] # type: str + validator_classname = datatype.title().replace("_", "") + "Validator" + validator_class = eval(validator_classname) + + kwargs = { + k: validator_info[k] + for k in validator_info + if k not in ["valType", "description", "role"] + } + + return validator_class( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + def validate_element_with_indexed_name(self, val, validator, inds): + """ + Helper to add indexes to a validator's name, call validate_coerce on + a value, then restore the original validator name. + + This makes sure that if a validation error message is raised, the + property name the user sees includes the index(es) of the offending + element. + + Parameters + ---------- + val: + A value to be validated + validator + A validator + inds + List of one or more non-negative integers that represent the + nested index of the value being validated + Returns + ------- + val + validated value + + Raises + ------ + ValueError + if val fails validation + """ + orig_name = validator.plotly_name + new_name = self.plotly_name + for i in inds: + new_name += "[" + str(i) + "]" + validator.plotly_name = new_name + try: + val = validator.validate_coerce(val) + finally: + validator.plotly_name = orig_name + + return val + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + return None + elif not is_array(v): + self.raise_invalid_val(v) + + # Save off original v value to use in error reporting + orig_v = v + + # Convert everything into nested lists + # This way we don't need to worry about nested numpy arrays + v = to_scalar_or_list(v) + + is_v_2d = v and is_array(v[0]) + + if is_v_2d and self.dimensions in ("1-2", 2): + if is_array(self.items): + # e.g. 2D list as parcoords.dimensions.constraintrange + # check that all items are there for each nested element + for i, row in enumerate(v): + # Check row length + if not is_array(row) or len(row) != len(self.items): + self.raise_invalid_val(orig_v[i], [i]) + + for j, validator in enumerate(self.item_validators): + row[j] = self.validate_element_with_indexed_name( + v[i][j], validator, [i, j] + ) + else: + # e.g. 2D list as layout.grid.subplots + # check that all elements match individual validator + validator = self.item_validators[0] + for i, row in enumerate(v): + if not is_array(row): + self.raise_invalid_val(orig_v[i], [i]) + + for j, el in enumerate(row): + row[j] = self.validate_element_with_indexed_name( + el, validator, [i, j] + ) + elif v and self.dimensions == 2: + # e.g. 1D list passed as layout.grid.subplots + self.raise_invalid_val(orig_v[0], [0]) + elif not is_array(self.items): + # e.g. 1D list passed as layout.grid.xaxes + validator = self.item_validators[0] + for i, el in enumerate(v): + v[i] = self.validate_element_with_indexed_name(el, validator, [i]) + + elif not self.free_length and len(v) != len(self.item_validators): + # e.g. 3 element list as layout.xaxis.range + self.raise_invalid_val(orig_v) + elif self.free_length and len(v) > len(self.item_validators): + # e.g. 4 element list as layout.updatemenu.button.args + self.raise_invalid_val(orig_v) + else: + # We have a 1D array of the correct length + for i, (el, validator) in enumerate(zip(v, self.item_validators)): + # Validate coerce elements + v[i] = validator.validate_coerce(el) + + return v + + def present(self, v): + if v is None: + return None + else: + if ( + self.dimensions == 2 + or self.dimensions == "1-2" + and v + and is_array(v[0]) + ): + # 2D case + v = copy.deepcopy(v) + for row in v: + for i, (el, validator) in enumerate(zip(row, self.item_validators)): + row[i] = validator.present(el) + + return tuple(tuple(row) for row in v) + else: + # 1D case + v = copy.copy(v) + # Call present on each of the item validators + for i, (el, validator) in enumerate(zip(v, self.item_validators)): + # Validate coerce elements + v[i] = validator.present(el) + + # Return tuple form of + return tuple(v) + + +class LiteralValidator(BaseValidator): + """ + Validator for readonly literal values + """ + + def __init__(self, plotly_name, parent_name, val, **kwargs): + super(LiteralValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.val = val + + def validate_coerce(self, v): + if v != self.val: + raise ValueError( + """\ + The '{plotly_name}' property of {parent_name} is read-only""".format( + plotly_name=self.plotly_name, parent_name=self.parent_name + ) + ) + else: + return v + + +class DashValidator(EnumeratedValidator): + """ + Special case validator for handling dash properties that may be specified + as lists of dash lengths. These are not currently specified in the + schema. + + "dash": { + "valType": "string", + "values": [ + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" + ], + "dflt": "solid", + "role": "style", + "editType": "style", + "description": "Sets the dash style of lines. Set to a dash type + string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or + *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." + }, + """ + + def __init__(self, plotly_name, parent_name, values, **kwargs): + # Add regex to handle dash length lists + dash_list_regex = r"/^\d+(\.\d+)?(px|%)?((,|\s)\s*\d+(\.\d+)?(px|%)?)*$/" + + values = values + [dash_list_regex] + + # Call EnumeratedValidator superclass + super(DashValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, values=values, **kwargs + ) + + def description(self): + # Separate regular values from regular expressions + enum_vals = [] + enum_regexs = [] + for v, regex in zip(self.values, self.val_regexs): + if regex is not None: + enum_regexs.append(regex.pattern) + else: + enum_vals.append(v) + desc = """\ + The '{name}' property is an enumeration that may be specified as:""".format( + name=self.plotly_name + ) + + if enum_vals: + enum_vals_str = "\n".join( + textwrap.wrap( + repr(enum_vals), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + width=80, + ) + ) + + desc = ( + desc + + """ + - One of the following dash styles: +{enum_vals_str}""".format(enum_vals_str=enum_vals_str) + ) + + desc = ( + desc + + """ + - A string containing a dash length list in pixels or percentages + (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) +""" + ) + return desc + + +class ImageUriValidator(BaseValidator): + _PIL = None + + try: + _PIL = import_module("PIL") + except ImportError: + pass + + def __init__(self, plotly_name, parent_name, **kwargs): + super(ImageUriValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + def description(self): + desc = """\ + The '{plotly_name}' property is an image URI that may be specified as: + - A remote image URI string + (e.g. 'http://www.somewhere.com/image.png') + - A data URI image string + (e.g. 'data:image/png;base64,iVBORw0KGgoAAAANSU') + - A PIL.Image.Image object which will be immediately converted + to a data URI image string + See http://pillow.readthedocs.io/en/latest/reference/Image.html + """.format(plotly_name=self.plotly_name) + return desc + + def validate_coerce(self, v): + if v is None: + pass + elif isinstance(v, str): + # Future possibilities: + # - Detect filesystem system paths and convert to URI + # - Validate either url or data uri + pass + elif self._PIL and isinstance(v, self._PIL.Image.Image): + # Convert PIL image to png data uri string + v = self.pil_image_to_uri(v) + else: + self.raise_invalid_val(v) + + return v + + @staticmethod + def pil_image_to_uri(v): + in_mem_file = io.BytesIO() + v.save(in_mem_file, format="PNG") + in_mem_file.seek(0) + img_bytes = in_mem_file.read() + base64_encoded_result_bytes = base64.b64encode(img_bytes) + base64_encoded_result_str = base64_encoded_result_bytes.decode("ascii") + v = "data:image/png;base64,{base64_encoded_result_str}".format( + base64_encoded_result_str=base64_encoded_result_str + ) + return v + + +class CompoundValidator(BaseValidator): + def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): + super(CompoundValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Save element class string + self.data_class_str = data_class_str + self._data_class = None + self.data_docs = data_docs + self.module_str = CompoundValidator.compute_graph_obj_module_str( + self.data_class_str, parent_name + ) + + @staticmethod + def compute_graph_obj_module_str(data_class_str, parent_name): + if parent_name == "frame" and data_class_str in ["Data", "Layout"]: + # Special case. There are no graph_objs.frame.Data or + # graph_objs.frame.Layout classes. These are remapped to + # graph_objs.Data and graph_objs.Layout + + parent_parts = parent_name.split(".") + module_str = ".".join(["plotly.graph_objs"] + parent_parts[1:]) + elif parent_name == "layout.template" and data_class_str == "Layout": + # Remap template's layout to regular layout + module_str = "plotly.graph_objs" + elif "layout.template.data" in parent_name: + # Remap template's traces to regular traces + parent_name = parent_name.replace("layout.template.data.", "") + if parent_name: + module_str = "plotly.graph_objs." + parent_name + else: + module_str = "plotly.graph_objs" + elif parent_name: + module_str = "plotly.graph_objs." + parent_name + else: + module_str = "plotly.graph_objs" + + return module_str + + @property + def data_class(self): + if self._data_class is None: + module = import_module(self.module_str) + self._data_class = getattr(module, self.data_class_str) + + return self._data_class + + def description(self): + desc = ( + """\ + The '{plotly_name}' property is an instance of {class_str} + that may be specified as: + - An instance of :class:`{module_str}.{class_str}` + - A dict of string/value properties that will be passed + to the {class_str} constructor""" + ).format( + plotly_name=self.plotly_name, + class_str=self.data_class_str, + module_str=self.module_str, + ) + + return desc + + def validate_coerce(self, v, skip_invalid=False, _validate=True): + if v is None: + v = self.data_class() + + elif isinstance(v, dict): + v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate) + + elif isinstance(v, self.data_class): + # Copy object + v = self.data_class(v) + else: + if skip_invalid: + v = self.data_class() + else: + self.raise_invalid_val(v) + + v._plotly_name = self.plotly_name + return v + + def present(self, v): + # Return compound object as-is + return v + + +class TitleValidator(CompoundValidator): + """ + This is a special validator to allow compound title properties + (e.g. layout.title, layout.xaxis.title, etc.) to be set as strings + or numbers. These strings are mapped to the 'text' property of the + compound validator. + """ + + def __init__(self, *args, **kwargs): + super(TitleValidator, self).__init__(*args, **kwargs) + + def validate_coerce(self, v, skip_invalid=False): + if isinstance(v, (str, int, float)): + v = {"text": v} + return super(TitleValidator, self).validate_coerce(v, skip_invalid=skip_invalid) + + +class CompoundArrayValidator(BaseValidator): + def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): + super(CompoundArrayValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Save element class string + self.data_class_str = data_class_str + self._data_class = None + + self.data_docs = data_docs + self.module_str = CompoundValidator.compute_graph_obj_module_str( + self.data_class_str, parent_name + ) + + def description(self): + desc = ( + """\ + The '{plotly_name}' property is a tuple of instances of + {class_str} that may be specified as: + - A list or tuple of instances of {module_str}.{class_str} + - A list or tuple of dicts of string/value properties that + will be passed to the {class_str} constructor""" + ).format( + plotly_name=self.plotly_name, + class_str=self.data_class_str, + module_str=self.module_str, + ) + + return desc + + @property + def data_class(self): + if self._data_class is None: + module = import_module(self.module_str) + self._data_class = getattr(module, self.data_class_str) + + return self._data_class + + def validate_coerce(self, v, skip_invalid=False): + if v is None: + v = [] + + elif isinstance(v, (list, tuple)): + res = [] + invalid_els = [] + for v_el in v: + if isinstance(v_el, self.data_class): + res.append(self.data_class(v_el)) + elif isinstance(v_el, dict): + res.append(self.data_class(v_el, skip_invalid=skip_invalid)) + else: + if skip_invalid: + res.append(self.data_class()) + else: + res.append(None) + invalid_els.append(v_el) + + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(res) + else: + if skip_invalid: + v = [] + else: + self.raise_invalid_val(v) + + return v + + def present(self, v): + # Return compound object as tuple + return tuple(v) + + +class BaseDataValidator(BaseValidator): + def __init__( + self, class_strs_map, plotly_name, parent_name, set_uid=False, **kwargs + ): + super(BaseDataValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.class_strs_map = class_strs_map + self._class_map = {} + self.set_uid = set_uid + + def description(self): + trace_types = str(list(self.class_strs_map.keys())) + + trace_types_wrapped = "\n".join( + textwrap.wrap( + trace_types, + initial_indent=" One of: ", + subsequent_indent=" " * 21, + width=79 - 12, + ) + ) + + desc = ( + """\ + The '{plotly_name}' property is a tuple of trace instances + that may be specified as: + - A list or tuple of trace instances + (e.g. [Scatter(...), Bar(...)]) + - A single trace instance + (e.g. Scatter(...), Bar(...), etc.) + - A list or tuple of dicts of string/value properties where: + - The 'type' property specifies the trace type +{trace_types} + + - All remaining properties are passed to the constructor of + the specified trace type + + (e.g. [{{'type': 'scatter', ...}}, {{'type': 'bar, ...}}])""" + ).format(plotly_name=self.plotly_name, trace_types=trace_types_wrapped) + + return desc + + def get_trace_class(self, trace_name): + # Import trace classes + if trace_name not in self._class_map: + trace_module = import_module("plotly.graph_objs") + trace_class_name = self.class_strs_map[trace_name] + self._class_map[trace_name] = getattr(trace_module, trace_class_name) + + return self._class_map[trace_name] + + def validate_coerce(self, v, skip_invalid=False, _validate=True): + from plotly.basedatatypes import BaseTraceType + + # Import Histogram2dcontour, this is the deprecated name of the + # Histogram2dContour trace. + from plotly.graph_objs import Histogram2dcontour + + if v is None: + v = [] + else: + if not isinstance(v, (list, tuple)): + v = [v] + + res = [] + invalid_els = [] + for v_el in v: + if isinstance(v_el, BaseTraceType): + if isinstance(v_el, Histogram2dcontour): + v_el = dict(type="histogram2dcontour", **v_el._props) + else: + v_el = v_el._props + + if isinstance(v_el, dict): + type_in_v_el = "type" in v_el + trace_type = v_el.pop("type", "scatter") + + if trace_type not in self.class_strs_map: + if skip_invalid: + # Treat as scatter trace + trace = self.get_trace_class("scatter")( + skip_invalid=skip_invalid, _validate=_validate, **v_el + ) + res.append(trace) + else: + res.append(None) + invalid_els.append(v_el) + else: + trace = self.get_trace_class(trace_type)( + skip_invalid=skip_invalid, _validate=_validate, **v_el + ) + res.append(trace) + + if type_in_v_el: + # Restore type in v_el + v_el["type"] = trace_type + else: + if skip_invalid: + # Add empty scatter trace + trace = self.get_trace_class("scatter")() + res.append(trace) + else: + res.append(None) + invalid_els.append(v_el) + + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(res) + + # Set new UIDs + if self.set_uid: + for trace in v: + trace.uid = str(uuid.uuid4()) + + return v + + +class BaseTemplateValidator(CompoundValidator): + def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): + super(BaseTemplateValidator, self).__init__( + plotly_name=plotly_name, + parent_name=parent_name, + data_class_str=data_class_str, + data_docs=data_docs, + **kwargs, + ) + + def description(self): + compound_description = super(BaseTemplateValidator, self).description() + compound_description += """ + - The name of a registered template where current registered templates + are stored in the plotly.io.templates configuration object. The names + of all registered templates can be retrieved with: + >>> import plotly.io as pio + >>> list(pio.templates) # doctest: +ELLIPSIS + ['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', ...] + + - A string containing multiple registered template names, joined on '+' + characters (e.g. 'template1+template2'). In this case the resulting + template is computed by merging together the collection of registered + templates""" + + return compound_description + + def validate_coerce(self, v, skip_invalid=False): + import plotly.io as pio + + try: + # Check if v is a template identifier + # (could be any hashable object) + if v in pio.templates: + return copy.deepcopy(pio.templates[v]) + # Otherwise, if v is a string, check to see if it consists of + # multiple template names joined on '+' characters + elif isinstance(v, str): + template_names = v.split("+") + if all([name in pio.templates for name in template_names]): + return pio.templates.merge_templates(*template_names) + + except TypeError: + # v is un-hashable + pass + + # Check for empty template + if v == {} or isinstance(v, self.data_class) and v.to_plotly_json() == {}: + # Replace empty template with {'data': {'scatter': [{}]}} so that we can + # tell the difference between an un-initialized template and a template + # explicitly set to empty. + return self.data_class(data_scatter=[{}]) + + return super(BaseTemplateValidator, self).validate_coerce( + v, skip_invalid=skip_invalid + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.__swatches.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.__swatches.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/.__swatches.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._carto.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._carto.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._carto.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._cmocean.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._cmocean.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._cmocean.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._colorbrewer.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._colorbrewer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._colorbrewer.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._cyclical.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._cyclical.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._cyclical.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._diverging.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._diverging.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._diverging.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._plotlyjs.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._plotlyjs.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._plotlyjs.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._qualitative.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._qualitative.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._qualitative.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._sequential.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/._sequential.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78abe774f49393a346c1b98af7d1c14ec6edc1ea --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__init__.py @@ -0,0 +1,883 @@ +""" +colors +===== + +Functions that manipulate colors and arrays of colors. + +----- +There are three basic types of color types: rgb, hex and tuple: + +rgb - An rgb color is a string of the form 'rgb(a,b,c)' where a, b and c are +integers between 0 and 255 inclusive. + +hex - A hex color is a string of the form '#xxxxxx' where each x is a +character that belongs to the set [0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]. This is +just the set of characters used in the hexadecimal numeric system. + +tuple - A tuple color is a 3-tuple of the form (a,b,c) where a, b and c are +floats between 0 and 1 inclusive. + +----- +Colormaps and Colorscales: +A colormap or a colorscale is a correspondence between values - Pythonic +objects such as strings and floats - to colors. + +There are typically two main types of colormaps that exist: numerical and +categorical colormaps. + +Numerical: +---------- +Numerical colormaps are used when the coloring column being used takes a +spectrum of values or numbers. + +A classic example from the Plotly library: +``` +rainbow_colorscale = [ + [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'], + [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'], + [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'], + [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'], + [1, 'rgb(255,0,0)'] +] +``` + +Notice that this colorscale is a list of lists with each inner list containing +a number and a color. These left hand numbers in the nested lists go from 0 to +1, and they are like pointers tell you when a number is mapped to a specific +color. + +If you have a column of numbers `col_num` that you want to plot, and you know + +``` +min(col_num) = 0 +max(col_num) = 100 +``` + +then if you pull out the number `12.5` in the list and want to figure out what +color the corresponding chart element (bar, scatter plot, etc) is going to be, +you'll figure out that proportionally 12.5 to 100 is the same as 0.125 to 1. +So, the point will be mapped to 'rgb(0,0,200)'. + +All other colors between the pinned values in a colorscale are linearly +interpolated. + +Categorical: +------------ +Alternatively, a categorical colormap is used to assign a specific value in a +color column to a specific color everytime it appears in the dataset. + +A column of strings in a panadas.dataframe that is chosen to serve as the +color index would naturally use a categorical colormap. However, you can +choose to use a categorical colormap with a column of numbers. + +Be careful! If you have a lot of unique numbers in your color column you will +end up with a colormap that is massive and may slow down graphing performance. +""" + +import decimal +from numbers import Number + +from _plotly_utils import exceptions + + +# Built-in qualitative color sequences and sequential, +# diverging and cyclical color scales. +# +# Initially ported over from plotly_express +from . import ( # noqa: F401 + qualitative, + sequential, + diverging, + cyclical, + cmocean, + colorbrewer, + carto, + plotlyjs, +) + +DEFAULT_PLOTLY_COLORS = [ + "rgb(31, 119, 180)", + "rgb(255, 127, 14)", + "rgb(44, 160, 44)", + "rgb(214, 39, 40)", + "rgb(148, 103, 189)", + "rgb(140, 86, 75)", + "rgb(227, 119, 194)", + "rgb(127, 127, 127)", + "rgb(188, 189, 34)", + "rgb(23, 190, 207)", +] + +PLOTLY_SCALES = { + "Greys": [[0, "rgb(0,0,0)"], [1, "rgb(255,255,255)"]], + "YlGnBu": [ + [0, "rgb(8,29,88)"], + [0.125, "rgb(37,52,148)"], + [0.25, "rgb(34,94,168)"], + [0.375, "rgb(29,145,192)"], + [0.5, "rgb(65,182,196)"], + [0.625, "rgb(127,205,187)"], + [0.75, "rgb(199,233,180)"], + [0.875, "rgb(237,248,217)"], + [1, "rgb(255,255,217)"], + ], + "Greens": [ + [0, "rgb(0,68,27)"], + [0.125, "rgb(0,109,44)"], + [0.25, "rgb(35,139,69)"], + [0.375, "rgb(65,171,93)"], + [0.5, "rgb(116,196,118)"], + [0.625, "rgb(161,217,155)"], + [0.75, "rgb(199,233,192)"], + [0.875, "rgb(229,245,224)"], + [1, "rgb(247,252,245)"], + ], + "YlOrRd": [ + [0, "rgb(128,0,38)"], + [0.125, "rgb(189,0,38)"], + [0.25, "rgb(227,26,28)"], + [0.375, "rgb(252,78,42)"], + [0.5, "rgb(253,141,60)"], + [0.625, "rgb(254,178,76)"], + [0.75, "rgb(254,217,118)"], + [0.875, "rgb(255,237,160)"], + [1, "rgb(255,255,204)"], + ], + "Bluered": [[0, "rgb(0,0,255)"], [1, "rgb(255,0,0)"]], + # modified RdBu based on + # www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf + "RdBu": [ + [0, "rgb(5,10,172)"], + [0.35, "rgb(106,137,247)"], + [0.5, "rgb(190,190,190)"], + [0.6, "rgb(220,170,132)"], + [0.7, "rgb(230,145,90)"], + [1, "rgb(178,10,28)"], + ], + # Scale for non-negative numeric values + "Reds": [ + [0, "rgb(220,220,220)"], + [0.2, "rgb(245,195,157)"], + [0.4, "rgb(245,160,105)"], + [1, "rgb(178,10,28)"], + ], + # Scale for non-positive numeric values + "Blues": [ + [0, "rgb(5,10,172)"], + [0.35, "rgb(40,60,190)"], + [0.5, "rgb(70,100,245)"], + [0.6, "rgb(90,120,245)"], + [0.7, "rgb(106,137,247)"], + [1, "rgb(220,220,220)"], + ], + "Picnic": [ + [0, "rgb(0,0,255)"], + [0.1, "rgb(51,153,255)"], + [0.2, "rgb(102,204,255)"], + [0.3, "rgb(153,204,255)"], + [0.4, "rgb(204,204,255)"], + [0.5, "rgb(255,255,255)"], + [0.6, "rgb(255,204,255)"], + [0.7, "rgb(255,153,255)"], + [0.8, "rgb(255,102,204)"], + [0.9, "rgb(255,102,102)"], + [1, "rgb(255,0,0)"], + ], + "Rainbow": [ + [0, "rgb(150,0,90)"], + [0.125, "rgb(0,0,200)"], + [0.25, "rgb(0,25,255)"], + [0.375, "rgb(0,152,255)"], + [0.5, "rgb(44,255,150)"], + [0.625, "rgb(151,255,0)"], + [0.75, "rgb(255,234,0)"], + [0.875, "rgb(255,111,0)"], + [1, "rgb(255,0,0)"], + ], + "Portland": [ + [0, "rgb(12,51,131)"], + [0.25, "rgb(10,136,186)"], + [0.5, "rgb(242,211,56)"], + [0.75, "rgb(242,143,56)"], + [1, "rgb(217,30,30)"], + ], + "Jet": [ + [0, "rgb(0,0,131)"], + [0.125, "rgb(0,60,170)"], + [0.375, "rgb(5,255,255)"], + [0.625, "rgb(255,255,0)"], + [0.875, "rgb(250,0,0)"], + [1, "rgb(128,0,0)"], + ], + "Hot": [ + [0, "rgb(0,0,0)"], + [0.3, "rgb(230,0,0)"], + [0.6, "rgb(255,210,0)"], + [1, "rgb(255,255,255)"], + ], + "Blackbody": [ + [0, "rgb(0,0,0)"], + [0.2, "rgb(230,0,0)"], + [0.4, "rgb(230,210,0)"], + [0.7, "rgb(255,255,255)"], + [1, "rgb(160,200,255)"], + ], + "Earth": [ + [0, "rgb(0,0,130)"], + [0.1, "rgb(0,180,180)"], + [0.2, "rgb(40,210,40)"], + [0.4, "rgb(230,230,50)"], + [0.6, "rgb(120,70,20)"], + [1, "rgb(255,255,255)"], + ], + "Electric": [ + [0, "rgb(0,0,0)"], + [0.15, "rgb(30,0,100)"], + [0.4, "rgb(120,0,100)"], + [0.6, "rgb(160,90,0)"], + [0.8, "rgb(230,200,0)"], + [1, "rgb(255,250,220)"], + ], + "Viridis": [ + [0, "#440154"], + [0.06274509803921569, "#48186a"], + [0.12549019607843137, "#472d7b"], + [0.18823529411764706, "#424086"], + [0.25098039215686274, "#3b528b"], + [0.3137254901960784, "#33638d"], + [0.3764705882352941, "#2c728e"], + [0.4392156862745098, "#26828e"], + [0.5019607843137255, "#21918c"], + [0.5647058823529412, "#1fa088"], + [0.6274509803921569, "#28ae80"], + [0.6901960784313725, "#3fbc73"], + [0.7529411764705882, "#5ec962"], + [0.8156862745098039, "#84d44b"], + [0.8784313725490196, "#addc30"], + [0.9411764705882353, "#d8e219"], + [1, "#fde725"], + ], + "Cividis": [ + [0.000000, "rgb(0,32,76)"], + [0.058824, "rgb(0,42,102)"], + [0.117647, "rgb(0,52,110)"], + [0.176471, "rgb(39,63,108)"], + [0.235294, "rgb(60,74,107)"], + [0.294118, "rgb(76,85,107)"], + [0.352941, "rgb(91,95,109)"], + [0.411765, "rgb(104,106,112)"], + [0.470588, "rgb(117,117,117)"], + [0.529412, "rgb(131,129,120)"], + [0.588235, "rgb(146,140,120)"], + [0.647059, "rgb(161,152,118)"], + [0.705882, "rgb(176,165,114)"], + [0.764706, "rgb(192,177,109)"], + [0.823529, "rgb(209,191,102)"], + [0.882353, "rgb(225,204,92)"], + [0.941176, "rgb(243,219,79)"], + [1.000000, "rgb(255,233,69)"], + ], +} + + +def color_parser(colors, function): + """ + Takes color(s) and a function and applies the function on the color(s) + + In particular, this function identifies whether the given color object + is an iterable or not and applies the given color-parsing function to + the color or iterable of colors. If given an iterable, it will only be + able to work with it if all items in the iterable are of the same type + - rgb string, hex string or tuple + """ + if isinstance(colors, str): + return function(colors) + + if isinstance(colors, tuple) and isinstance(colors[0], Number): + return function(colors) + + if hasattr(colors, "__iter__"): + if isinstance(colors, tuple): + new_color_tuple = tuple(function(item) for item in colors) + return new_color_tuple + + else: + new_color_list = [function(item) for item in colors] + return new_color_list + + +def validate_colors(colors, colortype="tuple"): + """ + Validates color(s) and returns a list of color(s) of a specified type + """ + from numbers import Number + + if colors is None: + colors = DEFAULT_PLOTLY_COLORS + + if isinstance(colors, str): + if colors in PLOTLY_SCALES: + colors_list = colorscale_to_colors(PLOTLY_SCALES[colors]) + # TODO: fix _gantt.py/_scatter.py so that they can accept the + # actual colorscale and not just a list of the first and last + # color in the plotly colorscale. In resolving this issue we + # will be removing the immediate line below + colors = [colors_list[0]] + [colors_list[-1]] + elif "rgb" in colors or "#" in colors: + colors = [colors] + else: + raise exceptions.PlotlyError( + "If your colors variable is a string, it must be a " + "Plotly scale, an rgb color or a hex color." + ) + + elif isinstance(colors, tuple): + if isinstance(colors[0], Number): + colors = [colors] + else: + colors = list(colors) + + # convert color elements in list to tuple color + for j, each_color in enumerate(colors): + if "rgb" in each_color: + each_color = color_parser(each_color, unlabel_rgb) + for value in each_color: + if value > 255.0: + raise exceptions.PlotlyError( + "Whoops! The elements in your rgb colors " + "tuples cannot exceed 255.0." + ) + each_color = color_parser(each_color, unconvert_from_RGB_255) + colors[j] = each_color + + if "#" in each_color: + each_color = color_parser(each_color, hex_to_rgb) + each_color = color_parser(each_color, unconvert_from_RGB_255) + + colors[j] = each_color + + if isinstance(each_color, tuple): + for value in each_color: + if value > 1.0: + raise exceptions.PlotlyError( + "Whoops! The elements in your colors tuples cannot exceed 1.0." + ) + colors[j] = each_color + + if colortype == "rgb" and not isinstance(colors, str): + for j, each_color in enumerate(colors): + rgb_color = color_parser(each_color, convert_to_RGB_255) + colors[j] = color_parser(rgb_color, label_rgb) + + return colors + + +def validate_colors_dict(colors, colortype="tuple"): + """ + Validates dictionary of color(s) + """ + # validate each color element in the dictionary + for key in colors: + if "rgb" in colors[key]: + colors[key] = color_parser(colors[key], unlabel_rgb) + for value in colors[key]: + if value > 255.0: + raise exceptions.PlotlyError( + "Whoops! The elements in your rgb colors " + "tuples cannot exceed 255.0." + ) + colors[key] = color_parser(colors[key], unconvert_from_RGB_255) + + if "#" in colors[key]: + colors[key] = color_parser(colors[key], hex_to_rgb) + colors[key] = color_parser(colors[key], unconvert_from_RGB_255) + + if isinstance(colors[key], tuple): + for value in colors[key]: + if value > 1.0: + raise exceptions.PlotlyError( + "Whoops! The elements in your colors tuples cannot exceed 1.0." + ) + + if colortype == "rgb": + for key in colors: + colors[key] = color_parser(colors[key], convert_to_RGB_255) + colors[key] = color_parser(colors[key], label_rgb) + + return colors + + +def convert_colors_to_same_type( + colors, + colortype="rgb", + scale=None, + return_default_colors=False, + num_of_defualt_colors=2, +): + """ + Converts color(s) to the specified color type + + Takes a single color or an iterable of colors, as well as a list of scale + values, and outputs a 2-pair of the list of color(s) converted all to an + rgb or tuple color type, aswell as the scale as the second element. If + colors is a Plotly Scale name, then 'scale' will be forced to the scale + from the respective colorscale and the colors in that colorscale will also + be coverted to the selected colortype. If colors is None, then there is an + option to return portion of the DEFAULT_PLOTLY_COLORS + + :param (str|tuple|list) colors: either a plotly scale name, an rgb or hex + color, a color tuple or a list/tuple of colors + :param (list) scale: see docs for validate_scale_values() + + :rtype (tuple) (colors_list, scale) if scale is None in the function call, + then scale will remain None in the returned tuple + """ + colors_list = [] + + if colors is None and return_default_colors is True: + colors_list = DEFAULT_PLOTLY_COLORS[0:num_of_defualt_colors] + + if isinstance(colors, str): + if colors in PLOTLY_SCALES: + colors_list = colorscale_to_colors(PLOTLY_SCALES[colors]) + if scale is None: + scale = colorscale_to_scale(PLOTLY_SCALES[colors]) + + elif "rgb" in colors or "#" in colors: + colors_list = [colors] + + elif isinstance(colors, tuple): + if isinstance(colors[0], Number): + colors_list = [colors] + else: + colors_list = list(colors) + + elif isinstance(colors, list): + colors_list = colors + + # validate scale + if scale is not None: + validate_scale_values(scale) + + if len(colors_list) != len(scale): + raise exceptions.PlotlyError( + "Make sure that the length of your scale matches the length " + "of your list of colors which is {}.".format(len(colors_list)) + ) + + # convert all colors to rgb + for j, each_color in enumerate(colors_list): + if "#" in each_color: + each_color = color_parser(each_color, hex_to_rgb) + each_color = color_parser(each_color, label_rgb) + colors_list[j] = each_color + + elif isinstance(each_color, tuple): + each_color = color_parser(each_color, convert_to_RGB_255) + each_color = color_parser(each_color, label_rgb) + colors_list[j] = each_color + + if colortype == "rgb": + return (colors_list, scale) + elif colortype == "tuple": + for j, each_color in enumerate(colors_list): + each_color = color_parser(each_color, unlabel_rgb) + each_color = color_parser(each_color, unconvert_from_RGB_255) + colors_list[j] = each_color + return (colors_list, scale) + else: + raise exceptions.PlotlyError( + "You must select either rgb or tuple for your colortype variable." + ) + + +def convert_dict_colors_to_same_type(colors_dict, colortype="rgb"): + """ + Converts a colors in a dictionary of colors to the specified color type + + :param (dict) colors_dict: a dictionary whose values are single colors + """ + for key in colors_dict: + if "#" in colors_dict[key]: + colors_dict[key] = color_parser(colors_dict[key], hex_to_rgb) + colors_dict[key] = color_parser(colors_dict[key], label_rgb) + + elif isinstance(colors_dict[key], tuple): + colors_dict[key] = color_parser(colors_dict[key], convert_to_RGB_255) + colors_dict[key] = color_parser(colors_dict[key], label_rgb) + + if colortype == "rgb": + return colors_dict + elif colortype == "tuple": + for key in colors_dict: + colors_dict[key] = color_parser(colors_dict[key], unlabel_rgb) + colors_dict[key] = color_parser(colors_dict[key], unconvert_from_RGB_255) + return colors_dict + else: + raise exceptions.PlotlyError( + "You must select either rgb or tuple for your colortype variable." + ) + + +def validate_scale_values(scale): + """ + Validates scale values from a colorscale + + :param (list) scale: a strictly increasing list of floats that begins + with 0 and ends with 1. Its usage derives from a colorscale which is + a list of two-lists (a list with two elements) of the form + [value, color] which are used to determine how interpolation weighting + works between the colors in the colorscale. Therefore scale is just + the extraction of these values from the two-lists in order + """ + if len(scale) < 2: + raise exceptions.PlotlyError( + "You must input a list of scale values that has at least two values." + ) + + if (scale[0] != 0) or (scale[-1] != 1): + raise exceptions.PlotlyError( + "The first and last number in your scale must be 0.0 and 1.0 respectively." + ) + + if not all(x < y for x, y in zip(scale, scale[1:])): + raise exceptions.PlotlyError( + "'scale' must be a list that contains a strictly increasing " + "sequence of numbers." + ) + + +def validate_colorscale(colorscale): + """Validate the structure, scale values and colors of colorscale.""" + if not isinstance(colorscale, list): + # TODO Write tests for these exceptions + raise exceptions.PlotlyError("A valid colorscale must be a list.") + if not all(isinstance(innerlist, list) for innerlist in colorscale): + raise exceptions.PlotlyError("A valid colorscale must be a list of lists.") + colorscale_colors = colorscale_to_colors(colorscale) + scale_values = colorscale_to_scale(colorscale) + + validate_scale_values(scale_values) + validate_colors(colorscale_colors) + + +def make_colorscale(colors, scale=None): + """ + Makes a colorscale from a list of colors and a scale + + Takes a list of colors and scales and constructs a colorscale based + on the colors in sequential order. If 'scale' is left empty, a linear- + interpolated colorscale will be generated. If 'scale' is a specificed + list, it must be the same legnth as colors and must contain all floats + For documentation regarding to the form of the output, see + https://plot.ly/python/reference/#mesh3d-colorscale + + :param (list) colors: a list of single colors + """ + colorscale = [] + + # validate minimum colors length of 2 + if len(colors) < 2: + raise exceptions.PlotlyError( + "You must input a list of colors that has at least two colors." + ) + + if scale is None: + scale_incr = 1.0 / (len(colors) - 1) + return [[i * scale_incr, color] for i, color in enumerate(colors)] + + else: + if len(colors) != len(scale): + raise exceptions.PlotlyError( + "The length of colors and scale must be the same." + ) + + validate_scale_values(scale) + + colorscale = [list(tup) for tup in zip(scale, colors)] + return colorscale + + +def find_intermediate_color(lowcolor, highcolor, intermed, colortype="tuple"): + """ + Returns the color at a given distance between two colors + + This function takes two color tuples, where each element is between 0 + and 1, along with a value 0 < intermed < 1 and returns a color that is + intermed-percent from lowcolor to highcolor. If colortype is set to 'rgb', + the function will automatically convert the rgb type to a tuple, find the + intermediate color and return it as an rgb color. + """ + if colortype == "rgb": + # convert to tuple color, eg. (1, 0.45, 0.7) + lowcolor = unlabel_rgb(lowcolor) + highcolor = unlabel_rgb(highcolor) + + diff_0 = float(highcolor[0] - lowcolor[0]) + diff_1 = float(highcolor[1] - lowcolor[1]) + diff_2 = float(highcolor[2] - lowcolor[2]) + + inter_med_tuple = ( + lowcolor[0] + intermed * diff_0, + lowcolor[1] + intermed * diff_1, + lowcolor[2] + intermed * diff_2, + ) + + if colortype == "rgb": + # back to an rgb string, e.g. rgb(30, 20, 10) + inter_med_rgb = label_rgb(inter_med_tuple) + return inter_med_rgb + + return inter_med_tuple + + +def unconvert_from_RGB_255(colors): + """ + Return a tuple where each element gets divided by 255 + + Takes a (list of) color tuple(s) where each element is between 0 and + 255. Returns the same tuples where each tuple element is normalized to + a value between 0 and 1 + """ + return (colors[0] / (255.0), colors[1] / (255.0), colors[2] / (255.0)) + + +def convert_to_RGB_255(colors): + """ + Multiplies each element of a triplet by 255 + + Each coordinate of the color tuple is rounded to the nearest float and + then is turned into an integer. If a number is of the form x.5, then + if x is odd, the number rounds up to (x+1). Otherwise, it rounds down + to just x. This is the way rounding works in Python 3 and in current + statistical analysis to avoid rounding bias + + :param (list) rgb_components: grabs the three R, G and B values to be + returned as computed in the function + """ + rgb_components = [] + + for component in colors: + rounded_num = decimal.Decimal(str(component * 255.0)).quantize( + decimal.Decimal("1"), rounding=decimal.ROUND_HALF_EVEN + ) + # convert rounded number to an integer from 'Decimal' form + rounded_num = int(rounded_num) + rgb_components.append(rounded_num) + + return (rgb_components[0], rgb_components[1], rgb_components[2]) + + +def n_colors(lowcolor, highcolor, n_colors, colortype="tuple"): + """ + Splits a low and high color into a list of n_colors colors in it + + Accepts two color tuples and returns a list of n_colors colors + which form the intermediate colors between lowcolor and highcolor + from linearly interpolating through RGB space. If colortype is 'rgb' + the function will return a list of colors in the same form. + """ + if colortype == "rgb": + # convert to tuple + lowcolor = unlabel_rgb(lowcolor) + highcolor = unlabel_rgb(highcolor) + + diff_0 = float(highcolor[0] - lowcolor[0]) + incr_0 = diff_0 / (n_colors - 1) + diff_1 = float(highcolor[1] - lowcolor[1]) + incr_1 = diff_1 / (n_colors - 1) + diff_2 = float(highcolor[2] - lowcolor[2]) + incr_2 = diff_2 / (n_colors - 1) + list_of_colors = [] + + def _constrain_color(c): + if c > 255.0: + return 255.0 + elif c < 0.0: + return 0.0 + else: + return c + + for index in range(n_colors): + new_tuple = ( + _constrain_color(lowcolor[0] + (index * incr_0)), + _constrain_color(lowcolor[1] + (index * incr_1)), + _constrain_color(lowcolor[2] + (index * incr_2)), + ) + list_of_colors.append(new_tuple) + + if colortype == "rgb": + # back to an rgb string + list_of_colors = color_parser(list_of_colors, label_rgb) + + return list_of_colors + + +def label_rgb(colors): + """ + Takes tuple (a, b, c) and returns an rgb color 'rgb(a, b, c)' + """ + return "rgb(%s, %s, %s)" % (colors[0], colors[1], colors[2]) + + +def unlabel_rgb(colors): + """ + Takes rgb color(s) 'rgb(a, b, c)' and returns tuple(s) (a, b, c) + + This function takes either an 'rgb(a, b, c)' color or a list of + such colors and returns the color tuples in tuple(s) (a, b, c) + """ + str_vals = "" + for index in range(len(colors)): + try: + float(colors[index]) + str_vals = str_vals + colors[index] + except ValueError: + if colors[index] == "," or colors[index] == ".": + str_vals = str_vals + colors[index] + + str_vals = str_vals + "," + numbers = [] + str_num = "" + for char in str_vals: + if char != ",": + str_num = str_num + char + else: + numbers.append(float(str_num)) + str_num = "" + return (numbers[0], numbers[1], numbers[2]) + + +def hex_to_rgb(value): + """ + Calculates rgb values from a hex color code. + + :param (string) value: Hex color string + + :rtype (tuple) (r_value, g_value, b_value): tuple of rgb values + """ + value = value.lstrip("#") + hex_total_length = len(value) + rgb_section_length = hex_total_length // 3 + return tuple( + int(value[i : i + rgb_section_length], 16) + for i in range(0, hex_total_length, rgb_section_length) + ) + + +def colorscale_to_colors(colorscale): + """ + Extracts the colors from colorscale as a list + """ + color_list = [] + for item in colorscale: + color_list.append(item[1]) + return color_list + + +def colorscale_to_scale(colorscale): + """ + Extracts the interpolation scale values from colorscale as a list + """ + scale_list = [] + for item in colorscale: + scale_list.append(item[0]) + return scale_list + + +def convert_colorscale_to_rgb(colorscale): + """ + Converts the colors in a colorscale to rgb colors + + A colorscale is an array of arrays, each with a numeric value as the + first item and a color as the second. This function specifically is + converting a colorscale with tuple colors (each coordinate between 0 + and 1) into a colorscale with the colors transformed into rgb colors + """ + for color in colorscale: + color[1] = convert_to_RGB_255(color[1]) + + for color in colorscale: + color[1] = label_rgb(color[1]) + return colorscale + + +def named_colorscales(): + """ + Returns lowercased names of built-in continuous colorscales. + """ + from _plotly_utils.basevalidators import ColorscaleValidator + + return [c for c in ColorscaleValidator("", "").named_colorscales] + + +def get_colorscale(name): + """ + Returns the colorscale for a given name. See `named_colorscales` for the + built-in colorscales. + """ + from _plotly_utils.basevalidators import ColorscaleValidator + + if not isinstance(name, str): + raise exceptions.PlotlyError("Name argument have to be a string.") + + name = name.lower() + if name[-2:] == "_r": + should_reverse = True + name = name[:-2] + else: + should_reverse = False + + if name in ColorscaleValidator("", "").named_colorscales: + colorscale = ColorscaleValidator("", "").named_colorscales[name] + else: + raise exceptions.PlotlyError(f"Colorscale {name} is not a built-in scale.") + + if should_reverse: + colorscale = colorscale[::-1] + return make_colorscale(colorscale) + + +def sample_colorscale(colorscale, samplepoints, low=0.0, high=1.0, colortype="rgb"): + """ + Samples a colorscale at specific points. + + Interpolates between colors in a colorscale to find the specific colors + corresponding to the specified sample values. The colorscale can be specified + as a list of `[scale, color]` pairs, as a list of colors, or as a named + plotly colorscale. The samplepoints can be specefied as an iterable of specific + points in the range [0.0, 1.0], or as an integer number of points which will + be spaced equally between the low value (default 0.0) and the high value + (default 1.0). The output is a list of colors, formatted according to the + specified colortype. + """ + from bisect import bisect_left + + try: + validate_colorscale(colorscale) + except exceptions.PlotlyError: + if isinstance(colorscale, str): + colorscale = get_colorscale(colorscale) + else: + colorscale = make_colorscale(colorscale) + + scale = colorscale_to_scale(colorscale) + validate_scale_values(scale) + colors = colorscale_to_colors(colorscale) + colors = validate_colors(colors, colortype="tuple") + + if isinstance(samplepoints, int): + samplepoints = [ + low + idx / (samplepoints - 1) * (high - low) for idx in range(samplepoints) + ] + elif isinstance(samplepoints, float): + samplepoints = [samplepoints] + + sampled_colors = [] + for point in samplepoints: + high = bisect_left(scale, point) + low = high - 1 + interpolant = (point - scale[low]) / (scale[high] - scale[low]) + sampled_color = find_intermediate_color(colors[low], colors[high], interpolant) + sampled_colors.append(sampled_color) + return validate_colors(sampled_colors, colortype=colortype) diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/_swatches.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/_swatches.py new file mode 100644 index 0000000000000000000000000000000000000000..f93b651011a832df130d42510f8767e7b123ac1d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/_swatches.py @@ -0,0 +1,161 @@ +def _swatches(module_names, module_contents, template=None): + """ + Parameters + ---------- + template : str or dict or plotly.graph_objects.layout.Template instance + The figure template name or definition. + + Returns + ------- + fig : graph_objects.Figure containing the displayed image + A `Figure` object. This figure demonstrates the color scales and + sequences in this module, as stacked bar charts. + """ + import plotly.graph_objs as go + from plotly.express._core import apply_default_cascade + + args = dict(template=template) + apply_default_cascade(args, constructor=None) + + sequences = [ + (k, v) + for k, v in module_contents.items() + if not (k.startswith("_") or k.startswith("swatches") or k.endswith("_r")) + ] + + return go.Figure( + data=[ + go.Bar( + orientation="h", + y=[name] * len(colors), + x=[1] * len(colors), + customdata=list(range(len(colors))), + marker=dict(color=colors), + hovertemplate="%{y}[%{customdata}] = %{marker.color}", + ) + for name, colors in reversed(sequences) + ], + layout=dict( + title="plotly.colors." + module_names.split(".")[-1], + barmode="stack", + barnorm="fraction", + bargap=0.5, + showlegend=False, + xaxis=dict(range=[-0.02, 1.02], showticklabels=False, showgrid=False), + height=max(600, 40 * len(sequences)), + template=args["template"], + margin=dict(b=10), + ), + ) + + +def _swatches_continuous(module_names, module_contents, template=None): + """ + Parameters + ---------- + template : str or dict or plotly.graph_objects.layout.Template instance + The figure template name or definition. + + Returns + ------- + fig : graph_objects.Figure containing the displayed image + A `Figure` object. This figure demonstrates the color scales and + sequences in this module, as stacked bar charts. + """ + import plotly.graph_objs as go + from plotly.express._core import apply_default_cascade + + args = dict(template=template) + apply_default_cascade(args, constructor=None) + + sequences = [ + (k, v) + for k, v in module_contents.items() + if not (k.startswith("_") or k.startswith("swatches") or k.endswith("_r")) + ] + + n = 100 + + return go.Figure( + data=[ + go.Bar( + orientation="h", + y=[name] * n, + x=[1] * n, + customdata=[(x + 1) / n for x in range(n)], + marker=dict(color=list(range(n)), colorscale=name, line_width=0), + hovertemplate="%{customdata}", + name=name, + ) + for name, colors in reversed(sequences) + ], + layout=dict( + title="plotly.colors." + module_names.split(".")[-1], + barmode="stack", + barnorm="fraction", + bargap=0.3, + showlegend=False, + xaxis=dict(range=[-0.02, 1.02], showticklabels=False, showgrid=False), + height=max(600, 40 * len(sequences)), + width=500, + template=args["template"], + margin=dict(b=10), + ), + ) + + +def _swatches_cyclical(module_names, module_contents, template=None): + """ + Parameters + ---------- + template : str or dict or plotly.graph_objects.layout.Template instance + The figure template name or definition. + + Returns + ------- + fig : graph_objects.Figure containing the displayed image + A `Figure` object. This figure demonstrates the color scales and + sequences in this module, as polar bar charts. + """ + import plotly.graph_objects as go + from plotly.subplots import make_subplots + from plotly.express._core import apply_default_cascade + + args = dict(template=template) + apply_default_cascade(args, constructor=None) + + rows = 2 + cols = 4 + scales = [ + (k, v) + for k, v in module_contents.items() + if not (k.startswith("_") or k.startswith("swatches") or k.endswith("_r")) + ] + names = [name for name, colors in scales] + fig = make_subplots( + rows=rows, + cols=cols, + subplot_titles=names, + specs=[[{"type": "polar"}] * cols] * rows, + ) + + for i, (name, scale) in enumerate(scales): + fig.add_trace( + go.Barpolar( + r=[1] * int(360 / 5), + theta=list(range(0, 360, 5)), + marker_color=list(range(0, 360, 5)), + marker_cmin=0, + marker_cmax=360, + marker_colorscale=name, + name=name, + ), + row=int(i / cols) + 1, + col=i % cols + 1, + ) + fig.update_traces(width=5.2, marker_line_width=0, base=0.5, showlegend=False) + fig.update_polars(angularaxis_visible=False, radialaxis_visible=False) + fig.update_layout( + title="plotly.colors." + module_names.split(".")[-1], template=args["template"] + ) + return fig diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/carto.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/carto.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c503f32519e5a7341c2aeaf6cfa15260881963 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/carto.py @@ -0,0 +1,419 @@ +""" +Color sequences and scales from CARTO's CartoColors + +Learn more at https://github.com/CartoDB/CartoColor + +CARTOColors are made available under a Creative Commons Attribution license: https://creativecommons.org/licenses/by/3.0/us/ +""" + +from ._swatches import _swatches + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + +Burg = [ + "rgb(255, 198, 196)", + "rgb(244, 163, 168)", + "rgb(227, 129, 145)", + "rgb(204, 96, 125)", + "rgb(173, 70, 108)", + "rgb(139, 48, 88)", + "rgb(103, 32, 68)", +] + +Burgyl = [ + "rgb(251, 230, 197)", + "rgb(245, 186, 152)", + "rgb(238, 138, 130)", + "rgb(220, 113, 118)", + "rgb(200, 88, 108)", + "rgb(156, 63, 93)", + "rgb(112, 40, 74)", +] + +Redor = [ + "rgb(246, 210, 169)", + "rgb(245, 183, 142)", + "rgb(241, 156, 124)", + "rgb(234, 129, 113)", + "rgb(221, 104, 108)", + "rgb(202, 82, 104)", + "rgb(177, 63, 100)", +] + +Oryel = [ + "rgb(236, 218, 154)", + "rgb(239, 196, 126)", + "rgb(243, 173, 106)", + "rgb(247, 148, 93)", + "rgb(249, 123, 87)", + "rgb(246, 99, 86)", + "rgb(238, 77, 90)", +] + +Peach = [ + "rgb(253, 224, 197)", + "rgb(250, 203, 166)", + "rgb(248, 181, 139)", + "rgb(245, 158, 114)", + "rgb(242, 133, 93)", + "rgb(239, 106, 76)", + "rgb(235, 74, 64)", +] + +Pinkyl = [ + "rgb(254, 246, 181)", + "rgb(255, 221, 154)", + "rgb(255, 194, 133)", + "rgb(255, 166, 121)", + "rgb(250, 138, 118)", + "rgb(241, 109, 122)", + "rgb(225, 83, 131)", +] + +Mint = [ + "rgb(228, 241, 225)", + "rgb(180, 217, 204)", + "rgb(137, 192, 182)", + "rgb(99, 166, 160)", + "rgb(68, 140, 138)", + "rgb(40, 114, 116)", + "rgb(13, 88, 95)", +] + +Blugrn = [ + "rgb(196, 230, 195)", + "rgb(150, 210, 164)", + "rgb(109, 188, 144)", + "rgb(77, 162, 132)", + "rgb(54, 135, 122)", + "rgb(38, 107, 110)", + "rgb(29, 79, 96)", +] + +Darkmint = [ + "rgb(210, 251, 212)", + "rgb(165, 219, 194)", + "rgb(123, 188, 176)", + "rgb(85, 156, 158)", + "rgb(58, 124, 137)", + "rgb(35, 93, 114)", + "rgb(18, 63, 90)", +] + +Emrld = [ + "rgb(211, 242, 163)", + "rgb(151, 225, 150)", + "rgb(108, 192, 139)", + "rgb(76, 155, 130)", + "rgb(33, 122, 121)", + "rgb(16, 89, 101)", + "rgb(7, 64, 80)", +] + +Aggrnyl = [ + "rgb(36, 86, 104)", + "rgb(15, 114, 121)", + "rgb(13, 143, 129)", + "rgb(57, 171, 126)", + "rgb(110, 197, 116)", + "rgb(169, 220, 103)", + "rgb(237, 239, 93)", +] + +Bluyl = [ + "rgb(247, 254, 174)", + "rgb(183, 230, 165)", + "rgb(124, 203, 162)", + "rgb(70, 174, 160)", + "rgb(8, 144, 153)", + "rgb(0, 113, 139)", + "rgb(4, 82, 117)", +] + +Teal = [ + "rgb(209, 238, 234)", + "rgb(168, 219, 217)", + "rgb(133, 196, 201)", + "rgb(104, 171, 184)", + "rgb(79, 144, 166)", + "rgb(59, 115, 143)", + "rgb(42, 86, 116)", +] + +Tealgrn = [ + "rgb(176, 242, 188)", + "rgb(137, 232, 172)", + "rgb(103, 219, 165)", + "rgb(76, 200, 163)", + "rgb(56, 178, 163)", + "rgb(44, 152, 160)", + "rgb(37, 125, 152)", +] + +Purp = [ + "rgb(243, 224, 247)", + "rgb(228, 199, 241)", + "rgb(209, 175, 232)", + "rgb(185, 152, 221)", + "rgb(159, 130, 206)", + "rgb(130, 109, 186)", + "rgb(99, 88, 159)", +] + +Purpor = [ + "rgb(249, 221, 218)", + "rgb(242, 185, 196)", + "rgb(229, 151, 185)", + "rgb(206, 120, 179)", + "rgb(173, 95, 173)", + "rgb(131, 75, 160)", + "rgb(87, 59, 136)", +] + +Sunset = [ + "rgb(243, 231, 155)", + "rgb(250, 196, 132)", + "rgb(248, 160, 126)", + "rgb(235, 127, 134)", + "rgb(206, 102, 147)", + "rgb(160, 89, 160)", + "rgb(92, 83, 165)", +] + +Magenta = [ + "rgb(243, 203, 211)", + "rgb(234, 169, 189)", + "rgb(221, 136, 172)", + "rgb(202, 105, 157)", + "rgb(177, 77, 142)", + "rgb(145, 53, 125)", + "rgb(108, 33, 103)", +] + +Sunsetdark = [ + "rgb(252, 222, 156)", + "rgb(250, 164, 118)", + "rgb(240, 116, 110)", + "rgb(227, 79, 111)", + "rgb(220, 57, 119)", + "rgb(185, 37, 122)", + "rgb(124, 29, 111)", +] + +Agsunset = [ + "rgb(75, 41, 145)", + "rgb(135, 44, 162)", + "rgb(192, 54, 157)", + "rgb(234, 79, 136)", + "rgb(250, 120, 118)", + "rgb(246, 169, 122)", + "rgb(237, 217, 163)", +] + +Brwnyl = [ + "rgb(237, 229, 207)", + "rgb(224, 194, 162)", + "rgb(211, 156, 131)", + "rgb(193, 118, 111)", + "rgb(166, 84, 97)", + "rgb(129, 55, 83)", + "rgb(84, 31, 63)", +] + +# Diverging schemes + +Armyrose = [ + "rgb(121, 130, 52)", + "rgb(163, 173, 98)", + "rgb(208, 211, 162)", + "rgb(253, 251, 228)", + "rgb(240, 198, 195)", + "rgb(223, 145, 163)", + "rgb(212, 103, 128)", +] + +Fall = [ + "rgb(61, 89, 65)", + "rgb(119, 136, 104)", + "rgb(181, 185, 145)", + "rgb(246, 237, 189)", + "rgb(237, 187, 138)", + "rgb(222, 138, 90)", + "rgb(202, 86, 44)", +] + +Geyser = [ + "rgb(0, 128, 128)", + "rgb(112, 164, 148)", + "rgb(180, 200, 168)", + "rgb(246, 237, 189)", + "rgb(237, 187, 138)", + "rgb(222, 138, 90)", + "rgb(202, 86, 44)", +] + +Temps = [ + "rgb(0, 147, 146)", + "rgb(57, 177, 133)", + "rgb(156, 203, 134)", + "rgb(233, 226, 156)", + "rgb(238, 180, 121)", + "rgb(232, 132, 113)", + "rgb(207, 89, 126)", +] + +Tealrose = [ + "rgb(0, 147, 146)", + "rgb(114, 170, 161)", + "rgb(177, 199, 179)", + "rgb(241, 234, 200)", + "rgb(229, 185, 173)", + "rgb(217, 137, 148)", + "rgb(208, 88, 126)", +] + +Tropic = [ + "rgb(0, 155, 158)", + "rgb(66, 183, 185)", + "rgb(167, 211, 212)", + "rgb(241, 241, 241)", + "rgb(228, 193, 217)", + "rgb(214, 145, 193)", + "rgb(199, 93, 171)", +] + +Earth = [ + "rgb(161, 105, 40)", + "rgb(189, 146, 90)", + "rgb(214, 189, 141)", + "rgb(237, 234, 194)", + "rgb(181, 200, 184)", + "rgb(121, 167, 172)", + "rgb(40, 135, 161)", +] + +# Qualitative palettes + +Antique = [ + "rgb(133, 92, 117)", + "rgb(217, 175, 107)", + "rgb(175, 100, 88)", + "rgb(115, 111, 76)", + "rgb(82, 106, 131)", + "rgb(98, 83, 119)", + "rgb(104, 133, 92)", + "rgb(156, 156, 94)", + "rgb(160, 97, 119)", + "rgb(140, 120, 93)", + "rgb(124, 124, 124)", +] + +Bold = [ + "rgb(127, 60, 141)", + "rgb(17, 165, 121)", + "rgb(57, 105, 172)", + "rgb(242, 183, 1)", + "rgb(231, 63, 116)", + "rgb(128, 186, 90)", + "rgb(230, 131, 16)", + "rgb(0, 134, 149)", + "rgb(207, 28, 144)", + "rgb(249, 123, 114)", + "rgb(165, 170, 153)", +] + +Pastel = [ + "rgb(102, 197, 204)", + "rgb(246, 207, 113)", + "rgb(248, 156, 116)", + "rgb(220, 176, 242)", + "rgb(135, 197, 95)", + "rgb(158, 185, 243)", + "rgb(254, 136, 177)", + "rgb(201, 219, 116)", + "rgb(139, 224, 164)", + "rgb(180, 151, 231)", + "rgb(179, 179, 179)", +] + +Prism = [ + "rgb(95, 70, 144)", + "rgb(29, 105, 150)", + "rgb(56, 166, 165)", + "rgb(15, 133, 84)", + "rgb(115, 175, 72)", + "rgb(237, 173, 8)", + "rgb(225, 124, 5)", + "rgb(204, 80, 62)", + "rgb(148, 52, 110)", + "rgb(111, 64, 112)", + "rgb(102, 102, 102)", +] + +Safe = [ + "rgb(136, 204, 238)", + "rgb(204, 102, 119)", + "rgb(221, 204, 119)", + "rgb(17, 119, 51)", + "rgb(51, 34, 136)", + "rgb(170, 68, 153)", + "rgb(68, 170, 153)", + "rgb(153, 153, 51)", + "rgb(136, 34, 85)", + "rgb(102, 17, 0)", + "rgb(136, 136, 136)", +] + +Vivid = [ + "rgb(229, 134, 6)", + "rgb(93, 105, 177)", + "rgb(82, 188, 163)", + "rgb(153, 201, 69)", + "rgb(204, 97, 176)", + "rgb(36, 121, 108)", + "rgb(218, 165, 27)", + "rgb(47, 138, 196)", + "rgb(118, 78, 159)", + "rgb(237, 100, 90)", + "rgb(165, 170, 153)", +] + +Aggrnyl_r = Aggrnyl[::-1] +Agsunset_r = Agsunset[::-1] +Antique_r = Antique[::-1] +Armyrose_r = Armyrose[::-1] +Blugrn_r = Blugrn[::-1] +Bluyl_r = Bluyl[::-1] +Bold_r = Bold[::-1] +Brwnyl_r = Brwnyl[::-1] +Burg_r = Burg[::-1] +Burgyl_r = Burgyl[::-1] +Darkmint_r = Darkmint[::-1] +Earth_r = Earth[::-1] +Emrld_r = Emrld[::-1] +Fall_r = Fall[::-1] +Geyser_r = Geyser[::-1] +Magenta_r = Magenta[::-1] +Mint_r = Mint[::-1] +Oryel_r = Oryel[::-1] +Pastel_r = Pastel[::-1] +Peach_r = Peach[::-1] +Pinkyl_r = Pinkyl[::-1] +Prism_r = Prism[::-1] +Purp_r = Purp[::-1] +Purpor_r = Purpor[::-1] +Redor_r = Redor[::-1] +Safe_r = Safe[::-1] +Sunset_r = Sunset[::-1] +Sunsetdark_r = Sunsetdark[::-1] +Teal_r = Teal[::-1] +Tealgrn_r = Tealgrn[::-1] +Tealrose_r = Tealrose[::-1] +Temps_r = Temps[::-1] +Tropic_r = Tropic[::-1] +Vivid_r = Vivid[::-1] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cmocean.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cmocean.py new file mode 100644 index 0000000000000000000000000000000000000000..18944b59361865b9dd192ea453dfdf2c13024279 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cmocean.py @@ -0,0 +1,296 @@ +""" +Color scales from the cmocean project + +Learn more at https://matplotlib.org/cmocean/ + +cmocean is made available under an MIT license: https://github.com/matplotlib/cmocean/blob/master/LICENSE.txt +""" + +from ._swatches import _swatches, _swatches_continuous + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + + +def swatches_continuous(template=None): + return _swatches_continuous(__name__, globals(), template) + + +swatches_continuous.__doc__ = _swatches_continuous.__doc__ + + +turbid = [ + "rgb(232, 245, 171)", + "rgb(220, 219, 137)", + "rgb(209, 193, 107)", + "rgb(199, 168, 83)", + "rgb(186, 143, 66)", + "rgb(170, 121, 60)", + "rgb(151, 103, 58)", + "rgb(129, 87, 56)", + "rgb(104, 72, 53)", + "rgb(80, 59, 46)", + "rgb(57, 45, 37)", + "rgb(34, 30, 27)", +] +thermal = [ + "rgb(3, 35, 51)", + "rgb(13, 48, 100)", + "rgb(53, 50, 155)", + "rgb(93, 62, 153)", + "rgb(126, 77, 143)", + "rgb(158, 89, 135)", + "rgb(193, 100, 121)", + "rgb(225, 113, 97)", + "rgb(246, 139, 69)", + "rgb(251, 173, 60)", + "rgb(246, 211, 70)", + "rgb(231, 250, 90)", +] +haline = [ + "rgb(41, 24, 107)", + "rgb(42, 35, 160)", + "rgb(15, 71, 153)", + "rgb(18, 95, 142)", + "rgb(38, 116, 137)", + "rgb(53, 136, 136)", + "rgb(65, 157, 133)", + "rgb(81, 178, 124)", + "rgb(111, 198, 107)", + "rgb(160, 214, 91)", + "rgb(212, 225, 112)", + "rgb(253, 238, 153)", +] +solar = [ + "rgb(51, 19, 23)", + "rgb(79, 28, 33)", + "rgb(108, 36, 36)", + "rgb(135, 47, 32)", + "rgb(157, 66, 25)", + "rgb(174, 88, 20)", + "rgb(188, 111, 19)", + "rgb(199, 137, 22)", + "rgb(209, 164, 32)", + "rgb(217, 192, 44)", + "rgb(222, 222, 59)", + "rgb(224, 253, 74)", +] +ice = [ + "rgb(3, 5, 18)", + "rgb(25, 25, 51)", + "rgb(44, 42, 87)", + "rgb(58, 60, 125)", + "rgb(62, 83, 160)", + "rgb(62, 109, 178)", + "rgb(72, 134, 187)", + "rgb(89, 159, 196)", + "rgb(114, 184, 205)", + "rgb(149, 207, 216)", + "rgb(192, 229, 232)", + "rgb(234, 252, 253)", +] +gray = [ + "rgb(0, 0, 0)", + "rgb(16, 16, 16)", + "rgb(38, 38, 38)", + "rgb(59, 59, 59)", + "rgb(81, 80, 80)", + "rgb(102, 101, 101)", + "rgb(124, 123, 122)", + "rgb(146, 146, 145)", + "rgb(171, 171, 170)", + "rgb(197, 197, 195)", + "rgb(224, 224, 223)", + "rgb(254, 254, 253)", +] +oxy = [ + "rgb(63, 5, 5)", + "rgb(101, 6, 13)", + "rgb(138, 17, 9)", + "rgb(96, 95, 95)", + "rgb(119, 118, 118)", + "rgb(142, 141, 141)", + "rgb(166, 166, 165)", + "rgb(193, 192, 191)", + "rgb(222, 222, 220)", + "rgb(239, 248, 90)", + "rgb(230, 210, 41)", + "rgb(220, 174, 25)", +] +deep = [ + "rgb(253, 253, 204)", + "rgb(206, 236, 179)", + "rgb(156, 219, 165)", + "rgb(111, 201, 163)", + "rgb(86, 177, 163)", + "rgb(76, 153, 160)", + "rgb(68, 130, 155)", + "rgb(62, 108, 150)", + "rgb(62, 82, 143)", + "rgb(64, 60, 115)", + "rgb(54, 43, 77)", + "rgb(39, 26, 44)", +] +dense = [ + "rgb(230, 240, 240)", + "rgb(191, 221, 229)", + "rgb(156, 201, 226)", + "rgb(129, 180, 227)", + "rgb(115, 154, 228)", + "rgb(117, 127, 221)", + "rgb(120, 100, 202)", + "rgb(119, 74, 175)", + "rgb(113, 50, 141)", + "rgb(100, 31, 104)", + "rgb(80, 20, 66)", + "rgb(54, 14, 36)", +] +algae = [ + "rgb(214, 249, 207)", + "rgb(186, 228, 174)", + "rgb(156, 209, 143)", + "rgb(124, 191, 115)", + "rgb(85, 174, 91)", + "rgb(37, 157, 81)", + "rgb(7, 138, 78)", + "rgb(13, 117, 71)", + "rgb(23, 95, 61)", + "rgb(25, 75, 49)", + "rgb(23, 55, 35)", + "rgb(17, 36, 20)", +] +matter = [ + "rgb(253, 237, 176)", + "rgb(250, 205, 145)", + "rgb(246, 173, 119)", + "rgb(240, 142, 98)", + "rgb(231, 109, 84)", + "rgb(216, 80, 83)", + "rgb(195, 56, 90)", + "rgb(168, 40, 96)", + "rgb(138, 29, 99)", + "rgb(107, 24, 93)", + "rgb(76, 21, 80)", + "rgb(47, 15, 61)", +] +speed = [ + "rgb(254, 252, 205)", + "rgb(239, 225, 156)", + "rgb(221, 201, 106)", + "rgb(194, 182, 59)", + "rgb(157, 167, 21)", + "rgb(116, 153, 5)", + "rgb(75, 138, 20)", + "rgb(35, 121, 36)", + "rgb(11, 100, 44)", + "rgb(18, 78, 43)", + "rgb(25, 56, 34)", + "rgb(23, 35, 18)", +] +amp = [ + "rgb(241, 236, 236)", + "rgb(230, 209, 203)", + "rgb(221, 182, 170)", + "rgb(213, 156, 137)", + "rgb(205, 129, 103)", + "rgb(196, 102, 73)", + "rgb(186, 74, 47)", + "rgb(172, 44, 36)", + "rgb(149, 19, 39)", + "rgb(120, 14, 40)", + "rgb(89, 13, 31)", + "rgb(60, 9, 17)", +] +tempo = [ + "rgb(254, 245, 244)", + "rgb(222, 224, 210)", + "rgb(189, 206, 181)", + "rgb(153, 189, 156)", + "rgb(110, 173, 138)", + "rgb(65, 157, 129)", + "rgb(25, 137, 125)", + "rgb(18, 116, 117)", + "rgb(25, 94, 106)", + "rgb(28, 72, 93)", + "rgb(25, 51, 80)", + "rgb(20, 29, 67)", +] +phase = [ + "rgb(167, 119, 12)", + "rgb(197, 96, 51)", + "rgb(217, 67, 96)", + "rgb(221, 38, 163)", + "rgb(196, 59, 224)", + "rgb(153, 97, 244)", + "rgb(95, 127, 228)", + "rgb(40, 144, 183)", + "rgb(15, 151, 136)", + "rgb(39, 153, 79)", + "rgb(119, 141, 17)", + "rgb(167, 119, 12)", +] +balance = [ + "rgb(23, 28, 66)", + "rgb(41, 58, 143)", + "rgb(11, 102, 189)", + "rgb(69, 144, 185)", + "rgb(142, 181, 194)", + "rgb(210, 216, 219)", + "rgb(230, 210, 204)", + "rgb(213, 157, 137)", + "rgb(196, 101, 72)", + "rgb(172, 43, 36)", + "rgb(120, 14, 40)", + "rgb(60, 9, 17)", +] +delta = [ + "rgb(16, 31, 63)", + "rgb(38, 62, 144)", + "rgb(30, 110, 161)", + "rgb(60, 154, 171)", + "rgb(140, 193, 186)", + "rgb(217, 229, 218)", + "rgb(239, 226, 156)", + "rgb(195, 182, 59)", + "rgb(115, 152, 5)", + "rgb(34, 120, 36)", + "rgb(18, 78, 43)", + "rgb(23, 35, 18)", +] +curl = [ + "rgb(20, 29, 67)", + "rgb(28, 72, 93)", + "rgb(18, 115, 117)", + "rgb(63, 156, 129)", + "rgb(153, 189, 156)", + "rgb(223, 225, 211)", + "rgb(241, 218, 206)", + "rgb(224, 160, 137)", + "rgb(203, 101, 99)", + "rgb(164, 54, 96)", + "rgb(111, 23, 91)", + "rgb(51, 13, 53)", +] + +algae_r = algae[::-1] +amp_r = amp[::-1] +balance_r = balance[::-1] +curl_r = curl[::-1] +deep_r = deep[::-1] +delta_r = delta[::-1] +dense_r = dense[::-1] +gray_r = gray[::-1] +haline_r = haline[::-1] +ice_r = ice[::-1] +matter_r = matter[::-1] +oxy_r = oxy[::-1] +phase_r = phase[::-1] +solar_r = solar[::-1] +speed_r = speed[::-1] +tempo_r = tempo[::-1] +thermal_r = thermal[::-1] +turbid_r = turbid[::-1] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/colorbrewer.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/colorbrewer.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb286e43e0e90944f7b76d70d3bee80708461e5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/colorbrewer.py @@ -0,0 +1,494 @@ +""" +Color scales and sequences from the colorbrewer 2 project + +Learn more at http://colorbrewer2.org + +colorbrewer is made available under an Apache license: http://colorbrewer2.org/export/LICENSE.txt +""" + +from ._swatches import _swatches + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + +BrBG = [ + "rgb(84,48,5)", + "rgb(140,81,10)", + "rgb(191,129,45)", + "rgb(223,194,125)", + "rgb(246,232,195)", + "rgb(245,245,245)", + "rgb(199,234,229)", + "rgb(128,205,193)", + "rgb(53,151,143)", + "rgb(1,102,94)", + "rgb(0,60,48)", +] + +PRGn = [ + "rgb(64,0,75)", + "rgb(118,42,131)", + "rgb(153,112,171)", + "rgb(194,165,207)", + "rgb(231,212,232)", + "rgb(247,247,247)", + "rgb(217,240,211)", + "rgb(166,219,160)", + "rgb(90,174,97)", + "rgb(27,120,55)", + "rgb(0,68,27)", +] + +PiYG = [ + "rgb(142,1,82)", + "rgb(197,27,125)", + "rgb(222,119,174)", + "rgb(241,182,218)", + "rgb(253,224,239)", + "rgb(247,247,247)", + "rgb(230,245,208)", + "rgb(184,225,134)", + "rgb(127,188,65)", + "rgb(77,146,33)", + "rgb(39,100,25)", +] + +PuOr = [ + "rgb(127,59,8)", + "rgb(179,88,6)", + "rgb(224,130,20)", + "rgb(253,184,99)", + "rgb(254,224,182)", + "rgb(247,247,247)", + "rgb(216,218,235)", + "rgb(178,171,210)", + "rgb(128,115,172)", + "rgb(84,39,136)", + "rgb(45,0,75)", +] + +RdBu = [ + "rgb(103,0,31)", + "rgb(178,24,43)", + "rgb(214,96,77)", + "rgb(244,165,130)", + "rgb(253,219,199)", + "rgb(247,247,247)", + "rgb(209,229,240)", + "rgb(146,197,222)", + "rgb(67,147,195)", + "rgb(33,102,172)", + "rgb(5,48,97)", +] + +RdGy = [ + "rgb(103,0,31)", + "rgb(178,24,43)", + "rgb(214,96,77)", + "rgb(244,165,130)", + "rgb(253,219,199)", + "rgb(255,255,255)", + "rgb(224,224,224)", + "rgb(186,186,186)", + "rgb(135,135,135)", + "rgb(77,77,77)", + "rgb(26,26,26)", +] + +RdYlBu = [ + "rgb(165,0,38)", + "rgb(215,48,39)", + "rgb(244,109,67)", + "rgb(253,174,97)", + "rgb(254,224,144)", + "rgb(255,255,191)", + "rgb(224,243,248)", + "rgb(171,217,233)", + "rgb(116,173,209)", + "rgb(69,117,180)", + "rgb(49,54,149)", +] + +RdYlGn = [ + "rgb(165,0,38)", + "rgb(215,48,39)", + "rgb(244,109,67)", + "rgb(253,174,97)", + "rgb(254,224,139)", + "rgb(255,255,191)", + "rgb(217,239,139)", + "rgb(166,217,106)", + "rgb(102,189,99)", + "rgb(26,152,80)", + "rgb(0,104,55)", +] + +Spectral = [ + "rgb(158,1,66)", + "rgb(213,62,79)", + "rgb(244,109,67)", + "rgb(253,174,97)", + "rgb(254,224,139)", + "rgb(255,255,191)", + "rgb(230,245,152)", + "rgb(171,221,164)", + "rgb(102,194,165)", + "rgb(50,136,189)", + "rgb(94,79,162)", +] + +Set1 = [ + "rgb(228,26,28)", + "rgb(55,126,184)", + "rgb(77,175,74)", + "rgb(152,78,163)", + "rgb(255,127,0)", + "rgb(255,255,51)", + "rgb(166,86,40)", + "rgb(247,129,191)", + "rgb(153,153,153)", +] + + +Pastel1 = [ + "rgb(251,180,174)", + "rgb(179,205,227)", + "rgb(204,235,197)", + "rgb(222,203,228)", + "rgb(254,217,166)", + "rgb(255,255,204)", + "rgb(229,216,189)", + "rgb(253,218,236)", + "rgb(242,242,242)", +] +Dark2 = [ + "rgb(27,158,119)", + "rgb(217,95,2)", + "rgb(117,112,179)", + "rgb(231,41,138)", + "rgb(102,166,30)", + "rgb(230,171,2)", + "rgb(166,118,29)", + "rgb(102,102,102)", +] +Set2 = [ + "rgb(102,194,165)", + "rgb(252,141,98)", + "rgb(141,160,203)", + "rgb(231,138,195)", + "rgb(166,216,84)", + "rgb(255,217,47)", + "rgb(229,196,148)", + "rgb(179,179,179)", +] + + +Pastel2 = [ + "rgb(179,226,205)", + "rgb(253,205,172)", + "rgb(203,213,232)", + "rgb(244,202,228)", + "rgb(230,245,201)", + "rgb(255,242,174)", + "rgb(241,226,204)", + "rgb(204,204,204)", +] + +Set3 = [ + "rgb(141,211,199)", + "rgb(255,255,179)", + "rgb(190,186,218)", + "rgb(251,128,114)", + "rgb(128,177,211)", + "rgb(253,180,98)", + "rgb(179,222,105)", + "rgb(252,205,229)", + "rgb(217,217,217)", + "rgb(188,128,189)", + "rgb(204,235,197)", + "rgb(255,237,111)", +] + +Accent = [ + "rgb(127,201,127)", + "rgb(190,174,212)", + "rgb(253,192,134)", + "rgb(255,255,153)", + "rgb(56,108,176)", + "rgb(240,2,127)", + "rgb(191,91,23)", + "rgb(102,102,102)", +] + + +Paired = [ + "rgb(166,206,227)", + "rgb(31,120,180)", + "rgb(178,223,138)", + "rgb(51,160,44)", + "rgb(251,154,153)", + "rgb(227,26,28)", + "rgb(253,191,111)", + "rgb(255,127,0)", + "rgb(202,178,214)", + "rgb(106,61,154)", + "rgb(255,255,153)", + "rgb(177,89,40)", +] + + +Blues = [ + "rgb(247,251,255)", + "rgb(222,235,247)", + "rgb(198,219,239)", + "rgb(158,202,225)", + "rgb(107,174,214)", + "rgb(66,146,198)", + "rgb(33,113,181)", + "rgb(8,81,156)", + "rgb(8,48,107)", +] + +BuGn = [ + "rgb(247,252,253)", + "rgb(229,245,249)", + "rgb(204,236,230)", + "rgb(153,216,201)", + "rgb(102,194,164)", + "rgb(65,174,118)", + "rgb(35,139,69)", + "rgb(0,109,44)", + "rgb(0,68,27)", +] + +BuPu = [ + "rgb(247,252,253)", + "rgb(224,236,244)", + "rgb(191,211,230)", + "rgb(158,188,218)", + "rgb(140,150,198)", + "rgb(140,107,177)", + "rgb(136,65,157)", + "rgb(129,15,124)", + "rgb(77,0,75)", +] + +GnBu = [ + "rgb(247,252,240)", + "rgb(224,243,219)", + "rgb(204,235,197)", + "rgb(168,221,181)", + "rgb(123,204,196)", + "rgb(78,179,211)", + "rgb(43,140,190)", + "rgb(8,104,172)", + "rgb(8,64,129)", +] + +Greens = [ + "rgb(247,252,245)", + "rgb(229,245,224)", + "rgb(199,233,192)", + "rgb(161,217,155)", + "rgb(116,196,118)", + "rgb(65,171,93)", + "rgb(35,139,69)", + "rgb(0,109,44)", + "rgb(0,68,27)", +] + +Greys = [ + "rgb(255,255,255)", + "rgb(240,240,240)", + "rgb(217,217,217)", + "rgb(189,189,189)", + "rgb(150,150,150)", + "rgb(115,115,115)", + "rgb(82,82,82)", + "rgb(37,37,37)", + "rgb(0,0,0)", +] + +OrRd = [ + "rgb(255,247,236)", + "rgb(254,232,200)", + "rgb(253,212,158)", + "rgb(253,187,132)", + "rgb(252,141,89)", + "rgb(239,101,72)", + "rgb(215,48,31)", + "rgb(179,0,0)", + "rgb(127,0,0)", +] + +Oranges = [ + "rgb(255,245,235)", + "rgb(254,230,206)", + "rgb(253,208,162)", + "rgb(253,174,107)", + "rgb(253,141,60)", + "rgb(241,105,19)", + "rgb(217,72,1)", + "rgb(166,54,3)", + "rgb(127,39,4)", +] + +PuBu = [ + "rgb(255,247,251)", + "rgb(236,231,242)", + "rgb(208,209,230)", + "rgb(166,189,219)", + "rgb(116,169,207)", + "rgb(54,144,192)", + "rgb(5,112,176)", + "rgb(4,90,141)", + "rgb(2,56,88)", +] + +PuBuGn = [ + "rgb(255,247,251)", + "rgb(236,226,240)", + "rgb(208,209,230)", + "rgb(166,189,219)", + "rgb(103,169,207)", + "rgb(54,144,192)", + "rgb(2,129,138)", + "rgb(1,108,89)", + "rgb(1,70,54)", +] + +PuRd = [ + "rgb(247,244,249)", + "rgb(231,225,239)", + "rgb(212,185,218)", + "rgb(201,148,199)", + "rgb(223,101,176)", + "rgb(231,41,138)", + "rgb(206,18,86)", + "rgb(152,0,67)", + "rgb(103,0,31)", +] + +Purples = [ + "rgb(252,251,253)", + "rgb(239,237,245)", + "rgb(218,218,235)", + "rgb(188,189,220)", + "rgb(158,154,200)", + "rgb(128,125,186)", + "rgb(106,81,163)", + "rgb(84,39,143)", + "rgb(63,0,125)", +] + +RdPu = [ + "rgb(255,247,243)", + "rgb(253,224,221)", + "rgb(252,197,192)", + "rgb(250,159,181)", + "rgb(247,104,161)", + "rgb(221,52,151)", + "rgb(174,1,126)", + "rgb(122,1,119)", + "rgb(73,0,106)", +] + +Reds = [ + "rgb(255,245,240)", + "rgb(254,224,210)", + "rgb(252,187,161)", + "rgb(252,146,114)", + "rgb(251,106,74)", + "rgb(239,59,44)", + "rgb(203,24,29)", + "rgb(165,15,21)", + "rgb(103,0,13)", +] + +YlGn = [ + "rgb(255,255,229)", + "rgb(247,252,185)", + "rgb(217,240,163)", + "rgb(173,221,142)", + "rgb(120,198,121)", + "rgb(65,171,93)", + "rgb(35,132,67)", + "rgb(0,104,55)", + "rgb(0,69,41)", +] + +YlGnBu = [ + "rgb(255,255,217)", + "rgb(237,248,177)", + "rgb(199,233,180)", + "rgb(127,205,187)", + "rgb(65,182,196)", + "rgb(29,145,192)", + "rgb(34,94,168)", + "rgb(37,52,148)", + "rgb(8,29,88)", +] + +YlOrBr = [ + "rgb(255,255,229)", + "rgb(255,247,188)", + "rgb(254,227,145)", + "rgb(254,196,79)", + "rgb(254,153,41)", + "rgb(236,112,20)", + "rgb(204,76,2)", + "rgb(153,52,4)", + "rgb(102,37,6)", +] + +YlOrRd = [ + "rgb(255,255,204)", + "rgb(255,237,160)", + "rgb(254,217,118)", + "rgb(254,178,76)", + "rgb(253,141,60)", + "rgb(252,78,42)", + "rgb(227,26,28)", + "rgb(189,0,38)", + "rgb(128,0,38)", +] + +Accent_r = Accent[::-1] +Blues_r = Blues[::-1] +BrBG_r = BrBG[::-1] +BuGn_r = BuGn[::-1] +BuPu_r = BuPu[::-1] +Dark2_r = Dark2[::-1] +GnBu_r = GnBu[::-1] +Greens_r = Greens[::-1] +Greys_r = Greys[::-1] +OrRd_r = OrRd[::-1] +Oranges_r = Oranges[::-1] +PRGn_r = PRGn[::-1] +Paired_r = Paired[::-1] +Pastel1_r = Pastel1[::-1] +Pastel2_r = Pastel2[::-1] +PiYG_r = PiYG[::-1] +PuBu_r = PuBu[::-1] +PuBuGn_r = PuBuGn[::-1] +PuOr_r = PuOr[::-1] +PuRd_r = PuRd[::-1] +Purples_r = Purples[::-1] +RdBu_r = RdBu[::-1] +RdGy_r = RdGy[::-1] +RdPu_r = RdPu[::-1] +RdYlBu_r = RdYlBu[::-1] +RdYlGn_r = RdYlGn[::-1] +Reds_r = Reds[::-1] +Set1_r = Set1[::-1] +Set2_r = Set2[::-1] +Set3_r = Set3[::-1] +Spectral_r = Spectral[::-1] +YlGn_r = YlGn[::-1] +YlGnBu_r = YlGnBu[::-1] +YlOrBr_r = YlOrBr[::-1] +YlOrRd_r = YlOrRd[::-1] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cyclical.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cyclical.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb7d07e2e3cda931db4014e5a9095448540377e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cyclical.py @@ -0,0 +1,157 @@ +""" +Cyclical color scales are appropriate for continuous data that has a natural cyclical \ +structure, such as temporal data (hour of day, day of week, day of year, seasons) or +complex numbers or other phase data. +""" + +from ._swatches import _swatches, _swatches_continuous, _swatches_cyclical + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + + +def swatches_continuous(template=None): + return _swatches_continuous(__name__, globals(), template) + + +swatches_continuous.__doc__ = _swatches_continuous.__doc__ + + +def swatches_cyclical(template=None): + return _swatches_cyclical(__name__, globals(), template) + + +swatches_cyclical.__doc__ = _swatches_cyclical.__doc__ + + +Twilight = [ + "#e2d9e2", + "#9ebbc9", + "#6785be", + "#5e43a5", + "#421257", + "#471340", + "#8e2c50", + "#ba6657", + "#ceac94", + "#e2d9e2", +] +IceFire = [ + "#000000", + "#001f4d", + "#003786", + "#0e58a8", + "#217eb8", + "#30a4ca", + "#54c8df", + "#9be4ef", + "#e1e9d1", + "#f3d573", + "#e7b000", + "#da8200", + "#c65400", + "#ac2301", + "#820000", + "#4c0000", + "#000000", +] +Edge = [ + "#313131", + "#3d019d", + "#3810dc", + "#2d47f9", + "#2593ff", + "#2adef6", + "#60fdfa", + "#aefdff", + "#f3f3f1", + "#fffda9", + "#fafd5b", + "#f7da29", + "#ff8e25", + "#f8432d", + "#d90d39", + "#97023d", + "#313131", +] +Phase = [ + "rgb(167, 119, 12)", + "rgb(197, 96, 51)", + "rgb(217, 67, 96)", + "rgb(221, 38, 163)", + "rgb(196, 59, 224)", + "rgb(153, 97, 244)", + "rgb(95, 127, 228)", + "rgb(40, 144, 183)", + "rgb(15, 151, 136)", + "rgb(39, 153, 79)", + "rgb(119, 141, 17)", + "rgb(167, 119, 12)", +] +HSV = [ + "#ff0000", + "#ffa700", + "#afff00", + "#08ff00", + "#00ff9f", + "#00b7ff", + "#0010ff", + "#9700ff", + "#ff00bf", + "#ff0000", +] +mrybm = [ + "#f884f7", + "#f968c4", + "#ea4388", + "#cf244b", + "#b51a15", + "#bd4304", + "#cc6904", + "#d58f04", + "#cfaa27", + "#a19f62", + "#588a93", + "#2269c4", + "#3e3ef0", + "#6b4ef9", + "#956bfa", + "#cd7dfe", + "#f884f7", +] +mygbm = [ + "#ef55f1", + "#fb84ce", + "#fbafa1", + "#fcd471", + "#f0ed35", + "#c6e516", + "#96d310", + "#61c10b", + "#31ac28", + "#439064", + "#3d719a", + "#284ec8", + "#2e21ea", + "#6324f5", + "#9139fa", + "#c543fa", + "#ef55f1", +] + +Edge_r = Edge[::-1] +HSV_r = HSV[::-1] +IceFire_r = IceFire[::-1] +Phase_r = Phase[::-1] +Twilight_r = Twilight[::-1] +mrybm_r = mrybm[::-1] +mygbm_r = mygbm[::-1] + +__all__ = [ + "swatches", + "swatches_cyclical", +] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/diverging.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/diverging.py new file mode 100644 index 0000000000000000000000000000000000000000..53170df9c097f81c225b0bc014868393523a1f72 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/diverging.py @@ -0,0 +1,75 @@ +""" +Diverging color scales are appropriate for continuous data that has a natural midpoint \ +other otherwise informative special value, such as 0 altitude, or the boiling point +of a liquid. The color scales in this module are \ +mostly meant to be passed in as the `color_continuous_scale` argument to various \ +functions, and to be used with the `color_continuous_midpoint` argument. +""" + +from .colorbrewer import ( # noqa: F401 + BrBG, + PRGn, + PiYG, + PuOr, + RdBu, + RdGy, + RdYlBu, + RdYlGn, + Spectral, + BrBG_r, + PRGn_r, + PiYG_r, + PuOr_r, + RdBu_r, + RdGy_r, + RdYlBu_r, + RdYlGn_r, + Spectral_r, +) +from .cmocean import ( # noqa: F401 + balance, + delta, + curl, + oxy, + balance_r, + delta_r, + curl_r, + oxy_r, +) +from .carto import ( # noqa: F401 + Armyrose, + Fall, + Geyser, + Temps, + Tealrose, + Tropic, + Earth, + Armyrose_r, + Fall_r, + Geyser_r, + Temps_r, + Tealrose_r, + Tropic_r, + Earth_r, +) + +from .plotlyjs import Picnic, Portland, Picnic_r, Portland_r # noqa: F401 + +from ._swatches import _swatches, _swatches_continuous + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + + +def swatches_continuous(template=None): + return _swatches_continuous(__name__, globals(), template) + + +swatches_continuous.__doc__ = _swatches_continuous.__doc__ + + +__all__ = ["swatches"] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/plotlyjs.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/plotlyjs.py new file mode 100644 index 0000000000000000000000000000000000000000..a49ae023e5c82d490bf6cd97a8d8d473d8f30c61 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/plotlyjs.py @@ -0,0 +1,180 @@ +# Copied from +# https://github.com/plotly/plotly.js/blob/master/src/components/colorscale/scales.js + +# NOTE: these differ slightly from plotly.colors.PLOTLY_SCALES from Plotly.js because +# those ones don't have perfectly evenly spaced steps ... +# not sure when this skew was introduced, possibly as early as Plotly.py v4.0 + +Blackbody = [ + "rgb(0,0,0)", + "rgb(230,0,0)", + "rgb(230,210,0)", + "rgb(255,255,255)", + "rgb(160,200,255)", +] +Bluered = ["rgb(0,0,255)", "rgb(255,0,0)"] +Blues = [ + "rgb(5,10,172)", + "rgb(40,60,190)", + "rgb(70,100,245)", + "rgb(90,120,245)", + "rgb(106,137,247)", + "rgb(220,220,220)", +] +Cividis = [ + "rgb(0,32,76)", + "rgb(0,42,102)", + "rgb(0,52,110)", + "rgb(39,63,108)", + "rgb(60,74,107)", + "rgb(76,85,107)", + "rgb(91,95,109)", + "rgb(104,106,112)", + "rgb(117,117,117)", + "rgb(131,129,120)", + "rgb(146,140,120)", + "rgb(161,152,118)", + "rgb(176,165,114)", + "rgb(192,177,109)", + "rgb(209,191,102)", + "rgb(225,204,92)", + "rgb(243,219,79)", + "rgb(255,233,69)", +] +Earth = [ + "rgb(0,0,130)", + "rgb(0,180,180)", + "rgb(40,210,40)", + "rgb(230,230,50)", + "rgb(120,70,20)", + "rgb(255,255,255)", +] +Electric = [ + "rgb(0,0,0)", + "rgb(30,0,100)", + "rgb(120,0,100)", + "rgb(160,90,0)", + "rgb(230,200,0)", + "rgb(255,250,220)", +] +Greens = [ + "rgb(0,68,27)", + "rgb(0,109,44)", + "rgb(35,139,69)", + "rgb(65,171,93)", + "rgb(116,196,118)", + "rgb(161,217,155)", + "rgb(199,233,192)", + "rgb(229,245,224)", + "rgb(247,252,245)", +] +Greys = ["rgb(0,0,0)", "rgb(255,255,255)"] +Hot = ["rgb(0,0,0)", "rgb(230,0,0)", "rgb(255,210,0)", "rgb(255,255,255)"] +Jet = [ + "rgb(0,0,131)", + "rgb(0,60,170)", + "rgb(5,255,255)", + "rgb(255,255,0)", + "rgb(250,0,0)", + "rgb(128,0,0)", +] +Picnic = [ + "rgb(0,0,255)", + "rgb(51,153,255)", + "rgb(102,204,255)", + "rgb(153,204,255)", + "rgb(204,204,255)", + "rgb(255,255,255)", + "rgb(255,204,255)", + "rgb(255,153,255)", + "rgb(255,102,204)", + "rgb(255,102,102)", + "rgb(255,0,0)", +] +Portland = [ + "rgb(12,51,131)", + "rgb(10,136,186)", + "rgb(242,211,56)", + "rgb(242,143,56)", + "rgb(217,30,30)", +] +Rainbow = [ + "rgb(150,0,90)", + "rgb(0,0,200)", + "rgb(0,25,255)", + "rgb(0,152,255)", + "rgb(44,255,150)", + "rgb(151,255,0)", + "rgb(255,234,0)", + "rgb(255,111,0)", + "rgb(255,0,0)", +] +RdBu = [ + "rgb(5,10,172)", + "rgb(106,137,247)", + "rgb(190,190,190)", + "rgb(220,170,132)", + "rgb(230,145,90)", + "rgb(178,10,28)", +] +Reds = ["rgb(220,220,220)", "rgb(245,195,157)", "rgb(245,160,105)", "rgb(178,10,28)"] +Viridis = [ + "#440154", + "#48186a", + "#472d7b", + "#424086", + "#3b528b", + "#33638d", + "#2c728e", + "#26828e", + "#21918c", + "#1fa088", + "#28ae80", + "#3fbc73", + "#5ec962", + "#84d44b", + "#addc30", + "#d8e219", + "#fde725", +] +YlGnBu = [ + "rgb(8,29,88)", + "rgb(37,52,148)", + "rgb(34,94,168)", + "rgb(29,145,192)", + "rgb(65,182,196)", + "rgb(127,205,187)", + "rgb(199,233,180)", + "rgb(237,248,217)", + "rgb(255,255,217)", +] +YlOrRd = [ + "rgb(128,0,38)", + "rgb(189,0,38)", + "rgb(227,26,28)", + "rgb(252,78,42)", + "rgb(253,141,60)", + "rgb(254,178,76)", + "rgb(254,217,118)", + "rgb(255,237,160)", + "rgb(255,255,204)", +] + +Blackbody_r = Blackbody[::-1] +Bluered_r = Bluered[::-1] +Blues_r = Blues[::-1] +Cividis_r = Cividis[::-1] +Earth_r = Earth[::-1] +Electric_r = Electric[::-1] +Greens_r = Greens[::-1] +Greys_r = Greys[::-1] +Hot_r = Hot[::-1] +Jet_r = Jet[::-1] +Picnic_r = Picnic[::-1] +Portland_r = Portland[::-1] +Rainbow_r = Rainbow[::-1] +RdBu_r = RdBu[::-1] +Reds_r = Reds[::-1] +Viridis_r = Viridis[::-1] +YlGnBu_r = YlGnBu[::-1] +YlOrRd_r = YlOrRd[::-1] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/qualitative.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/qualitative.py new file mode 100644 index 0000000000000000000000000000000000000000..c26a55783a790bd9c9f4a2fe32c0fe54a09d04c4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/qualitative.py @@ -0,0 +1,184 @@ +""" +Qualitative color sequences are appropriate for data that has no natural ordering, such \ +as categories, colors, names, countries etc. The color sequences in this module are \ +mostly meant to be passed in as the `color_discrete_sequence` argument to various functions. +""" + +from ._swatches import _swatches + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + +Plotly = [ + "#636EFA", + "#EF553B", + "#00CC96", + "#AB63FA", + "#FFA15A", + "#19D3F3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52", +] + +D3 = [ + "#1F77B4", + "#FF7F0E", + "#2CA02C", + "#D62728", + "#9467BD", + "#8C564B", + "#E377C2", + "#7F7F7F", + "#BCBD22", + "#17BECF", +] +G10 = [ + "#3366CC", + "#DC3912", + "#FF9900", + "#109618", + "#990099", + "#0099C6", + "#DD4477", + "#66AA00", + "#B82E2E", + "#316395", +] +T10 = [ + "#4C78A8", + "#F58518", + "#E45756", + "#72B7B2", + "#54A24B", + "#EECA3B", + "#B279A2", + "#FF9DA6", + "#9D755D", + "#BAB0AC", +] +Alphabet = [ + "#AA0DFE", + "#3283FE", + "#85660D", + "#782AB6", + "#565656", + "#1C8356", + "#16FF32", + "#F7E1A0", + "#E2E2E2", + "#1CBE4F", + "#C4451C", + "#DEA0FD", + "#FE00FA", + "#325A9B", + "#FEAF16", + "#F8A19F", + "#90AD1C", + "#F6222E", + "#1CFFCE", + "#2ED9FF", + "#B10DA1", + "#C075A6", + "#FC1CBF", + "#B00068", + "#FBE426", + "#FA0087", +] +Dark24 = [ + "#2E91E5", + "#E15F99", + "#1CA71C", + "#FB0D0D", + "#DA16FF", + "#222A2A", + "#B68100", + "#750D86", + "#EB663B", + "#511CFB", + "#00A08B", + "#FB00D1", + "#FC0080", + "#B2828D", + "#6C7C32", + "#778AAE", + "#862A16", + "#A777F1", + "#620042", + "#1616A7", + "#DA60CA", + "#6C4516", + "#0D2A63", + "#AF0038", +] +Light24 = [ + "#FD3216", + "#00FE35", + "#6A76FC", + "#FED4C4", + "#FE00CE", + "#0DF9FF", + "#F6F926", + "#FF9616", + "#479B55", + "#EEA6FB", + "#DC587D", + "#D626FF", + "#6E899C", + "#00B5F7", + "#B68E00", + "#C9FBE5", + "#FF0092", + "#22FFA7", + "#E3EE9E", + "#86CE00", + "#BC7196", + "#7E7DCD", + "#FC6955", + "#E48F72", +] + +Alphabet_r = Alphabet[::-1] +D3_r = D3[::-1] +Dark24_r = Dark24[::-1] +G10_r = G10[::-1] +Light24_r = Light24[::-1] +Plotly_r = Plotly[::-1] +T10_r = T10[::-1] + +from .colorbrewer import ( # noqa: E402 F401 + Set1, + Pastel1, + Dark2, + Set2, + Pastel2, + Set3, + Set1_r, + Pastel1_r, + Dark2_r, + Set2_r, + Pastel2_r, + Set3_r, +) +from .carto import ( # noqa: E402 F401 + Antique, + Bold, + Pastel, + Prism, + Safe, + Vivid, + Antique_r, + Bold_r, + Pastel_r, + Prism_r, + Safe_r, + Vivid_r, +) + + +__all__ = ["swatches"] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/sequential.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9ccf6b6fb2465677b031305ad307d4dd2ebae5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/sequential.py @@ -0,0 +1,257 @@ +""" +Sequential color scales are appropriate for most continuous data, but in some cases it \ +can be helpful to use a `plotly.colors.diverging` or \ +`plotly.colors.cyclical` scale instead. The color scales in this module are \ +mostly meant to be passed in as the `color_continuous_scale` argument to various functions. +""" + +from ._swatches import _swatches, _swatches_continuous + + +def swatches(template=None): + return _swatches(__name__, globals(), template) + + +swatches.__doc__ = _swatches.__doc__ + + +def swatches_continuous(template=None): + return _swatches_continuous(__name__, globals(), template) + + +swatches_continuous.__doc__ = _swatches_continuous.__doc__ + +Plotly3 = [ + "#0508b8", + "#1910d8", + "#3c19f0", + "#6b1cfb", + "#981cfd", + "#bf1cfd", + "#dd2bfd", + "#f246fe", + "#fc67fd", + "#fe88fc", + "#fea5fd", + "#febefe", + "#fec3fe", +] + +Viridis = [ + "#440154", + "#482878", + "#3e4989", + "#31688e", + "#26828e", + "#1f9e89", + "#35b779", + "#6ece58", + "#b5de2b", + "#fde725", +] +Cividis = [ + "#00224e", + "#123570", + "#3b496c", + "#575d6d", + "#707173", + "#8a8678", + "#a59c74", + "#c3b369", + "#e1cc55", + "#fee838", +] + +Inferno = [ + "#000004", + "#1b0c41", + "#4a0c6b", + "#781c6d", + "#a52c60", + "#cf4446", + "#ed6925", + "#fb9b06", + "#f7d13d", + "#fcffa4", +] +Magma = [ + "#000004", + "#180f3d", + "#440f76", + "#721f81", + "#9e2f7f", + "#cd4071", + "#f1605d", + "#fd9668", + "#feca8d", + "#fcfdbf", +] +Plasma = [ + "#0d0887", + "#46039f", + "#7201a8", + "#9c179e", + "#bd3786", + "#d8576b", + "#ed7953", + "#fb9f3a", + "#fdca26", + "#f0f921", +] +Turbo = [ + "#30123b", + "#4145ab", + "#4675ed", + "#39a2fc", + "#1bcfd4", + "#24eca6", + "#61fc6c", + "#a4fc3b", + "#d1e834", + "#f3c63a", + "#fe9b2d", + "#f36315", + "#d93806", + "#b11901", + "#7a0402", +] + +Cividis_r = Cividis[::-1] +Inferno_r = Inferno[::-1] +Magma_r = Magma[::-1] +Plasma_r = Plasma[::-1] +Plotly3_r = Plotly3[::-1] +Turbo_r = Turbo[::-1] +Viridis_r = Viridis[::-1] + +from .plotlyjs import ( # noqa: E402 F401 + Blackbody, + Bluered, + Electric, + Hot, + Jet, + Rainbow, + Blackbody_r, + Bluered_r, + Electric_r, + Hot_r, + Jet_r, + Rainbow_r, +) + +from .colorbrewer import ( # noqa: E402 F401 + Blues, + BuGn, + BuPu, + GnBu, + Greens, + Greys, + OrRd, + Oranges, + PuBu, + PuBuGn, + PuRd, + Purples, + RdBu, + RdPu, + Reds, + YlGn, + YlGnBu, + YlOrBr, + YlOrRd, + Blues_r, + BuGn_r, + BuPu_r, + GnBu_r, + Greens_r, + Greys_r, + OrRd_r, + Oranges_r, + PuBu_r, + PuBuGn_r, + PuRd_r, + Purples_r, + RdBu_r, + RdPu_r, + Reds_r, + YlGn_r, + YlGnBu_r, + YlOrBr_r, + YlOrRd_r, +) + +from .cmocean import ( # noqa: E402 F401 + turbid, + thermal, + haline, + solar, + ice, + gray, + deep, + dense, + algae, + matter, + speed, + amp, + tempo, + turbid_r, + thermal_r, + haline_r, + solar_r, + ice_r, + gray_r, + deep_r, + dense_r, + algae_r, + matter_r, + speed_r, + amp_r, + tempo_r, +) + +from .carto import ( # noqa: E402 F401 + Burg, + Burgyl, + Redor, + Oryel, + Peach, + Pinkyl, + Mint, + Blugrn, + Darkmint, + Emrld, + Aggrnyl, + Bluyl, + Teal, + Tealgrn, + Purp, + Purpor, + Sunset, + Magenta, + Sunsetdark, + Agsunset, + Brwnyl, + Burg_r, + Burgyl_r, + Redor_r, + Oryel_r, + Peach_r, + Pinkyl_r, + Mint_r, + Blugrn_r, + Darkmint_r, + Emrld_r, + Aggrnyl_r, + Bluyl_r, + Teal_r, + Tealgrn_r, + Purp_r, + Purpor_r, + Sunset_r, + Magenta_r, + Sunsetdark_r, + Agsunset_r, + Brwnyl_r, +) + +__all__ = ["swatches"] diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/data_utils.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb05b03114c4475fe2040d7808a1f3b63676558 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/data_utils.py @@ -0,0 +1,75 @@ +from io import BytesIO +import base64 +from .png import Writer, from_array + +try: + from PIL import Image + + pil_imported = True +except ImportError: + pil_imported = False + + +def image_array_to_data_uri(img, backend="pil", compression=4, ext="png"): + """Converts a numpy array of uint8 into a base64 png or jpg string. + + Parameters + ---------- + img: ndarray of uint8 + array image + backend: str + 'auto', 'pil' or 'pypng'. If 'auto', Pillow is used if installed, + otherwise pypng. + compression: int, between 0 and 9 + compression level to be passed to the backend + ext: str, 'png' or 'jpg' + compression format used to generate b64 string + """ + # PIL and pypng error messages are quite obscure so we catch invalid compression values + if compression < 0 or compression > 9: + raise ValueError("compression level must be between 0 and 9.") + alpha = False + if img.ndim == 2: + mode = "L" + elif img.ndim == 3 and img.shape[-1] == 3: + mode = "RGB" + elif img.ndim == 3 and img.shape[-1] == 4: + mode = "RGBA" + alpha = True + else: + raise ValueError("Invalid image shape") + if backend == "auto": + backend = "pil" if pil_imported else "pypng" + if ext != "png" and backend != "pil": + raise ValueError("jpg binary strings are only available with PIL backend") + + if backend == "pypng": + ndim = img.ndim + sh = img.shape + if ndim == 3: + img = img.reshape((sh[0], sh[1] * sh[2])) + w = Writer( + sh[1], sh[0], greyscale=(ndim == 2), alpha=alpha, compression=compression + ) + img_png = from_array(img, mode=mode) + prefix = "data:image/png;base64," + with BytesIO() as stream: + w.write(stream, img_png.rows) + base64_string = prefix + base64.b64encode(stream.getvalue()).decode("utf-8") + else: # pil + if not pil_imported: + raise ImportError( + "pillow needs to be installed to use `backend='pil'. Please" + "install pillow or use `backend='pypng'." + ) + pil_img = Image.fromarray(img) + if ext == "jpg" or ext == "jpeg": + prefix = "data:image/jpeg;base64," + ext = "jpeg" + else: + prefix = "data:image/png;base64," + ext = "png" + with BytesIO() as stream: + pil_img.save(stream, format=ext, compress_level=compression) + base64_string = prefix + base64.b64encode(stream.getvalue()).decode("utf-8") + return base64_string diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/exceptions.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..836ef59e21532334561044a7bf2f9db92d72bb6d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/exceptions.py @@ -0,0 +1,97 @@ +class PlotlyError(Exception): + pass + + +class PlotlyEmptyDataError(PlotlyError): + pass + + +class PlotlyGraphObjectError(PlotlyError): + def __init__(self, message="", path=(), notes=()): + """ + General graph object error for validation failures. + + :param (str|unicode) message: The error message. + :param (iterable) path: A path pointing to the error. + :param notes: Add additional notes, but keep default exception message. + + """ + self.message = message + self.plain_message = message # for backwards compat + self.path = list(path) + self.notes = notes + super(PlotlyGraphObjectError, self).__init__(message) + + def __str__(self): + """This is called by Python to present the error message.""" + format_dict = { + "message": self.message, + "path": "[" + "][".join(repr(k) for k in self.path) + "]", + "notes": "\n".join(self.notes), + } + return "{message}\n\nPath To Error: {path}\n\n{notes}".format(**format_dict) + + +class PlotlyDictKeyError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"attribute": path[-1], "object_name": obj._name} + message = "'{attribute}' is not allowed in '{object_name}'".format( + **format_dict + ) + notes = [obj.help(return_help=True)] + list(notes) + super(PlotlyDictKeyError, self).__init__( + message=message, path=path, notes=notes + ) + + +class PlotlyDictValueError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"attribute": path[-1], "object_name": obj._name} + message = "'{attribute}' has invalid value inside '{object_name}'".format( + **format_dict + ) + notes = [obj.help(path[-1], return_help=True)] + list(notes) + super(PlotlyDictValueError, self).__init__( + message=message, notes=notes, path=path + ) + + +class PlotlyListEntryError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"index": path[-1], "object_name": obj._name} + message = "Invalid entry found in '{object_name}' at index, '{index}'".format( + **format_dict + ) + notes = [obj.help(return_help=True)] + list(notes) + super(PlotlyListEntryError, self).__init__( + message=message, path=path, notes=notes + ) + + +class PlotlyDataTypeError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"index": path[-1], "object_name": obj._name} + message = "Invalid entry found in '{object_name}' at index, '{index}'".format( + **format_dict + ) + note = "It's invalid because it doesn't contain a valid 'type' value." + notes = [note] + list(notes) + super(PlotlyDataTypeError, self).__init__( + message=message, path=path, notes=notes + ) + + +class PlotlyKeyError(KeyError): + """ + KeyErrors are not printed as beautifully as other errors (this is so that + {}[''] prints "KeyError: ''" and not "KeyError:"). So here we use + LookupError's __str__ to make a PlotlyKeyError object which will print nicer + error messages for KeyErrors. + """ + + def __str__(self): + return LookupError.__str__(self) diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/files.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/files.py new file mode 100644 index 0000000000000000000000000000000000000000..68d11bd4a69bdd172b92c7cad32a670dfaa872e1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/files.py @@ -0,0 +1,37 @@ +import os + +PLOTLY_DIR = os.environ.get( + "PLOTLY_DIR", os.path.join(os.path.expanduser("~"), ".plotly") +) +TEST_FILE = os.path.join(PLOTLY_DIR, ".permission_test") + + +def _permissions(): + try: + if not os.path.exists(PLOTLY_DIR): + try: + os.mkdir(PLOTLY_DIR) + except Exception: + # in case of race + if not os.path.isdir(PLOTLY_DIR): + raise + with open(TEST_FILE, "w") as f: + f.write("testing\n") + try: + os.remove(TEST_FILE) + except Exception: + pass + return True + except Exception: # Do not trap KeyboardInterrupt. + return False + + +_file_permissions = None + + +def ensure_writable_plotly_dir(): + # Cache permissions status + global _file_permissions + if _file_permissions is None: + _file_permissions = _permissions() + return _file_permissions diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/importers.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/importers.py new file mode 100644 index 0000000000000000000000000000000000000000..20c77c1c8433649c0e1526e0616294036f9ec64a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/importers.py @@ -0,0 +1,50 @@ +import importlib + + +def relative_import(parent_name, rel_modules=(), rel_classes=()): + """ + Helper function to import submodules lazily in Python 3.7+ + + Parameters + ---------- + rel_modules: list of str + list of submodules to import, of the form .submodule + rel_classes: list of str + list of submodule classes/variables to import, of the form ._submodule.Foo + + Returns + ------- + tuple + Tuple that should be assigned to __all__, __getattr__ in the caller + """ + module_names = {rel_module.split(".")[-1]: rel_module for rel_module in rel_modules} + class_names = {rel_path.split(".")[-1]: rel_path for rel_path in rel_classes} + + def __getattr__(import_name): + # In Python 3.7+, lazy import submodules + + # Check for submodule + if import_name in module_names: + rel_import = module_names[import_name] + return importlib.import_module(rel_import, parent_name) + + # Check for submodule class + if import_name in class_names: + rel_path_parts = class_names[import_name].split(".") + rel_module = ".".join(rel_path_parts[:-1]) + class_name = import_name + class_module = importlib.import_module(rel_module, parent_name) + return getattr(class_module, class_name) + + raise AttributeError( + "module {__name__!r} has no attribute {name!r}".format( + name=import_name, __name__=parent_name + ) + ) + + __all__ = list(module_names) + list(class_names) + + def __dir__(): + return __all__ + + return __all__, __getattr__, __dir__ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/optional_imports.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/optional_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a31e087a34fe445683a2c55a20ff8e99d123a24c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/optional_imports.py @@ -0,0 +1,36 @@ +""" +Stand-alone module to provide information about whether optional deps exist. + +""" + +from importlib import import_module +import logging +import sys + +logger = logging.getLogger(__name__) +_not_importable = set() + + +def get_module(name, should_load=True): + """ + Return module or None. Absolute import is required. + + :param (str) name: Dot-separated module path. E.g., 'scipy.stats'. + :raise: (ImportError) Only when exc_msg is defined. + :return: (module|None) If import succeeds, the module will be returned. + + """ + if not should_load: + return sys.modules.get(name, None) + + if name not in _not_importable: + try: + return import_module(name) + except ImportError: + _not_importable.add(name) + except Exception: + _not_importable.add(name) + msg = f"Error importing optional module {name}" + logger.exception(msg) + + return None diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/png.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/png.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9e58560f2867a0fe1d113f83101756c5fcc373 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/png.py @@ -0,0 +1,2350 @@ +#!/usr/bin/env python + +# Vendored code from pypng https://github.com/drj11/pypng +# png.py - PNG encoder/decoder in pure Python +# +# Copyright (C) 2006 Johann C. Rocholl +# Portions Copyright (C) 2009 David Jones +# And probably portions Copyright (C) 2006 Nicko van Someren +# +# Original concept by Johann C. Rocholl. +# +# LICENCE (MIT) +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +""" +The ``png`` module can read and write PNG files. + +Installation and Overview +------------------------- + +``pip install pypng`` + +For help, type ``import png; help(png)`` in your python interpreter. + +A good place to start is the :class:`Reader` and :class:`Writer` classes. + +Coverage of PNG formats is fairly complete; +all allowable bit depths (1/2/4/8/16/24/32/48/64 bits per pixel) and +colour combinations are supported: + +- greyscale (1/2/4/8/16 bit); +- RGB, RGBA, LA (greyscale with alpha) with 8/16 bits per channel; +- colour mapped images (1/2/4/8 bit). + +Interlaced images, +which support a progressive display when downloading, +are supported for both reading and writing. + +A number of optional chunks can be specified (when writing) +and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``. + +The ``sBIT`` chunk can be used to specify precision for +non-native bit depths. + +Requires Python 3.5 or higher. +Installation is trivial, +but see the ``README.txt`` file (with the source distribution) for details. + +Full use of all features will need some reading of the PNG specification +http://www.w3.org/TR/2003/REC-PNG-20031110/. + +The package also comes with command line utilities. + +- ``pripamtopng`` converts + `Netpbm `_ PAM/PNM files to PNG; +- ``pripngtopam`` converts PNG to file PAM/PNM. + +There are a few more for simple PNG manipulations. + +Spelling and Terminology +------------------------ + +Generally British English spelling is used in the documentation. +So that's "greyscale" and "colour". +This not only matches the author's native language, +it's also used by the PNG specification. + +Colour Models +------------- + +The major colour models supported by PNG (and hence by PyPNG) are: + +- greyscale; +- greyscale--alpha; +- RGB; +- RGB--alpha. + +Also referred to using the abbreviations: L, LA, RGB, RGBA. +Each letter codes a single channel: +*L* is for Luminance or Luma or Lightness (greyscale images); +*A* stands for Alpha, the opacity channel +(used for transparency effects, but higher values are more opaque, +so it makes sense to call it opacity); +*R*, *G*, *B* stand for Red, Green, Blue (colour image). + +Lists, arrays, sequences, and so on +----------------------------------- + +When getting pixel data out of this module (reading) and +presenting data to this module (writing) there are +a number of ways the data could be represented as a Python value. + +The preferred format is a sequence of *rows*, +which each row being a sequence of *values*. +In this format, the values are in pixel order, +with all the values from all the pixels in a row +being concatenated into a single sequence for that row. + +Consider an image that is 3 pixels wide by 2 pixels high, and each pixel +has RGB components: + +Sequence of rows:: + + list([R,G,B, R,G,B, R,G,B], + [R,G,B, R,G,B, R,G,B]) + +Each row appears as its own list, +but the pixels are flattened so that three values for one pixel +simply follow the three values for the previous pixel. + +This is the preferred because +it provides a good compromise between space and convenience. +PyPNG regards itself as at liberty to replace any sequence type with +any sufficiently compatible other sequence type; +in practice each row is an array (``bytearray`` or ``array.array``). + +To allow streaming the outer list is sometimes +an iterator rather than an explicit list. + +An alternative format is a single array holding all the values. + +Array of values:: + + [R,G,B, R,G,B, R,G,B, + R,G,B, R,G,B, R,G,B] + +The entire image is one single giant sequence of colour values. +Generally an array will be used (to save space), not a list. + +The top row comes first, +and within each row the pixels are ordered from left-to-right. +Within a pixel the values appear in the order R-G-B-A +(or L-A for greyscale--alpha). + +There is another format, which should only be used with caution. +It is mentioned because it is used internally, +is close to what lies inside a PNG file itself, +and has some support from the public API. +This format is called *packed*. +When packed, each row is a sequence of bytes (integers from 0 to 255), +just as it is before PNG scanline filtering is applied. +When the bit depth is 8 this is the same as a sequence of rows; +when the bit depth is less than 8 (1, 2 and 4), +several pixels are packed into each byte; +when the bit depth is 16 each pixel value is decomposed into 2 bytes +(and `packed` is a misnomer). +This format is used by the :meth:`Writer.write_packed` method. +It isn't usually a convenient format, +but may be just right if the source data for +the PNG image comes from something that uses a similar format +(for example, 1-bit BMPs, or another PNG file). +""" + +__version__ = "0.0.20" + +import collections +import io # For io.BytesIO +import itertools +import math + +# http://www.python.org/doc/2.4.4/lib/module-operator.html +import operator +import re +import struct +import sys + +# http://www.python.org/doc/2.4.4/lib/module-warnings.html +import warnings +import zlib + +from array import array + + +__all__ = ["Image", "Reader", "Writer", "write_chunks", "from_array"] + + +# The PNG signature. +# http://www.w3.org/TR/PNG/#5PNG-file-signature +signature = struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10) + +# The xstart, ystart, xstep, ystep for the Adam7 interlace passes. +adam7 = ( + (0, 0, 8, 8), + (4, 0, 8, 8), + (0, 4, 4, 8), + (2, 0, 4, 4), + (0, 2, 2, 4), + (1, 0, 2, 2), + (0, 1, 1, 2), +) + + +def adam7_generate(width, height): + """ + Generate the coordinates for the reduced scanlines + of an Adam7 interlaced image + of size `width` by `height` pixels. + + Yields a generator for each pass, + and each pass generator yields a series of (x, y, xstep) triples, + each one identifying a reduced scanline consisting of + pixels starting at (x, y) and taking every xstep pixel to the right. + """ + + for xstart, ystart, xstep, ystep in adam7: + if xstart >= width: + continue + yield ((xstart, y, xstep) for y in range(ystart, height, ystep)) + + +# Models the 'pHYs' chunk (used by the Reader) +Resolution = collections.namedtuple("_Resolution", "x y unit_is_meter") + + +def group(s, n): + return list(zip(*[iter(s)] * n)) + + +def isarray(x): + return isinstance(x, array) + + +def check_palette(palette): + """ + Check a palette argument (to the :class:`Writer` class) for validity. + Returns the palette as a list if okay; + raises an exception otherwise. + """ + + # None is the default and is allowed. + if palette is None: + return None + + p = list(palette) + if not (0 < len(p) <= 256): + raise ProtocolError( + "a palette must have between 1 and 256 entries," + " see https://www.w3.org/TR/PNG/#11PLTE" + ) + seen_triple = False + for i, t in enumerate(p): + if len(t) not in (3, 4): + raise ProtocolError("palette entry %d: entries must be 3- or 4-tuples." % i) + if len(t) == 3: + seen_triple = True + if seen_triple and len(t) == 4: + raise ProtocolError( + "palette entry %d: all 4-tuples must precede all 3-tuples" % i + ) + for x in t: + if int(x) != x or not (0 <= x <= 255): + raise ProtocolError( + "palette entry %d: values must be integer: 0 <= x <= 255" % i + ) + return p + + +def check_sizes(size, width, height): + """ + Check that these arguments, if supplied, are consistent. + Return a (width, height) pair. + """ + + if not size: + return width, height + + if len(size) != 2: + raise ProtocolError("size argument should be a pair (width, height)") + if width is not None and width != size[0]: + raise ProtocolError( + "size[0] (%r) and width (%r) should match when both are used." + % (size[0], width) + ) + if height is not None and height != size[1]: + raise ProtocolError( + "size[1] (%r) and height (%r) should match when both are used." + % (size[1], height) + ) + return size + + +def check_color(c, greyscale, which): + """ + Checks that a colour argument for transparent or background options + is the right form. + Returns the colour + (which, if it's a bare integer, is "corrected" to a 1-tuple). + """ + + if c is None: + return c + if greyscale: + try: + len(c) + except TypeError: + c = (c,) + if len(c) != 1: + raise ProtocolError("%s for greyscale must be 1-tuple" % which) + if not is_natural(c[0]): + raise ProtocolError("%s colour for greyscale must be integer" % which) + else: + if not ( + len(c) == 3 and is_natural(c[0]) and is_natural(c[1]) and is_natural(c[2]) + ): + raise ProtocolError("%s colour must be a triple of integers" % which) + return c + + +class Error(Exception): + def __str__(self): + return self.__class__.__name__ + ": " + " ".join(self.args) + + +class FormatError(Error): + """ + Problem with input file format. + In other words, PNG file does not conform to + the specification in some way and is invalid. + """ + + +class ProtocolError(Error): + """ + Problem with the way the programming interface has been used, + or the data presented to it. + """ + + +class ChunkError(FormatError): + pass + + +class Default: + """The default for the greyscale paramter.""" + + +class Writer: + """ + PNG encoder in pure Python. + """ + + def __init__( + self, + width=None, + height=None, + size=None, + greyscale=Default, + alpha=False, + bitdepth=8, + palette=None, + transparent=None, + background=None, + gamma=None, + compression=None, + interlace=False, + planes=None, + colormap=None, + maxval=None, + chunk_limit=2**20, + x_pixels_per_unit=None, + y_pixels_per_unit=None, + unit_is_meter=False, + ): + """ + Create a PNG encoder object. + + Arguments: + + width, height + Image size in pixels, as two separate arguments. + size + Image size (w,h) in pixels, as single argument. + greyscale + Pixels are greyscale, not RGB. + alpha + Input data has alpha channel (RGBA or LA). + bitdepth + Bit depth: from 1 to 16 (for each channel). + palette + Create a palette for a colour mapped image (colour type 3). + transparent + Specify a transparent colour (create a ``tRNS`` chunk). + background + Specify a default background colour (create a ``bKGD`` chunk). + gamma + Specify a gamma value (create a ``gAMA`` chunk). + compression + zlib compression level: 0 (none) to 9 (more compressed); + default: -1 or None. + interlace + Create an interlaced image. + chunk_limit + Write multiple ``IDAT`` chunks to save memory. + x_pixels_per_unit + Number of pixels a unit along the x axis (write a + `pHYs` chunk). + y_pixels_per_unit + Number of pixels a unit along the y axis (write a + `pHYs` chunk). Along with `x_pixel_unit`, this gives + the pixel size ratio. + unit_is_meter + `True` to indicate that the unit (for the `pHYs` + chunk) is metre. + + The image size (in pixels) can be specified either by using the + `width` and `height` arguments, or with the single `size` + argument. + If `size` is used it should be a pair (*width*, *height*). + + The `greyscale` argument indicates whether input pixels + are greyscale (when true), or colour (when false). + The default is true unless `palette=` is used. + + The `alpha` argument (a boolean) specifies + whether input pixels have an alpha channel (or not). + + `bitdepth` specifies the bit depth of the source pixel values. + Each channel may have a different bit depth. + Each source pixel must have values that are + an integer between 0 and ``2**bitdepth-1``, where + `bitdepth` is the bit depth for the corresponding channel. + For example, 8-bit images have values between 0 and 255. + PNG only stores images with bit depths of + 1,2,4,8, or 16 (the same for all channels). + When `bitdepth` is not one of these values or where + channels have different bit depths, + the next highest valid bit depth is selected, + and an ``sBIT`` (significant bits) chunk is generated + that specifies the original precision of the source image. + In this case the supplied pixel values will be rescaled to + fit the range of the selected bit depth. + + The PNG file format supports many bit depth / colour model + combinations, but not all. + The details are somewhat arcane + (refer to the PNG specification for full details). + Briefly: + Bit depths < 8 (1,2,4) are only allowed with greyscale and + colour mapped images; + colour mapped images cannot have bit depth 16. + + For colour mapped images + (in other words, when the `palette` argument is specified) + the `bitdepth` argument must match one of + the valid PNG bit depths: 1, 2, 4, or 8. + (It is valid to have a PNG image with a palette and + an ``sBIT`` chunk, but the meaning is slightly different; + it would be awkward to use the `bitdepth` argument for this.) + + The `palette` option, when specified, + causes a colour mapped image to be created: + the PNG colour type is set to 3; + `greyscale` must not be true; `alpha` must not be true; + `transparent` must not be set. + The bit depth must be 1,2,4, or 8. + When a colour mapped image is created, + the pixel values are palette indexes and + the `bitdepth` argument specifies the size of these indexes + (not the size of the colour values in the palette). + + The palette argument value should be a sequence of 3- or + 4-tuples. + 3-tuples specify RGB palette entries; + 4-tuples specify RGBA palette entries. + All the 4-tuples (if present) must come before all the 3-tuples. + A ``PLTE`` chunk is created; + if there are 4-tuples then a ``tRNS`` chunk is created as well. + The ``PLTE`` chunk will contain all the RGB triples in the same + sequence; + the ``tRNS`` chunk will contain the alpha channel for + all the 4-tuples, in the same sequence. + Palette entries are always 8-bit. + + If specified, the `transparent` and `background` parameters must be + a tuple with one element for each channel in the image. + Either a 3-tuple of integer (RGB) values for a colour image, or + a 1-tuple of a single integer for a greyscale image. + + If specified, the `gamma` parameter must be a positive number + (generally, a `float`). + A ``gAMA`` chunk will be created. + Note that this will not change the values of the pixels as + they appear in the PNG file, + they are assumed to have already + been converted appropriately for the gamma specified. + + The `compression` argument specifies the compression level to + be used by the ``zlib`` module. + Values from 1 to 9 (highest) specify compression. + 0 means no compression. + -1 and ``None`` both mean that the ``zlib`` module uses + the default level of compession (which is generally acceptable). + + If `interlace` is true then an interlaced image is created + (using PNG's so far only interace method, *Adam7*). + This does not affect how the pixels should be passed in, + rather it changes how they are arranged into the PNG file. + On slow connexions interlaced images can be + partially decoded by the browser to give + a rough view of the image that is + successively refined as more image data appears. + + .. note :: + + Enabling the `interlace` option requires the entire image + to be processed in working memory. + + `chunk_limit` is used to limit the amount of memory used whilst + compressing the image. + In order to avoid using large amounts of memory, + multiple ``IDAT`` chunks may be created. + """ + + # At the moment the `planes` argument is ignored; + # its purpose is to act as a dummy so that + # ``Writer(x, y, **info)`` works, where `info` is a dictionary + # returned by Reader.read and friends. + # Ditto for `colormap`. + + width, height = check_sizes(size, width, height) + del size + + if not is_natural(width) or not is_natural(height): + raise ProtocolError("width and height must be integers") + if width <= 0 or height <= 0: + raise ProtocolError("width and height must be greater than zero") + # http://www.w3.org/TR/PNG/#7Integers-and-byte-order + if width > 2**31 - 1 or height > 2**31 - 1: + raise ProtocolError("width and height cannot exceed 2**31-1") + + if alpha and transparent is not None: + raise ProtocolError("transparent colour not allowed with alpha channel") + + # bitdepth is either single integer, or tuple of integers. + # Convert to tuple. + try: + len(bitdepth) + except TypeError: + bitdepth = (bitdepth,) + for b in bitdepth: + valid = is_natural(b) and 1 <= b <= 16 + if not valid: + raise ProtocolError( + "each bitdepth %r must be a positive integer <= 16" % (bitdepth,) + ) + + # Calculate channels, and + # expand bitdepth to be one element per channel. + palette = check_palette(palette) + alpha = bool(alpha) + colormap = bool(palette) + if greyscale is Default and palette: + greyscale = False + greyscale = bool(greyscale) + if colormap: + color_planes = 1 + planes = 1 + else: + color_planes = (3, 1)[greyscale] + planes = color_planes + alpha + if len(bitdepth) == 1: + bitdepth *= planes + + bitdepth, self.rescale = check_bitdepth_rescale( + palette, bitdepth, transparent, alpha, greyscale + ) + + # These are assertions, because above logic should have + # corrected or raised all problematic cases. + if bitdepth < 8: + assert greyscale or palette + assert not alpha + if bitdepth > 8: + assert not palette + + transparent = check_color(transparent, greyscale, "transparent") + background = check_color(background, greyscale, "background") + + # It's important that the true boolean values + # (greyscale, alpha, colormap, interlace) are converted + # to bool because Iverson's convention is relied upon later on. + self.width = width + self.height = height + self.transparent = transparent + self.background = background + self.gamma = gamma + self.greyscale = greyscale + self.alpha = alpha + self.colormap = colormap + self.bitdepth = int(bitdepth) + self.compression = compression + self.chunk_limit = chunk_limit + self.interlace = bool(interlace) + self.palette = palette + self.x_pixels_per_unit = x_pixels_per_unit + self.y_pixels_per_unit = y_pixels_per_unit + self.unit_is_meter = bool(unit_is_meter) + + self.color_type = 4 * self.alpha + 2 * (not greyscale) + 1 * self.colormap + assert self.color_type in (0, 2, 3, 4, 6) + + self.color_planes = color_planes + self.planes = planes + # :todo: fix for bitdepth < 8 + self.psize = (self.bitdepth / 8) * self.planes + + def write(self, outfile, rows): + """ + Write a PNG image to the output file. + `rows` should be an iterable that yields each row + (each row is a sequence of values). + The rows should be the rows of the original image, + so there should be ``self.height`` rows of + ``self.width * self.planes`` values. + If `interlace` is specified (when creating the instance), + then an interlaced PNG file will be written. + Supply the rows in the normal image order; + the interlacing is carried out internally. + + .. note :: + + Interlacing requires the entire image to be in working memory. + """ + + # Values per row + vpr = self.width * self.planes + + def check_rows(rows): + """ + Yield each row in rows, + but check each row first (for correct width). + """ + for i, row in enumerate(rows): + try: + wrong_length = len(row) != vpr + except TypeError: + # When using an itertools.ichain object or + # other generator not supporting __len__, + # we set this to False to skip the check. + wrong_length = False + if wrong_length: + # Note: row numbers start at 0. + raise ProtocolError( + "Expected %d values but got %d values, in row %d" + % (vpr, len(row), i) + ) + yield row + + if self.interlace: + fmt = "BH"[self.bitdepth > 8] + a = array(fmt, itertools.chain(*check_rows(rows))) + return self.write_array(outfile, a) + + nrows = self.write_passes(outfile, check_rows(rows)) + if nrows != self.height: + raise ProtocolError( + "rows supplied (%d) does not match height (%d)" % (nrows, self.height) + ) + + def write_passes(self, outfile, rows): + """ + Write a PNG image to the output file. + + Most users are expected to find the :meth:`write` or + :meth:`write_array` method more convenient. + + The rows should be given to this method in the order that + they appear in the output file. + For straightlaced images, this is the usual top to bottom ordering. + For interlaced images the rows should have been interlaced before + passing them to this function. + + `rows` should be an iterable that yields each row + (each row being a sequence of values). + """ + + # Ensure rows are scaled (to 4-/8-/16-bit), + # and packed into bytes. + + if self.rescale: + rows = rescale_rows(rows, self.rescale) + + if self.bitdepth < 8: + rows = pack_rows(rows, self.bitdepth) + elif self.bitdepth == 16: + rows = unpack_rows(rows) + + return self.write_packed(outfile, rows) + + def write_packed(self, outfile, rows): + """ + Write PNG file to `outfile`. + `rows` should be an iterator that yields each packed row; + a packed row being a sequence of packed bytes. + + The rows have a filter byte prefixed and + are then compressed into one or more IDAT chunks. + They are not processed any further, + so if bitdepth is other than 1, 2, 4, 8, 16, + the pixel values should have been scaled + before passing them to this method. + + This method does work for interlaced images but it is best avoided. + For interlaced images, the rows should be + presented in the order that they appear in the file. + """ + + self.write_preamble(outfile) + + # http://www.w3.org/TR/PNG/#11IDAT + if self.compression is not None: + compressor = zlib.compressobj(self.compression) + else: + compressor = zlib.compressobj() + + # data accumulates bytes to be compressed for the IDAT chunk; + # it's compressed when sufficiently large. + data = bytearray() + + for i, row in enumerate(rows): + # Add "None" filter type. + # Currently, it's essential that this filter type be used + # for every scanline as + # we do not mark the first row of a reduced pass image; + # that means we could accidentally compute + # the wrong filtered scanline if we used + # "up", "average", or "paeth" on such a line. + data.append(0) + data.extend(row) + if len(data) > self.chunk_limit: + compressed = compressor.compress(data) + if len(compressed): + write_chunk(outfile, b"IDAT", compressed) + data = bytearray() + + compressed = compressor.compress(bytes(data)) + flushed = compressor.flush() + if len(compressed) or len(flushed): + write_chunk(outfile, b"IDAT", compressed + flushed) + # http://www.w3.org/TR/PNG/#11IEND + write_chunk(outfile, b"IEND") + return i + 1 + + def write_preamble(self, outfile): + # http://www.w3.org/TR/PNG/#5PNG-file-signature + outfile.write(signature) + + # http://www.w3.org/TR/PNG/#11IHDR + write_chunk( + outfile, + b"IHDR", + struct.pack( + "!2I5B", + self.width, + self.height, + self.bitdepth, + self.color_type, + 0, + 0, + self.interlace, + ), + ) + + # See :chunk:order + # http://www.w3.org/TR/PNG/#11gAMA + if self.gamma is not None: + write_chunk( + outfile, b"gAMA", struct.pack("!L", int(round(self.gamma * 1e5))) + ) + + # See :chunk:order + # http://www.w3.org/TR/PNG/#11sBIT + if self.rescale: + write_chunk( + outfile, + b"sBIT", + struct.pack("%dB" % self.planes, *[s[0] for s in self.rescale]), + ) + + # :chunk:order: Without a palette (PLTE chunk), + # ordering is relatively relaxed. + # With one, gAMA chunk must precede PLTE chunk + # which must precede tRNS and bKGD. + # See http://www.w3.org/TR/PNG/#5ChunkOrdering + if self.palette: + p, t = make_palette_chunks(self.palette) + write_chunk(outfile, b"PLTE", p) + if t: + # tRNS chunk is optional; + # Only needed if palette entries have alpha. + write_chunk(outfile, b"tRNS", t) + + # http://www.w3.org/TR/PNG/#11tRNS + if self.transparent is not None: + if self.greyscale: + fmt = "!1H" + else: + fmt = "!3H" + write_chunk(outfile, b"tRNS", struct.pack(fmt, *self.transparent)) + + # http://www.w3.org/TR/PNG/#11bKGD + if self.background is not None: + if self.greyscale: + fmt = "!1H" + else: + fmt = "!3H" + write_chunk(outfile, b"bKGD", struct.pack(fmt, *self.background)) + + # http://www.w3.org/TR/PNG/#11pHYs + if self.x_pixels_per_unit is not None and self.y_pixels_per_unit is not None: + tup = ( + self.x_pixels_per_unit, + self.y_pixels_per_unit, + int(self.unit_is_meter), + ) + write_chunk(outfile, b"pHYs", struct.pack("!LLB", *tup)) + + def write_array(self, outfile, pixels): + """ + Write an array that holds all the image values + as a PNG file on the output file. + See also :meth:`write` method. + """ + + if self.interlace: + if not isarray(pixels): + # Coerce to array type + fmt = "BH"[self.bitdepth > 8] + pixels = array(fmt, pixels) + self.write_passes(outfile, self.array_scanlines_interlace(pixels)) + else: + self.write_passes(outfile, self.array_scanlines(pixels)) + + def array_scanlines(self, pixels): + """ + Generates rows (each a sequence of values) from + a single array of values. + """ + + # Values per row + vpr = self.width * self.planes + stop = 0 + for y in range(self.height): + start = stop + stop = start + vpr + yield pixels[start:stop] + + def array_scanlines_interlace(self, pixels): + """ + Generator for interlaced scanlines from an array. + `pixels` is the full source image as a single array of values. + The generator yields each scanline of the reduced passes in turn, + each scanline being a sequence of values. + """ + + # http://www.w3.org/TR/PNG/#8InterlaceMethods + # Array type. + fmt = "BH"[self.bitdepth > 8] + # Value per row + vpr = self.width * self.planes + + # Each iteration generates a scanline starting at (x, y) + # and consisting of every xstep pixels. + for lines in adam7_generate(self.width, self.height): + for x, y, xstep in lines: + # Pixels per row (of reduced image) + ppr = int(math.ceil((self.width - x) / float(xstep))) + # Values per row (of reduced image) + reduced_row_len = ppr * self.planes + if xstep == 1: + # Easy case: line is a simple slice. + offset = y * vpr + yield pixels[offset : offset + vpr] + continue + # We have to step by xstep, + # which we can do one plane at a time + # using the step in Python slices. + row = array(fmt) + # There's no easier way to set the length of an array + row.extend(pixels[0:reduced_row_len]) + offset = y * vpr + x * self.planes + end_offset = (y + 1) * vpr + skip = self.planes * xstep + for i in range(self.planes): + row[i :: self.planes] = pixels[offset + i : end_offset : skip] + yield row + + +def write_chunk(outfile, tag, data=b""): + """ + Write a PNG chunk to the output file, including length and + checksum. + """ + + data = bytes(data) + # http://www.w3.org/TR/PNG/#5Chunk-layout + outfile.write(struct.pack("!I", len(data))) + outfile.write(tag) + outfile.write(data) + checksum = zlib.crc32(tag) + checksum = zlib.crc32(data, checksum) + checksum &= 2**32 - 1 + outfile.write(struct.pack("!I", checksum)) + + +def write_chunks(out, chunks): + """Create a PNG file by writing out the chunks.""" + + out.write(signature) + for chunk in chunks: + write_chunk(out, *chunk) + + +def rescale_rows(rows, rescale): + """ + Take each row in rows (an iterator) and yield + a fresh row with the pixels scaled according to + the rescale parameters in the list `rescale`. + Each element of `rescale` is a tuple of + (source_bitdepth, target_bitdepth), + with one element per channel. + """ + + # One factor for each channel + fs = [float(2 ** s[1] - 1) / float(2 ** s[0] - 1) for s in rescale] + + # Assume all target_bitdepths are the same + target_bitdepths = set(s[1] for s in rescale) + assert len(target_bitdepths) == 1 + (target_bitdepth,) = target_bitdepths + typecode = "BH"[target_bitdepth > 8] + + # Number of channels + n_chans = len(rescale) + + for row in rows: + rescaled_row = array(typecode, iter(row)) + for i in range(n_chans): + channel = array(typecode, (int(round(fs[i] * x)) for x in row[i::n_chans])) + rescaled_row[i::n_chans] = channel + yield rescaled_row + + +def pack_rows(rows, bitdepth): + """Yield packed rows that are a byte array. + Each byte is packed with the values from several pixels. + """ + + assert bitdepth < 8 + assert 8 % bitdepth == 0 + + # samples per byte + spb = int(8 / bitdepth) + + def make_byte(block): + """Take a block of (2, 4, or 8) values, + and pack them into a single byte. + """ + + res = 0 + for v in block: + res = (res << bitdepth) + v + return res + + for row in rows: + a = bytearray(row) + # Adding padding bytes so we can group into a whole + # number of spb-tuples. + n = float(len(a)) + extra = math.ceil(n / spb) * spb - n + a.extend([0] * int(extra)) + # Pack into bytes. + # Each block is the samples for one byte. + blocks = group(a, spb) + yield bytearray(make_byte(block) for block in blocks) + + +def unpack_rows(rows): + """Unpack each row from being 16-bits per value, + to being a sequence of bytes. + """ + for row in rows: + fmt = "!%dH" % len(row) + yield bytearray(struct.pack(fmt, *row)) + + +def make_palette_chunks(palette): + """ + Create the byte sequences for a ``PLTE`` and + if necessary a ``tRNS`` chunk. + Returned as a pair (*p*, *t*). + *t* will be ``None`` if no ``tRNS`` chunk is necessary. + """ + + p = bytearray() + t = bytearray() + + for x in palette: + p.extend(x[0:3]) + if len(x) > 3: + t.append(x[3]) + if t: + return p, t + return p, None + + +def check_bitdepth_rescale(palette, bitdepth, transparent, alpha, greyscale): + """ + Returns (bitdepth, rescale) pair. + """ + + if palette: + if len(bitdepth) != 1: + raise ProtocolError("with palette, only a single bitdepth may be used") + (bitdepth,) = bitdepth + if bitdepth not in (1, 2, 4, 8): + raise ProtocolError("with palette, bitdepth must be 1, 2, 4, or 8") + if transparent is not None: + raise ProtocolError("transparent and palette not compatible") + if alpha: + raise ProtocolError("alpha and palette not compatible") + if greyscale: + raise ProtocolError("greyscale and palette not compatible") + return bitdepth, None + + # No palette, check for sBIT chunk generation. + + if greyscale and not alpha: + # Single channel, L. + (bitdepth,) = bitdepth + if bitdepth in (1, 2, 4, 8, 16): + return bitdepth, None + if bitdepth > 8: + targetbitdepth = 16 + elif bitdepth == 3: + targetbitdepth = 4 + else: + assert bitdepth in (5, 6, 7) + targetbitdepth = 8 + return targetbitdepth, [(bitdepth, targetbitdepth)] + + assert alpha or not greyscale + + depth_set = tuple(set(bitdepth)) + if depth_set in [(8,), (16,)]: + # No sBIT required. + (bitdepth,) = depth_set + return bitdepth, None + + targetbitdepth = (8, 16)[max(bitdepth) > 8] + return targetbitdepth, [(b, targetbitdepth) for b in bitdepth] + + +# Regex for decoding mode string +RegexModeDecode = re.compile("(LA?|RGBA?);?([0-9]*)", flags=re.IGNORECASE) + + +def from_array(a, mode=None, info={}): + """ + Create a PNG :class:`Image` object from a 2-dimensional array. + One application of this function is easy PIL-style saving: + ``png.from_array(pixels, 'L').save('foo.png')``. + + Unless they are specified using the *info* parameter, + the PNG's height and width are taken from the array size. + The first axis is the height; the second axis is the + ravelled width and channel index. + The array is treated is a sequence of rows, + each row being a sequence of values (``width*channels`` in number). + So an RGB image that is 16 pixels high and 8 wide will + occupy a 2-dimensional array that is 16x24 + (each row will be 8*3 = 24 sample values). + + *mode* is a string that specifies the image colour format in a + PIL-style mode. It can be: + + ``'L'`` + greyscale (1 channel) + ``'LA'`` + greyscale with alpha (2 channel) + ``'RGB'`` + colour image (3 channel) + ``'RGBA'`` + colour image with alpha (4 channel) + + The mode string can also specify the bit depth + (overriding how this function normally derives the bit depth, + see below). + Appending ``';16'`` to the mode will cause the PNG to be + 16 bits per channel; + any decimal from 1 to 16 can be used to specify the bit depth. + + When a 2-dimensional array is used *mode* determines how many + channels the image has, and so allows the width to be derived from + the second array dimension. + + The array is expected to be a ``numpy`` array, + but it can be any suitable Python sequence. + For example, a list of lists can be used: + ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. + The exact rules are: ``len(a)`` gives the first dimension, height; + ``len(a[0])`` gives the second dimension. + It's slightly more complicated than that because + an iterator of rows can be used, and it all still works. + Using an iterator allows data to be streamed efficiently. + + The bit depth of the PNG is normally taken from + the array element's datatype + (but if *mode* specifies a bitdepth then that is used instead). + The array element's datatype is determined in a way which + is supposed to work both for ``numpy`` arrays and for Python + ``array.array`` objects. + A 1 byte datatype will give a bit depth of 8, + a 2 byte datatype will give a bit depth of 16. + If the datatype does not have an implicit size, + like the above example where it is a plain Python list of lists, + then a default of 8 is used. + + The *info* parameter is a dictionary that can + be used to specify metadata (in the same style as + the arguments to the :class:`png.Writer` class). + For this function the keys that are useful are: + + height + overrides the height derived from the array dimensions and + allows *a* to be an iterable. + width + overrides the width derived from the array dimensions. + bitdepth + overrides the bit depth derived from the element datatype + (but must match *mode* if that also specifies a bit depth). + + Generally anything specified in the *info* dictionary will + override any implicit choices that this function would otherwise make, + but must match any explicit ones. + For example, if the *info* dictionary has a ``greyscale`` key then + this must be true when mode is ``'L'`` or ``'LA'`` and + false when mode is ``'RGB'`` or ``'RGBA'``. + """ + + # We abuse the *info* parameter by modifying it. Take a copy here. + # (Also typechecks *info* to some extent). + info = dict(info) + + # Syntax check mode string. + match = RegexModeDecode.match(mode) + if not match: + raise Error("mode string should be 'RGB' or 'L;16' or similar.") + + mode, bitdepth = match.groups() + if bitdepth: + bitdepth = int(bitdepth) + + # Colour format. + if "greyscale" in info: + if bool(info["greyscale"]) != ("L" in mode): + raise ProtocolError("info['greyscale'] should match mode.") + info["greyscale"] = "L" in mode + + alpha = "A" in mode + if "alpha" in info: + if bool(info["alpha"]) != alpha: + raise ProtocolError("info['alpha'] should match mode.") + info["alpha"] = alpha + + # Get bitdepth from *mode* if possible. + if bitdepth: + if info.get("bitdepth") and bitdepth != info["bitdepth"]: + raise ProtocolError( + "bitdepth (%d) should match bitdepth of info (%d)." + % (bitdepth, info["bitdepth"]) + ) + info["bitdepth"] = bitdepth + + # Fill in and/or check entries in *info*. + # Dimensions. + width, height = check_sizes(info.get("size"), info.get("width"), info.get("height")) + if width: + info["width"] = width + if height: + info["height"] = height + + if "height" not in info: + try: + info["height"] = len(a) + except TypeError: + raise ProtocolError("len(a) does not work, supply info['height'] instead.") + + planes = len(mode) + if "planes" in info: + if info["planes"] != planes: + raise Error("info['planes'] should match mode.") + + # In order to work out whether we the array is 2D or 3D we need its + # first row, which requires that we take a copy of its iterator. + # We may also need the first row to derive width and bitdepth. + a, t = itertools.tee(a) + row = next(t) + del t + + testelement = row + if "width" not in info: + width = len(row) // planes + info["width"] = width + + if "bitdepth" not in info: + try: + dtype = testelement.dtype + # goto the "else:" clause. Sorry. + except AttributeError: + try: + # Try a Python array.array. + bitdepth = 8 * testelement.itemsize + except AttributeError: + # We can't determine it from the array element's datatype, + # use a default of 8. + bitdepth = 8 + else: + # If we got here without exception, + # we now assume that the array is a numpy array. + if dtype.kind == "b": + bitdepth = 1 + else: + bitdepth = 8 * dtype.itemsize + info["bitdepth"] = bitdepth + + for thing in ["width", "height", "bitdepth", "greyscale", "alpha"]: + assert thing in info + + return Image(a, info) + + +# So that refugee's from PIL feel more at home. Not documented. +fromarray = from_array + + +class Image: + """A PNG image. You can create an :class:`Image` object from + an array of pixels by calling :meth:`png.from_array`. It can be + saved to disk with the :meth:`save` method. + """ + + def __init__(self, rows, info): + """ + .. note :: + + The constructor is not public. Please do not call it. + """ + + self.rows = rows + self.info = info + + def save(self, file): + """Save the image to the named *file*. + + See `.write()` if you already have an open file object. + + In general, you can only call this method once; + after it has been called the first time the PNG image is written, + the source data will have been streamed, and + cannot be streamed again. + """ + + w = Writer(**self.info) + + with open(file, "wb") as fd: + w.write(fd, self.rows) + + def write(self, file): + """Write the image to the open file object. + + See `.save()` if you have a filename. + + In general, you can only call this method once; + after it has been called the first time the PNG image is written, + the source data will have been streamed, and + cannot be streamed again. + """ + + w = Writer(**self.info) + w.write(file, self.rows) + + +class Reader: + """ + Pure Python PNG decoder in pure Python. + """ + + def __init__(self, _guess=None, filename=None, file=None, bytes=None): + """ + The constructor expects exactly one keyword argument. + If you supply a positional argument instead, + it will guess the input type. + Choose from the following keyword arguments: + + filename + Name of input file (a PNG file). + file + A file-like object (object with a read() method). + bytes + ``bytes`` or ``bytearray`` with PNG data. + + """ + keywords_supplied = ( + (_guess is not None) + + (filename is not None) + + (file is not None) + + (bytes is not None) + ) + if keywords_supplied != 1: + raise TypeError("Reader() takes exactly 1 argument") + + # Will be the first 8 bytes, later on. See validate_signature. + self.signature = None + self.transparent = None + # A pair of (len,type) if a chunk has been read but its data and + # checksum have not (in other words the file position is just + # past the 4 bytes that specify the chunk type). + # See preamble method for how this is used. + self.atchunk = None + + if _guess is not None: + if isarray(_guess): + bytes = _guess + elif isinstance(_guess, str): + filename = _guess + elif hasattr(_guess, "read"): + file = _guess + + if bytes is not None: + self.file = io.BytesIO(bytes) + elif filename is not None: + self.file = open(filename, "rb") + elif file is not None: + self.file = file + else: + raise ProtocolError("expecting filename, file or bytes array") + + def chunk(self, lenient=False): + """ + Read the next PNG chunk from the input file; + returns a (*type*, *data*) tuple. + *type* is the chunk's type as a byte string + (all PNG chunk types are 4 bytes long). + *data* is the chunk's data content, as a byte string. + + If the optional `lenient` argument evaluates to `True`, + checksum failures will raise warnings rather than exceptions. + """ + + self.validate_signature() + + # http://www.w3.org/TR/PNG/#5Chunk-layout + if not self.atchunk: + self.atchunk = self._chunk_len_type() + if not self.atchunk: + raise ChunkError("No more chunks.") + length, type = self.atchunk + self.atchunk = None + + data = self.file.read(length) + if len(data) != length: + raise ChunkError( + "Chunk %s too short for required %i octets." % (type, length) + ) + checksum = self.file.read(4) + if len(checksum) != 4: + raise ChunkError("Chunk %s too short for checksum." % type) + verify = zlib.crc32(type) + verify = zlib.crc32(data, verify) + verify = struct.pack("!I", verify) + if checksum != verify: + (a,) = struct.unpack("!I", checksum) + (b,) = struct.unpack("!I", verify) + message = "Checksum error in %s chunk: 0x%08X != 0x%08X." % ( + type.decode("ascii"), + a, + b, + ) + if lenient: + warnings.warn(message, RuntimeWarning) + else: + raise ChunkError(message) + return type, data + + def chunks(self): + """Return an iterator that will yield each chunk as a + (*chunktype*, *content*) pair. + """ + + while True: + t, v = self.chunk() + yield t, v + if t == b"IEND": + break + + def undo_filter(self, filter_type, scanline, previous): + """ + Undo the filter for a scanline. + `scanline` is a sequence of bytes that + does not include the initial filter type byte. + `previous` is decoded previous scanline + (for straightlaced images this is the previous pixel row, + but for interlaced images, it is + the previous scanline in the reduced image, + which in general is not the previous pixel row in the final image). + When there is no previous scanline + (the first row of a straightlaced image, + or the first row in one of the passes in an interlaced image), + then this argument should be ``None``. + + The scanline will have the effects of filtering removed; + the result will be returned as a fresh sequence of bytes. + """ + + # :todo: Would it be better to update scanline in place? + result = scanline + + if filter_type == 0: + return result + + if filter_type not in (1, 2, 3, 4): + raise FormatError( + "Invalid PNG Filter Type. " + "See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters ." + ) + + # Filter unit. The stride from one pixel to the corresponding + # byte from the previous pixel. Normally this is the pixel + # size in bytes, but when this is smaller than 1, the previous + # byte is used instead. + fu = max(1, self.psize) + + # For the first line of a pass, synthesize a dummy previous + # line. An alternative approach would be to observe that on the + # first line 'up' is the same as 'null', 'paeth' is the same + # as 'sub', with only 'average' requiring any special case. + if not previous: + previous = bytearray([0] * len(scanline)) + + # Call appropriate filter algorithm. Note that 0 has already + # been dealt with. + fn = ( + None, + undo_filter_sub, + undo_filter_up, + undo_filter_average, + undo_filter_paeth, + )[filter_type] + fn(fu, scanline, previous, result) + return result + + def _deinterlace(self, raw): + """ + Read raw pixel data, undo filters, deinterlace, and flatten. + Return a single array of values. + """ + + # Values per row (of the target image) + vpr = self.width * self.planes + + # Values per image + vpi = vpr * self.height + # Interleaving writes to the output array randomly + # (well, not quite), so the entire output array must be in memory. + # Make a result array, and make it big enough. + if self.bitdepth > 8: + a = array("H", [0] * vpi) + else: + a = bytearray([0] * vpi) + source_offset = 0 + + for lines in adam7_generate(self.width, self.height): + # The previous (reconstructed) scanline. + # `None` at the beginning of a pass + # to indicate that there is no previous line. + recon = None + for x, y, xstep in lines: + # Pixels per row (reduced pass image) + ppr = int(math.ceil((self.width - x) / float(xstep))) + # Row size in bytes for this pass. + row_size = int(math.ceil(self.psize * ppr)) + + filter_type = raw[source_offset] + source_offset += 1 + scanline = raw[source_offset : source_offset + row_size] + source_offset += row_size + recon = self.undo_filter(filter_type, scanline, recon) + # Convert so that there is one element per pixel value + flat = self._bytes_to_values(recon, width=ppr) + if xstep == 1: + assert x == 0 + offset = y * vpr + a[offset : offset + vpr] = flat + else: + offset = y * vpr + x * self.planes + end_offset = (y + 1) * vpr + skip = self.planes * xstep + for i in range(self.planes): + a[offset + i : end_offset : skip] = flat[i :: self.planes] + + return a + + def _iter_bytes_to_values(self, byte_rows): + """ + Iterator that yields each scanline; + each scanline being a sequence of values. + `byte_rows` should be an iterator that yields + the bytes of each row in turn. + """ + + for row in byte_rows: + yield self._bytes_to_values(row) + + def _bytes_to_values(self, bs, width=None): + """Convert a packed row of bytes into a row of values. + Result will be a freshly allocated object, + not shared with the argument. + """ + + if self.bitdepth == 8: + return bytearray(bs) + if self.bitdepth == 16: + return array("H", struct.unpack("!%dH" % (len(bs) // 2), bs)) + + assert self.bitdepth < 8 + if width is None: + width = self.width + # Samples per byte + spb = 8 // self.bitdepth + out = bytearray() + mask = 2**self.bitdepth - 1 + shifts = [self.bitdepth * i for i in reversed(list(range(spb)))] + for o in bs: + out.extend([mask & (o >> i) for i in shifts]) + return out[:width] + + def _iter_straight_packed(self, byte_blocks): + """Iterator that undoes the effect of filtering; + yields each row as a sequence of packed bytes. + Assumes input is straightlaced. + `byte_blocks` should be an iterable that yields the raw bytes + in blocks of arbitrary size. + """ + + # length of row, in bytes + rb = self.row_bytes + a = bytearray() + # The previous (reconstructed) scanline. + # None indicates first line of image. + recon = None + for some_bytes in byte_blocks: + a.extend(some_bytes) + while len(a) >= rb + 1: + filter_type = a[0] + scanline = a[1 : rb + 1] + del a[: rb + 1] + recon = self.undo_filter(filter_type, scanline, recon) + yield recon + if len(a) != 0: + # :file:format We get here with a file format error: + # when the available bytes (after decompressing) do not + # pack into exact rows. + raise FormatError("Wrong size for decompressed IDAT chunk.") + assert len(a) == 0 + + def validate_signature(self): + """ + If signature (header) has not been read then read and + validate it; otherwise do nothing. + """ + + if self.signature: + return + self.signature = self.file.read(8) + if self.signature != signature: + raise FormatError("PNG file has invalid signature.") + + def preamble(self, lenient=False): + """ + Extract the image metadata by reading + the initial part of the PNG file up to + the start of the ``IDAT`` chunk. + All the chunks that precede the ``IDAT`` chunk are + read and either processed for metadata or discarded. + + If the optional `lenient` argument evaluates to `True`, + checksum failures will raise warnings rather than exceptions. + """ + + self.validate_signature() + + while True: + if not self.atchunk: + self.atchunk = self._chunk_len_type() + if self.atchunk is None: + raise FormatError("This PNG file has no IDAT chunks.") + if self.atchunk[1] == b"IDAT": + return + self.process_chunk(lenient=lenient) + + def _chunk_len_type(self): + """ + Reads just enough of the input to + determine the next chunk's length and type; + return a (*length*, *type*) pair where *type* is a byte sequence. + If there are no more chunks, ``None`` is returned. + """ + + x = self.file.read(8) + if not x: + return None + if len(x) != 8: + raise FormatError("End of file whilst reading chunk length and type.") + length, type = struct.unpack("!I4s", x) + if length > 2**31 - 1: + raise FormatError("Chunk %s is too large: %d." % (type, length)) + # Check that all bytes are in valid ASCII range. + # https://www.w3.org/TR/2003/REC-PNG-20031110/#5Chunk-layout + type_bytes = set(bytearray(type)) + if not (type_bytes <= set(range(65, 91)) | set(range(97, 123))): + raise FormatError("Chunk %r has invalid Chunk Type." % list(type)) + return length, type + + def process_chunk(self, lenient=False): + """ + Process the next chunk and its data. + This only processes the following chunk types: + ``IHDR``, ``PLTE``, ``bKGD``, ``tRNS``, ``gAMA``, ``sBIT``, ``pHYs``. + All other chunk types are ignored. + + If the optional `lenient` argument evaluates to `True`, + checksum failures will raise warnings rather than exceptions. + """ + + type, data = self.chunk(lenient=lenient) + method = "_process_" + type.decode("ascii") + m = getattr(self, method, None) + if m: + m(data) + + def _process_IHDR(self, data): + # http://www.w3.org/TR/PNG/#11IHDR + if len(data) != 13: + raise FormatError("IHDR chunk has incorrect length.") + ( + self.width, + self.height, + self.bitdepth, + self.color_type, + self.compression, + self.filter, + self.interlace, + ) = struct.unpack("!2I5B", data) + + check_bitdepth_colortype(self.bitdepth, self.color_type) + + if self.compression != 0: + raise FormatError("Unknown compression method %d" % self.compression) + if self.filter != 0: + raise FormatError( + "Unknown filter method %d," + " see http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters ." + % self.filter + ) + if self.interlace not in (0, 1): + raise FormatError( + "Unknown interlace method %d, see " + "http://www.w3.org/TR/2003/REC-PNG-20031110/#8InterlaceMethods" + " ." % self.interlace + ) + + # Derived values + # http://www.w3.org/TR/PNG/#6Colour-values + colormap = bool(self.color_type & 1) + greyscale = not (self.color_type & 2) + alpha = bool(self.color_type & 4) + color_planes = (3, 1)[greyscale or colormap] + planes = color_planes + alpha + + self.colormap = colormap + self.greyscale = greyscale + self.alpha = alpha + self.color_planes = color_planes + self.planes = planes + self.psize = float(self.bitdepth) / float(8) * planes + if int(self.psize) == self.psize: + self.psize = int(self.psize) + self.row_bytes = int(math.ceil(self.width * self.psize)) + # Stores PLTE chunk if present, and is used to check + # chunk ordering constraints. + self.plte = None + # Stores tRNS chunk if present, and is used to check chunk + # ordering constraints. + self.trns = None + # Stores sBIT chunk if present. + self.sbit = None + + def _process_PLTE(self, data): + # http://www.w3.org/TR/PNG/#11PLTE + if self.plte: + warnings.warn("Multiple PLTE chunks present.") + self.plte = data + if len(data) % 3 != 0: + raise FormatError("PLTE chunk's length should be a multiple of 3.") + if len(data) > (2**self.bitdepth) * 3: + raise FormatError("PLTE chunk is too long.") + if len(data) == 0: + raise FormatError("Empty PLTE is not allowed.") + + def _process_bKGD(self, data): + try: + if self.colormap: + if not self.plte: + warnings.warn("PLTE chunk is required before bKGD chunk.") + self.background = struct.unpack("B", data) + else: + self.background = struct.unpack("!%dH" % self.color_planes, data) + except struct.error: + raise FormatError("bKGD chunk has incorrect length.") + + def _process_tRNS(self, data): + # http://www.w3.org/TR/PNG/#11tRNS + self.trns = data + if self.colormap: + if not self.plte: + warnings.warn("PLTE chunk is required before tRNS chunk.") + else: + if len(data) > len(self.plte) / 3: + # Was warning, but promoted to Error as it + # would otherwise cause pain later on. + raise FormatError("tRNS chunk is too long.") + else: + if self.alpha: + raise FormatError( + "tRNS chunk is not valid with colour type %d." % self.color_type + ) + try: + self.transparent = struct.unpack("!%dH" % self.color_planes, data) + except struct.error: + raise FormatError("tRNS chunk has incorrect length.") + + def _process_gAMA(self, data): + try: + self.gamma = struct.unpack("!L", data)[0] / 100000.0 + except struct.error: + raise FormatError("gAMA chunk has incorrect length.") + + def _process_sBIT(self, data): + self.sbit = data + if ( + self.colormap + and len(data) != 3 + or not self.colormap + and len(data) != self.planes + ): + raise FormatError("sBIT chunk has incorrect length.") + + def _process_pHYs(self, data): + # http://www.w3.org/TR/PNG/#11pHYs + self.phys = data + fmt = "!LLB" + if len(data) != struct.calcsize(fmt): + raise FormatError("pHYs chunk has incorrect length.") + self.x_pixels_per_unit, self.y_pixels_per_unit, unit = struct.unpack(fmt, data) + self.unit_is_meter = bool(unit) + + def read(self, lenient=False): + """ + Read the PNG file and decode it. + Returns (`width`, `height`, `rows`, `info`). + + May use excessive memory. + + `rows` is a sequence of rows; + each row is a sequence of values. + + If the optional `lenient` argument evaluates to True, + checksum failures will raise warnings rather than exceptions. + """ + + def iteridat(): + """Iterator that yields all the ``IDAT`` chunks as strings.""" + while True: + type, data = self.chunk(lenient=lenient) + if type == b"IEND": + # http://www.w3.org/TR/PNG/#11IEND + break + if type != b"IDAT": + continue + # type == b'IDAT' + # http://www.w3.org/TR/PNG/#11IDAT + if self.colormap and not self.plte: + warnings.warn("PLTE chunk is required before IDAT chunk") + yield data + + self.preamble(lenient=lenient) + raw = decompress(iteridat()) + + if self.interlace: + + def rows_from_interlace(): + """Yield each row from an interlaced PNG.""" + # It's important that this iterator doesn't read + # IDAT chunks until it yields the first row. + bs = bytearray(itertools.chain(*raw)) + arraycode = "BH"[self.bitdepth > 8] + # Like :meth:`group` but + # producing an array.array object for each row. + values = self._deinterlace(bs) + vpr = self.width * self.planes + for i in range(0, len(values), vpr): + row = array(arraycode, values[i : i + vpr]) + yield row + + rows = rows_from_interlace() + else: + rows = self._iter_bytes_to_values(self._iter_straight_packed(raw)) + info = dict() + for attr in "greyscale alpha planes bitdepth interlace".split(): + info[attr] = getattr(self, attr) + info["size"] = (self.width, self.height) + for attr in "gamma transparent background".split(): + a = getattr(self, attr, None) + if a is not None: + info[attr] = a + if getattr(self, "x_pixels_per_unit", None): + info["physical"] = Resolution( + self.x_pixels_per_unit, self.y_pixels_per_unit, self.unit_is_meter + ) + if self.plte: + info["palette"] = self.palette() + return self.width, self.height, rows, info + + def read_flat(self): + """ + Read a PNG file and decode it into a single array of values. + Returns (*width*, *height*, *values*, *info*). + + May use excessive memory. + + `values` is a single array. + + The :meth:`read` method is more stream-friendly than this, + because it returns a sequence of rows. + """ + + x, y, pixel, info = self.read() + arraycode = "BH"[info["bitdepth"] > 8] + pixel = array(arraycode, itertools.chain(*pixel)) + return x, y, pixel, info + + def palette(self, alpha="natural"): + """ + Returns a palette that is a sequence of 3-tuples or 4-tuples, + synthesizing it from the ``PLTE`` and ``tRNS`` chunks. + These chunks should have already been processed (for example, + by calling the :meth:`preamble` method). + All the tuples are the same size: + 3-tuples if there is no ``tRNS`` chunk, + 4-tuples when there is a ``tRNS`` chunk. + + Assumes that the image is colour type + 3 and therefore a ``PLTE`` chunk is required. + + If the `alpha` argument is ``'force'`` then an alpha channel is + always added, forcing the result to be a sequence of 4-tuples. + """ + + if not self.plte: + raise FormatError("Required PLTE chunk is missing in colour type 3 image.") + plte = group(array("B", self.plte), 3) + if self.trns or alpha == "force": + trns = array("B", self.trns or []) + trns.extend([255] * (len(plte) - len(trns))) + plte = list(map(operator.add, plte, group(trns, 1))) + return plte + + def asDirect(self): + """ + Returns the image data as a direct representation of + an ``x * y * planes`` array. + This removes the need for callers to deal with + palettes and transparency themselves. + Images with a palette (colour type 3) are converted to RGB or RGBA; + images with transparency (a ``tRNS`` chunk) are converted to + LA or RGBA as appropriate. + When returned in this format the pixel values represent + the colour value directly without needing to refer + to palettes or transparency information. + + Like the :meth:`read` method this method returns a 4-tuple: + + (*width*, *height*, *rows*, *info*) + + This method normally returns pixel values with + the bit depth they have in the source image, but + when the source PNG has an ``sBIT`` chunk it is inspected and + can reduce the bit depth of the result pixels; + pixel values will be reduced according to the bit depth + specified in the ``sBIT`` chunk. + PNG nerds should note a single result bit depth is + used for all channels: + the maximum of the ones specified in the ``sBIT`` chunk. + An RGB565 image will be rescaled to 6-bit RGB666. + + The *info* dictionary that is returned reflects + the `direct` format and not the original source image. + For example, an RGB source image with a ``tRNS`` chunk + to represent a transparent colour, + will start with ``planes=3`` and ``alpha=False`` for the + source image, + but the *info* dictionary returned by this method + will have ``planes=4`` and ``alpha=True`` because + an alpha channel is synthesized and added. + + *rows* is a sequence of rows; + each row being a sequence of values + (like the :meth:`read` method). + + All the other aspects of the image data are not changed. + """ + + self.preamble() + + # Simple case, no conversion necessary. + if not self.colormap and not self.trns and not self.sbit: + return self.read() + + x, y, pixels, info = self.read() + + if self.colormap: + info["colormap"] = False + info["alpha"] = bool(self.trns) + info["bitdepth"] = 8 + info["planes"] = 3 + bool(self.trns) + plte = self.palette() + + def iterpal(pixels): + for row in pixels: + row = [plte[x] for x in row] + yield array("B", itertools.chain(*row)) + + pixels = iterpal(pixels) + elif self.trns: + # It would be nice if there was some reasonable way + # of doing this without generating a whole load of + # intermediate tuples. But tuples does seem like the + # easiest way, with no other way clearly much simpler or + # much faster. (Actually, the L to LA conversion could + # perhaps go faster (all those 1-tuples!), but I still + # wonder whether the code proliferation is worth it) + it = self.transparent + maxval = 2 ** info["bitdepth"] - 1 + planes = info["planes"] + info["alpha"] = True + info["planes"] += 1 + typecode = "BH"[info["bitdepth"] > 8] + + def itertrns(pixels): + for row in pixels: + # For each row we group it into pixels, then form a + # characterisation vector that says whether each + # pixel is opaque or not. Then we convert + # True/False to 0/maxval (by multiplication), + # and add it as the extra channel. + row = group(row, planes) + opa = map(it.__ne__, row) + opa = map(maxval.__mul__, opa) + opa = list(zip(opa)) # convert to 1-tuples + yield array(typecode, itertools.chain(*map(operator.add, row, opa))) + + pixels = itertrns(pixels) + targetbitdepth = None + if self.sbit: + sbit = struct.unpack("%dB" % len(self.sbit), self.sbit) + targetbitdepth = max(sbit) + if targetbitdepth > info["bitdepth"]: + raise Error("sBIT chunk %r exceeds bitdepth %d" % (sbit, self.bitdepth)) + if min(sbit) <= 0: + raise Error("sBIT chunk %r has a 0-entry" % sbit) + if targetbitdepth: + shift = info["bitdepth"] - targetbitdepth + info["bitdepth"] = targetbitdepth + + def itershift(pixels): + for row in pixels: + yield [p >> shift for p in row] + + pixels = itershift(pixels) + return x, y, pixels, info + + def _as_rescale(self, get, targetbitdepth): + """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" + + width, height, pixels, info = get() + maxval = 2 ** info["bitdepth"] - 1 + targetmaxval = 2**targetbitdepth - 1 + factor = float(targetmaxval) / float(maxval) + info["bitdepth"] = targetbitdepth + + def iterscale(): + for row in pixels: + yield [int(round(x * factor)) for x in row] + + if maxval == targetmaxval: + return width, height, pixels, info + else: + return width, height, iterscale(), info + + def asRGB8(self): + """ + Return the image data as an RGB pixels with 8-bits per sample. + This is like the :meth:`asRGB` method except that + this method additionally rescales the values so that + they are all between 0 and 255 (8-bit). + In the case where the source image has a bit depth < 8 + the transformation preserves all the information; + where the source image has bit depth > 8, then + rescaling to 8-bit values loses precision. + No dithering is performed. + Like :meth:`asRGB`, + an alpha channel in the source image will raise an exception. + + This function returns a 4-tuple: + (*width*, *height*, *rows*, *info*). + *width*, *height*, *info* are as per the :meth:`read` method. + + *rows* is the pixel data as a sequence of rows. + """ + + return self._as_rescale(self.asRGB, 8) + + def asRGBA8(self): + """ + Return the image data as RGBA pixels with 8-bits per sample. + This method is similar to :meth:`asRGB8` and :meth:`asRGBA`: + The result pixels have an alpha channel, *and* + values are rescaled to the range 0 to 255. + The alpha channel is synthesized if necessary + (with a small speed penalty). + """ + + return self._as_rescale(self.asRGBA, 8) + + def asRGB(self): + """ + Return image as RGB pixels. + RGB colour images are passed through unchanged; + greyscales are expanded into RGB triplets + (there is a small speed overhead for doing this). + + An alpha channel in the source image will raise an exception. + + The return values are as for the :meth:`read` method except that + the *info* reflect the returned pixels, not the source image. + In particular, + for this method ``info['greyscale']`` will be ``False``. + """ + + width, height, pixels, info = self.asDirect() + if info["alpha"]: + raise Error("will not convert image with alpha channel to RGB") + if not info["greyscale"]: + return width, height, pixels, info + info["greyscale"] = False + info["planes"] = 3 + + if info["bitdepth"] > 8: + + def newarray(): + return array("H", [0]) + + else: + + def newarray(): + return bytearray([0]) + + def iterrgb(): + for row in pixels: + a = newarray() * 3 * width + for i in range(3): + a[i::3] = row + yield a + + return width, height, iterrgb(), info + + def asRGBA(self): + """ + Return image as RGBA pixels. + Greyscales are expanded into RGB triplets; + an alpha channel is synthesized if necessary. + The return values are as for the :meth:`read` method except that + the *info* reflect the returned pixels, not the source image. + In particular, for this method + ``info['greyscale']`` will be ``False``, and + ``info['alpha']`` will be ``True``. + """ + + width, height, pixels, info = self.asDirect() + if info["alpha"] and not info["greyscale"]: + return width, height, pixels, info + typecode = "BH"[info["bitdepth"] > 8] + maxval = 2 ** info["bitdepth"] - 1 + maxbuffer = struct.pack("=" + typecode, maxval) * 4 * width + + if info["bitdepth"] > 8: + + def newarray(): + return array("H", maxbuffer) + + else: + + def newarray(): + return bytearray(maxbuffer) + + if info["alpha"] and info["greyscale"]: + # LA to RGBA + def convert(): + for row in pixels: + # Create a fresh target row, then copy L channel + # into first three target channels, and A channel + # into fourth channel. + a = newarray() + convert_la_to_rgba(row, a) + yield a + + elif info["greyscale"]: + # L to RGBA + def convert(): + for row in pixels: + a = newarray() + convert_l_to_rgba(row, a) + yield a + + else: + assert not info["alpha"] and not info["greyscale"] + # RGB to RGBA + + def convert(): + for row in pixels: + a = newarray() + convert_rgb_to_rgba(row, a) + yield a + + info["alpha"] = True + info["greyscale"] = False + info["planes"] = 4 + return width, height, convert(), info + + +def decompress(data_blocks): + """ + `data_blocks` should be an iterable that + yields the compressed data (from the ``IDAT`` chunks). + This yields decompressed byte strings. + """ + + # Currently, with no max_length parameter to decompress, + # this routine will do one yield per IDAT chunk: Not very + # incremental. + d = zlib.decompressobj() + # Each IDAT chunk is passed to the decompressor, then any + # remaining state is decompressed out. + for data in data_blocks: + # :todo: add a max_length argument here to limit output size. + yield bytearray(d.decompress(data)) + yield bytearray(d.flush()) + + +def check_bitdepth_colortype(bitdepth, colortype): + """ + Check that `bitdepth` and `colortype` are both valid, + and specified in a valid combination. + Returns (None) if valid, raise an Exception if not valid. + """ + + if bitdepth not in (1, 2, 4, 8, 16): + raise FormatError("invalid bit depth %d" % bitdepth) + if colortype not in (0, 2, 3, 4, 6): + raise FormatError("invalid colour type %d" % colortype) + # Check indexed (palettized) images have 8 or fewer bits + # per pixel; check only indexed or greyscale images have + # fewer than 8 bits per pixel. + if colortype & 1 and bitdepth > 8: + raise FormatError( + "Indexed images (colour type %d) cannot" + " have bitdepth > 8 (bit depth %d)." + " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ." + % (bitdepth, colortype) + ) + if bitdepth < 8 and colortype not in (0, 3): + raise FormatError( + "Illegal combination of bit depth (%d)" + " and colour type (%d)." + " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ." + % (bitdepth, colortype) + ) + + +def is_natural(x): + """A non-negative integer.""" + try: + is_integer = int(x) == x + except (TypeError, ValueError): + return False + return is_integer and x >= 0 + + +def undo_filter_sub(filter_unit, scanline, previous, result): + """Undo sub filter.""" + + ai = 0 + # Loops starts at index fu. Observe that the initial part + # of the result is already filled in correctly with + # scanline. + for i in range(filter_unit, len(result)): + x = scanline[i] + a = result[ai] + result[i] = (x + a) & 0xFF + ai += 1 + + +def undo_filter_up(filter_unit, scanline, previous, result): + """Undo up filter.""" + + for i in range(len(result)): + x = scanline[i] + b = previous[i] + result[i] = (x + b) & 0xFF + + +def undo_filter_average(filter_unit, scanline, previous, result): + """Undo up filter.""" + + ai = -filter_unit + for i in range(len(result)): + x = scanline[i] + if ai < 0: + a = 0 + else: + a = result[ai] + b = previous[i] + result[i] = (x + ((a + b) >> 1)) & 0xFF + ai += 1 + + +def undo_filter_paeth(filter_unit, scanline, previous, result): + """Undo Paeth filter.""" + + # Also used for ci. + ai = -filter_unit + for i in range(len(result)): + x = scanline[i] + if ai < 0: + a = c = 0 + else: + a = result[ai] + c = previous[ai] + b = previous[i] + p = a + b - c + pa = abs(p - a) + pb = abs(p - b) + pc = abs(p - c) + if pa <= pb and pa <= pc: + pr = a + elif pb <= pc: + pr = b + else: + pr = c + result[i] = (x + pr) & 0xFF + ai += 1 + + +def convert_la_to_rgba(row, result): + for i in range(3): + result[i::4] = row[0::2] + result[3::4] = row[1::2] + + +def convert_l_to_rgba(row, result): + """ + Convert a grayscale image to RGBA. + This method assumes the alpha channel in result is + already correctly initialized. + """ + for i in range(3): + result[i::4] = row + + +def convert_rgb_to_rgba(row, result): + """ + Convert an RGB image to RGBA. + This method assumes the alpha channel in result is + already correctly initialized. + """ + for i in range(3): + result[i::4] = row[i::3] + + +# Only reason to include this in this module is that +# several utilities need it, and it is small. +def binary_stdin(): + """ + A sys.stdin that returns bytes. + """ + + return sys.stdin.buffer + + +def binary_stdout(): + """ + A sys.stdout that accepts bytes. + """ + + stdout = sys.stdout.buffer + + # On Windows the C runtime file orientation needs changing. + if sys.platform == "win32": + import msvcrt + import os + + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + + return stdout + + +def cli_open(path): + if path == "-": + return binary_stdin() + return open(path, "rb") diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/utils.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..07a2b9e0b938314627342632fc8f7412cda9c4b2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/utils.py @@ -0,0 +1,557 @@ +import base64 +import decimal +import json as _json +import sys +import re +from functools import reduce + +from _plotly_utils.optional_imports import get_module +from _plotly_utils.basevalidators import ( + ImageUriValidator, + copy_to_readonly_numpy_array, + is_homogeneous_array, +) + + +int8min = -128 +int8max = 127 +int16min = -32768 +int16max = 32767 +int32min = -2147483648 +int32max = 2147483647 + +uint8max = 255 +uint16max = 65535 +uint32max = 4294967295 + +plotlyjsShortTypes = { + "int8": "i1", + "uint8": "u1", + "int16": "i2", + "uint16": "u2", + "int32": "i4", + "uint32": "u4", + "float32": "f4", + "float64": "f8", +} + + +def to_typed_array_spec(v): + """ + Convert numpy array to plotly.js typed array spec + If not possible return the original value + """ + v = copy_to_readonly_numpy_array(v) + + # Skip b64 encoding if numpy is not installed, + # or if v is not a numpy array, or if v is empty + np = get_module("numpy", should_load=False) + if not np or not isinstance(v, np.ndarray) or v.size == 0: + return v + + dtype = str(v.dtype) + + # convert default Big Ints until we could support them in plotly.js + if dtype == "int64": + max = v.max() + min = v.min() + if max <= int8max and min >= int8min: + v = v.astype("int8") + elif max <= int16max and min >= int16min: + v = v.astype("int16") + elif max <= int32max and min >= int32min: + v = v.astype("int32") + else: + return v + + elif dtype == "uint64": + max = v.max() + min = v.min() + if max <= uint8max and min >= 0: + v = v.astype("uint8") + elif max <= uint16max and min >= 0: + v = v.astype("uint16") + elif max <= uint32max and min >= 0: + v = v.astype("uint32") + else: + return v + + dtype = str(v.dtype) + + if dtype in plotlyjsShortTypes: + arrObj = { + "dtype": plotlyjsShortTypes[dtype], + "bdata": base64.b64encode(v).decode("ascii"), + } + + if v.ndim > 1: + arrObj["shape"] = str(v.shape)[1:-1] + + return arrObj + + return v + + +def is_skipped_key(key): + """ + Return whether the key is skipped for conversion to the typed array spec + """ + skipped_keys = ["geojson", "layer", "layers", "range"] + return any(skipped_key == key for skipped_key in skipped_keys) + + +def convert_to_base64(obj): + if isinstance(obj, dict): + for key, value in obj.items(): + if is_skipped_key(key): + continue + elif is_homogeneous_array(value): + obj[key] = to_typed_array_spec(value) + else: + convert_to_base64(value) + elif isinstance(obj, list) or isinstance(obj, tuple): + for value in obj: + convert_to_base64(value) + + +def cumsum(x): + """ + Custom cumsum to avoid a numpy import. + """ + + def _reducer(a, x): + if len(a) == 0: + return [x] + return a + [a[-1] + x] + + ret = reduce(_reducer, x, []) + return ret + + +class PlotlyJSONEncoder(_json.JSONEncoder): + """ + Meant to be passed as the `cls` kwarg to json.dumps(obj, cls=..) + + See PlotlyJSONEncoder.default for more implementation information. + + Additionally, this encoder overrides nan functionality so that 'Inf', + 'NaN' and '-Inf' encode to 'null'. Which is stricter JSON than the Python + version. + + """ + + def coerce_to_strict(self, const): + """ + This is used to ultimately *encode* into strict JSON, see `encode` + + """ + # before python 2.7, 'true', 'false', 'null', were include here. + if const in ("Infinity", "-Infinity", "NaN"): + return None + else: + return const + + def encode(self, o): + """ + Load and then dump the result using parse_constant kwarg + + Note that setting invalid separators will cause a failure at this step. + + """ + # this will raise errors in a normal-expected way + encoded_o = super(PlotlyJSONEncoder, self).encode(o) + # Brute force guessing whether NaN or Infinity values are in the string + # We catch false positive cases (e.g. strings such as titles, labels etc.) + # but this is ok since the intention is to skip the decoding / reencoding + # step when it's completely safe + + if not ("NaN" in encoded_o or "Infinity" in encoded_o): + return encoded_o + + # now: + # 1. `loads` to switch Infinity, -Infinity, NaN to None + # 2. `dumps` again so you get 'null' instead of extended JSON + try: + new_o = _json.loads(encoded_o, parse_constant=self.coerce_to_strict) + except ValueError: + # invalid separators will fail here. raise a helpful exception + raise ValueError( + "Encoding into strict JSON failed. Did you set the separators " + "valid JSON separators?" + ) + else: + return _json.dumps( + new_o, + sort_keys=self.sort_keys, + indent=self.indent, + separators=(self.item_separator, self.key_separator), + ) + + def default(self, obj): + """ + Accept an object (of unknown type) and try to encode with priority: + 1. builtin: user-defined objects + 2. sage: sage math cloud + 3. pandas: dataframes/series + 4. numpy: ndarrays + 5. datetime: time/datetime objects + + Each method throws a NotEncoded exception if it fails. + + The default method will only get hit if the object is not a type that + is naturally encoded by json: + + Normal objects: + dict object + list, tuple array + str, unicode string + int, long, float number + True true + False false + None null + + Extended objects: + float('nan') 'NaN' + float('infinity') 'Infinity' + float('-infinity') '-Infinity' + + Therefore, we only anticipate either unknown iterables or values here. + + """ + # TODO: The ordering if these methods is *very* important. Is this OK? + encoding_methods = ( + self.encode_as_plotly, + self.encode_as_sage, + self.encode_as_numpy, + self.encode_as_pandas, + self.encode_as_datetime, + self.encode_as_date, + self.encode_as_list, # because some values have `tolist` do last. + self.encode_as_decimal, + self.encode_as_pil, + ) + for encoding_method in encoding_methods: + try: + return encoding_method(obj) + except NotEncodable: + pass + return _json.JSONEncoder.default(self, obj) + + @staticmethod + def encode_as_plotly(obj): + """Attempt to use a builtin `to_plotly_json` method.""" + try: + return obj.to_plotly_json() + except AttributeError: + raise NotEncodable + + @staticmethod + def encode_as_list(obj): + """Attempt to use `tolist` method to convert to normal Python list.""" + if hasattr(obj, "tolist"): + return obj.tolist() + else: + raise NotEncodable + + @staticmethod + def encode_as_sage(obj): + """Attempt to convert sage.all.RR to floats and sage.all.ZZ to ints""" + sage_all = get_module("sage.all") + if not sage_all: + raise NotEncodable + + if obj in sage_all.RR: + return float(obj) + elif obj in sage_all.ZZ: + return int(obj) + else: + raise NotEncodable + + @staticmethod + def encode_as_pandas(obj): + """Attempt to convert pandas.NaT / pandas.NA""" + pandas = get_module("pandas", should_load=False) + if not pandas: + raise NotEncodable + + if obj is pandas.NaT: + return None + + # pandas.NA was introduced in pandas 1.0 + if hasattr(pandas, "NA") and obj is pandas.NA: + return None + + raise NotEncodable + + @staticmethod + def encode_as_numpy(obj): + """Attempt to convert numpy.ma.core.masked""" + numpy = get_module("numpy", should_load=False) + if not numpy: + raise NotEncodable + + if obj is numpy.ma.core.masked: + return float("nan") + elif isinstance(obj, numpy.ndarray) and obj.dtype.kind == "M": + try: + return numpy.datetime_as_string(obj).tolist() + except TypeError: + pass + + raise NotEncodable + + @staticmethod + def encode_as_datetime(obj): + """Convert datetime objects to iso-format strings""" + try: + return obj.isoformat() + except AttributeError: + raise NotEncodable + + @staticmethod + def encode_as_date(obj): + """Attempt to convert to utc-iso time string using date methods.""" + try: + time_string = obj.isoformat() + except AttributeError: + raise NotEncodable + else: + return iso_to_plotly_time_string(time_string) + + @staticmethod + def encode_as_decimal(obj): + """Attempt to encode decimal by converting it to float""" + if isinstance(obj, decimal.Decimal): + return float(obj) + else: + raise NotEncodable + + @staticmethod + def encode_as_pil(obj): + """Attempt to convert PIL.Image.Image to base64 data uri""" + image = get_module("PIL.Image") + if image is not None and isinstance(obj, image.Image): + return ImageUriValidator.pil_image_to_uri(obj) + else: + raise NotEncodable + + +class NotEncodable(Exception): + pass + + +def iso_to_plotly_time_string(iso_string): + """Remove timezone info and replace 'T' delimeter with ' ' (ws).""" + # make sure we don't send timezone info to plotly + if (iso_string.split("-")[:3] == "00:00") or (iso_string.split("+")[0] == "00:00"): + raise Exception( + "Plotly won't accept timestrings with timezone info.\n" + "All timestrings are assumed to be in UTC." + ) + + iso_string = iso_string.replace("-00:00", "").replace("+00:00", "") + + if iso_string.endswith("T00:00:00"): + return iso_string.replace("T00:00:00", "") + else: + return iso_string.replace("T", " ") + + +def template_doc(**names): + def _decorator(func): + if not sys.version_info[:2] == (3, 2): + if func.__doc__ is not None: + func.__doc__ = func.__doc__.format(**names) + return func + + return _decorator + + +def _natural_sort_strings(vals, reverse=False): + def key(v): + v_parts = re.split(r"(\d+)", v) + for i in range(len(v_parts)): + try: + v_parts[i] = int(v_parts[i]) + except ValueError: + # not an int + pass + return tuple(v_parts) + + return sorted(vals, key=key, reverse=reverse) + + +def _get_int_type(): + np = get_module("numpy", should_load=False) + if np: + int_type = (int, np.integer) + else: + int_type = (int,) + return int_type + + +def split_multichar(ss, chars): + """ + Split all the strings in ss at any of the characters in chars. + Example: + + >>> ss = ["a.string[0].with_separators"] + >>> chars = list(".[]_") + >>> split_multichar(ss, chars) + ['a', 'string', '0', '', 'with', 'separators'] + + :param (list) ss: A list of strings. + :param (list) chars: Is a list of chars (note: not a string). + """ + if len(chars) == 0: + return ss + c = chars.pop() + ss = reduce(lambda x, y: x + y, map(lambda x: x.split(c), ss)) + return split_multichar(ss, chars) + + +def split_string_positions(ss): + """ + Given a list of strings split using split_multichar, return a list of + integers representing the indices of the first character of every string in + the original string. + Example: + + >>> ss = ["a.string[0].with_separators"] + >>> chars = list(".[]_") + >>> ss_split = split_multichar(ss, chars) + >>> ss_split + ['a', 'string', '0', '', 'with', 'separators'] + >>> split_string_positions(ss_split) + [0, 2, 9, 11, 12, 17] + + :param (list) ss: A list of strings. + """ + return list( + map( + lambda t: t[0] + t[1], + zip(range(len(ss)), cumsum([0] + list(map(len, ss[:-1])))), + ) + ) + + +def display_string_positions(p, i=None, offset=0, length=1, char="^", trim=True): + """ + Return a string that is whitespace except at p[i] which is replaced with char. + If i is None then all the indices of the string in p are replaced with char. + + Example: + + >>> ss = ["a.string[0].with_separators"] + >>> chars = list(".[]_") + >>> ss_split = split_multichar(ss, chars) + >>> ss_split + ['a', 'string', '0', '', 'with', 'separators'] + >>> ss_pos = split_string_positions(ss_split) + >>> ss[0] + 'a.string[0].with_separators' + >>> display_string_positions(ss_pos,4) + ' ^' + >>> display_string_positions(ss_pos,4,offset=1,length=3,char="~",trim=False) + ' ~~~ ' + >>> display_string_positions(ss_pos) + '^ ^ ^ ^^ ^' + :param (list) p: A list of integers. + :param (integer|None) i: Optional index of p to display. + :param (integer) offset: Allows adding a number of spaces to the replacement. + :param (integer) length: Allows adding a replacement that is the char + repeated length times. + :param (str) char: allows customizing the replacement character. + :param (boolean) trim: trims the remaining whitespace if True. + """ + s = [" " for _ in range(max(p) + 1 + offset + length)] + maxaddr = 0 + if i is None: + for p_ in p: + for temp in range(length): + maxaddr = p_ + offset + temp + s[maxaddr] = char + else: + for temp in range(length): + maxaddr = p[i] + offset + temp + s[maxaddr] = char + ret = "".join(s) + if trim: + ret = ret[: maxaddr + 1] + return ret + + +def chomp_empty_strings(strings, c, reverse=False): + """ + Given a list of strings, some of which are the empty string "", replace the + empty strings with c and combine them with the closest non-empty string on + the left or "" if it is the first string. + Examples: + for c="_" + ['hey', '', 'why', '', '', 'whoa', '', ''] -> ['hey_', 'why__', 'whoa__'] + ['', 'hi', '', "I'm", 'bob', '', ''] -> ['_', 'hi_', "I'm", 'bob__'] + ['hi', "i'm", 'a', 'good', 'string'] -> ['hi', "i'm", 'a', 'good', 'string'] + Some special cases are: + [] -> [] + [''] -> [''] + ['', ''] -> ['_'] + ['', '', '', ''] -> ['___'] + If reverse is true, empty strings are combined with closest non-empty string + on the right or "" if it is the last string. + """ + + def _rev(vals): + return [s[::-1] for s in vals][::-1] + + if reverse: + return _rev(chomp_empty_strings(_rev(strings), c)) + if not len(strings): + return strings + if sum(map(len, strings)) == 0: + return [c * (len(strings) - 1)] + + class _Chomper: + def __init__(self, c): + self.c = c + + def __call__(self, x, y): + # x is list up to now + # y is next item in list + # x should be [""] initially, and then empty strings filtered out at the + # end + if len(y) == 0: + return x[:-1] + [x[-1] + self.c] + else: + return x + [y] + + return list(filter(len, reduce(_Chomper(c), strings, [""]))) + + +# taken from +# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python +def levenshtein(s1, s2): + if len(s1) < len(s2): + return levenshtein(s2, s1) # len(s1) >= len(s2) + if len(s2) == 0: + return len(s1) + previous_row = range(len(s2) + 1) + for i, c1 in enumerate(s1): + current_row = [i + 1] + for j, c2 in enumerate(s2): + # j+1 instead of j since previous_row and current_row are one character longer + # than s2 + insertions = previous_row[j + 1] + 1 + deletions = current_row[j] + 1 + substitutions = previous_row[j] + (c1 != c2) + current_row.append(min(insertions, deletions, substitutions)) + previous_row = current_row + return previous_row[-1] + + +def find_closest_string(string, strings): + def _key(s): + # sort by levenshtein distance and lexographically to maintain a stable + # sort for different keys with the same levenshtein distance + return (levenshtein(s, string), s) + + return sorted(strings, key=_key)[0] diff --git a/.venv_haddock/lib/python3.12/site-packages/_yaml/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/_yaml/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_yaml/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_yaml/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/_yaml/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_yaml/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/_yaml/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._INSTALLER b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._INSTALLER differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._METADATA b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._METADATA differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._RECORD b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._RECORD differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._WHEEL b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._WHEEL differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._licenses b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._licenses new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._licenses differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._top_level.txt b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/._top_level.txt differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..666069f83768bf7c831d3b24b08dff8b82288d8c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/METADATA @@ -0,0 +1,323 @@ +Metadata-Version: 2.4 +Name: biopython +Version: 1.87 +Summary: Freely available tools for computational molecular biology. +Author-email: The Biopython Contributors +License-Expression: LicenseRef-Biopython-License-Agreement +Project-URL: Homepage, https://biopython.org/ +Project-URL: Documentation, https://biopython.org/wiki/Documentation +Project-URL: Source, https://github.com/biopython/biopython/ +Project-URL: Tracker, https://github.com/biopython/biopython/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Bio-Informatics +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE.rst +Requires-Dist: numpy +Dynamic: license-file + +.. image:: https://img.shields.io/pypi/v/biopython.svg?logo=pypi + :alt: Biopython on the Python Package Index (PyPI) + :target: https://pypi.python.org/pypi/biopython +.. image:: https://img.shields.io/conda/vn/conda-forge/biopython.svg?logo=conda-forge + :alt: Biopython on the Conda package conda-forge channel + :target: https://anaconda.org/conda-forge/biopython +.. image:: https://results.pre-commit.ci/badge/github/biopython/biopython/master.svg + :target: https://results.pre-commit.ci/latest/github/biopython/biopython/master + :alt: pre-commit.ci status +.. image:: https://img.shields.io/circleci/build/github/biopython/biopython.svg?logo=circleci + :alt: Linux testing with CircleCI + :target: https://app.circleci.com/pipelines/github/biopython/biopython +.. image:: https://img.shields.io/appveyor/ci/biopython/biopython/master.svg?logo=appveyor + :alt: Windows testing with AppVeyor + :target: https://ci.appveyor.com/project/biopython/biopython/history +.. image:: https://img.shields.io/github/actions/workflow/status/biopython/biopython/ci.yml?logo=github-actions + :alt: GitHub workflow status + :target: https://github.com/biopython/biopython/actions +.. image:: https://img.shields.io/codecov/c/github/biopython/biopython/master.svg?logo=codecov + :alt: Test coverage on CodeCov + :target: https://codecov.io/github/biopython/biopython/ +.. image:: https://depsy.org/api/package/pypi/biopython/badge.svg + :alt: Research software impact on Depsy + :target: https://depsy.org/package/python/biopython + +.. image:: https://github.com/biopython/biopython/raw/master/Doc/images/biopython_logo_m.png + :alt: The Biopython Project + :target: https://biopython.org + +Biopython README file +===================== + +The Biopython Project is an international association of developers of freely +available Python tools for computational molecular biology. + +This README file is intended primarily for people interested in working +with the Biopython source code, either one of the releases from the +https://biopython.org website, or from our repository on GitHub +https://github.com/biopython/biopython + +Our user-centric documentation, `The Biopython Tutorial and Cookbook, and API +documentation `_, is generated from our +repository using Sphinx. + +The `NEWS `_ +file summarises the changes in each release of Biopython, alongside the +`DEPRECATED +`_ +file which notes API breakages. + +The Biopython package is open source software made available under generous +terms. Please see the `LICENSE +`_ file for +further details. + +If you use Biopython in work contributing to a scientific publication, we ask +that you cite our application note (below) or one of the module specific +publications (listed on our website): + +Cock, P.J.A. et al. Biopython: freely available Python tools for computational +molecular biology and bioinformatics. Bioinformatics 2009 Jun 1; 25(11) 1422-3 +https://doi.org/10.1093/bioinformatics/btp163 pmid:19304878 + + +For the impatient +================= + +Python includes the package management system "pip" which should allow you to +install Biopython (and its dependency NumPy if needed), upgrade or uninstall +with just one terminal command:: + + pip install biopython + pip install --upgrade biopython + pip uninstall biopython + +Since Biopython 1.70 we have provided pre-compiled binary wheel packages on +PyPI for Linux, macOS and Windows. This means pip install should be quick, +and not require a compiler. + +As a developer or potential contributor, you may wish to download, build and +install Biopython yourself. This is described below. + + +Python Requirements +=================== + +We currently recommend using Python 3.13 from https://www.python.org + +Biopython is currently supported and tested on the following Python +implementations: + +- Python 3.10, 3.11, 3.12, 3.13 and 3.14 -- see https://www.python.org + +- PyPy3.10 v7.3.17 -- or later, see https://www.pypy.org + + +Optional Dependencies +===================== + +Biopython requires NumPy (see https://www.numpy.org) which will be installed +automatically if you install Biopython with pip (see below for compiling +Biopython yourself). + +Depending on which parts of Biopython you plan to use, there are a number of +other optional Python dependencies, which can be installed later if needed: + +- ReportLab, see https://www.reportlab.com/opensource/ (optional) + This package is only used in ``Bio.Graphics``, so if you do not need this + functionality, you will not need to install this package. + +- matplotlib, see https://matplotlib.org/ (optional) + ``Bio.Phylo`` uses this package to plot phylogenetic trees. + +- networkx, see https://networkx.github.io/ (optional) and + pygraphviz or pydot, see https://pygraphviz.github.io/ and + https://code.google.com/p/pydot/ (optional) + These packages are used for certain niche functions in ``Bio.Phylo``. + +- rdflib, see https://github.com/RDFLib/rdflib (optional) + This package is used in the CDAO parser under ``Bio.Phylo``. + +- psycopg2, see https://initd.org/psycopg/ (optional) or + PyGreSQL (pgdb), see https://www.pygresql.org/ (optional) + These packages are used by ``BioSQL`` to access a PostgreSQL database. + +- MySQL Connector/Python, see https://dev.mysql.com/downloads/connector/python/ + This package is used by ``BioSQL`` to access a MySQL database, and is + supported on PyPy too. + +- mysqlclient, see https://github.com/PyMySQL/mysqlclient-python (optional) + This is a fork of the older MySQLdb and is used by ``BioSQL`` to access a + MySQL database. It is supported by PyPy. + +In addition there are a number of useful third party tools you may wish to +install such as standalone NCBI BLAST, EMBOSS or ClustalW. + + +Installation From Source +======================== + +We recommend using the pre-compiled binary wheels available on PyPI using:: + + pip install biopython + +However, if you need to compile Biopython yourself, the following are required +at compile time: + +- Python including development header files like ``python.h``, which on Linux + are often not installed by default (trying looking for and installing a + package named ``python-dev`` or ``python-devel`` as well as the ``python`` + package). + +- Appropriate C compiler for your version of Python, for example GCC on Linux, + or MSVC on Windows. For Windows, you must install the 'Visual Studio Build Tools' + and select the 'Desktop development with C++' workload. For macOS, use Apple's + command line tools, which can be installed with the terminal command:: + + xcode-select --install + + This will offer to install Apple's XCode development suite - you can, but it + is not needed and takes a lot of disk space. + +Then either download and decompress our source code, or fetch it using git. +Now change directory to the Biopython source code folder and run:: + + pip install -e . --group dev + cd Tests + python run_tests.py + +Substitute ``python`` with your specific version if required, for example +``python3``, or ``pypy3``. + +To exclude tests that require an internet connection (and which may take a +long time), use the ``--offline`` option:: + + cd Tests + python run_tests.py --offline + +Testing +======= + +Biopython includes a suite of regression tests to check if everything is +running correctly. To run the tests, go to the biopython source code +directory and type:: + + pip install -e . --group dev + cd Tests + python run_tests.py + +If you want to skip the online tests (which is recommended when doing repeated +testing), use:: + + cd Tests + python run_tests.py --offline + +Do not panic if you see messages warning of skipped tests:: + + test_DocSQL ... skipping. Install MySQLdb if you want to use Bio.DocSQL. + +This most likely means that a package is not installed. You can +ignore this if it occurs in the tests for a module that you were not +planning on using. If you did want to use that module, please install +the required dependency and re-run the tests. + +Some of the tests may fail due to network issues, this is often down to +chance or a service outage. If the problem does not go away on +re-running the tests, you can use the ``--offline`` option. + +There is more testing information in the Biopython Tutorial & Cookbook. + + +Experimental code +================= + +Biopython 1.61 introduced a new warning, ``Bio.BiopythonExperimentalWarning``, +which is used to mark any experimental code included in the otherwise +stable Biopython releases. Such 'beta' level code is ready for wider +testing, but still likely to change, and should only be tried by early +adopters in order to give feedback via the biopython-dev mailing list. + +We'd expect such experimental code to reach stable status within one or two +releases, at which point our normal policies about trying to preserve +backwards compatibility would apply. + + +Bugs +==== + +While we try to ship a robust package, bugs inevitably pop up. If you are +having problems that might be caused by a bug in Biopython, it is possible +that it has already been identified. Update to the latest release if you are +not using it already, and retry. If the problem persists, please search our +bug database and our mailing lists to see if it has already been reported +(and hopefully fixed), and if not please do report the bug. We can't fix +problems we don't know about ;) + +Issue tracker: https://github.com/biopython/biopython/issues + +If you suspect the problem lies within a parser, it is likely that the data +format has changed and broken the parsing code. (The text BLAST and GenBank +formats seem to be particularly fragile.) Thus, the parsing code in +Biopython is sometimes updated faster than we can build Biopython releases. +You can get the most recent parser by pulling the relevant files (e.g. the +ones in ``Bio.SeqIO`` or ``Bio.Blast``) from our git repository. However, be +careful when doing this, because the code in github is not as well-tested +as released code, and may contain new dependencies. + +In any bug report, please let us know: + +1. Which operating system and hardware (32 bit or 64 bit) you are using +2. Python version +3. Biopython version (or git commit/date) +4. Traceback that occurs (the full error message) + +And also ideally: + +5. Example code that breaks +6. A data file that causes the problem + + +Contributing, Bug Reports +========================= + +Biopython is run by volunteers from all over the world, with many types of +backgrounds. We are always looking for people interested in helping with code +development, web-site management, documentation writing, technical +administration, and whatever else comes up. + +If you wish to contribute, please first read `CONTRIBUTING.rst +`_ here, +visit our web site https://biopython.org and join our mailing list: +https://biopython.org/wiki/Mailing_lists + + +Distribution Structure +====================== + +- ``README.rst`` -- This file. +- ``NEWS.rst`` -- Release notes and news. +- ``LICENSE.rst`` -- What you can do with the code. +- ``CONTRIB.rst`` -- An (incomplete) list of people who helped Biopython in + one way or another. +- ``CONTRIBUTING.rst`` -- An overview about how to contribute to Biopython. +- ``DEPRECATED.rst`` -- Contains information about modules in Biopython that + were removed or no longer recommended for use, and how to update code that + uses those modules. +- ``MANIFEST.in`` -- Configures which files to include in releases. +- ``pyproject.toml`` -- Project metadata and build configuration. +- ``Bio/`` -- The main code base code. +- ``BioSQL/`` -- Code for using Biopython with BioSQL databases. +- ``Doc/`` -- Documentation. +- ``Scripts/`` -- Miscellaneous, possibly useful, standalone scripts. +- ``Tests/`` -- Regression testing code including sample data files. diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9ddc5f90460c2acafa4472d8c68f1951e72a8c7a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/RECORD @@ -0,0 +1,958 @@ +Bio/Affy/CelFile.py,sha256=-6lVGx7aOb7Re6fZUihtfoUSk0KGfdtTFvY7BvrIXS0,23598 +Bio/Affy/__init__.py,sha256=uM4tj7wOTHWfkae1s65HLs_FVthj_s1HZGpE1dAIUIM,296 +Bio/Affy/__pycache__/CelFile.cpython-312.pyc,, +Bio/Affy/__pycache__/__init__.cpython-312.pyc,, +Bio/Align/AlignInfo.py,sha256=z9F530E2KbSs6HAMtF2g-pE33Csor-eh3F2C6f3V3z4,1714 +Bio/Align/__init__.py,sha256=cl5F7qDBgJngolxpWPGGNJ0rPLaHxSR4v9ZQz89rneQ,196531 +Bio/Align/__pycache__/AlignInfo.cpython-312.pyc,, +Bio/Align/__pycache__/__init__.cpython-312.pyc,, +Bio/Align/__pycache__/a2m.cpython-312.pyc,, +Bio/Align/__pycache__/analysis.cpython-312.pyc,, +Bio/Align/__pycache__/bed.cpython-312.pyc,, +Bio/Align/__pycache__/bigbed.cpython-312.pyc,, +Bio/Align/__pycache__/bigmaf.cpython-312.pyc,, +Bio/Align/__pycache__/bigpsl.cpython-312.pyc,, +Bio/Align/__pycache__/chain.cpython-312.pyc,, +Bio/Align/__pycache__/clustal.cpython-312.pyc,, +Bio/Align/__pycache__/emboss.cpython-312.pyc,, +Bio/Align/__pycache__/exonerate.cpython-312.pyc,, +Bio/Align/__pycache__/fasta.cpython-312.pyc,, +Bio/Align/__pycache__/hhr.cpython-312.pyc,, +Bio/Align/__pycache__/interfaces.cpython-312.pyc,, +Bio/Align/__pycache__/maf.cpython-312.pyc,, +Bio/Align/__pycache__/mauve.cpython-312.pyc,, +Bio/Align/__pycache__/msf.cpython-312.pyc,, +Bio/Align/__pycache__/nexus.cpython-312.pyc,, +Bio/Align/__pycache__/phylip.cpython-312.pyc,, +Bio/Align/__pycache__/psl.cpython-312.pyc,, +Bio/Align/__pycache__/sam.cpython-312.pyc,, +Bio/Align/__pycache__/stockholm.cpython-312.pyc,, +Bio/Align/__pycache__/tabular.cpython-312.pyc,, +Bio/Align/_aligncore.c,sha256=XIFP1a7-IovM8IUSb2zFtqfvp1OISfK_lU4mAIS5huw,14084 +Bio/Align/_aligncore.cpython-312-darwin.so,sha256=CqgWKJ0dmdMz9nLE4AW4AuPsa6ckryUbP9-B7cVBKHc,52592 +Bio/Align/_alignmentcounts.c,sha256=OZzqyjbhB2f4wDYqJtBsGXl7HPEIDA7h2gr2kSRSufs,70159 +Bio/Align/_alignmentcounts.cpython-312-darwin.so,sha256=ZAx4hIxKXrYtszxKXo8F_dVCgWAUQpYOx4C6vfzjecE,62216 +Bio/Align/_codonaligner.c,sha256=Yq8HKUntswz7OI20b5sMKlW4YPI4c4nKLxS9TrzFRPc,33299 +Bio/Align/_codonaligner.cpython-312-darwin.so,sha256=w5vQsGg0wZgnigiaZo69R0LlHTadteOdLkldaTq8HXA,57840 +Bio/Align/_pairwisealigner.c,sha256=5kcA0dz-YI-pn_ZeJQDXxlSLTcaQOTkNMmyfuECTUU4,273667 +Bio/Align/_pairwisealigner.cpython-312-darwin.so,sha256=NFkrWHKNxEYXShwmZR-uEo9ZDrPmgBvPky8pqCQgqVY,191432 +Bio/Align/_pairwisealigner.h,sha256=b_VTM2cB46jSDCeEws70HvU2dP5XL7GV_VTILzyzXsw,1917 +Bio/Align/a2m.py,sha256=LMR8M-hMLn42kGjTf6RJe9UHhzsDFsXGS6MODo016ag,4523 +Bio/Align/analysis.py,sha256=HM0zy_rDcXD-zXtOe4SFTIpEGEE7Og2bg5S3rwOWHoA,46214 +Bio/Align/bed.py,sha256=8DPKzBfnQkoDfkHi2y_pTraYUZNmEQAICshbVa6-M68,9932 +Bio/Align/bigbed.py,sha256=cH5UxRqdM98LLjNy4cXLz8PaYOevxfJvzzWyFlpCrEc,81937 +Bio/Align/bigmaf.py,sha256=NUgveu9XTH8_xNhH8bl4N4fNU0iiCkvTsYAaqeNv4Zc,13708 +Bio/Align/bigpsl.py,sha256=bdPyWjvJo4zloR_aipbIENckQYw7zTbufgirKFCSX3g,23416 +Bio/Align/chain.py,sha256=e5vhCM0bu_k6egGhIsqMNBQvAVC_onMfz60p6FDsvZs,9448 +Bio/Align/clustal.py,sha256=MAbn8dfDqZblya_LGUsm0xxw5ycrVXnjU2ajN8zADks,9298 +Bio/Align/emboss.py,sha256=KIURqXKSAmD5a4etWkLt0HKI7BTm5lzCN0ceDvPJRO8,10387 +Bio/Align/exonerate.py,sha256=xJkeDnuVX-XbSn1fF6JnLXxx6_dAHnsHD35Gn_tpypo,26538 +Bio/Align/fasta.py,sha256=zkJ7TpdQunqs8n83YZWMgGHgKpND6BE5UnUJykLnxrk,3141 +Bio/Align/hhr.py,sha256=QySsXM_4Tu_2rrXNf0JGVomd5Ee9tY7t-ADib-I361A,9503 +Bio/Align/interfaces.py,sha256=NmSP7FwXmC7_WTk9Rk98Ie3qhSYpSDymD8IbWmf9kMc,12461 +Bio/Align/maf.py,sha256=qN51GXqk-7L38rsbgpdViNFRr2bP-jZC3NXPIJyJ774,18139 +Bio/Align/mauve.py,sha256=1SH9HSCXqSoOEGUSiKZ6mxZ1hW-RQz55X_F_DU2UvLo,10056 +Bio/Align/msf.py,sha256=UdoJ8cJlw0SWtP24oLi3NC2xZJ3YceqO50IJNzCuH6Y,9481 +Bio/Align/nexus.py,sha256=VxWzBEa7jLnHB_UjyfFpswK3CEuzAbSAH3n6jXfPv2E,7330 +Bio/Align/phylip.py,sha256=YoACjXqfB7aM_MJvhZM4UmLyoQGnzs5UniycGII6J9Y,6401 +Bio/Align/psl.py,sha256=F3aBFmusMF4TqJaojQAOiOSCIM3jfyrOj9ryJvlcAxg,22119 +Bio/Align/sam.py,sha256=0X6JI8-QxRs1QvWSefFyudBKWnDgB-eA-yvNMxUmj1Q,30565 +Bio/Align/stockholm.py,sha256=hIZ5RFxiMip8xPLFGol2x7MTiLlqLfcKQCeflMj4IIg,26134 +Bio/Align/substitution_matrices/__init__.py,sha256=jflADnCmma97h44cuazElfuYA19-LQm-yLxdCa_Oj4k,17563 +Bio/Align/substitution_matrices/__pycache__/__init__.cpython-312.pyc,, +Bio/Align/substitution_matrices/_arraycore.c,sha256=wYyNgHpXhEB0Y3S1cud7rcot8ZEjbPPDvkWSOcRzmj0,7958 +Bio/Align/substitution_matrices/_arraycore.cpython-312-darwin.so,sha256=qXYdfIFK0QdwQojfT1XPjVn_27SQ715X6qJs2TXvxQE,52224 +Bio/Align/substitution_matrices/_arraycore.h,sha256=kHkxjHuShJGv6RUADE-KISnbenfO1c3jj5uldPAuPM0,102 +Bio/Align/substitution_matrices/data/BENNER22,sha256=pLCoTJDekvb473IF0amcjRMUsl8UVZvg3TZ5mmfdwLw,2387 +Bio/Align/substitution_matrices/data/BENNER6,sha256=80wckPQPTG6Tuxa-wn1uD8-PWj1gQB9HpZpzSiH-cjk,2387 +Bio/Align/substitution_matrices/data/BENNER74,sha256=XhMG7539bm3wQ7ELNKxYBDxr8hB5GlA-MXrIQJKXjZw,2387 +Bio/Align/substitution_matrices/data/BLASTN,sha256=Dbn4BDSPOvF09mpiAsnAquB6uAcmxNT8a24y8KnEHgA,1715 +Bio/Align/substitution_matrices/data/BLASTP,sha256=Y3PzICgVynftfFWSw1ljW2zHozHX5CXQ86L6E2ywnRc,4009 +Bio/Align/substitution_matrices/data/BLOSUM45,sha256=GaB31QYKlKYhKtYJ3zA6JARjhzppaU6fV2xXYvv_2wk,2122 +Bio/Align/substitution_matrices/data/BLOSUM50,sha256=oVLjC4r8q0IoH_hgS8UTWL6YJTFV_eYq4gcHgFoNPWc,2122 +Bio/Align/substitution_matrices/data/BLOSUM62,sha256=hVENOEbubV9HeOQlz42vbg27iJswby0TQ04SVHgO-0A,2122 +Bio/Align/substitution_matrices/data/BLOSUM80,sha256=LllxdrgJKAi6GZz8nYDcjWV7Wj5QFd-4HVVyhYGc4Yc,2124 +Bio/Align/substitution_matrices/data/BLOSUM90,sha256=TebOIl7Y7oTgQcT2PC2vL0Oqhs3RsSCGgHTchJXHIU8,2122 +Bio/Align/substitution_matrices/data/DAYHOFF,sha256=f-YLd7bROKNeBoi9hRO-CP4mMUwxRXB9MWt6QyccTyM,2451 +Bio/Align/substitution_matrices/data/FENG,sha256=G8s8SLX2aFQlUkZ7ZCjxSh4SToY3PSkcuiRK_HsF1m0,1120 +Bio/Align/substitution_matrices/data/GENETIC,sha256=6gpGJV6X2xl6rmBBqiFKQDGOWsiNfXE-9bia767Ci7I,2380 +Bio/Align/substitution_matrices/data/GONNET1992,sha256=JwpOMtw7Z9b4KSikBiuPzm_0ievvE4iJ-HRn7echzic,2351 +Bio/Align/substitution_matrices/data/HOXD70,sha256=gRhfiXDqmcnwCUYEKC2oOCaDI9La-1MM1m9lBa_KVA0,275 +Bio/Align/substitution_matrices/data/JOHNSON,sha256=PRZBltCi7f8QFWKFZvo4sMgTbzJ_VNA3aMa125BohME,2818 +Bio/Align/substitution_matrices/data/JONES,sha256=uUzz4ilD3P85EYrgnReDgmKiH0Jb84_XG_Gmh6jQBEw,2413 +Bio/Align/substitution_matrices/data/LEVIN,sha256=lHAFw0KjmBdDbvyy8_XUNWZ_pFdQ8MuAZ0y1--GlAsc,1542 +Bio/Align/substitution_matrices/data/MCLACHLAN,sha256=OAHsc-AezSkvUgZlTv8ikxXGoi-ePAQQNdf1EIBKJ18,1092 +Bio/Align/substitution_matrices/data/MDM78,sha256=tv145JMZpAo6wD0pUYd-bGMouv4gHqq6KEUKX3oqe-U,2859 +Bio/Align/substitution_matrices/data/MEGABLAST,sha256=vxn1KrNl43MAP29eNuBhpXOm8hMmgIRjlE6gilxhgq4,1730 +Bio/Align/substitution_matrices/data/NUC.4.4,sha256=xgPkb5oVn7RRYyzfn5xoe659qtsw-yZF9f0Jys5wdJA,1171 +Bio/Align/substitution_matrices/data/PAM250,sha256=k2zF7yPgJixf2vdNXYH1iEjrdMyg1b7w85bSexaJcE4,2068 +Bio/Align/substitution_matrices/data/PAM30,sha256=j8VojReY4jJuqzcZue6SmZUqIMlDTkxVKL9FMuRYbmM,2666 +Bio/Align/substitution_matrices/data/PAM70,sha256=0YDiLYDyWtpBLW62MHD-cifJVHxmc3Jykf2bLUUpRuU,2666 +Bio/Align/substitution_matrices/data/RAO,sha256=s3vlt4JrQenqxkgtEPYfKmZDxZpfMUGrQ279nLVe1l4,1581 +Bio/Align/substitution_matrices/data/RISLER,sha256=RcTVfz3ex_pS8P-7vhOBXyk3HtqeTP8hJa3mi2lC1s0,2456 +Bio/Align/substitution_matrices/data/SCHNEIDER,sha256=YCM7j6uEsY44G7VztWNWqRFbJ4GN92dlvYeHvewtfEk,25459 +Bio/Align/substitution_matrices/data/STR,sha256=0Nn1oAYAgB1uNfZh--Zh3wgq71ksh0DbED-JBO22Nsk,1543 +Bio/Align/substitution_matrices/data/TRANS,sha256=M2lqFdEQTolEvHho6h8yT_a79oN3Y_SKbs9eV12MTS0,402 +Bio/Align/tabular.py,sha256=mGGJMxaGuHif_DkDNZF1VK9X_gLuFUzG8UrxhW5Zngg,16525 +Bio/AlignIO/ClustalIO.py,sha256=B9VI8tsp9423ehMUQeyYH-0caAuX-wqG5O6PSJ-WQUc,12152 +Bio/AlignIO/EmbossIO.py,sha256=ZmqRN385EVqpCPZd8Il_68pXVLTv3Wqjv_GjYv100X4,8749 +Bio/AlignIO/FastaIO.py,sha256=NW_pTDRqLIpuj8Uqln-IwduoP278Lrl7msItgQTxfP4,13355 +Bio/AlignIO/Interfaces.py,sha256=KgbcHY8FscYiHZzqCsC6kaRWZC21fXXhUzXK67DFKPQ,5598 +Bio/AlignIO/MafIO.py,sha256=nWxfIWTNoApKks0kjqWwXFDhy6LBLbhX2ed1ChxYjAs,35258 +Bio/AlignIO/MauveIO.py,sha256=EFDGlFzbG4rdjXEkqIGYIyOICxy2LtqChVgtFxoczX4,13300 +Bio/AlignIO/MsfIO.py,sha256=nYDa0UogWSyHNRL9scivzipgttnigJkL9yhPq2RnR7s,14209 +Bio/AlignIO/NexusIO.py,sha256=NXaVyjNuGC2RF6WBHis6P4ho2Xr4u4klem6c5rEDd7k,6226 +Bio/AlignIO/PhylipIO.py,sha256=9dkxgR-Z6UjehL-QayqbUSEdMZq6yZUCu2zTsUYQbVw,17138 +Bio/AlignIO/StockholmIO.py,sha256=PslgEcwyFLaXmk2gxgvleNS6Tw_rwWLs_VviQda717I,26397 +Bio/AlignIO/__init__.py,sha256=H6m587Wlij96BjMY06G4x2Y2RgKoDkIbuojrlKFwKqk,18499 +Bio/AlignIO/__pycache__/ClustalIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/EmbossIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/FastaIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/Interfaces.cpython-312.pyc,, +Bio/AlignIO/__pycache__/MafIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/MauveIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/MsfIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/NexusIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/PhylipIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/StockholmIO.cpython-312.pyc,, +Bio/AlignIO/__pycache__/__init__.cpython-312.pyc,, +Bio/Alphabet/__init__.py,sha256=dSLKJHXBnpVSwhn0CI4lngrjIbs40_dxTVkE5W4DnQg,1201 +Bio/Alphabet/__pycache__/__init__.cpython-312.pyc,, +Bio/Blast/NCBIWWW.py,sha256=k8ObKV4kRbI2nAWEvYsAs_tZUA7kg7Q1lv_cNI7lPFI,14116 +Bio/Blast/NCBIXML.py,sha256=L52ZDPr62nO90Sh9d9gzxL4qGbNX1cswwWTAE5reccI,49592 +Bio/Blast/__init__.py,sha256=D-8BGE2SU2a2Os-HFnA133jn95Pgwuyfokt6pVi4Ukc,51446 +Bio/Blast/__pycache__/NCBIWWW.cpython-312.pyc,, +Bio/Blast/__pycache__/NCBIXML.cpython-312.pyc,, +Bio/Blast/__pycache__/__init__.cpython-312.pyc,, +Bio/Blast/__pycache__/_parser.cpython-312.pyc,, +Bio/Blast/__pycache__/_writers.cpython-312.pyc,, +Bio/Blast/_parser.py,sha256=YYR-pSbWviWWVbIKcgtWdKlA42sYSruUn-6W2C5QRMQ,41609 +Bio/Blast/_writers.py,sha256=0pwXM4JQdV88zb_sIthZbjPJ3sxre49jpnaV2GzFRqc,39674 +Bio/CAPS/__init__.py,sha256=LyarDVqCzvIEsas4MsIVFyWWrbRDqf6K0bq7bUPWuss,4111 +Bio/CAPS/__pycache__/__init__.cpython-312.pyc,, +Bio/Cluster/__init__.py,sha256=K9m6A-Yyh3UiA-VHNtGi66TXCu1KYe14hZvkyhjRDXg,50617 +Bio/Cluster/__pycache__/__init__.cpython-312.pyc,, +Bio/Cluster/_cluster.cpython-312-darwin.so,sha256=bk_9F47SP0tJqR5odPEoBev1Au2QAKn-FTZd-gazOpA,145344 +Bio/Cluster/cluster.c,sha256=rImdaSesCaORbsowXmNQhjpSfh9SRJYTrpCRAjfxsos,169419 +Bio/Cluster/cluster.h,sha256=vjyDYtx1pHJzqM-Xz-kD7-h-nfaj3ncAhluusi6b6Nw,4135 +Bio/Cluster/clustermodule.c,sha256=1g0TlzhRenMPYaHiawzGRbT8B2bx2ud_ubYfLE7pntM,78475 +Bio/Compass/__init__.py,sha256=9erbso1s0178fUpE20wNxxRk4a6I3WkhvikNFima6ZE,6954 +Bio/Compass/__pycache__/__init__.cpython-312.pyc,, +Bio/Data/CodonTable.py,sha256=gQKGwPyW3wqFPdEXiBRZXP8fOcsJYCn5VGRjdG8UkrQ,50509 +Bio/Data/IUPACData.py,sha256=iX-0LxvW4_g3vmkYrmxU535hATsoTLq9Tn38AXI-GpE,9223 +Bio/Data/PDBData.py,sha256=eg1XGcbzZKKzjYipAGg_Hu7Gf8ZBuVEcO2a5AKC-C4s,22894 +Bio/Data/__init__.py,sha256=O1j0QX2yYPYShUh2AkuTlamT0-p0fLWN9UqxB0nI10U,353 +Bio/Data/__pycache__/CodonTable.cpython-312.pyc,, +Bio/Data/__pycache__/IUPACData.cpython-312.pyc,, +Bio/Data/__pycache__/PDBData.cpython-312.pyc,, +Bio/Data/__pycache__/__init__.cpython-312.pyc,, +Bio/Emboss/Primer3.py,sha256=HSXIA9kRIBB3usGm3klOtKM--GmuuBMiYfmBvXX04UQ,5576 +Bio/Emboss/PrimerSearch.py,sha256=06js3szg1IXXvH_1KjiKOvNLv02yAmzS31j9sRPwhVE,2521 +Bio/Emboss/__init__.py,sha256=COuy4yEwiWplMnGIdXhrQlAIcxsnTA4NGQiHNf-sOH4,355 +Bio/Emboss/__pycache__/Primer3.cpython-312.pyc,, +Bio/Emboss/__pycache__/PrimerSearch.cpython-312.pyc,, +Bio/Emboss/__pycache__/__init__.cpython-312.pyc,, +Bio/Entrez/DTDs/BITS-embedded-index2.ent,sha256=HdPxOSvsisukxE7_pma4EjFks-IyF7wIxM7w4PxMc3I,16498 +Bio/Entrez/DTDs/BITS-question-answer2.ent,sha256=AijL9jgSolxyUWIjrolhKCJyRbxzlUe__iHEMpRfgP4,26770 +Bio/Entrez/DTDs/Docsum_3_0.dtd,sha256=7ZGcRICWuGjRBLhEUfA3JLDyncXxzkM29-jFler0NSw,660 +Bio/Entrez/DTDs/Docsum_3_0.mod.dtd,sha256=jTAG4Mgbc1UMwUfjHfWHm1HmpANnD7MBfQFbmT6Yps8,33675 +Bio/Entrez/DTDs/Docsum_3_1.dtd,sha256=I8oC3ye63BK1LQHPF1tO_Hzf19lAjWYBpJr4ZnmYLvg,660 +Bio/Entrez/DTDs/Docsum_3_1.mod.dtd,sha256=CW-GuJb2W_SKpeAISZRPN_JDrL54AGwVV5pHF78AV10,33691 +Bio/Entrez/DTDs/Docsum_3_2.dtd,sha256=Y1Ar3m3bMggIlB1pAWi04mWSq7e9SeA9P2UBGbd68Sg,660 +Bio/Entrez/DTDs/Docsum_3_2.mod.dtd,sha256=xCXs81yq14ssk6YYPAdf3da_xdmarTkMweNlyIYtFSo,36007 +Bio/Entrez/DTDs/Docsum_3_3.dtd,sha256=7fpkqJthafb1WFmA84XzqGYURoblfd4x4AxyC9h8qOk,660 +Bio/Entrez/DTDs/Docsum_3_3.mod.dtd,sha256=TWoPWXJq_opkfQCMhKMDLPyCzh2EYALKPu2L2-1c0cA,41304 +Bio/Entrez/DTDs/Docsum_3_4.dtd,sha256=h2_g2ihfHHTZig0Uo7KX4hxLnxFPIexbtogTqfH_nwk,660 +Bio/Entrez/DTDs/Docsum_3_4.mod.dtd,sha256=IS9RllcI91GHGDnSrLn3sMrltu-RdpIWgwiTzyTM9cA,41537 +Bio/Entrez/DTDs/EMBL_General.dtd,sha256=Aq63w9Awp4caUK-H3ibEkX6L8_sNWNcyxTMQvPTqxC4,792 +Bio/Entrez/DTDs/EMBL_General.mod.dtd,sha256=7qr0rLYAFronVM0Ty1GZXHkEK1rGDjAf_hFkrp0Er94,2871 +Bio/Entrez/DTDs/GenBank_General.dtd,sha256=XhHIWzgaltizgo3j7DOvoF1h4phLjIZytcd0QTwOJq4,807 +Bio/Entrez/DTDs/GenBank_General.mod.dtd,sha256=pNW5YNvmpP9yHP4WTE0YzwUzrubtxQBsp6jJm8mwyI8,1743 +Bio/Entrez/DTDs/HomoloGene.dtd,sha256=B1d7yMAYc8rB37Rz2ZHKnDDbOiAoaIVwh3U-hAvpp5c,3500 +Bio/Entrez/DTDs/HomoloGene.mod.dtd,sha256=j4UTVS0E063j9Ua6J6xDLKq51MtP8UwwC9EyKpvK0ro,6460 +Bio/Entrez/DTDs/INSD_INSDSeq.dtd,sha256=bhpy5ifC60JR388lQzYuZ66SdQMEADaVCaxaoy-iJus,671 +Bio/Entrez/DTDs/INSD_INSDSeq.mod.dtd,sha256=j74Wtsl0pIV6uyYoTMclFsybwkoi6KtNEQqb16NVSv4,14705 +Bio/Entrez/DTDs/JATS-XHTMLtablesetup1-3.ent,sha256=mZdLRl62Vz55Lkw5SkaxR8QNk_ZQOJQGyxBG6v2iaVo,31246 +Bio/Entrez/DTDs/JATS-ali-namespace1-3.ent,sha256=BA2fFqwQ32iY1Jh6p60iXnJVFBvj7B9YOH5npwIM8jU,15260 +Bio/Entrez/DTDs/JATS-archivearticle1-3-mathml3.dtd,sha256=Og8oTSuf4-3NCCVTO_qsDVYL6QSIX7iWm9M5sPqX_SM,51353 +Bio/Entrez/DTDs/JATS-archivecustom-classes1-3.ent,sha256=Ntq3zOsyHpsSvqSg4girNzoLCc0MhvnwKzHTLMRv1qQ,20885 +Bio/Entrez/DTDs/JATS-archivecustom-mixes1-3.ent,sha256=tFeXpjQ6PcWo5AmvYY5L657LkEN0e6sd6QRUD_G0ADQ,31272 +Bio/Entrez/DTDs/JATS-archivecustom-models1-3.ent,sha256=G0DPDpzfyPRSWm_1ETVkCr9d8ua1eFi8SlaLiHL_nGk,78956 +Bio/Entrez/DTDs/JATS-archivecustom-modules1-3.ent,sha256=5WHlK7QhG0bFW-jSreT6ulwLaHgbVULjsy8Z1QtFZ5k,20899 +Bio/Entrez/DTDs/JATS-articlemeta1-3.ent,sha256=givPeJeH4FEJMLqHfezdx-LJaSvwlx7CAynwnPFFySQ,128551 +Bio/Entrez/DTDs/JATS-backmatter1-3.ent,sha256=6hXgTU5p9ZI9L5OTE3Twlt8HGdipwRlFXC0sBRSOkJQ,26909 +Bio/Entrez/DTDs/JATS-chars1-3.ent,sha256=Hhc9-54mfOrjh0otYtnqchrPW6Wj3dMKFtTISWn6fdo,35219 +Bio/Entrez/DTDs/JATS-common-atts1-3.ent,sha256=tfrDvJBBEWUdFrINXtfQ0F0mp75YDoMThy9D3biwQIw,18691 +Bio/Entrez/DTDs/JATS-common1-3.ent,sha256=U_8xp3x7efQ5XjNZT2M8uNWwGrR4_SxTom8VbRN8AJ4,237581 +Bio/Entrez/DTDs/JATS-default-classes1-3.ent,sha256=buWgECKx383aTQUjsEAzVFutSZRJ1BdexZcNmktIzf8,75822 +Bio/Entrez/DTDs/JATS-default-mixes1-3.ent,sha256=GnaB1wLbUTfHotkzi8oYdJFVmtpZ0E0SJDVNDXyRnTU,32971 +Bio/Entrez/DTDs/JATS-display1-3.ent,sha256=vrA3TnAcxKac18PJIWyygjD6v6vy5f5tmRTPW4Z-o88,65828 +Bio/Entrez/DTDs/JATS-format1-3.ent,sha256=fA8xHFkQVIDdgSZiqlHMWQrAIgC54LyoZDdtyo2pgoU,50729 +Bio/Entrez/DTDs/JATS-funding1-3.ent,sha256=9g9Oy82LEvU0VnDHAv8KvMr6oORqy5XgVWWDA5yNbfk,56436 +Bio/Entrez/DTDs/JATS-journalmeta1-3.ent,sha256=5oy_UmO8kcfA7zsLtFzHodrgbo7f1aBjkVsGPRj1e7Q,29732 +Bio/Entrez/DTDs/JATS-link1-3.ent,sha256=E4gdGlp828-WFUL0NXXtUExeljN295YDZVpls8tXnME,30254 +Bio/Entrez/DTDs/JATS-list1-3.ent,sha256=1Uz0L45ztFPb3zhM_7lKYAJ47mzSu4c5ENUH3J0H5cU,32721 +Bio/Entrez/DTDs/JATS-math1-3.ent,sha256=OwhtspWPZHD8m1vJfwlPMWDLY67nRIftGj6R4XenDSQ,27873 +Bio/Entrez/DTDs/JATS-mathml3-mathmlsetup1-3.ent,sha256=KBCPgQhY765S2Y2b1UuiKf-qJ8U3Lb9UfyLuWYoOw-w,23901 +Bio/Entrez/DTDs/JATS-mathml3-modules1-3.ent,sha256=cBkuhZJBL9lVM93WoDY_txtlBelpM7Zu4Yj3ufPiqvg,16430 +Bio/Entrez/DTDs/JATS-modules1-3.ent,sha256=9fAQVjLO00yN8VVGz9KMUI5qaIhMTkUehAhfsFgITQg,37192 +Bio/Entrez/DTDs/JATS-nlmcitation1-3.ent,sha256=vzO5DNSQHgKuMEaFWx9L3vgnjs3kRQTrabujXm-TFRI,21564 +Bio/Entrez/DTDs/JATS-notat1-3.ent,sha256=YSjM8iWIZxMZnNZU2ESeEpttH4NIN2Pv5bBcqM6gJZ8,20223 +Bio/Entrez/DTDs/JATS-para1-3.ent,sha256=zmfZO66wDCT0L3aEedWfGGE582YXcLtjEKLTCDaht0k,32349 +Bio/Entrez/DTDs/JATS-phrase1-3.ent,sha256=uAnwHD4M_BWYI3nlm0wEvN4t80xRO765zvdZj163exY,33583 +Bio/Entrez/DTDs/JATS-references1-3.ent,sha256=VOQLBPVFE-LBwIjQIqNvJHsDXDxWFq58qTBs3suQLJg,73018 +Bio/Entrez/DTDs/JATS-related-object1-3.ent,sha256=qiW_ere8_UPZC5NO2X5GRWReh4w0MDq-Ji2foz65_BU,21380 +Bio/Entrez/DTDs/JATS-section1-3.ent,sha256=uZFlQNek5V1HwkwQ2Pgz_hiOHza6pEK3afuL6HjBUIM,23664 +Bio/Entrez/DTDs/JATS-xmlspecchars1-3.ent,sha256=NV_F_YdYiVWkq1duVwKlUG2AgcdOgSCllXUQDBjpTLc,24007 +Bio/Entrez/DTDs/MMDB.dtd,sha256=8o_TklOQ25jAD9yjCIy6uDfstP8-XW9RoMPPRWQFlpk,3893 +Bio/Entrez/DTDs/MMDB.mod.dtd,sha256=H4DSNhGf-qKWKXnf5xuEOCklfMxDslvPw9NyLiNHuhM,9382 +Bio/Entrez/DTDs/MMDB_Chemical_graph.dtd,sha256=Yp9KueP5jPkYXwCSrp7vmJmwqfsA8fuVG78SkjTijxA,3908 +Bio/Entrez/DTDs/MMDB_Chemical_graph.mod.dtd,sha256=Q-4oVDmtOIVQ9LmDxUM2-K3Sbqm0D8-ZqeJh6-ucr20,17213 +Bio/Entrez/DTDs/MMDB_Features.dtd,sha256=ZnIklyKSjNpLBlva9FynGHTaTnzu2WtWq9ztwydkQUM,3902 +Bio/Entrez/DTDs/MMDB_Features.mod.dtd,sha256=IE-HX9S9Y3Gyn60rlWC-fh7CtKPLqbSD6LV_Osbres0,28680 +Bio/Entrez/DTDs/MMDB_Structural_model.dtd,sha256=wY_C4hHNch8U15uUdnkz-KfCAFVVmNicgAfcNRJi-RY,3910 +Bio/Entrez/DTDs/MMDB_Structural_model.mod.dtd,sha256=dnc8V4-Sl8FvHwkWSogB5fi7pP7sRp1JFjDn91-l9wk,25075 +Bio/Entrez/DTDs/NCBI_Access.dtd,sha256=aNyJgAUlVxBghaPmGYk7rCDIXVmq70ZP7gFRVLZtIyA,665 +Bio/Entrez/DTDs/NCBI_Access.mod.dtd,sha256=qKGcufgqJMxBImW6GSOW_tTaT1mi1qZgUURhBPvDfj4,1221 +Bio/Entrez/DTDs/NCBI_Biblio.dtd,sha256=4yEPk-cGVfNsPJenNS2pBAqSReVHM3AlNeS1linwaL4,785 +Bio/Entrez/DTDs/NCBI_Biblio.mod.dtd,sha256=YYKdqksAsjrAlJ2yh3nbEMazrHqCASSmnGzjBugih2k,15918 +Bio/Entrez/DTDs/NCBI_BioSource.dtd,sha256=cnHbtmIS-gasedMlLCGCeU3ZYtyCWqbvFbHEde0cdlY,925 +Bio/Entrez/DTDs/NCBI_BioSource.mod.dtd,sha256=pkvjkUm6yzLzgeAqBNdN-q1Kw8OOlMWxfCj-B5CHGLA,4641 +Bio/Entrez/DTDs/NCBI_BioTree.dtd,sha256=K1rYdVK9B6y5etOoIr7nMfTD8nkzL4SwshMBY9vgIiU,671 +Bio/Entrez/DTDs/NCBI_BioTree.mod.dtd,sha256=fmRrhBNPfzAota7-8azgpmSWGVll0_LHE9Jt4tbva3c,2444 +Bio/Entrez/DTDs/NCBI_Blast4.dtd,sha256=XE6zyvOLzcNIUxZRGqJNK3_U2irEHUB9pLYdTH2UtyY,3740 +Bio/Entrez/DTDs/NCBI_Blast4.mod.dtd,sha256=rEsskJxU9R8uJ8Y4fnIWWT2mU6PvgBOrT87r0CxUXoU,39597 +Bio/Entrez/DTDs/NCBI_BlastDL.dtd,sha256=C9GLe5fnXGyY_nikZvrPM56bDihl15k6NyynZxH-IrQ,3507 +Bio/Entrez/DTDs/NCBI_BlastDL.mod.dtd,sha256=zi2_S-CDfO452KQI4VVdAeAD-XLnhlh3oCTlnLOs5_w,4281 +Bio/Entrez/DTDs/NCBI_BlastOutput.dtd,sha256=cdvqJTUh_mkkbVosh_pNMlQtB7zAwhB5dheilvgc4RE,692 +Bio/Entrez/DTDs/NCBI_BlastOutput.mod.dtd,sha256=RqhaX3g_hua-nUpJDFJg-BgSioGZv9sNw-O2zQ7Fqms,6579 +Bio/Entrez/DTDs/NCBI_Cdd.dtd,sha256=CdiGbFqR-DV5tdc8wYh2uq7gXe2V-z9ZWHBsgQSkQRM,4347 +Bio/Entrez/DTDs/NCBI_Cdd.mod.dtd,sha256=5y3dtlMKYPglaz0eyYG4R2Evc56Z1lG6fsKMbEllHZA,28292 +Bio/Entrez/DTDs/NCBI_Cn3d.dtd,sha256=Gvmx4-FWSEv9Yuccw3wdAcQqLDN9kBv7qnlxJSpWwog,4005 +Bio/Entrez/DTDs/NCBI_Cn3d.mod.dtd,sha256=3M65R1gc7Mpmw2sU7KjOXwdZtW06gbexLzLYAVzjy-I,16758 +Bio/Entrez/DTDs/NCBI_Entity.mod.dtd,sha256=2xe54TA_By5tbMPPdFxcocMFUNiaoxK-MJFpfQiF3rY,410 +Bio/Entrez/DTDs/NCBI_Entrez2.dtd,sha256=i3aMulqQN3f3sMQE4dGE9DgdOKyf7HicJFHrb8DU70E,671 +Bio/Entrez/DTDs/NCBI_Entrez2.mod.dtd,sha256=4vIwr4XgQaZMDi_HErtpq2qQPSWRc_Wre4kHQ6nvXUo,21922 +Bio/Entrez/DTDs/NCBI_Entrezgene.dtd,sha256=4dr19jpGDBjYASME3hB3nuNefr3b6-0Yu13NQGZjIrU,3525 +Bio/Entrez/DTDs/NCBI_Entrezgene.mod.dtd,sha256=GO27Y6hhPHANlymRgNW9boI0Xc7Xt9602hG2oBFEVyc,10316 +Bio/Entrez/DTDs/NCBI_FeatDef.dtd,sha256=STKp93xHN6S9hAENQp2knyrDCOt15bFYLwodC6711h4,671 +Bio/Entrez/DTDs/NCBI_FeatDef.mod.dtd,sha256=BocJqizMjC-hxnfyiAUq45MCjHeeCFgUnIeABvyZ06g,2358 +Bio/Entrez/DTDs/NCBI_GBSeq.dtd,sha256=Rt8os_PzMrx1h5pzp_JTau4_480vgjxpmFvBEWcoevI,659 +Bio/Entrez/DTDs/NCBI_GBSeq.mod.dtd,sha256=8i-pBCxZbXUHT-FTRpznGQzXSFEBdjxDyThRFt78ipE,11502 +Bio/Entrez/DTDs/NCBI_Gene.dtd,sha256=lJ8t650BA1NONodHzpqwCmB3o5kL9bgb-wi4WSaSGV8,776 +Bio/Entrez/DTDs/NCBI_Gene.mod.dtd,sha256=H2T7ARAKtJrQEF9QzBXoiGB0pKT2CXAz0TDZ5YC23Vs,2381 +Bio/Entrez/DTDs/NCBI_General.dtd,sha256=tpy7lJG6xQOMqa0T3BJe-6JFZMM697YCM4j4Pj9Ejuk,671 +Bio/Entrez/DTDs/NCBI_General.mod.dtd,sha256=jLoXdJQ4E3nQ1TohN6yyeXuoWnUMruPLXX4md8Xi0gU,8215 +Bio/Entrez/DTDs/NCBI_ID1Access.dtd,sha256=MsUZrJscC5vRHo7Yp1B3mmNg7RwEUW8ImarKYh_kl2c,3629 +Bio/Entrez/DTDs/NCBI_ID1Access.mod.dtd,sha256=qieXojxAkci4Xb9DoODr8gDHJmzYqL3pNeY0rfn9Wa0,5733 +Bio/Entrez/DTDs/NCBI_ID2Access.dtd,sha256=t4yTR8qVNiLvTYYKcSCz7BWnbdTYomz5masiqrXcvMs,3757 +Bio/Entrez/DTDs/NCBI_ID2Access.mod.dtd,sha256=ROwJqyXoOX6vRvbEV2GgXQhMs99-dPVlL_OzzYqPEBc,23205 +Bio/Entrez/DTDs/NCBI_MedArchive.dtd,sha256=NkTQHe7O85nrerhqwtwqWv86XQscMH0x-rnJTJMPoj0,1378 +Bio/Entrez/DTDs/NCBI_MedArchive.mod.dtd,sha256=LocUWbGjILixCPx9R6ejdnkUqDf1mfN4U5S2sCDCAIw,6931 +Bio/Entrez/DTDs/NCBI_Medlars.dtd,sha256=RQg93Tgoex1uX_N-h_6DuUSj52BhJC6mTb80rP62qzA,907 +Bio/Entrez/DTDs/NCBI_Medlars.mod.dtd,sha256=kEb6kwItqxMaFX0EqqZiS5ZZ-00NsSbm2RsMYYysosw,1617 +Bio/Entrez/DTDs/NCBI_Medline.dtd,sha256=uNxb4wBqbRKcfXJpIl4uGX9iGxSCbMl8H1X3fZWoDBA,907 +Bio/Entrez/DTDs/NCBI_Medline.mod.dtd,sha256=8ig5vQcNkB-ewUBH87dL4eZ1jx7PfYBrD5Cu1I-khqc,5757 +Bio/Entrez/DTDs/NCBI_Mim.dtd,sha256=uIMYWrK7Vkz4KybpYIisCcjQasikRgHDb3ejlBjoiJc,647 +Bio/Entrez/DTDs/NCBI_Mim.mod.dtd,sha256=EKfBcoxMQslGMvtu-miMdKTXl4SbrTSt79kxeIUbp_c,8395 +Bio/Entrez/DTDs/NCBI_Mime.dtd,sha256=g5TECscn4CAgkQGhnN2dMYCGWaGEeBxSAbXe6nIemoQ,4461 +Bio/Entrez/DTDs/NCBI_Mime.mod.dtd,sha256=XNM01f8sKIvAjauudb_Sw5mvNuZiKV7LIh4-7sdK2yI,7270 +Bio/Entrez/DTDs/NCBI_ObjPrt.dtd,sha256=7Gq9WPyaC40Z32jSFI1mUSjlhpa4_MoU2j4gk_xKMXk,665 +Bio/Entrez/DTDs/NCBI_ObjPrt.mod.dtd,sha256=RnbU0oDsnOIGZF0BdztML0jQ1Q55wiK2r-8wRjZLmPQ,3131 +Bio/Entrez/DTDs/NCBI_Organism.dtd,sha256=IuGRTHZm4KQkFOpyG403aGfMu6XOJUExHyoJd9iKAtg,796 +Bio/Entrez/DTDs/NCBI_Organism.mod.dtd,sha256=80ahiOw_6ZGGx1Nid4bNeIaDF_Mi9xLkKBd_7MySIu4,5250 +Bio/Entrez/DTDs/NCBI_PCAssay.dtd,sha256=FeKjeUP0QTeI1hZSXetaF3ZVrf5H7K2UaZdrRBW80EA,1519 +Bio/Entrez/DTDs/NCBI_PCAssay.mod.dtd,sha256=y9liJr3Sn_e86C5Pj96wx30zhQbYZ16jUpRM58Ni0QE,31800 +Bio/Entrez/DTDs/NCBI_PCSubstance.dtd,sha256=Fs3zuVllU7A01hMiVIszL0jU8Lbwbt6G9wJ-LvuaJMU,1155 +Bio/Entrez/DTDs/NCBI_PCSubstance.mod.dtd,sha256=iTRVhiSo-ZUbvRRcJCATx61K6Zivll6JBsYEJA1Puhc,43623 +Bio/Entrez/DTDs/NCBI_Project.dtd,sha256=VMcguPNeuLZ1owpGOQJdFSefv1l2jp6sTn4l5wbj63Y,3736 +Bio/Entrez/DTDs/NCBI_Project.mod.dtd,sha256=641_UjWWjD7ZJplh3GeE-4mV0ckW3YvoKTDNgNadhA0,3769 +Bio/Entrez/DTDs/NCBI_Protein.dtd,sha256=XoSIPrbCwWUlr5Na7ErJBZuAzTuCAAZ_XVDOerrK-lU,791 +Bio/Entrez/DTDs/NCBI_Protein.mod.dtd,sha256=XJpQe9rFagTmn8rjm8s5m_pwItuQiHCJy0oO7fndYeo,1791 +Bio/Entrez/DTDs/NCBI_Pub.dtd,sha256=ZzB3n3MApCzPgQYieV3ZH5uTs2bzSHCvq6CUo5Zs6dY,1003 +Bio/Entrez/DTDs/NCBI_Pub.mod.dtd,sha256=pJ8PIYUpeCbYSfe21M2nokaDf8I9N1U3A1e-o6ANUqQ,2700 +Bio/Entrez/DTDs/NCBI_PubMed.dtd,sha256=jfXKsD32O_oU9OkWJ9SfYII1oBXFztsBKZod_z_rZBM,1021 +Bio/Entrez/DTDs/NCBI_PubMed.mod.dtd,sha256=hx45aYybW7oskwnK2glFb8utcYxMZ_TX2ABpNwEH694,1698 +Bio/Entrez/DTDs/NCBI_RNA.dtd,sha256=r9OFvk7A659wRiWVRNoArDnEaaTdtPRHBHQpKROL4vg,3383 +Bio/Entrez/DTDs/NCBI_RNA.mod.dtd,sha256=nmjKpennw3EMJjWoIwH2bmMB61omr6WxZ25RuqjD2Mw,3379 +Bio/Entrez/DTDs/NCBI_Remap.dtd,sha256=BSNg9ciSemrUMYRbhFzEPqCykkH5atXm02SdVTuZOIU,3495 +Bio/Entrez/DTDs/NCBI_Remap.mod.dtd,sha256=KGt0KiHjGCc1sUSD2-N5VpC5wHPrGEIy37p1SP7kLuI,4064 +Bio/Entrez/DTDs/NCBI_Rsite.dtd,sha256=sBQz31SvF5nV5tALDmRfyZs4yrnnc8uTpNvFxqpSfi8,781 +Bio/Entrez/DTDs/NCBI_Rsite.mod.dtd,sha256=5O2ab5claOg5Wf6JNcDaTuKXGIs5QViiymj0BkXwjZo,1044 +Bio/Entrez/DTDs/NCBI_ScoreMat.dtd,sha256=NmgfAx8RaUNGHBaR7DOmEMt2AU0yc7WG9K3tyuOsJSM,3629 +Bio/Entrez/DTDs/NCBI_ScoreMat.mod.dtd,sha256=9Gw8gKkTNFmGTi1584tZZBovlgBLGDWjHZd0a4k_aH4,19503 +Bio/Entrez/DTDs/NCBI_SeqCode.dtd,sha256=wsElBnAymD7ZRSv3ZvnbKjSgk8iGUq9XXuyGxapmJ3k,671 +Bio/Entrez/DTDs/NCBI_SeqCode.mod.dtd,sha256=uUxXZhHSTPAKKk0-4RptG-LRAeJafTscRoEhgBjLMIM,4231 +Bio/Entrez/DTDs/NCBI_SeqTable.dtd,sha256=3KTsu1iq8OItYeHtZjWrae3pvUsP9aGdNf0bbFFr798,3389 +Bio/Entrez/DTDs/NCBI_SeqTable.mod.dtd,sha256=RPllvGSZE0tO-2XEpCho53s9MD45WAnkyh3-JAWz6FE,9912 +Bio/Entrez/DTDs/NCBI_Seq_split.dtd,sha256=X16El8p5HwFPJ4CxEcua2N4SEpKOelWU_JFe67AK628,3634 +Bio/Entrez/DTDs/NCBI_Seq_split.mod.dtd,sha256=qUeN5WBuzbmu89QOz3F7JctUZyKtoPfRN_VGiqsKRUY,11475 +Bio/Entrez/DTDs/NCBI_Seqalign.dtd,sha256=RhPcqjot4vmAR9jSBnGbtJSbA2YTo4_bxaDMR8Ib6Rc,3389 +Bio/Entrez/DTDs/NCBI_Seqalign.mod.dtd,sha256=kT7uwFilHKjmrtXIKT-zrE5286yrYh6dPAoJL37dcVM,15026 +Bio/Entrez/DTDs/NCBI_Seqfeat.dtd,sha256=8KYy27sT11PRnsNSWnF2PZgxacG6Cv8OMi7d86sarpQ,3387 +Bio/Entrez/DTDs/NCBI_Seqfeat.mod.dtd,sha256=dCtWissG5XTffQFX-gthe5iPFDTnnqOGfT-InZYrqlM,19204 +Bio/Entrez/DTDs/NCBI_Seqloc.dtd,sha256=MMew861PLYRaQEIfaRMM-H756AvcCvL0o9HkQpH7s6I,3385 +Bio/Entrez/DTDs/NCBI_Seqloc.mod.dtd,sha256=IX528bn4S5ymU7j2hTz7Yx4jgQ6ElMcW9TX1OB1L-1c,7383 +Bio/Entrez/DTDs/NCBI_Seqres.dtd,sha256=9oAqimMEHPsqKoURtjYNaxgAHLTZtmd7vYzi_CjD3JE,3385 +Bio/Entrez/DTDs/NCBI_Seqres.mod.dtd,sha256=cQDPBXeSofBlWTCwu6uGyOW5G3YJevgaJOsQn9tGV-o,3149 +Bio/Entrez/DTDs/NCBI_Seqset.dtd,sha256=vskX5qkvEHsabozo5iqezsFAQcGQU6xcNXZ3qeeTAFo,3501 +Bio/Entrez/DTDs/NCBI_Seqset.mod.dtd,sha256=8xlQ9oG56eq2BYgKt1GCedpJCF4hWb-0aZEgTEnW8eY,3479 +Bio/Entrez/DTDs/NCBI_Sequence.dtd,sha256=cEI03PDqxwzgDlkMvk-yufxXOkxbmiLBdHfFP3lpAso,3384 +Bio/Entrez/DTDs/NCBI_Sequence.mod.dtd,sha256=ugzzX_6CJi9vDxu-rr-DS7TWRCD7P0nkogrO71SjhpY,26293 +Bio/Entrez/DTDs/NCBI_Submit.dtd,sha256=2jzCuajZbqJvPoTF22NYAqGlvEwWUJrqCwwj9zJw6JE,3617 +Bio/Entrez/DTDs/NCBI_Submit.mod.dtd,sha256=iunQK7Rdu_dJjAL57g9EtrVCeJgN6XBAs1YZBmhOcjc,4130 +Bio/Entrez/DTDs/NCBI_Systems.dtd,sha256=saQQjxO3-Ks3cUNKRQcuH6ohDk7B3pqeLBzwUisEZOY,3379 +Bio/Entrez/DTDs/NCBI_TSeq.dtd,sha256=LPbK2qwPbhLfzCXU7PPkmINBum2m4B4AlQ-eVoBI6Uc,656 +Bio/Entrez/DTDs/NCBI_TSeq.mod.dtd,sha256=zLhRDIfejxx9RPh45qlPjqwDRW3GG4-fwHMSX3kxHgo,1660 +Bio/Entrez/DTDs/NCBI_TxInit.dtd,sha256=vRmESYnpRfducIFeY0II8XETa9Ob7NI4TU2KTq6xVac,1138 +Bio/Entrez/DTDs/NCBI_TxInit.mod.dtd,sha256=tav_Ms5Qjq0gpvoOchuOXWJ60klKNE5oVDs1nw5xIwc,4625 +Bio/Entrez/DTDs/NCBI_Variation.dtd,sha256=eOKRTGIVa7CfavmYAUcIUTIATK22k-pv_VP9zU-ammY,3389 +Bio/Entrez/DTDs/NCBI_Variation.mod.dtd,sha256=jOApQ49K2X-F535-yGDGe6AEXKHwbgI1Xw6o1zW0b_E,27155 +Bio/Entrez/DTDs/NCBI_all.dtd,sha256=e7XeHIev6wThr8s_9uT6Sj7dF502nfGA4AgasRVLWaA,7893 +Bio/Entrez/DTDs/NSE.dtd,sha256=L3mgGXxnzx01qvIBuZOTjsC728XRdSMsCCXmYrh3UX8,625 +Bio/Entrez/DTDs/NSE.mod.dtd,sha256=a9BTqZurN6mGOvZlKNl8oitJrM6dQEugMmCR2-cUHGo,26853 +Bio/Entrez/DTDs/OMSSA.dtd,sha256=elWNHN0VKqkg863NvGWFO4VJOTXI6AosZA1bwQhF7HE,3470 +Bio/Entrez/DTDs/OMSSA.mod.dtd,sha256=zYCmIZ8CvtO1XstO-USMaLB3ncW-dc4Zw4XPYigMcFc,34917 +Bio/Entrez/DTDs/PDB_General.dtd,sha256=2_8JUKHvYtGc5MbAbyHjyFHMInGYJV6AEBDlR_aHxjg,787 +Bio/Entrez/DTDs/PDB_General.mod.dtd,sha256=1Xf6BTjyGHtvdyzp7XhkKzR7PbhjabjpCflNjeskbAw,1815 +Bio/Entrez/DTDs/PIR_General.dtd,sha256=-ud6dN3XRycgCzGBmFSCnq_Ho9hWQQMRZU4EEhdUTWM,3387 +Bio/Entrez/DTDs/PIR_General.mod.dtd,sha256=-6Jr11CVBrhoTEQNzFNNrdpvdNGxxr0HXI9Eu3am-DQ,2076 +Bio/Entrez/DTDs/PRF_General.dtd,sha256=F2YTtdyaRdvDRJwzl7fjtOOjQhLu-uGn6orG0QO2or8,667 +Bio/Entrez/DTDs/PRF_General.mod.dtd,sha256=o658lwkLDcTseWREFx4FNkYOw48KN2O4BMnwXSM2vAs,1535 +Bio/Entrez/DTDs/SP_General.dtd,sha256=pLIfpaLpOVA8MpuwMafaPZIpyDLgufZ3sgH5ZQlE4OY,3386 +Bio/Entrez/DTDs/SP_General.mod.dtd,sha256=DV5zmzP4a089dU9nmr9UoMN6vdsY4_E0zNKCKgus2Og,2375 +Bio/Entrez/DTDs/XHTMLtablesetup.ent,sha256=pMSlJTftz5OwjyC-_grm-L9Lt5SykBZ4K2y75qamIUo,17329 +Bio/Entrez/DTDs/archivearticle.dtd,sha256=MET5vcqH_9QEV5gRIurHth8T9TPNqzu4vJCm7nm5Lr8,51298 +Bio/Entrez/DTDs/archivecustom-classes.ent,sha256=jkaxy1V46gWHJaAPv_cURSxpeZ5GsRjJRC90dT-L_MU,8304 +Bio/Entrez/DTDs/archivecustom-mixes.ent,sha256=do9tIJzVSIakOmoPnqzpuh8Ff8n4SQtQ6MTQNrLM2_8,16646 +Bio/Entrez/DTDs/archivecustom-models.ent,sha256=J6c2_-uusjX9lF3_1BXufKGpUjFs-uowm2UWGY16E4s,38921 +Bio/Entrez/DTDs/archivecustom-modules.ent,sha256=eC_FFu2d1dccqSyqNlAsjC2QGquV5GltHbN7cq-qoeU,6412 +Bio/Entrez/DTDs/articlemeta.ent,sha256=uFAN9ouF3yNmbrDhMpZKyWyCEK6_Vdp92OXh-vYDQHY,98004 +Bio/Entrez/DTDs/backmatter.ent,sha256=9U5ZalynymL5Bnwn7BzEx2nf2A-I4rXn63C-WSRNXIs,15090 +Bio/Entrez/DTDs/bookdoc_100301.dtd,sha256=vFcHye_i6RW6WL4y1md-TCiqVpzGKN9c_-nczdCprys,2645 +Bio/Entrez/DTDs/bookdoc_110101.dtd,sha256=vFcHye_i6RW6WL4y1md-TCiqVpzGKN9c_-nczdCprys,2645 +Bio/Entrez/DTDs/bookdoc_120101.dtd,sha256=vFcHye_i6RW6WL4y1md-TCiqVpzGKN9c_-nczdCprys,2645 +Bio/Entrez/DTDs/bookdoc_130101.dtd,sha256=qPFrpOOa8kYltgzEfAgaQbbr8xQXP4pqPODUGYoDOJ0,2756 +Bio/Entrez/DTDs/bookdoc_140101.dtd,sha256=qPFrpOOa8kYltgzEfAgaQbbr8xQXP4pqPODUGYoDOJ0,2756 +Bio/Entrez/DTDs/bookdoc_150101.dtd,sha256=qPFrpOOa8kYltgzEfAgaQbbr8xQXP4pqPODUGYoDOJ0,2756 +Bio/Entrez/DTDs/chars.ent,sha256=L9fpP6AGUsz2Wo5U6LUb5MdbnhW1sZiC6L7V6XawdiM,21412 +Bio/Entrez/DTDs/common.ent,sha256=lYzWjlvFGDis2_4aZ5USQzbj82ke-0Eufkiq19rcyOI,152388 +Bio/Entrez/DTDs/default-classes.ent,sha256=bKFYECnPymhiNfGAvMzXC23PtCh6JfVOXCs_6DY-O88,33182 +Bio/Entrez/DTDs/default-mixes.ent,sha256=a4Jeda6RyIzAJocDYu8HIwmYGNjtPajAVROOzbNBKxg,19402 +Bio/Entrez/DTDs/display.ent,sha256=-Q_ZSQ6I2h1hyqCY4l5b5fzu-ysJ_ioTrFebMlLAmbw,82067 +Bio/Entrez/DTDs/eInfo_020511.dtd,sha256=aG7lBmF68KNsiNhllCUOq2xzmKPIMIaTDIIYqglQHu8,1655 +Bio/Entrez/DTDs/eLink_090910.dtd,sha256=Xd4mnBGw0Ca8OjCt0PA9kYtJbHMf0HvinZ-0TGS0YVo,2299 +Bio/Entrez/DTDs/eLink_101123.dtd,sha256=KZA8UxqTi-KrRbg7fG0oNYC6kTkP7ZEPl2mjR3GhdUo,2447 +Bio/Entrez/DTDs/ePost_020511.dtd,sha256=VwukI9A1PW-pcy4LB5RRdVGo5mD5DSzHuyBJlahe58g,520 +Bio/Entrez/DTDs/eSearch_020511.dtd,sha256=VsL7ZmztSk9zda9el2g1wyXmcAUycr0h05FIV5gS74c,2392 +Bio/Entrez/DTDs/eSpell.dtd,sha256=_yDVizsLoKjolPHON7ML7gwxLmy3o7XX2ukYe_ith74,736 +Bio/Entrez/DTDs/eSummary_041029.dtd,sha256=jug43errNhwuF6lbH-lN7MBveyaa-WyO1aoQc_z9lno,602 +Bio/Entrez/DTDs/egquery.dtd,sha256=vtauwIAeqdzXhi8fJqy6uf5d_zdFOzZuZvRxeL2uxnE,851 +Bio/Entrez/DTDs/einfo.dtd,sha256=flJk5s4yhvq2W46q0pD0IaUFxoWr2-tBnGdm9T992yg,1980 +Bio/Entrez/DTDs/elink.dtd,sha256=KZA8UxqTi-KrRbg7fG0oNYC6kTkP7ZEPl2mjR3GhdUo,2447 +Bio/Entrez/DTDs/elink_020122.dtd,sha256=rgPalXtmk1Rso0bdRQJ-BffTifYDIH8U4wrqMjV3ZHo,466 +Bio/Entrez/DTDs/epost.dtd,sha256=VwukI9A1PW-pcy4LB5RRdVGo5mD5DSzHuyBJlahe58g,520 +Bio/Entrez/DTDs/esearch.dtd,sha256=l70GlAyVx6cmllr64-CaHZ_hZarRHpjMgKlOfx-qLTg,3337 +Bio/Entrez/DTDs/esummary-v1.dtd,sha256=jug43errNhwuF6lbH-lN7MBveyaa-WyO1aoQc_z9lno,602 +Bio/Entrez/DTDs/esummary_clinvar.dtd,sha256=RP5QjEFbx2KWBmu416JXdLZY2AAmlzztsjoFnISfHUI,8040 +Bio/Entrez/DTDs/esummary_gene.dtd,sha256=C8f6fxR15cYmfhlXoV6PBfxDvUeNdEjQtADLDCfCED8,4163 +Bio/Entrez/DTDs/format.ent,sha256=mOa7_62TyBZK4MpJZg5uA1cf1Ct_npcIP_S-SdE038A,22746 +Bio/Entrez/DTDs/htmltable.dtd,sha256=Wsju2DzjtiVma4L6uHLIsWjgo33tI66XuGHFqPAjUcw,9849 +Bio/Entrez/DTDs/isoamsa.ent,sha256=GH1Jw-gM7KnbalbN-r9vURh8O5mUN6qXH2PNZP3XzXc,11589 +Bio/Entrez/DTDs/isoamsb.ent,sha256=vkg9B1QqbTGdi_k172ht9dPYe2P1fxe0bn-A_FHhp7k,9556 +Bio/Entrez/DTDs/isoamsc.ent,sha256=kkw1k-mOi7niKBtyXei8epMheTJFHDXtdp52KhuD3us,2254 +Bio/Entrez/DTDs/isoamsn.ent,sha256=uaQalCFMcgho83l6Fmclp8pdIAFiIOuZgK3gQhMTCzw,7945 +Bio/Entrez/DTDs/isoamso.ent,sha256=MUriBI5j9FfvAICPOj6-PNwIGnz8mP2UYamc4761b8U,4432 +Bio/Entrez/DTDs/isoamsr.ent,sha256=2vpeKkPl2fr1zOpPpNm6ibxcDMnkTjONXZa5omE2iWU,14133 +Bio/Entrez/DTDs/isobox.ent,sha256=OKYRXaEovQpTA_P3oQklQBQrximz9cAQmUgvjWx3Ug4,3507 +Bio/Entrez/DTDs/isocyr1.ent,sha256=4RZ1xTRw5BypIRbMTUQVGwhF2sRPzFp4w_suYiYjIMI,5257 +Bio/Entrez/DTDs/isocyr2.ent,sha256=o5qiJMRO3kMU-gtjp-k31-FNVn4rL31p0bKkpYYotB8,2457 +Bio/Entrez/DTDs/isodia.ent,sha256=PagdFcNO-RUrdtmLv3jk_X5UpdZmYN_MI2FVOzNH7tY,1473 +Bio/Entrez/DTDs/isogrk1.ent,sha256=2dnwGe2Lc0E8EWD350mZPMVA6oVxSOYouDmtpgrQ3g8,4102 +Bio/Entrez/DTDs/isogrk2.ent,sha256=0KNMYv6j4IuuUXwICFmLCbRb2_D_R2JF5K5dmZm377U,2389 +Bio/Entrez/DTDs/isogrk3.ent,sha256=IYAcnVbnWehXbNVEI6NX7dNB5xGV5_JUrNAGIvfJG5k,3699 +Bio/Entrez/DTDs/isogrk4.ent,sha256=_8ljq43-ZfUbsweyM7r0YRf4Si_g4irr_oDvR3qyOOY,3591 +Bio/Entrez/DTDs/isolat1.ent,sha256=W3kRUuV2drO4xQe8BNJYRGc8NMd1Hz9xtH8W-kJifoY,5199 +Bio/Entrez/DTDs/isolat2.ent,sha256=24pU6kXFzYpHUBxydqiLYOp_pFFgdNR9AxAcES2qXWw,8865 +Bio/Entrez/DTDs/isomfrk.ent,sha256=JimvrtuftcqxXJC5nK1YPHjG2mrwAM66u7U4mSqgHP8,4478 +Bio/Entrez/DTDs/isomopf.ent,sha256=Hz2gfe7th4LvrmrpJIjbSyVQTGm5M5O94IJiCEvD15Q,2522 +Bio/Entrez/DTDs/isomscr.ent,sha256=S8sjXp0WakDU1GV9iQurkUaUwci8_15v2Wn7a9s8ZQY,4557 +Bio/Entrez/DTDs/isonum.ent,sha256=pNQC3pk9UhI7jdM-dpj2GgT47Thiw0pTwqjfcSMAEDY,5816 +Bio/Entrez/DTDs/isopub.ent,sha256=Q3t5NQ4EXQafFMeUFIaslOIbIMo3Y_8OuqYRv74oj2g,6594 +Bio/Entrez/DTDs/isotech.ent,sha256=X1MbZMTwss4Zsis4Tzp0hWtzXSozESNO-GwdqyHz64M,12399 +Bio/Entrez/DTDs/journalmeta.ent,sha256=dzUy8aYJxnIhzOo-89FetC2SdNzw0voECvr4iURLabc,18988 +Bio/Entrez/DTDs/link.ent,sha256=gaeJl3kpZ3_55PqVPDyfKDKDIqJP3DeHblgOpnbT23k,28360 +Bio/Entrez/DTDs/list.ent,sha256=ke4CYbWhohcvZqPauNBIg5DHjgt14YHIC7I7qi21h9o,25663 +Bio/Entrez/DTDs/math.ent,sha256=X-ID1KnAz2HTqrA8uvB2-2-HXRl2W8r8ihZndVVRlp8,18334 +Bio/Entrez/DTDs/mathml-in-pubmed.mod,sha256=JEdFDllSTYme0pm9WjE1hVURKy0T3l1SF4qY_vl9Swo,6820 +Bio/Entrez/DTDs/mathml2-qname-1.mod,sha256=2WYXCQgVtax_DMJE4Wz0nQYiWxt4-m_z4bXTCQVcC4M,12948 +Bio/Entrez/DTDs/mathml2.dtd,sha256=LjOhvDtndW7BQF0QNX2kBSpQpFqlMJFco7vFzZt6cYM,50791 +Bio/Entrez/DTDs/mathml3-qname1.mod,sha256=jQEYIgRVtqAiZb6x9XmOqw5Ewdq1OrqrTYXPvMKvR54,12255 +Bio/Entrez/DTDs/mathml3.dtd,sha256=i8bDuihkXJJ6zm0wKRgN5q6hvEW3B6EMW8OKG-MDRbc,42407 +Bio/Entrez/DTDs/mathmlsetup.ent,sha256=RzVijIpCuL4kHtnef50H_1a0-cBO3A7br72QDQmOrfA,10452 +Bio/Entrez/DTDs/mmlalias.ent,sha256=UtxHlmtlUp5otOF_AU2fHD3go844XrpmAPpvLoD_MTc,37695 +Bio/Entrez/DTDs/mmlextra.ent,sha256=FbyPdxTAfPqtooS9wi9uilpAfmgvPpixayMHxXdRNac,7776 +Bio/Entrez/DTDs/modules.ent,sha256=5Bc42vE99Qe1AWFGxkg2gtTBo0QWEYCC606EcY_5eos,21579 +Bio/Entrez/DTDs/nlm-articleset-2.0.dtd,sha256=jF_rBcGNoIoWfnub1luNiHXJBQqN9o8MFwYwA1FLrLw,35333 +Bio/Entrez/DTDs/nlmcatalogrecordset_170601.dtd,sha256=zVBPd7C12RnewTsqOjHadIr0YvvGqtPJQOwF1mVgttc,12369 +Bio/Entrez/DTDs/nlmcommon_011101.dtd,sha256=TFRRotd5JhjVeEinqvdicxEOs6ok9HHYfAhRH_QF5cs,5839 +Bio/Entrez/DTDs/nlmcommon_080101.dtd,sha256=xWMdAKnEPC6kc8T6xB0paFhED9dLEOtF-TthiyYfmrc,7946 +Bio/Entrez/DTDs/nlmcommon_090101.dtd,sha256=4fnrqF1p_yKMHENZcBrbSLeVnsEPwbHle2OurokOr9c,8638 +Bio/Entrez/DTDs/nlmmedline_011101.dtd,sha256=cUX6PfwkxEPqxuwPNSKk8Vfk9I_JKvabXgPce78eCEM,2053 +Bio/Entrez/DTDs/nlmmedline_080101.dtd,sha256=77exsUHPLwoKRzo0pVgxI8SjJzcFrvdXZyrVldF7Jis,3017 +Bio/Entrez/DTDs/nlmmedline_090101.dtd,sha256=8TtPnfW4afjOcJBoAxtbyalsrSwSmcqEHRnpM46Vj2A,3195 +Bio/Entrez/DTDs/nlmmedlinecitation_011101.dtd,sha256=z4M-4ZKpYAozJH9Z9g3wF-GCrh75ETskz41QAfCnF6Y,6760 +Bio/Entrez/DTDs/nlmmedlinecitation_080101.dtd,sha256=QscN6yGVx51XAiy8erXcDUYif-sf82_P0es35iP6sHc,5001 +Bio/Entrez/DTDs/nlmmedlinecitation_090101.dtd,sha256=0btDyH1pypO0U0lfalZ6QoYpzQ4roOenTc0VF6_2nYA,5262 +Bio/Entrez/DTDs/nlmmedlinecitationset_100101.dtd,sha256=IifD6QlOXTx350NGYvXOJzhjDJX520dgprFpVH9IGWM,9322 +Bio/Entrez/DTDs/nlmmedlinecitationset_100301.dtd,sha256=DPVPngtaWtRLr1q2NyocXA07NemyB38MEZpMPBZYgEc,9618 +Bio/Entrez/DTDs/nlmmedlinecitationset_110101.dtd,sha256=9yPia1GT1mpWB3OBxHzfZG2Xl3c2sv_mazO-KseOZdo,9308 +Bio/Entrez/DTDs/nlmmedlinecitationset_120101.dtd,sha256=jC6j_N1lYmVncbfyIOK-OneNvKaOqufeYoN58SYKKAk,8829 +Bio/Entrez/DTDs/nlmmedlinecitationset_130101.dtd,sha256=L9mUro3WB95nv_yu1ANnzW1tySHbTSzLhX6fur-PgoY,8995 +Bio/Entrez/DTDs/nlmmedlinecitationset_130501.dtd,sha256=WzNSa95vM2mHY2EqINOpTgT7wFU5lcSqEbF_Mc-UBXc,9033 +Bio/Entrez/DTDs/nlmmedlinecitationset_140101.dtd,sha256=bfpnLgztqwGHpayi8B1BOnW4L_ZMGIignFitoyGwuzU,9112 +Bio/Entrez/DTDs/nlmmedlinecitationset_150101.dtd,sha256=HW9VKNWFMq8rkzeS8HeaWjwrh2fkKJNzpmwcpJR4cZQ,8947 +Bio/Entrez/DTDs/nlmserials_080101.dtd,sha256=Bqg_xRNPDFzaZRKSCPyoW5vRHnJHyrS2fOeKFl_4aJI,5672 +Bio/Entrez/DTDs/nlmserials_100101.dtd,sha256=odmX_CV_rHEq0IOsX1psIdJ2ShqvDHlYjPUdSv3SO7o,6703 +Bio/Entrez/DTDs/nlmsharedcatcit_080101.dtd,sha256=1ze4V86srXps-XNepcgKeWMOK1mte0MT0KkgJ98ylBc,3185 +Bio/Entrez/DTDs/nlmsharedcatcit_090101.dtd,sha256=7cUZKV1Pysy5q64byPx9OsOQ3lDmlbDRXnJwRxIC828,3317 +Bio/Entrez/DTDs/notat.ent,sha256=8T3TF0GSFDrlpY_l4ekQlxOUDlijaIoUxi9-H7ahkrs,9656 +Bio/Entrez/DTDs/para.ent,sha256=dL0ilkXsSkhRk9qXS2jesdvNqvBYTHpG7lPckDLB5jg,23807 +Bio/Entrez/DTDs/phrase.ent,sha256=DAkQer5pKPRhDJ9x-ymZyJlvHkYexH8X8V2yjaboG2s,15750 +Bio/Entrez/DTDs/pmc-1.dtd,sha256=XqrPQO-uHRN3spjNGBM3lsqHtczbZmL9RPTGZYGvxTc,25142 +Bio/Entrez/DTDs/pubmed_020114.dtd,sha256=IAGfdULpjjPODM-484qKyuXuXB2TwZbLuIqLUmOseNE,2714 +Bio/Entrez/DTDs/pubmed_080101.dtd,sha256=CkV3XF9NEkA_lYaFwWaRbvPH26mOQi5RMfmOaaSd2-U,3045 +Bio/Entrez/DTDs/pubmed_090101.dtd,sha256=zHzlgy2wCVoj0tq43VBKgQaWn-7ng1c5HtMgSM8ejiU,3059 +Bio/Entrez/DTDs/pubmed_100101.dtd,sha256=ELG9N5PSni2xixzYk3wIGog-2BW6Sv7nq3npxuShg7Q,3126 +Bio/Entrez/DTDs/pubmed_100301.dtd,sha256=LGYfgB3eC_Xp-bVRnufJT6AunEPNmnIH1PZgSll-dss,3434 +Bio/Entrez/DTDs/pubmed_110101.dtd,sha256=v3RFxJfGLCmYYS5XO4FZcIFmoGe0BlfY2I8PtAZmLgI,3434 +Bio/Entrez/DTDs/pubmed_120101.dtd,sha256=Ldmtv03z9o_IGFjjntrCcNMvYlEhr4qNje6ZDyVxF_M,3434 +Bio/Entrez/DTDs/pubmed_130101.dtd,sha256=tCV7OTohcjx4BotvD1YuFeoxXuAcEuRVlYu7qNuCsoM,3434 +Bio/Entrez/DTDs/pubmed_130501.dtd,sha256=gse-pDXqfgfBWrXq5YUSlbI3-Uo2I_kWcxAYvDIOABk,3445 +Bio/Entrez/DTDs/pubmed_140101.dtd,sha256=MGQK_6agHEmmwLIsKzzuPmbdJ88ZngdX-tmgqDQ3AGM,3445 +Bio/Entrez/DTDs/pubmed_150101.dtd,sha256=4FsJ1veegs8frYmQV7BBdqY2q8-bDV8I4r_7CBM4P_Y,3445 +Bio/Entrez/DTDs/pubmed_180101.dtd,sha256=ZeC8wT6YZTNGD5LaTx1c9nhXpXGFsjqdu8rHB5sVEkc,13062 +Bio/Entrez/DTDs/pubmed_180601.dtd,sha256=ok38f9usTiSV-0_iQcOetobtQS5cHonNWQOgM_Pbb6U,13869 +Bio/Entrez/DTDs/pubmed_190101.dtd,sha256=84BRtNsD6GjVDS7WKSNl1lC2d5PmmwN4BwDwI1LanCM,14576 +Bio/Entrez/DTDs/pubmed_230101.dtd,sha256=TkZv5Njde4wzImi4_aQ9-MOtYqVCRLqjySutwazQaCw,14297 +Bio/Entrez/DTDs/pubmed_240101.dtd,sha256=P520LjqcFh41LY5zAmNxiB4Kjc-Bh-70zPJk_MJLiuM,14624 +Bio/Entrez/DTDs/pubmed_250101.dtd,sha256=jJo8UgJZu3nKh8BAIWcetH_TAGRqoYE72ITEGCF9FXM,14430 +Bio/Entrez/DTDs/references.ent,sha256=VpAcxvqPMQxXGCd0znOX8xAZTKF3nLxcx_0oChQLa3A,40015 +Bio/Entrez/DTDs/section.ent,sha256=DV-jbZDiKokNZNVmCwgeqwYwYjA4Ljsvqei9MUOfjRk,13173 +Bio/Entrez/DTDs/taxon.dtd,sha256=fecg7a0W5zvdn3E2YLbucD6jVV5M1Z2iecyuRfYZ5ZM,4003 +Bio/Entrez/DTDs/xhtml-inlstyle-1.mod,sha256=gbwS95pApcQVeLn9MTH9csLQK11OyNGBkcZDUAbc3V4,1141 +Bio/Entrez/DTDs/xhtml-table-1.mod,sha256=Oetem0tGJ9dBbfi7A5TxAHEd0lL7fPehMW-AzNeQewk,9503 +Bio/Entrez/DTDs/xmlspecchars.ent,sha256=6hVOLeK0wKOtEy7qJqh1-b_z0a_GBRZL7PBKIn8eQpw,13595 +Bio/Entrez/Parser.py,sha256=24E47QFOlNBiNyoBJxldXc0raSta7nMhlbvRQz085uo,46942 +Bio/Entrez/XSDs/IPGReportSet.xsd,sha256=N71qfT3YknPSaTnHdx8VSAPzrDkcuAqQpILeQLJ3bTk,3536 +Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd,sha256=AAMj-wM5qk6ye-LMlTb-DQN60l5Ka1_gJ12_E_U1BPk,12059 +Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd,sha256=yox6a4NST2jKr4hsq6E1NQSKy9m3i_MIbt6ipu3qlnQ,774 +Bio/Entrez/__init__.py,sha256=8e7KjzCrun1wJKtcmhmOfgXvre3eAocdcCRCBeUXkeY,29644 +Bio/Entrez/__pycache__/Parser.cpython-312.pyc,, +Bio/Entrez/__pycache__/__init__.cpython-312.pyc,, +Bio/ExPASy/Enzyme.py,sha256=sdjDF6_Da2YnELLRaiQNTltVpUZBHnthHSecDtenyIk,4570 +Bio/ExPASy/Prodoc.py,sha256=Ql5Esgo0rmOiYXvscuznFCdErITLndWFAQdggDnYp88,5009 +Bio/ExPASy/Prosite.py,sha256=X3iA6M2uZNKaGDAEQQiqBpYdyOD11P091fZII6ARYB0,11495 +Bio/ExPASy/ScanProsite.py,sha256=4EgmQTq4YTfilavG1aYUBHK3wZw3B0Vx7fMEhUUaGBY,5284 +Bio/ExPASy/__init__.py,sha256=3Y5zdyliQ21IRxVbKvl6mBPaIKhIK3yoi5MsQ8k7X-E,4357 +Bio/ExPASy/__pycache__/Enzyme.cpython-312.pyc,, +Bio/ExPASy/__pycache__/Prodoc.cpython-312.pyc,, +Bio/ExPASy/__pycache__/Prosite.cpython-312.pyc,, +Bio/ExPASy/__pycache__/ScanProsite.cpython-312.pyc,, +Bio/ExPASy/__pycache__/__init__.cpython-312.pyc,, +Bio/ExPASy/__pycache__/cellosaurus.cpython-312.pyc,, +Bio/ExPASy/cellosaurus.py,sha256=Uqy0t9crZIhJDRMPZn7g-rtnDESvubhhjE9mZ1Y0-1U,6670 +Bio/File.py,sha256=fUMuPiu1Ga6lA2t9uUuKNYUjbxhWFue83L55rOmW9aY,24702 +Bio/GenBank/Record.py,sha256=SFyMTwtna69VKJJYtXT_7G6Bjb7vhMvSmq2vR0cd7fk,23278 +Bio/GenBank/Scanner.py,sha256=5QcncBnSs5DaY6zGrUPbyVjRoEJHNr4ZROadxzONj2g,87392 +Bio/GenBank/__init__.py,sha256=P0kTRl-KHM3Jap2lY3fwxdU9WjE2MMqDqeol7s-V_uE,43718 +Bio/GenBank/__pycache__/Record.cpython-312.pyc,, +Bio/GenBank/__pycache__/Scanner.cpython-312.pyc,, +Bio/GenBank/__pycache__/__init__.cpython-312.pyc,, +Bio/GenBank/__pycache__/utils.cpython-312.pyc,, +Bio/GenBank/utils.py,sha256=_c9Po0p-Ay1xqcMmC5yaY2KwokMdZqivB-kME5-SqE4,2229 +Bio/Geo/Record.py,sha256=EX7prbB4ZpXvE8gCu7vg7GDTt8IfTW8CrgjyIpUn650,2972 +Bio/Geo/__init__.py,sha256=gfdjcBv6lQ5sab212l-jCzPuK4KTHeZQJDeV8pAq-sg,2176 +Bio/Geo/__pycache__/Record.cpython-312.pyc,, +Bio/Geo/__pycache__/__init__.cpython-312.pyc,, +Bio/Graphics/BasicChromosome.py,sha256=gvnILx6mhsH_XYbM8D3el5dXJ8UodLLtBSCSTcIyvNs,31526 +Bio/Graphics/ColorSpiral.py,sha256=1RllyUiU0f_WZ1J229NYqFo_aYp2VDaB_qcDacgGVkE,7349 +Bio/Graphics/Comparative.py,sha256=63R_JmAdrcR0p-PL8nNBnNcT_QOM2KGQu--dNv1Yn2o,6632 +Bio/Graphics/DisplayRepresentation.py,sha256=Tjn1fPHS0FOcooQ4M0h0EiAF6V6eePGfUZdm_tZqA7k,6749 +Bio/Graphics/Distribution.py,sha256=Mg4hS50WbYc3CDmXySdYZE_gz02JSvvica9Zn05ZD2g,9301 +Bio/Graphics/GenomeDiagram/_AbstractDrawer.py,sha256=i4FWKAszkBMAdLLWhYKZiHA5NyGF7QBwPEUL1sXl9gE,18539 +Bio/Graphics/GenomeDiagram/_CircularDrawer.py,sha256=h8o1OIpHkBPElCtyBtfwq1urghXFsLJOiqti2p0WhJE,68783 +Bio/Graphics/GenomeDiagram/_Colors.py,sha256=nw6Eswcq6OwVQZ32WkvQAp7ng7n0RhHclBoV1eBYvPU,9678 +Bio/Graphics/GenomeDiagram/_CrossLink.py,sha256=dwUCIZYVTt1dFepzY4qWP86GEPJ5zrIFXGiJEjM_JuA,3309 +Bio/Graphics/GenomeDiagram/_Diagram.py,sha256=30SLEWndoRgs657YERQB6EQnF3FvTjMqrrA2zA3Xf1o,15633 +Bio/Graphics/GenomeDiagram/_Feature.py,sha256=oW6LPMPIrDtwjhMaeYk7mPyjDC-2MeZLx1nXxzTwHMk,8064 +Bio/Graphics/GenomeDiagram/_FeatureSet.py,sha256=I3N2nIo3LWUmHhY2X5kDNeZDFcvKIg-rtSFTAtgBkZ4,7774 +Bio/Graphics/GenomeDiagram/_Graph.py,sha256=LpzVWx9XUgn2A6_77uG-nuGcSWhgUYGUXjxaRyPWO1s,6838 +Bio/Graphics/GenomeDiagram/_GraphSet.py,sha256=evDWezSVo_9MXt2W1fSp9k7QxonRURG5PBgWorLKKlY,5634 +Bio/Graphics/GenomeDiagram/_LinearDrawer.py,sha256=TeSFV9lD7xHqp4y1C305BDK_U3TG1EGZAe9TNl5hSO8,63449 +Bio/Graphics/GenomeDiagram/_Track.py,sha256=qshNMFoxMFHKh2HHLaoqZP7kZ_RXmVcvxhWFppOQUh0,11662 +Bio/Graphics/GenomeDiagram/__init__.py,sha256=KtXssbsNzeG4tYwgwPua5f9ydF0kp2UX_c2K_qypHiU,1172 +Bio/Graphics/GenomeDiagram/__pycache__/_AbstractDrawer.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_CircularDrawer.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_Colors.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_CrossLink.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_Diagram.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_Feature.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_FeatureSet.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_Graph.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_GraphSet.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_LinearDrawer.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/_Track.cpython-312.pyc,, +Bio/Graphics/GenomeDiagram/__pycache__/__init__.cpython-312.pyc,, +Bio/Graphics/KGML_vis.py,sha256=OkI6oIkzQeVsxXk-RyzmIZM5BVij5APKcODE_YKPkeQ,17637 +Bio/Graphics/__init__.py,sha256=43mq7-w22n_AGlQkOqqrr6o--DoETbevHRwgHHDQNLA,3300 +Bio/Graphics/__pycache__/BasicChromosome.cpython-312.pyc,, +Bio/Graphics/__pycache__/ColorSpiral.cpython-312.pyc,, +Bio/Graphics/__pycache__/Comparative.cpython-312.pyc,, +Bio/Graphics/__pycache__/DisplayRepresentation.cpython-312.pyc,, +Bio/Graphics/__pycache__/Distribution.cpython-312.pyc,, +Bio/Graphics/__pycache__/KGML_vis.cpython-312.pyc,, +Bio/Graphics/__pycache__/__init__.cpython-312.pyc,, +Bio/HMM/__init__.py,sha256=okwrOJ6vAlLIJrAUERUWS31R8rN1EUQvcXlUr0T1FQo,283 +Bio/HMM/__pycache__/__init__.cpython-312.pyc,, +Bio/KEGG/Compound/__init__.py,sha256=Ezkr17o6MC_3SrziqWzvjhTgAH3-ZxuRbSNh-fQFrqU,5470 +Bio/KEGG/Compound/__pycache__/__init__.cpython-312.pyc,, +Bio/KEGG/Enzyme/__init__.py,sha256=2vdcLAeM3tnuUH6rH_musgToOm14hScEtrBSy4MA8f8,11185 +Bio/KEGG/Enzyme/__pycache__/__init__.cpython-312.pyc,, +Bio/KEGG/Gene/__init__.py,sha256=bRw6lqK2qgU1-oSoJgmmM_crsG4qfbQFoIuJJorTdno,4288 +Bio/KEGG/Gene/__pycache__/__init__.cpython-312.pyc,, +Bio/KEGG/KGML/KGML_parser.py,sha256=CFuPIqGfoUdzbyyO7AYjq1dOboKuEfxmJPukiClNp5E,6347 +Bio/KEGG/KGML/KGML_pathway.py,sha256=yNohdxjYB3aByjc5ncrfpeCU3jtb5J98SXeEszOU300,27600 +Bio/KEGG/KGML/__init__.py,sha256=ukRQD0nvdi63W3GSkea6JBvESgr-glQK-_0If6CdDro,516 +Bio/KEGG/KGML/__pycache__/KGML_parser.cpython-312.pyc,, +Bio/KEGG/KGML/__pycache__/KGML_pathway.cpython-312.pyc,, +Bio/KEGG/KGML/__pycache__/__init__.cpython-312.pyc,, +Bio/KEGG/Map/__init__.py,sha256=1fC5kUk2y3gBg8U0amU03LBQzk0n5-i9WRAnAizSOM0,1642 +Bio/KEGG/Map/__pycache__/__init__.cpython-312.pyc,, +Bio/KEGG/REST.py,sha256=Var39F7iAs4w6EchIIjteksdnCgNjAxMeUXG6J8d2TE,11302 +Bio/KEGG/__init__.py,sha256=R9b11HHpx7j_5R1Zh3RcqYVn18Ge0fQn5ecdXNP681g,3038 +Bio/KEGG/__pycache__/REST.cpython-312.pyc,, +Bio/KEGG/__pycache__/__init__.cpython-312.pyc,, +Bio/Medline/__init__.py,sha256=v8wuyY_BI2HS_XPrR_wiZdTgQG-kmTUYIKtZamVV058,6272 +Bio/Medline/__pycache__/__init__.cpython-312.pyc,, +Bio/NMR/NOEtools.py,sha256=ivb_vEtACYGL3rmTsUL-gQEwbMuV_vfFV-pcSd-2EdA,3353 +Bio/NMR/__init__.py,sha256=Nh9dRG4raRrtUIZt1NA_7hQ0IylsA8Wt7iPlOfHiZqc,332 +Bio/NMR/__pycache__/NOEtools.cpython-312.pyc,, +Bio/NMR/__pycache__/__init__.cpython-312.pyc,, +Bio/NMR/__pycache__/xpktools.cpython-312.pyc,, +Bio/NMR/xpktools.py,sha256=x0pZrA8aE2Ux9b3WLooMMypy2y1yYMVA8w1K1oOK-SM,9274 +Bio/Nexus/Nexus.py,sha256=bAcaX1GtllyPnYXPRS9XfPInbEX5HevpYROxkncGCWI,83879 +Bio/Nexus/Nodes.py,sha256=_4ISSokpZzxsl8ttvC6TKsufDRKkzqCtvm7R5rp3IFc,5828 +Bio/Nexus/StandardData.py,sha256=Oa3cGxQ7a4tbNHUny9s6f4rY-4R1PjnwIX9az6B-MWA,3996 +Bio/Nexus/Trees.py,sha256=U4AWSE1Quj-xHDyzp2SXFN_0uHKP-tj9ui7HZrh-Los,40311 +Bio/Nexus/__init__.py,sha256=ngZ2q80ta5PB-RTcmHVpf3HMlpIKN3uLBB3f_z2648g,388 +Bio/Nexus/__pycache__/Nexus.cpython-312.pyc,, +Bio/Nexus/__pycache__/Nodes.cpython-312.pyc,, +Bio/Nexus/__pycache__/StandardData.cpython-312.pyc,, +Bio/Nexus/__pycache__/Trees.cpython-312.pyc,, +Bio/Nexus/__pycache__/__init__.cpython-312.pyc,, +Bio/Nexus/cnexus.c,sha256=LWFHaUPHuaH44gx6m2u3oY0tp7KL1HciHhWjxPa5ojY,3741 +Bio/Nexus/cnexus.cpython-312-darwin.so,sha256=nAm_WSg7yWo1Fu_EOuF15vcBaOw8RDKYdOTQlS6KMhg,50880 +Bio/PDB/AbstractPropertyMap.py,sha256=4xW0sC-UUBFfqtcUsMYcA7XmMGfkkKPhvw_U6EDlw6g,4080 +Bio/PDB/Atom.py,sha256=rE26TKAU-fNkjgEtaIhfmJkOksw1Cdrv7T1xi-hgfzs,20424 +Bio/PDB/Chain.py,sha256=l1EZNpHNERvbqnUN2pfYX6f2Ho1Zyz_Y0cQjvvG_wzM,7101 +Bio/PDB/DSSP.py,sha256=V-dZoMQXlgr5XJ4GD7QnU_XI9ZzjjOsx-1C7qDlwUMI,20210 +Bio/PDB/Dice.py,sha256=6i-rMhTr1GCzosccoOnrimApJN28N20lLW8A9t_CKFQ,2315 +Bio/PDB/Entity.py,sha256=SH0PEO3oS0wLkSpyEIvoKDDIZ_NE28CC_gsZfrHdR2I,18506 +Bio/PDB/FragmentMapper.py,sha256=2bM9vuNvbHnjmZcuDIGTYePIneOggsK_2zdh9AfXrzw,9621 +Bio/PDB/HSExposure.py,sha256=uNC36Byn5tW-fMttn7DTqLxtXBpYS2aNIh6q1omTR2c,11337 +Bio/PDB/MMCIF2Dict.py,sha256=C0GGBvX-qQpIQfVLlBXr1zUWd_CmcMVenE7EqvcqPYo,5063 +Bio/PDB/MMCIFParser.py,sha256=0NFbbSDi3jCt3Nl9VAJcMBAdHvciZCXif1iKHjwDe7M,25471 +Bio/PDB/Model.py,sha256=9jlTAdzmpdAm10BGCratNJCnsEklaRcqOGIpkxUdscY,2358 +Bio/PDB/NACCESS.py,sha256=uoevihcnPjdi-KAoncAS2reDQBXrUcNUQPULqOuUCqQ,7219 +Bio/PDB/NeighborSearch.py,sha256=3HKwxAuvcznxflAImQzAeREtNbfKKV7aqXUPHNalOsk,4490 +Bio/PDB/PDBExceptions.py,sha256=Zg5aQWKFIDFHOd5Ynh65auHJXp967PWSIbqaEzL10Iw,934 +Bio/PDB/PDBIO.py,sha256=cb5hVhWLaVGAVXquZosDTJCAXZGzyN1u7hfgoHWYSAo,16445 +Bio/PDB/PDBList.py,sha256=rj315ZxYZXMiqJo12K0r2dItSf0754Ff0-K8-ezcKlc,31347 +Bio/PDB/PDBMLParser.py,sha256=3hOtdAOSXPZf9x21sIr6CmBPK4YXZsqFHBDooRF_mts,6858 +Bio/PDB/PDBParser.py,sha256=u0D-TlIrjyMy0rLpRFyl5lf4eTFnh6VPl5tgM7T5brc,17185 +Bio/PDB/PICIO.py,sha256=T2ULeIhoq9VA3GqnKGKUlWGmGiAhXMlDSRpNa8OZE6Y,41280 +Bio/PDB/PSEA.py,sha256=lnLfeYNItavkJzE8YNwp5M9JrPCbnentURk4yuCw7ZQ,3141 +Bio/PDB/Polypeptide.py,sha256=iD3f4MG6y5h1UfbtMZrwEBpWRQCiGe6FpycaFJCBreA,14220 +Bio/PDB/Residue.py,sha256=586-gp0Psi1wkciYpUW4yZBu8R2WEJNedv59iBfz3Ag,6395 +Bio/PDB/ResidueDepth.py,sha256=5_59-WIdwTnulnVlm33JLIe7sBi8Um97BvtYhViLAu4,22252 +Bio/PDB/SASA.py,sha256=8IPAOSc_4Uhghpwwr_n0hkKkxZMfQ8sLCJ9OxkTJT08,8505 +Bio/PDB/SCADIO.py,sha256=o9hReAxg3xhQlZbDPWIa0npjxCKnDzcV58fKsXenCLs,35847 +Bio/PDB/Selection.py,sha256=EnmaQGGPyIbz4rOnnUlAxeMmuHSOxsZzRIOW020wRgI,2589 +Bio/PDB/Structure.py,sha256=-9aSoKFlx9p7sGw9hAz2P_bGFOX1Q86Acolty8ljvds,2147 +Bio/PDB/StructureAlignment.py,sha256=CLyJT66r-zMyRaAZ4OJb42YmfBjimCW9mwYwzQScWU4,7021 +Bio/PDB/StructureBuilder.py,sha256=zTPwI3_S_a8SMvlXpnDxNmCp01J0hKsNSvrZcsICidA,12137 +Bio/PDB/Superimposer.py,sha256=GDH3mSgA3P6v7RNdiOtwHRrCJpCIdHhKv1eN24T-9tY,1943 +Bio/PDB/__init__.py,sha256=KIynAABv3lQBZRnOje4YlOyUgK6I8QT9xCbUS-2_bLw,3092 +Bio/PDB/__pycache__/AbstractPropertyMap.cpython-312.pyc,, +Bio/PDB/__pycache__/Atom.cpython-312.pyc,, +Bio/PDB/__pycache__/Chain.cpython-312.pyc,, +Bio/PDB/__pycache__/DSSP.cpython-312.pyc,, +Bio/PDB/__pycache__/Dice.cpython-312.pyc,, +Bio/PDB/__pycache__/Entity.cpython-312.pyc,, +Bio/PDB/__pycache__/FragmentMapper.cpython-312.pyc,, +Bio/PDB/__pycache__/HSExposure.cpython-312.pyc,, +Bio/PDB/__pycache__/MMCIF2Dict.cpython-312.pyc,, +Bio/PDB/__pycache__/MMCIFParser.cpython-312.pyc,, +Bio/PDB/__pycache__/Model.cpython-312.pyc,, +Bio/PDB/__pycache__/NACCESS.cpython-312.pyc,, +Bio/PDB/__pycache__/NeighborSearch.cpython-312.pyc,, +Bio/PDB/__pycache__/PDBExceptions.cpython-312.pyc,, +Bio/PDB/__pycache__/PDBIO.cpython-312.pyc,, +Bio/PDB/__pycache__/PDBList.cpython-312.pyc,, +Bio/PDB/__pycache__/PDBMLParser.cpython-312.pyc,, +Bio/PDB/__pycache__/PDBParser.cpython-312.pyc,, +Bio/PDB/__pycache__/PICIO.cpython-312.pyc,, +Bio/PDB/__pycache__/PSEA.cpython-312.pyc,, +Bio/PDB/__pycache__/Polypeptide.cpython-312.pyc,, +Bio/PDB/__pycache__/Residue.cpython-312.pyc,, +Bio/PDB/__pycache__/ResidueDepth.cpython-312.pyc,, +Bio/PDB/__pycache__/SASA.cpython-312.pyc,, +Bio/PDB/__pycache__/SCADIO.cpython-312.pyc,, +Bio/PDB/__pycache__/Selection.cpython-312.pyc,, +Bio/PDB/__pycache__/Structure.cpython-312.pyc,, +Bio/PDB/__pycache__/StructureAlignment.cpython-312.pyc,, +Bio/PDB/__pycache__/StructureBuilder.cpython-312.pyc,, +Bio/PDB/__pycache__/Superimposer.cpython-312.pyc,, +Bio/PDB/__pycache__/__init__.cpython-312.pyc,, +Bio/PDB/__pycache__/alphafold_db.cpython-312.pyc,, +Bio/PDB/__pycache__/binary_cif.cpython-312.pyc,, +Bio/PDB/__pycache__/cealign.cpython-312.pyc,, +Bio/PDB/__pycache__/ic_data.cpython-312.pyc,, +Bio/PDB/__pycache__/ic_rebuild.cpython-312.pyc,, +Bio/PDB/__pycache__/internal_coords.cpython-312.pyc,, +Bio/PDB/__pycache__/mmcifio.cpython-312.pyc,, +Bio/PDB/__pycache__/parse_pdb_header.cpython-312.pyc,, +Bio/PDB/__pycache__/qcprot.cpython-312.pyc,, +Bio/PDB/__pycache__/vectors.cpython-312.pyc,, +Bio/PDB/_bcif_helper.cpython-312-darwin.so,sha256=PrhXEfJIruVwQHe2X1vbgzw99txH3-zVFRJUB5Y4u8E,51424 +Bio/PDB/alphafold_db.py,sha256=Iv0Iy0v3CWpSwLO98uESFmw2lkdYtj5GsLf78gBZ1oo,3991 +Bio/PDB/bcifhelpermodule.c,sha256=CDYshdZg_5X-lZDtkeexoNiH1V2JDacV-qT9kmqVYds,4816 +Bio/PDB/binary_cif.py,sha256=iuGPZvTHZY4P2GlcR_E9_gWl6z49jXcSubNcfrKFxu4,10229 +Bio/PDB/ccealign.cpython-312-darwin.so,sha256=lJXFpAUDHO7Q38malC0EXHdk6xmpa8bvlovQDqTTR6I,52256 +Bio/PDB/ccealignmodule.c,sha256=T1n8HK0IGORAElHC0OUsUzmgLjcjB5g8ZjTrkTD8NOs,26731 +Bio/PDB/cealign.py,sha256=DJsfZ6tcSbY79xKE0m-rVjhOysQqIU_zOFQ1rOvVQV0,7535 +Bio/PDB/ic_data.py,sha256=_yXXal4_LU4DVr61WBLgU2JN6qwcm51p7Akn5pi5aHQ,59270 +Bio/PDB/ic_rebuild.py,sha256=8HvehhUTm36TdaN_KWLbGggBUfG3Yi3K43nhEFklIoo,18341 +Bio/PDB/internal_coords.py,sha256=Yw928UOvsTB6RaK6luknG20KbkgYpfUcBS01GbyrK74,188712 +Bio/PDB/kdtrees.c,sha256=RZP17Wur4pOmhFvArz8G9RmAcSQHZPSK6gZuGoCgPNQ,38489 +Bio/PDB/kdtrees.cpython-312-darwin.so,sha256=dBSfbK0vVYhlN1SELqPJHbXwTKYStmXaqzTo2rsLefE,55056 +Bio/PDB/mmcifio.py,sha256=VLG9DjpF-LMMPnc8z_vpBpXuI7vEqbcPo7D9hlFhEO8,15454 +Bio/PDB/mmtf/DefaultParser.py,sha256=9AFF9xVj0ruenFJy-qFU19R6P4NoNQ7idJa8oMGU26Y,8888 +Bio/PDB/mmtf/__init__.py,sha256=J24rQXRAxb43roQx7RZvitT85abXUKIfOO1BmPPcWTE,1568 +Bio/PDB/mmtf/__pycache__/DefaultParser.cpython-312.pyc,, +Bio/PDB/mmtf/__pycache__/__init__.cpython-312.pyc,, +Bio/PDB/mmtf/__pycache__/mmtfio.cpython-312.pyc,, +Bio/PDB/mmtf/mmtfio.py,sha256=40X-U24c1KtZYDMTaLPWBFjK97ZveV-_9I4Ck5Mqeik,11174 +Bio/PDB/parse_pdb_header.py,sha256=wjUBgHLnqAojAMCftFofJGNTU9gAJerD6i-VWAZwYb0,13618 +Bio/PDB/qcprot.py,sha256=6TiN_JayaSeRfhEAAoXHLpwbZt5pBalIYUj4ctKx_uM,12295 +Bio/PDB/vectors.py,sha256=u57Y4V6Ppkz11kTggWLOB10TqaKqx23h-uKK4GI-LWc,20145 +Bio/Pathway/Rep/Graph.py,sha256=nrtXU1tSCBYSzQLC72-JADXtgn3GaLGE8PGJSBOvbo0,5865 +Bio/Pathway/Rep/MultiGraph.py,sha256=wvjmawcQoAqOYJHJwXgok8OGSM1EDXGweitvuF5PPkU,6779 +Bio/Pathway/Rep/__init__.py,sha256=at4OJza1C4g5QTYe0DWPYHyH_PjXNKRWapNINfVB4ig,575 +Bio/Pathway/Rep/__pycache__/Graph.cpython-312.pyc,, +Bio/Pathway/Rep/__pycache__/MultiGraph.cpython-312.pyc,, +Bio/Pathway/Rep/__pycache__/__init__.cpython-312.pyc,, +Bio/Pathway/__init__.py,sha256=bPdJG_Wxz2ygj4rq2mjom0YVkmADB5ydseudrj45Z3U,10763 +Bio/Pathway/__pycache__/__init__.cpython-312.pyc,, +Bio/Phylo/BaseTree.py,sha256=N69rc175o0NwoxfsWUl0__bJYHKHud2SYYDiT59_o94,44799 +Bio/Phylo/CDAO.py,sha256=zJfBYZBdA4LhMW9JSQ_phD_cgIxXQfWUfKLtdgtTbSY,1662 +Bio/Phylo/CDAOIO.py,sha256=w0DsTBMLm2egoLZ9EhMnqv5yE-SxK5pB97T0Zyj1Z2I,16066 +Bio/Phylo/Consensus.py,sha256=XDwwRs68NC5KsTGl51R2k248sAyoCecrMwmi-pjTMjQ,24305 +Bio/Phylo/NeXML.py,sha256=boHxjwQjFtTi60P7tbqvjiqgJ8YvlJAlrzW7vTZFriE,1404 +Bio/Phylo/NeXMLIO.py,sha256=TClB94T1wsvSqdZ9CNG0AoeijSrkeIb-ZMwXV5cGTjE,10974 +Bio/Phylo/Newick.py,sha256=Z3dOQM0GdqD3Vtlonn5vGLIGxs0fOYogrMOEK4_0bj4,1298 +Bio/Phylo/NewickIO.py,sha256=KUtLtvtxd86t2JfCvUAsvIomA8h8Xx06fSXqVsZ9Jyg,12911 +Bio/Phylo/NexusIO.py,sha256=6W3MIGuRDNixAkqQ-HfB3tiDIkK6m6ng-d5ncYmAC2s,2672 +Bio/Phylo/PAML/__init__.py,sha256=Wlo4XIDffJhmHZm1zpQ3l1PT-STCKQIE0JERLVcBCaY,325 +Bio/Phylo/PAML/__pycache__/__init__.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/_paml.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/_parse_baseml.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/_parse_codeml.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/_parse_yn00.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/baseml.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/chi2.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/codeml.cpython-312.pyc,, +Bio/Phylo/PAML/__pycache__/yn00.cpython-312.pyc,, +Bio/Phylo/PAML/_paml.py,sha256=AxKMp6BmzEiz9cS7N9OhcJNLKUza_4AUE-cpC0GX5QM,5118 +Bio/Phylo/PAML/_parse_baseml.py,sha256=icHahwSmYnWVd8xCpoWxf1oVRIG_7Kq6RC8awXSCiSs,11408 +Bio/Phylo/PAML/_parse_codeml.py,sha256=lDHO5sx7LJFsq_vUlsgBxz2wbK_64fDGOZhhEVzk6XY,21149 +Bio/Phylo/PAML/_parse_yn00.py,sha256=_3X3fMZKAOrGWI2h7nnBU3YS2WhHz3dZncEtPdoXbn8,6820 +Bio/Phylo/PAML/baseml.py,sha256=WOXc-nBPwzrKRT74Y_iak-9n54nBBdjNzXZRqM4W8bo,8719 +Bio/Phylo/PAML/chi2.py,sha256=rOGetcZeZ_GW-YlTy_GKli_4dYEsHH5NQYxJNlFfPws,3743 +Bio/Phylo/PAML/codeml.py,sha256=z7MMMNDCjVJvTjzAMHJ0tdg59584xvdCLyKESRYSr1s,9371 +Bio/Phylo/PAML/yn00.py,sha256=dY_Z7I2DyhYYd4O6OP__cQDZCt6PRekjOGNcUsOao24,6168 +Bio/Phylo/PhyloXML.py,sha256=ckZGwnOgidFcHEIkS-SWIT1Xkeyl5S8i3o7OV6XoUyg,46829 +Bio/Phylo/PhyloXMLIO.py,sha256=hKesIc4S5xNob3cMQgthf8qF8i9RFqAHr-HEqm_Bh0E,32340 +Bio/Phylo/TreeConstruction.py,sha256=iFBHLPWgpzxeTpGv6fI7jgXOoHc_idLPKyfvdn6fFRY,48988 +Bio/Phylo/__init__.py,sha256=I9sH2KCL5_Q2WwbLm-r9Fs20eSdQemAWmQO2Y0-pUOI,683 +Bio/Phylo/__pycache__/BaseTree.cpython-312.pyc,, +Bio/Phylo/__pycache__/CDAO.cpython-312.pyc,, +Bio/Phylo/__pycache__/CDAOIO.cpython-312.pyc,, +Bio/Phylo/__pycache__/Consensus.cpython-312.pyc,, +Bio/Phylo/__pycache__/NeXML.cpython-312.pyc,, +Bio/Phylo/__pycache__/NeXMLIO.cpython-312.pyc,, +Bio/Phylo/__pycache__/Newick.cpython-312.pyc,, +Bio/Phylo/__pycache__/NewickIO.cpython-312.pyc,, +Bio/Phylo/__pycache__/NexusIO.cpython-312.pyc,, +Bio/Phylo/__pycache__/PhyloXML.cpython-312.pyc,, +Bio/Phylo/__pycache__/PhyloXMLIO.cpython-312.pyc,, +Bio/Phylo/__pycache__/TreeConstruction.cpython-312.pyc,, +Bio/Phylo/__pycache__/__init__.cpython-312.pyc,, +Bio/Phylo/__pycache__/_cdao_owl.cpython-312.pyc,, +Bio/Phylo/__pycache__/_io.cpython-312.pyc,, +Bio/Phylo/__pycache__/_utils.cpython-312.pyc,, +Bio/Phylo/_cdao_owl.py,sha256=iC54sav9Hr0GAvnvR6SCGGJtbzFz93t4iJ98i7UVsGs,109367 +Bio/Phylo/_io.py,sha256=gu3_melHtwVGHVe0pcLfBxKkiQW0h2xkcEd2sF2w-YI,2678 +Bio/Phylo/_utils.py,sha256=ydw3YO4xWdTPVWQ0rWiJA9_9Grh6Z3a0-1q6mCFAhew,22303 +Bio/PopGen/GenePop/FileParser.py,sha256=XOuLzb19tYC2l9kfEClh1DFN7WukxRkRAqaJ-gS3sBk,11861 +Bio/PopGen/GenePop/LargeFileParser.py,sha256=IOH8yfg02lB-wUZheXDXPE1L3dAnUAQJ-UWql25oLBg,3919 +Bio/PopGen/GenePop/__init__.py,sha256=_zZsbbWImQpUY4SfTR_UZ9j1M96-iqNMQcI8pnyuT30,7462 +Bio/PopGen/GenePop/__pycache__/FileParser.cpython-312.pyc,, +Bio/PopGen/GenePop/__pycache__/LargeFileParser.cpython-312.pyc,, +Bio/PopGen/GenePop/__pycache__/__init__.cpython-312.pyc,, +Bio/PopGen/__init__.py,sha256=SWc6kj2QqJnhoB6P7AzcfiSj9HIBXt65aHSZLMdLsCU,359 +Bio/PopGen/__pycache__/__init__.cpython-312.pyc,, +Bio/Restriction/PrintFormat.py,sha256=vmHyuQG2r6URF9-N_N8_LURWYdeRm-PKv4EMJRg98i0,16232 +Bio/Restriction/Restriction.py,sha256=JMLrSJR80C0nmzjSyKkt9W3vpG7KOoAaImdKYDrQTSs,83609 +Bio/Restriction/Restriction_Dictionary.py,sha256=KnkJkpXbrWBh6mehHgU3h8WR_LLrEPyMD4nq2QjfoCs,562312 +Bio/Restriction/__init__.py,sha256=PWWjOJk8zs9wFk43IRplNMKtBE0wa40QGpf93SZkvcQ,7846 +Bio/Restriction/__pycache__/PrintFormat.cpython-312.pyc,, +Bio/Restriction/__pycache__/Restriction.cpython-312.pyc,, +Bio/Restriction/__pycache__/Restriction_Dictionary.cpython-312.pyc,, +Bio/Restriction/__pycache__/__init__.cpython-312.pyc,, +Bio/SCOP/Cla.py,sha256=QQaaTRm8MhgkIc9kmWjzSBJzDZ8yPflzqGPahGPOkYE,3922 +Bio/SCOP/Des.py,sha256=E01r8L7xyH4u_pE_BdQWfgLZQzjxxy9yNQlK_wMms8E,3004 +Bio/SCOP/Dom.py,sha256=n2Vz4JCwgp1KYPCdWIHqnz3ox5zVapFKiikAmMtRBHU,2466 +Bio/SCOP/Hie.py,sha256=V89zuR10IszC0g1ElG9kJ4l18AmX7k8IiPuld5TbXPM,2963 +Bio/SCOP/Raf.py,sha256=5alSIWZ8cChAcbLJ-WdiJ78OJq4UOXKWD6pu0QTvEK4,10317 +Bio/SCOP/Residues.py,sha256=B6uF848LZAhqP_arxU6y20Wf5vghMPtX2t_6YRBP88k,3083 +Bio/SCOP/__init__.py,sha256=c3hBShiNDaIyiFMkAyvPHWDVgdLWkKMz3cD8UPaQER0,31276 +Bio/SCOP/__pycache__/Cla.cpython-312.pyc,, +Bio/SCOP/__pycache__/Des.cpython-312.pyc,, +Bio/SCOP/__pycache__/Dom.cpython-312.pyc,, +Bio/SCOP/__pycache__/Hie.cpython-312.pyc,, +Bio/SCOP/__pycache__/Raf.cpython-312.pyc,, +Bio/SCOP/__pycache__/Residues.cpython-312.pyc,, +Bio/SCOP/__pycache__/__init__.cpython-312.pyc,, +Bio/SVDSuperimposer/__init__.py,sha256=tx50Pd3Ze2JlwzJElQLx0tvKadmtyBOa3Fgkll8JQrE,6256 +Bio/SVDSuperimposer/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/BlastIO/__init__.py,sha256=ucZ_p5ltygjjeP4_BNzCyMF-nF-t_yT3qTWde58xKjE,17923 +Bio/SearchIO/BlastIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/BlastIO/__pycache__/blast_tab.cpython-312.pyc,, +Bio/SearchIO/BlastIO/__pycache__/blast_xml.cpython-312.pyc,, +Bio/SearchIO/BlastIO/blast_tab.py,sha256=Xh_B0zTNnFmCukINkyx2ZfuCnOp2oeEnO4kUkJpK91Q,33824 +Bio/SearchIO/BlastIO/blast_xml.py,sha256=236zeNwhlmVIb0c5xrCh2pQS0kgamoGCB72B-iGgu60,37031 +Bio/SearchIO/BlatIO.py,sha256=bKLnyCRGVnIp592mGUhAt2BApPY0uyC6h-coz97kUf8,31398 +Bio/SearchIO/ExonerateIO/__init__.py,sha256=R4mdx-hmQ-GY_RSnZRrF2PiOcJYeaBr4ehvhwUl9V5E,13047 +Bio/SearchIO/ExonerateIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/ExonerateIO/__pycache__/_base.cpython-312.pyc,, +Bio/SearchIO/ExonerateIO/__pycache__/exonerate_cigar.cpython-312.pyc,, +Bio/SearchIO/ExonerateIO/__pycache__/exonerate_text.cpython-312.pyc,, +Bio/SearchIO/ExonerateIO/__pycache__/exonerate_vulgar.cpython-312.pyc,, +Bio/SearchIO/ExonerateIO/_base.py,sha256=j7nW9rqQ3TlGr_ZLJXJIFz7PKjtwkMVNwvKHSSP65Bw,21071 +Bio/SearchIO/ExonerateIO/exonerate_cigar.py,sha256=C7qLNaMMeeWpt7jIDFMTTw2BVLUjNn2O4mTeg1gGCeM,4106 +Bio/SearchIO/ExonerateIO/exonerate_text.py,sha256=2iZbeVHy6iFhJNTa4khDzag7vLql8g__1nOpEmJV1ZE,20463 +Bio/SearchIO/ExonerateIO/exonerate_vulgar.py,sha256=OymbeXbgHFyEgvbB2_E9bwQQbqq7TxAy-sBxONVMFvE,8307 +Bio/SearchIO/FastaIO.py,sha256=9-TItA1-b5cpp1cFmbMZzdZsYtAXwWZrL_U3DFSxLEU,25993 +Bio/SearchIO/HHsuiteIO/__init__.py,sha256=Uwu-QC0n7JZwEEFqbCoXsmAjiColuhLRZlWHJjx0_O0,639 +Bio/SearchIO/HHsuiteIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/HHsuiteIO/__pycache__/hhsuite2_text.cpython-312.pyc,, +Bio/SearchIO/HHsuiteIO/hhsuite2_text.py,sha256=OmDl977VgdlewVKAfr-pcwCm6kNQA9DPFZ6b_3Shap8,9354 +Bio/SearchIO/HmmerIO/__init__.py,sha256=RpjGWuRZOqb_z93d_xEwEAGgrxEB8lQCOSKvYMALIIw,20466 +Bio/SearchIO/HmmerIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/HmmerIO/__pycache__/_base.cpython-312.pyc,, +Bio/SearchIO/HmmerIO/__pycache__/hmmer2_text.cpython-312.pyc,, +Bio/SearchIO/HmmerIO/__pycache__/hmmer3_domtab.cpython-312.pyc,, +Bio/SearchIO/HmmerIO/__pycache__/hmmer3_tab.cpython-312.pyc,, +Bio/SearchIO/HmmerIO/__pycache__/hmmer3_text.cpython-312.pyc,, +Bio/SearchIO/HmmerIO/_base.py,sha256=qSiP2JbGjWPOXuWsvN2F7gSPOZTbyAzHj5CvRFtmWoo,1482 +Bio/SearchIO/HmmerIO/hmmer2_text.py,sha256=A5_YMdp-ugLORE4AY5kk8MCmFDBjxXoaO15OJeENBbc,12932 +Bio/SearchIO/HmmerIO/hmmer3_domtab.py,sha256=magDmjA-r3S2_dfWq93TBP2aFQ9ezZQCJdSVaN_4vIY,14071 +Bio/SearchIO/HmmerIO/hmmer3_tab.py,sha256=ElBtEi4dtO56Ne_BnahnLxzHJl8p9091MChy3XX09U4,12910 +Bio/SearchIO/HmmerIO/hmmer3_text.py,sha256=M7VcbL42350ZwwL2kX5noxUousAIIgbOLCU_eTKb1qY,20043 +Bio/SearchIO/InfernalIO/__init__.py,sha256=xF4wQKNLbfTMiKFL6NmU-sgSphriy_0aXlN9ngzPoyY,15555 +Bio/SearchIO/InfernalIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/InfernalIO/__pycache__/_base.cpython-312.pyc,, +Bio/SearchIO/InfernalIO/__pycache__/infernal_tab.cpython-312.pyc,, +Bio/SearchIO/InfernalIO/__pycache__/infernal_text.cpython-312.pyc,, +Bio/SearchIO/InfernalIO/_base.py,sha256=w_itxTD5azRfaA3PCZ13UYRq6t4TEg2BzA-WjnST5Fc,1415 +Bio/SearchIO/InfernalIO/infernal_tab.py,sha256=tlJZ7DQ672DfHlL7AJI3E9qiJG61T8dhsOU5ngeaJ0o,14947 +Bio/SearchIO/InfernalIO/infernal_text.py,sha256=jchZqcR-pep7NzWycllszemlQX0sr1UcKeFQSFYeCCY,21628 +Bio/SearchIO/InterproscanIO/__init__.py,sha256=bnQbZAEmthvBubnQn6tu0nCovgYmCS1eVdxs7cC83Kw,5155 +Bio/SearchIO/InterproscanIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/InterproscanIO/__pycache__/interproscan_xml.cpython-312.pyc,, +Bio/SearchIO/InterproscanIO/interproscan_xml.py,sha256=sDeP_ssPvhifYzZ2sta4ils2DzqB4WunEUQw9D2Shuk,7547 +Bio/SearchIO/__init__.py,sha256=rvNn0BsWNe_PrQ_fhnvwCVBupcWDi_tcYf8uQDOsohg,29177 +Bio/SearchIO/__pycache__/BlatIO.cpython-312.pyc,, +Bio/SearchIO/__pycache__/FastaIO.cpython-312.pyc,, +Bio/SearchIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/__pycache__/_index.cpython-312.pyc,, +Bio/SearchIO/__pycache__/_utils.cpython-312.pyc,, +Bio/SearchIO/_index.py,sha256=KGWJfTcPTWPyv7HxVjebifl_jsFqIKxJNUdz327rLgw,1233 +Bio/SearchIO/_model/__init__.py,sha256=sE-9oUiX0HdKUC_Z0njFA7giJrlDUUAfczNvnDfJh3s,2479 +Bio/SearchIO/_model/__pycache__/__init__.cpython-312.pyc,, +Bio/SearchIO/_model/__pycache__/_base.cpython-312.pyc,, +Bio/SearchIO/_model/__pycache__/hit.cpython-312.pyc,, +Bio/SearchIO/_model/__pycache__/hsp.cpython-312.pyc,, +Bio/SearchIO/_model/__pycache__/query.cpython-312.pyc,, +Bio/SearchIO/_model/_base.py,sha256=NEVzhcvyY79M-ByUjdz9WmDtRu1xMMC8Pf_a1na1aHo,2671 +Bio/SearchIO/_model/hit.py,sha256=gXAkhuGNv7eSrlTA18nf7eqaGdCCmBxkc3Dc4fyTGIs,17396 +Bio/SearchIO/_model/hsp.py,sha256=XDuwCr30WxKv1nbUt1Ii6Ywlj-c7-s7ql3j8ZFqW0CU,48308 +Bio/SearchIO/_model/query.py,sha256=xKg8NCsJ1Q37KKXAfjMdV_479ocNz_FyB4Op5H_txeM,30199 +Bio/SearchIO/_utils.py,sha256=Od-zvdwFUZzhjVHNX0pmayza0bZZs93hfOLaMCnBYUM,5596 +Bio/Seq.py,sha256=rSosheRMdEVtyd1vRXy9TnsPCyxNwPa8KKcahny-FWs,114972 +Bio/SeqFeature.py,sha256=o8vTou8W9C6CBBCwuEM5ZCmNOuKMATecYNQ1cBws334,80760 +Bio/SeqIO/AbiIO.py,sha256=V_Xo_WI9uOTAVAl_zQtXaItb-uHE1VjXfzdiZK8PUyk,26249 +Bio/SeqIO/AceIO.py,sha256=jCS6DUiK-p0GbXMT697yy26IVbCn5s23ioLdqmtpfaE,4769 +Bio/SeqIO/FastaIO.py,sha256=g-aGuutrm-r34JwqI_j5TY_ORSRn99UAcdA4EBsE-nU,22100 +Bio/SeqIO/GckIO.py,sha256=-QoNJdwRbGbyB1IOiSB5kslShMg91BRdBhMlB5nNWzw,8994 +Bio/SeqIO/GfaIO.py,sha256=VSxljdd4Roa3n1pOkwkleA2WWy9cEUa514aTKJTehfM,7091 +Bio/SeqIO/IgIO.py,sha256=tkSa-vuU81cyjxX4FMU2n-Q_8St6evLQQTb0iqdwKf8,4068 +Bio/SeqIO/InsdcIO.py,sha256=1RQD7Mucudr3wyh5Xesgb5zK5D9ciaAl7g2XZ7A8T80,58571 +Bio/SeqIO/Interfaces.py,sha256=7IQvUADcSKI77Mha-MAMzJFc7g-cErjK11mMvL673sk,8325 +Bio/SeqIO/NibIO.py,sha256=Ocrhdhjgaqzje4mvNblzOjZGyd4jFx8WXTqLJ6hp0HM,5857 +Bio/SeqIO/PdbIO.py,sha256=hJDdg5z4ScgyRrV-NzP9ycK6qQPMaeCVRROgdRntido,22748 +Bio/SeqIO/PhdIO.py,sha256=7ifjaPVED1o3MKv432rvGG42LiIEvlRzADvhOhexYMg,6330 +Bio/SeqIO/PirIO.py,sha256=Iu6PhBKNs8aOCFdcwfN3XJL-BCZs7jft69WZQfvWYV0,10021 +Bio/SeqIO/QualityIO.py,sha256=Uxb7_DI_kVmYzVMSES5pOkUxrRC_JOlaggd435rvv8U,95985 +Bio/SeqIO/SeqXmlIO.py,sha256=OTO_RnjmwihhNlEkzxmMFSFfjO6WRENtOD4gbq6377M,30529 +Bio/SeqIO/SffIO.py,sha256=hhKYmSxTzR0YW4JETeipZHX-YE8VLIYhcDRMFg7Wdao,55380 +Bio/SeqIO/SnapGeneIO.py,sha256=G5WNqTsF3qw9qCATgPiFLoH9UtITo86hyh3tsNgVKg0,12385 +Bio/SeqIO/SwissIO.py,sha256=qRTDePuE-EQGRkraWtpegtmTK6Yur2L6Sd0eaEnvVdI,5251 +Bio/SeqIO/TabIO.py,sha256=6mbOO5fpUk8iY7X4q0wqozXvwUAR4ra7wH2HCyjGO8I,5125 +Bio/SeqIO/TwoBitIO.py,sha256=PDXnfMeDfVi6ez2YiNmZn5LG2BsISu1V4lj_3piOn_A,11165 +Bio/SeqIO/UniprotIO.py,sha256=SaBS6NUanEyySnGkiXQARtmsRQ2NONwBAslpi7j69iA,24645 +Bio/SeqIO/XdnaIO.py,sha256=ixODv7NjTXyPr7Pj05eMkLFEhPxCArRJKo3Xk31uBhE,12342 +Bio/SeqIO/__init__.py,sha256=orRUs-vmBmrysNZTQjslwDyELAgb7082Q9NPClcLsR8,45723 +Bio/SeqIO/__pycache__/AbiIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/AceIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/FastaIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/GckIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/GfaIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/IgIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/InsdcIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/Interfaces.cpython-312.pyc,, +Bio/SeqIO/__pycache__/NibIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/PdbIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/PhdIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/PirIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/QualityIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/SeqXmlIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/SffIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/SnapGeneIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/SwissIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/TabIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/TwoBitIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/UniprotIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/XdnaIO.cpython-312.pyc,, +Bio/SeqIO/__pycache__/__init__.cpython-312.pyc,, +Bio/SeqIO/__pycache__/_index.cpython-312.pyc,, +Bio/SeqIO/_index.py,sha256=wkH3rAsSV68s481L68TAQ2YWkZW-qDKOeZOuNXGXqdE,27642 +Bio/SeqIO/_twoBitIO.c,sha256=vgig9JSepUZMZCLr9TM55Zil_mtKqdKiDPHvN_Efn7Y,22033 +Bio/SeqIO/_twoBitIO.cpython-312-darwin.so,sha256=eafrc5Ajj_aGhv1MF2YqY2bWj8EHJ8RNy1HxvHTAQqc,51680 +Bio/SeqRecord.py,sha256=eLyYfA2ERI9WreLwxNAO3nsgoB3pJDoTtdz-1eEQYfI,61621 +Bio/SeqUtils/CheckSum.py,sha256=unmsn9dSkJqmuHjuSMnJydlbyMlWotm6CsHxMbFIOpk,3510 +Bio/SeqUtils/IsoelectricPoint.py,sha256=k6DTKbpjee3QfFP16o7LOcloTZIYqz_LRzbhMk4srtI,6557 +Bio/SeqUtils/MeltingTemp.py,sha256=Tzy8WF_9aNVDhtQPXtsROnwurkqkOIxrSWvO7N7AZQA,43151 +Bio/SeqUtils/ProtParam.py,sha256=0KU-ykP3-nkfptAApXwmMKdpQwTCmhz1vjlzYATyAE8,13174 +Bio/SeqUtils/ProtParamData.py,sha256=SIpMM2VWxeaqQekgjNSpOQ16KdPYPiyL4fDLUYxxiUc,18172 +Bio/SeqUtils/__init__.py,sha256=vW42dv28AciOGTE_G6v2XJZpcBlGDx5z4dE2OS3PfWo,25604 +Bio/SeqUtils/__pycache__/CheckSum.cpython-312.pyc,, +Bio/SeqUtils/__pycache__/IsoelectricPoint.cpython-312.pyc,, +Bio/SeqUtils/__pycache__/MeltingTemp.cpython-312.pyc,, +Bio/SeqUtils/__pycache__/ProtParam.cpython-312.pyc,, +Bio/SeqUtils/__pycache__/ProtParamData.cpython-312.pyc,, +Bio/SeqUtils/__pycache__/__init__.cpython-312.pyc,, +Bio/SeqUtils/__pycache__/lcc.cpython-312.pyc,, +Bio/SeqUtils/lcc.py,sha256=XBY4ZRGoRiUEqmz55dhnLpPLi9ebKhIUa7VEJhHtMd8,5502 +Bio/Sequencing/Ace.py,sha256=_Su6gu-odBELWvCtZmz3y6CnXBMJEji1q1h1CHSnpYg,20432 +Bio/Sequencing/Phd.py,sha256=qMigC5HmXLowegKMXobMa6QppCKAPjvDcsqflle9URg,5684 +Bio/Sequencing/__init__.py,sha256=r9llSVj9cqJveTCKxDHw-pDPdvL4KBYil12zby9QpMg,530 +Bio/Sequencing/__pycache__/Ace.cpython-312.pyc,, +Bio/Sequencing/__pycache__/Phd.cpython-312.pyc,, +Bio/Sequencing/__pycache__/__init__.cpython-312.pyc,, +Bio/SwissProt/KeyWList.py,sha256=DiMiwlFCWMPtyvoly2fkkmgTPG75tJUXQ1S6EPGnUA0,3468 +Bio/SwissProt/__init__.py,sha256=5nmAYalbLowU1VFcN_UAtyH4PkYQ_7vCHnTG0Fbw0zw,32910 +Bio/SwissProt/__pycache__/KeyWList.cpython-312.pyc,, +Bio/SwissProt/__pycache__/__init__.cpython-312.pyc,, +Bio/TogoWS/__init__.py,sha256=Vsw0IMrIQ52k-Gu4WH6Yd-i_-D1RgqhPhqa7_gwJTL8,13966 +Bio/TogoWS/__pycache__/__init__.cpython-312.pyc,, +Bio/UniGene/__init__.py,sha256=EjnkeKTzkJhq2ghSOeMC3E_eZ4U89LFGCS1n6-s9otw,12738 +Bio/UniGene/__pycache__/__init__.cpython-312.pyc,, +Bio/UniProt/GOA.py,sha256=nXzgZAiC1P4HsuLfM7z0ca4h5cH8auBNISEB9-hve6w,15791 +Bio/UniProt/__init__.py,sha256=eQwo82zOz4o9hqJMSle0K9brewdx5a_NcHp3fRXDsA8,5376 +Bio/UniProt/__pycache__/GOA.cpython-312.pyc,, +Bio/UniProt/__pycache__/__init__.cpython-312.pyc,, +Bio/__init__.py,sha256=WQPbWoi90aKnzAgfzTFcra9pO0jG8JPpDukzxllOn3o,5411 +Bio/__pycache__/File.cpython-312.pyc,, +Bio/__pycache__/Seq.cpython-312.pyc,, +Bio/__pycache__/SeqFeature.cpython-312.pyc,, +Bio/__pycache__/SeqRecord.cpython-312.pyc,, +Bio/__pycache__/__init__.cpython-312.pyc,, +Bio/__pycache__/_utils.cpython-312.pyc,, +Bio/__pycache__/bgzf.cpython-312.pyc,, +Bio/__pycache__/pairwise2.cpython-312.pyc,, +Bio/_utils.py,sha256=_WcE3XdMiyta5aTDdZVRnFTdou8D0REGZkhLlOMCgqs,2918 +Bio/bgzf.py,sha256=Eun1RXey_n9mSttJrH15wIEZrFRaOyjREP5Rasc2KIo,39777 +Bio/codonalign/__init__.py,sha256=umcOampgYmjCJAIl5qzKktYZbKKMDaMp5OXlFvD-_j0,30114 +Bio/codonalign/__pycache__/__init__.cpython-312.pyc,, +Bio/codonalign/__pycache__/codonalignment.cpython-312.pyc,, +Bio/codonalign/__pycache__/codonseq.cpython-312.pyc,, +Bio/codonalign/codonalignment.py,sha256=EZGYrxbqWHbH7lUsoGXYK0ziAwH3Iginpb7sHajH_Ws,18231 +Bio/codonalign/codonseq.py,sha256=FwHAAfwhK_VvQs-uyhK15phwPG92_0WiVnFXcwOsWrA,47934 +Bio/cpairwise2.cpython-312-darwin.so,sha256=2YBuX1Y_xzlCxaQlPl4MOlturMuuxAJRdmv4Itl52Ow,52304 +Bio/cpairwise2module.c,sha256=rCEMYaN3LJnust0hpjlojfGh_YAXM6fi6hXaMAudayU,16868 +Bio/motifs/__init__.py,sha256=I7OyH7iRI3-UovgMYufgBbhP1FolNHS1-08KqvYYjIU,22158 +Bio/motifs/__pycache__/__init__.cpython-312.pyc,, +Bio/motifs/__pycache__/alignace.cpython-312.pyc,, +Bio/motifs/__pycache__/clusterbuster.cpython-312.pyc,, +Bio/motifs/__pycache__/mast.cpython-312.pyc,, +Bio/motifs/__pycache__/matrix.cpython-312.pyc,, +Bio/motifs/__pycache__/meme.cpython-312.pyc,, +Bio/motifs/__pycache__/minimal.cpython-312.pyc,, +Bio/motifs/__pycache__/pfm.cpython-312.pyc,, +Bio/motifs/__pycache__/thresholds.cpython-312.pyc,, +Bio/motifs/__pycache__/transfac.cpython-312.pyc,, +Bio/motifs/__pycache__/xms.cpython-312.pyc,, +Bio/motifs/_pwm.c,sha256=1vOzUu0th-NZdHXc50b4IhZyRM0hQH4itjMvIBTnx4g,5793 +Bio/motifs/_pwm.cpython-312-darwin.so,sha256=zldhaoVwzNuB9eHgv4Hu5vpYWykYGstQ4MYNdj5nLWA,51384 +Bio/motifs/alignace.py,sha256=-Fqz1ka9VKwPpB8PPZTuMm5GGu29UQhHqR52IFBrBb4,2118 +Bio/motifs/clusterbuster.py,sha256=VXUM9fCXJv2HIdkhSInlKuSaxWn3wpAfd_Yt1q_p8EI,3852 +Bio/motifs/jaspar/__init__.py,sha256=BM-AozLo_6eKvpwnfjpSIGoMQx-dX6BogdNCYIJX53Y,11388 +Bio/motifs/jaspar/__pycache__/__init__.cpython-312.pyc,, +Bio/motifs/jaspar/__pycache__/db.cpython-312.pyc,, +Bio/motifs/jaspar/db.py,sha256=Nl1fmXPhRWxdo-5EhP-5NhrSCO8KC69IEq-FnQh_pw0,27980 +Bio/motifs/mast.py,sha256=WKoDkBRSJ9IvpmolXrS3otOBPDYDR1lFt7uJHrzUSoo,4915 +Bio/motifs/matrix.py,sha256=sVzzwoIEREiuWwpcPsSoeJzg1DliBgq5OuoiRS7WJh4,24049 +Bio/motifs/meme.py,sha256=_wQt896H1uky4K2Tc2bO-PVsvSoZh6ntss1eeW7qMp8,6397 +Bio/motifs/minimal.py,sha256=SK1OHuxU3RdubK82hzUH-cBOGIYYAfoMq9kmkKw9HjM,7161 +Bio/motifs/pfm.py,sha256=4KvB9j7fnGQKBQs-_SCGYqG5qnlCmQcREe9gEkvG9vo,17229 +Bio/motifs/thresholds.py,sha256=o0K4bKPNYpVsribsDmOhIsV10lY31NNL1_HbT3sRwM4,4530 +Bio/motifs/transfac.py,sha256=fDi-ExuWX5_74iIo9Id7lT-8jPB_iMN9OLbDJHla_zw,12127 +Bio/motifs/xms.py,sha256=NNRXpG5JZC5Twy5CHB4GjpYhWjiJTLlVabRRUxJ32Hc,3942 +Bio/pairwise2.py,sha256=6TqFmPrI58IMlevMDgLowi1bEshJfKERp-wVvnt4sWQ,53156 +Bio/phenotype/__init__.py,sha256=ygNXhDYIMSb8C3woqkvCOOyefr98MUssE6KqRokIL8Q,8353 +Bio/phenotype/__pycache__/__init__.cpython-312.pyc,, +Bio/phenotype/__pycache__/phen_micro.cpython-312.pyc,, +Bio/phenotype/__pycache__/pm_fitting.cpython-312.pyc,, +Bio/phenotype/phen_micro.py,sha256=Bep81ibmizySAfbLVcyffqGeqWvRt8Te-2v4WDeqF0w,37710 +Bio/phenotype/pm_fitting.py,sha256=W6zMBSSDPYdGrLRH6p9sL38z7HGNArEVBj7Xt7_KCEw,4208 +Bio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +BioSQL/BioSeq.py,sha256=IodmnonVHMfl3BRXgYMo3DQq08IbRKW81eYEjgVDTjE,21795 +BioSQL/BioSeqDatabase.py,sha256=F3L8O1Csm8HWhNdDoAWykVXdjUJRN5JbuCLV1_uoJ7M,31312 +BioSQL/DBUtils.py,sha256=D8a89mQyIpo54_Nc2ZG376rhqLrFFdvtquoXX9MSFiU,4657 +BioSQL/Loader.py,sha256=VXvVd9CM7im8_b89uFlF44YC4R0ACVeHKUOYrFKbpN4,51599 +BioSQL/__init__.py,sha256=D4hw16z-KuugA_YcEa83q2zz2CNLDopcRHrPvFeSVKM,617 +BioSQL/__pycache__/BioSeq.cpython-312.pyc,, +BioSQL/__pycache__/BioSeqDatabase.cpython-312.pyc,, +BioSQL/__pycache__/DBUtils.cpython-312.pyc,, +BioSQL/__pycache__/Loader.cpython-312.pyc,, +BioSQL/__pycache__/__init__.cpython-312.pyc,, +BioSQL/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +biopython-1.87.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +biopython-1.87.dist-info/METADATA,sha256=fzwcehh1yVgVs5euzF5bkLETW6DHsctEeonCOGYsjxA,13290 +biopython-1.87.dist-info/RECORD,, +biopython-1.87.dist-info/WHEEL,sha256=cMbdUR4MuJwKTk_cclTNco-OW6sDrQbwZ6MlSMtlrI4,136 +biopython-1.87.dist-info/licenses/LICENSE.rst,sha256=EdHryq0uufDwmj3x3rSsqZpNo2aumucPgox0R6JN5FM,3267 +biopython-1.87.dist-info/top_level.txt,sha256=jN-JQ-4c2AzNqKFp3H5s0o2dIfGhg0SAVilkXmnLl_M,11 diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..97b96f8a4ace0c35478ca986b129de36d8ab6e07 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp312-cp312-macosx_11_0_arm64 +Generator: delocate 0.13.0 + diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/licenses/._LICENSE.rst b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/licenses/._LICENSE.rst new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/licenses/._LICENSE.rst differ diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/licenses/LICENSE.rst b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/licenses/LICENSE.rst new file mode 100644 index 0000000000000000000000000000000000000000..eb5e305afbc43dc771e9e9935479af4aa9515674 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/licenses/LICENSE.rst @@ -0,0 +1,68 @@ +Biopython is currently released under the "Biopython License Agreement" +(given in full below). Unless stated otherwise in individual file headers, +all Biopython's files are under the "Biopython License Agreement". + +Some files are explicitly dual licensed under your choice of the +"Biopython License Agreement" or the "BSD 3-Clause License" (both given +in full below). This is with the intention of later offering all of +Biopython under this dual licensing approach. + + +------------------------------------------------------------------------------ + + +Biopython License Agreement +--------------------------- + +Permission to use, copy, modify, and distribute this software and its +documentation with or without modifications and for any purpose and +without fee is hereby granted, provided that any copyright notices +appear in all copies and that both those copyright notices and this +permission notice appear in supporting documentation, and that the +names of the contributors or copyright holders not be used in +advertising or publicity pertaining to distribution of the software +without specific prior permission. + +THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT +OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +OR PERFORMANCE OF THIS SOFTWARE. + + +------------------------------------------------------------------------------ + + +BSD 3-Clause License +-------------------- + +Copyright (c) 1999-2025, The Biopython Contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/top_level.txt b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a526a961b7280638c3f579e683378883efaa598c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/biopython-1.87.dist-info/top_level.txt @@ -0,0 +1,2 @@ +Bio +BioSQL diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/dateutil/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/.__common.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/.__common.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/.__common.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/.__version.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/.__version.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/.__version.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._easter.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/._easter.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._easter.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._parser b/.venv_haddock/lib/python3.12/site-packages/dateutil/._parser new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._parser differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._relativedelta.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/._relativedelta.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._relativedelta.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._rrule.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/._rrule.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._rrule.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._tz b/.venv_haddock/lib/python3.12/site-packages/dateutil/._tz new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._tz differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._tzwin.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/._tzwin.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._tzwin.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._utils.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/._utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._utils.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/._zoneinfo b/.venv_haddock/lib/python3.12/site-packages/dateutil/._zoneinfo new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/._zoneinfo differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/__init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c19c06fe14476a9bfa4f1f60de7a997a41191c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +import sys + +try: + from ._version import version as __version__ +except ImportError: + __version__ = 'unknown' + +__all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz', + 'utils', 'zoneinfo'] + +def __getattr__(name): + import importlib + + if name in __all__: + return importlib.import_module("." + name, __name__) + raise AttributeError( + "module {!r} has not attribute {!r}".format(__name__, name) + ) + + +def __dir__(): + # __dir__ should include all the lazy-importable modules as well. + return [x for x in globals() if x not in sys.modules] + __all__ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/_common.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb2659bd2986125fcfb4afea5bae9efc2dcd1a0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/_common.py @@ -0,0 +1,43 @@ +""" +Common code used in multiple modules. +""" + + +class weekday(object): + __slots__ = ["weekday", "n"] + + def __init__(self, weekday, n=None): + self.weekday = weekday + self.n = n + + def __call__(self, n): + if n == self.n: + return self + else: + return self.__class__(self.weekday, n) + + def __eq__(self, other): + try: + if self.weekday != other.weekday or self.n != other.n: + return False + except AttributeError: + return False + return True + + def __hash__(self): + return hash(( + self.weekday, + self.n, + )) + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] + if not self.n: + return s + else: + return "%s(%+d)" % (s, self.n) + +# vim:ts=4:sw=4:et diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/_version.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ddda98098527a73348e694c2edb691fd625475fc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/_version.py @@ -0,0 +1,4 @@ +# file generated by setuptools_scm +# don't change, don't track in version control +__version__ = version = '2.9.0.post0' +__version_tuple__ = version_tuple = (2, 9, 0) diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/easter.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/easter.py new file mode 100644 index 0000000000000000000000000000000000000000..f74d1f7442473997245ac683b8a269a3574d1ba4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/easter.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +""" +This module offers a generic Easter computing method for any given year, using +Western, Orthodox or Julian algorithms. +""" + +import datetime + +__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] + +EASTER_JULIAN = 1 +EASTER_ORTHODOX = 2 +EASTER_WESTERN = 3 + + +def easter(year, method=EASTER_WESTERN): + """ + This method was ported from the work done by GM Arts, + on top of the algorithm by Claus Tondering, which was + based in part on the algorithm of Ouding (1940), as + quoted in "Explanatory Supplement to the Astronomical + Almanac", P. Kenneth Seidelmann, editor. + + This algorithm implements three different Easter + calculation methods: + + 1. Original calculation in Julian calendar, valid in + dates after 326 AD + 2. Original method, with date converted to Gregorian + calendar, valid in years 1583 to 4099 + 3. Revised method, in Gregorian calendar, valid in + years 1583 to 4099 as well + + These methods are represented by the constants: + + * ``EASTER_JULIAN = 1`` + * ``EASTER_ORTHODOX = 2`` + * ``EASTER_WESTERN = 3`` + + The default method is method 3. + + More about the algorithm may be found at: + + `GM Arts: Easter Algorithms `_ + + and + + `The Calendar FAQ: Easter `_ + + """ + + if not (1 <= method <= 3): + raise ValueError("invalid method") + + # g - Golden year - 1 + # c - Century + # h - (23 - Epact) mod 30 + # i - Number of days from March 21 to Paschal Full Moon + # j - Weekday for PFM (0=Sunday, etc) + # p - Number of days from March 21 to Sunday on or before PFM + # (-6 to 28 methods 1 & 3, to 56 for method 2) + # e - Extra days to add for method 2 (converting Julian + # date to Gregorian date) + + y = year + g = y % 19 + e = 0 + if method < 3: + # Old method + i = (19*g + 15) % 30 + j = (y + y//4 + i) % 7 + if method == 2: + # Extra dates to convert Julian to Gregorian date + e = 10 + if y > 1600: + e = e + y//100 - 16 - (y//100 - 16)//4 + else: + # New method + c = y//100 + h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 + i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) + j = (y + y//4 + i + 2 - c + c//4) % 7 + + # p can be from -6 to 56 corresponding to dates 22 March to 23 May + # (later dates apply to method 2, although 23 May never actually occurs) + p = i - j + e + d = 1 + (p + 27 + (p + 6)//40) % 31 + m = 3 + (p + 26)//30 + return datetime.date(int(y), int(m), int(d)) diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.__parser.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.__parser.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/.__parser.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/._isoparser.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/._isoparser.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/._isoparser.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/__init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d174b0e4dcc472999b75e55ebb88af320ae38081 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/__init__.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +from ._parser import parse, parser, parserinfo, ParserError +from ._parser import DEFAULTPARSER, DEFAULTTZPARSER +from ._parser import UnknownTimezoneWarning + +from ._parser import __doc__ + +from .isoparser import isoparser, isoparse + +__all__ = ['parse', 'parser', 'parserinfo', + 'isoparse', 'isoparser', + 'ParserError', + 'UnknownTimezoneWarning'] + + +### +# Deprecate portions of the private interface so that downstream code that +# is improperly relying on it is given *some* notice. + + +def __deprecated_private_func(f): + from functools import wraps + import warnings + + msg = ('{name} is a private function and may break without warning, ' + 'it will be moved and or renamed in future versions.') + msg = msg.format(name=f.__name__) + + @wraps(f) + def deprecated_func(*args, **kwargs): + warnings.warn(msg, DeprecationWarning) + return f(*args, **kwargs) + + return deprecated_func + +def __deprecate_private_class(c): + import warnings + + msg = ('{name} is a private class and may break without warning, ' + 'it will be moved and or renamed in future versions.') + msg = msg.format(name=c.__name__) + + class private_class(c): + __doc__ = c.__doc__ + + def __init__(self, *args, **kwargs): + warnings.warn(msg, DeprecationWarning) + super(private_class, self).__init__(*args, **kwargs) + + private_class.__name__ = c.__name__ + + return private_class + + +from ._parser import _timelex, _resultbase +from ._parser import _tzparser, _parsetz + +_timelex = __deprecate_private_class(_timelex) +_tzparser = __deprecate_private_class(_tzparser) +_resultbase = __deprecate_private_class(_resultbase) +_parsetz = __deprecated_private_func(_parsetz) diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/_parser.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..37d1663b2f72447800d9a553929e3de932244289 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/_parser.py @@ -0,0 +1,1613 @@ +# -*- coding: utf-8 -*- +""" +This module offers a generic date/time string parser which is able to parse +most known formats to represent a date and/or time. + +This module attempts to be forgiving with regards to unlikely input formats, +returning a datetime object even for dates which are ambiguous. If an element +of a date/time stamp is omitted, the following rules are applied: + +- If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour + on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is + specified. +- If a time zone is omitted, a timezone-naive datetime is returned. + +If any other elements are missing, they are taken from the +:class:`datetime.datetime` object passed to the parameter ``default``. If this +results in a day number exceeding the valid number of days per month, the +value falls back to the end of the month. + +Additional resources about date/time string formats can be found below: + +- `A summary of the international standard date and time notation + `_ +- `W3C Date and Time Formats `_ +- `Time Formats (Planetary Rings Node) `_ +- `CPAN ParseDate module + `_ +- `Java SimpleDateFormat Class + `_ +""" +from __future__ import unicode_literals + +import datetime +import re +import string +import time +import warnings + +from calendar import monthrange +from io import StringIO + +import six +from six import integer_types, text_type + +from decimal import Decimal + +from warnings import warn + +from .. import relativedelta +from .. import tz + +__all__ = ["parse", "parserinfo", "ParserError"] + + +# TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth +# making public and/or figuring out if there is something we can +# take off their plate. +class _timelex(object): + # Fractional seconds are sometimes split by a comma + _split_decimal = re.compile("([.,])") + + def __init__(self, instream): + if isinstance(instream, (bytes, bytearray)): + instream = instream.decode() + + if isinstance(instream, text_type): + instream = StringIO(instream) + elif getattr(instream, 'read', None) is None: + raise TypeError('Parser must be a string or character stream, not ' + '{itype}'.format(itype=instream.__class__.__name__)) + + self.instream = instream + self.charstack = [] + self.tokenstack = [] + self.eof = False + + def get_token(self): + """ + This function breaks the time string into lexical units (tokens), which + can be parsed by the parser. Lexical units are demarcated by changes in + the character set, so any continuous string of letters is considered + one unit, any continuous string of numbers is considered one unit. + + The main complication arises from the fact that dots ('.') can be used + both as separators (e.g. "Sep.20.2009") or decimal points (e.g. + "4:30:21.447"). As such, it is necessary to read the full context of + any dot-separated strings before breaking it into tokens; as such, this + function maintains a "token stack", for when the ambiguous context + demands that multiple tokens be parsed at once. + """ + if self.tokenstack: + return self.tokenstack.pop(0) + + seenletters = False + token = None + state = None + + while not self.eof: + # We only realize that we've reached the end of a token when we + # find a character that's not part of the current token - since + # that character may be part of the next token, it's stored in the + # charstack. + if self.charstack: + nextchar = self.charstack.pop(0) + else: + nextchar = self.instream.read(1) + while nextchar == '\x00': + nextchar = self.instream.read(1) + + if not nextchar: + self.eof = True + break + elif not state: + # First character of the token - determines if we're starting + # to parse a word, a number or something else. + token = nextchar + if self.isword(nextchar): + state = 'a' + elif self.isnum(nextchar): + state = '0' + elif self.isspace(nextchar): + token = ' ' + break # emit token + else: + break # emit token + elif state == 'a': + # If we've already started reading a word, we keep reading + # letters until we find something that's not part of a word. + seenletters = True + if self.isword(nextchar): + token += nextchar + elif nextchar == '.': + token += nextchar + state = 'a.' + else: + self.charstack.append(nextchar) + break # emit token + elif state == '0': + # If we've already started reading a number, we keep reading + # numbers until we find something that doesn't fit. + if self.isnum(nextchar): + token += nextchar + elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): + token += nextchar + state = '0.' + else: + self.charstack.append(nextchar) + break # emit token + elif state == 'a.': + # If we've seen some letters and a dot separator, continue + # parsing, and the tokens will be broken up later. + seenletters = True + if nextchar == '.' or self.isword(nextchar): + token += nextchar + elif self.isnum(nextchar) and token[-1] == '.': + token += nextchar + state = '0.' + else: + self.charstack.append(nextchar) + break # emit token + elif state == '0.': + # If we've seen at least one dot separator, keep going, we'll + # break up the tokens later. + if nextchar == '.' or self.isnum(nextchar): + token += nextchar + elif self.isword(nextchar) and token[-1] == '.': + token += nextchar + state = 'a.' + else: + self.charstack.append(nextchar) + break # emit token + + if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or + token[-1] in '.,')): + l = self._split_decimal.split(token) + token = l[0] + for tok in l[1:]: + if tok: + self.tokenstack.append(tok) + + if state == '0.' and token.count('.') == 0: + token = token.replace(',', '.') + + return token + + def __iter__(self): + return self + + def __next__(self): + token = self.get_token() + if token is None: + raise StopIteration + + return token + + def next(self): + return self.__next__() # Python 2.x support + + @classmethod + def split(cls, s): + return list(cls(s)) + + @classmethod + def isword(cls, nextchar): + """ Whether or not the next character is part of a word """ + return nextchar.isalpha() + + @classmethod + def isnum(cls, nextchar): + """ Whether the next character is part of a number """ + return nextchar.isdigit() + + @classmethod + def isspace(cls, nextchar): + """ Whether the next character is whitespace """ + return nextchar.isspace() + + +class _resultbase(object): + + def __init__(self): + for attr in self.__slots__: + setattr(self, attr, None) + + def _repr(self, classname): + l = [] + for attr in self.__slots__: + value = getattr(self, attr) + if value is not None: + l.append("%s=%s" % (attr, repr(value))) + return "%s(%s)" % (classname, ", ".join(l)) + + def __len__(self): + return (sum(getattr(self, attr) is not None + for attr in self.__slots__)) + + def __repr__(self): + return self._repr(self.__class__.__name__) + + +class parserinfo(object): + """ + Class which handles what inputs are accepted. Subclass this to customize + the language and acceptable values for each parameter. + + :param dayfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the day (``True``) or month (``False``). If + ``yearfirst`` is set to ``True``, this distinguishes between YDM + and YMD. Default is ``False``. + + :param yearfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the year. If ``True``, the first number is taken + to be the year, otherwise the last number is taken to be the year. + Default is ``False``. + """ + + # m from a.m/p.m, t from ISO T separator + JUMP = [" ", ".", ",", ";", "-", "/", "'", + "at", "on", "and", "ad", "m", "t", "of", + "st", "nd", "rd", "th"] + + WEEKDAYS = [("Mon", "Monday"), + ("Tue", "Tuesday"), # TODO: "Tues" + ("Wed", "Wednesday"), + ("Thu", "Thursday"), # TODO: "Thurs" + ("Fri", "Friday"), + ("Sat", "Saturday"), + ("Sun", "Sunday")] + MONTHS = [("Jan", "January"), + ("Feb", "February"), # TODO: "Febr" + ("Mar", "March"), + ("Apr", "April"), + ("May", "May"), + ("Jun", "June"), + ("Jul", "July"), + ("Aug", "August"), + ("Sep", "Sept", "September"), + ("Oct", "October"), + ("Nov", "November"), + ("Dec", "December")] + HMS = [("h", "hour", "hours"), + ("m", "minute", "minutes"), + ("s", "second", "seconds")] + AMPM = [("am", "a"), + ("pm", "p")] + UTCZONE = ["UTC", "GMT", "Z", "z"] + PERTAIN = ["of"] + TZOFFSET = {} + # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", + # "Anno Domini", "Year of Our Lord"] + + def __init__(self, dayfirst=False, yearfirst=False): + self._jump = self._convert(self.JUMP) + self._weekdays = self._convert(self.WEEKDAYS) + self._months = self._convert(self.MONTHS) + self._hms = self._convert(self.HMS) + self._ampm = self._convert(self.AMPM) + self._utczone = self._convert(self.UTCZONE) + self._pertain = self._convert(self.PERTAIN) + + self.dayfirst = dayfirst + self.yearfirst = yearfirst + + self._year = time.localtime().tm_year + self._century = self._year // 100 * 100 + + def _convert(self, lst): + dct = {} + for i, v in enumerate(lst): + if isinstance(v, tuple): + for v in v: + dct[v.lower()] = i + else: + dct[v.lower()] = i + return dct + + def jump(self, name): + return name.lower() in self._jump + + def weekday(self, name): + try: + return self._weekdays[name.lower()] + except KeyError: + pass + return None + + def month(self, name): + try: + return self._months[name.lower()] + 1 + except KeyError: + pass + return None + + def hms(self, name): + try: + return self._hms[name.lower()] + except KeyError: + return None + + def ampm(self, name): + try: + return self._ampm[name.lower()] + except KeyError: + return None + + def pertain(self, name): + return name.lower() in self._pertain + + def utczone(self, name): + return name.lower() in self._utczone + + def tzoffset(self, name): + if name in self._utczone: + return 0 + + return self.TZOFFSET.get(name) + + def convertyear(self, year, century_specified=False): + """ + Converts two-digit years to year within [-50, 49] + range of self._year (current local time) + """ + + # Function contract is that the year is always positive + assert year >= 0 + + if year < 100 and not century_specified: + # assume current century to start + year += self._century + + if year >= self._year + 50: # if too far in future + year -= 100 + elif year < self._year - 50: # if too far in past + year += 100 + + return year + + def validate(self, res): + # move to info + if res.year is not None: + res.year = self.convertyear(res.year, res.century_specified) + + if ((res.tzoffset == 0 and not res.tzname) or + (res.tzname == 'Z' or res.tzname == 'z')): + res.tzname = "UTC" + res.tzoffset = 0 + elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): + res.tzoffset = 0 + return True + + +class _ymd(list): + def __init__(self, *args, **kwargs): + super(self.__class__, self).__init__(*args, **kwargs) + self.century_specified = False + self.dstridx = None + self.mstridx = None + self.ystridx = None + + @property + def has_year(self): + return self.ystridx is not None + + @property + def has_month(self): + return self.mstridx is not None + + @property + def has_day(self): + return self.dstridx is not None + + def could_be_day(self, value): + if self.has_day: + return False + elif not self.has_month: + return 1 <= value <= 31 + elif not self.has_year: + # Be permissive, assume leap year + month = self[self.mstridx] + return 1 <= value <= monthrange(2000, month)[1] + else: + month = self[self.mstridx] + year = self[self.ystridx] + return 1 <= value <= monthrange(year, month)[1] + + def append(self, val, label=None): + if hasattr(val, '__len__'): + if val.isdigit() and len(val) > 2: + self.century_specified = True + if label not in [None, 'Y']: # pragma: no cover + raise ValueError(label) + label = 'Y' + elif val > 100: + self.century_specified = True + if label not in [None, 'Y']: # pragma: no cover + raise ValueError(label) + label = 'Y' + + super(self.__class__, self).append(int(val)) + + if label == 'M': + if self.has_month: + raise ValueError('Month is already set') + self.mstridx = len(self) - 1 + elif label == 'D': + if self.has_day: + raise ValueError('Day is already set') + self.dstridx = len(self) - 1 + elif label == 'Y': + if self.has_year: + raise ValueError('Year is already set') + self.ystridx = len(self) - 1 + + def _resolve_from_stridxs(self, strids): + """ + Try to resolve the identities of year/month/day elements using + ystridx, mstridx, and dstridx, if enough of these are specified. + """ + if len(self) == 3 and len(strids) == 2: + # we can back out the remaining stridx value + missing = [x for x in range(3) if x not in strids.values()] + key = [x for x in ['y', 'm', 'd'] if x not in strids] + assert len(missing) == len(key) == 1 + key = key[0] + val = missing[0] + strids[key] = val + + assert len(self) == len(strids) # otherwise this should not be called + out = {key: self[strids[key]] for key in strids} + return (out.get('y'), out.get('m'), out.get('d')) + + def resolve_ymd(self, yearfirst, dayfirst): + len_ymd = len(self) + year, month, day = (None, None, None) + + strids = (('y', self.ystridx), + ('m', self.mstridx), + ('d', self.dstridx)) + + strids = {key: val for key, val in strids if val is not None} + if (len(self) == len(strids) > 0 or + (len(self) == 3 and len(strids) == 2)): + return self._resolve_from_stridxs(strids) + + mstridx = self.mstridx + + if len_ymd > 3: + raise ValueError("More than three YMD values") + elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): + # One member, or two members with a month string + if mstridx is not None: + month = self[mstridx] + # since mstridx is 0 or 1, self[mstridx-1] always + # looks up the other element + other = self[mstridx - 1] + else: + other = self[0] + + if len_ymd > 1 or mstridx is None: + if other > 31: + year = other + else: + day = other + + elif len_ymd == 2: + # Two members with numbers + if self[0] > 31: + # 99-01 + year, month = self + elif self[1] > 31: + # 01-99 + month, year = self + elif dayfirst and self[1] <= 12: + # 13-01 + day, month = self + else: + # 01-13 + month, day = self + + elif len_ymd == 3: + # Three members + if mstridx == 0: + if self[1] > 31: + # Apr-2003-25 + month, year, day = self + else: + month, day, year = self + elif mstridx == 1: + if self[0] > 31 or (yearfirst and self[2] <= 31): + # 99-Jan-01 + year, month, day = self + else: + # 01-Jan-01 + # Give precedence to day-first, since + # two-digit years is usually hand-written. + day, month, year = self + + elif mstridx == 2: + # WTF!? + if self[1] > 31: + # 01-99-Jan + day, year, month = self + else: + # 99-01-Jan + year, day, month = self + + else: + if (self[0] > 31 or + self.ystridx == 0 or + (yearfirst and self[1] <= 12 and self[2] <= 31)): + # 99-01-01 + if dayfirst and self[2] <= 12: + year, day, month = self + else: + year, month, day = self + elif self[0] > 12 or (dayfirst and self[1] <= 12): + # 13-01-01 + day, month, year = self + else: + # 01-13-01 + month, day, year = self + + return year, month, day + + +class parser(object): + def __init__(self, info=None): + self.info = info or parserinfo() + + def parse(self, timestr, default=None, + ignoretz=False, tzinfos=None, **kwargs): + """ + Parse the date/time string into a :class:`datetime.datetime` object. + + :param timestr: + Any date/time string using the supported formats. + + :param default: + The default datetime object, if this is a datetime object and not + ``None``, elements specified in ``timestr`` replace elements in the + default object. + + :param ignoretz: + If set ``True``, time zones in parsed strings are ignored and a + naive :class:`datetime.datetime` object is returned. + + :param tzinfos: + Additional time zone names / aliases which may be present in the + string. This argument maps time zone names (and optionally offsets + from those time zones) to time zones. This parameter can be a + dictionary with timezone aliases mapping time zone names to time + zones or a function taking two parameters (``tzname`` and + ``tzoffset``) and returning a time zone. + + The timezones to which the names are mapped can be an integer + offset from UTC in seconds or a :class:`tzinfo` object. + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> from dateutil.parser import parse + >>> from dateutil.tz import gettz + >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} + >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) + >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, + tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) + + This parameter is ignored if ``ignoretz`` is set. + + :param \\*\\*kwargs: + Keyword arguments as passed to ``_parse()``. + + :return: + Returns a :class:`datetime.datetime` object or, if the + ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the + first element being a :class:`datetime.datetime` object, the second + a tuple containing the fuzzy tokens. + + :raises ParserError: + Raised for invalid or unknown string format, if the provided + :class:`tzinfo` is not in a valid format, or if an invalid date + would be created. + + :raises TypeError: + Raised for non-string or character stream input. + + :raises OverflowError: + Raised if the parsed date exceeds the largest valid C integer on + your system. + """ + + if default is None: + default = datetime.datetime.now().replace(hour=0, minute=0, + second=0, microsecond=0) + + res, skipped_tokens = self._parse(timestr, **kwargs) + + if res is None: + raise ParserError("Unknown string format: %s", timestr) + + if len(res) == 0: + raise ParserError("String does not contain a date: %s", timestr) + + try: + ret = self._build_naive(res, default) + except ValueError as e: + six.raise_from(ParserError(str(e) + ": %s", timestr), e) + + if not ignoretz: + ret = self._build_tzaware(ret, res, tzinfos) + + if kwargs.get('fuzzy_with_tokens', False): + return ret, skipped_tokens + else: + return ret + + class _result(_resultbase): + __slots__ = ["year", "month", "day", "weekday", + "hour", "minute", "second", "microsecond", + "tzname", "tzoffset", "ampm","any_unused_tokens"] + + def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, + fuzzy_with_tokens=False): + """ + Private method which performs the heavy lifting of parsing, called from + ``parse()``, which passes on its ``kwargs`` to this function. + + :param timestr: + The string to parse. + + :param dayfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the day (``True``) or month (``False``). If + ``yearfirst`` is set to ``True``, this distinguishes between YDM + and YMD. If set to ``None``, this value is retrieved from the + current :class:`parserinfo` object (which itself defaults to + ``False``). + + :param yearfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the year. If ``True``, the first number is taken + to be the year, otherwise the last number is taken to be the year. + If this is set to ``None``, the value is retrieved from the current + :class:`parserinfo` object (which itself defaults to ``False``). + + :param fuzzy: + Whether to allow fuzzy parsing, allowing for string like "Today is + January 1, 2047 at 8:21:00AM". + + :param fuzzy_with_tokens: + If ``True``, ``fuzzy`` is automatically set to True, and the parser + will return a tuple where the first element is the parsed + :class:`datetime.datetime` datetimestamp and the second element is + a tuple containing the portions of the string which were ignored: + + .. doctest:: + + >>> from dateutil.parser import parse + >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) + (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) + + """ + if fuzzy_with_tokens: + fuzzy = True + + info = self.info + + if dayfirst is None: + dayfirst = info.dayfirst + + if yearfirst is None: + yearfirst = info.yearfirst + + res = self._result() + l = _timelex.split(timestr) # Splits the timestr into tokens + + skipped_idxs = [] + + # year/month/day list + ymd = _ymd() + + len_l = len(l) + i = 0 + try: + while i < len_l: + + # Check if it's a number + value_repr = l[i] + try: + value = float(value_repr) + except ValueError: + value = None + + if value is not None: + # Numeric token + i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) + + # Check weekday + elif info.weekday(l[i]) is not None: + value = info.weekday(l[i]) + res.weekday = value + + # Check month name + elif info.month(l[i]) is not None: + value = info.month(l[i]) + ymd.append(value, 'M') + + if i + 1 < len_l: + if l[i + 1] in ('-', '/'): + # Jan-01[-99] + sep = l[i + 1] + ymd.append(l[i + 2]) + + if i + 3 < len_l and l[i + 3] == sep: + # Jan-01-99 + ymd.append(l[i + 4]) + i += 2 + + i += 2 + + elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and + info.pertain(l[i + 2])): + # Jan of 01 + # In this case, 01 is clearly year + if l[i + 4].isdigit(): + # Convert it here to become unambiguous + value = int(l[i + 4]) + year = str(info.convertyear(value)) + ymd.append(year, 'Y') + else: + # Wrong guess + pass + # TODO: not hit in tests + i += 4 + + # Check am/pm + elif info.ampm(l[i]) is not None: + value = info.ampm(l[i]) + val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) + + if val_is_ampm: + res.hour = self._adjust_ampm(res.hour, value) + res.ampm = value + + elif fuzzy: + skipped_idxs.append(i) + + # Check for a timezone name + elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): + res.tzname = l[i] + res.tzoffset = info.tzoffset(res.tzname) + + # Check for something like GMT+3, or BRST+3. Notice + # that it doesn't mean "I am 3 hours after GMT", but + # "my time +3 is GMT". If found, we reverse the + # logic so that timezone parsing code will get it + # right. + if i + 1 < len_l and l[i + 1] in ('+', '-'): + l[i + 1] = ('+', '-')[l[i + 1] == '+'] + res.tzoffset = None + if info.utczone(res.tzname): + # With something like GMT+3, the timezone + # is *not* GMT. + res.tzname = None + + # Check for a numbered timezone + elif res.hour is not None and l[i] in ('+', '-'): + signal = (-1, 1)[l[i] == '+'] + len_li = len(l[i + 1]) + + # TODO: check that l[i + 1] is integer? + if len_li == 4: + # -0300 + hour_offset = int(l[i + 1][:2]) + min_offset = int(l[i + 1][2:]) + elif i + 2 < len_l and l[i + 2] == ':': + # -03:00 + hour_offset = int(l[i + 1]) + min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? + i += 2 + elif len_li <= 2: + # -[0]3 + hour_offset = int(l[i + 1][:2]) + min_offset = 0 + else: + raise ValueError(timestr) + + res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) + + # Look for a timezone name between parenthesis + if (i + 5 < len_l and + info.jump(l[i + 2]) and l[i + 3] == '(' and + l[i + 5] == ')' and + 3 <= len(l[i + 4]) and + self._could_be_tzname(res.hour, res.tzname, + None, l[i + 4])): + # -0300 (BRST) + res.tzname = l[i + 4] + i += 4 + + i += 1 + + # Check jumps + elif not (info.jump(l[i]) or fuzzy): + raise ValueError(timestr) + + else: + skipped_idxs.append(i) + i += 1 + + # Process year/month/day + year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) + + res.century_specified = ymd.century_specified + res.year = year + res.month = month + res.day = day + + except (IndexError, ValueError): + return None, None + + if not info.validate(res): + return None, None + + if fuzzy_with_tokens: + skipped_tokens = self._recombine_skipped(l, skipped_idxs) + return res, tuple(skipped_tokens) + else: + return res, None + + def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): + # Token is a number + value_repr = tokens[idx] + try: + value = self._to_decimal(value_repr) + except Exception as e: + six.raise_from(ValueError('Unknown numeric token'), e) + + len_li = len(value_repr) + + len_l = len(tokens) + + if (len(ymd) == 3 and len_li in (2, 4) and + res.hour is None and + (idx + 1 >= len_l or + (tokens[idx + 1] != ':' and + info.hms(tokens[idx + 1]) is None))): + # 19990101T23[59] + s = tokens[idx] + res.hour = int(s[:2]) + + if len_li == 4: + res.minute = int(s[2:]) + + elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): + # YYMMDD or HHMMSS[.ss] + s = tokens[idx] + + if not ymd and '.' not in tokens[idx]: + ymd.append(s[:2]) + ymd.append(s[2:4]) + ymd.append(s[4:]) + else: + # 19990101T235959[.59] + + # TODO: Check if res attributes already set. + res.hour = int(s[:2]) + res.minute = int(s[2:4]) + res.second, res.microsecond = self._parsems(s[4:]) + + elif len_li in (8, 12, 14): + # YYYYMMDD + s = tokens[idx] + ymd.append(s[:4], 'Y') + ymd.append(s[4:6]) + ymd.append(s[6:8]) + + if len_li > 8: + res.hour = int(s[8:10]) + res.minute = int(s[10:12]) + + if len_li > 12: + res.second = int(s[12:]) + + elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: + # HH[ ]h or MM[ ]m or SS[.ss][ ]s + hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) + (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) + if hms is not None: + # TODO: checking that hour/minute/second are not + # already set? + self._assign_hms(res, value_repr, hms) + + elif idx + 2 < len_l and tokens[idx + 1] == ':': + # HH:MM[:SS[.ss]] + res.hour = int(value) + value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? + (res.minute, res.second) = self._parse_min_sec(value) + + if idx + 4 < len_l and tokens[idx + 3] == ':': + res.second, res.microsecond = self._parsems(tokens[idx + 4]) + + idx += 2 + + idx += 2 + + elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): + sep = tokens[idx + 1] + ymd.append(value_repr) + + if idx + 2 < len_l and not info.jump(tokens[idx + 2]): + if tokens[idx + 2].isdigit(): + # 01-01[-01] + ymd.append(tokens[idx + 2]) + else: + # 01-Jan[-01] + value = info.month(tokens[idx + 2]) + + if value is not None: + ymd.append(value, 'M') + else: + raise ValueError() + + if idx + 3 < len_l and tokens[idx + 3] == sep: + # We have three members + value = info.month(tokens[idx + 4]) + + if value is not None: + ymd.append(value, 'M') + else: + ymd.append(tokens[idx + 4]) + idx += 2 + + idx += 1 + idx += 1 + + elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): + if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: + # 12 am + hour = int(value) + res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) + idx += 1 + else: + # Year, month or day + ymd.append(value) + idx += 1 + + elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): + # 12am + hour = int(value) + res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) + idx += 1 + + elif ymd.could_be_day(value): + ymd.append(value) + + elif not fuzzy: + raise ValueError() + + return idx + + def _find_hms_idx(self, idx, tokens, info, allow_jump): + len_l = len(tokens) + + if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: + # There is an "h", "m", or "s" label following this token. We take + # assign the upcoming label to the current token. + # e.g. the "12" in 12h" + hms_idx = idx + 1 + + elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and + info.hms(tokens[idx+2]) is not None): + # There is a space and then an "h", "m", or "s" label. + # e.g. the "12" in "12 h" + hms_idx = idx + 2 + + elif idx > 0 and info.hms(tokens[idx-1]) is not None: + # There is a "h", "m", or "s" preceding this token. Since neither + # of the previous cases was hit, there is no label following this + # token, so we use the previous label. + # e.g. the "04" in "12h04" + hms_idx = idx-1 + + elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and + info.hms(tokens[idx-2]) is not None): + # If we are looking at the final token, we allow for a + # backward-looking check to skip over a space. + # TODO: Are we sure this is the right condition here? + hms_idx = idx - 2 + + else: + hms_idx = None + + return hms_idx + + def _assign_hms(self, res, value_repr, hms): + # See GH issue #427, fixing float rounding + value = self._to_decimal(value_repr) + + if hms == 0: + # Hour + res.hour = int(value) + if value % 1: + res.minute = int(60*(value % 1)) + + elif hms == 1: + (res.minute, res.second) = self._parse_min_sec(value) + + elif hms == 2: + (res.second, res.microsecond) = self._parsems(value_repr) + + def _could_be_tzname(self, hour, tzname, tzoffset, token): + return (hour is not None and + tzname is None and + tzoffset is None and + len(token) <= 5 and + (all(x in string.ascii_uppercase for x in token) + or token in self.info.UTCZONE)) + + def _ampm_valid(self, hour, ampm, fuzzy): + """ + For fuzzy parsing, 'a' or 'am' (both valid English words) + may erroneously trigger the AM/PM flag. Deal with that + here. + """ + val_is_ampm = True + + # If there's already an AM/PM flag, this one isn't one. + if fuzzy and ampm is not None: + val_is_ampm = False + + # If AM/PM is found and hour is not, raise a ValueError + if hour is None: + if fuzzy: + val_is_ampm = False + else: + raise ValueError('No hour specified with AM or PM flag.') + elif not 0 <= hour <= 12: + # If AM/PM is found, it's a 12 hour clock, so raise + # an error for invalid range + if fuzzy: + val_is_ampm = False + else: + raise ValueError('Invalid hour specified for 12-hour clock.') + + return val_is_ampm + + def _adjust_ampm(self, hour, ampm): + if hour < 12 and ampm == 1: + hour += 12 + elif hour == 12 and ampm == 0: + hour = 0 + return hour + + def _parse_min_sec(self, value): + # TODO: Every usage of this function sets res.second to the return + # value. Are there any cases where second will be returned as None and + # we *don't* want to set res.second = None? + minute = int(value) + second = None + + sec_remainder = value % 1 + if sec_remainder: + second = int(60 * sec_remainder) + return (minute, second) + + def _parse_hms(self, idx, tokens, info, hms_idx): + # TODO: Is this going to admit a lot of false-positives for when we + # just happen to have digits and "h", "m" or "s" characters in non-date + # text? I guess hex hashes won't have that problem, but there's plenty + # of random junk out there. + if hms_idx is None: + hms = None + new_idx = idx + elif hms_idx > idx: + hms = info.hms(tokens[hms_idx]) + new_idx = hms_idx + else: + # Looking backwards, increment one. + hms = info.hms(tokens[hms_idx]) + 1 + new_idx = idx + + return (new_idx, hms) + + # ------------------------------------------------------------------ + # Handling for individual tokens. These are kept as methods instead + # of functions for the sake of customizability via subclassing. + + def _parsems(self, value): + """Parse a I[.F] seconds value into (seconds, microseconds).""" + if "." not in value: + return int(value), 0 + else: + i, f = value.split(".") + return int(i), int(f.ljust(6, "0")[:6]) + + def _to_decimal(self, val): + try: + decimal_value = Decimal(val) + # See GH 662, edge case, infinite value should not be converted + # via `_to_decimal` + if not decimal_value.is_finite(): + raise ValueError("Converted decimal value is infinite or NaN") + except Exception as e: + msg = "Could not convert %s to decimal" % val + six.raise_from(ValueError(msg), e) + else: + return decimal_value + + # ------------------------------------------------------------------ + # Post-Parsing construction of datetime output. These are kept as + # methods instead of functions for the sake of customizability via + # subclassing. + + def _build_tzinfo(self, tzinfos, tzname, tzoffset): + if callable(tzinfos): + tzdata = tzinfos(tzname, tzoffset) + else: + tzdata = tzinfos.get(tzname) + # handle case where tzinfo is paased an options that returns None + # eg tzinfos = {'BRST' : None} + if isinstance(tzdata, datetime.tzinfo) or tzdata is None: + tzinfo = tzdata + elif isinstance(tzdata, text_type): + tzinfo = tz.tzstr(tzdata) + elif isinstance(tzdata, integer_types): + tzinfo = tz.tzoffset(tzname, tzdata) + else: + raise TypeError("Offset must be tzinfo subclass, tz string, " + "or int offset.") + return tzinfo + + def _build_tzaware(self, naive, res, tzinfos): + if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): + tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) + aware = naive.replace(tzinfo=tzinfo) + aware = self._assign_tzname(aware, res.tzname) + + elif res.tzname and res.tzname in time.tzname: + aware = naive.replace(tzinfo=tz.tzlocal()) + + # Handle ambiguous local datetime + aware = self._assign_tzname(aware, res.tzname) + + # This is mostly relevant for winter GMT zones parsed in the UK + if (aware.tzname() != res.tzname and + res.tzname in self.info.UTCZONE): + aware = aware.replace(tzinfo=tz.UTC) + + elif res.tzoffset == 0: + aware = naive.replace(tzinfo=tz.UTC) + + elif res.tzoffset: + aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) + + elif not res.tzname and not res.tzoffset: + # i.e. no timezone information was found. + aware = naive + + elif res.tzname: + # tz-like string was parsed but we don't know what to do + # with it + warnings.warn("tzname {tzname} identified but not understood. " + "Pass `tzinfos` argument in order to correctly " + "return a timezone-aware datetime. In a future " + "version, this will raise an " + "exception.".format(tzname=res.tzname), + category=UnknownTimezoneWarning) + aware = naive + + return aware + + def _build_naive(self, res, default): + repl = {} + for attr in ("year", "month", "day", "hour", + "minute", "second", "microsecond"): + value = getattr(res, attr) + if value is not None: + repl[attr] = value + + if 'day' not in repl: + # If the default day exceeds the last day of the month, fall back + # to the end of the month. + cyear = default.year if res.year is None else res.year + cmonth = default.month if res.month is None else res.month + cday = default.day if res.day is None else res.day + + if cday > monthrange(cyear, cmonth)[1]: + repl['day'] = monthrange(cyear, cmonth)[1] + + naive = default.replace(**repl) + + if res.weekday is not None and not res.day: + naive = naive + relativedelta.relativedelta(weekday=res.weekday) + + return naive + + def _assign_tzname(self, dt, tzname): + if dt.tzname() != tzname: + new_dt = tz.enfold(dt, fold=1) + if new_dt.tzname() == tzname: + return new_dt + + return dt + + def _recombine_skipped(self, tokens, skipped_idxs): + """ + >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] + >>> skipped_idxs = [0, 1, 2, 5] + >>> _recombine_skipped(tokens, skipped_idxs) + ["foo bar", "baz"] + """ + skipped_tokens = [] + for i, idx in enumerate(sorted(skipped_idxs)): + if i > 0 and idx - 1 == skipped_idxs[i - 1]: + skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] + else: + skipped_tokens.append(tokens[idx]) + + return skipped_tokens + + +DEFAULTPARSER = parser() + + +def parse(timestr, parserinfo=None, **kwargs): + """ + + Parse a string in one of the supported formats, using the + ``parserinfo`` parameters. + + :param timestr: + A string containing a date/time stamp. + + :param parserinfo: + A :class:`parserinfo` object containing parameters for the parser. + If ``None``, the default arguments to the :class:`parserinfo` + constructor are used. + + The ``**kwargs`` parameter takes the following keyword arguments: + + :param default: + The default datetime object, if this is a datetime object and not + ``None``, elements specified in ``timestr`` replace elements in the + default object. + + :param ignoretz: + If set ``True``, time zones in parsed strings are ignored and a naive + :class:`datetime` object is returned. + + :param tzinfos: + Additional time zone names / aliases which may be present in the + string. This argument maps time zone names (and optionally offsets + from those time zones) to time zones. This parameter can be a + dictionary with timezone aliases mapping time zone names to time + zones or a function taking two parameters (``tzname`` and + ``tzoffset``) and returning a time zone. + + The timezones to which the names are mapped can be an integer + offset from UTC in seconds or a :class:`tzinfo` object. + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> from dateutil.parser import parse + >>> from dateutil.tz import gettz + >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} + >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) + >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, + tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) + + This parameter is ignored if ``ignoretz`` is set. + + :param dayfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the day (``True``) or month (``False``). If + ``yearfirst`` is set to ``True``, this distinguishes between YDM and + YMD. If set to ``None``, this value is retrieved from the current + :class:`parserinfo` object (which itself defaults to ``False``). + + :param yearfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the year. If ``True``, the first number is taken to + be the year, otherwise the last number is taken to be the year. If + this is set to ``None``, the value is retrieved from the current + :class:`parserinfo` object (which itself defaults to ``False``). + + :param fuzzy: + Whether to allow fuzzy parsing, allowing for string like "Today is + January 1, 2047 at 8:21:00AM". + + :param fuzzy_with_tokens: + If ``True``, ``fuzzy`` is automatically set to True, and the parser + will return a tuple where the first element is the parsed + :class:`datetime.datetime` datetimestamp and the second element is + a tuple containing the portions of the string which were ignored: + + .. doctest:: + + >>> from dateutil.parser import parse + >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) + (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) + + :return: + Returns a :class:`datetime.datetime` object or, if the + ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the + first element being a :class:`datetime.datetime` object, the second + a tuple containing the fuzzy tokens. + + :raises ParserError: + Raised for invalid or unknown string formats, if the provided + :class:`tzinfo` is not in a valid format, or if an invalid date would + be created. + + :raises OverflowError: + Raised if the parsed date exceeds the largest valid C integer on + your system. + """ + if parserinfo: + return parser(parserinfo).parse(timestr, **kwargs) + else: + return DEFAULTPARSER.parse(timestr, **kwargs) + + +class _tzparser(object): + + class _result(_resultbase): + + __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", + "start", "end"] + + class _attr(_resultbase): + __slots__ = ["month", "week", "weekday", + "yday", "jyday", "day", "time"] + + def __repr__(self): + return self._repr("") + + def __init__(self): + _resultbase.__init__(self) + self.start = self._attr() + self.end = self._attr() + + def parse(self, tzstr): + res = self._result() + l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] + used_idxs = list() + try: + + len_l = len(l) + + i = 0 + while i < len_l: + # BRST+3[BRDT[+2]] + j = i + while j < len_l and not [x for x in l[j] + if x in "0123456789:,-+"]: + j += 1 + if j != i: + if not res.stdabbr: + offattr = "stdoffset" + res.stdabbr = "".join(l[i:j]) + else: + offattr = "dstoffset" + res.dstabbr = "".join(l[i:j]) + + for ii in range(j): + used_idxs.append(ii) + i = j + if (i < len_l and (l[i] in ('+', '-') or l[i][0] in + "0123456789")): + if l[i] in ('+', '-'): + # Yes, that's right. See the TZ variable + # documentation. + signal = (1, -1)[l[i] == '+'] + used_idxs.append(i) + i += 1 + else: + signal = -1 + len_li = len(l[i]) + if len_li == 4: + # -0300 + setattr(res, offattr, (int(l[i][:2]) * 3600 + + int(l[i][2:]) * 60) * signal) + elif i + 1 < len_l and l[i + 1] == ':': + # -03:00 + setattr(res, offattr, + (int(l[i]) * 3600 + + int(l[i + 2]) * 60) * signal) + used_idxs.append(i) + i += 2 + elif len_li <= 2: + # -[0]3 + setattr(res, offattr, + int(l[i][:2]) * 3600 * signal) + else: + return None + used_idxs.append(i) + i += 1 + if res.dstabbr: + break + else: + break + + + if i < len_l: + for j in range(i, len_l): + if l[j] == ';': + l[j] = ',' + + assert l[i] == ',' + + i += 1 + + if i >= len_l: + pass + elif (8 <= l.count(',') <= 9 and + not [y for x in l[i:] if x != ',' + for y in x if y not in "0123456789+-"]): + # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] + for x in (res.start, res.end): + x.month = int(l[i]) + used_idxs.append(i) + i += 2 + if l[i] == '-': + value = int(l[i + 1]) * -1 + used_idxs.append(i) + i += 1 + else: + value = int(l[i]) + used_idxs.append(i) + i += 2 + if value: + x.week = value + x.weekday = (int(l[i]) - 1) % 7 + else: + x.day = int(l[i]) + used_idxs.append(i) + i += 2 + x.time = int(l[i]) + used_idxs.append(i) + i += 2 + if i < len_l: + if l[i] in ('-', '+'): + signal = (-1, 1)[l[i] == "+"] + used_idxs.append(i) + i += 1 + else: + signal = 1 + used_idxs.append(i) + res.dstoffset = (res.stdoffset + int(l[i]) * signal) + + # This was a made-up format that is not in normal use + warn(('Parsed time zone "%s"' % tzstr) + + 'is in a non-standard dateutil-specific format, which ' + + 'is now deprecated; support for parsing this format ' + + 'will be removed in future versions. It is recommended ' + + 'that you switch to a standard format like the GNU ' + + 'TZ variable format.', tz.DeprecatedTzFormatWarning) + elif (l.count(',') == 2 and l[i:].count('/') <= 2 and + not [y for x in l[i:] if x not in (',', '/', 'J', 'M', + '.', '-', ':') + for y in x if y not in "0123456789"]): + for x in (res.start, res.end): + if l[i] == 'J': + # non-leap year day (1 based) + used_idxs.append(i) + i += 1 + x.jyday = int(l[i]) + elif l[i] == 'M': + # month[-.]week[-.]weekday + used_idxs.append(i) + i += 1 + x.month = int(l[i]) + used_idxs.append(i) + i += 1 + assert l[i] in ('-', '.') + used_idxs.append(i) + i += 1 + x.week = int(l[i]) + if x.week == 5: + x.week = -1 + used_idxs.append(i) + i += 1 + assert l[i] in ('-', '.') + used_idxs.append(i) + i += 1 + x.weekday = (int(l[i]) - 1) % 7 + else: + # year day (zero based) + x.yday = int(l[i]) + 1 + + used_idxs.append(i) + i += 1 + + if i < len_l and l[i] == '/': + used_idxs.append(i) + i += 1 + # start time + len_li = len(l[i]) + if len_li == 4: + # -0300 + x.time = (int(l[i][:2]) * 3600 + + int(l[i][2:]) * 60) + elif i + 1 < len_l and l[i + 1] == ':': + # -03:00 + x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 + used_idxs.append(i) + i += 2 + if i + 1 < len_l and l[i + 1] == ':': + used_idxs.append(i) + i += 2 + x.time += int(l[i]) + elif len_li <= 2: + # -[0]3 + x.time = (int(l[i][:2]) * 3600) + else: + return None + used_idxs.append(i) + i += 1 + + assert i == len_l or l[i] == ',' + + i += 1 + + assert i >= len_l + + except (IndexError, ValueError, AssertionError): + return None + + unused_idxs = set(range(len_l)).difference(used_idxs) + res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) + return res + + +DEFAULTTZPARSER = _tzparser() + + +def _parsetz(tzstr): + return DEFAULTTZPARSER.parse(tzstr) + + +class ParserError(ValueError): + """Exception subclass used for any failure to parse a datetime string. + + This is a subclass of :py:exc:`ValueError`, and should be raised any time + earlier versions of ``dateutil`` would have raised ``ValueError``. + + .. versionadded:: 2.8.1 + """ + def __str__(self): + try: + return self.args[0] % self.args[1:] + except (TypeError, IndexError): + return super(ParserError, self).__str__() + + def __repr__(self): + args = ", ".join("'%s'" % arg for arg in self.args) + return "%s(%s)" % (self.__class__.__name__, args) + + +class UnknownTimezoneWarning(RuntimeWarning): + """Raised when the parser finds a timezone it cannot parse into a tzinfo. + + .. versionadded:: 2.7.0 + """ +# vim:ts=4:sw=4:et diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/isoparser.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/isoparser.py new file mode 100644 index 0000000000000000000000000000000000000000..7060087df4776a07347cbb60127a70db393e3a65 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/parser/isoparser.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +""" +This module offers a parser for ISO-8601 strings + +It is intended to support all valid date, time and datetime formats per the +ISO-8601 specification. + +..versionadded:: 2.7.0 +""" +from datetime import datetime, timedelta, time, date +import calendar +from dateutil import tz + +from functools import wraps + +import re +import six + +__all__ = ["isoparse", "isoparser"] + + +def _takes_ascii(f): + @wraps(f) + def func(self, str_in, *args, **kwargs): + # If it's a stream, read the whole thing + str_in = getattr(str_in, 'read', lambda: str_in)() + + # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII + if isinstance(str_in, six.text_type): + # ASCII is the same in UTF-8 + try: + str_in = str_in.encode('ascii') + except UnicodeEncodeError as e: + msg = 'ISO-8601 strings should contain only ASCII characters' + six.raise_from(ValueError(msg), e) + + return f(self, str_in, *args, **kwargs) + + return func + + +class isoparser(object): + def __init__(self, sep=None): + """ + :param sep: + A single character that separates date and time portions. If + ``None``, the parser will accept any single character. + For strict ISO-8601 adherence, pass ``'T'``. + """ + if sep is not None: + if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): + raise ValueError('Separator must be a single, non-numeric ' + + 'ASCII character') + + sep = sep.encode('ascii') + + self._sep = sep + + @_takes_ascii + def isoparse(self, dt_str): + """ + Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. + + An ISO-8601 datetime string consists of a date portion, followed + optionally by a time portion - the date and time portions are separated + by a single character separator, which is ``T`` in the official + standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be + combined with a time portion. + + Supported date formats are: + + Common: + + - ``YYYY`` + - ``YYYY-MM`` + - ``YYYY-MM-DD`` or ``YYYYMMDD`` + + Uncommon: + + - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) + - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day + + The ISO week and day numbering follows the same logic as + :func:`datetime.date.isocalendar`. + + Supported time formats are: + + - ``hh`` + - ``hh:mm`` or ``hhmm`` + - ``hh:mm:ss`` or ``hhmmss`` + - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) + + Midnight is a special case for `hh`, as the standard supports both + 00:00 and 24:00 as a representation. The decimal separator can be + either a dot or a comma. + + + .. caution:: + + Support for fractional components other than seconds is part of the + ISO-8601 standard, but is not currently implemented in this parser. + + Supported time zone offset formats are: + + - `Z` (UTC) + - `±HH:MM` + - `±HHMM` + - `±HH` + + Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, + with the exception of UTC, which will be represented as + :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such + as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. + + :param dt_str: + A string or stream containing only an ISO-8601 datetime string + + :return: + Returns a :class:`datetime.datetime` representing the string. + Unspecified components default to their lowest value. + + .. warning:: + + As of version 2.7.0, the strictness of the parser should not be + considered a stable part of the contract. Any valid ISO-8601 string + that parses correctly with the default settings will continue to + parse correctly in future versions, but invalid strings that + currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not + guaranteed to continue failing in future versions if they encode + a valid date. + + .. versionadded:: 2.7.0 + """ + components, pos = self._parse_isodate(dt_str) + + if len(dt_str) > pos: + if self._sep is None or dt_str[pos:pos + 1] == self._sep: + components += self._parse_isotime(dt_str[pos + 1:]) + else: + raise ValueError('String contains unknown ISO components') + + if len(components) > 3 and components[3] == 24: + components[3] = 0 + return datetime(*components) + timedelta(days=1) + + return datetime(*components) + + @_takes_ascii + def parse_isodate(self, datestr): + """ + Parse the date portion of an ISO string. + + :param datestr: + The string portion of an ISO string, without a separator + + :return: + Returns a :class:`datetime.date` object + """ + components, pos = self._parse_isodate(datestr) + if pos < len(datestr): + raise ValueError('String contains unknown ISO ' + + 'components: {!r}'.format(datestr.decode('ascii'))) + return date(*components) + + @_takes_ascii + def parse_isotime(self, timestr): + """ + Parse the time portion of an ISO string. + + :param timestr: + The time portion of an ISO string, without a separator + + :return: + Returns a :class:`datetime.time` object + """ + components = self._parse_isotime(timestr) + if components[0] == 24: + components[0] = 0 + return time(*components) + + @_takes_ascii + def parse_tzstr(self, tzstr, zero_as_utc=True): + """ + Parse a valid ISO time zone string. + + See :func:`isoparser.isoparse` for details on supported formats. + + :param tzstr: + A string representing an ISO time zone offset + + :param zero_as_utc: + Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones + + :return: + Returns :class:`dateutil.tz.tzoffset` for offsets and + :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is + specified) offsets equivalent to UTC. + """ + return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) + + # Constants + _DATE_SEP = b'-' + _TIME_SEP = b':' + _FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)') + + def _parse_isodate(self, dt_str): + try: + return self._parse_isodate_common(dt_str) + except ValueError: + return self._parse_isodate_uncommon(dt_str) + + def _parse_isodate_common(self, dt_str): + len_str = len(dt_str) + components = [1, 1, 1] + + if len_str < 4: + raise ValueError('ISO string too short') + + # Year + components[0] = int(dt_str[0:4]) + pos = 4 + if pos >= len_str: + return components, pos + + has_sep = dt_str[pos:pos + 1] == self._DATE_SEP + if has_sep: + pos += 1 + + # Month + if len_str - pos < 2: + raise ValueError('Invalid common month') + + components[1] = int(dt_str[pos:pos + 2]) + pos += 2 + + if pos >= len_str: + if has_sep: + return components, pos + else: + raise ValueError('Invalid ISO format') + + if has_sep: + if dt_str[pos:pos + 1] != self._DATE_SEP: + raise ValueError('Invalid separator in ISO string') + pos += 1 + + # Day + if len_str - pos < 2: + raise ValueError('Invalid common day') + components[2] = int(dt_str[pos:pos + 2]) + return components, pos + 2 + + def _parse_isodate_uncommon(self, dt_str): + if len(dt_str) < 4: + raise ValueError('ISO string too short') + + # All ISO formats start with the year + year = int(dt_str[0:4]) + + has_sep = dt_str[4:5] == self._DATE_SEP + + pos = 4 + has_sep # Skip '-' if it's there + if dt_str[pos:pos + 1] == b'W': + # YYYY-?Www-?D? + pos += 1 + weekno = int(dt_str[pos:pos + 2]) + pos += 2 + + dayno = 1 + if len(dt_str) > pos: + if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: + raise ValueError('Inconsistent use of dash separator') + + pos += has_sep + + dayno = int(dt_str[pos:pos + 1]) + pos += 1 + + base_date = self._calculate_weekdate(year, weekno, dayno) + else: + # YYYYDDD or YYYY-DDD + if len(dt_str) - pos < 3: + raise ValueError('Invalid ordinal day') + + ordinal_day = int(dt_str[pos:pos + 3]) + pos += 3 + + if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): + raise ValueError('Invalid ordinal day' + + ' {} for year {}'.format(ordinal_day, year)) + + base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) + + components = [base_date.year, base_date.month, base_date.day] + return components, pos + + def _calculate_weekdate(self, year, week, day): + """ + Calculate the day of corresponding to the ISO year-week-day calendar. + + This function is effectively the inverse of + :func:`datetime.date.isocalendar`. + + :param year: + The year in the ISO calendar + + :param week: + The week in the ISO calendar - range is [1, 53] + + :param day: + The day in the ISO calendar - range is [1 (MON), 7 (SUN)] + + :return: + Returns a :class:`datetime.date` + """ + if not 0 < week < 54: + raise ValueError('Invalid week: {}'.format(week)) + + if not 0 < day < 8: # Range is 1-7 + raise ValueError('Invalid weekday: {}'.format(day)) + + # Get week 1 for the specific year: + jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it + week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) + + # Now add the specific number of weeks and days to get what we want + week_offset = (week - 1) * 7 + (day - 1) + return week_1 + timedelta(days=week_offset) + + def _parse_isotime(self, timestr): + len_str = len(timestr) + components = [0, 0, 0, 0, None] + pos = 0 + comp = -1 + + if len_str < 2: + raise ValueError('ISO time too short') + + has_sep = False + + while pos < len_str and comp < 5: + comp += 1 + + if timestr[pos:pos + 1] in b'-+Zz': + # Detect time zone boundary + components[-1] = self._parse_tzstr(timestr[pos:]) + pos = len_str + break + + if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP: + has_sep = True + pos += 1 + elif comp == 2 and has_sep: + if timestr[pos:pos+1] != self._TIME_SEP: + raise ValueError('Inconsistent use of colon separator') + pos += 1 + + if comp < 3: + # Hour, minute, second + components[comp] = int(timestr[pos:pos + 2]) + pos += 2 + + if comp == 3: + # Fraction of a second + frac = self._FRACTION_REGEX.match(timestr[pos:]) + if not frac: + continue + + us_str = frac.group(1)[:6] # Truncate to microseconds + components[comp] = int(us_str) * 10**(6 - len(us_str)) + pos += len(frac.group()) + + if pos < len_str: + raise ValueError('Unused components in ISO string') + + if components[0] == 24: + # Standard supports 00:00 and 24:00 as representations of midnight + if any(component != 0 for component in components[1:4]): + raise ValueError('Hour may only be 24 at 24:00:00.000') + + return components + + def _parse_tzstr(self, tzstr, zero_as_utc=True): + if tzstr == b'Z' or tzstr == b'z': + return tz.UTC + + if len(tzstr) not in {3, 5, 6}: + raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') + + if tzstr[0:1] == b'-': + mult = -1 + elif tzstr[0:1] == b'+': + mult = 1 + else: + raise ValueError('Time zone offset requires sign') + + hours = int(tzstr[1:3]) + if len(tzstr) == 3: + minutes = 0 + else: + minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):]) + + if zero_as_utc and hours == 0 and minutes == 0: + return tz.UTC + else: + if minutes > 59: + raise ValueError('Invalid minutes in time zone offset') + + if hours > 23: + raise ValueError('Invalid hours in time zone offset') + + return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) + + +DEFAULT_ISOPARSER = isoparser() +isoparse = DEFAULT_ISOPARSER.isoparse diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/relativedelta.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/relativedelta.py new file mode 100644 index 0000000000000000000000000000000000000000..cd323a549e0f182541ebcde2d2ea1adfbbd9701e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/relativedelta.py @@ -0,0 +1,599 @@ +# -*- coding: utf-8 -*- +import datetime +import calendar + +import operator +from math import copysign + +from six import integer_types +from warnings import warn + +from ._common import weekday + +MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) + +__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] + + +class relativedelta(object): + """ + The relativedelta type is designed to be applied to an existing datetime and + can replace specific components of that datetime, or represents an interval + of time. + + It is based on the specification of the excellent work done by M.-A. Lemburg + in his + `mx.DateTime `_ extension. + However, notice that this type does *NOT* implement the same algorithm as + his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. + + There are two different ways to build a relativedelta instance. The + first one is passing it two date/datetime classes:: + + relativedelta(datetime1, datetime2) + + The second one is passing it any number of the following keyword arguments:: + + relativedelta(arg1=x,arg2=y,arg3=z...) + + year, month, day, hour, minute, second, microsecond: + Absolute information (argument is singular); adding or subtracting a + relativedelta with absolute information does not perform an arithmetic + operation, but rather REPLACES the corresponding value in the + original datetime with the value(s) in relativedelta. + + years, months, weeks, days, hours, minutes, seconds, microseconds: + Relative information, may be negative (argument is plural); adding + or subtracting a relativedelta with relative information performs + the corresponding arithmetic operation on the original datetime value + with the information in the relativedelta. + + weekday: + One of the weekday instances (MO, TU, etc) available in the + relativedelta module. These instances may receive a parameter N, + specifying the Nth weekday, which could be positive or negative + (like MO(+1) or MO(-2)). Not specifying it is the same as specifying + +1. You can also use an integer, where 0=MO. This argument is always + relative e.g. if the calculated date is already Monday, using MO(1) + or MO(-1) won't change the day. To effectively make it absolute, use + it in combination with the day argument (e.g. day=1, MO(1) for first + Monday of the month). + + leapdays: + Will add given days to the date found, if year is a leap + year, and the date found is post 28 of february. + + yearday, nlyearday: + Set the yearday or the non-leap year day (jump leap days). + These are converted to day/month/leapdays information. + + There are relative and absolute forms of the keyword + arguments. The plural is relative, and the singular is + absolute. For each argument in the order below, the absolute form + is applied first (by setting each attribute to that value) and + then the relative form (by adding the value to the attribute). + + The order of attributes considered when this relativedelta is + added to a datetime is: + + 1. Year + 2. Month + 3. Day + 4. Hours + 5. Minutes + 6. Seconds + 7. Microseconds + + Finally, weekday is applied, using the rule described above. + + For example + + >>> from datetime import datetime + >>> from dateutil.relativedelta import relativedelta, MO + >>> dt = datetime(2018, 4, 9, 13, 37, 0) + >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) + >>> dt + delta + datetime.datetime(2018, 4, 2, 14, 37) + + First, the day is set to 1 (the first of the month), then 25 hours + are added, to get to the 2nd day and 14th hour, finally the + weekday is applied, but since the 2nd is already a Monday there is + no effect. + + """ + + def __init__(self, dt1=None, dt2=None, + years=0, months=0, days=0, leapdays=0, weeks=0, + hours=0, minutes=0, seconds=0, microseconds=0, + year=None, month=None, day=None, weekday=None, + yearday=None, nlyearday=None, + hour=None, minute=None, second=None, microsecond=None): + + if dt1 and dt2: + # datetime is a subclass of date. So both must be date + if not (isinstance(dt1, datetime.date) and + isinstance(dt2, datetime.date)): + raise TypeError("relativedelta only diffs datetime/date") + + # We allow two dates, or two datetimes, so we coerce them to be + # of the same type + if (isinstance(dt1, datetime.datetime) != + isinstance(dt2, datetime.datetime)): + if not isinstance(dt1, datetime.datetime): + dt1 = datetime.datetime.fromordinal(dt1.toordinal()) + elif not isinstance(dt2, datetime.datetime): + dt2 = datetime.datetime.fromordinal(dt2.toordinal()) + + self.years = 0 + self.months = 0 + self.days = 0 + self.leapdays = 0 + self.hours = 0 + self.minutes = 0 + self.seconds = 0 + self.microseconds = 0 + self.year = None + self.month = None + self.day = None + self.weekday = None + self.hour = None + self.minute = None + self.second = None + self.microsecond = None + self._has_time = 0 + + # Get year / month delta between the two + months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) + self._set_months(months) + + # Remove the year/month delta so the timedelta is just well-defined + # time units (seconds, days and microseconds) + dtm = self.__radd__(dt2) + + # If we've overshot our target, make an adjustment + if dt1 < dt2: + compare = operator.gt + increment = 1 + else: + compare = operator.lt + increment = -1 + + while compare(dt1, dtm): + months += increment + self._set_months(months) + dtm = self.__radd__(dt2) + + # Get the timedelta between the "months-adjusted" date and dt1 + delta = dt1 - dtm + self.seconds = delta.seconds + delta.days * 86400 + self.microseconds = delta.microseconds + else: + # Check for non-integer values in integer-only quantities + if any(x is not None and x != int(x) for x in (years, months)): + raise ValueError("Non-integer years and months are " + "ambiguous and not currently supported.") + + # Relative information + self.years = int(years) + self.months = int(months) + self.days = days + weeks * 7 + self.leapdays = leapdays + self.hours = hours + self.minutes = minutes + self.seconds = seconds + self.microseconds = microseconds + + # Absolute information + self.year = year + self.month = month + self.day = day + self.hour = hour + self.minute = minute + self.second = second + self.microsecond = microsecond + + if any(x is not None and int(x) != x + for x in (year, month, day, hour, + minute, second, microsecond)): + # For now we'll deprecate floats - later it'll be an error. + warn("Non-integer value passed as absolute information. " + + "This is not a well-defined condition and will raise " + + "errors in future versions.", DeprecationWarning) + + if isinstance(weekday, integer_types): + self.weekday = weekdays[weekday] + else: + self.weekday = weekday + + yday = 0 + if nlyearday: + yday = nlyearday + elif yearday: + yday = yearday + if yearday > 59: + self.leapdays = -1 + if yday: + ydayidx = [31, 59, 90, 120, 151, 181, 212, + 243, 273, 304, 334, 366] + for idx, ydays in enumerate(ydayidx): + if yday <= ydays: + self.month = idx+1 + if idx == 0: + self.day = yday + else: + self.day = yday-ydayidx[idx-1] + break + else: + raise ValueError("invalid year day (%d)" % yday) + + self._fix() + + def _fix(self): + if abs(self.microseconds) > 999999: + s = _sign(self.microseconds) + div, mod = divmod(self.microseconds * s, 1000000) + self.microseconds = mod * s + self.seconds += div * s + if abs(self.seconds) > 59: + s = _sign(self.seconds) + div, mod = divmod(self.seconds * s, 60) + self.seconds = mod * s + self.minutes += div * s + if abs(self.minutes) > 59: + s = _sign(self.minutes) + div, mod = divmod(self.minutes * s, 60) + self.minutes = mod * s + self.hours += div * s + if abs(self.hours) > 23: + s = _sign(self.hours) + div, mod = divmod(self.hours * s, 24) + self.hours = mod * s + self.days += div * s + if abs(self.months) > 11: + s = _sign(self.months) + div, mod = divmod(self.months * s, 12) + self.months = mod * s + self.years += div * s + if (self.hours or self.minutes or self.seconds or self.microseconds + or self.hour is not None or self.minute is not None or + self.second is not None or self.microsecond is not None): + self._has_time = 1 + else: + self._has_time = 0 + + @property + def weeks(self): + return int(self.days / 7.0) + + @weeks.setter + def weeks(self, value): + self.days = self.days - (self.weeks * 7) + value * 7 + + def _set_months(self, months): + self.months = months + if abs(self.months) > 11: + s = _sign(self.months) + div, mod = divmod(self.months * s, 12) + self.months = mod * s + self.years = div * s + else: + self.years = 0 + + def normalized(self): + """ + Return a version of this object represented entirely using integer + values for the relative attributes. + + >>> relativedelta(days=1.5, hours=2).normalized() + relativedelta(days=+1, hours=+14) + + :return: + Returns a :class:`dateutil.relativedelta.relativedelta` object. + """ + # Cascade remainders down (rounding each to roughly nearest microsecond) + days = int(self.days) + + hours_f = round(self.hours + 24 * (self.days - days), 11) + hours = int(hours_f) + + minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) + minutes = int(minutes_f) + + seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) + seconds = int(seconds_f) + + microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) + + # Constructor carries overflow back up with call to _fix() + return self.__class__(years=self.years, months=self.months, + days=days, hours=hours, minutes=minutes, + seconds=seconds, microseconds=microseconds, + leapdays=self.leapdays, year=self.year, + month=self.month, day=self.day, + weekday=self.weekday, hour=self.hour, + minute=self.minute, second=self.second, + microsecond=self.microsecond) + + def __add__(self, other): + if isinstance(other, relativedelta): + return self.__class__(years=other.years + self.years, + months=other.months + self.months, + days=other.days + self.days, + hours=other.hours + self.hours, + minutes=other.minutes + self.minutes, + seconds=other.seconds + self.seconds, + microseconds=(other.microseconds + + self.microseconds), + leapdays=other.leapdays or self.leapdays, + year=(other.year if other.year is not None + else self.year), + month=(other.month if other.month is not None + else self.month), + day=(other.day if other.day is not None + else self.day), + weekday=(other.weekday if other.weekday is not None + else self.weekday), + hour=(other.hour if other.hour is not None + else self.hour), + minute=(other.minute if other.minute is not None + else self.minute), + second=(other.second if other.second is not None + else self.second), + microsecond=(other.microsecond if other.microsecond + is not None else + self.microsecond)) + if isinstance(other, datetime.timedelta): + return self.__class__(years=self.years, + months=self.months, + days=self.days + other.days, + hours=self.hours, + minutes=self.minutes, + seconds=self.seconds + other.seconds, + microseconds=self.microseconds + other.microseconds, + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + if not isinstance(other, datetime.date): + return NotImplemented + elif self._has_time and not isinstance(other, datetime.datetime): + other = datetime.datetime.fromordinal(other.toordinal()) + year = (self.year or other.year)+self.years + month = self.month or other.month + if self.months: + assert 1 <= abs(self.months) <= 12 + month += self.months + if month > 12: + year += 1 + month -= 12 + elif month < 1: + year -= 1 + month += 12 + day = min(calendar.monthrange(year, month)[1], + self.day or other.day) + repl = {"year": year, "month": month, "day": day} + for attr in ["hour", "minute", "second", "microsecond"]: + value = getattr(self, attr) + if value is not None: + repl[attr] = value + days = self.days + if self.leapdays and month > 2 and calendar.isleap(year): + days += self.leapdays + ret = (other.replace(**repl) + + datetime.timedelta(days=days, + hours=self.hours, + minutes=self.minutes, + seconds=self.seconds, + microseconds=self.microseconds)) + if self.weekday: + weekday, nth = self.weekday.weekday, self.weekday.n or 1 + jumpdays = (abs(nth) - 1) * 7 + if nth > 0: + jumpdays += (7 - ret.weekday() + weekday) % 7 + else: + jumpdays += (ret.weekday() - weekday) % 7 + jumpdays *= -1 + ret += datetime.timedelta(days=jumpdays) + return ret + + def __radd__(self, other): + return self.__add__(other) + + def __rsub__(self, other): + return self.__neg__().__radd__(other) + + def __sub__(self, other): + if not isinstance(other, relativedelta): + return NotImplemented # In case the other object defines __rsub__ + return self.__class__(years=self.years - other.years, + months=self.months - other.months, + days=self.days - other.days, + hours=self.hours - other.hours, + minutes=self.minutes - other.minutes, + seconds=self.seconds - other.seconds, + microseconds=self.microseconds - other.microseconds, + leapdays=self.leapdays or other.leapdays, + year=(self.year if self.year is not None + else other.year), + month=(self.month if self.month is not None else + other.month), + day=(self.day if self.day is not None else + other.day), + weekday=(self.weekday if self.weekday is not None else + other.weekday), + hour=(self.hour if self.hour is not None else + other.hour), + minute=(self.minute if self.minute is not None else + other.minute), + second=(self.second if self.second is not None else + other.second), + microsecond=(self.microsecond if self.microsecond + is not None else + other.microsecond)) + + def __abs__(self): + return self.__class__(years=abs(self.years), + months=abs(self.months), + days=abs(self.days), + hours=abs(self.hours), + minutes=abs(self.minutes), + seconds=abs(self.seconds), + microseconds=abs(self.microseconds), + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + + def __neg__(self): + return self.__class__(years=-self.years, + months=-self.months, + days=-self.days, + hours=-self.hours, + minutes=-self.minutes, + seconds=-self.seconds, + microseconds=-self.microseconds, + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + + def __bool__(self): + return not (not self.years and + not self.months and + not self.days and + not self.hours and + not self.minutes and + not self.seconds and + not self.microseconds and + not self.leapdays and + self.year is None and + self.month is None and + self.day is None and + self.weekday is None and + self.hour is None and + self.minute is None and + self.second is None and + self.microsecond is None) + # Compatibility with Python 2.x + __nonzero__ = __bool__ + + def __mul__(self, other): + try: + f = float(other) + except TypeError: + return NotImplemented + + return self.__class__(years=int(self.years * f), + months=int(self.months * f), + days=int(self.days * f), + hours=int(self.hours * f), + minutes=int(self.minutes * f), + seconds=int(self.seconds * f), + microseconds=int(self.microseconds * f), + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + + __rmul__ = __mul__ + + def __eq__(self, other): + if not isinstance(other, relativedelta): + return NotImplemented + if self.weekday or other.weekday: + if not self.weekday or not other.weekday: + return False + if self.weekday.weekday != other.weekday.weekday: + return False + n1, n2 = self.weekday.n, other.weekday.n + if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): + return False + return (self.years == other.years and + self.months == other.months and + self.days == other.days and + self.hours == other.hours and + self.minutes == other.minutes and + self.seconds == other.seconds and + self.microseconds == other.microseconds and + self.leapdays == other.leapdays and + self.year == other.year and + self.month == other.month and + self.day == other.day and + self.hour == other.hour and + self.minute == other.minute and + self.second == other.second and + self.microsecond == other.microsecond) + + def __hash__(self): + return hash(( + self.weekday, + self.years, + self.months, + self.days, + self.hours, + self.minutes, + self.seconds, + self.microseconds, + self.leapdays, + self.year, + self.month, + self.day, + self.hour, + self.minute, + self.second, + self.microsecond, + )) + + def __ne__(self, other): + return not self.__eq__(other) + + def __div__(self, other): + try: + reciprocal = 1 / float(other) + except TypeError: + return NotImplemented + + return self.__mul__(reciprocal) + + __truediv__ = __div__ + + def __repr__(self): + l = [] + for attr in ["years", "months", "days", "leapdays", + "hours", "minutes", "seconds", "microseconds"]: + value = getattr(self, attr) + if value: + l.append("{attr}={value:+g}".format(attr=attr, value=value)) + for attr in ["year", "month", "day", "weekday", + "hour", "minute", "second", "microsecond"]: + value = getattr(self, attr) + if value is not None: + l.append("{attr}={value}".format(attr=attr, value=repr(value))) + return "{classname}({attrs})".format(classname=self.__class__.__name__, + attrs=", ".join(l)) + + +def _sign(x): + return int(copysign(1, x)) + +# vim:ts=4:sw=4:et diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/rrule.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/rrule.py new file mode 100644 index 0000000000000000000000000000000000000000..571a0d2bc886a7ea4c06196b2f52e740c2ed6e9f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/rrule.py @@ -0,0 +1,1737 @@ +# -*- coding: utf-8 -*- +""" +The rrule module offers a small, complete, and very fast, implementation of +the recurrence rules documented in the +`iCalendar RFC `_, +including support for caching of results. +""" +import calendar +import datetime +import heapq +import itertools +import re +import sys +from functools import wraps +# For warning about deprecation of until and count +from warnings import warn + +from six import advance_iterator, integer_types + +from six.moves import _thread, range + +from ._common import weekday as weekdaybase + +try: + from math import gcd +except ImportError: + from fractions import gcd + +__all__ = ["rrule", "rruleset", "rrulestr", + "YEARLY", "MONTHLY", "WEEKLY", "DAILY", + "HOURLY", "MINUTELY", "SECONDLY", + "MO", "TU", "WE", "TH", "FR", "SA", "SU"] + +# Every mask is 7 days longer to handle cross-year weekly periods. +M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 + + [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) +M365MASK = list(M366MASK) +M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) +MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) +MDAY365MASK = list(MDAY366MASK) +M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) +NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) +NMDAY365MASK = list(NMDAY366MASK) +M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) +M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) +WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 +del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] +MDAY365MASK = tuple(MDAY365MASK) +M365MASK = tuple(M365MASK) + +FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY'] + +(YEARLY, + MONTHLY, + WEEKLY, + DAILY, + HOURLY, + MINUTELY, + SECONDLY) = list(range(7)) + +# Imported on demand. +easter = None +parser = None + + +class weekday(weekdaybase): + """ + This version of weekday does not allow n = 0. + """ + def __init__(self, wkday, n=None): + if n == 0: + raise ValueError("Can't create weekday with n==0") + + super(weekday, self).__init__(wkday, n) + + +MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) + + +def _invalidates_cache(f): + """ + Decorator for rruleset methods which may invalidate the + cached length. + """ + @wraps(f) + def inner_func(self, *args, **kwargs): + rv = f(self, *args, **kwargs) + self._invalidate_cache() + return rv + + return inner_func + + +class rrulebase(object): + def __init__(self, cache=False): + if cache: + self._cache = [] + self._cache_lock = _thread.allocate_lock() + self._invalidate_cache() + else: + self._cache = None + self._cache_complete = False + self._len = None + + def __iter__(self): + if self._cache_complete: + return iter(self._cache) + elif self._cache is None: + return self._iter() + else: + return self._iter_cached() + + def _invalidate_cache(self): + if self._cache is not None: + self._cache = [] + self._cache_complete = False + self._cache_gen = self._iter() + + if self._cache_lock.locked(): + self._cache_lock.release() + + self._len = None + + def _iter_cached(self): + i = 0 + gen = self._cache_gen + cache = self._cache + acquire = self._cache_lock.acquire + release = self._cache_lock.release + while gen: + if i == len(cache): + acquire() + if self._cache_complete: + break + try: + for j in range(10): + cache.append(advance_iterator(gen)) + except StopIteration: + self._cache_gen = gen = None + self._cache_complete = True + break + release() + yield cache[i] + i += 1 + while i < self._len: + yield cache[i] + i += 1 + + def __getitem__(self, item): + if self._cache_complete: + return self._cache[item] + elif isinstance(item, slice): + if item.step and item.step < 0: + return list(iter(self))[item] + else: + return list(itertools.islice(self, + item.start or 0, + item.stop or sys.maxsize, + item.step or 1)) + elif item >= 0: + gen = iter(self) + try: + for i in range(item+1): + res = advance_iterator(gen) + except StopIteration: + raise IndexError + return res + else: + return list(iter(self))[item] + + def __contains__(self, item): + if self._cache_complete: + return item in self._cache + else: + for i in self: + if i == item: + return True + elif i > item: + return False + return False + + # __len__() introduces a large performance penalty. + def count(self): + """ Returns the number of recurrences in this set. It will have go + through the whole recurrence, if this hasn't been done before. """ + if self._len is None: + for x in self: + pass + return self._len + + def before(self, dt, inc=False): + """ Returns the last recurrence before the given datetime instance. The + inc keyword defines what happens if dt is an occurrence. With + inc=True, if dt itself is an occurrence, it will be returned. """ + if self._cache_complete: + gen = self._cache + else: + gen = self + last = None + if inc: + for i in gen: + if i > dt: + break + last = i + else: + for i in gen: + if i >= dt: + break + last = i + return last + + def after(self, dt, inc=False): + """ Returns the first recurrence after the given datetime instance. The + inc keyword defines what happens if dt is an occurrence. With + inc=True, if dt itself is an occurrence, it will be returned. """ + if self._cache_complete: + gen = self._cache + else: + gen = self + if inc: + for i in gen: + if i >= dt: + return i + else: + for i in gen: + if i > dt: + return i + return None + + def xafter(self, dt, count=None, inc=False): + """ + Generator which yields up to `count` recurrences after the given + datetime instance, equivalent to `after`. + + :param dt: + The datetime at which to start generating recurrences. + + :param count: + The maximum number of recurrences to generate. If `None` (default), + dates are generated until the recurrence rule is exhausted. + + :param inc: + If `dt` is an instance of the rule and `inc` is `True`, it is + included in the output. + + :yields: Yields a sequence of `datetime` objects. + """ + + if self._cache_complete: + gen = self._cache + else: + gen = self + + # Select the comparison function + if inc: + comp = lambda dc, dtc: dc >= dtc + else: + comp = lambda dc, dtc: dc > dtc + + # Generate dates + n = 0 + for d in gen: + if comp(d, dt): + if count is not None: + n += 1 + if n > count: + break + + yield d + + def between(self, after, before, inc=False, count=1): + """ Returns all the occurrences of the rrule between after and before. + The inc keyword defines what happens if after and/or before are + themselves occurrences. With inc=True, they will be included in the + list, if they are found in the recurrence set. """ + if self._cache_complete: + gen = self._cache + else: + gen = self + started = False + l = [] + if inc: + for i in gen: + if i > before: + break + elif not started: + if i >= after: + started = True + l.append(i) + else: + l.append(i) + else: + for i in gen: + if i >= before: + break + elif not started: + if i > after: + started = True + l.append(i) + else: + l.append(i) + return l + + +class rrule(rrulebase): + """ + That's the base of the rrule operation. It accepts all the keywords + defined in the RFC as its constructor parameters (except byday, + which was renamed to byweekday) and more. The constructor prototype is:: + + rrule(freq) + + Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, + or SECONDLY. + + .. note:: + Per RFC section 3.3.10, recurrence instances falling on invalid dates + and times are ignored rather than coerced: + + Recurrence rules may generate recurrence instances with an invalid + date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM + on a day where the local time is moved forward by an hour at 1:00 + AM). Such recurrence instances MUST be ignored and MUST NOT be + counted as part of the recurrence set. + + This can lead to possibly surprising behavior when, for example, the + start date occurs at the end of the month: + + >>> from dateutil.rrule import rrule, MONTHLY + >>> from datetime import datetime + >>> start_date = datetime(2014, 12, 31) + >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date)) + ... # doctest: +NORMALIZE_WHITESPACE + [datetime.datetime(2014, 12, 31, 0, 0), + datetime.datetime(2015, 1, 31, 0, 0), + datetime.datetime(2015, 3, 31, 0, 0), + datetime.datetime(2015, 5, 31, 0, 0)] + + Additionally, it supports the following keyword arguments: + + :param dtstart: + The recurrence start. Besides being the base for the recurrence, + missing parameters in the final recurrence instances will also be + extracted from this date. If not given, datetime.now() will be used + instead. + :param interval: + The interval between each freq iteration. For example, when using + YEARLY, an interval of 2 means once every two years, but with HOURLY, + it means once every two hours. The default interval is 1. + :param wkst: + The week start day. Must be one of the MO, TU, WE constants, or an + integer, specifying the first day of the week. This will affect + recurrences based on weekly periods. The default week start is got + from calendar.firstweekday(), and may be modified by + calendar.setfirstweekday(). + :param count: + If given, this determines how many occurrences will be generated. + + .. note:: + As of version 2.5.0, the use of the keyword ``until`` in conjunction + with ``count`` is deprecated, to make sure ``dateutil`` is fully + compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` + **must not** occur in the same call to ``rrule``. + :param until: + If given, this must be a datetime instance specifying the upper-bound + limit of the recurrence. The last recurrence in the rule is the greatest + datetime that is less than or equal to the value specified in the + ``until`` parameter. + + .. note:: + As of version 2.5.0, the use of the keyword ``until`` in conjunction + with ``count`` is deprecated, to make sure ``dateutil`` is fully + compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` + **must not** occur in the same call to ``rrule``. + :param bysetpos: + If given, it must be either an integer, or a sequence of integers, + positive or negative. Each given integer will specify an occurrence + number, corresponding to the nth occurrence of the rule inside the + frequency period. For example, a bysetpos of -1 if combined with a + MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will + result in the last work day of every month. + :param bymonth: + If given, it must be either an integer, or a sequence of integers, + meaning the months to apply the recurrence to. + :param bymonthday: + If given, it must be either an integer, or a sequence of integers, + meaning the month days to apply the recurrence to. + :param byyearday: + If given, it must be either an integer, or a sequence of integers, + meaning the year days to apply the recurrence to. + :param byeaster: + If given, it must be either an integer, or a sequence of integers, + positive or negative. Each integer will define an offset from the + Easter Sunday. Passing the offset 0 to byeaster will yield the Easter + Sunday itself. This is an extension to the RFC specification. + :param byweekno: + If given, it must be either an integer, or a sequence of integers, + meaning the week numbers to apply the recurrence to. Week numbers + have the meaning described in ISO8601, that is, the first week of + the year is that containing at least four days of the new year. + :param byweekday: + If given, it must be either an integer (0 == MO), a sequence of + integers, one of the weekday constants (MO, TU, etc), or a sequence + of these constants. When given, these variables will define the + weekdays where the recurrence will be applied. It's also possible to + use an argument n for the weekday instances, which will mean the nth + occurrence of this weekday in the period. For example, with MONTHLY, + or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the + first friday of the month where the recurrence happens. Notice that in + the RFC documentation, this is specified as BYDAY, but was renamed to + avoid the ambiguity of that keyword. + :param byhour: + If given, it must be either an integer, or a sequence of integers, + meaning the hours to apply the recurrence to. + :param byminute: + If given, it must be either an integer, or a sequence of integers, + meaning the minutes to apply the recurrence to. + :param bysecond: + If given, it must be either an integer, or a sequence of integers, + meaning the seconds to apply the recurrence to. + :param cache: + If given, it must be a boolean value specifying to enable or disable + caching of results. If you will use the same rrule instance multiple + times, enabling caching will improve the performance considerably. + """ + def __init__(self, freq, dtstart=None, + interval=1, wkst=None, count=None, until=None, bysetpos=None, + bymonth=None, bymonthday=None, byyearday=None, byeaster=None, + byweekno=None, byweekday=None, + byhour=None, byminute=None, bysecond=None, + cache=False): + super(rrule, self).__init__(cache) + global easter + if not dtstart: + if until and until.tzinfo: + dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0) + else: + dtstart = datetime.datetime.now().replace(microsecond=0) + elif not isinstance(dtstart, datetime.datetime): + dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) + else: + dtstart = dtstart.replace(microsecond=0) + self._dtstart = dtstart + self._tzinfo = dtstart.tzinfo + self._freq = freq + self._interval = interval + self._count = count + + # Cache the original byxxx rules, if they are provided, as the _byxxx + # attributes do not necessarily map to the inputs, and this can be + # a problem in generating the strings. Only store things if they've + # been supplied (the string retrieval will just use .get()) + self._original_rule = {} + + if until and not isinstance(until, datetime.datetime): + until = datetime.datetime.fromordinal(until.toordinal()) + self._until = until + + if self._dtstart and self._until: + if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None): + # According to RFC5545 Section 3.3.10: + # https://tools.ietf.org/html/rfc5545#section-3.3.10 + # + # > If the "DTSTART" property is specified as a date with UTC + # > time or a date with local time and time zone reference, + # > then the UNTIL rule part MUST be specified as a date with + # > UTC time. + raise ValueError( + 'RRULE UNTIL values must be specified in UTC when DTSTART ' + 'is timezone-aware' + ) + + if count is not None and until: + warn("Using both 'count' and 'until' is inconsistent with RFC 5545" + " and has been deprecated in dateutil. Future versions will " + "raise an error.", DeprecationWarning) + + if wkst is None: + self._wkst = calendar.firstweekday() + elif isinstance(wkst, integer_types): + self._wkst = wkst + else: + self._wkst = wkst.weekday + + if bysetpos is None: + self._bysetpos = None + elif isinstance(bysetpos, integer_types): + if bysetpos == 0 or not (-366 <= bysetpos <= 366): + raise ValueError("bysetpos must be between 1 and 366, " + "or between -366 and -1") + self._bysetpos = (bysetpos,) + else: + self._bysetpos = tuple(bysetpos) + for pos in self._bysetpos: + if pos == 0 or not (-366 <= pos <= 366): + raise ValueError("bysetpos must be between 1 and 366, " + "or between -366 and -1") + + if self._bysetpos: + self._original_rule['bysetpos'] = self._bysetpos + + if (byweekno is None and byyearday is None and bymonthday is None and + byweekday is None and byeaster is None): + if freq == YEARLY: + if bymonth is None: + bymonth = dtstart.month + self._original_rule['bymonth'] = None + bymonthday = dtstart.day + self._original_rule['bymonthday'] = None + elif freq == MONTHLY: + bymonthday = dtstart.day + self._original_rule['bymonthday'] = None + elif freq == WEEKLY: + byweekday = dtstart.weekday() + self._original_rule['byweekday'] = None + + # bymonth + if bymonth is None: + self._bymonth = None + else: + if isinstance(bymonth, integer_types): + bymonth = (bymonth,) + + self._bymonth = tuple(sorted(set(bymonth))) + + if 'bymonth' not in self._original_rule: + self._original_rule['bymonth'] = self._bymonth + + # byyearday + if byyearday is None: + self._byyearday = None + else: + if isinstance(byyearday, integer_types): + byyearday = (byyearday,) + + self._byyearday = tuple(sorted(set(byyearday))) + self._original_rule['byyearday'] = self._byyearday + + # byeaster + if byeaster is not None: + if not easter: + from dateutil import easter + if isinstance(byeaster, integer_types): + self._byeaster = (byeaster,) + else: + self._byeaster = tuple(sorted(byeaster)) + + self._original_rule['byeaster'] = self._byeaster + else: + self._byeaster = None + + # bymonthday + if bymonthday is None: + self._bymonthday = () + self._bynmonthday = () + else: + if isinstance(bymonthday, integer_types): + bymonthday = (bymonthday,) + + bymonthday = set(bymonthday) # Ensure it's unique + + self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0)) + self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0)) + + # Storing positive numbers first, then negative numbers + if 'bymonthday' not in self._original_rule: + self._original_rule['bymonthday'] = tuple( + itertools.chain(self._bymonthday, self._bynmonthday)) + + # byweekno + if byweekno is None: + self._byweekno = None + else: + if isinstance(byweekno, integer_types): + byweekno = (byweekno,) + + self._byweekno = tuple(sorted(set(byweekno))) + + self._original_rule['byweekno'] = self._byweekno + + # byweekday / bynweekday + if byweekday is None: + self._byweekday = None + self._bynweekday = None + else: + # If it's one of the valid non-sequence types, convert to a + # single-element sequence before the iterator that builds the + # byweekday set. + if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"): + byweekday = (byweekday,) + + self._byweekday = set() + self._bynweekday = set() + for wday in byweekday: + if isinstance(wday, integer_types): + self._byweekday.add(wday) + elif not wday.n or freq > MONTHLY: + self._byweekday.add(wday.weekday) + else: + self._bynweekday.add((wday.weekday, wday.n)) + + if not self._byweekday: + self._byweekday = None + elif not self._bynweekday: + self._bynweekday = None + + if self._byweekday is not None: + self._byweekday = tuple(sorted(self._byweekday)) + orig_byweekday = [weekday(x) for x in self._byweekday] + else: + orig_byweekday = () + + if self._bynweekday is not None: + self._bynweekday = tuple(sorted(self._bynweekday)) + orig_bynweekday = [weekday(*x) for x in self._bynweekday] + else: + orig_bynweekday = () + + if 'byweekday' not in self._original_rule: + self._original_rule['byweekday'] = tuple(itertools.chain( + orig_byweekday, orig_bynweekday)) + + # byhour + if byhour is None: + if freq < HOURLY: + self._byhour = {dtstart.hour} + else: + self._byhour = None + else: + if isinstance(byhour, integer_types): + byhour = (byhour,) + + if freq == HOURLY: + self._byhour = self.__construct_byset(start=dtstart.hour, + byxxx=byhour, + base=24) + else: + self._byhour = set(byhour) + + self._byhour = tuple(sorted(self._byhour)) + self._original_rule['byhour'] = self._byhour + + # byminute + if byminute is None: + if freq < MINUTELY: + self._byminute = {dtstart.minute} + else: + self._byminute = None + else: + if isinstance(byminute, integer_types): + byminute = (byminute,) + + if freq == MINUTELY: + self._byminute = self.__construct_byset(start=dtstart.minute, + byxxx=byminute, + base=60) + else: + self._byminute = set(byminute) + + self._byminute = tuple(sorted(self._byminute)) + self._original_rule['byminute'] = self._byminute + + # bysecond + if bysecond is None: + if freq < SECONDLY: + self._bysecond = ((dtstart.second,)) + else: + self._bysecond = None + else: + if isinstance(bysecond, integer_types): + bysecond = (bysecond,) + + self._bysecond = set(bysecond) + + if freq == SECONDLY: + self._bysecond = self.__construct_byset(start=dtstart.second, + byxxx=bysecond, + base=60) + else: + self._bysecond = set(bysecond) + + self._bysecond = tuple(sorted(self._bysecond)) + self._original_rule['bysecond'] = self._bysecond + + if self._freq >= HOURLY: + self._timeset = None + else: + self._timeset = [] + for hour in self._byhour: + for minute in self._byminute: + for second in self._bysecond: + self._timeset.append( + datetime.time(hour, minute, second, + tzinfo=self._tzinfo)) + self._timeset.sort() + self._timeset = tuple(self._timeset) + + def __str__(self): + """ + Output a string that would generate this RRULE if passed to rrulestr. + This is mostly compatible with RFC5545, except for the + dateutil-specific extension BYEASTER. + """ + + output = [] + h, m, s = [None] * 3 + if self._dtstart: + output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S')) + h, m, s = self._dtstart.timetuple()[3:6] + + parts = ['FREQ=' + FREQNAMES[self._freq]] + if self._interval != 1: + parts.append('INTERVAL=' + str(self._interval)) + + if self._wkst: + parts.append('WKST=' + repr(weekday(self._wkst))[0:2]) + + if self._count is not None: + parts.append('COUNT=' + str(self._count)) + + if self._until: + parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S')) + + if self._original_rule.get('byweekday') is not None: + # The str() method on weekday objects doesn't generate + # RFC5545-compliant strings, so we should modify that. + original_rule = dict(self._original_rule) + wday_strings = [] + for wday in original_rule['byweekday']: + if wday.n: + wday_strings.append('{n:+d}{wday}'.format( + n=wday.n, + wday=repr(wday)[0:2])) + else: + wday_strings.append(repr(wday)) + + original_rule['byweekday'] = wday_strings + else: + original_rule = self._original_rule + + partfmt = '{name}={vals}' + for name, key in [('BYSETPOS', 'bysetpos'), + ('BYMONTH', 'bymonth'), + ('BYMONTHDAY', 'bymonthday'), + ('BYYEARDAY', 'byyearday'), + ('BYWEEKNO', 'byweekno'), + ('BYDAY', 'byweekday'), + ('BYHOUR', 'byhour'), + ('BYMINUTE', 'byminute'), + ('BYSECOND', 'bysecond'), + ('BYEASTER', 'byeaster')]: + value = original_rule.get(key) + if value: + parts.append(partfmt.format(name=name, vals=(','.join(str(v) + for v in value)))) + + output.append('RRULE:' + ';'.join(parts)) + return '\n'.join(output) + + def replace(self, **kwargs): + """Return new rrule with same attributes except for those attributes given new + values by whichever keyword arguments are specified.""" + new_kwargs = {"interval": self._interval, + "count": self._count, + "dtstart": self._dtstart, + "freq": self._freq, + "until": self._until, + "wkst": self._wkst, + "cache": False if self._cache is None else True } + new_kwargs.update(self._original_rule) + new_kwargs.update(kwargs) + return rrule(**new_kwargs) + + def _iter(self): + year, month, day, hour, minute, second, weekday, yearday, _ = \ + self._dtstart.timetuple() + + # Some local variables to speed things up a bit + freq = self._freq + interval = self._interval + wkst = self._wkst + until = self._until + bymonth = self._bymonth + byweekno = self._byweekno + byyearday = self._byyearday + byweekday = self._byweekday + byeaster = self._byeaster + bymonthday = self._bymonthday + bynmonthday = self._bynmonthday + bysetpos = self._bysetpos + byhour = self._byhour + byminute = self._byminute + bysecond = self._bysecond + + ii = _iterinfo(self) + ii.rebuild(year, month) + + getdayset = {YEARLY: ii.ydayset, + MONTHLY: ii.mdayset, + WEEKLY: ii.wdayset, + DAILY: ii.ddayset, + HOURLY: ii.ddayset, + MINUTELY: ii.ddayset, + SECONDLY: ii.ddayset}[freq] + + if freq < HOURLY: + timeset = self._timeset + else: + gettimeset = {HOURLY: ii.htimeset, + MINUTELY: ii.mtimeset, + SECONDLY: ii.stimeset}[freq] + if ((freq >= HOURLY and + self._byhour and hour not in self._byhour) or + (freq >= MINUTELY and + self._byminute and minute not in self._byminute) or + (freq >= SECONDLY and + self._bysecond and second not in self._bysecond)): + timeset = () + else: + timeset = gettimeset(hour, minute, second) + + total = 0 + count = self._count + while True: + # Get dayset with the right frequency + dayset, start, end = getdayset(year, month, day) + + # Do the "hard" work ;-) + filtered = False + for i in dayset[start:end]: + if ((bymonth and ii.mmask[i] not in bymonth) or + (byweekno and not ii.wnomask[i]) or + (byweekday and ii.wdaymask[i] not in byweekday) or + (ii.nwdaymask and not ii.nwdaymask[i]) or + (byeaster and not ii.eastermask[i]) or + ((bymonthday or bynmonthday) and + ii.mdaymask[i] not in bymonthday and + ii.nmdaymask[i] not in bynmonthday) or + (byyearday and + ((i < ii.yearlen and i+1 not in byyearday and + -ii.yearlen+i not in byyearday) or + (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and + -ii.nextyearlen+i-ii.yearlen not in byyearday)))): + dayset[i] = None + filtered = True + + # Output results + if bysetpos and timeset: + poslist = [] + for pos in bysetpos: + if pos < 0: + daypos, timepos = divmod(pos, len(timeset)) + else: + daypos, timepos = divmod(pos-1, len(timeset)) + try: + i = [x for x in dayset[start:end] + if x is not None][daypos] + time = timeset[timepos] + except IndexError: + pass + else: + date = datetime.date.fromordinal(ii.yearordinal+i) + res = datetime.datetime.combine(date, time) + if res not in poslist: + poslist.append(res) + poslist.sort() + for res in poslist: + if until and res > until: + self._len = total + return + elif res >= self._dtstart: + if count is not None: + count -= 1 + if count < 0: + self._len = total + return + total += 1 + yield res + else: + for i in dayset[start:end]: + if i is not None: + date = datetime.date.fromordinal(ii.yearordinal + i) + for time in timeset: + res = datetime.datetime.combine(date, time) + if until and res > until: + self._len = total + return + elif res >= self._dtstart: + if count is not None: + count -= 1 + if count < 0: + self._len = total + return + + total += 1 + yield res + + # Handle frequency and interval + fixday = False + if freq == YEARLY: + year += interval + if year > datetime.MAXYEAR: + self._len = total + return + ii.rebuild(year, month) + elif freq == MONTHLY: + month += interval + if month > 12: + div, mod = divmod(month, 12) + month = mod + year += div + if month == 0: + month = 12 + year -= 1 + if year > datetime.MAXYEAR: + self._len = total + return + ii.rebuild(year, month) + elif freq == WEEKLY: + if wkst > weekday: + day += -(weekday+1+(6-wkst))+self._interval*7 + else: + day += -(weekday-wkst)+self._interval*7 + weekday = wkst + fixday = True + elif freq == DAILY: + day += interval + fixday = True + elif freq == HOURLY: + if filtered: + # Jump to one iteration before next day + hour += ((23-hour)//interval)*interval + + if byhour: + ndays, hour = self.__mod_distance(value=hour, + byxxx=self._byhour, + base=24) + else: + ndays, hour = divmod(hour+interval, 24) + + if ndays: + day += ndays + fixday = True + + timeset = gettimeset(hour, minute, second) + elif freq == MINUTELY: + if filtered: + # Jump to one iteration before next day + minute += ((1439-(hour*60+minute))//interval)*interval + + valid = False + rep_rate = (24*60) + for j in range(rep_rate // gcd(interval, rep_rate)): + if byminute: + nhours, minute = \ + self.__mod_distance(value=minute, + byxxx=self._byminute, + base=60) + else: + nhours, minute = divmod(minute+interval, 60) + + div, hour = divmod(hour+nhours, 24) + if div: + day += div + fixday = True + filtered = False + + if not byhour or hour in byhour: + valid = True + break + + if not valid: + raise ValueError('Invalid combination of interval and ' + + 'byhour resulting in empty rule.') + + timeset = gettimeset(hour, minute, second) + elif freq == SECONDLY: + if filtered: + # Jump to one iteration before next day + second += (((86399 - (hour * 3600 + minute * 60 + second)) + // interval) * interval) + + rep_rate = (24 * 3600) + valid = False + for j in range(0, rep_rate // gcd(interval, rep_rate)): + if bysecond: + nminutes, second = \ + self.__mod_distance(value=second, + byxxx=self._bysecond, + base=60) + else: + nminutes, second = divmod(second+interval, 60) + + div, minute = divmod(minute+nminutes, 60) + if div: + hour += div + div, hour = divmod(hour, 24) + if div: + day += div + fixday = True + + if ((not byhour or hour in byhour) and + (not byminute or minute in byminute) and + (not bysecond or second in bysecond)): + valid = True + break + + if not valid: + raise ValueError('Invalid combination of interval, ' + + 'byhour and byminute resulting in empty' + + ' rule.') + + timeset = gettimeset(hour, minute, second) + + if fixday and day > 28: + daysinmonth = calendar.monthrange(year, month)[1] + if day > daysinmonth: + while day > daysinmonth: + day -= daysinmonth + month += 1 + if month == 13: + month = 1 + year += 1 + if year > datetime.MAXYEAR: + self._len = total + return + daysinmonth = calendar.monthrange(year, month)[1] + ii.rebuild(year, month) + + def __construct_byset(self, start, byxxx, base): + """ + If a `BYXXX` sequence is passed to the constructor at the same level as + `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some + specifications which cannot be reached given some starting conditions. + + This occurs whenever the interval is not coprime with the base of a + given unit and the difference between the starting position and the + ending position is not coprime with the greatest common denominator + between the interval and the base. For example, with a FREQ of hourly + starting at 17:00 and an interval of 4, the only valid values for + BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not + coprime. + + :param start: + Specifies the starting position. + :param byxxx: + An iterable containing the list of allowed values. + :param base: + The largest allowable value for the specified frequency (e.g. + 24 hours, 60 minutes). + + This does not preserve the type of the iterable, returning a set, since + the values should be unique and the order is irrelevant, this will + speed up later lookups. + + In the event of an empty set, raises a :exception:`ValueError`, as this + results in an empty rrule. + """ + + cset = set() + + # Support a single byxxx value. + if isinstance(byxxx, integer_types): + byxxx = (byxxx, ) + + for num in byxxx: + i_gcd = gcd(self._interval, base) + # Use divmod rather than % because we need to wrap negative nums. + if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0: + cset.add(num) + + if len(cset) == 0: + raise ValueError("Invalid rrule byxxx generates an empty set.") + + return cset + + def __mod_distance(self, value, byxxx, base): + """ + Calculates the next value in a sequence where the `FREQ` parameter is + specified along with a `BYXXX` parameter at the same "level" + (e.g. `HOURLY` specified with `BYHOUR`). + + :param value: + The old value of the component. + :param byxxx: + The `BYXXX` set, which should have been generated by + `rrule._construct_byset`, or something else which checks that a + valid rule is present. + :param base: + The largest allowable value for the specified frequency (e.g. + 24 hours, 60 minutes). + + If a valid value is not found after `base` iterations (the maximum + number before the sequence would start to repeat), this raises a + :exception:`ValueError`, as no valid values were found. + + This returns a tuple of `divmod(n*interval, base)`, where `n` is the + smallest number of `interval` repetitions until the next specified + value in `byxxx` is found. + """ + accumulator = 0 + for ii in range(1, base + 1): + # Using divmod() over % to account for negative intervals + div, value = divmod(value + self._interval, base) + accumulator += div + if value in byxxx: + return (accumulator, value) + + +class _iterinfo(object): + __slots__ = ["rrule", "lastyear", "lastmonth", + "yearlen", "nextyearlen", "yearordinal", "yearweekday", + "mmask", "mrange", "mdaymask", "nmdaymask", + "wdaymask", "wnomask", "nwdaymask", "eastermask"] + + def __init__(self, rrule): + for attr in self.__slots__: + setattr(self, attr, None) + self.rrule = rrule + + def rebuild(self, year, month): + # Every mask is 7 days longer to handle cross-year weekly periods. + rr = self.rrule + if year != self.lastyear: + self.yearlen = 365 + calendar.isleap(year) + self.nextyearlen = 365 + calendar.isleap(year + 1) + firstyday = datetime.date(year, 1, 1) + self.yearordinal = firstyday.toordinal() + self.yearweekday = firstyday.weekday() + + wday = datetime.date(year, 1, 1).weekday() + if self.yearlen == 365: + self.mmask = M365MASK + self.mdaymask = MDAY365MASK + self.nmdaymask = NMDAY365MASK + self.wdaymask = WDAYMASK[wday:] + self.mrange = M365RANGE + else: + self.mmask = M366MASK + self.mdaymask = MDAY366MASK + self.nmdaymask = NMDAY366MASK + self.wdaymask = WDAYMASK[wday:] + self.mrange = M366RANGE + + if not rr._byweekno: + self.wnomask = None + else: + self.wnomask = [0]*(self.yearlen+7) + # no1wkst = firstwkst = self.wdaymask.index(rr._wkst) + no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7 + if no1wkst >= 4: + no1wkst = 0 + # Number of days in the year, plus the days we got + # from last year. + wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7 + else: + # Number of days in the year, minus the days we + # left in last year. + wyearlen = self.yearlen-no1wkst + div, mod = divmod(wyearlen, 7) + numweeks = div+mod//4 + for n in rr._byweekno: + if n < 0: + n += numweeks+1 + if not (0 < n <= numweeks): + continue + if n > 1: + i = no1wkst+(n-1)*7 + if no1wkst != firstwkst: + i -= 7-firstwkst + else: + i = no1wkst + for j in range(7): + self.wnomask[i] = 1 + i += 1 + if self.wdaymask[i] == rr._wkst: + break + if 1 in rr._byweekno: + # Check week number 1 of next year as well + # TODO: Check -numweeks for next year. + i = no1wkst+numweeks*7 + if no1wkst != firstwkst: + i -= 7-firstwkst + if i < self.yearlen: + # If week starts in next year, we + # don't care about it. + for j in range(7): + self.wnomask[i] = 1 + i += 1 + if self.wdaymask[i] == rr._wkst: + break + if no1wkst: + # Check last week number of last year as + # well. If no1wkst is 0, either the year + # started on week start, or week number 1 + # got days from last year, so there are no + # days from last year's last week number in + # this year. + if -1 not in rr._byweekno: + lyearweekday = datetime.date(year-1, 1, 1).weekday() + lno1wkst = (7-lyearweekday+rr._wkst) % 7 + lyearlen = 365+calendar.isleap(year-1) + if lno1wkst >= 4: + lno1wkst = 0 + lnumweeks = 52+(lyearlen + + (lyearweekday-rr._wkst) % 7) % 7//4 + else: + lnumweeks = 52+(self.yearlen-no1wkst) % 7//4 + else: + lnumweeks = -1 + if lnumweeks in rr._byweekno: + for i in range(no1wkst): + self.wnomask[i] = 1 + + if (rr._bynweekday and (month != self.lastmonth or + year != self.lastyear)): + ranges = [] + if rr._freq == YEARLY: + if rr._bymonth: + for month in rr._bymonth: + ranges.append(self.mrange[month-1:month+1]) + else: + ranges = [(0, self.yearlen)] + elif rr._freq == MONTHLY: + ranges = [self.mrange[month-1:month+1]] + if ranges: + # Weekly frequency won't get here, so we may not + # care about cross-year weekly periods. + self.nwdaymask = [0]*self.yearlen + for first, last in ranges: + last -= 1 + for wday, n in rr._bynweekday: + if n < 0: + i = last+(n+1)*7 + i -= (self.wdaymask[i]-wday) % 7 + else: + i = first+(n-1)*7 + i += (7-self.wdaymask[i]+wday) % 7 + if first <= i <= last: + self.nwdaymask[i] = 1 + + if rr._byeaster: + self.eastermask = [0]*(self.yearlen+7) + eyday = easter.easter(year).toordinal()-self.yearordinal + for offset in rr._byeaster: + self.eastermask[eyday+offset] = 1 + + self.lastyear = year + self.lastmonth = month + + def ydayset(self, year, month, day): + return list(range(self.yearlen)), 0, self.yearlen + + def mdayset(self, year, month, day): + dset = [None]*self.yearlen + start, end = self.mrange[month-1:month+1] + for i in range(start, end): + dset[i] = i + return dset, start, end + + def wdayset(self, year, month, day): + # We need to handle cross-year weeks here. + dset = [None]*(self.yearlen+7) + i = datetime.date(year, month, day).toordinal()-self.yearordinal + start = i + for j in range(7): + dset[i] = i + i += 1 + # if (not (0 <= i < self.yearlen) or + # self.wdaymask[i] == self.rrule._wkst): + # This will cross the year boundary, if necessary. + if self.wdaymask[i] == self.rrule._wkst: + break + return dset, start, i + + def ddayset(self, year, month, day): + dset = [None] * self.yearlen + i = datetime.date(year, month, day).toordinal() - self.yearordinal + dset[i] = i + return dset, i, i + 1 + + def htimeset(self, hour, minute, second): + tset = [] + rr = self.rrule + for minute in rr._byminute: + for second in rr._bysecond: + tset.append(datetime.time(hour, minute, second, + tzinfo=rr._tzinfo)) + tset.sort() + return tset + + def mtimeset(self, hour, minute, second): + tset = [] + rr = self.rrule + for second in rr._bysecond: + tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) + tset.sort() + return tset + + def stimeset(self, hour, minute, second): + return (datetime.time(hour, minute, second, + tzinfo=self.rrule._tzinfo),) + + +class rruleset(rrulebase): + """ The rruleset type allows more complex recurrence setups, mixing + multiple rules, dates, exclusion rules, and exclusion dates. The type + constructor takes the following keyword arguments: + + :param cache: If True, caching of results will be enabled, improving + performance of multiple queries considerably. """ + + class _genitem(object): + def __init__(self, genlist, gen): + try: + self.dt = advance_iterator(gen) + genlist.append(self) + except StopIteration: + pass + self.genlist = genlist + self.gen = gen + + def __next__(self): + try: + self.dt = advance_iterator(self.gen) + except StopIteration: + if self.genlist[0] is self: + heapq.heappop(self.genlist) + else: + self.genlist.remove(self) + heapq.heapify(self.genlist) + + next = __next__ + + def __lt__(self, other): + return self.dt < other.dt + + def __gt__(self, other): + return self.dt > other.dt + + def __eq__(self, other): + return self.dt == other.dt + + def __ne__(self, other): + return self.dt != other.dt + + def __init__(self, cache=False): + super(rruleset, self).__init__(cache) + self._rrule = [] + self._rdate = [] + self._exrule = [] + self._exdate = [] + + @_invalidates_cache + def rrule(self, rrule): + """ Include the given :py:class:`rrule` instance in the recurrence set + generation. """ + self._rrule.append(rrule) + + @_invalidates_cache + def rdate(self, rdate): + """ Include the given :py:class:`datetime` instance in the recurrence + set generation. """ + self._rdate.append(rdate) + + @_invalidates_cache + def exrule(self, exrule): + """ Include the given rrule instance in the recurrence set exclusion + list. Dates which are part of the given recurrence rules will not + be generated, even if some inclusive rrule or rdate matches them. + """ + self._exrule.append(exrule) + + @_invalidates_cache + def exdate(self, exdate): + """ Include the given datetime instance in the recurrence set + exclusion list. Dates included that way will not be generated, + even if some inclusive rrule or rdate matches them. """ + self._exdate.append(exdate) + + def _iter(self): + rlist = [] + self._rdate.sort() + self._genitem(rlist, iter(self._rdate)) + for gen in [iter(x) for x in self._rrule]: + self._genitem(rlist, gen) + exlist = [] + self._exdate.sort() + self._genitem(exlist, iter(self._exdate)) + for gen in [iter(x) for x in self._exrule]: + self._genitem(exlist, gen) + lastdt = None + total = 0 + heapq.heapify(rlist) + heapq.heapify(exlist) + while rlist: + ritem = rlist[0] + if not lastdt or lastdt != ritem.dt: + while exlist and exlist[0] < ritem: + exitem = exlist[0] + advance_iterator(exitem) + if exlist and exlist[0] is exitem: + heapq.heapreplace(exlist, exitem) + if not exlist or ritem != exlist[0]: + total += 1 + yield ritem.dt + lastdt = ritem.dt + advance_iterator(ritem) + if rlist and rlist[0] is ritem: + heapq.heapreplace(rlist, ritem) + self._len = total + + + + +class _rrulestr(object): + """ Parses a string representation of a recurrence rule or set of + recurrence rules. + + :param s: + Required, a string defining one or more recurrence rules. + + :param dtstart: + If given, used as the default recurrence start if not specified in the + rule string. + + :param cache: + If set ``True`` caching of results will be enabled, improving + performance of multiple queries considerably. + + :param unfold: + If set ``True`` indicates that a rule string is split over more + than one line and should be joined before processing. + + :param forceset: + If set ``True`` forces a :class:`dateutil.rrule.rruleset` to + be returned. + + :param compatible: + If set ``True`` forces ``unfold`` and ``forceset`` to be ``True``. + + :param ignoretz: + If set ``True``, time zones in parsed strings are ignored and a naive + :class:`datetime.datetime` object is returned. + + :param tzids: + If given, a callable or mapping used to retrieve a + :class:`datetime.tzinfo` from a string representation. + Defaults to :func:`dateutil.tz.gettz`. + + :param tzinfos: + Additional time zone names / aliases which may be present in a string + representation. See :func:`dateutil.parser.parse` for more + information. + + :return: + Returns a :class:`dateutil.rrule.rruleset` or + :class:`dateutil.rrule.rrule` + """ + + _freq_map = {"YEARLY": YEARLY, + "MONTHLY": MONTHLY, + "WEEKLY": WEEKLY, + "DAILY": DAILY, + "HOURLY": HOURLY, + "MINUTELY": MINUTELY, + "SECONDLY": SECONDLY} + + _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, + "FR": 4, "SA": 5, "SU": 6} + + def _handle_int(self, rrkwargs, name, value, **kwargs): + rrkwargs[name.lower()] = int(value) + + def _handle_int_list(self, rrkwargs, name, value, **kwargs): + rrkwargs[name.lower()] = [int(x) for x in value.split(',')] + + _handle_INTERVAL = _handle_int + _handle_COUNT = _handle_int + _handle_BYSETPOS = _handle_int_list + _handle_BYMONTH = _handle_int_list + _handle_BYMONTHDAY = _handle_int_list + _handle_BYYEARDAY = _handle_int_list + _handle_BYEASTER = _handle_int_list + _handle_BYWEEKNO = _handle_int_list + _handle_BYHOUR = _handle_int_list + _handle_BYMINUTE = _handle_int_list + _handle_BYSECOND = _handle_int_list + + def _handle_FREQ(self, rrkwargs, name, value, **kwargs): + rrkwargs["freq"] = self._freq_map[value] + + def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): + global parser + if not parser: + from dateutil import parser + try: + rrkwargs["until"] = parser.parse(value, + ignoretz=kwargs.get("ignoretz"), + tzinfos=kwargs.get("tzinfos")) + except ValueError: + raise ValueError("invalid until date") + + def _handle_WKST(self, rrkwargs, name, value, **kwargs): + rrkwargs["wkst"] = self._weekday_map[value] + + def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs): + """ + Two ways to specify this: +1MO or MO(+1) + """ + l = [] + for wday in value.split(','): + if '(' in wday: + # If it's of the form TH(+1), etc. + splt = wday.split('(') + w = splt[0] + n = int(splt[1][:-1]) + elif len(wday): + # If it's of the form +1MO + for i in range(len(wday)): + if wday[i] not in '+-0123456789': + break + n = wday[:i] or None + w = wday[i:] + if n: + n = int(n) + else: + raise ValueError("Invalid (empty) BYDAY specification.") + + l.append(weekdays[self._weekday_map[w]](n)) + rrkwargs["byweekday"] = l + + _handle_BYDAY = _handle_BYWEEKDAY + + def _parse_rfc_rrule(self, line, + dtstart=None, + cache=False, + ignoretz=False, + tzinfos=None): + if line.find(':') != -1: + name, value = line.split(':') + if name != "RRULE": + raise ValueError("unknown parameter name") + else: + value = line + rrkwargs = {} + for pair in value.split(';'): + name, value = pair.split('=') + name = name.upper() + value = value.upper() + try: + getattr(self, "_handle_"+name)(rrkwargs, name, value, + ignoretz=ignoretz, + tzinfos=tzinfos) + except AttributeError: + raise ValueError("unknown parameter '%s'" % name) + except (KeyError, ValueError): + raise ValueError("invalid '%s': %s" % (name, value)) + return rrule(dtstart=dtstart, cache=cache, **rrkwargs) + + def _parse_date_value(self, date_value, parms, rule_tzids, + ignoretz, tzids, tzinfos): + global parser + if not parser: + from dateutil import parser + + datevals = [] + value_found = False + TZID = None + + for parm in parms: + if parm.startswith("TZID="): + try: + tzkey = rule_tzids[parm.split('TZID=')[-1]] + except KeyError: + continue + if tzids is None: + from . import tz + tzlookup = tz.gettz + elif callable(tzids): + tzlookup = tzids + else: + tzlookup = getattr(tzids, 'get', None) + if tzlookup is None: + msg = ('tzids must be a callable, mapping, or None, ' + 'not %s' % tzids) + raise ValueError(msg) + + TZID = tzlookup(tzkey) + continue + + # RFC 5445 3.8.2.4: The VALUE parameter is optional, but may be found + # only once. + if parm not in {"VALUE=DATE-TIME", "VALUE=DATE"}: + raise ValueError("unsupported parm: " + parm) + else: + if value_found: + msg = ("Duplicate value parameter found in: " + parm) + raise ValueError(msg) + value_found = True + + for datestr in date_value.split(','): + date = parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos) + if TZID is not None: + if date.tzinfo is None: + date = date.replace(tzinfo=TZID) + else: + raise ValueError('DTSTART/EXDATE specifies multiple timezone') + datevals.append(date) + + return datevals + + def _parse_rfc(self, s, + dtstart=None, + cache=False, + unfold=False, + forceset=False, + compatible=False, + ignoretz=False, + tzids=None, + tzinfos=None): + global parser + if compatible: + forceset = True + unfold = True + + TZID_NAMES = dict(map( + lambda x: (x.upper(), x), + re.findall('TZID=(?P[^:]+):', s) + )) + s = s.upper() + if not s.strip(): + raise ValueError("empty string") + if unfold: + lines = s.splitlines() + i = 0 + while i < len(lines): + line = lines[i].rstrip() + if not line: + del lines[i] + elif i > 0 and line[0] == " ": + lines[i-1] += line[1:] + del lines[i] + else: + i += 1 + else: + lines = s.split() + if (not forceset and len(lines) == 1 and (s.find(':') == -1 or + s.startswith('RRULE:'))): + return self._parse_rfc_rrule(lines[0], cache=cache, + dtstart=dtstart, ignoretz=ignoretz, + tzinfos=tzinfos) + else: + rrulevals = [] + rdatevals = [] + exrulevals = [] + exdatevals = [] + for line in lines: + if not line: + continue + if line.find(':') == -1: + name = "RRULE" + value = line + else: + name, value = line.split(':', 1) + parms = name.split(';') + if not parms: + raise ValueError("empty property name") + name = parms[0] + parms = parms[1:] + if name == "RRULE": + for parm in parms: + raise ValueError("unsupported RRULE parm: "+parm) + rrulevals.append(value) + elif name == "RDATE": + for parm in parms: + if parm != "VALUE=DATE-TIME": + raise ValueError("unsupported RDATE parm: "+parm) + rdatevals.append(value) + elif name == "EXRULE": + for parm in parms: + raise ValueError("unsupported EXRULE parm: "+parm) + exrulevals.append(value) + elif name == "EXDATE": + exdatevals.extend( + self._parse_date_value(value, parms, + TZID_NAMES, ignoretz, + tzids, tzinfos) + ) + elif name == "DTSTART": + dtvals = self._parse_date_value(value, parms, TZID_NAMES, + ignoretz, tzids, tzinfos) + if len(dtvals) != 1: + raise ValueError("Multiple DTSTART values specified:" + + value) + dtstart = dtvals[0] + else: + raise ValueError("unsupported property: "+name) + if (forceset or len(rrulevals) > 1 or rdatevals + or exrulevals or exdatevals): + if not parser and (rdatevals or exdatevals): + from dateutil import parser + rset = rruleset(cache=cache) + for value in rrulevals: + rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, + ignoretz=ignoretz, + tzinfos=tzinfos)) + for value in rdatevals: + for datestr in value.split(','): + rset.rdate(parser.parse(datestr, + ignoretz=ignoretz, + tzinfos=tzinfos)) + for value in exrulevals: + rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, + ignoretz=ignoretz, + tzinfos=tzinfos)) + for value in exdatevals: + rset.exdate(value) + if compatible and dtstart: + rset.rdate(dtstart) + return rset + else: + return self._parse_rfc_rrule(rrulevals[0], + dtstart=dtstart, + cache=cache, + ignoretz=ignoretz, + tzinfos=tzinfos) + + def __call__(self, s, **kwargs): + return self._parse_rfc(s, **kwargs) + + +rrulestr = _rrulestr() + +# vim:ts=4:sw=4:et diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.__common.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.__common.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.__common.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.__factories.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.__factories.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/.__factories.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/._tz.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/._tz.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/._tz.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/._win.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/._win.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/._win.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/__init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af1352c47292f4eebc5cae8da45641b5544558e3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +from .tz import * +from .tz import __doc__ + +__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", + "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz", + "enfold", "datetime_ambiguous", "datetime_exists", + "resolve_imaginary", "UTC", "DeprecatedTzFormatWarning"] + + +class DeprecatedTzFormatWarning(Warning): + """Warning raised when time zones are parsed from deprecated formats.""" diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/_common.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ac11831522b266114d5b68ee1da298e3aeb14a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/_common.py @@ -0,0 +1,419 @@ +from six import PY2 + +from functools import wraps + +from datetime import datetime, timedelta, tzinfo + + +ZERO = timedelta(0) + +__all__ = ['tzname_in_python2', 'enfold'] + + +def tzname_in_python2(namefunc): + """Change unicode output into bytestrings in Python 2 + + tzname() API changed in Python 3. It used to return bytes, but was changed + to unicode strings + """ + if PY2: + @wraps(namefunc) + def adjust_encoding(*args, **kwargs): + name = namefunc(*args, **kwargs) + if name is not None: + name = name.encode() + + return name + + return adjust_encoding + else: + return namefunc + + +# The following is adapted from Alexander Belopolsky's tz library +# https://github.com/abalkin/tz +if hasattr(datetime, 'fold'): + # This is the pre-python 3.6 fold situation + def enfold(dt, fold=1): + """ + Provides a unified interface for assigning the ``fold`` attribute to + datetimes both before and after the implementation of PEP-495. + + :param fold: + The value for the ``fold`` attribute in the returned datetime. This + should be either 0 or 1. + + :return: + Returns an object for which ``getattr(dt, 'fold', 0)`` returns + ``fold`` for all versions of Python. In versions prior to + Python 3.6, this is a ``_DatetimeWithFold`` object, which is a + subclass of :py:class:`datetime.datetime` with the ``fold`` + attribute added, if ``fold`` is 1. + + .. versionadded:: 2.6.0 + """ + return dt.replace(fold=fold) + +else: + class _DatetimeWithFold(datetime): + """ + This is a class designed to provide a PEP 495-compliant interface for + Python versions before 3.6. It is used only for dates in a fold, so + the ``fold`` attribute is fixed at ``1``. + + .. versionadded:: 2.6.0 + """ + __slots__ = () + + def replace(self, *args, **kwargs): + """ + Return a datetime with the same attributes, except for those + attributes given new values by whichever keyword arguments are + specified. Note that tzinfo=None can be specified to create a naive + datetime from an aware datetime with no conversion of date and time + data. + + This is reimplemented in ``_DatetimeWithFold`` because pypy3 will + return a ``datetime.datetime`` even if ``fold`` is unchanged. + """ + argnames = ( + 'year', 'month', 'day', 'hour', 'minute', 'second', + 'microsecond', 'tzinfo' + ) + + for arg, argname in zip(args, argnames): + if argname in kwargs: + raise TypeError('Duplicate argument: {}'.format(argname)) + + kwargs[argname] = arg + + for argname in argnames: + if argname not in kwargs: + kwargs[argname] = getattr(self, argname) + + dt_class = self.__class__ if kwargs.get('fold', 1) else datetime + + return dt_class(**kwargs) + + @property + def fold(self): + return 1 + + def enfold(dt, fold=1): + """ + Provides a unified interface for assigning the ``fold`` attribute to + datetimes both before and after the implementation of PEP-495. + + :param fold: + The value for the ``fold`` attribute in the returned datetime. This + should be either 0 or 1. + + :return: + Returns an object for which ``getattr(dt, 'fold', 0)`` returns + ``fold`` for all versions of Python. In versions prior to + Python 3.6, this is a ``_DatetimeWithFold`` object, which is a + subclass of :py:class:`datetime.datetime` with the ``fold`` + attribute added, if ``fold`` is 1. + + .. versionadded:: 2.6.0 + """ + if getattr(dt, 'fold', 0) == fold: + return dt + + args = dt.timetuple()[:6] + args += (dt.microsecond, dt.tzinfo) + + if fold: + return _DatetimeWithFold(*args) + else: + return datetime(*args) + + +def _validate_fromutc_inputs(f): + """ + The CPython version of ``fromutc`` checks that the input is a ``datetime`` + object and that ``self`` is attached as its ``tzinfo``. + """ + @wraps(f) + def fromutc(self, dt): + if not isinstance(dt, datetime): + raise TypeError("fromutc() requires a datetime argument") + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + return f(self, dt) + + return fromutc + + +class _tzinfo(tzinfo): + """ + Base class for all ``dateutil`` ``tzinfo`` objects. + """ + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + + dt = dt.replace(tzinfo=self) + + wall_0 = enfold(dt, fold=0) + wall_1 = enfold(dt, fold=1) + + same_offset = wall_0.utcoffset() == wall_1.utcoffset() + same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) + + return same_dt and not same_offset + + def _fold_status(self, dt_utc, dt_wall): + """ + Determine the fold status of a "wall" datetime, given a representation + of the same datetime as a (naive) UTC datetime. This is calculated based + on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all + datetimes, and that this offset is the actual number of hours separating + ``dt_utc`` and ``dt_wall``. + + :param dt_utc: + Representation of the datetime as UTC + + :param dt_wall: + Representation of the datetime as "wall time". This parameter must + either have a `fold` attribute or have a fold-naive + :class:`datetime.tzinfo` attached, otherwise the calculation may + fail. + """ + if self.is_ambiguous(dt_wall): + delta_wall = dt_wall - dt_utc + _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) + else: + _fold = 0 + + return _fold + + def _fold(self, dt): + return getattr(dt, 'fold', 0) + + def _fromutc(self, dt): + """ + Given a timezone-aware datetime in a given timezone, calculates a + timezone-aware datetime in a new timezone. + + Since this is the one time that we *know* we have an unambiguous + datetime object, we take this opportunity to determine whether the + datetime is ambiguous and in a "fold" state (e.g. if it's the first + occurrence, chronologically, of the ambiguous datetime). + + :param dt: + A timezone-aware :class:`datetime.datetime` object. + """ + + # Re-implement the algorithm from Python's datetime.py + dtoff = dt.utcoffset() + if dtoff is None: + raise ValueError("fromutc() requires a non-None utcoffset() " + "result") + + # The original datetime.py code assumes that `dst()` defaults to + # zero during ambiguous times. PEP 495 inverts this presumption, so + # for pre-PEP 495 versions of python, we need to tweak the algorithm. + dtdst = dt.dst() + if dtdst is None: + raise ValueError("fromutc() requires a non-None dst() result") + delta = dtoff - dtdst + + dt += delta + # Set fold=1 so we can default to being in the fold for + # ambiguous dates. + dtdst = enfold(dt, fold=1).dst() + if dtdst is None: + raise ValueError("fromutc(): dt.dst gave inconsistent " + "results; cannot convert") + return dt + dtdst + + @_validate_fromutc_inputs + def fromutc(self, dt): + """ + Given a timezone-aware datetime in a given timezone, calculates a + timezone-aware datetime in a new timezone. + + Since this is the one time that we *know* we have an unambiguous + datetime object, we take this opportunity to determine whether the + datetime is ambiguous and in a "fold" state (e.g. if it's the first + occurrence, chronologically, of the ambiguous datetime). + + :param dt: + A timezone-aware :class:`datetime.datetime` object. + """ + dt_wall = self._fromutc(dt) + + # Calculate the fold status given the two datetimes. + _fold = self._fold_status(dt, dt_wall) + + # Set the default fold value for ambiguous dates + return enfold(dt_wall, fold=_fold) + + +class tzrangebase(_tzinfo): + """ + This is an abstract base class for time zones represented by an annual + transition into and out of DST. Child classes should implement the following + methods: + + * ``__init__(self, *args, **kwargs)`` + * ``transitions(self, year)`` - this is expected to return a tuple of + datetimes representing the DST on and off transitions in standard + time. + + A fully initialized ``tzrangebase`` subclass should also provide the + following attributes: + * ``hasdst``: Boolean whether or not the zone uses DST. + * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects + representing the respective UTC offsets. + * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short + abbreviations in DST and STD, respectively. + * ``_hasdst``: Whether or not the zone has DST. + + .. versionadded:: 2.6.0 + """ + def __init__(self): + raise NotImplementedError('tzrangebase is an abstract base class') + + def utcoffset(self, dt): + isdst = self._isdst(dt) + + if isdst is None: + return None + elif isdst: + return self._dst_offset + else: + return self._std_offset + + def dst(self, dt): + isdst = self._isdst(dt) + + if isdst is None: + return None + elif isdst: + return self._dst_base_offset + else: + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + if self._isdst(dt): + return self._dst_abbr + else: + return self._std_abbr + + def fromutc(self, dt): + """ Given a datetime in UTC, return local time """ + if not isinstance(dt, datetime): + raise TypeError("fromutc() requires a datetime argument") + + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + # Get transitions - if there are none, fixed offset + transitions = self.transitions(dt.year) + if transitions is None: + return dt + self.utcoffset(dt) + + # Get the transition times in UTC + dston, dstoff = transitions + + dston -= self._std_offset + dstoff -= self._std_offset + + utc_transitions = (dston, dstoff) + dt_utc = dt.replace(tzinfo=None) + + isdst = self._naive_isdst(dt_utc, utc_transitions) + + if isdst: + dt_wall = dt + self._dst_offset + else: + dt_wall = dt + self._std_offset + + _fold = int(not isdst and self.is_ambiguous(dt_wall)) + + return enfold(dt_wall, fold=_fold) + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + if not self.hasdst: + return False + + start, end = self.transitions(dt.year) + + dt = dt.replace(tzinfo=None) + return (end <= dt < end + self._dst_base_offset) + + def _isdst(self, dt): + if not self.hasdst: + return False + elif dt is None: + return None + + transitions = self.transitions(dt.year) + + if transitions is None: + return False + + dt = dt.replace(tzinfo=None) + + isdst = self._naive_isdst(dt, transitions) + + # Handle ambiguous dates + if not isdst and self.is_ambiguous(dt): + return not self._fold(dt) + else: + return isdst + + def _naive_isdst(self, dt, transitions): + dston, dstoff = transitions + + dt = dt.replace(tzinfo=None) + + if dston < dstoff: + isdst = dston <= dt < dstoff + else: + isdst = not dstoff <= dt < dston + + return isdst + + @property + def _dst_base_offset(self): + return self._dst_offset - self._std_offset + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s(...)" % self.__class__.__name__ + + __reduce__ = object.__reduce__ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/_factories.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..f8a65891a023ebf9eb0c24d391ba67541b7133f1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/_factories.py @@ -0,0 +1,80 @@ +from datetime import timedelta +import weakref +from collections import OrderedDict + +from six.moves import _thread + + +class _TzSingleton(type): + def __init__(cls, *args, **kwargs): + cls.__instance = None + super(_TzSingleton, cls).__init__(*args, **kwargs) + + def __call__(cls): + if cls.__instance is None: + cls.__instance = super(_TzSingleton, cls).__call__() + return cls.__instance + + +class _TzFactory(type): + def instance(cls, *args, **kwargs): + """Alternate constructor that returns a fresh instance""" + return type.__call__(cls, *args, **kwargs) + + +class _TzOffsetFactory(_TzFactory): + def __init__(cls, *args, **kwargs): + cls.__instances = weakref.WeakValueDictionary() + cls.__strong_cache = OrderedDict() + cls.__strong_cache_size = 8 + + cls._cache_lock = _thread.allocate_lock() + + def __call__(cls, name, offset): + if isinstance(offset, timedelta): + key = (name, offset.total_seconds()) + else: + key = (name, offset) + + instance = cls.__instances.get(key, None) + if instance is None: + instance = cls.__instances.setdefault(key, + cls.instance(name, offset)) + + # This lock may not be necessary in Python 3. See GH issue #901 + with cls._cache_lock: + cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) + + # Remove an item if the strong cache is overpopulated + if len(cls.__strong_cache) > cls.__strong_cache_size: + cls.__strong_cache.popitem(last=False) + + return instance + + +class _TzStrFactory(_TzFactory): + def __init__(cls, *args, **kwargs): + cls.__instances = weakref.WeakValueDictionary() + cls.__strong_cache = OrderedDict() + cls.__strong_cache_size = 8 + + cls.__cache_lock = _thread.allocate_lock() + + def __call__(cls, s, posix_offset=False): + key = (s, posix_offset) + instance = cls.__instances.get(key, None) + + if instance is None: + instance = cls.__instances.setdefault(key, + cls.instance(s, posix_offset)) + + # This lock may not be necessary in Python 3. See GH issue #901 + with cls.__cache_lock: + cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) + + # Remove an item if the strong cache is overpopulated + if len(cls.__strong_cache) > cls.__strong_cache_size: + cls.__strong_cache.popitem(last=False) + + return instance + diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/tz.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/tz.py new file mode 100644 index 0000000000000000000000000000000000000000..617591446bd92eb1cc7b7d67fa3f17435e691cdd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/tz.py @@ -0,0 +1,1849 @@ +# -*- coding: utf-8 -*- +""" +This module offers timezone implementations subclassing the abstract +:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format +files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, +etc), TZ environment string (in all known formats), given ranges (with help +from relative deltas), local machine timezone, fixed offset timezone, and UTC +timezone. +""" +import datetime +import struct +import time +import sys +import os +import bisect +import weakref +from collections import OrderedDict + +import six +from six import string_types +from six.moves import _thread +from ._common import tzname_in_python2, _tzinfo +from ._common import tzrangebase, enfold +from ._common import _validate_fromutc_inputs + +from ._factories import _TzSingleton, _TzOffsetFactory +from ._factories import _TzStrFactory +try: + from .win import tzwin, tzwinlocal +except ImportError: + tzwin = tzwinlocal = None + +# For warning about rounding tzinfo +from warnings import warn + +ZERO = datetime.timedelta(0) +EPOCH = datetime.datetime(1970, 1, 1, 0, 0) +EPOCHORDINAL = EPOCH.toordinal() + + +@six.add_metaclass(_TzSingleton) +class tzutc(datetime.tzinfo): + """ + This is a tzinfo object that represents the UTC time zone. + + **Examples:** + + .. doctest:: + + >>> from datetime import * + >>> from dateutil.tz import * + + >>> datetime.now() + datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) + + >>> datetime.now(tzutc()) + datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) + + >>> datetime.now(tzutc()).tzname() + 'UTC' + + .. versionchanged:: 2.7.0 + ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will + always return the same object. + + .. doctest:: + + >>> from dateutil.tz import tzutc, UTC + >>> tzutc() is tzutc() + True + >>> tzutc() is UTC + True + """ + def utcoffset(self, dt): + return ZERO + + def dst(self, dt): + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return "UTC" + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + return False + + @_validate_fromutc_inputs + def fromutc(self, dt): + """ + Fast track version of fromutc() returns the original ``dt`` object for + any valid :py:class:`datetime.datetime` object. + """ + return dt + + def __eq__(self, other): + if not isinstance(other, (tzutc, tzoffset)): + return NotImplemented + + return (isinstance(other, tzutc) or + (isinstance(other, tzoffset) and other._offset == ZERO)) + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s()" % self.__class__.__name__ + + __reduce__ = object.__reduce__ + + +#: Convenience constant providing a :class:`tzutc()` instance +#: +#: .. versionadded:: 2.7.0 +UTC = tzutc() + + +@six.add_metaclass(_TzOffsetFactory) +class tzoffset(datetime.tzinfo): + """ + A simple class for representing a fixed offset from UTC. + + :param name: + The timezone name, to be returned when ``tzname()`` is called. + :param offset: + The time zone offset in seconds, or (since version 2.6.0, represented + as a :py:class:`datetime.timedelta` object). + """ + def __init__(self, name, offset): + self._name = name + + try: + # Allow a timedelta + offset = offset.total_seconds() + except (TypeError, AttributeError): + pass + + self._offset = datetime.timedelta(seconds=_get_supported_offset(offset)) + + def utcoffset(self, dt): + return self._offset + + def dst(self, dt): + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return self._name + + @_validate_fromutc_inputs + def fromutc(self, dt): + return dt + self._offset + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + return False + + def __eq__(self, other): + if not isinstance(other, tzoffset): + return NotImplemented + + return self._offset == other._offset + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s(%s, %s)" % (self.__class__.__name__, + repr(self._name), + int(self._offset.total_seconds())) + + __reduce__ = object.__reduce__ + + +class tzlocal(_tzinfo): + """ + A :class:`tzinfo` subclass built around the ``time`` timezone functions. + """ + def __init__(self): + super(tzlocal, self).__init__() + + self._std_offset = datetime.timedelta(seconds=-time.timezone) + if time.daylight: + self._dst_offset = datetime.timedelta(seconds=-time.altzone) + else: + self._dst_offset = self._std_offset + + self._dst_saved = self._dst_offset - self._std_offset + self._hasdst = bool(self._dst_saved) + self._tznames = tuple(time.tzname) + + def utcoffset(self, dt): + if dt is None and self._hasdst: + return None + + if self._isdst(dt): + return self._dst_offset + else: + return self._std_offset + + def dst(self, dt): + if dt is None and self._hasdst: + return None + + if self._isdst(dt): + return self._dst_offset - self._std_offset + else: + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return self._tznames[self._isdst(dt)] + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + naive_dst = self._naive_is_dst(dt) + return (not naive_dst and + (naive_dst != self._naive_is_dst(dt - self._dst_saved))) + + def _naive_is_dst(self, dt): + timestamp = _datetime_to_timestamp(dt) + return time.localtime(timestamp + time.timezone).tm_isdst + + def _isdst(self, dt, fold_naive=True): + # We can't use mktime here. It is unstable when deciding if + # the hour near to a change is DST or not. + # + # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, + # dt.minute, dt.second, dt.weekday(), 0, -1)) + # return time.localtime(timestamp).tm_isdst + # + # The code above yields the following result: + # + # >>> import tz, datetime + # >>> t = tz.tzlocal() + # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() + # 'BRDT' + # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() + # 'BRST' + # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() + # 'BRST' + # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() + # 'BRDT' + # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() + # 'BRDT' + # + # Here is a more stable implementation: + # + if not self._hasdst: + return False + + # Check for ambiguous times: + dstval = self._naive_is_dst(dt) + fold = getattr(dt, 'fold', None) + + if self.is_ambiguous(dt): + if fold is not None: + return not self._fold(dt) + else: + return True + + return dstval + + def __eq__(self, other): + if isinstance(other, tzlocal): + return (self._std_offset == other._std_offset and + self._dst_offset == other._dst_offset) + elif isinstance(other, tzutc): + return (not self._hasdst and + self._tznames[0] in {'UTC', 'GMT'} and + self._std_offset == ZERO) + elif isinstance(other, tzoffset): + return (not self._hasdst and + self._tznames[0] == other._name and + self._std_offset == other._offset) + else: + return NotImplemented + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s()" % self.__class__.__name__ + + __reduce__ = object.__reduce__ + + +class _ttinfo(object): + __slots__ = ["offset", "delta", "isdst", "abbr", + "isstd", "isgmt", "dstoffset"] + + def __init__(self): + for attr in self.__slots__: + setattr(self, attr, None) + + def __repr__(self): + l = [] + for attr in self.__slots__: + value = getattr(self, attr) + if value is not None: + l.append("%s=%s" % (attr, repr(value))) + return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) + + def __eq__(self, other): + if not isinstance(other, _ttinfo): + return NotImplemented + + return (self.offset == other.offset and + self.delta == other.delta and + self.isdst == other.isdst and + self.abbr == other.abbr and + self.isstd == other.isstd and + self.isgmt == other.isgmt and + self.dstoffset == other.dstoffset) + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __getstate__(self): + state = {} + for name in self.__slots__: + state[name] = getattr(self, name, None) + return state + + def __setstate__(self, state): + for name in self.__slots__: + if name in state: + setattr(self, name, state[name]) + + +class _tzfile(object): + """ + Lightweight class for holding the relevant transition and time zone + information read from binary tzfiles. + """ + attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list', + 'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first'] + + def __init__(self, **kwargs): + for attr in self.attrs: + setattr(self, attr, kwargs.get(attr, None)) + + +class tzfile(_tzinfo): + """ + This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` + format timezone files to extract current and historical zone information. + + :param fileobj: + This can be an opened file stream or a file name that the time zone + information can be read from. + + :param filename: + This is an optional parameter specifying the source of the time zone + information in the event that ``fileobj`` is a file object. If omitted + and ``fileobj`` is a file stream, this parameter will be set either to + ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. + + See `Sources for Time Zone and Daylight Saving Time Data + `_ for more information. + Time zone files can be compiled from the `IANA Time Zone database files + `_ with the `zic time zone compiler + `_ + + .. note:: + + Only construct a ``tzfile`` directly if you have a specific timezone + file on disk that you want to read into a Python ``tzinfo`` object. + If you want to get a ``tzfile`` representing a specific IANA zone, + (e.g. ``'America/New_York'``), you should call + :func:`dateutil.tz.gettz` with the zone identifier. + + + **Examples:** + + Using the US Eastern time zone as an example, we can see that a ``tzfile`` + provides time zone information for the standard Daylight Saving offsets: + + .. testsetup:: tzfile + + from dateutil.tz import gettz + from datetime import datetime + + .. doctest:: tzfile + + >>> NYC = gettz('America/New_York') + >>> NYC + tzfile('/usr/share/zoneinfo/America/New_York') + + >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST + 2016-01-03 00:00:00-05:00 + + >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT + 2016-07-07 00:00:00-04:00 + + + The ``tzfile`` structure contains a fully history of the time zone, + so historical dates will also have the right offsets. For example, before + the adoption of the UTC standards, New York used local solar mean time: + + .. doctest:: tzfile + + >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT + 1901-04-12 00:00:00-04:56 + + And during World War II, New York was on "Eastern War Time", which was a + state of permanent daylight saving time: + + .. doctest:: tzfile + + >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT + 1944-02-07 00:00:00-04:00 + + """ + + def __init__(self, fileobj, filename=None): + super(tzfile, self).__init__() + + file_opened_here = False + if isinstance(fileobj, string_types): + self._filename = fileobj + fileobj = open(fileobj, 'rb') + file_opened_here = True + elif filename is not None: + self._filename = filename + elif hasattr(fileobj, "name"): + self._filename = fileobj.name + else: + self._filename = repr(fileobj) + + if fileobj is not None: + if not file_opened_here: + fileobj = _nullcontext(fileobj) + + with fileobj as file_stream: + tzobj = self._read_tzfile(file_stream) + + self._set_tzdata(tzobj) + + def _set_tzdata(self, tzobj): + """ Set the time zone data of this object from a _tzfile object """ + # Copy the relevant attributes over as private attributes + for attr in _tzfile.attrs: + setattr(self, '_' + attr, getattr(tzobj, attr)) + + def _read_tzfile(self, fileobj): + out = _tzfile() + + # From tzfile(5): + # + # The time zone information files used by tzset(3) + # begin with the magic characters "TZif" to identify + # them as time zone information files, followed by + # sixteen bytes reserved for future use, followed by + # six four-byte values of type long, written in a + # ``standard'' byte order (the high-order byte + # of the value is written first). + if fileobj.read(4).decode() != "TZif": + raise ValueError("magic not found") + + fileobj.read(16) + + ( + # The number of UTC/local indicators stored in the file. + ttisgmtcnt, + + # The number of standard/wall indicators stored in the file. + ttisstdcnt, + + # The number of leap seconds for which data is + # stored in the file. + leapcnt, + + # The number of "transition times" for which data + # is stored in the file. + timecnt, + + # The number of "local time types" for which data + # is stored in the file (must not be zero). + typecnt, + + # The number of characters of "time zone + # abbreviation strings" stored in the file. + charcnt, + + ) = struct.unpack(">6l", fileobj.read(24)) + + # The above header is followed by tzh_timecnt four-byte + # values of type long, sorted in ascending order. + # These values are written in ``standard'' byte order. + # Each is used as a transition time (as returned by + # time(2)) at which the rules for computing local time + # change. + + if timecnt: + out.trans_list_utc = list(struct.unpack(">%dl" % timecnt, + fileobj.read(timecnt*4))) + else: + out.trans_list_utc = [] + + # Next come tzh_timecnt one-byte values of type unsigned + # char; each one tells which of the different types of + # ``local time'' types described in the file is associated + # with the same-indexed transition time. These values + # serve as indices into an array of ttinfo structures that + # appears next in the file. + + if timecnt: + out.trans_idx = struct.unpack(">%dB" % timecnt, + fileobj.read(timecnt)) + else: + out.trans_idx = [] + + # Each ttinfo structure is written as a four-byte value + # for tt_gmtoff of type long, in a standard byte + # order, followed by a one-byte value for tt_isdst + # and a one-byte value for tt_abbrind. In each + # structure, tt_gmtoff gives the number of + # seconds to be added to UTC, tt_isdst tells whether + # tm_isdst should be set by localtime(3), and + # tt_abbrind serves as an index into the array of + # time zone abbreviation characters that follow the + # ttinfo structure(s) in the file. + + ttinfo = [] + + for i in range(typecnt): + ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) + + abbr = fileobj.read(charcnt).decode() + + # Then there are tzh_leapcnt pairs of four-byte + # values, written in standard byte order; the + # first value of each pair gives the time (as + # returned by time(2)) at which a leap second + # occurs; the second gives the total number of + # leap seconds to be applied after the given time. + # The pairs of values are sorted in ascending order + # by time. + + # Not used, for now (but seek for correct file position) + if leapcnt: + fileobj.seek(leapcnt * 8, os.SEEK_CUR) + + # Then there are tzh_ttisstdcnt standard/wall + # indicators, each stored as a one-byte value; + # they tell whether the transition times associated + # with local time types were specified as standard + # time or wall clock time, and are used when + # a time zone file is used in handling POSIX-style + # time zone environment variables. + + if ttisstdcnt: + isstd = struct.unpack(">%db" % ttisstdcnt, + fileobj.read(ttisstdcnt)) + + # Finally, there are tzh_ttisgmtcnt UTC/local + # indicators, each stored as a one-byte value; + # they tell whether the transition times associated + # with local time types were specified as UTC or + # local time, and are used when a time zone file + # is used in handling POSIX-style time zone envi- + # ronment variables. + + if ttisgmtcnt: + isgmt = struct.unpack(">%db" % ttisgmtcnt, + fileobj.read(ttisgmtcnt)) + + # Build ttinfo list + out.ttinfo_list = [] + for i in range(typecnt): + gmtoff, isdst, abbrind = ttinfo[i] + gmtoff = _get_supported_offset(gmtoff) + tti = _ttinfo() + tti.offset = gmtoff + tti.dstoffset = datetime.timedelta(0) + tti.delta = datetime.timedelta(seconds=gmtoff) + tti.isdst = isdst + tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] + tti.isstd = (ttisstdcnt > i and isstd[i] != 0) + tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) + out.ttinfo_list.append(tti) + + # Replace ttinfo indexes for ttinfo objects. + out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx] + + # Set standard, dst, and before ttinfos. before will be + # used when a given time is before any transitions, + # and will be set to the first non-dst ttinfo, or to + # the first dst, if all of them are dst. + out.ttinfo_std = None + out.ttinfo_dst = None + out.ttinfo_before = None + if out.ttinfo_list: + if not out.trans_list_utc: + out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0] + else: + for i in range(timecnt-1, -1, -1): + tti = out.trans_idx[i] + if not out.ttinfo_std and not tti.isdst: + out.ttinfo_std = tti + elif not out.ttinfo_dst and tti.isdst: + out.ttinfo_dst = tti + + if out.ttinfo_std and out.ttinfo_dst: + break + else: + if out.ttinfo_dst and not out.ttinfo_std: + out.ttinfo_std = out.ttinfo_dst + + for tti in out.ttinfo_list: + if not tti.isdst: + out.ttinfo_before = tti + break + else: + out.ttinfo_before = out.ttinfo_list[0] + + # Now fix transition times to become relative to wall time. + # + # I'm not sure about this. In my tests, the tz source file + # is setup to wall time, and in the binary file isstd and + # isgmt are off, so it should be in wall time. OTOH, it's + # always in gmt time. Let me know if you have comments + # about this. + lastdst = None + lastoffset = None + lastdstoffset = None + lastbaseoffset = None + out.trans_list = [] + + for i, tti in enumerate(out.trans_idx): + offset = tti.offset + dstoffset = 0 + + if lastdst is not None: + if tti.isdst: + if not lastdst: + dstoffset = offset - lastoffset + + if not dstoffset and lastdstoffset: + dstoffset = lastdstoffset + + tti.dstoffset = datetime.timedelta(seconds=dstoffset) + lastdstoffset = dstoffset + + # If a time zone changes its base offset during a DST transition, + # then you need to adjust by the previous base offset to get the + # transition time in local time. Otherwise you use the current + # base offset. Ideally, I would have some mathematical proof of + # why this is true, but I haven't really thought about it enough. + baseoffset = offset - dstoffset + adjustment = baseoffset + if (lastbaseoffset is not None and baseoffset != lastbaseoffset + and tti.isdst != lastdst): + # The base DST has changed + adjustment = lastbaseoffset + + lastdst = tti.isdst + lastoffset = offset + lastbaseoffset = baseoffset + + out.trans_list.append(out.trans_list_utc[i] + adjustment) + + out.trans_idx = tuple(out.trans_idx) + out.trans_list = tuple(out.trans_list) + out.trans_list_utc = tuple(out.trans_list_utc) + + return out + + def _find_last_transition(self, dt, in_utc=False): + # If there's no list, there are no transitions to find + if not self._trans_list: + return None + + timestamp = _datetime_to_timestamp(dt) + + # Find where the timestamp fits in the transition list - if the + # timestamp is a transition time, it's part of the "after" period. + trans_list = self._trans_list_utc if in_utc else self._trans_list + idx = bisect.bisect_right(trans_list, timestamp) + + # We want to know when the previous transition was, so subtract off 1 + return idx - 1 + + def _get_ttinfo(self, idx): + # For no list or after the last transition, default to _ttinfo_std + if idx is None or (idx + 1) >= len(self._trans_list): + return self._ttinfo_std + + # If there is a list and the time is before it, return _ttinfo_before + if idx < 0: + return self._ttinfo_before + + return self._trans_idx[idx] + + def _find_ttinfo(self, dt): + idx = self._resolve_ambiguous_time(dt) + + return self._get_ttinfo(idx) + + def fromutc(self, dt): + """ + The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. + + :param dt: + A :py:class:`datetime.datetime` object. + + :raises TypeError: + Raised if ``dt`` is not a :py:class:`datetime.datetime` object. + + :raises ValueError: + Raised if this is called with a ``dt`` which does not have this + ``tzinfo`` attached. + + :return: + Returns a :py:class:`datetime.datetime` object representing the + wall time in ``self``'s time zone. + """ + # These isinstance checks are in datetime.tzinfo, so we'll preserve + # them, even if we don't care about duck typing. + if not isinstance(dt, datetime.datetime): + raise TypeError("fromutc() requires a datetime argument") + + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + # First treat UTC as wall time and get the transition we're in. + idx = self._find_last_transition(dt, in_utc=True) + tti = self._get_ttinfo(idx) + + dt_out = dt + datetime.timedelta(seconds=tti.offset) + + fold = self.is_ambiguous(dt_out, idx=idx) + + return enfold(dt_out, fold=int(fold)) + + def is_ambiguous(self, dt, idx=None): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + if idx is None: + idx = self._find_last_transition(dt) + + # Calculate the difference in offsets from current to previous + timestamp = _datetime_to_timestamp(dt) + tti = self._get_ttinfo(idx) + + if idx is None or idx <= 0: + return False + + od = self._get_ttinfo(idx - 1).offset - tti.offset + tt = self._trans_list[idx] # Transition time + + return timestamp < tt + od + + def _resolve_ambiguous_time(self, dt): + idx = self._find_last_transition(dt) + + # If we have no transitions, return the index + _fold = self._fold(dt) + if idx is None or idx == 0: + return idx + + # If it's ambiguous and we're in a fold, shift to a different index. + idx_offset = int(not _fold and self.is_ambiguous(dt, idx)) + + return idx - idx_offset + + def utcoffset(self, dt): + if dt is None: + return None + + if not self._ttinfo_std: + return ZERO + + return self._find_ttinfo(dt).delta + + def dst(self, dt): + if dt is None: + return None + + if not self._ttinfo_dst: + return ZERO + + tti = self._find_ttinfo(dt) + + if not tti.isdst: + return ZERO + + # The documentation says that utcoffset()-dst() must + # be constant for every dt. + return tti.dstoffset + + @tzname_in_python2 + def tzname(self, dt): + if not self._ttinfo_std or dt is None: + return None + return self._find_ttinfo(dt).abbr + + def __eq__(self, other): + if not isinstance(other, tzfile): + return NotImplemented + return (self._trans_list == other._trans_list and + self._trans_idx == other._trans_idx and + self._ttinfo_list == other._ttinfo_list) + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) + + def __reduce__(self): + return self.__reduce_ex__(None) + + def __reduce_ex__(self, protocol): + return (self.__class__, (None, self._filename), self.__dict__) + + +class tzrange(tzrangebase): + """ + The ``tzrange`` object is a time zone specified by a set of offsets and + abbreviations, equivalent to the way the ``TZ`` variable can be specified + in POSIX-like systems, but using Python delta objects to specify DST + start, end and offsets. + + :param stdabbr: + The abbreviation for standard time (e.g. ``'EST'``). + + :param stdoffset: + An integer or :class:`datetime.timedelta` object or equivalent + specifying the base offset from UTC. + + If unspecified, +00:00 is used. + + :param dstabbr: + The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). + + If specified, with no other DST information, DST is assumed to occur + and the default behavior or ``dstoffset``, ``start`` and ``end`` is + used. If unspecified and no other DST information is specified, it + is assumed that this zone has no DST. + + If this is unspecified and other DST information is *is* specified, + DST occurs in the zone but the time zone abbreviation is left + unchanged. + + :param dstoffset: + A an integer or :class:`datetime.timedelta` object or equivalent + specifying the UTC offset during DST. If unspecified and any other DST + information is specified, it is assumed to be the STD offset +1 hour. + + :param start: + A :class:`relativedelta.relativedelta` object or equivalent specifying + the time and time of year that daylight savings time starts. To + specify, for example, that DST starts at 2AM on the 2nd Sunday in + March, pass: + + ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` + + If unspecified and any other DST information is specified, the default + value is 2 AM on the first Sunday in April. + + :param end: + A :class:`relativedelta.relativedelta` object or equivalent + representing the time and time of year that daylight savings time + ends, with the same specification method as in ``start``. One note is + that this should point to the first time in the *standard* zone, so if + a transition occurs at 2AM in the DST zone and the clocks are set back + 1 hour to 1AM, set the ``hours`` parameter to +1. + + + **Examples:** + + .. testsetup:: tzrange + + from dateutil.tz import tzrange, tzstr + + .. doctest:: tzrange + + >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") + True + + >>> from dateutil.relativedelta import * + >>> range1 = tzrange("EST", -18000, "EDT") + >>> range2 = tzrange("EST", -18000, "EDT", -14400, + ... relativedelta(hours=+2, month=4, day=1, + ... weekday=SU(+1)), + ... relativedelta(hours=+1, month=10, day=31, + ... weekday=SU(-1))) + >>> tzstr('EST5EDT') == range1 == range2 + True + + """ + def __init__(self, stdabbr, stdoffset=None, + dstabbr=None, dstoffset=None, + start=None, end=None): + + global relativedelta + from dateutil import relativedelta + + self._std_abbr = stdabbr + self._dst_abbr = dstabbr + + try: + stdoffset = stdoffset.total_seconds() + except (TypeError, AttributeError): + pass + + try: + dstoffset = dstoffset.total_seconds() + except (TypeError, AttributeError): + pass + + if stdoffset is not None: + self._std_offset = datetime.timedelta(seconds=stdoffset) + else: + self._std_offset = ZERO + + if dstoffset is not None: + self._dst_offset = datetime.timedelta(seconds=dstoffset) + elif dstabbr and stdoffset is not None: + self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) + else: + self._dst_offset = ZERO + + if dstabbr and start is None: + self._start_delta = relativedelta.relativedelta( + hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) + else: + self._start_delta = start + + if dstabbr and end is None: + self._end_delta = relativedelta.relativedelta( + hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) + else: + self._end_delta = end + + self._dst_base_offset_ = self._dst_offset - self._std_offset + self.hasdst = bool(self._start_delta) + + def transitions(self, year): + """ + For a given year, get the DST on and off transition times, expressed + always on the standard time side. For zones with no transitions, this + function returns ``None``. + + :param year: + The year whose transitions you would like to query. + + :return: + Returns a :class:`tuple` of :class:`datetime.datetime` objects, + ``(dston, dstoff)`` for zones with an annual DST transition, or + ``None`` for fixed offset zones. + """ + if not self.hasdst: + return None + + base_year = datetime.datetime(year, 1, 1) + + start = base_year + self._start_delta + end = base_year + self._end_delta + + return (start, end) + + def __eq__(self, other): + if not isinstance(other, tzrange): + return NotImplemented + + return (self._std_abbr == other._std_abbr and + self._dst_abbr == other._dst_abbr and + self._std_offset == other._std_offset and + self._dst_offset == other._dst_offset and + self._start_delta == other._start_delta and + self._end_delta == other._end_delta) + + @property + def _dst_base_offset(self): + return self._dst_base_offset_ + + +@six.add_metaclass(_TzStrFactory) +class tzstr(tzrange): + """ + ``tzstr`` objects are time zone objects specified by a time-zone string as + it would be passed to a ``TZ`` variable on POSIX-style systems (see + the `GNU C Library: TZ Variable`_ for more details). + + There is one notable exception, which is that POSIX-style time zones use an + inverted offset format, so normally ``GMT+3`` would be parsed as an offset + 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an + offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX + behavior, pass a ``True`` value to ``posix_offset``. + + The :class:`tzrange` object provides the same functionality, but is + specified using :class:`relativedelta.relativedelta` objects. rather than + strings. + + :param s: + A time zone string in ``TZ`` variable format. This can be a + :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: + :class:`unicode`) or a stream emitting unicode characters + (e.g. :class:`StringIO`). + + :param posix_offset: + Optional. If set to ``True``, interpret strings such as ``GMT+3`` or + ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the + POSIX standard. + + .. caution:: + + Prior to version 2.7.0, this function also supported time zones + in the format: + + * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` + * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` + + This format is non-standard and has been deprecated; this function + will raise a :class:`DeprecatedTZFormatWarning` until + support is removed in a future version. + + .. _`GNU C Library: TZ Variable`: + https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html + """ + def __init__(self, s, posix_offset=False): + global parser + from dateutil.parser import _parser as parser + + self._s = s + + res = parser._parsetz(s) + if res is None or res.any_unused_tokens: + raise ValueError("unknown string format") + + # Here we break the compatibility with the TZ variable handling. + # GMT-3 actually *means* the timezone -3. + if res.stdabbr in ("GMT", "UTC") and not posix_offset: + res.stdoffset *= -1 + + # We must initialize it first, since _delta() needs + # _std_offset and _dst_offset set. Use False in start/end + # to avoid building it two times. + tzrange.__init__(self, res.stdabbr, res.stdoffset, + res.dstabbr, res.dstoffset, + start=False, end=False) + + if not res.dstabbr: + self._start_delta = None + self._end_delta = None + else: + self._start_delta = self._delta(res.start) + if self._start_delta: + self._end_delta = self._delta(res.end, isend=1) + + self.hasdst = bool(self._start_delta) + + def _delta(self, x, isend=0): + from dateutil import relativedelta + kwargs = {} + if x.month is not None: + kwargs["month"] = x.month + if x.weekday is not None: + kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) + if x.week > 0: + kwargs["day"] = 1 + else: + kwargs["day"] = 31 + elif x.day: + kwargs["day"] = x.day + elif x.yday is not None: + kwargs["yearday"] = x.yday + elif x.jyday is not None: + kwargs["nlyearday"] = x.jyday + if not kwargs: + # Default is to start on first sunday of april, and end + # on last sunday of october. + if not isend: + kwargs["month"] = 4 + kwargs["day"] = 1 + kwargs["weekday"] = relativedelta.SU(+1) + else: + kwargs["month"] = 10 + kwargs["day"] = 31 + kwargs["weekday"] = relativedelta.SU(-1) + if x.time is not None: + kwargs["seconds"] = x.time + else: + # Default is 2AM. + kwargs["seconds"] = 7200 + if isend: + # Convert to standard time, to follow the documented way + # of working with the extra hour. See the documentation + # of the tzinfo class. + delta = self._dst_offset - self._std_offset + kwargs["seconds"] -= delta.seconds + delta.days * 86400 + return relativedelta.relativedelta(**kwargs) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._s)) + + +class _tzicalvtzcomp(object): + def __init__(self, tzoffsetfrom, tzoffsetto, isdst, + tzname=None, rrule=None): + self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) + self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) + self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom + self.isdst = isdst + self.tzname = tzname + self.rrule = rrule + + +class _tzicalvtz(_tzinfo): + def __init__(self, tzid, comps=[]): + super(_tzicalvtz, self).__init__() + + self._tzid = tzid + self._comps = comps + self._cachedate = [] + self._cachecomp = [] + self._cache_lock = _thread.allocate_lock() + + def _find_comp(self, dt): + if len(self._comps) == 1: + return self._comps[0] + + dt = dt.replace(tzinfo=None) + + try: + with self._cache_lock: + return self._cachecomp[self._cachedate.index( + (dt, self._fold(dt)))] + except ValueError: + pass + + lastcompdt = None + lastcomp = None + + for comp in self._comps: + compdt = self._find_compdt(comp, dt) + + if compdt and (not lastcompdt or lastcompdt < compdt): + lastcompdt = compdt + lastcomp = comp + + if not lastcomp: + # RFC says nothing about what to do when a given + # time is before the first onset date. We'll look for the + # first standard component, or the first component, if + # none is found. + for comp in self._comps: + if not comp.isdst: + lastcomp = comp + break + else: + lastcomp = comp[0] + + with self._cache_lock: + self._cachedate.insert(0, (dt, self._fold(dt))) + self._cachecomp.insert(0, lastcomp) + + if len(self._cachedate) > 10: + self._cachedate.pop() + self._cachecomp.pop() + + return lastcomp + + def _find_compdt(self, comp, dt): + if comp.tzoffsetdiff < ZERO and self._fold(dt): + dt -= comp.tzoffsetdiff + + compdt = comp.rrule.before(dt, inc=True) + + return compdt + + def utcoffset(self, dt): + if dt is None: + return None + + return self._find_comp(dt).tzoffsetto + + def dst(self, dt): + comp = self._find_comp(dt) + if comp.isdst: + return comp.tzoffsetdiff + else: + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return self._find_comp(dt).tzname + + def __repr__(self): + return "" % repr(self._tzid) + + __reduce__ = object.__reduce__ + + +class tzical(object): + """ + This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure + as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. + + :param `fileobj`: + A file or stream in iCalendar format, which should be UTF-8 encoded + with CRLF endings. + + .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 + """ + def __init__(self, fileobj): + global rrule + from dateutil import rrule + + if isinstance(fileobj, string_types): + self._s = fileobj + # ical should be encoded in UTF-8 with CRLF + fileobj = open(fileobj, 'r') + else: + self._s = getattr(fileobj, 'name', repr(fileobj)) + fileobj = _nullcontext(fileobj) + + self._vtz = {} + + with fileobj as fobj: + self._parse_rfc(fobj.read()) + + def keys(self): + """ + Retrieves the available time zones as a list. + """ + return list(self._vtz.keys()) + + def get(self, tzid=None): + """ + Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. + + :param tzid: + If there is exactly one time zone available, omitting ``tzid`` + or passing :py:const:`None` value returns it. Otherwise a valid + key (which can be retrieved from :func:`keys`) is required. + + :raises ValueError: + Raised if ``tzid`` is not specified but there are either more + or fewer than 1 zone defined. + + :returns: + Returns either a :py:class:`datetime.tzinfo` object representing + the relevant time zone or :py:const:`None` if the ``tzid`` was + not found. + """ + if tzid is None: + if len(self._vtz) == 0: + raise ValueError("no timezones defined") + elif len(self._vtz) > 1: + raise ValueError("more than one timezone available") + tzid = next(iter(self._vtz)) + + return self._vtz.get(tzid) + + def _parse_offset(self, s): + s = s.strip() + if not s: + raise ValueError("empty offset") + if s[0] in ('+', '-'): + signal = (-1, +1)[s[0] == '+'] + s = s[1:] + else: + signal = +1 + if len(s) == 4: + return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal + elif len(s) == 6: + return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal + else: + raise ValueError("invalid offset: " + s) + + def _parse_rfc(self, s): + lines = s.splitlines() + if not lines: + raise ValueError("empty string") + + # Unfold + i = 0 + while i < len(lines): + line = lines[i].rstrip() + if not line: + del lines[i] + elif i > 0 and line[0] == " ": + lines[i-1] += line[1:] + del lines[i] + else: + i += 1 + + tzid = None + comps = [] + invtz = False + comptype = None + for line in lines: + if not line: + continue + name, value = line.split(':', 1) + parms = name.split(';') + if not parms: + raise ValueError("empty property name") + name = parms[0].upper() + parms = parms[1:] + if invtz: + if name == "BEGIN": + if value in ("STANDARD", "DAYLIGHT"): + # Process component + pass + else: + raise ValueError("unknown component: "+value) + comptype = value + founddtstart = False + tzoffsetfrom = None + tzoffsetto = None + rrulelines = [] + tzname = None + elif name == "END": + if value == "VTIMEZONE": + if comptype: + raise ValueError("component not closed: "+comptype) + if not tzid: + raise ValueError("mandatory TZID not found") + if not comps: + raise ValueError( + "at least one component is needed") + # Process vtimezone + self._vtz[tzid] = _tzicalvtz(tzid, comps) + invtz = False + elif value == comptype: + if not founddtstart: + raise ValueError("mandatory DTSTART not found") + if tzoffsetfrom is None: + raise ValueError( + "mandatory TZOFFSETFROM not found") + if tzoffsetto is None: + raise ValueError( + "mandatory TZOFFSETFROM not found") + # Process component + rr = None + if rrulelines: + rr = rrule.rrulestr("\n".join(rrulelines), + compatible=True, + ignoretz=True, + cache=True) + comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, + (comptype == "DAYLIGHT"), + tzname, rr) + comps.append(comp) + comptype = None + else: + raise ValueError("invalid component end: "+value) + elif comptype: + if name == "DTSTART": + # DTSTART in VTIMEZONE takes a subset of valid RRULE + # values under RFC 5545. + for parm in parms: + if parm != 'VALUE=DATE-TIME': + msg = ('Unsupported DTSTART param in ' + + 'VTIMEZONE: ' + parm) + raise ValueError(msg) + rrulelines.append(line) + founddtstart = True + elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): + rrulelines.append(line) + elif name == "TZOFFSETFROM": + if parms: + raise ValueError( + "unsupported %s parm: %s " % (name, parms[0])) + tzoffsetfrom = self._parse_offset(value) + elif name == "TZOFFSETTO": + if parms: + raise ValueError( + "unsupported TZOFFSETTO parm: "+parms[0]) + tzoffsetto = self._parse_offset(value) + elif name == "TZNAME": + if parms: + raise ValueError( + "unsupported TZNAME parm: "+parms[0]) + tzname = value + elif name == "COMMENT": + pass + else: + raise ValueError("unsupported property: "+name) + else: + if name == "TZID": + if parms: + raise ValueError( + "unsupported TZID parm: "+parms[0]) + tzid = value + elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): + pass + else: + raise ValueError("unsupported property: "+name) + elif name == "BEGIN" and value == "VTIMEZONE": + tzid = None + comps = [] + invtz = True + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._s)) + + +if sys.platform != "win32": + TZFILES = ["/etc/localtime", "localtime"] + TZPATHS = ["/usr/share/zoneinfo", + "/usr/lib/zoneinfo", + "/usr/share/lib/zoneinfo", + "/etc/zoneinfo"] +else: + TZFILES = [] + TZPATHS = [] + + +def __get_gettz(): + tzlocal_classes = (tzlocal,) + if tzwinlocal is not None: + tzlocal_classes += (tzwinlocal,) + + class GettzFunc(object): + """ + Retrieve a time zone object from a string representation + + This function is intended to retrieve the :py:class:`tzinfo` subclass + that best represents the time zone that would be used if a POSIX + `TZ variable`_ were set to the same value. + + If no argument or an empty string is passed to ``gettz``, local time + is returned: + + .. code-block:: python3 + + >>> gettz() + tzfile('/etc/localtime') + + This function is also the preferred way to map IANA tz database keys + to :class:`tzfile` objects: + + .. code-block:: python3 + + >>> gettz('Pacific/Kiritimati') + tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') + + On Windows, the standard is extended to include the Windows-specific + zone names provided by the operating system: + + .. code-block:: python3 + + >>> gettz('Egypt Standard Time') + tzwin('Egypt Standard Time') + + Passing a GNU ``TZ`` style string time zone specification returns a + :class:`tzstr` object: + + .. code-block:: python3 + + >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') + tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') + + :param name: + A time zone name (IANA, or, on Windows, Windows keys), location of + a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone + specifier. An empty string, no argument or ``None`` is interpreted + as local time. + + :return: + Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` + subclasses. + + .. versionchanged:: 2.7.0 + + After version 2.7.0, any two calls to ``gettz`` using the same + input strings will return the same object: + + .. code-block:: python3 + + >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') + True + + In addition to improving performance, this ensures that + `"same zone" semantics`_ are used for datetimes in the same zone. + + + .. _`TZ variable`: + https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html + + .. _`"same zone" semantics`: + https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html + """ + def __init__(self): + + self.__instances = weakref.WeakValueDictionary() + self.__strong_cache_size = 8 + self.__strong_cache = OrderedDict() + self._cache_lock = _thread.allocate_lock() + + def __call__(self, name=None): + with self._cache_lock: + rv = self.__instances.get(name, None) + + if rv is None: + rv = self.nocache(name=name) + if not (name is None + or isinstance(rv, tzlocal_classes) + or rv is None): + # tzlocal is slightly more complicated than the other + # time zone providers because it depends on environment + # at construction time, so don't cache that. + # + # We also cannot store weak references to None, so we + # will also not store that. + self.__instances[name] = rv + else: + # No need for strong caching, return immediately + return rv + + self.__strong_cache[name] = self.__strong_cache.pop(name, rv) + + if len(self.__strong_cache) > self.__strong_cache_size: + self.__strong_cache.popitem(last=False) + + return rv + + def set_cache_size(self, size): + with self._cache_lock: + self.__strong_cache_size = size + while len(self.__strong_cache) > size: + self.__strong_cache.popitem(last=False) + + def cache_clear(self): + with self._cache_lock: + self.__instances = weakref.WeakValueDictionary() + self.__strong_cache.clear() + + @staticmethod + def nocache(name=None): + """A non-cached version of gettz""" + tz = None + if not name: + try: + name = os.environ["TZ"] + except KeyError: + pass + if name is None or name in ("", ":"): + for filepath in TZFILES: + if not os.path.isabs(filepath): + filename = filepath + for path in TZPATHS: + filepath = os.path.join(path, filename) + if os.path.isfile(filepath): + break + else: + continue + if os.path.isfile(filepath): + try: + tz = tzfile(filepath) + break + except (IOError, OSError, ValueError): + pass + else: + tz = tzlocal() + else: + try: + if name.startswith(":"): + name = name[1:] + except TypeError as e: + if isinstance(name, bytes): + new_msg = "gettz argument should be str, not bytes" + six.raise_from(TypeError(new_msg), e) + else: + raise + if os.path.isabs(name): + if os.path.isfile(name): + tz = tzfile(name) + else: + tz = None + else: + for path in TZPATHS: + filepath = os.path.join(path, name) + if not os.path.isfile(filepath): + filepath = filepath.replace(' ', '_') + if not os.path.isfile(filepath): + continue + try: + tz = tzfile(filepath) + break + except (IOError, OSError, ValueError): + pass + else: + tz = None + if tzwin is not None: + try: + tz = tzwin(name) + except (WindowsError, UnicodeEncodeError): + # UnicodeEncodeError is for Python 2.7 compat + tz = None + + if not tz: + from dateutil.zoneinfo import get_zonefile_instance + tz = get_zonefile_instance().get(name) + + if not tz: + for c in name: + # name is not a tzstr unless it has at least + # one offset. For short values of "name", an + # explicit for loop seems to be the fastest way + # To determine if a string contains a digit + if c in "0123456789": + try: + tz = tzstr(name) + except ValueError: + pass + break + else: + if name in ("GMT", "UTC"): + tz = UTC + elif name in time.tzname: + tz = tzlocal() + return tz + + return GettzFunc() + + +gettz = __get_gettz() +del __get_gettz + + +def datetime_exists(dt, tz=None): + """ + Given a datetime and a time zone, determine whether or not a given datetime + would fall in a gap. + + :param dt: + A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` + is provided.) + + :param tz: + A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If + ``None`` or not provided, the datetime's own time zone will be used. + + :return: + Returns a boolean value whether or not the "wall time" exists in + ``tz``. + + .. versionadded:: 2.7.0 + """ + if tz is None: + if dt.tzinfo is None: + raise ValueError('Datetime is naive and no time zone provided.') + tz = dt.tzinfo + + dt = dt.replace(tzinfo=None) + + # This is essentially a test of whether or not the datetime can survive + # a round trip to UTC. + dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz) + dt_rt = dt_rt.replace(tzinfo=None) + + return dt == dt_rt + + +def datetime_ambiguous(dt, tz=None): + """ + Given a datetime and a time zone, determine whether or not a given datetime + is ambiguous (i.e if there are two times differentiated only by their DST + status). + + :param dt: + A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` + is provided.) + + :param tz: + A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If + ``None`` or not provided, the datetime's own time zone will be used. + + :return: + Returns a boolean value whether or not the "wall time" is ambiguous in + ``tz``. + + .. versionadded:: 2.6.0 + """ + if tz is None: + if dt.tzinfo is None: + raise ValueError('Datetime is naive and no time zone provided.') + + tz = dt.tzinfo + + # If a time zone defines its own "is_ambiguous" function, we'll use that. + is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) + if is_ambiguous_fn is not None: + try: + return tz.is_ambiguous(dt) + except Exception: + pass + + # If it doesn't come out and tell us it's ambiguous, we'll just check if + # the fold attribute has any effect on this particular date and time. + dt = dt.replace(tzinfo=tz) + wall_0 = enfold(dt, fold=0) + wall_1 = enfold(dt, fold=1) + + same_offset = wall_0.utcoffset() == wall_1.utcoffset() + same_dst = wall_0.dst() == wall_1.dst() + + return not (same_offset and same_dst) + + +def resolve_imaginary(dt): + """ + Given a datetime that may be imaginary, return an existing datetime. + + This function assumes that an imaginary datetime represents what the + wall time would be in a zone had the offset transition not occurred, so + it will always fall forward by the transition's change in offset. + + .. doctest:: + + >>> from dateutil import tz + >>> from datetime import datetime + >>> NYC = tz.gettz('America/New_York') + >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) + 2017-03-12 03:30:00-04:00 + + >>> KIR = tz.gettz('Pacific/Kiritimati') + >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) + 1995-01-02 12:30:00+14:00 + + As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, + existing datetime, so a round-trip to and from UTC is sufficient to get + an extant datetime, however, this generally "falls back" to an earlier time + rather than falling forward to the STD side (though no guarantees are made + about this behavior). + + :param dt: + A :class:`datetime.datetime` which may or may not exist. + + :return: + Returns an existing :class:`datetime.datetime`. If ``dt`` was not + imaginary, the datetime returned is guaranteed to be the same object + passed to the function. + + .. versionadded:: 2.7.0 + """ + if dt.tzinfo is not None and not datetime_exists(dt): + + curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() + old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() + + dt += curr_offset - old_offset + + return dt + + +def _datetime_to_timestamp(dt): + """ + Convert a :class:`datetime.datetime` object to an epoch timestamp in + seconds since January 1, 1970, ignoring the time zone. + """ + return (dt.replace(tzinfo=None) - EPOCH).total_seconds() + + +if sys.version_info >= (3, 6): + def _get_supported_offset(second_offset): + return second_offset +else: + def _get_supported_offset(second_offset): + # For python pre-3.6, round to full-minutes if that's not the case. + # Python's datetime doesn't accept sub-minute timezones. Check + # http://python.org/sf/1447945 or https://bugs.python.org/issue5288 + # for some information. + old_offset = second_offset + calculated_offset = 60 * ((second_offset + 30) // 60) + return calculated_offset + + +try: + # Python 3.7 feature + from contextlib import nullcontext as _nullcontext +except ImportError: + class _nullcontext(object): + """ + Class for wrapping contexts so that they are passed through in a + with statement. + """ + def __init__(self, context): + self.context = context + + def __enter__(self): + return self.context + + def __exit__(*args, **kwargs): + pass + +# vim:ts=4:sw=4:et diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/win.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/win.py new file mode 100644 index 0000000000000000000000000000000000000000..cde07ba792c40903f0c334839140173b39fd8124 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tz/win.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +""" +This module provides an interface to the native time zone data on Windows, +including :py:class:`datetime.tzinfo` implementations. + +Attempting to import this module on a non-Windows platform will raise an +:py:obj:`ImportError`. +""" +# This code was originally contributed by Jeffrey Harris. +import datetime +import struct + +from six.moves import winreg +from six import text_type + +try: + import ctypes + from ctypes import wintypes +except ValueError: + # ValueError is raised on non-Windows systems for some horrible reason. + raise ImportError("Running tzwin on non-Windows system") + +from ._common import tzrangebase + +__all__ = ["tzwin", "tzwinlocal", "tzres"] + +ONEWEEK = datetime.timedelta(7) + +TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" +TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" +TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" + + +def _settzkeyname(): + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) + try: + winreg.OpenKey(handle, TZKEYNAMENT).Close() + TZKEYNAME = TZKEYNAMENT + except WindowsError: + TZKEYNAME = TZKEYNAME9X + handle.Close() + return TZKEYNAME + + +TZKEYNAME = _settzkeyname() + + +class tzres(object): + """ + Class for accessing ``tzres.dll``, which contains timezone name related + resources. + + .. versionadded:: 2.5.0 + """ + p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char + + def __init__(self, tzres_loc='tzres.dll'): + # Load the user32 DLL so we can load strings from tzres + user32 = ctypes.WinDLL('user32') + + # Specify the LoadStringW function + user32.LoadStringW.argtypes = (wintypes.HINSTANCE, + wintypes.UINT, + wintypes.LPWSTR, + ctypes.c_int) + + self.LoadStringW = user32.LoadStringW + self._tzres = ctypes.WinDLL(tzres_loc) + self.tzres_loc = tzres_loc + + def load_name(self, offset): + """ + Load a timezone name from a DLL offset (integer). + + >>> from dateutil.tzwin import tzres + >>> tzr = tzres() + >>> print(tzr.load_name(112)) + 'Eastern Standard Time' + + :param offset: + A positive integer value referring to a string from the tzres dll. + + .. note:: + + Offsets found in the registry are generally of the form + ``@tzres.dll,-114``. The offset in this case is 114, not -114. + + """ + resource = self.p_wchar() + lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) + nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) + return resource[:nchar] + + def name_from_string(self, tzname_str): + """ + Parse strings as returned from the Windows registry into the time zone + name as defined in the registry. + + >>> from dateutil.tzwin import tzres + >>> tzr = tzres() + >>> print(tzr.name_from_string('@tzres.dll,-251')) + 'Dateline Daylight Time' + >>> print(tzr.name_from_string('Eastern Standard Time')) + 'Eastern Standard Time' + + :param tzname_str: + A timezone name string as returned from a Windows registry key. + + :return: + Returns the localized timezone string from tzres.dll if the string + is of the form `@tzres.dll,-offset`, else returns the input string. + """ + if not tzname_str.startswith('@'): + return tzname_str + + name_splt = tzname_str.split(',-') + try: + offset = int(name_splt[1]) + except: + raise ValueError("Malformed timezone string.") + + return self.load_name(offset) + + +class tzwinbase(tzrangebase): + """tzinfo class based on win32's timezones available in the registry.""" + def __init__(self): + raise NotImplementedError('tzwinbase is an abstract base class') + + def __eq__(self, other): + # Compare on all relevant dimensions, including name. + if not isinstance(other, tzwinbase): + return NotImplemented + + return (self._std_offset == other._std_offset and + self._dst_offset == other._dst_offset and + self._stddayofweek == other._stddayofweek and + self._dstdayofweek == other._dstdayofweek and + self._stdweeknumber == other._stdweeknumber and + self._dstweeknumber == other._dstweeknumber and + self._stdhour == other._stdhour and + self._dsthour == other._dsthour and + self._stdminute == other._stdminute and + self._dstminute == other._dstminute and + self._std_abbr == other._std_abbr and + self._dst_abbr == other._dst_abbr) + + @staticmethod + def list(): + """Return a list of all time zones known to the system.""" + with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: + with winreg.OpenKey(handle, TZKEYNAME) as tzkey: + result = [winreg.EnumKey(tzkey, i) + for i in range(winreg.QueryInfoKey(tzkey)[0])] + return result + + def display(self): + """ + Return the display name of the time zone. + """ + return self._display + + def transitions(self, year): + """ + For a given year, get the DST on and off transition times, expressed + always on the standard time side. For zones with no transitions, this + function returns ``None``. + + :param year: + The year whose transitions you would like to query. + + :return: + Returns a :class:`tuple` of :class:`datetime.datetime` objects, + ``(dston, dstoff)`` for zones with an annual DST transition, or + ``None`` for fixed offset zones. + """ + + if not self.hasdst: + return None + + dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, + self._dsthour, self._dstminute, + self._dstweeknumber) + + dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, + self._stdhour, self._stdminute, + self._stdweeknumber) + + # Ambiguous dates default to the STD side + dstoff -= self._dst_base_offset + + return dston, dstoff + + def _get_hasdst(self): + return self._dstmonth != 0 + + @property + def _dst_base_offset(self): + return self._dst_base_offset_ + + +class tzwin(tzwinbase): + """ + Time zone object created from the zone info in the Windows registry + + These are similar to :py:class:`dateutil.tz.tzrange` objects in that + the time zone data is provided in the format of a single offset rule + for either 0 or 2 time zone transitions per year. + + :param: name + The name of a Windows time zone key, e.g. "Eastern Standard Time". + The full list of keys can be retrieved with :func:`tzwin.list`. + """ + + def __init__(self, name): + self._name = name + + with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: + tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name) + with winreg.OpenKey(handle, tzkeyname) as tzkey: + keydict = valuestodict(tzkey) + + self._std_abbr = keydict["Std"] + self._dst_abbr = keydict["Dlt"] + + self._display = keydict["Display"] + + # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm + tup = struct.unpack("=3l16h", keydict["TZI"]) + stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 + dstoffset = stdoffset-tup[2] # + DaylightBias * -1 + self._std_offset = datetime.timedelta(minutes=stdoffset) + self._dst_offset = datetime.timedelta(minutes=dstoffset) + + # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs + # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx + (self._stdmonth, + self._stddayofweek, # Sunday = 0 + self._stdweeknumber, # Last = 5 + self._stdhour, + self._stdminute) = tup[4:9] + + (self._dstmonth, + self._dstdayofweek, # Sunday = 0 + self._dstweeknumber, # Last = 5 + self._dsthour, + self._dstminute) = tup[12:17] + + self._dst_base_offset_ = self._dst_offset - self._std_offset + self.hasdst = self._get_hasdst() + + def __repr__(self): + return "tzwin(%s)" % repr(self._name) + + def __reduce__(self): + return (self.__class__, (self._name,)) + + +class tzwinlocal(tzwinbase): + """ + Class representing the local time zone information in the Windows registry + + While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` + module) to retrieve time zone information, ``tzwinlocal`` retrieves the + rules directly from the Windows registry and creates an object like + :class:`dateutil.tz.tzwin`. + + Because Windows does not have an equivalent of :func:`time.tzset`, on + Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the + time zone settings *at the time that the process was started*, meaning + changes to the machine's time zone settings during the run of a program + on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`. + Because ``tzwinlocal`` reads the registry directly, it is unaffected by + this issue. + """ + def __init__(self): + with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: + with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: + keydict = valuestodict(tzlocalkey) + + self._std_abbr = keydict["StandardName"] + self._dst_abbr = keydict["DaylightName"] + + try: + tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME, + sn=self._std_abbr) + with winreg.OpenKey(handle, tzkeyname) as tzkey: + _keydict = valuestodict(tzkey) + self._display = _keydict["Display"] + except OSError: + self._display = None + + stdoffset = -keydict["Bias"]-keydict["StandardBias"] + dstoffset = stdoffset-keydict["DaylightBias"] + + self._std_offset = datetime.timedelta(minutes=stdoffset) + self._dst_offset = datetime.timedelta(minutes=dstoffset) + + # For reasons unclear, in this particular key, the day of week has been + # moved to the END of the SYSTEMTIME structure. + tup = struct.unpack("=8h", keydict["StandardStart"]) + + (self._stdmonth, + self._stdweeknumber, # Last = 5 + self._stdhour, + self._stdminute) = tup[1:5] + + self._stddayofweek = tup[7] + + tup = struct.unpack("=8h", keydict["DaylightStart"]) + + (self._dstmonth, + self._dstweeknumber, # Last = 5 + self._dsthour, + self._dstminute) = tup[1:5] + + self._dstdayofweek = tup[7] + + self._dst_base_offset_ = self._dst_offset - self._std_offset + self.hasdst = self._get_hasdst() + + def __repr__(self): + return "tzwinlocal()" + + def __str__(self): + # str will return the standard name, not the daylight name. + return "tzwinlocal(%s)" % repr(self._std_abbr) + + def __reduce__(self): + return (self.__class__, ()) + + +def picknthweekday(year, month, dayofweek, hour, minute, whichweek): + """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ + first = datetime.datetime(year, month, 1, hour, minute) + + # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), + # Because 7 % 7 = 0 + weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) + wd = weekdayone + ((whichweek - 1) * ONEWEEK) + if (wd.month != month): + wd -= ONEWEEK + + return wd + + +def valuestodict(key): + """Convert a registry key's values to a dictionary.""" + dout = {} + size = winreg.QueryInfoKey(key)[1] + tz_res = None + + for i in range(size): + key_name, value, dtype = winreg.EnumValue(key, i) + if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: + # If it's a DWORD (32-bit integer), it's stored as unsigned - convert + # that to a proper signed integer + if value & (1 << 31): + value = value - (1 << 32) + elif dtype == winreg.REG_SZ: + # If it's a reference to the tzres DLL, load the actual string + if value.startswith('@tzres'): + tz_res = tz_res or tzres() + value = tz_res.name_from_string(value) + + value = value.rstrip('\x00') # Remove trailing nulls + + dout[key_name] = value + + return dout diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/tzwin.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/tzwin.py new file mode 100644 index 0000000000000000000000000000000000000000..cebc673e40fc376653ebf037e96f0a6d0b33e906 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/tzwin.py @@ -0,0 +1,2 @@ +# tzwin has moved to dateutil.tz.win +from .tz.win import * diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/utils.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dd2d245a0bebcd5fc37ac20526aabbd5358dab0e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/utils.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +""" +This module offers general convenience and utility functions for dealing with +datetimes. + +.. versionadded:: 2.7.0 +""" +from __future__ import unicode_literals + +from datetime import datetime, time + + +def today(tzinfo=None): + """ + Returns a :py:class:`datetime` representing the current day at midnight + + :param tzinfo: + The time zone to attach (also used to determine the current day). + + :return: + A :py:class:`datetime.datetime` object representing the current day + at midnight. + """ + + dt = datetime.now(tzinfo) + return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) + + +def default_tzinfo(dt, tzinfo): + """ + Sets the ``tzinfo`` parameter on naive datetimes only + + This is useful for example when you are provided a datetime that may have + either an implicit or explicit time zone, such as when parsing a time zone + string. + + .. doctest:: + + >>> from dateutil.tz import tzoffset + >>> from dateutil.parser import parse + >>> from dateutil.utils import default_tzinfo + >>> dflt_tz = tzoffset("EST", -18000) + >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) + 2014-01-01 12:30:00+00:00 + >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) + 2014-01-01 12:30:00-05:00 + + :param dt: + The datetime on which to replace the time zone + + :param tzinfo: + The :py:class:`datetime.tzinfo` subclass instance to assign to + ``dt`` if (and only if) it is naive. + + :return: + Returns an aware :py:class:`datetime.datetime`. + """ + if dt.tzinfo is not None: + return dt + else: + return dt.replace(tzinfo=tzinfo) + + +def within_delta(dt1, dt2, delta): + """ + Useful for comparing two datetimes that may have a negligible difference + to be considered equal. + """ + delta = abs(delta) + difference = dt1 - dt2 + return -delta <= difference <= delta diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/._dateutil-zoneinfo.tar.gz b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/._dateutil-zoneinfo.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..1a316d03852d90a87a52d7747cdf1a6805e49e0f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/._dateutil-zoneinfo.tar.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbd1f4c19356c9f782c0fce50a927d08f5a7a89ae88cc56fe8e671aeba8ef15d +size 4096 diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/._rebuild.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/._rebuild.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/._rebuild.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/__init__.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34f11ad66c88047f2c049a4cdcc937b4b78ea6d6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/__init__.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +import warnings +import json + +from tarfile import TarFile +from pkgutil import get_data +from io import BytesIO + +from dateutil.tz import tzfile as _tzfile + +__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] + +ZONEFILENAME = "dateutil-zoneinfo.tar.gz" +METADATA_FN = 'METADATA' + + +class tzfile(_tzfile): + def __reduce__(self): + return (gettz, (self._filename,)) + + +def getzoneinfofile_stream(): + try: + return BytesIO(get_data(__name__, ZONEFILENAME)) + except IOError as e: # TODO switch to FileNotFoundError? + warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror)) + return None + + +class ZoneInfoFile(object): + def __init__(self, zonefile_stream=None): + if zonefile_stream is not None: + with TarFile.open(fileobj=zonefile_stream) as tf: + self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name) + for zf in tf.getmembers() + if zf.isfile() and zf.name != METADATA_FN} + # deal with links: They'll point to their parent object. Less + # waste of memory + links = {zl.name: self.zones[zl.linkname] + for zl in tf.getmembers() if + zl.islnk() or zl.issym()} + self.zones.update(links) + try: + metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) + metadata_str = metadata_json.read().decode('UTF-8') + self.metadata = json.loads(metadata_str) + except KeyError: + # no metadata in tar file + self.metadata = None + else: + self.zones = {} + self.metadata = None + + def get(self, name, default=None): + """ + Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method + for retrieving zones from the zone dictionary. + + :param name: + The name of the zone to retrieve. (Generally IANA zone names) + + :param default: + The value to return in the event of a missing key. + + .. versionadded:: 2.6.0 + + """ + return self.zones.get(name, default) + + +# The current API has gettz as a module function, although in fact it taps into +# a stateful class. So as a workaround for now, without changing the API, we +# will create a new "global" class instance the first time a user requests a +# timezone. Ugly, but adheres to the api. +# +# TODO: Remove after deprecation period. +_CLASS_ZONE_INSTANCE = [] + + +def get_zonefile_instance(new_instance=False): + """ + This is a convenience function which provides a :class:`ZoneInfoFile` + instance using the data provided by the ``dateutil`` package. By default, it + caches a single instance of the ZoneInfoFile object and returns that. + + :param new_instance: + If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and + used as the cached instance for the next call. Otherwise, new instances + are created only as necessary. + + :return: + Returns a :class:`ZoneInfoFile` object. + + .. versionadded:: 2.6 + """ + if new_instance: + zif = None + else: + zif = getattr(get_zonefile_instance, '_cached_instance', None) + + if zif is None: + zif = ZoneInfoFile(getzoneinfofile_stream()) + + get_zonefile_instance._cached_instance = zif + + return zif + + +def gettz(name): + """ + This retrieves a time zone from the local zoneinfo tarball that is packaged + with dateutil. + + :param name: + An IANA-style time zone name, as found in the zoneinfo file. + + :return: + Returns a :class:`dateutil.tz.tzfile` time zone object. + + .. warning:: + It is generally inadvisable to use this function, and it is only + provided for API compatibility with earlier versions. This is *not* + equivalent to ``dateutil.tz.gettz()``, which selects an appropriate + time zone based on the inputs, favoring system zoneinfo. This is ONLY + for accessing the dateutil-specific zoneinfo (which may be out of + date compared to the system zoneinfo). + + .. deprecated:: 2.6 + If you need to use a specific zoneinfofile over the system zoneinfo, + instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call + :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. + + Use :func:`get_zonefile_instance` to retrieve an instance of the + dateutil-provided zoneinfo. + """ + warnings.warn("zoneinfo.gettz() will be removed in future versions, " + "to use the dateutil-provided zoneinfo files, instantiate a " + "ZoneInfoFile object and use ZoneInfoFile.zones.get() " + "instead. See the documentation for details.", + DeprecationWarning) + + if len(_CLASS_ZONE_INSTANCE) == 0: + _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) + return _CLASS_ZONE_INSTANCE[0].zones.get(name) + + +def gettz_db_metadata(): + """ Get the zonefile metadata + + See `zonefile_metadata`_ + + :returns: + A dictionary with the database metadata + + .. deprecated:: 2.6 + See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, + query the attribute ``zoneinfo.ZoneInfoFile.metadata``. + """ + warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " + "versions, to use the dateutil-provided zoneinfo files, " + "ZoneInfoFile object and query the 'metadata' attribute " + "instead. See the documentation for details.", + DeprecationWarning) + + if len(_CLASS_ZONE_INSTANCE) == 0: + _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) + return _CLASS_ZONE_INSTANCE[0].metadata diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..ff62a934a5009337271c60501278a7a34913a20b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3ea52e7b6e968de0d884df1288193596fa95b803db4f92a18279a7398004475 +size 156400 diff --git a/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/rebuild.py b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/rebuild.py new file mode 100644 index 0000000000000000000000000000000000000000..684c6586f091350c347f2b6150935f5214ffec27 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/dateutil/zoneinfo/rebuild.py @@ -0,0 +1,75 @@ +import logging +import os +import tempfile +import shutil +import json +from subprocess import check_call, check_output +from tarfile import TarFile + +from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME + + +def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): + """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* + + filename is the timezone tarball from ``ftp.iana.org/tz``. + + """ + tmpdir = tempfile.mkdtemp() + zonedir = os.path.join(tmpdir, "zoneinfo") + moduledir = os.path.dirname(__file__) + try: + with TarFile.open(filename) as tf: + for name in zonegroups: + tf.extract(name, tmpdir) + filepaths = [os.path.join(tmpdir, n) for n in zonegroups] + + _run_zic(zonedir, filepaths) + + # write metadata file + with open(os.path.join(zonedir, METADATA_FN), 'w') as f: + json.dump(metadata, f, indent=4, sort_keys=True) + target = os.path.join(moduledir, ZONEFILENAME) + with TarFile.open(target, "w:%s" % format) as tf: + for entry in os.listdir(zonedir): + entrypath = os.path.join(zonedir, entry) + tf.add(entrypath, entry) + finally: + shutil.rmtree(tmpdir) + + +def _run_zic(zonedir, filepaths): + """Calls the ``zic`` compiler in a compatible way to get a "fat" binary. + + Recent versions of ``zic`` default to ``-b slim``, while older versions + don't even have the ``-b`` option (but default to "fat" binaries). The + current version of dateutil does not support Version 2+ TZif files, which + causes problems when used in conjunction with "slim" binaries, so this + function is used to ensure that we always get a "fat" binary. + """ + + try: + help_text = check_output(["zic", "--help"]) + except OSError as e: + _print_on_nosuchfile(e) + raise + + if b"-b " in help_text: + bloat_args = ["-b", "fat"] + else: + bloat_args = [] + + check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths) + + +def _print_on_nosuchfile(e): + """Print helpful troubleshooting message + + e is an exception raised by subprocess.check_call() + + """ + if e.errno == 2: + logging.error( + "Could not find zic. Perhaps you need to install " + "libc-bin or some other package that provides it, " + "or it's not in your PATH?") diff --git a/.venv_haddock/lib/python3.12/site-packages/distutils-precedence.pth b/.venv_haddock/lib/python3.12/site-packages/distutils-precedence.pth new file mode 100644 index 0000000000000000000000000000000000000000..c659194195f07bd6f19b5522515551309af14a3d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/distutils-precedence.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2638ce9e2500e572a5e0de7faed6661eb569d1b696fcba07b0dd223da5f5d224 +size 151 diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._INSTALLER b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._INSTALLER differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._METADATA b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._METADATA differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._RECORD b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._RECORD differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._WHEEL b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._WHEEL differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._licenses b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._licenses new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._licenses differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._top_level.txt b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/._top_level.txt differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..da4623c2df72438087c0a853b9f7cf4c9515525b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/METADATA @@ -0,0 +1,28 @@ +Metadata-Version: 2.4 +Name: freesasa +Version: 2.2.1 +Summary: Calculate solvent accessible surface areas of proteins +Home-page: http://freesasa.github.io/ +Author: Simon Mitternacht +License: MIT +Keywords: structural biology,proteins,bioinformatics +Classifier: Development Status :: 5 - Production/Stable +Classifier: Topic :: Scientific/Engineering :: Bio-Informatics +Classifier: Topic :: Scientific/Engineering :: Chemistry +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +License-File: LICENSE.txt +Dynamic: author +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: summary + +This module provides bindings for the FreeSASA C library. See http://freesasa.github.io/python/ for documentation. diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d896abc2d0da828ce763b247cf951684f820ad96 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/RECORD @@ -0,0 +1,34 @@ +../../../include/site/python3.12/freesasa/classifier.c,sha256=QuOypS0HeJsvfC00uJQRIfy3B9ESyL5xiZxr2nwQzkc,35591 +../../../include/site/python3.12/freesasa/classifier.h,sha256=sOKgAMIOXDWWbqsCCVzvsaRPuryifufjbtZUc2HQQ3E,3892 +../../../include/site/python3.12/freesasa/classifier_naccess.c,sha256=zvtxtks_MLjXjOibwJEO9avBL2Kxb1Wdnfm6Rtud5Fg,21027 +../../../include/site/python3.12/freesasa/classifier_oons.c,sha256=TCq2jX6JRDUSDj6XPGsRZ5bWNgeSmsNrJntrNG58StA,15528 +../../../include/site/python3.12/freesasa/classifier_protor.c,sha256=smnSPFn73TDSeKkhOKdywELYbUnRcC-vYdMX0ds0Fog,32827 +../../../include/site/python3.12/freesasa/coord.c,sha256=4Z7x-9uBdMt4QXrrX6YJuFMXi0vIeWdJEmMTktzjVwQ,6745 +../../../include/site/python3.12/freesasa/coord.h,sha256=X2wcRh-4p5ohI1snT4wKIO68VVwL4LfLhsZxOJnM9Ps,9655 +../../../include/site/python3.12/freesasa/freesasa.c,sha256=HdK4t5ziSaFFb87MPjBfuTA1fX3Lugt9LwXlIRaewFY,6264 +../../../include/site/python3.12/freesasa/freesasa.h,sha256=HzQtufMN6g_XJyBFXIetrgjgEQljx6DoNRaZyi8VU88,49886 +../../../include/site/python3.12/freesasa/freesasa_internal.h,sha256=_xQzC0bVomyLhRw-2RrOX3dq22StxL8f4Qi61CWndmQ,14465 +../../../include/site/python3.12/freesasa/lexer.c,sha256=W5aUyYV6Gw0bseRnPGP6FI8Z32chj9e460dstgB-m98,61622 +../../../include/site/python3.12/freesasa/lexer.h,sha256=sXp5aWS_NgsRXYPmplaE1GhTTTkUW42L8jrjIgXXgVA,8630 +../../../include/site/python3.12/freesasa/log.c,sha256=vW5bCZYHcP4IARFlDP7z853KkEdlR5nn9q0G4UxeOv0,7861 +../../../include/site/python3.12/freesasa/nb.c,sha256=6_h6oq1lyBAd4XwDil2oTrxtEpFM7eGAuQeM9QOy6_4,15541 +../../../include/site/python3.12/freesasa/nb.h,sha256=jaKOzW6-YVQzNLFeypvt7SouCxMoYv2liqBIGtEE4WU,2041 +../../../include/site/python3.12/freesasa/node.c,sha256=0BWahd-TV0QXKFAJgVsHa7SExsrsEGxVoMJnv3PYRT8,19924 +../../../include/site/python3.12/freesasa/parser.c,sha256=MBsZ8NX8TgbDPkVEGXjoYPNIwLN5pXL36-953vd76ms,51255 +../../../include/site/python3.12/freesasa/parser.h,sha256=nO9gF0kztlJE1nnabh-msSv-PABZN6lQepL-6_hFclA,2723 +../../../include/site/python3.12/freesasa/pdb.c,sha256=sabnoL63I_3k9aeiSZEeRPVwKFrd920XMvowxMUc_e8,12746 +../../../include/site/python3.12/freesasa/pdb.h,sha256=DZDM0KcSkjvwfC9YFRYyUsxG6OMeAnokl9coQs6nBEA,6761 +../../../include/site/python3.12/freesasa/rsa.c,sha256=OiNoqehuFGHtZBc-hEUcp7_Vo480YwO5mQwwdoPdKq0,6056 +../../../include/site/python3.12/freesasa/sasa_lr.c,sha256=W7meigB7HWeafmYcToLkFOw06NI3PFEkJjXQjOyUo7A,13910 +../../../include/site/python3.12/freesasa/sasa_sr.c,sha256=bJg7HZpSAABD10H5Fx9_YdFzmoJVB4wIGflnaHkCmho,9542 +../../../include/site/python3.12/freesasa/selection.c,sha256=2E7hqhHawETKspw2eoK7w_s2drTuuZgfeI31GMEJWXo,27380 +../../../include/site/python3.12/freesasa/selection.h,sha256=4hN-ryHR6g-Lu2cqwE23cb5_HOKSg1riOtQtAJGj4_A,1345 +../../../include/site/python3.12/freesasa/structure.c,sha256=qc97rrNNYv-WqkqgskSOZcvCgWr84lRVeJcKf87fa_Q,35165 +../../../include/site/python3.12/freesasa/util.c,sha256=RffIRstokC0qsiiwZKMx5pKMSW8EWWvwXRoZWIZ61X0,2786 +freesasa-2.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +freesasa-2.2.1.dist-info/METADATA,sha256=HlSBCXpnLYfB9COp1efDUjYPhx1mb1CYEnWUGjatpQA,1017 +freesasa-2.2.1.dist-info/RECORD,, +freesasa-2.2.1.dist-info/WHEEL,sha256=CltXN3lQvXbHxKDtiDwW0RNzF8s2WyBuPbOAX_ZeQlA,109 +freesasa-2.2.1.dist-info/licenses/LICENSE.txt,sha256=wszU7NQ3S0N_vNRFEQF27pIPlZtcknvqIxqRbJOfp0U,1085 +freesasa-2.2.1.dist-info/top_level.txt,sha256=lrUU06PGnY5L5fM8Sm8XZBESUDWcf0rlRoEIHREIAS0,9 +freesasa.cpython-312-darwin.so,sha256=_PFdHl19_V5VKB6kQyIodQwkA5hXnH32t6pxcQxA2wM,455360 diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8d50c4c4341e43d84cba38818c2df1cac345e13b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-macosx_11_0_arm64 + diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/licenses/._LICENSE.txt b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/licenses/._LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/licenses/._LICENSE.txt differ diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/licenses/LICENSE.txt b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..430cb7a557e5b7fdf0db9413a56fba1438937390 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Simon Mitternacht + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/top_level.txt b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e50ca32c064787a6eb7261eb8937f021f37e15a0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa-2.2.1.dist-info/top_level.txt @@ -0,0 +1 @@ +freesasa diff --git a/.venv_haddock/lib/python3.12/site-packages/freesasa.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/freesasa.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..f96e88876fbdeac431a3b3bc925406f450f03971 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/freesasa.cpython-312-darwin.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcf15d1e5d7dfd5e55281ea4432228750c240398579c7df6b7aa71710c40db03 +size 455360 diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/haddock/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._bin b/.venv_haddock/lib/python3.12/site-packages/haddock/._bin new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._bin differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._clis b/.venv_haddock/lib/python3.12/site-packages/haddock/._clis new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._clis differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._cns b/.venv_haddock/lib/python3.12/site-packages/haddock/._cns new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._cns differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._core b/.venv_haddock/lib/python3.12/site-packages/haddock/._core new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._core differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._deps b/.venv_haddock/lib/python3.12/site-packages/haddock/._deps new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._deps differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._fcc b/.venv_haddock/lib/python3.12/site-packages/haddock/._fcc new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._fcc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._gear b/.venv_haddock/lib/python3.12/site-packages/haddock/._gear new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._gear differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._libs b/.venv_haddock/lib/python3.12/site-packages/haddock/._libs new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._libs differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._modules b/.venv_haddock/lib/python3.12/site-packages/haddock/._modules new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._modules differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/._prodrg b/.venv_haddock/lib/python3.12/site-packages/haddock/._prodrg new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/._prodrg differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/__init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d7ebc862b9cf00bf77a7341904708973405541 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/__init__.py @@ -0,0 +1,47 @@ +"""HADDOCK3 library.""" +import logging +import sys +from pathlib import Path +from importlib.metadata import version as package_version + +log = logging.getLogger(__name__) +log.handlers.clear() +log.setLevel(logging.DEBUG) +handler = logging.StreamHandler(sys.stdout) +handler.setFormatter(logging.Formatter( + "[%(asctime)s %(module)s %(levelname)s] %(message)s")) +log.addHandler(handler) + +haddock3_source_path = Path(__file__).resolve().parent +haddock3_repository_path = haddock3_source_path.parents[1] +core_path = Path(haddock3_source_path, "core") +toppar_path = Path(haddock3_source_path, "cns", "toppar") +modules_defaults_path = Path(haddock3_source_path, "modules", "defaults.yaml") + +FCC_path = Path(haddock3_source_path.parent, 'fcc') +RMSD_path = Path(haddock3_source_path.parent, 'fast-rmsdmatrix') + +config_expert_levels = ("easy", "expert", "guru") +# yaml parameters with this `explevel` should be ignored when reading the yaml +_hidden_level = "hidden" + + +class EmptyPath: + """Define the type EmptyPath.""" + + def __str__(self) -> str: + return "" + + def __repr__(self) -> str: + return "" + + def __bool__(self) -> bool: + return False + + +# version +version = package_version("haddock3") + +v_major, v_minor, v_patch = version.split('.') + +contact_us = 'https://github.com/haddocking/haddock3/issues' diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._contact_fcc b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._contact_fcc new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._contact_fcc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._contact_fcc.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._contact_fcc.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._contact_fcc.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._fast-rmsdmatrix b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._fast-rmsdmatrix new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._fast-rmsdmatrix differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._fast_rmsdmatrix.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._fast_rmsdmatrix.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._fast_rmsdmatrix.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._haddock-restraints b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._haddock-restraints new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/._haddock-restraints differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/contact_fcc b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/contact_fcc new file mode 100644 index 0000000000000000000000000000000000000000..17e84b7305f56f47fcb0294197183e0371840a0d Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/contact_fcc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/contact_fcc.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/contact_fcc.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..0742ba3c30c90eef3b9bc7cb069dfd99403a50c8 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/contact_fcc.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/fast-rmsdmatrix b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/fast-rmsdmatrix new file mode 100644 index 0000000000000000000000000000000000000000..bebc981b8ad871a14170094b9505c0dee6052704 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/fast-rmsdmatrix differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/fast_rmsdmatrix.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/fast_rmsdmatrix.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..f9318bc50d0658dc8648988d81d0fc70fd11f873 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/fast_rmsdmatrix.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/bin/haddock-restraints b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/haddock-restraints new file mode 100644 index 0000000000000000000000000000000000000000..6e135d631cfa8da2f1c3b8b3a9a35e39a8a5f788 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/bin/haddock-restraints @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0dab3ca8b90da46b6370bd6af48968dd3dcdb9deb8f6a085a6d0cce4f4f1ea69 +size 2157456 diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_analyse.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_analyse.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_analyse.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_cfg.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_cfg.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_clean.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_clean.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_cp.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_cp.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_dmn.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_dmn.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_dmn.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_mpi.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_mpi.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_mpi.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_pp.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_pp.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_pp.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_re.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_re.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_re.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_restraints.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_restraints.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_restraints.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_score.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_score.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_score.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_traceback.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_traceback.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_traceback.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_unpack.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._cli_unpack.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._re b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._re new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._re differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._restraints b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._restraints new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._restraints differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._wrapper_haddock_restraints.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._wrapper_haddock_restraints.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/._wrapper_haddock_restraints.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/__init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..768d257c08d65d903d0f1b343cfd4825e0248ceb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/__init__.py @@ -0,0 +1,8 @@ +""" +Command-line interfaces. + +HADDOCK3 has a series of command-line interfaces (CLIs), from which the most important +one is ``haddock3``. You can ask help to the CLIs with the ``-h`` flag:: + + haddock3 -h +""" diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..65e4b78e7cf4b17556be81d1433f0fdece4c550b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +""" +Run HADDOCK3 docking simulation. + +This is the main command-line client to run HADDOCK3 docking +simulations. To prepare a simulation, setup configuration file defining +a HADDOCK3 workflow and use this command-line client to execute that +workflow. + +Usage:: + + haddock3 -h + haddock3 +""" +import argparse +import sys +from pathlib import Path + +from haddock import log +from haddock.core.defaults import RUNDIR +from haddock.core.typing import ( + ArgumentParser, + Callable, + FilePath, + LogLevel, + Namespace, + Optional, +) +from haddock.gear.extend_run import EXTEND_RUN_DEFAULT, add_extend_run +from haddock.gear.restart_run import add_restart_arg +from haddock.libs.libcli import add_version_arg, arg_file_exist +from haddock.libs.liblog import add_loglevel_arg + + +# Command line interface parser +ap = argparse.ArgumentParser() + +ap.add_argument( + "workflow", + type=arg_file_exist, + help=( + "The input configuration file path describing " + "the workflow to be performed" + ), + ) + +add_restart_arg(ap) +add_extend_run(ap) + +ap.add_argument( + "--setup", + help="Only setup the run, do not execute", + action="store_true", + dest="setup_only", +) + +add_loglevel_arg(ap) +add_version_arg(ap) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(_ap(), main) + + +def main( + workflow: FilePath, + restart: Optional[int] = None, + extend_run: Optional[FilePath] = EXTEND_RUN_DEFAULT, + setup_only: bool = False, + log_level: LogLevel = "INFO", +) -> None: + """ + Run an HADDOCK3 workflow. + + Parameters + ---------- + workflow : str or pathlib.Path + The path to the workflow (config file). + + restart : int + The step to restart the run from (inclusive). + Defaults to None, which ignores this option. + + extend_run : str or Path + The path created with `haddock3-copy` to start the run from. + Defaults to None, which ignores this option. + + setup_only : bool, optional + Whether to setup the run without running it. + Defaults to False. + + log_level : str, optional + The logging level: INFO, DEBUG, ERROR, WARNING, CRITICAL. + """ + # anti-pattern to speed up CLI initiation + from time import time + + from haddock.gear.extend_run import WorkflowManagerExtend + from haddock.gear.greetings import ( + get_adieu, + get_initial_greeting, + gen_feedback_messages, + ) + from haddock.gear.postprocessing import archive_run + from haddock.gear.prepare_run import setup_run + from haddock.libs.libio import working_directory + from haddock.libs.liblog import ( + add_log_for_CLI, + add_stringio_handler, + log_file_name, + log_formatters, + ) + from haddock.libs.libtimer import convert_seconds_to_min_sec + from haddock.libs.libutil import log_error_and_exit + from haddock.libs.libworkflow import WorkflowManager + from haddock.modules import get_module_steps_folders + + start = time() + # the io.StringIO handler is a trick to save the log while run_dir + # is not read from the configuration file and the log can be saved + # in the final file. + # + # Nonetheless, the log is saved in stdout and stderr in case it + # breaks before the actual logfile is defined. + # See lines further down on how we resolve this trick + add_stringio_handler( + log, + log_level=log_level, + formatter=log_formatters[log_level], + ) + + log.info(get_initial_greeting()) + + with log_error_and_exit(): + params, other_params = setup_run( + workflow, + restart_from=restart, + extend_run=extend_run, + ) + + # here we the io.StringIO handler log information, and reset the log + # handlers to fit the CLI and HADDOCK3 specifications. + log_temporary = log.handlers[-1].stream.getvalue() # type: ignore + _run_dir: str = other_params[RUNDIR] + log_file = Path(_run_dir, log_file_name) + add_log_for_CLI(log, log_level, log_file) + + # here we append the log information in the previous io.StringIO() + # handler in the log file already in the run_dir + with open(log_file, "a") as fout: + fout.write(log_temporary) + + if setup_only: + log.info("We have setup the run, only.") + gen_feedback_messages(log.info) + log.info(get_adieu()) + return + + if extend_run: + steps_folders = get_module_steps_folders(extend_run) + restart_step = max([int(fold.split('_')[0]) for fold in steps_folders]) + restart_step += 1 + WorkflowManager_ = WorkflowManagerExtend + + else: + restart_step = restart + WorkflowManager_ = WorkflowManager + + with (working_directory(_run_dir), log_error_and_exit()): + workflow = WorkflowManager_( + workflow_params=params, + start=restart_step, + **other_params, + ) + + # Main loop of execution + workflow.run() + + # Run post-processing steps + if other_params["postprocess"]: + workflow.postprocess(self_contained=other_params["gen_archive"]) + # Clean outputs + workflow.clean() + + # Generate archive of the run + if other_params["gen_archive"]: + _run_archive, _analysis_archive = archive_run(_run_dir) + log.info(f"Run archive created: {_run_archive}!") + if _analysis_archive: + log.info(f"Run analysis archive created: {_analysis_archive}") + + # Finish + end = time() + elapsed = convert_seconds_to_min_sec(end - start) + log.info(f"This HADDOCK3 run took: {elapsed}") + gen_feedback_messages(log.info) + log.info(get_adieu()) + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_analyse.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_analyse.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec4779a0a9abb53b32f530b99e6ca4465ff9cff --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_analyse.py @@ -0,0 +1,864 @@ +""" +Analyse a set of steps of a run. + +Considering the example run:: + + run1/ + 0_topoaa/ + 1_rigidbody/ + 2_seletop/ + 3_flexref/ + (etc...) + + +USAGE:: + + haddock3-analyse -r -m + haddock3-analyse -r run1 -m 1 3 + + +Where, ``-m 1 3`` means that the analysis will be performed on ``1_rigidbody`` + and ``3_flexref``. +""" + +import argparse +import os +import shutil +import sys +from pathlib import Path + +from haddock import log +from haddock.clis.cli_unpack import main as haddock3_unpack +from haddock.clis.cli_clean import main as haddock3_clean +from haddock.core.defaults import INTERACTIVE_RE_SUFFIX +from haddock.core.typing import ( + Any, + ArgumentParser, + Callable, + FilePath, + ImgFormat, + Namespace, + Optional, + ParamDict, + ParamMap, + ) +from haddock.gear.yaml2cfg import read_from_yaml_config +from haddock.gear.clean_steps import _unpack_gz +from haddock.libs.libcli import _ParamsToDict +from haddock.libs.libio import archive_files_ext +from haddock.libs.libontology import ModuleIO +from haddock.libs.libplots import ( + ClRank, + box_plot_handler, + clt_table_handler, + read_capri_table, + report_generator, + scatter_plot_handler, + SUPPORTED_OUTPUT_FORMATS, + ) +from haddock.modules import get_module_steps_folders +from haddock.modules.analysis.caprieval import ( + DEFAULT_CONFIG as caprieval_params, + ) +from haddock.modules.analysis.caprieval import HaddockModule + + +ANA_FOLDER = "analysis" # name of the analysis folder +INTER_STR = INTERACTIVE_RE_SUFFIX # suffix of interactive analysis folders + + +# Command line interface parser +ap = argparse.ArgumentParser( + prog="haddock3-analyse", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +ap.add_argument( + "-r", + "--run-dir", + help="The input run directory.", + required=True, +) + +ap.add_argument( + "-m", + "--modules", + nargs="+", + help="The number of the steps to copy.", + required=True, + type=int, +) + +ap.add_argument( + "-t", + "--top_clusters", + help="The number of clusters to show.", + required=False, + type=int, + default=10, +) + +ap.add_argument( + "--format", + help="produce images in the desired format", + required=False, + type=str, + default=None, + choices=list(SUPPORTED_OUTPUT_FORMATS), +) + +ap.add_argument( + "--scale", help="scale for images", required=False, type=float, default=1.0 +) + +ap.add_argument( + "--inter", + help="interactive analysis", + required=False, + type=bool, + default=False, + ) + +ap.add_argument( + "--is_cleaned", + help="is the directory going to be cleaned?", + required=False, + type=bool, + default=False, +) + +ap.add_argument( + "--offline", + help="Should plots js functions be self-contained?", + required=False, + type=bool, + default=False, +) + +ap.add_argument( + "--mode", + help="mode of execution", + required=False, + type=str, + default="local", + choices=["local", "batch", "mpi"], +) + +ap.add_argument( + "--ncores", + help="number of cores to use", + required=False, + type=int, + default=1, +) + +ap.add_argument( + "--self-contained", + help="If self-contained is set, models will be copied locally in the analysis directory, allowing to visualize structures outside of the haddock3 run.", + required=False, + default=False, + type=bool, +) + + +ap.add_argument( + "-p", + "--other-params", + dest="other_params", + help=( + "Any other parameter of the `caprieval` module." + "For example: -p reference_fname target.pdb." + "You can give any number of parameters." + ), + action=_ParamsToDict, + default={}, + nargs="*", +) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = vars(load_args(ap)) + kwargs = cmd.pop("other_params") + main(**cmd, **kwargs) + + +def maincli() -> None: + """Execute main client.""" + cli(_ap(), main) + + +def get_cluster_ranking( + capri_clt_filename: FilePath, + top_clusters: int, + ) -> ClRank: + """ + Get capri cluster ranking. + + Parameters + ---------- + capri_clt_filename : str or Path + capri cluster filename + top_clusters : int + Number of clusters to be considered + + Returns + ------- + cl_ranking : dict + {cluster_id : cluster_rank} dictionary + """ + cl_ranking: ClRank = {} + dfcl = read_capri_table(capri_clt_filename) + for n in range(min(top_clusters, dfcl.shape[0])): + cl_ranking[dfcl["cluster_id"].iloc[n]] = dfcl["caprieval_rank"].iloc[n] + return cl_ranking + + +def update_paths( + capri_ss_filename: FilePath, toch: str = "../", toadd: str = "../../" +) -> None: + """ + Update paths in capri_ss_filename. + + Parameters + ---------- + capri_ss_filename : str or Path + capri ss filename + toch : str + string to be replaced + toadd : str + string to be added + """ + new_lines: list[str] = [] + with open(capri_ss_filename, "r") as rfile: + for ln in rfile: + new_ln = ln.replace(toch, toadd) + new_lines.append(new_ln) + + with open(capri_ss_filename, "w") as wfile: + for ln in new_lines: + wfile.write(ln) + return + + +def run_capri_analysis( + step: str, + run_dir: FilePath, + capri_dict: ParamMap, + is_cleaned: bool, + mode: str, + ncores: int, + ) -> None: + """ + Run the caprieval analysis. + + Parameters + ---------- + step : str + step name + run_dir : str or Path + path to run directory + capri_dict : dict + capri dictionary of parameters + """ + # retrieve json file with all information + io = ModuleIO() + filename = Path("..", f"{step}/io.json") + io.load(filename) + # unpack the files if they are compressed + if is_cleaned: + path_to_unpack = io.output[0].rel_path.parent + haddock3_unpack(path_to_unpack, ncores=ncores) + # define step_order. We add one to it, as the caprieval module will + # interpret itself as being after the selected step + step_order = int(step.split("_")[0]) + 1 + # create capri + caprieval_module = HaddockModule( + order=step_order, + path=Path(run_dir), + init_params=caprieval_params, + ) + caprieval_module.update_params(**capri_dict) + # updating mode and ncores + caprieval_module.params["mode"] = mode + caprieval_module.params["ncores"] = ncores + # update model info + caprieval_module.previous_io = io + # run capri module + caprieval_module._run() + # compress files if they should be compressed + if is_cleaned: + haddock3_clean(path_to_unpack, ncores=ncores) + + +def update_capri_dict(default_capri: ParamDict, kwargs: ParamMap) -> ParamDict: + """ + Update capri dictionary. + + Parameters + ---------- + default_capri : dict + default capri dictionary of parameters + kwargs : dict + dictionary of input elements + + Returns + ------- + capri_dict : dict + updated capri dictionary of parameters + """ + capri_dict = default_capri.copy() + for param in kwargs: + if param not in default_capri: + sys.exit( + f"* ERROR * Parameter {param!r} is not " + "a valid `caprieval` parameter" + ) + else: + if param.endswith("fname"): # using full path for files + rel_path = Path(kwargs[param]) + _param = rel_path.resolve() + kwargs[param] = _param + capri_dict[param] = kwargs[param] + log.info(f"setting {param} to {kwargs[param]}") + + return capri_dict + + +def update_paths_in_capri_dict( + capri_dict: ParamDict, target_path: FilePath +) -> ParamDict: + """ + Make capri_dict specific to target_path. + + Parameters + ---------- + capri_dict : dict + capri dictionary of parameters + target_path : Path + path to the output folder + + Returns + ------- + new_capri_dict : dict + target_path-specific capri dictionary of parameters + """ + new_capri_dict = capri_dict.copy() + for key in new_capri_dict: + if key.endswith("fname") and new_capri_dict[key] not in ["", None]: + try: + ref_path = Path(target_path, "reference.pdb") + shutil.copy(new_capri_dict[key], ref_path) + new_capri_dict[key] = Path("reference.pdb") + except FileNotFoundError: + sys.exit(f"file not found {new_capri_dict[key]}") + return new_capri_dict + + +def get_top_ranked_mapping( + capri_filename: FilePath, + cluster_ranking: ClRank, + clustered_topX: int = 4, + unclustered_topX: int = 10, + ) -> dict[Path, Path]: + """Obtain mapping of top ranked files to their future paths. + + Parameters + ---------- + capri_filename : FilePath + capri_ss.tsv filepath + cluster_ranking : ClRank + Cluster ranking, if the form of {cluster_id: cluster_rank} dictionary + clustered_topX : int, optional + Number of models to access per cluster. Default is 4. + unclustered_topX : int, optional + Number of unclustered models to access. Default is 10. + + Returns + ------- + top_ranked_mapping : dict[Path, Path] + Mapping between original filepath and new (future) one + """ + # Set mapping of generated files + top_ranked_mapping: dict[Path, Path] = {} + + # Read table + capri_df = read_capri_table(capri_filename, comment="#") + # Group by clusters + gb_cluster = capri_df.groupby("cluster_id") + + # Loop over clusters + for cl_id, cl_df in gb_cluster: + # Filter only top clusters + if cl_id in cluster_ranking.keys(): + # If clustered structure + if cl_id != "-": + # Retrieve only top 4 models per cluster + structs = cl_df.loc[cl_df["model-cluster_ranking"] <= clustered_topX][["model", "model-cluster_ranking"]] # noqa : E501 + # If un-clustered structures + else: + # Retrieve top 10 + structs = cl_df.loc[cl_df["caprieval_rank"] <= unclustered_topX][["model", "caprieval_rank"]] # noqa : E501 + # Rename columns to access them using same keywords + structs.columns = ["model", "rank"] + # iterate over the structures + for _, row in structs.iterrows(): + # Point rank + rank = row["rank"] + # set target name + if cl_id != "-": + # Give it its cluster name + target_name = ( + f"cluster_{cluster_ranking[cl_id]}" + f"_model_{rank}.pdb" + ) + else: + # Give it its rank name + target_name = f"model_{rank}.pdb" + + # Generate structure path + struct = Path(row["model"]) + struct_gz = Path(f"{struct}.gz") + # copy the structure + if Path(struct).exists(): + top_ranked_mapping[struct] = Path(target_name) + elif struct_gz.exists(): + top_ranked_mapping[struct_gz] = Path(target_name) + else: + log.warning(f"structure {struct} not found") + return top_ranked_mapping + +def zip_top_ranked( + top_ranked_mapping: dict[Path, Path], + summary_name: str, + gen_archive: bool, + ) -> Optional[Path]: + """ + Zip the top ranked structures. + + Parameters + ---------- + capri_filename : str or Path + capri ss filename + cluster_ranking : dict + {cluster_id : cluster_rank} dictionary + summary_name: str + Base name of the archive to be generated + gen_archive: bool + Should the archive be generated? + clustered_topX: int + Number of models to access per cluster. Default is 4. + unclustered_topX: int + Number of models to access when no clusters. Default is 10. + + Return + ------ + output_fname : Optional[Path] + Path to the generated output. Can be a .tgz archive or a directory. + """ + for ori_fpath, new_name in top_ranked_mapping.items(): + # If already compressed + if ori_fpath.suffix == ".gz": + copied_fpath = Path(shutil.copy(ori_fpath, ".")) + # unpack the file + _unpack_gz(copied_fpath) + # Rename it + shutil.move(copied_fpath.name.replace(".gz", ""), new_name) + else: + shutil.copy(ori_fpath, new_name) + + # Compress pdb files + if gen_archive: + archive_was_created = archive_files_ext(".", "pdb") + # Delete the pdb files + for file_ in top_ranked_mapping.values(): + Path(file_).unlink() + output_fname = Path(f"{summary_name}.tgz") + if archive_was_created: + # move archive to summary + shutil.move("pdb.tgz", output_fname) + log.info(f"Top structures summary archive {output_fname} created!") + return + else: + log.warning(f"Summary archive {output_fname} not created!") + return None + # Generate a directory holding all the structures + else: + output_fname = Path(summary_name) + output_fname.mkdir(parents=True, exist_ok=True) + for ori_fpath, new_name in top_ranked_mapping.items(): + # Create new path + next_filepath = Path(output_fname, str(new_name)) + # Hold it in mapping dict + top_ranked_mapping[ori_fpath] = Path(next_filepath) + # Displace file + shutil.move(new_name, top_ranked_mapping[ori_fpath]) + log.info(f"Top structures copied into {output_fname}!") + return output_fname + + +def analyse_step( + step: str, + run_dir: FilePath, + capri_dict: ParamDict, + target_path: Path, + top_clusters: int, + format: Optional[ImgFormat], + scale: Optional[float], + is_cleaned: Optional[bool], + offline: bool = False, + mode: str = "local", + ncores: int = 4, + self_contained: bool = False, + clustered_topX: int = 4, + unclustered_topX: int = 10, +) -> None: + """ + Analyse a step. + + If the step is a caprieval step, use the available capri files. + Otherwise, launch a capri analysis. + + Parameters + ---------- + step : str + step name + run_dir : str or Path + path to run directory + capri_dict : dict + capri dictionary of parameters + target_path : Path + path to the output folder + top_clusters : int + Number of clusters to be considered + format : str + Produce images in the selected format. + scale : int + scale for images. + is_cleaned: bool + is the directory going to be cleaned? + offline: bool + Should plots js functions be self-contained? + mode: str + mode of execution + ncores: int + number of cores to use + self_contained : bool + Should the analysis directory contain the models? + clustered_topX: int + Number of models to access per cluster. Default is 4. + unclustered_topX: int + Number of models to access when no clusters. Default is 10. + """ + log.info(f"Analysing step {step}") + # Create directory + target_path.mkdir(parents=True, exist_ok=False) + # Build caprieval output file names/paths + ss_filename = Path("capri_ss.tsv") + clt_filename = Path("capri_clt.tsv") + step_name = step.split("_")[1] + ss_fname = Path(run_dir, f"{step}/{ss_filename}") + clt_fname = Path(run_dir, f"{step}/{clt_filename}") + # Search for caprieval output files + if step_name != "caprieval": + if ss_fname.exists() and clt_fname.exists(): + log.info(f"step {step} has caprieval data, files are available") + run_capri = False + else: + capri_dict = update_paths_in_capri_dict(capri_dict, target_path) + run_capri = True + else: + log.info(f"step {step} is caprieval, files should be already available") + run_capri = False + + # If caprieval data available, just copy them + if not run_capri: + shutil.copy(ss_fname, target_path) + shutil.copy(clt_fname, target_path) + + # Go to directory where to write all the analysis figures / report + os.chdir(target_path) + # if the step is not caprieval, caprieval must be run + if run_capri: + run_capri_analysis(step, run_dir, capri_dict, is_cleaned, mode, ncores) + + log.info("CAPRI files identified") + # plotting + + if clt_filename.exists(): + cluster_ranking = get_cluster_ranking(clt_filename, top_clusters) + else: + raise Exception(f"clustering file {clt_filename} does not exist") + if ss_filename.exists(): + # Generate file mapping for top ranked structures + top_ranked_mapping = get_top_ranked_mapping( + ss_filename, + cluster_ranking, + clustered_topX=clustered_topX, + unclustered_topX=unclustered_topX, + ) + # provide a zipped archive of the top ranked structures + zip_top_ranked( + top_ranked_mapping, + "summary", + not self_contained, + ) + log.info("Plotting results..") + scatters = scatter_plot_handler( + ss_filename, + cluster_ranking, + format, + scale, + offline=offline, + ) + boxes = box_plot_handler( + ss_filename, + cluster_ranking, + format, + scale, + offline=offline, + ) + tables = clt_table_handler( + clt_filename, + ss_filename, + is_cleaned, + topX_clusters=top_clusters, + clustered_topX=clustered_topX, + unclustered_topX=unclustered_topX, + top_ranked_mapping=top_ranked_mapping if self_contained else None, + ) + report_generator(boxes, scatters, tables, step, ".", offline) + + +def validate_format(_format: Optional[ImgFormat]) -> Optional[ImgFormat]: + """Validate the optional argument `format`. + + Parameters + ---------- + _format : Optional[ImgFormat] + A optential output format set by the user. + + Returns + ------- + Optional[ImgFormat] + A valid output format for the figures to be generated. + + Raises + ------ + ImportError + When the kaleido package is not installed. + ValueError + When the export format is not supported by plotly / kaleido. + """ + # Optional, so if not defined, return _format (None) + if not _format: + return _format + # Make sure it is lower case + format = _format.lower() + # Check if part of supported output formats + if format in SUPPORTED_OUTPUT_FORMATS: + # Make sure the `kaleido` package is installed + try: + import kaleido # noqa : F401 + except ImportError: + raise ImportError( + f"Exporting with format {format} requires the use of `kaleido`" + f" package, that seems not to be installed. {os.linesep}" + "Please install it with: `pip install kaleido==0.2.*`" + ) + # At this stage, everything should go smooth with the export format + else: + # Return supported format + return format + # Raise error if unsupported format + raise ValueError( + f"Format `{format}` is not supported.{os.linesep}" + f"Supported formats: {SUPPORTED_OUTPUT_FORMATS}." + ) + + +def main( + run_dir: FilePath, + modules: list[int], + top_clusters: int, + format: Optional[ImgFormat], + scale: Optional[float], + inter: Optional[bool], + is_cleaned: Optional[bool], + offline: bool = False, + mode: Optional[str] = None, + ncores: Optional[int] = None, + self_contained: bool = False, + **kwargs: Any, +) -> None: + """ + Analyse CLI. + + Parameters + ---------- + run_dir : str or Path + Path to the original run directory. + modules : list of ints + List of the integer prefix of the modules to copy. + top_clusters : int + Number of clusters to be considered. + format : str + Produce images in the selected format. + scale : int + scale for images. + inter: bool + analyse only steps labelled as 'interactive' + is_cleaned: bool + is the directory going to be cleaned? + offline: bool + Should plots js functions be self-contained? + mode: str + mode of execution + ncores: int + number of cores to use + self_contained : bool + Should the analysis directory contain the models? + """ + log.level = 20 + log.info( + f"Running haddock3-analyse on {run_dir}, modules {modules}, " + f"with top_clusters = {top_clusters}" + ) + # Validate output format + format = validate_format(format) + + # Obtain starting working directory + ori_cwd = os.getcwd() + # modifying the parameters + default_capri = read_from_yaml_config(caprieval_params) + capri_dict = update_capri_dict(default_capri, kwargs) + + os.chdir(run_dir) + # Create analysis folder + rundir_cwd = os.getcwd() + outdir = Path(ANA_FOLDER) + try: + outdir.mkdir(exist_ok=False) + log.info(f"Created directory: {str(outdir.resolve())}") + except FileExistsError: + log.warning(f"Directory {str(outdir.resolve())} already exists.") + + # Reading steps + log.info("Reading input run directory") + # get the module folders from the run_dir input + sel_steps = get_module_steps_folders(Path("./"), modules) + if inter: + sel_steps = [st for st in sel_steps if st.endswith(INTER_STR)] + else: + sel_steps = [st for st in sel_steps if not st.endswith(INTER_STR)] + log.info(f"selected steps: {', '.join(sel_steps)}") + + # analysis + good_folder_paths: list[Path] = [] + bad_folder_paths: list[Path] = [] + for step in sel_steps: + subfolder_name = f"{step}_analysis" + target_path = Path(subfolder_name) + + # check if subfolder is already present + dest_path = Path(ANA_FOLDER, subfolder_name) + if dest_path.exists(): + if len(os.listdir(dest_path)) != 0 and not inter: + log.warning( + f"{dest_path} exists and is not empty. " + "Skipping analysis..." + ) + continue + else: # subfolder is empty or is interactive, remove it. + log.info(f"Removing folder {dest_path}.") + shutil.rmtree(dest_path) + + # run the analysis + try: + analyse_step( + step, + Path("./"), + capri_dict, + target_path, + top_clusters, + format, + scale, + is_cleaned, + offline=offline, + mode=mode, + ncores=ncores, + self_contained=self_contained, + ) + except Exception as e: + log.warning( + f"Could not execute the analysis for step {step}. " + f"The following error occurred: {e}" + ) + bad_folder_paths.append(target_path) + else: + good_folder_paths.append(target_path) + + # going back + os.chdir(rundir_cwd) + + # moving files into analysis folder + if good_folder_paths != []: + log.info("moving files to analysis folder") + urls: list[str] = [] + for directory in good_folder_paths: + shutil.move(directory, outdir) + url = f"- [{Path(directory, 'report.html')}](http://0.0.0.0:8000/{Path(directory, 'report.html')}) " # noqa : E501 + urls.append(url) + + # Adding instructions on how to setup the server + readme_fpath = Path(outdir, "README.md") + readme_fpath.write_text( + f"# Usage{os.linesep}{os.linesep}" + "To view structures or download the structure files, " + f"in a terminal run the command:{os.linesep}```bash{os.linesep}" + f"python -m http.server --directory .{os.linesep}```{os.linesep}" + f"And open the link following links in a web browser:{os.linesep}" + f"{os.linesep.join(urls)}{os.linesep}" + ) + assert readme_fpath.exists() + + if bad_folder_paths != []: + log.info("cancelling unsuccesful analysis folders") + for directory in bad_folder_paths: + if directory.exists(): + shutil.rmtree(directory) + + # substituting the correct paths in the capri_ss files + # after moving files into analysis folder + for directory in good_folder_paths: + ss_file = Path(outdir, directory, "capri_ss.tsv") + if ss_file.exists(): + log.info(f"updating paths in {ss_file}") + update_paths(ss_file, "../", "../../") + report_file = Path(outdir, directory, "report.html") + log.info(f"View the results in {report_file}") + info_msg = ( + "To view structures or download the structure files, " + f"in a terminal run the command: {os.linesep}" + f">python -m http.server --directory {rundir_cwd}{os.linesep}" + # "By default, http server runs on `http://0.0.0.0:8000/`. " + f"And open the link http://0.0.0.0:8000/{report_file} " + "in a web browser." + ) + log.info(info_msg) + os.chdir(ori_cwd) + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_cfg.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..9e06305cd3f4e7419e28c98195cfbf41f0107d7e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_cfg.py @@ -0,0 +1,236 @@ +""" +Extract the default configuration file for each module. + +By default presents the parameters from the three expertise levels: + `basic`, `intermediate`, and `guru`. + +Usage:: + + haddock3-cfg # prints only the general parametes + haddock3-cfg -g # same as above + haddock3-cfg -m MODULE # prints only the module parameters + haddock3-cfg -m MODULE -l LEVEL + haddock3-cfg -m topoaa -l all + haddock3-cfg -m rigidbody -l all -g # prints the module and the globals +""" +import argparse +import importlib +import os +import sys + +from pathlib import Path + +from haddock import config_expert_levels, core_path +from haddock.core.typing import ( + ArgumentParser, + Callable, + ExpertLevel, + Namespace, + Optional, +) +from haddock.modules import modules_category + + +ap = argparse.ArgumentParser( + prog="HADDOCK3 config retriever", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +ap.add_argument( + "-m", + dest="module", + help="The module for which you want to retrieve the default configuration.", + choices=sorted(modules_category.keys()), + default=None, +) + +ap.add_argument( + "-l", + dest="explevel", + required=False, + help='The expertise level of the parameters. Defaults to "all".', + default="all", + choices=config_expert_levels + ("all",), +) + +ap.add_argument( + "-g", + "--globals", + dest="global_params", + help="Add also the optional module's general parameters.", + action="store_true", +) + +ap.add_argument( + "-d", + "--details", + dest="details", + help="Add detailed parameter description found in 'long'.", + action="store_true", + default=False, +) + + +def _ap() -> ArgumentParser: + return ap + + +# command-line client helper functions +# load_args, cli, maincli +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + + # I didn't want to to have the `--globals` param as a negative parameter + # ('store_false'). However, `module` and `globals` can't both be false. + # In order for the commands below performing the same: + # + # haddock3-cfg + # haddock3-cfg -g + # + # we need this quick if statement. Which basically adjust the argparse to + # the default values in the main function. + # @joaomcteixeira + if cmd.global_params is False and cmd.module is None: + cmd.global_params = True + + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main( + module: Optional[str] = None, + explevel: str = "all", + global_params: bool = True, + details: bool = False, +) -> None: + """ + Extract the defaults in the form of a run configuration file. + + Parameters + ---------- + module : str or None + The module name to extract the defaults from. + If ``None`` given, we expect ``global_params`` to be ``True``, + otherwise nothing will be printed. + + explevel : str + Filter the parameters according to the expert level. Output all + parameters that belong to the referred level or below. Choices + are: all, easy, expert, and guru. + + global_params : bool + Whether to add the module's general global parameter. If + ``True`` and ``module`` is ``None``, outputs only the general + parameters. + + details : bool + Whether to add the 'long' description of each parameter. + """ + from haddock import modules_defaults_path + from haddock.gear.yaml2cfg import yaml2cfg_text + from haddock.libs.libio import read_from_yaml + + new_config = "" + + if global_params: + # Read general parameters + general_cfg = read_from_yaml(modules_defaults_path) + general_params_str = yaml2cfg_text( + general_cfg, + module=None, + explevel="all", + details=details, + ) + general_comment = os.linesep.join( + ( + "#" * 50, + "# The parameters below are optional parameters. ", + "# They can either be used as global parameters or as part ", + "# of the module's parameters", + "#" * 50, + ) + ) + + # Read mandatory parmeters + mandatory_cfg_path = Path(core_path, "mandatory.yaml") + general_mandatory_cfg = read_from_yaml(mandatory_cfg_path) + general_mandatory_params_str = yaml2cfg_text( + general_mandatory_cfg, + module=None, + explevel="all", + details=details, + mandatory_param=True, + ) + mandatory_comment = os.linesep.join( + ( + "#" * 50, + "# The parameters below are mandatory parameters.", + "# They must be specified in your configuration file!", + "#" * 50, + ) + ) + + # Read optional parameters + optional_cfg_path = Path(core_path, "optional.yaml") + general_optional_cfg = read_from_yaml(optional_cfg_path) + general_optional_params_str = yaml2cfg_text( + general_optional_cfg, + module=None, + explevel="all", + details=details, + ) + optional_comment = os.linesep.join( + ( + "#" * 50, + "# The parameters below are optional global parameters.", + "#" * 50, + ) + ) + # Concatenate all of them + new_config = os.linesep.join( + ( + mandatory_comment, + general_mandatory_params_str, + optional_comment, + general_optional_params_str, + general_comment, + general_params_str, + ) + ) + + if module: + module_name = ".".join( + ( + "haddock", + "modules", + modules_category[module], + module, + ) + ) + + module_lib = importlib.import_module(module_name) + cfg = module_lib.DEFAULT_CONFIG + + ycfg = read_from_yaml(cfg) + module_config = yaml2cfg_text(ycfg, module, explevel, details=details) + + new_config = os.linesep.join((new_config, module_config)) + + sys.stdout.write(new_config) + + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_clean.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2ec97ca017d929904d113fe8e8dfbc087f8c3c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_clean.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +""" +Clean the output of an HADDOCK3 run directory. + +The clean process performs file archiving and file compressing +operations. + +All `.inp` and `.out` files are deleted except for the first one, which +is compressed to `.gz`. On the other hand, all `.seed` and `.con` files +are compressed and archived to `.tgz` files. Finally, `.pdb` and `.psf` +files are compressed to `.gz`. + +The can either be a whole HADDOCK3 run folder or a +specific folder of the workflow step. defines the number of +threads to use; by default uses a single core. + +Usage:: + + haddock3-clean -h + haddock3-clean + haddock3-clean run1 + haddock3-clean run1/1_rigidbody + haddock3-clean run1 -n # uses all cores + haddock3-clean run1 -n 2 # uses 2 cores +""" +import argparse +import sys + +from haddock.core.typing import ( + ArgumentParser, + Callable, + FilePath, + Namespace, + Optional, +) +from haddock.libs import libcli + + +# Command line interface parser +ap = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +libcli.add_rundir_arg(ap) +libcli.add_ncores_arg(ap) +libcli.add_version_arg(ap) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main(run_dir: FilePath, ncores: Optional[int] = 1) -> None: + """ + Clean a HADDOCK3 directory. + + Usually, this concerns compressing and archiving files (see below). + + Parameters + ---------- + run_dir : str or :external:py:class:`pathlib.Path`. + The path to the run directory or to a folder of a specific step + of the workflow. + + ncores : int, or None + The number of cores to use. If ``None``, use all possible threads. + Defaults to 1. + + See Also + -------- + `haddock.gear.clean_steps` + """ + # anti-pattern to speed up CLI initiation + from pathlib import Path + + from haddock import log + from haddock.gear.clean_steps import clean_output + from haddock.libs.libtimer import log_time + from haddock.libs.libutil import parse_ncores + from haddock.modules import get_module_steps_folders, is_step_folder + + log.info(f"Compressing {str(run_dir)!r} folder") + ncores = parse_ncores(ncores) + + if is_step_folder(run_dir): + with log_time("compressing took"): + clean_output(run_dir, ncores) + + else: + step_folders = get_module_steps_folders(run_dir) + for folder in step_folders: + with log_time("compressing took"): + clean_output(Path(run_dir, folder), ncores) + + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_cp.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..95bb419f64e82debad772d77611d89c6d2546f25 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_cp.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +""" +Copy steps to a new run. + +In HADDOCK3 you can copy successful steps from a run directory to a new +directory and use them as starting points for a new run. + +Considering the example:: + + run1/ + 0_topoaa/ + 1_rigidbody/ + 2_caprieval/ + 3_seletop/ + 4_flexref/ + (etc...) + +You can use `4_flexref` step folder as a starting point for a new run. + +USAGE:: + + haddock3-copy -r -m -o + haddock3-copy -r run1 -m 0 4 -o run2 + +Where, ``-m 0 4`` will copy ``0_topoaa`` and ``4_flexref`` to . + +**Note:** If the new run uses CNS-dependent modules, you **also need** +to copy the folder corresponding to the initial topology creation (the +`topoaa` module). + +`haddock3-copy` will also copy the corresponding files in the `data` +directory and update the file contents in the copied folder such that +the information on the run directory and the new step folder names match. +The output result of the above commands is:: + + run2/ + 0_topoaa/ + 1_flexref/ + +Following, you can use the `haddock3` command with the `--extend-run` +option to continue a new run:: + + haddock3 new-config.cfg --extend-run run2 +""" +import argparse +import os +import sys + +from haddock import log +from haddock.core.typing import ArgumentParser, Callable, FilePath, Namespace +from haddock.libs.libcli import add_version_arg + + +# Command line interface parser +ap = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + +ap.add_argument( + "-r", + "--run-dir", + help="The input run directory.", + required=True, + ) + +ap.add_argument( + "-m", + "--modules", + nargs="+", + help="The IDs of the steps to copy (separated by spaces).", + required=True, + type=int, + ) + +ap.add_argument( + "-o", + "--output", + help="The new run directory.", + required=True, + ) + +add_version_arg(ap) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main(run_dir: FilePath, modules: list[int], output: FilePath) -> None: + """ + Copy steps from a run directory to a new run directory. + + Also updates paths references in step files accordingly. + + Parameters + ---------- + run_dir : str or Path + Path to the original run directory. + + modules : list of ints + List of the integer prefix of the modules to copy. + + output : str or Path + The new run directory to create and where to copy the steps. + """ + from pathlib import Path + + from haddock.gear.clean_steps import unpack_compressed_and_archived_files + from haddock.gear.extend_run import ( + copy_renum_step_folders, + update_contents_of_new_steps, + ) + from haddock.gear.zerofill import zero_fill + from haddock.modules import get_module_steps_folders + + log.info("Reading input run directory") + # get the module folders from the run_dir input + steps = get_module_steps_folders(run_dir) + selected_steps = [steps[i] for i in range(len(steps)) if i in modules] + log.info(f"selected steps: {', '.join(selected_steps)}") + + # make new run dir + outdir = Path(output) + try: + outdir.mkdir(parents=True, exist_ok=False) + except FileExistsError: + log.error(f"Directory {str(outdir.resolve())} already exists.") + sys.exit(1) + log.info(f"Created directory: {str(outdir.resolve())}") + + # copy folders over + zero_fill.set_zerofill_number(len(selected_steps)) + new_step_folder = copy_renum_step_folders(run_dir, outdir, selected_steps) + + # copy data folders + # `data_steps` are selected to avoid FileNotFoundError because some steps + # do not have a `data` folder. + # See https://github.com/haddocking/haddock3/issues/559 + data_steps = [ + step for step in selected_steps + if os.path.exists(Path(run_dir, "data", step)) + ] + copy_renum_step_folders( + Path(run_dir, "data"), + Path(outdir, "data"), + data_steps, + ) + + # update step names in files + # update run dir names in files + unpack_compressed_and_archived_files( + new_step_folder, + ncores=1, + dec_all=True, + ) + update_contents_of_new_steps(selected_steps, run_dir, outdir) + + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_dmn.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_dmn.py new file mode 100644 index 0000000000000000000000000000000000000000..93988913aecd4a05391cd7326c73eccecb3d6d06 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_dmn.py @@ -0,0 +1,333 @@ +r""" +HADDOCK3 benchmark submission daemon. + +For more information read our benchmark tutorial at `docs/benchmark.tut` +in HADDOCK3 repository site: https://github.com/haddocking/haddock3:: + + (_) L|J + (") | + /_\--| + _/\ / | + _W_ | + +Usage:: + + haddock3-dmn -h + haddock3-dmn --job-limit [OPTIONS] +""" +import argparse +import os +import subprocess +import sys +import time +from pathlib import Path + +from haddock.core.typing import ArgumentParser, Callable, Namespace, Optional + + +workload_manager_launch = { + "slurm": "sbatch", + "torque": "qsub", +} +"""options for the different job queue systems supported""" + + +# prepares client arguments +ap = argparse.ArgumentParser( + prog="HADDOCK3 benchmark submission daemon.", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +ap.add_argument( + "benchmark_path", + help="Path to the benchmark folder as prepared by `haddock3-bm` interface.", + type=Path, +) + +ap.add_argument( + "--job-limit", + dest="job_limit", + help="How many jobs should run at the same time. Default: 10", + default=10, + type=int, +) + +ap.add_argument( + "--job-sys", + dest="manager", + help="The system where the jobs will be run. Default `slurm`.", + choices=tuple(workload_manager_launch.keys()), + default="slurm", +) + +ap.add_argument( + "--restart", + help="Restart the RUNNING jobs. DONE jobs won't be touched.", + action="store_true", +) + +ap.add_argument( + "--sort-first", + dest="sort_first", + help=( + "Sort jobs by size in ascending order. If not given jobs are order by " + "size in descending order: the biggest first." + ), + action="store_true", +) + + +def _ap() -> ArgumentParser: + return ap + + +class Job: + """ + Job task. + + Controls the status of each job. + + Parameters + ---------- + job_f : pathlib.Path + The path to the job file. + + launch_command : str + The command to launch the job. For example `sbatch`. + """ + + def __init__(self, job_f: Path, launch_command: str) -> None: + self.job_filename = job_f + + self.launch_command = launch_command + + # previous jog path + job_stem = job_f.stem + self.job_run_folder = Path(job_f.parents[1], f"run-{job_stem}") + + self.check_done = Path(self.job_run_folder, "DONE") + self.check_running = Path(self.job_run_folder, "RUNNING") + self.check_available = Path(self.job_run_folder, "AVAILABLE") + self.check_fail = Path(self.job_run_folder, "FAIL") + self.status = None + + self.status_files = [ + self.check_done, + self.check_running, + self.check_fail, + self.check_available, + ] + + def get_status(self) -> Optional[str]: + """ + Get job status. + + The job status depends on the present of files: `AVAILABLE`, + `RUNNING`, `DONE`, and `FAIL` created by `haddock-bm` jobs. + + Status is assigned to `self.status` and returned. + """ + for _file in self.status_files: + if _file.exists(): + self.status = _file.stem # type: ignore + break + return self.status + + def submit(self) -> None: + """ + Submit job. + + Run command `$launch_command $job_filename`. + """ + subprocess.run(cmds := [self.launch_command, str(self.job_filename)]) + print("Job sent: ", cmds) + + def restart(self) -> None: + """ + Restart the status of the job to `AVAILABLE`. + + Does this by removing all status files and creating the file + `AVAILABLE`. + """ + self.check_done.unlink(missing_ok=True) + self.check_running.unlink(missing_ok=True) + self.check_fail.unlink(missing_ok=True) + self.check_available.touch(exist_ok=True) + + +def get_current_jobs(grep: str = "BM5") -> int: + """ + Get current number of jobs for which job-name has the `grep` word. + + List of jobs is retrieve using the command `qstat`. + + Parameters + ---------- + grep : str + The string to search job-names for. + + Return + ------ + int + The number of jobs with the word `grep` in their name. + """ + concurrent_cmd = "qstat -a | awk '{print $4}' | grep " + grep + " | wc -l" + p = subprocess.Popen( + concurrent_cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + output = p.communicate()[0] + njobs = int(output.decode("utf-8")) + print(f"Found {njobs} in the queue.") + return njobs + + +def calc_size(job_path: Path) -> int: + """ + Calculate the size of the job. + + Expects the job file to be in a folder structure as defined by + `haddock3-bm`. + + The size of the jobs is defined by the number of carbon-alpha lines + in the `target.pdb` file. + """ + target_pdb = Path(job_path.parents[1], "input", "target.pdb") + lines = target_pdb.read_text().split(os.linesep) + size = sum(1 for line in lines if line[11:16].strip() == "CA") + return size + + +def filter_by_status(job_list: list[Job], status: str = "AVAILABLE") -> list[Job]: + """ + Filter jobs by their status. + + Only jobs with `status` are accepted. + + Parameters + ---------- + job_list : list of Job objects. + + Returns + ------- + list + The list with the `Job`s with matching `status`. + """ + jobs = [j for j in job_list if j.get_status() == status] + print(f"Number of {status} jobs: {len(jobs)}.") + return jobs + + +# command-line client helper functions +# load_args, cli, maincli +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main( + benchmark_path: Path, + job_limit: int = 10, + manager: str = "slurm", + restart: bool = False, + sort_first: bool = False, +) -> None: + """ + Execute the benchmark daemon. + + The parameters defined here are the same as defined in the client + arguments. + + This is the main function of the client. If you want to run the + daemon withOUT using the command line and instead importing its + functionalities and setting it up from another pythong script, you + should import this function. + + >>> from haddock.clis.cli_dmn import main + + Parameters + ---------- + benchmark_path : pathlib.Path + The path of the benchmark folder as created by the `haddock3-bm` + interface. + + job_limit : int + The max number of jobs to send to the queue. + + manager : str + A key to the `workload_manager_launch` dictionary. Selects the queue + management system. + + restart : bool + Whether to restart the `RUNNING` jobs that might have been halted + in previous daemon runs. Defaults to False. + + sort_first : bool + Whether to sort jobs by their size in ascending manner. That is, + the sorted jobs first. Defaults to False, the longer first. + """ + # lists of all the job files in the benchmark_path folder + job_list = list(benchmark_path.glob("*/jobs/*.job")) + + # breaks if no jobs are found + if not job_list: + sys.exit("+ ERROR! No jobs found in folder: {str(benchmark_path)!r}") + + # sorts the job list + job_list.sort(key=calc_size, reverse=not (sort_first)) # noqa: E275 + + # create the job objects according to the queue managing systme + _jobsys = workload_manager_launch[manager] + jobs = [Job(j, _jobsys) for j in job_list] + + # restart previously (halted) `RUNNING` jobs - if selected. + if restart: + running_jobs = filter_by_status(jobs, status="RUNNING") + for _job in running_jobs: + _job.restart() + + # Lists the available jobs (those with status `AVAILABLE`) + available_jobs = filter_by_status(jobs) + + # runs the daemon loop, only if there are available jobs :-) + while available_jobs: + # get the number of available queue slots according to the + # job limit parameter + # + # 0 is added to avoid going to negative values in case a job + # had been manually submitted. + empty_slots = max(0, job_limit - get_current_jobs()) + print("empty slots: ", empty_slots) + + # send jobs if there are empty slots + for i in range(empty_slots): + available_jobs[i].submit() + time.sleep(5) + + # chill before repeating the process. + print("chilling for 120 seconds...") + time.sleep(120) + + # refreshes the available_jobs list + available_jobs = filter_by_status(jobs) + + # done + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_mpi.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_mpi.py new file mode 100644 index 0000000000000000000000000000000000000000..8d50e6c5ebdee2d0fdea6766f4cb19d38067a97a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_mpi.py @@ -0,0 +1,123 @@ +""" +MPI-wrapper for executing pickled CNSJobs created by libmpi. + +This was developed for use of lbimpi but it might be useful in some specific + scenario as a cli. + +For more information please refer to the README.md in the examples folder. + +Usage:: + + haddock3-mpitask -h + haddock3-mpitask tasks.pkl +""" + +import argparse +import pickle +import sys + +from haddock.core.typing import ( + AnyT, + ArgumentParser, + Callable, + FilePath, + Namespace, +) +from haddock.libs.libsubprocess import CNSJob + + +# Note! ######################################################################################## +# It's important to not define `MPI` and `COMM` directly but to use the `get_mpi` +# function to ensure that the MPI module is only loaded when needed. +# This is important for testing purposes, and this CLI should further be refactored to not use +# global variables. +MPI = None +COMM = None +# Note! ######################################################################################## + + +def get_mpi(): + """Lazy load MPI and COMM.""" + global MPI, COMM + if MPI is None: + try: + from mpi4py import MPI as _MPI + + MPI = _MPI + COMM = MPI.COMM_WORLD + except ImportError as e: + _msg = ( + f"{e} - To run this cli you must have mpi4py and " + "OpenMPI installed in the system" + ) + sys.exit(_msg) + return MPI, COMM + + +def split_tasks(task_l: list[AnyT], n: int) -> list[list[AnyT]]: + """Split tasks into equal lenght chunks.""" + return [task_l[_i::n] for _i in range(n)] + + +# ========================================================================# +# helper functions to enhance flexibility and modularity of the CLIs + +ap = argparse.ArgumentParser( + prog="MPI-wrapper for executing pickled CNSJobs created by libmpi", + description=__doc__, +) + +ap.add_argument( + "pickled_tasks", + help="The input pickled tasks path", +) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +# ========================================================================# + + +def main(pickled_tasks: FilePath) -> None: + """Execute the tasks.""" + MPI, COMM = get_mpi() + if COMM.rank == 0: + with open(pickled_tasks, "rb") as pkl: + tasks = pickle.load(pkl) + mpi_jobs = split_tasks(tasks, COMM.size) + else: + mpi_jobs = None + + jobs: list[CNSJob] = COMM.scatter(mpi_jobs, root=0) + + results: list[FilePath] = [] + for job in jobs: + job.run() + # check if the job has an input file + if hasattr(job, "input_file"): + results.append(job.input_file) + + # COMM.Barrier() + # results = MPI.COMM_WORLD.gather(results, root=0) + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_pp.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_pp.py new file mode 100644 index 0000000000000000000000000000000000000000..e289531469446c2f23c8f9492502406045a2429e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_pp.py @@ -0,0 +1,168 @@ +""" +HADDOCK3 PDB preprocessing client. + +Process PDB files for agreement with HADDOCK3 requirements. Follows the +logic implemented in the :py:mod:`haddock.gear.preprocessing`. See +documentation pages for more details. + +You can use the `--dry` option to report on the performed changes +without actually performing the changes. + +Corrected PDBs are saved to new files named after the `--suffix` option. +Original PDBs are never overwritten, unless `--suffix` is given an empty +string. + +You can pass multiple PDB files to the command-line. + +Usage:: + + haddock-pp file1.pdb file2.pdb + haddock-pp file1.pdb file2.pdb --suffix _new + haddock-pp file1.pdb file2.pdb --dry +""" +import argparse +import sys +from pathlib import Path + +from haddock import log +from haddock.core.typing import ( + ArgumentParser, + Callable, + FilePath, + Namespace, + Optional, +) +from haddock.gear.preprocessing import process_pdbs, read_additional_residues +from haddock.libs.libcli import add_output_dir_arg +from haddock.libs.libio import add_suffix_to_files, save_lines_to_files + + +SUFFIX_DEFAULT = "_processed" + +ap = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +ap.add_argument( + "pdb_files", + help="Input PDB files.", + nargs="+", +) + +ap.add_argument( + "-d", + "--dry", + help="Perform a dry run. Informs changes without modifying files.", + action="store_true", +) + +ap.add_argument( + "-t", + "--topfile", + help="Additional .top files.", + nargs="*", +) + +ap.add_argument( + "-s", + "--suffix", + help=f"Suffix to output files. Defaults to {SUFFIX_DEFAULT!r}", + default=SUFFIX_DEFAULT, +) + +add_output_dir_arg(ap) + + +# client helper functions +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = vars(load_args(ap)) + # I use this `pop` structure to maintain the unpacking argument in + # the `main` function because I foresee the `main` to be used from + # other parts of the software(s) + main(*cmd.pop("pdb_files"), **cmd) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main( + *pdb_files: FilePath, + dry: bool = False, + output_directory: Optional[FilePath] = None, + suffix: str = SUFFIX_DEFAULT, + topfile: Optional[FilePath] = None, +) -> None: + """ + Process PDB files. + + Parameters + ---------- + dry : bool + Whether to perform a dry test only. + + output_directory : str or ``pathlib.Path`` + The directory where to save the output. Defaults to the current + working directory. + + suffix : str + The suffix to append to the new files. Will be added before the + file extension. Original extension will be kept. + + topfile : str or ``pathlib.Path`` + The path to an additional HADDOCK3 topology file. + """ + log.info("Starting processing PDB files.") + log.info(f"Total number of PDB files: {len(pdb_files)}") + + if dry: + log.info( + "You selected the `--dry` option. No new files will be created. " + "A report of the changes that would be performed in the PDB files " + "will be printed." + ) + + new_residues = read_additional_residues(topfile) if topfile else None + + log.info("Processing the PDB files... " "This may take a bit if there are many.") + + processed_pdbs = process_pdbs( + *pdb_files, + dry=dry, + user_supported_residues=new_residues, + ) + + if dry: + log.info("Everything done. Exiting...") + sys.exit(0) + + log.info("Finished processing PDBs. Saving to disk...") + if output_directory is None: + output_directory = Path.cwd() + else: + output_directory = Path(output_directory) + log.info("Output dir: {!r}".format(str(output_directory))) + output_directory.mkdir(parents=True, exist_ok=True) + + pdb_names = (Path(output_directory, Path(pdb).name) for pdb in pdb_files) + out_files = add_suffix_to_files(pdb_names, suffix) + save_lines_to_files(out_files, processed_pdbs) + + log.info("Everything done. Exiting...") + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_re.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_re.py new file mode 100644 index 0000000000000000000000000000000000000000..16c36374155b729368a44aae6dc0147ee44c2dcd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_re.py @@ -0,0 +1,60 @@ +""" +HADDOCK 3.0 CLI for interactive tasks. +""" +import argparse +import sys +import os + +from haddock.clis.re.clustfcc import add_clustfcc_arguments, reclustfcc +from haddock.clis.re.clustrmsd import add_clustrmsd_arguments, reclustrmsd +from haddock.clis.re.score import add_rescore_arguments, rescore + +# Command line interface parser +ap = argparse.ArgumentParser( + prog="haddock3-re", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + +subparsers = ap.add_subparsers(title='subcommands', + help='valid subcommands', + ) + +# score subcommand +rescore_subcommand = subparsers.add_parser('score') +rescore_subcommand.set_defaults(func=rescore) +rescore_subcommand = add_rescore_arguments(rescore_subcommand) +# clustrmsd subcommand +clustrmsd_subcommand = subparsers.add_parser('clustrmsd') +clustrmsd_subcommand.set_defaults(func=reclustrmsd) +clustrmsd_subcommand = add_clustrmsd_arguments(clustrmsd_subcommand) +# clustfcc subcommand +clustfcc_subcommand = subparsers.add_parser('clustfcc') +clustfcc_subcommand.set_defaults(func=reclustfcc) +clustfcc_subcommand = add_clustfcc_arguments(clustfcc_subcommand) + + +def _ap(): + return ap + + +def load_args(ap): + """Load argument parser args.""" + return ap.parse_args() + + +def maincli(): + """Execute main client.""" + args = ap.parse_args() + cmd = vars(load_args(ap)) + if "func" not in cmd.keys(): + sys.stderr.write(f"Error: no subcommand given.{os.linesep}") + ap.print_help() + sys.exit(1) + else: + cmd.pop("func") + args.func(**cmd) + + +if __name__ == "__main__": + sys.exit(maincli()) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_restraints.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_restraints.py new file mode 100644 index 0000000000000000000000000000000000000000..30807a77176db1dddda0c4ca74709216108c4109 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_restraints.py @@ -0,0 +1,143 @@ +""" +HADDOCK3 CLI for restraints-related tasks. + +DISCLAIMER: these scripts have been ported from old code and are not +optimized for code quality and performance. They are provided as a convenience +for the user. + +USAGE:: + + haddock3-restraints + +For the list of available tasks, run:: + + haddock3-restraints -h + +For the list of arguments for a given task, run:: + + haddock3-restraints -h +""" + +import argparse +import sys + +from haddock import log +from haddock.clis.restraints.active_passive_to_ambig import ( + actpass_to_ambig, + add_actpass_to_ambig_arguments, + ) +from haddock.clis.restraints.calc_accessibility import ( + add_calc_accessibility_arguments, + calc_accessibility, + ) +from haddock.clis.restraints.passive_from_active import ( + add_pass_from_act_arguments, + passive_from_active, + ) +from haddock.clis.restraints.restrain_bodies import ( + add_restrain_bodies_arguments, + restrain_bodies, + ) +from haddock.clis.restraints.validate_tbl import ( + add_validate_tbl_arguments, + validate_tbl, + ) +from haddock.clis.restraints.z_surface_restraints import ( + add_z_surf_restraints_arguments, + gen_z_surface_restraints, + ) +from haddock.clis.restraints.random_removal import ( + add_rand_removal_arguments, + main as random_removal, + ) +from haddock.clis.restraints.restrain_ligand import ( + add_restrain_ligand_arguments, + main as restrain_ligand, + ) + +# Command line interface parser +ap = argparse.ArgumentParser( + prog="haddock3-restraints", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +subparsers = ap.add_subparsers( + title="subcommands", + description="valid subcommands", + help="additional help", +) + +# restrain_bodies subcommand +restrain_bodies_subcommand = subparsers.add_parser("restrain_bodies") +restrain_bodies_subcommand.set_defaults(func=restrain_bodies) +restrain_bodies_subcommand = add_restrain_bodies_arguments(restrain_bodies_subcommand) + +# passive_from_active subcommand +pass_from_act_subcommand = subparsers.add_parser("passive_from_active") +pass_from_act_subcommand.set_defaults(func=passive_from_active) +pass_from_act_subcommand = add_pass_from_act_arguments(pass_from_act_subcommand) + +# validate_tbl subcommand +validate_tbl_subcommand = subparsers.add_parser("validate_tbl") +validate_tbl_subcommand.set_defaults(func=validate_tbl) +validate_tbl_subcommand = add_validate_tbl_arguments(validate_tbl_subcommand) + +# active_passive_to_ambig subcommand +actpass_to_ambig_subcommand = subparsers.add_parser("active_passive_to_ambig") +actpass_to_ambig_subcommand.set_defaults(func=actpass_to_ambig) +actpass_to_ambig_subcommand = add_actpass_to_ambig_arguments( + actpass_to_ambig_subcommand +) + +# calc_accessibility subcommand +calc_accessibility_subcommand = subparsers.add_parser("calc_accessibility") +calc_accessibility_subcommand.set_defaults(func=calc_accessibility) +calc_accessibility_subcommand = add_calc_accessibility_arguments( + calc_accessibility_subcommand +) + +# z_surface_restraints subcommand +z_surface_restraints_subcommand = subparsers.add_parser("z_surface_restraints") +z_surface_restraints_subcommand.set_defaults(func=gen_z_surface_restraints) +z_surface_restraints_subcommand = add_z_surf_restraints_arguments( + z_surface_restraints_subcommand +) + +# random_removal subcommand +restraints_random_removal_subcommand = subparsers.add_parser("random_removal") +restraints_random_removal_subcommand.set_defaults(func=random_removal) +restraints_random_removal_subcommand = add_rand_removal_arguments( + restraints_random_removal_subcommand +) + +# restrain_ligand subcommand +restraints_restrain_ligand_subcommand = subparsers.add_parser("restrain_ligand") +restraints_restrain_ligand_subcommand.set_defaults(func=restrain_ligand) +restraints_restrain_ligand_subcommand = add_restrain_ligand_arguments( + restraints_restrain_ligand_subcommand +) + + +def _ap(): + return ap + + +def load_args(ap): + """Load argument parser args.""" + return ap.parse_args() + + +def maincli(): + """Execute main client.""" + args = ap.parse_args() + cmd = vars(load_args(ap)) + try: + cmd.pop("func") + except KeyError: + sys.exit(ap.print_help()) + args.func(**cmd) + + +if __name__ == "__main__": + sys.exit(maincli()) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_score.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_score.py new file mode 100644 index 0000000000000000000000000000000000000000..a981996bb7e2f087294a9c145fddd602080a9d9c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_score.py @@ -0,0 +1,300 @@ +""" +A simple tool to calculate the HADDOCK-score of a complex. + +You can pass to the command-line any parameter accepted by the `emscoring` +module. For this, use the ``-p`` option writing the name of the parameters +followed by the desired value. Write booleans with capital letter. + +Use the ``haddock3-cfg`` command-line to obtain the list of parameters for +the ``emscoring`` module. + +Usage:: + + haddock3-score complex.pdb + haddock3-score complex.pdb -p nemsteps 50 + haddock3-score complex.pdb -p nemsteps 50 w_air 1 + haddock3-score complex.pdb -p nemsteps 50 w_air 1 electflag True + +""" +import argparse +import sys +import tempfile + +from haddock.core.typing import ( + Any, + ArgumentParser, + Callable, + FilePath, + Namespace, + ) +from haddock.libs.libcli import _ParamsToDict + + +ap = argparse.ArgumentParser( + prog="haddock3-score", + description=__doc__, + ) + +ap.add_argument("pdb_file", help="Input PDB file") + +ap.add_argument( + "--run_dir", + default="haddock-score-client", + type=str, + required=False, + help="Run directory name.", + ) + +ap.add_argument( + "--full", + action="store_true", + help="Print all energy components", + ) + +ap.add_argument( + "--outputpdb", + action="store_true", + help="Save the output PDB file (minimized structure)", + ) + +ap.add_argument( + "--outputpsf", + action="store_true", + help="Save the output PSF file (topology)", + ) + +ap.add_argument( + "-k" "--keep-all", + dest="keep_all", + action="store_true", + help="Keep the whole run folder.", + ) + +ap.add_argument( + "-p", + "--other-params", + dest="other_params", + help=( + "Any other parameter of the `emscoring` module. " + "For example: -p nemsteps 1000. You can give any number of " + "parameters." + ), + action=_ParamsToDict, + default={}, + nargs="*", + ) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = vars(load_args(ap)) + kwargs = cmd.pop("other_params") + main(**cmd, **kwargs) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main( + pdb_file: FilePath, + run_dir: FilePath, + full: bool = False, + outputpdb: bool = False, + outputpsf: bool = False, + keep_all: bool = False, + **kwargs: Any, + ) -> None: + """ + Calculate the score of a complex using the ``emscoring`` module. + + Parameters + ---------- + pdb_file : str or pathlib.Path + The path to the PDB containing the complex. + + full : bool + Print all energy components. + + outputpdb : bool + Save the PDB file resulting from the scoring calculation. + + outputpsf : bool + Save the PSF file resulting from the scoring calculation; this + is the CNS topology created before running the calculation. + + keep_all : bool + Keep the whole temporary run folder. ``haddock3-score`` creates + a temporary run folder where the calculations are performed. If + ``keep_all`` is True, this folder is **not** deleted after when + the calculation finishes. + + kwargs : any + Any additional arguments that will be passed to the ``emscoring`` + module. + """ + import os + import logging + import shutil + from contextlib import suppress + from pathlib import Path + + from haddock import log, EmptyPath + from haddock.gear.haddockmodel import HaddockModel + from haddock.gear.yaml2cfg import read_from_yaml_config + from haddock.gear.zerofill import zero_fill + from haddock.libs.libio import working_directory + from haddock.libs.libworkflow import WorkflowManager + from haddock.modules.scoring.emscoring import DEFAULT_CONFIG + + log.setLevel(logging.ERROR) + + input_pdb = Path(pdb_file).resolve() + if not input_pdb.exists(): + sys.exit(f"* ERROR * Input PDB file {str(input_pdb)!r} does not exist") + + # config all parameters are correctly spelled. + default_emscoring = read_from_yaml_config(DEFAULT_CONFIG) + ems_dict = default_emscoring.copy() + n_warnings = 0 + for param, value in kwargs.items(): + # Check if the parameter name is in the emscoring module ones + if param not in default_emscoring: + sys.exit( + f"* ERROR * Parameter {param!r} is not a " + f"valid `emscoring` parameter.{os.linesep}" + "Valid emscoring parameters are: " + f"{', '.join(sorted(default_emscoring))}" + ) + # Compare the user-given value to the default one + if value != default_emscoring[param]: + print( + f"* ATTENTION * Value ({value}) of parameter {param} " + f"different from default ({default_emscoring[param]})" + ) + # get the type of default value + default_type = type(default_emscoring[param]) + # cast the value to the same type + if default_type == bool: + if value.lower() not in ["true", "false"]: + sys.exit(f"* ERROR * Boolean parameter {param} should be True or False") + value = value.lower() == "true" + elif param.endswith("_fname"): + value = EmptyPath() if str(value) == "" else Path(value).resolve() + else: + value = default_type(value) + ems_dict[param] = value + n_warnings += 1 + if n_warnings != 0: + print( + "* ATTENTION * Non-default parameter values were used. " + "They should be properly reported if the output " + "data are used for publication." + ) + print(f"used emscoring parameters: {ems_dict}") + + # create run directory + run_dir = Path(run_dir) + with suppress(FileNotFoundError): + shutil.rmtree(run_dir) + run_dir.mkdir() + zero_fill.set_zerofill_number(2) + + # create temporary file + with tempfile.NamedTemporaryFile(prefix=input_pdb.stem, suffix=".pdb") as tmp: + + # create a copy of the input pdb + input_pdb_copy = Path(tmp.name) + shutil.copy(input_pdb, input_pdb_copy) + + # Setting up a full workflow set of parameters + workflow_params = { + "topoaa": { + "molecules": [input_pdb_copy], + "ligand_param_fname": ems_dict["ligand_param_fname"], + "ligand_top_fname": ems_dict["ligand_top_fname"], + }, + "emscoring": ems_dict, + } + + print("> starting calculations...") + + # run workflow + with working_directory(run_dir): + workflow = WorkflowManager( + workflow_params=workflow_params, + start=0, + run_dir=run_dir, + ) + workflow.run() + + # Build expected pdb filepath + minimized_mol = Path(run_dir, "1_emscoring", "emscoring_1.pdb") + haddock_score_component_dic = HaddockModel(minimized_mol).energies + + vdw = haddock_score_component_dic["vdw"] + elec = haddock_score_component_dic["elec"] + desolv = haddock_score_component_dic["desolv"] + air = haddock_score_component_dic["air"] + bsa = haddock_score_component_dic["bsa"] + + # Compute the haddock score + # emscoring is equivalent to itw + haddock_score_itw = ( + ems_dict["w_vdw"] * vdw + + ems_dict["w_elec"] * elec + + ems_dict["w_desolv"] * desolv + + ems_dict["w_air"] * air + + ems_dict["w_bsa"] * bsa + ) + + print( + "> HADDOCK-score =" + f" ({ems_dict['w_vdw']} * vdw)" + f" + ({ems_dict['w_elec']} * elec)" + f" + ({ems_dict['w_desolv']} * desolv)" + f" + ({ems_dict['w_air']} * air)" + f" + ({ems_dict['w_bsa']} * bsa)" + ) + print(f"> HADDOCK-score (emscoring) = {haddock_score_itw:.4f}") + + if full: + print(f"> vdw={vdw},elec={elec},desolv={desolv},air={air},bsa={bsa}") + + if outputpdb: + outputpdb_name = Path(f"{input_pdb.stem}_hs.pdb") + print(f"> writing {outputpdb_name}") + shutil.copy( + Path(run_dir, "1_emscoring", "emscoring_1.pdb"), + outputpdb_name, + ) + + if outputpsf: + outputpsf_name = Path(f"{input_pdb.stem}_hs.psf") + print(f"> writing {outputpsf_name}") + shutil.copy( + Path(run_dir, "0_topoaa", f"{input_pdb_copy.stem}_haddock.psf"), + outputpsf_name, + ) + + if not keep_all: + shutil.rmtree(run_dir) + else: + print( + 'The folder where the calculations were performed was kept.' + f' See folder: {run_dir}' + ) + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_traceback.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_traceback.py new file mode 100644 index 0000000000000000000000000000000000000000..584f447562cd8ea80f45d56b3707332fbdfcf8b5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_traceback.py @@ -0,0 +1,370 @@ +""" +Traces back PDB files from a HADDOCK run directory. + +Given an input run directory, haddock3-traceback traces back each model to the +initial input molecules used, providing the rank of each intermediate model. + +USAGE:: + + haddock3-traceback -r + +""" +import argparse +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +from haddock import log +from haddock.core.typing import Any, FilePath +from haddock.libs import libcli +from haddock.libs.libontology import ModuleIO, PDBFile +from haddock.libs.libplots import make_traceback_plot +from haddock.modules import get_module_steps_folders + + +TRACK_FOLDER = "traceback" # name of the traceback folder + + +def get_steps_without_pdbs(run_dir, all_steps): + """ + Get the modules that do not produce PDB files. + + Parameters + ---------- + run_dir : str or pathlib.Path + Path to the run directory. + + all_steps : list + List of all the steps in the run directory. + + Returns + ------- + steps_without_pdbs : list + List of steps that did not produce PDB files. + """ + steps_without_pdbs = [] + for step in all_steps: + if step.endswith("topoaa"): + steps_without_pdbs.append(step) + else: + step_dir = Path(run_dir, step) + if step_dir.is_dir(): + pdbs = list(step_dir.glob("*.pdb*")) + if len(pdbs) == 0: + steps_without_pdbs.append(step) + return steps_without_pdbs + + +def get_ori_names(n: int, pdbfile: PDBFile, max_topo_len: int) -> tuple[list, int]: + """ + Get the original name(s) of the PDB file. + + Parameters + ---------- + n : int + Step number. + pdbfile : PDBFile + PDBFile object. + max_topo_len : int + Maximum length of the topologies found so far. + + Returns + ------- + ori_names : list + List of original names. + max_topo_len : int + Maximum length of the topologies found so far. + """ + if n != 0: # not the first step, ori_name should be defined + ori_names = [pdbfile.ori_name] + else: # first step, we get topology files instead of ori_name + # topology can either be a list of topologies or a single + # topology + if isinstance(pdbfile.topology, list): + ori_names = [el.file_name for el in pdbfile.topology] + if len(pdbfile.topology) > max_topo_len: + max_topo_len = len(pdbfile.topology) + else: + ori_names = [pdbfile.topology.file_name] # type: ignore + max_topo_len = 1 + return ori_names, max_topo_len + + +def traceback_dataframe( + data_dict: dict, rank_dict: dict, sel_step: list, max_topo_len: int +) -> pd.DataFrame: + """ + Create traceback dataframe by combining together ranks and data. + + Parameters + ---------- + data_dict : dict + Dictionary containing the data to be traced back. + rank_dict : dict + Dictionary containing the ranks of the data to be traced back. + sel_step : list + List of selected steps. + max_topo_len : int + Maximum length of the topologies. + + Returns + ------- + df_ord : pandas.DataFrame + Dataframe containing the traceback data. + """ + # get last step of the workflow + last_step = sel_step[-1] + # data dict to dataframe + df_data = pd.DataFrame.from_dict(data_dict, orient="index") + df_data.reset_index(inplace=True) + # assign columns + data_cols = [el for el in reversed(sel_step)] + data_cols.extend([f"00_topo{i+1}" for i in range(max_topo_len)]) + df_data.columns = data_cols + + # same for the rank_dict + df_ranks = pd.DataFrame.from_dict(rank_dict, orient="index") + df_ranks.reset_index(inplace=True) + ranks_col = [last_step] # the key to merge the dataframes + ranks_col.extend([f"{el}_rank" for el in reversed(sel_step)]) + df_ranks.columns = ranks_col + + # merging the data and ranks dataframes + df_merged = pd.merge(df_data, df_ranks, on=last_step) + ordered_cols = sorted(df_merged.columns) + df_ord = df_merged[ordered_cols] + # last thing: substituting unk records with - in the last step + unk_records = df_ord[f"{last_step}"].str.startswith("unk") + df_ord.loc[unk_records, last_step] = "-" + return df_ord + + +def order_traceback_df(df_output, sel_step): + """ + Order the traceback dataframe. Each step is ordered by rank. + + Parameters + ---------- + df_output : pandas.DataFrame + Dataframe containing the traceback data. + + sel_step : list + List of selected steps. + + Returns + ------- + df_output : pandas.DataFrame + Dataframe containing the ordered traceback data. + """ + # loop over sel_step in reverse order + sorted_list = [] + indexes = [] + for n in range(len(sel_step) - 1, -1, -1): + rank_col = sel_step[n] + "_rank" + # take only models with a rank + df_last = df_output[df_output[rank_col] != "-"] + # remove from df_last the indexes that are already in the dataframe + df_last = df_last[~df_last.index.isin(indexes)] + # sorting the dataframe by rank + sorted_df_last = df_last.sort_values(by=rank_col) + sorted_list.append(sorted_df_last) + # concat the current indexes with the previous ones + indexes = sorted_df_last.index.tolist() + indexes + df_output = pd.concat(sorted_list) + return df_output + + +def subset_traceback(traceback_df: pd.DataFrame, cons_filename: Path) -> pd.DataFrame: + """ + Generate a subset the traceback dataframe with the top 40 models. + + Parameters + ---------- + traceback_df : pandas.DataFrame + Dataframe containing the traceback data. + + cons_filename : pathlib.Path + name of the consensus file. + + Returns + ------- + rank_data_subset : pandas.DataFrame + Dataframe containing the subset of the traceback data. + """ + red_traceback_df = traceback_df.head(40) + rank_data = red_traceback_df.filter(regex='rank$') + # get the last column: this will define the name of the models + last_column = red_traceback_df.columns[-2] + last_column_data = red_traceback_df[last_column] + # concat the ranks with the model name + rank_data = pd.concat([last_column_data, rank_data], axis=1) + # the rank of the last column must be defined + last_column_rank = last_column + "_rank" + # copy avoids SettingWithCopyWarning + rank_data_subset = rank_data[rank_data[last_column_rank] != '-'].copy() + rank_columns = rank_data_subset.columns[1:].tolist() + rank_data_subset[rank_columns] = rank_data_subset[rank_columns].apply(pd.to_numeric, errors='coerce') + rank_data_subset = rank_data_subset.sort_values(by=last_column_rank, ascending=True) + + # rename the columns + rank_data_subset.columns = ["Model"] + rank_columns + # sum the ranks + rank_data_subset["Sum-of-Ranks"] = rank_data_subset[rank_columns].sum(axis=1) + rank_data_subset.to_csv(cons_filename, index=False, sep="\t") + return rank_data_subset + + +# Command line interface parser +ap = argparse.ArgumentParser( + prog="haddock3-traceback", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +libcli.add_rundir_arg(ap) + + +def load_args(ap): + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap, main): + """Command-line interface entry point.""" + cmd = vars(load_args(ap)) + main(**cmd) + + +def maincli(): + """Execute main client.""" + cli(ap, main) + + +def main(run_dir: FilePath, offline: bool = False) -> None: + """ + Traceback CLI. + + Parameters + ---------- + run_dir : str or Path + Path to the original run directory. + """ + log.level = 20 + log.info(f"Running haddock3-traceback on {run_dir}") + + # Reading steps + log.info("Reading input run directory") + # get the module folders from the run_dir input + all_steps = get_module_steps_folders(Path(run_dir)) + log.info(f"All_steps: {', '.join(all_steps)}") + ana_modules = get_steps_without_pdbs(run_dir, all_steps) + log.info(f"Modules not to be analysed: {', '.join(ana_modules)}") + sel_step = [st for st in all_steps if st not in ana_modules] + # check if there are steps to traceback + if len(sel_step) == 0: + log.info("No steps to trace back. Exiting.") + return + else: + log.info(f"Steps to trace back: {', '.join(sel_step)}") + + # creating traceback folder + outdir = Path(run_dir, TRACK_FOLDER) + try: + outdir.mkdir(exist_ok=False) + log.info(f"Created directory: {str(outdir.resolve())}") + except FileExistsError: + log.warning(f"Directory {str(outdir.resolve())} already exists.") + + data_dict: dict[Any, Any] = {} + rank_dict: dict[Any, Any] = {} + unk_idx, max_topo_len = 0, 0 + # this cycle goes through the steps in reverse order + for n in range(len(sel_step) - 1, -1, -1): + log.info(f"Tracing back step {sel_step[n]}") + # correcting names in the dictionary. The ori_name must be complemented + # with the step folder name + for key in data_dict.keys(): + if data_dict[key][-1] != "-": + data_dict[key][-1] = f"../{sel_step[n]}/{data_dict[key][-1]}" + + delta = len(sel_step) - n - 1 # how many steps have we gone back? + # loading the .json file + json_path = Path(run_dir, sel_step[n], "io.json") + io = ModuleIO() + io.load(json_path) + # list all the values in the data_dict + ls_values = [x for val in data_dict.values() for x in val] + # getting and sorting the ranks for the current step folder + ranks = [pdbfile.score for pdbfile in io.output] + ranks_argsort = np.argsort(ranks) + + # iterating through the pdbfiles to fill data_dict and rank_dict + for i, pdbfile in enumerate(io.output): + rank = np.where(ranks_argsort == i)[0][0] + 1 + # getting the original names + ori_names, max_topo_len = get_ori_names(n, pdbfile, max_topo_len) + if n != len(sel_step) - 1: + if str(pdbfile.rel_path) not in ls_values: + # this is the first step in which the pdbfile appears. + # This means that it was discarded for the subsequent steps + # We need to add the pdbfile to the data_dict + keys = [f"unk{unk_idx}"] + data_dict[keys[0]] = ["-" for el in range(delta - 1)] + data_dict[keys[0]].append(str(pdbfile.rel_path)) + rank_dict[keys[0]] = ["-" for el in range(delta)] + unk_idx += 1 + else: + # we've already seen this pdb before. + idxs = [i for i, el in enumerate(ls_values) if el==str(pdbfile.rel_path)] + keys = [list(data_dict.keys())[idx // delta] for idx in idxs] + + # assignment + for el in ori_names: + for key in keys: + data_dict[key].append(el) + for key in keys: + rank_dict[key].append(rank) + else: # last step of the workflow + data_dict[str(pdbfile.rel_path)] = [on for on in ori_names] + rank_dict[str(pdbfile.rel_path)] = [rank] + + # print(f"rank_dict {rank_dict}") + # print(f"data_dict {data_dict}, maxtopo {max_topo_len}") + + # stripping away relative paths + final_data_dict = {} + for key in data_dict.keys(): + new_key = key.split("/")[-1] + final_data_dict[new_key] = [el.split("/")[-1] for el in data_dict[key]] + final_rank_dict = {} + for key in rank_dict.keys(): + new_key = key.split("/")[-1] + final_rank_dict[new_key] = rank_dict[key] + # dumping the data into a dataframe + df_output = traceback_dataframe( + final_data_dict, final_rank_dict, sel_step, max_topo_len + ) + + # ordering the dataframe + df_output = order_traceback_df(df_output, sel_step) + # dumping the dataframe + track_filename = Path(run_dir, TRACK_FOLDER, "traceback.tsv") + log.info( + f"Output dataframe {track_filename} " f"created with shape {df_output.shape}" + ) + df_output.to_csv(track_filename, sep="\t", index=False) + + # taking (and writing) a subset of the dataframe + consensus_filename = Path(run_dir, TRACK_FOLDER, "consensus.tsv") + rank_data_subset = subset_traceback(df_output, consensus_filename) + + # plotting the traceback dataframe + plot_filename = Path(run_dir, TRACK_FOLDER, "traceback.html") + make_traceback_plot(rank_data_subset, plot_filename, offline=offline) + return + + +if __name__ == "__main__": + sys.exit(maincli()) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_unpack.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..6dbd5487341a464cf86c6eb7464fc141aae3e231 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/cli_unpack.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +""" +Unpack the output of an HADDOCK3 run directory. + +The unpack process performs file unpacking and file decompressing +operations. File with extension `seed` and `con` are unpacked from +their `.tgz` files. While files with `.pdb.gz` and `.psf.gz` extension +are uncompressed. If `--all` is given, unpack also `.inp.gz` and +`.out.gz` files. + +This CLI performs the opposite operations as the ``haddock3-clean`` +command-line. + +The can either be a whole HADDOCK3 run folder or a +specific folder of the workflow step. defined the number of +threads to use. + +Usage:: + + haddock3-unpack -h + haddock3-unpack -r + haddock3-unpack run1 + haddock3-unpack run1/1_rigidbody + haddock3-unpack run1 -n # uses all cores + haddock3-unpack run1 -n 2 # uses 2 cores + haddock3-unpack run1 -n 2 -a + haddock3-unpack run1 -n 2 --all +""" +import argparse +import sys + +from haddock.core.typing import ( + ArgumentParser, + Callable, + FilePath, + Namespace, + Optional, +) +from haddock.libs import libcli + + +# Command line interface parser +ap = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, +) + +libcli.add_rundir_arg(ap) + +ap.add_argument( + "--all", + "-a", + dest="dec_all", + help="Unpack all files (includes `.inp` and `.out`).", + action="store_true", +) + +libcli.add_ncores_arg(ap) +libcli.add_version_arg(ap) + + +def _ap() -> ArgumentParser: + return ap + + +def load_args(ap: ArgumentParser) -> Namespace: + """Load argument parser args.""" + return ap.parse_args() + + +def cli(ap: ArgumentParser, main: Callable[..., None]) -> None: + """Command-line interface entry point.""" + cmd = load_args(ap) + main(**vars(cmd)) + + +def maincli() -> None: + """Execute main client.""" + cli(ap, main) + + +def main(run_dir: FilePath, ncores: Optional[int] = 1, dec_all: bool = False) -> None: + """ + Unpack a HADDOCK3 run directory step folders. + + Usually, this concerns uncompressing and unpacking files. + + It performs the oposity function as + :py:func:`haddock.clis.cli_clean.main`. + + Parameters + ---------- + run_dir : str or :external:py:class:`pathlib.Path`. + The path to the run directory or to a folder of a specific step + of the workflow. + + ncores : int, or None + The number of cores to use. If ``None``, use all possible threads. + Defaults to 1. + + See Also + -------- + `haddock.gear.clean_steps` + """ + # anti-pattern to speed up CLI initiation + from pathlib import Path + + from haddock import log + from haddock.gear.clean_steps import unpack_compressed_and_archived_files + from haddock.libs.libtimer import log_time + from haddock.libs.libutil import parse_ncores + from haddock.modules import get_module_steps_folders, is_step_folder + + log.info(f"Unpacking {str(run_dir)!r} folder") + ncores = parse_ncores(ncores) + + if is_step_folder(run_dir): + with log_time("unpacking took"): + unpack_compressed_and_archived_files( + [run_dir], + ncores, + dec_all=dec_all, + ) + + else: + step_folders = [Path(run_dir, p) for p in get_module_steps_folders(run_dir)] + with log_time("unpacking took"): + unpack_compressed_and_archived_files( + step_folders, + ncores, + dec_all=dec_all, + ) + + return + + +if __name__ == "__main__": + sys.exit(maincli()) # type: ignore diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._clustfcc.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._clustfcc.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._clustfcc.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._clustrmsd.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._clustrmsd.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._clustrmsd.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._score.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._score.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/._score.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/__init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/__init__.py @@ -0,0 +1 @@ + diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/clustfcc.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/clustfcc.py new file mode 100644 index 0000000000000000000000000000000000000000..fd5e2f5a038842345f371af18f954a33ff1d4277 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/clustfcc.py @@ -0,0 +1,215 @@ +"""haddock3-re clustfcc subcommand.""" + +import shutil +from pathlib import Path + +from haddock import log +from haddock.core.defaults import INTERACTIVE_RE_SUFFIX +from haddock.core.typing import Union +from haddock.gear.config import load as read_config +from haddock.gear.config import save as save_config +from haddock.libs.libclust import ( + add_cluster_info, + get_cluster_matrix_plot_clt_dt, + plot_cluster_matrix, + rank_clusters, + write_structure_list, + ) +from haddock.libs.libfcc import create_elements, load_matrix +from haddock.libs.libinteractive import look_for_capri, rewrite_capri_tables +from haddock.libs.libontology import ModuleIO +from haddock.modules.analysis.clustfcc.clustfcc import ( + get_cluster_centers, + iterate_clustering, + write_clusters, + write_clustfcc_file, + ) + + +def add_clustfcc_arguments(clustfcc_subcommand): + """Add arguments to the clustfcc subcommand.""" + clustfcc_subcommand.add_argument( + "clustfcc_dir", + help="The clustfcc directory to recluster.", + ) + + clustfcc_subcommand.add_argument( + "-f", + "--clust_cutoff", + help="Minimum fraction of common contacts to be considered in a cluster.", # noqa: E501 + required=False, + type=float, + ) + + clustfcc_subcommand.add_argument( + "-s", + "--strictness", + help="Strictness factor.", + required=False, + type=float, + ) + + clustfcc_subcommand.add_argument( + "-t", + "--min_population", + help="Clustering population threshold.", + required=False, + type=int, + ) + + clustfcc_subcommand.add_argument( + "-p", + "--plot_matrix", + help="Generate the matrix plot with the clusters.", + required=False, + default=False, + action="store_true", + ) + + return clustfcc_subcommand + + +def reclustfcc( + clustfcc_dir: str, + clust_cutoff: Union[bool, float] = None, + strictness: Union[bool, float] = None, + min_population: Union[bool, int] = None, + plot_matrix: bool = True, +) -> Path: + """ + Recluster the models in the clustfcc directory. + + Parameters + ---------- + clustfcc_dir : str + Path to the clustfcc directory. + + clust_cutoff : Union[bool, float] + Fraction of common contacts to not be considered a singleton model. + + strictness : Union[bool, float] + Fraction of common contacts to be considered to be part of the same + cluster. + + min_population : Union[bool, int] + Minimum cluster population. + + plot_matrix : bool + Should the corresponding matrix plot be generated. + + Returns + ------- + outdir : Path + Path to the interactive directory. + """ + log.info(f"Reclustering {clustfcc_dir}") + + # create the interactive folder + run_dir = Path(clustfcc_dir).parent + clustfcc_name = Path(clustfcc_dir).name + outdir = Path(run_dir, f"{clustfcc_name}_{INTERACTIVE_RE_SUFFIX}") + outdir.mkdir(exist_ok=True) + + # create an io object + io = ModuleIO() + filename = Path(clustfcc_dir, "io.json") + io.load(filename) + models = io.input + # copying io.json to the new directory + shutil.copy(filename, Path(outdir, "io.json")) + + # load the original clustering parameters via json + clustfcc_params = read_config(Path(clustfcc_dir, "params.cfg")) + key = list(clustfcc_params["final_cfg"].keys())[0] + clustfcc_params = clustfcc_params["final_cfg"][key] + log.info(f"Previous clustering parameters: {clustfcc_params}") + + # adjust the parameters + if clust_cutoff is not None: + clustfcc_params["clust_cutoff"] = clust_cutoff + if strictness is not None: + clustfcc_params["strictness"] = strictness + if min_population is not None: + clustfcc_params["min_population"] = min_population + clustfcc_params["plot_matrix"] = plot_matrix + + matrix = load_matrix(Path(clustfcc_dir, "fcc.matrix")) + # load the fcc matrix + pool = create_elements( + matrix, + clustfcc_params["clust_cutoff"], + clustfcc_params["strictness"], + ) + + # iterate clustering until at least one cluster is found + clusters, min_population = iterate_clustering( + pool, clustfcc_params["min_population"] + ) + clustfcc_params["min_population"] = min_population + log.info(f"Updated clustering parameters: {clustfcc_params}") + + # Prepare output and read the elements + clt_dic = {} + if clusters: + write_clusters(clusters, out_filename=Path(outdir, "cluster.out")) + + # Get the cluster centers + clt_dic, clt_centers = get_cluster_centers(clusters, models) + + _score_dic, sorted_score_dic = rank_clusters(clt_dic, min_population) + + output_models = add_cluster_info(sorted_score_dic, clt_dic) + + # Write unclustered structures + write_structure_list( + models, output_models, out_fname=Path(outdir, "clustfcc.tsv") + ) + + write_clustfcc_file( + clusters, + clt_centers, + clt_dic, + clustfcc_params, + sorted_score_dic, + output_fname=Path(outdir, "clustfcc.txt"), + ) + + save_config(clustfcc_params, Path(outdir, "params.cfg")) + + # analysis + clustfcc_id = int(clustfcc_name.split("_")[0]) + caprieval_folder = look_for_capri(run_dir, clustfcc_id) + if caprieval_folder: + log.info("Rewriting capri tables") + rewrite_capri_tables(caprieval_folder, clt_dic, outdir) + + else: + output_models = models + + # Generate matrix plot + if clustfcc_params["plot_matrix"]: + log.info("Generating graphical representation of the clusters.") + # Obtain final models indices + final_order_idx, labels, cluster_ids = [], [], [] + for pdb in output_models: + final_order_idx.append(models.index(pdb)) + labels.append(pdb.file_name.replace(".pdb", "")) + cluster_ids.append(pdb.clt_id) + # Get custom cluster data + matrix_cluster_dt, cluster_limits = get_cluster_matrix_plot_clt_dt(cluster_ids) + # Define output filename + html_matrix_basepath = Path(outdir, "fcc_matrix") + # Plot matrix + html_matrixpath = plot_cluster_matrix( + Path(clustfcc_dir, "fcc.matrix"), + final_order_idx, + labels, + dttype="FCC", + diag_fill=1, + output_fname=html_matrix_basepath, + matrix_cluster_dt=matrix_cluster_dt, + cluster_limits=cluster_limits, + ) + log.info(f"Plotting matrix in {html_matrixpath}") + + return outdir diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/clustrmsd.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/clustrmsd.py new file mode 100644 index 0000000000000000000000000000000000000000..38b185b5d72c00d6813db692f9d9a281bcbd5cd4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/clustrmsd.py @@ -0,0 +1,289 @@ +"""haddock3-re clustrmsd subcommand.""" +from pathlib import Path +import numpy as np + +from haddock import log +from haddock.core.defaults import INTERACTIVE_RE_SUFFIX +from haddock.core.typing import Union, Optional +from haddock.gear.config import load as read_config +from haddock.gear.config import save as save_config +from haddock.modules import get_module_steps_folders +from haddock.libs.libclust import ( + add_cluster_info, + clustrmsd_tolerance_params, + get_cluster_matrix_plot_clt_dt, + plot_cluster_matrix, + rank_clusters, + write_structure_list, + ) +from haddock.libs.libinteractive import look_for_capri, rewrite_capri_tables +from haddock.libs.libontology import ModuleIO +from haddock.modules.analysis.clustrmsd.clustrmsd import ( + get_clusters, + get_matrix_path, + iterate_min_population, + order_clusters, + write_clusters, + write_clustrmsd_file, + ) + + +def add_clustrmsd_arguments(clustrmsd_subcommand): + """Add arguments to the clustrmsd subcommand.""" + clustrmsd_subcommand.add_argument( + "clustrmsd_dir", + help="The clustrmsd directory to recluster.", + ) + + clustrmsd_subcommand.add_argument( + "-n", + "--n_clusters", + help="number of clusters to generate.", + required=False, + type=int, + ) + + clustrmsd_subcommand.add_argument( + "-d", + "--clust_cutoff", + help="clustering cutoff distance.", + required=False, + type=float, + ) + + clustrmsd_subcommand.add_argument( + "-t", + "--min_population", + help="minimum cluster population.", + required=False, + type=int, + ) + + clustrmsd_subcommand.add_argument( + "-p", + "--plot_matrix", + help="Generate the matrix plot with the clusters.", + required=False, + default=False, + action='store_true', + ) + + return clustrmsd_subcommand + + +def reclustrmsd( + clustrmsd_dir: str, + n_clusters: Union[bool, int] = None, + clust_cutoff: Union[bool, float] = None, + min_population: Union[bool, int] = None, + plot_matrix: bool = True, + ) -> Path: + """ + Recluster the models in the clustrmsd directory. + + Parameters + ---------- + clustrmsd_dir : str + Path to the clustrmsd directory. + + n_clusters : Union[bool, int] + Number of clusters to generate. + + clust_cutoff : Union[bool, float] + Clustering cutoff distance. + + min_population : Union[bool, int] + Cluster population min_population. + + plot_matrix : bool + Should the corresponding matrix plot be generated. + + Returns + ------- + outdir : Path + Path to the interactive directory. + """ + log.info(f"Reclustering {clustrmsd_dir}") + + run_dir = Path(clustrmsd_dir).parent + clustrmsd_name = Path(clustrmsd_dir).name + # create the interactive folder + outdir = Path(run_dir, f"{clustrmsd_name}_{INTERACTIVE_RE_SUFFIX}") + outdir.mkdir(exist_ok=True) + + # create an io object + io = ModuleIO() + filename = Path(clustrmsd_dir, "io.json") + io.load(filename) + models = io.input + + # load the original clustering parameters via json + clustrmsd_params = read_config(Path(clustrmsd_dir, "params.cfg")) + key = list(clustrmsd_params['final_cfg'].keys())[0] + clustrmsd_params = clustrmsd_params['final_cfg'][key] + log.info(f"Previous clustering parameters: {clustrmsd_params}") + + # setting previous tolerance, just in case no new parameters are given + tolerance_param_name, tolerance = clustrmsd_tolerance_params( + clustrmsd_params, + ) + + # adjust the parameters + if n_clusters is not None: + clustrmsd_params["n_clusters"] = n_clusters + clustrmsd_params["criterion"] = "maxclust" + tolerance = n_clusters + else: + if clust_cutoff is not None: + clustrmsd_params["clust_cutoff"] = clust_cutoff + clustrmsd_params["criterion"] = "distance" + tolerance = clust_cutoff + + if min_population is not None: + clustrmsd_params["min_population"] = min_population + + clustrmsd_params["plot_matrix"] = plot_matrix + + log.info( + f"Clustering with {tolerance_param_name} = {tolerance}, " + f"and criterion {clustrmsd_params['criterion']}" + ) + + # load the clustering dendrogram + dendrogram = np.loadtxt(Path(clustrmsd_dir, "dendrogram.txt")) + + # get the clusters + cluster_arr = get_clusters( + dendrogram, + tolerance, + clustrmsd_params["criterion"], + ) + log.info(f"clusters {cluster_arr}") + + if clustrmsd_params['criterion'] == "distance": + cluster_arr, min_population = iterate_min_population( + cluster_arr, + clustrmsd_params['min_population'] + ) + clustrmsd_params['min_population'] = min_population + log.info(f"Updated clustering parameters = {clustrmsd_params}") + + # processing the clusters + clusters, cluster_arr = order_clusters(cluster_arr) + log.info(f"clusters = {clusters}") + log.info(f"cluster_arr = {cluster_arr}") + + clt_dic, cluster_centers = write_clusters( + clusters, + cluster_arr, + models, + out_filename=Path(outdir, "cluster.out"), + rmsd_matrix=None, + centers=False + ) + + score_dic, sorted_score_dic = rank_clusters( + clt_dic, + clustrmsd_params["min_population"] + ) + + output_models = add_cluster_info(sorted_score_dic, clt_dic) + + write_structure_list( + models, + output_models, + out_fname=Path(outdir, "clustrmsd.tsv"), + ) + + write_clustrmsd_file( + clusters, + clt_dic, + cluster_centers, + score_dic, + sorted_score_dic, + clustrmsd_params, + output_fname=Path(outdir, "clustrmsd.txt"), + ) + + # Draw the matrix + if clustrmsd_params["plot_matrix"]: + if not (matrix_json_path := search_previousstep_matrix(clustrmsd_dir)): + log.warn( + "Could not find the rmsd matrix in previous step." + " Unable to produce a graph out of it!" + ) + else: + log.info("Generating graphical representation of the clusters.") + matrix_io = ModuleIO() + matrix_io.load(matrix_json_path) + # Obtain final models indices + final_order_idx, labels, cluster_ids = [], [], [] + for pdb in output_models: + final_order_idx.append(models.index(pdb)) + labels.append(pdb.file_name.replace('.pdb', '')) + cluster_ids.append(pdb.clt_id) + # Get custom cluster data + matrix_cluster_dt, cluster_limits = get_cluster_matrix_plot_clt_dt( + cluster_ids + ) + # Define output filename + html_matrix_basepath = Path(outdir, 'rmsd_matrix') + # Plot matrix + html_matrixpath = plot_cluster_matrix( + get_matrix_path(matrix_io.input[0]), + final_order_idx, + labels, + dttype='RMSD(Å)', + reverse=True, + diag_fill=0, + output_fname=html_matrix_basepath, + matrix_cluster_dt=matrix_cluster_dt, + cluster_limits=cluster_limits, + ) + log.info(f"Plotting matrix in {html_matrixpath}") + + # save the io.json file + io.save(outdir) + + # save the updated parameters in a json file + save_config(clustrmsd_params, Path(outdir, "params.cfg")) + + # analysis + clustrmsd_id = int(clustrmsd_name.split("_")[0]) + caprieval_folder = look_for_capri(run_dir, clustrmsd_id) + if caprieval_folder: + log.info("Rewriting capri tables") + rewrite_capri_tables(caprieval_folder, clt_dic, outdir) + + return outdir + + +def search_previousstep_matrix(clustrmsd_dir: str) -> Optional[Path]: + """Retrieve the path of the previous step matrix_json file. + + Parameters + ---------- + clustrmsd_dir : str + Path to the clustrmsd directory. + + Returns + ------- + matrix_json : Optional[Path] + Path to the matrix_json file. + """ + # Compute previous step index + previous_step_ind = int(str(Path(clustrmsd_dir).name).split('_')[0]) - 1 + workflow_dir = Path(clustrmsd_dir).parent + # Try to get previous step directory name + try: + previous_steps = get_module_steps_folders( + workflow_dir, + [previous_step_ind], + ) + previous_step = previous_steps[0] + except IndexError: + return None + else: + matrix_json = Path(workflow_dir, previous_step, "rmsd_matrix.json") + if matrix_json.exists(): + return matrix_json diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/score.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/score.py new file mode 100644 index 0000000000000000000000000000000000000000..afda8a699f5c2ee0b7fd33e56c85b716013a83ab --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/re/score.py @@ -0,0 +1,148 @@ +"""haddock3-re score subcommand.""" +import json +from pathlib import Path +import sys + +from haddock import log +from haddock.core.defaults import INTERACTIVE_RE_SUFFIX +from haddock.core.typing import Union +from haddock.libs.libinteractive import handle_ss_file, handle_clt_file +from haddock.libs.libplots import read_capri_table + + +def add_rescore_arguments(rescore_subcommand): + """Add arguments to the score subcommand.""" + rescore_subcommand.add_argument( + "capri_dir", + help="The caprieval directory to rescore.", + ) + + rescore_subcommand.add_argument( + "-e", + "--w_elec", + help="weight of the electrostatic component.", + required=False, + type=float, + ) + + rescore_subcommand.add_argument( + "-w", + "--w_vdw", + help="weight of the van-der-Waals component.", + required=False, + type=float, + ) + + rescore_subcommand.add_argument( + "-d", + "--w_desolv", + help="weight of the desolvation component.", + required=False, + type=float, + ) + + rescore_subcommand.add_argument( + "-b", + "--w_bsa", + help="weight of the BSA component.", + required=False, + type=float, + ) + + rescore_subcommand.add_argument( + "-a", + "--w_air", + help="weight of the AIR component.", + required=False, + type=float, + ) + + return rescore_subcommand + + +ANA_FOLDER = "interactive" # name of the analysis folder + + +def rescore( + capri_dir: Union[str, Path], + w_elec: Union[bool, float] = None, + w_vdw: Union[bool, float] = None, + w_desolv: Union[bool, float] = None, + w_bsa: Union[bool, float] = None, + w_air: Union[bool, float] = None, + ) -> Path: + """Rescore the CAPRI models.""" + log.info(f"Rescoring {capri_dir}") + # load the scoring pars via json + weights_filename = Path(capri_dir, "weights_params.json") + if not weights_filename.exists(): + log.error(f"weights file {weights_filename} not found. Exiting.") + sys.exit(1) + scoring_pars = json.load(open(weights_filename, "r")) + log.info(f"Previous scoring parameters: {scoring_pars}") + if w_elec is not None: + scoring_pars.update({"w_elec": w_elec}) + if w_vdw is not None: + scoring_pars.update({"w_vdw": w_vdw}) + if w_desolv is not None: + scoring_pars.update({"w_desolv": w_desolv}) + if w_bsa is not None: + scoring_pars.update({"w_bsa": w_bsa}) + if w_air is not None: + scoring_pars.update({"w_air": w_air}) + + log.info(f"Rescoring parameters: {scoring_pars}") + + capri_ss = Path(capri_dir, "capri_ss.tsv") + capri_clt = Path(capri_dir, "capri_clt.tsv") + if not capri_ss.exists() or not capri_clt.exists(): + log.error("capri_ss.tsv or capri_clt.tsv not found. Exiting.") + sys.exit(1) + # ss file + df_ss = read_capri_table(capri_ss) + # now we want to rewrite the score parameter + new_scores = scoring_pars["w_vdw"] * df_ss["vdw"] + \ + scoring_pars["w_elec"] * df_ss["elec"] + \ + scoring_pars["w_bsa"] * df_ss["bsa"] + \ + scoring_pars["w_desolv"] * df_ss["desolv"] + \ + scoring_pars["w_air"] * df_ss["air"] + + df_ss["score"] = new_scores + + # now we want to write the new capri_ss.tsv file + run_dir = Path(capri_dir).parent + capri_name = Path(capri_dir).name + + # create the interactive folder + outdir = Path(run_dir, f"{capri_name}_{INTERACTIVE_RE_SUFFIX}") + outdir.mkdir(exist_ok=True) + + # handle ss file first + df_ss, clt_ranks_dict = handle_ss_file(df_ss) + capri_ss_file = Path(outdir, "capri_ss.tsv") + log.info(f"Saving capri_ss file to {capri_ss_file}") + df_ss.to_csv(capri_ss_file, sep="\t", index=False, float_format="%.3f") + + df_clt = handle_clt_file(df_ss, clt_ranks_dict) + capri_clt_file = Path(outdir, "capri_clt.tsv") + df_clt.to_csv( + capri_clt_file, + sep="\t", + index=False, + float_format="%.3f", + ) + + # Write the latest parameters file + # define output fname + rescoring_params_fname = Path(outdir, "weights_params.json") + # write json file + with open(rescoring_params_fname, 'w', encoding='utf-8') as jsonf: + json.dump( + scoring_pars, + jsonf, + indent=4, + ) + log.info(f"new rescoring parameters written in: {rescoring_params_fname}") + + # return path to the new interactive folder + return outdir diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._active_passive_to_ambig.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._active_passive_to_ambig.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._active_passive_to_ambig.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._calc_accessibility.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._calc_accessibility.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._calc_accessibility.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._naccess.config b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._naccess.config new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._naccess.config differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._passive_from_active.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._passive_from_active.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._passive_from_active.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._random_removal.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._random_removal.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._random_removal.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._restrain_bodies.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._restrain_bodies.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._restrain_bodies.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._restrain_ligand.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._restrain_ligand.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._restrain_ligand.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._validate_tbl.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._validate_tbl.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._validate_tbl.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._webservice.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._webservice.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._webservice.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._z_surface_restraints.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._z_surface_restraints.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/._z_surface_restraints.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/__init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/active_passive_to_ambig.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/active_passive_to_ambig.py new file mode 100644 index 0000000000000000000000000000000000000000..3affb3a83fbeeb54536ea035a966b45d2e33574b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/active_passive_to_ambig.py @@ -0,0 +1,75 @@ +"""haddock3-restraints active_passive_to_ambig subcommand. + +Given two files containing active (in the first line) and passive (second line) + residues to be used by HADDOCK, this command gives in output the corresponding + ambig.tbl file. + +Usage: + haddock3-restraints active_passive_to_ambig file_actpass_one file_actpass_two [--segid-one] [--segid-two] + +An example content for file_actpass_one is + 72 73 74 75 81 83 84 89 90 92 94 96 97 98 115 116 117 + 3 24 46 47 48 50 66 76 77 79 80 82 86 87 88 91 93 95 118 119 120 +""" +from haddock.libs.librestraints import active_passive_to_ambig, parse_actpass_file + + +def add_actpass_to_ambig_arguments(actpass_to_ambig_subcommand): + """Add arguments to the score subcommand.""" + actpass_to_ambig_subcommand.add_argument( + "actpass_one", + type=str, + help="First actpass file", + ) + + actpass_to_ambig_subcommand.add_argument( + "actpass_two", + type=str, + help="Second actpass file", + ) + + actpass_to_ambig_subcommand.add_argument( + "--segid-one", + type=str, + help="Segid to use for the first model", + default="A" + ) + + actpass_to_ambig_subcommand.add_argument( + "--segid-two", + type=str, + help="Segid to use for the second model", + default="B" + ) + + return actpass_to_ambig_subcommand + + +def actpass_to_ambig(actpass_one, actpass_two, segid_one, segid_two): + """Generate ambig from two actpass files. + + Parameters + ---------- + actpass_one : str + path to first actpass file + + actpass_two : str + path to second actpass file + + segid_one : str + segid to use for the first model + + segid_two : str + segid to use for the second model + """ + active1, passive1 = parse_actpass_file(actpass_one) + active2, passive2 = parse_actpass_file(actpass_two) + # Check if there are active residues in at least one of the two files + if active1 == [] and active2 == []: + raise ValueError( + f"No active residues found in {actpass_one} and {actpass_two}. " + "No restraints will be generated." + ) + active_passive_to_ambig(active1, passive1, active2, passive2, segid_one, segid_two) + + return diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/calc_accessibility.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/calc_accessibility.py new file mode 100644 index 0000000000000000000000000000000000000000..a3283d87c10f888110d4954fd5493efff446388c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/calc_accessibility.py @@ -0,0 +1,309 @@ +"""haddock3-restraints calc_accessibility subcommand. + +Given a pdb file, it will calculate the relative accessibility of +the side chains and return a list of surface exposed residues. + +Nucleic acids bases are considered to be always accessible. + +Usage: + haddock3-restraints calc_accessibility + Path to a PDB file to analyse + [-c ] Relative side-chain accessibility cutoff + [--log_level ] DEBUG, INFO, WARNING, ERROR, or CRITICAL + [--export_to_actpass] Flag to export accessible resiudes + [--probe_radius ] Probe radius for the accessibility calculation +""" + + +import logging +import os +from pathlib import Path +from freesasa import Structure + +from haddock.core.typing import Union +from haddock.libs.librestraints import DEFAULT_PROBE_RADIUS, REL_ASA + + +# As this script is a subcommand of the `haddock3-restraints` cli, +# it requires its own options and arguments that are managed here. +def add_calc_accessibility_arguments(calc_accessibility_subcommand): + """Add arguments to the calc_accessibility subcommand.""" + calc_accessibility_subcommand.add_argument( + "input_pdb_file", + type=str, + help="input PDB structure.", + ) + + calc_accessibility_subcommand.add_argument( + "-c", + "--cutoff", + help="Relative cutoff for sidechain accessibility", + required=False, + default=0.4, + type=float, + ) + + calc_accessibility_subcommand.add_argument( + "--log_level", + default='INFO', + choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'), + help="Logging level", + required=False, + ) + + calc_accessibility_subcommand.add_argument( + "--export_to_actpass", + default=False, + action="store_true", + help="Export the exposed residues as passive to an actpass file", + required=False, + ) + + calc_accessibility_subcommand.add_argument( + "--probe_radius", + default=DEFAULT_PROBE_RADIUS, + type=float, + help="Probe radius for the accessibility calculation", + required=False, + ) + + return calc_accessibility_subcommand + + +########################################################## +# Define set of resiudes / bases handeled by this script # +########################################################## +DEFAULT_BASES = ["DA", "DC", "DG", "DT", "A", "C", "G", "U"] +MODIFIED_BASES = ["DJ"] +STANDARD_AA = [ + 'ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', + 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', + ] +MODIFIED_AA = [ + 'ACE', 'ALY', 'ASH', 'CFE', 'CHX', 'CSP', 'CTN', 'CYC', 'CYF', 'CYM', + 'DDZ', 'DUM', 'GLH', 'HLY', 'HYP', 'M3L', 'MLY', 'MLZ', 'MSE', 'NEP', + 'PNS', 'PTR', 'SEP', 'TOP', 'TYP', 'TYS', + ] # , 'THP'='TOP'? +VALID_AA = STANDARD_AA + MODIFIED_AA +VALID_BASES = DEFAULT_BASES + MODIFIED_BASES +VALID_IONS = [ + "LI", "F", "NA", "MG", "AL", "CL", "K", "CA", "V", "CR", "MN", "FE", "NI", + "CO", "CU", "ZN", "BR", "KR", "SR", "MO", "AG", "CD", "I", "CS", "HO", + "YB", "OS", "IR", "PT", "AU", "HG", "PB", + ] + + +def get_accessibility( + pdb_f: Union[Path, str], + probe_radius: float = DEFAULT_PROBE_RADIUS, + ) -> dict[str, dict[int, dict[str, float]]]: + """Compute per-residue accessibility values. + + Calls `FreeSASA `_ using its Python API + and returns per-residue accessibility values. + + Parameters + ---------- + pdb_f : Union[Path, str] + Path to the PDB file of interest. + + Return + ------ + resid_access : dict[str, dict[int, dict[str, float]]] + Dictionary containing a list of accessible residues for each chain(s). + """ + naccess_unsupported_aa = ['HEC', 'TIP', 'ACE', 'THP', 'HEB', 'CTN'] + logging.info("Calculate accessibility...") + try: + from freesasa import Classifier, calc, Parameters + except ImportError as err: + logging.error("calc_accessibility requires the 'freesasa' Python API") + raise ImportError(err) + + # Initiate data holders + asa_data: dict[tuple[str, str, int, str], float] = {} + rsa_data: dict[tuple[str, str, int], float] = {} + rel_main_chain: dict[tuple[str, str, int], float] = {} + rel_side_chain: dict[tuple[str, str, int], float] = {} + # Point relative asa data + _rsa = REL_ASA['total'] + _rsa_bb = REL_ASA['bb'] + _rsa_sc = REL_ASA['sc'] + + # Workaround to get relative accessibility values for Nucleic Acids + # -> will always be accessible ! + for na in VALID_BASES: + _rsa[na] = 1 + _rsa_bb[na] = 1 + _rsa_sc[na] = 1 + + _script_path = '/'.join(os.path.realpath(__file__).split('/')[:-1]) + config_path = _script_path + '/naccess.config' + classifier = Classifier(config_path) + + struct = Structure(pdb_f, classifier, options={}) + struct.setRadiiWithClassifier(classifier) + # if the probe_radius is different from the default value + # we need to redefine the parameters + if probe_radius != DEFAULT_PROBE_RADIUS: + new_parameters = Parameters( + { + 'algorithm': 'LeeRichards', + 'probe-radius': probe_radius, + 'n-points': Parameters.defaultParameters['n-points'], + 'n-slices': Parameters.defaultParameters['n-slices'], + 'n-threads': Parameters.defaultParameters['n-threads'], + } + ) + result = calc(struct, parameters=new_parameters) + else: + result = calc(struct) + + # iterate over all atoms to get SASA and residue name + for idx in range(struct.nAtoms()): + atname = struct.atomName(idx).strip() + resname = struct.residueName(idx).strip() + resid = int(struct.residueNumber(idx)) + chain = struct.chainLabel(idx) + at_uid = (chain, resname, resid, atname) + res_uid = (chain, resname, resid) + + asa = result.atomArea(idx) + asa_data[at_uid] = asa + # add asa to residue + rsa_data[res_uid] = rsa_data.get(res_uid, 0) + asa + + # If residue name is unknown, this is probably an ion, + # set a relative accessibility of -1 + if resname not in _rsa and ( + resname not in VALID_AA + VALID_BASES + or resname[:2] in VALID_IONS + or resname in naccess_unsupported_aa + ): + logging.warning(f"UPDATED RSA for {resname}") + _rsa[resname] = -1 + _rsa_bb[resname] = -1 + _rsa_sc[resname] = -1 + + # 3 cases: Regular amino-acid, regular nucleic acid, ion + if (resname not in VALID_BASES and atname in ('C', 'N', 'O')) or \ + (resname in VALID_BASES and atname in ('P', 'C1', 'C9')): + rel_main_chain[res_uid] = rel_main_chain.get(res_uid, 0) + asa + elif all([ + resname not in VALID_AA + VALID_BASES, + resname[:2] in VALID_IONS, + ]): + rel_main_chain[res_uid] = rel_main_chain.get(res_uid, 0) + asa + rel_side_chain[res_uid] = rel_side_chain.get(res_uid, 0) + asa + else: + rel_side_chain[res_uid] = rel_side_chain.get(res_uid, 0) + asa + # convert total asa to relative asa + rsa_data.update( + (res_uid, asa / _rsa[res_uid[1]]) + for res_uid, asa in rsa_data.items() + ) + rel_main_chain.update( + (res_uid, asa / _rsa_bb[res_uid[1]] * 100) + for res_uid, asa in rel_main_chain.items() + ) + rel_side_chain.update( + (res_uid, asa / _rsa_sc[res_uid[1]] * 100) + for res_uid, asa in rel_side_chain.items() + ) + # We format to fit the pipeline + resid_access: dict[str, dict[int, dict[str, float]]] = {} + for res_uid, access in rel_main_chain.items(): + chain = res_uid[0] + # resname = res_uid[1] + resnum = res_uid[2] + if chain not in resid_access: + resid_access[chain] = {} + resid_access[chain][resnum] = { + 'side_chain_rel': rel_side_chain.get(res_uid, 0), + 'main_chain_rel': access, + } + # Display accessible residues + for chain in resid_access: + logging.info(f"Chain: {chain} - {len(resid_access[chain])} residues") + return resid_access + + +def apply_cutoff( + access_data: dict[str, dict[int, dict[str, float]]], + cutoff: float, + ) -> dict[str, list[int]]: + """Apply a cutoff to the sidechain relative accessibility.""" + logging.info(f'Applying cutoff to side_chain_rel - {cutoff}') + # saving the results in a dictionary + result_dict: dict[str, list[int]] = {} + for chain in access_data: + result_list: list[int] = [] + for res in access_data[chain]: + sc_rel_accessibility = access_data[chain][res]['side_chain_rel'] + if sc_rel_accessibility >= cutoff * 100: + result_list.append(res) + result_list = list(set(result_list)) + result_list.sort() + result_str = ','.join(map(str, result_list)) + logging.info(f'Chain {chain} - {result_str}') + # putting the data in the dictionary + result_dict[chain] = result_list + return result_dict + + +def export_passive( + result_dict: dict[str, list[int]], + prefix: str = '', + ) -> None: + """Export the exposed residues as passive to an actpass file.""" + for chain in result_dict: + filename = Path(f"{prefix}passive_{chain}.actpass") + logging.info(f"Writing exposed residues as passive in: {filename}") + if filename.exists(): + logging.error( + f"File {filename} already exists, nothing performed!" + ) + else: + with open(filename, "w") as f: + f.write(os.linesep) # Add empty line as no active residues + f.write(f"{' '.join(map(str, result_dict[chain]))}") + + +def calc_accessibility( + input_pdb_file: Union[Path, str], + cutoff: float = 0.4, + log_level: str = "INFO", + export_to_actpass: bool = False, + probe_radius: float = DEFAULT_PROBE_RADIUS, + ) -> None: + """Calculate the accessibility of the side chains and apply a cutoff. + + Parameters + ---------- + input_pdb_file : str + Path to the PDB file. + cutoff : float + Relative cutoff for sidechain accessibility, default = 0.4 + log_level : str + Logging level. + export_to_actpass : bool + Export the exposed residues as passive to an actpass file. + probe_radius : float + Probe radius for the accessibility calculation. + """ + logging.basicConfig( + level=log_level, + format='%(asctime)s L%(lineno)d %(levelname)s - %(message)s', + datefmt='%d/%m/%Y %H:%M:%S', + ) + # Compute per-residues accessibilities + access_dic = get_accessibility(input_pdb_file, probe_radius) + # Filter residues based on accessibility cutoff + result_dict = apply_cutoff(access_dic, cutoff) + + # export residues as passive to an actpass file + if export_to_actpass: + export_passive( + result_dict, + prefix=f'{Path(input_pdb_file).stem}_', + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/naccess.config b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/naccess.config new file mode 100644 index 0000000000000000000000000000000000000000..57075ef62099d4ecac9073d1f55bc6ca51316a9f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/naccess.config @@ -0,0 +1,414 @@ +# Contributed by João Rodrigues & Mikael Trellet + +name: NACCESS + +types: +C_ALI 1.87 apolar +C_CAR 1.76 apolar +C_NUC 1.80 apolar +N_AMN 1.50 polar +N_AMD 1.65 polar +N_NUC 1.60 polar +O 1.40 polar +S 1.85 apolar +SE 1.80 apolar +P 1.90 apolar + +atoms: +ANY C C_CAR +ANY O O +ANY CA C_ALI +ANY N N_AMD +ANY CB C_ALI +ANY OXT O +# nucleic acid +ANY P P +ANY OP1 O +ANY OP2 O +ANY OP3 O +ANY O1P O +ANY O2P O +ANY O3P O +ANY O5' O +ANY O4' O +ANY O3' O +ANY O2' O +ANY C5' C_NUC +ANY C4' C_NUC +ANY C3' C_NUC +ANY C2' C_NUC +ANY C1' C_NUC + +ALA CB C_ALI # included so that RSA values will be generated + +ARG CG C_ALI +ARG CD C_ALI +ARG NE N_AMD +ARG CZ C_CAR +ARG NH1 N_AMD +ARG NH2 N_AMD + +ASN CG C_CAR +ASN OD1 O +ASN ND2 N_AMD + +ASP CG C_CAR +ASP OD1 O +ASP OD2 O + +CYS SG S + +GLN CG C_ALI +GLN CD C_CAR +GLN OE1 O +GLN NE2 N_AMD + +GLU CG C_ALI +GLU CD C_CAR +GLU OE1 O +GLU OE2 O + +GLY CA C_ALI # included so that RSA values will be generated + +HIS CG C_CAR +HIS ND1 N_AMD +HIS CD2 C_CAR +HIS NE2 N_AMD +HIS CE1 C_CAR + +ILE CG1 C_ALI +ILE CG2 C_ALI +ILE CD1 C_ALI + +LEU CG C_ALI +LEU CD1 C_ALI +LEU CD2 C_ALI + +LYS CG C_ALI +LYS CD C_ALI +LYS CE C_ALI +LYS NZ N_AMN + +MET CG C_ALI +MET SD S +MET CE C_ALI + +PHE CG C_CAR +PHE CD1 C_CAR +PHE CD2 C_CAR +PHE CE1 C_CAR +PHE CE2 C_CAR +PHE CZ C_CAR + +PRO CG C_ALI +PRO CD C_ALI + +SEC SE SE + +SER OG O + +THR OG1 O +THR CG2 C_ALI + +TRP CG C_CAR +TRP CD1 C_CAR +TRP CD2 C_CAR +TRP NE1 N_AMD +TRP CE2 C_CAR +TRP CE3 C_CAR +TRP CZ2 C_CAR +TRP CZ3 C_CAR +TRP CH2 C_CAR + +TYR CG C_CAR +TYR CD1 C_CAR +TYR CD2 C_CAR +TYR CE1 C_CAR +TYR CE2 C_CAR +TYR CZ C_CAR +TYR OH O + +VAL CG1 C_ALI +VAL CG2 C_ALI + +# Modified aa + +ALY CG C_ALI +ALY CD C_ALI +ALY CE C_ALI +ALY NZ N_AMN + +ASH CG C_CAR +ASH OD1 O +ASH OD2 O + +CYM SG S + +CSP SG S + +CYF SG S + +CYC SG S + +CFE SG S + +DDZ CB C_ALI + +GLH CG C_ALI +GLH CD C_CAR +GLH OE1 O +GLH OE2 O + +HYP CG C_ALI +HYP CD C_ALI + +MLZ CG C_ALI +MLZ CD C_ALI +MLZ CE C_ALI +MLZ NZ N_AMN + +MLY CG C_ALI +MLY CD C_ALI +MLY CE C_ALI +MLY NZ N_AMN + +M3L CG C_ALI +M3L CD C_ALI +M3L CE C_ALI +M3L NZ N_AMN + +NEP CG C_CAR +NEP ND1 N_AMD +NEP CD2 C_CAR +NEP NE2 N_AMD +NEP CE1 C_CAR + +PTR CG C_CAR +PTR CD1 C_CAR +PTR CD2 C_CAR +PTR CE1 C_CAR +PTR CE2 C_CAR +PTR CZ C_CAR +PTR OH O + +SEP OG O + +TOP OG1 O +TOP CG2 C_ALI + +TYP CG C_CAR +TYP CD1 C_CAR +TYP CD2 C_CAR +TYP CE1 C_CAR +TYP CE2 C_CAR +TYP CZ C_CAR +TYP OH O + +TYS CG C_CAR +TYS CD1 C_CAR +TYS CD2 C_CAR +TYS CE1 C_CAR +TYS CE2 C_CAR +TYS CZ C_CAR +TYS OH O + +PNS OG O +PNS O1P O +PNS O2P O +PNS O3P O +PNS O33 O +PNS O35 O +PNS O40 O +PNS S44 S + +PNS N36 N_AMD +PNS N41 N_AMD +PNS C32 C_CAR +PNS C34 C_CAR +PNS C39 C_CAR +PNS C28 C_ALI +PNS C29 C_ALI +PNS C30 C_ALI +PNS C31 C_ALI +PNS C37 C_ALI +PNS C38 C_ALI +PNS C42 C_ALI +PNS C43 C_ALI + +# Nucleic acids + +A N9 N_NUC +A C8 C_NUC +A N7 N_NUC +A C5 C_NUC +A C6 C_NUC +A N6 N_NUC +A N1 N_NUC +A C2 C_NUC +A N3 N_NUC +A C4 C_NUC + +C N1 N_NUC +C C2 C_NUC +C O2 O +C N3 N_NUC +C C4 C_NUC +C N4 N_NUC +C C5 C_NUC +C C6 C_NUC + +G N9 N_NUC +G C8 C_NUC +G N7 N_NUC +G C5 C_NUC +G C6 C_NUC +G O6 O +G N1 N_NUC +G C2 C_NUC +G N2 N_NUC +G N3 N_NUC +G C4 C_NUC + +I N9 N_NUC +I C8 C_NUC +I N7 N_NUC +I C5 C_NUC +I C6 C_NUC +I O6 O +I N1 N_NUC +I C2 C_NUC +I N3 N_NUC +I C4 C_NUC + +T N1 N_NUC +T C2 C_NUC +T O2 O +T N3 N_NUC +T C4 C_NUC +T O4 O +T C5 C_NUC +T C7 C_NUC +T C6 C_NUC + +U N1 N_NUC +U C2 C_NUC +U O2 O +U N3 N_NUC +U C4 C_NUC +U O4 O +U C5 C_NUC +U C6 C_NUC + +DA N9 N_NUC +DA C8 C_NUC +DA N7 N_NUC +DA C5 C_NUC +DA C6 C_NUC +DA N6 N_NUC +DA N1 N_NUC +DA C2 C_NUC +DA N3 N_NUC +DA C4 C_NUC + +DC N1 N_NUC +DC C2 C_NUC +DC O2 O +DC N3 N_NUC +DC C4 C_NUC +DC N4 N_NUC +DC C5 C_NUC +DC C6 C_NUC + +DG N9 N_NUC +DG C8 C_NUC +DG N7 N_NUC +DG C5 C_NUC +DG C6 C_NUC +DG O6 O +DG N1 N_NUC +DG C2 C_NUC +DG N2 N_NUC +DG N3 N_NUC +DG C4 C_NUC + +DI N9 N_NUC +DI C8 C_NUC +DI N7 N_NUC +DI C5 C_NUC +DI C6 C_NUC +DI O6 O +DI N1 N_NUC +DI C2 C_NUC +DI N3 N_NUC +DI C4 C_NUC + +DT N1 N_NUC +DT C2 C_NUC +DT O2 O +DT N3 N_NUC +DT C4 C_NUC +DT O4 O +DT C5 C_NUC +DT C7 C_NUC +DT C6 C_NUC + +DU N1 N_NUC +DU C2 C_NUC +DU O2 O +DU N3 N_NUC +DU C4 C_NUC +DU O4 O +DU C5 C_NUC +DU C6 C_NUC + +ADE N9 N_NUC +ADE C8 C_NUC +ADE N7 N_NUC +ADE C5 C_NUC +ADE C6 C_NUC +ADE N6 N_NUC +ADE N1 N_NUC +ADE C2 C_NUC +ADE N3 N_NUC +ADE C4 C_NUC + +CYT N1 N_NUC +CYT C2 C_NUC +CYT O2 O +CYT N3 N_NUC +CYT C4 C_NUC +CYT N4 N_NUC +CYT C5 C_NUC +CYT C6 C_NUC + +GUA N9 N_NUC +GUA C8 C_NUC +GUA N7 N_NUC +GUA C5 C_NUC +GUA C6 C_NUC +GUA O6 O +GUA N1 N_NUC +GUA C2 C_NUC +GUA N2 N_NUC +GUA N3 N_NUC +GUA C4 C_NUC + +THY N1 N_NUC +THY C2 C_NUC +THY O2 O +THY N3 N_NUC +THY C4 C_NUC +THY O4 O +THY C5 C_NUC +THY C7 C_NUC +THY C6 C_NUC + +URA N1 N_NUC +URA C2 C_NUC +URA O2 O +URA N3 N_NUC +URA C4 C_NUC +URA O4 O +URA C5 C_NUC +URA C6 C_NUC + diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/passive_from_active.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/passive_from_active.py new file mode 100644 index 0000000000000000000000000000000000000000..8a1a3c397fcb760d5588bc2663e0508494499605 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/passive_from_active.py @@ -0,0 +1,76 @@ +"""haddock3-restraints passive_from_active subcommand. + +Given a list of active_residues and a PDB structure, it will return a list of +surface exposed passive residues within a 6.5A radius (by default) from the active residues. + +When provided with a list of surface residues, it will filter the list for those +that are within the radius (6.5A by default) from the active residues. + +Usage: + haddock3-restraints passive_from_active [-c ] [-s ] [-r ] +""" + +import sys + +from haddock.libs.librestraints import passive_from_active_raw + + +def add_pass_from_act_arguments(pass_from_act_subcommand): + """Add arguments to the pass_from_act subcommand.""" + pass_from_act_subcommand.add_argument( + "structure", + type=str, + help="input PDB structure.", + ) + + pass_from_act_subcommand.add_argument( + "active_list", + help="List of active residues IDs (int) separated by commas", + type=str, + ) + + pass_from_act_subcommand.add_argument( + "-c", + "--chain-id", + help="Chain id to be used in the PDB file (default: All)", + required=False, + ) + + pass_from_act_subcommand.add_argument( + "-s", + "--surface-list", + help="List of surface residues IDs (int) separated by commas", + required=False, + type=str, + ) + + pass_from_act_subcommand.add_argument( + "-r", + "--radius", + help="Radius to consider for the passive residues (default: 6.5A)", + required=False, + type=float, + default=6.5, + ) + + return pass_from_act_subcommand + + +def passive_from_active(structure, active_list, chain_id=None, surface_list="", radius=6.5): + """Get the passive residues.""" + + active = [int(res) for res in active_list.split(',')] + surface = [] + if surface_list: + surface = [int(res) for res in surface_list.split(',')] + + try: + passive = passive_from_active_raw( + structure, active, chain_id, surface, radius + ) + except Exception as e: + print(e) + sys.exit(1) + + print(' '.join([str(r) for r in passive])) + return diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/random_removal.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/random_removal.py new file mode 100644 index 0000000000000000000000000000000000000000..de7476c9f0401b737c1c2f5e13c5f27833ba47a5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/random_removal.py @@ -0,0 +1,171 @@ +"""haddock3-restraints random_removal subcommand. + +Given an input ambiguous file (.tbl), this subcommand will generate an archive +containing multiple tbl files, each containing a subset of the initial ones. + +The subset is tuned by the optional argument --ratio (-r) +The number of generated files in the archive is tuned by the argument --nb-tbl (-n) +The random seed can be tuned using --seed (-s), for reproducibility issues + +Usage: + haddock3-restraints random_removal [-r ] [-n ] [-s ] + +positional arguments: + tblfile input tbl restraint file. + +options: + -h, --help show this help message and exit + -r RATIO, --ratio RATIO + Ratio of restraints to be randomly removed. + -s SEED, --seed SEED Pseudo-random seed. + -n NB_TBL, --nb-tbl NB_TBL + Number of ambiguous files to generate in the archive. +""" + +import os +import sys +import tarfile +from io import BytesIO +from pathlib import Path + +from haddock.core.typing import Union +from haddock.libs.librestraints import get_restraint_subset + + +def add_rand_removal_arguments(rand_removal_subcommand): + """Add arguments to the random removal subcommand.""" + rand_removal_subcommand.add_argument( + "tblfile", + type=str, + help="input tbl restraint file.", + ) + + rand_removal_subcommand.add_argument( + "-r", + "--ratio", + help="Ratio of restraints to be randomly removed. (default: %(default)s)", + required=False, + default=0.5, + type=float, + ) + + rand_removal_subcommand.add_argument( + "-s", + "--seed", + help="Pseudo-random seed. (default: %(default)s)", + required=False, + default=917, # Same as the one in various modules (iniseed) + type=int, + ) + + rand_removal_subcommand.add_argument( + "-n", + "--nb-tbl", + help="Number of ambiguous files to generate in the archive. (default: %(default)s)", + required=False, + type=int, + default=10, + ) + + return rand_removal_subcommand + + +def random_removal( + tblfile: Union[str, Path], + ratio: float, + nb_tbl: int = 10, + seed: int = 917, + ) -> Path: + """Generate an archive containing the randomly removed restraints. + + Parameters + ---------- + tblfile : Union[str, Path] + Path the the input ambiguous file + ratio : float + Ration of restraints to be removed + nb_tbl : int, optional + Number of ambig files to generate in the archive, by default 10 + seed : int, optional + Initial random seed, by default 917 + + Returns + ------- + Union[str, Path] + Path to the generated archive containing `nb_tbl` restraints in it. + """ + if nb_tbl < 1: + sys.exit( + "Number of restraints files to generate must be " + f">= 1 (now set to {nb_tbl})" + ) + # Initiate the tbl archive holding all the restraints + tbl_archive_fpath = Path( + Path(tblfile).parent.resolve(), + Path(tblfile).name + ".tgz", + ) + tbl_archive = tarfile.open(tbl_archive_fpath, "w:gz") + + # Initiate restraints subset generator + try: + subsets_restraints = get_restraint_subset( + tblfile, + ratio, + seed=seed, + ) + except ValueError as e: + sys.exit(e) + + # Loop over number of tbl file to generate + for i in range(1, nb_tbl + 1): + # Obtain a subset of restraints + subset_restraints = next(subsets_restraints) + # Combine them to a string containing the restraints + subset_restraints_str = os.linesep.join(subset_restraints) + # Create tarinfo object + tarinfo = tarfile.TarInfo(f"{Path(tblfile).stem}_rr{i}.tbl") + tarinfo.size = len(subset_restraints_str) + # Add this file to the archive + tbl_archive.addfile( + tarinfo, + BytesIO(subset_restraints_str.encode("utf-8")), + ) + # Closing things + tbl_archive.close() + subsets_restraints.close() + # Return the generated archive path + return tbl_archive_fpath + + +def main( + tblfile: Union[str, Path], + ratio: float, + nb_tbl: int = 10, + seed: int = 917, + ) -> None: + """Simple wrapper of the random_removal function. + + Parameters + ---------- + tblfile : Union[str, Path] + Path the the input ambiguous file + ratio : float + Ration of restraints to be removed + nb_tbl : int, optional + Number of ambig files to generate in the archive, by default 10 + seed : int, optional + Initial random seed, by default 917 + + Returns + ------- + Union[str, Path] + Path to the generated archive containing `nb_tbl` restraints in it. + """ + archive_fpath = random_removal(tblfile, ratio, nb_tbl=nb_tbl, seed=seed) + print( + f"Generated archive path: {archive_fpath}!{os.linesep}" + f"Note that resulting restraints might be redundant{os.linesep}" + f"By using this file, we suggest to:{os.linesep}" + f"- turn off random removal (random_removal = false){os.linesep}" + "- turn on the previous ambig in later stages (previous_ambig = true)" + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/restrain_bodies.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/restrain_bodies.py new file mode 100644 index 0000000000000000000000000000000000000000..81804edc9272464e020cdeb12fc0c9b107c798d7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/restrain_bodies.py @@ -0,0 +1,72 @@ +"""haddock3-restraints restrain_bodies subcommand. + +The restrain_bodies subcommand creates distance restraints to lock several +chains together. Useful to avoid unnatural flexibility or movement due to +sequence/numbering gaps. + +Usage:: + + haddock3-restraints restrain_bodies [--exclude] [--verbose] +""" + +import logging +import sys +import random + +from haddock.libs.librestraints import read_structure, get_bodies, build_restraints, generate_tbl + +# Set random seed to have reproducibility +random.seed(917) + +def add_restrain_bodies_arguments(restraint_bodies_subcommand): + restraint_bodies_subcommand.add_argument( + "structure", + help="The PDB structure to be restrained.", + ) + + restraint_bodies_subcommand.add_argument( + "-e", + "--exclude", + help="Chains to exclude from the calculation.", + required=False, + type=str, + ) + + restraint_bodies_subcommand.add_argument( + "-v", + "--verbose", + help="Tune verbosity of the output.", + required=False, + default=0, + type=int, + ) + + restraint_bodies_subcommand + + +def restrain_bodies(structure, exclude=None, verbose=0): # noqa: E501 + """Create distance restraints to lock several chains together. + + Parameters + ---------- + structure : str + The PDB structure to be restrained. + + exclude : str + Chains to exclude from the calculation. + + verbose : int + Tune verbosity of the output. + """ + if verbose== 1: + logging.basicConfig(level=logging.INFO) + elif verbose > 1: + logging.basicConfig(level=logging.DEBUG) + else: + logging.basicConfig(level=logging.WARNING) + + # Main logic + atom_lst = read_structure(structure, exclude=exclude) + bodies = get_bodies(atom_lst) + restraints = build_restraints(bodies) + generate_tbl(atom_lst, restraints) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/restrain_ligand.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/restrain_ligand.py new file mode 100644 index 0000000000000000000000000000000000000000..010df7ed62ac6ba385a0af7df32310cbb59a2c60 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/restrain_ligand.py @@ -0,0 +1,223 @@ +"""haddock3-restraints restrain_ligand subcommand. + +Given an input PDB file and a residue name (ligands), the tool will create +unambiguous restraints to keep this ligand in place during the refinements. + + +Usage: + haddock3-restraints restrain_ligand -r -d -n + +positional arguments: + pdb_file Input PDB file. + ligand_name Residue name. + +options: + -h, --help show this help message and exit + -r RADIUS, --radius RADIUS + Radius used for neighbors search around center of mass of ligand. + (default: 10.0) + -n MAX_RESTRAINTS, --max-restraints MAX_RESTRAINTS + Maximum number of restraints to return. (default: 200) + -d DEVIATION, --deviation DEVIATION + Allowed deviation from actual distance. (default: 1.0) +""" + +import os +import sys +import random +from pathlib import Path + +import numpy as np +from Bio.PDB import PDBParser +from Bio.PDB import NeighborSearch + +from haddock.core.typing import Union + + +def add_restrain_ligand_arguments(restrain_ligand_subcommand): + """Add arguments to the random removal subcommand.""" + restrain_ligand_subcommand.add_argument( + "pdb_file", + type=str, + help="Input PDB file.", + ) + restrain_ligand_subcommand.add_argument( + "ligand_name", + type=str, + help="Name of the residue for which restraints must be generated.", + ) + restrain_ligand_subcommand.add_argument( + "-r", + "--radius", + help=( + "Radius, in Angstrom, used for neighbors search around " + "center of mass of ligand. (default: %(default)s)" + ), + required=False, + default=10.0, + type=float, + ) + restrain_ligand_subcommand.add_argument( + "-d", + "--deviation", + help=( + "Allowed deviation from actual distance, in Angstrom. " + "(default: %(default)s)" + ), + required=False, + default=1.0, + type=float, + ) + restrain_ligand_subcommand.add_argument( + "-n", + "--max-restraints", + help="Maximum number of restraints to return. (default: %(default)s)", + required=False, + default=200, + type=int, + ) + return restrain_ligand_subcommand + + +def restrain_ligand( + pdbfile: Union[str, Path], + ligand_name: str, + radius: float = 10.0, + deviation: float = 1.0, + max_restraints: int = 20, + ) -> str: + """Generate unambiguous restraints to keep a ligand in place. + + Parameters + ---------- + pdbfile : Union[str, Path] + Path to a PDB file containing a ligand + ligand_name : str + Residue name of the ligand to work with + radius : float, optional + Radius used for neighbors search around center of mass of ligand, by default 10.0 + deviation : float, optional + Allowed deviation from actual distance, by default 1.0 + max_restraints : int, optional + Maximum number of restraints to return, by default 20 + + Returns + ------- + unambig_str : str + The actual unambiguous restraints as a string. + """ + # Read in structure + pdb_parser = PDBParser(QUIET=1) + structure = pdb_parser.get_structure("", pdbfile) + + # Remove hydrogens + for atom in structure.get_atoms(): + if atom.element == "H": + res = atom.parent + res.detach_child(atom.name) + + # Try to find the ligand in the structure + ligand = None + for residue in structure.get_residues(): + if residue.resname.strip() == ligand_name.strip(): + ligand = residue + break + # Case where the ligand is not found in the structure + if not ligand: + print(f"[!!] Ligand residue '{ligand_name}' not found in structure") + sys.exit(1) + + # Calculate center of mass of the ligand + ligand_com = list(map(lambda x: sum(x)/len(x), zip(*[at.coord for at in ligand]))) + ligand_com = np.asarray(ligand_com, dtype=np.float32) + + # Create a selection of aminoacid/nucleotide atoms + # (excl. waters, other ligands, etc) + # also filters atoms that are from the queried ligand + sel_atoms = [ + at for at in structure.get_atoms() + if at.parent.id[0] == ' ' and at.parent != ligand + ] + # Perfom neighbor search on this selection + ns = NeighborSearch(sel_atoms) + neighbors = ns.search(ligand_com, radius, level="R") # 10A radius, return residues + + # Calculate residue closer to each ligand atom and the respective distance + ligand_atoms = ligand.child_list + min_dist_list, _seen = [], set() + + # Loop over ligand atoms + for l_atm in ligand_atoms: + distances = [] + # Loop over neighbors residues and atoms + for residue_atoms in neighbors: + for r_atm in residue_atoms: + # Compute distance and hold it + distances.append((r_atm, l_atm, r_atm - l_atm)) + # Sort list by distances + distances.sort(key=lambda x: x[-1]) + # Loop over sorted distances + for closest_candidate in distances: + candidate_residue = closest_candidate[0].parent + # One restraint per residue to keep the number of restraints small + # If a residue is already used, take next one + if candidate_residue not in _seen: + min_dist_list.append(closest_candidate) + _seen.add(candidate_residue) + break + + # Output + assign_str_template = ( + "assign (segi {receptor_chainid:4s} and resi {receptor_resid:4d} " + "and name {receptor_atname:6s}){linesep:s}" + " (segi {ligand_chainid:4s} and resi {ligand_resid:4d} " + "and name {ligand_atname:6s}) " + "{distance:6.3f} {deviation:.2f} {deviation:.2f}{linesep:s}" + ) + + _unambig_str_list: list[str] = [] + # Loop over all min distances + for dist in min_dist_list: + r_at, l_at, d = dist + # Build assign statement + assign_str = assign_str_template.format( + receptor_chainid=r_at.parent.parent.id, + receptor_resid=r_at.parent.id[1], + receptor_atname='"' + r_at.name + '"', + ligand_chainid=l_at.parent.parent.id, + ligand_resid=l_at.parent.id[1], + ligand_atname='"' + l_at.name + '"', + distance=d, + deviation=deviation, + linesep=os.linesep, + ) + _unambig_str_list.append(assign_str) + + # Limit the number of restraints + if max_restraints < len(_unambig_str_list): + random.seed(420) + unambig_str_list = random.sample(_unambig_str_list, max_restraints) + else: + unambig_str_list = _unambig_str_list + + # Concatenate into a single string + unambig_str = f"! Restraints to fix {ligand_name} in its initial position{os.linesep}" + unambig_str += "".join(unambig_str_list) + return unambig_str + + +def main( + pdb_file: Union[str, Path], + ligand_name: str, + radius: float = 10.0, + deviation: float = 1.0, + max_restraints: int = 20, + ) -> None: + """Simple wrapper of the restrain_ligand function.""" + unambig_str = restrain_ligand( + pdb_file, ligand_name, + radius=radius, + deviation=deviation, + max_restraints=max_restraints, + ) + print(unambig_str) diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/validate_tbl.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/validate_tbl.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ec55b33e2ffaa4bd39e2c4c8eb77af86eae843 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/validate_tbl.py @@ -0,0 +1,58 @@ +"""haddock3-restraints validate_tbl subcommand. + +The validate_tbl subcommand validates an input TBL file. + +Usage: + haddock3-restraints validate_tbl [--silent] [--quick] +""" +from pathlib import Path +from haddock.libs.librestraints import check_parenthesis, validate_tbldata + +def add_validate_tbl_arguments(validate_tbl_subcommand): + """Add arguments to the score subcommand.""" + validate_tbl_subcommand.add_argument( + "tbl_file", + type=str, + help="TBL file to be validated", + ) + + validate_tbl_subcommand.add_argument( + "--pcs", + help="PCS mode", + action='store_true', + ) + + validate_tbl_subcommand.add_argument( + "--quick", + help="Check global formatting before going line by line " + "(opening/closing parenthesis and quotation marks", + action='store_true', + ) + + validate_tbl_subcommand.add_argument( + "--silent", + help="Only output errors, do not output TBL file at the end", + action='store_true', + ) + + return validate_tbl_subcommand + + +def validate_tbl(tbl_file, pcs, quick=False, silent=False): + """Get the passive residues.""" + if quick: + tbldata = open(tbl_file).read() + # Check the parenthesis and quotation marks opening/closure + check_parenthesis(tbldata) + + if Path(tbl_file).exists(): + tbldata = open(tbl_file).read() + # Parse and process the restraints + if silent: + validate_tbldata(tbldata, pcs) + else: + print(validate_tbldata(tbldata, pcs)) + else: + raise Exception(f"TBL file {tbl_file} does not exist, check the path") + + return diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/webservice.py b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/webservice.py new file mode 100644 index 0000000000000000000000000000000000000000..8d778bab0d56a1399dff3d0dd7797ab2385a95c0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/clis/restraints/webservice.py @@ -0,0 +1,300 @@ +"""Webservice for the haddock3 restraints module. + +Exposes the haddock3-restraints CLI subcommands as a RESTful webservice. +Also includes endpoint for PDB preprocessing. + +Run with: + +```shell +uvicorn --port 5000 haddock.clis.restraints.webservice:app +``` + +The Swagger UI is running at http://127.0.0.1:5000/docs . + +To pass a PDB file in the JSON body of a request, +it needs to be gzipped and then base64 encoded. + +A base64 encoded gzipped PDB file can made with: + +```shell +cat examples/data/2oob.pdb | gzip | base64 -w 0 > 2oob.pdb.gz.base64 +``` + +Background for PDB file handling: + +To store a multiline string, like a pdb file, +in JSON we need to encode it in base64. +Base64 encoding make things 1.33 times bigger. +A pdb is text which can be compressed a lot. +To transfer less data we can compress the pdb +with gzip before base64 encoding. +For example the 2oob.pdb 74.8Kb becomes 101Kb when base64 encoded +while first gzip and then base64 encode it is 25.4Kb. +""" + +import gzip +import io +import tempfile +from base64 import b64decode +from contextlib import redirect_stdout +from typing import Annotated + +from fastapi import FastAPI, HTTPException, status +from fastapi.middleware.gzip import GZipMiddleware +from pdbtools.pdb_chain import alter_chain +from pdbtools.pdb_fixinsert import fix_insertions +from pdbtools.pdb_selaltloc import select_by_occupancy +from pdbtools.pdb_selchain import select_chain +from pdbtools.pdb_tidy import tidy_pdbfile +from pdbtools.pdb_delhetatm import remove_hetatm +from pdbtools.pdb_keepcoord import keep_coordinates +from pydantic import BaseModel, Field +from starlette.responses import PlainTextResponse + +from haddock.clis.restraints.calc_accessibility import ( + apply_cutoff, + get_accessibility, +) +from haddock.clis.restraints.restrain_bodies import ( + restrain_bodies as restrain_bodies_raw, +) +from haddock.libs.librestraints import ( + active_passive_to_ambig, + check_parenthesis, + passive_from_active_raw, + validate_tbldata, +) + + +app = FastAPI() +app.add_middleware(GZipMiddleware, minimum_size=1000) + + +def unpacked_structure( + structure: str, +) -> bytes: + """Gunzips a base64 encoded string.""" + decoded = b64decode(structure) + return gzip.decompress(decoded) + + +def unpacked_tbl(tbl: str) -> str: + """Gunzips a base64 encoded tbl file contents.""" + return gzip.decompress(b64decode(tbl)).decode("utf-8") + + +Structure = Annotated[ + str, + Field( + description="The structure file as a base64 encoded gzipped string.", + json_schema_extra=dict( + contentMediaType="text/plain", + contentEncoding="base64", + ) + ), +] + + +class PassiveFromActiveRequest(BaseModel): + structure: Structure + active: list[int] = Field( + description="List of active restraints.", examples=[[1, 2, 3]] + ) + chain: str = Field(default="A", description="The chain identifier.") + surface: list[int] = Field(default=[], description="List of surface restraints.") + radius: float = Field(default=6.5, description="The radius from active.") + + +@app.post("/passive_from_active", tags=["restraints"]) +def calculate_passive_from_active( + request: PassiveFromActiveRequest, +) -> list[int]: + """Calculate active restraints to passive restraints.""" + structure = unpacked_structure(request.structure) + + with tempfile.NamedTemporaryFile() as structure_file: + structure_file.write(structure) + + try: + passive = passive_from_active_raw( + structure=structure_file.name, + active=request.active, + chain_id=request.chain, + surface=request.surface, + radius=request.radius, + ) + return passive + except Exception as e: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e) + ) from e + + +class ActPassToAmbigRequest(BaseModel): + active1: list[int] = Field( + description="List of active residues for the first model.", examples=[[1, 2, 3]] + ) + active2: list[int] = Field( + description="List of active residues for the second model.", + examples=[[4, 5, 6]], + ) + passive1: list[int] = Field( + description="List of passive residues for the first model.", + examples=[[7, 8, 9]], + ) + passive2: list[int] = Field( + description="List of passive residues for the second model.", + examples=[[10, 11, 12]], + ) + segid1: str = Field(default="A", description="Segid to use for the first model.") + segid2: str = Field(default="B", description="Segid to use for the second model.") + + +@app.post("/actpass_to_ambig", response_class=PlainTextResponse, tags=["restraints"]) +def calculate_actpass_to_ambig( + request: ActPassToAmbigRequest, +) -> str: + """Get the passive residues.""" + output = io.StringIO() + with redirect_stdout(output): + active_passive_to_ambig( + active1=request.active1, + passive1=request.passive1, + active2=request.active2, + passive2=request.passive2, + segid1=request.segid1, + segid2=request.segid2, + ) + ambig = output.getvalue() + return ambig.strip() + + +class RestrainBodiesRequest(BaseModel): + structure: Structure + exclude: list[str] = Field( + default=[], + description="Chains to exclude from the calculation.", + examples=[["B"]], + ) + + +@app.post("/restrain_bodies", response_class=PlainTextResponse, tags=["restraints"]) +def restrain_bodies(request: RestrainBodiesRequest) -> str: + """Create distance restraints to lock several chains together.""" + structure = unpacked_structure(request.structure) + with tempfile.NamedTemporaryFile() as structure_file: + structure_file.write(structure) + + output = io.StringIO() + with redirect_stdout(output): + restrain_bodies_raw( + structure=structure_file.name, + exclude=request.exclude, + ) + tbl = output.getvalue() + return tbl.strip() + + +class CalcAccessibilityRequest(BaseModel): + structure: Structure + cutoff: float = Field( + description="Relative cutoff for sidechain accessibility.", examples=[0.4] + ) + + +@app.post("/calc_accessibility", tags=["restraints"]) +def calculate_accessibility( + request: CalcAccessibilityRequest, +) -> dict[str, list[int]]: + """Calculate the accessibility of the side chains and apply a cutoff.""" + structure = unpacked_structure(request.structure) + + with tempfile.NamedTemporaryFile() as structure_file: + structure_file.write(structure) + + try: + access_dic = get_accessibility(structure_file.name) + # Filter residues based on accessibility cutoff + result_dict = apply_cutoff(access_dic, request.cutoff) + return result_dict + except AssertionError as e: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e) + ) from e + + +class ValidateTblRequest(BaseModel): + tbl: Annotated[ + str, + Field( + description="The TBL file as base64 encoded gzipped string.", + json_schema_extra=dict( + contentMediaType="text/plain", + contentEncoding="base64", + ) + ), + ] + pcs: bool = Field( + default=False, + description="Flag to indicate if the TBL file is in PCS mode.", + ) + quick: bool = Field( + default=False, + description="Check global formatting before going line by line (opening/closing parenthesis and quotation marks.", + ) + + +@app.post("/validate_tbl", response_class=PlainTextResponse, tags=["restraints"]) +def validate_tbl( + request: ValidateTblRequest, +) -> str: + tbl = unpacked_tbl(request.tbl) + try: + if request.quick: + check_parenthesis(tbl) + return validate_tbldata(tbl, request.pcs) + except Exception as e: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e) + ) from e + + +class PDBPreprocessRequest(BaseModel): + structure: Structure + from_chain: str = Field(description="Chains to keep", examples=["A"]) + to_chain: str = Field(description="New chain identifier", examples=["A"]) + delhetatm: bool = Field(description="Delete HETATM records", examples=[True], default=False) + keepcoord: bool = Field(description="Remove all non-coordinate records", examples=[True], default=False) + + +@app.post("/preprocess_pdb", response_class=PlainTextResponse, tags=["pdb"]) +def preprocess_pdb(request: PDBPreprocessRequest) -> str: + """Preprocess a PDB file. + + Runs the following [pdbtools](http://www.bonvinlab.org/pdb-tools/) pipeline: + + ```shell + cat pdb | pdb_tidy -strict | pdb_selchain - | pdb_chain - | pdb_fixinsert | pdb_selaltloc | pdb_tidy -strict + ``` + + or with `delhetatm` and `keepcoord` set to true: + + ```shell + cat pdb | pdb_tidy -strict | pdb_selchain - | pdb_chain - | pdb_delhetatm | \ + pdb_fixinsert | pdb_keepcoord | pdb_selaltloc | pdb_tidy -strict + ``` + + """ + structure = unpacked_structure(request.structure).decode("latin_1") + lines = structure.splitlines() + lines = list(tidy_pdbfile(lines, strict=True)) + lines = list(select_chain(lines, request.from_chain)) + lines = list(alter_chain(lines, request.to_chain)) + if request.delhetatm: + lines = list(remove_hetatm(lines)) + lines = list(fix_insertions(lines, [])) + if request.keepcoord: + lines = list(keep_coordinates(lines)) + lines = list(select_by_occupancy(lines)) + lines = list(tidy_pdbfile(lines, strict=True)) + return "".join(lines)