deltric 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.
- deltric-0.1.0/LICENSE +201 -0
- deltric-0.1.0/PKG-INFO +22 -0
- deltric-0.1.0/README.md +2 -0
- deltric-0.1.0/deltric/__init__.py +0 -0
- deltric-0.1.0/deltric/deltric.py +80 -0
- deltric-0.1.0/deltric/utils.py +295 -0
- deltric-0.1.0/deltric.egg-info/PKG-INFO +22 -0
- deltric-0.1.0/deltric.egg-info/SOURCES.txt +11 -0
- deltric-0.1.0/deltric.egg-info/dependency_links.txt +1 -0
- deltric-0.1.0/deltric.egg-info/requires.txt +7 -0
- deltric-0.1.0/deltric.egg-info/top_level.txt +1 -0
- deltric-0.1.0/pyproject.toml +28 -0
- deltric-0.1.0/setup.cfg +4 -0
deltric-0.1.0/LICENSE
ADDED
|
@@ -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 [yyyy] [name of copyright owner]
|
|
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.
|
deltric-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deltric
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A clustering algorithm implementation with sklearn-like API
|
|
5
|
+
Author-email: Your Name <your@email.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/TomasJavurek/deltric
|
|
8
|
+
Project-URL: Issues, https://github.com/TomasJavurek/deltric/issues
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy
|
|
13
|
+
Requires-Dist: scikit-learn
|
|
14
|
+
Requires-Dist: scipy
|
|
15
|
+
Requires-Dist: networkx
|
|
16
|
+
Requires-Dist: umap-learn
|
|
17
|
+
Requires-Dist: pandas
|
|
18
|
+
Requires-Dist: statsmodels
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
dt = DelTriC(prune_param=1.497, merge_param=-0.773, dim_reduction='umap', back_proj=True, anomaly_sensitivity=0.9)
|
|
22
|
+
labels = dt.fit_predict(X)
|
deltric-0.1.0/README.md
ADDED
|
File without changes
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from sklearn.base import BaseEstimator, ClusterMixin
|
|
3
|
+
from sklearn.utils.validation import check_array
|
|
4
|
+
from .utils import cluster_tri
|
|
5
|
+
|
|
6
|
+
# import your existing functions here
|
|
7
|
+
# from .deltric_core import cluster_tri # keep your implementation intact
|
|
8
|
+
|
|
9
|
+
class DelTriC(BaseEstimator, ClusterMixin):
|
|
10
|
+
"""
|
|
11
|
+
DelTriC clustering algorithm.
|
|
12
|
+
Compatible with scikit-learn estimator API.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
prune_param=-0.8,
|
|
18
|
+
merge_param=0.0,
|
|
19
|
+
min_cluster_size=10,
|
|
20
|
+
dim_reduction="umap",
|
|
21
|
+
back_proj=True,
|
|
22
|
+
anomaly_sensitivity=0.99,
|
|
23
|
+
random_state=42,
|
|
24
|
+
):
|
|
25
|
+
self.prune_param = prune_param
|
|
26
|
+
self.merge_param = merge_param
|
|
27
|
+
self.min_cluster_size = min_cluster_size
|
|
28
|
+
self.dim_reduction = dim_reduction
|
|
29
|
+
self.back_proj = back_proj
|
|
30
|
+
self.anomaly_sensitivity = anomaly_sensitivity
|
|
31
|
+
self.random_state = random_state
|
|
32
|
+
|
|
33
|
+
def fit(self, X, y=None):
|
|
34
|
+
"""
|
|
35
|
+
Fit the DelTriC model to data X.
|
|
36
|
+
|
|
37
|
+
Parameters
|
|
38
|
+
----------
|
|
39
|
+
X : array-like of shape (n_samples, n_features)
|
|
40
|
+
The input data.
|
|
41
|
+
y : Ignored
|
|
42
|
+
Not used, present for API consistency by convention.
|
|
43
|
+
"""
|
|
44
|
+
X = check_array(X)
|
|
45
|
+
|
|
46
|
+
# keep original DelTriC core untouched
|
|
47
|
+
self.labels_ = cluster_tri(
|
|
48
|
+
X,
|
|
49
|
+
prune_param=self.prune_param,
|
|
50
|
+
merge_param=self.merge_param,
|
|
51
|
+
min_cluster_size=self.min_cluster_size,
|
|
52
|
+
dim_reduction=self.dim_reduction,
|
|
53
|
+
back_proj=self.back_proj,
|
|
54
|
+
anomaly_sensitivity=self.anomaly_sensitivity,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return self
|
|
58
|
+
|
|
59
|
+
def fit_predict(self, X, y=None):
|
|
60
|
+
"""
|
|
61
|
+
Fit to data X and return cluster labels.
|
|
62
|
+
"""
|
|
63
|
+
self.fit(X, y)
|
|
64
|
+
return self.labels_
|
|
65
|
+
|
|
66
|
+
def get_params(self, deep=True):
|
|
67
|
+
return {
|
|
68
|
+
"prune_param": self.prune_param,
|
|
69
|
+
"merge_param": self.merge_param,
|
|
70
|
+
"min_cluster_size": self.min_cluster_size,
|
|
71
|
+
"dim_reduction": self.dim_reduction,
|
|
72
|
+
"back_proj": self.back_proj,
|
|
73
|
+
"anomaly_sensitivity": self.anomaly_sensitivity,
|
|
74
|
+
"random_state": self.random_state,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
def set_params(self, **params):
|
|
78
|
+
for k, v in params.items():
|
|
79
|
+
setattr(self, k, v)
|
|
80
|
+
return self
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from sklearn.decomposition import PCA
|
|
4
|
+
from scipy.spatial import Delaunay
|
|
5
|
+
import networkx as nx
|
|
6
|
+
from sklearn.manifold import TSNE
|
|
7
|
+
from umap import UMAP
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from statsmodels import robust
|
|
11
|
+
|
|
12
|
+
ANOMALY_THRESH = 3
|
|
13
|
+
|
|
14
|
+
def get_triangles_with_edges(X, project_dim=2, method='umap', back_proj=True):
|
|
15
|
+
# Project if needed
|
|
16
|
+
if method == 'pca' and X.shape[1] > project_dim:
|
|
17
|
+
projector = PCA(n_components=project_dim, random_state=42)
|
|
18
|
+
X_proj = projector.fit_transform(X)
|
|
19
|
+
elif method == 'umap' and X.shape[1] > project_dim:
|
|
20
|
+
projector = UMAP(n_components=project_dim, random_state=42)
|
|
21
|
+
X_proj = projector.fit_transform(X)
|
|
22
|
+
elif method == 'none' or X.shape[1] <= project_dim:
|
|
23
|
+
X_proj = X
|
|
24
|
+
else:
|
|
25
|
+
raise ValueError("Invalid projection method. Choose from 'pca', 'umap', or 'none'.")
|
|
26
|
+
|
|
27
|
+
tri = Delaunay(X_proj)
|
|
28
|
+
triangles = tri.simplices # shape (num_triangles, 3)
|
|
29
|
+
|
|
30
|
+
# Calculate triangle sizes (max edge length)
|
|
31
|
+
triangle_sizes = []
|
|
32
|
+
triangle_sizes_proj = []
|
|
33
|
+
for simplex in triangles:
|
|
34
|
+
pts = X[list(simplex)] # original space points for accurate edge lengths
|
|
35
|
+
pts_proj = X_proj[list(simplex)]
|
|
36
|
+
if back_proj==False:
|
|
37
|
+
pts = pts_proj
|
|
38
|
+
edges = [np.linalg.norm(pts[i] - pts[(i+1)%3]) for i in range(3)]
|
|
39
|
+
edges_proj = [np.linalg.norm(pts_proj[i] - pts_proj[(i+1)%3]) for i in range(3)]
|
|
40
|
+
max_edge = max(edges)
|
|
41
|
+
max_edge_proj = max(edges_proj)
|
|
42
|
+
triangle_sizes.append(max_edge)
|
|
43
|
+
triangle_sizes_proj.append(max_edge_proj)
|
|
44
|
+
|
|
45
|
+
return triangles, np.array(triangle_sizes), np.array(triangle_sizes_proj), X_proj
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# 4️⃣ Get clusters from remaining edges
|
|
49
|
+
def get_clusters(edges, n_points):
|
|
50
|
+
G = nx.Graph()
|
|
51
|
+
G.add_nodes_from(range(n_points))
|
|
52
|
+
G.add_edges_from(edges)
|
|
53
|
+
clusters = [list(c) for c in nx.connected_components(G)]
|
|
54
|
+
return clusters
|
|
55
|
+
|
|
56
|
+
def cluster_umap_representative(X, X_proj, clusters):
|
|
57
|
+
reps = []
|
|
58
|
+
for cluster in clusters:
|
|
59
|
+
pts_proj = X_proj[cluster]
|
|
60
|
+
center = pts_proj.mean(axis=0)
|
|
61
|
+
# find the index in the original dataset
|
|
62
|
+
idx = cluster[np.argmin(np.linalg.norm(pts_proj - center, axis=1))]
|
|
63
|
+
reps.append(X_proj[idx]) # X would be actual point, if X_proj used, the merging effectively runs only in umap space. There is only few points after creating centroids, thus umap would create manifolds wrongly.
|
|
64
|
+
return np.array(reps)
|
|
65
|
+
|
|
66
|
+
def merge_anomalies_triangles(X, X_proj, clusters, triangles, sizes, proj_sizes, dist_thresh=0.15,
|
|
67
|
+
anomaly_thresh=1, max_iter=1, debug=True):
|
|
68
|
+
|
|
69
|
+
scaling_factor = (np.median(proj_sizes) / np.median(sizes))
|
|
70
|
+
|
|
71
|
+
# Map point -> cluster
|
|
72
|
+
point_to_cluster = {}
|
|
73
|
+
for ci, cluster in enumerate(clusters):
|
|
74
|
+
for p in cluster:
|
|
75
|
+
point_to_cluster[p] = ci
|
|
76
|
+
|
|
77
|
+
merged_clusters = [list(c) for c in clusters] # deep copy
|
|
78
|
+
|
|
79
|
+
for it in range(max_iter):
|
|
80
|
+
if debug:
|
|
81
|
+
print(f"\nIteration {it+1}/{max_iter}")
|
|
82
|
+
|
|
83
|
+
merged_any = False
|
|
84
|
+
anomaly_count = 0
|
|
85
|
+
merged_count = 0
|
|
86
|
+
|
|
87
|
+
for ci, cluster in enumerate(list(merged_clusters)):
|
|
88
|
+
if len(cluster) > anomaly_thresh:
|
|
89
|
+
continue # only anomalies
|
|
90
|
+
if len(cluster) == 0:
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
anomaly_count += 1
|
|
94
|
+
# p = cluster[0]
|
|
95
|
+
|
|
96
|
+
dists = {}
|
|
97
|
+
for p in cluster:
|
|
98
|
+
|
|
99
|
+
# Find triangles containing this anomaly
|
|
100
|
+
tri_mask = np.any(triangles == p, axis=1)
|
|
101
|
+
tri_candidates = triangles[tri_mask]
|
|
102
|
+
size_candidates = sizes[tri_mask]
|
|
103
|
+
|
|
104
|
+
if tri_candidates.size == 0:
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
# Collect neighbors from all triangles
|
|
108
|
+
neighbor_points = set()
|
|
109
|
+
for tri in tri_candidates:
|
|
110
|
+
for q in tri:
|
|
111
|
+
if q != p and q in point_to_cluster and point_to_cluster[q] != ci:
|
|
112
|
+
neighbor_points.add(q)
|
|
113
|
+
|
|
114
|
+
neighbor_points = list(neighbor_points)
|
|
115
|
+
|
|
116
|
+
# Distances to anomaly in both spaces
|
|
117
|
+
for q in neighbor_points:
|
|
118
|
+
d_X = scaling_factor * np.linalg.norm(X[p] - X[q])
|
|
119
|
+
d_Xproj = np.linalg.norm(X_proj[p] - X_proj[q])
|
|
120
|
+
_d = max(d_X, d_Xproj)
|
|
121
|
+
dists[q] = _d if _d < dists.get(q, float('inf')) else dists.get(q, float('inf'))
|
|
122
|
+
|
|
123
|
+
n = len(dists)
|
|
124
|
+
if n == 0:
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
# Aggregate scores per cluster
|
|
128
|
+
cluster_scores = {}
|
|
129
|
+
mean_size = scaling_factor * np.mean(sizes) # could also use np.mean(size_candidates)
|
|
130
|
+
for q, dist in dists.items():
|
|
131
|
+
if dist == 0:
|
|
132
|
+
continue
|
|
133
|
+
neigh_cluster = point_to_cluster[q]
|
|
134
|
+
contrib = 1.0 / dist
|
|
135
|
+
cluster_scores[neigh_cluster] = cluster_scores.get(neigh_cluster, 0.0) + contrib
|
|
136
|
+
|
|
137
|
+
if not cluster_scores:
|
|
138
|
+
continue
|
|
139
|
+
|
|
140
|
+
# Normalize by n and multiply by mean_size
|
|
141
|
+
for k in cluster_scores:
|
|
142
|
+
cluster_scores[k] = (1.0 / n) * mean_size * cluster_scores[k]
|
|
143
|
+
|
|
144
|
+
# Pick cluster with max score
|
|
145
|
+
target_cluster, best_score = max(cluster_scores.items(), key=lambda x: x[1])
|
|
146
|
+
|
|
147
|
+
if best_score > dist_thresh:
|
|
148
|
+
continue
|
|
149
|
+
|
|
150
|
+
# Merge anomaly
|
|
151
|
+
merged_clusters[target_cluster].extend(cluster)
|
|
152
|
+
merged_clusters[ci] = []
|
|
153
|
+
merged_any = True
|
|
154
|
+
merged_count += 1
|
|
155
|
+
|
|
156
|
+
if debug:
|
|
157
|
+
print(f" - Anomalies processed: {anomaly_count}")
|
|
158
|
+
print(f" - Merged this round: {merged_count}")
|
|
159
|
+
|
|
160
|
+
# Update mapping if we merged
|
|
161
|
+
if merged_any:
|
|
162
|
+
point_to_cluster = {}
|
|
163
|
+
for ci, cluster in enumerate(merged_clusters):
|
|
164
|
+
for p in cluster:
|
|
165
|
+
point_to_cluster[p] = ci
|
|
166
|
+
else:
|
|
167
|
+
break # no more merges → stop early
|
|
168
|
+
|
|
169
|
+
# Remove empty clusters
|
|
170
|
+
merged_clusters = [sorted(c) for c in merged_clusters if len(c) > 0]
|
|
171
|
+
return merged_clusters
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def sigma_prune_triangles(triangles, sizes, proj_sizes, sigma_factor):
|
|
175
|
+
# Normalize sizes to have comparable scales
|
|
176
|
+
#scaling_factor = (np.median(proj_sizes) / np.median(sizes))
|
|
177
|
+
#sizes_z = sizes * scaling_factor
|
|
178
|
+
#proj_sizes_z = proj_sizes
|
|
179
|
+
|
|
180
|
+
# sizes_z = (sizes - sizes.mean()) / sizes.std()
|
|
181
|
+
# proj_sizes_z = (proj_sizes - proj_sizes.mean()) / proj_sizes.std()
|
|
182
|
+
# mean_size = np.mean(sizes_z)
|
|
183
|
+
# sigma = np.std(sizes_z)
|
|
184
|
+
# threshold = mean_size + sigma_factor * sigma
|
|
185
|
+
|
|
186
|
+
# sizes_z = dominant_bump_normalization(sizes, sigma_factor)
|
|
187
|
+
# proj_sizes_z = dominant_bump_normalization(proj_sizes, sigma_factor)
|
|
188
|
+
# threshold = sigma_factor # since sizes_z are already in z-score form
|
|
189
|
+
|
|
190
|
+
mu = np.median(sizes)
|
|
191
|
+
sigma = robust.mad(sizes) # robust std
|
|
192
|
+
sizes_z = (sizes - mu) / sigma
|
|
193
|
+
mu = np.median(proj_sizes)
|
|
194
|
+
sigma = robust.mad(proj_sizes) # robust std
|
|
195
|
+
proj_sizes_z = (proj_sizes - mu) / sigma
|
|
196
|
+
|
|
197
|
+
mean_size = np.mean(sizes_z)
|
|
198
|
+
sigma = np.std(sizes_z)
|
|
199
|
+
threshold = mean_size + sigma_factor * sigma
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
kept_triangles = triangles[np.maximum(sizes_z, proj_sizes_z) <= threshold] # we trust umap to create a distinct clusters
|
|
203
|
+
rm_triangles = triangles[np.maximum(sizes_z, proj_sizes_z) > threshold]
|
|
204
|
+
edges = set()
|
|
205
|
+
rm_edges = set()
|
|
206
|
+
for tri in rm_triangles:
|
|
207
|
+
for i in range(3):
|
|
208
|
+
a, b = sorted((tri[i], tri[(i+1)%3]))
|
|
209
|
+
rm_edges.add((a, b))
|
|
210
|
+
for tri in kept_triangles:
|
|
211
|
+
for i in range(3):
|
|
212
|
+
a, b = sorted((tri[i], tri[(i+1)%3]))
|
|
213
|
+
edges.add((a, b))
|
|
214
|
+
return list(edges), list(rm_edges), threshold
|
|
215
|
+
|
|
216
|
+
def merge_clusters(X, X_proj, clusters, method, merge_param, back_proj=True, anomaly_thresh=2, min_centroids=5):
|
|
217
|
+
# Compute centroids of clusters in original high-dimensional space
|
|
218
|
+
# centroids = np.array([np.mean(X[cluster], axis=0) for cluster in clusters])
|
|
219
|
+
anomalies = [cl for cl in clusters if len(cl) <= anomaly_thresh]
|
|
220
|
+
rich_clusters = [cl for cl in clusters if len(cl) > anomaly_thresh]
|
|
221
|
+
centroids = cluster_umap_representative(X, X_proj, rich_clusters)
|
|
222
|
+
if len(centroids) < min_centroids:
|
|
223
|
+
return clusters
|
|
224
|
+
|
|
225
|
+
try:
|
|
226
|
+
# Triangulate on centroids
|
|
227
|
+
triangles, sizes, proj_sizes, _ = get_triangles_with_edges(centroids, project_dim=2, method=method, back_proj=back_proj)
|
|
228
|
+
|
|
229
|
+
# Merge clusters if triangle size <= mean + merge_param*sigma
|
|
230
|
+
edges_between_clusters, _, _ = sigma_prune_triangles(triangles, sizes, proj_sizes, sigma_factor=merge_param)
|
|
231
|
+
|
|
232
|
+
# Build graph where nodes are clusters and edges mean merge
|
|
233
|
+
G = nx.Graph()
|
|
234
|
+
G.add_nodes_from(range(len(rich_clusters)))
|
|
235
|
+
G.add_edges_from(edges_between_clusters)
|
|
236
|
+
|
|
237
|
+
merged_clusters = []
|
|
238
|
+
for comp in nx.connected_components(G):
|
|
239
|
+
merged_points = []
|
|
240
|
+
for cluster_idx in comp:
|
|
241
|
+
merged_points.extend(rich_clusters[cluster_idx])
|
|
242
|
+
merged_clusters.append(sorted(merged_points))
|
|
243
|
+
|
|
244
|
+
return merged_clusters + anomalies # add back anomalies as separate clusters
|
|
245
|
+
except:
|
|
246
|
+
print('!!! Cluster Merging Failed !!!')
|
|
247
|
+
return clusters
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def tri_cluster_sigma_merge(X, prune_param=0.15, merge_param=-0.2, method='umap', anomaly_sensitivity=0.5, back_proj=True, debug=False):
|
|
251
|
+
# Step 1: Triangles & sigma pruning
|
|
252
|
+
triangles, sizes, proj_sizes, X_proj = get_triangles_with_edges(X, project_dim=2, method=method, back_proj=back_proj)
|
|
253
|
+
pruned_edges, rm_edges, threshold = sigma_prune_triangles(triangles, sizes, proj_sizes, sigma_factor=prune_param)
|
|
254
|
+
clusters = get_clusters(pruned_edges, len(X))
|
|
255
|
+
if debug:
|
|
256
|
+
print(f"After pruning: {len(clusters)} clusters")
|
|
257
|
+
print(f"Anomalies: {len([cl for cl in clusters if len(cl) <= ANOMALY_THRESH])}")
|
|
258
|
+
|
|
259
|
+
# Step 2: Merge pass on centroids
|
|
260
|
+
merged_clusters = merge_clusters(X, X_proj, clusters, method, merge_param, back_proj=back_proj, anomaly_thresh=ANOMALY_THRESH)
|
|
261
|
+
if debug:
|
|
262
|
+
print(f"After merging clusters: {len(merged_clusters)} clusters")
|
|
263
|
+
|
|
264
|
+
if anomaly_sensitivity < 1.00:
|
|
265
|
+
# threshold = np.mean(sizes) + np.std(sizes) * prune_param
|
|
266
|
+
# dist_thresh = threshold / anomaly_sensitivity # fix this completely to the projected space
|
|
267
|
+
dist_thresh = 1.0 - anomaly_sensitivity
|
|
268
|
+
# merged_clusters = merge_anomalies(X, X_proj, merged_clusters, dist_thresh=dist_thresh, anomaly_thresh=ANOMALY_THRESH)
|
|
269
|
+
_X = X
|
|
270
|
+
if back_proj==False:
|
|
271
|
+
_X = X_proj
|
|
272
|
+
merged_clusters = merge_anomalies_triangles(_X, X_proj, merged_clusters, triangles, sizes, proj_sizes, dist_thresh=dist_thresh, anomaly_thresh=ANOMALY_THRESH, max_iter=3, debug=True)
|
|
273
|
+
|
|
274
|
+
if debug:
|
|
275
|
+
print(f"After merging anomalies: {len(merged_clusters)} clusters")
|
|
276
|
+
|
|
277
|
+
# Keeping same output structure, but adding merged_clusters as extra
|
|
278
|
+
return triangles, sizes, pruned_edges, rm_edges, merged_clusters
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def cluster_tri(X, prune_param=-0.8, merge_param=0.0, min_cluster_size=10, dim_reduction='umap', back_proj=True, anomaly_sensitivity=0.99):
|
|
282
|
+
_, _, pruned_edges, _, clusters = tri_cluster_sigma_merge(X, prune_param=prune_param, merge_param=merge_param, method=dim_reduction, back_proj=back_proj, anomaly_sensitivity=anomaly_sensitivity)
|
|
283
|
+
|
|
284
|
+
# Start with all points as noise
|
|
285
|
+
labels = np.full(len(X), -1, dtype=int)
|
|
286
|
+
|
|
287
|
+
label_id = 0
|
|
288
|
+
for cluster in clusters:
|
|
289
|
+
if len(cluster) > ANOMALY_THRESH:
|
|
290
|
+
for idx in cluster:
|
|
291
|
+
labels[idx] = label_id
|
|
292
|
+
label_id += 1
|
|
293
|
+
# else: keep as -1 (noise)
|
|
294
|
+
|
|
295
|
+
return labels
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deltric
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A clustering algorithm implementation with sklearn-like API
|
|
5
|
+
Author-email: Your Name <your@email.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/TomasJavurek/deltric
|
|
8
|
+
Project-URL: Issues, https://github.com/TomasJavurek/deltric/issues
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy
|
|
13
|
+
Requires-Dist: scikit-learn
|
|
14
|
+
Requires-Dist: scipy
|
|
15
|
+
Requires-Dist: networkx
|
|
16
|
+
Requires-Dist: umap-learn
|
|
17
|
+
Requires-Dist: pandas
|
|
18
|
+
Requires-Dist: statsmodels
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
dt = DelTriC(prune_param=1.497, merge_param=-0.773, dim_reduction='umap', back_proj=True, anomaly_sensitivity=0.9)
|
|
22
|
+
labels = dt.fit_predict(X)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
deltric/__init__.py
|
|
5
|
+
deltric/deltric.py
|
|
6
|
+
deltric/utils.py
|
|
7
|
+
deltric.egg-info/PKG-INFO
|
|
8
|
+
deltric.egg-info/SOURCES.txt
|
|
9
|
+
deltric.egg-info/dependency_links.txt
|
|
10
|
+
deltric.egg-info/requires.txt
|
|
11
|
+
deltric.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
deltric
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "deltric"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="Your Name", email="your@email.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "A clustering algorithm implementation with sklearn-like API"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
license = { text = "MIT" }
|
|
14
|
+
requires-python = ">=3.8"
|
|
15
|
+
|
|
16
|
+
dependencies = [
|
|
17
|
+
"numpy",
|
|
18
|
+
"scikit-learn",
|
|
19
|
+
"scipy",
|
|
20
|
+
"networkx",
|
|
21
|
+
"umap-learn",
|
|
22
|
+
"pandas",
|
|
23
|
+
"statsmodels"
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/TomasJavurek/deltric"
|
|
28
|
+
Issues = "https://github.com/TomasJavurek/deltric/issues"
|
deltric-0.1.0/setup.cfg
ADDED