evolutionary_planning/cost.rs
1//! Costs and evaluated individuals: the NaN policy, the total order used for every sort, and
2//! the [`Individual`] pair of a genome and its cost.
3//!
4//! Every objective in this crate is minimised (see `docs/design.md`).
5
6use alloc::vec::Vec;
7use core::cmp::Ordering;
8
9/// Maps NaN to `+∞`, so a broken objective yields the worst possible individual instead of
10/// poisoning comparisons. Applied once to every value an objective returns.
11///
12/// ```
13/// use evolutionary_planning::sanitize;
14///
15/// assert_eq!(sanitize(f64::NAN), f64::INFINITY);
16/// assert_eq!(sanitize(-1.5), -1.5);
17/// ```
18#[must_use]
19pub fn sanitize(cost: f64) -> f64 {
20 if cost.is_nan() { f64::INFINITY } else { cost }
21}
22
23/// A genome together with its (sanitised) cost; smaller is better.
24#[derive(Debug, Clone, PartialEq)]
25pub struct Individual<G> {
26 /// The candidate solution.
27 pub genome: G,
28 /// Its cost as returned by the objective, NaN mapped to `+∞`.
29 pub cost: f64,
30}
31
32impl<G> Individual<G> {
33 /// Pairs `genome` with `cost`, sanitising the cost.
34 #[must_use]
35 pub fn new(genome: G, cost: f64) -> Self {
36 Self {
37 genome,
38 cost: sanitize(cost),
39 }
40 }
41}
42
43/// Compares two costs; costs are sanitised, so `total_cmp` orders them like `<` would.
44pub(crate) fn compare(a: f64, b: f64) -> Ordering {
45 a.total_cmp(&b)
46}
47
48/// Returns the indices of `costs` sorted ascending by cost, ties broken by index, so the
49/// order never depends on the sort algorithm.
50#[must_use]
51pub fn ranking(costs: &[f64]) -> Vec<usize> {
52 let mut order: Vec<usize> = (0..costs.len()).collect();
53 order.sort_by(|&a, &b| compare(costs[a], costs[b]).then(a.cmp(&b)));
54
55 order
56}
57
58/// Sorts `population` ascending by cost; stable, so ties keep their order.
59pub(crate) fn sort_population<G>(population: &mut [Individual<G>]) {
60 population.sort_by(|a, b| compare(a.cost, b.cost));
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 /// Ties are broken by index and NaN sorts last after sanitising.
68 #[test]
69 fn ranking_is_stable_and_nan_last() {
70 let costs = [2.0, 1.0, sanitize(f64::NAN), 1.0, -0.0];
71
72 assert_eq!(ranking(&costs), [4, 1, 3, 0, 2]);
73 }
74}