Skip to main content

evolutionary_planning/
sas.rs

1//! Genetic search over SAS+ plans (feature `sas-plus`): plans are GLEAM action chains of
2//! operator ids, decoded by simulating the [`sas_plus::Task`], scored by EvoPlan's fitness
3//! cascade, and repaired phenotypically or genotypically.
4//!
5//! Decoding uses only [`Task::initial_state`], [`Task::is_applicable`], [`Task::apply`] and
6//! [`Task::is_goal`], exactly the steps of [`Task::validate_plan`], so axioms and conditional
7//! effects behave identically and every plan reported as valid passes `validate_plan` with
8//! the same cost (tested).
9//!
10//! The cost of a chain (minimised):
11//!
12//! - **valid** (the decoded plan reaches the goal): its plan cost;
13//! - **invalid**: `penalty + unsatisfied goal facts + (1 - executed fraction)`, where the
14//!   penalty exceeds every valid plan's cost. Invalid chains are ranked by how close they get
15//!   instead of all scoring the same (Jakob's rule against flat penalties; EvoPlan ranks
16//!   invalid plans by the fraction that executes).
17//!
18//! ```
19//! use evolutionary_planning::sas::{Config, solve};
20//! use evolutionary_planning::{Limits, SplitMix64};
21//! use sas_plus::{Fact, Operator, State, Task, Variable, Effect};
22//!
23//! // A counter 0 -> 1 -> 2 with a goal of 2.
24//! let step = |from: u32| Operator {
25//!     name: format!("inc{from}"),
26//!     pre: vec![Fact::new(0, from)],
27//!     eff: vec![Effect::new(Fact::new(0, from + 1))],
28//!     cost: 1,
29//! };
30//! let task = Task {
31//!     variables: vec![Variable::new("x", 3)],
32//!     operators: vec![step(0), step(1)],
33//!     initial: State(vec![0]),
34//!     goal: vec![Fact::new(0, 2)],
35//!     axioms: vec![],
36//! };
37//! let result = solve(&task, &Config::default(), &mut Limits::evaluations(2_000), &mut SplitMix64::new(1));
38//! assert_eq!(result.plan, Some(vec![0, 1]));
39//! assert_eq!(task.validate_plan(&[0, 1]), result.cost);
40//! ```
41
42use alloc::vec::Vec;
43
44use rand_core::Rng;
45use sas_plus::{OpId, State, Task};
46
47use crate::ga::{Config as GaConfig, Ga, Operators, Scheme};
48use crate::operators::chain::{
49    CutAndSplice, DeleteGene, GeneShift, InsertGene, ReplaceGene, SegmentInversion,
50};
51use crate::operators::selection::Tournament;
52use crate::operators::{Initializer, Mutation, Repair, mix};
53use crate::rng::below;
54use crate::{Budget, Objective, Outcome, Stats};
55
56/// How a chain is interpreted when an operator is not applicable.
57#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
58pub enum Decoding {
59    /// Phenotypic repair: inapplicable operators are skipped. The default; it lets order
60    /// changes spread over several offspring (Jakob 2021, section 4.1.4).
61    #[default]
62    Skip,
63    /// Execution stops at the first inapplicable operator (EvoPlan's validated prefix).
64    Strict,
65}
66
67/// The result of simulating a chain.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Decoded {
70    /// The executed operators, up to and including the one that reached the goal.
71    pub plan: Vec<OpId>,
72    /// The cost of `plan`.
73    pub cost: u64,
74    /// Whether `plan` reaches the goal.
75    pub reaches_goal: bool,
76    /// How many genes were looked at before decoding stopped (the goal, the end of the chain,
77    /// or the first inapplicable gene under [`Decoding::Strict`]).
78    pub inspected: usize,
79    /// The number of goal facts that do not hold in the final state.
80    pub unsatisfied_goals: usize,
81}
82
83/// A SAS+ task as an [`Objective`] over operator chains.
84#[derive(Debug, Clone, Copy)]
85pub struct PlanObjective<'t> {
86    /// The task.
87    task: &'t Task,
88    /// The decoding rule.
89    decoding: Decoding,
90    /// The cost added to every invalid chain; above any valid plan's cost.
91    penalty: f64,
92}
93
94impl<'t> PlanObjective<'t> {
95    /// Scores chains of at most `max_len` operators of `task`.
96    #[must_use]
97    pub fn new(task: &'t Task, decoding: Decoding, max_len: usize) -> Self {
98        let max_cost = task
99            .operators
100            .iter()
101            .map(|o| u64::from(o.cost))
102            .max()
103            .unwrap_or(0);
104        #[expect(
105            clippy::cast_precision_loss,
106            reason = "plan cost bounds far below 2^52"
107        )]
108        let penalty = (max_cost.saturating_mul(max_len as u64) + 1) as f64;
109
110        Self {
111            task,
112            decoding,
113            penalty,
114        }
115    }
116
117    /// The penalty added to invalid chains.
118    #[must_use]
119    pub fn penalty(&self) -> f64 {
120        self.penalty
121    }
122
123    /// Simulates `chain` from the initial state.
124    #[must_use]
125    pub fn decode(&self, chain: &[OpId]) -> Decoded {
126        let task = self.task;
127        let mut state = task.initial_state();
128        let mut plan = Vec::new();
129        let mut cost = 0;
130        let mut inspected = 0;
131        let mut reaches_goal = task.is_goal(&state);
132        for &op in chain {
133            if reaches_goal {
134                break;
135            }
136
137            inspected += 1;
138            if op >= task.operators.len() || !task.is_applicable(op, &state) {
139                if self.decoding == Decoding::Strict {
140                    break;
141                }
142                continue;
143            }
144
145            state = task.apply(op, &state);
146            cost += u64::from(task.operators[op].cost);
147            plan.push(op);
148            reaches_goal = task.is_goal(&state);
149        }
150
151        Decoded {
152            unsatisfied_goals: unsatisfied(task, &state),
153            plan,
154            cost,
155            reaches_goal,
156            inspected,
157        }
158    }
159
160    /// The cost of a decoded chain of `len` genes: plan cost if valid, otherwise the
161    /// penalty plus the distance terms.
162    #[must_use]
163    pub fn score(&self, decoded: &Decoded, len: usize) -> f64 {
164        if decoded.reaches_goal {
165            #[expect(clippy::cast_precision_loss, reason = "plan costs far below 2^52")]
166            return decoded.cost as f64;
167        }
168
169        #[expect(clippy::cast_precision_loss, reason = "counts far below 2^52")]
170        let executed = if len == 0 {
171            0.0
172        } else {
173            decoded.plan.len() as f64 / len as f64
174        };
175        #[expect(clippy::cast_precision_loss, reason = "counts far below 2^52")]
176        let unsatisfied = decoded.unsatisfied_goals as f64;
177
178        self.penalty + unsatisfied + (1.0 - executed)
179    }
180}
181
182impl Objective<Vec<OpId>> for PlanObjective<'_> {
183    fn evaluate(&mut self, genome: &Vec<OpId>) -> f64 {
184        self.score(&self.decode(genome), genome.len())
185    }
186}
187
188/// The goal facts that do not hold in `state`.
189fn unsatisfied(task: &Task, state: &State) -> usize {
190    task.goal
191        .iter()
192        .filter(|f| state.0[f.var] != f.value)
193        .count()
194}
195
196/// Uniform random operator ids of a task: the gene sampler of the chain operators.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct RandomOperator {
199    /// The number of operators of the task, at least `1`.
200    pub count: usize,
201}
202
203impl Initializer<OpId> for RandomOperator {
204    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> OpId {
205        below(rng, self.count)
206    }
207}
208
209/// Random walks of applicable operators from the initial state, of uniform length in
210/// `1..=max_len` (shorter if a dead end or the goal is reached): an initial population of
211/// executable chains.
212#[derive(Debug, Clone, Copy)]
213pub struct ApplicableWalk<'t> {
214    /// The task.
215    pub task: &'t Task,
216    /// The longest walk.
217    pub max_len: usize,
218}
219
220impl Initializer<Vec<OpId>> for ApplicableWalk<'_> {
221    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<OpId> {
222        let task = self.task;
223        let len = 1 + below(rng, self.max_len.max(1));
224        let mut state = task.initial_state();
225        let mut walk = Vec::with_capacity(len);
226        while walk.len() < len && !task.is_goal(&state) {
227            let applicable: Vec<OpId> = task.applicable_operators(&state).collect();
228            if applicable.is_empty() {
229                break;
230            }
231
232            let op = applicable[below(rng, applicable.len())];
233            state = task.apply(op, &state);
234            walk.push(op);
235        }
236
237        walk
238    }
239}
240
241/// Whether and how chains are repaired genotypically.
242#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
243pub enum RepairMode {
244    /// No genotypic repair: chains keep their inapplicable genes, and only the decoding
245    /// skips them (phenotypic repair; the default, following Jakob's advice that genotypic
246    /// repair freezes order changes that need several steps).
247    #[default]
248    Off,
249    /// Write the executed plan back: inapplicable genes are dropped and the chain is cut
250    /// after the goal.
251    Drop,
252    /// Like `Drop`, but each inapplicable gene is replaced by a uniformly chosen applicable
253    /// operator.
254    Replace,
255}
256
257/// Genotypic repair of operator chains, see [`RepairMode`].
258#[derive(Debug, Clone, Copy)]
259pub struct PlanRepair<'t> {
260    /// The task.
261    pub task: &'t Task,
262    /// What the repair does.
263    pub mode: RepairMode,
264}
265
266impl Repair<Vec<OpId>> for PlanRepair<'_> {
267    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<OpId>, rng: &mut R) {
268        if self.mode == RepairMode::Off {
269            return;
270        }
271
272        let task = self.task;
273        let mut state = task.initial_state();
274        let mut repaired = Vec::with_capacity(genome.len());
275        for &op in genome.iter() {
276            if task.is_goal(&state) {
277                break;
278            }
279
280            let op = if op < task.operators.len() && task.is_applicable(op, &state) {
281                op
282            } else if self.mode == RepairMode::Replace {
283                let applicable: Vec<OpId> = task.applicable_operators(&state).collect();
284                if applicable.is_empty() {
285                    continue;
286                }
287                applicable[below(rng, applicable.len())]
288            } else {
289                continue;
290            };
291
292            state = task.apply(op, &state);
293            repaired.push(op);
294        }
295
296        *genome = repaired;
297    }
298}
299
300/// Parameters of [`solve`].
301#[derive(Debug, Clone, Copy, PartialEq)]
302pub struct Config {
303    /// The GA population size.
304    pub population_size: usize,
305    /// The longest chain.
306    pub max_len: usize,
307    /// The decoding rule.
308    pub decoding: Decoding,
309    /// The genotypic repair applied to every child.
310    pub repair: RepairMode,
311}
312
313impl Default for Config {
314    /// 60 chains of at most 40 operators, phenotypic skipping, no genotypic repair.
315    fn default() -> Self {
316        Self {
317            population_size: 60,
318            max_len: 40,
319            decoding: Decoding::Skip,
320            repair: RepairMode::Off,
321        }
322    }
323}
324
325/// The result of [`solve`].
326#[derive(Debug, Clone, PartialEq)]
327pub struct PlanOutcome {
328    /// The best valid plan found, decoded (only executed operators); `None` if no chain
329    /// reached the goal.
330    pub plan: Option<Vec<OpId>>,
331    /// Its cost, equal to `task.validate_plan(plan)`.
332    pub cost: Option<u64>,
333    /// The raw GA outcome over chains.
334    pub outcome: Outcome<Vec<OpId>>,
335}
336
337/// Searches for a cheap plan with a steady-state GA over GLEAM chains: applicable random
338/// walks as the initial population, cut-and-splice crossover and a mix of gene insertion,
339/// deletion, replacement, shift and segment inversion.
340///
341/// # Panics
342///
343/// Panics if the task has no operators.
344pub fn solve<B, R>(task: &Task, config: &Config, budget: &mut B, rng: &mut R) -> PlanOutcome
345where
346    B: Budget<Stats> + ?Sized,
347    R: Rng + ?Sized,
348{
349    assert!(
350        !task.operators.is_empty(),
351        "a task without operators has no plans to evolve"
352    );
353
354    let mutation = chain_mutation(task.operators.len(), config.max_len);
355    let mut ga = Ga::new(
356        GaConfig {
357            population_size: config.population_size,
358            elitism: 2,
359            crossover_rate: 0.6,
360            mutation_rate: 1.0,
361            scheme: Scheme::SteadyState {
362                only_if_better: false,
363            },
364        },
365        Operators {
366            init: ApplicableWalk {
367                task,
368                max_len: config.max_len,
369            },
370            selection: Tournament { size: 3 },
371            crossover: CutAndSplice {
372                max_len: config.max_len,
373            },
374            mutation,
375            repair: PlanRepair {
376                task,
377                mode: config.repair,
378            },
379        },
380    );
381    let mut objective = PlanObjective::new(task, config.decoding, config.max_len);
382    let outcome = ga.run(&mut objective, budget, &mut (), rng);
383    let decoded = outcome.best_genome().map(|chain| objective.decode(chain));
384    let (plan, cost) = match decoded {
385        Some(d) if d.reaches_goal => (Some(d.plan), Some(d.cost)),
386        _ => (None, None),
387    };
388
389    PlanOutcome {
390        plan,
391        cost,
392        outcome,
393    }
394}
395
396/// GLEAM's operator mix for plan chains: gene insertion and deletion, replacement, gene shift
397/// and segment inversion, weighted towards insertion and replacement.
398fn chain_mutation(operators: usize, max_len: usize) -> impl Mutation<Vec<OpId>> {
399    let genes = RandomOperator { count: operators };
400
401    mix(
402        mix(
403            InsertGene { genes, max_len },
404            2.0,
405            DeleteGene { min_len: 0 },
406            1.0,
407        ),
408        3.0,
409        mix(
410            ReplaceGene { genes },
411            2.0,
412            mix(
413                GeneShift,
414                1.0,
415                SegmentInversion {
416                    max_segment: Some(4),
417                },
418                1.0,
419            ),
420            2.0,
421        ),
422        4.0,
423    )
424}
425
426#[cfg(test)]
427mod tests {
428    use sas_plus::random::{RandomTaskParams, random_task};
429
430    use super::*;
431    use crate::{Limits, SplitMix64};
432
433    /// The outcome counts of [`solve`] over 40 random tasks with conditional effects and
434    /// axioms: `(solvable, found, optimal)`. Every reported plan must pass `validate_plan` with
435    /// the reported cost and never beat the optimum from `perfect_heuristic`.
436    fn validate_over_random_tasks(config: &Config) -> (usize, usize, usize) {
437        let (mut solvable, mut found, mut optimal) = (0, 0, 0);
438        for seed in 0..40 {
439            let params = RandomTaskParams {
440                num_vars: 4,
441                max_domain: 3,
442                num_ops: 12,
443                max_cost: 4,
444                max_conditions: 1,
445                num_derived: usize::from(seed % 2 == 1),
446            };
447            let task = random_task(seed, params);
448            let Some(best) = task.perfect_heuristic()(&task.initial_state()) else {
449                continue;
450            };
451
452            solvable += 1;
453            let result = solve(
454                &task,
455                config,
456                &mut Limits::evaluations(6_000),
457                &mut SplitMix64::new(seed),
458            );
459            if let (Some(plan), Some(cost)) = (&result.plan, result.cost) {
460                assert_eq!(
461                    task.validate_plan(plan),
462                    Some(cost),
463                    "{config:?}, seed {seed}"
464                );
465                assert!(
466                    cost >= best,
467                    "{config:?}, seed {seed}: {cost} < optimum {best}"
468                );
469                found += 1;
470                optimal += usize::from(cost == best);
471            }
472        }
473
474        (solvable, found, optimal)
475    }
476
477    /// Every decoding and repair combination reports only valid plans; the default finds a
478    /// plan for 90 % of the solvable tasks and an optimal one for half.
479    #[test]
480    fn plans_validate_against_sas_plus() {
481        for decoding in [Decoding::Skip, Decoding::Strict] {
482            for repair in [RepairMode::Off, RepairMode::Drop, RepairMode::Replace] {
483                let config = Config {
484                    decoding,
485                    repair,
486                    ..Config::default()
487                };
488                let (solvable, found, optimal) = validate_over_random_tasks(&config);
489                assert!(solvable >= 10, "only {solvable} solvable tasks");
490                if config == Config::default() {
491                    assert!(found * 10 >= solvable * 9, "found {found} of {solvable}");
492                    assert!(optimal * 2 >= solvable, "optimal {optimal} of {solvable}");
493                }
494            }
495        }
496    }
497
498    /// The cascade ranks invalid chains by unsatisfied goals and executed fraction, below any
499    /// valid plan; strict decoding stops at the first inapplicable gene.
500    #[test]
501    fn fitness_cascade() {
502        let task = random_task(3, RandomTaskParams::default());
503        let objective = PlanObjective::new(&task, Decoding::Strict, 10);
504        let decoded = objective.decode(&[usize::MAX, 0, 1]);
505
506        assert_eq!(decoded.inspected, 1);
507        assert_eq!(decoded.plan, Vec::<OpId>::new());
508        let score = objective.score(&decoded, 3);
509        assert!(score >= objective.penalty());
510    }
511
512    /// Genotypic repair produces executable chains.
513    #[test]
514    fn repair_makes_chains_executable() {
515        let task = random_task(5, RandomTaskParams::default());
516        let mut rng = SplitMix64::new(2);
517        let mut repair = PlanRepair {
518            task: &task,
519            mode: RepairMode::Replace,
520        };
521        let objective = PlanObjective::new(&task, Decoding::Strict, 20);
522        for _ in 0..50 {
523            let mut chain: Vec<OpId> = (0..10)
524                .map(|_| below(&mut rng, task.operators.len()))
525                .collect();
526            repair.repair(&mut chain, &mut rng);
527            let decoded = objective.decode(&chain);
528            assert_eq!(decoded.plan, chain[..decoded.plan.len()]);
529            assert_eq!(decoded.plan.len(), chain.len());
530        }
531    }
532}