damicore-tree-builder 0.1.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.
- damicore_tree_builder-0.1.0/.gitignore +224 -0
- damicore_tree_builder-0.1.0/LICENSE +201 -0
- damicore_tree_builder-0.1.0/PKG-INFO +64 -0
- damicore_tree_builder-0.1.0/README.md +35 -0
- damicore_tree_builder-0.1.0/pyproject.toml +60 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/__init__.py +16 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/api.py +116 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/artifacts.py +68 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/config.py +7 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/errors.py +10 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/models.py +41 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/neighbor_joining.py +175 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/newick.py +67 -0
- damicore_tree_builder-0.1.0/src/damicore_tree_builder/py.typed +0 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
|
|
42
|
+
# Local scratch / generated output (never commit)
|
|
43
|
+
.temp/
|
|
44
|
+
.tox/
|
|
45
|
+
.nox/
|
|
46
|
+
.coverage
|
|
47
|
+
.coverage.*
|
|
48
|
+
.cache
|
|
49
|
+
nosetests.xml
|
|
50
|
+
coverage.xml
|
|
51
|
+
*.cover
|
|
52
|
+
*.py.cover
|
|
53
|
+
.hypothesis/
|
|
54
|
+
.pytest_cache/
|
|
55
|
+
cover/
|
|
56
|
+
|
|
57
|
+
# Translations
|
|
58
|
+
*.mo
|
|
59
|
+
*.pot
|
|
60
|
+
|
|
61
|
+
# Django stuff:
|
|
62
|
+
*.log
|
|
63
|
+
local_settings.py
|
|
64
|
+
db.sqlite3
|
|
65
|
+
db.sqlite3-journal
|
|
66
|
+
|
|
67
|
+
# Flask stuff:
|
|
68
|
+
instance/
|
|
69
|
+
.webassets-cache
|
|
70
|
+
|
|
71
|
+
# Scrapy stuff:
|
|
72
|
+
.scrapy
|
|
73
|
+
|
|
74
|
+
# Sphinx documentation
|
|
75
|
+
docs/_build/
|
|
76
|
+
|
|
77
|
+
# PyBuilder
|
|
78
|
+
.pybuilder/
|
|
79
|
+
target/
|
|
80
|
+
|
|
81
|
+
# Jupyter Notebook
|
|
82
|
+
.ipynb_checkpoints
|
|
83
|
+
|
|
84
|
+
# IPython
|
|
85
|
+
profile_default/
|
|
86
|
+
ipython_config.py
|
|
87
|
+
|
|
88
|
+
# pyenv
|
|
89
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
90
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
91
|
+
# .python-version
|
|
92
|
+
|
|
93
|
+
# pipenv
|
|
94
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
95
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
96
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
97
|
+
# install all needed dependencies.
|
|
98
|
+
#Pipfile.lock
|
|
99
|
+
|
|
100
|
+
# UV
|
|
101
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
102
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
103
|
+
# commonly ignored for libraries.
|
|
104
|
+
#uv.lock
|
|
105
|
+
|
|
106
|
+
# poetry
|
|
107
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
108
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
109
|
+
# commonly ignored for libraries.
|
|
110
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
111
|
+
#poetry.lock
|
|
112
|
+
#poetry.toml
|
|
113
|
+
|
|
114
|
+
# pdm
|
|
115
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
116
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
117
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
118
|
+
#pdm.lock
|
|
119
|
+
#pdm.toml
|
|
120
|
+
.pdm-python
|
|
121
|
+
.pdm-build/
|
|
122
|
+
|
|
123
|
+
# pixi
|
|
124
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
125
|
+
#pixi.lock
|
|
126
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
127
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
128
|
+
.pixi
|
|
129
|
+
|
|
130
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
131
|
+
__pypackages__/
|
|
132
|
+
|
|
133
|
+
# Celery stuff
|
|
134
|
+
celerybeat-schedule
|
|
135
|
+
celerybeat.pid
|
|
136
|
+
|
|
137
|
+
# SageMath parsed files
|
|
138
|
+
*.sage.py
|
|
139
|
+
|
|
140
|
+
# Environments
|
|
141
|
+
.env
|
|
142
|
+
.envrc
|
|
143
|
+
.venv
|
|
144
|
+
env/
|
|
145
|
+
venv/
|
|
146
|
+
ENV/
|
|
147
|
+
env.bak/
|
|
148
|
+
venv.bak/
|
|
149
|
+
|
|
150
|
+
# Spyder project settings
|
|
151
|
+
.spyderproject
|
|
152
|
+
.spyproject
|
|
153
|
+
|
|
154
|
+
# Rope project settings
|
|
155
|
+
.ropeproject
|
|
156
|
+
|
|
157
|
+
# mkdocs documentation
|
|
158
|
+
/site
|
|
159
|
+
|
|
160
|
+
# mypy
|
|
161
|
+
.mypy_cache/
|
|
162
|
+
.dmypy.json
|
|
163
|
+
dmypy.json
|
|
164
|
+
|
|
165
|
+
# Pyre type checker
|
|
166
|
+
.pyre/
|
|
167
|
+
|
|
168
|
+
# pytype static type analyzer
|
|
169
|
+
.pytype/
|
|
170
|
+
|
|
171
|
+
# Cython debug symbols
|
|
172
|
+
cython_debug/
|
|
173
|
+
|
|
174
|
+
# PyCharm
|
|
175
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
176
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
177
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
178
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
179
|
+
#.idea/
|
|
180
|
+
|
|
181
|
+
# Abstra
|
|
182
|
+
# Abstra is an AI-powered process automation framework.
|
|
183
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
184
|
+
# Learn more at https://abstra.io/docs
|
|
185
|
+
.abstra/
|
|
186
|
+
|
|
187
|
+
# Visual Studio Code
|
|
188
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
189
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
190
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
191
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
192
|
+
# .vscode/
|
|
193
|
+
|
|
194
|
+
# Ruff stuff:
|
|
195
|
+
.ruff_cache/
|
|
196
|
+
|
|
197
|
+
# PyPI configuration file
|
|
198
|
+
.pypirc
|
|
199
|
+
|
|
200
|
+
# Cursor
|
|
201
|
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
|
202
|
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
|
203
|
+
# refer to https://docs.cursor.com/context/ignore-files
|
|
204
|
+
.cursorignore
|
|
205
|
+
.cursorindexingignore
|
|
206
|
+
|
|
207
|
+
# Marimo
|
|
208
|
+
marimo/_static/
|
|
209
|
+
marimo/_lsp/
|
|
210
|
+
__marimo__/
|
|
211
|
+
|
|
212
|
+
# LaTeX build artefacts (papers)
|
|
213
|
+
models/**/paper/*.aux
|
|
214
|
+
models/**/paper/*.bbl
|
|
215
|
+
models/**/paper/*.bcf
|
|
216
|
+
models/**/paper/*.blg
|
|
217
|
+
models/**/paper/*.fdb_latexmk
|
|
218
|
+
models/**/paper/*.fls
|
|
219
|
+
models/**/paper/*.log
|
|
220
|
+
models/**/paper/*.out
|
|
221
|
+
models/**/paper/*.run.xml
|
|
222
|
+
models/**/paper/*.synctex.gz
|
|
223
|
+
models/**/paper/*.toc
|
|
224
|
+
models/**/paper/*.pdf
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Ennio Politi Lopes
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: damicore-tree-builder
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Neighbor-Joining tree builder for the DAMICORE pipeline.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Delbem-Research-and-Innovation/damicore
|
|
6
|
+
Project-URL: Repository, https://github.com/Delbem-Research-and-Innovation/damicore
|
|
7
|
+
Project-URL: Issues, https://github.com/Delbem-Research-and-Innovation/damicore/issues
|
|
8
|
+
Project-URL: Documentation, https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md
|
|
9
|
+
Project-URL: Changelog, https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Ennio Politi Lopes <enniolopes@users.noreply.github.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: damicore,neighbor-joining,newick,phylogenetics,tree
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: <3.15,>=3.11
|
|
26
|
+
Requires-Dist: numpy<3,>=1.26
|
|
27
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# damicore-tree-builder
|
|
31
|
+
|
|
32
|
+
damicore-tree-builder builds a deterministic Neighbor Joining tree from a
|
|
33
|
+
distance matrix and its labels. It is the third stage of the DAMICORE pipeline;
|
|
34
|
+
most users install the aggregate `damicore` distribution, which runs all four
|
|
35
|
+
stages end to end. Install this package alone to build trees without the rest of
|
|
36
|
+
the pipeline.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install damicore-tree-builder
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Python
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from damicore_tree_builder import build_tree
|
|
46
|
+
|
|
47
|
+
result = build_tree("distance.npy", "labels.json", "run")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`distance.npy` and `labels.json` are produced by the sibling `damicore-distance`
|
|
51
|
+
distribution; the call writes `tree.json` plus Newick, and `tree.json` is the
|
|
52
|
+
input the sibling `damicore-clusterizer` distribution consumes. The path API
|
|
53
|
+
copies into a temporary memory map, reuses slots, evaluates Q pairwise without
|
|
54
|
+
materializing it, and preserves negative branches. `neighbor_joining(matrix,
|
|
55
|
+
labels)` is available for small in-memory matrices.
|
|
56
|
+
|
|
57
|
+
## Links
|
|
58
|
+
|
|
59
|
+
- Repository: <https://github.com/Delbem-Research-and-Innovation/damicore>
|
|
60
|
+
- Issues: <https://github.com/Delbem-Research-and-Innovation/damicore/issues>
|
|
61
|
+
- Documentation:
|
|
62
|
+
<https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md>
|
|
63
|
+
|
|
64
|
+
Licensed under Apache-2.0.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# damicore-tree-builder
|
|
2
|
+
|
|
3
|
+
damicore-tree-builder builds a deterministic Neighbor Joining tree from a
|
|
4
|
+
distance matrix and its labels. It is the third stage of the DAMICORE pipeline;
|
|
5
|
+
most users install the aggregate `damicore` distribution, which runs all four
|
|
6
|
+
stages end to end. Install this package alone to build trees without the rest of
|
|
7
|
+
the pipeline.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install damicore-tree-builder
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Python
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from damicore_tree_builder import build_tree
|
|
17
|
+
|
|
18
|
+
result = build_tree("distance.npy", "labels.json", "run")
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`distance.npy` and `labels.json` are produced by the sibling `damicore-distance`
|
|
22
|
+
distribution; the call writes `tree.json` plus Newick, and `tree.json` is the
|
|
23
|
+
input the sibling `damicore-clusterizer` distribution consumes. The path API
|
|
24
|
+
copies into a temporary memory map, reuses slots, evaluates Q pairwise without
|
|
25
|
+
materializing it, and preserves negative branches. `neighbor_joining(matrix,
|
|
26
|
+
labels)` is available for small in-memory matrices.
|
|
27
|
+
|
|
28
|
+
## Links
|
|
29
|
+
|
|
30
|
+
- Repository: <https://github.com/Delbem-Research-and-Innovation/damicore>
|
|
31
|
+
- Issues: <https://github.com/Delbem-Research-and-Innovation/damicore/issues>
|
|
32
|
+
- Documentation:
|
|
33
|
+
<https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md>
|
|
34
|
+
|
|
35
|
+
Licensed under Apache-2.0.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "damicore-tree-builder"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Neighbor-Joining tree builder for the DAMICORE pipeline."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Ennio Politi Lopes", email = "enniolopes@users.noreply.github.com" }]
|
|
9
|
+
requires-python = ">=3.11,<3.15"
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 4 - Beta",
|
|
12
|
+
"Intended Audience :: Science/Research",
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
15
|
+
"Programming Language :: Python :: 3.11",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Programming Language :: Python :: 3.13",
|
|
18
|
+
"Programming Language :: Python :: 3.14",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
keywords = ["damicore", "neighbor-joining", "phylogenetics", "tree", "newick"]
|
|
24
|
+
dependencies = ["numpy>=1.26,<3", "pydantic>=2.10,<3"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/Delbem-Research-and-Innovation/damicore"
|
|
28
|
+
Repository = "https://github.com/Delbem-Research-and-Innovation/damicore"
|
|
29
|
+
Issues = "https://github.com/Delbem-Research-and-Innovation/damicore/issues"
|
|
30
|
+
Documentation = "https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md"
|
|
31
|
+
Changelog = "https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/CHANGELOG.md"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["hatchling>=1.31.0,<2"]
|
|
35
|
+
build-backend = "hatchling.build"
|
|
36
|
+
|
|
37
|
+
# Workspace-only files are excluded on purpose: each package's Makefile only includes
|
|
38
|
+
# ../package.mk, pyrightconfig.json extends ../../pyrightconfig.json, and tests/ depends
|
|
39
|
+
# on the workspace conftest and dev tooling, so none of them work in an sdist unpacked
|
|
40
|
+
# outside the monorepo. The repository .gitignore still ships: hatchling force-includes
|
|
41
|
+
# the located VCS ignore file so an sdist-to-wheel build selects files the same way, and
|
|
42
|
+
# `exclude` deliberately cannot override that.
|
|
43
|
+
[tool.hatch.build.targets.sdist]
|
|
44
|
+
exclude = ["Makefile", "pyrightconfig.json", "tests"]
|
|
45
|
+
|
|
46
|
+
[tool.ruff]
|
|
47
|
+
line-length = 100
|
|
48
|
+
exclude = [".venv", "dist", "__pycache__"]
|
|
49
|
+
|
|
50
|
+
[tool.ruff.lint]
|
|
51
|
+
select = ["E", "F", "I", "RUF100", "UP"]
|
|
52
|
+
|
|
53
|
+
[tool.pytest.ini_options]
|
|
54
|
+
testpaths = ["tests"]
|
|
55
|
+
pythonpath = ["src"]
|
|
56
|
+
markers = ["unit: fast isolated unit tests"]
|
|
57
|
+
# --cov-branch and the floor mirror the root configuration on purpose: coverage resolves
|
|
58
|
+
# its config from the working directory, so a package-scoped run would otherwise report
|
|
59
|
+
# line coverage with no threshold and read as a stronger result than it is.
|
|
60
|
+
addopts = "--cov=damicore_tree_builder --cov-branch --cov-report=term-missing --cov-fail-under=90"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from damicore_tree_builder.api import build_tree
|
|
2
|
+
from damicore_tree_builder.config import TreeBuildConfig
|
|
3
|
+
from damicore_tree_builder.errors import TreeBuilderError
|
|
4
|
+
from damicore_tree_builder.models import Tree, TreeBuildResult, TreeEdge, TreeNode
|
|
5
|
+
from damicore_tree_builder.neighbor_joining import neighbor_joining
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"build_tree",
|
|
9
|
+
"neighbor_joining",
|
|
10
|
+
"TreeBuildConfig",
|
|
11
|
+
"TreeBuildResult",
|
|
12
|
+
"Tree",
|
|
13
|
+
"TreeNode",
|
|
14
|
+
"TreeEdge",
|
|
15
|
+
"TreeBuilderError",
|
|
16
|
+
]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
|
9
|
+
|
|
10
|
+
from damicore_tree_builder.artifacts import write_tree_artifacts
|
|
11
|
+
from damicore_tree_builder.config import TreeBuildConfig
|
|
12
|
+
from damicore_tree_builder.errors import TreeBuilderError
|
|
13
|
+
from damicore_tree_builder.models import Tree, TreeBuildResult
|
|
14
|
+
from damicore_tree_builder.neighbor_joining import build_neighbor_joining, validate_matrix
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _LabelsArtifact(BaseModel):
|
|
18
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
19
|
+
|
|
20
|
+
schema_version: Literal[1]
|
|
21
|
+
object_ids: tuple[str, ...]
|
|
22
|
+
labels: tuple[str, ...]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _load_labels(path: Path) -> tuple[list[str], list[str]]:
|
|
26
|
+
try:
|
|
27
|
+
artifact = _LabelsArtifact.model_validate_json(path.read_text(encoding="utf-8"))
|
|
28
|
+
object_ids = list(artifact.object_ids)
|
|
29
|
+
labels = list(artifact.labels)
|
|
30
|
+
except (OSError, ValidationError) as exc:
|
|
31
|
+
raise TreeBuilderError("Invalid labels artifact", code="artifact_validation_error") from exc
|
|
32
|
+
if (
|
|
33
|
+
len(object_ids) != len(labels)
|
|
34
|
+
or len(set(object_ids)) != len(object_ids)
|
|
35
|
+
or len(set(labels)) != len(labels)
|
|
36
|
+
):
|
|
37
|
+
raise TreeBuilderError(
|
|
38
|
+
"labels and object_ids must have equal length and unique values",
|
|
39
|
+
code="artifact_validation_error",
|
|
40
|
+
)
|
|
41
|
+
return object_ids, labels
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_tree(
|
|
45
|
+
matrix_path: str | Path,
|
|
46
|
+
labels_path: str | Path,
|
|
47
|
+
output_dir: str | Path,
|
|
48
|
+
*,
|
|
49
|
+
config: TreeBuildConfig | None = None,
|
|
50
|
+
) -> TreeBuildResult:
|
|
51
|
+
"""Build and persist a deterministic Neighbor Joining tree."""
|
|
52
|
+
started = time.monotonic()
|
|
53
|
+
settings = config or TreeBuildConfig()
|
|
54
|
+
destination = Path(output_dir).resolve()
|
|
55
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
if (destination / "tree.json").exists() or (destination / "tree.nwk").exists():
|
|
57
|
+
raise TreeBuilderError(
|
|
58
|
+
"Tree outputs already exist in the output directory",
|
|
59
|
+
code="output_directory_conflict_error",
|
|
60
|
+
)
|
|
61
|
+
labels, display_labels = _load_labels(Path(labels_path).resolve())
|
|
62
|
+
try:
|
|
63
|
+
original = np.load(Path(matrix_path).resolve(), mmap_mode="r", allow_pickle=False)
|
|
64
|
+
except (OSError, ValueError) as exc:
|
|
65
|
+
raise TreeBuilderError(
|
|
66
|
+
"Distance matrix artifact is unreadable",
|
|
67
|
+
code="artifact_validation_error",
|
|
68
|
+
) from exc
|
|
69
|
+
validate_matrix(original, labels, settings.q_block_size)
|
|
70
|
+
workspace_path = destination / "tree-work.npy"
|
|
71
|
+
workspace = np.lib.format.open_memmap(
|
|
72
|
+
workspace_path, mode="w+", dtype=np.float64, shape=original.shape
|
|
73
|
+
)
|
|
74
|
+
try:
|
|
75
|
+
for start in range(0, original.shape[0], settings.q_block_size):
|
|
76
|
+
stop = min(start + settings.q_block_size, original.shape[0])
|
|
77
|
+
workspace[start:stop] = original[start:stop]
|
|
78
|
+
workspace.flush()
|
|
79
|
+
tree = build_neighbor_joining(
|
|
80
|
+
workspace,
|
|
81
|
+
labels,
|
|
82
|
+
display_labels,
|
|
83
|
+
q_block_size=settings.q_block_size,
|
|
84
|
+
)
|
|
85
|
+
tree_path, newick_path = write_tree_artifacts(tree, destination)
|
|
86
|
+
try:
|
|
87
|
+
validated = Tree.model_validate_json(tree_path.read_text(encoding="utf-8"))
|
|
88
|
+
if len([node for node in validated.nodes if node.kind == "leaf"]) != len(labels):
|
|
89
|
+
raise TreeBuilderError(
|
|
90
|
+
"Persisted tree lost leaves", code="artifact_validation_error"
|
|
91
|
+
)
|
|
92
|
+
newick = newick_path.read_text(encoding="utf-8")
|
|
93
|
+
# Only the terminator is checked. A semicolon inside a quoted label is data, so
|
|
94
|
+
# counting them rejects valid output this package itself produces.
|
|
95
|
+
if not newick.rstrip("\n").endswith(";"):
|
|
96
|
+
raise TreeBuilderError(
|
|
97
|
+
"Persisted Newick artifact is malformed",
|
|
98
|
+
code="artifact_validation_error",
|
|
99
|
+
)
|
|
100
|
+
except BaseException:
|
|
101
|
+
# The next run refuses a directory holding either artifact, so a rejected write
|
|
102
|
+
# must not survive as a file that only manual cleanup can clear.
|
|
103
|
+
tree_path.unlink(missing_ok=True)
|
|
104
|
+
newick_path.unlink(missing_ok=True)
|
|
105
|
+
raise
|
|
106
|
+
negative = sum(edge.length < 0 for edge in tree.edges)
|
|
107
|
+
finally:
|
|
108
|
+
del workspace
|
|
109
|
+
workspace_path.unlink(missing_ok=True)
|
|
110
|
+
return TreeBuildResult(
|
|
111
|
+
tree_path=tree_path,
|
|
112
|
+
newick_path=newick_path,
|
|
113
|
+
leaf_count=len(labels),
|
|
114
|
+
negative_branch_count=negative,
|
|
115
|
+
timing=time.monotonic() - started,
|
|
116
|
+
)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from damicore_tree_builder.models import Tree
|
|
9
|
+
from damicore_tree_builder.newick import to_newick
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _stage(path: Path, payload: str) -> str:
|
|
13
|
+
"""Write `payload` beside `path` and return the temporary name, unrenamed."""
|
|
14
|
+
descriptor, temporary_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
|
|
15
|
+
try:
|
|
16
|
+
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
|
|
17
|
+
stream.write(payload)
|
|
18
|
+
stream.flush()
|
|
19
|
+
os.fsync(stream.fileno())
|
|
20
|
+
except BaseException:
|
|
21
|
+
os.unlink(temporary_name)
|
|
22
|
+
raise
|
|
23
|
+
return temporary_name
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def write_tree_artifacts(tree: Tree, destination: Path) -> tuple[Path, Path]:
|
|
27
|
+
"""Publish both tree artifacts, or neither.
|
|
28
|
+
|
|
29
|
+
The two files describe one tree, and the run that follows refuses a directory that already
|
|
30
|
+
holds either of them. Renaming the first into place before the second exists would
|
|
31
|
+
therefore let one failed write strand a tree.json that no later run can clear on its own,
|
|
32
|
+
so both payloads are rendered and staged first and renamed only once both exist.
|
|
33
|
+
"""
|
|
34
|
+
tree_path = destination / "tree.json"
|
|
35
|
+
newick_path = destination / "tree.nwk"
|
|
36
|
+
|
|
37
|
+
tree_text = (
|
|
38
|
+
json.dumps(
|
|
39
|
+
tree.model_dump(mode="json"),
|
|
40
|
+
indent=2,
|
|
41
|
+
sort_keys=True,
|
|
42
|
+
allow_nan=False,
|
|
43
|
+
)
|
|
44
|
+
+ "\n"
|
|
45
|
+
)
|
|
46
|
+
newick_text = to_newick(tree) + "\n"
|
|
47
|
+
|
|
48
|
+
tree_temp = _stage(tree_path, tree_text)
|
|
49
|
+
try:
|
|
50
|
+
newick_temp = _stage(newick_path, newick_text)
|
|
51
|
+
except BaseException:
|
|
52
|
+
os.unlink(tree_temp)
|
|
53
|
+
raise
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
os.replace(tree_temp, tree_path)
|
|
57
|
+
except BaseException:
|
|
58
|
+
os.unlink(tree_temp)
|
|
59
|
+
os.unlink(newick_temp)
|
|
60
|
+
raise
|
|
61
|
+
try:
|
|
62
|
+
os.replace(newick_temp, newick_path)
|
|
63
|
+
except BaseException:
|
|
64
|
+
# tree.json is already published; withdraw it so the directory is left as found.
|
|
65
|
+
os.unlink(newick_temp)
|
|
66
|
+
tree_path.unlink(missing_ok=True)
|
|
67
|
+
raise
|
|
68
|
+
return tree_path, newick_path
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TreeNode(BaseModel):
|
|
10
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
11
|
+
|
|
12
|
+
id: str
|
|
13
|
+
kind: Literal["leaf", "internal"]
|
|
14
|
+
label: str | None = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TreeEdge(BaseModel):
|
|
18
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
19
|
+
|
|
20
|
+
source: str
|
|
21
|
+
target: str
|
|
22
|
+
length: float = Field(allow_inf_nan=False)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Tree(BaseModel):
|
|
26
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
27
|
+
|
|
28
|
+
schema_version: Literal[1] = 1
|
|
29
|
+
root_id: str
|
|
30
|
+
nodes: tuple[TreeNode, ...]
|
|
31
|
+
edges: tuple[TreeEdge, ...]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TreeBuildResult(BaseModel):
|
|
35
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
36
|
+
|
|
37
|
+
tree_path: Path
|
|
38
|
+
newick_path: Path
|
|
39
|
+
leaf_count: int = Field(ge=0)
|
|
40
|
+
negative_branch_count: int = Field(ge=0)
|
|
41
|
+
timing: float = Field(ge=0)
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import numpy.typing as npt
|
|
9
|
+
|
|
10
|
+
from damicore_tree_builder.errors import TreeBuilderError
|
|
11
|
+
from damicore_tree_builder.models import Tree, TreeEdge, TreeNode
|
|
12
|
+
|
|
13
|
+
# Section 15.2: two Q scores closer than this, relative to the magnitude of the better one,
|
|
14
|
+
# are one tie for the lexicographic rule to break.
|
|
15
|
+
#
|
|
16
|
+
# An exact float64 comparison asserts a precision the input never had: every distance here is
|
|
17
|
+
# a ratio of integer compressed sizes, so its meaningful digits run out long before the
|
|
18
|
+
# 16th. Worse, the ties the rule exists to break are precisely the ones rounding destroys --
|
|
19
|
+
# with four clusters left, Q(i,j) and Q(k,l) for complementary pairs are algebraically equal
|
|
20
|
+
# for *every* matrix, yet float64 detects that only about 60% of the time, and no summation
|
|
21
|
+
# strategy fixes it because the cancellation happens in the final subtraction rather than in
|
|
22
|
+
# the sums. A relative band restores the rule and makes the choice stable across platforms.
|
|
23
|
+
_TIE_RELATIVE_TOLERANCE = 1e-9
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _tie_band(score: float) -> float:
|
|
27
|
+
"""Half-width of the tie band around `score`, scaled to its magnitude."""
|
|
28
|
+
return _TIE_RELATIVE_TOLERANCE * max(1.0, abs(score))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def validate_matrix(
|
|
32
|
+
matrix: np.ndarray[Any, Any],
|
|
33
|
+
labels: Sequence[str],
|
|
34
|
+
block_size: int = 512,
|
|
35
|
+
) -> None:
|
|
36
|
+
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1] or matrix.shape[0] != len(labels):
|
|
37
|
+
raise TreeBuilderError(
|
|
38
|
+
"Distance matrix shape does not match labels", code="distance_matrix_validation_error"
|
|
39
|
+
)
|
|
40
|
+
if len(labels) < 2 or len(set(labels)) != len(labels):
|
|
41
|
+
raise TreeBuilderError(
|
|
42
|
+
"At least two unique labels are required", code="distance_matrix_validation_error"
|
|
43
|
+
)
|
|
44
|
+
if matrix.dtype != np.float64:
|
|
45
|
+
raise TreeBuilderError(
|
|
46
|
+
"Distance matrix must be float64",
|
|
47
|
+
code="distance_matrix_validation_error",
|
|
48
|
+
)
|
|
49
|
+
size = len(labels)
|
|
50
|
+
for row_start in range(0, size, block_size):
|
|
51
|
+
row_stop = min(row_start + block_size, size)
|
|
52
|
+
if not np.isfinite(matrix[row_start:row_stop]).all():
|
|
53
|
+
raise TreeBuilderError(
|
|
54
|
+
"Distance matrix must be finite",
|
|
55
|
+
code="distance_matrix_validation_error",
|
|
56
|
+
)
|
|
57
|
+
for row in range(row_start, row_stop):
|
|
58
|
+
if float(matrix[row, row]) != 0.0:
|
|
59
|
+
raise TreeBuilderError(
|
|
60
|
+
"Distance matrix diagonal must be exactly zero",
|
|
61
|
+
code="distance_matrix_validation_error",
|
|
62
|
+
)
|
|
63
|
+
# pyright: ignore is on np.array_equal, whose numpy stub is partially
|
|
64
|
+
# unknown under strict mode; the arrays themselves are fully typed.
|
|
65
|
+
symmetric = np.array_equal( # pyright: ignore[reportUnknownMemberType]
|
|
66
|
+
matrix[row, :], matrix[:, row]
|
|
67
|
+
)
|
|
68
|
+
if not bool(symmetric):
|
|
69
|
+
raise TreeBuilderError(
|
|
70
|
+
"Distance matrix must be bitwise symmetric",
|
|
71
|
+
code="distance_matrix_validation_error",
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def neighbor_joining(matrix: npt.NDArray[np.floating[Any]], labels: Sequence[str]) -> Tree:
|
|
76
|
+
"""Build a deterministic Neighbor Joining tree, copying the input matrix."""
|
|
77
|
+
copied = np.array(matrix, dtype=np.float64, copy=True, order="C")
|
|
78
|
+
validate_matrix(copied, labels)
|
|
79
|
+
return build_neighbor_joining(copied, list(labels), q_block_size=512)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def build_neighbor_joining(
|
|
83
|
+
work: np.ndarray[Any, Any],
|
|
84
|
+
labels: list[str],
|
|
85
|
+
display_labels: list[str] | None = None,
|
|
86
|
+
*,
|
|
87
|
+
q_block_size: int,
|
|
88
|
+
) -> Tree:
|
|
89
|
+
active = list(labels)
|
|
90
|
+
slots = {label: index for index, label in enumerate(labels)}
|
|
91
|
+
rendered_labels = display_labels or labels
|
|
92
|
+
nodes = [
|
|
93
|
+
TreeNode(id=identifier, kind="leaf", label=rendered_labels[index])
|
|
94
|
+
for index, identifier in enumerate(labels)
|
|
95
|
+
]
|
|
96
|
+
edges: list[TreeEdge] = []
|
|
97
|
+
internal_index = 1
|
|
98
|
+
|
|
99
|
+
while len(active) > 2:
|
|
100
|
+
active.sort()
|
|
101
|
+
count = len(active)
|
|
102
|
+
# Recomputed from the matrix each round rather than carried forward, so no drift
|
|
103
|
+
# accumulates across iterations. The cost is O(r^2), which the Q scan below already
|
|
104
|
+
# pays, so nothing changes asymptotically.
|
|
105
|
+
row_sums = {
|
|
106
|
+
node: float(sum(work[slots[node], slots[other]] for other in active if other != node))
|
|
107
|
+
for node in active
|
|
108
|
+
}
|
|
109
|
+
# Section 15.2: the smallest Q wins, and pairs within the tie band are resolved by the
|
|
110
|
+
# smallest pair of IDs. `active` is sorted and pairs are visited in that order, so the
|
|
111
|
+
# running pair is always the lexicographically earliest one seen so far; a later pair
|
|
112
|
+
# therefore replaces it only by winning outright, never by tying with it.
|
|
113
|
+
best_score = math.inf
|
|
114
|
+
best_pair: tuple[str, str] | None = None
|
|
115
|
+
for block_start in range(0, count, q_block_size):
|
|
116
|
+
block_stop = min(block_start + q_block_size, count)
|
|
117
|
+
for left_index in range(block_start, block_stop):
|
|
118
|
+
left = active[left_index]
|
|
119
|
+
for right in active[left_index + 1 :]:
|
|
120
|
+
score = (
|
|
121
|
+
(count - 2) * float(work[slots[left], slots[right]])
|
|
122
|
+
- row_sums[left]
|
|
123
|
+
- row_sums[right]
|
|
124
|
+
)
|
|
125
|
+
if best_pair is None or score < best_score - _tie_band(best_score):
|
|
126
|
+
best_pair = (left, right)
|
|
127
|
+
best_score = score
|
|
128
|
+
elif score < best_score:
|
|
129
|
+
# Inside the band: keep the earlier pair, tighten the band's centre.
|
|
130
|
+
best_score = score
|
|
131
|
+
# `active` holds at least three labels here, so the pair loop above always ran and
|
|
132
|
+
# `best_pair` is always set; asserting it is how the type narrows without a dead branch.
|
|
133
|
+
assert best_pair is not None
|
|
134
|
+
left, right = best_pair
|
|
135
|
+
left_slot, right_slot = slots[left], slots[right]
|
|
136
|
+
distance = float(work[left_slot, right_slot])
|
|
137
|
+
delta = (row_sums[left] - row_sums[right]) / (count - 2)
|
|
138
|
+
left_length = 0.5 * (distance + delta)
|
|
139
|
+
right_length = distance - left_length
|
|
140
|
+
internal = f"nj_{internal_index:06d}"
|
|
141
|
+
internal_index += 1
|
|
142
|
+
nodes.append(TreeNode(id=internal, kind="internal"))
|
|
143
|
+
edges.extend(
|
|
144
|
+
[
|
|
145
|
+
TreeEdge(source=internal, target=left, length=left_length),
|
|
146
|
+
TreeEdge(source=internal, target=right, length=right_length),
|
|
147
|
+
]
|
|
148
|
+
)
|
|
149
|
+
remaining = [node for node in active if node not in (left, right)]
|
|
150
|
+
for other in remaining:
|
|
151
|
+
other_slot = slots[other]
|
|
152
|
+
left_distance = float(work[left_slot, other_slot])
|
|
153
|
+
right_distance = float(work[right_slot, other_slot])
|
|
154
|
+
updated = 0.5 * (left_distance + right_distance - distance)
|
|
155
|
+
work[left_slot, other_slot] = updated
|
|
156
|
+
work[other_slot, left_slot] = updated
|
|
157
|
+
work[left_slot, left_slot] = 0.0
|
|
158
|
+
slots.pop(left)
|
|
159
|
+
slots.pop(right)
|
|
160
|
+
slots[internal] = left_slot
|
|
161
|
+
active = [*remaining, internal]
|
|
162
|
+
|
|
163
|
+
active.sort()
|
|
164
|
+
left, right = active
|
|
165
|
+
final_length = float(work[slots[left], slots[right]]) / 2.0
|
|
166
|
+
root = "nj_root"
|
|
167
|
+
nodes.append(TreeNode(id=root, kind="internal"))
|
|
168
|
+
edges.extend(
|
|
169
|
+
[
|
|
170
|
+
TreeEdge(source=root, target=left, length=final_length),
|
|
171
|
+
TreeEdge(source=root, target=right, length=final_length),
|
|
172
|
+
]
|
|
173
|
+
)
|
|
174
|
+
ordered_edges = tuple(sorted(edges, key=lambda edge: (edge.source, edge.target)))
|
|
175
|
+
return Tree(root_id=root, nodes=tuple(nodes), edges=ordered_edges)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from damicore_tree_builder.errors import TreeBuilderError
|
|
4
|
+
from damicore_tree_builder.models import Tree
|
|
5
|
+
|
|
6
|
+
# Underscore is in this set on purpose. Newick converts an unquoted underscore to a blank on
|
|
7
|
+
# reading, and every id this package emits contains one (`column_000001`, `nj_root`), so an
|
|
8
|
+
# unquoted label reaches a conforming viewer with its digits split off from its prefix.
|
|
9
|
+
_MUST_QUOTE = " \t\n\r():;,[]'_"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _escape(identifier: str) -> str:
|
|
13
|
+
if identifier and all(character not in identifier for character in _MUST_QUOTE):
|
|
14
|
+
return identifier
|
|
15
|
+
return "'" + identifier.replace("'", "''") + "'"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def to_newick(tree: Tree) -> str:
|
|
19
|
+
"""Render `tree` as a Newick string closed by a single terminator.
|
|
20
|
+
|
|
21
|
+
The traversal is iterative because tree depth is not bounded by the object count in any
|
|
22
|
+
useful way: Neighbor Joining produces a caterpillar of depth n-1 whenever one taxon joins
|
|
23
|
+
per round, so a recursive renderer exhausts the interpreter stack inside the supported
|
|
24
|
+
input range rather than at some unreachable extreme.
|
|
25
|
+
|
|
26
|
+
Raises
|
|
27
|
+
------
|
|
28
|
+
TreeBuilderError
|
|
29
|
+
If the edges reach a node already on the current path. A recursive renderer ends such
|
|
30
|
+
a cycle with RecursionError; an iterative one would otherwise never terminate.
|
|
31
|
+
"""
|
|
32
|
+
children: dict[str, list[tuple[str, float]]] = {}
|
|
33
|
+
for edge in tree.edges:
|
|
34
|
+
children.setdefault(edge.source, []).append((edge.target, edge.length))
|
|
35
|
+
|
|
36
|
+
# A node's own branch length belongs to the edge that reaches it, not to the node, so
|
|
37
|
+
# `body` holds each subtree rendered without it and the length is appended per edge.
|
|
38
|
+
body: dict[str, str] = {}
|
|
39
|
+
on_path: set[str] = set()
|
|
40
|
+
stack: list[tuple[str, bool]] = [(tree.root_id, False)]
|
|
41
|
+
while stack:
|
|
42
|
+
node_id, expanded = stack.pop()
|
|
43
|
+
if expanded:
|
|
44
|
+
on_path.discard(node_id)
|
|
45
|
+
descendants = sorted(children.get(node_id, []), key=lambda item: item[0])
|
|
46
|
+
prefix = ""
|
|
47
|
+
if descendants:
|
|
48
|
+
prefix = (
|
|
49
|
+
"("
|
|
50
|
+
+ ",".join(
|
|
51
|
+
body[child] + ":" + repr(float(length)) for child, length in descendants
|
|
52
|
+
)
|
|
53
|
+
+ ")"
|
|
54
|
+
)
|
|
55
|
+
body[node_id] = prefix + _escape(node_id)
|
|
56
|
+
continue
|
|
57
|
+
if node_id in on_path:
|
|
58
|
+
raise TreeBuilderError(
|
|
59
|
+
"Tree edges form a cycle",
|
|
60
|
+
code="artifact_validation_error",
|
|
61
|
+
node_id=node_id,
|
|
62
|
+
)
|
|
63
|
+
on_path.add(node_id)
|
|
64
|
+
stack.append((node_id, True))
|
|
65
|
+
stack.extend((child, False) for child, _ in children.get(node_id, []))
|
|
66
|
+
|
|
67
|
+
return body[tree.root_id] + ";"
|
|
File without changes
|