Skip to main content

evolutionary_planning/
multi.rs

1//! The bookkeeping shared by the multi-objective algorithms: the evaluator (budget, NaN
2//! sanitising, counters, events) and [`MultiOutcome`].
3
4use alloc::vec::Vec;
5
6use crate::pareto::{Evaluated, non_dominated_sort};
7use crate::{Budget, Event, MultiObjective, Observer, Stats, Stop, sanitize};
8
9/// The result of a multi-objective run.
10#[derive(Debug, Clone, PartialEq)]
11pub struct MultiOutcome<G> {
12    /// The first non-dominated front (under constrained domination) of the final population
13    /// or archive: feasible members only, unless no member is feasible.
14    pub front: Vec<Evaluated<G>>,
15    /// The final population.
16    pub population: Vec<Evaluated<G>>,
17    /// The counters at the end of the run. [`Stats::best_cost`] stays `+∞`: there is no single
18    /// best cost, so a target cost never stops a multi-objective run.
19    pub stats: Stats,
20    /// Why the run ended.
21    pub stop: Stop,
22}
23
24/// Counts evaluations against a budget for a [`MultiObjective`].
25pub(crate) struct MultiEvaluator<'a, M: ?Sized, B: ?Sized, Obs: ?Sized> {
26    /// The problem.
27    problem: &'a mut M,
28    /// Asked before every evaluation.
29    budget: &'a mut B,
30    /// Receives `Generation` events.
31    observer: &'a mut Obs,
32    /// The counters so far.
33    pub(crate) stats: Stats,
34    /// The number of objectives.
35    pub(crate) objectives: usize,
36}
37
38impl<'a, M: ?Sized, B, Obs> MultiEvaluator<'a, M, B, Obs>
39where
40    B: Budget<Stats> + ?Sized,
41    Obs: Observer + ?Sized,
42{
43    /// Starts counting from zero.
44    pub(crate) fn new<G>(problem: &'a mut M, budget: &'a mut B, observer: &'a mut Obs) -> Self
45    where
46        M: MultiObjective<G>,
47    {
48        let objectives = problem.objectives();
49
50        Self {
51            problem,
52            budget,
53            observer,
54            stats: Stats::default(),
55            objectives,
56        }
57    }
58
59    /// Evaluates `genome` unless the budget is exhausted.
60    pub(crate) fn evaluate<G>(&mut self, genome: G) -> Option<Evaluated<G>>
61    where
62        M: MultiObjective<G>,
63    {
64        if self.budget.exhausted(&self.stats) {
65            return None;
66        }
67
68        let mut objectives = alloc::vec![0.0; self.objectives];
69        let violation = sanitize(self.problem.evaluate(&genome, &mut objectives)).max(0.0);
70        for value in &mut objectives {
71            *value = sanitize(*value);
72        }
73
74        self.stats.evaluations += 1;
75
76        Some(Evaluated {
77            genome,
78            objectives,
79            violation,
80        })
81    }
82
83    /// Marks a generation as complete.
84    pub(crate) fn end_generation(&mut self) {
85        self.stats.generations += 1;
86        if Obs::ENABLED {
87            self.observer.observe(Event::Generation {
88                stats: self.stats,
89                population_best: f64::INFINITY,
90            });
91        }
92    }
93
94    /// Ends the run: computes the first front of `population`.
95    pub(crate) fn outcome<G: Clone>(
96        &self,
97        population: Vec<Evaluated<G>>,
98        stop: Stop,
99    ) -> MultiOutcome<G> {
100        MultiOutcome {
101            front: first_front(&population),
102            population,
103            stats: self.stats,
104            stop,
105        }
106    }
107}
108
109/// The first front under constrained domination; feasible members only if any is feasible
110/// (constrained domination already guarantees that).
111pub(crate) fn first_front<G: Clone>(population: &[Evaluated<G>]) -> Vec<Evaluated<G>> {
112    let points: Vec<&[f64]> = population.iter().map(|e| e.objectives.as_slice()).collect();
113    let violations: Vec<f64> = population.iter().map(|e| e.violation).collect();
114    let fronts = non_dominated_sort(&points, &violations);
115
116    fronts
117        .first()
118        .map(|front| front.iter().map(|&i| population[i].clone()).collect())
119        .unwrap_or_default()
120}