1use alloc::vec::Vec;
10
11use rand_core::Rng;
12
13use super::{Crossover, Initializer, Mutation, Repair};
14use crate::rng::{below, chance, shuffle, standard_normal, uniform, unit_f64};
15
16#[derive(Debug, Clone, PartialEq)]
27pub struct Bounds {
28 lower: Vec<f64>,
30 upper: Vec<f64>,
32}
33
34impl Bounds {
35 #[must_use]
41 pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Self {
42 assert_eq!(lower.len(), upper.len(), "bounds of different dimension");
43 for (lo, hi) in lower.iter().zip(&upper) {
44 assert!(
45 lo.is_finite() && hi.is_finite() && lo <= hi,
46 "invalid bound [{lo}, {hi}]"
47 );
48 }
49
50 Self { lower, upper }
51 }
52
53 #[must_use]
59 pub fn uniform(dimension: usize, low: f64, high: f64) -> Self {
60 Self::new(alloc::vec![low; dimension], alloc::vec![high; dimension])
61 }
62
63 #[must_use]
65 pub fn dimension(&self) -> usize {
66 self.lower.len()
67 }
68
69 #[must_use]
71 pub fn lower(&self) -> &[f64] {
72 &self.lower
73 }
74
75 #[must_use]
77 pub fn upper(&self) -> &[f64] {
78 &self.upper
79 }
80
81 #[must_use]
83 pub fn width(&self, i: usize) -> f64 {
84 self.upper[i] - self.lower[i]
85 }
86
87 #[must_use]
89 pub fn contains(&self, x: &[f64]) -> bool {
90 x.len() == self.dimension()
91 && x.iter()
92 .enumerate()
93 .all(|(i, v)| (self.lower[i]..=self.upper[i]).contains(v))
94 }
95
96 pub fn clamp(&self, x: &mut [f64]) {
98 for (i, v) in x.iter_mut().enumerate() {
99 *v = v.clamp(self.lower[i], self.upper[i]);
100 }
101 }
102
103 #[must_use]
105 pub fn center(&self) -> Vec<f64> {
106 self.lower
107 .iter()
108 .zip(&self.upper)
109 .map(|(lo, hi)| 0.5 * (lo + hi))
110 .collect()
111 }
112}
113
114impl Initializer<Vec<f64>> for Bounds {
116 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<f64> {
117 (0..self.dimension())
118 .map(|i| uniform(rng, self.lower[i], self.upper[i]))
119 .collect()
120 }
121}
122
123pub fn latin_hypercube<R: Rng + ?Sized>(
139 bounds: &Bounds,
140 count: usize,
141 rng: &mut R,
142) -> Vec<Vec<f64>> {
143 let mut points = alloc::vec![alloc::vec![0.0; bounds.dimension()]; count];
144 let mut strata: Vec<usize> = (0..count).collect();
145 #[expect(
146 clippy::cast_precision_loss,
147 reason = "sample counts are far below 2^52"
148 )]
149 let n = count as f64;
150 for i in 0..bounds.dimension() {
151 shuffle(rng, &mut strata);
152 for (point, &stratum) in points.iter_mut().zip(&strata) {
153 #[expect(
154 clippy::cast_precision_loss,
155 reason = "sample counts are far below 2^52"
156 )]
157 let offset = (stratum as f64 + unit_f64(rng)) / n;
158 point[i] = (bounds.lower[i] + offset * bounds.width(i)).min(bounds.upper[i]);
159 }
160 }
161
162 points
163}
164
165fn gene_rate(rate: Option<f64>, n: usize) -> f64 {
167 #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
168 let default = 1.0 / n.max(1) as f64;
169
170 rate.unwrap_or(default)
171}
172
173#[derive(Debug, Clone, Copy, PartialEq)]
176pub struct Gaussian {
177 pub sigma: f64,
179 pub rate: Option<f64>,
181}
182
183impl Mutation<Vec<f64>> for Gaussian {
184 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, rng: &mut R) {
185 let rate = gene_rate(self.rate, genome.len());
186 for_some_genes(genome.len(), rate, rng, |i, rng| {
187 genome[i] += self.sigma * standard_normal(rng);
188 });
189 }
190}
191
192fn for_some_genes<R: Rng + ?Sized>(
195 n: usize,
196 rate: f64,
197 rng: &mut R,
198 mut f: impl FnMut(usize, &mut R),
199) {
200 if n == 0 {
201 return;
202 }
203
204 let mut any = false;
205 for i in 0..n {
206 if chance(rng, rate) {
207 f(i, rng);
208 any = true;
209 }
210 }
211
212 if !any {
213 let i = below(rng, n);
214 f(i, rng);
215 }
216}
217
218#[derive(Debug, Clone, PartialEq)]
222pub struct Polynomial {
223 pub bounds: Bounds,
225 pub eta: f64,
227 pub rate: Option<f64>,
229}
230
231impl Mutation<Vec<f64>> for Polynomial {
232 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, rng: &mut R) {
233 let rate = gene_rate(self.rate, genome.len());
234 let bounds = &self.bounds;
235 let eta = self.eta;
236 for_some_genes(genome.len(), rate, rng, |i, rng| {
237 genome[i] = polynomial_step(
238 genome[i],
239 bounds.lower[i],
240 bounds.upper[i],
241 eta,
242 unit_f64(rng),
243 );
244 });
245 }
246}
247
248fn polynomial_step(y: f64, low: f64, high: f64, eta: f64, u: f64) -> f64 {
250 let width = high - low;
251 if width <= 0.0 {
252 return low;
253 }
254
255 let power = 1.0 / (eta + 1.0);
256 let delta_q = if u <= 0.5 {
257 let xy = 1.0 - (y - low) / width;
258 let value = 2.0 * u + (1.0 - 2.0 * u) * libm::pow(xy, eta + 1.0);
259 libm::pow(value, power) - 1.0
260 } else {
261 let xy = 1.0 - (high - y) / width;
262 let value = 2.0 * (1.0 - u) + 2.0 * (u - 0.5) * libm::pow(xy, eta + 1.0);
263 1.0 - libm::pow(value, power)
264 };
265
266 (y + delta_q * width).clamp(low, high)
267}
268
269#[derive(Debug, Clone, PartialEq)]
272pub struct UniformReset {
273 pub bounds: Bounds,
275 pub rate: Option<f64>,
277}
278
279impl Mutation<Vec<f64>> for UniformReset {
280 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, rng: &mut R) {
281 let rate = gene_rate(self.rate, genome.len());
282 let bounds = &self.bounds;
283 for_some_genes(genome.len(), rate, rng, |i, rng| {
284 genome[i] = uniform(rng, bounds.lower[i], bounds.upper[i]);
285 });
286 }
287}
288
289#[derive(Debug, Clone, PartialEq)]
294pub struct Sbx {
295 pub bounds: Bounds,
297 pub eta: f64,
300}
301
302impl Crossover<Vec<f64>> for Sbx {
303 fn crossover<R: Rng + ?Sized>(
304 &mut self,
305 a: &Vec<f64>,
306 b: &Vec<f64>,
307 rng: &mut R,
308 ) -> [Vec<f64>; 2] {
309 let mut c1 = a.clone();
310 let mut c2 = b.clone();
311 for i in 0..a.len().min(b.len()) {
312 if unit_f64(rng) > 0.5 || (a[i] - b[i]).abs() <= 1e-14 {
313 continue;
314 }
315
316 let (low, high) = (self.bounds.lower[i], self.bounds.upper[i]);
317 let (y1, y2) = if a[i] < b[i] {
318 (a[i], b[i])
319 } else {
320 (b[i], a[i])
321 };
322 let u = unit_f64(rng);
323 let lower_child = sbx_child(
324 y1,
325 y2,
326 1.0 + 2.0 * (y1 - low) / (y2 - y1),
327 self.eta,
328 u,
329 -1.0,
330 );
331 let upper_child = sbx_child(
332 y1,
333 y2,
334 1.0 + 2.0 * (high - y2) / (y2 - y1),
335 self.eta,
336 u,
337 1.0,
338 );
339 let (x1, x2) = (lower_child.clamp(low, high), upper_child.clamp(low, high));
340 if unit_f64(rng) < 0.5 {
341 c1[i] = x2;
342 c2[i] = x1;
343 } else {
344 c1[i] = x1;
345 c2[i] = x2;
346 }
347 }
348
349 [c1, c2]
350 }
351}
352
353fn sbx_child(y1: f64, y2: f64, beta: f64, eta: f64, u: f64, sign: f64) -> f64 {
356 let alpha = 2.0 - libm::pow(beta, -(eta + 1.0));
357 let beta_q = if u <= 1.0 / alpha {
358 libm::pow(u * alpha, 1.0 / (eta + 1.0))
359 } else {
360 libm::pow(1.0 / (2.0 - u * alpha), 1.0 / (eta + 1.0))
361 };
362
363 0.5 * ((y1 + y2) + sign * beta_q * (y2 - y1))
364}
365
366#[derive(Debug, Clone, PartialEq)]
370pub struct Blx {
371 pub bounds: Bounds,
373 pub alpha: f64,
375}
376
377impl Crossover<Vec<f64>> for Blx {
378 fn crossover<R: Rng + ?Sized>(
379 &mut self,
380 a: &Vec<f64>,
381 b: &Vec<f64>,
382 rng: &mut R,
383 ) -> [Vec<f64>; 2] {
384 let mut children = [a.clone(), b.clone()];
385 for child in &mut children {
386 for i in 0..a.len().min(b.len()) {
387 let (lo, hi) = (a[i].min(b[i]), a[i].max(b[i]));
388 let spread = self.alpha * (hi - lo);
389 let value = uniform(rng, lo - spread, hi + spread);
390 child[i] = value.clamp(self.bounds.lower[i], self.bounds.upper[i]);
391 }
392 }
393
394 children
395 }
396}
397
398#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
401pub struct Arithmetic;
402
403impl Crossover<Vec<f64>> for Arithmetic {
404 fn crossover<R: Rng + ?Sized>(
405 &mut self,
406 a: &Vec<f64>,
407 b: &Vec<f64>,
408 rng: &mut R,
409 ) -> [Vec<f64>; 2] {
410 let lambda = unit_f64(rng);
411 let blend = |x: f64, y: f64, l: f64| l * x + (1.0 - l) * y;
412
413 [
414 a.iter()
415 .zip(b)
416 .map(|(&x, &y)| blend(x, y, lambda))
417 .collect(),
418 a.iter()
419 .zip(b)
420 .map(|(&x, &y)| blend(x, y, 1.0 - lambda))
421 .collect(),
422 ]
423 }
424}
425
426#[derive(Debug, Clone, Copy, PartialEq)]
430pub struct IsoLineDd {
431 pub sigma_iso: f64,
433 pub sigma_line: f64,
435}
436
437impl Crossover<Vec<f64>> for IsoLineDd {
438 fn crossover<R: Rng + ?Sized>(
439 &mut self,
440 a: &Vec<f64>,
441 b: &Vec<f64>,
442 rng: &mut R,
443 ) -> [Vec<f64>; 2] {
444 let child = |x: &[f64], y: &[f64], rng: &mut R| {
445 let line = self.sigma_line * standard_normal(rng);
446 x.iter()
447 .zip(y)
448 .map(|(p, q)| p + self.sigma_iso * standard_normal(rng) + line * (q - p))
449 .collect()
450 };
451
452 [child(a, b, rng), child(b, a, rng)]
453 }
454}
455
456#[derive(Debug, Clone, PartialEq)]
458pub struct Clamp(pub Bounds);
459
460impl Repair<Vec<f64>> for Clamp {
461 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, _rng: &mut R) {
462 self.0.clamp(genome);
463 }
464}
465
466#[derive(Debug, Clone, PartialEq)]
469pub struct Reflect(pub Bounds);
470
471impl Repair<Vec<f64>> for Reflect {
472 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, _rng: &mut R) {
473 for (i, value) in genome.iter_mut().enumerate() {
474 *value = reflect(*value, self.0.lower[i], self.0.upper[i]);
475 }
476 }
477}
478
479fn reflect(x: f64, low: f64, high: f64) -> f64 {
481 let width = high - low;
482 if width <= 0.0 || !x.is_finite() {
483 return x.clamp(low, high);
484 }
485
486 let period = 2.0 * width;
487 let mut offset = (x - low) % period;
488 if offset < 0.0 {
489 offset += period;
490 }
491
492 if offset <= width {
493 low + offset
494 } else {
495 high - (offset - width)
496 }
497}
498
499#[cfg(test)]
500mod tests {
501 use alloc::vec;
502
503 use super::*;
504 use crate::SplitMix64;
505
506 #[test]
508 fn bounded_operators_stay_inside() {
509 let bounds = Bounds::uniform(5, -1.0, 2.0);
510 let mut rng = SplitMix64::new(7);
511 let mut init = bounds.clone();
512 let mut sbx = Sbx {
513 bounds: bounds.clone(),
514 eta: 15.0,
515 };
516 let mut blx = Blx {
517 bounds: bounds.clone(),
518 alpha: 0.5,
519 };
520 let mut poly = Polynomial {
521 bounds: bounds.clone(),
522 eta: 20.0,
523 rate: Some(1.0),
524 };
525 for _ in 0..500 {
526 let a = init.initialize(&mut rng);
527 let b = init.initialize(&mut rng);
528 for mut child in sbx
529 .crossover(&a, &b, &mut rng)
530 .into_iter()
531 .chain(blx.crossover(&a, &b, &mut rng))
532 {
533 assert!(bounds.contains(&child), "{child:?}");
534 poly.mutate(&mut child, &mut rng);
535 assert!(bounds.contains(&child), "{child:?}");
536 }
537 }
538 }
539
540 #[test]
542 fn reflection_folds() {
543 assert!((reflect(2.5, 0.0, 2.0) - 1.5).abs() < 1e-12);
544 assert!((reflect(-0.5, 0.0, 2.0) - 0.5).abs() < 1e-12);
545 assert!((reflect(5.0, 0.0, 2.0) - 1.0).abs() < 1e-12);
546 assert!((reflect(1.25, 0.0, 2.0) - 1.25).abs() < 1e-12);
547 }
548
549 #[test]
551 fn sbx_of_equal_parents_is_identity() {
552 let mut sbx = Sbx {
553 bounds: Bounds::uniform(3, 0.0, 1.0),
554 eta: 15.0,
555 };
556 let p = vec![0.2, 0.5, 0.9];
557
558 assert_eq!(
559 sbx.crossover(&p, &p, &mut SplitMix64::new(1)),
560 [p.clone(), p]
561 );
562 }
563
564 #[test]
566 fn latin_hypercube_stratifies() {
567 let bounds = Bounds::uniform(3, -2.0, 2.0);
568 let points = latin_hypercube(&bounds, 10, &mut SplitMix64::new(3));
569 for i in 0..3 {
570 let mut strata: Vec<usize> = points
571 .iter()
572 .map(|p| {
573 #[expect(
574 clippy::cast_possible_truncation,
575 clippy::cast_sign_loss,
576 reason = "test"
577 )]
578 let s = ((p[i] + 2.0) / 4.0 * 10.0) as usize;
579 s
580 })
581 .collect();
582 strata.sort_unstable();
583 assert_eq!(strata, (0..10).collect::<Vec<_>>());
584 }
585 }
586}