damicore-clusterizer 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.
@@ -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,63 @@
1
+ Metadata-Version: 2.5
2
+ Name: damicore-clusterizer
3
+ Version: 0.1.0
4
+ Summary: FastGreedy clustering stage 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: clustering,community-detection,damicore,fastgreedy,modularity
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: igraph<1.1,>=1.0
27
+ Requires-Dist: numpy<3,>=1.26
28
+ Requires-Dist: pydantic<3,>=2.10
29
+ Description-Content-Type: text/markdown
30
+
31
+ # damicore-clusterizer
32
+
33
+ damicore-clusterizer clusters every node of a validated DAMICORE tree with
34
+ igraph FastGreedy and projects the resulting communities onto leaves. It is the
35
+ fourth and final stage of the DAMICORE pipeline; most users install the
36
+ aggregate `damicore` distribution, which runs all four stages end to end.
37
+ Install this package alone to cluster trees without the rest of the pipeline.
38
+
39
+ ```bash
40
+ pip install damicore-clusterizer
41
+ ```
42
+
43
+ ## Python
44
+
45
+ ```python
46
+ from damicore_clusterizer import ClusterConfig, cluster_tree
47
+
48
+ result = cluster_tree("tree.json", "run", config=ClusterConfig(num_clusters=None))
49
+ ```
50
+
51
+ `tree.json` is produced by the sibling `damicore-tree-builder` distribution; the
52
+ call writes cluster membership as `membership.csv` and `clusters.json`. Negative
53
+ branch lengths receive one global shift, and output cluster IDs and leaf
54
+ ordering are deterministic.
55
+
56
+ ## Links
57
+
58
+ - Repository: <https://github.com/Delbem-Research-and-Innovation/damicore>
59
+ - Issues: <https://github.com/Delbem-Research-and-Innovation/damicore/issues>
60
+ - Documentation:
61
+ <https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md>
62
+
63
+ Licensed under Apache-2.0.
@@ -0,0 +1,33 @@
1
+ # damicore-clusterizer
2
+
3
+ damicore-clusterizer clusters every node of a validated DAMICORE tree with
4
+ igraph FastGreedy and projects the resulting communities onto leaves. It is the
5
+ fourth and final stage of the DAMICORE pipeline; most users install the
6
+ aggregate `damicore` distribution, which runs all four stages end to end.
7
+ Install this package alone to cluster trees without the rest of the pipeline.
8
+
9
+ ```bash
10
+ pip install damicore-clusterizer
11
+ ```
12
+
13
+ ## Python
14
+
15
+ ```python
16
+ from damicore_clusterizer import ClusterConfig, cluster_tree
17
+
18
+ result = cluster_tree("tree.json", "run", config=ClusterConfig(num_clusters=None))
19
+ ```
20
+
21
+ `tree.json` is produced by the sibling `damicore-tree-builder` distribution; the
22
+ call writes cluster membership as `membership.csv` and `clusters.json`. Negative
23
+ branch lengths receive one global shift, and output cluster IDs and leaf
24
+ ordering are deterministic.
25
+
26
+ ## Links
27
+
28
+ - Repository: <https://github.com/Delbem-Research-and-Innovation/damicore>
29
+ - Issues: <https://github.com/Delbem-Research-and-Innovation/damicore/issues>
30
+ - Documentation:
31
+ <https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md>
32
+
33
+ Licensed under Apache-2.0.
@@ -0,0 +1,60 @@
1
+ [project]
2
+ name = "damicore-clusterizer"
3
+ version = "0.1.0"
4
+ description = "FastGreedy clustering stage 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", "clustering", "community-detection", "fastgreedy", "modularity"]
24
+ dependencies = ["igraph>=1.0,<1.1", "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_clusterizer --cov-branch --cov-report=term-missing --cov-fail-under=90"
@@ -0,0 +1,6 @@
1
+ from damicore_clusterizer.api import cluster_tree
2
+ from damicore_clusterizer.config import ClusterConfig
3
+ from damicore_clusterizer.errors import ClusterizerError
4
+ from damicore_clusterizer.models import ClusterResult
5
+
6
+ __all__ = ["cluster_tree", "ClusterConfig", "ClusterResult", "ClusterizerError"]
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from pathlib import Path
5
+
6
+ from damicore_clusterizer.artifacts import write_cluster_artifacts
7
+ from damicore_clusterizer.config import ClusterConfig
8
+ from damicore_clusterizer.errors import ClusterizerError
9
+ from damicore_clusterizer.fastgreedy import fastgreedy_membership
10
+ from damicore_clusterizer.models import ClusterResult
11
+ from damicore_clusterizer.tree_graph import load_tree_graph
12
+
13
+
14
+ def cluster_tree(
15
+ tree_path: str | Path,
16
+ output_dir: str | Path,
17
+ *,
18
+ config: ClusterConfig | None = None,
19
+ ) -> ClusterResult:
20
+ """Cluster every node in an unrooted tree and project communities to leaves."""
21
+ started = time.monotonic()
22
+ settings = config or ClusterConfig()
23
+ source = load_tree_graph(Path(tree_path).resolve())
24
+ if settings.num_clusters is not None and settings.num_clusters > len(source.object_ids):
25
+ raise ClusterizerError(
26
+ "num_clusters cannot exceed the leaf count", code="configuration_error"
27
+ )
28
+ membership, community_count, modularity = fastgreedy_membership(
29
+ source.graph,
30
+ settings.num_clusters,
31
+ )
32
+ names = source.vertex_names
33
+ raw_leaf_groups: dict[int, list[str]] = {}
34
+ for vertex_index, community in enumerate(membership):
35
+ name = str(names[vertex_index])
36
+ if name in source.object_ids:
37
+ raw_leaf_groups.setdefault(int(community), []).append(name)
38
+ ordered_groups = sorted(
39
+ (tuple(sorted(group)) for group in raw_leaf_groups.values() if group),
40
+ key=lambda group: group,
41
+ )
42
+ cluster_for = {
43
+ object_id: cluster for cluster, group in enumerate(ordered_groups) for object_id in group
44
+ }
45
+ if set(cluster_for) != set(source.object_ids):
46
+ raise ClusterizerError("Cluster membership is incomplete", code="clusterization_error")
47
+
48
+ destination = Path(output_dir).resolve()
49
+ destination.mkdir(parents=True, exist_ok=True)
50
+ if (destination / "membership.csv").exists() or (destination / "clusters.json").exists():
51
+ raise ClusterizerError(
52
+ "Cluster outputs already exist without a reusable receipt",
53
+ code="output_directory_conflict_error",
54
+ )
55
+ membership_path, clusters_path = write_cluster_artifacts(
56
+ destination,
57
+ source.object_ids,
58
+ source.labels,
59
+ cluster_for,
60
+ ordered_groups,
61
+ )
62
+ return ClusterResult(
63
+ membership_path=membership_path,
64
+ clusters_path=clusters_path,
65
+ community_count=community_count,
66
+ cluster_count=len(ordered_groups),
67
+ modularity=modularity,
68
+ timing=time.monotonic() - started,
69
+ )
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import io
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+
14
+ class _ClusterItem(BaseModel):
15
+ model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
16
+
17
+ cluster: int = Field(ge=0)
18
+ object_ids: tuple[str, ...]
19
+ labels: tuple[str, ...]
20
+
21
+
22
+ class _ClustersArtifact(BaseModel):
23
+ model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
24
+
25
+ schema_version: Literal[1]
26
+ clusters: tuple[_ClusterItem, ...]
27
+
28
+
29
+ def _stage(path: Path, payload: str, newline: str) -> str:
30
+ """Write `payload` beside `path` and return the temporary name, unrenamed."""
31
+ descriptor, temporary_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
32
+ try:
33
+ with os.fdopen(descriptor, "w", encoding="utf-8", newline=newline) as stream:
34
+ stream.write(payload)
35
+ stream.flush()
36
+ os.fsync(stream.fileno())
37
+ except BaseException:
38
+ os.unlink(temporary_name)
39
+ raise
40
+ return temporary_name
41
+
42
+
43
+ def write_cluster_artifacts(
44
+ destination: Path,
45
+ object_ids: tuple[str, ...],
46
+ labels: dict[str, str],
47
+ cluster_for: dict[str, int],
48
+ ordered_groups: list[tuple[str, ...]],
49
+ ) -> tuple[Path, Path]:
50
+ """Publish both cluster artifacts, or neither.
51
+
52
+ The two files describe one clustering, and the run that follows refuses a directory that
53
+ already holds either of them. Renaming the first into place before the second exists
54
+ would therefore let one failed write strand a membership.csv that no later run can clear
55
+ on its own, so both are staged first and renamed only once both exist.
56
+ """
57
+ membership_path = destination / "membership.csv"
58
+ clusters_path = destination / "clusters.json"
59
+
60
+ rows = io.StringIO()
61
+ writer = csv.writer(rows, lineterminator="\n")
62
+ writer.writerow(["object_id", "label", "cluster"])
63
+ for object_id in object_ids:
64
+ writer.writerow([object_id, labels[object_id], cluster_for[object_id]])
65
+
66
+ payload = _ClustersArtifact(
67
+ schema_version=1,
68
+ clusters=tuple(
69
+ _ClusterItem(
70
+ cluster=cluster,
71
+ object_ids=group,
72
+ labels=tuple(labels[object_id] for object_id in group),
73
+ )
74
+ for cluster, group in enumerate(ordered_groups)
75
+ ),
76
+ )
77
+ clusters_text = (
78
+ json.dumps(payload.model_dump(mode="json"), indent=2, sort_keys=True, allow_nan=False)
79
+ + "\n"
80
+ )
81
+
82
+ membership_temp = _stage(membership_path, rows.getvalue(), newline="")
83
+ try:
84
+ clusters_temp = _stage(clusters_path, clusters_text, newline="\n")
85
+ except BaseException:
86
+ os.unlink(membership_temp)
87
+ raise
88
+
89
+ try:
90
+ os.replace(membership_temp, membership_path)
91
+ except BaseException:
92
+ os.unlink(membership_temp)
93
+ os.unlink(clusters_temp)
94
+ raise
95
+ try:
96
+ os.replace(clusters_temp, clusters_path)
97
+ except BaseException:
98
+ # membership.csv is already published; withdraw it so the directory is left as found.
99
+ os.unlink(clusters_temp)
100
+ membership_path.unlink(missing_ok=True)
101
+ raise
102
+ return membership_path, clusters_path
@@ -0,0 +1,7 @@
1
+ from pydantic import BaseModel, ConfigDict, Field
2
+
3
+
4
+ class ClusterConfig(BaseModel):
5
+ model_config = ConfigDict(frozen=True, extra="forbid")
6
+
7
+ num_clusters: int | None = Field(default=None, ge=1)
@@ -0,0 +1,8 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class ClusterizerError(Exception):
5
+ def __init__(self, message: str, *, code: str = "clusterizer_error", **context: object) -> None:
6
+ super().__init__(message)
7
+ self.code = code
8
+ self.context = context
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import igraph as ig
6
+
7
+
8
+ def fastgreedy_membership(
9
+ graph: ig.Graph,
10
+ num_clusters: int | None,
11
+ ) -> tuple[list[int], int, float]:
12
+ dendrogram = graph.community_fastgreedy(weights="weight")
13
+ # igraph's VertexDendrogram.as_clustering is untyped in the shipped stubs, so the result
14
+ # arrives as Unknown; Any isolates that one library boundary rather than the module.
15
+ clustering: Any = (
16
+ dendrogram.as_clustering()
17
+ if num_clusters is None
18
+ else dendrogram.as_clustering(n=num_clusters)
19
+ )
20
+ return (
21
+ [int(value) for value in clustering.membership],
22
+ len(clustering),
23
+ float(clustering.modularity),
24
+ )
@@ -0,0 +1,14 @@
1
+ from pathlib import Path
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field
4
+
5
+
6
+ class ClusterResult(BaseModel):
7
+ model_config = ConfigDict(frozen=True, extra="forbid")
8
+
9
+ membership_path: Path
10
+ clusters_path: Path
11
+ community_count: int = Field(ge=0)
12
+ cluster_count: int = Field(ge=0)
13
+ modularity: float = Field(allow_inf_nan=False)
14
+ timing: float = Field(ge=0)
@@ -0,0 +1,170 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import igraph as ig
9
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
10
+
11
+ from damicore_clusterizer.errors import ClusterizerError
12
+
13
+
14
+ class _TreeNode(BaseModel):
15
+ model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
16
+
17
+ id: str
18
+ kind: Literal["leaf", "internal"]
19
+ label: str | None
20
+
21
+
22
+ class _TreeEdge(BaseModel):
23
+ model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
24
+
25
+ source: str
26
+ target: str
27
+ length: float = Field(allow_inf_nan=False)
28
+
29
+
30
+ class _TreeArtifact(BaseModel):
31
+ model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
32
+
33
+ schema_version: Literal[1]
34
+ root_id: str
35
+ nodes: tuple[_TreeNode, ...]
36
+ edges: tuple[_TreeEdge, ...]
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class GraphInput:
41
+ graph: ig.Graph
42
+ # Vertex order as igraph holds it. Exposed here so callers never read graph.vs
43
+ # themselves: this module is the only place that touches igraph's attribute API.
44
+ vertex_names: tuple[str, ...]
45
+ object_ids: tuple[str, ...]
46
+ labels: dict[str, str]
47
+
48
+
49
+ def _edge_weights(lengths: list[float]) -> list[float]:
50
+ """Map branch lengths onto the strictly positive edge weights FastGreedy is given.
51
+
52
+ A shorter branch joins a closer pair, so the weight is the reciprocal of the length. The
53
+ reciprocals are then translated so the smallest is exactly one, and that translation is
54
+ the point of this function: modularity is a weighted sum, so a single unbounded weight
55
+ would decide the partition by itself, and a reciprocal is unbounded as the length
56
+ approaches zero. Translating here rather than on the lengths keeps the ratio between
57
+ weights bounded by the spread of the data.
58
+
59
+ It also settles what a negative branch means. Neighbor Joining emits one where the matrix
60
+ contradicts the split it is making, and the reciprocal of a negative length sorts below
61
+ every positive one, so such a branch becomes the weakest edge rather than the strongest.
62
+
63
+ The result is at least one everywhere and is unchanged by rescaling every length.
64
+
65
+ Raises
66
+ ------
67
+ ClusterizerError
68
+ If a length is zero, which has no reciprocal, or so small that its reciprocal
69
+ overflows. Neither is repaired here: a repair would be the unbounded weight this
70
+ function exists to avoid.
71
+ """
72
+ reciprocals: list[float] = []
73
+ for length in lengths:
74
+ if length == 0.0:
75
+ raise ClusterizerError(
76
+ "Branch length is zero and has no reciprocal weight",
77
+ code="tree_format_error",
78
+ )
79
+ value = 1.0 / length
80
+ if not math.isfinite(value):
81
+ raise ClusterizerError(
82
+ "Branch length is too small to carry a finite weight",
83
+ code="tree_format_error",
84
+ )
85
+ reciprocals.append(value)
86
+
87
+ mean = sum(reciprocals) / len(reciprocals)
88
+ deviation = math.sqrt(sum((value - mean) ** 2 for value in reciprocals) / len(reciprocals))
89
+ if deviation == 0.0:
90
+ # Every branch has the same length, so the reciprocals carry no ordering to spread.
91
+ return [1.0] * len(reciprocals)
92
+ lowest = min(reciprocals)
93
+ return [1.0 + (value - lowest) / deviation for value in reciprocals]
94
+
95
+
96
+ def _load_tree_graph(path: Path) -> GraphInput:
97
+ try:
98
+ artifact = _TreeArtifact.model_validate_json(path.read_text(encoding="utf-8"))
99
+ root_id = artifact.root_id
100
+ nodes = artifact.nodes
101
+ edges = artifact.edges
102
+ except (OSError, ValidationError) as exc:
103
+ raise ClusterizerError("Invalid tree artifact", code="tree_format_error") from exc
104
+
105
+ node_ids = [node.id for node in nodes]
106
+ if len(node_ids) != len(set(node_ids)):
107
+ raise ClusterizerError("Tree node ids are not unique", code="tree_format_error")
108
+ if root_id not in node_ids:
109
+ raise ClusterizerError("Tree root_id names no node", code="tree_format_error")
110
+ root_node = next(node for node in nodes if node.id == root_id)
111
+ if root_node.kind != "internal":
112
+ raise ClusterizerError("Tree root must be internal", code="tree_format_error")
113
+ leaves = tuple(node.id for node in nodes if node.kind == "leaf")
114
+ if len(leaves) < 2:
115
+ raise ClusterizerError("Tree must contain at least two leaves", code="tree_format_error")
116
+ # Validate and collect in one pass: a separate `any(...)` guard establishes the invariant
117
+ # for a reader but not for the comprehension that follows, which then carries `str | None`.
118
+ labels: dict[str, str] = {}
119
+ for node in nodes:
120
+ if node.kind != "leaf":
121
+ continue
122
+ if not isinstance(node.label, str):
123
+ raise ClusterizerError("Every leaf must have a string label", code="tree_format_error")
124
+ labels[node.id] = node.label
125
+ root_edges = [edge for edge in edges if edge.source == root_id]
126
+ if len(root_edges) != 2:
127
+ raise ClusterizerError("Tree root must have exactly two children", code="tree_format_error")
128
+
129
+ retained_nodes = [node_id for node_id in node_ids if node_id != root_id]
130
+ index = {node_id: position for position, node_id in enumerate(retained_nodes)}
131
+ graph_edges: list[tuple[int, int]] = []
132
+ lengths: list[float] = []
133
+ for edge in edges:
134
+ source, target = edge.source, edge.target
135
+ if source == root_id:
136
+ continue
137
+ if source not in index or target not in index:
138
+ raise ClusterizerError("Tree edge references an unknown node", code="tree_format_error")
139
+ graph_edges.append((index[source], index[target]))
140
+ lengths.append(edge.length)
141
+ left, right = root_edges
142
+ graph_edges.append((index[left.target], index[right.target]))
143
+ lengths.append(left.length + right.length)
144
+ if any(not math.isfinite(length) for length in lengths):
145
+ raise ClusterizerError("Branch lengths must be finite", code="tree_format_error")
146
+ if len(graph_edges) != len(retained_nodes) - 1:
147
+ raise ClusterizerError("Unrooted tree must have n-1 edges", code="tree_format_error")
148
+ graph = ig.Graph(n=len(retained_nodes), edges=graph_edges, directed=False)
149
+ if not graph.is_connected():
150
+ raise ClusterizerError("Tree graph is disconnected", code="tree_format_error")
151
+ graph.vs["name"] = retained_nodes
152
+ graph.es["weight"] = _edge_weights(lengths)
153
+ return GraphInput(
154
+ graph=graph,
155
+ vertex_names=tuple(retained_nodes),
156
+ object_ids=leaves,
157
+ labels=labels,
158
+ )
159
+
160
+
161
+ def load_tree_graph(path: Path) -> GraphInput:
162
+ try:
163
+ return _load_tree_graph(path)
164
+ except ClusterizerError:
165
+ raise
166
+ except (KeyError, TypeError, ValueError, OverflowError) as exc:
167
+ raise ClusterizerError(
168
+ "Tree artifact does not match schema version 1",
169
+ code="tree_format_error",
170
+ ) from exc