Skip to main content

evolutionary_planning/
rhea.rs

1//! Rolling-horizon evolutionary planning (RHEA; Perez et al. 2013) over a caller-supplied
2//! forward model, with random-mutation hill climbing (RMHC) as the population-of-one case
3//! used by Olesen et al. (2020) to plan in the latent space of a learned world model.
4//!
5//! At every decision the planner evolves action sequences of length `horizon`, each scored
6//! by rolling it out through the model from the current state; it returns the first action
7//! of the best sequence. With *shift buffering* the best sequence is shifted by one step,
8//! padded with a random action and becomes the starting point of the next decision, so the
9//! search is not repeated from scratch. Each decision spends exactly
10//! [`Config::evaluations`] sequence evaluations (at least one per initial sequence).
11//!
12//! The model is the caller's: a simulator, an analytic model or a learned one. This crate
13//! minimises, so [`ForwardModel::step`] reports a per-step **cost** (use `-reward` for a
14//! reward-based model).
15//!
16//! ```
17//! use evolutionary_planning::rhea::{Config, ForwardModel, RollingHorizon, Step};
18//! use evolutionary_planning::operators::initializer_fn;
19//! use evolutionary_planning::{SplitMix64, below};
20//! use rand_core::Rng;
21//!
22//! /// A corridor: move left (-1) or right (+1); every step before reaching cell 5 costs 1.
23//! struct Corridor;
24//!
25//! impl ForwardModel for Corridor {
26//!     type State = i32;
27//!     type Action = i32;
28//!
29//!     fn step<R: Rng + ?Sized>(&mut self, state: &i32, action: &i32, _rng: &mut R) -> Step<i32> {
30//!         let next = state + action;
31//!         Step { state: next, cost: 1.0, done: next == 5 }
32//!     }
33//! }
34//!
35//! let actions = initializer_fn(|rng| if below(rng, 2) == 0 { -1 } else { 1 });
36//! let mut planner = RollingHorizon::rmhc(Config { horizon: 8, ..Config::default() }, actions);
37//! let mut rng = SplitMix64::new(1);
38//! let mut state = 0;
39//! for _ in 0..5 {
40//!     let decision = planner.plan(&mut Corridor, &state, &mut rng);
41//!     state += decision.action;
42//! }
43//! assert_eq!(state, 5);
44//! ```
45
46use alloc::vec::Vec;
47
48use rand_core::Rng;
49
50use crate::operators::selection::{Selection, Tournament};
51use crate::operators::sequence::UniformCrossover;
52use crate::operators::{Crossover, Initializer, Mutation};
53use crate::rng::{below, chance};
54use crate::{ranking, sanitize};
55
56/// The result of one model step.
57#[derive(Debug, Clone, PartialEq)]
58pub struct Step<S> {
59    /// The successor state.
60    pub state: S,
61    /// The cost of the step (minimised; `-reward` for reward models).
62    pub cost: f64,
63    /// Whether the episode ended: the rest of the sequence is not simulated.
64    pub done: bool,
65}
66
67/// A forward model: what happens when an action is taken in a state.
68///
69/// Stochastic models draw from `rng`; [`Config::rollouts`] averages several samples.
70pub trait ForwardModel {
71    /// The world state.
72    type State: Clone;
73    /// An action.
74    type Action: Clone;
75
76    /// Simulates one step from `state` under `action`.
77    fn step<R: Rng + ?Sized>(
78        &mut self,
79        state: &Self::State,
80        action: &Self::Action,
81        rng: &mut R,
82    ) -> Step<Self::State>;
83}
84
85/// Parameters of a [`RollingHorizon`] planner.
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct Config {
88    /// The length of every action sequence, at least `1`.
89    pub horizon: usize,
90    /// The number of sequences evolved; `1` is RMHC.
91    pub population_size: usize,
92    /// Sequence evaluations (each `rollouts` model rollouts) per decision. Exact, except that
93    /// every sequence of the initial population is evaluated, so the effective budget is at
94    /// least `population_size`.
95    pub evaluations: u64,
96    /// The discount `γ ∈ (0, 1]` of step costs; `1` is the undiscounted sum of Olesen et al.
97    pub discount: f64,
98    /// Rollouts averaged per evaluation, for stochastic models.
99    pub rollouts: usize,
100    /// Keep the best sequence, shifted by one step, as the seed of the next decision.
101    pub shift_buffer: bool,
102    /// RMHC on stochastic models: re-evaluate the incumbent each iteration so one lucky
103    /// rollout cannot hold the lead forever.
104    pub reevaluate: bool,
105    /// The per-action mutation probability of the default point mutation; `None` means
106    /// `1 / horizon`. At least one action always changes.
107    pub mutation_rate: Option<f64>,
108}
109
110impl Default for Config {
111    /// Horizon 10, RMHC, 200 evaluations per decision, undiscounted, one rollout, shift
112    /// buffering on.
113    fn default() -> Self {
114        Self {
115            horizon: 10,
116            population_size: 1,
117            evaluations: 200,
118            discount: 1.0,
119            rollouts: 1,
120            shift_buffer: true,
121            reevaluate: false,
122            mutation_rate: None,
123        }
124    }
125}
126
127/// One decision of the planner.
128#[derive(Debug, Clone, PartialEq)]
129pub struct Decision<A> {
130    /// The action to execute now: the first of the best sequence.
131    pub action: A,
132    /// The whole best sequence.
133    pub plan: Vec<A>,
134    /// Its estimated (discounted) cost.
135    pub cost: f64,
136    /// Sequence evaluations spent on this decision.
137    pub evaluations: u64,
138}
139
140/// Replaces each action with probability `rate` (default `1/n`) by a fresh random action;
141/// at least one changes. The default mutation of the planner.
142#[derive(Debug, Clone, Copy, PartialEq)]
143pub struct PointMutation<S> {
144    /// The action sampler.
145    pub actions: S,
146    /// The per-action probability; `None` means `1/n`.
147    pub rate: Option<f64>,
148}
149
150impl<A, S: Initializer<A>> Mutation<Vec<A>> for PointMutation<S> {
151    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<A>, rng: &mut R) {
152        if genome.is_empty() {
153            return;
154        }
155
156        #[expect(clippy::cast_precision_loss, reason = "horizons are far below 2^52")]
157        let rate = self.rate.unwrap_or(1.0 / genome.len() as f64);
158        let mut changed = false;
159        for action in genome.iter_mut() {
160            if chance(rng, rate) {
161                *action = self.actions.initialize(rng);
162                changed = true;
163            }
164        }
165
166        if !changed {
167            let at = below(rng, genome.len());
168            genome[at] = self.actions.initialize(rng);
169        }
170    }
171}
172
173/// The rolling-horizon planner.
174#[derive(Debug, Clone, PartialEq)]
175pub struct RollingHorizon<A, S, M> {
176    /// The parameters.
177    pub config: Config,
178    /// Samples random actions (initial sequences and shift-buffer padding).
179    pub actions: S,
180    /// Mutates a sequence.
181    pub mutation: M,
182    /// The sequences carried over from the last decision (shifted), if any.
183    buffer: Vec<Vec<A>>,
184}
185
186impl<A: Clone, S: Initializer<A> + Clone> RollingHorizon<A, S, PointMutation<S>> {
187    /// A planner with the default point mutation.
188    #[must_use]
189    pub fn new(config: Config, actions: S) -> Self {
190        let mutation = PointMutation {
191            actions: actions.clone(),
192            rate: config.mutation_rate,
193        };
194
195        Self {
196            config,
197            actions,
198            mutation,
199            buffer: Vec::new(),
200        }
201    }
202
203    /// RMHC: a planner with a population of one (whatever `config` says).
204    #[must_use]
205    pub fn rmhc(config: Config, actions: S) -> Self {
206        Self::new(
207            Config {
208                population_size: 1,
209                ..config
210            },
211            actions,
212        )
213    }
214}
215
216impl<A: Clone, S: Initializer<A>, M: Mutation<Vec<A>>> RollingHorizon<A, S, M> {
217    /// A planner with a custom sequence mutation (for example Gaussian perturbation of
218    /// continuous actions).
219    #[must_use]
220    pub fn with_mutation(config: Config, actions: S, mutation: M) -> Self {
221        Self {
222            config,
223            actions,
224            mutation,
225            buffer: Vec::new(),
226        }
227    }
228
229    /// Forgets the shift buffer, for example at the start of a new episode.
230    pub fn reset(&mut self) {
231        self.buffer.clear();
232    }
233
234    /// Plans from `state` and returns the first action of the best sequence found.
235    ///
236    /// # Panics
237    ///
238    /// Panics if the horizon, population size or rollout count is `0`.
239    pub fn plan<F, R>(&mut self, model: &mut F, state: &F::State, rng: &mut R) -> Decision<A>
240    where
241        F: ForwardModel<Action = A>,
242        R: Rng + ?Sized,
243    {
244        let c = self.config;
245        assert!(
246            c.horizon > 0 && c.population_size > 0 && c.rollouts > 0,
247            "horizon, population and rollouts must be positive"
248        );
249
250        let mut population = self.seed_population(rng);
251        let mut evaluations = 0;
252        let mut costs: Vec<f64> = Vec::with_capacity(population.len());
253        for sequence in &population {
254            costs.push(self.evaluate(model, state, sequence, rng));
255            evaluations += 1;
256        }
257
258        while evaluations < c.evaluations.max(1) {
259            let remaining = c.evaluations.max(1) - evaluations;
260            if c.population_size == 1 {
261                evaluations += self.hill_climb_step(
262                    model,
263                    state,
264                    &mut population[0],
265                    &mut costs[0],
266                    remaining,
267                    rng,
268                );
269            } else {
270                evaluations +=
271                    self.generation(model, state, &mut population, &mut costs, remaining, rng);
272            }
273        }
274
275        self.decide(&population, &costs, evaluations, rng)
276    }
277
278    /// The shifted buffer, topped up with random sequences.
279    fn seed_population<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<Vec<A>> {
280        let c = self.config;
281        let mut population: Vec<Vec<A>> = core::mem::take(&mut self.buffer);
282        population.truncate(c.population_size);
283        for sequence in &mut population {
284            sequence.resize_with(c.horizon, || self.actions.initialize(rng));
285        }
286
287        while population.len() < c.population_size {
288            population.push(
289                (0..c.horizon)
290                    .map(|_| self.actions.initialize(rng))
291                    .collect(),
292            );
293        }
294
295        population
296    }
297
298    /// One RMHC iteration within `remaining` evaluations (the incumbent is re-evaluated only
299    /// if two remain); returns the evaluations spent.
300    fn hill_climb_step<F, R>(
301        &mut self,
302        model: &mut F,
303        state: &F::State,
304        current: &mut Vec<A>,
305        cost: &mut f64,
306        remaining: u64,
307        rng: &mut R,
308    ) -> u64
309    where
310        F: ForwardModel<Action = A>,
311        R: Rng + ?Sized,
312    {
313        let mut spent = 0;
314        if self.config.reevaluate && remaining >= 2 {
315            *cost = self.evaluate(model, state, current, rng);
316            spent += 1;
317        }
318
319        let mut candidate = current.clone();
320        self.mutation.mutate(&mut candidate, rng);
321        let candidate_cost = self.evaluate(model, state, &candidate, rng);
322        if candidate_cost <= *cost {
323            *current = candidate;
324            *cost = candidate_cost;
325        }
326
327        spent + 1
328    }
329
330    /// One generation of the population variant (elitism one, binary tournament, uniform
331    /// crossover, mutation) with at most `remaining` evaluations; slots left when they run
332    /// out keep the best old sequences. Returns the evaluations spent.
333    fn generation<F, R>(
334        &mut self,
335        model: &mut F,
336        state: &F::State,
337        population: &mut Vec<Vec<A>>,
338        costs: &mut Vec<f64>,
339        remaining: u64,
340        rng: &mut R,
341    ) -> u64
342    where
343        F: ForwardModel<Action = A>,
344        R: Rng + ?Sized,
345    {
346        let order = ranking(costs);
347        let mut next = alloc::vec![population[order[0]].clone()];
348        let mut next_costs = alloc::vec![costs[order[0]]];
349        let mut parents = Vec::with_capacity(2);
350        let mut spent = 0;
351        while next.len() < population.len() && spent < remaining {
352            parents.clear();
353            Tournament { size: 2 }.select(costs, 2, rng, &mut parents);
354            let [mut child, _] = UniformCrossover::default().crossover(
355                &population[parents[0]],
356                &population[parents[1]],
357                rng,
358            );
359            self.mutation.mutate(&mut child, rng);
360            next_costs.push(self.evaluate(model, state, &child, rng));
361            next.push(child);
362            spent += 1;
363        }
364
365        for &k in order.iter().skip(1) {
366            if next.len() == population.len() {
367                break;
368            }
369            next.push(population[k].clone());
370            next_costs.push(costs[k]);
371        }
372
373        *population = next;
374        *costs = next_costs;
375        spent
376    }
377
378    /// Picks the best sequence, fills the shift buffer and builds the decision.
379    fn decide<R: Rng + ?Sized>(
380        &mut self,
381        population: &[Vec<A>],
382        costs: &[f64],
383        evaluations: u64,
384        rng: &mut R,
385    ) -> Decision<A> {
386        let order = ranking(costs);
387        let best = order[0];
388        let plan = population[best].clone();
389        if self.config.shift_buffer {
390            self.buffer = order
391                .iter()
392                .map(|&k| {
393                    let mut shifted: Vec<A> = population[k][1..].to_vec();
394                    shifted.push(self.actions.initialize(rng));
395                    shifted
396                })
397                .collect();
398        }
399
400        Decision {
401            action: plan[0].clone(),
402            cost: costs[best],
403            plan,
404            evaluations,
405        }
406    }
407
408    /// The mean discounted cost of `rollouts` rollouts of `sequence` from `state`.
409    fn evaluate<F, R>(&self, model: &mut F, state: &F::State, sequence: &[A], rng: &mut R) -> f64
410    where
411        F: ForwardModel<Action = A>,
412        R: Rng + ?Sized,
413    {
414        let mut total = 0.0;
415        for _ in 0..self.config.rollouts {
416            total += rollout(model, state, sequence, self.config.discount, rng);
417        }
418
419        #[expect(clippy::cast_precision_loss, reason = "rollout counts are tiny")]
420        let mean = total / self.config.rollouts as f64;
421
422        sanitize(mean)
423    }
424}
425
426/// The discounted cost of executing `sequence` from `state` until it ends or the episode does.
427pub fn rollout<F, R>(
428    model: &mut F,
429    state: &F::State,
430    sequence: &[F::Action],
431    discount: f64,
432    rng: &mut R,
433) -> f64
434where
435    F: ForwardModel,
436    R: Rng + ?Sized,
437{
438    let mut current = state.clone();
439    let mut total = 0.0;
440    let mut weight = 1.0;
441    for action in sequence {
442        let step = model.step(&current, action, rng);
443        total += weight * step.cost;
444        if step.done {
445            break;
446        }
447
448        weight *= discount;
449        current = step.state;
450    }
451
452    total
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use crate::operators::{initializer_fn, mutation_fn};
459    use crate::{SplitMix64, standard_normal, unit_f64};
460
461    /// A corridor of cells; each step costs the remaining distance to the goal (an auxiliary
462    /// criterion in Jakob's sense: it rewards progress, not only arrival); with `slip` the
463    /// move fails.
464    struct Corridor {
465        /// The goal cell.
466        goal: i32,
467        /// The probability that a move does nothing.
468        slip: f64,
469    }
470
471    impl ForwardModel for Corridor {
472        type State = i32;
473        type Action = i32;
474
475        fn step<R: Rng + ?Sized>(&mut self, state: &i32, action: &i32, rng: &mut R) -> Step<i32> {
476            let next = if unit_f64(rng) < self.slip {
477                *state
478            } else {
479                state + action
480            };
481            Step {
482                state: next,
483                cost: f64::from((self.goal - next).abs()),
484                done: next == self.goal,
485            }
486        }
487    }
488
489    /// A corridor planner with function-pointer action sampling.
490    type CorridorPlanner<M> =
491        RollingHorizon<i32, crate::operators::InitializerFn<fn(&mut dyn Rng) -> i32>, M>;
492
493    /// Runs a closed-loop episode; returns the steps to the goal.
494    fn episode<M: Mutation<Vec<i32>>>(
495        planner: &mut CorridorPlanner<M>,
496        slip: f64,
497        seed: u64,
498    ) -> usize {
499        let mut model = Corridor { goal: 6, slip };
500        let mut rng = SplitMix64::new(seed);
501        let mut state = 0;
502        for t in 0..100 {
503            if state == 6 {
504                return t;
505            }
506            let decision = planner.plan(&mut model, &state, &mut rng);
507            state = model.step(&state, &decision.action, &mut rng).state;
508        }
509
510        100
511    }
512
513    /// The action sampler of the corridor: -1, 0 or +1.
514    fn moves(rng: &mut dyn Rng) -> i32 {
515        i32::try_from(below(rng, 3)).expect("small") - 1
516    }
517
518    /// RMHC and the population variant walk straight to the goal on the deterministic
519    /// corridor.
520    #[test]
521    fn deterministic_corridor() {
522        for population_size in [1, 8] {
523            let config = Config {
524                horizon: 10,
525                population_size,
526                evaluations: 300,
527                ..Config::default()
528            };
529            let mut planner =
530                RollingHorizon::new(config, initializer_fn(moves as fn(&mut dyn Rng) -> i32));
531            assert_eq!(
532                episode(&mut planner, 0.0, 3),
533                6,
534                "population {population_size}"
535            );
536        }
537    }
538
539    /// Each decision spends exactly the configured evaluations, with re-evaluation and with a
540    /// population.
541    #[test]
542    fn exact_evaluations_per_decision() {
543        for (population_size, reevaluate) in [(1, false), (1, true), (7, false)] {
544            let config = Config {
545                horizon: 6,
546                population_size,
547                reevaluate,
548                evaluations: 101,
549                ..Config::default()
550            };
551            let mut planner =
552                RollingHorizon::new(config, initializer_fn(moves as fn(&mut dyn Rng) -> i32));
553            let mut model = Corridor { goal: 6, slip: 0.0 };
554            let decision = planner.plan(&mut model, &0, &mut SplitMix64::new(1));
555            assert_eq!(decision.evaluations, 101, "{population_size} {reevaluate}");
556        }
557    }
558
559    /// With slipping moves and averaged, re-evaluated rollouts the goal is still reached
560    /// quickly.
561    #[test]
562    fn stochastic_corridor() {
563        let config = Config {
564            horizon: 10,
565            rollouts: 4,
566            reevaluate: true,
567            ..Config::default()
568        };
569        let mut planner =
570            RollingHorizon::new(config, initializer_fn(moves as fn(&mut dyn Rng) -> i32));
571        let steps = episode(&mut planner, 0.2, 5);
572
573        assert!(steps <= 14, "{steps} steps");
574    }
575
576    /// The shift buffer carries the plan: a deterministic plan found once is kept, so later
577    /// decisions follow it even with a single evaluation each.
578    #[test]
579    fn shift_buffer_keeps_the_plan() {
580        let config = Config {
581            horizon: 8,
582            evaluations: 400,
583            ..Config::default()
584        };
585        let mut planner =
586            RollingHorizon::new(config, initializer_fn(moves as fn(&mut dyn Rng) -> i32));
587        let mut model = Corridor { goal: 6, slip: 0.0 };
588        let mut rng = SplitMix64::new(9);
589        let first = planner.plan(&mut model, &0, &mut rng);
590        planner.config.evaluations = 1;
591        let second = planner.plan(&mut model, &first.action, &mut rng);
592
593        assert_eq!(second.plan[..first.plan.len() - 1], first.plan[1..]);
594    }
595
596    /// Continuous actions with a Gaussian sequence mutation steer a point mass to the origin.
597    #[test]
598    fn continuous_point_mass() {
599        /// Position and velocity; the action is an acceleration in [-1, 1].
600        struct PointMass;
601
602        impl ForwardModel for PointMass {
603            type State = (f64, f64);
604            type Action = f64;
605
606            fn step<R: Rng + ?Sized>(
607                &mut self,
608                s: &(f64, f64),
609                a: &f64,
610                _rng: &mut R,
611            ) -> Step<(f64, f64)> {
612                let a = a.clamp(-1.0, 1.0);
613                let v = s.1 + 0.1 * a;
614                let x = s.0 + 0.1 * v;
615                Step {
616                    state: (x, v),
617                    cost: x * x + 0.1 * v * v + 0.01 * a * a,
618                    done: false,
619                }
620            }
621        }
622
623        let mutation = mutation_fn(|plan: &mut Vec<f64>, rng: &mut dyn Rng| {
624            for a in plan.iter_mut() {
625                *a = (*a + 0.3 * standard_normal(rng)).clamp(-1.0, 1.0);
626            }
627        });
628        let config = Config {
629            horizon: 20,
630            evaluations: 300,
631            ..Config::default()
632        };
633        let mut planner = RollingHorizon::with_mutation(
634            config,
635            initializer_fn(|rng| 2.0 * unit_f64(rng) - 1.0),
636            mutation,
637        );
638        let mut rng = SplitMix64::new(2);
639        let mut state = (1.0, 0.0);
640        for _ in 0..150 {
641            let decision = planner.plan(&mut PointMass, &state, &mut rng);
642            state = PointMass.step(&state, &decision.action, &mut rng).state;
643        }
644
645        assert!(state.0.abs() < 0.1 && state.1.abs() < 0.2, "{state:?}");
646    }
647}