Skip to main content

evolutionary_planning/
trajectory.rs

1//! Online trajectory optimisation with warm-started CMA-ES, after the online motion planner
2//! of Yue et al. (2023): a trajectory is a control sequence of `steps × controls` reals that
3//! the caller's objective rolls out through its dynamics, and every control period the plan
4//! is re-optimised under a small evaluation budget, starting from
5//!
6//! 1. the previous solution shifted by one step, keeping σ and the covariance (also shifted),
7//!    when there is one (receding horizon); otherwise
8//! 2. a stored solution of a nearby task from a [`WarmStartLibrary`] (Yue et al.'s pre-motion
9//!    library, within a radius of the task descriptor); otherwise
10//! 3. a cold start at the centre of the bounds (or zero).
11//!
12//! The paper warm-starts differential evolution; here the same library seeds CMA-ES, whose
13//! mean, step size and covariance carry over between replans (see the paper table).
14//!
15//! ```
16//! use evolutionary_planning::trajectory::{Config, OnlineOptimizer};
17//! use evolutionary_planning::SplitMix64;
18//!
19//! // A 1D point mass with acceleration controls; drive it from x = 1 to rest at 0.
20//! let rollout = |state: (f64, f64), controls: &[f64]| {
21//!     let (mut x, mut v, mut cost) = (state.0, state.1, 0.0);
22//!     for &a in controls {
23//!         v += 0.1 * a;
24//!         x += 0.1 * v;
25//!         cost += x * x + 0.1 * v * v + 0.01 * a * a;
26//!     }
27//!     cost
28//! };
29//! let mut planner = OnlineOptimizer::new(Config { steps: 15, controls: 1, ..Config::default() });
30//! let mut rng = SplitMix64::new(1);
31//! let mut state = (1.0, 0.0);
32//! for _ in 0..60 {
33//!     let plan = planner.replan(&mut |u: &Vec<f64>| rollout(state, u), None, &mut rng);
34//!     let a = plan.first()[0];
35//!     state.1 += 0.1 * a;
36//!     state.0 += 0.1 * state.1;
37//! }
38//! assert!(state.0.abs() < 0.1);
39//! ```
40
41use alloc::vec::Vec;
42
43use rand_core::Rng;
44
45use crate::cmaes::{CmaEs, Config as CmaConfig};
46use crate::de::WarmStartLibrary;
47use crate::operators::real::Bounds;
48use crate::{Limits, Objective};
49
50/// Parameters of an [`OnlineOptimizer`].
51#[derive(Debug, Clone, PartialEq)]
52pub struct Config {
53    /// The number of control steps in a plan, at least `1`.
54    pub steps: usize,
55    /// The number of controls per step, at least `1`.
56    pub controls: usize,
57    /// The step size of a cold or library start.
58    pub sigma: f64,
59    /// The smallest step size a warm start begins with, so the new tail of a shifted plan
60    /// can still move.
61    pub min_sigma: f64,
62    /// Objective evaluations per replan.
63    pub evaluations: u64,
64    /// CMA-ES population size; `None` for the default.
65    pub lambda: Option<usize>,
66    /// Per-control bounds `(low, high)`, applied to every step by CMA-ES's boundary penalty;
67    /// `None` is unbounded.
68    pub bounds: Option<Vec<(f64, f64)>>,
69    /// The radius within which a library entry warm-starts a new task.
70    pub library_radius: f64,
71}
72
73impl Default for Config {
74    /// 20 steps of one control, `σ = 0.5`, `σ_min = 0.05`, 300 evaluations per replan, no
75    /// bounds, library radius `0.05` (the paper's threshold).
76    fn default() -> Self {
77        Self {
78            steps: 20,
79            controls: 1,
80            sigma: 0.5,
81            min_sigma: 0.05,
82            evaluations: 300,
83            lambda: None,
84            bounds: None,
85            library_radius: 0.05,
86        }
87    }
88}
89
90/// Where a replan started from.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum WarmStart {
93    /// From scratch.
94    Cold,
95    /// From the previous plan shifted by one step.
96    Shifted,
97    /// From a library entry of a nearby task.
98    Library,
99}
100
101/// The result of one replan.
102#[derive(Debug, Clone, PartialEq)]
103pub struct Replan {
104    /// The best control sequence, `steps × controls` values, step-major.
105    pub controls: Vec<f64>,
106    /// Its cost.
107    pub cost: f64,
108    /// How the search was started.
109    pub warm_start: WarmStart,
110    /// The number of controls per step.
111    per_step: usize,
112}
113
114impl Replan {
115    /// The controls of the first step: what to execute now.
116    #[must_use]
117    pub fn first(&self) -> &[f64] {
118        &self.controls[..self.per_step]
119    }
120}
121
122/// The state carried from one replan to the next.
123#[derive(Debug, Clone, PartialEq)]
124struct Carry {
125    /// The best controls of the last replan.
126    controls: Vec<f64>,
127    /// The final step size.
128    sigma: f64,
129    /// The final covariance, row-major.
130    covariance: Vec<f64>,
131}
132
133/// A receding-horizon trajectory optimiser.
134#[derive(Debug, Clone, PartialEq)]
135pub struct OnlineOptimizer {
136    /// The parameters.
137    pub config: Config,
138    /// Solutions of solved tasks, by descriptor.
139    pub library: WarmStartLibrary,
140    /// The previous replan's state, if any.
141    carry: Option<Carry>,
142}
143
144impl OnlineOptimizer {
145    /// A fresh optimiser with an empty library.
146    #[must_use]
147    pub fn new(config: Config) -> Self {
148        Self {
149            config,
150            library: WarmStartLibrary::new(),
151            carry: None,
152        }
153    }
154
155    /// Starts a new task: the next replan does not shift the previous plan (it may use the
156    /// library).
157    pub fn reset(&mut self) {
158        self.carry = None;
159    }
160
161    /// Stores the last plan in the library under `descriptor` (for example the task's target),
162    /// for warm starts of nearby tasks after a [`OnlineOptimizer::reset`].
163    pub fn remember(&mut self, descriptor: Vec<f64>) {
164        if let Some(carry) = &self.carry {
165            self.library.insert(descriptor, carry.controls.clone());
166        }
167    }
168
169    /// Re-optimises the plan under `objective` (which rolls a control sequence out from the
170    /// current state), consulting the library with `descriptor` on a fresh task.
171    ///
172    /// # Panics
173    ///
174    /// Panics if `steps` or `controls` is `0`, or the bounds do not have one pair per control.
175    pub fn replan<O, R>(
176        &mut self,
177        objective: &mut O,
178        descriptor: Option<&[f64]>,
179        rng: &mut R,
180    ) -> Replan
181    where
182        O: Objective<Vec<f64>> + ?Sized,
183        R: Rng + ?Sized,
184    {
185        let c = &self.config;
186        assert!(
187            c.steps > 0 && c.controls > 0,
188            "a plan needs at least one step and one control"
189        );
190        let n = c.steps * c.controls;
191        let cma_config = CmaConfig {
192            lambda: c.lambda,
193            bounds: self.bounds(),
194            ..CmaConfig::default()
195        };
196        let (mut cma, warm_start) = self.start(n, cma_config, descriptor);
197        let outcome = cma.minimize(
198            objective,
199            &mut Limits::evaluations(self.config.evaluations),
200            &mut (),
201            rng,
202        );
203        let (controls, cost) = outcome.best.map_or_else(
204            || (cma.mean().to_vec(), f64::INFINITY),
205            |b| (b.genome, b.cost),
206        );
207        let (sigma, covariance) = carried_distribution(&cma);
208        self.carry = Some(Carry {
209            controls: controls.clone(),
210            sigma,
211            covariance,
212        });
213
214        Replan {
215            controls,
216            cost,
217            warm_start,
218            per_step: self.config.controls,
219        }
220    }
221
222    /// The flattened bounds of a whole plan, if any.
223    fn bounds(&self) -> Option<Bounds> {
224        let per_control = self.config.bounds.as_ref()?;
225        assert_eq!(
226            per_control.len(),
227            self.config.controls,
228            "one bound pair per control"
229        );
230        let (lower, upper) = (0..self.config.steps)
231            .flat_map(|_| per_control.iter().copied())
232            .unzip();
233
234        Some(Bounds::new(lower, upper))
235    }
236
237    /// Chooses the warm start and builds the CMA-ES state.
238    fn start(&self, n: usize, config: CmaConfig, descriptor: Option<&[f64]>) -> (CmaEs, WarmStart) {
239        let c = &self.config;
240        if let Some(carry) = self
241            .carry
242            .as_ref()
243            .filter(|carry| carry.controls.len() == n)
244        {
245            let mean = shift_controls(&carry.controls, c.controls);
246            let covariance = shift_covariance(&carry.covariance, n, c.controls);
247            let sigma = carry.sigma.max(c.min_sigma);
248            return (
249                CmaEs::with_covariance(mean, sigma, covariance, config),
250                WarmStart::Shifted,
251            );
252        }
253
254        let library_hit = descriptor
255            .and_then(|d| self.library.nearest(d, c.library_radius))
256            .filter(|(_, solution)| solution.len() == n);
257        if let Some((_, solution)) = library_hit {
258            return (
259                CmaEs::new(solution.to_vec(), c.sigma, config),
260                WarmStart::Library,
261            );
262        }
263
264        let mean = config
265            .bounds
266            .as_ref()
267            .map_or_else(|| alloc::vec![0.0; n], Bounds::center);
268        (CmaEs::new(mean, c.sigma, config), WarmStart::Cold)
269    }
270}
271
272/// The step size and covariance to carry into the next replan: `C` scaled to unit mean
273/// variance (with σ scaled inversely, the same distribution), so that the σ floor of the warm
274/// start bounds the actual spread; reset to `I` when `C` has become ill-conditioned (above
275/// `1e12`), which happens over long runs once the plan has converged and the task changes.
276fn carried_distribution(cma: &CmaEs) -> (f64, Vec<f64>) {
277    let n = cma.mean().len();
278    let covariance = cma.covariance();
279    #[expect(clippy::cast_precision_loss, reason = "plan sizes are far below 2^52")]
280    let mean_variance = (0..n).map(|i| covariance[i * n + i]).sum::<f64>() / n as f64;
281    if !(mean_variance > 0.0 && mean_variance.is_finite()) || cma.condition() > 1e12 {
282        let mut identity = alloc::vec![0.0; n * n];
283        (0..n).for_each(|i| identity[i * n + i] = 1.0);
284        return (cma.sigma(), identity);
285    }
286
287    let scaled = covariance.iter().map(|c| c / mean_variance).collect();
288
289    (cma.sigma() * libm::sqrt(mean_variance), scaled)
290}
291
292/// Drops the first step and repeats the last one: the receding-horizon shift of a plan.
293fn shift_controls(controls: &[f64], per_step: usize) -> Vec<f64> {
294    let mut shifted = controls[per_step..].to_vec();
295    shifted.extend_from_slice(&controls[controls.len() - per_step..]);
296
297    shifted
298}
299
300/// Shifts a covariance over plans by one step: the block of steps `1..` moves to `0..`, and
301/// the new last step gets an uncorrelated block with the old last step's variances.
302fn shift_covariance(covariance: &[f64], n: usize, per_step: usize) -> Vec<f64> {
303    let mut shifted = alloc::vec![0.0; n * n];
304    let kept = n - per_step;
305    for i in 0..kept {
306        for j in 0..kept {
307            shifted[i * n + j] = covariance[(i + per_step) * n + j + per_step];
308        }
309    }
310
311    for i in kept..n {
312        shifted[i * n + i] = covariance[i * n + i];
313    }
314
315    shifted
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::SplitMix64;
322
323    /// The cost of a control sequence for a 1D point mass heading for `target`.
324    fn point_mass(state: (f64, f64), target: f64, controls: &[f64]) -> f64 {
325        let (mut x, mut v, mut cost) = (state.0, state.1, 0.0);
326        for &a in controls {
327            v += 0.1 * a;
328            x += 0.1 * v;
329            cost += (x - target) * (x - target) + 0.1 * v * v + 0.01 * a * a;
330        }
331
332        cost
333    }
334
335    /// Runs a closed loop of `periods` replans; returns the accumulated closed-loop cost.
336    fn closed_loop(planner: &mut OnlineOptimizer, warm: bool, periods: usize, seed: u64) -> f64 {
337        let mut rng = SplitMix64::new(seed);
338        let mut state = (1.0, 0.0);
339        let mut total = 0.0;
340        for _ in 0..periods {
341            if !warm {
342                planner.reset();
343            }
344
345            let plan = planner.replan(
346                &mut |u: &Vec<f64>| point_mass(state, 0.0, u),
347                None,
348                &mut rng,
349            );
350            let a = plan.first()[0];
351            state.1 += 0.1 * a;
352            state.0 += 0.1 * state.1;
353            total += state.0 * state.0 + 0.1 * state.1 * state.1 + 0.01 * a * a;
354        }
355
356        total
357    }
358
359    /// With a tight budget, shifting the previous plan beats re-planning from scratch.
360    #[test]
361    fn shifted_warm_start_beats_cold() {
362        let config = Config {
363            steps: 20,
364            evaluations: 60,
365            ..Config::default()
366        };
367        let warm = closed_loop(&mut OnlineOptimizer::new(config.clone()), true, 50, 3);
368        let cold = closed_loop(&mut OnlineOptimizer::new(config), false, 50, 3);
369
370        assert!(warm < cold, "warm {warm} vs cold {cold}");
371    }
372
373    /// A library entry of a nearby task warm-starts a new task to a better plan.
374    #[test]
375    fn library_warm_start() {
376        let config = Config {
377            steps: 15,
378            evaluations: 3_000,
379            ..Config::default()
380        };
381        let mut planner = OnlineOptimizer::new(config);
382        let mut rng = SplitMix64::new(4);
383        planner.replan(
384            &mut |u: &Vec<f64>| point_mass((0.0, 0.0), 1.0, u),
385            Some(&[1.0]),
386            &mut rng,
387        );
388        planner.remember(alloc::vec![1.0]);
389
390        planner.reset();
391        planner.config.evaluations = 50;
392        let warm = planner.replan(
393            &mut |u: &Vec<f64>| point_mass((0.0, 0.0), 1.02, u),
394            Some(&[1.02]),
395            &mut rng,
396        );
397        planner.reset();
398        let cold = planner.replan(
399            &mut |u: &Vec<f64>| point_mass((0.0, 0.0), 1.02, u),
400            Some(&[3.0]),
401            &mut rng,
402        );
403
404        assert_eq!(warm.warm_start, WarmStart::Library);
405        assert_eq!(cold.warm_start, WarmStart::Cold);
406        assert!(warm.cost < cold.cost, "{} vs {}", warm.cost, cold.cost);
407    }
408
409    /// Over a thousand periods with the target moving halfway, the warm-started loop
410    /// re-converges: the carried distribution never collapses.
411    #[test]
412    fn long_run_with_target_change() {
413        let config = Config {
414            steps: 15,
415            evaluations: 60,
416            ..Config::default()
417        };
418        let mut planner = OnlineOptimizer::new(config);
419        let mut rng = SplitMix64::new(6);
420        let mut state = (0.0, 0.0);
421        for period in 0..1_000 {
422            let target = if period < 500 { 0.5 } else { -0.5 };
423            let plan = planner.replan(
424                &mut |u: &Vec<f64>| point_mass(state, target, u),
425                None,
426                &mut rng,
427            );
428            let a = plan.first()[0];
429            state.1 += 0.1 * a;
430            state.0 += 0.1 * state.1;
431            if period == 499 {
432                assert!((state.0 - 0.5).abs() < 0.05, "first target: {state:?}");
433            }
434        }
435
436        assert!(
437            (state.0 + 0.5).abs() < 0.05 && state.1.abs() < 0.1,
438            "second target: {state:?}"
439        );
440    }
441
442    /// The shifts move blocks by one step.
443    #[test]
444    fn shifts() {
445        assert_eq!(
446            shift_controls(&[1.0, 2.0, 3.0, 4.0], 2),
447            [3.0, 4.0, 3.0, 4.0]
448        );
449        let c = [1.0, 0.1, 0.1, 2.0];
450        assert_eq!(shift_covariance(&c, 2, 1), [2.0, 0.0, 0.0, 2.0]);
451    }
452
453    /// Bounds keep the executed controls inside.
454    #[test]
455    fn bounded_controls() {
456        let config = Config {
457            steps: 10,
458            bounds: Some(alloc::vec![(-0.2, 0.2)]),
459            ..Config::default()
460        };
461        let mut planner = OnlineOptimizer::new(config);
462        let plan = planner.replan(
463            &mut |u: &Vec<f64>| point_mass((1.0, 0.0), 0.0, u),
464            None,
465            &mut SplitMix64::new(1),
466        );
467
468        assert!(plan.controls.iter().all(|a| (-0.2..=0.2).contains(a)));
469    }
470}