1use 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#[derive(Debug, Clone, PartialEq)]
58pub struct Step<S> {
59 pub state: S,
61 pub cost: f64,
63 pub done: bool,
65}
66
67pub trait ForwardModel {
71 type State: Clone;
73 type Action: Clone;
75
76 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#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct Config {
88 pub horizon: usize,
90 pub population_size: usize,
92 pub evaluations: u64,
96 pub discount: f64,
98 pub rollouts: usize,
100 pub shift_buffer: bool,
102 pub reevaluate: bool,
105 pub mutation_rate: Option<f64>,
108}
109
110impl Default for Config {
111 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#[derive(Debug, Clone, PartialEq)]
129pub struct Decision<A> {
130 pub action: A,
132 pub plan: Vec<A>,
134 pub cost: f64,
136 pub evaluations: u64,
138}
139
140#[derive(Debug, Clone, Copy, PartialEq)]
143pub struct PointMutation<S> {
144 pub actions: S,
146 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#[derive(Debug, Clone, PartialEq)]
175pub struct RollingHorizon<A, S, M> {
176 pub config: Config,
178 pub actions: S,
180 pub mutation: M,
182 buffer: Vec<Vec<A>>,
184}
185
186impl<A: Clone, S: Initializer<A> + Clone> RollingHorizon<A, S, PointMutation<S>> {
187 #[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 #[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 #[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 pub fn reset(&mut self) {
231 self.buffer.clear();
232 }
233
234 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 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 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 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 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 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
426pub 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(¤t, 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 struct Corridor {
465 goal: i32,
467 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 type CorridorPlanner<M> =
491 RollingHorizon<i32, crate::operators::InitializerFn<fn(&mut dyn Rng) -> i32>, M>;
492
493 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 fn moves(rng: &mut dyn Rng) -> i32 {
515 i32::try_from(below(rng, 3)).expect("small") - 1
516 }
517
518 #[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 #[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 #[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 #[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 #[test]
598 fn continuous_point_mass() {
599 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}