use alloc::vec::Vec;
use rand_core::Rng;
use sas_plus::{OpId, State, Task};
use crate::ga::{Config as GaConfig, Ga, Operators, Scheme};
use crate::operators::chain::{
CutAndSplice, DeleteGene, GeneShift, InsertGene, ReplaceGene, SegmentInversion,
};
use crate::operators::selection::Tournament;
use crate::operators::{Initializer, Mutation, Repair, mix};
use crate::rng::below;
use crate::{Budget, Objective, Outcome, Stats};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Decoding {
#[default]
Skip,
Strict,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decoded {
pub plan: Vec<OpId>,
pub cost: u64,
pub reaches_goal: bool,
pub inspected: usize,
pub unsatisfied_goals: usize,
}
#[derive(Debug, Clone, Copy)]
pub struct PlanObjective<'t> {
task: &'t Task,
decoding: Decoding,
penalty: f64,
}
impl<'t> PlanObjective<'t> {
#[must_use]
pub fn new(task: &'t Task, decoding: Decoding, max_len: usize) -> Self {
let max_cost = task
.operators
.iter()
.map(|o| u64::from(o.cost))
.max()
.unwrap_or(0);
#[expect(
clippy::cast_precision_loss,
reason = "plan cost bounds far below 2^52"
)]
let penalty = (max_cost.saturating_mul(max_len as u64) + 1) as f64;
Self {
task,
decoding,
penalty,
}
}
#[must_use]
pub fn penalty(&self) -> f64 {
self.penalty
}
#[must_use]
pub fn decode(&self, chain: &[OpId]) -> Decoded {
let task = self.task;
let mut state = task.initial_state();
let mut plan = Vec::new();
let mut cost = 0;
let mut inspected = 0;
let mut reaches_goal = task.is_goal(&state);
for &op in chain {
if reaches_goal {
break;
}
inspected += 1;
if op >= task.operators.len() || !task.is_applicable(op, &state) {
if self.decoding == Decoding::Strict {
break;
}
continue;
}
state = task.apply(op, &state);
cost += u64::from(task.operators[op].cost);
plan.push(op);
reaches_goal = task.is_goal(&state);
}
Decoded {
unsatisfied_goals: unsatisfied(task, &state),
plan,
cost,
reaches_goal,
inspected,
}
}
#[must_use]
pub fn score(&self, decoded: &Decoded, len: usize) -> f64 {
if decoded.reaches_goal {
#[expect(clippy::cast_precision_loss, reason = "plan costs far below 2^52")]
return decoded.cost as f64;
}
#[expect(clippy::cast_precision_loss, reason = "counts far below 2^52")]
let executed = if len == 0 {
0.0
} else {
decoded.plan.len() as f64 / len as f64
};
#[expect(clippy::cast_precision_loss, reason = "counts far below 2^52")]
let unsatisfied = decoded.unsatisfied_goals as f64;
self.penalty + unsatisfied + (1.0 - executed)
}
}
impl Objective<Vec<OpId>> for PlanObjective<'_> {
fn evaluate(&mut self, genome: &Vec<OpId>) -> f64 {
self.score(&self.decode(genome), genome.len())
}
}
fn unsatisfied(task: &Task, state: &State) -> usize {
task.goal
.iter()
.filter(|f| state.0[f.var] != f.value)
.count()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RandomOperator {
pub count: usize,
}
impl Initializer<OpId> for RandomOperator {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> OpId {
below(rng, self.count)
}
}
#[derive(Debug, Clone, Copy)]
pub struct ApplicableWalk<'t> {
pub task: &'t Task,
pub max_len: usize,
}
impl Initializer<Vec<OpId>> for ApplicableWalk<'_> {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<OpId> {
let task = self.task;
let len = 1 + below(rng, self.max_len.max(1));
let mut state = task.initial_state();
let mut walk = Vec::with_capacity(len);
while walk.len() < len && !task.is_goal(&state) {
let applicable: Vec<OpId> = task.applicable_operators(&state).collect();
if applicable.is_empty() {
break;
}
let op = applicable[below(rng, applicable.len())];
state = task.apply(op, &state);
walk.push(op);
}
walk
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RepairMode {
#[default]
Off,
Drop,
Replace,
}
#[derive(Debug, Clone, Copy)]
pub struct PlanRepair<'t> {
pub task: &'t Task,
pub mode: RepairMode,
}
impl Repair<Vec<OpId>> for PlanRepair<'_> {
fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<OpId>, rng: &mut R) {
if self.mode == RepairMode::Off {
return;
}
let task = self.task;
let mut state = task.initial_state();
let mut repaired = Vec::with_capacity(genome.len());
for &op in genome.iter() {
if task.is_goal(&state) {
break;
}
let op = if op < task.operators.len() && task.is_applicable(op, &state) {
op
} else if self.mode == RepairMode::Replace {
let applicable: Vec<OpId> = task.applicable_operators(&state).collect();
if applicable.is_empty() {
continue;
}
applicable[below(rng, applicable.len())]
} else {
continue;
};
state = task.apply(op, &state);
repaired.push(op);
}
*genome = repaired;
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub population_size: usize,
pub max_len: usize,
pub decoding: Decoding,
pub repair: RepairMode,
}
impl Default for Config {
fn default() -> Self {
Self {
population_size: 60,
max_len: 40,
decoding: Decoding::Skip,
repair: RepairMode::Off,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PlanOutcome {
pub plan: Option<Vec<OpId>>,
pub cost: Option<u64>,
pub outcome: Outcome<Vec<OpId>>,
}
pub fn solve<B, R>(task: &Task, config: &Config, budget: &mut B, rng: &mut R) -> PlanOutcome
where
B: Budget<Stats> + ?Sized,
R: Rng + ?Sized,
{
assert!(
!task.operators.is_empty(),
"a task without operators has no plans to evolve"
);
let mutation = chain_mutation(task.operators.len(), config.max_len);
let mut ga = Ga::new(
GaConfig {
population_size: config.population_size,
elitism: 2,
crossover_rate: 0.6,
mutation_rate: 1.0,
scheme: Scheme::SteadyState {
only_if_better: false,
},
},
Operators {
init: ApplicableWalk {
task,
max_len: config.max_len,
},
selection: Tournament { size: 3 },
crossover: CutAndSplice {
max_len: config.max_len,
},
mutation,
repair: PlanRepair {
task,
mode: config.repair,
},
},
);
let mut objective = PlanObjective::new(task, config.decoding, config.max_len);
let outcome = ga.run(&mut objective, budget, &mut (), rng);
let decoded = outcome.best_genome().map(|chain| objective.decode(chain));
let (plan, cost) = match decoded {
Some(d) if d.reaches_goal => (Some(d.plan), Some(d.cost)),
_ => (None, None),
};
PlanOutcome {
plan,
cost,
outcome,
}
}
fn chain_mutation(operators: usize, max_len: usize) -> impl Mutation<Vec<OpId>> {
let genes = RandomOperator { count: operators };
mix(
mix(
InsertGene { genes, max_len },
2.0,
DeleteGene { min_len: 0 },
1.0,
),
3.0,
mix(
ReplaceGene { genes },
2.0,
mix(
GeneShift,
1.0,
SegmentInversion {
max_segment: Some(4),
},
1.0,
),
2.0,
),
4.0,
)
}
#[cfg(test)]
mod tests {
use sas_plus::random::{RandomTaskParams, random_task};
use super::*;
use crate::{Limits, SplitMix64};
fn validate_over_random_tasks(config: &Config) -> (usize, usize, usize) {
let (mut solvable, mut found, mut optimal) = (0, 0, 0);
for seed in 0..40 {
let params = RandomTaskParams {
num_vars: 4,
max_domain: 3,
num_ops: 12,
max_cost: 4,
max_conditions: 1,
num_derived: usize::from(seed % 2 == 1),
};
let task = random_task(seed, params);
let Some(best) = task.perfect_heuristic()(&task.initial_state()) else {
continue;
};
solvable += 1;
let result = solve(
&task,
config,
&mut Limits::evaluations(6_000),
&mut SplitMix64::new(seed),
);
if let (Some(plan), Some(cost)) = (&result.plan, result.cost) {
assert_eq!(
task.validate_plan(plan),
Some(cost),
"{config:?}, seed {seed}"
);
assert!(
cost >= best,
"{config:?}, seed {seed}: {cost} < optimum {best}"
);
found += 1;
optimal += usize::from(cost == best);
}
}
(solvable, found, optimal)
}
#[test]
fn plans_validate_against_sas_plus() {
for decoding in [Decoding::Skip, Decoding::Strict] {
for repair in [RepairMode::Off, RepairMode::Drop, RepairMode::Replace] {
let config = Config {
decoding,
repair,
..Config::default()
};
let (solvable, found, optimal) = validate_over_random_tasks(&config);
assert!(solvable >= 10, "only {solvable} solvable tasks");
if config == Config::default() {
assert!(found * 10 >= solvable * 9, "found {found} of {solvable}");
assert!(optimal * 2 >= solvable, "optimal {optimal} of {solvable}");
}
}
}
}
#[test]
fn fitness_cascade() {
let task = random_task(3, RandomTaskParams::default());
let objective = PlanObjective::new(&task, Decoding::Strict, 10);
let decoded = objective.decode(&[usize::MAX, 0, 1]);
assert_eq!(decoded.inspected, 1);
assert_eq!(decoded.plan, Vec::<OpId>::new());
let score = objective.score(&decoded, 3);
assert!(score >= objective.penalty());
}
#[test]
fn repair_makes_chains_executable() {
let task = random_task(5, RandomTaskParams::default());
let mut rng = SplitMix64::new(2);
let mut repair = PlanRepair {
task: &task,
mode: RepairMode::Replace,
};
let objective = PlanObjective::new(&task, Decoding::Strict, 20);
for _ in 0..50 {
let mut chain: Vec<OpId> = (0..10)
.map(|_| below(&mut rng, task.operators.len()))
.collect();
repair.repair(&mut chain, &mut rng);
let decoded = objective.decode(&chain);
assert_eq!(decoded.plan, chain[..decoded.plan.len()]);
assert_eq!(decoded.plan.len(), chain.len());
}
}
}