1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
58pub enum Decoding {
59 #[default]
62 Skip,
63 Strict,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Decoded {
70 pub plan: Vec<OpId>,
72 pub cost: u64,
74 pub reaches_goal: bool,
76 pub inspected: usize,
79 pub unsatisfied_goals: usize,
81}
82
83#[derive(Debug, Clone, Copy)]
85pub struct PlanObjective<'t> {
86 task: &'t Task,
88 decoding: Decoding,
90 penalty: f64,
92}
93
94impl<'t> PlanObjective<'t> {
95 #[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 #[must_use]
119 pub fn penalty(&self) -> f64 {
120 self.penalty
121 }
122
123 #[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 #[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
188fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct RandomOperator {
199 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#[derive(Debug, Clone, Copy)]
213pub struct ApplicableWalk<'t> {
214 pub task: &'t Task,
216 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
243pub enum RepairMode {
244 #[default]
248 Off,
249 Drop,
252 Replace,
255}
256
257#[derive(Debug, Clone, Copy)]
259pub struct PlanRepair<'t> {
260 pub task: &'t Task,
262 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#[derive(Debug, Clone, Copy, PartialEq)]
302pub struct Config {
303 pub population_size: usize,
305 pub max_len: usize,
307 pub decoding: Decoding,
309 pub repair: RepairMode,
311}
312
313impl Default for Config {
314 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#[derive(Debug, Clone, PartialEq)]
327pub struct PlanOutcome {
328 pub plan: Option<Vec<OpId>>,
331 pub cost: Option<u64>,
333 pub outcome: Outcome<Vec<OpId>>,
335}
336
337pub 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
396fn 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 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 #[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 #[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 #[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}