1use std::collections::VecDeque;
6
7use num_traits::Float;
8use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
9use srtree::{Euclidean, SRTree};
10
11pub type Labels = Vec<i32>;
13pub type Lifetimes = Vec<i32>;
15
16pub fn fit<T>(data: &[Vec<T>], eps: T) -> (Labels, Lifetimes)
18where
19 T: Float + Send + Sync,
20{
21 let indices = build_neighbour_graph(data, eps);
22
23 let (labels, lifetime) = fit_with(&indices);
24
25 (labels, lifetime)
26}
27
28pub fn fit_with(indices: &[Vec<usize>]) -> (Labels, Lifetimes) {
30 let (lifetimes, sorted_ids) = compute_lifetime(indices);
31
32 let labels = cluster(indices, &lifetimes, &sorted_ids);
33
34 (labels, lifetimes)
35}
36
37fn build_neighbour_graph<T>(data: &[Vec<T>], eps: T) -> Vec<Vec<usize>>
39where
40 T: Float + Send + Sync,
41{
42 let index = SRTree::default(data, Euclidean::default()).unwrap();
43
44 data.par_iter()
45 .enumerate()
46 .map(|(row_i, p)| {
47 let mut neighbours = index.query_radius(p, eps);
49
50 neighbours.retain(|col_id| *col_id != row_i);
52
53 neighbours
54 })
55 .collect()
56}
57
58fn compute_lifetime(indices: &[Vec<usize>]) -> (Lifetimes, Vec<usize>) {
60 let n = indices.len();
61
62 let mut lifetimes = vec![-1; n];
63 let mut sorted_ids = vec![0; n];
64 let mut filter = vec![false; n];
65
66 let mut buckets = Vec::with_capacity(8);
68 let mut degree: Vec<_> = indices
69 .iter()
70 .enumerate()
71 .map(|(idx, neighbours)| {
72 let d = neighbours.len();
73
74 while d >= buckets.len() {
75 buckets.push(Vec::with_capacity(n / 8));
76 }
77 unsafe { buckets.get_unchecked_mut(d).push(idx) };
78
79 d
80 })
81 .collect();
82
83 let mut rpos = n; let mut r = 1; let mut current_min_deg = 0;
86
87 let mut worklist: Vec<usize> = Vec::with_capacity(64);
88
89 while current_min_deg < buckets.len() {
90 let mut current_bucket = std::mem::take(&mut buckets[current_min_deg]);
91
92 current_bucket.retain(|idx| *unsafe { lifetimes.get_unchecked(*idx) } == -1);
94
95 if current_bucket.is_empty() {
97 current_min_deg += 1;
98 continue;
99 }
100
101 for idx in current_bucket {
102 *unsafe { lifetimes.get_unchecked_mut(idx) } = r;
104
105 rpos -= 1;
107 *unsafe { sorted_ids.get_unchecked_mut(rpos) } = idx;
108
109 for &nb in unsafe { indices.get_unchecked(idx) }.iter() {
111 if unsafe { *lifetimes.get_unchecked(nb) } != -1 {
112 continue; }
114
115 let is_known = unsafe { filter.get_unchecked_mut(nb) };
116 if !*is_known {
117 *is_known = true;
118 worklist.push(nb);
119 }
120 }
121 }
122
123 for nb in worklist.drain(..) {
125 unsafe { *filter.get_unchecked_mut(nb) = false };
127
128 if *unsafe { lifetimes.get_unchecked(nb) } != -1 {
130 continue;
131 }
132
133 let deg = unsafe { degree.get_unchecked_mut(nb) };
134
135 if *deg < current_min_deg {
137 continue;
138 };
139
140 *deg -= 1;
142
143 unsafe { buckets.get_unchecked_mut(*deg).push(nb) };
145 }
146
147 r += 1
148 }
149
150 (lifetimes, sorted_ids)
151}
152
153fn cluster(indices: &[Vec<usize>], lifetimes: &[i32], sorted_ids: &[usize]) -> Labels {
155 let n = indices.len();
156 assert_eq!(lifetimes.len(), n);
157 assert_eq!(sorted_ids.len(), n);
158
159 let mut labels = vec![-2; n];
160 let mut filter = vec![false; n];
161 let mut seeds_idx = Vec::with_capacity(32);
162
163 for (idx, lt) in lifetimes.iter().enumerate() {
164 let (mut low, mut high) = (0, 0);
166
167 let indices = unsafe { indices.get_unchecked(idx) };
168
169 for ii in indices.iter() {
170 let nb_lt = unsafe { lifetimes.get_unchecked(*ii) };
171 if lt < nb_lt {
172 high += 1;
173 }
174 if lt > nb_lt {
175 low += 1;
176 }
177 }
178
179 let label = unsafe { labels.get_unchecked_mut(idx) };
181
182 if indices.is_empty() {
183 *label = -1;
185 } else {
186 if high < low {
187 *unsafe { filter.get_unchecked_mut(idx) } = true;
189 }
190 if high == 0 && low > 0 {
191 seeds_idx.push(idx);
193 }
194 }
195 }
196
197 let mut cluster_id = 0;
199 let mut to_visit = VecDeque::with_capacity(64);
200
201 for seed_idx in seeds_idx {
202 if !unsafe { *filter.get_unchecked(seed_idx) } {
204 continue;
205 }
206
207 to_visit.push_back(seed_idx);
208
209 while let Some(idx) = to_visit.pop_front() {
210 let first_visit = unsafe { filter.get_unchecked_mut(idx) };
211 if *first_visit {
213 *first_visit = false;
215
216 *unsafe { labels.get_unchecked_mut(idx) } = cluster_id;
218
219 for nb in unsafe { indices.get_unchecked(idx).iter() } {
221 if *unsafe { filter.get_unchecked(*nb) } {
223 to_visit.push_back(*nb);
224 }
225 }
226 }
227 }
228
229 cluster_id += 1;
230 }
231
232 let mut counts: Vec<usize> = vec![0; cluster_id as usize + 1];
234
235 for &idx in sorted_ids.iter() {
236 if unsafe { *labels.get_unchecked(idx) } != -2 {
238 continue;
239 }
240
241 counts.fill_with(Default::default);
243
244 let mut max_count = 0;
246 let mut max_label = -1;
247
248 for &nb in unsafe { indices.get_unchecked(idx) }.iter() {
249 let nb_label = unsafe { *labels.get_unchecked(nb) };
250
251 if nb_label < 0 {
253 continue;
254 }
255
256 let count = unsafe { counts.get_unchecked_mut(nb_label as usize) };
258 *count += 1;
259
260 if *count > max_count {
262 max_count = *count;
263 max_label = nb_label;
264 }
265 }
266
267 *unsafe { labels.get_unchecked_mut(idx) } = max_label;
268 }
269
270 labels
271}