diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_130501.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_130501.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a3c640c149010892b4bdb3038f276835190148bd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_130501.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_140101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_140101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..45708154c914a94e723ada0d5b6db79110ba4aeb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_140101.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_150101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_150101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..7c0933d2be2d8e28d5814e6c0f7cd24ebeaa4423 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_150101.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..48bec8a8b5a85626a56381294aedafa2288f3f2b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180101.dtd @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180601.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180601.dtd new file mode 100644 index 0000000000000000000000000000000000000000..aab61e779e296c4cff9f229bfc14e479132816a5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180601.dtd @@ -0,0 +1,454 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_190101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_190101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a1cd16776c0a0c23b8b50ae9eff6940302a98512 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_190101.dtd @@ -0,0 +1,478 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_230101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_230101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fb1354e94eb04db2913eb71ba48cb4f301630c64 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_230101.dtd @@ -0,0 +1,468 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_240101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_240101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..72682c6cb31aace443100fa9f0a14dff000801df --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_240101.dtd @@ -0,0 +1,477 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_250101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_250101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..31926f63d0e33e4964a25dd3610aca9dd0911e89 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_250101.dtd @@ -0,0 +1,475 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/references.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/references.ent new file mode 100644 index 0000000000000000000000000000000000000000..591cb9f11bf5531c24b5107db0815b210ef19f6b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/references.ent @@ -0,0 +1,726 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/section.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/section.ent new file mode 100644 index 0000000000000000000000000000000000000000..17d0128f85eddffbfde191eeab6e2fd959e3ac44 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/section.ent @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/taxon.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/taxon.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fadf481bcbdff9d63e44abf97d7b0deb5c777ce8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/taxon.dtd @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-inlstyle-1.mod b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-inlstyle-1.mod new file mode 100644 index 0000000000000000000000000000000000000000..79accd45d273afba190c3a7ea897f28c91e3d063 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-inlstyle-1.mod @@ -0,0 +1,34 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-table-1.mod b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-table-1.mod new file mode 100644 index 0000000000000000000000000000000000000000..2b8eeef3aa12706c7f47a03981afc8730cf4dc8c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-table-1.mod @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]> + + + +]]> + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + +]]> + + + +]]> + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xmlspecchars.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xmlspecchars.ent new file mode 100644 index 0000000000000000000000000000000000000000..bb15ade7dfe8ccad08487e65d6a1dfd882a24748 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xmlspecchars.ent @@ -0,0 +1,290 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%ISOlat1; +%ISOlat2; +%ISObox; +%ISOdia; +%ISOnum; +%ISOpub; +%ISOtech; +%ISOgrk1; +%ISOgrk2; +%ISOgrk3; +%ISOgrk4; +%ISOcyr1; +%ISOcyr2; +%ISOamsa; +%ISOamsb; +%ISOamsc; +%ISOamsn; +%ISOamso; +%ISOamsr; +%ISOmscr; +%ISOmfrk; +%ISOmopf; + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/Parser.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/Parser.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7bab984d8fa858f8cd9638d66fd73c9a714ca1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/Parser.py @@ -0,0 +1,1165 @@ +# Copyright 2008-2014 by Michiel de Hoon. All rights reserved. +# Revisions 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. + +"""Parser for XML results returned by NCBI's Entrez Utilities. + +This parser is used by the read() function in Bio.Entrez, and is not +intended be used directly. + +The question is how to represent an XML file as Python objects. Some +XML files returned by NCBI look like lists, others look like dictionaries, +and others look like a mix of lists and dictionaries. + +My approach is to classify each possible element in the XML as a plain +string, an integer, a list, a dictionary, or a structure. The latter is a +dictionary where the same key can occur multiple times; in Python, it is +represented as a dictionary where that key occurs once, pointing to a list +of values found in the XML file. + +The parser then goes through the XML and creates the appropriate Python +object for each element. The different levels encountered in the XML are +preserved on the Python side. So a subelement of a subelement of an element +is a value in a dictionary that is stored in a list which is a value in +some other dictionary (or a value in a list which itself belongs to a list +which is a value in a dictionary, and so on). Attributes encountered in +the XML are stored as a dictionary in a member .attributes of each element, +and the tag name is saved in a member .tag. + +To decide which kind of Python object corresponds to each element in the +XML, the parser analyzes the DTD referred at the top of (almost) every +XML file returned by the Entrez Utilities. This is preferred over a hand- +written solution, since the number of DTDs is rather large and their +contents may change over time. About half the code in this parser deals +with parsing the DTD, and the other half with the XML itself. +""" + +import os +import warnings +import xml.etree.ElementTree as ET +from collections import Counter +from io import BytesIO +from urllib.parse import urlparse +from urllib.request import urlopen +from xml.parsers import expat +from xml.sax.saxutils import escape + +from Bio import StreamModeError + +# The following four classes are used to add a member .attributes to integers, +# strings, lists, and dictionaries, respectively. + + +class NoneElement: + """NCBI Entrez XML element mapped to None.""" + + def __init__(self, tag, attributes, key): + """Create a NoneElement.""" + self.tag = tag + self.key = key + self.attributes = attributes + + def __repr__(self): + """Return a string representation of the object.""" + try: + attributes = self.attributes + except AttributeError: + return "NoneElement" + return "NoneElement(attributes=%r)" % attributes + + def __eq__(self, other): + if isinstance(other, NoneElement): + return True + return False + + +class IntegerElement(int): + """NCBI Entrez XML element mapped to an integer.""" + + def __new__(cls, value, *args, **kwargs): + """Create an IntegerElement.""" + return int.__new__(cls, value) + + def __init__(self, value, tag, attributes, key): + """Initialize an IntegerElement.""" + self.tag = tag + self.attributes = attributes + self.key = key + + def __repr__(self): + """Return a string representation of the object.""" + text = int.__repr__(self) + try: + attributes = self.attributes + except AttributeError: + return text + return f"IntegerElement({text}, attributes={attributes!r})" + + +class StringElement(str): + """NCBI Entrez XML element mapped to a string.""" + + def __new__(cls, value, *args, **kwargs): + """Create a StringElement.""" + return str.__new__(cls, value) + + def __init__(self, value, tag, attributes, key): + """Initialize a StringElement.""" + self.tag = tag + self.attributes = attributes + self.key = key + + def __repr__(self): + """Return a string representation of the object.""" + text = str.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"StringElement({text}, attributes={attributes!r})" + + +class ListElement(list): + """NCBI Entrez XML element mapped to a list.""" + + def __init__(self, tag, attributes, allowed_tags, key=None): + """Create a ListElement.""" + self.tag = tag + if key is None: + self.key = tag + else: + self.key = key + self.attributes = attributes + self.allowed_tags = allowed_tags + + def __repr__(self): + """Return a string representation of the object.""" + text = list.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"ListElement({text}, attributes={attributes!r})" + + def store(self, value): + """Append an element to the list, checking tags.""" + key = value.key + if self.allowed_tags is not None and key not in self.allowed_tags: + raise ValueError("Unexpected item '%s' in list" % key) + del value.key + self.append(value) + + +class DictionaryElement(dict): + """NCBI Entrez XML element mapped to a dictionaray.""" + + def __init__(self, tag, attrs, allowed_tags, repeated_tags=None, key=None): + """Create a DictionaryElement.""" + self.tag = tag + if key is None: + self.key = tag + else: + self.key = key + self.attributes = attrs + self.allowed_tags = allowed_tags + self.repeated_tags = repeated_tags + if repeated_tags: + for key in repeated_tags: + self[key] = [] + + def __repr__(self): + """Return a string representation of the object.""" + text = dict.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"DictElement({text}, attributes={attributes!r})" + + def store(self, value): + """Add an entry to the dictionary, checking tags.""" + key = value.key + tag = value.tag + if self.allowed_tags is not None and tag not in self.allowed_tags: + raise ValueError("Unexpected item '%s' in dictionary" % key) + del value.key + if self.repeated_tags and key in self.repeated_tags: + self[key].append(value) + else: + self[key] = value + + +class OrderedListElement(list): + """NCBI Entrez XML element mapped to a list of lists. + + OrderedListElement is used to describe a list of repeating elements such as + A, B, C, A, B, C, A, B, C ... where each set of A, B, C forms a group. This + is then stored as [[A, B, C], [A, B, C], [A, B, C], ...] + """ + + def __init__(self, tag, attributes, allowed_tags, first_tag, key=None): + """Create an OrderedListElement.""" + self.tag = tag + if key is None: + self.key = tag + else: + self.key = key + self.attributes = attributes + self.allowed_tags = allowed_tags + self.first_tag = first_tag + + def __repr__(self): + """Return a string representation of the object.""" + text = list.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"OrderedListElement({text}, attributes={attributes!r})" + + def store(self, value): + """Append an element to the list, checking tags.""" + key = value.key + if self.allowed_tags is not None and key not in self.allowed_tags: + raise ValueError("Unexpected item '%s' in list" % key) + if key == self.first_tag: + self.append([]) + self[-1].append(value) + + +class ErrorElement(str): + """NCBI Entrez XML element containing an error message.""" + + def __new__(cls, value, *args, **kwargs): + """Create an ErrorElement.""" + return str.__new__(cls, value) + + def __init__(self, value, tag): + """Initialize an ErrorElement.""" + self.tag = tag + self.key = tag + + def __repr__(self): + """Return the error message as a string.""" + text = str.__repr__(self) + return f"ErrorElement({text})" + + +class NotXMLError(ValueError): + """Failed to parse file as XML.""" + + def __init__(self, message): + """Initialize the class.""" + self.msg = message + + def __str__(self): + """Return a string summary of the exception.""" + return ( + "Failed to parse the XML data (%s). Please make sure that the input data " + "are in XML format." % self.msg + ) + + +class CorruptedXMLError(ValueError): + """Corrupted XML.""" + + def __init__(self, message): + """Initialize the class.""" + self.msg = message + + def __str__(self): + """Return a string summary of the exception.""" + return ( + "Failed to parse the XML data (%s). Please make sure that the input data " + "are not corrupted." % self.msg + ) + + +class ValidationError(ValueError): + """XML tag found which was not defined in the DTD. + + Validating parsers raise this error if the parser finds a tag in the XML + that is not defined in the DTD. Non-validating parsers do not raise this + error. The Bio.Entrez.read and Bio.Entrez.parse functions use validating + parsers by default (see those functions for more information). + """ + + def __init__(self, name): + """Initialize the class.""" + self.name = name + + def __str__(self): + """Return a string summary of the exception.""" + return ( + "Failed to find tag '%s' in the DTD. To skip all tags that " + "are not represented in the DTD, please call Bio.Entrez.read " + "or Bio.Entrez.parse with validate=False." % self.name + ) + + +class DataHandlerMeta(type): + """A metaclass is needed until Python supports @classproperty.""" + + def __init__(cls, *args, **kwargs): + """Initialize the class.""" + from Bio import Entrez + + try: + cls.directory = Entrez.local_cache # use default directory for local cache + except PermissionError: + cls._directory = Entrez.local_cache # no local cache + del Entrez + + @property + def directory(cls): + """Directory for caching XSD and DTD files.""" + return cls._directory + + @directory.setter + def directory(cls, value): + """Set a custom directory for the local DTD/XSD directories.""" + if value is None: + import platform + + if platform.system() == "Windows": + value = os.path.join(os.getenv("APPDATA"), "biopython") + else: # Unix/Linux/Mac + home = os.path.expanduser("~") + value = os.path.join(home, ".config", "biopython") + # Create DTD local directory + cls.local_dtd_dir = os.path.join(value, "Bio", "Entrez", "DTDs") + os.makedirs(cls.local_dtd_dir, exist_ok=True) + # Create XSD local directory + cls.local_xsd_dir = os.path.join(value, "Bio", "Entrez", "XSDs") + os.makedirs(cls.local_xsd_dir, exist_ok=True) + # Save the directory name after creating the DTD and XSD local + # directories to ensure there was no PermissionError. + cls._directory = value + + +class DataHandler(metaclass=DataHandlerMeta): + """Data handler for parsing NCBI XML from Entrez.""" + + from Bio import Entrez + + global_dtd_dir = os.path.join(Entrez.__path__[0], "DTDs") + global_xsd_dir = os.path.join(Entrez.__path__[0], "XSDs") + local_dtd_dir = None + local_xsd_dir = None + + del Entrez + + def __init__(self, validate, escape, ignore_errors): + """Create a DataHandler object.""" + self.dtd_urls = [] + self.element = None + self.level = 0 + self.bypass_url_security = False + self.data = [] + self.attributes = None + self.allowed_tags = None + self.constructors = {} + self.strings = {} + self.items = set() + self.errors = set() + self.validating = validate + self.ignore_errors = ignore_errors + self.parser = expat.ParserCreate(namespace_separator=" ") + self.parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) + self.parser.XmlDeclHandler = self.xmlDeclHandler + self.schema_namespace = None + self.namespace_level = Counter() + self.namespace_prefix = {} + if escape: + self.characterDataHandler = self.characterDataHandlerEscape + else: + self.characterDataHandler = self.characterDataHandlerRaw + + def read(self, source): + """Set up the parser and let it read the XML results.""" + # Expat's parser.ParseFile function only accepts binary data; + # see also the comment below for Entrez.parse. + try: + stream = open(source, "rb") + except TypeError: # not a path, assume we received a stream + if source.read(0) != b"": + raise StreamModeError( + "the XML file must be opened in binary mode." + ) from None + stream = source + if stream.read(0) != b"": + raise TypeError("file should be opened in binary mode") + try: + self.parser.ParseFile(stream) + except expat.ExpatError as e: + if self.parser.StartElementHandler: + # We saw the initial = 2: + # Then the first record is finished, while the second record + # is still a work in progress. + record = records.pop(0) + yield record + + except expat.ExpatError as e: + if self.parser.StartElementHandler: + # We saw the initial " + self.data.append(tag) + self.parser.EndElementHandler = self.endRawElementHandler + self.level += 1 + + def startSkipElementHandler(self, name, attrs): + """Handle start of an XML skip element.""" + self.level += 1 + + def endStringElementHandler(self, tag): + """Handle end of an XML string element.""" + element = self.element + if element is not None: + self.parser.StartElementHandler = self.startElementHandler + self.parser.EndElementHandler = self.endElementHandler + self.parser.CharacterDataHandler = self.skipCharacterDataHandler + data = "".join(self.data) + self.data = [] + attributes = self.attributes + self.attributes = None + if self.namespace_prefix: + try: + uri, name = tag.split() + except ValueError: + pass + else: + prefix = self.namespace_prefix[uri] + tag = f"{prefix}:{name}" + if tag in self.items: + assert tag == "Item" + key = attributes["Name"] + del attributes["Name"] + else: + key = tag + value = StringElement(data, tag, attributes, key) + if element is None: + self.record = element + else: + element.store(value) + self.allowed_tags = None + + def endRawElementHandler(self, name): + """Handle end of an XML raw element.""" + self.level -= 1 + if self.level == 0: + self.parser.EndElementHandler = self.endStringElementHandler + if self.namespace_prefix: + try: + uri, name = name.split() + except ValueError: + pass + tag = "" % name + self.data.append(tag) + + def endSkipElementHandler(self, name): + """Handle end of an XML skip element.""" + self.level -= 1 + if self.level == 0: + self.parser.StartElementHandler = self.startElementHandler + self.parser.EndElementHandler = self.endElementHandler + + def endErrorElementHandler(self, tag): + """Handle end of an XML error element.""" + element = self.element + if element is not None: + self.parser.StartElementHandler = self.startElementHandler + self.parser.EndElementHandler = self.endElementHandler + self.parser.CharacterDataHandler = self.skipCharacterDataHandler + data = "".join(self.data) + if data == "": + return + if self.ignore_errors is False: + raise RuntimeError(data) + self.data = [] + value = ErrorElement(data, tag) + if element is None: + self.record = element + else: + element.store(value) + + def endElementHandler(self, name): + """Handle end of an XML element.""" + element = self.element + self.element = element.parent + del element.parent + + def endIntegerElementHandler(self, tag): + """Handle end of an XML integer element.""" + attributes = self.attributes + self.attributes = None + assert tag == "Item" + key = attributes["Name"] + del attributes["Name"] + if self.data: + value = int("".join(self.data)) + self.data = [] + value = IntegerElement(value, tag, attributes, key) + else: + value = NoneElement(tag, attributes, key) + element = self.element + if element is None: + self.record = value + else: + self.parser.EndElementHandler = self.endElementHandler + self.parser.CharacterDataHandler = self.skipCharacterDataHandler + if value is None: + return + element.store(value) + + def characterDataHandlerRaw(self, content): + """Handle character data as-is (raw).""" + self.data.append(content) + + def characterDataHandlerEscape(self, content): + """Handle character data by encoding it.""" + content = escape(content) + self.data.append(content) + + def skipCharacterDataHandler(self, content): + """Handle character data by skipping it.""" + + def parse_xsd(self, root): + """Parse an XSD file.""" + prefix = "{http://www.w3.org/2001/XMLSchema}" + for element in root: + isSimpleContent = False + attribute_keys = [] + keys = [] + multiple = [] + assert element.tag == prefix + "element" + name = element.attrib["name"] + assert len(element) == 1 + complexType = element[0] + assert complexType.tag == prefix + "complexType" + for component in complexType: + tag = component.tag + if tag == prefix + "attribute": + # we could distinguish by type; keeping string for now + attribute_keys.append(component.attrib["name"]) + elif tag == prefix + "sequence": + maxOccurs = component.attrib.get("maxOccurs", "1") + for key in component: + assert key.tag == prefix + "element" + ref = key.attrib["ref"] + keys.append(ref) + if maxOccurs != "1" or key.attrib.get("maxOccurs", "1") != "1": + multiple.append(ref) + elif tag == prefix + "simpleContent": + assert len(component) == 1 + extension = component[0] + assert extension.tag == prefix + "extension" + assert extension.attrib["base"] == "xs:string" + for attribute in extension: + assert attribute.tag == prefix + "attribute" + # we could distinguish by type; keeping string for now + attribute_keys.append(attribute.attrib["name"]) + isSimpleContent = True + allowed_tags = frozenset(keys) + if len(keys) == 1 and keys == multiple: + assert not isSimpleContent + args = (allowed_tags,) + self.constructors[name] = (ListElement, args) + elif len(keys) >= 1: + assert not isSimpleContent + repeated_tags = frozenset(multiple) + args = (allowed_tags, repeated_tags) + self.constructors[name] = (DictionaryElement, args) + else: + self.strings[name] = allowed_tags + + def elementDecl(self, name, model): + """Call a call-back function for each element declaration in a DTD. + + This is used for each element declaration in a DTD like:: + + + + The purpose of this function is to determine whether this element + should be regarded as a string, integer, list, dictionary, structure, + or error. + """ + if name.upper() == "ERROR": + self.errors.add(name) + return + if name == "Item" and model == ( + expat.model.XML_CTYPE_MIXED, + expat.model.XML_CQUANT_REP, + None, + ((expat.model.XML_CTYPE_NAME, expat.model.XML_CQUANT_NONE, "Item", ()),), + ): + # Special case. As far as I can tell, this only occurs in the + # eSummary DTD. + self.items.add(name) + return + # First, remove ignorable parentheses around declarations + while ( + model[0] in (expat.model.XML_CTYPE_SEQ, expat.model.XML_CTYPE_CHOICE) + and model[1] in (expat.model.XML_CQUANT_NONE, expat.model.XML_CQUANT_OPT) + and len(model[3]) == 1 + ): + model = model[3][0] + # PCDATA declarations correspond to strings + if model[0] in (expat.model.XML_CTYPE_MIXED, expat.model.XML_CTYPE_EMPTY): + if model[1] == expat.model.XML_CQUANT_REP: + children = model[3] + allowed_tags = frozenset(child[2] for child in children) + else: + allowed_tags = frozenset() + self.strings[name] = allowed_tags + return + # Children can be anything; use a dictionary-type element + if model == (expat.model.XML_CTYPE_ANY, expat.model.XML_CQUANT_NONE, None, ()): + allowed_tags = None + repeated_tags = None + args = (allowed_tags, repeated_tags) + self.constructors[name] = (DictionaryElement, args) + return + # List-type elements + if model[0] in ( + expat.model.XML_CTYPE_CHOICE, + expat.model.XML_CTYPE_SEQ, + ) and model[1] in (expat.model.XML_CQUANT_PLUS, expat.model.XML_CQUANT_REP): + children = model[3] + allowed_tags = frozenset(child[2] for child in children) + if model[0] == expat.model.XML_CTYPE_SEQ: + if len(children) > 1: + assert model[1] == expat.model.XML_CQUANT_PLUS + first_child = children[0] + assert first_child[1] == expat.model.XML_CQUANT_NONE + first_tag = first_child[2] + args = allowed_tags, first_tag + self.constructors[name] = (OrderedListElement, args) + return + assert len(children) == 1 + self.constructors[name] = (ListElement, (allowed_tags,)) + return + # This is the tricky case. Check which keys can occur multiple + # times. If only one key is possible, and it can occur multiple + # times, then this is a list. If more than one key is possible, + # but none of them can occur multiple times, then this is a + # dictionary. Otherwise, this is a structure. + # In 'single' and 'multiple', we keep track which keys can occur + # only once, and which can occur multiple times. + single = [] + multiple = [] + errors = [] + # The 'count' function is called recursively to make sure all the + # children in this model are counted. + + def count(model): + quantifier, key, children = model[1:] + if key is None: + if quantifier in ( + expat.model.XML_CQUANT_PLUS, + expat.model.XML_CQUANT_REP, + ): + for child in children: + multiple.append(child[2]) + else: + for child in children: + count(child) + elif key.upper() == "ERROR": + errors.append(key) + else: + if quantifier in ( + expat.model.XML_CQUANT_NONE, + expat.model.XML_CQUANT_OPT, + ): + single.append(key) + elif quantifier in ( + expat.model.XML_CQUANT_PLUS, + expat.model.XML_CQUANT_REP, + ): + multiple.append(key) + + count(model) + if len(single) == 0 and len(multiple) == 1: + allowed_tags = frozenset(multiple + errors) + self.constructors[name] = (ListElement, (allowed_tags,)) + else: + allowed_tags = frozenset(single + multiple + errors) + repeated_tags = frozenset(multiple) + args = (allowed_tags, repeated_tags) + self.constructors[name] = (DictionaryElement, args) + + def open_dtd_file(self, filename): + """Open specified DTD file.""" + if DataHandler.local_dtd_dir is not None: + path = os.path.join(DataHandler.local_dtd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + path = os.path.join(DataHandler.global_dtd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + return None + + def open_xsd_file(self, filename): + """Open specified XSD file.""" + if DataHandler.local_xsd_dir is not None: + path = os.path.join(DataHandler.local_xsd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + path = os.path.join(DataHandler.global_xsd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + return None + + def save_dtd_file(self, filename, text): + """Save DTD file to cache.""" + if DataHandler.local_dtd_dir is None: + return + path = os.path.join(DataHandler.local_dtd_dir, filename) + try: + handle = open(path, "wb") + except OSError: + warnings.warn(f"Failed to save {filename} at {path}") + else: + handle.write(text) + handle.close() + + def save_xsd_file(self, filename, text): + """Save XSD file to cache.""" + if DataHandler.local_xsd_dir is None: + return + path = os.path.join(DataHandler.local_xsd_dir, filename) + try: + handle = open(path, "wb") + except OSError: + warnings.warn(f"Failed to save {filename} at {path}") + else: + handle.write(text) + handle.close() + + def verify_security(self, url, verify_hostname=True): + """Check if the given URL is from a trustable source. + + When ``self.bypass_url_security`` evaluates to ``True``, + all URL security checks will be skipped. + """ + if not self.bypass_url_security: + parts = urlparse(url) + scheme = parts.scheme + hostname = parts.hostname + if scheme != "https" or ( + verify_hostname and not hostname.endswith(".nlm.nih.gov") + ): + raise ValueError(f"Expected secure URL to NCBI, found {url!r}") + + def externalEntityRefHandler(self, context, base, systemId, publicId): + """Handle external entity reference in order to cache DTD locally. + + The purpose of this function is to load the DTD locally, instead + of downloading it from the URL specified in the XML. Using the local + DTD results in much faster parsing. If the DTD is not found locally, + we try to download it. If new DTDs become available from NCBI, + putting them in Bio/Entrez/DTDs will allow the parser to see them. + """ + urlinfo = urlparse(systemId) + if urlinfo.scheme in ["http", "https", "ftp"]: + # Then this is an absolute path to the DTD. + url = systemId + elif urlinfo.scheme == "": + # Then this is a relative path to the DTD. + # Look at the parent URL to find the full path. + try: + source = self.dtd_urls[-1] + except IndexError: + # Assume the default URL for DTDs if the top parent + # does not contain an absolute path + source = "https://www.ncbi.nlm.nih.gov/dtd/" + else: + source = os.path.dirname(source) + # urls always have a forward slash, don't use os.path.join + url = source.rstrip("/") + "/" + systemId + else: + raise ValueError("Unexpected URL scheme %r" % urlinfo.scheme) + + # NOTE: This trusts any external references from a trusted parent, + # even if these external references go to unknown hosts, + # e.g. when NCBI starts referencing things on a new host + # from existing DTD files. + # Needs to be checked *prior* to appending to ``self.dtd_urls``. + self.verify_security(url, verify_hostname=not self.dtd_urls) + + # NOTE: Since ``self.dtd_urls`` being non-empty has security + # consequences with the check above, we use a ``finally`` wrap + # here, in order to guarantee that push and pop are matched. + self.dtd_urls.append(url) + try: + # First, try to load the local version of the DTD file + location, filename = os.path.split(systemId) + handle = self.open_dtd_file(filename) + if not handle: + # DTD is not available as a local file. Try accessing it through + # the internet instead. + try: + handle = urlopen(url) + except OSError: + raise RuntimeError( + f"Failed to access {filename} at {url}" + ) from None + text = handle.read() + handle.close() + self.save_dtd_file(filename, text) + handle = BytesIO(text) + + parser = self.parser.ExternalEntityParserCreate(context) + parser.ElementDeclHandler = self.elementDecl + parser.ParseFile(handle) + handle.close() + finally: + self.dtd_urls.pop() + + self.parser.StartElementHandler = self.startElementHandler + return 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._IPGReportSet.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._IPGReportSet.xsd new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._IPGReportSet.xsd differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._NCBI_BlastOutput2.mod.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._NCBI_BlastOutput2.mod.xsd new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._NCBI_BlastOutput2.mod.xsd differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._NCBI_BlastOutput2.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._NCBI_BlastOutput2.xsd new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/._NCBI_BlastOutput2.xsd differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/IPGReportSet.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/IPGReportSet.xsd new file mode 100644 index 0000000000000000000000000000000000000000..6194a26727bc0fa51df15e582b0b1fe87fb2589d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/IPGReportSet.xsd @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd new file mode 100644 index 0000000000000000000000000000000000000000..827422b44db36661b51bda703d6e888c1bc8a2b4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd @@ -0,0 +1,360 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd new file mode 100644 index 0000000000000000000000000000000000000000..ffe5c683dff985b8fb7c53e169aef03d98aee57b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17806d5a4fc605d58c6e999dff8ff1e442a1be9e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__init__.py @@ -0,0 +1,747 @@ +# Copyright 1999-2000 by Jeffrey Chang. All rights reserved. +# Copyright 2008-2013 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2011-2016 by Peter Cock. All rights reserved. +# Revisions copyright 2015 by Eric Rasche. All rights reserved. +# Revisions copyright 2015 by Carlos Pena. 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 NCBI over the WWW. + +The main Entrez web page is available at: +https://www.ncbi.nlm.nih.gov/search/ + +Entrez Programming Utilities web page is available at: +https://www.ncbi.nlm.nih.gov/books/NBK25501/ + +This module provides a number of functions like ``efetch`` (short for +Entrez Fetch) which will return the data as a handle object. This is +a standard interface used in Python for reading data from a file, or +in this case a remote network connection, and provides methods like +``.read()`` or offers iteration over the contents line by line. See +also "What the heck is a handle?" in the Biopython Tutorial and +Cookbook: https://biopython.org/docs/latest/Tutorial/index.html + +The handle returned by these functions can be either in text mode or +in binary mode, depending on the data requested and the results +returned by NCBI Entrez. Typically, XML data will be in binary mode +while other data will be in text mode, as required by the downstream +parser to parse the data. + +Unlike a handle to a file on disk from the ``open(filename)`` function, +which has a ``.name`` attribute giving the filename, the handles from +``Bio.Entrez`` all have a ``.url`` attribute instead giving the URL +used to connect to the NCBI Entrez API. + +The ``epost``, ``efetch``, and ``esummary`` tools take an "id" parameter +which corresponds to one or more database UIDs (or accession.version +identifiers in the case of sequence databases such as "nuccore" or +"protein"). The Python value of the "id" keyword passed to these functions +may be either a single ID as a string or integer or multiple IDs as an +iterable of strings/integers. You may also pass a single string containing +multiple IDs delimited by commas. The ``elink`` tool also accepts multiple +IDs but the argument is handled differently than the other three. See that +function's docstring for more information. + +All the functions that send requests to the NCBI Entrez API will +automatically respect the NCBI rate limit (of 3 requests per second +without an API key, or 10 requests per second with an API key) and +will automatically retry when encountering transient failures +(i.e. connection failures or HTTP 5XX codes). By default, Biopython +does a maximum of three tries before giving up, and sleeps for 15 +seconds between tries. You can tweak these parameters by setting +``Bio.Entrez.max_tries`` and ``Bio.Entrez.sleep_between_tries``. + +The Entrez module also provides an XML parser which takes a handle +as input. + +Variables: + + - email Set the Entrez email parameter (default is not set). + - tool Set the Entrez tool parameter (default is ``biopython``). + - api_key Personal API key from NCBI. If not set, only 3 queries per + second are allowed. 10 queries per seconds otherwise with a + valid API key. + - max_tries Configures how many times failed requests will be + automatically retried on error (default is 3). + - sleep_between_tries The delay, in seconds, before retrying a request on + error (default is 15). + +Functions: + + - efetch Retrieves records in the requested format from a list of one or + more primary IDs or from the user's environment + - epost Posts a file containing a list of primary IDs for future use in + the user's environment to use with subsequent search strategies + - esearch Searches and retrieves primary IDs (for use in EFetch, ELink, + and ESummary) and term translations and optionally retains + results for future use in the user's environment. + - elink Checks for the existence of an external or Related Articles link + from a list of one or more primary IDs. Retrieves primary IDs + and relevancy scores for links to Entrez databases or Related + Articles; creates a hyperlink to the primary LinkOut provider + for a specific ID and database, or lists LinkOut URLs + and Attributes for multiple IDs. + - einfo Provides field index term counts, last update, and available + links for each database. + - esummary Retrieves document summaries from a list of primary IDs or from + the user's environment. + - egquery Provides Entrez database counts in XML for a single search + using Global Query. + - espell Retrieves spelling suggestions. + - ecitmatch Retrieves PubMed IDs (PMIDs) that correspond to a set of + input citation strings. + + - read Parses the XML results returned by any of the above functions. + Alternatively, the XML data can be read from a file opened in binary mode. + Typical usage is: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.einfo() # or esearch, efetch, ... + >>> record = Entrez.read(handle) + >>> handle.close() + + where record is now a Python dictionary or list. + + - parse Parses the XML results returned by those of the above functions + which can return multiple records - such as efetch, esummary + and elink. Typical usage is: + + >>> handle = Entrez.efetch(db="taxonomy", id="9615,9685", retmode="xml") + >>> records = Entrez.parse(handle) + >>> for record in records: + ... print(record['TaxId'], record["OtherNames"]['GenbankCommonName']) + ... + 9615 dog + 9685 domestic cat + >>> handle.close() + + This function is appropriate only if the XML file contains + multiple records, and is particular useful for large files. + + - _open Internally used function. + +""" + +import io +import time +import warnings +from urllib.error import HTTPError +from urllib.error import URLError +from urllib.parse import urlencode +from urllib.request import Request +from urllib.request import urlopen + +from Bio._utils import function_with_previous + +email = None +max_tries = 3 +sleep_between_tries = 15 +tool = "biopython" +api_key = None +local_cache = None + + +# XXX retmode? +def epost(db, **keywds): + """Post a file of identifiers for future use. + + Posts a file containing a list of UIs for future use in the user's + environment to use with subsequent search strategies. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EPost + + :returns: Handle to the results. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi" + variables = {"db": db} + variables.update(keywds) + request = _build_request(cgi, variables, post=True) + return _open(request) + + +def efetch(db, **keywords): + """Fetch Entrez results which are returned as a handle. + + EFetch retrieves records in the requested format from a list or set of one or + more UIs or from user's environment. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.efetch(db="nucleotide", id="AY851612", rettype="gb", retmode="text") + >>> print(handle.readline().strip()) + LOCUS AY851612 892 bp DNA linear PLN 10-APR-2007 + >>> handle.close() + + This will automatically use an HTTP POST rather than HTTP GET if there + are over 200 identifiers as recommended by the NCBI. + + **Warning:** The NCBI changed the default retmode in Feb 2012, so many + databases which previously returned text output now give XML. + + :returns: Handle to the results. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi" + variables = {"db": db} + variables.update(keywords) + request = _build_request(cgi, variables) + return _open(request) + + +def esearch(db, term, **keywds): + """Run an Entrez search and return a handle to the results. + + ESearch searches and retrieves primary IDs (for use in EFetch, ELink + and ESummary) and term translations, and optionally retains results + for future use in the user's environment. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.esearch( + ... db="nucleotide", retmax=10, idtype="acc", + ... term="opuntia[ORGN] accD 2007[Publication Date]" + ... ) + ... + >>> record = Entrez.read(handle) + >>> handle.close() + >>> int(record["Count"]) >= 2 + True + >>> "EF590893.1" in record["IdList"] + True + >>> "EF590892.1" in record["IdList"] + True + + :returns: Handle to the results, which are always in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" + variables = {"db": db, "term": term} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def elink(**keywds): + """Check for linked external articles and return a handle. + + ELink checks for the existence of an external or Related Articles link + from a list of one or more primary IDs; retrieves IDs and relevancy + scores for links to Entrez databases or Related Articles; creates a + hyperlink to the primary LinkOut provider for a specific ID and + database, or lists LinkOut URLs and attributes for multiple IDs. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ELink + + Note that ELink treats the "id" parameter differently than the other + tools when multiple values are given. You should generally pass multiple + UIDs as a list of strings or integers. This will provide a "one-to-one" + mapping from source database UIDs to destination database UIDs in the + result. If multiple source UIDs are passed as a single comma-delimited + string all destination UIDs will be mixed together in the result. + + This example finds articles related to the Biopython application + note's entry in the PubMed database: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> pmid = "19304878" + >>> handle = Entrez.elink(dbfrom="pubmed", id=pmid, linkname="pubmed_pubmed") + >>> record = Entrez.read(handle) + >>> handle.close() + >>> print(record[0]["LinkSetDb"][0]["LinkName"]) + pubmed_pubmed + >>> linked = [link["Id"] for link in record[0]["LinkSetDb"][0]["Link"]] + >>> "14630660" in linked + True + + This is explained in much more detail in the Biopython Tutorial. + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables, join_ids=False) + return _open(request) + + +def einfo(**keywds): + """Return a summary of the Entrez databases as a results handle. + + EInfo provides field names, index term counts, last update, and + available links for each Entrez database. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EInfo + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> record = Entrez.read(Entrez.einfo()) + >>> 'pubmed' in record['DbList'] + True + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def esummary(**keywds): + """Retrieve document summaries as a results handle. + + ESummary retrieves document summaries from a list of primary IDs or + from the user's environment. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESummary + + This example discovers more about entry 19923 in the structure + database: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.esummary(db="structure", id="19923") + >>> record = Entrez.read(handle) + >>> handle.close() + >>> print(record[0]["Id"]) + 19923 + >>> print(record[0]["PdbDescr"]) + CRYSTAL STRUCTURE OF E. COLI ACONITASE B + + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def espell(**keywds): + """Retrieve spelling suggestions as a results handle. + + ESpell retrieves spelling suggestions, if available. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESpell + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> record = Entrez.read(Entrez.espell(term="biopythooon")) + >>> print(record["Query"]) + biopythooon + >>> print(record["CorrectedQuery"]) + biopython + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/espell.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def _update_ecitmatch_variables(keywds): + # XML is the only supported value, and it actually returns TXT. + variables = {"retmode": "xml"} + citation_keys = ( + "journal_title", + "year", + "volume", + "first_page", + "author_name", + "key", + ) + + # Accept pre-formatted strings + if isinstance(keywds["bdata"], str): + variables.update(keywds) + else: + # Alternatively accept a nicer interface + variables["db"] = keywds["db"] + bdata = [] + for citation in keywds["bdata"]: + formatted_citation = "|".join( + [citation.get(key, "") for key in citation_keys] + ) + bdata.append(formatted_citation) + variables["bdata"] = "\r".join(bdata) + return variables + + +def ecitmatch(**keywds): + """Retrieve PMIDs for input citation strings, returned as a handle. + + ECitMatch retrieves PubMed IDs (PMIDs) that correspond to a set of input + citation strings. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ECitMatch + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> citation_1 = {"journal_title": "proc natl acad sci u s a", + ... "year": "1991", "volume": "88", "first_page": "3248", + ... "author_name": "mann bj", "key": "citation_1"} + >>> handle = Entrez.ecitmatch(db="pubmed", bdata=[citation_1]) + >>> print(handle.read().strip().split("|")) + ['proc natl acad sci u s a', '1991', '88', '3248', 'mann bj', 'citation_1', '2014248'] + >>> handle.close() + + :returns: Handle to the results, by default in plain text. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/ecitmatch.cgi" + variables = _update_ecitmatch_variables(keywds) + request = _build_request(cgi, variables, ecitmatch=True) + return _open(request) + + +def read(source, validate=True, escape=False, ignore_errors=False): + """Parse an XML file from the NCBI Entrez Utilities into python objects. + + This function parses an XML file created by NCBI's Entrez Utilities, + returning a multilevel data structure of Python lists and dictionaries. + Most XML files returned by NCBI's Entrez Utilities can be parsed by + this function, provided its DTD is available. Biopython includes the + DTDs for most commonly used Entrez Utilities. + + The argument ``source`` must be a file or file-like object opened in binary + mode, or a filename. The parser detects the encoding from the XML file, and + uses it to convert all text in the XML to the correct Unicode string. The + functions in Bio.Entrez to access NCBI Entrez will automatically return XML + data in binary mode. For files, use mode "rb" when opening the file, as in + + >>> from Bio import Entrez + >>> path = "Entrez/esearch1.xml" + >>> stream = open(path, "rb") # opened in binary mode + >>> record = Entrez.read(stream) + >>> print(record['QueryTranslation']) + "biopython"[All Fields] + >>> stream.close() + + Alternatively, you can use the filename directly, as in + + >>> record = Entrez.read(path) + >>> print(record['QueryTranslation']) + "biopython"[All Fields] + + which is safer, as the file stream will automatically be closed after the + record has been read, or if an error occurs. + + If validate is True (default), the parser will validate the XML file + against the DTD, and raise an error if the XML file contains tags that + are not represented in the DTD. If validate is False, the parser will + simply skip such tags. + + If escape is True, all characters that are not valid HTML are replaced + by HTML escape characters to guarantee that the returned strings are + valid HTML fragments. For example, a less-than sign (<) is replaced by + <. If escape is False (default), the string is returned as is. + + If ignore_errors is False (default), any error messages in the XML file + will raise a RuntimeError. If ignore_errors is True, error messages will + be stored as ErrorElement items, without raising an exception. + + Whereas the data structure seems to consist of generic Python lists, + dictionaries, strings, and so on, each of these is actually a class + derived from the base type. This allows us to store the attributes + (if any) of each element in a dictionary my_element.attributes, and + the tag name in my_element.tag. + """ + from .Parser import DataHandler + + handler = DataHandler(validate, escape, ignore_errors) + record = handler.read(source) + return record + + +def parse(source, validate=True, escape=False, ignore_errors=False): + """Parse an XML file from the NCBI Entrez Utilities into python objects. + + This function parses an XML file created by NCBI's Entrez Utilities, + returning a multilevel data structure of Python lists and dictionaries. + This function is suitable for XML files that (in Python) can be represented + as a list of individual records. Whereas 'read' reads the complete file + and returns a single Python list, 'parse' is a generator function that + returns the records one by one. This function is therefore particularly + useful for parsing large files. + + Most XML files returned by NCBI's Entrez Utilities can be parsed by + this function, provided its DTD is available. Biopython includes the + DTDs for most commonly used Entrez Utilities. + + The argument ``source`` must be a file or file-like object opened in binary + mode, or a filename. The parser detects the encoding from the XML file, and + uses it to convert all text in the XML to the correct Unicode string. The + functions in Bio.Entrez to access NCBI Entrez will automatically return XML + data in binary mode. For files, use mode "rb" when opening the file, as in + + >>> from Bio import Entrez + >>> path = "Entrez/taxonomy.xml" + >>> stream = open(path, "rb") # opened in binary mode + >>> records = Entrez.parse(stream) + >>> for record in records: + ... print(record['TaxId'], record["OtherNames"]['GenbankCommonName']) + ... + 9615 dog + 9685 domestic cat + >>> stream.close() + + Alternatively, you can use the filename directly, as in + + >>> records = Entrez.parse(path) + >>> for record in records: + ... print(record['TaxId'], record["OtherNames"]['GenbankCommonName']) + ... + 9615 dog + 9685 domestic cat + + which is safer, as the file stream will automatically be closed after all + the records have been read, or if an error occurs. + + If validate is True (default), the parser will validate the XML file + against the DTD, and raise an error if the XML file contains tags that + are not represented in the DTD. If validate is False, the parser will + simply skip such tags. + + If escape is True, all characters that are not valid HTML are replaced + by HTML escape characters to guarantee that the returned strings are + valid HTML fragments. For example, a less-than sign (<) is replaced by + <. If escape is False (default), the string is returned as is. + + If ignore_errors is False (default), any error messages in the XML file + will raise a RuntimeError. If ignore_errors is True, error messages will + be stored as ErrorElement items, without raising an exception. + + Whereas the data structure seems to consist of generic Python lists, + dictionaries, strings, and so on, each of these is actually a class + derived from the base type. This allows us to store the attributes + (if any) of each element in a dictionary my_element.attributes, and + the tag name in my_element.tag. + """ + from .Parser import DataHandler + + handler = DataHandler(validate, escape, ignore_errors) + records = handler.parse(source) + return records + + +@function_with_previous +def _open(request): + """Make an HTTP request to Entrez, handling errors and enforcing rate limiting (PRIVATE). + + Does some simple error checking and will try again after certain types of errors, up to + ``max_retries`` times. This function also enforces the "up to three queries per second + rule" to avoid abusing the NCBI servers (this limit is increased to 10 if using an API key). + + :param req_or_cgi: A Request object returned by ``_build_request``. + :type req_or_cgi: urllib.request.Request + :returns: Handle to HTTP response as returned by ``urllib.request.urlopen``. Will be wrapped in + an ``io.TextIOWrapper`` if its content type is plain text. + :rtype: http.client.HTTPResponse or io.TextIOWrapper + :raises urllib.error.URLError: Errors raised by ``urlopen`` past the maximum number of retries. + """ + # NCBI requirement: At most three queries per second if no API key is provided. + # Equivalently, at least a third of second between queries + # Using just 0.333333334 seconds sometimes hit the NCBI rate limit, + # the slightly longer pause of 0.37 seconds has been more reliable. + delay = 0.1 if _has_api_key(request) else 0.37 + current = time.time() + wait = _open.previous + delay - current + if wait > 0: + time.sleep(wait) + _open.previous = current + wait + else: + _open.previous = current + + for i in range(max_tries): + try: + handle = urlopen(request) + except HTTPError as exception: + # Reraise if the final try fails + if i >= max_tries - 1: + raise + # Reraise if the exception is triggered by a HTTP 4XX error + # indicating some kind of bad request, UNLESS it's specifically a + # 429 "Too Many Requests" response. NCBI seems to sometimes + # erroneously return 429s even when their rate limit is + # honored (and indeed even with the rate-limit-related fudging + # higher up in this function in place), so the best we can do is + # treat them as a serverside error and try again after sleeping + # for a bit. + if exception.code // 100 == 4 and exception.code != 429: + raise + except URLError: + # Reraise if the final try fails + if i >= max_tries - 1: + raise + # Treat as a transient error and try again after a brief delay: + time.sleep(sleep_between_tries) + else: + break + + subtype = handle.headers.get_content_subtype() + if subtype == "plain": + url = handle.url + handle = io.TextIOWrapper(handle, encoding="UTF-8") + handle.url = url + return handle + + +_open.previous = 0 + + +def _build_request(cgi, params=None, post=None, ecitmatch=False, join_ids=True): + """Build a Request object for an E-utility. + + :param str cgi: base URL for the CGI script to access. + :param params: Mapping containing options to pass to the CGI script. Keys must be strings. + :type params: dict or None + :param bool post: Whether to use the HTTP POST method rather than GET. By default (``post=None``), + POST is used if the URL encoded parameters would be over 1000 characters long, as is + suggested in the E-Utilities documentation. + :param bool ecitmatch: Don't URL-encode pipe ("|") characters, this is expected by the ecitmatch + tool. + :param bool join_ids: Passed to ``_construct_params``. + :returns: A request object ready to be passed to ``_open``. + :rtype: urllib.request.Request + """ + params = _construct_params(params, join_ids=join_ids) + + params_str = urlencode(params, doseq=True) + if ecitmatch: + params_str = params_str.replace("%7C", "|") + + # By default, post is None. Set to a boolean to over-ride length choice: + if post is None and len(params_str) > 1000: + post = True + + # NCBI prefers an HTTP POST instead of an HTTP GET if there are more than about 200 IDs + if post is None and "id" in params: + idcount = params["id"].count(",") + 1 + if idcount >= 200: + post = True + + if post: + return Request(cgi, data=params_str.encode("utf8"), method="POST") + else: + return Request(cgi + "?" + params_str, method="GET") + + +def _construct_params(params, join_ids=True): + """Construct/format parameter dict for an Entrez request. + + :param params: User-supplied parameters. + :type params: dict or None + :param bool join_ids: If True and the "id" key of ``params`` is a list + containing multiple UIDs, join them into a single comma-delimited string. + :returns: Parameters with defaults added and keys with None values removed. + :rtype: dict + """ + if params is None: + params = {} + + # Tell Entrez that we are using Biopython (or whatever the user has + # specified explicitly in the parameters or by changing the default) + params.setdefault("tool", tool) + + # Tell Entrez who we are + params.setdefault("email", email) + params.setdefault("api_key", api_key) + + # Remove None values from the parameters + for key, value in list(params.items()): + if value is None: + del params[key] + + # Warn if email not set + if "email" not in params: + warnings.warn( + """ + Email address is not specified. + + To make use of NCBI's E-utilities, NCBI requires you to specify your + email address with each request. As an example, if your email address + is A.N.Other@example.com, you can specify it as follows: + from Bio import Entrez + Entrez.email = 'A.N.Other@example.com' + In case of excessive usage of the E-utilities, NCBI will attempt to contact + a user at the email address provided before blocking access to the + E-utilities.""", + UserWarning, + ) + + # Format "id" parameter properly + if join_ids and "id" in params: + params["id"] = _format_ids(params["id"]) + + return params + + +def _format_ids(ids): + """Convert one or more UIDs to a single comma-delimited string. + + Input may be a single ID as an integer or string, an iterable of strings/ints, + or a string of IDs already separated by commas. + """ + if isinstance(ids, int): + # Single integer, just convert to str + return str(ids) + + if isinstance(ids, str): + # String which represents one or more IDs joined by commas + # Remove any whitespace around commas if they are present + return ",".join(id.strip() for id in ids.split(",")) + + # Not a string or integer, assume iterable + return ",".join(map(str, ids)) + + +def _has_api_key(request): + """Check if a Request has the api_key parameter set, to set the rate limit. + + Works with GET or POST requests. + """ + if request.method == "POST": + return b"api_key=" in request.data + return "api_key=" in request.full_url + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Enzyme.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Enzyme.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Enzyme.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Prodoc.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Prodoc.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Prodoc.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Prosite.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Prosite.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._Prosite.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._ScanProsite.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._ScanProsite.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._ScanProsite.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._cellosaurus.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._cellosaurus.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/._cellosaurus.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Enzyme.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Enzyme.py new file mode 100644 index 0000000000000000000000000000000000000000..ca162b1013231b935a058fa814180766349c62d6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Enzyme.py @@ -0,0 +1,159 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# Copyright 2009 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. + +"""Parse the enzyme.dat file from Enzyme at ExPASy. + +See https://www.expasy.org/enzyme/ + +Tested with the release of 03-Mar-2009. + +Functions: + - read Reads a file containing one ENZYME entry + - parse Reads a file containing multiple ENZYME entries + +Classes: + - Record Holds ENZYME data. + +""" + + +def parse(handle): + """Parse ENZYME records. + + This function is for parsing ENZYME files containing multiple + records. + + Arguments: + - handle - handle to the file. + + """ + while True: + record = __read(handle) + if not record: + break + yield record + + +def read(handle): + """Read one ENZYME record. + + This function is for parsing ENZYME files containing + exactly one record. + + Arguments: + - handle - handle to the file. + + """ + record = __read(handle) + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one ENZYME record found") + return record + + +class Record(dict): + """Holds information from an ExPASy ENZYME record as a Python dictionary. + + Each record contains the following keys: + + - ID: EC number + - DE: Recommended name + - AN: Alternative names (if any) + - CA: Catalytic activity + - CF: Cofactors (if any) + - PR: Pointers to any Prosite documentation entries that correspond to the + enzyme + - DR: Pointers to any Swiss-Prot protein sequence entries that correspond + to the enzyme + - CC: Comments + + """ + + def __init__(self): + """Initialize the class.""" + dict.__init__(self) + self["ID"] = "" + self["DE"] = "" + self["AN"] = [] + self["CA"] = "" + self["CF"] = "" + self["CC"] = [] # one comment per line + self["PR"] = [] + self["DR"] = [] + + def __repr__(self): + """Return the canonical string representation of the Record object.""" + if self["ID"]: + if self["DE"]: + return f"{self.__class__.__name__} ({self['ID']}, {self['DE']})" + else: + return f"{self.__class__.__name__} ({self['ID']})" + else: + return f"{self.__class__.__name__} ( )" + + def __str__(self): + """Return a readable string representation of the Record object.""" + output = [ + "ID: " + self["ID"], + "DE: " + self["DE"], + "AN: " + repr(self["AN"]), + "CA: '" + self["CA"] + "'", + "CF: " + self["CF"], + "CC: " + repr(self["CC"]), + "PR: " + repr(self["PR"]), + "DR: %d Records" % len(self["DR"]), + ] + return "\n".join(output) + + +# Everything below is private + + +def __read(handle): + record = None + for line in handle: + key, value = line[:2], line[5:].rstrip() + if key == "ID": + record = Record() + record["ID"] = value + elif key == "DE": + record["DE"] += value + elif key == "AN": + if record["AN"] and not record["AN"][-1].endswith("."): + record["AN"][-1] += " " + value + else: + record["AN"].append(value) + elif key == "CA": + record["CA"] += value + elif key == "DR": + pair_data = value.rstrip(";").split(";") + for pair in pair_data: + t1, t2 = pair.split(",") + row = [t1.strip(), t2.strip()] + record["DR"].append(row) + elif key == "CF": + if record["CF"]: + record["CF"] += " " + value + else: + record["CF"] = value + elif key == "PR": + assert value.startswith("PROSITE; ") + value = value[9:].rstrip(";") + record["PR"].append(value) + elif key == "CC": + if value.startswith("-!- "): + record["CC"].append(value[4:]) + elif value.startswith(" ") and record["CC"]: + record["CC"][-1] += value[3:] + # copyright notice is silently skipped + elif key == "//": + if record: + return record + else: # This was the copyright notice + continue + if record: + raise ValueError("Unexpected end of stream") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prodoc.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prodoc.py new file mode 100644 index 0000000000000000000000000000000000000000..8120b010ac42ae7d5fe6f92a3ce44b241d0d38c0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prodoc.py @@ -0,0 +1,173 @@ +# Copyright 2000 by Jeffrey Chang. 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 prosite.doc file from Prosite. + +See https://www.expasy.org/prosite/ + +Tested with: + - Release 15.0, July 1998 + - Release 16.0, July 1999 + - Release 20.22, 13 November 2007 + - Release 20.43, 10 February 2009 + +Functions: + - read Read a Prodoc file containing exactly one Prodoc entry. + - parse Iterates over entries in a Prodoc file. + +Classes: + - Record Holds Prodoc data. + - Reference Holds data from a Prodoc reference. + +""" + + +def read(handle): + """Read in a record from a file with exactly one Prodoc record.""" + record = __read(handle) + # We should have reached the end of the record by now + line = handle.readline() + if line: + raise ValueError("More than one Prodoc record found") + return record + + +def parse(handle): + """Iterate over the records in a Prodoc file.""" + while True: + record = __read(handle) + if not record: + return + yield record + + +class Record: + """Holds information from a Prodoc record. + + Attributes: + - accession Accession number of the record. + - prosite_refs List of tuples (prosite accession, prosite name). + - text Free format text. + - references List of reference objects. + + """ + + def __init__(self): + """Initialize the class.""" + self.accession = "" + self.prosite_refs = [] + self.text = "" + self.references = [] + + +class Reference: + """Holds information from a Prodoc citation. + + Attributes: + - number Number of the reference. (string) + - authors Names of the authors. + - citation Describes the citation. + + """ + + def __init__(self): + """Initialize the class.""" + self.number = "" + self.authors = "" + self.citation = "" + + +# Below are private functions + + +def __read_prosite_reference_line(record, line): + line = line.rstrip() + if line[-1] != "}": + raise ValueError(f"I don't understand the Prosite reference on line\n{line}") + acc, name = line[1:-1].split("; ") + record.prosite_refs.append((acc, name)) + + +def __read_text_line(record, line): + record.text += line + return True + + +def __read_reference_start(record, line): + # Read the references + reference = Reference() + reference.number = line[1:3].strip() + if line[1] == "E": + # If it's an electronic reference, then the URL is on the + # line, instead of the author. + reference.citation = line[4:].strip() + else: + reference.authors = line[4:].strip() + record.references.append(reference) + + +def __read_reference_line(record, line): + if not line.strip(): + return False + reference = record.references[-1] + if line.startswith(" "): + if reference.authors[-1] == ",": + reference.authors += line[4:].rstrip() + else: + reference.citation += line[5:] + return True + raise Exception(f"I don't understand the reference line\n{line}") + + +def __read_copyright_line(record, line): + # Skip the copyright statement + if line.startswith("+----"): + return False + return True + + +def __read(handle): + # Skip blank lines between records + for line in handle: + line = line.rstrip() + if line and not line.startswith("//"): + break + else: + return None + record = Record() + # Read the accession number + if not line.startswith("{PDOC"): + raise ValueError("Line does not start with '{PDOC':\n%s" % line) + if line[-1] != "}": + raise ValueError(f"I don't understand accession line\n{line}") + record.accession = line[1:-1] + # Read the Prosite references + for line in handle: + if line.startswith("{PS"): + __read_prosite_reference_line(record, line) + else: + break + else: + raise ValueError("Unexpected end of stream.") + # Read the actual text + if not line.startswith("{BEGIN"): + raise ValueError("Line does not start with '{BEGIN':\n%s" % line) + read_line = __read_text_line + for line in handle: + if line.startswith("{END}"): + # Clean up the record and return + for reference in record.references: + reference.citation = reference.citation.rstrip() + reference.authors = reference.authors.rstrip() + return record + elif line[0] == "[" and line[3] == "]" and line[4] == " ": + __read_reference_start(record, line) + read_line = __read_reference_line + elif line.startswith("+----"): + read_line = __read_copyright_line + elif read_line: + if not read_line(record, line): + read_line = None + raise ValueError("Unexpected end of stream.") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prosite.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prosite.py new file mode 100644 index 0000000000000000000000000000000000000000..266ca68acdc3a301c9c37250d07f84d516797f35 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prosite.py @@ -0,0 +1,308 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# Copyright 2000 by Jeffrey Chang. All rights reserved. +# Revisions Copyright 2007 by Peter Cock. All rights reserved. +# Revisions Copyright 2009 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. +"""Parser for the prosite dat file from Prosite at ExPASy. + +See https://www.expasy.org/prosite/ + +Tested with: + - Release 20.43, 10-Feb-2009 + - Release 2017_03 of 15-Mar-2017. + +Functions: + - read Reads a Prosite file containing one Prosite record + - parse Iterates over records in a Prosite file. + +Classes: + - Record Holds Prosite data. + +""" + + +def parse(handle): + """Parse Prosite records. + + This function is for parsing Prosite files containing multiple + records. + + Arguments: + - handle - handle to the file. + + """ + while True: + record = __read(handle) + if not record: + break + yield record + + +def read(handle): + """Read one Prosite record. + + This function is for parsing Prosite files containing + exactly one record. + + Arguments: + - handle - handle to the file. + + """ + record = __read(handle) + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one Prosite record found") + return record + + +class Record: + """Holds information from a Prosite record. + + Main attributes: + - name ID of the record. e.g. ADH_ZINC + - type Type of entry. e.g. PATTERN, MATRIX, or RULE + - accession e.g. PS00387 + - created Date the entry was created. (MMM-YYYY for releases + before January 2017, DD-MMM-YYYY since January 2017) + - data_update Date the 'primary' data was last updated. + - info_update Date data other than 'primary' data was last updated. + - pdoc ID of the PROSITE DOCumentation. + - description Free-format description. + - pattern The PROSITE pattern. See docs. + - matrix List of strings that describes a matrix entry. + - rules List of rule definitions (from RU lines). (strings) + - prorules List of prorules (from PR lines). (strings) + + NUMERICAL RESULTS: + - nr_sp_release SwissProt release. + - nr_sp_seqs Number of seqs in that release of Swiss-Prot. (int) + - nr_total Number of hits in Swiss-Prot. tuple of (hits, seqs) + - nr_positive True positives. tuple of (hits, seqs) + - nr_unknown Could be positives. tuple of (hits, seqs) + - nr_false_pos False positives. tuple of (hits, seqs) + - nr_false_neg False negatives. (int) + - nr_partial False negatives, because they are fragments. (int) + + COMMENTS: + - cc_taxo_range Taxonomic range. See docs for format + - cc_max_repeat Maximum number of repetitions in a protein + - cc_site Interesting site. list of tuples (pattern pos, desc.) + - cc_skip_flag Can this entry be ignored? + - cc_matrix_type + - cc_scaling_db + - cc_author + - cc_ft_key + - cc_ft_desc + - cc_version version number (introduced in release 19.0) + + The following are all lists if tuples (swiss-prot accession, swiss-prot name). + + DATA BANK REFERENCES: + - dr_positive + - dr_false_neg + - dr_false_pos + - dr_potential Potential hits, but fingerprint region not yet available. + - dr_unknown Could possibly belong + - pdb_structs List of PDB entries. + + """ + + def __init__(self): + """Initialize the class.""" + self.name = "" + self.type = "" + self.accession = "" + self.created = "" + self.data_update = "" + self.info_update = "" + self.pdoc = "" + + self.description = "" + self.pattern = "" + self.matrix = [] + self.rules = [] + self.prorules = [] + self.postprocessing = [] + + self.nr_sp_release = "" + self.nr_sp_seqs = "" + self.nr_total = (None, None) + self.nr_positive = (None, None) + self.nr_unknown = (None, None) + self.nr_false_pos = (None, None) + self.nr_false_neg = None + self.nr_partial = None + + self.cc_taxo_range = "" + self.cc_max_repeat = "" + self.cc_site = [] + self.cc_skip_flag = "" + + self.dr_positive = [] + self.dr_false_neg = [] + self.dr_false_pos = [] + self.dr_potential = [] + self.dr_unknown = [] + + self.pdb_structs = [] + + +# Everything below are private functions + + +def __read(handle): + import re + + record = None + for line in handle: + keyword, value = line[:2], line[5:].rstrip() + if keyword == "ID": + record = Record() + cols = value.split("; ") + if len(cols) != 2: + raise ValueError(f"I don't understand identification line\n{line}") + record.name = cols[0] + record.type = cols[1].rstrip(".") # don't want '.' + elif keyword == "AC": + record.accession = value.rstrip(";") + elif keyword == "DT": + # e.g. from January 2017, + # DT 01-APR-1990 CREATED; 01-APR-1990 DATA UPDATE; 01-APR-1990 INFO UPDATE. + # Older files had brackets round the date descriptions and used MMM-YYYY + dates = value.rstrip(".").split("; ") + if dates[0].endswith((" (CREATED)", " CREATED")): + # Remove last word + record.created = dates[0].rsplit(" ", 1)[0] + else: + raise ValueError(f"I don't understand date line\n{line}") + if dates[1].endswith((" (DATA UPDATE)", " DATA UPDATE")): + # Remove last two words + record.data_update = dates[1].rsplit(" ", 2)[0] + else: + raise ValueError(f"I don't understand date line\n{line}") + if dates[2].endswith((" (INFO UPDATE)", " INFO UPDATE")): + # Remove last two words + record.info_update = dates[2].rsplit(" ", 2)[0] + else: + raise ValueError(f"I don't understand date line\n{line}") + elif keyword == "DE": + record.description = value + elif keyword == "PA": + record.pattern += value + elif keyword == "MA": + record.matrix.append(value) + elif keyword == "PP": + record.postprocessing.extend(value.split(";")) + elif keyword == "RU": + record.rules.append(value) + elif keyword == "NR": + cols = value.split(";") + for col in cols: + if not col: + continue + qual, data = (word.lstrip() for word in col.split("=")) + if qual == "/RELEASE": + release, seqs = data.split(",") + record.nr_sp_release = release + record.nr_sp_seqs = int(seqs) + elif qual == "/FALSE_NEG": + record.nr_false_neg = int(data) + elif qual == "/PARTIAL": + record.nr_partial = int(data) + elif qual in ["/TOTAL", "/POSITIVE", "/UNKNOWN", "/FALSE_POS"]: + m = re.match(r"(\d+)\((\d+)\)", data) + if not m: + raise Exception(f"Broken data {data} in comment line\n{line!r}") + hits = tuple(map(int, m.groups())) + if qual == "/TOTAL": + record.nr_total = hits + elif qual == "/POSITIVE": + record.nr_positive = hits + elif qual == "/UNKNOWN": + record.nr_unknown = hits + elif qual == "/FALSE_POS": + record.nr_false_pos = hits + else: + raise ValueError(f"Unknown qual {qual} in comment line\n{line!r}") + elif keyword == "CC": + # Expect CC lines like this: + # CC /TAXO-RANGE=??EPV; /MAX-REPEAT=2; + # Can (normally) split on ";" and then on "=" + cols = value.split(";") + for col in cols: + if not col or col[:17] == "Automatic scaling": + # DNAJ_2 in Release 15 has a non-standard comment line: + # CC Automatic scaling using reversed database + # Throw it away. (Should I keep it?) + continue + if col.count("=") == 0: + # Missing qualifier! Can we recover gracefully? + # For example, from Bug 2403, in PS50293 have: + # CC /AUTHOR=K_Hofmann; N_Hulo + continue + qual, data = (word.lstrip() for word in col.split("=")) + if qual == "/TAXO-RANGE": + record.cc_taxo_range = data + elif qual == "/MAX-REPEAT": + record.cc_max_repeat = data + elif qual == "/SITE": + pos, desc = data.split(",") + record.cc_site.append((int(pos), desc)) + elif qual == "/SKIP-FLAG": + record.cc_skip_flag = data + elif qual == "/MATRIX_TYPE": + record.cc_matrix_type = data + elif qual == "/SCALING_DB": + record.cc_scaling_db = data + elif qual == "/AUTHOR": + record.cc_author = data + elif qual == "/FT_KEY": + record.cc_ft_key = data + elif qual == "/FT_DESC": + record.cc_ft_desc = data + elif qual == "/VERSION": + record.cc_version = data + else: + raise ValueError(f"Unknown qual {qual} in comment line\n{line!r}") + elif keyword == "DR": + refs = value.split(";") + for ref in refs: + if not ref: + continue + acc, name, type = (word.strip() for word in ref.split(",")) + if type == "T": + record.dr_positive.append((acc, name)) + elif type == "F": + record.dr_false_pos.append((acc, name)) + elif type == "N": + record.dr_false_neg.append((acc, name)) + elif type == "P": + record.dr_potential.append((acc, name)) + elif type == "?": + record.dr_unknown.append((acc, name)) + else: + raise ValueError(f"I don't understand type flag {type}") + elif keyword == "3D": + cols = value.split() + for id in cols: + record.pdb_structs.append(id.rstrip(";")) + elif keyword == "PR": + rules = value.split(";") + record.prorules.extend(rules) + elif keyword == "DO": + record.pdoc = value.rstrip(";") + elif keyword == "//": + if not record: + # Then this was the copyright statement + continue + break + else: + raise ValueError(f"Unknown keyword {keyword} found") + else: + return + if not record: + raise ValueError("Unexpected end of stream.") + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/ScanProsite.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/ScanProsite.py new file mode 100644 index 0000000000000000000000000000000000000000..1eb2779b209a0cba7e711108c08ad9a538c83feb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/ScanProsite.py @@ -0,0 +1,151 @@ +# Copyright 2009 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 for calling and parsing ScanProsite from ExPASy.""" + +from urllib.parse import urlencode +from urllib.request import urlopen +from xml.sax import handler +from xml.sax.expatreader import ExpatParser + +# October 28th 2020 it was recognised that between October 10th 2020 and October +# 28th the main url of prosite changed from https://www.expasy.org to +# https://prosite.expasy.org. Thus a change in the mirror was issued from +# https://www.expasy.org to https://prosite.expasy.org. +PROSITE_URL = "https://prosite.expasy.org" + + +class Record(list): + """Represents search results returned by ScanProsite. + + This record is a list containing the search results returned by + ScanProsite. The record also contains the data members n_match, + n_seq, capped, and warning. + """ + + def __init__(self): + """Initialize the class.""" + self.n_match = None + self.n_seq = None + self.capped = None + self.warning = None + + +def scan(seq="", mirror=PROSITE_URL, output="xml", **keywords): + """Execute a ScanProsite search. + + Arguments: + - mirror: The ScanProsite mirror to be used + (default: PROSITE_URL). + - seq: The query sequence, or UniProtKB (Swiss-Prot, + TrEMBL) accession + - output: Format of the search results + (default: xml) + + Further search parameters can be passed as keywords; see the + documentation for programmatic access to ScanProsite at + https://prosite.expasy.org/scanprosite/scanprosite_doc.html + for a description of such parameters. + + This function returns a handle to the search results returned by + ScanProsite. Search results in the XML format can be parsed into a + Python object, by using the Bio.ExPASy.ScanProsite.read function. + + """ + if output != "xml": + raise NotImplementedError("Only output='xml' is supported currently.") + parameters = {"seq": seq, "output": output} + for key, value in keywords.items(): + if value is not None: + parameters[key] = value + command = urlencode(parameters) + url = f"{mirror}/cgi-bin/prosite/scanprosite/PSScan.cgi?{command}" + handle = urlopen(url) + return handle + + +def read(handle): + """Parse search results returned by ScanProsite into a Python object.""" + content_handler = ContentHandler() + saxparser = Parser() + saxparser.setContentHandler(content_handler) + saxparser.parse(handle) + record = content_handler.record + return record + + +# The classes below are considered private + + +class Parser(ExpatParser): + """Process the result from a ScanProsite search (PRIVATE).""" + + def __init__(self): + """Initialize the class.""" + ExpatParser.__init__(self) + self.firsttime = True + + def feed(self, data, isFinal=0): + """Raise an Error if plain text is received in the data. + + This is to show the Error messages returned by ScanProsite. + """ + # Error messages returned by the ScanProsite server are formatted as + # as plain text instead of an XML document. To catch such error + # messages, we override the feed method of the Expat parser. + # The error message is (hopefully) contained in the data that was just + # fed to the parser. + if self.firsttime: + if data[:22].decode("utf-8") != "": + raise ValueError(data) + self.firsttime = False + return ExpatParser.feed(self, data, isFinal) + + +class ContentHandler(handler.ContentHandler): + """Process and fill in the records, results of the search (PRIVATE).""" + + integers = ("start", "stop") + strings = ( + "sequence_ac", + "sequence_id", + "sequence_db", + "signature_ac", + "level", + "level_tag", + ) + + def __init__(self): + """Initialize the class.""" + self.element = [] + + def startElement(self, name, attrs): + """Define the beginning of a record and stores the search record.""" + self.element.append(name) + self.content = "" + if self.element == ["scanprosite_response", "matchset"]: + self.record = Record() + self.record.n_match = int(attrs["n_match"]) + self.record.n_seq = int(attrs["n_seq"]) + elif self.element == ["scanprosite_response", "matchset", "match"]: + match = {} + self.record.append(match) + + def endElement(self, name): + """Define the end of the search record.""" + assert name == self.element.pop() + if self.element == ["scanprosite_response", "matchset", "match"]: + match = self.record[-1] + if name in ContentHandler.integers: + match[name] = int(self.content) + elif name in ContentHandler.strings: + match[name] = self.content + else: + # Unknown type, treat it as a string + match[name] = self.content + + def characters(self, content): + """Store the record content.""" + self.content += content diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d72b486adc4e71edfcf3803ff6ed8349f9d63fa0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__init__.py @@ -0,0 +1,138 @@ +# Copyright 2000 by Jeffrey Chang. 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 access resources at ExPASy over the WWW. + +See https://www.expasy.org/ + + +Functions: + - get_prodoc_entry Interface to the get-prodoc-entry CGI script. + - get_prosite_entry Interface to the get-prosite-entry CGI script. + - get_prosite_raw Interface to the get-prosite-raw CGI script. + - get_sprot_raw Interface to the get-sprot-raw CGI script. + +""" + +import io +from urllib.error import HTTPError +from urllib.request import urlopen + + +def get_prodoc_entry( + id, cgi="https://prosite.expasy.org/cgi-bin/prosite/get-prodoc-entry" +): + """Get a text handle to a PRODOC entry at ExPASy in HTML format. + + >>> from Bio import ExPASy + >>> import os + >>> with ExPASy.get_prodoc_entry('PDOC00001') as in_handle: + ... html = in_handle.read() + ... + >>> with open("myprodocrecord.html", "w") as out_handle: + ... length = out_handle.write(html) + ... + >>> os.remove("myprodocrecord.html") # tidy up + + For a non-existing key XXX, ExPASy returns an HTML-formatted page + containing this text: 'There is currently no PROSITE entry for' + """ + return _open(f"{cgi}?{id}") + + +def get_prosite_entry( + id, cgi="https://prosite.expasy.org/cgi-bin/prosite/get-prosite-entry" +): + """Get a text handle to a PROSITE entry at ExPASy in HTML format. + + >>> from Bio import ExPASy + >>> import os + >>> with ExPASy.get_prosite_entry('PS00001') as in_handle: + ... html = in_handle.read() + ... + >>> with open("myprositerecord.html", "w") as out_handle: + ... length = out_handle.write(html) + ... + >>> os.remove("myprositerecord.html") # tidy up + + For a non-existing key XXX, ExPASy returns an HTML-formatted page + containing this text: 'There is currently no PROSITE entry for' + """ + return _open(f"{cgi}?{id}") + + +def get_prosite_raw(id, cgi=None): + """Get a text handle to a raw PROSITE or PRODOC record at ExPASy. + + The cgi argument is deprecated due to changes in the ExPASy + website. + + >>> from Bio import ExPASy + >>> from Bio.ExPASy import Prosite + >>> with ExPASy.get_prosite_raw('PS00001') as handle: + ... record = Prosite.read(handle) + ... + >>> print(record.accession) + PS00001 + + This function raises a ValueError if the identifier does not exist: + + >>> handle = ExPASy.get_prosite_raw("DOES_NOT_EXIST") + Traceback (most recent call last): + ... + ValueError: Failed to find entry 'DOES_NOT_EXIST' on ExPASy + + """ + try: + handle = _open(f"https://prosite.expasy.org/{id}.txt") + except HTTPError as exception: + if exception.code == 404: + raise ValueError("Failed to find entry '%s' on ExPASy" % id) from None + else: + raise + # This has happened historically, redirected to main page: + if handle.url == "https://www.expasy.org/": + raise ValueError(f"Failed to find entry '{id}' on ExPASy") from None + return handle + + +def get_sprot_raw(id): + """Get a text handle to a raw SwissProt entry at ExPASy. + + For an ID of XXX, fetches http://www.uniprot.org/uniprot/XXX.txt + (as per the https://www.expasy.org/expasy_urls.html documentation). + + >>> from Bio import ExPASy + >>> from Bio import SwissProt + >>> with ExPASy.get_sprot_raw("O23729") as handle: + ... record = SwissProt.read(handle) + ... + >>> print(record.entry_name) + CHS3_BROFI + + This function raises a ValueError if the identifier does not exist: + + >>> ExPASy.get_sprot_raw("DOES_NOT_EXIST") + Traceback (most recent call last): + ... + ValueError: Failed to find SwissProt entry 'DOES_NOT_EXIST' + + """ + try: + handle = _open(f"http://www.uniprot.org/uniprot/{id}.txt") + except HTTPError as exception: + if exception.code in (400, 404): + raise ValueError(f"Failed to find SwissProt entry '{id}'") from None + else: + raise + return handle + + +def _open(url): + """Open URL and convert to text assuming UTF-8 encoding (PRIVATE).""" + handle = urlopen(url) + text_handle = io.TextIOWrapper(handle, encoding="UTF-8") + text_handle.url = handle.url + return text_handle diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/cellosaurus.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/cellosaurus.py new file mode 100644 index 0000000000000000000000000000000000000000..53c19b1f6e0c72586688867cb7f2fbda88cf84cc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/cellosaurus.py @@ -0,0 +1,208 @@ +# Copyright 2016 by Stephen Marshall. 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. + +"""Parser for the cellosaurus.txt file from ExPASy. + +See https://web.expasy.org/cellosaurus/ + +Tested with the release of Version 18 (July 2016). + +Functions: + - read Reads a file containing one cell line entry + - parse Reads a file containing multiple cell line entries + +Classes: + - Record Holds cell line data. + +Examples +-------- +This example downloads the Cellosaurus database and parses it. Note that +urlopen returns a stream of bytes, while the parser expects a stream of plain +string, so we use TextIOWrapper to convert bytes to string using the UTF-8 +encoding. This is not needed if you download the cellosaurus.txt file in +advance and open it (see the comment below). + + >>> from urllib.request import urlopen + >>> from io import TextIOWrapper + >>> from Bio.ExPASy import cellosaurus + >>> url = "ftp://ftp.expasy.org/databases/cellosaurus/cellosaurus.txt" + >>> bytestream = urlopen(url) + >>> textstream = TextIOWrapper(bytestream, "UTF-8") + >>> # alternatively, use + >>> # textstream = open("cellosaurus.txt") + >>> # if you downloaded the cellosaurus.txt file in advance. + >>> records = cellosaurus.parse(textstream) + >>> for record in records: + ... if 'Homo sapiens' in record['OX'][0]: + ... print(record['ID']) # doctest:+ELLIPSIS + ... + #15310-LN + #W7079 + (L)PC6 + 0.5alpha + ... + +""" + + +def parse(handle): + """Parse cell line records. + + This function is for parsing cell line files containing multiple + records. + + Arguments: + - handle - handle to the file. + + """ + while True: + record = __read(handle) + if not record: + break + yield record + + +def read(handle): + """Read one cell line record. + + This function is for parsing cell line files containing + exactly one record. + + Arguments: + - handle - handle to the file. + + """ + record = __read(handle) + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one cell line record found") + return record + + +class Record(dict): + """Holds information from an ExPASy Cellosaurus record as a Python dictionary. + + Each record contains the following keys: + + ========= ============================== ======================= + Line code Content Occurrence in an entry + ========= ============================== ======================= + ID Identifier (cell line name) Once; starts an entry + AC Accession (CVCL_xxxx) Once + AS Secondary accession number(s) Optional; once + SY Synonyms Optional; once + DR Cross-references Optional; once or more + RX References identifiers Optional: once or more + WW Web pages Optional; once or more + CC Comments Optional; once or more + ST STR profile data Optional; twice or more + DI Diseases Optional; once or more + OX Species of origin Once or more + HI Hierarchy Optional; once or more + OI Originate from same individual Optional; once or more + SX Sex of cell Optional; once + AG Age of donor at sampling Optional; once + CA Category Once + DT Date (entry history) Once + // Terminator Once; ends an entry + ========= ============================== ======================= + + """ + + def __init__(self): + """Initialize the class.""" + dict.__init__(self) + self["ID"] = "" + self["AC"] = "" + self["AS"] = "" + self["SY"] = "" + self["DR"] = [] + self["RX"] = [] + self["WW"] = [] + self["CC"] = [] + self["ST"] = [] + self["DI"] = [] + self["OX"] = [] + self["HI"] = [] + self["OI"] = [] + self["SX"] = "" + self["AG"] = "" + self["CA"] = "" + self["DT"] = "" + + def __repr__(self): + """Return the canonical string representation of the Record object.""" + if self["ID"]: + if self["AC"]: + return f"{self.__class__.__name__} ({self['ID']}, {self['AC']})" + else: + return f"{self.__class__.__name__} ({self['ID']})" + else: + return f"{self.__class__.__name__} ( )" + + def __str__(self): + """Return a readable string representation of the Record object.""" + output = "ID: " + self["ID"] + output += " AC: " + self["AC"] + output += " AS: " + self["AS"] + output += " SY: " + self["SY"] + output += " DR: " + repr(self["DR"]) + output += " RX: " + repr(self["RX"]) + output += " WW: " + repr(self["WW"]) + output += " CC: " + repr(self["CC"]) + output += " ST: " + repr(self["ST"]) + output += " DI: " + repr(self["DI"]) + output += " OX: " + repr(self["OX"]) + output += " HI: " + repr(self["HI"]) + output += " OI: " + repr(self["OI"]) + output += " SX: " + self["SX"] + output += " AG: " + self["AG"] + output += " CA: " + self["CA"] + output += " DT: " + self["DT"] + return output + + +# Everything below is private + + +def __read(handle): + record = None + + for line in handle: + key, value = line[:2], line[5:].rstrip() + if key == "ID": + record = Record() + record["ID"] = value + elif key in ["AC", "AS", "SY", "SX", "AG", "CA", "DT"]: + record[key] += value + elif key in [ + # just append to the fields defined as lists, not to strings + "RX", + "WW", + "CC", + "ST", + "DI", + "OX", + "HI", + "OI", + ]: + record[key].append(value) + elif key == "DR": + k, v = value.split(";") + record["DR"].append((k.strip(), v.strip())) + elif key == "//": + if record: + return record + else: + continue + if record: + raise ValueError("Unexpected end of stream") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/File.py b/.venv_haddock/lib/python3.12/site-packages/Bio/File.py new file mode 100644 index 0000000000000000000000000000000000000000..d89a0d6d0dae2e1cef23dd91d22187aec9eac718 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/File.py @@ -0,0 +1,626 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# Copyright 2009-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. +"""Code for more fancy file handles. + +Bio.File defines private classes used in Bio.SeqIO and Bio.SearchIO for +indexing files. These are not intended for direct use. +""" + +import collections.abc +import contextlib +import itertools +import os +from abc import ABC +from abc import abstractmethod + +try: + import sqlite3 +except ImportError: + # May be missing if Python was compiled from source without its dependencies + sqlite3 = None # type: ignore + + +@contextlib.contextmanager +def as_handle(handleish, mode="r", **kwargs): + r"""Context manager to ensure we are using a handle. + + Context manager for arguments that can be passed to SeqIO and AlignIO read, write, + and parse methods: either file objects or path-like objects (strings, pathlib.Path + instances, or more generally, anything that can be handled by the builtin 'open' + function). + + When given a path-like object, returns an open file handle to that path, with provided + mode, which will be closed when the manager exits. + + All other inputs are returned, and are *not* closed. + + Arguments: + - handleish - Either a file handle or path-like object (anything which can be + passed to the builtin 'open' function, such as str, bytes, + pathlib.Path, and os.DirEntry objects) + - mode - Mode to open handleish (used only if handleish is a string) + - kwargs - Further arguments to pass to open(...) + + Examples + -------- + >>> from Bio import File + >>> import os + >>> with File.as_handle('seqs.fasta', 'w') as fp: + ... fp.write('>test\nACGT') + ... + 10 + >>> fp.closed + True + + >>> handle = open('seqs.fasta', 'w') + >>> with File.as_handle(handle) as fp: + ... fp.write('>test\nACGT') + ... + 10 + >>> fp.closed + False + >>> fp.close() + >>> os.remove("seqs.fasta") # tidy up + + """ + try: + with open(handleish, mode, **kwargs) as fp: + yield fp + except TypeError: + yield handleish + + +def _open_for_random_access(filename): + """Open a file in binary mode, spot if it is BGZF format etc (PRIVATE). + + This functionality is used by the Bio.SeqIO and Bio.SearchIO index + and index_db functions. + + If the file is gzipped but not BGZF, a specific ValueError is raised. + """ + handle = open(filename, "rb") + magic = handle.read(2) + handle.seek(0) + + if magic == b"\x1f\x8b": + # This is a gzipped file, but is it BGZF? + from . import bgzf + + try: + # If it is BGZF, we support that + return bgzf.BgzfReader(mode="rb", fileobj=handle) + except ValueError as e: + assert "BGZF" in str(e) + # Not a BGZF file after all, + handle.close() + raise ValueError( + "Gzipped files are not suitable for indexing, " + "please use BGZF (blocked gzip format) instead." + ) from None + + return handle + + +# The rest of this file defines code used in Bio.SeqIO and Bio.SearchIO +# for indexing + + +class _IndexedSeqFileProxy(ABC): + """Abstract base class for file format specific random access (PRIVATE). + + This is subclasses in both Bio.SeqIO for indexing as SeqRecord + objects, and in Bio.SearchIO for indexing QueryResult objects. + + Subclasses for each file format should define '__iter__', 'get' + and optionally 'get_raw' methods. + """ + + @abstractmethod + def __iter__(self): + """Return (identifier, offset, length in bytes) tuples. + + The length can be zero where it is not implemented or not + possible for a particular file format. + """ + raise NotImplementedError + + @abstractmethod + def get(self, offset): + """Return parsed object for this entry.""" + # Most file formats with self contained records can be handled by + # parsing StringIO(self.get_raw(offset).decode()) + raise NotImplementedError + + def get_raw(self, offset): + """Return the raw record from the file as a bytes string (if implemented). + + If the key is not found, a KeyError exception is raised. + + This may not have been implemented for all file formats. + """ + # Should be done by each sub-class (if possible) + raise NotImplementedError("Not available for this file format.") + + +class _IndexedSeqFileDict(collections.abc.Mapping): + """Read only dictionary interface to a sequential record file. + + This code is used in both Bio.SeqIO for indexing as SeqRecord + objects, and in Bio.SearchIO for indexing QueryResult objects. + + Keeps the keys and associated file offsets in memory, reads the file + to access entries as objects parsing them on demand. This approach + is memory limited, but will work even with millions of records. + + Note duplicate keys are not allowed. If this happens, a ValueError + exception is raised. + + As used in Bio.SeqIO, by default the SeqRecord's id string is used + as the dictionary key. In Bio.SearchIO, the query's id string is + used. This can be changed by supplying an optional key_function, + a callback function which will be given the record id and must + return the desired key. For example, this allows you to parse + NCBI style FASTA identifiers, and extract the GI number to use + as the dictionary key. + + Note that this dictionary is essentially read only. You cannot + add or change values, pop values, nor clear the dictionary. + """ + + def __init__(self, random_access_proxy, key_function, repr, obj_repr): + """Initialize the class.""" + # Use key_function=None for default value + self._proxy = random_access_proxy + self._key_function = key_function + self._repr = repr + self._obj_repr = obj_repr + self._cached_prev_record = (None, None) # (key, record) + if key_function: + offset_iter = ( + (key_function(key), offset, length) + for (key, offset, length) in random_access_proxy + ) + else: + offset_iter = random_access_proxy + offsets = {} + for key, offset, length in offset_iter: + # Note - we don't store the length because I want to minimise the + # memory requirements. With the SQLite backend the length is kept + # and is used to speed up the get_raw method (by about 3 times). + # The length should be provided by all the current backends except + # SFF where there is an existing Roche index we can reuse (very fast + # but lacks the record lengths) + # assert length or format in ["sff", "sff-trim"], \ + # "%s at offset %i given length %r (%s format %s)" \ + # % (key, offset, length, filename, format) + if key in offsets: + self._proxy._handle.close() + raise ValueError(f"Duplicate key '{key}'") + else: + offsets[key] = offset + self._offsets = offsets + + def __repr__(self): + """Return a string representation of the File object.""" + return self._repr + + def __str__(self): + """Create a string representation of the File object.""" + # TODO - How best to handle the __str__ for SeqIO and SearchIO? + if self: + return f"{{{list(self.keys())[0]!r} : {self._obj_repr}(...), ...}}" + else: + return "{}" + + def __len__(self): + """Return the number of records.""" + return len(self._offsets) + + def __iter__(self): + """Iterate over the keys.""" + return iter(self._offsets) + + def __getitem__(self, key): + """Return record for the specified key. + + As an optimization when repeatedly asked to look up the same record, + the key and record are cached so that if the *same* record is + requested next time, it can be returned without going to disk. + """ + if key == self._cached_prev_record[0]: + return self._cached_prev_record[1] + # Pass the offset to the proxy + record = self._proxy.get(self._offsets[key]) + if self._key_function: + key2 = self._key_function(record.id) + else: + key2 = record.id + if key != key2: + raise ValueError(f"Key did not match ({key} vs {key2})") + self._cached_prev_record = (key, record) + return record + + def get_raw(self, key): + """Return the raw record from the file as a bytes string. + + If the key is not found, a KeyError exception is raised. + """ + # Pass the offset to the proxy + return self._proxy.get_raw(self._offsets[key]) + + def close(self): + """Close the file handle being used to read the data. + + Once called, further use of the index won't work. The sole purpose + of this method is to allow explicit handle closure - for example + if you wish to delete the file, on Windows you must first close + all open handles to that file. + """ + self._proxy._handle.close() + + +class _SQLiteManySeqFilesDict(_IndexedSeqFileDict): + """Read only dictionary interface to many sequential record files. + + This code is used in both Bio.SeqIO for indexing as SeqRecord + objects, and in Bio.SearchIO for indexing QueryResult objects. + + Keeps the keys, file-numbers and offsets in an SQLite database. To access + a record by key, reads from the offset in the appropriate file and then + parses the record into an object. + + There are OS limits on the number of files that can be open at once, + so a pool are kept. If a record is required from a closed file, then + one of the open handles is closed first. + """ + + def __init__( + self, + index_filename, + filenames, + proxy_factory, + fmt, + key_function, + repr, + max_open=10, + ): + """Initialize the class.""" + # TODO? - Don't keep filename list in memory (just in DB)? + # Should save a chunk of memory if dealing with 1000s of files. + # Furthermore could compare a generator to the DB on reloading + # (no need to turn it into a list) + + if sqlite3 is None: + # Python was compiled without sqlite3 support + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Python was compiled without the sqlite3 module" + ) + if filenames is not None: + filenames = list(filenames) # In case it was a generator + + # Cache the arguments as private variables + self._index_filename = index_filename + self._filenames = filenames + self._format = fmt + self._key_function = key_function + self._proxy_factory = proxy_factory + self._repr = repr + self._max_open = max_open + self._proxies = {} + + # Note if using SQLite :memory: trick index filename, this will + # give $PWD as the relative path (which is fine). + self._relative_path = os.path.abspath(os.path.dirname(index_filename)) + + if os.path.isfile(index_filename): + self._load_index() + else: + self._build_index() + + def _load_index(self): + """Call from __init__ to reuse an existing index (PRIVATE).""" + index_filename = self._index_filename + relative_path = self._relative_path + filenames = self._filenames + fmt = self._format + proxy_factory = self._proxy_factory + + con = sqlite3.dbapi2.connect(index_filename, check_same_thread=False) + self._con = con + # Check the count... + try: + (count,) = con.execute( + "SELECT value FROM meta_data WHERE key=?;", ("count",) + ).fetchone() + self._length = int(count) + if self._length == -1: + con.close() + raise ValueError("Unfinished/partial database") from None + + # use MAX(_ROWID_) to obtain the number of sequences in the database + # using COUNT(key) is quite slow in SQLITE + # (https://stackoverflow.com/questions/8988915/sqlite-count-slow-on-big-tables) + (count,) = con.execute("SELECT MAX(_ROWID_) FROM offset_data;").fetchone() + if self._length != int(count): + con.close() + raise ValueError( + "Corrupt database? %i entries not %i" % (int(count), self._length) + ) from None + (self._format,) = con.execute( + "SELECT value FROM meta_data WHERE key=?;", ("format",) + ).fetchone() + if fmt and fmt != self._format: + con.close() + raise ValueError( + f"Index file says format {self._format}, not {fmt}" + ) from None + try: + (filenames_relative_to_index,) = con.execute( + "SELECT value FROM meta_data WHERE key=?;", + ("filenames_relative_to_index",), + ).fetchone() + filenames_relative_to_index = ( + filenames_relative_to_index.upper() == "TRUE" + ) + except TypeError: + # Original behaviour, assume if meta_data missing + filenames_relative_to_index = False + self._filenames = [ + row[0] + for row in con.execute( + "SELECT name FROM file_data ORDER BY file_number;" + ).fetchall() + ] + if filenames_relative_to_index: + # Not implicitly relative to $PWD, explicitly relative to index file + relative_path = os.path.abspath(os.path.dirname(index_filename)) + tmp = [] + for f in self._filenames: + if os.path.isabs(f): + tmp.append(f) + else: + # Would be stored with Unix / path separator, so convert + # it to the local OS path separator here: + tmp.append( + os.path.join(relative_path, f.replace("/", os.path.sep)) + ) + self._filenames = tmp + del tmp + if filenames and len(filenames) != len(self._filenames): + con.close() + raise ValueError( + "Index file says %i files, not %i" + % (len(self._filenames), len(filenames)) + ) from None + if filenames and filenames != self._filenames: + for old, new in zip(self._filenames, filenames): + # Want exact match (after making relative to the index above) + if os.path.abspath(old) != os.path.abspath(new): + con.close() + if filenames_relative_to_index: + raise ValueError( + "Index file has different filenames, e.g. %r != %r" + % (os.path.abspath(old), os.path.abspath(new)) + ) from None + else: + raise ValueError( + "Index file has different filenames " + "[This is an old index where any relative paths " + "were relative to the original working directory]. " + "e.g. %r != %r" + % (os.path.abspath(old), os.path.abspath(new)) + ) from None + # Filenames are equal (after imposing abspath) + except sqlite3.OperationalError as err: + con.close() + raise ValueError(f"Not a Biopython index database? {err}") from None + # Now we have the format (from the DB if not given to us), + if not proxy_factory(self._format): + con.close() + raise ValueError(f"Unsupported format '{self._format}'") + + def _build_index(self): + """Call from __init__ to create a new index (PRIVATE).""" + index_filename = self._index_filename + relative_path = self._relative_path + filenames = self._filenames + fmt = self._format + key_function = self._key_function + proxy_factory = self._proxy_factory + max_open = self._max_open + random_access_proxies = self._proxies + + if not fmt or not filenames: + raise ValueError( + f"Filenames to index and format required to build {index_filename!r}" + ) + if not proxy_factory(fmt): + raise ValueError(f"Unsupported format '{fmt}'") + # Create the index + con = sqlite3.dbapi2.connect(index_filename) + self._con = con + # print("Creating index") + # Sqlite PRAGMA settings for speed + con.execute("PRAGMA synchronous=OFF") + con.execute("PRAGMA locking_mode=EXCLUSIVE") + # Don't index the key column until the end (faster) + # con.execute("CREATE TABLE offset_data (key TEXT PRIMARY KEY, " + # "offset INTEGER);") + con.execute("CREATE TABLE meta_data (key TEXT, value TEXT);") + con.execute("INSERT INTO meta_data (key, value) VALUES (?,?);", ("count", -1)) + con.execute("INSERT INTO meta_data (key, value) VALUES (?,?);", ("format", fmt)) + con.execute( + "INSERT INTO meta_data (key, value) VALUES (?,?);", + ("filenames_relative_to_index", "True"), + ) + # TODO - Record the file size and modified date? + con.execute("CREATE TABLE file_data (file_number INTEGER, name TEXT);") + con.execute( + "CREATE TABLE offset_data (key TEXT, " + "file_number INTEGER, offset INTEGER, length INTEGER);" + ) + count = 0 + for file_index, filename in enumerate(filenames): + # Default to storing as an absolute path, + f = os.path.abspath(filename) + if not os.path.isabs(filename) and not os.path.isabs(index_filename): + # Since user gave BOTH filename & index as relative paths, + # we will store this relative to the index file even though + # if it may now start ../ (meaning up a level) + # Note for cross platform use (e.g. shared drive over SAMBA), + # convert any Windows slash into Unix style for rel paths. + f = os.path.relpath(filename, relative_path).replace(os.path.sep, "/") + elif (os.path.dirname(os.path.abspath(filename)) + os.path.sep).startswith( + relative_path + os.path.sep + ): + # Since sequence file is in same directory or sub directory, + # might as well make this into a relative path: + f = os.path.relpath(filename, relative_path).replace(os.path.sep, "/") + assert not f.startswith("../"), f + # print("DEBUG - storing %r as [%r] %r" % (filename, relative_path, f)) + con.execute( + "INSERT INTO file_data (file_number, name) VALUES (?,?);", + (file_index, f), + ) + random_access_proxy = proxy_factory(fmt, filename) + if key_function: + offset_iter = ( + (key_function(key), file_index, offset, length) + for (key, offset, length) in random_access_proxy + ) + else: + offset_iter = ( + (key, file_index, offset, length) + for (key, offset, length) in random_access_proxy + ) + while True: + batch = list(itertools.islice(offset_iter, 100)) + if not batch: + break + # print("Inserting batch of %i offsets, %s ... %s" + # % (len(batch), batch[0][0], batch[-1][0])) + con.executemany( + "INSERT INTO offset_data (key,file_number,offset,length) VALUES (?,?,?,?);", + batch, + ) + con.commit() + count += len(batch) + if len(random_access_proxies) < max_open: + random_access_proxies[file_index] = random_access_proxy + else: + random_access_proxy._handle.close() + self._length = count + # print("About to index %i entries" % count) + try: + con.execute( + "CREATE UNIQUE INDEX IF NOT EXISTS key_index ON offset_data(key);" + ) + except sqlite3.IntegrityError as err: + self._proxies = random_access_proxies + self.close() + con.close() + raise ValueError(f"Duplicate key? {err}") from None + con.execute("PRAGMA locking_mode=NORMAL") + con.execute("UPDATE meta_data SET value = ? WHERE key = ?;", (count, "count")) + con.commit() + # print("Index created") + + def __repr__(self): + return self._repr + + def __contains__(self, key): + return bool( + self._con.execute( + "SELECT key FROM offset_data WHERE key=?;", (key,) + ).fetchone() + ) + + def __len__(self): + """Return the number of records indexed.""" + return self._length + # return self._con.execute("SELECT COUNT(key) FROM offset_data;").fetchone()[0] + + def __iter__(self): + """Iterate over the keys.""" + for row in self._con.execute( + "SELECT key FROM offset_data ORDER BY file_number, offset;" + ): + yield str(row[0]) + + def __getitem__(self, key): + """Return record for the specified key.""" + # Pass the offset to the proxy + row = self._con.execute( + "SELECT file_number, offset FROM offset_data WHERE key=?;", (key,) + ).fetchone() + if not row: + raise KeyError + file_number, offset = row + proxies = self._proxies + if file_number in proxies: + record = proxies[file_number].get(offset) + else: + if len(proxies) >= self._max_open: + # Close an old handle... + proxies.popitem()[1]._handle.close() + # Open a new handle... + proxy = self._proxy_factory(self._format, self._filenames[file_number]) + record = proxy.get(offset) + proxies[file_number] = proxy + if self._key_function: + key2 = self._key_function(record.id) + else: + key2 = record.id + if key != key2: + raise ValueError(f"Key did not match ({key} vs {key2})") + return record + + def get_raw(self, key): + """Return the raw record from the file as a bytes string. + + If the key is not found, a KeyError exception is raised. + """ + # Pass the offset to the proxy + row = self._con.execute( + "SELECT file_number, offset, length FROM offset_data WHERE key=?;", (key,) + ).fetchone() + if not row: + raise KeyError + file_number, offset, length = row + proxies = self._proxies + if file_number in proxies: + if length: + # Shortcut if we have the length + h = proxies[file_number]._handle + h.seek(offset) + return h.read(length) + else: + return proxies[file_number].get_raw(offset) + else: + # This code is duplicated from __getitem__ to avoid a function call + if len(proxies) >= self._max_open: + # Close an old handle... + proxies.popitem()[1]._handle.close() + # Open a new handle... + proxy = self._proxy_factory(self._format, self._filenames[file_number]) + proxies[file_number] = proxy + if length: + # Shortcut if we have the length + h = proxy._handle + h.seek(offset) + return h.read(length) + else: + return proxy.get_raw(offset) + + def close(self): + """Close any open file handles.""" + proxies = self._proxies + while proxies: + proxies.popitem()[1]._handle.close() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._Record.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._Record.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._Record.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._Scanner.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._Scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._Scanner.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._utils.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/._utils.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Record.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Record.py new file mode 100644 index 0000000000000000000000000000000000000000..b96da8bef4a5b1967d70ec7c35e931d20a95fccc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Record.py @@ -0,0 +1,669 @@ +# 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. +# + +"""Hold GenBank data in a straightforward format. + +Classes: + - Record - All of the information in a GenBank record. + - Reference - hold reference data for a record. + - Feature - Hold the information in a Feature Table. + - Qualifier - Qualifiers on a Feature. + +""" + +import Bio.GenBank + + +def _wrapped_genbank(information, indent, wrap_space=1, split_char=" "): + """Write a line of GenBank info that can wrap over multiple lines (PRIVATE). + + This takes a line of information which can potentially wrap over + multiple lines, and breaks it up with carriage returns and + indentation so it fits properly into a GenBank record. + + Arguments: + - information - The string holding the information we want + wrapped in GenBank method. + - indent - The indentation on the lines we are writing. + - wrap_space - Whether or not to wrap only on spaces in the + information. + - split_char - A specific character to split the lines on. By default + spaces are used. + + """ + info_length = Record.GB_LINE_LENGTH - indent + + if not information: + # GenBank files use "." for missing data + return ".\n" + + if wrap_space: + info_parts = information.split(split_char) + else: + cur_pos = 0 + info_parts = [] + while cur_pos < len(information): + info_parts.append(information[cur_pos : cur_pos + info_length]) + cur_pos += info_length + + # first get the information string split up by line + output_parts = [] + cur_part = "" + for info_part in info_parts: + if len(cur_part) + 1 + len(info_part) > info_length: + if cur_part: + if split_char != " ": + cur_part += split_char + output_parts.append(cur_part) + cur_part = info_part + else: + if cur_part == "": + cur_part = info_part + else: + cur_part += split_char + info_part + + # add the last bit of information to the output + if cur_part: + output_parts.append(cur_part) + + # now format the information string for return + output_info = output_parts[0] + "\n" + for output_part in output_parts[1:]: + output_info += " " * indent + output_part + "\n" + + return output_info + + +def _indent_genbank(information, indent): + """Write out information with the specified indent (PRIVATE). + + Unlike _wrapped_genbank, this function makes no attempt to wrap + lines -- it assumes that the information already has newlines in the + appropriate places, and will add the specified indent to the start of + each line. + """ + # split the info into lines based on line breaks + info_parts = information.split("\n") + + # the first line will have no indent + output_info = info_parts[0] + "\n" + for info_part in info_parts[1:]: + output_info += " " * indent + info_part + "\n" + + return output_info + + +class Record: + """Hold GenBank information in a format similar to the original record. + + The Record class is meant to make data easy to get to when you are + just interested in looking at GenBank data. + + Attributes: + - locus - The name specified after the LOCUS keyword in the GenBank + record. This may be the accession number, or a clone id or something else. + - size - The size of the record. + - residue_type - The type of residues making up the sequence in this + record. Normally something like RNA, DNA or PROTEIN, but may be as + esoteric as 'ss-RNA circular'. + - data_file_division - The division this record is stored under in + GenBank (ie. PLN -> plants; PRI -> humans, primates; BCT -> bacteria...) + - date - The date of submission of the record, in a form like '28-JUL-1998' + - accession - list of all accession numbers for the sequence. + - nid - Nucleotide identifier number. + - pid - Proteint identifier number + - version - The accession number + version (ie. AB01234.2) + - db_source - Information about the database the record came from + - gi - The NCBI gi identifier for the record. + - keywords - A list of keywords related to the record. + - segment - If the record is one of a series, this is info about which + segment this record is (something like '1 of 6'). + - source - The source of material where the sequence came from. + - organism - The genus and species of the organism (ie. 'Homo sapiens') + - taxonomy - A listing of the taxonomic classification of the organism, + starting general and getting more specific. + - references - A list of Reference objects. + - comment - Text with any kind of comment about the record. + - features - A listing of Features making up the feature table. + - base_counts - A string with the counts of bases for the sequence. + - origin - A string specifying info about the origin of the sequence. + - sequence - A string with the sequence itself. + - contig - A string of location information for a CONTIG in a RefSeq file + - project - The genome sequencing project numbers + (will be replaced by the dblink cross-references in 2009). + - dblinks - The genome sequencing project number(s) and other links. + (will replace the project information in 2009). + + """ + + # constants for outputting GenBank information + GB_LINE_LENGTH = 79 + GB_BASE_INDENT = 12 + GB_FEATURE_INDENT = 21 + GB_INTERNAL_INDENT = 2 + GB_OTHER_INTERNAL_INDENT = 3 + GB_FEATURE_INTERNAL_INDENT = 5 + GB_SEQUENCE_INDENT = 9 + + BASE_FORMAT = "%-" + str(GB_BASE_INDENT) + "s" + INTERNAL_FORMAT = ( + " " * GB_INTERNAL_INDENT + "%-" + str(GB_BASE_INDENT - GB_INTERNAL_INDENT) + "s" + ) + OTHER_INTERNAL_FORMAT = ( + " " * GB_OTHER_INTERNAL_INDENT + + "%-" + + str(GB_BASE_INDENT - GB_OTHER_INTERNAL_INDENT) + + "s" + ) + + BASE_FEATURE_FORMAT = "%-" + str(GB_FEATURE_INDENT) + "s" + INTERNAL_FEATURE_FORMAT = ( + " " * GB_FEATURE_INTERNAL_INDENT + + "%-" + + str(GB_FEATURE_INDENT - GB_FEATURE_INTERNAL_INDENT) + + "s" + ) + SEQUENCE_FORMAT = "%" + str(GB_SEQUENCE_INDENT) + "s" + + def __init__(self): + """Initialize the class.""" + self.accession = [] + self.base_counts = "" + self.comment = "" + self.contig = "" + self.data_file_division = "" + self.date = "" + self.db_source = "" + self.dblinks = [] + self.definition = "" + self.features = [] + self.gi = "" + self.keywords = [] + self.locus = "" + self.molecule_type = "" + self.nid = "" + self.organism = "" + self.origin = "" + self.pid = "" + self.primary = [] + self.projects = [] + self.references = [] + self.residue_type = "" + self.segment = "" + self.sequence = "" + self.size = "" + self.source = "" + self.taxonomy = [] + self.topology = "" + self.version = "" + self.wgs = "" + self.wgs_scafld = [] + + def __str__(self): + """Provide a GenBank formatted output option for a Record. + + The objective of this is to provide an easy way to read in a GenBank + record, modify it somehow, and then output it in 'GenBank format.' + We are striving to make this work so that a parsed Record that is + output using this function will look exactly like the original + record. + + Much of the output is based on format description info at: + + ftp://ncbi.nlm.nih.gov/genbank/gbrel.txt + """ + output = self._locus_line() + output += self._definition_line() + output += self._accession_line() + output += self._version_line() + output += self._project_line() + output += self._dblink_line() + output += self._nid_line() + output += self._pid_line() + output += self._keywords_line() + output += self._db_source_line() + output += self._segment_line() + output += self._source_line() + output += self._organism_line() + for reference in self.references: + output += str(reference) + output += self._comment_line() + output += self._features_line() + for feature in self.features: + output += str(feature) + output += self._base_count_line() + output += self._origin_line() + output += self._sequence_line() + output += self._wgs_line() + output += self._wgs_scafld_line() + output += self._contig_line() + output += "//" + return output + + def _locus_line(self): + """Provide the output string for the LOCUS line (PRIVATE).""" + output = "LOCUS" + output += " " * 7 # 6-12 spaces + output += "%-9s" % self.locus + output += " " # 22 space + output += "%7s" % self.size + if "PROTEIN" in self.residue_type: + output += " aa" + else: + output += " bp " + + # treat circular types differently, since they'll have long residue + # types + if "circular" in self.residue_type: + output += "%17s" % self.residue_type + # second case: ss-DNA types of records + elif "-" in self.residue_type: + output += "%7s" % self.residue_type + output += " " * 10 # spaces for circular + else: + output += " " * 3 # spaces for stuff like ss- + output += "%-4s" % self.residue_type + output += " " * 10 # spaces for circular + + output += " " * 2 + output += "%3s" % self.data_file_division + output += " " * 7 # spaces for 56-63 + output += "%11s" % self.date + output += "\n" + return output + + def _definition_line(self): + """Provide output for the DEFINITION line (PRIVATE).""" + output = Record.BASE_FORMAT % "DEFINITION" + output += _wrapped_genbank(self.definition + ".", Record.GB_BASE_INDENT) + return output + + def _accession_line(self): + """Output for the ACCESSION line (PRIVATE).""" + if self.accession: + output = Record.BASE_FORMAT % "ACCESSION" + + acc_info = "" + for accession in self.accession: + acc_info += f"{accession} " + # strip off an extra space at the end + acc_info = acc_info.rstrip() + output += _wrapped_genbank(acc_info, Record.GB_BASE_INDENT) + else: + output = "" + + return output + + def _version_line(self): + """Output for the VERSION line (PRIVATE).""" + if self.version: + output = Record.BASE_FORMAT % "VERSION" + output += self.version + output += " GI:" + output += f"{self.gi}\n" + else: + output = "" + return output + + def _project_line(self): + output = "" + if len(self.projects) > 0: + output = Record.BASE_FORMAT % "PROJECT" + output += f"{' '.join(self.projects)}\n" + return output + + def _dblink_line(self): + output = "" + if len(self.dblinks) > 0: + output = Record.BASE_FORMAT % "DBLINK" + dblink_info = "\n".join(self.dblinks) + output += _wrapped_genbank(dblink_info, Record.GB_BASE_INDENT) + return output + + def _nid_line(self): + """Output for the NID line. Use of NID is obsolete in GenBank files (PRIVATE).""" + if self.nid: + output = Record.BASE_FORMAT % "NID" + output += f"{self.nid}\n" + else: + output = "" + return output + + def _pid_line(self): + """Output for PID line. Presumedly, PID usage is also obsolete (PRIVATE).""" + if self.pid: + output = Record.BASE_FORMAT % "PID" + output += f"{self.pid}\n" + else: + output = "" + return output + + def _keywords_line(self): + """Output for the KEYWORDS line (PRIVATE).""" + output = "" + if self.keywords: + output += Record.BASE_FORMAT % "KEYWORDS" + keyword_info = "" + for keyword in self.keywords: + keyword_info += f"{keyword}; " + # replace the ; at the end with a period + keyword_info = keyword_info[:-2] + keyword_info += "." + + output += _wrapped_genbank(keyword_info, Record.GB_BASE_INDENT) + + return output + + def _db_source_line(self): + """Output for DBSOURCE line (PRIVATE).""" + if self.db_source: + output = Record.BASE_FORMAT % "DBSOURCE" + output += f"{self.db_source}\n" + else: + output = "" + return output + + def _segment_line(self): + """Output for the SEGMENT line (PRIVATE).""" + output = "" + if self.segment: + output += Record.BASE_FORMAT % "SEGMENT" + output += _wrapped_genbank(self.segment, Record.GB_BASE_INDENT) + return output + + def _source_line(self): + """Output for SOURCE line on where the sample came from (PRIVATE).""" + output = Record.BASE_FORMAT % "SOURCE" + output += _wrapped_genbank(self.source, Record.GB_BASE_INDENT) + return output + + def _organism_line(self): + """Output for ORGANISM line with taxonomy info (PRIVATE).""" + output = Record.INTERNAL_FORMAT % "ORGANISM" + # Now that species names can be too long, this line can wrap (Bug 2591) + output += _wrapped_genbank(self.organism, Record.GB_BASE_INDENT) + output += " " * Record.GB_BASE_INDENT + taxonomy_info = "" + for tax in self.taxonomy: + taxonomy_info += f"{tax}; " + # replace the ; at the end with a period + taxonomy_info = taxonomy_info[:-2] + taxonomy_info += "." + output += _wrapped_genbank(taxonomy_info, Record.GB_BASE_INDENT) + + return output + + def _comment_line(self): + """Output for the COMMENT lines (PRIVATE).""" + output = "" + if self.comment: + output += Record.BASE_FORMAT % "COMMENT" + output += _indent_genbank(self.comment, Record.GB_BASE_INDENT) + return output + + def _features_line(self): + """Output for the FEATURES line (PRIVATE).""" + output = "" + if len(self.features) > 0: + output += Record.BASE_FEATURE_FORMAT % "FEATURES" + output += "Location/Qualifiers\n" + return output + + def _base_count_line(self): + """Output for the BASE COUNT line with base information (PRIVATE).""" + output = "" + if self.base_counts: + output += Record.BASE_FORMAT % "BASE COUNT " + # split up the base counts into their individual parts + count_parts = self.base_counts.split(" ") + while "" in count_parts: + count_parts.remove("") + # deal with the standard case, with a normal origin line + # like: 474 a 356 c 428 g 364 t + if len(count_parts) % 2 == 0: + while len(count_parts) > 0: + count_info = count_parts.pop(0) + count_type = count_parts.pop(0) + + output += f"{count_info:>7} {count_type}" + # deal with ugly ORIGIN lines like: + # 1311257 a2224835 c2190093 g1309889 t + # by just outputting the raw information + else: + output += self.base_counts + output += "\n" + return output + + def _origin_line(self): + """Output for the ORIGIN line (PRIVATE).""" + output = "" + # only output the ORIGIN line if we have a sequence + if self.sequence: + output += Record.BASE_FORMAT % "ORIGIN" + if self.origin: + output += _wrapped_genbank(self.origin, Record.GB_BASE_INDENT) + else: + output += "\n" + return output + + def _sequence_line(self): + """Output for all of the sequence (PRIVATE).""" + output = "" + if self.sequence: + cur_seq_pos = 0 + while cur_seq_pos < len(self.sequence): + output += Record.SEQUENCE_FORMAT % str(cur_seq_pos + 1) + + for section in range(6): + start_pos = cur_seq_pos + section * 10 + end_pos = start_pos + 10 + seq_section = self.sequence[start_pos:end_pos] + output += f" {seq_section.lower()}" + + # stop looping if we are out of sequence + if end_pos > len(self.sequence): + break + + output += "\n" + cur_seq_pos += 60 + return output + + def _wgs_line(self): + output = "" + if self.wgs: + output += Record.BASE_FORMAT % "WGS" + output += self.wgs + return output + + def _wgs_scafld_line(self): + output = "" + if self.wgs_scafld: + output += Record.BASE_FORMAT % "WGS_SCAFLD" + output += self.wgs_scafld + return output + + def _contig_line(self): + """Output for CONTIG location information from RefSeq (PRIVATE).""" + output = "" + if self.contig: + output += Record.BASE_FORMAT % "CONTIG" + output += _wrapped_genbank( + self.contig, Record.GB_BASE_INDENT, split_char="," + ) + return output + + +class Reference: + """Hold information from a GenBank reference. + + Attributes: + - number - The number of the reference in the listing of references. + - bases - The bases in the sequence the reference refers to. + - authors - String with all of the authors. + - consrtm - Consortium the authors belong to. + - title - The title of the reference. + - journal - Information about the journal where the reference appeared. + - medline_id - The medline id for the reference. + - pubmed_id - The pubmed_id for the reference. + - remark - Free-form remarks about the reference. + + """ + + def __init__(self): + """Initialize the class.""" + self.number = "" + self.bases = "" + self.authors = "" + self.consrtm = "" + self.title = "" + self.journal = "" + self.medline_id = "" + self.pubmed_id = "" + self.remark = "" + + def __str__(self): + """Convert the reference to a GenBank format string.""" + output = self._reference_line() + output += self._authors_line() + output += self._consrtm_line() + output += self._title_line() + output += self._journal_line() + output += self._medline_line() + output += self._pubmed_line() + output += self._remark_line() + + return output + + def _reference_line(self): + """Output for REFERENCE lines (PRIVATE).""" + output = Record.BASE_FORMAT % "REFERENCE" + if self.number: + if self.bases: + output += "%-3s" % self.number + output += f"{self.bases}" + else: + output += f"{self.number}" + + output += "\n" + return output + + def _authors_line(self): + """Output for AUTHORS information (PRIVATE).""" + output = "" + if self.authors: + output += Record.INTERNAL_FORMAT % "AUTHORS" + output += _wrapped_genbank(self.authors, Record.GB_BASE_INDENT) + return output + + def _consrtm_line(self): + """Output for CONSRTM information (PRIVATE).""" + output = "" + if self.consrtm: + output += Record.INTERNAL_FORMAT % "CONSRTM" + output += _wrapped_genbank(self.consrtm, Record.GB_BASE_INDENT) + return output + + def _title_line(self): + """Output for TITLE information (PRIVATE).""" + output = "" + if self.title: + output += Record.INTERNAL_FORMAT % "TITLE" + output += _wrapped_genbank(self.title, Record.GB_BASE_INDENT) + return output + + def _journal_line(self): + """Output for JOURNAL information (PRIVATE).""" + output = "" + if self.journal: + output += Record.INTERNAL_FORMAT % "JOURNAL" + output += _wrapped_genbank(self.journal, Record.GB_BASE_INDENT) + return output + + def _medline_line(self): + """Output for MEDLINE information (PRIVATE).""" + output = "" + if self.medline_id: + output += Record.INTERNAL_FORMAT % "MEDLINE" + output += self.medline_id + "\n" + return output + + def _pubmed_line(self): + """Output for PUBMED information (PRIVATE).""" + output = "" + if self.pubmed_id: + output += Record.OTHER_INTERNAL_FORMAT % "PUBMED" + output += self.pubmed_id + "\n" + return output + + def _remark_line(self): + """Output for REMARK information (PRIVATE).""" + output = "" + if self.remark: + output += Record.INTERNAL_FORMAT % "REMARK" + output += _wrapped_genbank(self.remark, Record.GB_BASE_INDENT) + return output + + +class Feature: + """Hold information about a Feature in the Feature Table of GenBank record. + + Attributes: + - key - The key name of the feature (ie. source) + - location - The string specifying the location of the feature. + - qualifiers - A list of Qualifier objects in the feature. + + """ + + def __init__(self, key="", location=""): + """Initialize the class.""" + self.key = key + self.location = location + self.qualifiers = [] + + def __repr__(self): + """Representation of the object for debugging or logging.""" + return f"Feature(key={self.key!r}, location={self.location!r})" + + def __str__(self): + """Return feature as a GenBank format string.""" + output = Record.INTERNAL_FEATURE_FORMAT % self.key + output += _wrapped_genbank( + self.location, Record.GB_FEATURE_INDENT, split_char="," + ) + for qualifier in self.qualifiers: + output += str(qualifier) + return output + + +class Qualifier: + """Hold information about a qualifier in a GenBank feature. + + Attributes: + - key - The key name of the qualifier (ie. /organism=) + - value - The value of the qualifier ("Dictyostelium discoideum"). + + """ + + def __init__(self, key="", value=""): + """Initialize the class.""" + self.key = key + self.value = value + + def __repr__(self): + """Representation of the object for debugging or logging.""" + return f"Qualifier(key={self.key!r}, value={self.value!r})" + + def __str__(self): + """Return feature qualifier as a GenBank format string.""" + output = " " * Record.GB_FEATURE_INDENT + # determine whether we can wrap on spaces + space_wrap = 1 + for no_space_key in Bio.GenBank._BaseGenBankConsumer.remove_space_keys: + if no_space_key in self.key: + space_wrap = 0 + # return double quotes as-is, leave it to the user to escape them + return output + _wrapped_genbank( + self.key + self.value, Record.GB_FEATURE_INDENT, space_wrap + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Scanner.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..7aaf38e5f2a537899978b6895b5ce02c66d82a81 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Scanner.py @@ -0,0 +1,1929 @@ +# Copyright 2007-2017 by Peter Cock. All rights reserved. +# Revisions copyright 2010 by Uri Laserson. 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. +"""Internal code for parsing GenBank and EMBL files (PRIVATE). + +This code is NOT intended for direct use. It provides a basic scanner +(for use with a event consumer such as Bio.GenBank._FeatureConsumer) +to parse a GenBank or EMBL file (with their shared INSDC feature table). + +It is used by Bio.GenBank to parse GenBank files +It is also used by Bio.SeqIO to parse GenBank and EMBL files + +Feature Table Documentation: + +- http://www.insdc.org/files/feature_table.html +- http://www.ncbi.nlm.nih.gov/projects/collab/FT/index.html +- ftp://ftp.ncbi.nih.gov/genbank/docs/ +""" +# 17-MAR-2009: added wgs, wgs_scafld for GenBank whole genome shotgun master records. +# These are GenBank files that summarize the content of a project, and provide lists of +# scaffold and contig files in the project. These will be in annotations['wgs'] and +# annotations['wgs_scafld']. These GenBank files do not have sequences. See +# http://groups.google.com/group/bionet.molbio.genbank/browse_thread/thread/51fb88bf39e7dc36 +# http://is.gd/nNgk +# for more details of this format, and an example. +# Added by Ying Huang & Iddo Friedberg + +import re +import sys +import warnings +from collections import defaultdict + +from Bio import BiopythonParserWarning +from Bio.File import as_handle +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class InsdcScanner: + """Basic functions for breaking up a GenBank/EMBL file into sub sections. + + The International Nucleotide Sequence Database Collaboration (INSDC) + between the DDBJ, EMBL, and GenBank. These organisations all use the + same "Feature Table" layout in their plain text flat file formats. + + However, the header and sequence sections of an EMBL file are very + different in layout to those produced by GenBank/DDBJ. + """ + + # These constants get redefined with sensible values in the sub classes: + RECORD_START = "XXX" # "LOCUS " or "ID " + HEADER_WIDTH = 3 # 12 or 5 + FEATURE_START_MARKERS = ["XXX***FEATURES***XXX"] + FEATURE_END_MARKERS = ["XXX***END FEATURES***XXX"] + FEATURE_QUALIFIER_INDENT = 0 + FEATURE_QUALIFIER_SPACER = "" + SEQUENCE_HEADERS = ["XXX"] # with right hand side spaces removed + + def __init__(self, debug=0): + """Initialize the class.""" + assert len(self.RECORD_START) == self.HEADER_WIDTH + for marker in self.SEQUENCE_HEADERS: + assert marker == marker.rstrip() + assert len(self.FEATURE_QUALIFIER_SPACER) == self.FEATURE_QUALIFIER_INDENT + self.debug = debug + self.handle = None + self.line = None + + def set_handle(self, handle): + """Set the handle attribute.""" + self.handle = handle + self.line = "" + + def find_start(self): + """Read in lines until find the ID/LOCUS line, which is returned. + + Any preamble (such as the header used by the NCBI on ``*.seq.gz`` archives) + will we ignored. + """ + while True: + if self.line: + line = self.line + self.line = "" + else: + line = self.handle.readline() + if not line: + if self.debug: + print("End of file") + return None + if isinstance(line[0], int): + # Same exception as for FASTQ files + raise ValueError("Is this handle in binary mode not text mode?") + if line[: self.HEADER_WIDTH] == self.RECORD_START: + if self.debug > 1: + print("Found the start of a record:\n" + line) + break + line = line.rstrip() + if line == "//": + if self.debug > 1: + print("Skipping // marking end of last record") + elif line == "": + if self.debug > 1: + print("Skipping blank line before record") + else: + # Ignore any header before the first ID/LOCUS line. + if self.debug > 1: + print("Skipping header line before record:\n" + line) + self.line = line + return line + + def parse_header(self): + """Return list of strings making up the header. + + New line characters are removed. + + Assumes you have just read in the ID/LOCUS line. + """ + if self.line[: self.HEADER_WIDTH] != self.RECORD_START: + raise ValueError("Not at start of record") + + header_lines = [] + while True: + line = self.handle.readline() + if not line: + raise ValueError("Premature end of line during sequence data") + line = line.rstrip() + if line in self.FEATURE_START_MARKERS: + if self.debug: + print("Found feature table") + break + # if line[:self.HEADER_WIDTH]==self.FEATURE_START_MARKER[:self.HEADER_WIDTH]: + # if self.debug : print("Found header table (?)") + # break + if line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + if self.debug: + print("Found start of sequence") + break + if line == "//": + raise ValueError("Premature end of sequence data marker '//' found") + header_lines.append(line) + self.line = line + return header_lines + + def parse_features(self, skip=False): + """Return list of tuples for the features (if present). + + Each feature is returned as a tuple (key, location, qualifiers) + where key and location are strings (e.g. "CDS" and + "complement(join(490883..490885,1..879))") while qualifiers + is a list of two string tuples (feature qualifier keys and values). + + Assumes you have already read to the start of the features table. + """ + if self.line.rstrip() not in self.FEATURE_START_MARKERS: + if self.debug: + print("Didn't find any feature table") + return [] + + while self.line.rstrip() in self.FEATURE_START_MARKERS: + self.line = self.handle.readline() + + features = [] + line = self.line + while True: + if not line: + raise ValueError("Premature end of line during features table") + if line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + if self.debug: + print("Found start of sequence") + break + line = line.rstrip() + if line == "//": + raise ValueError("Premature end of features table, marker '//' found") + if line in self.FEATURE_END_MARKERS: + if self.debug: + print("Found end of features") + line = self.handle.readline() + break + if line[2 : self.FEATURE_QUALIFIER_INDENT].strip() == "": + # This is an empty feature line between qualifiers. Empty + # feature lines within qualifiers are handled below (ignored). + line = self.handle.readline() + continue + if len(line) < self.FEATURE_QUALIFIER_INDENT: + warnings.warn( + f"line too short to contain a feature: {line!r}", + BiopythonParserWarning, + ) + line = self.handle.readline() + continue + + if skip: + line = self.handle.readline() + while ( + line[: self.FEATURE_QUALIFIER_INDENT] + == self.FEATURE_QUALIFIER_SPACER + ): + line = self.handle.readline() + else: + # Build up a list of the lines making up this feature: + if ( + line[self.FEATURE_QUALIFIER_INDENT] != " " + and " " in line[self.FEATURE_QUALIFIER_INDENT :] + ): + # The feature table design enforces a length limit on the feature keys. + # Some third party files (e.g. IGMT's EMBL like files) solve this by + # over indenting the location and qualifiers. + feature_key, line = line[2:].strip().split(None, 1) + feature_lines = [line] + warnings.warn( + f"Over indented {feature_key} feature?", + BiopythonParserWarning, + ) + else: + feature_key = line[2 : self.FEATURE_QUALIFIER_INDENT].strip() + feature_lines = [line[self.FEATURE_QUALIFIER_INDENT :]] + line = self.handle.readline() + while line[ + : self.FEATURE_QUALIFIER_INDENT + ] == self.FEATURE_QUALIFIER_SPACER or ( + line != "" and line.rstrip() == "" + ): # cope with blank lines in the midst of a feature + # Use strip to remove any harmless trailing white space AND and leading + # white space (e.g. out of spec files with too much indentation) + feature_lines.append(line[self.FEATURE_QUALIFIER_INDENT :].strip()) + line = self.handle.readline() + features.append(self.parse_feature(feature_key, feature_lines)) + self.line = line + return features + + def parse_feature(self, feature_key, lines): + r"""Parse a feature given as a list of strings into a tuple. + + Expects a feature as a list of strings, returns a tuple (key, location, + qualifiers) + + For example given this GenBank feature:: + + CDS complement(join(490883..490885,1..879)) + /locus_tag="NEQ001" + /note="conserved hypothetical [Methanococcus jannaschii]; + COG1583:Uncharacterized ACR; IPR001472:Bipartite nuclear + localization signal; IPR002743: Protein of unknown + function DUF57" + /codon_start=1 + /transl_table=11 + /product="hypothetical protein" + /protein_id="NP_963295.1" + /db_xref="GI:41614797" + /db_xref="GeneID:2732620" + /translation="MRLLLELKALNSIDKKQLSNYLIQGFIYNILKNTEYSWLHNWKK + EKYFNFTLIPKKDIIENKRYYLIISSPDKRFIEVLHNKIKDLDIITIGLAQFQLRKTK + KFDPKLRFPWVTITPIVLREGKIVILKGDKYYKVFVKRLEELKKYNLIKKKEPILEEP + IEISLNQIKDGWKIIDVKDRYYDFRNKSFSAFSNWLRDLKEQSLRKYNNFCGKNFYFE + EAIFEGFTFYKTVSIRIRINRGEAVYIGTLWKELNVYRKLDKEEREFYKFLYDCGLGS + LNSMGFGFVNTKKNSAR" + + Then should give input key="CDS" and the rest of the data as a list of strings + lines=["complement(join(490883..490885,1..879))", ..., "LNSMGFGFVNTKKNSAR"] + where the leading spaces and trailing newlines have been removed. + + Returns tuple containing: (key as string, location string, qualifiers as list) + as follows for this example: + + key = "CDS", string + location = "complement(join(490883..490885,1..879))", string + qualifiers = list of string tuples: + + [('locus_tag', '"NEQ001"'), + ('note', '"conserved hypothetical [Methanococcus jannaschii];\nCOG1583:..."'), + ('codon_start', '1'), + ('transl_table', '11'), + ('product', '"hypothetical protein"'), + ('protein_id', '"NP_963295.1"'), + ('db_xref', '"GI:41614797"'), + ('db_xref', '"GeneID:2732620"'), + ('translation', '"MRLLLELKALNSIDKKQLSNYLIQGFIYNILKNTEYSWLHNWKK\nEKYFNFT..."')] + + In the above example, the "note" and "translation" were edited for compactness, + and they would contain multiple new line characters (displayed above as \n) + + If a qualifier is quoted (in this case, everything except codon_start and + transl_table) then the quotes are NOT removed. + + Note that no whitespace is removed. + """ + # Skip any blank lines + iterator = (x for x in lines if x) + try: + line = next(iterator) + + feature_location = line.strip() + while feature_location[-1:] == ",": + # Multiline location, still more to come! + line = next(iterator) + feature_location += line.strip() + if feature_location.count("(") > feature_location.count(")"): + # Including the prev line in warning would be more explicit, + # but this way get one-and-only-one warning shown by default: + warnings.warn( + "Non-standard feature line wrapping (didn't break on comma)?", + BiopythonParserWarning, + ) + while feature_location[-1:] == "," or feature_location.count( + "(" + ) > feature_location.count(")"): + line = next(iterator) + feature_location += line.strip() + + qualifiers = [] + + for line_number, line in enumerate(iterator): + # check for extra wrapping of the location closing parentheses + if line_number == 0 and line.startswith(")"): + feature_location += line.strip() + elif line[0] == "/": + # New qualifier + i = line.find("=") + key = line[1:i] # does not work if i==-1 + value = line[i + 1 :] # we ignore 'value' if i==-1 + if i and value.startswith(" ") and value.lstrip().startswith('"'): + warnings.warn( + "White space after equals in qualifier", + BiopythonParserWarning, + ) + value = value.lstrip() + if i == -1: + # Qualifier with no key, e.g. /pseudo + key = line[1:] + qualifiers.append((key, None)) + elif not value: + # ApE can output /note= + qualifiers.append((key, "")) + elif value == '"': + # One single quote + if self.debug: + print(f"Single quote {key}:{value}") + # DO NOT remove the quote... + qualifiers.append((key, value)) + elif value[0] == '"': + # Quoted... + value_list = [value] + while value_list[-1][-1] != '"': + value_list.append(next(iterator)) + value = "\n".join(value_list) + # DO NOT remove the quotes... + qualifiers.append((key, value)) + else: + # Unquoted + # if debug : print("Unquoted line %s:%s" % (key,value)) + qualifiers.append((key, value)) + else: + # Unquoted continuation + assert len(qualifiers) > 0 + assert key == qualifiers[-1][0] + # if debug : print("Unquoted Cont %s:%s" % (key, line)) + if qualifiers[-1][1] is None: + raise StopIteration + qualifiers[-1] = (key, qualifiers[-1][1] + "\n" + line) + return feature_key, feature_location, qualifiers + except StopIteration: + # Bummer + raise ValueError( + "Problem with '%s' feature:\n%s" % (feature_key, "\n".join(lines)) + ) from None + + def parse_footer(self): + """Return a tuple containing a list of any misc strings, and the sequence.""" + # This is a basic bit of code to scan and discard the sequence, + # which was useful when developing the sub classes. + if self.line in self.FEATURE_END_MARKERS: + while self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + self.line = self.handle.readline() + if not self.line: + raise ValueError("Premature end of file") + self.line = self.line.rstrip() + + if self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + raise ValueError("Not at start of sequence") + while True: + line = self.handle.readline() + if not line: + raise ValueError("Premature end of line during sequence data") + line = line.rstrip() + if line == "//": + break + self.line = line + return [], "" # Dummy values! + + def _feed_first_line(self, consumer, line): + """Handle the LOCUS/ID line, passing data to the consumer (PRIVATE). + + This should be implemented by the EMBL / GenBank specific subclass + + Used by the parse_records() and parse() methods. + """ + + def _feed_header_lines(self, consumer, lines): + """Handle the header lines (list of strings), passing data to the consumer (PRIVATE). + + This should be implemented by the EMBL / GenBank specific subclass + + Used by the parse_records() and parse() methods. + """ + + @staticmethod + def _feed_feature_table(consumer, feature_tuples): + """Handle the feature table (list of tuples), passing data to the consumer (PRIVATE). + + Used by the parse_records() and parse() methods. + """ + consumer.start_feature_table() + for feature_key, location_string, qualifiers in feature_tuples: + consumer.feature_key(feature_key) + consumer.location(location_string) + for q_key, q_value in qualifiers: + if q_value is None: + consumer.feature_qualifier(q_key, q_value) + else: + consumer.feature_qualifier(q_key, q_value.replace("\n", " ")) + + def _feed_misc_lines(self, consumer, lines): + """Handle any lines between features and sequence (list of strings), passing data to the consumer (PRIVATE). + + This should be implemented by the EMBL / GenBank specific subclass + + Used by the parse_records() and parse() methods. + """ + + def feed(self, handle, consumer, do_features=True): + """Feed a set of data into the consumer. + + This method is intended for use with the "old" code in Bio.GenBank + + Arguments: + - handle - A handle with the information to parse. + - consumer - The consumer that should be informed of events. + - do_features - Boolean, should the features be parsed? + Skipping the features can be much faster. + + Return values: + - true - Passed a record + - false - Did not find a record + + """ + # Should work with both EMBL and GenBank files provided the + # equivalent Bio.GenBank._FeatureConsumer methods are called... + self.set_handle(handle) + if not self.find_start(): + # Could not find (another) record + consumer.data = None + return False + + # We use the above class methods to parse the file into a simplified format. + # The first line, header lines and any misc lines after the features will be + # dealt with by GenBank / EMBL specific derived classes. + + # First line and header: + self._feed_first_line(consumer, self.line) + self._feed_header_lines(consumer, self.parse_header()) + + # Features (common to both EMBL and GenBank): + if do_features: + self._feed_feature_table(consumer, self.parse_features(skip=False)) + else: + self.parse_features(skip=True) # ignore the data + + # Footer and sequence + misc_lines, sequence_string = self.parse_footer() + self._feed_misc_lines(consumer, misc_lines) + + consumer.sequence(sequence_string) + # Calls to consumer.base_number() do nothing anyway + consumer.record_end("//") + + assert self.line == "//" + + # And we are done + return True + + def parse(self, handle, do_features=True): + """Return a SeqRecord (with SeqFeatures if do_features=True). + + See also the method parse_records() for use on multi-record files. + """ + from Bio.GenBank import _FeatureConsumer + from Bio.GenBank.utils import FeatureValueCleaner + + consumer = _FeatureConsumer( + use_fuzziness=1, feature_cleaner=FeatureValueCleaner() + ) + + if self.feed(handle, consumer, do_features): + return consumer.data + else: + return None + + def parse_records(self, handle, do_features=True): + """Parse records, return a SeqRecord object iterator. + + Each record (from the ID/LOCUS line to the // line) becomes a SeqRecord + + The SeqRecord objects include SeqFeatures if do_features=True + + This method is intended for use in Bio.SeqIO + """ + # This is a generator function + with as_handle(handle) as handle: + while True: + record = self.parse(handle, do_features) + if record is None: + break + if record.id is None: + raise ValueError( + "Failed to parse the record's ID. Invalid ID line?" + ) + if record.name == "": + raise ValueError( + "Failed to parse the record's name. Invalid ID line?" + ) + if record.description == "": + raise ValueError("Failed to parse the record's description") + yield record + + def parse_cds_features( + self, handle, alphabet=None, tags2id=("protein_id", "locus_tag", "product") + ): + """Parse CDS features, return SeqRecord object iterator. + + Each CDS feature becomes a SeqRecord. + + Arguments: + - alphabet - Obsolete, should be left as None. + - tags2id - Tuple of three strings, the feature keys to use + for the record id, name and description, + + This method is intended for use in Bio.SeqIO + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + with as_handle(handle) as handle: + self.set_handle(handle) + while self.find_start(): + # Got an EMBL or GenBank record... + self.parse_header() # ignore header lines! + feature_tuples = self.parse_features() + # self.parse_footer() # ignore footer lines! + while True: + line = self.handle.readline() + if not line: + break + if line[:2] == "//": + break + self.line = line.rstrip() + + # Now go though those features... + for key, location_string, qualifiers in feature_tuples: + if key == "CDS": + # Create SeqRecord + # ================ + # SeqRecord objects cannot be created with annotations, they + # must be added afterwards. So create an empty record and + # then populate it: + record = SeqRecord(seq=None) + annotations = record.annotations + annotations["molecule_type"] = "protein" + # Should we add a location object to the annotations? + # I *think* that only makes sense for SeqFeatures with their + # sub features... + annotations["raw_location"] = location_string.replace(" ", "") + + for qualifier_name, qualifier_data in qualifiers: + if ( + qualifier_data is not None + and qualifier_data[0] == '"' + and qualifier_data[-1] == '"' + ): + # Remove quotes + qualifier_data = qualifier_data[1:-1] + # Append the data to the annotation qualifier... + if qualifier_name == "translation": + assert record.seq is None, "Multiple translations!" + record.seq = Seq(qualifier_data.replace("\n", "")) + elif qualifier_name == "db_xref": + # its a list, possibly empty. Its safe to extend + record.dbxrefs.append(qualifier_data) + else: + if qualifier_data is not None: + qualifier_data = qualifier_data.replace( + "\n", " " + ).replace(" ", " ") + try: + annotations[qualifier_name] += " " + qualifier_data + except KeyError: + # Not an addition to existing data, its the first bit + annotations[qualifier_name] = qualifier_data + + # Fill in the ID, Name, Description + # ================================= + try: + record.id = annotations[tags2id[0]] + except KeyError: + pass + try: + record.name = annotations[tags2id[1]] + except KeyError: + pass + try: + record.description = annotations[tags2id[2]] + except KeyError: + pass + + yield record + + +class EmblScanner(InsdcScanner): + """For extracting chunks of information in EMBL files.""" + + RECORD_START = "ID " + HEADER_WIDTH = 5 + FEATURE_START_MARKERS = ["FH Key Location/Qualifiers", "FH"] + FEATURE_END_MARKERS = ["XX"] # XX can also mark the end of many things! + FEATURE_QUALIFIER_INDENT = 21 + FEATURE_QUALIFIER_SPACER = "FT" + " " * (FEATURE_QUALIFIER_INDENT - 2) + SEQUENCE_HEADERS = ["SQ", "CO"] # Remove trailing spaces + + EMBL_INDENT = HEADER_WIDTH + EMBL_SPACER = " " * EMBL_INDENT + + def parse_footer(self): + """Return a tuple containing a list of any misc strings, and the sequence.""" + if self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + raise ValueError(f"Footer format unexpected: '{self.line}'") + + # Note that the SQ line can be split into several lines... + misc_lines = [] + while self.line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + misc_lines.append(self.line) + self.line = self.handle.readline() + if not self.line: + raise ValueError("Premature end of file") + self.line = self.line.rstrip() + + if not ( + self.line[: self.HEADER_WIDTH] == " " * self.HEADER_WIDTH + or self.line.strip() == "//" + ): + raise ValueError(f"Unexpected content after SQ or CO line: {self.line!r}") + + seq_lines = [] + line = self.line + while True: + if not line: + raise ValueError("Premature end of file in sequence data") + line = line.strip() + if not line: + raise ValueError("Blank line in sequence data") + if line == "//": + break + if self.line[: self.HEADER_WIDTH] != (" " * self.HEADER_WIDTH): + raise ValueError( + "Problem with characters in header line, " + " or incorrect header width: " + self.line + ) + # Remove tailing number now, remove spaces later + linersplit = line.rsplit(None, 1) + if len(linersplit) == 2 and linersplit[1].isdigit(): + seq_lines.append(linersplit[0]) + elif line.isdigit(): + # Special case of final blank line with no bases + # just the sequence coordinate + pass + else: + warnings.warn( + "EMBL sequence line missing coordinates", BiopythonParserWarning + ) + seq_lines.append(line) + line = self.handle.readline() + self.line = line + return misc_lines, "".join(seq_lines).replace(" ", "") + + def _feed_first_line(self, consumer, line): + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + if line[self.HEADER_WIDTH :].count(";") == 6: + # Looks like the semi colon separated style introduced in 2006 + self._feed_first_line_new(consumer, line) + elif line[self.HEADER_WIDTH :].count(";") == 3: + if line.rstrip().endswith(" SQ"): + # EMBL-bank patent data + self._feed_first_line_patents(consumer, line) + else: + # Looks like the pre 2006 style + self._feed_first_line_old(consumer, line) + elif line[self.HEADER_WIDTH :].count(";") == 2: + # Looks like KIKO patent data + self._feed_first_line_patents_kipo(consumer, line) + else: + raise ValueError("Did not recognise the ID line layout:\n" + line) + + def _feed_first_line_patents(self, consumer, line): + # Old style EMBL patent records where ID line ended SQ + # Not 100% sure that PRT here is really molecule type and + # not the data file division... + # + # Either Non-Redundant Level 1 database records, + # ID ; ; ; + # e.g. ID NRP_AX000635; PRT; NR1; 15 SQ + # + # Or, Non-Redundant Level 2 database records: + # ID ; ; ; + # e.g. ID NRP0000016E; PRT; NR2; 5 SQ + # e.g. ID NRP_AX000635; PRT; NR1; 15 SQ + fields = [ + data.strip() for data in line[self.HEADER_WIDTH :].strip()[:-3].split(";") + ] + assert len(fields) == 4 + consumer.locus(fields[0]) + consumer.residue_type(fields[1]) # semi-redundant + consumer.data_file_division(fields[2]) + # TODO - Record cluster size? + + def _feed_first_line_patents_kipo(self, consumer, line): + # EMBL format patent sequence from KIPO, e.g. + # ftp://ftp.ebi.ac.uk/pub/databases/patentdata/kipo_prt.dat.gz + # + # e.g. ID DI500001 STANDARD; PRT; 111 AA. + # + # This follows the style of _feed_first_line_old + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + fields = [line[self.HEADER_WIDTH :].split(None, 1)[0]] + fields.extend(line[self.HEADER_WIDTH :].split(None, 1)[1].split(";")) + fields = [entry.strip() for entry in fields] + """ + The tokens represent: + + 0. Primary accession number + (space sep) + 1. ??? (e.g. standard) + (semi-colon) + 2. Molecule type (protein)? Division? Always 'PRT' + 3. Sequence length (e.g. '111 AA.') + """ + consumer.locus(fields[0]) # Should we also call the accession consumer? + # consumer.molecule_type(fields[2]) + self._feed_seq_length(consumer, fields[3]) + + def _feed_first_line_old(self, consumer, line): + # Expects an ID line in the style before 2006, e.g. + # ID SC10H5 standard; DNA; PRO; 4870 BP. + # ID BSUB9999 standard; circular DNA; PRO; 4214630 BP. + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + fields = [line[self.HEADER_WIDTH :].split(None, 1)[0]] + fields.extend(line[self.HEADER_WIDTH :].split(None, 1)[1].split(";")) + fields = [entry.strip() for entry in fields] + """ + The tokens represent: + + 0. Primary accession number + (space sep) + 1. ??? (e.g. standard) + (semi-colon) + 2. Topology and/or Molecule type (e.g. 'circular DNA' or 'DNA') + 3. Taxonomic division (e.g. 'PRO') + 4. Sequence length (e.g. '4639675 BP.') + + """ + consumer.locus(fields[0]) # Should we also call the accession consumer? + consumer.residue_type(fields[2]) + if "circular" in fields[2]: + consumer.topology("circular") + consumer.molecule_type(fields[2].replace("circular", "").strip()) + elif "linear" in fields[2]: + consumer.topology("linear") + consumer.molecule_type(fields[2].replace("linear", "").strip()) + else: + consumer.molecule_type(fields[2].strip()) + consumer.data_file_division(fields[3]) + self._feed_seq_length(consumer, fields[4]) + + def _feed_first_line_new(self, consumer, line): + # Expects an ID line in the style introduced in 2006, e.g. + # ID X56734; SV 1; linear; mRNA; STD; PLN; 1859 BP. + # ID CD789012; SV 4; linear; genomic DNA; HTG; MAM; 500 BP. + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + fields = [data.strip() for data in line[self.HEADER_WIDTH :].strip().split(";")] + assert len(fields) == 7 + """ + The tokens represent: + + 0. Primary accession number + 1. Sequence version number + 2. Topology: 'circular' or 'linear' + 3. Molecule type (e.g. 'genomic DNA') + 4. Data class (e.g. 'STD') + 5. Taxonomic division (e.g. 'PRO') + 6. Sequence length (e.g. '4639675 BP.') + + """ + + consumer.locus(fields[0]) + + # Call the accession consumer now, to make sure we record + # something as the record.id, in case there is no AC line + consumer.accession(fields[0]) + + # TODO - How to deal with the version field? At the moment the consumer + # will try and use this for the ID which isn't ideal for EMBL files. + version_parts = fields[1].split() + if ( + len(version_parts) == 2 + and version_parts[0] == "SV" + and version_parts[1].isdigit() + ): + consumer.version_suffix(version_parts[1]) + + # Based on how the old GenBank parser worked, merge these two: + consumer.residue_type(" ".join(fields[2:4])) # Semi-obsolete + + consumer.topology(fields[2]) + consumer.molecule_type(fields[3]) + + # consumer.xxx(fields[4]) # TODO - What should we do with the data class? + + consumer.data_file_division(fields[5]) + + self._feed_seq_length(consumer, fields[6]) + + @staticmethod + def _feed_seq_length(consumer, text): + length_parts = text.split() + assert len(length_parts) == 2, f"Invalid sequence length string {text!r}" + assert length_parts[1].upper() in ["BP", "BP.", "AA", "AA."] + consumer.size(length_parts[0]) + + def _feed_header_lines(self, consumer, lines): + consumer_dict = { + "AC": "accession", + "SV": "version", # SV line removed in June 2006, now part of ID line + "DE": "definition", + # 'RN' : 'reference_num', + # 'RC' : reference comment... TODO + # 'RP' : 'reference_bases', + # 'RX' : reference cross reference... DOI or Pubmed + "RG": "consrtm", # optional consortium + # 'RA' : 'authors', + # 'RT' : 'title', + "RL": "journal", + "OS": "organism", + "OC": "taxonomy", + # 'DR' : data reference + "CC": "comment", + # 'XX' : splitter + } + # We have to handle the following specially: + # RX (depending on reference type...) + for line in lines: + line_type = line[: self.EMBL_INDENT].strip() + data = line[self.EMBL_INDENT :].strip() + if line_type == "XX": + pass + elif line_type == "RN": + # Reformat reference numbers for the GenBank based consumer + # e.g. '[1]' becomes '1' + if data[0] == "[" and data[-1] == "]": + data = data[1:-1] + consumer.reference_num(data) + elif line_type == "RP": + if data.strip() == "[-]": + # Patent EMBL files from KIPO just use: RN [-] + pass + else: + # Reformat reference numbers for the GenBank based consumer + # e.g. '1-4639675' becomes '(bases 1 to 4639675)' + # and '160-550, 904-1055' becomes '(bases 160 to 550; 904 to 1055)' + # Note could be multi-line, and end with a comma + parts = [ + bases.replace("-", " to ").strip() + for bases in data.split(",") + if bases.strip() + ] + consumer.reference_bases(f"(bases {'; '.join(parts)})") + elif line_type == "RT": + # Remove the enclosing quotes and trailing semi colon. + # Note the title can be split over multiple lines. + if data.startswith('"'): + data = data[1:] + if data.endswith('";'): + data = data[:-2] + consumer.title(data) + elif line_type == "RX": + # EMBL support three reference types at the moment: + # - PUBMED PUBMED bibliographic database (NLM) + # - DOI Digital Object Identifier (International DOI Foundation) + # - AGRICOLA US National Agriculture Library (NAL) of the US Department + # of Agriculture (USDA) + # + # Format: + # RX resource_identifier; identifier. + # + # e.g. + # RX DOI; 10.1016/0024-3205(83)90010-3. + # RX PUBMED; 264242. + # + # Currently our reference object only supports PUBMED and MEDLINE + # (as these were in GenBank files?). + key, value = data.split(";", 1) + if value.endswith("."): + value = value[:-1] + value = value.strip() + if key == "PUBMED": + consumer.pubmed_id(value) + # TODO - Handle other reference types (here and in BioSQL bindings) + elif line_type == "CC": + # Have to pass a list of strings for this one (not just a string) + consumer.comment([data]) + elif line_type == "DR": + # Database Cross-reference, format: + # DR database_identifier; primary_identifier; secondary_identifier. + # + # e.g. + # DR MGI; 98599; Tcrb-V4. + # + # TODO - How should we store any secondary identifier? + parts = data.rstrip(".").split(";") + # Turn it into "database_identifier:primary_identifier" to + # mimic the GenBank parser. e.g. "MGI:98599" + if len(parts) == 1: + warnings.warn( + "Malformed DR line in EMBL file.", BiopythonParserWarning + ) + else: + consumer.dblink(f"{parts[0].strip()}:{parts[1].strip()}") + elif line_type == "RA": + # Remove trailing ; at end of authors list + consumer.authors(data.rstrip(";")) + elif line_type == "PR": + # In the EMBL patent files, this is a PR (PRiority) line which + # provides the earliest active priority within the family. + # The priority number comes first, followed by the priority date. + # + # e.g. + # PR JP19990377484 16-DEC-1999 + # + # However, in most EMBL files this is a PR (PRoject) line which + # gives the BioProject reference number. + # + # e.g. + # PR Project:PRJNA60715; + # + # In GenBank files this corresponds to the old PROJECT line + # which was later replaced with the DBLINK line. + if data.startswith("Project:"): + # Remove trailing ; at end of the project reference + consumer.project(data.rstrip(";")) + elif line_type == "KW": + consumer.keywords(data.rstrip(";")) + elif line_type in consumer_dict: + # Its a semi-automatic entry! + getattr(consumer, consumer_dict[line_type])(data) + else: + if self.debug: + print(f"Ignoring EMBL header line:\n{line}") + + def _feed_misc_lines(self, consumer, lines): + # TODO - Should we do something with the information on the SQ line(s)? + lines.append("") + line_iter = iter(lines) + try: + for line in line_iter: + if line.startswith("CO "): + line = line[5:].strip() + contig_location = line + while True: + line = next(line_iter) + if not line: + break + elif line.startswith("CO "): + # Don't need to preserve the whitespace here. + contig_location += line[5:].strip() + else: + raise ValueError( + "Expected CO (contig) continuation line, got:\n" + line + ) + consumer.contig_location(contig_location) + if line.startswith("SQ Sequence "): + # e.g. + # SQ Sequence 219 BP; 82 A; 48 C; 33 G; 45 T; 11 other; + # + # Or, EMBL-bank patent, e.g. + # SQ Sequence 465 AA; 3963407aa91d3a0d622fec679a4524e0; MD5; + self._feed_seq_length( + consumer, line[14:].rstrip().rstrip(";").split(";", 1)[0] + ) + # TODO - Record the checksum etc? + return + except StopIteration: + raise ValueError("Problem in misc lines before sequence") from None + + +class _ImgtScanner(EmblScanner): + """For extracting chunks of information in IMGT (EMBL like) files (PRIVATE). + + IMGT files are like EMBL files but in order to allow longer feature types + the features should be indented by 25 characters not 21 characters. In + practice the IMGT flat files tend to use either 21 or 25 characters, so we + must cope with both. + + This is private to encourage use of Bio.SeqIO rather than Bio.GenBank. + """ + + FEATURE_START_MARKERS = [ + "FH Key Location/Qualifiers", + "FH Key Location/Qualifiers (from EMBL)", + "FH Key Location/Qualifiers", + "FH", + ] + + def _feed_first_line(self, consumer, line): + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + if line[self.HEADER_WIDTH :].count(";") != 5: + # Assume its an older EMBL-like line, + return EmblScanner._feed_first_line(self, consumer, line) + # Otherwise assume its the new (circa 2016) IMGT style + # as used in the IPD-IMGT/HLA Database + # + # https://github.com/ANHIG/IMGTHLA/ + # + # The key changes post 3.16 are the addition of an SV value + # to the ID line, these additions should make the format more + # similar to the ENA style. + # + # ID HLA00001 standard; DNA; HUM; 3503 BP. + # + # becomes + # + # ID HLA00001; SV 1; standard; DNA; HUM; 3503 BP. + fields = [data.strip() for data in line[self.HEADER_WIDTH :].strip().split(";")] + assert len(fields) == 6 + """ + The tokens represent: + + 0. Primary accession number (eg 'HLA00001') + 1. Sequence version number (eg 'SV 1') + 2. ??? eg 'standard' + 3. Molecule type (e.g. 'DNA') + 4. Taxonomic division (e.g. 'HUM') + 5. Sequence length (e.g. '3503 BP.') + """ + consumer.locus(fields[0]) + + # See TODO on the EMBL _feed_first_line_new about version field + version_parts = fields[1].split() + if ( + len(version_parts) == 2 + and version_parts[0] == "SV" + and version_parts[1].isdigit() + ): + consumer.version_suffix(version_parts[1]) + + consumer.residue_type(fields[3]) + if "circular" in fields[3]: + consumer.topology("circular") + consumer.molecule_type(fields[3].replace("circular", "").strip()) + elif "linear" in fields[3]: + consumer.topology("linear") + consumer.molecule_type(fields[3].replace("linear", "").strip()) + else: + consumer.molecule_type(fields[3].strip()) + consumer.data_file_division(fields[4]) + self._feed_seq_length(consumer, fields[5]) + + def parse_features(self, skip=False): + """Return list of tuples for the features (if present). + + Each feature is returned as a tuple (key, location, qualifiers) + where key and location are strings (e.g. "CDS" and + "complement(join(490883..490885,1..879))") while qualifiers + is a list of two string tuples (feature qualifier keys and values). + + Assumes you have already read to the start of the features table. + """ + if self.line.rstrip() not in self.FEATURE_START_MARKERS: + if self.debug: + print("Didn't find any feature table") + return [] + + while self.line.rstrip() in self.FEATURE_START_MARKERS: + self.line = self.handle.readline() + + bad_position_re = re.compile(r"([0-9]+)>") + + features = [] + line = self.line + while True: + if not line: + raise ValueError("Premature end of line during features table") + if line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + if self.debug: + print("Found start of sequence") + break + line = line.rstrip() + if line == "//": + raise ValueError("Premature end of features table, marker '//' found") + if line in self.FEATURE_END_MARKERS: + if self.debug: + print("Found end of features") + line = self.handle.readline() + break + if line[2 : self.FEATURE_QUALIFIER_INDENT].strip() == "": + # This is an empty feature line between qualifiers. Empty + # feature lines within qualifiers are handled below (ignored). + line = self.handle.readline() + continue + + if skip: + line = self.handle.readline() + while ( + line[: self.FEATURE_QUALIFIER_INDENT] + == self.FEATURE_QUALIFIER_SPACER + ): + line = self.handle.readline() + else: + assert line[:2] == "FT" + try: + feature_key, location_start = line[2:].strip().split() + except ValueError: + # e.g. "FT TRANSMEMBRANE-REGION2163..2240\n" + # Assume indent of 25 as per IMGT spec, with the location + # start in column 26 (one-based). + feature_key = line[2:25].strip() + location_start = line[25:].strip() + feature_lines = [location_start] + line = self.handle.readline() + while ( + line[: self.FEATURE_QUALIFIER_INDENT] + == self.FEATURE_QUALIFIER_SPACER + or line.rstrip() == "" + ): # cope with blank lines in the midst of a feature + # Use strip to remove any harmless trailing white space AND and leading + # white space (copes with 21 or 26 indents and orther variants) + assert line[:2] == "FT" + feature_lines.append(line[self.FEATURE_QUALIFIER_INDENT :].strip()) + line = self.handle.readline() + feature_key, location, qualifiers = self.parse_feature( + feature_key, feature_lines + ) + # Try to handle known problems with IMGT locations here: + if ">" in location: + # Nasty hack for common IMGT bug, should be >123 not 123> + # in a location string. At least here the meaning is clear, + # and since it is so common I don't want to issue a warning + # warnings.warn("Feature location %s is invalid, " + # "moving greater than sign before position" + # % location, BiopythonParserWarning) + location = bad_position_re.sub(r">\1", location) + features.append((feature_key, location, qualifiers)) + self.line = line + return features + + +class GenBankScanner(InsdcScanner): + """For extracting chunks of information in GenBank files.""" + + RECORD_START = "LOCUS " + HEADER_WIDTH = 12 + FEATURE_START_MARKERS = ["FEATURES Location/Qualifiers", "FEATURES"] + FEATURE_END_MARKERS: list[str] = [] + FEATURE_QUALIFIER_INDENT = 21 + FEATURE_QUALIFIER_SPACER = " " * FEATURE_QUALIFIER_INDENT + SEQUENCE_HEADERS = [ + "CONTIG", + "ORIGIN", + "BASE COUNT", + "WGS", + "TSA", + "TLS", + ] # trailing spaces removed + + GENBANK_INDENT = HEADER_WIDTH + GENBANK_SPACER = " " * GENBANK_INDENT + + STRUCTURED_COMMENT_START = "-START##" + STRUCTURED_COMMENT_END = "-END##" + STRUCTURED_COMMENT_DELIM = " :: " + + def parse_footer(self): + """Return a tuple containing a list of any misc strings, and the sequence.""" + if self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + raise ValueError(f"Footer format unexpected: '{self.line}'") + + misc_lines = [] + while ( + self.line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS + or self.line[: self.HEADER_WIDTH] == " " * self.HEADER_WIDTH + or "WGS" == self.line[:3] + ): + misc_lines.append(self.line.rstrip()) + self.line = self.handle.readline() + if not self.line: + raise ValueError("Premature end of file") + + if self.line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + raise ValueError(f"Eh? '{self.line}'") + + # Now just consume the sequence lines until reach the // marker + # or a CONTIG line + seq_lines = [] + line = self.line + while True: + if not line: + warnings.warn( + "Premature end of file in sequence data", BiopythonParserWarning + ) + line = "//" + break + line = line.rstrip() + if not line: + warnings.warn("Blank line in sequence data", BiopythonParserWarning) + line = self.handle.readline() + continue + if line == "//": + break + if line.startswith("CONTIG"): + break + if len(line) > 9 and line[9:10] != " ": + # Some broken programs indent the sequence by one space too many + # so try to get rid of that and test again. + warnings.warn( + "Invalid indentation for sequence line", BiopythonParserWarning + ) + line = line[1:] + if len(line) > 9 and line[9:10] != " ": + raise ValueError(f"Sequence line mal-formed, '{line}'") + seq_lines.append(line[10:]) # remove spaces later + line = self.handle.readline() + + self.line = line + return misc_lines, "".join(seq_lines).replace(" ", "") + + def _feed_first_line(self, consumer, line): + """Scan over and parse GenBank LOCUS line (PRIVATE). + + This must cope with several variants, primarily the old and new column + based standards from GenBank. Additionally EnsEMBL produces GenBank + files where the LOCUS line is space separated rather that following + the column based layout. + + We also try to cope with GenBank like files with partial LOCUS lines. + + As of release 229.0, the columns are no longer strictly in a given + position. See GenBank format release notes: + + "Historically, the LOCUS line has had a fixed length and its + elements have been presented at specific column positions... + But with the anticipated increases in the lengths of accession + numbers, and the advent of sequences that are gigabases long, + maintaining the column positions will not always be possible and + the overall length of the LOCUS line could exceed 79 characters." + + """ + ##################################### + # LOCUS line # + ##################################### + if line[0 : self.GENBANK_INDENT] != "LOCUS ": + raise ValueError("LOCUS line does not start correctly:\n" + line) + + # Have to break up the locus line, and handle the different bits of it. + # There are at least two different versions of the locus line... + if line[29:33] in [" bp ", " aa ", " rc "] and line[55:62] == " ": + # Old... note we insist on the 55:62 being empty to avoid trying + # to parse space separated LOCUS lines from Ensembl etc, see below. + # + # Positions Contents + # --------- -------- + # 00:06 LOCUS + # 06:12 spaces + # 12:?? Locus name + # ??:?? space + # ??:29 Length of sequence, right-justified + # 29:33 space, bp, space + # 33:41 strand type / molecule type, e.g. DNA + # 41:42 space + # 42:51 Blank (implies linear), linear or circular + # 51:52 space + # 52:55 The division code (e.g. BCT, VRL, INV) + # 55:62 space + # 62:73 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991) + # + # assert line[29:33] in [' bp ', ' aa ',' rc '] , \ + # 'LOCUS line does not contain size units at expected position:\n' + line + if line[41:42] != " ": + raise ValueError( + "LOCUS line does not contain space at position 42:\n" + line + ) + if line[42:51].strip() not in ["", "linear", "circular"]: + raise ValueError( + "LOCUS line does not contain valid entry " + "(linear, circular, ...):\n" + line + ) + if line[51:52] != " ": + raise ValueError( + "LOCUS line does not contain space at position 52:\n" + line + ) + # if line[55:62] != ' ': + # raise ValueError('LOCUS line does not contain spaces from position 56 to 62:\n' + line) + parse_date = False + if line[62:73].strip(): + parse_date = True + if line[64:65] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 65 in date:\n" + line, + BiopythonParserWarning, + ) + if line[68:69] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 69 in date:\n" + line, + BiopythonParserWarning, + ) + + name_and_length_str = line[self.GENBANK_INDENT : 29] + while " " in name_and_length_str: + name_and_length_str = name_and_length_str.replace(" ", " ") + name_and_length = name_and_length_str.split(" ") + if len(name_and_length) > 2: + raise ValueError( + "Cannot parse the name and length in the LOCUS line:\n" + line + ) + if len(name_and_length) == 1: + raise ValueError("Name and length collide in the LOCUS line:\n" + line) + # Should be possible to split them based on position, if + # a clear definition of the standard exists THAT AGREES with + # existing files. + name, length = name_and_length + if len(name) > 16: + # As long as the sequence is short, can steal its leading spaces + # to extend the name over the current 16 character limit. + # However, that deserves a warning as it is out of spec. + warnings.warn( + "GenBank LOCUS line identifier over 16 characters", + BiopythonParserWarning, + ) + consumer.locus(name) + consumer.size(length) + # consumer.residue_type(line[33:41].strip()) + + if line[33:51].strip() == "" and line[29:33] == " aa ": + # Amino acids -> protein (even if there is no residue type given) + consumer.residue_type("PROTEIN") + else: + consumer.residue_type(line[33:51].strip()) + + consumer.molecule_type(line[33:41].strip()) + consumer.topology(line[42:51].strip()) + consumer.data_file_division(line[52:55]) + if parse_date: + consumer.date(line[62:73]) + elif line[40:44] in [" bp ", " aa ", " rc "] and line[54:64].strip() in [ + "", + "linear", + "circular", + ]: + # New... linear/circular/big blank test should avoid EnsEMBL style + # LOCUS line being treated like a proper column based LOCUS line. + # + # Positions Contents + # --------- -------- + # 00:06 LOCUS + # 06:12 spaces + # 12:?? Locus name + # ??:?? space + # ??:40 Length of sequence, right-justified + # 40:44 space, bp, space + # 44:47 Blank, ss-, ds-, ms- + # 47:54 Blank, DNA, RNA, tRNA, mRNA, uRNA, snRNA, cDNA + # 54:55 space + # 55:63 Blank (implies linear), linear or circular + # 63:64 space + # 64:67 The division code (e.g. BCT, VRL, INV) + # 67:68 space + # 68:79 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991) + # + if len(line) < 79: + # JBEI genbank files seem to miss a division code and date + # See issue #1656 e.g. + # LOCUS pEH010 5743 bp DNA circular + warnings.warn( + f"Truncated LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + padding_len = 79 - len(line) + padding = " " * padding_len + line += padding + + if line[40:44] not in [" bp ", " aa ", " rc "]: + 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 + ) + parse_date = False + if line[68:79].strip(): + parse_date = True + if line[70:71] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 71 in date:\n" + line, + BiopythonParserWarning, + ) + if line[74:75] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 75 in date:\n" + line, + BiopythonParserWarning, + ) + + name_and_length_str = line[self.GENBANK_INDENT : 40] + while " " in name_and_length_str: + name_and_length_str = name_and_length_str.replace(" ", " ") + name_and_length = name_and_length_str.split(" ") + if len(name_and_length) > 2: + raise ValueError( + "Cannot parse the name and length in the LOCUS line:\n" + line + ) + if len(name_and_length) == 1: + raise ValueError("Name and length collide in the LOCUS line:\n" + line) + # Should be possible to split them based on position, if + # a clear definition of the stand exists THAT AGREES with + # existing files. + consumer.locus(name_and_length[0]) + consumer.size(name_and_length[1]) + + if line[44:54].strip() == "" and line[40:44] == " aa ": + # Amino acids -> protein (even if there is no residue type given) + consumer.residue_type(("PROTEIN " + line[54:63]).strip()) + else: + consumer.residue_type(line[44:63].strip()) + + consumer.molecule_type(line[44:54].strip()) + consumer.topology(line[55:63].strip()) + if line[64:76].strip(): + consumer.data_file_division(line[64:67]) + if parse_date: + consumer.date(line[68:79]) + elif line[self.GENBANK_INDENT :].strip().count(" ") == 0: + # Truncated LOCUS line, as produced by some EMBOSS tools - see bug 1762 + # + # e.g. + # + # "LOCUS U00096" + # + # rather than: + # + # "LOCUS U00096 4639675 bp DNA circular BCT" + # + # Positions Contents + # --------- -------- + # 00:06 LOCUS + # 06:12 spaces + # 12:?? Locus name + if line[self.GENBANK_INDENT :].strip() != "": + consumer.locus(line[self.GENBANK_INDENT :].strip()) + else: + # Must just have just "LOCUS ", is this even legitimate? + # We should be able to continue parsing... we need real world testcases! + warnings.warn( + f"Minimal LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + elif ( + len(line.split()) == 8 + and line.split()[3] in ("aa", "bp") + and line.split()[5] in ("linear", "circular") + ): + # Cope with invalidly spaced GenBank LOCUS lines like + # LOCUS AB070938 6497 bp DNA linear BCT 11-OCT-2001 + # This will also cope with extra long accession numbers and + # sequence lengths + splitline = line.split() + consumer.locus(splitline[1]) + # Provide descriptive error message if the sequence is too long + # for python to handle + + if int(splitline[2]) > sys.maxsize: + raise ValueError( + "Tried to load a sequence with a length %s, " + "your installation of python can only load " + "sesquences of length %s" % (splitline[2], sys.maxsize) + ) + else: + consumer.size(splitline[2]) + + consumer.residue_type(splitline[4]) + consumer.topology(splitline[5]) + consumer.data_file_division(splitline[6]) + consumer.date(splitline[7]) + if len(line) < 80: + warnings.warn( + "Attempting to parse malformed locus line:\n%r\n" + "Found locus %r size %r residue_type %r\n" + "Some fields may be wrong." + % (line, splitline[1], splitline[2], splitline[4]), + BiopythonParserWarning, + ) + elif len(line.split()) == 7 and line.split()[3] in ["aa", "bp"]: + # Cope with EnsEMBL genbank files which use space separation rather + # than the expected column based layout. e.g. + # LOCUS HG531_PATCH 1000000 bp DNA HTG 18-JUN-2011 + # LOCUS HG531_PATCH 759984 bp DNA HTG 18-JUN-2011 + # LOCUS HG506_HG1000_1_PATCH 814959 bp DNA HTG 18-JUN-2011 + # LOCUS HG506_HG1000_1_PATCH 1219964 bp DNA HTG 18-JUN-2011 + # Notice that the 'bp' can occur in the position expected by either + # the old or the new fixed column standards (parsed above). + splitline = line.split() + consumer.locus(splitline[1]) + consumer.size(splitline[2]) + consumer.residue_type(splitline[4]) + consumer.data_file_division(splitline[5]) + consumer.date(splitline[6]) + elif len(line.split()) >= 4 and line.split()[3] in ["aa", "bp"]: + # Cope with EMBOSS seqret output where it seems the locus id can cause + # the other fields to overflow. We just IGNORE the other fields! + warnings.warn( + f"Malformed LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + consumer.locus(line.split()[1]) + consumer.size(line.split()[2]) + elif len(line.split()) >= 4 and line.split()[-1] in ["aa", "bp"]: + # Cope with pseudo-GenBank files like this: + # "LOCUS RNA5 complete 1718 bp" + # Treat everything between LOCUS and the size as the identifier. + warnings.warn( + f"Malformed LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + consumer.locus(line[5:].rsplit(None, 2)[0].strip()) + consumer.size(line.split()[-2]) + else: + raise ValueError("Did not recognise the LOCUS line layout:\n" + line) + + def _feed_header_lines(self, consumer, lines): + # Following dictionary maps GenBank lines to the associated + # consumer methods - the special cases like LOCUS where one + # genbank line triggers several consumer calls have to be + # handled individually. + consumer_dict = { + "DEFINITION": "definition", + "ACCESSION": "accession", + "NID": "nid", + "PID": "pid", + "DBSOURCE": "db_source", + "KEYWORDS": "keywords", + "SEGMENT": "segment", + "SOURCE": "source", + "AUTHORS": "authors", + "CONSRTM": "consrtm", + "PROJECT": "project", + "TITLE": "title", + "JOURNAL": "journal", + "MEDLINE": "medline_id", + "PUBMED": "pubmed_id", + "REMARK": "remark", + } + # We have to handle the following specially: + # ORIGIN (locus, size, residue_type, data_file_division and date) + # COMMENT (comment) + # VERSION (version and gi) + # DBLINK (database links like projects, newlines important) + # REFERENCE (eference_num and reference_bases) + # ORGANISM (organism and taxonomy) + lines = [_f for _f in lines if _f] + lines.append("") # helps avoid getting StopIteration all the time + line_iter = iter(lines) + try: + line = next(line_iter) + while True: + if not line: + break + line_type = line[: self.GENBANK_INDENT].strip() + data = line[self.GENBANK_INDENT :].strip() + + if line_type == "VERSION": + # Need to call consumer.version(), and maybe also consumer.gi() as well. + # e.g. + # VERSION AC007323.5 GI:6587720 + while " " in data: + data = data.replace(" ", " ") + if " GI:" not in data: + consumer.version(data) + else: + if self.debug: + print( + "Version [" + + data.split(" GI:")[0] + + "], gi [" + + data.split(" GI:")[1] + + "]" + ) + consumer.version(data.split(" GI:")[0]) + consumer.gi(data.split(" GI:")[1]) + # Read in the next line! + line = next(line_iter) + elif line_type == "DBLINK": + # Need to call consumer.dblink() for each line, e.g. + # DBLINK Project: 57779 + # BioProject: PRJNA57779 + line = data.strip() + # Read in the next line, and see if its more of the DBLINK section: + while True: + next_line = next(line_iter) + if next_line[: self.GENBANK_INDENT] == self.GENBANK_SPACER: + # No new tag on next line, continue to add dbrefs + if next_line.count(":") == 0: + # This is a continuation of previous dbref + line += " " + next_line.strip() + else: + # Add this continuation to the data string + consumer.dblink(line.strip()) + line = next_line + continue + else: + # Add this continuation to the data string + consumer.dblink(line.strip()) + # End of the DBLINK, leave this text in the variable "line" + line = next_line + break + line = next(line_iter) + elif line_type == "REFERENCE": + if self.debug > 1: + print("Found reference [" + data + "]") + # Need to call consumer.reference_num() and consumer.reference_bases() + # e.g. + # REFERENCE 1 (bases 1 to 86436) + # + # Note that this can be multiline, see Bug 1968, e.g. + # + # REFERENCE 42 (bases 1517 to 1696; 3932 to 4112; 17880 to 17975; 21142 to + # 28259) + # + # For such cases we will call the consumer once only. + data = data.strip() + + # Read in the next line, and see if its more of the reference: + while True: + line = next(line_iter) + if line[: self.GENBANK_INDENT] == self.GENBANK_SPACER: + # Add this continuation to the data string + data += " " + line[self.GENBANK_INDENT :] + if self.debug > 1: + print("Extended reference text [" + data + "]") + else: + # End of the reference, leave this text in the variable "line" + break + + # We now have all the reference line(s) stored in a string, data, + # which we pass to the consumer + while " " in data: + data = data.replace(" ", " ") + if " " not in data: + if self.debug > 2: + print('Reference number "' + data + '"') + consumer.reference_num(data) + else: + if self.debug > 2: + print( + 'Reference number "' + + data[: data.find(" ")] + + '", "' + + data[data.find(" ") + 1 :] + + '"' + ) + consumer.reference_num(data[: data.find(" ")]) + consumer.reference_bases(data[data.find(" ") + 1 :]) + elif line_type == "ORGANISM": + # Typically the first line is the organism, and subsequent lines + # are the taxonomy lineage. However, given longer and longer + # species names (as more and more strains and sub strains get + # sequenced) the oragnism name can now get wrapped onto multiple + # lines. The NCBI say we have to recognise the lineage line by + # the presence of semi-colon delimited entries. In the long term, + # they are considering adding a new keyword (e.g. LINEAGE). + # See Bug 2591 for details. + organism_data = data + lineage_data = "" + while True: + line = next(line_iter) + if line[0 : self.GENBANK_INDENT] == self.GENBANK_SPACER: + if ( + lineage_data + or ";" in line + or line[self.GENBANK_INDENT :].strip() + in ( + "Bacteria.", + "Archaea.", + "Eukaryota.", + "Unclassified.", + "Viruses.", + "cellular organisms.", + "other sequences.", + "unclassified sequences.", + ) + ): + lineage_data += " " + line[self.GENBANK_INDENT :] + elif line[self.GENBANK_INDENT :].strip() == ".": + # No lineage data, just . place holder + pass + else: + organism_data += ( + " " + line[self.GENBANK_INDENT :].strip() + ) + else: + # End of organism and taxonomy + break + consumer.organism(organism_data) + if lineage_data.strip() == "" and self.debug > 1: + print("Taxonomy line(s) missing or blank") + consumer.taxonomy(lineage_data.strip()) + del organism_data, lineage_data + elif line_type == "COMMENT": + # A COMMENT can either be plain text or tabular (Structured Comment), + # or contain both. Multi-line comments are common. The code calls + # consumer.comment() once with a list where each entry + # is a line. If there's a structured comment consumer.structured_comment() + # is called with a dict of dicts where the secondary key/value pairs are + # the same as those in the structured comment table. The primary key is + # the title or header of the table (e.g. Assembly-Data, FluData). See + # http://www.ncbi.nlm.nih.gov/genbank/structuredcomment + # for more information on Structured Comments. + data = line[self.GENBANK_INDENT :] + if self.debug > 1: + print("Found comment") + comment_list = [] + structured_comment_dict = defaultdict(dict) + regex = rf"([^#]+){self.STRUCTURED_COMMENT_START}$" + structured_comment_key = re.search(regex, data) + if structured_comment_key is not None: + structured_comment_key = structured_comment_key.group(1) + if self.debug > 1: + print("Found Structured Comment") + else: + comment_list.append(data) + + while True: + line = next(line_iter) + data = line[self.GENBANK_INDENT :] + if line[0 : self.GENBANK_INDENT] == self.GENBANK_SPACER: + if self.STRUCTURED_COMMENT_START in data: + regex = rf"([^#]+){self.STRUCTURED_COMMENT_START}$" + structured_comment_key = re.search(regex, data) + if structured_comment_key is not None: + structured_comment_key = ( + structured_comment_key.group(1) + ) + else: + comment_list.append(data) + elif ( + structured_comment_key is not None + and self.STRUCTURED_COMMENT_DELIM.strip() in data + ): + match = re.search( + rf"(.+?)\s*{self.STRUCTURED_COMMENT_DELIM.strip()}\s*(.*)", + data, + ) + structured_comment_dict[structured_comment_key][ + match.group(1) + ] = match.group(2) + if self.debug > 2: + print( + "Structured Comment continuation [" + data + "]" + ) + elif ( + structured_comment_key is not None + and self.STRUCTURED_COMMENT_END not in data + ): + # Don't die on a malformed comment, just warn and carry on + if ( + structured_comment_key + not in structured_comment_dict + ): + warnings.warn( + f"Structured comment not parsed on malformed header line: {line}", + BiopythonParserWarning, + ) + continue + + # The current structured comment has a multiline value + previous_value_line = structured_comment_dict[ + structured_comment_key + ][match.group(1)] + structured_comment_dict[structured_comment_key][ + match.group(1) + ] = (previous_value_line + " " + line.strip()) + elif self.STRUCTURED_COMMENT_END in data: + # End of structured comment + structured_comment_key = None + else: + comment_list.append(data) + if self.debug > 2: + print("Comment continuation [" + data + "]") + else: + # End of the comment + break + if comment_list: + consumer.comment(comment_list) + if structured_comment_dict: + consumer.structured_comment(structured_comment_dict) + del comment_list, structured_comment_key, structured_comment_dict + elif line_type in consumer_dict: + # It's a semi-automatic entry! + # Now, this may be a multi line entry... + while True: + line = next(line_iter) + if line[0 : self.GENBANK_INDENT] == self.GENBANK_SPACER: + data += " " + line[self.GENBANK_INDENT :] + else: + # We now have all the data for this entry: + + # The DEFINITION field must ends with a period + # # see ftp://ftp.ncbi.nih.gov/genbank/gbrel.txt [3.4.5] + # and discussion https://github.com/biopython/biopython/pull/616 + # We consider this period belong to the syntax, not to the data + # So remove it if it exist + if line_type == "DEFINITION" and data.endswith("."): + data = data[:-1] + getattr(consumer, consumer_dict[line_type])(data) + # End of continuation - return to top of loop! + break + else: + if self.debug: + print("Ignoring GenBank header line:\n" % line) + # Read in next line + line = next(line_iter) + except StopIteration: + raise ValueError("Problem in header") from None + + def _feed_misc_lines(self, consumer, lines): + # Deals with a few misc lines between the features and the sequence + lines.append("") + line_iter = iter(lines) + try: + for line in line_iter: + if line.startswith("BASE COUNT"): + line = line[10:].strip() + if line: + if self.debug: + print("base_count = " + line) + consumer.base_count(line) + if line.startswith("ORIGIN"): + line = line[6:].strip() + if line: + if self.debug: + print("origin_name = " + line) + consumer.origin_name(line) + if line.startswith("TLS "): + line = line[3:].strip() + consumer.tls(line) + if line.startswith("TSA "): + line = line[3:].strip() + consumer.tsa(line) + if line.startswith("WGS "): + line = line[3:].strip() + consumer.wgs(line) + if line.startswith("WGS_SCAFLD"): + line = line[10:].strip() + consumer.add_wgs_scafld(line) + if line.startswith("CONTIG"): + line = line[6:].strip() + contig_location = line + while True: + line = next(line_iter) + if not line: + break + elif line[: self.GENBANK_INDENT] == self.GENBANK_SPACER: + # Don't need to preserve the whitespace here. + contig_location += line[self.GENBANK_INDENT :].rstrip() + elif line.startswith("ORIGIN"): + # Strange, seen this in GenPept files via Entrez gbwithparts + line = line[6:].strip() + if line: + consumer.origin_name(line) + break + else: + raise ValueError( + "Expected CONTIG continuation line, got:\n" + line + ) + consumer.contig_location(contig_location) + return + except StopIteration: + raise ValueError("Problem in misc lines before sequence") from None diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b947bc89431dce1a4cb089412a12935839949097 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/__init__.py @@ -0,0 +1,1206 @@ +# Copyright 2000 by Jeffrey Chang, Brad Chapman. All rights reserved. +# Copyright 2006-2017 by Peter Cock. 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 GenBank formatted files. + +Rather than using Bio.GenBank, you are now encouraged to use Bio.SeqIO with +the "genbank" or "embl" format names to parse GenBank or EMBL files into +SeqRecord and SeqFeature objects (see the Biopython tutorial for details). + +Using Bio.GenBank directly to parse GenBank files is only useful if you want +to obtain GenBank-specific Record objects, which is a much closer +representation to the raw file contents than the SeqRecord alternative from +the FeatureParser (used in Bio.SeqIO). + +To use the Bio.GenBank parser, there are two helper functions: + + - read Parse a handle containing a single GenBank record + as Bio.GenBank specific Record objects. + - parse Iterate over a handle containing multiple GenBank + records as Bio.GenBank specific Record objects. + +The following internal classes are not intended for direct use and may +be deprecated in a future release. + +Classes: + - Iterator Iterate through a file of GenBank entries + - FeatureParser Parse GenBank data in SeqRecord and SeqFeature objects. + - RecordParser Parse GenBank data into a Record object. + +Exceptions: + - ParserFailureError Exception indicating a failure in the parser (ie. + scanner or consumer) + +""" + +import re +import warnings + +from Bio import BiopythonParserWarning +from Bio.Seq import Seq +from Bio.SeqFeature import Location +from Bio.SeqFeature import LocationParserError +from Bio.SeqFeature import Reference +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation + +from .Scanner import GenBankScanner +from .utils import FeatureValueCleaner + +# Constants used to parse GenBank header lines +GENBANK_INDENT = 12 +GENBANK_SPACER = " " * GENBANK_INDENT + +# Constants for parsing GenBank feature lines +FEATURE_KEY_INDENT = 5 +FEATURE_QUALIFIER_INDENT = 21 +FEATURE_KEY_SPACER = " " * FEATURE_KEY_INDENT +FEATURE_QUALIFIER_SPACER = " " * FEATURE_QUALIFIER_INDENT + + +class Iterator: + """Iterator interface to move over a file of GenBank entries one at a time (OBSOLETE). + + This class is likely to be deprecated in a future release of Biopython. + Please use Bio.SeqIO.parse(..., format="gb") or Bio.GenBank.parse(...) + for SeqRecord and GenBank specific Record objects respectively instead. + """ + + def __init__(self, handle, parser=None): + """Initialize the iterator. + + Arguments: + - handle - A handle with GenBank entries to iterate through. + - parser - An optional parser to pass the entries through before + returning them. If None, then the raw entry will be returned. + + """ + self.handle = handle + self._parser = parser + + def __next__(self): + """Return the next GenBank record from the handle. + + Will return None if we ran out of records. + """ + if self._parser is None: + lines = [] + while True: + line = self.handle.readline() + if not line: + return None # Premature end of file? + lines.append(line) + if line.rstrip() == "//": + break + return "".join(lines) + try: + return self._parser.parse(self.handle) + except StopIteration: + return None + + def __iter__(self): + """Iterate over the records.""" + return iter(self.__next__, None) + + +class ParserFailureError(ValueError): + """Failure caused by some kind of problem in the parser.""" + + +_cleaner = FeatureValueCleaner() + + +class FeatureParser: + """Parse GenBank files into Seq + Feature objects (OBSOLETE). + + Direct use of this class is discouraged, and may be deprecated in + a future release of Biopython. + + Please use Bio.SeqIO.parse(...) or Bio.SeqIO.read(...) instead. + """ + + def __init__(self, debug_level=0, use_fuzziness=1, feature_cleaner=None): + """Initialize a GenBank parser and Feature consumer. + + Arguments: + - debug_level - An optional argument that species the amount of + debugging information the parser should spit out. By default we have + no debugging info (the fastest way to do things), but if you want + you can set this as high as two and see exactly where a parse fails. + - use_fuzziness - Specify whether or not to use fuzzy representations. + The default is 1 (use fuzziness). + - feature_cleaner - A class which will be used to clean out the + values of features. This class must implement the function + clean_value. GenBank.utils has a "standard" cleaner class, which + is used by default. + + """ + self._scanner = GenBankScanner(debug_level) + self.use_fuzziness = use_fuzziness + if feature_cleaner: + self._cleaner = feature_cleaner + else: + self._cleaner = _cleaner # default + + def parse(self, handle): + """Parse the specified handle.""" + _consumer = _FeatureConsumer(self.use_fuzziness, self._cleaner) + self._scanner.feed(handle, _consumer) + return _consumer.data + + +class RecordParser: + """Parse GenBank files into Record objects (OBSOLETE). + + Direct use of this class is discouraged, and may be deprecated in + a future release of Biopython. + + Please use the Bio.GenBank.parse(...) or Bio.GenBank.read(...) functions + instead. + """ + + def __init__(self, debug_level=0): + """Initialize the parser. + + Arguments: + - debug_level - An optional argument that species the amount of + debugging information the parser should spit out. By default we have + no debugging info (the fastest way to do things), but if you want + you can set this as high as two and see exactly where a parse fails. + + """ + self._scanner = GenBankScanner(debug_level) + + def parse(self, handle): + """Parse the specified handle into a GenBank record.""" + _consumer = _RecordConsumer() + + self._scanner.feed(handle, _consumer) + return _consumer.data + + +class _BaseGenBankConsumer: + """Abstract GenBank consumer providing useful general functions (PRIVATE). + + This just helps to eliminate some duplication in things that most + GenBank consumers want to do. + """ + + # Special keys in GenBank records that we should remove spaces from + # For instance, \translation keys have values which are proteins and + # should have spaces and newlines removed from them. This class + # attribute gives us more control over specific formatting problems. + remove_space_keys = ["translation"] + + def __init__(self): + pass + + @staticmethod + def _split_keywords(keyword_string): + """Split a string of keywords into a nice clean list (PRIVATE).""" + # process the keywords into a python list + if keyword_string == "" or keyword_string == ".": + keywords = "" + elif keyword_string[-1] == ".": + keywords = keyword_string[:-1] + else: + keywords = keyword_string + keyword_list = keywords.split(";") + return [x.strip() for x in keyword_list] + + @staticmethod + def _split_accessions(accession_string): + """Split a string of accession numbers into a list (PRIVATE).""" + # first replace all line feeds with spaces + # Also, EMBL style accessions are split with ';' + accession = accession_string.replace("\n", " ").replace(";", " ") + + return [x.strip() for x in accession.split() if x.strip()] + + @staticmethod + def _split_taxonomy(taxonomy_string): + """Split a string with taxonomy info into a list (PRIVATE).""" + if not taxonomy_string or taxonomy_string == ".": + # Missing data, no taxonomy + return [] + + if taxonomy_string[-1] == ".": + tax_info = taxonomy_string[:-1] + else: + tax_info = taxonomy_string + tax_list = tax_info.split(";") + return [ + item.strip() + for tax_item in tax_list + for item in tax_item.split("\n") + if item + ] + + @staticmethod + def _clean_location(location_string): + """Clean whitespace out of a location string (PRIVATE). + + The location parser isn't a fan of whitespace, so we clean it out + before feeding it into the parser. + """ + # Originally this imported string.whitespace and did a replace + # via a loop. It's simpler to just split on whitespace and rejoin + # the string - and this avoids importing string too. See Bug 2684. + return "".join(location_string.split()) + + @staticmethod + def _remove_newlines(text): + """Remove any newlines in the passed text, returning the new string (PRIVATE).""" + # get rid of newlines in the qualifier value + newlines = ["\n", "\r"] + for ws in newlines: + text = text.replace(ws, "") + + return text + + @staticmethod + def _normalize_spaces(text): + """Replace multiple spaces in the passed text with single spaces (PRIVATE).""" + # get rid of excessive spaces + return " ".join(x for x in text.split(" ") if x) + + @staticmethod + def _remove_spaces(text): + """Remove all spaces from the passed text (PRIVATE).""" + return text.replace(" ", "") + + @staticmethod + def _convert_to_python_numbers(start, end): + """Convert a start and end range to python notation (PRIVATE). + + In GenBank, starts and ends are defined in "biological" coordinates, + where 1 is the first base and [i, j] means to include both i and j. + + In python, 0 is the first base and [i, j] means to include i, but + not j. + + So, to convert "biological" to python coordinates, we need to + subtract 1 from the start, and leave the end and things should + be converted happily. + """ + new_start = start - 1 + new_end = end + + return new_start, new_end + + +class _FeatureConsumer(_BaseGenBankConsumer): + """Create a SeqRecord object with Features to return (PRIVATE). + + Attributes: + - use_fuzziness - specify whether or not to parse with fuzziness in + feature locations. + - feature_cleaner - a class that will be used to provide specialized + cleaning-up of feature values. + + """ + + def __init__(self, use_fuzziness, feature_cleaner=None): + from Bio.SeqRecord import SeqRecord + + _BaseGenBankConsumer.__init__(self) + self.data = SeqRecord(None, id=None) + self.data.id = None + self.data.description = "" + + self._use_fuzziness = use_fuzziness + self._feature_cleaner = feature_cleaner + + self._seq_type = "" + self._seq_data = [] + self._cur_reference = None + self._cur_feature = None + self._expected_size = None + + def locus(self, locus_name): + """Set the locus name is set as the name of the Sequence.""" + self.data.name = locus_name + + def size(self, content): + """Record the sequence length.""" + self._expected_size = int(content) + + def residue_type(self, type): + """Record the sequence type (SEMI-OBSOLETE). + + This reflects the fact that the topology (linear/circular) and + molecule type (e.g. DNA vs RNA) were a single field in early + files. Current GenBank/EMBL files have two fields. + """ + self._seq_type = type.strip() + + def topology(self, topology): + """Validate and record sequence topology. + + The topology argument should be "linear" or "circular" (string). + """ + if topology: + if topology not in ["linear", "circular"]: + raise ParserFailureError( + f"Unexpected topology {topology!r} should be linear or circular" + ) + self.data.annotations["topology"] = topology + + def molecule_type(self, mol_type): + """Validate and record the molecule type (for round-trip etc).""" + if mol_type: + if "circular" in mol_type or "linear" in mol_type: + raise ParserFailureError( + f"Molecule type {mol_type!r} should not include topology" + ) + + # Writing out records will fail if we have a lower case DNA + # or RNA string in here, so upper case it. + # This is a bit ugly, but we don't want to upper case e.g. + # the m in mRNA, but thanks to the strip we lost the spaces + # so we need to index from the back + if mol_type[-3:].upper() in ("DNA", "RNA") and not mol_type[-3:].isupper(): + warnings.warn( + f"Non-upper case molecule type in LOCUS line: {mol_type}", + BiopythonParserWarning, + ) + + self.data.annotations["molecule_type"] = mol_type + + def data_file_division(self, division): + self.data.annotations["data_file_division"] = division + + def date(self, submit_date): + self.data.annotations["date"] = submit_date + + def definition(self, definition): + """Set the definition as the description of the sequence.""" + if self.data.description: + # Append to any existing description + # e.g. EMBL files with two DE lines. + self.data.description += " " + definition + else: + self.data.description = definition + + def accession(self, acc_num): + """Set the accession number as the id of the sequence. + + If we have multiple accession numbers, the first one passed is + used. + """ + new_acc_nums = self._split_accessions(acc_num) + + # Also record them ALL in the annotations + try: + # On the off chance there was more than one accession line: + for acc in new_acc_nums: + # Prevent repeat entries + if acc not in self.data.annotations["accessions"]: + self.data.annotations["accessions"].append(acc) + except KeyError: + self.data.annotations["accessions"] = new_acc_nums + + # if we haven't set the id information yet, add the first acc num + if not self.data.id: + if len(new_acc_nums) > 0: + # self.data.id = new_acc_nums[0] + # Use the FIRST accession as the ID, not the first on this line! + self.data.id = self.data.annotations["accessions"][0] + + def tls(self, content): + self.data.annotations["tls"] = content.split("-") + + def tsa(self, content): + self.data.annotations["tsa"] = content.split("-") + + def wgs(self, content): + self.data.annotations["wgs"] = content.split("-") + + def add_wgs_scafld(self, content): + self.data.annotations.setdefault("wgs_scafld", []).append(content.split("-")) + + def nid(self, content): + self.data.annotations["nid"] = content + + def pid(self, content): + self.data.annotations["pid"] = content + + def version(self, version_id): + # Want to use the versioned accession as the record.id + # This comes from the VERSION line in GenBank files, or the + # obsolete SV line in EMBL. For the new EMBL files we need + # both the version suffix from the ID line and the accession + # from the AC line. + if version_id.count(".") == 1 and version_id.split(".")[1].isdigit(): + self.accession(version_id.split(".")[0]) + self.version_suffix(version_id.split(".")[1]) + elif version_id: + # For backwards compatibility... + self.data.id = version_id + + def project(self, content): + """Handle the information from the PROJECT line as a list of projects. + + e.g.:: + + PROJECT GenomeProject:28471 + + or:: + + PROJECT GenomeProject:13543 GenomeProject:99999 + + This is stored as dbxrefs in the SeqRecord to be consistent with the + projected switch of this line to DBLINK in future GenBank versions. + Note the NCBI plan to replace "GenomeProject:28471" with the shorter + "Project:28471" as part of this transition. + """ + content = content.replace("GenomeProject:", "Project:") + self.data.dbxrefs.extend(p for p in content.split() if p) + + def dblink(self, content): + """Store DBLINK cross references as dbxrefs in our record object. + + This line type is expected to replace the PROJECT line in 2009. e.g. + + During transition:: + + PROJECT GenomeProject:28471 + DBLINK Project:28471 + Trace Assembly Archive:123456 + + Once the project line is dropped:: + + DBLINK Project:28471 + Trace Assembly Archive:123456 + + Note GenomeProject -> Project. + + We'll have to see some real examples to be sure, but based on the + above example we can expect one reference per line. + + Note that at some point the NCBI have included an extra space, e.g.:: + + DBLINK Project: 28471 + + """ + # During the transition period with both PROJECT and DBLINK lines, + # we don't want to add the same cross reference twice. + while ": " in content: + content = content.replace(": ", ":") + if content.strip() not in self.data.dbxrefs: + self.data.dbxrefs.append(content.strip()) + + def version_suffix(self, version): + """Set the version to overwrite the id. + + Since the version provides the same information as the accession + number, plus some extra info, we set this as the id if we have + a version. + """ + # e.g. GenBank line: + # VERSION U49845.1 GI:1293613 + # or the obsolete EMBL line: + # SV U49845.1 + # Scanner calls consumer.version("U49845.1") + # which then calls consumer.version_suffix(1) + # + # e.g. EMBL new line: + # ID X56734; SV 1; linear; mRNA; STD; PLN; 1859 BP. + # Scanner calls consumer.version_suffix(1) + assert version.isdigit() + self.data.annotations["sequence_version"] = int(version) + + def db_source(self, content): + self.data.annotations["db_source"] = content.rstrip() + + def gi(self, content): + self.data.annotations["gi"] = content + + def keywords(self, content): + if "keywords" in self.data.annotations: + # Multi-line keywords, append to list + # Note EMBL states "A keyword is never split between lines." + self.data.annotations["keywords"].extend(self._split_keywords(content)) + else: + self.data.annotations["keywords"] = self._split_keywords(content) + + def segment(self, content): + self.data.annotations["segment"] = content + + def source(self, content): + # Note that some software (e.g. VectorNTI) may produce an empty + # source (rather than using a dot/period as might be expected). + if content == "": + source_info = "" + elif content[-1] == ".": + source_info = content[:-1] + else: + source_info = content + self.data.annotations["source"] = source_info + + def organism(self, content): + self.data.annotations["organism"] = content + + def taxonomy(self, content): + """Record (another line of) the taxonomy lineage.""" + lineage = self._split_taxonomy(content) + try: + self.data.annotations["taxonomy"].extend(lineage) + except KeyError: + self.data.annotations["taxonomy"] = lineage + + def reference_num(self, content): + """Signal the beginning of a new reference object.""" + # if we have a current reference that hasn't been added to + # the list of references, add it. + if self._cur_reference is not None: + self.data.annotations["references"].append(self._cur_reference) + else: + self.data.annotations["references"] = [] + + self._cur_reference = Reference() + + def reference_bases(self, content): + """Attempt to determine the sequence region the reference entails. + + Possible types of information we may have to deal with: + + (bases 1 to 86436) + (sites) + (bases 1 to 105654; 110423 to 111122) + 1 (residues 1 to 182) + """ + # first remove the parentheses + assert content.endswith(")"), content + ref_base_info = content[1:-1] + + all_locations = [] + # parse if we've got 'bases' and 'to' + if "bases" in ref_base_info and "to" in ref_base_info: + # get rid of the beginning 'bases' + ref_base_info = ref_base_info[5:] + locations = self._split_reference_locations(ref_base_info) + all_locations.extend(locations) + elif "residues" in ref_base_info and "to" in ref_base_info: + residues_start = ref_base_info.find("residues") + # get only the information after "residues" + ref_base_info = ref_base_info[(residues_start + len("residues ")) :] + locations = self._split_reference_locations(ref_base_info) + all_locations.extend(locations) + + # make sure if we are not finding information then we have + # the string 'sites' or the string 'bases' + elif ref_base_info == "sites" or ref_base_info.strip() == "bases": + pass + # otherwise raise an error + else: + raise ValueError( + f"Could not parse base info {ref_base_info} in record {self.data.id}" + ) + + self._cur_reference.location = all_locations + + def _split_reference_locations(self, location_string): + """Get reference locations out of a string of reference information (PRIVATE). + + The passed string should be of the form:: + + 1 to 20; 20 to 100 + + This splits the information out and returns a list of location objects + based on the reference locations. + """ + # split possibly multiple locations using the ';' + all_base_info = location_string.split(";") + + new_locations = [] + for base_info in all_base_info: + start, end = base_info.split("to") + new_start, new_end = self._convert_to_python_numbers( + int(start.strip()), int(end.strip()) + ) + this_location = SimpleLocation(new_start, new_end) + new_locations.append(this_location) + return new_locations + + def authors(self, content): + if self._cur_reference.authors: + self._cur_reference.authors += " " + content + else: + self._cur_reference.authors = content + + def consrtm(self, content): + if self._cur_reference.consrtm: + self._cur_reference.consrtm += " " + content + else: + self._cur_reference.consrtm = content + + def title(self, content): + if self._cur_reference is None: + warnings.warn( + "GenBank TITLE line without REFERENCE line.", BiopythonParserWarning + ) + elif self._cur_reference.title: + self._cur_reference.title += " " + content + else: + self._cur_reference.title = content + + def journal(self, content): + if self._cur_reference.journal: + self._cur_reference.journal += " " + content + else: + self._cur_reference.journal = content + + def medline_id(self, content): + self._cur_reference.medline_id = content + + def pubmed_id(self, content): + self._cur_reference.pubmed_id = content + + def remark(self, content): + """Deal with a reference comment.""" + if self._cur_reference.comment: + self._cur_reference.comment += " " + content + else: + self._cur_reference.comment = content + + def comment(self, content): + try: + self.data.annotations["comment"] += "\n" + "\n".join(content) + except KeyError: + self.data.annotations["comment"] = "\n".join(content) + + def structured_comment(self, content): + self.data.annotations["structured_comment"] = content + + def features_line(self, content): + """Get ready for the feature table when we reach the FEATURE line.""" + self.start_feature_table() + + def start_feature_table(self): + """Indicate we've got to the start of the feature table.""" + # make sure we've added on our last reference object + if self._cur_reference is not None: + self.data.annotations["references"].append(self._cur_reference) + self._cur_reference = None + + def feature_key(self, content): + # start a new feature + self._cur_feature = SeqFeature() + self._cur_feature.type = content + self.data.features.append(self._cur_feature) + + def location(self, content): + """Parse out location information from the location string. + + This uses simple Python code with some regular expressions to do the + parsing, and then translates the results into appropriate objects. + """ + # clean up newlines and other whitespace inside the location before + # parsing - locations should have no whitespace whatsoever + location_line = self._clean_location(content) + + # Older records have junk like replace(266,"c") in the + # location line. Newer records just replace this with + # the number 266 and have the information in a more reasonable + # place. So we'll just grab out the number and feed this to the + # parser. We shouldn't really be losing any info this way. + if "replace" in location_line: + comma_pos = location_line.find(",") + location_line = location_line[8:comma_pos] + + length = self._expected_size + # Check if the sequence is circular for features that span the origin + is_circular = "circular" in self.data.annotations.get("topology", "").lower() + stranded = "PROTEIN" not in self._seq_type.upper() + + try: + location = Location.fromstring(location_line, length, is_circular, stranded) + except LocationParserError as e: + warnings.warn( + f"{e}; setting feature location to None.", BiopythonParserWarning + ) + location = None + self._cur_feature.location = location + + def feature_qualifier(self, key, value): + """When we get a qualifier key and its value. + + Can receive None, since you can have valueless keys such as /pseudo + """ + # Hack to try to preserve historical behaviour of /pseudo etc + if value is None: + # if the key doesn't exist yet, add an empty string + if key not in self._cur_feature.qualifiers: + self._cur_feature.qualifiers[key] = [""] + return + # otherwise just skip this key + return + + # Remove enclosing quotation marks + if len(value) > 1 and value[0] == '"' and value[-1] == '"': + value = value[1:-1] + + # Handle NCBI escaping + # Warn if escaping is not according to standard + if re.search(r'[^"]"[^"]|^"[^"]|[^"]"$', value): + warnings.warn( + 'The NCBI states double-quote characters like " should be escaped as "" ' + "(two double - quotes), but here it was not: %r" % value, + BiopythonParserWarning, + ) + # Undo escaping, repeated double quotes -> one double quote + value = value.replace('""', '"') + + if self._feature_cleaner is not None: + value = self._feature_cleaner.clean_value(key, value) + + # if the qualifier name exists, append the value + if key in self._cur_feature.qualifiers: + self._cur_feature.qualifiers[key].append(value) + # otherwise start a new list of the key with its values + else: + self._cur_feature.qualifiers[key] = [value] + + def feature_qualifier_name(self, content_list): + """Use feature_qualifier instead (OBSOLETE).""" + raise NotImplementedError("Use the feature_qualifier method instead.") + + def feature_qualifier_description(self, content): + """Use feature_qualifier instead (OBSOLETE).""" + raise NotImplementedError("Use the feature_qualifier method instead.") + + def contig_location(self, content): + """Deal with CONTIG information.""" + # Historically this was stored as a SeqFeature object, but it was + # stored under record.annotations["contig"] and not under + # record.features with the other SeqFeature objects. + # + # The CONTIG location line can include additional tokens like + # Gap(), Gap(100) or Gap(unk100) which are not used in the feature + # location lines, so storing it using SeqFeature based location + # objects is difficult. + # + # We now store this a string, which means for BioSQL we are now in + # much better agreement with how BioPerl records the CONTIG line + # in the database. + # + # NOTE - This code assumes the scanner will return all the CONTIG + # lines already combined into one long string! + self.data.annotations["contig"] = content + + def origin_name(self, content): + pass + + def base_count(self, content): + pass + + def base_number(self, content): + pass + + def sequence(self, content): + """Add up sequence information as we get it. + + To try and make things speedier, this puts all of the strings + into a list of strings, and then uses string.join later to put + them together. Supposedly, this is a big time savings + """ + assert " " not in content + self._seq_data.append(content.upper()) + + def record_end(self, content): + """Clean up when we've finished the record.""" + # Try and append the version number to the accession for the full id + if not self.data.id: + if "accessions" in self.data.annotations: + raise ValueError( + "Problem adding version number to accession: " + + str(self.data.annotations["accessions"]) + ) + self.data.id = self.data.name # Good fall back? + elif self.data.id.count(".") == 0: + try: + self.data.id += ".%i" % self.data.annotations["sequence_version"] + except KeyError: + pass + + # add the sequence information + + sequence = "".join(self._seq_data) + + if ( + self._expected_size is not None + and len(sequence) != 0 + and self._expected_size != len(sequence) + ): + warnings.warn( + "Expected sequence length %i, found %i (%s)." + % (self._expected_size, len(sequence), self.data.id), + BiopythonParserWarning, + ) + + molecule_type = None + if self._seq_type: + # mRNA is really also DNA, since it is actually cDNA + if "DNA" in self._seq_type.upper() or "MRNA" in self._seq_type.upper(): + molecule_type = "DNA" + # are there ever really RNA sequences in GenBank? + elif "RNA" in self._seq_type.upper(): + # Even for data which was from RNA, the sequence string + # is usually given as DNA (T not U). Bug 3010 + molecule_type = "RNA" + elif ( + "PROTEIN" in self._seq_type.upper() or self._seq_type == "PRT" + ): # PRT is used in EMBL-bank for patents + molecule_type = "protein" + # work around ugly GenBank records which have circular or + # linear but no indication of sequence type + elif self._seq_type in ["circular", "linear", "unspecified"]: + pass + # we have a bug if we get here + else: + raise ValueError( + f"Could not determine molecule_type for seq_type {self._seq_type}" + ) + # Don't overwrite molecule_type + if molecule_type is not None: + self.data.annotations["molecule_type"] = self.data.annotations.get( + "molecule_type", molecule_type + ) + if not sequence and self._expected_size: + self.data.seq = Seq(None, length=self._expected_size) + else: + self.data.seq = Seq(sequence) + + +class _RecordConsumer(_BaseGenBankConsumer): + """Create a GenBank Record object from scanner generated information (PRIVATE).""" + + def __init__(self): + _BaseGenBankConsumer.__init__(self) + from . import Record + + self.data = Record.Record() + + self._seq_data = [] + self._cur_reference = None + self._cur_feature = None + self._cur_qualifier = None + + def tls(self, content): + self.data.tls = content.split("-") + + def tsa(self, content): + self.data.tsa = content.split("-") + + def wgs(self, content): + self.data.wgs = content.split("-") + + def add_wgs_scafld(self, content): + self.data.wgs_scafld.append(content.split("-")) + + def locus(self, content): + self.data.locus = content + + def size(self, content): + self.data.size = content + + def residue_type(self, content): + # Be lenient about parsing, but technically lowercase residue types are malformed. + if "dna" in content or "rna" in content: + warnings.warn( + f"Invalid seq_type ({content}): DNA/RNA should be uppercase.", + BiopythonParserWarning, + ) + self.data.residue_type = content + + def data_file_division(self, content): + self.data.data_file_division = content + + def date(self, content): + self.data.date = content + + def definition(self, content): + self.data.definition = content + + def accession(self, content): + for acc in self._split_accessions(content): + if acc not in self.data.accession: + self.data.accession.append(acc) + + def molecule_type(self, mol_type): + """Validate and record the molecule type (for round-trip etc).""" + if mol_type: + if "circular" in mol_type or "linear" in mol_type: + raise ParserFailureError( + f"Molecule type {mol_type!r} should not include topology" + ) + + # Writing out records will fail if we have a lower case DNA + # or RNA string in here, so upper case it. + # This is a bit ugly, but we don't want to upper case e.g. + # the m in mRNA, but thanks to the strip we lost the spaces + # so we need to index from the back + if mol_type[-3:].upper() in ("DNA", "RNA") and not mol_type[-3:].isupper(): + warnings.warn( + f"Non-upper case molecule type in LOCUS line: {mol_type}", + BiopythonParserWarning, + ) + + self.data.molecule_type = mol_type + + def topology(self, topology): + """Validate and record sequence topology. + + The topology argument should be "linear" or "circular" (string). + """ + if topology: + if topology not in ["linear", "circular"]: + raise ParserFailureError( + f"Unexpected topology {topology!r} should be linear or circular" + ) + self.data.topology = topology + + def nid(self, content): + self.data.nid = content + + def pid(self, content): + self.data.pid = content + + def version(self, content): + self.data.version = content + + def db_source(self, content): + self.data.db_source = content.rstrip() + + def gi(self, content): + self.data.gi = content + + def keywords(self, content): + self.data.keywords = self._split_keywords(content) + + def project(self, content): + self.data.projects.extend(p for p in content.split() if p) + + def dblink(self, content): + self.data.dblinks.append(content) + + def segment(self, content): + self.data.segment = content + + def source(self, content): + self.data.source = content + + def organism(self, content): + self.data.organism = content + + def taxonomy(self, content): + self.data.taxonomy = self._split_taxonomy(content) + + def reference_num(self, content): + """Grab the reference number and signal the start of a new reference.""" + # check if we have a reference to add + if self._cur_reference is not None: + self.data.references.append(self._cur_reference) + + from . import Record + + self._cur_reference = Record.Reference() + self._cur_reference.number = content + + def reference_bases(self, content): + self._cur_reference.bases = content + + def authors(self, content): + self._cur_reference.authors = content + + def consrtm(self, content): + self._cur_reference.consrtm = content + + def title(self, content): + if self._cur_reference is None: + warnings.warn( + "GenBank TITLE line without REFERENCE line.", BiopythonParserWarning + ) + return + self._cur_reference.title = content + + def journal(self, content): + self._cur_reference.journal = content + + def medline_id(self, content): + self._cur_reference.medline_id = content + + def pubmed_id(self, content): + self._cur_reference.pubmed_id = content + + def remark(self, content): + self._cur_reference.remark = content + + def comment(self, content): + self.data.comment += "\n".join(content) + + def structured_comment(self, content): + self.data.structured_comment = content + + def primary_ref_line(self, content): + """Save reference data for the PRIMARY line.""" + self.data.primary.append(content) + + def primary(self, content): + pass + + def features_line(self, content): + """Get ready for the feature table when we reach the FEATURE line.""" + self.start_feature_table() + + def start_feature_table(self): + """Signal the start of the feature table.""" + # we need to add on the last reference + if self._cur_reference is not None: + self.data.references.append(self._cur_reference) + + def feature_key(self, content): + """Grab the key of the feature and signal the start of a new feature.""" + # first add on feature information if we've got any + self._add_feature() + + from . import Record + + self._cur_feature = Record.Feature() + self._cur_feature.key = content + + def _add_feature(self): + """Add a feature to the record, with relevant checks (PRIVATE). + + This does all of the appropriate checking to make sure we haven't + left any info behind, and that we are only adding info if it + exists. + """ + if self._cur_feature is not None: + # if we have a left over qualifier, add it to the qualifiers + # on the current feature + if self._cur_qualifier is not None: + self._cur_feature.qualifiers.append(self._cur_qualifier) + + self._cur_qualifier = None + self.data.features.append(self._cur_feature) + + def location(self, content): + self._cur_feature.location = self._clean_location(content) + + def feature_qualifier(self, key, value): + self.feature_qualifier_name([key]) + if value is not None: + self.feature_qualifier_description(value) + + def feature_qualifier_name(self, content_list): + """Deal with qualifier names. + + We receive a list of keys, since you can have valueless keys such as + /pseudo which would be passed in with the next key (since no other + tags separate them in the file) + """ + from . import Record + + for content in content_list: + # the record parser keeps the /s -- add them if we don't have 'em + if not content.startswith("/"): + content = f"/{content}" + # add on a qualifier if we've got one + if self._cur_qualifier is not None: + self._cur_feature.qualifiers.append(self._cur_qualifier) + + self._cur_qualifier = Record.Qualifier() + self._cur_qualifier.key = content + + def feature_qualifier_description(self, content): + # if we have info then the qualifier key should have a ='s + if "=" not in self._cur_qualifier.key: + self._cur_qualifier.key = f"{self._cur_qualifier.key}=" + cur_content = self._remove_newlines(content) + # remove all spaces from the value if it is a type where spaces + # are not important + for remove_space_key in self.__class__.remove_space_keys: + if remove_space_key in self._cur_qualifier.key: + cur_content = self._remove_spaces(cur_content) + self._cur_qualifier.value = self._normalize_spaces(cur_content) + + def base_count(self, content): + self.data.base_counts = content + + def origin_name(self, content): + self.data.origin = content + + def contig_location(self, content): + """Signal that we have contig information to add to the record.""" + self.data.contig = self._clean_location(content) + + def sequence(self, content): + """Add sequence information to a list of sequence strings. + + This removes spaces in the data and uppercases the sequence, and + then adds it to a list of sequences. Later on we'll join this + list together to make the final sequence. This is faster than + adding on the new string every time. + """ + assert " " not in content + self._seq_data.append(content.upper()) + + def record_end(self, content): + """Signal the end of the record and do any necessary clean-up.""" + # add together all of the sequence parts to create the + # final sequence string + self.data.sequence = "".join(self._seq_data) + # add on the last feature + self._add_feature() + + +def parse(handle): + """Iterate over GenBank formatted entries as Record objects. + + >>> from Bio import GenBank + >>> with open("GenBank/NC_000932.gb") as handle: + ... for record in GenBank.parse(handle): + ... print(record.accession) + ['NC_000932'] + + To get SeqRecord objects use Bio.SeqIO.parse(..., format="gb") + instead. + """ + return iter(Iterator(handle, RecordParser())) + + +def read(handle): + """Read a handle containing a single GenBank entry as a Record object. + + >>> from Bio import GenBank + >>> with open("GenBank/NC_000932.gb") as handle: + ... record = GenBank.read(handle) + ... print(record.accession) + ['NC_000932'] + + To get a SeqRecord object use Bio.SeqIO.read(..., format="gb") + instead. + """ + iterator = parse(handle) + try: + record = next(iterator) + except StopIteration: + raise ValueError("No records found in handle") from None + try: + next(iterator) + raise ValueError("More than one record found in handle") + except StopIteration: + pass + return record + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/utils.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..60c91f8715a812687325a1e1f0d6e81b0fefb007 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/utils.py @@ -0,0 +1,66 @@ +# 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. +# + +"""Useful utilities for helping in parsing GenBank files.""" + + +class FeatureValueCleaner: + r"""Provide specialized capabilities for cleaning up values in features. + + This class is designed to provide a mechanism to clean up and process + values in the key/value pairs of GenBank features. This is useful + because in cases like:: + + /translation="MED + YDPWNLRFQSKYKSRDA" + + you'll otherwise end up with white space in it. + + This cleaning needs to be done on a case by case basis since it is + impossible to interpret whether you should be concatenating everything + (as in translations), or combining things with spaces (as might be + the case with /notes). + + >>> cleaner = FeatureValueCleaner(["translation"]) + >>> cleaner + FeatureValueCleaner(['translation']) + >>> cleaner.clean_value("translation", "MED\nYDPWNLRFQSKYKSRDA") + 'MEDYDPWNLRFQSKYKSRDA' + """ + + keys_to_process = ["translation"] + + def __init__(self, to_process=keys_to_process): + """Initialize with the keys we should deal with.""" + self._to_process = to_process + + def __repr__(self): + """Return a string representation of the class.""" + return f"{self.__class__.__name__}({self._to_process!r})" + + def clean_value(self, key_name, value): + """Clean the specified value and return it. + + If the value is not specified to be dealt with, the original value + will be returned. + """ + if key_name in self._to_process: + try: + cleaner = getattr(self, f"_clean_{key_name}") + except AttributeError: + raise AssertionError(f"No function to clean key: {key_name}") from None + value = cleaner(value) + return value + + def _clean_translation(self, value): + """Concatenate a translation value to one long protein string (PRIVATE).""" + translation_parts = value.split() + return "".join(translation_parts) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/._Record.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/._Record.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/._Record.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/Record.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/Record.py new file mode 100644 index 0000000000000000000000000000000000000000..037ef2c089ff9cab08ccef17c60ab355a9ab37b8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/Record.py @@ -0,0 +1,90 @@ +# Copyright 2001 by Katharine Lindner. All rights reserved. +# Copyright 2006 by PeterC. 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. + +"""Hold GEO data in a straightforward format. + +classes: +o Record - All of the information in an GEO record. + +See http://www.ncbi.nlm.nih.gov/geo/ +""" + + +class Record: + """Hold GEO information in a format similar to the original record. + + The Record class is meant to make data easy to get to when you are + just interested in looking at GEO data. + + Attributes: + entity_type + entity_id + entity_attributes + col_defs + table_rows + + """ + + def __init__(self): + """Initialize the class.""" + self.entity_type = "" + self.entity_id = "" + self.entity_attributes = {} + self.col_defs = {} + self.table_rows = [] + + def __str__(self): + """Return the GEO record as a string.""" + output = "" + output += f"GEO Type: {self.entity_type}\n" + output += f"GEO Id: {self.entity_id}\n" + att_keys = sorted(self.entity_attributes) + for key in att_keys: + contents = self.entity_attributes[key] + if isinstance(contents, list): + for item in contents: + try: + output += f"{key}: {item[:40]}\n" + output += out_block(item[40:]) + except Exception: # TODO: IndexError? + pass + elif isinstance(contents, str): + output += f"{key}: {contents[:40]}\n" + output += out_block(contents[40:]) + else: + raise RuntimeError(f"unexpected contents of type {type(contents)}") + col_keys = sorted(self.col_defs) + output += "Column Header Definitions\n" + for key in col_keys: + val = self.col_defs[key] + output += f" {key}: {val[:40]}\n" + output += out_block(val[40:], " ") + # May have to display VERY large tables, + # so only show the first 20 lines of data + MAX_ROWS = 20 + 1 # include header in count + for row in self.table_rows[0:MAX_ROWS]: + output += f"{self.table_rows.index(row)}: " + for col in row: + output += f"{col}\t" + output += "\n" + if len(self.table_rows) > MAX_ROWS: + output += "...\n" + row = self.table_rows[-1] + output += f"{self.table_rows.index(row)}: " + for col in row: + output += f"{col}\t" + output += "\n" + + return output + + +def out_block(text, prefix=""): + """Format text in blocks of 80 chars with an additional optional prefix.""" + output = "" + for j in range(0, len(text), 80): + output += f"{prefix}{text[j : j + 80]}\n" + output += "\n" + return output diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6735e9afb7878c2b8ce2aab6e1eca9b09ad53eb1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__init__.py @@ -0,0 +1,67 @@ +# Copyright 2001 by Katharine Lindner. All rights reserved. +# Copyright 2006 by PeterC. All rights reserved. +# 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. +"""Parser for files from NCBI's Gene Expression Omnibus (GEO). + +http://www.ncbi.nlm.nih.gov/geo/ +""" + +from . import Record + + +def _read_key_value(line): + words = line[1:].split("=", 1) + try: + key, value = words + value = value.strip() + except ValueError: + key = words[0] + value = "" + key = key.strip() + return key, value + + +def parse(handle): + """Read Gene Expression Omnibus records from file handle. + + Returns a generator object which yields Bio.Geo.Record() objects. + """ + record = None + for line in handle: + line = line.strip("\n").strip("\r") + if not line: + continue # Ignore empty lines + c = line[0] + if c == "^": + if record: + yield record + record = Record.Record() + record.entity_type, record.entity_id = _read_key_value(line) + elif c == "!": + if line in ( + "!Sample_table_begin", + "!Sample_table_end", + "!Platform_table_begin", + "!Platform_table_end", + ): + continue + key, value = _read_key_value(line) + if key in record.entity_attributes: + if isinstance(record.entity_attributes[key], list): + record.entity_attributes[key].append(value) + else: + existing = record.entity_attributes[key] + record.entity_attributes[key] = [existing, value] + else: + record.entity_attributes[key] = value + elif c == "#": + key, value = _read_key_value(line) + assert key not in record.col_defs + record.col_defs[key] = value + else: + row = line.split("\t") + record.table_rows.append(row) + yield record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._BasicChromosome.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._BasicChromosome.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._BasicChromosome.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._ColorSpiral.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._ColorSpiral.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._ColorSpiral.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._Comparative.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._Comparative.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._Comparative.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._DisplayRepresentation.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._DisplayRepresentation.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._DisplayRepresentation.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._Distribution.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._Distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._Distribution.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._GenomeDiagram b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._GenomeDiagram new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._GenomeDiagram differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._KGML_vis.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._KGML_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/._KGML_vis.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/BasicChromosome.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/BasicChromosome.py new file mode 100644 index 0000000000000000000000000000000000000000..c54d7cba2e9504c734f194b9cc97cc8253f385c7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/BasicChromosome.py @@ -0,0 +1,819 @@ +# Copyright 2001, 2003 by Brad Chapman. All rights reserved. +# Revisions copyright 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. +"""Draw representations of organism chromosomes with added information. + +These classes are meant to model the drawing of pictures of chromosomes. +This can be useful for lots of things, including displaying markers on +a chromosome (ie. for genetic mapping) and showing syteny between two +chromosomes. + +The structure of these classes is intended to be a Composite, so that +it will be easy to plug in and switch different parts without +breaking the general drawing capabilities of the system. The +relationship between classes is that everything derives from +_ChromosomeComponent, which specifies the overall interface. The parts +then are related so that an Organism contains Chromosomes, and these +Chromosomes contain ChromosomeSegments. This representation differs +from the canonical composite structure in that we don't really have +'leaf' nodes here -- all components can potentially hold sub-components. + +Most of the time the ChromosomeSegment class is what you'll want to +customize for specific drawing tasks. + +For providing drawing capabilities, these classes use reportlab: + +http://www.reportlab.com + +This provides nice output in PDF, SVG and postscript. If you have +reportlab's renderPM module installed you can also use PNG etc. +""" + +from reportlab.graphics.shapes import ArcPath +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import Line +from reportlab.graphics.shapes import Rect +from reportlab.graphics.shapes import String +from reportlab.graphics.shapes import Wedge +from reportlab.graphics.widgetbase import Widget +from reportlab.lib import colors +from reportlab.lib.pagesizes import letter +from reportlab.lib.units import inch +from reportlab.pdfbase.pdfmetrics import stringWidth + +from Bio.Graphics import _write +from Bio.Graphics.GenomeDiagram import _Colors + +_color_trans = _Colors.ColorTranslator() + + +class _ChromosomeComponent(Widget): + """Base class specifying the interface for a component of the system. + + This class should not be instantiated directly, but should be used + from derived classes. + """ + + def __init__(self): + """Initialize a chromosome component. + + Attributes: + - _sub_components -- Any components which are contained under + this parent component. This attribute should be accessed through + the add() and remove() functions. + + """ + self._sub_components = [] + + def add(self, component): + """Add a sub_component to the list of components under this item.""" + if not isinstance(component, _ChromosomeComponent): + raise TypeError(f"Expected a _ChromosomeComponent object, got {component}") + + self._sub_components.append(component) + + def remove(self, component): + """Remove the specified component from the subcomponents. + + Raises a ValueError if the component is not registered as a + sub_component. + """ + try: + self._sub_components.remove(component) + except ValueError: + raise ValueError( + f"Component {component} not found in sub_components." + ) from None + + def draw(self): + """Draw the specified component.""" + raise AssertionError("Subclasses must implement.") + + +class Organism(_ChromosomeComponent): + """Top level class for drawing chromosomes. + + This class holds information about an organism and all of its + chromosomes, and provides the top level object which could be used + for drawing a chromosome representation of an organism. + + Chromosomes should be added and removed from the Organism via the + add and remove functions. + """ + + def __init__(self, output_format="pdf"): + """Initialize the class.""" + _ChromosomeComponent.__init__(self) + + # customizable attributes + self.page_size = letter + self.title_size = 20 + + # Do we need this given we don't draw a legend? + # If so, should be a public API... + self._legend_height = 0 # 2 * inch + + self.output_format = output_format + + def draw(self, output_file, title): + """Draw out the information for the Organism. + + Arguments: + - output_file -- The name of a file specifying where the + document should be saved, or a handle to be written to. + The output format is set when creating the Organism object. + Alternatively, output_file=None will return the drawing using + the low-level ReportLab objects (for further processing, such + as adding additional graphics, before writing). + - title -- The output title of the produced document. + + """ + width, height = self.page_size + cur_drawing = Drawing(width, height) + + self._draw_title(cur_drawing, title, width, height) + + cur_x_pos = inch * 0.5 + if len(self._sub_components) > 0: + x_pos_change = (width - inch) / len(self._sub_components) + # no sub_components + else: + pass + + for sub_component in self._sub_components: + # set the drawing location of the chromosome + sub_component.start_x_position = cur_x_pos + 0.05 * x_pos_change + sub_component.end_x_position = cur_x_pos + 0.95 * x_pos_change + sub_component.start_y_position = height - 1.5 * inch + sub_component.end_y_position = self._legend_height + 1 * inch + + # do the drawing + sub_component.draw(cur_drawing) + + # update the locations for the next chromosome + cur_x_pos += x_pos_change + + self._draw_legend(cur_drawing, self._legend_height + 0.5 * inch, width) + + if output_file is None: + # Let the user take care of writing to the file... + return cur_drawing + + return _write(cur_drawing, output_file, self.output_format) + + def _draw_title(self, cur_drawing, title, width, height): + """Write out the title of the organism figure (PRIVATE).""" + title_string = String(width / 2, height - inch, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _draw_legend(self, cur_drawing, start_y, width): + """Draw a legend for the figure (PRIVATE). + + Subclasses should implement this (see also self._legend_height) to + provide specialized legends. + """ + + +class Chromosome(_ChromosomeComponent): + """Class for drawing a chromosome of an organism. + + This organizes the drawing of a single organisms chromosome. This + class can be instantiated directly, but the draw method makes the + most sense to be called in the context of an organism. + """ + + def __init__(self, chromosome_name): + """Initialize a Chromosome for drawing. + + Arguments: + - chromosome_name - The label for the chromosome. + + Attributes: + - start_x_position, end_x_position - The x positions on the page + where the chromosome should be drawn. This allows multiple + chromosomes to be drawn on a single page. + - start_y_position, end_y_position - The y positions on the page + where the chromosome should be contained. + + Configuration Attributes: + - title_size - The size of the chromosome title. + - scale_num - A number of scale the drawing by. This is useful if + you want to draw multiple chromosomes of different sizes at the + same scale. If this is not set, then the chromosome drawing will + be scaled by the number of segments in the chromosome (so each + chromosome will be the exact same final size). + + """ + _ChromosomeComponent.__init__(self) + + self._name = chromosome_name + + self.start_x_position = -1 + self.end_x_position = -1 + self.start_y_position = -1 + self.end_y_position = -1 + + self.title_size = 20 + self.scale_num = None + + self.label_size = 6 + self.chr_percent = 0.25 + self.label_sep_percent = self.chr_percent * 0.5 + self._color_labels = False + + def subcomponent_size(self): + """Return the scaled size of all subcomponents of this component.""" + total_sub = 0 + for sub_component in self._sub_components: + total_sub += sub_component.scale + + return total_sub + + def draw(self, cur_drawing): + """Draw a chromosome on the specified template. + + Ideally, the x_position and y_*_position attributes should be + set prior to drawing -- otherwise we're going to have some problems. + """ + for position in ( + self.start_x_position, + self.end_x_position, + self.start_y_position, + self.end_y_position, + ): + assert position != -1, "Need to set drawing coordinates." + + # first draw all of the sub-sections of the chromosome -- this + # will actually be the picture of the chromosome + cur_y_pos = self.start_y_position + if self.scale_num: + y_pos_change = ( + self.start_y_position * 0.95 - self.end_y_position + ) / self.scale_num + elif len(self._sub_components) > 0: + y_pos_change = ( + self.start_y_position * 0.95 - self.end_y_position + ) / self.subcomponent_size() + # no sub_components to draw + else: + pass + + left_labels = [] + right_labels = [] + for sub_component in self._sub_components: + this_y_pos_change = sub_component.scale * y_pos_change + + # set the location of the component to draw + sub_component.start_x_position = self.start_x_position + sub_component.end_x_position = self.end_x_position + sub_component.start_y_position = cur_y_pos + sub_component.end_y_position = cur_y_pos - this_y_pos_change + + # draw the sub component + sub_component._left_labels = [] + sub_component._right_labels = [] + sub_component.draw(cur_drawing) + left_labels += sub_component._left_labels + right_labels += sub_component._right_labels + + # update the position for the next component + cur_y_pos -= this_y_pos_change + + self._draw_labels(cur_drawing, left_labels, right_labels) + self._draw_label(cur_drawing, self._name) + + def _draw_label(self, cur_drawing, label_name): + """Draw a label for the chromosome (PRIVATE).""" + x_position = 0.5 * (self.start_x_position + self.end_x_position) + y_position = self.end_y_position + + label_string = String(x_position, y_position, label_name) + label_string.fontName = "Times-BoldItalic" + label_string.fontSize = self.title_size + label_string.textAnchor = "middle" + + cur_drawing.add(label_string) + + def _draw_labels(self, cur_drawing, left_labels, right_labels): + """Layout and draw sub-feature labels for the chromosome (PRIVATE). + + Tries to place each label at the same vertical position as the + feature it applies to, but will adjust the positions to avoid or + at least reduce label overlap. + + Draws the label text and a coloured line linking it to the + location (i.e. feature) it applies to. + """ + if not self._sub_components: + return + color_label = self._color_labels + + segment_width = (self.end_x_position - self.start_x_position) * self.chr_percent + label_sep = ( + self.end_x_position - self.start_x_position + ) * self.label_sep_percent + segment_x = self.start_x_position + 0.5 * ( + self.end_x_position - self.start_x_position - segment_width + ) + + y_limits = [ + limit + for sub_component in self._sub_components + for limit in (sub_component.start_y_position, sub_component.end_y_position) + ] + y_min = min(y_limits) + y_max = max(y_limits) + del y_limits + # Now do some label placement magic... + # from reportlab.pdfbase import pdfmetrics + # font = pdfmetrics.getFont('Helvetica') + # h = (font.face.ascent + font.face.descent) * 0.90 + h = self.label_size + for x1, x2, labels, anchor in [ + ( + segment_x, + segment_x - label_sep, + _place_labels(left_labels, y_min, y_max, h), + "end", + ), + ( + segment_x + segment_width, + segment_x + segment_width + label_sep, + _place_labels(right_labels, y_min, y_max, h), + "start", + ), + ]: + for y1, y2, color, back_color, name in labels: + cur_drawing.add( + Line(x1, y1, x2, y2, strokeColor=color, strokeWidth=0.25) + ) + label_string = String(x2, y2, name, textAnchor=anchor) + label_string.fontName = "Helvetica" + label_string.fontSize = h + if color_label: + label_string.fillColor = color + if back_color: + w = stringWidth(name, label_string.fontName, label_string.fontSize) + if x1 > x2: + w = w * -1.0 + cur_drawing.add( + Rect( + x2, + y2 - 0.1 * h, + w, + h, + strokeColor=back_color, + fillColor=back_color, + ) + ) + cur_drawing.add(label_string) + + +class ChromosomeSegment(_ChromosomeComponent): + """Draw a segment of a chromosome. + + This class provides the important configurable functionality of drawing + a Chromosome. Each segment has some customization available here, or can + be subclassed to define additional functionality. Most of the interesting + drawing stuff is likely to happen at the ChromosomeSegment level. + """ + + def __init__(self): + """Initialize a ChromosomeSegment. + + Attributes: + - start_x_position, end_x_position - Defines the x range we have + to draw things in. + - start_y_position, end_y_position - Defines the y range we have + to draw things in. + + Configuration Attributes: + - scale - A scaling value for the component. By default this is + set at 1 (ie -- has the same scale as everything else). Higher + values give more size to the component, smaller values give less. + - fill_color - A color to fill in the segment with. Colors are + available in reportlab.lib.colors + - label - A label to place on the chromosome segment. This should + be a text string specifying what is to be included in the label. + - label_size - The size of the label. + - chr_percent - The percentage of area that the chromosome + segment takes up. + + """ + _ChromosomeComponent.__init__(self) + + self.start_x_position = -1 + self.end_x_position = -1 + self.start_y_position = -1 + self.end_y_position = -1 + + # --- attributes for configuration + self.scale = 1 + self.fill_color = None + self.label = None + self.label_size = 6 + self.chr_percent = 0.25 + + def draw(self, cur_drawing): + """Draw a chromosome segment. + + Before drawing, the range we are drawing in needs to be set. + """ + for position in ( + self.start_x_position, + self.end_x_position, + self.start_y_position, + self.end_y_position, + ): + assert position != -1, "Need to set drawing coordinates." + + self._draw_subcomponents(cur_drawing) # Anything behind + self._draw_segment(cur_drawing) + self._overdraw_subcomponents(cur_drawing) # Anything on top + self._draw_label(cur_drawing) + + def _draw_subcomponents(self, cur_drawing): + """Draw any subcomponents of the chromosome segment (PRIVATE). + + This should be overridden in derived classes if there are + subcomponents to be drawn. + """ + + def _draw_segment(self, cur_drawing): + """Draw the current chromosome segment (PRIVATE).""" + # set the coordinates of the segment -- it'll take up the MIDDLE part + # of the space we have. + segment_y = self.end_y_position + segment_width = (self.end_x_position - self.start_x_position) * self.chr_percent + segment_height = self.start_y_position - self.end_y_position + segment_x = self.start_x_position + 0.5 * ( + self.end_x_position - self.start_x_position - segment_width + ) + + # first draw the sides of the segment + right_line = Line(segment_x, segment_y, segment_x, segment_y + segment_height) + left_line = Line( + segment_x + segment_width, + segment_y, + segment_x + segment_width, + segment_y + segment_height, + ) + + cur_drawing.add(right_line) + cur_drawing.add(left_line) + + # now draw the box, if it is filled in + if self.fill_color is not None: + fill_rectangle = Rect(segment_x, segment_y, segment_width, segment_height) + fill_rectangle.fillColor = self.fill_color + fill_rectangle.strokeColor = None + + cur_drawing.add(fill_rectangle) + + def _overdraw_subcomponents(self, cur_drawing): + """Draw any subcomponents of the chromosome segment over the main part (PRIVATE). + + This should be overridden in derived classes if there are + subcomponents to be drawn. + """ + + def _draw_label(self, cur_drawing): + """Add a label to the chromosome segment (PRIVATE). + + The label will be applied to the right of the segment. + + This may be overlapped by any sub-feature labels on other segments! + """ + if self.label is not None: + label_x = 0.5 * (self.start_x_position + self.end_x_position) + ( + self.chr_percent + 0.05 + ) * (self.end_x_position - self.start_x_position) + label_y = ( + self.start_y_position - self.end_y_position + ) / 2 + self.end_y_position + + label_string = String(label_x, label_y, self.label) + label_string.fontName = "Helvetica" + label_string.fontSize = self.label_size + + cur_drawing.add(label_string) + + +def _spring_layout(desired, minimum, maximum, gap=0): + """Try to layout label coordinates or other floats (PRIVATE). + + Originally written for the y-axis vertical positioning of labels on a + chromosome diagram (where the minimum gap between y-axis coordinates is + the label height), it could also potentially be used for x-axis placement, + or indeed radial placement for circular chromosomes within GenomeDiagram. + + In essence this is an optimisation problem, balancing the desire to have + each label as close as possible to its data point, but also to spread out + the labels to avoid overlaps. This could be described with a cost function + (modelling the label distance from the desired placement, and the inter- + label separations as springs) and solved as a multi-variable minimization + problem - perhaps with NumPy or SciPy. + + For now however, the implementation is a somewhat crude ad hoc algorithm. + + NOTE - This expects the input data to have been sorted! + """ + count = len(desired) + if count <= 1: + return desired # Easy! + if minimum >= maximum: + raise ValueError(f"Bad min/max {minimum:f} and {maximum:f}") + if min(desired) < minimum or max(desired) > maximum: + raise ValueError( + "Data %f to %f out of bounds (%f to %f)" + % (min(desired), max(desired), minimum, maximum) + ) + equal_step = (maximum - minimum) / (count - 1) + + if equal_step < gap: + import warnings + + from Bio import BiopythonWarning + + warnings.warn("Too many labels to avoid overlap", BiopythonWarning) + # Crudest solution + return [minimum + i * equal_step for i in range(count)] + + good = True + if gap: + prev = desired[0] + for next in desired[1:]: + if prev - next < gap: + good = False + break + if good: + return desired + + span = maximum - minimum + for split in [0.5 * span, span / 3.0, 2 * span / 3.0, 0.25 * span, 0.75 * span]: + midpoint = minimum + split + low = [x for x in desired if x <= midpoint - 0.5 * gap] + high = [x for x in desired if x > midpoint + 0.5 * gap] + if len(low) + len(high) < count: + # Bad split point, points right on boundary + continue + elif not low and len(high) * gap <= (span - split) + 0.5 * gap: + # Give a little of the unused low space to the high points + return _spring_layout(high, midpoint + 0.5 * gap, maximum, gap) + elif not high and len(low) * gap <= split + 0.5 * gap: + # Give a little of the unused highspace to the low points + return _spring_layout(low, minimum, midpoint - 0.5 * gap, gap) + elif ( + len(low) * gap <= split - 0.5 * gap + and len(high) * gap <= (span - split) - 0.5 * gap + ): + return _spring_layout( + low, minimum, midpoint - 0.5 * gap, gap + ) + _spring_layout(high, midpoint + 0.5 * gap, maximum, gap) + + # This can be count-productive now we can split out into the telomere or + # spacer-segment's vertical space... + # Try not to spread out as far as the min/max unless needed + low = min(desired) + high = max(desired) + if (high - low) / (count - 1) >= gap: + # Good, we don't need the full range, and can position the + # min and max exactly as well :) + equal_step = (high - low) / (count - 1) + return [low + i * equal_step for i in range(count)] + + low = 0.5 * (minimum + min(desired)) + high = 0.5 * (max(desired) + maximum) + if (high - low) / (count - 1) >= gap: + # Good, we don't need the full range + equal_step = (high - low) / (count - 1) + return [low + i * equal_step for i in range(count)] + + # Crudest solution + return [minimum + i * equal_step for i in range(count)] + + +# assert False, _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) +# assert _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) == \ +# [0.0, 0.125, 0.25, 0.375, 0.5, 0.75, 1.0] +# assert _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) == \ +# [0.0, 0.16666666666666666, 0.33333333333333331, 0.5, +# 0.66666666666666663, 0.83333333333333326, 1.0] + + +def _place_labels(desired_etc, minimum, maximum, gap=0): + # Want a list of lists/tuples for desired_etc + desired_etc.sort() + placed = _spring_layout([row[0] for row in desired_etc], minimum, maximum, gap) + for old, y2 in zip(desired_etc, placed): + # (y1, a, b, c, ..., z) --> (y1, y2, a, b, c, ..., z) + yield (old[0], y2) + tuple(old[1:]) + + +class AnnotatedChromosomeSegment(ChromosomeSegment): + """Annotated chromosome segment. + + This is like the ChromosomeSegment, but accepts a list of features. + """ + + def __init__( + self, + bp_length, + features, + default_feature_color=colors.blue, + name_qualifiers=("gene", "label", "name", "locus_tag", "product"), + ): + """Initialize. + + The features can either be SeqFeature objects, or tuples of values: + start (int), end (int), strand (+1, -1, O or None), label (string), + ReportLab color (string or object), and optional ReportLab fill color. + + Note we require 0 <= start <= end <= bp_length, and within the vertical + space allocated to this segment lines will be places according to the + start/end coordinates (starting from the top). + + Positive stand features are drawn on the right, negative on the left, + otherwise all the way across. + + We recommend using consistent units for all the segment's scale values + (e.g. their length in base pairs). + + When providing features as SeqFeature objects, the default color + is used, unless the feature's qualifiers include an Artemis colour + string (functionality also in GenomeDiagram). The caption also follows + the GenomeDiagram approach and takes the first qualifier from the list + or tuple specified in name_qualifiers. + + Note additional attribute label_sep_percent controls the percentage of + area that the chromosome segment takes up, by default half of the + chr_percent attribute (half of 25%, thus 12.5%) + + """ + ChromosomeSegment.__init__(self) + self.bp_length = bp_length + self.features = features + self.default_feature_color = default_feature_color + self.name_qualifiers = name_qualifiers + self.label_sep_percent = self.chr_percent * 0.5 + + def _overdraw_subcomponents(self, cur_drawing): + """Draw any annotated features on the chromosome segment (PRIVATE). + + Assumes _draw_segment already called to fill out the basic shape, + and assmes that uses the same boundaries. + """ + # set the coordinates of the segment -- it'll take up the MIDDLE part + # of the space we have. + segment_y = self.end_y_position + segment_width = (self.end_x_position - self.start_x_position) * self.chr_percent + label_sep = ( + self.end_x_position - self.start_x_position + ) * self.label_sep_percent + segment_height = self.start_y_position - self.end_y_position + segment_x = self.start_x_position + 0.5 * ( + self.end_x_position - self.start_x_position - segment_width + ) + + left_labels = [] + right_labels = [] + for f in self.features: + try: + # Assume SeqFeature objects + start = f.location.start + end = f.location.end + strand = f.location.strand + try: + # Handles Artemis colour integers, HTML colors, etc + color = _color_trans.translate(f.qualifiers["color"][0]) + except Exception: # TODO: ValueError? + color = self.default_feature_color + fill_color = color + name = "" + for qualifier in self.name_qualifiers: + if qualifier in f.qualifiers: + name = f.qualifiers[qualifier][0] + break + except AttributeError: + # Assume tuple of ints, string, and color + start, end, strand, name, color = f[:5] + color = _color_trans.translate(color) + if len(f) > 5: + fill_color = _color_trans.translate(f[5]) + else: + fill_color = color + assert 0 <= start <= end <= self.bp_length + if strand == +1: + # Right side only + x = segment_x + segment_width * 0.6 + w = segment_width * 0.4 + elif strand == -1: + # Left side only + x = segment_x + w = segment_width * 0.4 + else: + # Both or neither - full width + x = segment_x + w = segment_width + local_scale = segment_height / self.bp_length + fill_rectangle = Rect( + x, + segment_y + segment_height - local_scale * start, + w, + local_scale * (start - end), + ) + fill_rectangle.fillColor = fill_color + fill_rectangle.strokeColor = color + cur_drawing.add(fill_rectangle) + if name: + if fill_color == color: + back_color = None + else: + back_color = fill_color + value = ( + segment_y + segment_height - local_scale * start, + color, + back_color, + name, + ) + if strand == -1: + self._left_labels.append(value) + else: + self._right_labels.append(value) + + +class TelomereSegment(ChromosomeSegment): + """A segment that is located at the end of a linear chromosome. + + This is just like a regular segment, but it draws the end of a chromosome + which is represented by a half circle. This just overrides the + _draw_segment class of ChromosomeSegment to provide that specialized + drawing. + """ + + def __init__(self, inverted=0): + """Initialize a segment at the end of a chromosome. + + See ChromosomeSegment for all of the attributes that can be + customized in a TelomereSegments. + + Arguments: + - inverted -- Whether or not the telomere should be inverted + (ie. drawn on the bottom of a chromosome) + + """ + ChromosomeSegment.__init__(self) + + self._inverted = inverted + + def _draw_segment(self, cur_drawing): + """Draw a half circle representing the end of a linear chromosome (PRIVATE).""" + # set the coordinates of the segment -- it'll take up the MIDDLE part + # of the space we have. + width = (self.end_x_position - self.start_x_position) * self.chr_percent + height = self.start_y_position - self.end_y_position + center_x = 0.5 * (self.end_x_position + self.start_x_position) + start_x = center_x - 0.5 * width + if self._inverted: + center_y = self.start_y_position + start_angle = 180 + end_angle = 360 + else: + center_y = self.end_y_position + start_angle = 0 + end_angle = 180 + + cap_wedge = Wedge(center_x, center_y, width / 2, start_angle, end_angle, height) + cap_wedge.strokeColor = None + cap_wedge.fillColor = self.fill_color + cur_drawing.add(cap_wedge) + + # Now draw an arc for the curved edge of the wedge, + # omitting the flat end. + cap_arc = ArcPath() + cap_arc.addArc(center_x, center_y, width / 2, start_angle, end_angle, height) + cur_drawing.add(cap_arc) + + +class SpacerSegment(ChromosomeSegment): + """A segment that is located at the end of a linear chromosome. + + Doesn't draw anything, just empty space which can be helpful + for layout purposes (e.g. making room for feature labels). + """ + + def draw(self, cur_diagram): + """Draw nothing to the current diagram (dummy method). + + The segment spacer has no actual image in the diagram, + so this method therefore does nothing, but is defined + to match the expected API of the other segment objects. + """ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/ColorSpiral.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/ColorSpiral.py new file mode 100644 index 0000000000000000000000000000000000000000..1186fb7877c23fe3dc09bc2dd0cb77ad2b799b92 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/ColorSpiral.py @@ -0,0 +1,205 @@ +# Copyright 2012 by Leighton Pritchard. 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. +"""Generate RGB colours suitable for distinguishing categorical data. + +This module provides a class that implements a spiral 'path' through HSV +colour space, permitting the selection of a number of points along that path, +and returning the output in RGB colour space, suitable for use with ReportLab +and other graphics packages. + +This approach to colour choice was inspired by Bang Wong's Points of View +article: Color Coding, in Nature Methods _7_ 573 (https://doi.org/10.1038/nmeth0810-573). + +The module also provides helper functions that return a list for colours, or +a dictionary of colours (if passed an iterable containing the names of +categories to be coloured). +""" + +import colorsys # colour format conversions +import random # for jitter values +from math import exp +from math import floor +from math import log +from math import pi + + +class ColorSpiral: + """Implement a spiral path through HSV colour space. + + This class provides functions for sampling points along a logarithmic + spiral path through HSV colour space. + + The spiral is described by r = a * exp(b * t) where r is the distance + from the axis of the HSV cylinder to the current point in the spiral, + and t is the angle through which the spiral has turned to reach the + current point. a and b are (positive, real) parameters that control the + shape of the spiral. + + - a: the starting direction of the spiral + - b: the number of revolutions about the axis made by the spiral + + We permit the spiral to move along the cylinder ('in V-space') between + v_init and v_final, to give a gradation in V (essentially, brightness), + along the path, where v_init, v_final are in [0,1]. + + A brightness 'jitter' may also be provided as an absolute value in + V-space, to aid in distinguishing consecutive colour points on the + path. + """ + + def __init__(self, a=1, b=0.33, v_init=0.85, v_final=0.5, jitter=0.05): + """Initialize a logarithmic spiral path through HSV colour space. + + Arguments: + - a - Parameter a for the spiral, controls the initial spiral + direction. a > 0 + - b - parameter b for the spiral, controls the rate at which the + spiral revolves around the axis. b > 0 + - v_init - initial value of V (brightness) for the spiral. + v_init in [0,1] + - v_final - final value of V (brightness) for the spiral + v_final in [0,1] + - jitter - the degree of V (brightness) jitter to add to each + selected colour. The amount of jitter will be selected + from a uniform random distribution [-jitter, jitter], + and V will be maintained in [0,1]. + + """ + # Initialize attributes + self.a = a + self.b = b + self.v_init = v_init + self.v_final = v_final + self.jitter = jitter + + def get_colors(self, k, offset=0.1): + """Generate k different RBG colours evenly-space on the spiral. + + A generator returning the RGB colour space values for k + evenly-spaced points along the defined spiral in HSV space. + + Arguments: + - k - the number of points to return + - offset - how far along the spiral path to start. + + """ + # We use the offset to skip a number of similar colours near to HSV axis + assert offset > 0 and offset < 1, "offset must be in (0,1)" + v_rate = (self._v_final - self._v_init) / k + # Generator for colours: we have divided the arc length into sections + # of equal length, and step along them + for n in range(1, k + 1): + # For each value of n, t indicates the angle through which the + # spiral has turned, to this point + t = (1.0 / self._b) * ( + log(n + (k * offset)) - log((1 + offset) * k * self._a) + ) + # Put 0 <= h <= 2*pi, where h is the angular part of the polar + # coordinates for this point on the spiral + h = t + while h < 0: + h += 2 * pi + h = h - (floor(h / (2 * pi)) * pi) + # Now put h in [0, 1] for colorsys conversion + h = h / (2 * pi) + # r is the radial distance of this point from the centre + r = self._a * exp(self._b * t) + # v is the brightness of this point, linearly interpolated + # from self._v_init to self._v_final. Jitter size is sampled from + # a uniform distribution + if self._jitter: + jitter = random.random() * 2 * self._jitter - self._jitter + else: + jitter = 0 + v = self._v_init + (n * v_rate + jitter) + # We have arranged the arithmetic such that 0 <= r <= 1, so + # we can use this value directly as s in HSV + yield colorsys.hsv_to_rgb(h, r, max(0, min(v, 1))) + + def _get_a(self): + return self._a + + def _set_a(self, value): + self._a = max(0, value) + + def _get_b(self): + return self._b + + def _set_b(self, value): + self._b = max(0, value) + + def _get_v_init(self): + return self._v_init + + def _set_v_init(self, value): + self._v_init = max(0, min(1, value)) + + def _get_v_final(self): + return self._v_final + + def _set_v_final(self, value): + self._v_final = max(0, min(1, value)) + + def _get_jitter(self): + return self._jitter + + def _set_jitter(self, value): + self._jitter = max(0, min(1, value)) + + a = property( + _get_a, _set_a, doc="Parameter controlling initial spiral direction (a > 0)" + ) + b = property( + _get_b, + _set_b, + doc="Parameter controlling rate spiral revolves around axis (b > 0)", + ) + v_init = property( + _get_v_init, + _set_v_init, + doc="Initial value of V (brightness) for the spiral (range 0 to 1)", + ) + v_final = property( + _get_v_final, + _set_v_final, + doc="Final value of V (brightness) for the spiral (range 0 to 1)", + ) + jitter = property( + _get_jitter, + _set_jitter, + doc="Degree of V (brightness) jitter to add to each color (range 0 to 1)", + ) + + +# Convenience functions for those who don't want to bother with a +# ColorSpiral object +def get_colors(k, **kwargs): + """Return k colours selected by the ColorSpiral object, as a generator. + + Arguments: + - k - the number of colours to return + - kwargs - pass-through arguments to the ColorSpiral object + + """ + cs = ColorSpiral(**kwargs) + return cs.get_colors(k) + + +def get_color_dict(l, **kwargs): # noqa: E741 + """Return a dictionary of colours using the provided values as keys. + + Returns a dictionary, keyed by the members of iterable l, with a + colour assigned to each member. + + Arguments: + - l - an iterable representing classes to be coloured + - kwargs - pass-through arguments to the ColorSpiral object + + """ + cs = ColorSpiral(**kwargs) + colors = cs.get_colors(len(l)) + return dict(zip(l, colors)) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Comparative.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Comparative.py new file mode 100644 index 0000000000000000000000000000000000000000..22dccaa8ff250544d88c3078b8894496180dbfa4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Comparative.py @@ -0,0 +1,181 @@ +# Copyright 2001 by Brad Chapman. 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. +"""Plots to compare information between different sources. + +This file contains high level plots which are designed to be used to +compare different types of information. The most basic example is comparing +two variables in a traditional scatter plot. +""" + +from reportlab.graphics.charts.lineplots import LinePlot +from reportlab.graphics.charts.markers import makeEmptyCircle +from reportlab.graphics.charts.markers import makeEmptySquare +from reportlab.graphics.charts.markers import makeFilledCircle +from reportlab.graphics.charts.markers import makeFilledDiamond +from reportlab.graphics.charts.markers import makeFilledSquare +from reportlab.graphics.charts.markers import makeSmiley +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import String +from reportlab.lib import colors +from reportlab.lib.pagesizes import letter +from reportlab.lib.units import inch + +from Bio.Graphics import _write + + +class ComparativeScatterPlot: + """Display a scatter-type plot comparing two different kinds of info. + + Attributes; + - display_info - a 2D list of the information we'll be outputting. Each + top level list is a different data type, and each data point is a + two-tuple of the coordinates of a point. + + So if you had two distributions of points, it should look like:: + + display_info = [[(1, 2), (3, 4)], + [(5, 6), (7, 8)]] + + If everything is just one set of points, display_info can look like:: + + display_info = [[(1, 2), (3, 4), (5, 6)]] + + """ + + def __init__(self, output_format="pdf"): + """Initialize the class.""" + # customizable attributes + self.number_of_columns = 1 + self.page_size = letter + self.title_size = 20 + + self.output_format = output_format + + # the information we'll be writing + self.display_info = [] + + # initial colors and shapes used for drawing points + self.color_choices = [ + colors.red, + colors.green, + colors.blue, + colors.yellow, + colors.orange, + colors.black, + ] + self.shape_choices = [ + makeFilledCircle, + makeEmptySquare, + makeFilledDiamond, + makeFilledSquare, + makeEmptyCircle, + makeSmiley, + ] + + def draw_to_file(self, output_file, title): + """Write the comparative plot to a file. + + Arguments: + - output_file - The name of the file to output the information to, + or a handle to write to. + - title - A title to display on the graphic. + + """ + width, height = self.page_size + cur_drawing = Drawing(width, height) + + self._draw_title(cur_drawing, title, width, height) + + start_x = inch * 0.5 + end_x = width - inch * 0.5 + end_y = height - 1.5 * inch + start_y = 0.5 * inch + self._draw_scatter_plot(cur_drawing, start_x, start_y, end_x, end_y) + + return _write(cur_drawing, output_file, self.output_format) + + def _draw_title(self, cur_drawing, title, width, height): + """Add a title to the page we are outputting (PRIVATE).""" + title_string = String(width / 2, height - inch, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _draw_scatter_plot(self, cur_drawing, x_start, y_start, x_end, y_end): + """Draw a scatter plot on the drawing with the given coordinates (PRIVATE).""" + scatter_plot = LinePlot() + + # set the dimensions of the scatter plot + scatter_plot.x = x_start + scatter_plot.y = y_start + scatter_plot.width = abs(x_start - x_end) + scatter_plot.height = abs(y_start - y_end) + + scatter_plot.data = self.display_info + + scatter_plot.joinedLines = 0 + + # set the axes of the plot + x_min, x_max, y_min, y_max = self._find_min_max(self.display_info) + scatter_plot.xValueAxis.valueMin = x_min + scatter_plot.xValueAxis.valueMax = x_max + scatter_plot.xValueAxis.valueStep = (x_max - x_min) / 10.0 + + scatter_plot.yValueAxis.valueMin = y_min + scatter_plot.yValueAxis.valueMax = y_max + scatter_plot.yValueAxis.valueStep = (y_max - y_min) / 10.0 + + self._set_colors_and_shapes(scatter_plot, self.display_info) + + cur_drawing.add(scatter_plot) + + def _set_colors_and_shapes(self, scatter_plot, display_info): + """Set the colors and shapes of the points displayed (PRIVATE). + + By default this just sets all of the points according to the order + of colors and shapes defined in self.color_choices and + self.shape_choices. The first 5 shapes and colors are unique, the + rest of them are just set to the same color and shape (since I + ran out of shapes!). + + You can change how this function works by either changing the + values of the color_choices and shape_choices attributes, or + by inheriting from this class and overriding this function. + """ + for value_num in range(len(display_info)): + # if we have unique colors, add them + if (value_num + 1) < len(self.color_choices): + scatter_plot.lines[value_num].strokeColor = self.color_choices[ + value_num + ] + scatter_plot.lines[value_num].symbol = self.shape_choices[value_num] + # otherwise just use the last number + else: + scatter_plot.lines[value_num].strokeColor = self.color_choices[-1] + scatter_plot.lines[value_num].symbol = self.shape_choices[-1] + + def _find_min_max(self, info): + """Find min and max for x and y coordinates in the given data (PRIVATE).""" + x_min = info[0][0][0] + x_max = info[0][0][0] + y_min = info[0][0][1] + y_max = info[0][0][1] + + for two_d_list in info: + for x, y in two_d_list: + if x > x_max: + x_max = x + if x < x_min: + x_min = x + if y > y_max: + y_max = y + if y < y_min: + y_min = y + + return x_min, x_max, y_min, y_max diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/DisplayRepresentation.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/DisplayRepresentation.py new file mode 100644 index 0000000000000000000000000000000000000000..8135ebb8b240ba7479f34b937a1d5f688930fafd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/DisplayRepresentation.py @@ -0,0 +1,183 @@ +# Copyright 2001 by Brad Chapman. 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 information for graphical display. + +Classes in this module are designed to hold information in a way that +makes it easy to draw graphical figures. +""" + +from reportlab.lib import colors + +from Bio.Graphics.BasicChromosome import ChromosomeSegment +from Bio.Graphics.BasicChromosome import TelomereSegment + +# --- constants +# This is a default color scheme based on the light spectrum. +# Based on my vague recollections from biology, this is our friend ROY G. BIV +RAINBOW_COLORS = { + (1, 1): colors.violet, + (2, 2): colors.indigo, + (3, 3): colors.blue, + (4, 4): colors.green, + (5, 5): colors.yellow, + (6, 6): colors.orange, + (7, 20): colors.red, +} + + +class ChromosomeCounts: + """Represent a chromosome with count information. + + This is used to display information about counts along a chromosome. + The segments are expected to have different count information, which + will be displayed using a color scheme. + + I envision using this class when you think that certain regions of + the chromosome will be especially abundant in the counts, and you + want to pick those out. + """ + + def __init__(self, segment_names, color_scheme=RAINBOW_COLORS): + """Initialize a representation of chromosome counts. + + Arguments: + - segment_names - An ordered list of all segment names along + the chromosome. The count and other information will be added + to these. + - color_scheme - A coloring scheme to use in the counts. This + should be a dictionary mapping count ranges to colors (specified + in reportlab.lib.colors). + + """ + self._names = segment_names + self._count_info = {} + self._label_info = {} + self._scale_info = {} + for name in self._names: + self._count_info[name] = 0 + self._label_info[name] = None + self._scale_info[name] = 1 + + self._color_scheme = color_scheme + + def add_count(self, segment_name, count=1): + """Add counts to the given segment name. + + Arguments: + - segment_name - The name of the segment we should add counts to. + If the name is not present, a KeyError will be raised. + - count - The counts to add the current segment. This defaults to + a single count. + + """ + try: + self._count_info[segment_name] += count + except KeyError: + raise KeyError(f"Segment name {segment_name} not found.") from None + + def scale_segment_value(self, segment_name, scale_value=None): + """Divide the counts for a segment by some kind of scale value. + + This is useful if segments aren't represented by raw counts, but + are instead counts divided by some number. + """ + try: + self._count_info[segment_name] /= scale_value + except KeyError: + raise KeyError(f"Segment name {segment_name} not found.") from None + + def add_label(self, segment_name, label): + """Add a label to a specific segment. + + Raises a KeyError is the specified segment name is not found. + """ + if segment_name in self._label_info: + self._label_info[segment_name] = label + else: + raise KeyError(f"Segment name {segment_name} not found.") + + def set_scale(self, segment_name, scale): + """Set the scale for a specific chromosome segment. + + By default all segments have the same scale -- this allows scaling + by the size of the segment. + + Raises a KeyError is the specified segment name is not found. + """ + if segment_name in self._label_info: + self._scale_info[segment_name] = scale + else: + raise KeyError(f"Segment name {segment_name} not found.") + + def get_segment_info(self): + """Retrieve the color and label info about the segments. + + Returns a list consisting of two tuples specifying the counts and + label name for each segment. The list is ordered according to the + original listing of names. Labels are set as None if no label + was specified. + """ + order_info = [] + + for seg_name in self._names: + order_info.append((self._count_info[seg_name], self._label_info[seg_name])) + + return order_info + + def fill_chromosome(self, chromosome): + """Add the collected segment information to a chromosome for drawing. + + Arguments: + - chromosome - A Chromosome graphics object that we can add + chromosome segments to. + + This creates ChromosomeSegment (and TelomereSegment) objects to + fill in the chromosome. The information is derived from the + label and count information, with counts transformed to the + specified color map. + + Returns the chromosome with all of the segments added. + """ + for seg_num in range(len(self._names)): + is_end_segment = 0 + # make the top and bottom telomeres + if seg_num == 0: + cur_segment = TelomereSegment() + is_end_segment = 1 + elif seg_num == len(self._names) - 1: + cur_segment = TelomereSegment(1) + is_end_segment = 1 + # otherwise, they are just regular segments + else: + cur_segment = ChromosomeSegment() + + seg_name = self._names[seg_num] + if self._count_info[seg_name] > 0: + color = self._color_from_count(self._count_info[seg_name]) + cur_segment.fill_color = color + + if self._label_info[seg_name] is not None: + cur_segment.label = self._label_info[seg_name] + + # give end segments extra size so they look right + if is_end_segment: + cur_segment.scale = 3 + else: + cur_segment.scale = self._scale_info[seg_name] + + chromosome.add(cur_segment) + + return chromosome + + def _color_from_count(self, count): + """Translate the given count into a color using the color scheme (PRIVATE).""" + for count_start, count_end in self._color_scheme: + if count >= count_start and count <= count_end: + return self._color_scheme[(count_start, count_end)] + + # if we got here we didn't find a color for the count + raise ValueError(f"Count value {count} was not found in the color scheme.") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Distribution.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..70842ce6dbb60ea24841c6b0a0198c5c295d4c7d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Distribution.py @@ -0,0 +1,252 @@ +# Copyright 2001 by Brad Chapman. 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. +"""Display information distributed across a Chromosome-like object. + +These classes are meant to show the distribution of some kind of information +as it changes across any kind of segment. It was designed with chromosome +distributions in mind, but could also work for chromosome regions, BAC clones +or anything similar. + +Reportlab is used for producing the graphical output. +""" + +import math + +from reportlab.graphics.charts.barcharts import BarChartProperties +from reportlab.graphics.charts.barcharts import VerticalBarChart +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import String +from reportlab.graphics.widgetbase import TypedPropertyCollection +from reportlab.lib import colors +from reportlab.lib.pagesizes import letter +from reportlab.lib.units import inch + +from Bio.Graphics import _write + + +class DistributionPage: + """Display a grouping of distributions on a page. + + This organizes Distributions, and will display them nicely + on a single page. + """ + + def __init__(self, output_format="pdf"): + """Initialize the class.""" + self.distributions = [] + + # customizable attributes + self.number_of_columns = 1 + self.page_size = letter + self.title_size = 20 + + self.output_format = output_format + + def draw(self, output_file, title): + """Draw out the distribution information. + + Arguments: + - output_file - The name of the file to output the information to, + or a handle to write to. + - title - A title to display on the graphic. + + """ + width, height = self.page_size + cur_drawing = Drawing(width, height) + + self._draw_title(cur_drawing, title, width, height) + + # calculate the x and y position changes for each distribution + cur_x_pos = inch * 0.5 + end_x_pos = width - inch * 0.5 + cur_y_pos = height - 1.5 * inch + end_y_pos = 0.5 * inch + x_pos_change = (end_x_pos - cur_x_pos) / self.number_of_columns + num_y_rows = math.ceil(len(self.distributions) / self.number_of_columns) + y_pos_change = (cur_y_pos - end_y_pos) / num_y_rows + + self._draw_distributions( + cur_drawing, cur_x_pos, x_pos_change, cur_y_pos, y_pos_change, num_y_rows + ) + self._draw_legend(cur_drawing, 2.5 * inch, width) + + return _write(cur_drawing, output_file, self.output_format) + + def _draw_title(self, cur_drawing, title, width, height): + """Add the title of the figure to the drawing (PRIVATE).""" + title_string = String(width / 2, height - inch, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _draw_distributions( + self, + cur_drawing, + start_x_pos, + x_pos_change, + start_y_pos, + y_pos_change, + num_y_drawings, + ): + """Draw all of the distributions on the page (PRIVATE). + + Arguments: + - cur_drawing - The drawing we are working with. + - start_x_pos - The x position on the page to start drawing at. + - x_pos_change - The change in x position between each figure. + - start_y_pos - The y position on the page to start drawing at. + - y_pos_change - The change in y position between each figure. + - num_y_drawings - The number of drawings we'll have in the y + (up/down) direction. + + """ + for y_drawing in range(int(num_y_drawings)): + # if we are on the last y position, we may not be able + # to fill all of the x columns + if (y_drawing + 1) * self.number_of_columns > len(self.distributions): + num_x_drawings = ( + len(self.distributions) - y_drawing * self.number_of_columns + ) + else: + num_x_drawings = self.number_of_columns + for x_drawing in range(num_x_drawings): + dist_num = y_drawing * self.number_of_columns + x_drawing + cur_distribution = self.distributions[dist_num] + + # find the x and y boundaries of the distribution + x_pos = start_x_pos + x_drawing * x_pos_change + end_x_pos = x_pos + x_pos_change + end_y_pos = start_y_pos - y_drawing * y_pos_change + y_pos = end_y_pos - y_pos_change + + # draw the distribution + cur_distribution.draw(cur_drawing, x_pos, y_pos, end_x_pos, end_y_pos) + + def _draw_legend(self, cur_drawing, start_y, width): + """Add a legend to the figure (PRIVATE). + + Subclasses can implement to provide a specialized legend. + """ + + +class BarChartDistribution: + """Display the distribution of values as a bunch of bars.""" + + def __init__(self, display_info=None): + """Initialize a Bar Chart display of distribution info. + + Attributes: + - display_info - the information to be displayed in the distribution. + This should be ordered as a list of lists, where each internal list + is a data set to display in the bar chart. + + """ + if display_info is None: + display_info = [] + self.display_info = display_info + + self.x_axis_title = "" + self.y_axis_title = "" + self.chart_title = "" + self.chart_title_size = 10 + + self.padding_percent = 0.15 + + def draw(self, cur_drawing, start_x, start_y, end_x, end_y): + """Draw a bar chart with the info in the specified range.""" + bar_chart = VerticalBarChart() + if self.chart_title: + self._draw_title( + cur_drawing, self.chart_title, start_x, start_y, end_x, end_y + ) + # set the position of the bar chart + x_start, x_end, y_start, y_end = self._determine_position( + start_x, start_y, end_x, end_y + ) + + bar_chart.x = x_start + bar_chart.y = y_start + bar_chart.width = abs(x_start - x_end) + bar_chart.height = abs(y_start - y_end) + + # set the information in the bar chart + bar_chart.data = self.display_info + bar_chart.valueAxis.valueMin = min(self.display_info[0]) + bar_chart.valueAxis.valueMax = max(self.display_info[0]) + for data_set in self.display_info[1:]: + if min(data_set) < bar_chart.valueAxis.valueMin: + bar_chart.valueAxis.valueMin = min(data_set) + if max(data_set) > bar_chart.valueAxis.valueMax: + bar_chart.valueAxis.valueMax = max(data_set) + + # set other formatting options + if len(self.display_info) == 1: + bar_chart.groupSpacing = 0 + style = TypedPropertyCollection(BarChartProperties) + style.strokeWidth = 0 + style.strokeColor = colors.green + style[0].fillColor = colors.green + + bar_chart.bars = style + + # set the labels + # XXX labels don't work yet + # bar_chart.valueAxis.title = self.x_axis_title + # bar_chart.categoryAxis.title = self.y_axis_title + + cur_drawing.add(bar_chart) + + def _draw_title(self, cur_drawing, title, start_x, start_y, end_x, end_y): + """Add the title of the figure to the drawing (PRIVATE).""" + x_center = start_x + (end_x - start_x) / 2 + y_pos = end_y + (self.padding_percent * (start_y - end_y)) / 2 + title_string = String(x_center, y_pos, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.chart_title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _determine_position(self, start_x, start_y, end_x, end_y): + """Calculate the position of the chart with blank space (PRIVATE). + + This uses some padding around the chart, and takes into account + whether the chart has a title. It returns 4 values, which are, + in order, the x_start, x_end, y_start and y_end of the chart + itself. + """ + x_padding = self.padding_percent * (end_x - start_x) + y_padding = self.padding_percent * (start_y - end_y) + + new_x_start = start_x + x_padding + new_x_end = end_x - x_padding + + if self.chart_title: + new_y_start = start_y - y_padding - self.chart_title_size + else: + new_y_start = start_y - y_padding + + new_y_end = end_y + y_padding + + return new_x_start, new_x_end, new_y_start, new_y_end + + +class LineDistribution: + """Display the distribution of values as connected lines. + + This distribution displays the change in values across the object as + lines. This also allows multiple distributions to be displayed on a + single graph. + """ + + def __init__(self): + """Initialize the class.""" + + def draw(self, cur_drawing, start_x, start_y, end_x, end_y): + """Draw a line distribution into the current drawing.""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__AbstractDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__AbstractDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__AbstractDrawer.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__CircularDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__CircularDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__CircularDrawer.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Colors.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Colors.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Colors.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__CrossLink.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__CrossLink.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__CrossLink.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Diagram.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Diagram.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Diagram.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Feature.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Feature.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Feature.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__FeatureSet.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__FeatureSet.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__FeatureSet.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Graph.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Graph.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Graph.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__GraphSet.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__GraphSet.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__GraphSet.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__LinearDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__LinearDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__LinearDrawer.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Track.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Track.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.__Track.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..40d14be58def6195df1272e478ce673c24e6cee5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py @@ -0,0 +1,565 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2017 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""AbstractDrawer module (considered to be a private module, the API may change!). + +Provides: + - AbstractDrawer - Superclass for methods common to the Drawer objects + - page_sizes - Method that returns a ReportLab pagesize when passed + a valid ISO size + - draw_box - Method that returns a closed path object when passed + the proper coordinates. For HORIZONTAL boxes only. + - angle2trig - Method that returns a tuple of values that are the + vector for rotating a point through a passed angle, + about an origin + - intermediate_points - Method that returns a list of values intermediate + between the points in a passed dataset + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com + +For dealing with biological information, the package expects Biopython objects +like SeqFeatures. +""" + +from itertools import islice +from math import cos +from math import pi +from math import sin + +from reportlab.graphics.shapes import Polygon +from reportlab.lib import colors +from reportlab.lib import pagesizes + +################################################################################ +# METHODS +################################################################################ + + +# Utility method to translate strings to ISO page sizes +def page_sizes(size): + """Convert size string into a Reportlab pagesize. + + Arguments: + - size - A string representing a standard page size, eg 'A4' or 'LETTER' + + """ + sizes = { # ReportLab pagesizes, keyed by ISO string + "A0": pagesizes.A0, + "A1": pagesizes.A1, + "A2": pagesizes.A2, + "A3": pagesizes.A3, + "A4": pagesizes.A4, + "A5": pagesizes.A5, + "A6": pagesizes.A6, + "B0": pagesizes.B0, + "B1": pagesizes.B1, + "B2": pagesizes.B2, + "B3": pagesizes.B3, + "B4": pagesizes.B4, + "B5": pagesizes.B5, + "B6": pagesizes.B6, + "ELEVENSEVENTEEN": pagesizes.ELEVENSEVENTEEN, + "LEGAL": pagesizes.LEGAL, + "LETTER": pagesizes.LETTER, + } + try: + return sizes[size] + except KeyError: + raise ValueError(f"{size} not in list of page sizes") from None + + +def _stroke_and_fill_colors(color, border): + """Deal with border and fill colors (PRIVATE).""" + if not isinstance(color, colors.Color): + raise ValueError(f"Invalid color {color!r}") + + if color == colors.white and border is None: + # Force black border on white boxes with undefined border + strokecolor = colors.black + elif border is None: + strokecolor = color # use fill color + elif border: + if not isinstance(border, colors.Color): + raise ValueError(f"Invalid border color {border!r}") + strokecolor = border + else: + # e.g. False + strokecolor = None + + return strokecolor, color + + +def draw_box( + point1, point2, color=colors.lightgreen, border=None, colour=None, **kwargs +): + """Draw a box. + + Arguments: + - point1, point2 - coordinates for opposite corners of the box + (x,y tuples) + - color /colour - The color for the box (colour takes priority + over color) + - border - Border color for the box + + Returns a closed path object, beginning at (x1,y1) going round + the four points in order, and filling with the passed color. + """ + x1, y1 = point1 + x2, y2 = point2 + + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + del colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + x1, y1, x2, y2 = min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) + return Polygon( + [x1, y1, x2, y1, x2, y2, x1, y2], + strokeColor=strokecolor, + fillColor=color, + strokewidth=0, + **kwargs, + ) + + +def draw_cut_corner_box( + point1, point2, corner=0.5, color=colors.lightgreen, border=None, **kwargs +): + """Draw a box with the corners cut off.""" + x1, y1 = point1 + x2, y2 = point2 + + if not corner: + return draw_box(point1, point2, color, border) + elif corner < 0: + raise ValueError("Arrow head length ratio should be positive") + + strokecolor, color = _stroke_and_fill_colors(color, border) + + boxheight = y2 - y1 + boxwidth = x2 - x1 + x_corner = min(boxheight * 0.5 * corner, boxwidth * 0.5) + y_corner = min(boxheight * 0.5 * corner, boxheight * 0.5) + + points = [ + x1, + y1 + y_corner, + x1, + y2 - y_corner, + x1 + x_corner, + y2, + x2 - x_corner, + y2, + x2, + y2 - y_corner, + x2, + y1 + y_corner, + x2 - x_corner, + y1, + x1 + x_corner, + y1, + ] + return Polygon( + deduplicate(points), + strokeColor=strokecolor, + strokeWidth=1, + strokeLineJoin=1, # 1=round + fillColor=color, + **kwargs, + ) + + +def draw_polygon( + list_of_points, color=colors.lightgreen, border=None, colour=None, **kwargs +): + """Draw polygon. + + Arguments: + - list_of_point - list of (x,y) tuples for the corner coordinates + - color / colour - The color for the box + + Returns a closed path object, beginning at (x1,y1) going round + the four points in order, and filling with the passed colour. + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + del colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + xy_list = [] + for x, y in list_of_points: + xy_list.append(x) + xy_list.append(y) + + return Polygon( + deduplicate(xy_list), + strokeColor=strokecolor, + fillColor=color, + strokewidth=0, + **kwargs, + ) + + +def draw_arrow( + point1, + point2, + color=colors.lightgreen, + border=None, + shaft_height_ratio=0.4, + head_length_ratio=0.5, + orientation="right", + colour=None, + **kwargs, +): + """Draw an arrow. + + Returns a closed path object representing an arrow enclosed by the + box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height + given by shaft_height_ratio (relative to box height), a head length + given by head_length_ratio (also relative to box height), and + an orientation that may be 'left' or 'right'. + """ + x1, y1 = point1 + x2, y2 = point2 + + if shaft_height_ratio < 0 or 1 < shaft_height_ratio: + raise ValueError("Arrow shaft height ratio should be in range 0 to 1") + if head_length_ratio < 0: + raise ValueError("Arrow head length ratio should be positive") + + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + del colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + # Depending on the orientation, we define the bottom left (x1, y1) and + # top right (x2, y2) coordinates differently, but still draw the box + # using the same relative coordinates: + xmin, ymin = min(x1, x2), min(y1, y2) + xmax, ymax = max(x1, x2), max(y1, y2) + if orientation == "right": + x1, x2, y1, y2 = xmin, xmax, ymin, ymax + elif orientation == "left": + x1, x2, y1, y2 = xmax, xmin, ymin, ymax + else: + raise ValueError( + f"Invalid orientation {orientation!r}, should be 'left' or 'right'" + ) + + # We define boxheight and boxwidth accordingly, and calculate the shaft + # height from these. We also ensure that the maximum head length is + # the width of the box enclosure + boxheight = y2 - y1 + boxwidth = x2 - x1 + shaftheight = boxheight * shaft_height_ratio + headlength = min(abs(boxheight) * head_length_ratio, abs(boxwidth)) + if boxwidth < 0: + headlength *= -1 # reverse it + + shafttop = 0.5 * (boxheight + shaftheight) + shaftbase = boxheight - shafttop + headbase = boxwidth - headlength + midheight = 0.5 * boxheight + + points = [ + x1, + y1 + shafttop, + x1 + headbase, + y1 + shafttop, + x1 + headbase, + y2, + x2, + y1 + midheight, + x1 + headbase, + y1, + x1 + headbase, + y1 + shaftbase, + x1, + y1 + shaftbase, + ] + + return Polygon( + deduplicate(points), + strokeColor=strokecolor, + # strokeWidth=max(1, int(boxheight/40.)), + strokeWidth=1, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + fillColor=color, + **kwargs, + ) + + +def deduplicate(points): + """Remove adjacent duplicate points. + + This is important for use with the Polygon class since reportlab has a + bug with duplicate points. + + Arguments: + - points - list of points [x1, y1, x2, y2,...] + + Returns a list in the same format with consecutive duplicates removed + """ + assert len(points) % 2 == 0 + if len(points) < 2: + return points + newpoints = points[0:2] + for x, y in zip(islice(points, 2, None, 2), islice(points, 3, None, 2)): + if x != newpoints[-2] or y != newpoints[-1]: + newpoints.append(x) + newpoints.append(y) + return newpoints + + +def angle2trig(theta): + """Convert angle to a reportlab ready tuple. + + Arguments: + - theta - Angle in degrees, counter clockwise from horizontal + + Returns a representation of the passed angle in a format suitable + for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta), + cos(theta) tuple) + """ + c = cos(theta * pi / 180) + s = sin(theta * pi / 180) + return (c, s, -s, c) # Vector for rotating point around an origin + + +def intermediate_points(start, end, graph_data): + """Generate intermediate points describing provided graph data.. + + Returns a list of (start, end, value) tuples describing the passed + graph data as 'bins' between position midpoints. + """ + newdata = [] # data in form (X0, X1, val) + # add first block + newdata.append( + ( + start, + graph_data[0][0] + (graph_data[1][0] - graph_data[0][0]) / 2.0, + graph_data[0][1], + ) + ) + # add middle set + for index in range(1, len(graph_data) - 1): + lastxval, lastyval = graph_data[index - 1] + xval, yval = graph_data[index] + nextxval, nextyval = graph_data[index + 1] + newdata.append( + (lastxval + (xval - lastxval) / 2.0, xval + (nextxval - xval) / 2.0, yval) + ) + # add last block + newdata.append((xval + (nextxval - xval) / 2.0, end, graph_data[-1][1])) + return newdata + + +################################################################################ +# CLASSES +################################################################################ + + +class AbstractDrawer: + """Abstract Drawer. + + Attributes: + - tracklines Boolean for whether to draw lines delineating tracks + - pagesize Tuple describing the size of the page in pixels + - x0 Float X co-ord for leftmost point of drawable area + - xlim Float X co-ord for rightmost point of drawable area + - y0 Float Y co-ord for lowest point of drawable area + - ylim Float Y co-ord for topmost point of drawable area + - pagewidth Float pixel width of drawable area + - pageheight Float pixel height of drawable area + - xcenter Float X co-ord of center of drawable area + - ycenter Float Y co-ord of center of drawable area + - start Int, base to start drawing from + - end Int, base to stop drawing at + - length Size of sequence to be drawn + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + + def __init__( + self, + parent, + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=0, + cross_track_links=None, + ): + """Create the object. + + Arguments: + - parent Diagram object containing the data that the drawer draws + - pagesize String describing the ISO size of the image, or a tuple + of pixels + - orientation String describing the required orientation of the + final drawing ('landscape' or 'portrait') + - x Float (0->1) describing the relative size of the X + margins to the page + - y Float (0->1) describing the relative size of the Y + margins to the page + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xr Float (0->1) describing the relative size of the right X + margin to the page (overrides x) + - yt Float (0->1) describing the relative size of the top Y + margin to the page (overrides y) + - yb Float (0->1) describing the relative size of the lower Y + margin to the page (overrides y) + - start Int, the position to begin drawing the diagram at + - end Int, the position to stop drawing the diagram at + - tracklines Boolean flag to show (or not) lines delineating tracks + on the diagram + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + self._parent = parent # The calling Diagram object + + # Perform 'administrative' tasks of setting up the page + self.set_page_size(pagesize, orientation) # Set drawing size + self.set_margins(x, y, xl, xr, yt, yb) # Set page margins + self.set_bounds(start, end) # Set limits on what will be drawn + self.tracklines = tracklines # Set flags + if cross_track_links is None: + cross_track_links = [] + else: + self.cross_track_links = cross_track_links + + def set_page_size(self, pagesize, orientation): + """Set page size of the drawing.. + + Arguments: + - pagesize Size of the output image, a tuple of pixels (width, + height, or a string in the reportlab.lib.pagesizes + set of ISO sizes. + - orientation String: 'landscape' or 'portrait' + + """ + if isinstance(pagesize, str): # A string, so translate + pagesize = page_sizes(pagesize) + elif isinstance(pagesize, tuple): # A tuple, so don't translate + pass + else: + raise ValueError(f"Page size {pagesize} not recognised") + shortside, longside = min(pagesize), max(pagesize) + + orientation = orientation.lower() + if orientation not in ("landscape", "portrait"): + raise ValueError(f"Orientation {orientation} not recognised") + if orientation == "landscape": + self.pagesize = (longside, shortside) + else: + self.pagesize = (shortside, longside) + + def set_margins(self, x, y, xl, xr, yt, yb): + """Set page margins. + + Arguments: + - x Float(0->1), Absolute X margin as % of page + - y Float(0->1), Absolute Y margin as % of page + - xl Float(0->1), Left X margin as % of page + - xr Float(0->1), Right X margin as % of page + - yt Float(0->1), Top Y margin as % of page + - yb Float(0->1), Bottom Y margin as % of page + + Set the page margins as proportions of the page 0->1, and also + set the page limits x0, y0 and xlim, ylim, and page center + xorigin, yorigin, as well as overall page width and height + """ + # Set left, right, top and bottom margins + xmargin_l = xl or x + xmargin_r = xr or x + ymargin_top = yt or y + ymargin_btm = yb or y + + # Set page limits, center and height/width + self.x0, self.y0 = self.pagesize[0] * xmargin_l, self.pagesize[1] * ymargin_btm + self.xlim, self.ylim = ( + self.pagesize[0] * (1 - xmargin_r), + self.pagesize[1] * (1 - ymargin_top), + ) + self.pagewidth = self.xlim - self.x0 + self.pageheight = self.ylim - self.y0 + self.xcenter, self.ycenter = ( + self.x0 + self.pagewidth / 2.0, + self.y0 + self.pageheight / 2.0, + ) + + def set_bounds(self, start, end): + """Set start and end points for the drawing as a whole. + + Arguments: + - start - The first base (or feature mark) to draw from + - end - The last base (or feature mark) to draw to + + """ + low, high = self._parent.range() # Extent of tracks + + if start is not None and end is not None and start > end: + start, end = end, start + + if start is None or start < 0: # Check validity of passed args and + start = 0 # default to 0 + if end is None or end < 0: + end = high + 1 # default to track range top limit + + self.start, self.end = int(start), int(end) + self.length = self.end - self.start + 1 + + def is_in_bounds(self, value): + """Check if given value is within the region selected for drawing. + + Arguments: + - value - A base position + + """ + if value >= self.start and value <= self.end: + return 1 + return 0 + + def __len__(self): + """Return the length of the region to be drawn.""" + return self.length + + def _current_track_start_end(self): + track = self._parent[self.current_track_level] + if track.start is None: + start = self.start + else: + start = max(self.start, track.start) + if track.end is None: + end = self.end + else: + end = min(self.end, track.end) + return start, end diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CircularDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CircularDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea1775749bf8e4fcd94bc676446f4b03313d85e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CircularDrawer.py @@ -0,0 +1,1731 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2017 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""CircularDrawer module for GenomeDiagram.""" + +from math import cos +from math import pi +from math import sin + +from reportlab.graphics.shapes import ArcPath +from reportlab.graphics.shapes import Circle +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import Group +from reportlab.graphics.shapes import Line +from reportlab.graphics.shapes import Polygon +from reportlab.graphics.shapes import String +from reportlab.lib import colors + +from ._AbstractDrawer import _stroke_and_fill_colors +from ._AbstractDrawer import AbstractDrawer +from ._AbstractDrawer import draw_polygon +from ._AbstractDrawer import intermediate_points +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet + + +class CircularDrawer(AbstractDrawer): + """Object for drawing circular diagrams. + + Attributes: + - tracklines Boolean for whether to draw lines dilineating tracks + - pagesize Tuple describing the size of the page in pixels + - x0 Float X co-ord for leftmost point of drawable area + - xlim Float X co-ord for rightmost point of drawable area + - y0 Float Y co-ord for lowest point of drawable area + - ylim Float Y co-ord for topmost point of drawable area + - pagewidth Float pixel width of drawable area + - pageheight Float pixel height of drawable area + - xcenter Float X co-ord of center of drawable area + - ycenter Float Y co-ord of center of drawable area + - start Int, base to start drawing from + - end Int, base to stop drawing at + - length Size of sequence to be drawn + - track_size Float (0->1) the proportion of the track height to draw in + - drawing Drawing canvas + - drawn_tracks List of ints denoting which tracks are to be drawn + - current_track_level Int denoting which track is currently being drawn + - track_offsets Dictionary of number of pixels that each track top, + center and bottom is offset from the base of a fragment, keyed by track + - sweep Float (0->1) the proportion of the circle circumference to + use for the diagram + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + + def __init__( + self, + parent=None, + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=0, + track_size=0.75, + circular=1, + circle_core=0.0, + cross_track_links=None, + ): + """Create CircularDrawer object. + + Arguments: + - parent Diagram object containing the data that the drawer + draws + - pagesize String describing the ISO size of the image, or a tuple + of pixels + - orientation String describing the required orientation of the + final drawing ('landscape' or 'portrait') + - x Float (0->1) describing the relative size of the X + margins to the page + - y Float (0->1) describing the relative size of the Y + margins to the page + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xr Float (0->1) describing the relative size of the right X + margin to the page (overrides x) + - yt Float (0->1) describing the relative size of the top Y + margin to the page (overrides y) + - yb Float (0->1) describing the relative size of the lower Y + margin to the page (overrides y) + - start Int, the position to begin drawing the diagram at + - end Int, the position to stop drawing the diagram at + - tracklines Boolean flag to show (or not) lines delineating tracks + on the diagram + - track_size The proportion of the available track height that + should be taken up in drawing + - circular Boolean flaw to show whether the passed sequence is + circular or not + - circle_core The proportion of the available radius to leave + empty at the center of a circular diagram (0 to 1). + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + # Use the superclass' instantiation method + AbstractDrawer.__init__( + self, + parent, + pagesize, + orientation, + x, + y, + xl, + xr, + yt, + yb, + start, + end, + tracklines, + cross_track_links, + ) + + # Useful measurements on the page + self.track_size = track_size + self.circle_core = circle_core + # Determine proportion of circumference around which information will be drawn + if not circular: + self.sweep = 0.9 + else: + self.sweep = 1.0 + + def set_track_heights(self): + """Initialize track heights. + + Since tracks may not be of identical heights, the bottom and top + radius for each track is stored in a dictionary - self.track_radii, + keyed by track number + """ + bot_track = min(min(self.drawn_tracks), 1) + top_track = max(self.drawn_tracks) # The 'highest' track to draw + + trackunit_sum = 0 # Total number of 'units' taken up by all tracks + trackunits = {} # Start and & units for each track keyed by track number + heightholder = 0 # placeholder variable + for track in range(bot_track, top_track + 1): # track numbers to 'draw' + try: + trackheight = self._parent[track].height # Get track height + except Exception: # TODO: ValueError? IndexError? + trackheight = 1 + trackunit_sum += trackheight # increment total track unit height + trackunits[track] = (heightholder, heightholder + trackheight) + heightholder += trackheight # move to next height + + max_radius = 0.5 * min(self.pagewidth, self.pageheight) + trackunit_height = max_radius * (1 - self.circle_core) / trackunit_sum + track_core = max_radius * self.circle_core + + # Calculate top and bottom radii for each track + self.track_radii = {} # The inner, outer and center radii for each track + track_crop = ( + trackunit_height * (1 - self.track_size) / 2.0 + ) # 'step back' in pixels + for track in trackunits: + top = trackunits[track][1] * trackunit_height - track_crop + track_core + btm = trackunits[track][0] * trackunit_height + track_crop + track_core + ctr = btm + (top - btm) / 2.0 + self.track_radii[track] = (btm, ctr, top) + + def draw(self): + """Draw a circular diagram of the stored data.""" + # Instantiate the drawing canvas + self.drawing = Drawing(self.pagesize[0], self.pagesize[1]) + + feature_elements = [] # holds feature elements + feature_labels = [] # holds feature labels + greytrack_bgs = [] # holds track background + greytrack_labels = [] # holds track foreground labels + scale_axes = [] # holds scale axes + scale_labels = [] # holds scale axis labels + + # Get tracks to be drawn and set track sizes + self.drawn_tracks = self._parent.get_drawn_levels() + self.set_track_heights() + + # Go through each track in the parent (if it is to be drawn) one by + # one and collate the data as drawing elements + for track_level in self._parent.get_drawn_levels(): + self.current_track_level = track_level + track = self._parent[track_level] + gbgs, glabels = self.draw_greytrack(track) # Greytracks + greytrack_bgs.append(gbgs) + greytrack_labels.append(glabels) + features, flabels = self.draw_track(track) # Features and graphs + feature_elements.append(features) + feature_labels.append(flabels) + if track.scale: + axes, slabels = self.draw_scale(track) # Scale axes + scale_axes.append(axes) + scale_labels.append(slabels) + + feature_cross_links = [] + for cross_link_obj in self.cross_track_links: + cross_link_elements = self.draw_cross_link(cross_link_obj) + if cross_link_elements: + feature_cross_links.append(cross_link_elements) + + # Groups listed in order of addition to page (from back to front) + # Draw track backgrounds + # Draw feature cross track links + # Draw features and graphs + # Draw scale axes + # Draw scale labels + # Draw feature labels + # Draw track labels + element_groups = [ + greytrack_bgs, + feature_cross_links, + feature_elements, + scale_axes, + scale_labels, + feature_labels, + greytrack_labels, + ] + for element_group in element_groups: + for element_list in element_group: + [self.drawing.add(element) for element in element_list] + + if self.tracklines: + # Draw test tracks over top of diagram + self.draw_test_tracks() + + def draw_track(self, track): + """Return list of track elements and list of track labels.""" + track_elements = [] # Holds elements for features and graphs + track_labels = [] # Holds labels for features and graphs + + # Distribution dictionary for dealing with different set types + set_methods = {FeatureSet: self.draw_feature_set, GraphSet: self.draw_graph_set} + + for set in track.get_sets(): # Draw the feature or graph sets + elements, labels = set_methods[set.__class__](set) + track_elements += elements + track_labels += labels + return track_elements, track_labels + + def draw_feature_set(self, set): + """Return list of feature elements and list of labels for them.""" + # print('draw feature set') + feature_elements = [] # Holds diagram elements belonging to the features + label_elements = [] # Holds diagram elements belonging to feature labels + + # Collect all the elements for the feature set + for feature in set.get_features(): + if self.is_in_bounds(feature.start) or self.is_in_bounds(feature.end): + features, labels = self.draw_feature(feature) + feature_elements += features + label_elements += labels + + return feature_elements, label_elements + + def draw_feature(self, feature): + """Return list of feature elements and list of labels for them.""" + feature_elements = [] # Holds drawable elements for a single feature + label_elements = [] # Holds labels for a single feature + + if feature.hide: # Don't show feature: return early + return feature_elements, label_elements + + start, end = self._current_track_start_end() + # A single feature may be split into subfeatures, so loop over them + for locstart, locend in feature.locations: + if locend < start: + continue + locstart = max(locstart, start) + if end < locstart: + continue + locend = min(locend, end) + # Get sigil for the feature/ each subfeature + feature_sigil, label = self.get_feature_sigil(feature, locstart, locend) + feature_elements.append(feature_sigil) + if label is not None: # If there's a label + label_elements.append(label) + + return feature_elements, label_elements + + def get_feature_sigil(self, feature, locstart, locend, **kwargs): + """Return graphics for feature, and any required label for it. + + Arguments: + - feature Feature object + - locstart The start position of the feature + - locend The end position of the feature + + """ + # Establish the coordinates for the sigil + btm, ctr, top = self.track_radii[self.current_track_level] + + startangle, startcos, startsin = self.canvas_angle(locstart) + endangle, endcos, endsin = self.canvas_angle(locend) + midangle, midcos, midsin = self.canvas_angle((locend + locstart) / 2) + + # Distribution dictionary for various ways of drawing the feature + # Each method takes the inner and outer radii, the start and end angle + # subtended at the diagram center, and the color as arguments + draw_methods = { + "BOX": self._draw_sigil_box, + "OCTO": self._draw_sigil_cut_corner_box, + "JAGGY": self._draw_sigil_jaggy, + "ARROW": self._draw_sigil_arrow, + "BIGARROW": self._draw_sigil_big_arrow, + } + + # Get sigil for the feature, location dependent on the feature strand + method = draw_methods[feature.sigil] + kwargs["head_length_ratio"] = feature.arrowhead_length + kwargs["shaft_height_ratio"] = feature.arrowshaft_height + + # Support for clickable links... needs ReportLab 2.4 or later + # which added support for links in SVG output. + if hasattr(feature, "url"): + kwargs["hrefURL"] = feature.url + kwargs["hrefTitle"] = feature.name + + sigil = method( + btm, + ctr, + top, + startangle, + endangle, + feature.location.strand, + color=feature.color, + border=feature.border, + **kwargs, + ) + + if feature.label: # Feature needs a label + # The spaces are a hack to force a little space between the label + # and the edge of the feature + label = String( + 0, + 0, + f" {feature.name.strip()} ", + fontName=feature.label_font, + fontSize=feature.label_size, + fillColor=feature.label_color, + ) + labelgroup = Group(label) + if feature.label_strand: + strand = feature.label_strand + else: + strand = feature.location.strand + if feature.label_position in ("start", "5'", "left"): + # Position the label at the feature's start + if strand != -1: + label_angle = startangle + 0.5 * pi # Make text radial + sinval, cosval = startsin, startcos + else: + label_angle = endangle + 0.5 * pi # Make text radial + sinval, cosval = endsin, endcos + elif feature.label_position in ("middle", "center", "centre"): + # Position the label at the feature's midpoint + label_angle = midangle + 0.5 * pi # Make text radial + sinval, cosval = midsin, midcos + elif feature.label_position in ("end", "3'", "right"): + # Position the label at the feature's end + if strand != -1: + label_angle = endangle + 0.5 * pi # Make text radial + sinval, cosval = endsin, endcos + else: + label_angle = startangle + 0.5 * pi # Make text radial + sinval, cosval = startsin, startcos + elif startangle < pi: + # Default to placing the label the bottom of the feature + # as drawn on the page, meaning feature end on left half + label_angle = endangle + 0.5 * pi # Make text radial + sinval, cosval = endsin, endcos + else: + # Default to placing the label on the bottom of the feature, + # which means the feature end when on right hand half + label_angle = startangle + 0.5 * pi # Make text radial + sinval, cosval = startsin, startcos + if strand != -1: + # Feature label on top + radius = top + if startangle < pi: # Turn text round + label_angle -= pi + else: + labelgroup.contents[0].textAnchor = "end" + else: + # Feature label on bottom + radius = btm + if startangle < pi: # Turn text round and anchor end + label_angle -= pi + labelgroup.contents[0].textAnchor = "end" + x_pos = self.xcenter + radius * sinval + y_pos = self.ycenter + radius * cosval + coslabel = cos(label_angle) + sinlabel = sin(label_angle) + labelgroup.transform = ( + coslabel, + -sinlabel, + sinlabel, + coslabel, + x_pos, + y_pos, + ) + else: + # No label required + labelgroup = None + # if locstart > locend: + # print(locstart, locend, feature.location.strand, sigil, feature.name) + # print(locstart, locend, feature.name) + return sigil, labelgroup + + def draw_cross_link(self, cross_link): + """Draw a cross-link between features.""" + startA = cross_link.startA + startB = cross_link.startB + endA = cross_link.endA + endB = cross_link.endB + + if not self.is_in_bounds(startA) and not self.is_in_bounds(endA): + return None + if not self.is_in_bounds(startB) and not self.is_in_bounds(endB): + return None + + if startA < self.start: + startA = self.start + if startB < self.start: + startB = self.start + if self.end < endA: + endA = self.end + if self.end < endB: + endB = self.end + + trackobjA = cross_link._trackA(list(self._parent.tracks.values())) + trackobjB = cross_link._trackB(list(self._parent.tracks.values())) + assert trackobjA is not None + assert trackobjB is not None + if trackobjA == trackobjB: + raise NotImplementedError + + if trackobjA.start is not None: + if endA < trackobjA.start: + return + startA = max(startA, trackobjA.start) + if trackobjA.end is not None: + if trackobjA.end < startA: + return + endA = min(endA, trackobjA.end) + if trackobjB.start is not None: + if endB < trackobjB.start: + return + startB = max(startB, trackobjB.start) + if trackobjB.end is not None: + if trackobjB.end < startB: + return + endB = min(endB, trackobjB.end) + + for track_level in self._parent.get_drawn_levels(): + track = self._parent[track_level] + if track == trackobjA: + trackA = track_level + if track == trackobjB: + trackB = track_level + if trackA == trackB: + raise NotImplementedError + + startangleA, startcosA, startsinA = self.canvas_angle(startA) + startangleB, startcosB, startsinB = self.canvas_angle(startB) + endangleA, endcosA, endsinA = self.canvas_angle(endA) + endangleB, endcosB, endsinB = self.canvas_angle(endB) + + btmA, ctrA, topA = self.track_radii[trackA] + btmB, ctrB, topB = self.track_radii[trackB] + + if ctrA < ctrB: + return [ + self._draw_arc_poly( + topA, + btmB, + startangleA, + endangleA, + startangleB, + endangleB, + cross_link.color, + cross_link.border, + cross_link.flip, + ) + ] + else: + return [ + self._draw_arc_poly( + btmA, + topB, + startangleA, + endangleA, + startangleB, + endangleB, + cross_link.color, + cross_link.border, + cross_link.flip, + ) + ] + + def draw_graph_set(self, set): + """Return list of graph elements and list of their labels. + + Arguments: + - set GraphSet object + + """ + # print('draw graph set') + elements = [] # Holds graph elements + + # Distribution dictionary for how to draw the graph + style_methods = { + "line": self.draw_line_graph, + "heat": self.draw_heat_graph, + "bar": self.draw_bar_graph, + } + + for graph in set.get_graphs(): + elements += style_methods[graph.style](graph) + + return elements, [] + + def draw_line_graph(self, graph): + """Return line graph as list of drawable elements. + + Arguments: + - graph GraphData object + + """ + line_elements = [] # holds drawable elements + + # Get graph data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + btm, ctr, top = self.track_radii[self.current_track_level] + trackheight = 0.5 * (top - btm) + datarange = maxval - minval + if datarange == 0: + datarange = trackheight + + start, end = self._current_track_start_end() + data = graph[start:end] + + if not data: + return [] + + # midval is the value at which the x-axis is plotted, and is the + # central ring in the track + if graph.center is None: + midval = (maxval + minval) / 2.0 + else: + midval = graph.center + # Whichever is the greatest difference: max-midval or min-midval, is + # taken to specify the number of pixel units resolved along the + # y-axis + resolution = max((midval - minval), (maxval - midval)) + + # Start from first data point + pos, val = data[0] + lastangle, lastcos, lastsin = self.canvas_angle(pos) + # We calculate the track height + posheight = trackheight * (val - midval) / resolution + ctr + lastx = self.xcenter + posheight * lastsin # start xy coords + lasty = self.ycenter + posheight * lastcos + for pos, val in data: + posangle, poscos, possin = self.canvas_angle(pos) + posheight = trackheight * (val - midval) / resolution + ctr + x = self.xcenter + posheight * possin # next xy coords + y = self.ycenter + posheight * poscos + line_elements.append( + Line( + lastx, + lasty, + x, + y, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + lastx, lasty = x, y + return line_elements + + def draw_bar_graph(self, graph): + """Return list of drawable elements for a bar graph. + + Arguments: + - graph Graph object + + """ + # At each point contained in the graph data, we draw a vertical bar + # from the track center to the height of the datapoint value (positive + # values go up in one color, negative go down in the alternative + # color). + bar_elements = [] + + # Set the number of pixels per unit for the data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + btm, ctr, top = self.track_radii[self.current_track_level] + trackheight = 0.5 * (top - btm) + datarange = maxval - minval + if datarange == 0: + datarange = trackheight + data = graph[self.start : self.end] + # midval is the value at which the x-axis is plotted, and is the + # central ring in the track + if graph.center is None: + midval = (maxval + minval) / 2.0 + else: + midval = graph.center + + # Convert data into 'binned' blocks, covering half the distance to the + # next data point on either side, accounting for the ends of fragments + # and tracks + start, end = self._current_track_start_end() + data = intermediate_points(start, end, graph[start:end]) + + if not data: + return [] + + # Whichever is the greatest difference: max-midval or min-midval, is + # taken to specify the number of pixel units resolved along the + # y-axis + resolution = max((midval - minval), (maxval - midval)) + if resolution == 0: + resolution = trackheight + + # Create elements for the bar graph based on newdata + for pos0, pos1, val in data: + pos0angle, pos0cos, pos0sin = self.canvas_angle(pos0) + pos1angle, pos1cos, pos1sin = self.canvas_angle(pos1) + + barval = trackheight * (val - midval) / resolution + if barval >= 0: + barcolor = graph.poscolor + else: + barcolor = graph.negcolor + + # Draw bar + bar_elements.append( + self._draw_arc(ctr, ctr + barval, pos0angle, pos1angle, barcolor) + ) + return bar_elements + + def draw_heat_graph(self, graph): + """Return list of drawable elements for the heat graph. + + Arguments: + - graph Graph object + + """ + # At each point contained in the graph data, we draw a box that is the + # full height of the track, extending from the midpoint between the + # previous and current data points to the midpoint between the current + # and next data points + heat_elements = [] # holds drawable elements + + # Get graph data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + midval = (maxval + minval) / 2.0 # mid is the value at the X-axis + btm, ctr, top = self.track_radii[self.current_track_level] + trackheight = top - btm + + start, end = self._current_track_start_end() + data = intermediate_points(start, end, graph[start:end]) + + # Create elements on the graph, indicating a large positive value by + # the graph's poscolor, and a large negative value by the graph's + # negcolor attributes + for pos0, pos1, val in data: + pos0angle, pos0cos, pos0sin = self.canvas_angle(pos0) + pos1angle, pos1cos, pos1sin = self.canvas_angle(pos1) + + # Calculate the heat color, based on the differential between + # the value and the median value + heat = colors.linearlyInterpolatedColor( + graph.poscolor, graph.negcolor, maxval, minval, val + ) + + # Draw heat box + heat_elements.append( + self._draw_arc(btm, top, pos0angle, pos1angle, heat, border=heat) + ) + return heat_elements + + def draw_scale(self, track): + """Return list of elements in the scale and list of their labels. + + Arguments: + - track Track object + + """ + scale_elements = [] # holds axes and ticks + scale_labels = [] # holds labels + + if not track.scale: + # no scale required, exit early + return [], [] + + # Get track locations + btm, ctr, top = self.track_radii[self.current_track_level] + trackheight = top - ctr + + # X-axis + start, end = self._current_track_start_end() + if track.start is not None or track.end is not None: + # Draw an arc, leaving out the wedge + p = ArcPath(strokeColor=track.scale_color, fillColor=None) + startangle, startcos, startsin = self.canvas_angle(start) + endangle, endcos, endsin = self.canvas_angle(end) + p.addArc( + self.xcenter, + self.ycenter, + ctr, + 90 - (endangle * 180 / pi), + 90 - (startangle * 180 / pi), + ) + scale_elements.append(p) + del p + # Y-axis start marker + x0, y0 = self.xcenter + btm * startsin, self.ycenter + btm * startcos + x1, y1 = self.xcenter + top * startsin, self.ycenter + top * startcos + scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color)) + # Y-axis end marker + x0, y0 = self.xcenter + btm * endsin, self.ycenter + btm * endcos + x1, y1 = self.xcenter + top * endsin, self.ycenter + top * endcos + scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color)) + elif self.sweep < 1: + # Draw an arc, leaving out the wedge + p = ArcPath(strokeColor=track.scale_color, fillColor=None) + # Note reportlab counts angles anti-clockwise from the horizontal + # (as in mathematics, e.g. complex numbers and polar coordinates) + # in degrees. + p.addArc( + self.xcenter, + self.ycenter, + ctr, + startangledegrees=90 - 360 * self.sweep, + endangledegrees=90, + ) + scale_elements.append(p) + del p + # Y-axis start marker + x0, y0 = self.xcenter, self.ycenter + btm + x1, y1 = self.xcenter, self.ycenter + top + scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color)) + # Y-axis end marker + alpha = 2 * pi * self.sweep + x0, y0 = self.xcenter + btm * sin(alpha), self.ycenter + btm * cos(alpha) + x1, y1 = self.xcenter + top * sin(alpha), self.ycenter + top * cos(alpha) + scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color)) + else: + # Draw a full circle + scale_elements.append( + Circle( + self.xcenter, + self.ycenter, + ctr, + strokeColor=track.scale_color, + fillColor=None, + ) + ) + + start, end = self._current_track_start_end() + if track.scale_ticks: # Ticks are required on the scale + # Draw large ticks + # I want the ticks to be consistently positioned relative to + # the start of the sequence (position 0), not relative to the + # current viewpoint (self.start and self.end) + + ticklen = track.scale_largeticks * trackheight + tickiterval = int(track.scale_largetick_interval) + # Note that we could just start the list of ticks using + # range(0,self.end,tickinterval) and the filter out the + # ones before self.start - but this seems wasteful. + # Using tickiterval * (self.start/tickiterval) is a shortcut. + for tickpos in range( + tickiterval * (self.start // tickiterval), int(self.end), tickiterval + ): + if tickpos <= start or end <= tickpos: + continue + tick, label = self.draw_tick( + tickpos, ctr, ticklen, track, track.scale_largetick_labels + ) + scale_elements.append(tick) + if label is not None: # If there's a label, add it + scale_labels.append(label) + # Draw small ticks + ticklen = track.scale_smallticks * trackheight + tickiterval = int(track.scale_smalltick_interval) + for tickpos in range( + tickiterval * (self.start // tickiterval), int(self.end), tickiterval + ): + if tickpos <= start or end <= tickpos: + continue + tick, label = self.draw_tick( + tickpos, ctr, ticklen, track, track.scale_smalltick_labels + ) + scale_elements.append(tick) + if label is not None: # If there's a label, add it + scale_labels.append(label) + + # Check to see if the track contains a graph - if it does, get the + # minimum and maximum values, and put them on the scale Y-axis + # at 60 degree intervals, ordering the labels by graph_id + startangle, startcos, startsin = self.canvas_angle(start) + endangle, endcos, endsin = self.canvas_angle(end) + if track.axis_labels: + for set in track.get_sets(): + if set.__class__ is GraphSet: + # Y-axis + for n in range(7): + angle = n * 1.0471975511965976 + if angle < startangle or endangle < angle: + continue + ticksin, tickcos = sin(angle), cos(angle) + x0, y0 = ( + self.xcenter + btm * ticksin, + self.ycenter + btm * tickcos, + ) + x1, y1 = ( + self.xcenter + top * ticksin, + self.ycenter + top * tickcos, + ) + scale_elements.append( + Line(x0, y0, x1, y1, strokeColor=track.scale_color) + ) + + graph_label_min = [] + graph_label_max = [] + graph_label_mid = [] + for graph in set.get_graphs(): + quartiles = graph.quartiles() + minval, maxval = quartiles[0], quartiles[4] + if graph.center is None: + midval = (maxval + minval) / 2.0 + graph_label_min.append(f"{minval:.3f}") + graph_label_max.append(f"{maxval:.3f}") + graph_label_mid.append(f"{midval:.3f}") + else: + diff = max( + (graph.center - minval), (maxval - graph.center) + ) + minval = graph.center - diff + maxval = graph.center + diff + midval = graph.center + graph_label_mid.append(f"{midval:.3f}") + graph_label_min.append(f"{minval:.3f}") + graph_label_max.append(f"{maxval:.3f}") + xmid, ymid = (x0 + x1) / 2.0, (y0 + y1) / 2.0 + for limit, x, y in [ + (graph_label_min, x0, y0), + (graph_label_max, x1, y1), + (graph_label_mid, xmid, ymid), + ]: + label = String( + 0, + 0, + ";".join(limit), + fontName=track.scale_font, + fontSize=track.scale_fontsize, + fillColor=track.scale_color, + ) + label.textAnchor = "middle" + labelgroup = Group(label) + labelgroup.transform = ( + tickcos, + -ticksin, + ticksin, + tickcos, + x, + y, + ) + scale_labels.append(labelgroup) + + return scale_elements, scale_labels + + def draw_tick(self, tickpos, ctr, ticklen, track, draw_label): + """Return drawing element for a tick on the scale. + + Arguments: + - tickpos Int, position of the tick on the sequence + - ctr Float, Y co-ord of the center of the track + - ticklen How long to draw the tick + - track Track, the track the tick is drawn on + - draw_label Boolean, write the tick label? + + """ + # Calculate tick coordinates + tickangle, tickcos, ticksin = self.canvas_angle(tickpos) + x0, y0 = self.xcenter + ctr * ticksin, self.ycenter + ctr * tickcos + x1, y1 = ( + self.xcenter + (ctr + ticklen) * ticksin, + self.ycenter + (ctr + ticklen) * tickcos, + ) + # Calculate height of text label so it can be offset on lower half + # of diagram + # LP: not used, as not all fonts have ascent_descent data in reportlab.pdfbase._fontdata + # label_offset = _fontdata.ascent_descent[track.scale_font][0]*\ + # track.scale_fontsize/1000. + tick = Line(x0, y0, x1, y1, strokeColor=track.scale_color) + if draw_label: + # Put tick position on as label + if track.scale_format == "SInt": + if tickpos >= 1000000: + tickstring = str(tickpos // 1000000) + " Mbp" + elif tickpos >= 1000: + tickstring = str(tickpos // 1000) + " Kbp" + else: + tickstring = str(tickpos) + else: + tickstring = str(tickpos) + label = String( + 0, + 0, + tickstring, # Make label string + fontName=track.scale_font, + fontSize=track.scale_fontsize, + fillColor=track.scale_color, + ) + if tickangle > pi: + label.textAnchor = "end" + # LP: This label_offset depends on ascent_descent data, which is not available for all + # fonts, so has been deprecated. + # if 0.5*pi < tickangle < 1.5*pi: + # y1 -= label_offset + labelgroup = Group(label) + labelgroup.transform = (1, 0, 0, 1, x1, y1) + else: + labelgroup = None + return tick, labelgroup + + def draw_test_tracks(self): + """Draw blue test tracks with grene line down their center.""" + # Add lines only for drawn tracks + for track in self.drawn_tracks: + btm, ctr, top = self.track_radii[track] + self.drawing.add( + Circle( + self.xcenter, + self.ycenter, + top, + strokeColor=colors.blue, + fillColor=None, + ) + ) # top line + self.drawing.add( + Circle( + self.xcenter, + self.ycenter, + ctr, + strokeColor=colors.green, + fillColor=None, + ) + ) # middle line + self.drawing.add( + Circle( + self.xcenter, + self.ycenter, + btm, + strokeColor=colors.blue, + fillColor=None, + ) + ) # bottom line + + def draw_greytrack(self, track): + """Drawing element for grey background to passed Track object.""" + greytrack_bgs = [] # Holds track backgrounds + greytrack_labels = [] # Holds track foreground labels + + if not track.greytrack: # No greytrack required, return early + return [], [] + + # Get track location + btm, ctr, top = self.track_radii[self.current_track_level] + + start, end = self._current_track_start_end() + startangle, startcos, startsin = self.canvas_angle(start) + endangle, endcos, endsin = self.canvas_angle(end) + + # Make background + if track.start is not None or track.end is not None: + # Draw an arc, leaving out the wedge + p = ArcPath(strokeColor=track.scale_color, fillColor=None) + greytrack_bgs.append( + self._draw_arc( + btm, top, startangle, endangle, colors.Color(0.96, 0.96, 0.96) + ) + ) + elif self.sweep < 1: + # Make a partial circle, a large arc box + # This method assumes the correct center for us. + greytrack_bgs.append( + self._draw_arc( + btm, top, 0, 2 * pi * self.sweep, colors.Color(0.96, 0.96, 0.96) + ) + ) + else: + # Make a full circle (using a VERY thick linewidth) + greytrack_bgs.append( + Circle( + self.xcenter, + self.ycenter, + ctr, + strokeColor=colors.Color(0.96, 0.96, 0.96), + fillColor=None, + strokeWidth=top - btm, + ) + ) + + if track.greytrack_labels: + # Labels are required for this track + labelstep = self.length // track.greytrack_labels # label interval + for pos in range(self.start, self.end, labelstep): + label = String( + 0, + 0, + track.name, # Add a new label at + fontName=track.greytrack_font, # each interval + fontSize=track.greytrack_fontsize, + fillColor=track.greytrack_fontcolor, + ) + theta, costheta, sintheta = self.canvas_angle(pos) + if theta < startangle or endangle < theta: + continue + x, y = ( + self.xcenter + btm * sintheta, + self.ycenter + btm * costheta, + ) # start text halfway up marker + labelgroup = Group(label) + labelangle = ( + self.sweep * 2 * pi * (pos - self.start) / self.length - pi / 2 + ) + if theta > pi: + label.textAnchor = "end" # Anchor end of text to inner radius + labelangle += pi # and reorient it + cosA, sinA = cos(labelangle), sin(labelangle) + labelgroup.transform = (cosA, -sinA, sinA, cosA, x, y) + if not self.length - x <= labelstep: # Don't overrun the circle + greytrack_labels.append(labelgroup) + + return greytrack_bgs, greytrack_labels + + def canvas_angle(self, base): + """Given base-pair position, return (angle, cosine, sin) (PRIVATE).""" + angle = self.sweep * 2 * pi * (base - self.start) / self.length + return (angle, cos(angle), sin(angle)) + + def _draw_sigil_box( + self, bottom, center, top, startangle, endangle, strand, **kwargs + ): + """Draw BOX sigil (PRIVATE).""" + if strand == 1: + inner_radius = center + outer_radius = top + elif strand == -1: + inner_radius = bottom + outer_radius = center + else: + inner_radius = bottom + outer_radius = top + return self._draw_arc( + inner_radius, outer_radius, startangle, endangle, **kwargs + ) + + def _draw_arc( + self, + inner_radius, + outer_radius, + startangle, + endangle, + color, + border=None, + colour=None, + **kwargs, + ): + """Return closed path describing an arc box (PRIVATE). + + Arguments: + - inner_radius Float distance of inside of arc from drawing center + - outer_radius Float distance of outside of arc from drawing center + - startangle Float angle subtended by start of arc at drawing center + (in radians) + - endangle Float angle subtended by end of arc at drawing center + (in radians) + - color colors.Color object for arc (overridden by backwards + compatible argument with UK spelling, colour). + + Returns a closed path object describing an arced box corresponding to + the passed values. For very small angles, a simple four sided + polygon is used. + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + if abs(endangle - startangle) > 0.01: + # Wide arc, must use full curves + p = ArcPath(strokeColor=strokecolor, fillColor=color, strokewidth=0) + # Note reportlab counts angles anti-clockwise from the horizontal + # (as in mathematics, e.g. complex numbers and polar coordinates) + # but we use clockwise from the vertical. Also reportlab uses + # degrees, but we use radians. + p.addArc( + self.xcenter, + self.ycenter, + inner_radius, + 90 - (endangle * 180 / pi), + 90 - (startangle * 180 / pi), + moveTo=True, + ) + p.addArc( + self.xcenter, + self.ycenter, + outer_radius, + 90 - (endangle * 180 / pi), + 90 - (startangle * 180 / pi), + reverse=True, + ) + p.closePath() + return p + else: + # Cheat and just use a four sided polygon. + # Calculate trig values for angle and coordinates + startcos, startsin = cos(startangle), sin(startangle) + endcos, endsin = cos(endangle), sin(endangle) + x0, y0 = self.xcenter, self.ycenter # origin of the circle + x1, y1 = (x0 + inner_radius * startsin, y0 + inner_radius * startcos) + x2, y2 = (x0 + inner_radius * endsin, y0 + inner_radius * endcos) + x3, y3 = (x0 + outer_radius * endsin, y0 + outer_radius * endcos) + x4, y4 = (x0 + outer_radius * startsin, y0 + outer_radius * startcos) + return draw_polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], color, border) + + def _draw_arc_line( + self, path, start_radius, end_radius, start_angle, end_angle, move=False + ): + """Add a list of points to a path object (PRIVATE). + + Assumes angles given are in degrees! + + Represents what would be a straight line on a linear diagram. + """ + x0, y0 = self.xcenter, self.ycenter # origin of the circle + radius_diff = end_radius - start_radius + angle_diff = end_angle - start_angle + dx = 0.01 # heuristic + a = start_angle * pi / 180 + if move: + path.moveTo(x0 + start_radius * cos(a), y0 + start_radius * sin(a)) + else: + path.lineTo(x0 + start_radius * cos(a), y0 + start_radius * sin(a)) + x = dx + if 0.01 <= abs(dx): + while x < 1: + r = start_radius + x * radius_diff + a = ( + (start_angle + x * (angle_diff)) * pi / 180 + ) # to radians for sin/cos + # print(x0+r*cos(a), y0+r*sin(a)) + path.lineTo(x0 + r * cos(a), y0 + r * sin(a)) + x += dx + a = end_angle * pi / 180 + path.lineTo(x0 + end_radius * cos(a), y0 + end_radius * sin(a)) + + def _draw_arc_poly( + self, + inner_radius, + outer_radius, + inner_startangle, + inner_endangle, + outer_startangle, + outer_endangle, + color, + border=None, + flip=False, + **kwargs, + ): + """Return polygon path describing an arc.""" + strokecolor, color = _stroke_and_fill_colors(color, border) + + x0, y0 = self.xcenter, self.ycenter # origin of the circle + if ( + abs(inner_endangle - outer_startangle) > 0.01 + or abs(outer_endangle - inner_startangle) > 0.01 + or abs(inner_startangle - outer_startangle) > 0.01 + or abs(outer_startangle - outer_startangle) > 0.01 + ): + # Wide arc, must use full curves + p = ArcPath( + strokeColor=strokecolor, + fillColor=color, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + # Note reportlab counts angles anti-clockwise from the horizontal + # (as in mathematics, e.g. complex numbers and polar coordinates) + # but we use clockwise from the vertical. Also reportlab uses + # degrees, but we use radians. + i_start = 90 - (inner_startangle * 180 / pi) + i_end = 90 - (inner_endangle * 180 / pi) + o_start = 90 - (outer_startangle * 180 / pi) + o_end = 90 - (outer_endangle * 180 / pi) + p.addArc(x0, y0, inner_radius, i_end, i_start, moveTo=True, reverse=True) + if flip: + # Flipped, join end to start, + self._draw_arc_line(p, inner_radius, outer_radius, i_end, o_start) + p.addArc(x0, y0, outer_radius, o_end, o_start, reverse=True) + self._draw_arc_line(p, outer_radius, inner_radius, o_end, i_start) + else: + # Not flipped, join start to start, end to end + self._draw_arc_line(p, inner_radius, outer_radius, i_end, o_end) + p.addArc(x0, y0, outer_radius, o_end, o_start, reverse=False) + self._draw_arc_line(p, outer_radius, inner_radius, o_start, i_start) + p.closePath() + return p + else: + # Cheat and just use a four sided polygon. + # Calculate trig values for angle and coordinates + inner_startcos, inner_startsin = ( + cos(inner_startangle), + sin(inner_startangle), + ) + inner_endcos, inner_endsin = cos(inner_endangle), sin(inner_endangle) + outer_startcos, outer_startsin = ( + cos(outer_startangle), + sin(outer_startangle), + ) + outer_endcos, outer_endsin = cos(outer_endangle), sin(outer_endangle) + x1, y1 = ( + x0 + inner_radius * inner_startsin, + y0 + inner_radius * inner_startcos, + ) + x2, y2 = ( + x0 + inner_radius * inner_endsin, + y0 + inner_radius * inner_endcos, + ) + x3, y3 = ( + x0 + outer_radius * outer_endsin, + y0 + outer_radius * outer_endcos, + ) + x4, y4 = ( + x0 + outer_radius * outer_startsin, + y0 + outer_radius * outer_startcos, + ) + return draw_polygon( + [(x1, y1), (x2, y2), (x3, y3), (x4, y4)], + color, + border, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + ) + + def _draw_sigil_cut_corner_box( + self, + bottom, + center, + top, + startangle, + endangle, + strand, + color, + border=None, + corner=0.5, + **kwargs, + ): + """Draw OCTO sigil, box with corners cut off (PRIVATE).""" + if strand == 1: + inner_radius = center + outer_radius = top + elif strand == -1: + inner_radius = bottom + outer_radius = center + else: + inner_radius = bottom + outer_radius = top + + strokecolor, color = _stroke_and_fill_colors(color, border) + + startangle, endangle = min(startangle, endangle), max(startangle, endangle) + angle = endangle - startangle + + middle_radius = 0.5 * (inner_radius + outer_radius) + boxheight = outer_radius - inner_radius + + corner_len = min(0.5 * boxheight, 0.5 * boxheight * corner) + shaft_inner_radius = inner_radius + corner_len + shaft_outer_radius = outer_radius - corner_len + + cornerangle_delta = max( + 0.0, min(abs(boxheight) * 0.5 * corner / middle_radius, abs(angle * 0.5)) + ) + if angle < 0: + cornerangle_delta *= -1 # reverse it + + # Calculate trig values for angle and coordinates + startcos, startsin = cos(startangle), sin(startangle) + endcos, endsin = cos(endangle), sin(endangle) + x0, y0 = self.xcenter, self.ycenter # origin of the circle + p = ArcPath( + strokeColor=strokecolor, + fillColor=color, + strokeLineJoin=1, # 1=round + strokewidth=0, + **kwargs, + ) + # Inner curved edge + p.addArc( + self.xcenter, + self.ycenter, + inner_radius, + 90 - ((endangle - cornerangle_delta) * 180 / pi), + 90 - ((startangle + cornerangle_delta) * 180 / pi), + moveTo=True, + ) + # Corner edge - straight lines assumes small angle! + # TODO - Use self._draw_arc_line(p, ...) here if we expose corner setting + p.lineTo(x0 + shaft_inner_radius * startsin, y0 + shaft_inner_radius * startcos) + p.lineTo(x0 + shaft_outer_radius * startsin, y0 + shaft_outer_radius * startcos) + # Outer curved edge + p.addArc( + self.xcenter, + self.ycenter, + outer_radius, + 90 - ((endangle - cornerangle_delta) * 180 / pi), + 90 - ((startangle + cornerangle_delta) * 180 / pi), + reverse=True, + ) + # Corner edges + p.lineTo(x0 + shaft_outer_radius * endsin, y0 + shaft_outer_radius * endcos) + p.lineTo(x0 + shaft_inner_radius * endsin, y0 + shaft_inner_radius * endcos) + p.closePath() + return p + + def _draw_sigil_arrow( + self, bottom, center, top, startangle, endangle, strand, **kwargs + ): + """Draw ARROW sigil (PRIVATE).""" + if strand == 1: + inner_radius = center + outer_radius = top + orientation = "right" + elif strand == -1: + inner_radius = bottom + outer_radius = center + orientation = "left" + else: + inner_radius = bottom + outer_radius = top + orientation = "right" # backwards compatibility + return self._draw_arc_arrow( + inner_radius, + outer_radius, + startangle, + endangle, + orientation=orientation, + **kwargs, + ) + + def _draw_sigil_big_arrow( + self, bottom, center, top, startangle, endangle, strand, **kwargs + ): + """Draw BIGARROW sigil, like ARROW but straddles the axis (PRIVATE).""" + if strand == -1: + orientation = "left" + else: + orientation = "right" + return self._draw_arc_arrow( + bottom, top, startangle, endangle, orientation=orientation, **kwargs + ) + + def _draw_arc_arrow( + self, + inner_radius, + outer_radius, + startangle, + endangle, + color, + border=None, + shaft_height_ratio=0.4, + head_length_ratio=0.5, + orientation="right", + colour=None, + **kwargs, + ): + """Draw an arrow along an arc (PRIVATE).""" + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + # if orientation == 'right': + # startangle, endangle = min(startangle, endangle), max(startangle, endangle) + # elif orientation == 'left': + # startangle, endangle = max(startangle, endangle), min(startangle, endangle) + # else: + startangle, endangle = min(startangle, endangle), max(startangle, endangle) + if orientation != "left" and orientation != "right": + raise ValueError( + f"Invalid orientation {orientation!r}, should be 'left' or 'right'" + ) + + angle = endangle - startangle # angle subtended by arc + middle_radius = 0.5 * (inner_radius + outer_radius) + boxheight = outer_radius - inner_radius + shaft_height = boxheight * shaft_height_ratio + shaft_inner_radius = middle_radius - 0.5 * shaft_height + shaft_outer_radius = middle_radius + 0.5 * shaft_height + headangle_delta = max( + 0.0, min(abs(boxheight) * head_length_ratio / middle_radius, abs(angle)) + ) + if angle < 0: + headangle_delta *= -1 # reverse it + if orientation == "right": + headangle = endangle - headangle_delta + else: + headangle = startangle + headangle_delta + if startangle <= endangle: + headangle = max(min(headangle, endangle), startangle) + else: + headangle = max(min(headangle, startangle), endangle) + if not ( + startangle <= headangle <= endangle or endangle <= headangle <= startangle + ): + raise RuntimeError( + "Problem drawing arrow, invalid positions. " + "Start angle: %s, Head angle: %s, " + "End angle: %s, Angle: %s" % (startangle, headangle, endangle, angle) + ) + + # Calculate trig values for angle and coordinates + startcos, startsin = cos(startangle), sin(startangle) + headcos, headsin = cos(headangle), sin(headangle) + endcos, endsin = cos(endangle), sin(endangle) + x0, y0 = self.xcenter, self.ycenter # origin of the circle + if 0.5 >= abs(angle) and abs(headangle_delta) >= abs(angle): + # If the angle is small, and the arrow is all head, + # cheat and just use a triangle. + if orientation == "right": + x1, y1 = (x0 + inner_radius * startsin, y0 + inner_radius * startcos) + x2, y2 = (x0 + outer_radius * startsin, y0 + outer_radius * startcos) + x3, y3 = (x0 + middle_radius * endsin, y0 + middle_radius * endcos) + else: + x1, y1 = (x0 + inner_radius * endsin, y0 + inner_radius * endcos) + x2, y2 = (x0 + outer_radius * endsin, y0 + outer_radius * endcos) + x3, y3 = (x0 + middle_radius * startsin, y0 + middle_radius * startcos) + # return draw_polygon([(x1,y1),(x2,y2),(x3,y3)], color, border, + # stroke_line_join=1) + return Polygon( + [x1, y1, x2, y2, x3, y3], + strokeColor=border or color, + fillColor=color, + strokeLineJoin=1, # 1=round, not mitre! + strokewidth=0, + ) + elif orientation == "right": + p = ArcPath( + strokeColor=strokecolor, + fillColor=color, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + **kwargs, + ) + # Note reportlab counts angles anti-clockwise from the horizontal + # (as in mathematics, e.g. complex numbers and polar coordinates) + # but we use clockwise from the vertical. Also reportlab uses + # degrees, but we use radians. + p.addArc( + self.xcenter, + self.ycenter, + shaft_inner_radius, + 90 - (headangle * 180 / pi), + 90 - (startangle * 180 / pi), + moveTo=True, + ) + p.addArc( + self.xcenter, + self.ycenter, + shaft_outer_radius, + 90 - (headangle * 180 / pi), + 90 - (startangle * 180 / pi), + reverse=True, + ) + if abs(angle) < 0.5: + p.lineTo(x0 + outer_radius * headsin, y0 + outer_radius * headcos) + p.lineTo(x0 + middle_radius * endsin, y0 + middle_radius * endcos) + p.lineTo(x0 + inner_radius * headsin, y0 + inner_radius * headcos) + else: + self._draw_arc_line( + p, + outer_radius, + middle_radius, + 90 - (headangle * 180 / pi), + 90 - (endangle * 180 / pi), + ) + self._draw_arc_line( + p, + middle_radius, + inner_radius, + 90 - (endangle * 180 / pi), + 90 - (headangle * 180 / pi), + ) + p.closePath() + return p + else: + p = ArcPath( + strokeColor=strokecolor, + fillColor=color, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + **kwargs, + ) + # Note reportlab counts angles anti-clockwise from the horizontal + # (as in mathematics, e.g. complex numbers and polar coordinates) + # but we use clockwise from the vertical. Also reportlab uses + # degrees, but we use radians. + p.addArc( + self.xcenter, + self.ycenter, + shaft_inner_radius, + 90 - (endangle * 180 / pi), + 90 - (headangle * 180 / pi), + moveTo=True, + reverse=True, + ) + p.addArc( + self.xcenter, + self.ycenter, + shaft_outer_radius, + 90 - (endangle * 180 / pi), + 90 - (headangle * 180 / pi), + reverse=False, + ) + # Note - two staight lines is only a good approximation for small + # head angle, in general will need to curved lines here: + if abs(angle) < 0.5: + p.lineTo(x0 + outer_radius * headsin, y0 + outer_radius * headcos) + p.lineTo(x0 + middle_radius * startsin, y0 + middle_radius * startcos) + p.lineTo(x0 + inner_radius * headsin, y0 + inner_radius * headcos) + else: + self._draw_arc_line( + p, + outer_radius, + middle_radius, + 90 - (headangle * 180 / pi), + 90 - (startangle * 180 / pi), + ) + self._draw_arc_line( + p, + middle_radius, + inner_radius, + 90 - (startangle * 180 / pi), + 90 - (headangle * 180 / pi), + ) + p.closePath() + return p + + def _draw_sigil_jaggy( + self, + bottom, + center, + top, + startangle, + endangle, + strand, + color, + border=None, + **kwargs, + ): + """Draw JAGGY sigil (PRIVATE). + + Although we may in future expose the head/tail jaggy lengths, for now + both the left and right edges are drawn jagged. + """ + if strand == 1: + inner_radius = center + outer_radius = top + teeth = 2 + elif strand == -1: + inner_radius = bottom + outer_radius = center + teeth = 2 + else: + inner_radius = bottom + outer_radius = top + teeth = 4 + + # TODO, expose these settings? + tail_length_ratio = 1.0 + head_length_ratio = 1.0 + + strokecolor, color = _stroke_and_fill_colors(color, border) + + startangle, endangle = min(startangle, endangle), max(startangle, endangle) + angle = endangle - startangle # angle subtended by arc + height = outer_radius - inner_radius + + assert startangle <= endangle and angle >= 0 + if head_length_ratio and tail_length_ratio: + headangle = max( + endangle + - min(height * head_length_ratio / (center * teeth), angle * 0.5), + startangle, + ) + tailangle = min( + startangle + + min(height * tail_length_ratio / (center * teeth), angle * 0.5), + endangle, + ) + # With very small features, can due to floating point calculations + # violate the assertion below that start <= tail <= head <= end + tailangle = min(tailangle, headangle) + elif head_length_ratio: + headangle = max( + endangle - min(height * head_length_ratio / (center * teeth), angle), + startangle, + ) + tailangle = startangle + else: + headangle = endangle + tailangle = min( + startangle + min(height * tail_length_ratio / (center * teeth), angle), + endangle, + ) + + if not startangle <= tailangle <= headangle <= endangle: + raise RuntimeError( + "Problem drawing jaggy sigil, invalid " + "positions. Start angle: %s, " + "Tail angle: %s, Head angle: %s, End angle %s, " + "Angle: %s" % (startangle, tailangle, headangle, endangle, angle) + ) + + # Calculate trig values for angle and coordinates + startcos, startsin = cos(startangle), sin(startangle) + headcos, headsin = cos(headangle), sin(headangle) + endcos, endsin = cos(endangle), sin(endangle) + x0, y0 = self.xcenter, self.ycenter # origin of the circle + + p = ArcPath( + strokeColor=strokecolor, + fillColor=color, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + **kwargs, + ) + # Note reportlab counts angles anti-clockwise from the horizontal + # (as in mathematics, e.g. complex numbers and polar coordinates) + # but we use clockwise from the vertical. Also reportlab uses + # degrees, but we use radians. + p.addArc( + self.xcenter, + self.ycenter, + inner_radius, + 90 - (headangle * 180 / pi), + 90 - (tailangle * 180 / pi), + moveTo=True, + ) + for i in range(teeth): + p.addArc( + self.xcenter, + self.ycenter, + inner_radius + i * height / teeth, + 90 - (tailangle * 180 / pi), + 90 - (startangle * 180 / pi), + ) + # Curved line needed when drawing long jaggies + self._draw_arc_line( + p, + inner_radius + i * height / teeth, + inner_radius + (i + 1) * height / teeth, + 90 - (startangle * 180 / pi), + 90 - (tailangle * 180 / pi), + ) + p.addArc( + self.xcenter, + self.ycenter, + outer_radius, + 90 - (headangle * 180 / pi), + 90 - (tailangle * 180 / pi), + reverse=True, + ) + for i in range(teeth): + p.addArc( + self.xcenter, + self.ycenter, + outer_radius - i * height / teeth, + 90 - (endangle * 180 / pi), + 90 - (headangle * 180 / pi), + reverse=True, + ) + # Curved line needed when drawing long jaggies + self._draw_arc_line( + p, + outer_radius - i * height / teeth, + outer_radius - (i + 1) * height / teeth, + 90 - (endangle * 180 / pi), + 90 - (headangle * 180 / pi), + ) + p.closePath() + return p diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Colors.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Colors.py new file mode 100644 index 0000000000000000000000000000000000000000..a37e1071d4596c53866a1f117384c0aff5389e69 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Colors.py @@ -0,0 +1,234 @@ +# Copyright 2003-2008 by Leighton Pritchard. 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Colors module. + +Provides: + +- ColorTranslator - class to convert tuples of integers and floats into + colors.Color objects + +For drawing capabilities, this module uses reportlab to define colors: +http://www.reportlab.com +""" + +# ReportLab imports +from reportlab.lib import colors + + +class ColorTranslator: + """Class providing methods for translating representations of color into. + + Examples + -------- + >>> from Bio.Graphics import GenomeDiagram + >>> gdct=GenomeDiagram._Colors.ColorTranslator() + >>> print(gdct.float1_color((0.5, 0.5, 0.5))) + Color(.5,.5,.5,1) + >>> print(gdct.int255_color((1, 75, 240))) + Color(.003922,.294118,.941176,1) + >>> print(gdct.artemis_color(7)) + Color(1,1,0,1) + >>> print(gdct.scheme_color(2)) + Color(1,0,0,1) + >>> gdct.get_artemis_colorscheme() + {0: (Color(1,1,1,1), 'pathogenicity, adaptation, chaperones'), 1: (Color(.39,.39,.39,1), 'energy metabolism'), 2: (Color(1,0,0,1), 'information transfer'), 3: (Color(0,1,0,1), 'surface'), 4: (Color(0,0,1,1), 'stable RNA'), 5: (Color(0,1,1,1), 'degradation of large molecules'), 6: (Color(1,0,1,1), 'degradation of small molecules'), 7: (Color(1,1,0,1), 'central/intermediary/miscellaneous metabolism'), 8: (Color(.6,.98,.6,1), 'unknown'), 9: (Color(.53,.81,.98,1), 'regulators'), 10: (Color(1,.65,0,1), 'conserved hypotheticals'), 11: (Color(.78,.59,.39,1), 'pseudogenes and partial genes'), 12: (Color(1,.78,.78,1), 'phage/IS elements'), 13: (Color(.7,.7,.7,1), 'some miscellaneous information'), 14: (Color(0,0,0,1), ''), 15: (Color(1,.25,.25,1), 'secondary metabolism'), 16: (Color(1,.5,.5,1), ''), 17: (Color(1,.75,.75,1), '')} + + >>> print(gdct.translate((0.5, 0.5, 0.5))) + Color(.5,.5,.5,1) + >>> print(gdct.translate((1, 75, 240))) + Color(.003922,.294118,.941176,1) + >>> print(gdct.translate(7)) + Color(1,1,0,1) + >>> print(gdct.translate(2)) + Color(1,0,0,1) + + """ + + def __init__(self, filename=None): + """Initialize. + + Argument filename is the location of a file containing + colorscheme information. + """ + self._artemis_colorscheme = { + 0: (colors.Color(1, 1, 1), "pathogenicity, adaptation, chaperones"), + 1: (colors.Color(0.39, 0.39, 0.39), "energy metabolism"), + 2: (colors.Color(1, 0, 0), "information transfer"), + 3: (colors.Color(0, 1, 0), "surface"), + 4: (colors.Color(0, 0, 1), "stable RNA"), + 5: (colors.Color(0, 1, 1), "degradation of large molecules"), + 6: (colors.Color(1, 0, 1), "degradation of small molecules"), + 7: (colors.Color(1, 1, 0), "central/intermediary/miscellaneous metabolism"), + 8: (colors.Color(0.60, 0.98, 0.60), "unknown"), + 9: (colors.Color(0.53, 0.81, 0.98), "regulators"), + 10: (colors.Color(1, 0.65, 0), "conserved hypotheticals"), + 11: (colors.Color(0.78, 0.59, 0.39), "pseudogenes and partial genes"), + 12: (colors.Color(1, 0.78, 0.78), "phage/IS elements"), + 13: (colors.Color(0.70, 0.70, 0.70), "some miscellaneous information"), + 14: (colors.Color(0, 0, 0), ""), + 15: (colors.Color(1, 0.25, 0.25), "secondary metabolism"), + 16: (colors.Color(1, 0.5, 0.5), ""), + 17: (colors.Color(1, 0.75, 0.75), ""), + } # Hardwired Artemis color scheme + self._colorscheme = {} + if filename is not None: + self.read_colorscheme(filename) # Imported color scheme + else: + self._colorscheme = self._artemis_colorscheme + + def translate(self, color=None, colour=None): + """Translate a color into a ReportLab Color object. + + Arguments: + - color - Color defined as an int, a tuple of three ints 0->255 + or a tuple of three floats 0 -> 1, or a string giving + one of the named colors defined by ReportLab, or a + ReportLab color object (returned as is). + - colour - Backwards compatible alias using UK spelling (which + will over-ride any color argument). + + Returns a colors.Color object, determined semi-intelligently + depending on the input values + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + + if color is None: + raise ValueError("Passed color (or colour) must be a valid color type") + elif isinstance(color, int): + color = self.scheme_color(color) + elif isinstance(color, colors.Color): + return color + elif isinstance(color, str): + # Assume its a named reportlab color like "red". + color = colors.toColor(color) + elif isinstance(color, tuple) and isinstance(color[0], float): + color = self.float1_color(color) + elif isinstance(color, tuple) and isinstance(color[0], int): + color = self.int255_color(color) + return color + + def read_colorscheme(self, filename): + r"""Load colour scheme from file. + + Reads information from a file containing color information and stores + it internally. + + Argument filename is the location of a file defining colors in + tab-separated format plaintext as:: + + INT \t RED \t GREEN \t BLUE \t Comment + + Where RED, GREEN and BLUE are intensities in the range 0 -> 255, e.g.:: + + 2 \t 255 \t 0 \t 0 \t Red: Information transfer + + """ + with open(filename).readlines() as lines: + for line in lines: + data = line.strip().split("\t") + try: + label = int(data[0]) + red, green, blue = int(data[1]), int(data[2]), int(data[3]) + if len(data) > 4: + comment = data[4] + else: + comment = "" + self._colorscheme[label] = ( + self.int255_color((red, green, blue)), + comment, + ) + except ValueError: + raise ValueError( + "Expected INT \t INT \t INT \t INT \t string input" + ) from None + + def get_artemis_colorscheme(self): + """Return the Artemis color scheme as a dictionary.""" + return self._artemis_colorscheme + + def artemis_color(self, value): + """Artemis color (integer) to ReportLab Color object. + + Arguments: + - value: An int representing a functional class in the Artemis + color scheme (see www.sanger.ac.uk for a description), + or a string from a GenBank feature annotation for the + color which may be dot delimited (in which case the + first value is used). + + Takes an int representing a functional class in the Artemis color + scheme, and returns the appropriate colors.Color object + """ + try: + value = int(value) + except ValueError: + if value.count("."): # dot-delimited + value = int(value.split(".", 1)[0]) # Use only first integer + else: + raise + if value in self._artemis_colorscheme: + return self._artemis_colorscheme[value][0] + else: + raise ValueError("Artemis color out of range: %d" % value) + + def get_colorscheme(self): + """Return the user-defined color scheme as a dictionary.""" + return self._colorscheme + + def scheme_color(self, value): + """Map a user-defined color integer to a ReportLab Color object. + + - value: An int representing a single color in the user-defined + color scheme + + Takes an int representing a user-defined color and returns the + appropriate colors.Color object. + """ + if value in self._colorscheme: + return self._colorscheme[value][0] + else: + raise ValueError("Scheme color out of range: %d" % value) + + def int255_color(self, values): + """Map integer (red, green, blue) tuple to a ReportLab Color object. + + - values: A tuple of (red, green, blue) intensities as + integers in the range 0->255 + + Takes a tuple of (red, green, blue) intensity values in the range + 0 -> 255 and returns an appropriate colors.Color object. + """ + red, green, blue = values + factor = 1 / 255.0 + red, green, blue = red * factor, green * factor, blue * factor + return colors.Color(red, green, blue) + + def float1_color(self, values): + """Map float (red, green, blue) tuple to a ReportLab Color object. + + - values: A tuple of (red, green, blue) intensities as floats + in the range 0 -> 1 + + Takes a tuple of (red, green, blue) intensity values in the range + 0 -> 1 and returns an appropriate colors.Color object. + """ + red, green, blue = values + return colors.Color(red, green, blue) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=2) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CrossLink.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CrossLink.py new file mode 100644 index 0000000000000000000000000000000000000000..7958de4d51c3a4fc21da6eba81ad18baa57e3921 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CrossLink.py @@ -0,0 +1,100 @@ +# Copyright 2011-2017 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. +"""Genome Diagram Feature cross-link module.""" + +from reportlab.lib import colors + + +class CrossLink: + """Hold information for drawing a cross link between features.""" + + def __init__( + self, featureA, featureB, color=colors.lightgreen, border=None, flip=False + ): + """Create a new cross link. + + Arguments featureA and featureB should GenomeDiagram feature objects, + or 3-tuples (track object, start, end), and currently must be on + different tracks. + + The color and border arguments should be ReportLab colour objects, or + for border use a boolean False for no border, otherwise it defaults to + the same as the main colour. + + The flip argument draws an inverted cross link, useful for showing a + mapping where one sequence has been reversed. It is conventional to + also use a different colour (e.g. red for simple links, blue for any + flipped links). + """ + # Initialize attributes + self.featureA = featureA + self.featureB = featureB + self.color = color # default color to draw the feature + self.border = border + self.flip = flip + + @property + def startA(self): + """Start position of Feature A.""" + try: + return self.featureA.start + except AttributeError: + track, start, end = self.featureA + return start + + @property + def endA(self): + """End position of Feature A.""" + try: + return self.featureA.end + except AttributeError: + track, start, end = self.featureA + return end + + def _trackA(self, tracks): + try: + track, start, end = self.featureA + assert track in tracks + return track + except TypeError: + for track in tracks: + for feature_set in track.get_sets(): + if hasattr(feature_set, "features"): + if self.featureA in feature_set.features.values(): + return track + return None + + @property + def startB(self): + """Start position of Feature B.""" + try: + return self.featureB.start + except AttributeError: + track, start, end = self.featureB + return start + + @property + def endB(self): + """End position of Feature B.""" + try: + return self.featureB.end + except AttributeError: + track, start, end = self.featureB + return end + + def _trackB(self, tracks): + try: + track, start, end = self.featureB + assert track in tracks + return track + except TypeError: + for track in tracks: + for feature_set in track.get_sets(): + if hasattr(feature_set, "features"): + if self.featureB in feature_set.features.values(): + return track + return None diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Diagram.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Diagram.py new file mode 100644 index 0000000000000000000000000000000000000000..076de2267124ed00c5b69107772ee4942962420e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Diagram.py @@ -0,0 +1,411 @@ +# Copyright 2003-2008 by Leighton Pritchard. 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +"""Provides a container for information concerning the tracks to be drawn in a diagram. + +It also provides the interface for defining the diagram (possibly split these +functions in later version?). + +For drawing capabilities, this module uses reportlab to draw and write the +diagram: + +http://www.reportlab.com + +For dealing with biological information, the package expects BioPython +objects - namely SeqRecord objects containing SeqFeature objects. +""" + +try: + from reportlab.graphics import renderPM +except ImportError: + # This is an optional part of ReportLab, so may not be installed. + renderPM = None + +from Bio.Graphics import _write + +from ._CircularDrawer import CircularDrawer +from ._LinearDrawer import LinearDrawer +from ._Track import Track + + +def _first_defined(*args): + """Return the first non-null argument (PRIVATE).""" + for arg in args: + if arg is not None: + return arg + return None + + +class Diagram: + """Diagram container. + + Arguments: + - name - a string, identifier for the diagram. + - tracks - a list of Track objects comprising the diagram. + - format - a string, format of the diagram 'circular' or + 'linear', depending on the sort of diagram required. + - pagesize - a string, the pagesize of output describing the ISO + size of the image, or a tuple of pixels. + - orientation - a string describing the required orientation of the + final drawing ('landscape' or 'portrait'). + - x - a float (0->1), the proportion of the page to take + up with even X margins t the page. + - y - a float (0->1), the proportion of the page to take + up with even Y margins to the page. + - xl - a float (0->1), the proportion of the page to take + up with the left X margin to the page (overrides x). + - xr - a float (0->1), the proportion of the page to take + up with the right X margin to the page (overrides x). + - yt - a float (0->1), the proportion of the page to take + up with the top Y margin to the page (overrides y). + - yb - a float (0->1), the proportion of the page to take + up with the bottom Y margin to the page (overrides y). + - circle_core - a float, the proportion of the available radius to + leave empty at the center of a circular diagram (0 to 1). + - start - an integer, the base/aa position to start the diagram at. + - end - an integer, the base/aa position to end the diagram at. + - tracklines - a boolean, True if track guidelines are to be drawn. + - fragments - and integer, for a linear diagram, the number of equal + divisions into which the sequence is divided. + - fragment_size - a float (0->1), the proportion of the space + available to each fragment that should be used in drawing. + - track_size - a float (0->1), the proportion of the space + available to each track that should be used in drawing with sigils. + - circular - a boolean, True if the genome/sequence to be drawn + is, in reality, circular. + + """ + + def __init__( + self, + name=None, + format="circular", + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=False, + fragments=10, + fragment_size=None, + track_size=0.75, + circular=True, + circle_core=0.0, + ): + """Initialize. + + gdd = Diagram(name=None) + """ + self.tracks = {} # Holds all Track objects, keyed by level + self.name = name # Description of the diagram + # Diagram page setup attributes + self.format = format + self.pagesize = pagesize + self.orientation = orientation + self.x = x + self.y = y + self.xl = xl + self.xr = xr + self.yt = yt + self.yb = yb + self.start = start + self.end = end + self.tracklines = tracklines + self.fragments = fragments + if fragment_size is not None: + self.fragment_size = fragment_size + else: + if self.fragments == 1: + # For single fragments, default to full height + self.fragment_size = 1 + else: + # Otherwise keep a 10% gap between fragments + self.fragment_size = 0.9 + self.track_size = track_size + self.circular = circular + self.circle_core = circle_core + self.cross_track_links = [] + self.drawing = None + + def set_all_tracks(self, attr, value): + """Set the passed attribute of all tracks in the set to the passed value. + + Arguments: + - attr - An attribute of the Track class. + - value - The value to set that attribute. + + set_all_tracks(self, attr, value) + """ + for track in self.tracks.values(): + if hasattr(track, attr): + # If the feature has the attribute set it to the passed value + setattr(track, attr, value) + + def draw( + self, + format=None, + pagesize=None, + orientation=None, + x=None, + y=None, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=None, + fragments=None, + fragment_size=None, + track_size=None, + circular=None, + circle_core=None, + cross_track_links=None, + ): + """Draw the diagram, with passed parameters overriding existing attributes. + + gdd.draw(format='circular') + """ + # Pass the parameters to the drawer objects that will build the + # diagrams. At the moment, we detect overrides with an or in the + # Instantiation arguments, but I suspect there's a neater way to do + # this. + if format == "linear": + drawer = LinearDrawer( + self, + _first_defined(pagesize, self.pagesize), + _first_defined(orientation, self.orientation), + _first_defined(x, self.x), + _first_defined(y, self.y), + _first_defined(xl, self.xl), + _first_defined(xr, self.xr), + _first_defined(yt, self.yt), + _first_defined(yb, self.yb), + _first_defined(start, self.start), + _first_defined(end, self.end), + _first_defined(tracklines, self.tracklines), + _first_defined(fragments, self.fragments), + _first_defined(fragment_size, self.fragment_size), + _first_defined(track_size, self.track_size), + _first_defined(cross_track_links, self.cross_track_links), + ) + else: + drawer = CircularDrawer( + self, + _first_defined(pagesize, self.pagesize), + _first_defined(orientation, self.orientation), + _first_defined(x, self.x), + _first_defined(y, self.y), + _first_defined(xl, self.xl), + _first_defined(xr, self.xr), + _first_defined(yt, self.yt), + _first_defined(yb, self.yb), + _first_defined(start, self.start), + _first_defined(end, self.end), + _first_defined(tracklines, self.tracklines), + _first_defined(track_size, self.track_size), + _first_defined(circular, self.circular), + _first_defined(circle_core, self.circle_core), + _first_defined(cross_track_links, self.cross_track_links), + ) + drawer.draw() # Tell the drawer to complete the drawing + self.drawing = drawer.drawing # Get the completed drawing + + def write(self, filename="test1.ps", output="PS", dpi=72): + """Write the drawn diagram to a specified file, in a specified format. + + Arguments: + - filename - a string indicating the name of the output file, + or a handle to write to. + - output - a string indicating output format, one of PS, PDF, + SVG, or provided the ReportLab renderPM module is installed, one + of the bitmap formats JPG, BMP, GIF, PNG, TIFF or TIFF. The + format can be given in upper or lower case. + - dpi - an integer. Resolution (dots per inch) for bitmap formats. + + Returns: + No return value. + + write(self, filename='test1.ps', output='PS', dpi=72) + + """ + return _write(self.drawing, filename, output, dpi=dpi) + + def write_to_string(self, output="PS", dpi=72): + """Return a byte string containing the diagram in the requested format. + + Arguments: + - output - a string indicating output format, one of PS, PDF, + SVG, JPG, BMP, GIF, PNG, TIFF or TIFF (as specified for the write + method). + - dpi - Resolution (dots per inch) for bitmap formats. + + Returns: + Return the completed drawing as a bytes string in a prescribed + format. + + """ + # The ReportLab drawToString method, which this function used to call, + # originally just used a StringIO handle with the drawToFile method. + # + # TODO - Rename this method to include keyword bytes? + from io import BytesIO + + handle = BytesIO() + self.write(handle, output, dpi) + return handle.getvalue() + + def add_track(self, track, track_level): + """Add a Track object to the diagram. + + It also accepts instructions to place it at a particular level on the + diagram. + + Arguments: + - track - Track object to draw. + - track_level - an integer. The level at which the track will be + drawn (above an arbitrary baseline). + + add_track(self, track, track_level) + """ + if track is None: + raise ValueError("Must specify track") + if track_level not in self.tracks: # No track at that level + self.tracks[track_level] = track # so just add it + else: # Already a track there, so shunt all higher tracks up one + occupied_levels = sorted( + self.get_levels() + ) # Get list of occupied levels... + occupied_levels.reverse() # ...reverse it (highest first) + for val in occupied_levels: + # If track value >= that to be added + if val >= track.track_level: + self.tracks[val + 1] = self.tracks[val] # ...increment by 1 + self.tracks[track_level] = track # And put the new track in + self.tracks[track_level].track_level = track_level + + def new_track(self, track_level, **args): + """Add a new Track to the diagram at a given level. + + The track is returned for further user manipulation. + + Arguments: + - track_level - an integer. The level at which the track will be + drawn (above an arbitrary baseline). + + new_track(self, track_level) + """ + newtrack = Track() + for key in args: + setattr(newtrack, key, args[key]) + if track_level not in self.tracks: # No track at that level + self.tracks[track_level] = newtrack # so just add it + else: # Already a track there, so shunt all higher tracks up one + occupied_levels = sorted( + self.get_levels() + ) # Get list of occupied levels... + occupied_levels.reverse() # ...reverse (highest first)... + for val in occupied_levels: + if val >= track_level: + # Track value >= that to be added, increment by 1 + self.tracks[val + 1] = self.tracks[val] + self.tracks[track_level] = newtrack # And put the new track in + self.tracks[track_level].track_level = track_level + return newtrack + + def del_track(self, track_level): + """Remove the track to be drawn at a particular level on the diagram. + + Arguments: + - track_level - an integer. The level of the track on the diagram + to delete. + + del_track(self, track_level) + """ + del self.tracks[track_level] + + def get_tracks(self): + """Return a list of the tracks contained in the diagram.""" + return list(self.tracks.values()) + + def move_track(self, from_level, to_level): + """Move a track from one level on the diagram to another. + + Arguments: + - from_level - an integer. The level at which the track to be + moved is found. + - to_level - an integer. The level to move the track to. + + """ + aux = self.tracks[from_level] + del self.tracks[from_level] + self.add_track(aux, to_level) + + def renumber_tracks(self, low=1, step=1): + """Renumber all tracks consecutively. + + Optionally from a passed lowest number. + + Arguments: + - low - an integer. The track number to start from. + - step - an integer. The track interval for separation of + tracks. + + """ + track = low # Start numbering from here + levels = self.get_levels() + + conversion = {} # Holds new set of levels + for level in levels: # Starting at low... + conversion[track] = self.tracks[level] # Add old tracks to new set + conversion[track].track_level = track + track += step # step interval + self.tracks = conversion # Replace old set of levels with new set + + def get_levels(self): + """Return a sorted list of levels occupied by tracks in the diagram.""" + return sorted(self.tracks) + + def get_drawn_levels(self): + """Return a sorted list of levels occupied by tracks. + + These tracks are not explicitly hidden. + """ + return sorted(key for key in self.tracks if not self.tracks[key].hide) + + def range(self): + """Return lowest and highest base numbers from track features. + + Returned type is a tuple. + """ + lows, highs = [], [] + for track in self.tracks.values(): # Get ranges for each track + low, high = track.range() + lows.append(low) + highs.append(high) + return min(lows), max(highs) # Return extremes from all tracks + + def __getitem__(self, key): + """Return the track contained at the level of the passed key.""" + return self.tracks[key] + + def __str__(self): + """Return a formatted string describing the diagram.""" + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d tracks" % len(self.tracks)) + for level in self.get_levels(): + outstr.append("Track %d: %s\n" % (level, self.tracks[level])) + outstr = "\n".join(outstr) + return outstr diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Feature.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Feature.py new file mode 100644 index 0000000000000000000000000000000000000000..e3be610f62351d9980a62353c67211714e5b6ed6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Feature.py @@ -0,0 +1,197 @@ +# Copyright 2003-2008 by Leighton Pritchard. 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Feature module. + +Provides: + - Feature - class to wrap Bio.SeqFeature objects with drawing information + +For drawing capabilities, this module uses reportlab to define colors: +http://www.reportlab.com +""" + +# ReportLab imports +from reportlab.lib import colors + +# GenomeDiagram imports +from ._Colors import ColorTranslator + + +class Feature: + """Class to wrap Bio.SeqFeature objects for GenomeDiagram. + + Attributes: + - parent FeatureSet, container for the object + - id Unique id + - color color.Color, color to draw the feature + - hide Boolean for whether the feature will be drawn or not + - sigil String denoting the type of sigil to use for the feature. + Currently either "BOX" or "ARROW" are supported. + - arrowhead_length Float denoting length of the arrow head to be drawn, + relative to the bounding box height. The arrow shaft + takes up the remainder of the bounding box's length. + - arrowshaft_height Float denoting length of the representative arrow + shaft to be drawn, relative to the bounding box height. + The arrow head takes the full height of the bound box. + - name_qualifiers List of Strings, describes the qualifiers that may + contain feature names in the wrapped Bio.SeqFeature object + - label Boolean, 1 if the label should be shown + - label_font String describing the font to use for the feature label + - label_size Int describing the feature label font size + - label_color color.Color describing the feature label color + - label_angle Float describing the angle through which to rotate the + feature label in degrees (default = 45, linear only) + - label_position String, 'start', 'end' or 'middle' denoting where + to place the feature label. Leave as None for the default + which is 'start' for linear diagrams, and at the bottom of + the feature as drawn on circular diagrams. + - label_strand Integer -1 or +1 to explicitly place the label on the + forward or reverse strand. Default (None) follows th + feature's strand. Use -1 to put labels under (linear) or + inside (circular) the track, +1 to put them above (linear) + or outside (circular) the track. + - locations List of tuples of (start, end) ints describing where the + feature and any subfeatures start and end + - type String denoting the feature type + - name String denoting the feature name + - strand Int describing the strand on which the feature is found + + """ + + def __init__( + self, + parent=None, + feature_id=None, + feature=None, + color=colors.lightgreen, + label=0, + border=None, + colour=None, + ): + """Initialize. + + Arguments: + - parent FeatureSet containing the feature + - feature_id Unique id for the feature + - feature Bio.SeqFeature object to be wrapped + - color color.Color Color to draw the feature (overridden + by backwards compatible argument with UK spelling, colour). + Either argument is overridden if 'color' is found in feature + qualifiers + - border color.Color Color to draw the feature border, use + None for the same as the fill color, False for no border. + - label Boolean, 1 if the label should be shown + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + + self._colortranslator = ColorTranslator() + + # Initialize attributes + self.parent = parent + self.id = feature_id + self.color = color # default color to draw the feature + self.border = border + self._feature = None # Bio.SeqFeature object to wrap + self.hide = 0 # show by default + self.sigil = "BOX" + self.arrowhead_length = 0.5 # 50% of the box height + self.arrowshaft_height = 0.4 # 40% of the box height + self.name_qualifiers = ["gene", "label", "name", "locus_tag", "product"] + self.label = label + self.label_font = "Helvetica" + self.label_size = 6 + self.label_color = colors.black + self.label_angle = 45 + self.label_position = None # Expect 'start', 'middle', or 'end' (plus aliases) + self.label_strand = None # Expect +1 or -1 if overriding this + + if feature is not None: + self.set_feature(feature) + + def set_feature(self, feature): + """Define the Bio.SeqFeature object to be wrapped.""" + self._feature = feature + self.__process_feature() + + def __process_feature(self): + """Examine wrapped feature and set some properties accordingly (PRIVATE).""" + self.locations = [] + bounds = [] + # This will be a list of length one for a SimpleLocation: + for location in self._feature.location.parts: + start = int(location.start) + end = int(location.end) + # if start > end and self.strand == -1: + # start, end = end, start + self.locations.append((start, end)) + bounds += [start, end] + self.type = str(self._feature.type) # Feature type + # TODO - Strand can vary with subfeatures (e.g. mixed strand tRNA) + if self._feature.location.strand is None: + # This is the SeqFeature default (None), but the drawing code + # only expects 0, +1 or -1. + self.strand = 0 + else: + self.strand = int(self._feature.location.strand) # Feature strand + if "color" in self._feature.qualifiers: # Artemis color (if present) + self.color = self._colortranslator.artemis_color( + self._feature.qualifiers["color"][0] + ) + self.name = self.type + for qualifier in self.name_qualifiers: + if qualifier in self._feature.qualifiers: + self.name = self._feature.qualifiers[qualifier][0] + break + # Note will be 0 to N for origin wrapping feature on genome of length N + self.start, self.end = min(bounds), max(bounds) + + def get_feature(self): + """Return the unwrapped Bio.SeqFeature object.""" + return self._feature + + def set_colour(self, colour): + """Backwards compatible variant of set_color(self, color) using UK spelling.""" + color = self._colortranslator.translate(colour) + self.color = color + + def set_color(self, color): + """Set the color in which the feature will be drawn. + + Arguments: + - color The color to draw the feature - either a colors.Color + object, an RGB tuple of floats, or an integer corresponding a + colors in colors.txt + + """ + # TODO - Make this into the set method for a color property? + color = self._colortranslator.translate(color) + self.color = color + + def __getattr__(self, name): + """Get attribute by name. + + If the Feature class doesn't have the attribute called for, + check in self._feature for it. + """ + return getattr(self._feature, name) # try to get the attribute from the feature + + +################################################################################ +# RUN AS SCRIPT +################################################################################ + +if __name__ == "__main__": + # Test code + gdf = Feature() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_FeatureSet.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_FeatureSet.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0168cb9bcdbc75ae1245bb9fc7a8822c73d96e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_FeatureSet.py @@ -0,0 +1,207 @@ +# Copyright 2003-2008 by Leighton Pritchard. 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ +# +# Thanks to Peter Cock for the impetus to write the get_features() code to +# subselect Features. +# +################################################################################ + +"""FeatureSet module. + +Provides: + - FeatureSet - container for Feature objects + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +import re + +from ._Feature import Feature + + +class FeatureSet: + """FeatureSet object.""" + + def __init__(self, set_id=None, name=None, parent=None): + """Create the object. + + Arguments: + - set_id: Unique id for the set + - name: String identifying the feature set + + """ + self.parent = parent + self.id = id # Unique id for the set + self.next_id = 0 # counter for unique feature ids + self.features = {} # Holds features, keyed by ID + self.name = name # String describing the set + + def add_feature(self, feature, **kwargs): + """Add a new feature. + + Arguments: + - feature: Bio.SeqFeature object + - kwargs: Keyword arguments for Feature. Named attributes + of the Feature + + Add a Bio.SeqFeature object to the diagram (will be stored + internally in a Feature wrapper). + """ + id = self.next_id # get id number + f = Feature(self, id, feature) + self.features[id] = f # add feature + for key in kwargs: + if key == "colour" or key == "color": + # Deal with "colour" as a special case by also mapping to color. + # If Feature.py used a python property we wouldn't need to call + # set_color explicitly. However, this is important to make sure + # every color gets mapped to a colors object - for example color + # numbers, or strings (may not matter for PDF, but does for PNG). + self.features[id].set_color(kwargs[key]) + continue + setattr(self.features[id], key, kwargs[key]) + self.next_id += 1 # increment next id + return f + + def del_feature(self, feature_id): + """Delete a feature. + + Arguments: + - feature_id: Unique id of the feature to delete + + Remove a feature from the set, indicated by its id. + """ + del self.features[feature_id] + + def set_all_features(self, attr, value): + """Set an attribute of all the features. + + Arguments: + - attr: An attribute of the Feature class + - value: The value to set that attribute to + + Set the passed attribute of all features in the set to the + passed value. + """ + for feature in self.features.values(): + if hasattr(feature, attr): + # If the feature has the attribute, set it to the passed value + setattr(feature, attr, value) + + # For backwards compatibility, we support both colour and color. + # As a quick hack, make "colour" set both "colour" and "color". + # if attr=="colour": + # self.set_all_feature("color",value) + + def get_features(self, attribute=None, value=None, comparator=None): + """Retrieve features. + + Arguments: + - attribute: String, attribute of a Feature object + - value: The value desired of the attribute + - comparator: String, how to compare the Feature attribute to the + passed value + + If no attribute or value is given, return a list of all features in the + feature set. If both an attribute and value are given, then depending + on the comparator, then a list of all features in the FeatureSet + matching (or not) the passed value will be returned. Allowed comparators + are: 'startswith', 'not', 'like'. + + The user is expected to make a responsible decision about which feature + attributes to use with which passed values and comparator settings. + """ + # If no attribute or value specified, return all features + if attribute is None or value is None: + return list(self.features.values()) + # If no comparator is specified, return all features where the attribute + # value matches that passed + if comparator is None: + return [ + feature + for feature in self.features.values() + if getattr(feature, attribute) == value + ] + # If the comparator is 'not', return all features where the attribute + # value does not match that passed + elif comparator == "not": + return [ + feature + for feature in self.features.values() + if getattr(feature, attribute) != value + ] + # If the comparator is 'startswith', return all features where the attribute + # value does not match that passed + elif comparator == "startswith": + return [ + feature + for feature in self.features.values() + if getattr(feature, attribute).startswith(value) + ] + # If the comparator is 'like', use a regular expression search to identify + # features + elif comparator == "like": + return [ + feature + for feature in self.features.values() + if re.search(value, getattr(feature, attribute)) + ] + # As a final option, just return an empty list + return [] + + def get_ids(self): + """Return a list of all ids for the feature set.""" + return list(self.features.keys()) + + def range(self): + """Return the lowest and highest base (or mark) numbers as a tuple.""" + lows, highs = [], [] + for feature in self.features.values(): + for start, end in feature.locations: + lows.append(start) + highs.append(end) + if len(lows) != 0 and len(highs) != 0: # Default in case there is + return (min(lows), max(highs)) # nothing in the set + return 0, 0 + + def to_string(self, verbose=0): + """Return a formatted string with information about the set. + + Arguments: + - verbose: Boolean indicating whether a short (default) or + complete account of the set is required + + """ + if not verbose: # Short account only required + return f"{self}" + else: # Long account desired + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d features" % len(self.features)) + for key in self.features: + outstr.append(f"feature: {self.features[key]}") + return "\n".join(outstr) + + def __len__(self): + """Return the number of features in the set.""" + return len(self.features) + + def __getitem__(self, key): + """Return a feature, keyed by id.""" + return self.features[key] + + def __str__(self): + """Return a formatted string with information about the feature set.""" + outstr = [ + "\n<%s: %s %d features>" % (self.__class__, self.name, len(self.features)) + ] + return "\n".join(outstr) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Graph.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Graph.py new file mode 100644 index 0000000000000000000000000000000000000000..bda541613ba6a0cae74667db622f3c5ec5f0ac68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Graph.py @@ -0,0 +1,190 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2009 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Graph module. + +Provides: + - GraphData - Contains data from which a graph will be drawn, and + information about its presentation + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +from math import sqrt + +from reportlab.lib import colors + + +class GraphData: + """Graph Data. + + Attributes: + - id Unique identifier for the data + - data Dictionary of describing the data, keyed by position + - name String describing the data + - style String ('bar', 'heat', 'line') describing how to draw the data + - poscolor colors.Color for drawing high (some styles) or all + values + - negcolor colors.Color for drawing low values (some styles) + - linewidth Int, thickness to draw the line in 'line' styles + + """ + + def __init__( + self, + id=None, + data=None, + name=None, + style="bar", + color=colors.lightgreen, + altcolor=colors.darkseagreen, + center=None, + colour=None, + altcolour=None, + ): + """Initialize. + + Arguments: + - id Unique ID for the graph + - data List of (position, value) tuples + - name String describing the graph + - style String describing the presentation style ('bar', 'line', + 'heat') + - color colors.Color describing the color to draw all or the + 'high' (some styles) values (overridden by backwards + compatible argument with UK spelling, colour). + - altcolor colors.Color describing the color to draw the 'low' + values (some styles only) (overridden by backwards + compatible argument with UK spelling, colour). + - center Value at which x-axis crosses y-axis. + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + if altcolour is not None: + altcolor = altcolour + + self.id = id # Unique identifier for the graph + self.data = {} # holds values, keyed by sequence position + if data is not None: + self.set_data(data) + self.name = name # Descriptive string + + # Attributes describing how the graph will be drawn + self.style = style # One of 'bar', 'heat' or 'line' + self.poscolor = color # Color to draw all, or 'high' values + self.negcolor = altcolor # Color to draw 'low' values + self.linewidth = 2 # linewidth to use in line graphs + self.center = center # value at which x-axis crosses y-axis + + def set_data(self, data): + """Add data as a list of (position, value) tuples.""" + for pos, val in data: # Fill data dictionary + self.data[pos] = val + + def get_data(self): + """Return data as a list of sorted (position, value) tuples.""" + data = [] + for xval in self.data: + yval = self.data[xval] + data.append((xval, yval)) + data.sort() + return data + + def add_point(self, point): + """Add a single point to the set of data as a (position, value) tuple.""" + pos, val = point + self.data[pos] = val + + def quartiles(self): + """Return (minimum, lowerQ, medianQ, upperQ, maximum) values as tuple.""" + data = sorted(self.data.values()) + datalen = len(data) + return ( + data[0], + data[datalen // 4], + data[datalen // 2], + data[3 * datalen // 4], + data[-1], + ) + + def range(self): + """Return range of data as (start, end) tuple. + + Returns the range of the data, i.e. its start and end points on + the genome as a (start, end) tuple. + """ + positions = sorted(self.data) # i.e. dict keys + # Return first and last positions in graph + # print(len(self.data)) + return (positions[0], positions[-1]) + + def mean(self): + """Return the mean value for the data points (float).""" + data = list(self.data.values()) + return sum(data) / len(data) + + def stdev(self): + """Return the sample standard deviation for the data (float).""" + data = list(self.data.values()) + m = self.mean() + runtotal = 0.0 + for entry in data: + runtotal += (entry - m) ** 2 + # This is sample standard deviation; population stdev would involve + # division by len(data), rather than len(data)-1 + return sqrt(runtotal / (len(data) - 1)) + + def __len__(self): + """Return the number of points in the data set.""" + return len(self.data) + + def __getitem__(self, index): + """Return data value(s) at the given position. + + Given an integer representing position on the sequence + returns a float - the data value at the passed position. + + If a slice, returns graph data from the region as a list or + (position, value) tuples. Slices with step are not supported. + """ + if isinstance(index, int): + return self.data[index] + elif isinstance(index, slice): + # TODO - Why does it treat the end points both as inclusive? + # This doesn't match Python norms does it? + low = index.start + high = index.stop + if index.step is not None and index.step != 1: + raise ValueError + outlist = [] + for pos in sorted(self.data): + if pos >= low and pos <= high: + outlist.append((pos, self.data[pos])) + return outlist + else: + raise TypeError("Need an integer or a slice") + + def __str__(self): + """Return a string describing the graph data.""" + outstr = [f"\nGraphData: {self.name}, ID: {self.id}"] + outstr.append("Number of points: %d" % len(self.data)) + outstr.append(f"Mean data value: {self.mean()}") + outstr.append(f"Sample SD: {self.stdev():.3f}") + outstr.append( + "Minimum: %s\n1Q: %s\n2Q: %s\n3Q: %s\nMaximum: %s" % self.quartiles() + ) + outstr.append("Sequence Range: %s..%s" % self.range()) + return "\n".join(outstr) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_GraphSet.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_GraphSet.py new file mode 100644 index 0000000000000000000000000000000000000000..aeafee2931fa4fa4df9fe6dd0f78fef2b2a9db49 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_GraphSet.py @@ -0,0 +1,171 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2010 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ +# +# TODO: Make representation of Ymax and Ymin values at this level, so that +# calculation of graph/axis drawing is simplified + +"""GraphSet module. + +Provides: + - GraphSet - container for GraphData objects + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +# ReportLab imports + +from reportlab.lib import colors + +from ._Graph import GraphData + + +class GraphSet: + """Graph Set. + + Attributes: + - id Unique identifier for the set + - name String describing the set + + """ + + def __init__(self, name=None): + """Initialize. + + Arguments: + - name String identifying the graph set sensibly + + """ + self.id = id # Unique identifier for the set + self._next_id = 0 # Holds unique ids for graphs + self._graphs = {} # Holds graphs, keyed by unique id + self.name = name # Holds description of graph + + def new_graph( + self, + data, + name=None, + style="bar", + color=colors.lightgreen, + altcolor=colors.darkseagreen, + linewidth=1, + center=None, + colour=None, + altcolour=None, + centre=None, + ): + """Add a GraphData object to the diagram. + + Arguments: + - data List of (position, value) int tuples + - name String, description of the graph + - style String ('bar', 'heat', 'line') describing how the graph + will be drawn + - color colors.Color describing the color to draw all or 'high' + (some styles) data (overridden by backwards compatible + argument with UK spelling, colour). + - altcolor colors.Color describing the color to draw 'low' (some + styles) data (overridden by backwards compatible argument + with UK spelling, colour). + - linewidth Float describing linewidth for graph + - center Float setting the value at which the x-axis + crosses the y-axis (overridden by backwards + compatible argument with UK spelling, centre) + + Add a GraphData object to the diagram (will be stored internally). + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + if altcolour is not None: + altcolor = altcolour + if centre is not None: + center = centre + + id = self._next_id # get id number + graph = GraphData(id, data, name, style, color, altcolor, center) + graph.linewidth = linewidth + self._graphs[id] = graph # add graph data + self._next_id += 1 # increment next id + return graph + + def del_graph(self, graph_id): + """Remove a graph from the set, indicated by its id.""" + del self._graphs[graph_id] + + def get_graphs(self): + """Return list of all graphs in the graph set, sorted by id. + + Sorting is to ensure reliable stacking. + """ + return [self._graphs[id] for id in sorted(self._graphs)] + + def get_ids(self): + """Return a list of all ids for the graph set.""" + return list(self._graphs.keys()) + + def range(self): + """Return the lowest and highest base (or mark) numbers as a tuple.""" + lows, highs = [], [] + for graph in self._graphs.values(): + low, high = graph.range() + lows.append(low) + highs.append(high) + return (min(lows), max(highs)) + + def data_quartiles(self): + """Return (minimum, lowerQ, medianQ, upperQ, maximum) values as a tuple.""" + data = [] + for graph in self._graphs.values(): + data += list(graph.data.values()) + data.sort() + datalen = len(data) + return ( + data[0], + data[datalen / 4], + data[datalen / 2], + data[3 * datalen / 4], + data[-1], + ) + + def to_string(self, verbose=0): + """Return a formatted string with information about the set. + + Arguments: + - verbose - Flag indicating whether a short or complete account + of the set is required + + """ + if not verbose: + return f"{self}" + else: + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d graphs" % len(self._graphs)) + for key in self._graphs: + outstr.append(f"{self._graphs[key]}") + return "\n".join(outstr) + + def __len__(self): + """Return the number of graphs in the set.""" + return len(self._graphs) + + def __getitem__(self, key): + """Return a graph, keyed by id.""" + return self._graphs[key] + + def __str__(self): + """Return a formatted string with information about the feature set.""" + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d graphs" % len(self._graphs)) + outstr = "\n".join(outstr) + return outstr diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_LinearDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_LinearDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..39da87964e429b1c7ed631a6006b3e2e7ff6fbf8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_LinearDrawer.py @@ -0,0 +1,1584 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2009 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Linear Drawer module. + +Provides: + - LinearDrawer - Drawing object for linear diagrams + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +from math import ceil + +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import Group +from reportlab.graphics.shapes import Line +from reportlab.graphics.shapes import Polygon +from reportlab.graphics.shapes import String +from reportlab.lib import colors + +from ._AbstractDrawer import _stroke_and_fill_colors +from ._AbstractDrawer import AbstractDrawer +from ._AbstractDrawer import angle2trig +from ._AbstractDrawer import deduplicate +from ._AbstractDrawer import draw_arrow +from ._AbstractDrawer import draw_box +from ._AbstractDrawer import draw_cut_corner_box +from ._AbstractDrawer import intermediate_points +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet + + +class LinearDrawer(AbstractDrawer): + """Linear Drawer. + + Inherits from: + - AbstractDrawer + + Attributes: + - tracklines Boolean for whether to draw lines delineating tracks + - pagesize Tuple describing the size of the page in pixels + - x0 Float X co-ord for leftmost point of drawable area + - xlim Float X co-ord for rightmost point of drawable area + - y0 Float Y co-ord for lowest point of drawable area + - ylim Float Y co-ord for topmost point of drawable area + - pagewidth Float pixel width of drawable area + - pageheight Float pixel height of drawable area + - xcenter Float X co-ord of center of drawable area + - ycenter Float Y co-ord of center of drawable area + - start Int, base to start drawing from + - end Int, base to stop drawing at + - length Int, size of sequence to be drawn + - fragments Int, number of fragments into which to divide the + drawn sequence + - fragment_size Float (0->1) the proportion of the fragment height to + draw in + - track_size Float (0->1) the proportion of the track height to + draw in + - drawing Drawing canvas + - drawn_tracks List of ints denoting which tracks are to be drawn + - current_track_level Int denoting which track is currently being + drawn + - fragment_height Float total fragment height in pixels + - fragment_bases Int total fragment length in bases + - fragment_lines Dictionary of top and bottom y-coords of fragment, + keyed by fragment number + - fragment_limits Dictionary of start and end bases of each fragment, + keyed by fragment number + - track_offsets Dictionary of number of pixels that each track top, + center and bottom is offset from the base of a fragment, keyed by track + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + + def __init__( + self, + parent=None, + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=0, + fragments=10, + fragment_size=None, + track_size=0.75, + cross_track_links=None, + ): + """Initialize. + + Arguments: + - parent Diagram object containing the data that the drawer draws + - pagesize String describing the ISO size of the image, or a tuple + of pixels + - orientation String describing the required orientation of the + final drawing ('landscape' or 'portrait') + - x Float (0->1) describing the relative size of the X + margins to the page + - y Float (0->1) describing the relative size of the Y + margins to the page + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xr Float (0->1) describing the relative size of the right X + margin to the page (overrides x) + - yt Float (0->1) describing the relative size of the top Y + margin to the page (overrides y) + - yb Float (0->1) describing the relative size of the lower Y + margin to the page (overrides y) + - start Int, the position to begin drawing the diagram at + - end Int, the position to stop drawing the diagram at + - tracklines Boolean flag to show (or not) lines delineating tracks + on the diagram + - fragments Int, the number of equal fragments into which the + sequence should be divided for drawing + - fragment_size Float(0->1) The proportion of the available height + for the fragment that should be taken up in drawing + - track_size The proportion of the available track height that + should be taken up in drawing + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + """ + # Use the superclass' instantiation method + AbstractDrawer.__init__( + self, + parent, + pagesize, + orientation, + x, + y, + xl, + xr, + yt, + yb, + start, + end, + tracklines, + cross_track_links, + ) + + # Useful measurements on the page + self.fragments = fragments + if fragment_size is not None: + self.fragment_size = fragment_size + else: + if self.fragments == 1: + # For single fragments, default to full height + self.fragment_size = 1 + else: + # Otherwise keep a 10% gap between fragments + self.fragment_size = 0.9 + self.track_size = track_size + + def draw(self): + """Draw a linear diagram of the data in the parent Diagram object.""" + # Instantiate the drawing canvas + self.drawing = Drawing(self.pagesize[0], self.pagesize[1]) + + feature_elements = [] # holds feature elements + feature_labels = [] # holds feature labels + greytrack_bgs = [] # holds track background + greytrack_labels = [] # holds track foreground labels + scale_axes = [] # holds scale axes + scale_labels = [] # holds scale axis labels + + # Get the tracks to be drawn + self.drawn_tracks = self._parent.get_drawn_levels() + + # Set fragment and track sizes + self.init_fragments() + self.set_track_heights() + + # Go through each track in the parent (if it is to be drawn) one by + # one and collate the data as drawing elements + for track_level in self.drawn_tracks: # only use tracks to be drawn + self.current_track_level = track_level # establish track level + track = self._parent[track_level] # get the track at that level + gbgs, glabels = self.draw_greytrack(track) # get greytrack elements + greytrack_bgs.append(gbgs) + greytrack_labels.append(glabels) + features, flabels = self.draw_track(track) # get feature and graph elements + feature_elements.append(features) + feature_labels.append(flabels) + if track.scale: + axes, slabels = self.draw_scale(track) # get scale elements + scale_axes.append(axes) + scale_labels.append(slabels) + + feature_cross_links = [] + for cross_link_obj in self.cross_track_links: + cross_link_elements = self.draw_cross_link(cross_link_obj) + if cross_link_elements: + feature_cross_links.append(cross_link_elements) + + # Groups listed in order of addition to page (from back to front) + # Draw track backgrounds + # Draw feature cross track links + # Draw features and graphs + # Draw scale axes + # Draw scale labels + # Draw feature labels + # Draw track labels + element_groups = [ + greytrack_bgs, + feature_cross_links, + feature_elements, + scale_axes, + scale_labels, + feature_labels, + greytrack_labels, + ] + for element_group in element_groups: + for element_list in element_group: + [self.drawing.add(element) for element in element_list] + + if self.tracklines: # Draw test tracks over top of diagram + self.draw_test_tracks() + + def init_fragments(self): + """Initialize useful values for positioning diagram elements.""" + # Set basic heights, lengths etc + self.fragment_height = self.pageheight / self.fragments + # total fragment height in pixels + self.fragment_bases = ceil(self.length / self.fragments) + # fragment length in bases + + # Key fragment base and top lines by fragment number + # Holds bottom and top line locations of fragments, keyed by fragment number + self.fragment_lines = {} + # Number of pixels to crop the fragment: + fragment_crop = (1 - self.fragment_size) / 2 + fragy = self.ylim # Holder for current absolute fragment base + for fragment in range(self.fragments): + fragtop = fragy - fragment_crop * self.fragment_height # top - crop + fragbtm = ( + fragy - (1 - fragment_crop) * self.fragment_height + ) # bottom + crop + self.fragment_lines[fragment] = (fragbtm, fragtop) + fragy -= self.fragment_height # next fragment base + + # Key base starts and ends for each fragment by fragment number + self.fragment_limits = {} # Holds first and last base positions in a fragment + fragment_step = self.fragment_bases # bases per fragment + fragment_count = 0 + # Add start and end positions for each fragment to dictionary + for marker in range(int(self.start), int(self.end), int(fragment_step)): + self.fragment_limits[fragment_count] = (marker, marker + fragment_step) + fragment_count += 1 + + def set_track_heights(self): + """Set track heights. + + Since tracks may not be of identical heights, the bottom and top + offsets of each track relative to the fragment top and bottom is + stored in a dictionary - self.track_offsets, keyed by track number. + """ + bot_track = min(min(self.drawn_tracks), 1) + top_track = max(self.drawn_tracks) # The 'highest' track number to draw + + trackunit_sum = 0 # Total number of 'units' for the tracks + trackunits = {} # The start and end units for each track, keyed by track number + heightholder = 0 # placeholder variable + for track in range(bot_track, top_track + 1): # for all track numbers to 'draw' + try: + trackheight = self._parent[track].height # Get track height + except Exception: # TODO: IndexError? + trackheight = 1 # ...or default to 1 + trackunit_sum += trackheight # increment total track unit height + trackunits[track] = (heightholder, heightholder + trackheight) + heightholder += trackheight # move to next height + trackunit_height = self.fragment_height * self.fragment_size / trackunit_sum + + # Calculate top and bottom offsets for each track, relative to fragment + # base + track_offsets = {} # The offsets from fragment base for each track + track_crop = ( + trackunit_height * (1 - self.track_size) / 2.0 + ) # 'step back' in pixels + assert track_crop >= 0 + for track in trackunits: + top = trackunits[track][1] * trackunit_height - track_crop # top offset + btm = trackunits[track][0] * trackunit_height + track_crop # bottom offset + ctr = btm + (top - btm) / 2.0 # center offset + track_offsets[track] = (btm, ctr, top) + self.track_offsets = track_offsets + + def draw_test_tracks(self): + """Draw test tracks. + + Draw red lines indicating the top and bottom of each fragment, + and blue ones indicating tracks to be drawn. + """ + # Add lines for each fragment + for fbtm, ftop in self.fragment_lines.values(): + self.drawing.add( + Line(self.x0, ftop, self.xlim, ftop, strokeColor=colors.red) + ) # top line + self.drawing.add( + Line(self.x0, fbtm, self.xlim, fbtm, strokeColor=colors.red) + ) # bottom line + + # Add track lines for this fragment - but only for drawn tracks + for track in self.drawn_tracks: + trackbtm = fbtm + self.track_offsets[track][0] + trackctr = fbtm + self.track_offsets[track][1] + tracktop = fbtm + self.track_offsets[track][2] + self.drawing.add( + Line( + self.x0, tracktop, self.xlim, tracktop, strokeColor=colors.blue + ) + ) # top line + self.drawing.add( + Line( + self.x0, trackctr, self.xlim, trackctr, strokeColor=colors.green + ) + ) # center line + self.drawing.add( + Line( + self.x0, trackbtm, self.xlim, trackbtm, strokeColor=colors.blue + ) + ) # bottom line + + def draw_track(self, track): + """Draw track. + + Arguments: + - track Track object + + Returns a tuple (list of elements in the track, list of labels in + the track). + """ + track_elements = [] # Holds elements from features and graphs + track_labels = [] # Holds labels from features and graphs + + # Distribution dictionary for dealing with different set types + set_methods = {FeatureSet: self.draw_feature_set, GraphSet: self.draw_graph_set} + + for set in track.get_sets(): # Draw the feature or graph sets + elements, labels = set_methods[set.__class__](set) + track_elements += elements + track_labels += labels + return track_elements, track_labels + + def draw_tick(self, tickpos, ctr, ticklen, track, draw_label): + """Draw tick. + + Arguments: + - tickpos Int, position of the tick on the sequence + - ctr Float, Y co-ord of the center of the track + - ticklen How long to draw the tick + - track Track, the track the tick is drawn on + - draw_label Boolean, write the tick label? + + Returns a drawing element that is the tick on the scale + """ + if self.start >= tickpos and tickpos >= self.end: + raise RuntimeError( + "Tick at %i, but showing %i to %i" % (tickpos, self.start, self.end) + ) + if not ( + (track.start is None or track.start <= tickpos) + and (track.end is None or tickpos <= track.end) + ): + raise RuntimeError( + "Tick at %i, but showing %r to %r for track" + % (tickpos, track.start, track.end) + ) + fragment, tickx = self.canvas_location(tickpos) # Tick coordinates + assert fragment >= 0, "Fragment %i, tickpos %i" % (fragment, tickpos) + tctr = ctr + self.fragment_lines[fragment][0] # Center line of the track + tickx += self.x0 # Tick X co-ord + ticktop = tctr + ticklen # Y co-ord of tick top + tick = Line(tickx, tctr, tickx, ticktop, strokeColor=track.scale_color) + if draw_label: # Put tick position on as label + if track.scale_format == "SInt": + if tickpos >= 1000000: + tickstring = str(tickpos // 1000000) + " Mbp" + elif tickpos >= 1000: + tickstring = str(tickpos // 1000) + " Kbp" + else: + tickstring = str(tickpos) + else: + tickstring = str(tickpos) + label = String( + 0, + 0, + tickstring, # Make label string + fontName=track.scale_font, + fontSize=track.scale_fontsize, + fillColor=track.scale_color, + ) + labelgroup = Group(label) + rotation = angle2trig(track.scale_fontangle) + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + tickx, + ticktop, + ) + else: + labelgroup = None + return tick, labelgroup + + def draw_scale(self, track): + """Draw scale. + + Argument: + - track Track object + + Returns a tuple of (list of elements in the scale, list of labels + in the scale). + """ + scale_elements = [] # Holds axes and ticks + scale_labels = [] # Holds labels + + if not track.scale: # No scale required, exit early + return [], [] + + # Get track location + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = top - ctr + + # For each fragment, draw the scale for this track + start, end = self._current_track_start_end() + start_f, start_x = self.canvas_location(start) + end_f, end_x = self.canvas_location(end) + + for fragment in range(start_f, end_f + 1): + tbtm = btm + self.fragment_lines[fragment][0] + tctr = ctr + self.fragment_lines[fragment][0] + ttop = top + self.fragment_lines[fragment][0] + # X-axis + if fragment == start_f: + x_left = start_x + else: + x_left = 0 + if fragment == end_f: + x_right = end_x + # Y-axis end marker + scale_elements.append( + Line( + self.x0 + x_right, + tbtm, + self.x0 + x_right, + ttop, + strokeColor=track.scale_color, + ) + ) + else: + x_right = self.xlim - self.x0 + scale_elements.append( + Line( + self.x0 + x_left, + tctr, + self.x0 + x_right, + tctr, + strokeColor=track.scale_color, + ) + ) + # Y-axis start marker + scale_elements.append( + Line( + self.x0 + x_left, + tbtm, + self.x0 + x_left, + ttop, + strokeColor=track.scale_color, + ) + ) + + start, end = self._current_track_start_end() + if track.scale_ticks: # Ticks are required on the scale + # Draw large ticks + # I want the ticks to be consistently positioned relative to + # the start of the sequence (position 0), not relative to the + # current viewpoint (self.start and self.end) + + ticklen = track.scale_largeticks * trackheight + tickiterval = int(track.scale_largetick_interval) + # Note that we could just start the list of ticks using + # range(0,self.end,tickinterval) and the filter out the + # ones before self.start - but this seems wasteful. + # Using tickiterval * (self.start//tickiterval) is a shortcut. + for tickpos in range( + tickiterval * (self.start // tickiterval), int(self.end), tickiterval + ): + if tickpos <= start or end <= tickpos: + continue + tick, label = self.draw_tick( + tickpos, ctr, ticklen, track, track.scale_largetick_labels + ) + scale_elements.append(tick) + if label is not None: # If there's a label, add it + scale_labels.append(label) + # Draw small ticks + ticklen = track.scale_smallticks * trackheight + tickiterval = int(track.scale_smalltick_interval) + for tickpos in range( + tickiterval * (self.start // tickiterval), int(self.end), tickiterval + ): + if tickpos <= start or end <= tickpos: + continue + tick, label = self.draw_tick( + tickpos, ctr, ticklen, track, track.scale_smalltick_labels + ) + scale_elements.append(tick) + if label is not None: # If there's a label, add it + scale_labels.append(label) + + # Check to see if the track contains a graph - if it does, get the + # minimum and maximum values, and put them on the scale Y-axis + if track.axis_labels: + for set in track.get_sets(): # Check all sets... + if set.__class__ is GraphSet: # ...for a graph set + graph_label_min = [] + graph_label_mid = [] + graph_label_max = [] + for graph in set.get_graphs(): + quartiles = graph.quartiles() + minval, maxval = quartiles[0], quartiles[4] + if graph.center is None: + midval = (maxval + minval) / 2.0 + graph_label_min.append(f"{minval:.3f}") + graph_label_max.append(f"{maxval:.3f}") + else: + diff = max((graph.center - minval), (maxval - graph.center)) + minval = graph.center - diff + maxval = graph.center + diff + midval = graph.center + graph_label_mid.append(f"{midval:.3f}") + graph_label_min.append(f"{minval:.3f}") + graph_label_max.append(f"{maxval:.3f}") + for fragment in range( + start_f, end_f + 1 + ): # Add to all used fragment axes + tbtm = btm + self.fragment_lines[fragment][0] + tctr = ctr + self.fragment_lines[fragment][0] + ttop = top + self.fragment_lines[fragment][0] + if fragment == start_f: + x_left = start_x + else: + x_left = 0 + for val, pos in [ + (";".join(graph_label_min), tbtm), + (";".join(graph_label_max), ttop), + (";".join(graph_label_mid), tctr), + ]: + label = String( + 0, + 0, + val, + fontName=track.scale_font, + fontSize=track.scale_fontsize, + fillColor=track.scale_color, + ) + labelgroup = Group(label) + rotation = angle2trig(track.scale_fontangle) + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + self.x0 + x_left, + pos, + ) + scale_labels.append(labelgroup) + + return scale_elements, scale_labels + + def draw_greytrack(self, track): + """Draw greytrack. + + Arguments: + - track Track object + + Put in a grey background to the current track in all fragments, + if track specifies that we should. + """ + greytrack_bgs = [] # Holds grey track backgrounds + greytrack_labels = [] # Holds grey foreground labels + + if not track.greytrack: # No greytrack required, return early + return [], [] + + # Get track location + btm, ctr, top = self.track_offsets[self.current_track_level] + + start, end = self._current_track_start_end() + start_fragment, start_offset = self.canvas_location(start) + end_fragment, end_offset = self.canvas_location(end) + + # Add greytrack to all fragments for this track + for fragment in range(start_fragment, end_fragment + 1): + tbtm = btm + self.fragment_lines[fragment][0] + tctr = ctr + self.fragment_lines[fragment][0] + ttop = top + self.fragment_lines[fragment][0] + if fragment == start_fragment: + x1 = self.x0 + start_offset + else: + x1 = self.x0 + if fragment == end_fragment: + x2 = self.x0 + end_offset + else: + x2 = self.xlim + box = draw_box( + (x1, tbtm), + (x2, ttop), + colors.Color(0.96, 0.96, 0.96), # Grey track bg + ) # is just a box + greytrack_bgs.append(box) + + if track.greytrack_labels: # If labels are required + # # how far apart should they be? + labelstep = self.pagewidth / track.greytrack_labels + label = String( + 0, + 0, + track.name, # label contents + fontName=track.greytrack_font, + fontSize=track.greytrack_fontsize, + fillColor=track.greytrack_fontcolor, + ) + # Create a new labelgroup at each position the label is required + for x in range(int(self.x0), int(self.xlim), int(labelstep)): + if fragment == start_fragment and x < start_offset: + continue + if ( + fragment == end_fragment + and end_offset < x + label.getBounds()[2] + ): + continue + labelgroup = Group(label) + rotation = angle2trig(track.greytrack_font_rotation) + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + x, + tbtm, + ) + if not self.xlim - x <= labelstep: + # Don't overlap the end of the track + greytrack_labels.append(labelgroup) + + return greytrack_bgs, greytrack_labels + + def draw_feature_set(self, set): + """Draw feature set. + + Arguments: + - set FeatureSet object + + Returns a tuple (list of elements describing features, list of + labels for elements). + """ + # print("draw feature set") + feature_elements = [] # Holds diagram elements belonging to the features + label_elements = [] # Holds diagram elements belonging to feature labels + + # Collect all the elements for the feature set + for feature in set.get_features(): + if self.is_in_bounds(feature.start) or self.is_in_bounds(feature.end): + features, labels = self.draw_feature(feature) # get elements and labels + feature_elements += features + label_elements += labels + + return feature_elements, label_elements + + def draw_feature(self, feature): + """Draw feature. + + Arguments: + - feature Feature containing location info + + Returns tuple of (list of elements describing single feature, list + of labels for those elements). + """ + if feature.hide: # Feature hidden, don't draw it... + return [], [] + + feature_elements = [] # Holds diagram elements belonging to the feature + label_elements = [] # Holds labels belonging to the feature + + start, end = self._current_track_start_end() + # A single feature may be split into subfeatures, so loop over them + for locstart, locend in feature.locations: + if locend < start: + continue + locstart = max(locstart, start) + if end < locstart: + continue + locend = min(locend, end) + feature_boxes = self.draw_feature_location(feature, locstart, locend) + for box, label in feature_boxes: + feature_elements.append(box) + if label is not None: + label_elements.append(label) + + return feature_elements, label_elements + + def draw_feature_location(self, feature, locstart, locend): + """Draw feature location.""" + feature_boxes = [] + # Get start and end positions for feature/subfeatures + start_fragment, start_offset = self.canvas_location(locstart) + end_fragment, end_offset = self.canvas_location(locend) + # print("start_fragment, start_offset", start_fragment, start_offset) + # print("end_fragment, end_offset", end_fragment, end_offset) + # print("start, end", locstart, locend) + + # Note that there is a strange situation where a feature may be in + # several parts, and one or more of those parts may end up being + # drawn on a non-existent fragment. So we check that the start and + # end fragments do actually exist in terms of the drawing + allowed_fragments = list(self.fragment_limits.keys()) + if start_fragment in allowed_fragments and end_fragment in allowed_fragments: + # print(feature.name, feature.start, feature.end, start_offset, end_offset) + if start_fragment == end_fragment: # Feature is found on one fragment + feature_box, label = self.get_feature_sigil( + feature, start_offset, end_offset, start_fragment + ) + feature_boxes.append((feature_box, label)) + # feature_elements.append(feature_box) + # if label is not None: # There is a label for the feature + # label_elements.append(label) + else: # Feature is split over two or more fragments + fragment = start_fragment + start = start_offset + # The bit that runs up to the end of the first fragment, + # and any bits that subsequently span whole fragments + while self.fragment_limits[fragment][1] < locend: + # print(fragment, self.fragment_limits[fragment][1], locend) + feature_box, label = self.get_feature_sigil( + feature, start, self.pagewidth, fragment + ) + + fragment += 1 # move to next fragment + start = 0 # start next sigil from start of fragment + feature_boxes.append((feature_box, label)) + # feature_elements.append(feature_box) + # if label is not None: # There's a label for the feature + # label_elements.append(label) + # The last bit of the feature + # print(locend, self.end, fragment) + # print(self.fragment_bases, self.length) + feature_box, label = self.get_feature_sigil( + feature, 0, end_offset, fragment + ) + feature_boxes.append((feature_box, label)) + # if locstart > locend: + # print(locstart, locend, feature.location.strand, feature_boxes, feature.name) + return feature_boxes + + def draw_cross_link(self, cross_link): + """Draw cross-link between two features.""" + startA = cross_link.startA + startB = cross_link.startB + endA = cross_link.endA + endB = cross_link.endB + + if not self.is_in_bounds(startA) and not self.is_in_bounds(endA): + return None + if not self.is_in_bounds(startB) and not self.is_in_bounds(endB): + return None + + if startA < self.start: + startA = self.start + if startB < self.start: + startB = self.start + if self.end < endA: + endA = self.end + if self.end < endB: + endB = self.end + + trackobjA = cross_link._trackA(list(self._parent.tracks.values())) + trackobjB = cross_link._trackB(list(self._parent.tracks.values())) + assert trackobjA is not None + assert trackobjB is not None + if trackobjA == trackobjB: + raise NotImplementedError + + if trackobjA.start is not None: + if endA < trackobjA.start: + return + startA = max(startA, trackobjA.start) + if trackobjA.end is not None: + if trackobjA.end < startA: + return + endA = min(endA, trackobjA.end) + if trackobjB.start is not None: + if endB < trackobjB.start: + return + startB = max(startB, trackobjB.start) + if trackobjB.end is not None: + if trackobjB.end < startB: + return + endB = min(endB, trackobjB.end) + + for track_level in self._parent.get_drawn_levels(): + track = self._parent[track_level] + if track == trackobjA: + trackA = track_level + if track == trackobjB: + trackB = track_level + if trackA == trackB: + raise NotImplementedError + + strokecolor, fillcolor = _stroke_and_fill_colors( + cross_link.color, cross_link.border + ) + + allowed_fragments = list(self.fragment_limits.keys()) + + start_fragmentA, start_offsetA = self.canvas_location(startA) + end_fragmentA, end_offsetA = self.canvas_location(endA) + if ( + start_fragmentA not in allowed_fragments + or end_fragmentA not in allowed_fragments + ): + return + + start_fragmentB, start_offsetB = self.canvas_location(startB) + end_fragmentB, end_offsetB = self.canvas_location(endB) + if ( + start_fragmentB not in allowed_fragments + or end_fragmentB not in allowed_fragments + ): + return + + # TODO - Better drawing of flips when split between fragments + + answer = [] + for fragment in range( + min(start_fragmentA, start_fragmentB), max(end_fragmentA, end_fragmentB) + 1 + ): + btmA, ctrA, topA = self.track_offsets[trackA] + btmA += self.fragment_lines[fragment][0] + ctrA += self.fragment_lines[fragment][0] + topA += self.fragment_lines[fragment][0] + + btmB, ctrB, topB = self.track_offsets[trackB] + btmB += self.fragment_lines[fragment][0] + ctrB += self.fragment_lines[fragment][0] + topB += self.fragment_lines[fragment][0] + + if self.fragment_limits[fragment][1] < endA: + xAe = self.x0 + self.pagewidth + crop_rightA = True + else: + xAe = self.x0 + end_offsetA + crop_rightA = False + if self.fragment_limits[fragment][1] < endB: + xBe = self.x0 + self.pagewidth + crop_rightB = True + else: + xBe = self.x0 + end_offsetB + crop_rightB = False + + if fragment < start_fragmentA: + xAs = self.x0 + self.pagewidth + xAe = xAs + crop_leftA = False + elif fragment == start_fragmentA: + xAs = self.x0 + start_offsetA + crop_leftA = False + else: + xAs = self.x0 + crop_leftA = True + + if fragment < start_fragmentB: + xBs = self.x0 + self.pagewidth + xBe = xBs + crop_leftB = False + elif fragment == start_fragmentB: + xBs = self.x0 + start_offsetB + crop_leftB = False + else: + xBs = self.x0 + crop_leftB = True + + if ctrA < ctrB: + yA = topA + yB = btmB + else: + yA = btmA + yB = topB + + if fragment < start_fragmentB or end_fragmentB < fragment: + if cross_link.flip: + # Just draw A as a triangle to left/right + if fragment < start_fragmentB: + extra = [self.x0 + self.pagewidth, 0.5 * (yA + yB)] + else: + extra = [self.x0, 0.5 * (yA + yB)] + else: + if fragment < start_fragmentB: + extra = [ + self.x0 + self.pagewidth, + 0.7 * yA + 0.3 * yB, + self.x0 + self.pagewidth, + 0.3 * yA + 0.7 * yB, + ] + else: + extra = [ + self.x0, + 0.3 * yA + 0.7 * yB, + self.x0, + 0.7 * yA + 0.3 * yB, + ] + answer.append( + Polygon( + deduplicate([xAs, yA, xAe, yA] + extra), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif fragment < start_fragmentA or end_fragmentA < fragment: + if cross_link.flip: + # Just draw B as a triangle to left + if fragment < start_fragmentA: + extra = [self.x0 + self.pagewidth, 0.5 * (yA + yB)] + else: + extra = [self.x0, 0.5 * (yA + yB)] + else: + if fragment < start_fragmentA: + extra = [ + self.x0 + self.pagewidth, + 0.3 * yA + 0.7 * yB, + self.x0 + self.pagewidth, + 0.7 * yA + 0.3 * yB, + ] + else: + extra = [ + self.x0, + 0.7 * yA + 0.3 * yB, + self.x0, + 0.3 * yA + 0.7 * yB, + ] + answer.append( + Polygon( + deduplicate([xBs, yB, xBe, yB] + extra), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif cross_link.flip and ( + (crop_leftA and not crop_rightA) or (crop_leftB and not crop_rightB) + ): + # On left end of fragment... force "crossing" to margin + answer.append( + Polygon( + deduplicate( + [ + xAs, + yA, + xAe, + yA, + self.x0, + 0.5 * (yA + yB), + xBe, + yB, + xBs, + yB, + ] + ), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif cross_link.flip and ( + (crop_rightA and not crop_leftA) or (crop_rightB and not crop_leftB) + ): + # On right end... force "crossing" to margin + answer.append( + Polygon( + deduplicate( + [ + xAs, + yA, + xAe, + yA, + xBe, + yB, + xBs, + yB, + self.x0 + self.pagewidth, + 0.5 * (yA + yB), + ] + ), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif cross_link.flip: + answer.append( + Polygon( + deduplicate([xAs, yA, xAe, yA, xBs, yB, xBe, yB]), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + else: + answer.append( + Polygon( + deduplicate([xAs, yA, xAe, yA, xBe, yB, xBs, yB]), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + return answer + + def get_feature_sigil(self, feature, x0, x1, fragment, **kwargs): + """Get feature sigil. + + Arguments: + - feature Feature object + - x0 Start X coordinate on diagram + - x1 End X coordinate on diagram + - fragment The fragment on which the feature appears + + Returns a drawable indicator of the feature, and any required label + for it. + """ + # Establish coordinates for drawing + x0, x1 = self.x0 + x0, self.x0 + x1 + btm, ctr, top = self.track_offsets[self.current_track_level] + try: + btm += self.fragment_lines[fragment][0] + ctr += self.fragment_lines[fragment][0] + top += self.fragment_lines[fragment][0] + except Exception: # Only called if the method screws up big time + print("We've got a screw-up") + print(f"{self.start} {self.end}") + print(self.fragment_bases) + print(f"{x0!r} {x1!r}") + for locstart, locend in feature.locations: + print(self.canvas_location(locstart)) + print(self.canvas_location(locend)) + print(f"FEATURE\n{feature}") + raise + + # Distribution dictionary for various ways of drawing the feature + draw_methods = { + "BOX": self._draw_sigil_box, + "ARROW": self._draw_sigil_arrow, + "BIGARROW": self._draw_sigil_big_arrow, + "OCTO": self._draw_sigil_octo, + "JAGGY": self._draw_sigil_jaggy, + } + + method = draw_methods[feature.sigil] + kwargs["head_length_ratio"] = feature.arrowhead_length + kwargs["shaft_height_ratio"] = feature.arrowshaft_height + + # Support for clickable links... needs ReportLab 2.4 or later + # which added support for links in SVG output. + if hasattr(feature, "url"): + kwargs["hrefURL"] = feature.url + kwargs["hrefTitle"] = feature.name + + # Get sigil for the feature, give it the bounding box straddling + # the axis (it decides strand specific placement) + sigil = method( + btm, + ctr, + top, + x0, + x1, + strand=feature.location.strand, + color=feature.color, + border=feature.border, + **kwargs, + ) + + if feature.label_strand: + strand = feature.label_strand + else: + strand = feature.location.strand + if feature.label: # Feature requires a label + label = String( + 0, + 0, + feature.name, + fontName=feature.label_font, + fontSize=feature.label_size, + fillColor=feature.label_color, + ) + labelgroup = Group(label) + # Feature is on top, or covers both strands (location affects + # the height and rotation of the label) + if strand != -1: + rotation = angle2trig(feature.label_angle) + if feature.label_position in ("end", "3'", "right"): + pos = x1 + elif feature.label_position in ("middle", "center", "centre"): + pos = (x1 + x0) / 2.0 + else: + # Default to start, i.e. 'start', "5'", 'left' + pos = x0 + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + pos, + top, + ) + else: # Feature on bottom strand + rotation = angle2trig(feature.label_angle + 180) + if feature.label_position in ("end", "3'", "right"): + pos = x0 + elif feature.label_position in ("middle", "center", "centre"): + pos = (x1 + x0) / 2.0 + else: + # Default to start, i.e. 'start', "5'", 'left' + pos = x1 + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + pos, + btm, + ) + else: + labelgroup = None + return sigil, labelgroup + + def draw_graph_set(self, set): + """Draw graph set. + + Arguments: + - set GraphSet object + + Returns tuple (list of graph elements, list of graph labels). + """ + # print('draw graph set') + elements = [] # Holds graph elements + + # Distribution dictionary for how to draw the graph + style_methods = { + "line": self.draw_line_graph, + "heat": self.draw_heat_graph, + "bar": self.draw_bar_graph, + } + + for graph in set.get_graphs(): + elements += style_methods[graph.style](graph) + + return elements, [] + + def draw_line_graph(self, graph): + """Return a line graph as a list of drawable elements. + + Arguments: + - graph Graph object + + """ + # print('\tdraw_line_graph') + line_elements = [] # Holds drawable elements + + # Get graph data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = 0.5 * (top - btm) + datarange = maxval - minval + if datarange == 0: + datarange = trackheight + + start, end = self._current_track_start_end() + data = graph[start:end] + + # midval is the value at which the x-axis is plotted, and is the + # central ring in the track + if graph.center is None: + midval = (maxval + minval) / 2.0 + else: + midval = graph.center + # Whichever is the greatest difference: max-midval or min-midval, is + # taken to specify the number of pixel units resolved along the + # y-axis + resolution = max((midval - minval), (maxval - midval)) + + # Start from first data point + pos, val = data[0] + lastfrag, lastx = self.canvas_location(pos) + lastx += self.x0 # Start xy co-ords + lasty = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[lastfrag][0] + + ctr + ) + lastval = val + # Add a series of lines linking consecutive data points + for pos, val in data: + frag, x = self.canvas_location(pos) + x += self.x0 # next xy co-ords + y = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[frag][0] + + ctr + ) + if frag == lastfrag: # Points on the same fragment: draw the line + line_elements.append( + Line( + lastx, + lasty, + x, + y, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + else: # Points not on the same fragment, so interpolate + tempy = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[lastfrag][0] + + ctr + ) + line_elements.append( + Line( + lastx, + lasty, + self.xlim, + tempy, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + tempy = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[frag][0] + + ctr + ) + line_elements.append( + Line( + self.x0, + tempy, + x, + y, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + lastfrag, lastx, lasty, lastval = frag, x, y, val + + return line_elements + + def draw_heat_graph(self, graph): + """Return a list of drawable elements for the heat graph.""" + # print('\tdraw_heat_graph') + # At each point contained in the graph data, we draw a box that is the + # full height of the track, extending from the midpoint between the + # previous and current data points to the midpoint between the current + # and next data points + heat_elements = [] # Holds drawable elements for the graph + + # Get graph data and information + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + midval = (maxval + minval) / 2.0 # mid is the value at the X-axis + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = top - btm + + start, end = self._current_track_start_end() + data = intermediate_points(start, end, graph[start:end]) + + if not data: + return [] + + # Create elements on the graph, indicating a large positive value by + # the graph's poscolor, and a large negative value by the graph's + # negcolor attributes + for pos0, pos1, val in data: + # assert start <= pos0 <= pos1 <= end + fragment0, x0 = self.canvas_location(pos0) + fragment1, x1 = self.canvas_location(pos1) + x0, x1 = self.x0 + x0, self.x0 + x1 # account for margin + # print('x1 before:', x1) + + # Calculate the heat color, based on the differential between + # the value and the median value + heat = colors.linearlyInterpolatedColor( + graph.poscolor, graph.negcolor, maxval, minval, val + ) + + # Draw heat box + if fragment0 == fragment1: # Box is contiguous on one fragment + if pos1 >= self.fragment_limits[fragment0][1]: + x1 = self.xlim + ttop = top + self.fragment_lines[fragment0][0] + tbtm = btm + self.fragment_lines[fragment0][0] + # print('equal', pos0, pos1, val) + # print(pos0, pos1, fragment0, fragment1) + heat_elements.append( + draw_box((x0, tbtm), (x1, ttop), color=heat, border=None) + ) + else: # box is split over two or more fragments + # if pos0 >= self.fragment_limits[fragment0][0]: + # fragment0 += 1 + fragment = fragment0 + start_x = x0 + while self.fragment_limits[fragment][1] <= pos1: + # print(pos0, self.fragment_limits[fragment][1], pos1) + ttop = top + self.fragment_lines[fragment][0] + tbtm = btm + self.fragment_lines[fragment][0] + heat_elements.append( + draw_box( + (start_x, tbtm), (self.xlim, ttop), color=heat, border=None + ) + ) + fragment += 1 + start_x = self.x0 + ttop = top + self.fragment_lines[fragment][0] + tbtm = btm + self.fragment_lines[fragment][0] + # Add the last part of the bar + # print('x1 after:', x1, '\n') + heat_elements.append( + draw_box((self.x0, tbtm), (x1, ttop), color=heat, border=None) + ) + + return heat_elements + + def draw_bar_graph(self, graph): + """Return list of drawable elements for a bar graph.""" + # print('\tdraw_bar_graph') + # At each point contained in the graph data, we draw a vertical bar + # from the track center to the height of the datapoint value (positive + # values go up in one color, negative go down in the alternative + # color). + bar_elements = [] # Holds drawable elements for the graph + + # Set the number of pixels per unit for the data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = 0.5 * (top - btm) + datarange = maxval - minval + if datarange == 0: + datarange = trackheight + data = graph[self.start : self.end] + # midval is the value at which the x-axis is plotted, and is the + # central ring in the track + if graph.center is None: + midval = (maxval + minval) / 2.0 + else: + midval = graph.center + + # Convert data into 'binned' blocks, covering half the distance to the + # next data point on either side, accounting for the ends of fragments + # and tracks + start, end = self._current_track_start_end() + data = intermediate_points(start, end, graph[start:end]) + + if not data: + return [] + + # Whichever is the greatest difference: max-midval or min-midval, is + # taken to specify the number of pixel units resolved along the + # y-axis + resolution = max((midval - minval), (maxval - midval)) + if resolution == 0: + resolution = trackheight + + # Create elements for the bar graph based on newdata + for pos0, pos1, val in data: + fragment0, x0 = self.canvas_location(pos0) + fragment1, x1 = self.canvas_location(pos1) + x0, x1 = self.x0 + x0, self.x0 + x1 # account for margin + barval = trackheight * (val - midval) / resolution + if barval >= 0: # Different colors for bars that extend above... + barcolor = graph.poscolor + else: # ...or below the axis + barcolor = graph.negcolor + + # Draw bar + if fragment0 == fragment1: # Box is contiguous + if pos1 >= self.fragment_limits[fragment0][1]: + x1 = self.xlim + tctr = ctr + self.fragment_lines[fragment0][0] + barval += tctr + bar_elements.append(draw_box((x0, tctr), (x1, barval), color=barcolor)) + else: # Box is split over two or more fragments + fragment = fragment0 + # if pos0 >= self.fragment_limits[fragment0][0]: + # fragment += 1 + start = x0 + while self.fragment_limits[fragment][1] < pos1: + tctr = ctr + self.fragment_lines[fragment][0] + thisbarval = barval + tctr + bar_elements.append( + draw_box((start, tctr), (self.xlim, thisbarval), color=barcolor) + ) + fragment += 1 + start = self.x0 + tctr = ctr + self.fragment_lines[fragment1][0] + barval += tctr + # Add the last part of the bar + bar_elements.append( + draw_box((self.x0, tctr), (x1, barval), color=barcolor) + ) + + return bar_elements + + def canvas_location(self, base): + """Canvas location of a base on the genome. + + Arguments: + - base The base number on the genome sequence + + Returns the x-coordinate and fragment number of a base on the + genome sequence, in the context of the current drawing setup + """ + base = int(base - self.start) # number of bases we are from the start + fragment = int(base / self.fragment_bases) + if fragment < 1: # First fragment + base_offset = base + fragment = 0 + elif fragment >= self.fragments: + fragment = self.fragments - 1 + base_offset = self.fragment_bases + else: # Calculate number of bases from start of fragment + base_offset = base % self.fragment_bases + assert fragment < self.fragments, ( + base, + self.start, + self.end, + self.length, + self.fragment_bases, + ) + # Calculate number of pixels from start of fragment + x_offset = self.pagewidth * base_offset / self.fragment_bases + return fragment, x_offset + + def _draw_sigil_box(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw BOX sigil (PRIVATE).""" + if strand == 1: + y1 = center + y2 = top + elif strand == -1: + y1 = bottom + y2 = center + else: + y1 = bottom + y2 = top + return draw_box((x1, y1), (x2, y2), **kwargs) + + def _draw_sigil_octo(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw OCTO sigil, a box with the corners cut off (PRIVATE).""" + if strand == 1: + y1 = center + y2 = top + elif strand == -1: + y1 = bottom + y2 = center + else: + y1 = bottom + y2 = top + return draw_cut_corner_box((x1, y1), (x2, y2), **kwargs) + + def _draw_sigil_jaggy( + self, bottom, center, top, x1, x2, strand, color, border=None, **kwargs + ): + """Draw JAGGY sigil (PRIVATE). + + Although we may in future expose the head/tail jaggy lengths, for now + both the left and right edges are drawn jagged. + """ + if strand == 1: + y1 = center + y2 = top + teeth = 2 + elif strand == -1: + y1 = bottom + y2 = center + teeth = 2 + else: + y1 = bottom + y2 = top + teeth = 4 + + xmin = min(x1, x2) + xmax = max(x1, x2) + height = y2 - y1 + boxwidth = x2 - x1 + tooth_length = min(height / teeth, boxwidth * 0.5) + + headlength = tooth_length + taillength = tooth_length + + strokecolor, color = _stroke_and_fill_colors(color, border) + + points = [] + for i in range(teeth): + points.extend( + ( + xmin, + y1 + i * height / teeth, + xmin + taillength, + y1 + (i + 1) * height / teeth, + ) + ) + for i in range(teeth): + points.extend( + ( + xmax, + y1 + (teeth - i) * height / teeth, + xmax - headlength, + y1 + (teeth - i - 1) * height / teeth, + ) + ) + + return Polygon( + deduplicate(points), + strokeColor=strokecolor, + strokeWidth=1, + strokeLineJoin=1, # 1=round + fillColor=color, + **kwargs, + ) + + def _draw_sigil_arrow(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw ARROW sigil (PRIVATE).""" + if strand == 1: + y1 = center + y2 = top + orientation = "right" + elif strand == -1: + y1 = bottom + y2 = center + orientation = "left" + else: + y1 = bottom + y2 = top + orientation = "right" # backward compatibility + return draw_arrow((x1, y1), (x2, y2), orientation=orientation, **kwargs) + + def _draw_sigil_big_arrow(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw BIGARROW sigil, like ARROW but straddles the axis (PRIVATE).""" + if strand == -1: + orientation = "left" + else: + orientation = "right" + return draw_arrow((x1, bottom), (x2, top), orientation=orientation, **kwargs) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Track.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Track.py new file mode 100644 index 0000000000000000000000000000000000000000..1db922f49a62d76c2ed5a1b238280a72a34f292e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Track.py @@ -0,0 +1,284 @@ +# Copyright 2003-2008 by Leighton Pritchard. 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Track module. + +Provides: + - Track - Container for a single track on the diagram, containing + FeatureSet and GraphSet objects + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +from reportlab.lib import colors + +# GenomeDiagram imports +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet + +_grey = colors.Color(0.6, 0.6, 0.6) + + +class Track: + """Track. + + Attributes: + - height Int describing the relative height to other trackscale_fontsizes + in the diagram + - name String describing the track + - hide Boolean, 0 if the track is not to be drawn + - start, end Integers (or None) specifying start/end to draw just + a partial track. + - greytrack Boolean, 1 if a grey background to the track is to be + drawn + - greytrack_labels Int describing how many track-identifying labels + should be placed on the track at regular intervals + - greytrack_font String describing the font to use for the greytrack + labels + - greytrack_fontsize Int describing the font size to display the + labels on the grey track + - greytrack_font_rotation Int describing the angle through which to + rotate the grey track labels (Linear only) + - greytrack_font_color colors.Color describing the color to draw + the grey track labels + - scale Boolean, 1 if a scale is to be drawn on the track + - scale_format String, defaults to None, when scale values are written + as numerals. Setting this to 'SInt' invokes SI + unit-like multiples, such as Mbp, Kbp and so on. + - scale_color colors.Color to draw the elements of the scale + - scale_font String describing the font to use for the scale labels + - scale_fontsize Int describing the size of the scale label font + - scale_fontangle Int describing the angle at which to draw the scale + labels (linear only) + - scale_ticks Boolean, 1 if ticks should be drawn at all on the + scale + - scale_largeticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_smallticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_largetick_interval Int, describing the number of bases that + should separate large ticks + - scale_smalltick_interval Int, describing the number of bases that + should separate small ticks + - scale_largetick_labels Boolean describing whether position labels + should be written over large ticks + - scale_smalltick_labels Boolean describing whether position labels + should be written over small ticks + - axis_labels Boolean describing whether the value labels should + be placed on the Y axes + + """ + + def __init__( + self, + name=None, + height=1, + hide=0, + greytrack=0, + greytrack_labels=5, + greytrack_fontsize=8, + greytrack_font="Helvetica", + greytrack_font_rotation=0, + greytrack_font_color=_grey, + scale=1, + scale_format=None, + scale_color=colors.black, + scale_font="Helvetica", + scale_fontsize=6, + scale_fontangle=45, + scale_largeticks=0.5, + scale_ticks=1, + scale_smallticks=0.3, + scale_largetick_interval=1e6, + scale_smalltick_interval=1e4, + scale_largetick_labels=1, + scale_smalltick_labels=0, + axis_labels=1, + start=None, + end=None, + greytrack_font_colour=None, + scale_colour=None, + ): + """Initialize. + + Arguments: + - height Int describing the relative height to other tracks in the + diagram + - name String describing the track + - hide Boolean, 0 if the track is not to be drawn + - greytrack Boolean, 1 if a grey background to the track is to be + drawn + - greytrack_labels Int describing how many track-identifying labels + should be placed on the track at regular intervals + - greytrack_font String describing the font to use for the greytrack + labels + - greytrack_fontsize Int describing the font size to display the + labels on the grey track + - greytrack_font_rotation Int describing the angle through which to + rotate the grey track labels (Linear only) + - greytrack_font_color colors.Color describing the color to draw + the grey track labels (overridden by backwards compatible argument + with UK spelling, colour). + - scale Boolean, 1 if a scale is to be drawn on the track + - scale_color colors.Color to draw the elements of the scale + (overridden by backwards compatible argument with UK + spelling, colour). + - scale_font String describing the font to use for the scale labels + - scale_fontsize Int describing the size of the scale label font + - scale_fontangle Int describing the angle at which to draw the scale + labels (linear only) + - scale_ticks Boolean, 1 if ticks should be drawn at all on the + scale + - scale_largeticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_smallticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_largetick_interval Int, describing the number of bases that + should separate large ticks + - scale_smalltick_interval Int, describing the number of bases that + should separate small ticks + - scale_largetick_labels Boolean describing whether position labels + should be written over large ticks + - scale_smalltick_labels Boolean describing whether position labels + should be written over small ticks + - name String to help identify the track + - height Relative height to draw the track + - axis_labels Boolean describing whether the value labels should + be placed on the Y axes + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if greytrack_font_colour is not None: + greytrack_font_color = greytrack_font_colour + if scale_colour is not None: + scale_color = scale_colour + + self._next_id = 0 # This will count sets as they are added to the track + self._sets = {} # Holds sets, keyed by unique ID + + # Assign attribute values from instantiation + self.height = height + if name is not None: + self.name = str(name) + else: + self.name = "Track" + self.hide = hide + self.start = start + self.end = end + + # Attributes for the grey track background and labels + self.greytrack = greytrack + self.greytrack_labels = greytrack_labels + self.greytrack_fontsize = greytrack_fontsize + self.greytrack_font = greytrack_font + self.greytrack_font_rotation = greytrack_font_rotation + self.greytrack_fontcolor = greytrack_font_color + + # Attributes for the track scale + self.scale = scale + self.scale_format = scale_format + self.scale_color = scale_color + self.scale_font = scale_font + self.scale_fontsize = scale_fontsize + self.scale_fontangle = scale_fontangle + self.scale_ticks = scale_ticks + self.scale_largeticks = scale_largeticks + self.scale_smallticks = scale_smallticks + self.scale_largetick_interval = scale_largetick_interval + self.scale_smalltick_interval = scale_smalltick_interval + self.scale_largetick_labels = scale_largetick_labels + self.scale_smalltick_labels = scale_smalltick_labels + self.axis_labels = axis_labels + + def add_set(self, set): + """Add a preexisting FeatureSet or GraphSet object to the track.""" + set.id = self._next_id # Assign unique id to set + set.parent = self # Make set's parent this track + self._sets[self._next_id] = set # Add set, keyed by unique id + self._next_id += 1 # Increment unique set ids + + def new_set(self, type="feature", **args): + """Create a new FeatureSet or GraphSet object. + + Create a new FeatureSet or GraphSet object, add it to the + track, and return for user manipulation + """ + type_dict = {"feature": FeatureSet, "graph": GraphSet} + set = type_dict[type]() + for key in args: + setattr(set, key, args[key]) + set.id = self._next_id # Assign unique id to set + set.parent = self # Make set's parent this track + self._sets[self._next_id] = set # Add set, keyed by unique id + self._next_id += 1 # Increment unique set ids + return set + + def del_set(self, set_id): + """Remove the set with the passed id from the track.""" + del self._sets[set_id] + + def get_sets(self): + """Return the sets contained in this track.""" + return list(self._sets.values()) + + def get_ids(self): + """Return the ids of all sets contained in this track.""" + return list(self._sets.keys()) + + def range(self): + """Return the lowest and highest base (or mark) numbers as a tuple.""" + lows, highs = [], [] # Holds set of low and high values from sets + if self.start is not None: + lows.append(self.start) + if self.end is not None: + highs.append(self.end) + for set in self._sets.values(): + low, high = set.range() # Get each set range + lows.append(low) + highs.append(high) + if lows: + low = min(lows) + else: + low = None + if highs: + high = max(highs) + else: + high = None + return low, high # Return lowest and highest values + + def to_string(self, verbose=0): + """Return a formatted string with information about the track. + + Arguments: + - verbose - Boolean indicating whether a short or complete + account of the track is required + + """ + if not verbose: # Return the short description + return f"{self}" # Use __str__ method instead + else: # Return the long description + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d sets" % len(self._sets)) + for key in self._sets: + outstr.append(f"set: {self._sets[key]}") + return "\n".join(outstr) + + def __getitem__(self, key): + """Return the set with the passed id.""" + return self._sets[key] + + def __str__(self): + """Return a formatted string with information about the Track.""" + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d sets" % len(self._sets)) + return "\n".join(outstr) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1712a4ab7a39ded55a67b5d1f420ef28bb12f801 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/__init__.py @@ -0,0 +1,37 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2009 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. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +# ############################################################################# + +"""GenomeDiagram module integrated into Biopython.""" + +# Local imports, to make these classes available directly under the +# Bio.Graphics.GenomeDiagram namespace: + +from ._Colors import ColorTranslator +from ._CrossLink import CrossLink +from ._Diagram import Diagram +from ._Feature import Feature +from ._FeatureSet import FeatureSet +from ._Graph import GraphData +from ._GraphSet import GraphSet +from ._Track import Track + +__all__ = ( + "Diagram", + "Track", + "FeatureSet", + "Feature", + "GraphSet", + "GraphData", + "CrossLink", + "ColorTranslator", +) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/KGML_vis.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/KGML_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..12f9608356b4c55867b57d5a53da1bb02600a40a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/KGML_vis.py @@ -0,0 +1,442 @@ +# Copyright 2013 Leighton Pritchard. 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 and functions to visualise a KGML Pathway Map. + +The KGML definition is as of release KGML v0.7.1 +(http://www.kegg.jp/kegg/xml/docs/) + +Classes: +""" + +import os +import tempfile +from io import BytesIO + +try: + from reportlab.lib import colors + from reportlab.pdfgen import canvas +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install reportlab if you want to use KGML_vis." + ) from None + +try: + from PIL import Image +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install pillow if you want to use KGML_vis." + ) from None + +from urllib.request import urlopen + +from Bio.KEGG.KGML.KGML_pathway import Pathway + + +def darken(color, factor=0.7): + """Return darkened color as a ReportLab RGB color. + + Take a passed color and returns a Reportlab color that is darker by the + factor indicated in the parameter. + """ + newcol = color_to_reportlab(color) + for a in ["red", "green", "blue"]: + setattr(newcol, a, factor * getattr(newcol, a)) + return newcol + + +def color_to_reportlab(color): + """Return the passed color in Reportlab Color format. + + We allow colors to be specified as hex values, tuples, or Reportlab Color + objects, and with or without an alpha channel. This function acts as a + Rosetta stone for conversion of those formats to a Reportlab Color + object, with alpha value. + + Any other color specification is returned directly + """ + # Reportlab Color objects are in the format we want already + if isinstance(color, colors.Color): + return color + elif isinstance(color, str): # String implies hex color + if color.startswith("0x"): # Standardise to octothorpe + color.replace("0x", "#") + if len(color) == 7: + return colors.HexColor(color) + else: + try: + return colors.HexColor(color, hasAlpha=True) + except TypeError: # Catch pre-2.7 Reportlab + raise RuntimeError( + "Your reportlab seems to be too old, try 2.7 onwards" + ) from None + elif isinstance(color, tuple): # Tuple implies RGB(alpha) tuple + return colors.Color(*color) + return color + + +def get_temp_imagefilename(url): + """Return filename of temporary file containing downloaded image. + + Create a new temporary file to hold the image file at the passed URL + and return the filename. + """ + img = urlopen(url).read() + im = Image.open(BytesIO(img)) + # im.transpose(Image.FLIP_TOP_BOTTOM) + f = tempfile.NamedTemporaryFile(delete=False, suffix=".png") + fname = f.name + f.close() + im.save(fname, "PNG") + return fname + + +class KGMLCanvas: + """Reportlab Canvas-based representation of a KGML pathway map.""" + + def __init__( + self, + pathway, + import_imagemap=False, + label_compounds=True, + label_orthologs=True, + label_reaction_entries=True, + label_maps=True, + show_maps=False, + fontname="Helvetica", + fontsize=6, + draw_relations=True, + show_orthologs=True, + show_compounds=True, + show_genes=True, + show_reaction_entries=True, + margins=(0.02, 0.02), + ): + """Initialize the class.""" + self.pathway = pathway + self.show_maps = show_maps + self.show_orthologs = show_orthologs + self.show_compounds = show_compounds + self.show_genes = show_genes + self.show_reaction_entries = show_reaction_entries + self.label_compounds = label_compounds + self.label_orthologs = label_orthologs + self.label_reaction_entries = label_reaction_entries + self.label_maps = label_maps + self.fontname = fontname + self.fontsize = fontsize + self.draw_relations = draw_relations + self.non_reactant_transparency = 0.3 + self.import_imagemap = import_imagemap # Import the map .png from URL + # percentage of canvas that will be margin in on either side in the + # X and Y directions + self.margins = margins + + def draw(self, filename): + """Add the map elements to the drawing.""" + # Instantiate the drawing, first + # size x_max, y_max for now - we can add margins, later + if self.import_imagemap: + # We're drawing directly on the image, so we set the canvas to the + # same size as the image + if os.path.isfile(self.pathway.image): + imfilename = self.pathway.image + else: + imfilename = get_temp_imagefilename(self.pathway.image) + im = Image.open(imfilename) + cwidth, cheight = im.size + else: + # No image, so we set the canvas size to accommodate visible + # elements + cwidth, cheight = (self.pathway.bounds[1][0], self.pathway.bounds[1][1]) + # Instantiate canvas + self.drawing = canvas.Canvas( + filename, + bottomup=0, + pagesize=( + cwidth * (1 + 2 * self.margins[0]), + cheight * (1 + 2 * self.margins[1]), + ), + ) + self.drawing.setFont(self.fontname, self.fontsize) + # Transform the canvas to add the margins + self.drawing.translate( + self.margins[0] * self.pathway.bounds[1][0], + self.margins[1] * self.pathway.bounds[1][1], + ) + # Add the map image, if required + if self.import_imagemap: + self.drawing.saveState() + self.drawing.scale(1, -1) + self.drawing.translate(0, -cheight) + self.drawing.drawImage(imfilename, 0, 0) + self.drawing.restoreState() + # Add the reactions, compounds and maps + # Maps go on first, to be overlaid by more information. + # By default, they're slightly transparent. + if self.show_maps: + self.__add_maps() + if self.show_reaction_entries: + self.__add_reaction_entries() + if self.show_orthologs: + self.__add_orthologs() + if self.show_compounds: + self.__add_compounds() + if self.show_genes: + self.__add_genes() + # TODO: complete draw_relations code + # if self.draw_relations: + # self.__add_relations() + # Write the pathway map to PDF + self.drawing.save() + + def __add_maps(self): + """Add maps to the drawing of the map (PRIVATE). + + We do this first, as they're regional labels to be overlaid by + information. Also, we want to set the color to something subtle. + + We're using Hex colors because that's what KGML uses, and + Reportlab doesn't mind. + """ + for m in self.pathway.maps: + for g in m.graphics: + self.drawing.setStrokeColor("#888888") + self.drawing.setFillColor("#DDDDDD") + self.__add_graphics(g) + if self.label_maps: + self.drawing.setFillColor("#888888") + self.__add_labels(g) + + def __add_graphics(self, graphics): + """Add the passed graphics object to the map (PRIVATE). + + Add text, add after the graphics object, for sane Z-ordering. + """ + if graphics.type == "line": + p = self.drawing.beginPath() + x, y = graphics.coords[0] + # There are optional settings for lines that aren't necessarily + # part of the KGML DTD + if graphics.width is not None: + self.drawing.setLineWidth(graphics.width) + else: + self.drawing.setLineWidth(1) + p.moveTo(x, y) + for x, y in graphics.coords: + p.lineTo(x, y) + self.drawing.drawPath(p) + self.drawing.setLineWidth(1) # Return to default + # KGML defines the (x, y) coordinates as the centre of the circle/ + # rectangle/roundrectangle, but Reportlab uses the coordinates of the + # lower-left corner for rectangle/elif. + if graphics.type == "circle": + self.drawing.circle( + graphics.x, graphics.y, graphics.width * 0.5, stroke=1, fill=1 + ) + elif graphics.type == "roundrectangle": + self.drawing.roundRect( + graphics.x - graphics.width * 0.5, + graphics.y - graphics.height * 0.5, + graphics.width, + graphics.height, + min(graphics.width, graphics.height) * 0.1, + stroke=1, + fill=1, + ) + elif graphics.type == "rectangle": + self.drawing.rect( + graphics.x - graphics.width * 0.5, + graphics.y - graphics.height * 0.5, + graphics.width, + graphics.height, + stroke=1, + fill=1, + ) + + def __add_labels(self, graphics): + """Add labels for the passed graphics objects to the map (PRIVATE). + + We don't check that the labels fit inside objects such as circles/ + rectangles/roundrectangles. + """ + if graphics.type == "line": + # We use the midpoint of the line - sort of - we take the median + # line segment (list-wise, not in terms of length), and use the + # midpoint of that line. We could have other options here, + # maybe even parameterising it to a proportion of the total line + # length. + mid_idx = len(graphics.coords) * 0.5 + if int(mid_idx) != mid_idx: + idx1, idx2 = int(mid_idx - 0.5), int(mid_idx + 0.5) + else: + idx1, idx2 = int(mid_idx - 1), int(mid_idx) + x1, y1 = graphics.coords[idx1] + x2, y2 = graphics.coords[idx2] + x, y = 0.5 * (x1 + x2), 0.5 * (y1 + y2) + elif graphics.type == "circle": + x, y = graphics.x, graphics.y + elif graphics.type in ("rectangle", "roundrectangle"): + x, y = graphics.x, graphics.y + # How big so we want the text, and how many characters? + if graphics._parent.type == "map": + text = graphics.name + self.drawing.setFont(self.fontname, self.fontsize + 2) + elif len(graphics.name) < 15: + text = graphics.name + else: + text = graphics.name[:12] + "..." + self.drawing.drawCentredString(x, y, text) + self.drawing.setFont(self.fontname, self.fontsize) + + def __add_orthologs(self): + """Add 'ortholog' Entry elements to the drawing of the map (PRIVATE). + + In KGML, these are typically line objects, so we render them + before the compound circles to cover the unsightly ends/junctions. + """ + for ortholog in self.pathway.orthologs: + for g in ortholog.graphics: + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(color_to_reportlab(g.bgcolor)) + self.__add_graphics(g) + if self.label_orthologs: + # We want the label color to be slightly darker + # (where possible), so it can be read + self.drawing.setFillColor(darken(g.fgcolor)) + self.__add_labels(g) + + def __add_reaction_entries(self): + """Add Entry elements for Reactions to the map drawing (PRIVATE). + + In KGML, these are typically line objects, so we render them + before the compound circles to cover the unsightly ends/junctions + """ + for reaction in self.pathway.reaction_entries: + for g in reaction.graphics: + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(color_to_reportlab(g.bgcolor)) + self.__add_graphics(g) + if self.label_reaction_entries: + # We want the label color to be slightly darker + # (where possible), so it can be read + self.drawing.setFillColor(darken(g.fgcolor)) + self.__add_labels(g) + + def __add_compounds(self): + """Add compound elements to the drawing of the map (PRIVATE).""" + for compound in self.pathway.compounds: + for g in compound.graphics: + # Modify transparency of compounds that don't participate + # in reactions + fillcolor = color_to_reportlab(g.bgcolor) + if not compound.is_reactant: + fillcolor.alpha *= self.non_reactant_transparency + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(fillcolor) + self.__add_graphics(g) + if self.label_compounds: + if not compound.is_reactant: + t = 0.3 + else: + t = 1 + self.drawing.setFillColor(colors.Color(0.2, 0.2, 0.2, t)) + self.__add_labels(g) + + def __add_genes(self): + """Add gene elements to the drawing of the map (PRIVATE).""" + for gene in self.pathway.genes: + for g in gene.graphics: + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(color_to_reportlab(g.bgcolor)) + self.__add_graphics(g) + if self.label_compounds: + self.drawing.setFillColor(darken(g.fgcolor)) + self.__add_labels(g) + + def __add_relations(self): + """Add relations to the map (PRIVATE). + + This is tricky. There is no defined graphic in KGML for a + relation, and the corresponding entries are typically defined + as objects 'to be connected somehow'. KEGG uses KegSketch, which + is not public, and most third-party software draws straight line + arrows, with heads to indicate the appropriate direction + (at both ends for reversible reactions), using solid lines for + ECrel relation types, and dashed lines for maplink relation types. + + The relation has: + - entry1: 'from' node + - entry2: 'to' node + - subtype: what the relation refers to + + Typically we have entry1 = map/ortholog; entry2 = map/ortholog, + subtype = compound. + """ + # Dashed lines for maplinks, solid for everything else + for relation in list(self.pathway.relations): + if relation.type == "maplink": + self.drawing.setDash(6, 3) + else: + self.drawing.setDash() + for s in relation.subtypes: + subtype = self.pathway.entries[s[1]] + # Our aim is to draw an arrow from the entry1 object to the + # entry2 object, via the subtype object. + # 1) Entry 1 to subtype + self.__draw_arrow(relation.entry1, subtype) + # 2) subtype to Entry 2 + self.__draw_arrow(subtype, relation.entry2) + + def __draw_arrow(self, g_from, g_to): + """Draw an arrow between given Entry objects (PRIVATE). + + Draws an arrow from the g_from Entry object to the g_to + Entry object; both must have Graphics objects. + """ + # Centre and bound coordinates for the from and two objects + bounds_from, bounds_to = g_from.bounds, g_to.bounds + centre_from = ( + 0.5 * (bounds_from[0][0] + bounds_from[1][0]), + 0.5 * (bounds_from[0][1] + bounds_from[1][1]), + ) + centre_to = ( + 0.5 * (bounds_to[0][0] + bounds_to[1][0]), + 0.5 * (bounds_to[0][1] + bounds_to[1][1]), + ) + p = self.drawing.beginPath() + # print(True, g_from.name, g_to.name, bounds_to, bounds_from) + # If the 'from' and 'to' graphics are vertically-aligned, draw a line + # from the 'from' to the 'to' entity + if bounds_to[0][0] < centre_from[0] < bounds_to[1][0]: + # print(True, g_from.name, g_to.name, bounds_to, bounds_from) + if centre_to[1] > centre_from[1]: # to above from + p.moveTo(centre_from[0], bounds_from[1][1]) + p.lineTo(centre_from[0], bounds_to[0][1]) + # Draw arrow point - TODO + else: # to below from + p.moveTo(centre_from[0], bounds_from[0][1]) + p.lineTo(centre_from[0], bounds_to[1][1]) + # Draw arrow point - TODO + elif bounds_from[0][0] < centre_to[0] < bounds_from[1][0]: + # print(True, g_from.name, g_to.name, bounds_to, bounds_from) + if centre_to[1] > centre_from[1]: # to above from + p.moveTo(centre_to[0], bounds_from[1][1]) + p.lineTo(centre_to[0], bounds_to[0][1]) + # Draw arrow point - TODO + else: # to below from + p.moveTo(centre_to[0], bounds_from[0][1]) + p.lineTo(centre_to[0], bounds_to[1][1]) + # Draw arrow point - TODO + self.drawing.drawPath(p) # Draw arrow shaft + # print(g_from) + # print(bounds_from) + # print(g_to) + # print(bounds_to) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70372cee09af14576c532000fd5a231e1ab6b008 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/__init__.py @@ -0,0 +1,92 @@ +# Copyright 2008 by Brad Chapman. All rights reserved. +# Copyright 2008 by Michiel de Hoon. All rights reserved. +# Copyright 2009-2017 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.Graphics offers several graphical outputs, all using ReportLab.""" + +# Check if ReportLab is installed. +try: + import reportlab as r + + del r +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Please install ReportLab if you want " + "to use Bio.Graphics. You can find ReportLab at " + "http://www.reportlab.com/software/opensource/" + ) from None + + +# The following code is to allow all the Bio.Graphics +# code to deal with the different ReportLab renderers +# and the API quirks consistently. + + +def _write(drawing, output_file, format, dpi=72): + """Standardize output to files (PRIVATE). + + Writes the provided drawing out to a file in a prescribed format. + + - drawing - suitable ReportLab drawing object. + - output_file - a handle to write to, or a filename to write to. + - format - String indicating output format, one of PS, PDF, SVG, + or provided the ReportLab renderPM module is installed, + one of the bitmap formats JPG, BMP, GIF, PNG, TIFF or TIFF. + The format can be given in any case. + - dpi - Resolution (dots per inch) for bitmap formats. + + No return value. + """ + from reportlab.graphics import renderPDF + from reportlab.graphics import renderPS + from reportlab.graphics import renderSVG + + try: + from reportlab.graphics import renderPM + except ImportError: + # This is an optional part of ReportLab, so may not be installed. + # We'll raise a missing dependency error if rendering to a + # bitmap format is attempted. + renderPM = None + + formatdict = { + "PS": renderPS, + "EPS": renderPS, + # not sure which you actually get, PS or EPS, but + # GenomeDiagram used PS while other modules used EPS. + "PDF": renderPDF, + "SVG": renderSVG, + "JPG": renderPM, + "BMP": renderPM, + "GIF": renderPM, + "PNG": renderPM, + "TIFF": renderPM, + "TIF": renderPM, + } + try: + # If output is not a string, then .upper() will trigger + # an attribute error... + drawmethod = formatdict[format.upper()] # select drawing method + except (KeyError, AttributeError): + raise ValueError( + f"Output format should be one of {', '.join(formatdict)}" + ) from None + + if drawmethod is None: + # i.e. We wanted renderPM but it isn't installed + # See the import at the top of the function. + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError("Please install ReportLab's renderPM module") + + if drawmethod == renderPM: + # This has a different API to the other render objects + return drawmethod.drawToFile(drawing, output_file, format, dpi=dpi) + else: + return drawmethod.drawToFile(drawing, output_file) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a47710838931d12a3d58d6913fb879b9171e203a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__init__.py @@ -0,0 +1,5 @@ +# 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. +"""A selection of Hidden Markov Model code.""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Compound b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Compound new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Compound differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Enzyme b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Enzyme new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Enzyme differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Gene b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Gene new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Gene differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._KGML b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._KGML new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._KGML differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Map b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Map new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._Map differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._REST.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._REST.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/._REST.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..352cb2a550ac1cf2be76bc902c65ba569a3bdfc0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__init__.py @@ -0,0 +1,180 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# Copyright 2007 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. + +"""Code to work with the KEGG Ligand/Compound database. + +Functions: + - parse - Returns an iterator giving Record objects. + +Classes: + - Record - A representation of a KEGG Ligand/Compound. +""" + +from Bio.KEGG import _default_wrap +from Bio.KEGG import _struct_wrap +from Bio.KEGG import _wrap_kegg +from Bio.KEGG import _write_kegg + +# Set up line wrapping rules (see Bio.KEGG._wrap_kegg) +name_wrap = [0, "", (" ", "$", 1, 1), ("-", "$", 1, 1)] +id_wrap = _default_wrap +struct_wrap = _struct_wrap + + +class Record: + """Holds info from a KEGG Ligand/Compound record. + + Attributes: + - entry The entry identifier. + - name A list of the compound names. + - formula The chemical formula for the compound + - mass The molecular weight for the compound + - pathway A list of 3-tuples: ('PATH', pathway id, pathway) + - enzyme A list of the EC numbers. + - structures A list of 2-tuples: (database, list of struct ids) + - dblinks A list of 2-tuples: (database, list of link ids) + + """ + + def __init__(self): + """Initialize as new record.""" + self.entry = "" + self.name = [] + self.formula = "" + self.mass = "" + self.pathway = [] + self.enzyme = [] + self.structures = [] + self.dblinks = [] + + def __str__(self): + """Return a string representation of this Record.""" + return ( + self._entry() + + self._name() + + self._formula() + + self._mass() + + self._pathway() + + self._enzyme() + + self._structures() + + self._dblinks() + + "///" + ) + + def _entry(self): + return _write_kegg("ENTRY", [self.entry]) + + def _name(self): + return _write_kegg( + "NAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.name] + ) + + def _formula(self): + return _write_kegg("FORMULA", [self.formula]) + + def _mass(self): + return _write_kegg("MASS", [self.mass]) + + def _pathway(self): + s = [] + for entry in self.pathway: + s.append(entry[0] + " " + entry[1]) + return _write_kegg( + "PATHWAY", [_wrap_kegg(line, wrap_rule=id_wrap(16)) for line in s] + ) + + def _enzyme(self): + return _write_kegg( + "ENZYME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.enzyme] + ) + + def _structures(self): + s = [] + for entry in self.structures: + s.append(entry[0] + ": " + " ".join(entry[1]) + " ") + return _write_kegg( + "STRUCTURES", [_wrap_kegg(line, wrap_rule=struct_wrap(5)) for line in s] + ) + + def _dblinks(self): + s = [] + for entry in self.dblinks: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg( + "DBLINKS", [_wrap_kegg(line, wrap_rule=id_wrap(9)) for line in s] + ) + + +def parse(handle): + """Parse a KEGG Ligan/Compound file, returning Record objects. + + This is an iterator function, typically used in a for loop. For + example, using one of the example KEGG files in the Biopython + test suite, + + >>> with open("KEGG/compound.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... + C00023 Iron + C00017 Protein + C00099 beta-Alanine + C00294 Inosine + C00298 Trypsin + C00348 all-trans-Undecaprenyl phosphate + C00349 2-Methyl-3-oxopropanoate + C01386 NH2Mec + + """ + record = Record() + for line in handle: + if line[:3] == "///": + yield record + record = Record() + continue + if line[:12] != " ": + keyword = line[:12] + data = line[12:].strip() + if keyword == "ENTRY ": + words = data.split() + record.entry = words[0] + elif keyword == "NAME ": + data = data.strip(";") + record.name.append(data) + elif keyword == "ENZYME ": + while data: + column = data[:16] + data = data[16:] + enzyme = column.strip() + record.enzyme.append(enzyme) + elif keyword == "PATHWAY ": + map, name = data.split(" ") + pathway = ("PATH", map, name) + record.pathway.append(pathway) + elif keyword == "FORMULA ": + record.formula = data + elif keyword in ("MASS ", "EXACT_MASS "): + record.mass = data + elif keyword == "DBLINKS ": + if ":" in data: + key, values = data.split(":") + values = values.split() + row = (key, values) + record.dblinks.append(row) + else: + row = record.dblinks[-1] + key, values = row + values.extend(data.split()) + row = key, values + record.dblinks[-1] = row + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d06cf529d50d1f145caca7d0285581b732f567 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__init__.py @@ -0,0 +1,339 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# 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 KEGG Enzyme database. + +Functions: + - parse - Returns an iterator giving Record objects. + +Classes: + - Record - Holds the information from a KEGG Enzyme record. +""" + +from Bio.KEGG import _default_wrap +from Bio.KEGG import _struct_wrap +from Bio.KEGG import _wrap_kegg +from Bio.KEGG import _write_kegg + +# Set up line wrapping rules (see Bio.KEGG._wrap_kegg) +rxn_wrap = [ + 0, + "", + (" + ", "", 1, 1), + (" = ", "", 1, 1), + (" ", "$", 1, 1), + ("-", "$", 1, 1), +] +name_wrap = [0, "", (" ", "$", 1, 1), ("-", "$", 1, 1)] +id_wrap = _default_wrap +struct_wrap = _struct_wrap + + +class Record: + """Holds info from a KEGG Enzyme record. + + Attributes: + - entry The EC number (without the 'EC '). + - name A list of the enzyme names. + - classname A list of the classification terms. + - sysname The systematic name of the enzyme. + - reaction A list of the reaction description strings. + - substrate A list of the substrates. + - product A list of the products. + - inhibitor A list of the inhibitors. + - cofactor A list of the cofactors. + - effector A list of the effectors. + - comment A list of the comment strings. + - pathway A list of 3-tuples: (database, id, pathway) + - genes A list of 2-tuples: (organism, list of gene ids) + - disease A list of 3-tuples: (database, id, disease) + - structures A list of 2-tuples: (database, list of struct ids) + - dblinks A list of 2-tuples: (database, list of db ids) + + """ + + def __init__(self): + """Initialize a new Record.""" + self.entry = "" + self.name = [] + self.classname = [] + self.sysname = [] + self.reaction = [] + self.substrate = [] + self.product = [] + self.inhibitor = [] + self.cofactor = [] + self.effector = [] + self.comment = [] + self.pathway = [] + self.genes = [] + self.disease = [] + self.structures = [] + self.dblinks = [] + + def __str__(self): + """Return a string representation of this Record.""" + return ( + self._entry() + + self._name() + + self._classname() + + self._sysname() + + self._reaction() + + self._substrate() + + self._product() + + self._inhibitor() + + self._cofactor() + + self._effector() + + self._comment() + + self._pathway() + + self._genes() + + self._disease() + + self._structures() + + self._dblinks() + + "///" + ) + + def _entry(self): + return _write_kegg("ENTRY", ["EC " + self.entry]) + + def _name(self): + return _write_kegg( + "NAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.name] + ) + + def _classname(self): + return _write_kegg("CLASS", self.classname) + + def _sysname(self): + return _write_kegg( + "SYSNAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.sysname] + ) + + def _reaction(self): + return _write_kegg( + "REACTION", [_wrap_kegg(line, wrap_rule=rxn_wrap) for line in self.reaction] + ) + + def _substrate(self): + return _write_kegg( + "SUBSTRATE", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.substrate], + ) + + def _product(self): + return _write_kegg( + "PRODUCT", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.product] + ) + + def _inhibitor(self): + return _write_kegg( + "INHIBITOR", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.inhibitor], + ) + + def _cofactor(self): + return _write_kegg( + "COFACTOR", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.cofactor], + ) + + def _effector(self): + return _write_kegg( + "EFFECTOR", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.effector], + ) + + def _comment(self): + return _write_kegg( + "COMMENT", [_wrap_kegg(line, wrap_rule=id_wrap(0)) for line in self.comment] + ) + + def _pathway(self): + s = [] + for entry in self.pathway: + s.append(entry[0] + ": " + entry[1] + " " + entry[2]) + return _write_kegg( + "PATHWAY", [_wrap_kegg(line, wrap_rule=id_wrap(16)) for line in s] + ) + + def _genes(self): + s = [] + for entry in self.genes: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg( + "GENES", [_wrap_kegg(line, wrap_rule=id_wrap(5)) for line in s] + ) + + def _disease(self): + s = [] + for entry in self.disease: + s.append(entry[0] + ": " + entry[1] + " " + entry[2]) + return _write_kegg( + "DISEASE", [_wrap_kegg(line, wrap_rule=id_wrap(13)) for line in s] + ) + + def _structures(self): + s = [] + for entry in self.structures: + s.append(entry[0] + ": " + " ".join(entry[1]) + " ") + return _write_kegg( + "STRUCTURES", [_wrap_kegg(line, wrap_rule=struct_wrap(5)) for line in s] + ) + + def _dblinks(self): + # This is a bit of a cheat that won't work if enzyme entries + # have more than one link id per db id. For now, that's not + # the case - storing links ids in a list is only to make + # this class similar to the Compound.Record class. + s = [] + for entry in self.dblinks: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg("DBLINKS", s) + + +def parse(handle): + """Parse a KEGG Enzyme file, returning Record objects. + + This is an iterator function, typically used in a for loop. For + example, using one of the example KEGG files in the Biopython + test suite, + + >>> with open("KEGG/enzyme.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... + 1.1.1.1 alcohol dehydrogenase + 1.1.1.62 17beta-estradiol 17-dehydrogenase + 1.1.1.68 Transferred to 1.5.1.20 + 1.6.5.3 NADH:ubiquinone reductase (H+-translocating) + 1.14.13.28 3,9-dihydroxypterocarpan 6a-monooxygenase + 2.4.1.68 glycoprotein 6-alpha-L-fucosyltransferase + 3.1.1.6 acetylesterase + 2.7.2.1 acetate kinase + + """ + record = Record() + for line in handle: + if line[:3] == "///": + yield record + record = Record() + continue + if line[:12] != " ": + keyword = line[:12] + data = line[12:].strip() + if keyword == "ENTRY ": + words = data.split() + record.entry = words[1] + elif keyword == "CLASS ": + record.classname.append(data) + elif keyword == "COFACTOR ": + record.cofactor.append(data) + elif keyword == "COMMENT ": + record.comment.append(data) + elif keyword == "DBLINKS ": + if ":" in data: + key, values = data.split(":") + values = values.split() + row = (key, values) + record.dblinks.append(row) + else: + row = record.dblinks[-1] + key, values = row + values.extend(data.split()) + row = key, values + record.dblinks[-1] = row + elif keyword == "DISEASE ": + if ":" in data: + database, data = data.split(":") + number, name = data.split(None, 1) + row = (database, number, name) + record.disease.append(row) + else: + row = record.disease[-1] + database, number, name = row + name = name + " " + data + row = database, number, name + record.disease[-1] = row + elif keyword == "EFFECTOR ": + record.effector.append(data.strip(";")) + elif keyword == "GENES ": + if data[3:5] == ": " or data[4:6] == ": ": + key, values = data.split(":", 1) + values = [value.split("(")[0] for value in values.split()] + row = (key, values) + record.genes.append(row) + else: + row = record.genes[-1] + key, values = row + for value in data.split(): + value = value.split("(")[0] + values.append(value) + row = key, values + record.genes[-1] = row + elif keyword == "INHIBITOR ": + record.inhibitor.append(data.strip(";")) + elif keyword == "NAME ": + record.name.append(data.strip(";")) + elif keyword == "PATHWAY ": + if data[:5] == "PATH:": + _, map_num, name = data.split(None, 2) + pathway = ("PATH", map_num, name) + record.pathway.append(pathway) + else: + ec_num, name = data.split(None, 1) + pathway = "PATH", ec_num, name + record.pathway.append(pathway) + elif keyword == "PRODUCT ": + record.product.append(data.strip(";")) + elif keyword == "REACTION ": + record.reaction.append(data.strip(";")) + elif keyword == "STRUCTURES ": + if data[:4] == "PDB:": + database = data[:3] + accessions = data[4:].split() + row = (database, accessions) + record.structures.append(row) + else: + row = record.structures[-1] + database, accessions = row + accessions.extend(data.split()) + row = (database, accessions) + record.structures[-1] = row + elif keyword == "SUBSTRATE ": + record.substrate.append(data.strip(";")) + elif keyword == "SYSNAME ": + record.sysname.append(data.strip(";")) + + +def read(handle): + """Parse a KEGG Enzyme file with exactly one entry. + + If the handle contains no records, or more than one record, + an exception is raised. For example: + + >>> with open("KEGG/enzyme.new") as handle: + ... record = read(handle) + ... print("%s %s" % (record.entry, record.name[0])) + ... + 6.2.1.25 benzoate---CoA ligase + """ + records = parse(handle) + 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 + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e64ce8ab32381583680024d41ba86138dfb2c20f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__init__.py @@ -0,0 +1,142 @@ +# Copyright 2017 by Kozo Nishida. 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 work with the KEGG Gene database. + +Functions: +- parse - Returns an iterator giving Record objects. + +Classes: +- Record - A representation of a KEGG Gene. + +""" + +from Bio.KEGG import _default_wrap +from Bio.KEGG import _wrap_kegg +from Bio.KEGG import _write_kegg + +# Set up line wrapping rules (see Bio.KEGG._wrap_kegg) +name_wrap = [0, "", (" ", "$", 1, 1), ("-", "$", 1, 1)] +id_wrap = _default_wrap + + +class Record: + """Holds info from a KEGG Gene record. + + Attributes: + - entry The entry identifier. + - name A list of the gene names. + - definition The definition for the gene. + - orthology A list of 2-tuples: (orthology id, role) + - organism A tuple: (organism id, organism) + - position The position for the gene + - motif A list of 2-tuples: (database, list of link ids) + - dblinks A list of 2-tuples: (database, list of link ids) + + """ + + def __init__(self): + """Initialize new record.""" + self.entry = "" + self.name = [] + self.definition = "" + self.orthology = [] + self.organism = "" + self.position = "" + self.motif = [] + self.dblinks = [] + + def __str__(self): + """Return a string representation of this Record.""" + return self._entry() + self._name() + self._dblinks() + "///" + + def _entry(self): + return _write_kegg("ENTRY", [self.entry]) + + def _name(self): + return _write_kegg( + "NAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.name] + ) + + def _definition(self): + return _write_kegg("DEFINITION", [self.definition]) + + def _dblinks(self): + s = [] + for entry in self.dblinks: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg( + "DBLINKS", [_wrap_kegg(line, wrap_rule=id_wrap(9)) for line in s] + ) + + +def parse(handle): + """Parse a KEGG Gene file, returning Record objects. + + This is an iterator function, typically used in a for loop. For + example, using one of the example KEGG files in the Biopython + test suite, + + >>> with open("KEGG/gene.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... + b1174 minE + b1175 minD + + + """ + record = Record() + for line in handle: + if line[:3] == "///": + yield record + record = Record() + continue + if line[:12] != " ": + keyword = line[:12] + data = line[12:].strip() + if keyword == "ENTRY ": + words = data.split() + record.entry = words[0] + elif keyword == "NAME ": + data = data.strip(";") + record.name.append(data) + elif keyword == "DEFINITION ": + record.definition = data + elif keyword == "ORTHOLOGY ": + id, name = data.split(" ") + orthology = (id, name) + record.orthology.append(orthology) + elif keyword == "ORGANISM ": + id, name = data.split(" ") + organism = (id, name) + record.organism = organism + elif keyword == "POSITION ": + record.position = data + elif keyword == "MOTIF ": + key, values = data.split(": ") + values = values.split() + row = (key, values) + record.motif.append(row) + elif keyword == "DBLINKS ": + if ":" in data: + key, values = data.split(": ") + values = values.split() + row = (key, values) + record.dblinks.append(row) + else: + row = record.dblinks[-1] + key, values = row + values.extend(data.split()) + row = key, values + record.dblinks[-1] = row + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/._KGML_parser.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/._KGML_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/._KGML_parser.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/._KGML_pathway.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/._KGML_pathway.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/._KGML_pathway.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_parser.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..4132cfab0631bc36cf86bad8377852a144ee66df --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_parser.py @@ -0,0 +1,193 @@ +# Copyright 2013 by Leighton Pritchard. 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 and functions to parse a KGML pathway map. + +The KGML pathway map is parsed into the object structure defined in +KGML_Pathway.py in this module. + +Classes: + - KGMLParser - Parses KGML file + +Functions: + - read - Returns a single Pathway object, using KGMLParser internally + +""" + +from io import StringIO +from xml.etree import ElementTree + +from Bio.KEGG.KGML.KGML_pathway import Component +from Bio.KEGG.KGML.KGML_pathway import Entry +from Bio.KEGG.KGML.KGML_pathway import Graphics +from Bio.KEGG.KGML.KGML_pathway import Pathway +from Bio.KEGG.KGML.KGML_pathway import Reaction +from Bio.KEGG.KGML.KGML_pathway import Relation + + +def read(handle): + """Parse a single KEGG Pathway from given file handle. + + Returns a single Pathway object. There should be one and only + one pathway in each file, but there may well be pathological + examples out there. + """ + pathways = parse(handle) + try: + pathway = next(pathways) + except StopIteration: + raise ValueError("No pathways found in handle") from None + try: + next(pathways) + raise ValueError("More than one pathway found in handle") + except StopIteration: + pass + return pathway + + +def parse(handle): + """Return an iterator over Pathway elements. + + Arguments: + - handle - file handle to a KGML file for parsing, or a KGML string + + This is a generator for the return of multiple Pathway objects. + + """ + # Check handle + try: + handle.read(0) + except AttributeError: + try: + handle = StringIO(handle) + except TypeError: + raise TypeError( + "An XML-containing handle or an XML string must be provided" + ) from None + # Parse XML and return each Pathway + for event, elem in ElementTree.iterparse(handle, events=("start", "end")): + if event == "end" and elem.tag == "pathway": + yield KGMLParser(elem).parse() + elem.clear() + + +class KGMLParser: + """Parses a KGML XML Pathway entry into a Pathway object. + + Example: Read and parse large metabolism file + + >>> from Bio.KEGG.KGML.KGML_parser import read + >>> pathway = read(open('KEGG/ko01100.xml', 'r')) + >>> print(len(pathway.entries)) + 3628 + >>> print(len(pathway.reactions)) + 1672 + >>> print(len(pathway.maps)) + 149 + + >>> pathway = read(open('KEGG/ko00010.xml', 'r')) + >>> print(pathway) #doctest: +NORMALIZE_WHITESPACE + Pathway: Glycolysis / Gluconeogenesis + KEGG ID: path:ko00010 + Image file: http://www.kegg.jp/kegg/pathway/ko/ko00010.png + Organism: ko + Entries: 99 + Entry types: + ortholog: 61 + compound: 31 + map: 7 + + """ + + def __init__(self, elem): + """Initialize the class.""" + self.entry = elem + + def parse(self): + """Parse the input elements.""" + + def _parse_pathway(attrib): + for k, v in attrib.items(): + self.pathway.__setattr__(k, v) + + def _parse_entry(element): + new_entry = Entry() + for k, v in element.attrib.items(): + new_entry.__setattr__(k, v) + for subelement in element: + if subelement.tag == "graphics": + _parse_graphics(subelement, new_entry) + elif subelement.tag == "component": + _parse_component(subelement, new_entry) + self.pathway.add_entry(new_entry) + + def _parse_graphics(element, entry): + new_graphics = Graphics(entry) + for k, v in element.attrib.items(): + new_graphics.__setattr__(k, v) + entry.add_graphics(new_graphics) + + def _parse_component(element, entry): + new_component = Component(entry) + for k, v in element.attrib.items(): + new_component.__setattr__(k, v) + entry.add_component(new_component) + + def _parse_reaction(element): + new_reaction = Reaction() + for k, v in element.attrib.items(): + new_reaction.__setattr__(k, v) + for subelement in element: + if subelement.tag == "substrate": + new_reaction.add_substrate(int(subelement.attrib["id"])) + elif subelement.tag == "product": + new_reaction.add_product(int(subelement.attrib["id"])) + self.pathway.add_reaction(new_reaction) + + def _parse_relation(element): + new_relation = Relation() + new_relation.entry1 = int(element.attrib["entry1"]) + new_relation.entry2 = int(element.attrib["entry2"]) + new_relation.type = element.attrib["type"] + for subtype in element: + name, value = subtype.attrib["name"], subtype.attrib["value"] + if name in ("compound", "hidden compound"): + new_relation.subtypes.append((name, int(value))) + else: + new_relation.subtypes.append((name, value)) + self.pathway.add_relation(new_relation) + + # ========== + # Initialize Pathway + self.pathway = Pathway() + # Get information about the pathway itself + _parse_pathway(self.entry.attrib) + for element in self.entry: + if element.tag == "entry": + _parse_entry(element) + elif element.tag == "reaction": + _parse_reaction(element) + elif element.tag == "relation": + _parse_relation(element) + # Parsing of some elements not implemented - no examples yet + else: + # This should warn us of any unimplemented tags + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + f"Warning: tag {element.tag} not implemented in parser", + BiopythonParserWarning, + ) + return self.pathway + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_pathway.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_pathway.py new file mode 100644 index 0000000000000000000000000000000000000000..8e8c44b63b194c2963d6f7576dd38cfd7ef83abe --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_pathway.py @@ -0,0 +1,857 @@ +# Copyright 2013 by Leighton Pritchard. 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 represent a KGML Pathway Map. + +The KGML definition is as of release KGML v0.7.2 +(http://www.kegg.jp/kegg/xml/docs/) + +Classes: + - Pathway - Specifies graph information for the pathway map + - Relation - Specifies a relationship between two proteins or KOs, + or protein and compound. There is an implied direction to the + relationship in some cases. + - Reaction - A specific chemical reaction between a substrate and + a product. + - Entry - A node in the pathway graph + - Graphics - Entry subelement describing its visual representation + +""" + +import time +import xml.etree.ElementTree as ET +from itertools import chain +from xml.dom import minidom + + +# Pathway +class Pathway: + """Represents a KGML pathway from KEGG. + + Specifies graph information for the pathway map, as described in + release KGML v0.7.2 (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - name - KEGGID of the pathway map + - org - ko/ec/[org prefix] + - number - map number (integer) + - title - the map title + - image - URL of the image map for the pathway + - link - URL of information about the pathway + - entries - Dictionary of entries in the pathway, keyed by node ID + - reactions - Set of reactions in the pathway + + The name attribute has a restricted format, so we make it a property and + enforce the formatting. + + The Pathway object is the only allowed route for adding/removing + Entry, Reaction, or Relation elements. + + Entries are held in a dictionary and keyed by the node ID for the + pathway graph - this allows for ready access via the Reaction/Relation + etc. elements. Entries must be added before reference by any other + element. + + Reactions are held in a dictionary, keyed by node ID for the path. + The elements referred to in the reaction must be added before the + reaction itself. + + """ + + def __init__(self): + """Initialize the class.""" + self._name = "" + self.org = "" + self._number = None + self.title = "" + self.image = "" + self.link = "" + self.entries = {} + self._reactions = {} + self._relations = set() + + def get_KGML(self): + """Return the pathway as a string in prettified KGML format.""" + header = "\n".join( + [ + '', + "', + f"", + ] + ) + rough_xml = header + ET.tostring(self.element, "utf-8").decode() + reparsed = minidom.parseString(rough_xml) + return reparsed.toprettyxml(indent=" ") + + def add_entry(self, entry): + """Add an Entry element to the pathway.""" + # We insist that the node ID is an integer + if not isinstance(entry.id, int): + raise TypeError( + f"Node ID must be an integer, got {type(entry.id)} ({entry.id})" + ) + entry._pathway = self # Let the entry know about the pathway + self.entries[entry.id] = entry + + def remove_entry(self, entry): + """Remove an Entry element from the pathway.""" + if not isinstance(entry.id, int): + raise TypeError( + f"Node ID must be an integer, got {type(entry.id)} ({entry.id})" + ) + # We need to remove the entry from any other elements that may + # contain it, which means removing those elements + # TODO + del self.entries[entry.id] + + def add_reaction(self, reaction): + """Add a Reaction element to the pathway.""" + # We insist that the node ID is an integer and corresponds to an entry + if not isinstance(reaction.id, int): + raise ValueError( + f"Node ID must be an integer, got {type(reaction.id)} ({reaction.id})" + ) + if reaction.id not in self.entries: + raise ValueError("Reaction ID %d has no corresponding entry" % reaction.id) + reaction._pathway = self # Let the reaction know about the pathway + self._reactions[reaction.id] = reaction + + def remove_reaction(self, reaction): + """Remove a Reaction element from the pathway.""" + if not isinstance(reaction.id, int): + raise TypeError( + f"Node ID must be an integer, got {type(reaction.id)} ({reaction.id})" + ) + # We need to remove the reaction from any other elements that may + # contain it, which means removing those elements + # TODO + del self._reactions[reaction.id] + + def add_relation(self, relation): + """Add a Relation element to the pathway.""" + relation._pathway = self # Let the reaction know about the pathway + self._relations.add(relation) + + def remove_relation(self, relation): + """Remove a Relation element from the pathway.""" + self._relations.remove(relation) + + def __str__(self): + """Return a readable summary description string.""" + outstr = [ + f"Pathway: {self.title}", + f"KEGG ID: {self.name}", + f"Image file: {self.image}", + f"Organism: {self.org}", + "Entries: %d" % len(self.entries), + "Entry types:", + ] + for t in ["ortholog", "enzyme", "reaction", "gene", "group", "compound", "map"]: + etype = [e for e in self.entries.values() if e.type == t] + if len(etype): + outstr.append("\t%s: %d" % (t, len(etype))) + return "\n".join(outstr) + "\n" + + # Assert correct formatting of the pathway name, and other attributes + def _getname(self): + return self._name + + def _setname(self, value): + if not value.startswith("path:"): + raise ValueError(f"Pathway name should begin with 'path:', got {value}") + self._name = value + + def _delname(self): + del self._name + + name = property(_getname, _setname, _delname, "The KEGGID for the pathway map.") + + def _getnumber(self): + return self._number + + def _setnumber(self, value): + self._number = int(value) + + def _delnumber(self): + del self._number + + number = property(_getnumber, _setnumber, _delnumber, "The KEGG map number.") + + @property + def compounds(self): + """Get a list of entries of type compound.""" + return [e for e in self.entries.values() if e.type == "compound"] + + @property + def maps(self): + """Get a list of entries of type map.""" + return [e for e in self.entries.values() if e.type == "map"] + + @property + def orthologs(self): + """Get a list of entries of type ortholog.""" + return [e for e in self.entries.values() if e.type == "ortholog"] + + @property + def genes(self): + """Get a list of entries of type gene.""" + return [e for e in self.entries.values() if e.type == "gene"] + + @property + def reactions(self): + """Get a list of reactions in the pathway.""" + return self._reactions.values() + + @property + def reaction_entries(self): + """List of entries corresponding to each reaction in the pathway.""" + return [self.entries[i] for i in self._reactions] + + @property + def relations(self): + """Get a list of relations in the pathway.""" + return list(self._relations) + + @property + def element(self): + """Return the Pathway as a valid KGML element.""" + # The root is this Pathway element + pathway = ET.Element("pathway") + pathway.attrib = { + "name": self._name, + "org": self.org, + "number": str(self._number), + "title": self.title, + "image": self.image, + "link": self.link, + } + # We add the Entries in node ID order + for eid, entry in sorted(self.entries.items()): + pathway.append(entry.element) + # Next we add Relations + for relation in self._relations: + pathway.append(relation.element) + for eid, reaction in sorted(self._reactions.items()): + pathway.append(reaction.element) + return pathway + + @property + def bounds(self): + """Coordinate bounds for all Graphics elements in the Pathway. + + Returns the [(xmin, ymin), (xmax, ymax)] coordinates for all + Graphics elements in the Pathway + """ + xlist, ylist = [], [] + for b in [g.bounds for g in self.entries.values()]: + xlist.extend([b[0][0], b[1][0]]) + ylist.extend([b[0][1], b[1][1]]) + return [(min(xlist), min(ylist)), (max(xlist), max(ylist))] + + +# Entry +class Entry: + """Represent an Entry from KGML. + + Each Entry element is a node in the pathway graph, as described in + release KGML v0.7.2 (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - id - The ID of the entry in the pathway map (integer) + - names - List of KEGG IDs for the entry + - type - The type of the entry + - link - URL of information about the entry + - reaction - List of KEGG IDs of the corresponding reactions + (integer) + - graphics - List of Graphics objects describing the Entry's visual + representation + - components - List of component node ID for this Entry ('group') + - alt - List of alternate names for the Entry + + NOTE: The alt attribute represents a subelement of the substrate and + product elements in the KGML file + + """ + + def __init__(self): + """Initialize the class.""" + self._id = None + self._names = [] + self.type = "" + self.image = "" + self.link = "" + self.graphics = [] + self.components = set() + self.alt = [] + self._pathway = None + self._reactions = [] + + def __str__(self): + """Return readable descriptive string.""" + outstr = [ + "Entry node ID: %d" % self.id, + f"Names: {self.name}", + f"Type: {self.type}", + f"Components: {self.components}", + f"Reactions: {self.reaction}", + "Graphics elements: %d %s" % (len(self.graphics), self.graphics), + ] + return "\n".join(outstr) + "\n" + + def add_component(self, element): + """Add an element to the entry. + + If the Entry is already part of a pathway, make sure + the component already exists. + """ + if self._pathway is not None: + if element.id not in self._pathway.entries: + raise ValueError( + f"Component {element.id} is not an entry in the pathway" + ) + self.components.add(element) + + def remove_component(self, value): + """Remove the entry with the passed ID from the group.""" + self.components.remove(value) + + def add_graphics(self, entry): + """Add the Graphics entry.""" + self.graphics.append(entry) + + def remove_graphics(self, entry): + """Remove the Graphics entry with the passed ID from the group.""" + self.graphics.remove(entry) + + # Names may be given as a space-separated list of KEGG identifiers + def _getname(self): + return " ".join(self._names) + + def _setname(self, value): + self._names = value.split() + + def _delname(self): + self._names = [] + + name = property( + _getname, _setname, _delname, "List of KEGG identifiers for the Entry." + ) + + # Reactions may be given as a space-separated list of KEGG identifiers + def _getreaction(self): + return " ".join(self._reactions) + + def _setreaction(self, value): + self._reactions = value.split() + + def _delreaction(self): + self._reactions = [] + + reaction = property( + _getreaction, + _setreaction, + _delreaction, + "List of reaction KEGG IDs for this Entry.", + ) + + # We make sure that the node ID is an integer + def _getid(self): + return self._id + + def _setid(self, value): + self._id = int(value) + + def _delid(self): + del self._id + + id = property(_getid, _setid, _delid, "The pathway graph node ID for the Entry.") + + @property + def element(self): + """Return the Entry as a valid KGML element.""" + # The root is this Entry element + entry = ET.Element("entry") + entry.attrib = { + "id": str(self._id), + "name": self.name, + "link": self.link, + "type": self.type, + } + if len(self._reactions): + entry.attrib["reaction"] = self.reaction + if len(self.graphics): + for g in self.graphics: + entry.append(g.element) + if len(self.components): + for c in self.components: + entry.append(c.element) + return entry + + @property + def bounds(self): + """Coordinate bounds for all Graphics elements in the Entry. + + Return the [(xmin, ymin), (xmax, ymax)] coordinates for the Entry + Graphics elements. + """ + xlist, ylist = [], [] + for b in [g.bounds for g in self.graphics]: + xlist.extend([b[0][0], b[1][0]]) + ylist.extend([b[0][1], b[1][1]]) + return [(min(xlist), min(ylist)), (max(xlist), max(ylist))] + + @property + def is_reactant(self): + """Return true if this Entry participates in any reaction in its parent pathway.""" + for rxn in self._pathway.reactions: + if self._id in rxn.reactant_ids: + return True + return False + + +# Component +class Component: + """An Entry subelement used to represents a complex node. + + A subelement of the Entry element, used when the Entry is a complex + node, as described in release KGML v0.7.2 + (http://www.kegg.jp/kegg/xml/docs/) + + The Component acts as a collection (with type 'group', and typically + its own Graphics subelement), having only an ID. + """ + + def __init__(self, parent): + """Initialize the class.""" + self._id = None + self._parent = parent + + # We make sure that the node ID is an integer + def _getid(self): + return self._id + + def _setid(self, value): + self._id = int(value) + + def _delid(self): + del self._id + + id = property(_getid, _setid, _delid, "The pathway graph node ID for the Entry") + + @property + def element(self): + """Return the Component as a valid KGML element.""" + # The root is this Component element + component = ET.Element("component") + component.attrib = {"id": str(self._id)} + return component + + +# Graphics +class Graphics: + """An Entry subelement used to represents the visual representation. + + A subelement of Entry, specifying its visual representation, as + described in release KGML v0.7.2 (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - name Label for the graphics object + - x X-axis position of the object (int) + - y Y-axis position of the object (int) + - coords polyline coordinates, list of (int, int) tuples + - type object shape + - width object width (int) + - height object height (int) + - fgcolor object foreground color (hex RGB) + - bgcolor object background color (hex RGB) + + Some attributes are present only for specific graphics types. For + example, line types do not (typically) have a width. + We permit non-DTD attributes and attribute settings, such as + + dash List of ints, describing an on/off pattern for dashes + + """ + + def __init__(self, parent): + """Initialize the class.""" + self.name = "" + self._x = None + self._y = None + self._coords = None + self.type = "" + self._width = None + self._height = None + self.fgcolor = "" + self.bgcolor = "" + self._parent = parent + + # We make sure that the XY coordinates, width and height are numbers + def _getx(self): + return self._x + + def _setx(self, value): + self._x = float(value) + + def _delx(self): + del self._x + + x = property(_getx, _setx, _delx, "The X coordinate for the graphics element.") + + def _gety(self): + return self._y + + def _sety(self, value): + self._y = float(value) + + def _dely(self): + del self._y + + y = property(_gety, _sety, _dely, "The Y coordinate for the graphics element.") + + def _getwidth(self): + return self._width + + def _setwidth(self, value): + self._width = float(value) + + def _delwidth(self): + del self._width + + width = property( + _getwidth, _setwidth, _delwidth, "The width of the graphics element." + ) + + def _getheight(self): + return self._height + + def _setheight(self, value): + self._height = float(value) + + def _delheight(self): + del self._height + + height = property( + _getheight, _setheight, _delheight, "The height of the graphics element." + ) + + # We make sure that the polyline coordinates are integers, too + def _getcoords(self): + return self._coords + + def _setcoords(self, value): + clist = [int(e) for e in value.split(",")] + self._coords = [tuple(clist[i : i + 2]) for i in range(0, len(clist), 2)] + + def _delcoords(self): + del self._coords + + coords = property( + _getcoords, + _setcoords, + _delcoords, + "Polyline coordinates for the graphics element.", + ) + + # Set default colors + def _getfgcolor(self): + return self._fgcolor + + def _setfgcolor(self, value): + if value == "none": + self._fgcolor = "#000000" # this default defined in KGML spec + else: + self._fgcolor = value + + def _delfgcolor(self): + del self._fgcolor + + fgcolor = property(_getfgcolor, _setfgcolor, _delfgcolor, "Foreground color.") + + def _getbgcolor(self): + return self._bgcolor + + def _setbgcolor(self, value): + if value == "none": + self._bgcolor = "#000000" # this default defined in KGML spec + else: + self._bgcolor = value + + def _delbgcolor(self): + del self._bgcolor + + bgcolor = property(_getbgcolor, _setbgcolor, _delbgcolor, "Background color.") + + @property + def element(self): + """Return the Graphics as a valid KGML element.""" + # The root is this Component element + graphics = ET.Element("graphics") + if isinstance(self.fgcolor, str): # Assumes that string is hexstring + fghex = self.fgcolor + else: # Assumes ReportLab Color object + fghex = "#" + self.fgcolor.hexval()[2:] + if isinstance(self.bgcolor, str): # Assumes that string is hexstring + bghex = self.bgcolor + else: # Assumes ReportLab Color object + bghex = "#" + self.bgcolor.hexval()[2:] + graphics.attrib = { + "name": self.name, + "type": self.type, + "fgcolor": fghex, + "bgcolor": bghex, + } + for n, attr in [ + ("x", "_x"), + ("y", "_y"), + ("width", "_width"), + ("height", "_height"), + ]: + if getattr(self, attr) is not None: + graphics.attrib[n] = str(getattr(self, attr)) + if self.type == "line": # Need to write polycoords + graphics.attrib["coords"] = ",".join( + [str(e) for e in chain.from_iterable(self.coords)] + ) + return graphics + + @property + def bounds(self): + """Coordinate bounds for the Graphics element. + + Return the bounds of the Graphics object as an [(xmin, ymin), + (xmax, ymax)] tuple. Coordinates give the centre of the + circle, rectangle, roundrectangle elements, so we have to + adjust for the relevant width/height. + """ + if self.type == "line": + xlist = [x for x, y in self.coords] + ylist = [y for x, y in self.coords] + return [(min(xlist), min(ylist)), (max(xlist), max(ylist))] + else: + return [ + (self.x - self.width * 0.5, self.y - self.height * 0.5), + (self.x + self.width * 0.5, self.y + self.height * 0.5), + ] + + @property + def centre(self): + """Return the centre of the Graphics object as an (x, y) tuple.""" + return ( + 0.5 * (self.bounds[0][0] + self.bounds[1][0]), + 0.5 * (self.bounds[0][1] + self.bounds[1][1]), + ) + + +# Reaction +class Reaction: + """A specific chemical reaction with substrates and products. + + This describes a specific chemical reaction between one or more + substrates and one or more products. + + Attributes: + - id Pathway graph node ID of the entry + - names List of KEGG identifier(s) from the REACTION database + - type String: reversible or irreversible + - substrate Entry object of the substrate + - product Entry object of the product + + """ + + def __init__(self): + """Initialize the class.""" + self._id = None + self._names = [] + self.type = "" + self._substrates = set() + self._products = set() + self._pathway = None + + def __str__(self): + """Return an informative human-readable string.""" + outstr = [ + f"Reaction node ID: {self.id}", + f"Reaction KEGG IDs: {self.name}", + f"Type: {self.type}", + f"Substrates: {','.join([s.name for s in self.substrates])}", + f"Products: {','.join([s.name for s in self.products])}", + ] + return "\n".join(outstr) + "\n" + + def add_substrate(self, substrate_id): + """Add a substrate, identified by its node ID, to the reaction.""" + if self._pathway is not None: + if int(substrate_id) not in self._pathway.entries: + raise ValueError( + "Couldn't add substrate, no node ID %d in Pathway" + % int(substrate_id) + ) + self._substrates.add(substrate_id) + + def add_product(self, product_id): + """Add a product, identified by its node ID, to the reaction.""" + if self._pathway is not None: + if int(product_id) not in self._pathway.entries: + raise ValueError( + "Couldn't add product, no node ID %d in Pathway" % product_id + ) + self._products.add(int(product_id)) + + # The node ID is also the node ID of the Entry that corresponds to the + # reaction; we get the corresponding Entry when there is an associated + # Pathway + def _getid(self): + return self._id + + def _setid(self, value): + self._id = int(value) + + def _delid(self): + del self._id + + id = property(_getid, _setid, _delid, "Node ID for the reaction.") + + # Names may show up as a space-separated list of several KEGG identifiers + def _getnames(self): + return " ".join(self._names) + + def _setnames(self, value): + self._names.extend(value.split()) + + def _delnames(self): + del self.names + + name = property( + _getnames, _setnames, _delnames, "List of KEGG identifiers for the reaction." + ) + + # products and substrates are read-only properties, returning lists + # of Entry objects + @property + def substrates(self): + """Return list of substrate Entry elements.""" + return [self._pathway.entries[sid] for sid in self._substrates] + + @property + def products(self): + """Return list of product Entry elements.""" + return [self._pathway.entries[pid] for pid in self._products] + + @property + def entry(self): + """Return the Entry corresponding to this reaction.""" + return self._pathway.entries[self._id] + + @property + def reactant_ids(self): + """Return a list of substrate and product reactant IDs.""" + return self._products.union(self._substrates) + + @property + def element(self): + """Return KGML element describing the Reaction.""" + # The root is this Relation element + reaction = ET.Element("reaction") + reaction.attrib = {"id": str(self.id), "name": self.name, "type": self.type} + for s in self._substrates: + substrate = ET.Element("substrate") + substrate.attrib["id"] = str(s) + substrate.attrib["name"] = self._pathway.entries[s].name + reaction.append(substrate) + for p in self._products: + product = ET.Element("product") + product.attrib["id"] = str(p) + product.attrib["name"] = self._pathway.entries[p].name + reaction.append(product) + return reaction + + +# Relation +class Relation: + """A relationship between to products, KOs, or protein and compound. + + This describes a relationship between two products, KOs, or protein + and compound, as described in release KGML v0.7.2 + (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - entry1 - The first Entry object node ID defining the + relation (int) + - entry2 - The second Entry object node ID defining the + relation (int) + - type - The relation type + - subtypes - List of subtypes for the relation, as a list of + (name, value) tuples + + """ + + def __init__(self): + """Initialize the class.""" + self._entry1 = None + self._entry2 = None + self.type = "" + self.subtypes = [] + self._pathway = None + + def __str__(self): + """Return a useful human-readable string.""" + outstr = [ + "Relation (subtypes: %d):" % len(self.subtypes), + "Entry1:", + str(self.entry1), + "Entry2:", + str(self.entry2), + ] + for s in self.subtypes: + outstr.extend([f"Subtype: {s[0]}", str(s[1])]) + return "\n".join(outstr) + + # Properties entry1 and entry2 + def _getentry1(self): + if self._pathway is not None: + return self._pathway.entries[self._entry1] + return self._entry1 + + def _setentry1(self, value): + self._entry1 = int(value) + + def _delentry1(self): + del self._entry1 + + entry1 = property(_getentry1, _setentry1, _delentry1, "Entry1 of the relation.") + + def _getentry2(self): + if self._pathway is not None: + return self._pathway.entries[self._entry2] + return self._entry2 + + def _setentry2(self, value): + self._entry2 = int(value) + + def _delentry2(self): + del self._entry2 + + entry2 = property(_getentry2, _setentry2, _delentry2, "Entry2 of the relation.") + + @property + def element(self): + """Return KGML element describing the Relation.""" + # The root is this Relation element + relation = ET.Element("relation") + relation.attrib = { + "entry1": str(self._entry1), + "entry2": str(self._entry2), + "type": self.type, + } + for name, value in self.subtypes: + subtype = ET.Element("subtype") + subtype.attrib = {"name": name, "value": str(value)} + relation.append(subtype) + return relation diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9063911e55b86145856c2354636891db4d95ebd0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2013 by Leighton Pritchard. 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 work with data from the KEGG database. + +References: +Kanehisa, M. and Goto, S.; KEGG: Kyoto Encyclopedia of Genes and Genomes. +Nucleic Acids Res. 28, 29-34 (2000). + +URL: http://www.genome.ad.jp/kegg/ + +""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b37f763fbd5f6c4980b4220752016f979d2d14 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__init__.py @@ -0,0 +1,49 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# Copyright 2007 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. + +"""Load KEGG Pathway maps for use with the Biopython Pathway module. + +The pathway maps are in the format:: + + RXXXXX:[X.X.X.X:] A + 2 B <=> C + RXXXXX:[X.X.X.X:] 3C <=> 2 D + E + ... + +where RXXXXX is a five-digit reaction id, and X.X.X.X is the optional +EC number of the enzyme that catalyze the reaction. +""" + +from Bio.Pathway import Reaction + + +def parse(handle): + """Parse a KEGG pathway map.""" + for line in handle: + data, catalysts, reaction = line.split(":") + catalysts = [(catalysts,)] + reactants = {} + before, after = reaction.split("<=>") + compounds = before.split(" + ") + for compound in compounds: + compound = compound.strip() + try: + number, compound = compound.split() + number = -int(number) + except ValueError: + number = -1 + reactants[compound] = number + compounds = after.split(" + ") + for compound in compounds: + compound = compound.strip() + try: + number, compound = compound.split() + number = int(number) + except ValueError: + number = +1 + reactants[compound] = number + yield Reaction(reactants, catalysts, True, data) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/REST.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/REST.py new file mode 100644 index 0000000000000000000000000000000000000000..151f391c091ccbd774b46a425eb5d24e7170e724 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/REST.py @@ -0,0 +1,330 @@ +# Copyright 2014 by Kevin Wu. +# Revisions copyright 2014 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 REST-style KEGG online API. + +This module aims to make the KEGG online REST-style API easier to use. See: +https://www.kegg.jp/kegg/rest/keggapi.html + +The KEGG REST-style API provides simple access to a range of KEGG databases. +This works using simple URLs (which this module will construct for you), +with any errors indicated via HTTP error levels. + +The functionality is somewhat similar to Biopython's Bio.TogoWS and Bio.Entrez +modules. + +Currently KEGG 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. + +References: +Kanehisa, M. and Goto, S.; KEGG: Kyoto Encyclopedia of Genes and Genomes. +Nucleic Acids Res. 28, 29-34 (2000). + +""" + +import io +import time +from urllib.request import urlopen + +from Bio._utils import function_with_previous + + +@function_with_previous +def _q(op, arg1, arg2=None, arg3=None): + delay = 0.333333333 # one third of a second + current = time.time() + wait = _q.previous + delay - current + if wait > 0: + time.sleep(wait) + _q.previous = current + wait + else: + _q.previous = current + + URL = "https://rest.kegg.jp/%s" + if arg2 and arg3: + args = f"{op}/{arg1}/{arg2}/{arg3}" + elif arg2: + args = f"{op}/{arg1}/{arg2}" + else: + args = f"{op}/{arg1}" + resp = urlopen(URL % (args)) + + if "image" == arg2: + return resp + + handle = io.TextIOWrapper(resp, encoding="UTF-8") + handle.url = resp.url + return handle + + +_q.previous = 0 + + +# https://www.kegg.jp/kegg/rest/keggapi.html +def kegg_info(database): + """KEGG info - Displays the current statistics of a given database. + + db - database or organism (string) + + The argument db can be a KEGG database name (e.g. 'pathway' or its + official abbreviation, 'path'), or a KEGG organism code or T number + (e.g. 'hsa' or 'T01001' for human). + + A valid list of organism codes and their T numbers can be obtained + via kegg_info('organism') or https://rest.kegg.jp/list/organism + + """ + # TODO - return a string (rather than the handle?) + # TODO - cache and validate the organism code / T numbers? + # TODO - can we parse the somewhat formatted output? + # + # https://rest.kegg.jp/info/ + # + # = pathway | brite | module | disease | drug | environ | + # ko | genome | | compound | glycan | reaction | + # rpair | rclass | enzyme | genomes | genes | ligand | kegg + # = KEGG organism code or T number + return _q("info", database) + + +def kegg_list(database, org=None): + """KEGG list - Entry list for database, or specified database entries. + + db - database or organism (string) + org - optional organism (string), see below. + + For the pathway and module databases the optional organism can be + used to restrict the results. + + """ + # TODO - split into two functions (dbentries seems separate)? + # + # https://rest.kegg.jp/list// + # + # = pathway | module + # = KEGG organism code + if database in ("pathway", "module") and org: + resp = _q("list", database, org) + elif isinstance(database, str) and database and org: + raise ValueError("Invalid database arg for kegg list request.") + + # https://rest.kegg.jp/list/ + # + # = pathway | brite | module | disease | drug | environ | + # ko | genome | | compound | glycan | reaction | + # rpair | rclass | enzyme | organism + # = KEGG organism code or T number + # + # + # https://rest.kegg.jp/list/ + # + # = KEGG database entries involving the following + # = pathway | brite | module | disease | drug | environ | + # ko | genome | | compound | glycan | reaction | + # rpair | rclass | enzyme + # = KEGG organism code or T number + else: + if isinstance(database, list): + if len(database) > 100: + raise ValueError( + "Maximum number of databases is 100 for kegg list query" + ) + database = ("+").join(database) + resp = _q("list", database) + + return resp + + +def kegg_find(database, query, option=None): + """KEGG find - Data search. + + Finds entries with matching query keywords or other query data in + a given database. + + db - database or organism (string) + query - search terms (string) + option - search option (string), see below. + + For the compound and drug database, set option to the string 'formula', + 'exact_mass' or 'mol_weight' to search on that field only. The + chemical formula search is a partial match irrespective of the order + of atoms given. The exact mass (or molecular weight) is checked by + rounding off to the same decimal place as the query data. A range of + values may also be specified with the minus(-) sign. + + """ + # TODO - return list of tuples? + # + # https://rest.kegg.jp/find///