auto-palette 0.8.1

🎨 A Rust library that extracts prominent color palettes from images automatically.
Documentation
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::collections::BinaryHeap;

use crate::math::{
    neighbors::{neighbor::Neighbor, search::NeighborSearch},
    DistanceMetric,
    FloatNumber,
    Point,
};

/// Node of a k-d tree.
#[derive(Debug)]
struct Node {
    /// The splitting axis.
    axis: usize,
    /// The indices of the points.
    indices: Vec<usize>,
    /// The left child node.
    left: Option<Box<Node>>,
    /// The right child node.
    right: Option<Box<Node>>,
}

impl Node {
    /// Creates a new internal node.
    ///
    /// # Arguments
    /// * `axis` - The splitting axis.
    /// * `index` - The index of the point.
    /// * `left` - The left child node.
    /// * `right` - The right child node.
    ///
    /// # Returns
    /// A new internal node.
    #[must_use]
    fn new_node(axis: usize, index: usize, left: Option<Node>, right: Option<Node>) -> Self {
        Self {
            axis,
            indices: vec![index],
            left: left.map(Box::new),
            right: right.map(Box::new),
        }
    }

    /// Creates a new leaf node.
    ///
    /// # Arguments
    /// * `axis` - The splitting axis.
    /// * `indices` - The indices of the points.
    ///
    /// # Returns
    /// A new leaf node.
    #[must_use]
    fn new_leaf(axis: usize, indices: &[usize]) -> Self {
        Self {
            axis,
            indices: indices.to_vec(),
            left: None,
            right: None,
        }
    }

    /// Returns the index of the point.
    ///
    /// # Returns
    /// The index of the point.
    #[inline]
    #[must_use]
    fn index(&self) -> usize {
        self.indices[0]
    }

    /// Checks if the node is a leaf.
    ///
    /// # Returns
    /// `true` if the node is a leaf, otherwise `false`.
    #[inline]
    #[must_use]
    fn is_leaf(&self) -> bool {
        self.left.is_none() && self.right.is_none()
    }
}

/// k-d tree search algorithm.
///
/// # Type Parameters
/// * `T` - The floating point type.
/// * `N` - The dimension of the points.
#[derive(Debug)]
pub struct KDTreeSearch<'a, T, const N: usize>
where
    T: FloatNumber,
{
    /// The root node of the tree.
    root: Option<Box<Node>>,
    /// The points in the tree.
    points: &'a [Point<T, N>],
    /// The distance metric.
    metric: DistanceMetric,
}

impl<'a, T, const N: usize> KDTreeSearch<'a, T, N>
where
    T: 'a + FloatNumber,
{
    /// Builds a new `KDTreeSearch` instance.
    ///
    /// # Arguments
    /// * `points` - The points to search.
    /// * `metric` - The distance metric to use.
    /// * `leaf_size` - The maximum number of points in a leaf node.
    ///
    /// # Returns
    /// A new `KDTreeSearch` instance.
    pub fn build(points: &'a [Point<T, N>], metric: DistanceMetric, leaf_size: usize) -> Self {
        let mut indices: Vec<usize> = (0..points.len()).collect();
        let root = Self::split_node(points, leaf_size, &mut indices, 0);
        Self {
            root: root.map(Box::new),
            points,
            metric,
        }
    }

    #[inline]
    #[must_use]
    fn split_node(
        points: &[Point<T, N>],
        leaf_size: usize,
        indices: &mut [usize],
        depth: usize,
    ) -> Option<Node> {
        if indices.is_empty() {
            return None;
        }

        let axis = depth % N;
        if indices.len() <= leaf_size {
            return Some(Node::new_leaf(axis, indices));
        }

        indices.sort_by(|&index1, &index2| {
            // Compare the points by the splitting axis.
            points[index1][axis]
                .partial_cmp(&points[index2][axis])
                .unwrap()
        });

        let median = indices.len() / 2;
        let (left_indices, right_indices) = indices.split_at_mut(median);
        let left = Self::split_node(points, leaf_size, left_indices, depth + 1);
        let right = Self::split_node(points, leaf_size, &mut right_indices[1..], depth + 1);
        Some(Node::new_node(axis, indices[median], left, right))
    }

    fn search_leaf<F>(&self, node: &Node, query: &Point<T, N>, action: &mut F)
    where
        F: FnMut(usize, T),
    {
        node.indices.iter().for_each(|&index| {
            let point = &self.points[index];
            let distance = self.metric.measure(point, query);
            action(index, distance);
        });
    }

    #[allow(dead_code)]
    #[inline]
    fn search_recursive(
        &self,
        root: &Option<Box<Node>>,
        query: &Point<T, N>,
        k: usize,
        neighbors: &mut BinaryHeap<Neighbor<T>>,
    ) {
        let Some(ref node) = root else {
            return;
        };

        let mut best_distance = neighbors
            .peek()
            .map(|neighbor| neighbor.distance)
            .unwrap_or(T::infinity());
        let mut update_neighbors = |index, distance| {
            if distance >= best_distance {
                return;
            }

            if neighbors.len() == k {
                neighbors.pop();
            }
            neighbors.push(Neighbor::new(index, distance));
            best_distance = neighbors
                .peek()
                .map(|neighbor| neighbor.distance)
                .unwrap_or(T::infinity());
        };

        if node.is_leaf() {
            self.search_leaf(node, query, &mut update_neighbors);
            return;
        }

        let index = node.index();
        let point = &self.points[index];
        let distance = self.metric.measure(point, query);
        update_neighbors(index, distance);

        let axis = node.axis;
        let delta = (query[axis] - point[axis]).abs();
        let (near, far) = if query[axis] < point[axis] {
            (&node.left, &node.right)
        } else {
            (&node.right, &node.left)
        };

        self.search_recursive(near, query, k, neighbors);
        if delta < best_distance {
            self.search_recursive(far, query, k, neighbors);
        }
    }

    #[inline]
    fn search_nearest_recursive(
        &self,
        root: &Option<Box<Node>>,
        query: &Point<T, N>,
        nearest: &mut Neighbor<T>,
    ) {
        let Some(ref node) = root else {
            return;
        };

        let mut update_nearest = |index, distance| {
            if distance < nearest.distance {
                *nearest = Neighbor::new(index, distance);
            }
        };

        if node.is_leaf() {
            self.search_leaf(node, query, &mut update_nearest);
            return;
        }

        let index = node.index();
        let point = &self.points[index];
        let distance = self.metric.measure(point, query);
        update_nearest(index, distance);

        let axis = node.axis;
        let delta = (query[axis] - point[axis]).abs();
        let (near, far) = if query[axis] < point[axis] {
            (&node.left, &node.right)
        } else {
            (&node.right, &node.left)
        };

        self.search_nearest_recursive(near, query, nearest);
        if delta < nearest.distance {
            self.search_nearest_recursive(far, query, nearest);
        }
    }

    #[inline]
    fn search_radius_recursive(
        &self,
        root: &Option<Box<Node>>,
        query: &Point<T, N>,
        radius: T,
        neighbors: &mut Vec<Neighbor<T>>,
    ) {
        let Some(ref node) = root else {
            return;
        };

        if node.is_leaf() {
            self.search_leaf(node, query, &mut |index, distance| {
                if distance <= radius {
                    neighbors.push(Neighbor::new(index, distance));
                }
            });
            return;
        }

        let index = node.index();
        let point = &self.points[index];
        let distance = self.metric.measure(point, query);
        if distance <= radius {
            neighbors.push(Neighbor::new(index, distance));
        }

        let axis = node.axis;
        let (near, far) = if query[axis] < point[axis] {
            (&node.left, &node.right)
        } else {
            (&node.right, &node.left)
        };

        self.search_radius_recursive(near, query, radius, neighbors);
        if (query[axis] - point[axis]).abs() <= radius {
            self.search_radius_recursive(far, query, radius, neighbors);
        }
    }
}

impl<T, const N: usize> NeighborSearch<T, N> for KDTreeSearch<'_, T, N>
where
    T: FloatNumber,
{
    fn search(&self, query: &Point<T, N>, k: usize) -> Vec<Neighbor<T>> {
        if k == 0 {
            return Vec::new();
        }

        let mut neighbors = BinaryHeap::with_capacity(k);
        self.search_recursive(&self.root, query, k, &mut neighbors);
        neighbors.into_sorted_vec()
    }

    fn search_nearest(&self, query: &Point<T, N>) -> Option<Neighbor<T>> {
        let mut nearest = Neighbor::new(0, T::infinity());
        self.search_nearest_recursive(&self.root, query, &mut nearest);
        if nearest.distance.is_infinite() {
            None
        } else {
            Some(nearest)
        }
    }

    fn search_radius(&self, query: &Point<T, N>, radius: T) -> Vec<Neighbor<T>> {
        if radius < T::zero() {
            return Vec::new();
        }

        let mut neighbors = Vec::new();
        self.search_radius_recursive(&self.root, query, radius, &mut neighbors);
        neighbors
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[must_use]
    fn sample_points() -> Vec<Point<f32, 3>> {
        vec![
            [1.0, 2.0, 3.0], // 0
            [5.0, 1.0, 2.0], // 1
            [9.0, 3.0, 4.0], // 2
            [3.0, 9.0, 1.0], // 3
            [4.0, 8.0, 3.0], // 4
            [9.0, 1.0, 1.0], // 5
            [5.0, 0.0, 0.0], // 6
            [3.0, 2.0, 1.0], // 7
            [2.0, 5.0, 6.0], // 8
            [1.0, 3.0, 2.0], // 9
            [4.0, 2.0, 1.0], // 10
            [5.0, 3.0, 2.0], // 11
            [6.0, 2.0, 1.0], // 12
            [7.0, 3.0, 2.0], // 13
            [8.0, 2.0, 1.0], // 14
        ]
    }

    #[must_use]
    fn empty_points() -> Vec<Point<f32, 3>> {
        Vec::new()
    }

    #[test]
    fn test_build() {
        // Act
        let points = sample_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Assert
        assert!(search.root.is_some());
        assert_eq!(search.points.len(), points.len());
        assert_eq!(search.metric, DistanceMetric::Euclidean);
    }

    #[test]
    fn test_build_empty() {
        // Act
        let points = empty_points();
        let search: KDTreeSearch<f32, 3> =
            KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Assert
        assert!(search.root.is_none());
        assert_eq!(search.points.len(), 0);
        assert_eq!(search.metric, DistanceMetric::Euclidean);
    }

    #[test]
    fn test_search() {
        // Arrange
        let points = sample_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Act
        let query = [3.0, 5.0, 6.0];
        let neighbors = search.search(&query, 3);

        // Assert
        assert_eq!(neighbors.len(), 3);
        assert_eq!(neighbors[0].index, 8);
        assert_eq!(neighbors[0].distance, 1.0_f32.sqrt());
        assert_eq!(neighbors[1].index, 4);
        assert_eq!(neighbors[1].distance, 19.0_f32.sqrt());
        assert_eq!(neighbors[2].index, 0);
        assert_eq!(neighbors[2].distance, 22.0_f32.sqrt());
    }

    #[test]
    fn test_search_empty() {
        // Arrange
        let points = sample_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Act
        let query = [3.0, 5.0, 6.0];
        let neighbors = search.search(&query, 0);

        // Assert
        assert!(neighbors.is_empty());
    }

    #[test]
    fn test_search_nearest() {
        // Arrange
        let points = sample_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Act
        let query = [2.0, 2.0, 1.0];
        let nearest = search.search_nearest(&query).unwrap();

        // Assert
        assert_eq!(nearest.index, 7);
        assert_eq!(nearest.distance, 1.0_f32.sqrt());
    }

    #[test]
    fn test_search_nearest_empty() {
        // Arrange
        let points = empty_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Act
        let query = [3.0, 2.0, 1.0];
        let nearest = search.search_nearest(&query);

        // Assert
        assert!(nearest.is_none());
    }

    #[test]
    fn test_search_radius() {
        // Arrange
        let points = sample_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Act
        let query = [3.0, 5.0, 6.0];
        let neighbors = search.search_radius(&query, 4.5);

        // Assert
        assert_eq!(neighbors.len(), 2);
        assert_eq!(neighbors[0].index, 4);
        assert_eq!(neighbors[0].distance, 19.0_f32.sqrt());
        assert_eq!(neighbors[1].index, 8);
        assert_eq!(neighbors[1].distance, 1.0_f32.sqrt());
    }

    #[test]
    fn test_search_radius_empty() {
        // Arrange
        let points = sample_points();
        let search = KDTreeSearch::build(&points, DistanceMetric::Euclidean, 2);

        // Act
        let query = [3.0, 5.0, 6.0];
        let neighbors = search.search_radius(&query, -1.0);

        // Assert
        assert_eq!(neighbors.len(), 0);
    }
}