1use crate::error::{ClusterError, ClusterResult};
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6use torsh_tensor::Tensor;
7
8pub trait ClusteringResult: Clone + std::fmt::Debug {
10 fn labels(&self) -> Option<&Tensor>;
18
19 fn n_clusters(&self) -> usize;
21
22 fn centers(&self) -> Option<&Tensor> {
24 None
25 }
26
27 fn inertia(&self) -> Option<f64> {
29 None
30 }
31
32 fn n_iter(&self) -> Option<usize> {
34 None
35 }
36
37 fn converged(&self) -> bool {
39 true
40 }
41
42 fn metadata(&self) -> Option<&std::collections::HashMap<String, String>> {
44 None
45 }
46}
47
48pub trait Fit {
50 type Result: ClusteringResult;
51
52 fn fit(&self, data: &Tensor) -> ClusterResult<Self::Result>;
54}
55
56pub trait FitPredict {
58 type Result: ClusteringResult;
59
60 fn fit_predict(&self, data: &Tensor) -> ClusterResult<Self::Result>;
62}
63
64pub trait Transform {
66 fn transform(&self, data: &Tensor) -> ClusterResult<Tensor>;
68
69 fn predict_proba(&self, _data: &Tensor) -> ClusterResult<Tensor> {
71 Err(ClusterError::NotImplemented(
72 "predict_proba not implemented for this algorithm".to_string(),
73 ))
74 }
75}
76
77pub trait Predict {
79 fn predict(&self, data: &Tensor) -> ClusterResult<Tensor>;
81}
82
83pub trait ClusteringAlgorithm: Fit + FitPredict {
85 fn name(&self) -> &str;
87
88 fn get_params(&self) -> std::collections::HashMap<String, String>;
90
91 fn set_params(
93 &mut self,
94 params: std::collections::HashMap<String, String>,
95 ) -> ClusterResult<()>;
96
97 fn is_fitted(&self) -> bool {
99 false
100 }
101
102 fn validate_input(&self, data: &Tensor) -> ClusterResult<()> {
104 if data.shape().dims().is_empty() {
105 return Err(ClusterError::EmptyDataset);
106 }
107
108 if data.shape().dims()[0] == 0 {
109 return Err(ClusterError::EmptyDataset);
110 }
111
112 Ok(())
113 }
114
115 fn supported_distance_metrics(&self) -> Vec<&str> {
117 vec!["euclidean"]
118 }
119
120 fn complexity_info(&self) -> AlgorithmComplexity {
122 AlgorithmComplexity::default()
123 }
124}
125
126#[derive(Debug, Clone)]
128#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
129pub struct AlgorithmComplexity {
130 pub time_complexity: String,
132 pub space_complexity: String,
134 pub deterministic: bool,
136 pub online_capable: bool,
138 pub memory_pattern: MemoryPattern,
140}
141
142impl Default for AlgorithmComplexity {
143 fn default() -> Self {
144 Self {
145 time_complexity: "O(n)".to_string(),
146 space_complexity: "O(n)".to_string(),
147 deterministic: false,
148 online_capable: false,
149 memory_pattern: MemoryPattern::Linear,
150 }
151 }
152}
153
154#[derive(Debug, Clone)]
156#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
157pub enum MemoryPattern {
158 Linear,
160 Quadratic,
162 Constant,
164 Adaptive,
166}
167
168pub trait IncrementalClustering {
170 type Result: ClusteringResult;
171
172 fn partial_fit_one(&mut self, point: &Tensor) -> ClusterResult<()>;
174
175 fn partial_fit(&mut self, data: &Tensor) -> ClusterResult<()>;
177
178 fn current_result(&self) -> ClusterResult<Self::Result>;
180
181 fn reset(&mut self);
183}
184
185pub trait HierarchicalClustering {
187 type Tree;
188
189 fn get_tree(&self) -> Option<&Self::Tree> {
191 None
192 }
193
194 fn extract_flat_clustering(&self, n_clusters: usize) -> ClusterResult<Tensor>;
196
197 fn extract_clustering_by_distance(&self, threshold: f64) -> ClusterResult<Tensor>;
199}
200
201pub trait ProbabilisticClustering {
203 fn membership_probabilities(&self, data: &Tensor) -> ClusterResult<Tensor>;
205
206 fn cluster_parameters(&self) -> ClusterResult<Vec<std::collections::HashMap<String, Tensor>>>;
208
209 fn log_likelihood(&self, data: &Tensor) -> ClusterResult<f64>;
211
212 fn sample(&self, n_samples: usize) -> ClusterResult<Tensor>;
214}
215
216pub trait DensityBasedClustering {
218 fn core_points(&self) -> Option<&Tensor> {
220 None
221 }
222
223 fn noise_points(&self) -> Option<&Tensor> {
225 None
226 }
227
228 fn density_estimates(&self, data: &Tensor) -> ClusterResult<Tensor>;
230}
231
232pub trait ClusteringConfig: Clone + std::fmt::Debug {
234 fn validate(&self) -> ClusterResult<()>;
236
237 fn default() -> Self;
239
240 fn merge(&mut self, other: &Self);
242}