sphncs 0.3.1__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.
sphncs-0.3.1/LICENSE ADDED
@@ -0,0 +1,178 @@
1
+ Copyright 2026 Shawn Davis
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
sphncs-0.3.1/PKG-INFO ADDED
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: sphncs
3
+ Version: 0.3.1
4
+ Summary: Similarity-Preserving Hierarchical Nonparametric Clustering System
5
+ Author: Shawn Davis
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/shawn-davis/sphncs
8
+ Project-URL: Repository, https://github.com/shawn-davis/sphncs
9
+ Project-URL: Issues, https://github.com/shawn-davis/sphncs/issues
10
+ Keywords: clustering,density-estimation,fastmap,log-analysis,machine-learning
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: scipy>=1.10
26
+ Requires-Dist: scikit-learn>=1.3
27
+ Requires-Dist: KDEpy>=1.1
28
+ Requires-Dist: FastMapy>=0.2.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.4; extra == "dev"
31
+ Requires-Dist: ruff>=0.4; extra == "dev"
32
+ Provides-Extra: bench
33
+ Requires-Dist: rapidfuzz>=3.14; extra == "bench"
34
+ Requires-Dist: matplotlib>=3.8; extra == "bench"
35
+ Requires-Dist: drain3>=0.9.11; extra == "bench"
36
+ Dynamic: license-file
37
+
38
+ # sphncs
39
+
40
+ Licensed under [Apache-2.0](LICENSE).
41
+
42
+ `sphncs` is the **Similarity-Preserving Hierarchical Nonparametric Clustering
43
+ System**. It clusters any objects with a well-defined, non-negative distance
44
+ metric by embedding on-demand distances with FastMap and finding density
45
+ separations with `KDEpy.FFTKDE`.
46
+
47
+ It supports a lightweight single-dimension mode and an optional spectral-consensus
48
+ mode that combines KDE cluster assignments from several FastMap dimensions. An
49
+ optional first KDE can partition objects with any user-supplied scalar feature.
50
+ In spectral-consensus mode, automatic `k` is the median number of clusters
51
+ observed by the per-dimension KDE fits, rather than the number of embeddings.
52
+ Set `consensus_n_clusters` to `"min"`, `"mean"`, `"median"`, or `"max"` to
53
+ select another reduction of those observed counts; an explicit integer remains
54
+ available when a fixed target is required.
55
+ `extrema_prominence_fraction` controls how deep a KDE valley must be relative
56
+ to that KDE's density range (the default is `0.05`); smaller fractions preserve
57
+ more candidate modes.
58
+ The estimator uses three FastMap pivot-refinement passes. Configure the number
59
+ of passes with `fastmap_iters`.
60
+
61
+ ```python
62
+ from dataclasses import dataclass
63
+
64
+ from sphncs import SphncsClusterer
65
+
66
+
67
+ @dataclass
68
+ class Point:
69
+ x: float
70
+
71
+
72
+ def distance(left: Point, right: Point) -> float:
73
+ return abs(left.x - right.x)
74
+
75
+ model = SphncsClusterer(metric=distance)
76
+ labels = model.fit_predict([Point(0.0), Point(0.2), Point(10.0), Point(10.2)])
77
+ print(model.representatives_)
78
+ ```
79
+
80
+ For optional first-stage partitioning, provide a scalar feature. Partitioning is
81
+ hard routing: objects in different feature intervals are clustered separately.
82
+
83
+ ```python
84
+ model = SphncsClusterer(
85
+ metric=distance,
86
+ partitioning=True,
87
+ partitioning_feature=lambda point: point.x,
88
+ )
89
+ ```
90
+
91
+ String distances such as `normalized_levenshtein` and `char_ngram_jaccard`
92
+ remain available in `sphncs.distances`. They are conveniences, not a restriction
93
+ on the estimator's input type.
94
+
95
+ ### Log clustering
96
+
97
+ `LogSPHNCS` is the log-specific adapter. Its `log_filters` replace selected
98
+ fields with filter-specific, fixed-width masks before embedding and clustering.
99
+ The optional initial partitioner uses filtered strings by default; pass
100
+ `partitioning_before_transform=True` to derive its feature from the original
101
+ raw strings first. It uses length by default;
102
+ set `partitioning_feature="entropy"` for character Shannon entropy or
103
+ `"normalized_entropy"` for character-use evenness. Every marker is four
104
+ characters long: timestamps use `<#T>`, severity uses `<#S>`, UUIDs use `<#U>`,
105
+ IPs use `<#I>`, hex values use `<#H>`, numbers use `<#N>`, paths use `<#P>`,
106
+ quoted values use `<#Q>`, and identifiers use `<#D>`. Choose individual filters
107
+ (`timestamp`, `severity`, `uuid`, `ip`, `hex`, `number`, `path`, `quoted`, and
108
+ `identifier`), use `variable` for all value-masking filters, or use `all` for
109
+ every filter.
110
+
111
+ The `hex` filter recognizes `0x`-prefixed values. Short bare hexadecimal
112
+ sequence fields such as `0000000e` are normalized by the `number` filter, so
113
+ they match their decimal-only counterparts without masking longer component IDs.
114
+
115
+ `representatives_` contains the filtered form by default. The original training
116
+ lines remain available in the position-aligned `raw_strings_`, through
117
+ `get_raw_string(index)`, and as `raw_representatives_` for the cluster
118
+ representatives.
119
+
120
+ ```python
121
+ model = LogSPHNCS(
122
+ log_filters=["timestamp", "severity", "variable"],
123
+ )
124
+ ```
125
+
126
+ ### LogSPHNCS
127
+
128
+ `LogSPHNCS` defaults to all log filters,
129
+ 4-gram Jaccard, length partitioning, 10-dimensional spectral consensus, and
130
+ exact filtered-template compression. Raw records remain aligned in
131
+ `raw_strings_` and `raw_representatives_`.
132
+
133
+ ```python
134
+ from sphncs import LogSPHNCS
135
+
136
+ model = LogSPHNCS().fit(log_lines)
137
+ ```
138
+
139
+ ### Model persistence
140
+
141
+ Fitted models can be saved to a versioned, integrity-checked `.sphncs` archive
142
+ and loaded later. The archive preserves prediction and transformation state.
143
+ Each FastMap projection is persisted with FastMapy’s native versioned format.
144
+
145
+ ```python
146
+ model.save("logs.sphncs")
147
+ restored = LogSPHNCS.load("logs.sphncs")
148
+ assert restored.predict(log_lines).tolist() == model.predict(log_lines).tolist()
149
+ ```
150
+
151
+ Archives use Python pickle to support arbitrary input objects and user-supplied
152
+ metrics or transformers. Only load archives from sources you trust. Callables
153
+ must be importable functions (rather than lambdas or nested functions) to save
154
+ reliably. Format version 2 is validated on load; unsupported future formats are
155
+ rejected rather than loaded incorrectly.
156
+
157
+ `fastmapy` is included as the `vendor/fastmapy` Git submodule and isolated behind
158
+ an embedding adapter. It is used for all FastMap fits, including its `fit_many`
159
+ API for spectral-consensus embeddings; no pairwise string-distance matrix is
160
+ created or retained.
161
+
162
+ ## Development
163
+
164
+ ```bash
165
+ git submodule update --init --recursive
166
+ python -m pip install -e vendor/fastmapy
167
+ python -m pip install -e '.[dev]'
168
+ python -m pytest
169
+ ```
sphncs-0.3.1/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # sphncs
2
+
3
+ Licensed under [Apache-2.0](LICENSE).
4
+
5
+ `sphncs` is the **Similarity-Preserving Hierarchical Nonparametric Clustering
6
+ System**. It clusters any objects with a well-defined, non-negative distance
7
+ metric by embedding on-demand distances with FastMap and finding density
8
+ separations with `KDEpy.FFTKDE`.
9
+
10
+ It supports a lightweight single-dimension mode and an optional spectral-consensus
11
+ mode that combines KDE cluster assignments from several FastMap dimensions. An
12
+ optional first KDE can partition objects with any user-supplied scalar feature.
13
+ In spectral-consensus mode, automatic `k` is the median number of clusters
14
+ observed by the per-dimension KDE fits, rather than the number of embeddings.
15
+ Set `consensus_n_clusters` to `"min"`, `"mean"`, `"median"`, or `"max"` to
16
+ select another reduction of those observed counts; an explicit integer remains
17
+ available when a fixed target is required.
18
+ `extrema_prominence_fraction` controls how deep a KDE valley must be relative
19
+ to that KDE's density range (the default is `0.05`); smaller fractions preserve
20
+ more candidate modes.
21
+ The estimator uses three FastMap pivot-refinement passes. Configure the number
22
+ of passes with `fastmap_iters`.
23
+
24
+ ```python
25
+ from dataclasses import dataclass
26
+
27
+ from sphncs import SphncsClusterer
28
+
29
+
30
+ @dataclass
31
+ class Point:
32
+ x: float
33
+
34
+
35
+ def distance(left: Point, right: Point) -> float:
36
+ return abs(left.x - right.x)
37
+
38
+ model = SphncsClusterer(metric=distance)
39
+ labels = model.fit_predict([Point(0.0), Point(0.2), Point(10.0), Point(10.2)])
40
+ print(model.representatives_)
41
+ ```
42
+
43
+ For optional first-stage partitioning, provide a scalar feature. Partitioning is
44
+ hard routing: objects in different feature intervals are clustered separately.
45
+
46
+ ```python
47
+ model = SphncsClusterer(
48
+ metric=distance,
49
+ partitioning=True,
50
+ partitioning_feature=lambda point: point.x,
51
+ )
52
+ ```
53
+
54
+ String distances such as `normalized_levenshtein` and `char_ngram_jaccard`
55
+ remain available in `sphncs.distances`. They are conveniences, not a restriction
56
+ on the estimator's input type.
57
+
58
+ ### Log clustering
59
+
60
+ `LogSPHNCS` is the log-specific adapter. Its `log_filters` replace selected
61
+ fields with filter-specific, fixed-width masks before embedding and clustering.
62
+ The optional initial partitioner uses filtered strings by default; pass
63
+ `partitioning_before_transform=True` to derive its feature from the original
64
+ raw strings first. It uses length by default;
65
+ set `partitioning_feature="entropy"` for character Shannon entropy or
66
+ `"normalized_entropy"` for character-use evenness. Every marker is four
67
+ characters long: timestamps use `<#T>`, severity uses `<#S>`, UUIDs use `<#U>`,
68
+ IPs use `<#I>`, hex values use `<#H>`, numbers use `<#N>`, paths use `<#P>`,
69
+ quoted values use `<#Q>`, and identifiers use `<#D>`. Choose individual filters
70
+ (`timestamp`, `severity`, `uuid`, `ip`, `hex`, `number`, `path`, `quoted`, and
71
+ `identifier`), use `variable` for all value-masking filters, or use `all` for
72
+ every filter.
73
+
74
+ The `hex` filter recognizes `0x`-prefixed values. Short bare hexadecimal
75
+ sequence fields such as `0000000e` are normalized by the `number` filter, so
76
+ they match their decimal-only counterparts without masking longer component IDs.
77
+
78
+ `representatives_` contains the filtered form by default. The original training
79
+ lines remain available in the position-aligned `raw_strings_`, through
80
+ `get_raw_string(index)`, and as `raw_representatives_` for the cluster
81
+ representatives.
82
+
83
+ ```python
84
+ model = LogSPHNCS(
85
+ log_filters=["timestamp", "severity", "variable"],
86
+ )
87
+ ```
88
+
89
+ ### LogSPHNCS
90
+
91
+ `LogSPHNCS` defaults to all log filters,
92
+ 4-gram Jaccard, length partitioning, 10-dimensional spectral consensus, and
93
+ exact filtered-template compression. Raw records remain aligned in
94
+ `raw_strings_` and `raw_representatives_`.
95
+
96
+ ```python
97
+ from sphncs import LogSPHNCS
98
+
99
+ model = LogSPHNCS().fit(log_lines)
100
+ ```
101
+
102
+ ### Model persistence
103
+
104
+ Fitted models can be saved to a versioned, integrity-checked `.sphncs` archive
105
+ and loaded later. The archive preserves prediction and transformation state.
106
+ Each FastMap projection is persisted with FastMapy’s native versioned format.
107
+
108
+ ```python
109
+ model.save("logs.sphncs")
110
+ restored = LogSPHNCS.load("logs.sphncs")
111
+ assert restored.predict(log_lines).tolist() == model.predict(log_lines).tolist()
112
+ ```
113
+
114
+ Archives use Python pickle to support arbitrary input objects and user-supplied
115
+ metrics or transformers. Only load archives from sources you trust. Callables
116
+ must be importable functions (rather than lambdas or nested functions) to save
117
+ reliably. Format version 2 is validated on load; unsupported future formats are
118
+ rejected rather than loaded incorrectly.
119
+
120
+ `fastmapy` is included as the `vendor/fastmapy` Git submodule and isolated behind
121
+ an embedding adapter. It is used for all FastMap fits, including its `fit_many`
122
+ API for spectral-consensus embeddings; no pairwise string-distance matrix is
123
+ created or retained.
124
+
125
+ ## Development
126
+
127
+ ```bash
128
+ git submodule update --init --recursive
129
+ python -m pip install -e vendor/fastmapy
130
+ python -m pip install -e '.[dev]'
131
+ python -m pytest
132
+ ```
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sphncs"
7
+ version = "0.3.1"
8
+ description = "Similarity-Preserving Hierarchical Nonparametric Clustering System"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "Shawn Davis" }]
13
+ keywords = ["clustering", "density-estimation", "fastmap", "log-analysis", "machine-learning"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
25
+ ]
26
+ dependencies = [
27
+ "numpy>=1.24",
28
+ "scipy>=1.10",
29
+ "scikit-learn>=1.3",
30
+ "KDEpy>=1.1",
31
+ "FastMapy>=0.2.0",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ dev = ["pytest>=7.4", "ruff>=0.4"]
36
+ bench = ["rapidfuzz>=3.14", "matplotlib>=3.8", "drain3>=0.9.11"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/shawn-davis/sphncs"
40
+ Repository = "https://github.com/shawn-davis/sphncs"
41
+ Issues = "https://github.com/shawn-davis/sphncs/issues"
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+
46
+ [tool.setuptools.packages.find]
47
+ include = ["sphncs*"]
sphncs-0.3.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ """Similarity-Preserving Hierarchical Nonparametric Clustering System."""
2
+
3
+ from .estimator import SphncsClusterer
4
+ from .logs import LogSPHNCS
5
+ from .persistence import ModelPersistenceError
6
+ from .preprocessing import LogPreprocessor
7
+
8
+ __all__ = ["LogPreprocessor", "LogSPHNCS", "ModelPersistenceError", "SphncsClusterer"]
@@ -0,0 +1,81 @@
1
+ """One-dimensional KDE evaluation, extrema, labels, and representatives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import numpy as np
8
+ from scipy.signal import find_peaks
9
+
10
+
11
+ @dataclass
12
+ class DensityModel:
13
+ grid: np.ndarray
14
+ density: np.ndarray
15
+ boundaries: np.ndarray
16
+ modes: np.ndarray
17
+ labels: np.ndarray
18
+ representative_indices: np.ndarray
19
+
20
+ def predict(self, values: np.ndarray) -> np.ndarray:
21
+ return np.searchsorted(self.boundaries, values, side="right").astype(int)
22
+
23
+
24
+ def fit_density(
25
+ values: np.ndarray,
26
+ *,
27
+ bandwidth: str | float = "ISJ",
28
+ grid_points: int = 1024,
29
+ prominence: float | None = None,
30
+ prominence_fraction: float = 0.05,
31
+ min_samples: int = 3,
32
+ ) -> DensityModel:
33
+ """Fit FFTKDE and turn meaningful minima into interval labels."""
34
+ values = np.asarray(values, dtype=float).reshape(-1)
35
+ if values.size == 0:
36
+ raise ValueError("KDE requires at least one value")
37
+ lower, upper = float(values.min()), float(values.max())
38
+ if values.size < min_samples or np.isclose(lower, upper):
39
+ grid = np.linspace(lower - 0.5, upper + 0.5 if upper >= lower else lower + 0.5, max(2, grid_points))
40
+ density = np.zeros_like(grid)
41
+ mode = np.array([float(values.mean())])
42
+ labels = np.zeros(values.size, dtype=int)
43
+ return DensityModel(grid, density, np.array([], dtype=float), mode, labels, np.array([int(np.argmin(abs(values - mode[0])))]) )
44
+
45
+ padding = max((upper - lower) * 0.1, np.finfo(float).eps * 100)
46
+ grid = np.linspace(lower - padding, upper + padding, grid_points)
47
+ try:
48
+ from KDEpy import FFTKDE
49
+ except ImportError as exc: # pragma: no cover - dependency declaration is authoritative
50
+ raise ImportError("KDEpy is required; install sphncs with its runtime dependencies.") from exc
51
+ try:
52
+ density = np.asarray(FFTKDE(kernel="gaussian", bw=bandwidth).fit(values).evaluate(grid), dtype=float)
53
+ except ValueError:
54
+ # ISJ can fail to find a root for small, highly discrete partitions.
55
+ # Keep an explicit user-selected bandwidth strict, but make the default
56
+ # automatic choice robust by falling back to another KDEpy rule.
57
+ if not isinstance(bandwidth, str) or bandwidth.upper() != "ISJ":
58
+ raise
59
+ density = np.asarray(FFTKDE(kernel="gaussian", bw="silverman").fit(values).evaluate(grid), dtype=float)
60
+ scale = float(np.ptp(density))
61
+ effective_prominence = (
62
+ prominence
63
+ if prominence is not None
64
+ else max(scale * prominence_fraction, np.finfo(float).eps)
65
+ )
66
+ minima, _ = find_peaks(-density, prominence=effective_prominence)
67
+ boundaries = grid[minima]
68
+ labels = np.searchsorted(boundaries, values, side="right").astype(int)
69
+
70
+ modes: list[float] = []
71
+ representatives: list[int] = []
72
+ for label in range(len(boundaries) + 1):
73
+ left = -np.inf if label == 0 else boundaries[label - 1]
74
+ right = np.inf if label == len(boundaries) else boundaries[label]
75
+ mask = (grid > left) & (grid <= right)
76
+ mode = float(grid[mask][np.argmax(density[mask])])
77
+ members = np.flatnonzero(labels == label)
78
+ if members.size:
79
+ modes.append(mode)
80
+ representatives.append(int(members[np.argmin(abs(values[members] - mode))]))
81
+ return DensityModel(grid, density, boundaries, np.asarray(modes), labels, np.asarray(representatives, dtype=int))