evolutionary_planning/stl/fit.rs
1//! Evolutionary fitting of STL thresholds to demonstrations, after EvoPlan's constraint
2//! mining: maximise
3//! `E_{τ ∈ D+} ρ(τ, φ) - λ- E_{τ ∈ D-} max(0, ρ(τ, φ)) - λc · complexity(φ)`
4//! over the thresholds of a template formula, with CMA-ES. `D+` are acceptable traces,
5//! `D-` perturbed ones that should violate the constraint.
6//!
7//! EvoPlan searches over formula structure with LLM-proposed program edits; here the
8//! structure is the caller's template and only its thresholds evolve (see the paper table in
9//! `docs/design.md`).
10
11use alloc::vec::Vec;
12
13use rand_core::Rng;
14
15use super::Formula;
16use crate::cmaes::{CmaEs, Config};
17use crate::{Limits, Objective};
18
19/// Parameters of [`fit`].
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct FitConfig {
22 /// The weight `λ-` of satisfied negatives. The positive margin grows with slope `1` as a
23 /// threshold loosens, and each admitted negative adds slope `-λ- / |D-|`; so with
24 /// `λ- > |D-|` admitting even one negative never pays, while smaller weights trade a few
25 /// admitted negatives for margin on the positives.
26 pub negative_weight: f64,
27 /// The weight `λc` of the complexity term (constant for a fixed template; it matters when
28 /// several templates are compared by their [`Fitted::score`]).
29 pub complexity_weight: f64,
30 /// The initial CMA-ES step size, in threshold units.
31 pub sigma: f64,
32 /// The evaluation budget of CMA-ES.
33 pub evaluations: u64,
34}
35
36impl Default for FitConfig {
37 /// `λ- = 2`, `λc = 0.01`, `σ = 1`, 3000 evaluations.
38 fn default() -> Self {
39 Self {
40 negative_weight: 2.0,
41 complexity_weight: 0.01,
42 sigma: 1.0,
43 evaluations: 3_000,
44 }
45 }
46}
47
48/// A fitted formula and its score.
49#[derive(Debug, Clone, PartialEq)]
50pub struct Fitted {
51 /// The template with the fitted thresholds.
52 pub formula: Formula,
53 /// Its score (to maximise).
54 pub score: f64,
55}
56
57/// The EvoPlan mining score of `formula` on the demonstrations. Robustness values are clamped
58/// to `±1e6` so that vacuous windows (`±∞`) do not dominate the means.
59#[must_use]
60pub fn score<S: AsRef<[f64]>>(
61 formula: &Formula,
62 positives: &[Vec<S>],
63 negatives: &[Vec<S>],
64 config: &FitConfig,
65) -> f64 {
66 /// The clamp of infinite robustness values.
67 const BOUND: f64 = 1e6;
68
69 let mean = |values: &mut dyn Iterator<Item = f64>, count: usize| {
70 #[expect(clippy::cast_precision_loss, reason = "demonstration counts are small")]
71 let count = count.max(1) as f64;
72 values.sum::<f64>() / count
73 };
74 let rho = |trace: &Vec<S>| formula.robustness(trace).clamp(-BOUND, BOUND);
75 let satisfied = mean(&mut positives.iter().map(rho), positives.len());
76 let admitted = mean(
77 &mut negatives.iter().map(|t| rho(t).max(0.0)),
78 negatives.len(),
79 );
80 #[expect(clippy::cast_precision_loss, reason = "formula sizes are small")]
81 let complexity = formula.complexity() as f64;
82
83 satisfied - config.negative_weight * admitted - config.complexity_weight * complexity
84}
85
86/// Fits the thresholds of `template` to positive and negative demonstrations by maximising
87/// [`score`] with CMA-ES from the template's own thresholds.
88///
89/// ```
90/// use evolutionary_planning::stl::{FitConfig, Formula, fit};
91/// use evolutionary_planning::SplitMix64;
92///
93/// // Demonstrations keep speed (signal 0) at most 5; perturbed ones speed up to 10.
94/// let positives: Vec<Vec<[f64; 1]>> = (0..5).map(|k| vec![[3.0 + 0.4 * k as f64]; 4]).collect();
95/// let negatives: Vec<Vec<[f64; 1]>> = (0..5).map(|k| vec![[10.0 + k as f64]; 4]).collect();
96/// let template = Formula::always(0, 3, Formula::le(0, 0.0));
97/// // Five negatives: a weight above five forbids admitting any of them.
98/// let config = FitConfig { negative_weight: 10.0, ..FitConfig::default() };
99/// let fitted = fit(&template, &positives, &negatives, &config, &mut SplitMix64::new(1));
100/// let threshold = fitted.formula.thresholds()[0];
101/// assert!((4.6..=10.0 + 1e-6).contains(&threshold), "{threshold}");
102/// assert!(negatives.iter().all(|t| fitted.formula.robustness(t) <= 1e-6));
103/// ```
104pub fn fit<S: AsRef<[f64]>, R: Rng + ?Sized>(
105 template: &Formula,
106 positives: &[Vec<S>],
107 negatives: &[Vec<S>],
108 config: &FitConfig,
109 rng: &mut R,
110) -> Fitted {
111 let start = template.thresholds();
112 if start.is_empty() {
113 return Fitted {
114 formula: template.clone(),
115 score: score(template, positives, negatives, config),
116 };
117 }
118
119 let mut objective = |thresholds: &Vec<f64>| {
120 -score(
121 &template.with_thresholds(thresholds),
122 positives,
123 negatives,
124 config,
125 )
126 };
127 let mut cma = CmaEs::new(start.clone(), config.sigma, Config::default());
128 let outcome = cma.minimize(
129 &mut objective,
130 &mut Limits::evaluations(config.evaluations),
131 &mut (),
132 rng,
133 );
134 let thresholds = outcome.best.map_or(start, |b| b.genome);
135 let formula = template.with_thresholds(&thresholds);
136 let fitted_score = -objective.evaluate(&thresholds);
137
138 Fitted {
139 formula,
140 score: fitted_score,
141 }
142}