1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use std::collections::HashSet;
use crate::{math::matrix::MatrixView, FloatNumber};
/// Seed initializer for clustering algorithms.
#[derive(Debug)]
pub enum Initializer {
/// Seed initializer using a grid pattern.
Grid,
}
impl Initializer {
/// Initializes the seeds for clustering.
///
/// # Type Parameters
/// * `T` - The floating point type.
/// * `N` - The number of dimensions.
///
/// # Arguments
/// * `matrix` - The matrix of points.
/// * `k` - The number of seeds to initialize.
///
/// # Returns
/// A set of indices representing the seeds for clustering.
#[must_use]
pub fn initialize<T, const N: usize>(
&self,
matrix: &MatrixView<'_, T, N>,
k: usize,
) -> HashSet<usize>
where
T: FloatNumber,
{
if k == 0 {
return HashSet::new();
}
if k > matrix.size() {
return HashSet::from_iter(0..matrix.size());
}
match self {
Self::Grid => self.initialize_grid(matrix, k),
}
}
/// Initializes the seeds using a grid pattern.
///
/// # Type Parameters
/// * `T` - The floating point type.
/// * `N` - The number of dimensions.
///
/// # Arguments
/// * `matrix` - The matrix of points.
/// * `k` - The number of seeds to initialize.
///
/// # Returns
/// A set of indices representing the seeds for clustering.
#[must_use]
fn initialize_grid<T, const N: usize>(
&self,
matrix: &MatrixView<'_, T, N>,
k: usize,
) -> HashSet<usize>
where
T: FloatNumber,
{
let step = (T::from_usize(matrix.size()) / T::from_usize(k))
.sqrt()
.round()
.trunc_to_usize()
.max(1); // Ensure step is at least 1
let offset = step / 2;
let (cols, rows) = matrix.shape();
let mut seeds = HashSet::with_capacity(k);
'outer: for i in (offset..cols).step_by(step) {
'inner: for j in (offset..rows).step_by(step) {
let col = i.min(cols - 1);
let row = j.min(rows - 1);
let index = match matrix.index(col, row) {
Some(index) => index,
None => continue 'inner,
};
seeds.insert(index);
if seeds.len() >= k {
break 'outer;
}
}
}
seeds
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
use crate::math::{matrix::MatrixView, Point};
#[must_use]
fn sample_points<T>(cols: usize, rows: usize) -> Vec<Point<T, 2>>
where
T: FloatNumber,
{
vec![[T::zero(); 2]; cols * rows]
}
#[rstest]
#[case(1, vec![65])] // (5, 5)
#[case(2, vec![39, 46])] // (3, 3), (10, 3)
#[case(4, vec![26, 31, 86, 91])] // (2, 2), (7, 2), (2, 7), (7, 7)
#[case(6, vec![26, 30, 34, 74, 78, 82])] // (2, 2), (6, 2), (10, 2), (2, 6), (6, 6), (10, 6)
fn test_initialize_grid(#[case] k: usize, #[case] expected: Vec<usize>) {
// Arrange
let cols = 12;
let rows = 9;
let points = sample_points::<f64>(cols, rows);
let matrix = MatrixView::new(cols, rows, &points).unwrap();
// Act
let actual = Initializer::Grid.initialize(&matrix, k);
// Assert
assert_eq!(actual.len(), expected.len());
assert_eq!(actual, HashSet::from_iter(expected));
}
#[test]
fn test_initialize_zero_seeds() {
// Arrange
let cols = 4;
let rows = 9;
let points = sample_points::<f64>(cols, rows);
let matrix = MatrixView::new(cols, rows, &points).unwrap();
// Act
let actual = Initializer::Grid.initialize(&matrix, 0);
// Assert
assert_eq!(actual.len(), 0);
}
#[test]
fn test_initialize_too_many_seeds() {
// Arrange
let cols = 4;
let rows = 9;
let points = sample_points::<f64>(cols, rows);
let matrix = MatrixView::new(cols, rows, &points).unwrap();
// Act
let actual = Initializer::Grid.initialize(&matrix, cols * rows + 1);
// Assert
assert_eq!(actual.len(), 36);
}
}