1use alloc::vec::Vec;
35
36use rand_core::Rng;
37
38use super::{Crossover, Initializer, Mutation};
39use crate::operators::sequence::splice;
40use crate::rng::{below, uniform, unit_f64};
41
42#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct ParamSpec {
45 pub low: f64,
47 pub high: f64,
49 pub integer: bool,
51}
52
53impl ParamSpec {
54 #[must_use]
56 pub const fn real(low: f64, high: f64) -> Self {
57 Self {
58 low,
59 high,
60 integer: false,
61 }
62 }
63
64 #[must_use]
66 pub const fn integer(low: f64, high: f64) -> Self {
67 Self {
68 low,
69 high,
70 integer: true,
71 }
72 }
73
74 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
76 if self.integer {
77 let low = libm::ceil(self.low);
78 let high = libm::floor(self.high);
79 #[expect(
80 clippy::cast_possible_truncation,
81 clippy::cast_sign_loss,
82 reason = "the count of whole numbers in a finite parameter range"
83 )]
84 let count = (high - low) as usize + 1;
85 #[expect(
86 clippy::cast_precision_loss,
87 reason = "parameter ranges are far below 2^52"
88 )]
89 let offset = below(rng, count.max(1)) as f64;
90 low + offset
91 } else {
92 uniform(rng, self.low, self.high).min(self.high)
93 }
94 }
95
96 fn fit(&self, value: f64) -> f64 {
98 if self.integer {
99 libm::round(value).clamp(libm::ceil(self.low), libm::floor(self.high))
100 } else {
101 value.clamp(self.low, self.high)
102 }
103 }
104
105 fn admits(&self, value: f64) -> bool {
107 (self.low..=self.high).contains(&value)
108 && (!self.integer || libm::round(value).total_cmp(&value).is_eq())
109 }
110}
111
112#[derive(Debug, Clone, PartialEq)]
114pub struct ActionKind {
115 pub params: Vec<ParamSpec>,
117}
118
119impl ActionKind {
120 #[must_use]
122 pub fn new(params: Vec<ParamSpec>) -> Self {
123 Self { params }
124 }
125}
126
127#[derive(Debug, Clone, PartialEq)]
129pub struct Action {
130 pub kind: usize,
132 pub params: Vec<f64>,
134}
135
136#[derive(Debug, Clone, PartialEq)]
139pub struct ActionModel {
140 kinds: Vec<ActionKind>,
142}
143
144impl ActionModel {
145 #[must_use]
151 pub fn new(kinds: Vec<ActionKind>) -> Self {
152 assert!(
153 !kinds.is_empty(),
154 "an action model needs at least one action type"
155 );
156 for spec in kinds.iter().flat_map(|k| &k.params) {
157 assert!(
158 spec.low.is_finite() && spec.high.is_finite() && spec.low <= spec.high,
159 "invalid parameter range [{}, {}]",
160 spec.low,
161 spec.high
162 );
163 }
164
165 Self { kinds }
166 }
167
168 #[must_use]
170 pub fn kinds(&self) -> &[ActionKind] {
171 &self.kinds
172 }
173
174 #[must_use]
176 pub fn is_valid(&self, action: &Action) -> bool {
177 self.kinds.get(action.kind).is_some_and(|kind| {
178 kind.params.len() == action.params.len()
179 && kind
180 .params
181 .iter()
182 .zip(&action.params)
183 .all(|(spec, &v)| spec.admits(v))
184 })
185 }
186
187 fn sample_params<R: Rng + ?Sized>(&self, kind: usize, rng: &mut R) -> Vec<f64> {
189 self.kinds[kind]
190 .params
191 .iter()
192 .map(|spec| spec.sample(rng))
193 .collect()
194 }
195}
196
197impl Initializer<Action> for ActionModel {
198 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Action {
199 let kind = below(rng, self.kinds.len());
200 let params = self.sample_params(kind, rng);
201
202 Action { kind, params }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq)]
208pub struct RandomChain<S> {
209 pub genes: S,
211 pub min_len: usize,
213 pub max_len: usize,
215}
216
217impl<T, S: Initializer<T>> Initializer<Vec<T>> for RandomChain<S> {
218 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<T> {
219 let span = self.max_len.saturating_sub(self.min_len);
220 let len = self.min_len + below(rng, span + 1);
221
222 (0..len).map(|_| self.genes.initialize(rng)).collect()
223 }
224}
225
226fn segment<R: Rng + ?Sized>(rng: &mut R, n: usize, max_len: Option<usize>) -> (usize, usize) {
229 let start = below(rng, n);
230 let longest = (n - start).min(max_len.unwrap_or(usize::MAX)).max(1);
231 let len = 1 + below(rng, longest);
232
233 (start, start + len)
234}
235
236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
238pub struct GeneShift;
239
240impl<T> Mutation<Vec<T>> for GeneShift {
241 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
242 super::permutation::Insertion.mutate(genome, rng);
243 }
244}
245
246#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
248pub struct SegmentShift {
249 pub max_segment: Option<usize>,
251}
252
253impl<T> Mutation<Vec<T>> for SegmentShift {
254 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
255 if genome.len() < 2 {
256 return;
257 }
258
259 let (start, end) = segment(rng, genome.len(), self.max_segment);
260 let moved: Vec<T> = genome.drain(start..end).collect();
261 let at = below(rng, genome.len() + 1);
262 let tail = genome.split_off(at);
263 genome.extend(moved);
264 genome.extend(tail);
265 }
266}
267
268#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
270pub struct SegmentInversion {
271 pub max_segment: Option<usize>,
273}
274
275impl<T> Mutation<Vec<T>> for SegmentInversion {
276 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
277 if genome.len() >= 2 {
278 let (start, end) = segment(rng, genome.len(), self.max_segment);
279 genome[start..end].reverse();
280 }
281 }
282}
283
284#[derive(Debug, Clone, PartialEq)]
286pub struct InsertGene<S> {
287 pub genes: S,
289 pub max_len: usize,
291}
292
293impl<T, S: Initializer<T>> Mutation<Vec<T>> for InsertGene<S> {
294 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
295 if genome.len() < self.max_len {
296 let at = below(rng, genome.len() + 1);
297 genome.insert(at, self.genes.initialize(rng));
298 }
299 }
300}
301
302#[derive(Debug, Clone, PartialEq)]
304pub struct InsertSegment<S> {
305 pub genes: S,
307 pub max_segment: usize,
309 pub max_len: usize,
311}
312
313impl<T, S: Initializer<T>> Mutation<Vec<T>> for InsertSegment<S> {
314 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
315 let room = self
316 .max_len
317 .saturating_sub(genome.len())
318 .min(self.max_segment.max(1));
319 if room == 0 {
320 return;
321 }
322
323 let len = 1 + below(rng, room);
324 let at = below(rng, genome.len() + 1);
325 let tail = genome.split_off(at);
326 for _ in 0..len {
327 genome.push(self.genes.initialize(rng));
328 }
329
330 genome.extend(tail);
331 }
332}
333
334#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
336pub struct DeleteGene {
337 pub min_len: usize,
339}
340
341impl<T> Mutation<Vec<T>> for DeleteGene {
342 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
343 if genome.len() > self.min_len && !genome.is_empty() {
344 let at = below(rng, genome.len());
345 genome.remove(at);
346 }
347 }
348}
349
350#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
352pub struct DeleteSegment {
353 pub min_len: usize,
355 pub max_segment: Option<usize>,
357}
358
359impl<T> Mutation<Vec<T>> for DeleteSegment {
360 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
361 let removable = genome.len().saturating_sub(self.min_len);
362 if removable == 0 {
363 return;
364 }
365
366 let cap = Some(self.max_segment.unwrap_or(usize::MAX).min(removable));
367 let (start, end) = segment(rng, genome.len(), cap);
368 genome.drain(start..end);
369 }
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub struct DuplicateGene {
375 pub max_len: usize,
377}
378
379impl<T: Clone> Mutation<Vec<T>> for DuplicateGene {
380 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
381 if !genome.is_empty() && genome.len() < self.max_len {
382 let at = below(rng, genome.len());
383 genome.insert(at + 1, genome[at].clone());
384 }
385 }
386}
387
388#[derive(Debug, Clone, PartialEq)]
390pub struct ReplaceGene<S> {
391 pub genes: S,
393}
394
395impl<T, S: Initializer<T>> Mutation<Vec<T>> for ReplaceGene<S> {
396 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
397 if !genome.is_empty() {
398 let at = below(rng, genome.len());
399 genome[at] = self.genes.initialize(rng);
400 }
401 }
402}
403
404fn random_parameter<R: Rng + ?Sized>(genome: &[Action], rng: &mut R) -> Option<(usize, usize)> {
406 let with_params: Vec<usize> = (0..genome.len())
407 .filter(|&g| !genome[g].params.is_empty())
408 .collect();
409 if with_params.is_empty() {
410 return None;
411 }
412
413 let gene = with_params[below(rng, with_params.len())];
414
415 Some((gene, below(rng, genome[gene].params.len())))
416}
417
418#[derive(Debug, Clone, PartialEq)]
421pub struct ParamNewValue {
422 pub model: ActionModel,
424}
425
426impl Mutation<Vec<Action>> for ParamNewValue {
427 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Action>, rng: &mut R) {
428 if let Some((gene, param)) = random_parameter(genome, rng) {
429 let spec = self.model.kinds[genome[gene].kind].params[param];
430 genome[gene].params[param] = spec.sample(rng);
431 }
432 }
433}
434
435#[derive(Debug, Clone, PartialEq)]
442pub struct ParamShift {
443 pub model: ActionModel,
445}
446
447impl Mutation<Vec<Action>> for ParamShift {
448 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Action>, rng: &mut R) {
449 let Some((gene, param)) = random_parameter(genome, rng) else {
450 return;
451 };
452
453 let spec = self.model.kinds[genome[gene].kind].params[param];
454 let mut step = (spec.high - spec.low) * libm::pow(10.0, -3.0 * unit_f64(rng));
455 if spec.integer {
456 step = step.max(1.0);
457 }
458
459 let sign = if rng.next_u32() & 1 == 0 { -1.0 } else { 1.0 };
460 let value = &mut genome[gene].params[param];
461 *value = spec.fit(*value + sign * step);
462 }
463}
464
465#[derive(Debug, Clone, PartialEq)]
467pub struct ActionNewParams {
468 pub model: ActionModel,
470}
471
472impl Mutation<Vec<Action>> for ActionNewParams {
473 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Action>, rng: &mut R) {
474 if !genome.is_empty() {
475 let gene = below(rng, genome.len());
476 genome[gene].params = self.model.sample_params(genome[gene].kind, rng);
477 }
478 }
479}
480
481#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub struct CutAndSplice {
485 pub max_len: usize,
487}
488
489impl<T: Clone> Crossover<Vec<T>> for CutAndSplice {
490 fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
491 let cut_a = below(rng, a.len() + 1);
492 let cut_b = below(rng, b.len() + 1);
493 let mut c1 = splice(a, b, cut_a, cut_b);
494 let mut c2 = splice(b, a, cut_b, cut_a);
495 c1.truncate(self.max_len);
496 c2.truncate(self.max_len);
497
498 [c1, c2]
499 }
500}
501
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506pub struct NPoint {
507 pub points: usize,
509}
510
511impl<T: Clone> Crossover<Vec<T>> for NPoint {
512 fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
513 let mut fractions: Vec<f64> = (0..self.points.max(1)).map(|_| unit_f64(rng)).collect();
514 fractions.sort_by(f64::total_cmp);
515 let cuts_a = scaled_cuts(&fractions, a.len());
516 let cuts_b = scaled_cuts(&fractions, b.len());
517
518 [
519 alternate(a, b, &cuts_a, &cuts_b),
520 alternate(b, a, &cuts_b, &cuts_a),
521 ]
522 }
523}
524
525fn scaled_cuts(fractions: &[f64], len: usize) -> Vec<usize> {
527 let mut cuts = Vec::with_capacity(fractions.len() + 2);
528 cuts.push(0);
529 #[expect(
530 clippy::cast_possible_truncation,
531 clippy::cast_sign_loss,
532 clippy::cast_precision_loss,
533 reason = "a fraction in [0, 1) of a chain length"
534 )]
535 cuts.extend(
536 fractions
537 .iter()
538 .map(|f| libm::round(f * len as f64) as usize),
539 );
540 cuts.push(len);
541
542 cuts
543}
544
545fn alternate<T: Clone>(
547 first: &[T],
548 second: &[T],
549 cuts_first: &[usize],
550 cuts_second: &[usize],
551) -> Vec<T> {
552 let mut child = Vec::with_capacity(first.len().max(second.len()));
553 for k in 0..cuts_first.len() - 1 {
554 if k % 2 == 0 {
555 child.extend_from_slice(&first[cuts_first[k]..cuts_first[k + 1]]);
556 } else {
557 child.extend_from_slice(&second[cuts_second[k]..cuts_second[k + 1]]);
558 }
559 }
560
561 child
562}
563
564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567pub struct SegmentExchange {
568 pub max_len: usize,
570}
571
572impl<T: Clone> Crossover<Vec<T>> for SegmentExchange {
573 fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
574 if a.is_empty() || b.is_empty() {
575 return [a.clone(), b.clone()];
576 }
577
578 let (ia, ja) = segment(rng, a.len(), None);
579 let (ib, jb) = segment(rng, b.len(), None);
580 let build = |x: &[T], (i, j): (usize, usize), y: &[T], (k, l): (usize, usize)| {
581 let mut child = Vec::with_capacity(x.len() - (j - i) + (l - k));
582 child.extend_from_slice(&x[..i]);
583 child.extend_from_slice(&y[k..l]);
584 child.extend_from_slice(&x[j..]);
585 child.truncate(self.max_len);
586 child
587 };
588
589 [
590 build(a, (ia, ja), b, (ib, jb)),
591 build(b, (ib, jb), a, (ia, ja)),
592 ]
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use alloc::vec;
599
600 use proptest::prelude::*;
601
602 use super::*;
603 use crate::SplitMix64;
604
605 fn model() -> ActionModel {
607 ActionModel::new(vec![
608 ActionKind::new(vec![
609 ParamSpec::real(-1.0, 1.0),
610 ParamSpec::integer(0.0, 5.0),
611 ]),
612 ActionKind::new(vec![ParamSpec::integer(-3.0, 3.0)]),
613 ActionKind::new(vec![]),
614 ])
615 }
616
617 proptest! {
618 #[test]
620 fn chain_operators_keep_validity(seed in any::<u64>()) {
621 let mut rng = SplitMix64::new(seed);
622 let m = model();
623 let mut init = RandomChain { genes: m.clone(), min_len: 1, max_len: 8 };
624 let mut chain = init.initialize(&mut rng);
625 let mut ops = mix(
626 mix(ParamShift { model: m.clone() }, 1.0, ParamNewValue { model: m.clone() }, 1.0),
627 1.0,
628 mix(
629 mix(InsertSegment { genes: m.clone(), max_segment: 3, max_len: 12 }, 1.0, DeleteSegment { min_len: 1, max_segment: Some(3) }, 1.0),
630 1.0,
631 mix(SegmentShift::default(), 1.0, mix(DuplicateGene { max_len: 12 }, 1.0, ActionNewParams { model: m.clone() }, 1.0), 1.0),
632 1.0,
633 ),
634 1.0,
635 );
636 for _ in 0..50 {
637 ops.mutate(&mut chain, &mut rng);
638 prop_assert!((1..=12).contains(&chain.len()));
639 prop_assert!(chain.iter().all(|a| m.is_valid(a)));
640 }
641 }
642
643 #[test]
645 fn crossovers_reuse_parent_genes(seed in any::<u64>(), la in 0u32..10, lb in 0u32..10) {
646 let mut rng = SplitMix64::new(seed);
647 let a: Vec<u32> = (0..la).collect();
648 let b: Vec<u32> = (100..100 + lb).collect();
649 for [c1, c2] in [
650 CutAndSplice { max_len: 100 }.crossover(&a, &b, &mut rng),
651 NPoint { points: 3 }.crossover(&a, &b, &mut rng),
652 SegmentExchange { max_len: 100 }.crossover(&a, &b, &mut rng),
653 ] {
654 let mut all: Vec<u32> = c1.iter().chain(&c2).copied().collect();
655 all.sort_unstable();
656 let mut parents: Vec<u32> = a.iter().chain(&b).copied().collect();
657 parents.sort_unstable();
658 prop_assert_eq!(all, parents);
659 }
660 }
661 }
662
663 use crate::operators::mix;
664
665 #[test]
667 fn segment_shift_permutes() {
668 let mut rng = SplitMix64::new(4);
669 let mut chain: Vec<u32> = (0..20).collect();
670 for _ in 0..100 {
671 SegmentShift {
672 max_segment: Some(5),
673 }
674 .mutate(&mut chain, &mut rng);
675 SegmentInversion::default().mutate(&mut chain, &mut rng);
676 }
677
678 let mut sorted = chain.clone();
679 sorted.sort_unstable();
680 assert_eq!(sorted, (0..20).collect::<Vec<_>>());
681 }
682}