dcatoolkit 0.2.3__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/LICENSE +21 -21
  2. {dcatoolkit-0.2.3/src/dcatoolkit.egg-info → dcatoolkit-0.4.0}/PKG-INFO +120 -73
  3. dcatoolkit-0.4.0/README.md +63 -0
  4. dcatoolkit-0.4.0/pyproject.toml +84 -0
  5. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/setup.cfg +4 -4
  6. dcatoolkit-0.4.0/src/dcatoolkit/__init__.py +15 -0
  7. dcatoolkit-0.4.0/src/dcatoolkit/analytics.py +230 -0
  8. dcatoolkit-0.4.0/src/dcatoolkit/representation/__init__.py +6 -0
  9. dcatoolkit-0.4.0/src/dcatoolkit/representation/alignment.py +225 -0
  10. dcatoolkit-0.4.0/src/dcatoolkit/representation/di.py +326 -0
  11. dcatoolkit-0.4.0/src/dcatoolkit/representation/pairs.py +236 -0
  12. dcatoolkit-0.4.0/src/dcatoolkit/representation/structure.py +814 -0
  13. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0/src/dcatoolkit.egg-info}/PKG-INFO +120 -73
  14. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/src/dcatoolkit.egg-info/SOURCES.txt +9 -2
  15. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/src/dcatoolkit.egg-info/requires.txt +5 -4
  16. dcatoolkit-0.4.0/tests/test_alignments.py +170 -0
  17. dcatoolkit-0.4.0/tests/test_analytics.py +36 -0
  18. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/tests/test_contacts.py +95 -94
  19. dcatoolkit-0.4.0/tests/test_di.py +131 -0
  20. dcatoolkit-0.4.0/tests/test_pairs.py +195 -0
  21. dcatoolkit-0.4.0/tests/test_structure.py +37 -0
  22. dcatoolkit-0.2.3/README.md +0 -17
  23. dcatoolkit-0.2.3/pyproject.toml +0 -54
  24. dcatoolkit-0.2.3/src/dcatoolkit/__init__.py +0 -6
  25. dcatoolkit-0.2.3/src/dcatoolkit/analytics.py +0 -207
  26. dcatoolkit-0.2.3/src/dcatoolkit/representation.py +0 -1357
  27. dcatoolkit-0.2.3/tests/test_alignments.py +0 -88
  28. dcatoolkit-0.2.3/tests/test_sequence_numbering.py +0 -14
  29. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/src/dcatoolkit.egg-info/dependency_links.txt +0 -0
  30. {dcatoolkit-0.2.3 → dcatoolkit-0.4.0}/src/dcatoolkit.egg-info/top_level.txt +0 -0
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Raheel Syed Ahmed
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Raheel Syed Ahmed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,73 +1,120 @@
1
- Metadata-Version: 2.4
2
- Name: dcatoolkit
3
- Version: 0.2.3
4
- Summary: Collection of useful modules and representations for managing DCA output data.
5
- Author-email: Raheel Syed Ahmed <raheelsyedahmed@gmail.com>
6
- Maintainer-email: Raheel Syed Ahmed <raheelsyedahmed@gmail.com>
7
- License: MIT License
8
-
9
- Copyright (c) 2024 Raheel Syed Ahmed
10
-
11
- Permission is hereby granted, free of charge, to any person obtaining a copy
12
- of this software and associated documentation files (the "Software"), to deal
13
- in the Software without restriction, including without limitation the rights
14
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
- copies of the Software, and to permit persons to whom the Software is
16
- furnished to do so, subject to the following conditions:
17
-
18
- The above copyright notice and this permission notice shall be included in all
19
- copies or substantial portions of the Software.
20
-
21
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
- SOFTWARE.
28
-
29
- Keywords: dca,toolkit,DI,coevolution
30
- Classifier: Development Status :: 4 - Beta
31
- Classifier: Intended Audience :: Science/Research
32
- Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
33
- Classifier: License :: OSI Approved :: MIT License
34
- Classifier: Programming Language :: Python :: 3
35
- Classifier: Programming Language :: Python :: 3.10
36
- Classifier: Programming Language :: Python :: 3.11
37
- Classifier: Programming Language :: Python :: 3.12
38
- Requires-Python: >=3.10
39
- Description-Content-Type: text/markdown
40
- License-File: LICENSE
41
- Requires-Dist: biotite>=1.0.1
42
- Requires-Dist: matplotlib>=3.8.0
43
- Requires-Dist: numpy>=1.26.0
44
- Requires-Dist: pandas>=2.1.0
45
- Requires-Dist: scikit-learn>=1.3
46
- Requires-Dist: scipy>=1.11.0
47
- Provides-Extra: tests
48
- Requires-Dist: pytest; extra == "tests"
49
- Provides-Extra: docs
50
- Requires-Dist: sphinx; extra == "docs"
51
- Requires-Dist: pdoc; extra == "docs"
52
- Requires-Dist: numpydoc; extra == "docs"
53
- Provides-Extra: lint
54
- Requires-Dist: ruffle; extra == "lint"
55
- Dynamic: license-file
56
-
57
- # dcatoolkit
58
- Collection of useful modules and representations for managing DCA output data.
59
-
60
- ## Major Sections
61
- ### Representations
62
- * Use Pairs to load lists, tuples, sets, and ndarrays with the correct orientation of elements. This will allow you to yield integer pairs that can be mirrored (where y becomes x and vice versa) and to subset various pairs.
63
- * Use DirectInformationData to create 3-column structured ndarrays that can be sorted by "DI", mapped to a protein with a ResidueAlignment, and used to generate output for other programs (including UCSF Chimera)
64
- * Use ResidueAlignment to generate a reference map. Indices of one sequence of characters can be linked to their corresponding indices of the other sequence of characters. The dictionaries produced, domain-to-protein and protein-to-domain, allow for forward mapping and backmapping.
65
- * Use StructureInformation to find contacts in a protein structure and find atomic information related to specific pairs of interest.
66
- ### Analytics
67
- * Use MSATools to load in Multiple Sequence Alignment (MSA) data and provide functionality including generating frequency statistics on "gappiness" in the MSA and filtering and cleaning MSAs.
68
-
69
-
70
- ## Diagram of Hidden Markov Machine & Direct Coupling Analysis Pipeline
71
- <p align="center">
72
- <img src="https://github.com/user-attachments/assets/4768e08f-d513-4dbf-abc5-c80c1b3d42aa"/>
73
- </p>
1
+ Metadata-Version: 2.4
2
+ Name: dcatoolkit
3
+ Version: 0.4.0
4
+ Summary: Collection of useful modules and representations for managing DCA output data.
5
+ Author-email: Raheel Syed Ahmed <raheelsyedahmed@gmail.com>
6
+ Maintainer-email: Raheel Syed Ahmed <raheelsyedahmed@gmail.com>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2024 Raheel Syed Ahmed
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Project-URL: Homepage, https://github.com/RaheelSyedAhmed/dcatoolkit
30
+ Project-URL: Changelog, https://github.com/RaheelSyedAhmed/dcatoolkit/blob/main/CHANGELOG.md
31
+ Project-URL: Issues, https://github.com/RaheelSyedAhmed/dcatoolkit/issues
32
+ Keywords: dca,toolkit,DI,coevolution
33
+ Classifier: Development Status :: 4 - Beta
34
+ Classifier: Intended Audience :: Science/Research
35
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3.12
39
+ Requires-Python: >=3.12
40
+ Description-Content-Type: text/markdown
41
+ License-File: LICENSE
42
+ Requires-Dist: biotite>=1.7
43
+ Requires-Dist: numpy>=1.26.0
44
+ Requires-Dist: pandas>=2.1.0
45
+ Requires-Dist: scipy>=1.11.0
46
+ Provides-Extra: tests
47
+ Requires-Dist: pytest; extra == "tests"
48
+ Provides-Extra: docs
49
+ Requires-Dist: sphinx; extra == "docs"
50
+ Requires-Dist: pdoc; extra == "docs"
51
+ Requires-Dist: numpydoc; extra == "docs"
52
+ Provides-Extra: lint
53
+ Requires-Dist: ruff; extra == "lint"
54
+ Provides-Extra: plot
55
+ Requires-Dist: matplotlib>=3.10.9; extra == "plot"
56
+ Dynamic: license-file
57
+
58
+ # dcatoolkit
59
+ Collection of useful modules and representations for managing DCA output data.
60
+
61
+ ## Installation
62
+
63
+ ```bash
64
+ pip install dcatoolkit
65
+
66
+ # optional: adds matplotlib for the plotting example"
67
+ pip install "dcatoolkit[plot]"
68
+ ```
69
+
70
+ Requires Python 3.12+.
71
+ Upgrading from 0.2.x? See the [changelog](https://github.com/RaheelSyedAhmed/dcatoolkit/blob/main/CHANGELOG.md).
72
+
73
+ ## Major Sections
74
+ ### Representations
75
+ * Use Pairs to load lists, tuples, sets, and ndarrays with the correct orientation of elements. This will allow you to store integer pairs, in the form of structured arrays with fields `residue1` and `residue2` that can be mirrored (where y becomes x and vice versa) and subset.
76
+ * Use DirectInformationData to create structured ndarrays with `residue1`, `residue2`, and `DI` fields that can be sorted by `DI`, mapped to a protein with a ResidueAlignment, and used to generate output for other programs (including UCSF Chimera)
77
+ * Use ResidueAlignment to generate a reference map. Indices of one sequence of characters can be linked to their corresponding indices of the other sequence of characters. The dictionaries produced, domain-to-protein and protein-to-domain, allow for forward mapping and backmapping.
78
+ * Use StructureInformation to find contacts in a protein structure and find atomic information related to specific pairs of interest. It can read in PDBx/mmCIF and PDB files or fetch them from RCSB and find contacts between residues.
79
+ ### Analytics
80
+ * Use MSATools to load in Multiple Sequence Alignment (MSA) data and provide functionality including generating frequency statistics on "gappiness" in the MSA and filtering and cleaning MSAs.
81
+
82
+
83
+ ## Quick Start
84
+ ```python
85
+ from dcatoolkit import DirectInformationData, ResidueAlignment, StructureInformation
86
+
87
+ # Rank DI pairs and map them from MSA (domain) numbering onto the protein sequence.
88
+ di = DirectInformationData.load_from_DI_file("my_dca_output.DI")
89
+ alignment = ResidueAlignment.load_from_align_file("my_domain.align")
90
+ top_pairs = di.get_ranked_mapped_pairs(alignment, alignment, number=50)
91
+
92
+ # Compare the top pairs with residue contacts in a structure.
93
+ structure = StructureInformation.fetch_pdb("2KLL")
94
+ contacts = structure.get_contacts(ca_only=False, threshold=8, chain1="A", chain2="A")
95
+ hits = [pair for pair in top_pairs.tolist() if pair in contacts]
96
+ ```
97
+
98
+ ## Diagram of Hidden Markov Model & Direct Coupling Analysis Pipeline
99
+ <p align="center">
100
+ <img src="https://github.com/user-attachments/assets/4768e08f-d513-4dbf-abc5-c80c1b3d42aa"/>
101
+ </p>
102
+
103
+ ## Development
104
+
105
+ This project uses [uv](https://docs.astral.sh/uv/) for dependency management.
106
+
107
+ ```bash
108
+ git clone https://github.com/RaheelSyedAhmed/dcatoolkit.git
109
+ cd dcatoolkit
110
+ uv sync --all-extras
111
+ ```
112
+
113
+ Run the test suite (requires internet to fetch from RCSB):
114
+
115
+ ```bash
116
+ uv run pytest
117
+
118
+ uv sync --all-extras # Installs packages from tests, docs, lint, and plot.
119
+ uv run ruff check # linting
120
+ ```
@@ -0,0 +1,63 @@
1
+ # dcatoolkit
2
+ Collection of useful modules and representations for managing DCA output data.
3
+
4
+ ## Installation
5
+
6
+ ```bash
7
+ pip install dcatoolkit
8
+
9
+ # optional: adds matplotlib for the plotting example"
10
+ pip install "dcatoolkit[plot]"
11
+ ```
12
+
13
+ Requires Python 3.12+.
14
+ Upgrading from 0.2.x? See the [changelog](https://github.com/RaheelSyedAhmed/dcatoolkit/blob/main/CHANGELOG.md).
15
+
16
+ ## Major Sections
17
+ ### Representations
18
+ * Use Pairs to load lists, tuples, sets, and ndarrays with the correct orientation of elements. This will allow you to store integer pairs, in the form of structured arrays with fields `residue1` and `residue2` that can be mirrored (where y becomes x and vice versa) and subset.
19
+ * Use DirectInformationData to create structured ndarrays with `residue1`, `residue2`, and `DI` fields that can be sorted by `DI`, mapped to a protein with a ResidueAlignment, and used to generate output for other programs (including UCSF Chimera)
20
+ * Use ResidueAlignment to generate a reference map. Indices of one sequence of characters can be linked to their corresponding indices of the other sequence of characters. The dictionaries produced, domain-to-protein and protein-to-domain, allow for forward mapping and backmapping.
21
+ * Use StructureInformation to find contacts in a protein structure and find atomic information related to specific pairs of interest. It can read in PDBx/mmCIF and PDB files or fetch them from RCSB and find contacts between residues.
22
+ ### Analytics
23
+ * Use MSATools to load in Multiple Sequence Alignment (MSA) data and provide functionality including generating frequency statistics on "gappiness" in the MSA and filtering and cleaning MSAs.
24
+
25
+
26
+ ## Quick Start
27
+ ```python
28
+ from dcatoolkit import DirectInformationData, ResidueAlignment, StructureInformation
29
+
30
+ # Rank DI pairs and map them from MSA (domain) numbering onto the protein sequence.
31
+ di = DirectInformationData.load_from_DI_file("my_dca_output.DI")
32
+ alignment = ResidueAlignment.load_from_align_file("my_domain.align")
33
+ top_pairs = di.get_ranked_mapped_pairs(alignment, alignment, number=50)
34
+
35
+ # Compare the top pairs with residue contacts in a structure.
36
+ structure = StructureInformation.fetch_pdb("2KLL")
37
+ contacts = structure.get_contacts(ca_only=False, threshold=8, chain1="A", chain2="A")
38
+ hits = [pair for pair in top_pairs.tolist() if pair in contacts]
39
+ ```
40
+
41
+ ## Diagram of Hidden Markov Model & Direct Coupling Analysis Pipeline
42
+ <p align="center">
43
+ <img src="https://github.com/user-attachments/assets/4768e08f-d513-4dbf-abc5-c80c1b3d42aa"/>
44
+ </p>
45
+
46
+ ## Development
47
+
48
+ This project uses [uv](https://docs.astral.sh/uv/) for dependency management.
49
+
50
+ ```bash
51
+ git clone https://github.com/RaheelSyedAhmed/dcatoolkit.git
52
+ cd dcatoolkit
53
+ uv sync --all-extras
54
+ ```
55
+
56
+ Run the test suite (requires internet to fetch from RCSB):
57
+
58
+ ```bash
59
+ uv run pytest
60
+
61
+ uv sync --all-extras # Installs packages from tests, docs, lint, and plot.
62
+ uv run ruff check # linting
63
+ ```
@@ -0,0 +1,84 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dcatoolkit"
7
+ version = "0.4.0"
8
+ description = "Collection of useful modules and representations for managing DCA output data."
9
+ keywords = ["dca", "toolkit", "DI", "coevolution"]
10
+
11
+ readme = "README.md"
12
+ license = {file = "LICENSE"}
13
+
14
+ requires-python = ">=3.12"
15
+
16
+ authors = [
17
+ {name = "Raheel Syed Ahmed", email = "raheelsyedahmed@gmail.com"}
18
+ ]
19
+ maintainers = [
20
+ {name = "Raheel Syed Ahmed", email = "raheelsyedahmed@gmail.com"}
21
+ ]
22
+
23
+ dependencies = [
24
+ "biotite>=1.7",
25
+ "numpy>=1.26.0",
26
+ "pandas>=2.1.0",
27
+ "scipy>=1.11.0",
28
+ ]
29
+
30
+ classifiers = [
31
+ "Development Status :: 4 - Beta",
32
+ "Intended Audience :: Science/Research",
33
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
34
+ "License :: OSI Approved :: MIT License",
35
+ "Programming Language :: Python :: 3",
36
+ "Programming Language :: Python :: 3.12",
37
+ ]
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/RaheelSyedAhmed/dcatoolkit"
41
+ Changelog = "https://github.com/RaheelSyedAhmed/dcatoolkit/blob/main/CHANGELOG.md"
42
+ Issues = "https://github.com/RaheelSyedAhmed/dcatoolkit/issues"
43
+
44
+ [project.optional-dependencies]
45
+ tests = [
46
+ "pytest",
47
+ ]
48
+ docs = [
49
+ "sphinx",
50
+ "pdoc",
51
+ "numpydoc"
52
+ ]
53
+ lint = [
54
+ "ruff",
55
+ ]
56
+ plot = [
57
+ "matplotlib>=3.10.9",
58
+ ]
59
+ [tool.ruff]
60
+ # The target Python version is inferred from requires-python above.
61
+ # Lint the package and its tests; examples are standalone scripts.
62
+ extend-exclude = [
63
+ "examples",
64
+ # Python 2 scripts that generated the reference contact files in tests/pdb_info; not valid Python 3.
65
+ "tests/pdb_info/interface_contacts_allatom_args.py",
66
+ "tests/pdb_info/interface_contacts_calpha_args.py",
67
+ ]
68
+
69
+ [tool.ruff.lint]
70
+ # Explicit rule selection, so results don't change with ruff's defaults between versions.
71
+ select = [
72
+ "E4", "E7", "E9", # pycodestyle errors: imports, statements, syntax
73
+ "F", # Pyflakes: unused imports/variables, undefined names
74
+ "B", # flake8-bugbear: likely bugs
75
+ "I", # isort: import ordering
76
+ "UP", # pyupgrade: modern syntax for the target Python version
77
+ "C4", # flake8-comprehensions
78
+ "SIM", # flake8-simplify
79
+ "PIE", # flake8-pie: unnecessary code
80
+ "RUF", # Ruff-specific rules
81
+ ]
82
+ ignore = [
83
+ "B905", # zip() without strict=: most zips are equal-length by construction, and ResidueAlignment deliberately truncates mismatched align texts.
84
+ ]
@@ -1,4 +1,4 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,15 @@
1
+
2
+ from importlib.metadata import version as _version
3
+
4
+ __version__ = _version("dcatoolkit")
5
+ from .analytics import MSATools
6
+ from .representation import (
7
+ DirectInformationData,
8
+ MMCIFInformation,
9
+ Pairs,
10
+ PDBInformation,
11
+ ResidueAlignment,
12
+ StructureInformation,
13
+ )
14
+
15
+ __all__ = ['DirectInformationData', 'MMCIFInformation', 'MSATools', 'PDBInformation', 'Pairs', 'ResidueAlignment', 'StructureInformation']
@@ -0,0 +1,230 @@
1
+ import io
2
+ import re
3
+ import string
4
+ from collections import Counter
5
+ from collections.abc import Callable
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+ import numpy as np
10
+ import numpy.typing as npt
11
+
12
+
13
+ class MSATools:
14
+ """
15
+ Tools and interface for encapsulating MSA data and providing functionality for filtering and analysis.
16
+
17
+ Parameters
18
+ ----------
19
+ MSA : list of tuple of (str, str)
20
+ Loaded MSA that is a list of tuples where the first element is the header (including its leading ``">"``) and the second element is its corresponding sequence.
21
+
22
+ Attributes
23
+ ----------
24
+ MSA : list of tuple of (str, str)
25
+ The `MSA` supplied.
26
+ """
27
+ _GAP_CLEANUP_TABLE = str.maketrans('', '', string.ascii_lowercase + ".")
28
+
29
+ def __init__(self, MSA: list[tuple[str, str]]):
30
+ self.MSA = MSA
31
+
32
+ @staticmethod
33
+ def load_from_file(msa_source: str | io.IOBase | Path) -> 'MSATools':
34
+ """
35
+ Generates MSATools object from an MSA file in aligned FASTA (``.afa``) format.
36
+
37
+ Parameters
38
+ ----------
39
+ msa_source : str or pathlib.Path or io.BytesIO or io.TextIOBase
40
+ Filepath, or in-memory bytes or text stream, of the MSA in ``.afa`` format. Streams are read from the beginning.
41
+
42
+ Returns
43
+ -------
44
+ MSATools
45
+ An MSATools instance with the appropriate list of ``(header, sequence)`` tuples where sequences are simplified and converted to single line format.
46
+
47
+ Raises
48
+ ------
49
+ TypeError
50
+ If `msa_source` is not a filepath, ``io.BytesIO``, or ``io.TextIOBase``.
51
+
52
+ Notes
53
+ -----
54
+ Windows (``\\r\\n``) and old Mac (``\\r``) line endings are normalized to ``\\n`` before parsing. Headers keep their leading ``">"``.
55
+ """
56
+ data = ""
57
+ msa_entries: list[tuple[str, str]] = []
58
+ if isinstance(msa_source, (str, Path)):
59
+ with open(msa_source) as fs:
60
+ data = fs.read()
61
+ elif isinstance(msa_source, io.BytesIO):
62
+ data = msa_source.getvalue().decode()
63
+ elif isinstance(msa_source, io.TextIOBase):
64
+ msa_source.seek(0)
65
+ data = msa_source.read()
66
+ else:
67
+ raise TypeError("msa_file is not bytesIO, a TextIO, or a filepath.")
68
+
69
+ data = data.replace("\r\n", "\n").replace("\r", "\n")
70
+ split_data = data.split(">")[1:]
71
+ for entry in split_data:
72
+ header, _, rest = entry.partition("\n")
73
+ sequence = rest.replace("\n", "")
74
+ msa_entries.append((">"+header, sequence))
75
+ return MSATools(msa_entries)
76
+
77
+ @staticmethod
78
+ def get_sequence_max_cont_gaps(sequence: str) -> int:
79
+ """
80
+ Find maximum number of continuous gaps in a specific sequence.
81
+
82
+ Parameters
83
+ ----------
84
+ sequence : str
85
+ Sequence of characters, potentially containing multiple of ``"-"``, a gap character.
86
+
87
+ Returns
88
+ -------
89
+ int
90
+ The maximum number of continuous gaps (``"-"``) in a sequence, or 0 if there are none. Other characters, such as ``"."``, break a run of gaps.
91
+ """
92
+ return max((m.end() - m.start() for m in re.finditer(r"-+", sequence)), default=0)
93
+
94
+ def gap_frequency(self) -> tuple[dict[int, int], dict[int, float]]:
95
+ """
96
+ Calculates the frequency of maximum continuous gaps throughout the MSA where the key corresponds to the number of continuous gaps and the value corresponds to the number of sequences or the cumulative fraction of sequences.
97
+
98
+ Returns
99
+ -------
100
+ tuple of (dict of {int : int}, dict of {int : float})
101
+ Two element tuple where the first element maps each maximum continuous gap length to the number of sequences with it, and the second element maps it to the cumulative fraction (0 to 1) of sequences with that maximum or fewer.
102
+
103
+ See Also
104
+ --------
105
+ get_sequence_max_cont_gaps : Computes each sequence's maximum continuous gap length.
106
+ filter_by_continuous_gaps : Filters sequences by that length.
107
+
108
+ Notes
109
+ -----
110
+ Gaps are counted on the sequences as stored. To match the counts `filter_by_continuous_gaps()` uses, run this on an already filtered MSA, e.g. ``MSATools(msa.filter_by_continuous_gaps()).gap_frequency()``.
111
+ """
112
+ max_gap_counts = []
113
+ for _header, sequence in self.MSA:
114
+ max_gap_counts.append(MSATools.get_sequence_max_cont_gaps(sequence))
115
+ frequency_count_dict = dict(Counter(max_gap_counts))
116
+ cumul_perc_dict = {}
117
+ cumul_count = 0
118
+ for key in sorted(frequency_count_dict.keys()):
119
+ value = frequency_count_dict[key]
120
+ cumul_count += value
121
+ cumul_perc_dict[key] = cumul_count / len(self.MSA)
122
+ return (frequency_count_dict, cumul_perc_dict)
123
+
124
+ def filter_by_continuous_gaps(self, max_gaps: int | None=None) -> list[tuple[str, str]]:
125
+ """
126
+ Filter out entries in your MSA by the number of maximum continuous gaps specified unless None is provided. Also, removes ``"."`` characters and lowercase letters (insert positions) from the sequence.
127
+
128
+ Parameters
129
+ ----------
130
+ max_gaps : int, optional
131
+ The maximum allowed number of continuous gaps in a sequence. If None, no entries are removed, but sequences are still cleaned.
132
+
133
+ Returns
134
+ -------
135
+ list of tuple of (str, str)
136
+ List of entries that are valid in that their sequences' number of maximum continuous gaps is within the threshold supplied as `max_gaps`. Wrap it in ``MSATools(...)`` to keep working with it as an MSA.
137
+
138
+ Notes
139
+ -----
140
+ Insert characters are removed before gaps are counted, so gap runs that were separated only by ``"."`` or lowercase letters count as one run.
141
+ """
142
+ kept_entries = []
143
+ for header, sequence in self.MSA:
144
+ sequence = sequence.translate(MSATools._GAP_CLEANUP_TABLE)
145
+ if max_gaps is None or MSATools.get_sequence_max_cont_gaps(sequence) <= max_gaps:
146
+ kept_entries.append((header, sequence))
147
+ return kept_entries
148
+
149
+ def gap_proportion(self, agg_func: Callable[..., float | int]=np.mean, axis: Literal[0, 1] = 0) -> float | int:
150
+ """
151
+ Evaluates the gap proportion per alignment position (column) or per sequence (row) in the MSA, then aggregates it into one value.
152
+
153
+ Parameters
154
+ ----------
155
+ agg_func : callable, default numpy.mean
156
+ The aggregation function applied to get the expected result, usually a mean, max, or min value, of the gap proportions.
157
+ axis : {0, 1}, default 0
158
+ When `axis` is 0, gap proportions are computed per column, over every sequence in that column. When `axis` is 1, they are computed per row, over every column in that sequence.
159
+
160
+ Returns
161
+ -------
162
+ float or int
163
+ A numerical value determined by `agg_func` over the gap proportions.
164
+
165
+ Notes
166
+ -----
167
+ Any character that is not an ASCII letter (e.g. ``"-"`` or ``"."``) counts as a gap. All sequences must have the same length, as in an unfiltered or a filtered MSA.
168
+ """
169
+ num_rows = len(self.MSA)
170
+ num_cols = len(self.MSA[0][1])
171
+ flat = np.frombuffer("".join(seq for _, seq in self.MSA).encode("ascii"), dtype=np.uint8).reshape(num_rows, num_cols)
172
+ is_alpha = ((flat >= 65) & (flat <= 90)) | ((flat >= 97) & (flat <= 122))
173
+ non_alpha_counts = np.sum(~is_alpha, axis) / flat.shape[axis]
174
+ return agg_func(non_alpha_counts)
175
+
176
+ def write(self, destination: str | Path | io.TextIOBase) -> None:
177
+ """
178
+ Writes this MSA's headers and sequences to the destination specified, each header followed by its sequence on a single line.
179
+
180
+ Parameters
181
+ ----------
182
+ destination : str or pathlib.Path or io.TextIOBase
183
+ Filepath or writable text stream to write the MSA to.
184
+
185
+ Raises
186
+ ------
187
+ TypeError
188
+ If `destination` is not a filepath or a writable ``io.TextIOBase``.
189
+ """
190
+ lines = (f"{header}\n{sequence}\n" for header, sequence in self.MSA)
191
+ if isinstance(destination, (str, Path)):
192
+ with open(destination, 'w') as fs:
193
+ fs.writelines(lines)
194
+ elif isinstance(destination, io.TextIOBase) and destination.writable():
195
+ destination.writelines(lines)
196
+ else:
197
+ raise TypeError(f"Destination supplied is either not a filepath or is not a writeable TextIO object (got {type(destination).__name__}).")
198
+
199
+ def as_matrix(self) -> npt.NDArray:
200
+ """
201
+ Represents the MSA as a numpy matrix of sequences.
202
+
203
+ Returns
204
+ -------
205
+ numpy.ndarray
206
+ A ``<U1`` (one-character string) matrix with one row per sequence and one column per alignment position. Each cell is the sequence character for that sequence at that position.
207
+ """
208
+ return np.array([list(seq) for _, seq in self.MSA])
209
+
210
+ def __str__(self) -> str:
211
+ """
212
+ Returns the sequences present in the loaded MSA in string format.
213
+
214
+ Returns
215
+ -------
216
+ str
217
+ Each sequence in the instance separated with newline characters.
218
+ """
219
+ return "\n".join([seq for _, seq in self.MSA])
220
+
221
+ def __len__(self):
222
+ """
223
+ Returns the number of sequences, and equivalently, the number of headers in the MSA.
224
+
225
+ Returns
226
+ -------
227
+ int
228
+ Length of the MSA list of ``(header, sequence)`` tuples.
229
+ """
230
+ return len(self.MSA)
@@ -0,0 +1,6 @@
1
+ from .alignment import ResidueAlignment
2
+ from .di import DirectInformationData
3
+ from .pairs import Pairs
4
+ from .structure import MMCIFInformation, PDBInformation, StructureInformation
5
+
6
+ __all__ = ['DirectInformationData', 'MMCIFInformation', 'PDBInformation', 'Pairs', 'ResidueAlignment', 'StructureInformation']