Skip to main content

torsh_cluster/
traits.rs

1//! Core traits for clustering algorithms
2
3use crate::error::{ClusterError, ClusterResult};
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6use torsh_tensor::Tensor;
7
8/// Trait for clustering algorithm results
9pub trait ClusteringResult: Clone + std::fmt::Debug {
10    /// Get cluster labels for each data point, if available.
11    ///
12    /// Most algorithms always have labels, but online/incremental results
13    /// may not (e.g. before any batch has been processed), so this is
14    /// fallible rather than panicking. Concrete result types that always
15    /// have labels additionally expose an inherent `labels(&self) -> &Tensor`
16    /// method for convenient unwrapped access.
17    fn labels(&self) -> Option<&Tensor>;
18
19    /// Get number of clusters found
20    fn n_clusters(&self) -> usize;
21
22    /// Get cluster centers/representatives (if applicable)
23    fn centers(&self) -> Option<&Tensor> {
24        None
25    }
26
27    /// Get inertia/within-cluster sum of squares (if applicable)
28    fn inertia(&self) -> Option<f64> {
29        None
30    }
31
32    /// Get number of iterations to convergence (if applicable)
33    fn n_iter(&self) -> Option<usize> {
34        None
35    }
36
37    /// Check if algorithm converged
38    fn converged(&self) -> bool {
39        true
40    }
41
42    /// Get additional metadata
43    fn metadata(&self) -> Option<&std::collections::HashMap<String, String>> {
44        None
45    }
46}
47
48/// Trait for fitting clustering algorithms
49pub trait Fit {
50    type Result: ClusteringResult;
51
52    /// Fit the clustering algorithm to data
53    fn fit(&self, data: &Tensor) -> ClusterResult<Self::Result>;
54}
55
56/// Trait for fitting and predicting in one step
57pub trait FitPredict {
58    type Result: ClusteringResult;
59
60    /// Fit the algorithm and return predictions
61    fn fit_predict(&self, data: &Tensor) -> ClusterResult<Self::Result>;
62}
63
64/// Trait for transforming data using fitted clustering model
65pub trait Transform {
66    /// Transform data to cluster distance space
67    fn transform(&self, data: &Tensor) -> ClusterResult<Tensor>;
68
69    /// Transform data to cluster probability space (for probabilistic methods)
70    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
77/// Trait for predicting cluster assignments for new data
78pub trait Predict {
79    /// Predict cluster labels for new data
80    fn predict(&self, data: &Tensor) -> ClusterResult<Tensor>;
81}
82
83/// Main trait for clustering algorithms
84pub trait ClusteringAlgorithm: Fit + FitPredict {
85    /// Get algorithm name
86    fn name(&self) -> &str;
87
88    /// Get algorithm parameters as key-value pairs
89    fn get_params(&self) -> std::collections::HashMap<String, String>;
90
91    /// Set algorithm parameters
92    fn set_params(
93        &mut self,
94        params: std::collections::HashMap<String, String>,
95    ) -> ClusterResult<()>;
96
97    /// Check if algorithm is fitted
98    fn is_fitted(&self) -> bool {
99        false
100    }
101
102    /// Validate input data
103    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    /// Get supported distance metrics
116    fn supported_distance_metrics(&self) -> Vec<&str> {
117        vec!["euclidean"]
118    }
119
120    /// Get algorithm complexity information
121    fn complexity_info(&self) -> AlgorithmComplexity {
122        AlgorithmComplexity::default()
123    }
124}
125
126/// Information about algorithm computational complexity
127#[derive(Debug, Clone)]
128#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
129pub struct AlgorithmComplexity {
130    /// Time complexity description
131    pub time_complexity: String,
132    /// Space complexity description
133    pub space_complexity: String,
134    /// Whether algorithm is deterministic
135    pub deterministic: bool,
136    /// Whether algorithm supports online/incremental learning
137    pub online_capable: bool,
138    /// Typical memory usage pattern
139    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/// Memory usage patterns for clustering algorithms
155#[derive(Debug, Clone)]
156#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
157pub enum MemoryPattern {
158    /// Linear in number of data points
159    Linear,
160    /// Quadratic in number of data points
161    Quadratic,
162    /// Constant memory usage
163    Constant,
164    /// Memory usage depends on cluster structure
165    Adaptive,
166}
167
168/// Trait for incremental/online clustering algorithms
169pub trait IncrementalClustering {
170    type Result: ClusteringResult;
171
172    /// Add a single data point
173    fn partial_fit_one(&mut self, point: &Tensor) -> ClusterResult<()>;
174
175    /// Add a batch of data points
176    fn partial_fit(&mut self, data: &Tensor) -> ClusterResult<()>;
177
178    /// Get current clustering result
179    fn current_result(&self) -> ClusterResult<Self::Result>;
180
181    /// Reset the incremental state
182    fn reset(&mut self);
183}
184
185/// Trait for hierarchical clustering algorithms
186pub trait HierarchicalClustering {
187    type Tree;
188
189    /// Get the full clustering tree/dendrogram
190    fn get_tree(&self) -> Option<&Self::Tree> {
191        None
192    }
193
194    /// Extract flat clustering at given number of clusters
195    fn extract_flat_clustering(&self, n_clusters: usize) -> ClusterResult<Tensor>;
196
197    /// Extract flat clustering at given distance threshold
198    fn extract_clustering_by_distance(&self, threshold: f64) -> ClusterResult<Tensor>;
199}
200
201/// Trait for probabilistic clustering algorithms
202pub trait ProbabilisticClustering {
203    /// Get cluster membership probabilities
204    fn membership_probabilities(&self, data: &Tensor) -> ClusterResult<Tensor>;
205
206    /// Get cluster parameters (means, covariances, etc.)
207    fn cluster_parameters(&self) -> ClusterResult<Vec<std::collections::HashMap<String, Tensor>>>;
208
209    /// Compute log-likelihood of data
210    fn log_likelihood(&self, data: &Tensor) -> ClusterResult<f64>;
211
212    /// Sample from the cluster distribution
213    fn sample(&self, n_samples: usize) -> ClusterResult<Tensor>;
214}
215
216/// Trait for density-based clustering algorithms
217pub trait DensityBasedClustering {
218    /// Get core points (points with sufficient local density)
219    fn core_points(&self) -> Option<&Tensor> {
220        None
221    }
222
223    /// Get noise points (outliers)
224    fn noise_points(&self) -> Option<&Tensor> {
225        None
226    }
227
228    /// Get local density estimates
229    fn density_estimates(&self, data: &Tensor) -> ClusterResult<Tensor>;
230}
231
232/// Configuration trait for clustering algorithms
233pub trait ClusteringConfig: Clone + std::fmt::Debug {
234    /// Validate configuration parameters
235    fn validate(&self) -> ClusterResult<()>;
236
237    /// Get default configuration
238    fn default() -> Self;
239
240    /// Merge with another configuration
241    fn merge(&mut self, other: &Self);
242}