evolutionary_planning/operators/
selection.rs1use alloc::vec::Vec;
5
6use rand_core::Rng;
7
8use crate::cost::{compare, ranking};
9use crate::rng::{below, unit_f64};
10
11pub trait Selection {
13 fn select<R: Rng + ?Sized>(
17 &mut self,
18 costs: &[f64],
19 count: usize,
20 rng: &mut R,
21 out: &mut Vec<usize>,
22 );
23}
24
25impl<S: Selection + ?Sized> Selection for &mut S {
26 fn select<R: Rng + ?Sized>(
27 &mut self,
28 costs: &[f64],
29 count: usize,
30 rng: &mut R,
31 out: &mut Vec<usize>,
32 ) {
33 (**self).select(costs, count, rng, out);
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct Tournament {
50 pub size: usize,
52}
53
54impl Default for Tournament {
55 fn default() -> Self {
56 Self { size: 2 }
57 }
58}
59
60impl Selection for Tournament {
61 fn select<R: Rng + ?Sized>(
62 &mut self,
63 costs: &[f64],
64 count: usize,
65 rng: &mut R,
66 out: &mut Vec<usize>,
67 ) {
68 for _ in 0..count {
69 let mut winner = below(rng, costs.len());
70 for _ in 1..self.size.max(1) {
71 let contestant = below(rng, costs.len());
72 if compare(costs[contestant], costs[winner]).is_lt() {
73 winner = contestant;
74 }
75 }
76
77 out.push(winner);
78 }
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq)]
84pub struct Truncation {
85 pub fraction: f64,
87}
88
89impl Default for Truncation {
90 fn default() -> Self {
91 Self { fraction: 0.5 }
92 }
93}
94
95impl Selection for Truncation {
96 fn select<R: Rng + ?Sized>(
97 &mut self,
98 costs: &[f64],
99 count: usize,
100 rng: &mut R,
101 out: &mut Vec<usize>,
102 ) {
103 let order = ranking(costs);
104 let eligible = fraction_count(self.fraction, costs.len());
105 for _ in 0..count {
106 out.push(order[below(rng, eligible)]);
107 }
108 }
109}
110
111fn fraction_count(fraction: f64, n: usize) -> usize {
113 #[expect(
114 clippy::cast_possible_truncation,
115 clippy::cast_sign_loss,
116 clippy::cast_precision_loss,
117 reason = "a population fraction, clamped to 1..=n"
118 )]
119 let count = libm::ceil(fraction.clamp(0.0, 1.0) * n as f64) as usize;
120
121 count.clamp(1, n)
122}
123
124#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
126pub enum Sampling {
127 #[default]
129 Roulette,
130 Universal,
133}
134
135#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
139pub struct Proportional {
140 pub sampling: Sampling,
142}
143
144impl Selection for Proportional {
145 fn select<R: Rng + ?Sized>(
146 &mut self,
147 costs: &[f64],
148 count: usize,
149 rng: &mut R,
150 out: &mut Vec<usize>,
151 ) {
152 let worst = costs
153 .iter()
154 .copied()
155 .filter(|c| c.is_finite())
156 .fold(f64::NEG_INFINITY, f64::max);
157 let weights: Vec<f64> = costs
158 .iter()
159 .map(|&c| if c.is_finite() { worst - c } else { 0.0 })
160 .collect();
161
162 sample(&weights, count, self.sampling, rng, out);
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq)]
170pub struct LinearRanking {
171 pub pressure: f64,
173 pub sampling: Sampling,
175}
176
177impl Default for LinearRanking {
178 fn default() -> Self {
179 Self {
180 pressure: 1.5,
181 sampling: Sampling::Roulette,
182 }
183 }
184}
185
186impl Selection for LinearRanking {
187 fn select<R: Rng + ?Sized>(
188 &mut self,
189 costs: &[f64],
190 count: usize,
191 rng: &mut R,
192 out: &mut Vec<usize>,
193 ) {
194 let weights = ranking_weights(costs, self.pressure);
195
196 sample(&weights, count, self.sampling, rng, out);
197 }
198}
199
200pub(crate) fn ranking_weights(costs: &[f64], pressure: f64) -> Vec<f64> {
202 let n = costs.len();
203 let s = pressure.clamp(1.0, 2.0);
204 let mut weights = alloc::vec![0.0; n];
205 if n == 1 {
206 weights[0] = 1.0;
207 return weights;
208 }
209
210 #[expect(
211 clippy::cast_precision_loss,
212 reason = "population sizes are far below 2^52"
213 )]
214 let last = (n - 1) as f64;
215 for (rank, &index) in ranking(costs).iter().enumerate() {
216 #[expect(
217 clippy::cast_precision_loss,
218 reason = "population sizes are far below 2^52"
219 )]
220 let position = (last - rank as f64) / last;
221 weights[index] = 2.0 - s + 2.0 * (s - 1.0) * position;
222 }
223
224 weights
225}
226
227#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
229pub struct Uniform;
230
231impl Selection for Uniform {
232 fn select<R: Rng + ?Sized>(
233 &mut self,
234 costs: &[f64],
235 count: usize,
236 rng: &mut R,
237 out: &mut Vec<usize>,
238 ) {
239 for _ in 0..count {
240 out.push(below(rng, costs.len()));
241 }
242 }
243}
244
245pub(crate) fn sample<R: Rng + ?Sized>(
248 weights: &[f64],
249 count: usize,
250 sampling: Sampling,
251 rng: &mut R,
252 out: &mut Vec<usize>,
253) {
254 let total: f64 = weights.iter().sum();
255 if !(total > 0.0 && total.is_finite()) {
256 for _ in 0..count {
257 out.push(below(rng, weights.len()));
258 }
259 return;
260 }
261
262 match sampling {
263 Sampling::Roulette => {
264 for _ in 0..count {
265 out.push(spin(weights, total * unit_f64(rng)));
266 }
267 }
268 Sampling::Universal => universal(weights, total, count, rng, out),
269 }
270}
271
272fn spin(weights: &[f64], point: f64) -> usize {
274 let mut cumulative = 0.0;
275 let mut last_positive = 0;
276 for (index, &weight) in weights.iter().enumerate() {
277 if weight > 0.0 {
278 last_positive = index;
279 }
280
281 cumulative += weight;
282 if point < cumulative {
283 return index;
284 }
285 }
286
287 last_positive
289}
290
291fn universal<R: Rng + ?Sized>(
293 weights: &[f64],
294 total: f64,
295 count: usize,
296 rng: &mut R,
297 out: &mut Vec<usize>,
298) {
299 if count == 0 {
300 return;
301 }
302
303 #[expect(
304 clippy::cast_precision_loss,
305 reason = "selection counts are far below 2^52"
306 )]
307 let spacing = total / count as f64;
308 let mut pointer = spacing * unit_f64(rng);
309 let mut cumulative = weights[0];
310 let mut index = 0;
311 for _ in 0..count {
312 while pointer >= cumulative && index + 1 < weights.len() {
313 index += 1;
314 cumulative += weights[index];
315 }
316
317 out.push(index);
318 pointer += spacing;
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325 use crate::SplitMix64;
326
327 #[test]
329 fn big_tournament_prefers_best() {
330 let costs = [5.0, 1.0, 3.0, 4.0];
331 let mut out = Vec::new();
332 Tournament { size: 50 }.select(&costs, 100, &mut SplitMix64::new(3), &mut out);
333
334 assert!(out.iter().all(|&i| i == 1));
335 }
336
337 #[test]
339 fn truncation_stays_in_top() {
340 let costs = [5.0, 1.0, 3.0, 4.0];
341 let mut out = Vec::new();
342 Truncation { fraction: 0.5 }.select(&costs, 100, &mut SplitMix64::new(3), &mut out);
343
344 assert!(out.iter().all(|&i| i == 1 || i == 2));
345 }
346
347 #[test]
349 fn ranking_weights_are_linear() {
350 let w = ranking_weights(&[3.0, 1.0, 2.0], 1.2);
351
352 assert!((w.iter().sum::<f64>() - 3.0).abs() < 1e-12);
353 assert!((w[1] - 1.2).abs() < 1e-12 && (w[0] - 0.8).abs() < 1e-12);
354 }
355
356 #[test]
358 fn universal_has_minimal_spread() {
359 let weights = [1.0, 2.0, 3.0, 4.0];
360 let mut out = Vec::new();
361 sample(
362 &weights,
363 100,
364 Sampling::Universal,
365 &mut SplitMix64::new(9),
366 &mut out,
367 );
368 for (index, expected) in [10, 20, 30, 40].into_iter().enumerate() {
369 let got = out.iter().filter(|&&i| i == index).count();
370 assert!(got.abs_diff(expected) <= 1, "index {index}: {got}");
371 }
372 }
373
374 #[test]
376 fn proportional_skips_worst() {
377 let mut out = Vec::new();
378 Proportional::default().select(
379 &[1.0, 9.0, 2.0, f64::INFINITY],
380 200,
381 &mut SplitMix64::new(4),
382 &mut out,
383 );
384
385 assert!(out.iter().all(|&i| i == 0 || i == 2));
386 }
387}