Skip to main content

evolutionary_planning/de/
warm_start.rs

1//! A library of solved problems used to warm-start new searches, after the pre-motion
2//! library of Yue et al. (2023): solutions are stored under a task descriptor (for example a
3//! target state), and a new task whose descriptor lies within a radius of a stored one starts
4//! from that solution instead of from scratch.
5
6use alloc::vec::Vec;
7
8/// Stored solutions keyed by task descriptors, looked up by Euclidean distance.
9///
10/// A linear scan: libraries of hundreds of entries (Yue et al. store 567) are scanned in
11/// microseconds, and an index would only pay off for far larger ones.
12///
13/// ```
14/// use evolutionary_planning::de::WarmStartLibrary;
15///
16/// let mut library = WarmStartLibrary::new();
17/// library.insert(vec![0.6, 0.2], vec![1.0, 2.0, 3.0]);
18/// library.insert(vec![0.0, 0.0], vec![0.0, 0.0, 0.0]);
19///
20/// let (distance, solution) = library.nearest(&[0.58, 0.21], 0.05).expect("within radius");
21/// assert!(distance < 0.05);
22/// assert_eq!(solution, &[1.0, 2.0, 3.0]);
23/// assert!(library.nearest(&[0.3, 0.3], 0.05).is_none());
24/// ```
25#[derive(Debug, Clone, Default, PartialEq)]
26pub struct WarmStartLibrary {
27    /// `(descriptor, solution)` pairs in insertion order.
28    entries: Vec<(Vec<f64>, Vec<f64>)>,
29}
30
31impl WarmStartLibrary {
32    /// An empty library.
33    #[must_use]
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// Stores `solution` for the task described by `descriptor`.
39    pub fn insert(&mut self, descriptor: Vec<f64>, solution: Vec<f64>) {
40        self.entries.push((descriptor, solution));
41    }
42
43    /// The number of stored solutions.
44    #[must_use]
45    pub fn len(&self) -> usize {
46        self.entries.len()
47    }
48
49    /// Whether the library is empty.
50    #[must_use]
51    pub fn is_empty(&self) -> bool {
52        self.entries.is_empty()
53    }
54
55    /// The solution whose descriptor is nearest to `query`, with its distance, if that
56    /// distance is at most `radius`. Ties go to the earlier entry. Descriptors of a different
57    /// dimension never match.
58    #[must_use]
59    pub fn nearest(&self, query: &[f64], radius: f64) -> Option<(f64, &[f64])> {
60        self.entries
61            .iter()
62            .filter(|(descriptor, _)| descriptor.len() == query.len())
63            .map(|(descriptor, solution)| (distance(descriptor, query), solution.as_slice()))
64            .filter(|(d, _)| *d <= radius)
65            .min_by(|a, b| a.0.total_cmp(&b.0))
66    }
67
68    /// Up to `k` solutions within `radius` of `query`, nearest first: seeds for a population.
69    #[must_use]
70    pub fn neighbours(&self, query: &[f64], radius: f64, k: usize) -> Vec<Vec<f64>> {
71        let mut hits: Vec<(f64, usize)> = self
72            .entries
73            .iter()
74            .enumerate()
75            .filter(|(_, (descriptor, _))| descriptor.len() == query.len())
76            .map(|(index, (descriptor, _))| (distance(descriptor, query), index))
77            .filter(|(d, _)| *d <= radius)
78            .collect();
79        hits.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
80
81        hits.into_iter()
82            .take(k)
83            .map(|(_, index)| self.entries[index].1.clone())
84            .collect()
85    }
86}
87
88/// The Euclidean distance of two equally long vectors.
89fn distance(a: &[f64], b: &[f64]) -> f64 {
90    libm::sqrt(a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum())
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::de::{Config, De};
97    use crate::operators::real::Bounds;
98    use crate::{Limits, SplitMix64};
99
100    /// A warm start from a nearby solved task reaches the target with fewer evaluations.
101    #[test]
102    fn warm_start_saves_evaluations() {
103        let solve = |target: [f64; 4], seeds: Vec<Vec<f64>>| {
104            let mut de = De::new(Config::default(), Bounds::uniform(4, -10.0, 10.0));
105            let mut objective = |x: &Vec<f64>| {
106                x.iter()
107                    .zip(&target)
108                    .map(|(a, b)| (a - b) * (a - b))
109                    .sum::<f64>()
110            };
111            de.run_from(
112                seeds,
113                &mut objective,
114                &mut Limits::evaluations(50_000).with_target(1e-8),
115                &mut (),
116                &mut SplitMix64::new(1),
117            )
118        };
119
120        let first = solve([3.0, -2.0, 5.0, 1.0], Vec::new());
121        let mut library = WarmStartLibrary::new();
122        library.insert(
123            alloc::vec![3.0, -2.0],
124            first.best_genome().expect("solved").clone(),
125        );
126
127        let seeds = library.neighbours(&[3.05, -2.0], 0.1, 4);
128        let warm = solve([3.05, -2.0, 5.0, 1.0], seeds);
129        let cold = solve([3.05, -2.0, 5.0, 1.0], Vec::new());
130
131        assert!(warm.best_cost() <= 1e-8 && cold.best_cost() <= 1e-8);
132        assert!(
133            warm.stats.evaluations < cold.stats.evaluations,
134            "{} vs {}",
135            warm.stats.evaluations,
136            cold.stats.evaluations
137        );
138    }
139}