Skip to main content

ltc_rs/
lib.rs

1//! # Lifetime Clustering (LTC)
2//!
3//! Reference: J M Zollner, B Teuscher, W Mansour, and M Werner, "Efficent and robust topology-based clustering"
4
5use std::collections::VecDeque;
6
7use num_traits::Float;
8use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
9use srtree::{Euclidean, SRTree};
10
11/// Label values.
12pub type Labels = Vec<i32>;
13/// Lifetime values.
14pub type Lifetimes = Vec<i32>;
15
16/// Fit model.
17pub 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
28/// Fit model from neighbourhood indices.
29pub 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
37/// Construct fixed radius neighbour graph.
38fn 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            // radius search
48            let mut neighbours = index.query_radius(p, eps);
49
50            // drop diagonal i.e. self edges
51            neighbours.retain(|col_id| *col_id != row_i);
52
53            neighbours
54        })
55        .collect()
56}
57
58/// Compute lifetimes.
59fn 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    // buckets[d] has nodes with degree d
67    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; // pointer for reverse removal order
84    let mut r = 1; // round
85    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        // filter points without lifetime
93        current_bucket.retain(|idx| *unsafe { lifetimes.get_unchecked(*idx) } == -1);
94
95        // skip empty degree bucket
96        if current_bucket.is_empty() {
97            current_min_deg += 1;
98            continue;
99        }
100
101        for idx in current_bucket {
102            // assign lifetime
103            *unsafe { lifetimes.get_unchecked_mut(idx) } = r;
104
105            // record reverse removal order
106            rpos -= 1;
107            *unsafe { sorted_ids.get_unchecked_mut(rpos) } = idx;
108
109            // flag neighbors once (no duplicates)
110            for &nb in unsafe { indices.get_unchecked(idx) }.iter() {
111                if unsafe { *lifetimes.get_unchecked(nb) } != -1 {
112                    continue; // already removed
113                }
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        // each neighbor is decremented only once per round
124        for nb in worklist.drain(..) {
125            // reset flag
126            unsafe { *filter.get_unchecked_mut(nb) = false };
127
128            // skip points with assigned lifetime
129            if *unsafe { lifetimes.get_unchecked(nb) } != -1 {
130                continue;
131            }
132
133            let deg = unsafe { degree.get_unchecked_mut(nb) };
134
135            // skip points that can not appear in uppcoming buckets
136            if *deg < current_min_deg {
137                continue;
138            };
139
140            // update degree
141            *deg -= 1;
142
143            // add point to buckets
144            unsafe { buckets.get_unchecked_mut(*deg).push(nb) };
145        }
146
147        r += 1
148    }
149
150    (lifetimes, sorted_ids)
151}
152
153/// Assign labels.
154fn 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        // compute neighbour lifetime relations
165        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        // asigne label
180        let label = unsafe { labels.get_unchecked_mut(idx) };
181
182        if indices.is_empty() {
183            // noise
184            *label = -1;
185        } else {
186            if high < low {
187                // inner
188                *unsafe { filter.get_unchecked_mut(idx) } = true;
189            }
190            if high == 0 && low > 0 {
191                // seed (subset of inner)
192                seeds_idx.push(idx);
193            }
194        }
195    }
196
197    // Inner point assignment
198    let mut cluster_id = 0;
199    let mut to_visit = VecDeque::with_capacity(64);
200
201    for seed_idx in seeds_idx {
202        // skip already visited seeds
203        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            // only visit once
212            if *first_visit {
213                // mark as visied
214                *first_visit = false;
215
216                // set label
217                *unsafe { labels.get_unchecked_mut(idx) } = cluster_id;
218
219                // traverse
220                for nb in unsafe { indices.get_unchecked(idx).iter() } {
221                    // only follow unvisited edges between inner points
222                    if *unsafe { filter.get_unchecked(*nb) } {
223                        to_visit.push_back(*nb);
224                    }
225                }
226            }
227        }
228
229        cluster_id += 1;
230    }
231
232    // Outer point assignment.
233    let mut counts: Vec<usize> = vec![0; cluster_id as usize + 1];
234
235    for &idx in sorted_ids.iter() {
236        // skip already labeled points
237        if unsafe { *labels.get_unchecked(idx) } != -2 {
238            continue;
239        }
240
241        // count labeled neighbors (sparse over labels seen)
242        counts.fill_with(Default::default);
243
244        // pick argmax (tie break by first seen)
245        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            // ignore noise/unlabeled
252            if nb_label < 0 {
253                continue;
254            }
255
256            // increment
257            let count = unsafe { counts.get_unchecked_mut(nb_label as usize) };
258            *count += 1;
259
260            // update max
261            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}