rlevo-evolution 0.3.0

Evolutionary algorithms for rlevo (internal crate — use `rlevo` for the full API)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! Artificial Bee Colony.
//!
//! Canonical ABC fused into a single `Strategy::ask` / `tell` round per
//! generation. Each generation produces `2 · pop_size` candidate
//! solutions:
//!
//! 1. **Employed phase** (`pop_size` candidates). For every bee `i`, pick
//!    a neighbour `k ≠ i`, pick a random dimension `j`, and perturb:
//!    `v_ij = x_ij + φ·(x_ij − x_kj)` with `φ ∈ U[−1, 1]`.
//! 2. **Onlooker phase** (`pop_size` candidates). Draw a target `t` via
//!    tournament selection (fitness-biased), then perturb exactly as in
//!    the employed phase.
//!
//! `tell` scores the `2N` candidates, greedy-accepts the best
//! improvement per target bee, and increments the target's `trial`
//! counter when no candidate improved it. Scout bees — those with
//! `trial > limit` — are replaced by fresh uniform samples on device.
//!
//! # First-generation protocol
//!
//! `ask` detects the first call by checking whether `fitness` is empty
//! and, if so, returns the current colony unchanged (no perturbation).
//! `tell` detects the same condition and uses the received fitness to
//! seed `AbcState::fitness` and `best_genome` before returning.
//! Any caller that bypasses [`EvolutionaryHarness`] must therefore call
//! `ask` → evaluate → `tell` **twice** before the employed/onlooker
//! phases are active.
//!
//! [`EvolutionaryHarness`]: crate::strategy::EvolutionaryHarness
//!
//! # References
//!
//! - Karaboga (2005), *An idea based on honey bee swarm for numerical
//!   optimization* (Erciyes Univ. Tech. Report TR06).

use std::marker::PhantomData;

use burn::tensor::{Int, Tensor, TensorData, backend::Backend};
use rand::Rng;
use rand::RngExt;

use rlevo_core::bounds::Bounds;
use rlevo_core::config::{self, ConfigError, ConstraintKind, Validate};

use super::len_matches_pop;
use crate::ops::selection::{argmax_host, tournament_indices_host};
use crate::rng::{SeedPurpose, seed_stream};
use crate::strategy::{Strategy, StrategyMetrics};

/// Static configuration for [`ArtificialBeeColony`].
#[derive(Debug, Clone)]
pub struct AbcConfig {
    /// Colony size. The algorithm draws `2 · pop_size` candidates per
    /// generation (employed + onlooker).
    pub pop_size: usize,
    /// Genome dimensionality.
    pub genome_dim: usize,
    /// Search-space bounds.
    pub bounds: Bounds,
    /// Scout trigger. A bee with `trial > limit` is reinitialized.
    /// Karaboga's canonical default is `pop_size · genome_dim / 2`.
    pub limit: usize,
    /// Tournament size for onlooker selection. Canonical ABC uses
    /// roulette (fitness-proportionate); tournament is a GPU-friendly
    /// equivalent that reuses
    /// [`crate::ops::selection::tournament_indices_host`].
    pub tournament_size: usize,
}

impl AbcConfig {
    /// Default configuration for a given population size and genome dimensionality.
    ///
    /// The scout `limit` is set to `(pop_size * genome_dim) / 2` following
    /// Karaboga's canonical recommendation. The `tournament_size` defaults
    /// to `3` (three-way tournament for onlooker selection).
    #[must_use]
    pub fn default_for(pop_size: usize, genome_dim: usize) -> Self {
        Self {
            pop_size,
            genome_dim,
            bounds: Bounds::new(-5.12, 5.12),
            limit: (pop_size * genome_dim) / 2,
            tournament_size: 3,
        }
    }
}

impl Validate for AbcConfig {
    fn validate(&self) -> Result<(), ConfigError> {
        const C: &str = "AbcConfig";
        config::at_least(C, "pop_size", self.pop_size, 2)?;
        config::nonzero(C, "genome_dim", self.genome_dim)?;
        config::at_least(C, "limit", self.limit, 1)?;
        config::at_least(C, "tournament_size", self.tournament_size, 1)?;
        if self.tournament_size > 2 * self.pop_size {
            return Err(ConfigError {
                config: C,
                field: "tournament_size",
                kind: ConstraintKind::Custom("tournament_size must not exceed 2 * pop_size"),
            });
        }
        Ok(())
    }
}

/// Generation state for [`ArtificialBeeColony`].
///
/// Fields are private so the per-bee caches cannot fall out of sync with the
/// colony size from outside this module; construct one with
/// [`try_new`](AbcState::try_new) and read it through the accessors.
#[derive(Debug, Clone)]
pub struct AbcState<B: Backend> {
    /// Current colony, shape `(pop_size, D)`.
    colony: Tensor<B, 2>,
    /// Host-side fitness cache.
    fitness: Vec<f32>,
    /// Per-bee trial counter.
    trial: Vec<usize>,
    /// Target-bee mapping recorded by `ask` so `tell` knows which bee
    /// each candidate belongs to. Empty after `init` and after the
    /// bootstrap `ask` call (when `fitness` is still empty); populated
    /// with `2 · pop_size` indices from the second `ask` onward.
    target_of_candidate: Vec<usize>,
    /// Best-so-far genome.
    best_genome: Option<Tensor<B, 2>>,
    /// Best-so-far fitness.
    best_fitness: f32,
    /// Generation counter.
    generation: usize,
}

impl<B: Backend> AbcState<B> {
    /// Assembles a colony state, checking the per-bee caches match the colony.
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] if the colony has zero rows, if `fitness` or
    /// `trial` is non-empty with a length other than `pop_size`, or if
    /// `target_of_candidate` is non-empty with a length other than
    /// `2 · pop_size`.
    #[allow(clippy::too_many_arguments)]
    pub fn try_new(
        colony: Tensor<B, 2>,
        fitness: Vec<f32>,
        trial: Vec<usize>,
        target_of_candidate: Vec<usize>,
        best_genome: Option<Tensor<B, 2>>,
        best_fitness: f32,
        generation: usize,
    ) -> Result<Self, ConfigError> {
        let pop = colony.dims()[0];
        config::nonzero("AbcState", "pop_size", pop)?;
        len_matches_pop("AbcState", "fitness", pop, fitness.len())?;
        len_matches_pop("AbcState", "trial", pop, trial.len())?;
        if !target_of_candidate.is_empty() && target_of_candidate.len() != 2 * pop {
            return Err(ConfigError {
                config: "AbcState",
                field: "target_of_candidate",
                kind: ConstraintKind::Custom("length must equal 2 * pop_size"),
            });
        }
        Ok(Self {
            colony,
            fitness,
            trial,
            target_of_candidate,
            best_genome,
            best_fitness,
            generation,
        })
    }

    /// Current colony, shape `(pop_size, D)`.
    #[must_use]
    pub fn colony(&self) -> &Tensor<B, 2> {
        &self.colony
    }

    /// Host-side fitness cache (empty at bootstrap, else `pop_size` long).
    #[must_use]
    pub fn fitness(&self) -> &[f32] {
        &self.fitness
    }

    /// Per-bee trial counters, `pop_size` long.
    #[must_use]
    pub fn trial(&self) -> &[usize] {
        &self.trial
    }

    /// Candidate-to-bee mapping recorded by `ask` (`2 · pop_size` long, or
    /// empty at bootstrap).
    #[must_use]
    pub fn target_of_candidate(&self) -> &[usize] {
        &self.target_of_candidate
    }

    /// Best-so-far genome, or `None` before the first `tell`.
    #[must_use]
    pub fn best_genome(&self) -> Option<&Tensor<B, 2>> {
        self.best_genome.as_ref()
    }

    /// Best-so-far (canonical, maximise) fitness.
    #[must_use]
    pub fn best_fitness(&self) -> f32 {
        self.best_fitness
    }

    /// Generation counter.
    #[must_use]
    pub fn generation(&self) -> usize {
        self.generation
    }
}

/// Artificial Bee Colony strategy.
///
/// # Panics
///
/// [`Strategy::init`] panics if `params.pop_size < 2`, since the
/// employed-phase neighbour `k ≠ i` cannot be drawn from a colony of
/// one.
///
/// # Example
///
/// ```no_run
/// use burn::backend::Flex;
/// use rlevo_evolution::algorithms::metaheuristic::abc::{AbcConfig, ArtificialBeeColony};
///
/// let strategy = ArtificialBeeColony::<Flex>::new();
/// let params = AbcConfig::default_for(30, 10);
/// let _ = (strategy, params);
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct ArtificialBeeColony<B: Backend> {
    _backend: PhantomData<fn() -> B>,
}

impl<B: Backend> ArtificialBeeColony<B> {
    /// Builds a new (stateless) strategy object.
    #[must_use]
    pub fn new() -> Self {
        Self {
            _backend: PhantomData,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn build_candidates(
        targets: &[usize],
        neighbors: &[usize],
        dims: &[usize],
        phi: &[f32],
        colony: &Tensor<B, 2>,
        pop_size: usize,
        genome_dim: usize,
        device: &<B as burn::tensor::backend::BackendTypes>::Device,
    ) -> Tensor<B, 2> {
        // Base = copy of targets' rows (we only modify one dim each).
        #[allow(clippy::cast_possible_wrap)]
        let target_idx: Vec<i64> = targets.iter().map(|&i| i as i64).collect();
        let _ = pop_size; // number of candidates is inferred below
        let n_cand = targets.len();
        let target_tensor =
            Tensor::<B, 1, Int>::from_data(TensorData::new(target_idx, [n_cand]), device);
        let base = colony.clone().select(0, target_tensor);

        // Compute the perturbation for the single selected dim per row.
        #[allow(clippy::cast_possible_wrap)]
        let neighbor_idx: Vec<i64> = neighbors.iter().map(|&i| i as i64).collect();
        let neighbor_tensor =
            Tensor::<B, 1, Int>::from_data(TensorData::new(neighbor_idx, [n_cand]), device);
        let neighbor_rows = colony.clone().select(0, neighbor_tensor);

        // Build a (n_cand, D) mask with `1` at (row, dims[row]).
        let mut mask = vec![0i64; n_cand * genome_dim];
        for (row, &j) in dims.iter().enumerate() {
            mask[row * genome_dim + j] = 1;
        }
        let mask_bool =
            Tensor::<B, 2, Int>::from_data(TensorData::new(mask, [n_cand, genome_dim]), device)
                .equal_elem(1);

        // φ is per-row; broadcast to (n_cand, D).
        let phi_row = Tensor::<B, 1>::from_data(TensorData::new(phi.to_vec(), [n_cand]), device)
            .unsqueeze_dim::<2>(1)
            .expand([n_cand, genome_dim]);
        let delta = phi_row.mul(base.clone() - neighbor_rows);
        let perturbed = base.clone() + delta;
        base.mask_where(mask_bool, perturbed)
    }
}

impl<B: Backend> Strategy<B> for ArtificialBeeColony<B>
where
    B::Device: Clone,
{
    type Params = AbcConfig;
    type State = AbcState<B>;
    type Genome = Tensor<B, 2>;

    fn init(
        &self,
        params: &AbcConfig,
        rng: &mut dyn Rng,
        device: &<B as burn::tensor::backend::BackendTypes>::Device,
    ) -> AbcState<B> {
        debug_assert!(
            params.validate().is_ok(),
            "invalid AbcConfig reached init: {params:?}"
        );
        let (lo, hi): (f32, f32) = params.bounds.into();
        // Host-sample the initial colony from a deterministic `seed_stream`
        // rather than the process-wide Flex RNG (`B::seed` + `Tensor::random`),
        // whose draws interleave with sibling tests under the parallel runner
        // and are not reproducible across thread schedules.
        let pop = params.pop_size;
        let genome_dim = params.genome_dim;
        let mut stream = seed_stream(rng.next_u64(), 0, SeedPurpose::Init);
        let mut colony_rows = Vec::with_capacity(pop * genome_dim);
        for _ in 0..pop * genome_dim {
            colony_rows.push(lo + (hi - lo) * stream.random::<f32>());
        }
        let colony =
            Tensor::<B, 2>::from_data(TensorData::new(colony_rows, [pop, genome_dim]), device);
        AbcState {
            colony,
            fitness: Vec::new(),
            trial: vec![0; params.pop_size],
            target_of_candidate: Vec::new(),
            best_genome: None,
            best_fitness: f32::NEG_INFINITY,
            generation: 0,
        }
    }

    fn ask(
        &self,
        params: &AbcConfig,
        state: &AbcState<B>,
        rng: &mut dyn Rng,
        device: &<B as burn::tensor::backend::BackendTypes>::Device,
    ) -> (Tensor<B, 2>, AbcState<B>) {
        if state.fitness.is_empty() {
            return (state.colony.clone(), state.clone());
        }

        let pop = params.pop_size;
        let genome_dim = params.genome_dim;
        let n_cand = 2 * pop;

        let mut stream = seed_stream(rng.next_u64(), state.generation as u64, SeedPurpose::Other);

        let mut targets = Vec::with_capacity(n_cand);
        let mut neighbors = Vec::with_capacity(n_cand);
        let mut dims = Vec::with_capacity(n_cand);
        let mut phis = Vec::with_capacity(n_cand);

        // Employed phase — every bee is a target exactly once.
        for i in 0..pop {
            targets.push(i);
        }
        // Onlooker phase — tournament selection biased toward the
        // fittest (canonical maximise) sources.
        targets.extend(
            tournament_indices_host(&state.fitness, params.tournament_size, pop, &mut stream)
                .into_iter()
                .map(|w| usize::try_from(w).expect("winner index is non-negative")),
        );
        // Neighbour + dim + φ for every candidate.
        for &t in &targets {
            let mut k = stream.random_range(0..pop);
            if k == t {
                k = (k + 1) % pop;
            }
            neighbors.push(k);
            dims.push(stream.random_range(0..genome_dim));
            let phi = 2.0 * stream.random::<f32>() - 1.0;
            phis.push(phi);
        }

        let candidates = Self::build_candidates(
            &targets,
            &neighbors,
            &dims,
            &phis,
            &state.colony,
            pop,
            genome_dim,
            device,
        );
        let (lo, hi): (f32, f32) = params.bounds.into();
        let candidates = candidates.clamp(lo, hi);

        let mut next = state.clone();
        next.target_of_candidate = targets;
        (candidates, next)
    }

    #[allow(clippy::too_many_lines)]
    fn tell(
        &self,
        params: &AbcConfig,
        candidates: Tensor<B, 2>,
        fitness: Tensor<B, 1>,
        mut state: AbcState<B>,
        rng: &mut dyn Rng,
    ) -> (AbcState<B>, StrategyMetrics) {
        let fitness_host = fitness
            .into_data()
            .into_vec::<f32>()
            .expect("fitness tensor must be readable as f32");
        let device = candidates.device();
        let pop = params.pop_size;
        let genome_dim = params.genome_dim;

        // First tell: population is the initial colony being scored.
        if state.fitness.is_empty() {
            state.fitness.clone_from(&fitness_host);
            let best_idx = argmax_host(&fitness_host);
            state.best_fitness = fitness_host[best_idx];
            #[allow(clippy::cast_possible_wrap)]
            let idx = Tensor::<B, 1, Int>::from_data(
                TensorData::new(vec![best_idx as i64], [1]),
                &device,
            );
            state.best_genome = Some(candidates.clone().select(0, idx));
            state.colony = candidates;
            state.generation += 1;
            let m = StrategyMetrics::from_host_fitness(
                state.generation,
                &fitness_host,
                state.best_fitness,
            );
            state.best_fitness = m.best_fitness_ever();
            return (state, m);
        }

        // For every target, find the best improving candidate (if any).
        // `best_per_target[t] = (cand_idx, cand_fit)` when improvement.
        let mut best_per_target: Vec<Option<(usize, f32)>> = vec![None; pop];
        for (cand_idx, &t) in state.target_of_candidate.iter().enumerate() {
            let cand_fit = fitness_host[cand_idx];
            if cand_fit >= state.fitness[t] {
                match best_per_target[t] {
                    None => best_per_target[t] = Some((cand_idx, cand_fit)),
                    Some((_, prev)) if cand_fit > prev => {
                        best_per_target[t] = Some((cand_idx, cand_fit));
                    }
                    _ => {}
                }
            }
        }

        // Apply replacements via gather: we build an index tensor
        // `row_source[i]` that is either `i` (keep current) pointing
        // into `state.colony`, or `pop + cand_idx` pointing into a
        // stacked tensor `[state.colony; candidates]`.
        let stacked = Tensor::cat(vec![state.colony.clone(), candidates.clone()], 0);
        #[allow(clippy::cast_possible_wrap)]
        let mut rs: Vec<i64> = (0..pop).map(|i| i as i64).collect();
        let mut new_fitness = state.fitness.clone();
        for t in 0..pop {
            match best_per_target[t] {
                Some((cand_idx, cand_fit)) => {
                    #[allow(clippy::cast_possible_wrap)]
                    {
                        rs[t] = (pop + cand_idx) as i64;
                    }
                    new_fitness[t] = cand_fit;
                    state.trial[t] = 0;
                }
                None => {
                    state.trial[t] += 1;
                }
            }
        }
        let idx = Tensor::<B, 1, Int>::from_data(TensorData::new(rs, [pop]), &device);
        state.colony = stacked.select(0, idx);
        state.fitness = new_fitness;

        // Scout phase: reinit any bee whose trial exceeded the limit.
        let mut scouts: Vec<usize> = Vec::new();
        for (i, trial) in state.trial.iter_mut().enumerate() {
            if *trial > params.limit {
                scouts.push(i);
                *trial = 0;
            }
        }
        if !scouts.is_empty() {
            let (lo, hi): (f32, f32) = params.bounds.into();
            // Host-sample scout replacements from a deterministic
            // `seed_stream` so the refill is reproducible across thread
            // schedules rather than racing the global Flex RNG.
            let mut scout_stream = seed_stream(
                rng.next_u64(),
                state.generation as u64,
                SeedPurpose::Replacement,
            );
            let mut fresh_rows = Vec::with_capacity(scouts.len() * genome_dim);
            for _ in 0..scouts.len() * genome_dim {
                fresh_rows.push(lo + (hi - lo) * scout_stream.random::<f32>());
            }
            let fresh = Tensor::<B, 2>::from_data(
                TensorData::new(fresh_rows, [scouts.len(), genome_dim]),
                &device,
            );
            // Overwrite those rows via gather-trick.
            #[allow(clippy::cast_possible_wrap)]
            let mut rs2: Vec<i64> = (0..pop).map(|i| i as i64).collect();
            for (k, &scout) in scouts.iter().enumerate() {
                #[allow(clippy::cast_possible_wrap)]
                {
                    rs2[scout] = (pop + k) as i64;
                }
                // Scout fitness is unknown until next generation —
                // carry −INF (worst under maximise) so any candidate
                // improves it.
                state.fitness[scout] = f32::NEG_INFINITY;
            }
            let stacked2 = Tensor::cat(vec![state.colony.clone(), fresh], 0);
            let idx2 = Tensor::<B, 1, Int>::from_data(TensorData::new(rs2, [pop]), &device);
            state.colony = stacked2.select(0, idx2);
        }

        // Update best-so-far from the refreshed colony's fitness cache
        // (excluding INF-tagged scouts, which next `ask` evaluates).
        let best_idx = argmax_host(&state.fitness);
        if state.fitness[best_idx].is_finite() && state.fitness[best_idx] > state.best_fitness {
            state.best_fitness = state.fitness[best_idx];
            #[allow(clippy::cast_possible_wrap)]
            let idx = Tensor::<B, 1, Int>::from_data(
                TensorData::new(vec![best_idx as i64], [1]),
                &device,
            );
            state.best_genome = Some(state.colony.clone().select(0, idx));
        }

        state.generation += 1;
        let m =
            StrategyMetrics::from_host_fitness(state.generation, &fitness_host, state.best_fitness);
        state.best_fitness = m.best_fitness_ever();
        (state, m)
    }

    fn best(&self, state: &AbcState<B>) -> Option<(Tensor<B, 2>, f32)> {
        state
            .best_genome
            .as_ref()
            .map(|g| (g.clone(), state.best_fitness))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fitness::FromFitnessEvaluable;
    use crate::strategy::EvolutionaryHarness;
    use burn::backend::Flex;
    use rand::SeedableRng;
    use rand::rngs::StdRng;
    use rlevo_core::fitness::FitnessEvaluable;

    type TestBackend = Flex;

    #[test]
    fn try_new_checks_cache_lengths() {
        let device = Default::default();
        let colony = Tensor::<TestBackend, 2>::zeros([3, 2], &device);
        // Bootstrap (empty caches) and fully-populated caches both accept.
        assert!(
            AbcState::try_new(
                colony.clone(),
                vec![],
                vec![0; 3],
                vec![],
                None,
                f32::MIN,
                0
            )
            .is_ok()
        );
        assert!(
            AbcState::try_new(
                colony.clone(),
                vec![1.0; 3],
                vec![0; 3],
                vec![7; 6],
                None,
                1.0,
                1
            )
            .is_ok()
        );
        // fitness length 2 ≠ pop 3, and target_of_candidate 5 ≠ 2·pop.
        assert!(
            AbcState::try_new(
                colony.clone(),
                vec![1.0; 2],
                vec![0; 3],
                vec![],
                None,
                1.0,
                1
            )
            .is_err()
        );
        assert!(AbcState::try_new(colony, vec![], vec![], vec![0; 5], None, 1.0, 1).is_err());
        // Zero-row colony is rejected.
        let empty = Tensor::<TestBackend, 2>::zeros([0, 2], &device);
        assert!(AbcState::try_new(empty, vec![], vec![], vec![], None, 1.0, 0).is_err());
    }

    #[test]
    fn default_config_validates() {
        assert!(AbcConfig::default_for(30, 10).validate().is_ok());
    }

    #[test]
    fn rejects_pop_size_below_two() {
        let mut cfg = AbcConfig::default_for(30, 10);
        cfg.pop_size = 1;
        assert_eq!(cfg.validate().unwrap_err().field, "pop_size");
    }

    struct Sphere;
    struct SphereFit;
    impl FitnessEvaluable for SphereFit {
        type Individual = Vec<f64>;
        type Landscape = Sphere;
        fn evaluate(&self, x: &Self::Individual, _: &Self::Landscape) -> f64 {
            x.iter().map(|v| v * v).sum()
        }
    }

    // Regression for the inverted onlooker sense (issue #150): under the
    // canonical maximise convention onlookers must concentrate on the
    // *fittest* source, not the worst.
    #[test]
    fn onlooker_targets_prefer_best_source() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let mut params = AbcConfig::default_for(16, 4);
        params.tournament_size = 8;
        let mut rng = StdRng::seed_from_u64(11);
        let mut state = strategy.init(&params, &mut rng, &device);
        // Simulate a scored colony where bee 3 dominates.
        state.fitness = vec![0.0; 16];
        state.fitness[3] = 100.0;
        let (_candidates, next) = strategy.ask(&params, &state, &mut rng, &device);
        // Rows 0..pop are the employed phase; rows pop.. are onlookers.
        let onlooker_hits = next.target_of_candidate[16..]
            .iter()
            .filter(|&&t| t == 3)
            .count();
        // P(best wins an 8-ary tournament over pop 16) ≈ 0.40, so ~6 of
        // 16 onlookers in expectation; the inverted sense yields ~0.
        assert!(
            onlooker_hits >= 3,
            "onlooker hits on the best bee = {onlooker_hits} (expected ~6)",
        );
    }

    #[test]
    fn abc_converges_on_sphere_d10() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let params = AbcConfig::default_for(30, 10);
        let fitness_fn = FromFitnessEvaluable::new(SphereFit, Sphere);
        let mut harness = EvolutionaryHarness::<TestBackend, _, _>::new(
            strategy, params, fitness_fn, 13, device, 400,
        )
        .expect("valid params");
        harness.reset();
        while !harness.step(()).done {}
        let best = harness.latest_metrics().unwrap().best_fitness_ever();
        assert!(best < 1e-4, "ABC D10 best={best}");
    }

    /// Fitness fn: row 0 → `NaN`, the rest finite. `Maximize` so natural ==
    /// canonical, exercising the ADR-0034 harness sanitize with no `neg()` in
    /// between.
    struct PartialNanFitness;
    impl<B: Backend> crate::fitness::BatchFitnessFn<B, Tensor<B, 2>> for PartialNanFitness {
        fn evaluate_batch(
            &mut self,
            population: &Tensor<B, 2>,
            device: &<B as burn::tensor::backend::BackendTypes>::Device,
        ) -> Tensor<B, 1> {
            let n = population.dims()[0];
            #[allow(clippy::cast_precision_loss)]
            let mut vals: Vec<f32> = (0..n).map(|i| -(i as f32)).collect();
            vals[0] = f32::NAN;
            Tensor::<B, 1>::from_data(TensorData::new(vals, [n]), device)
        }
        fn sense(&self) -> rlevo_core::objective::ObjectiveSense {
            rlevo_core::objective::ObjectiveSense::Maximize
        }
    }

    // Gap (b): the bootstrap `ask` (empty `fitness`) returns the colony verbatim
    // — no perturbation, no candidate-to-bee map — so the harness scores
    // generation zero before the employed/onlooker phases activate.
    #[test]
    #[allow(clippy::float_cmp)] // byte-identical: `ask` clones `state.colony`
    fn ask_on_empty_fitness_returns_colony_unchanged() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let params = AbcConfig::default_for(6, 4);
        let mut rng = StdRng::seed_from_u64(3);
        let state = strategy.init(&params, &mut rng, &device);
        let (genome, next) = strategy.ask(&params, &state, &mut rng, &device);
        let before = state
            .colony()
            .clone()
            .into_data()
            .into_vec::<f32>()
            .expect("colony readable as f32");
        let after = genome
            .into_data()
            .into_vec::<f32>()
            .expect("genome readable as f32");
        assert_eq!(before, after);
        assert!(next.target_of_candidate().is_empty());
    }

    // Gap (a): a two-bee colony is the smallest legal ABC. The employed-phase
    // neighbour draw `k ≠ i` degenerates to the wrap `(k + 1) % pop`; this pins
    // that the wrap runs several generations without panicking.
    #[test]
    fn pop_size_two_minimal_colony_runs() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let params = AbcConfig::default_for(2, 3);
        let fitness_fn = FromFitnessEvaluable::new(SphereFit, Sphere);
        let mut harness = EvolutionaryHarness::<TestBackend, _, _>::new(
            strategy, params, fitness_fn, 5, device, 8,
        )
        .expect("valid params");
        harness.reset();
        while !harness.step(()).done {}
        assert!(
            harness
                .latest_metrics()
                .unwrap()
                .best_fitness_ever()
                .is_finite()
        );
    }

    // Gap (d): a single-dimension genome forces the per-candidate perturbation
    // mask to select the only column. Verifies the degenerate `(n_cand, 1)` mask
    // path runs end-to-end.
    #[test]
    fn genome_dim_one_degenerate_mask_runs() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let params = AbcConfig::default_for(6, 1);
        let fitness_fn = FromFitnessEvaluable::new(SphereFit, Sphere);
        let mut harness = EvolutionaryHarness::<TestBackend, _, _>::new(
            strategy, params, fitness_fn, 8, device, 8,
        )
        .expect("valid params");
        harness.reset();
        while !harness.step(()).done {}
        assert!(
            harness
                .latest_metrics()
                .unwrap()
                .best_fitness_ever()
                .is_finite()
        );
    }

    // Gap (c): scout reinitialization. A colony pinned at the canonical optimum
    // (fitness 0) receives only worse candidates, so every bee's `trial` counter
    // ticks past `limit` in a single `tell`, triggering a scout refill of the
    // whole colony (trials reset, rows resampled).
    #[test]
    #[allow(clippy::float_cmp)] // exact: scouts overwrite the all-zero seed colony
    fn scout_reinit_triggers_on_stagnation() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let mut params = AbcConfig::default_for(4, 2);
        params.limit = 1;
        // Colony at the (canonical) optimum: fitness 0, any perturbation worse.
        let colony = Tensor::<TestBackend, 2>::zeros([4, 2], &device);
        // Every bee already sits one step from the scout limit.
        let state = AbcState::try_new(
            colony,
            vec![0.0; 4],                 // current fitness
            vec![1; 4],                   // trial == limit
            vec![0, 1, 2, 3, 0, 1, 2, 3], // 2·pop candidate → target map
            None,
            f32::NEG_INFINITY,
            5,
        )
        .expect("valid state");
        // 2·pop candidates far from origin → canonical fitness −18 < 0; none
        // improves its target, so no acceptance and every trial increments.
        let candidates = Tensor::<TestBackend, 2>::full([8, 2], 3.0, &device);
        let fit =
            Tensor::<TestBackend, 1>::from_data(TensorData::new(vec![-18.0_f32; 8], [8]), &device);
        let mut rng = StdRng::seed_from_u64(9);
        let (next, _m) = strategy.tell(&params, candidates, fit, state, &mut rng);
        // trial hit limit + 1 everywhere → all bees scouted, counters reset.
        assert!(
            next.trial().iter().all(|&t| t == 0),
            "trials not reset: {:?}",
            next.trial()
        );
        // Scouted rows are fresh uniform draws, so the colony is no longer all-zero.
        let colony_vals = next
            .colony()
            .clone()
            .into_data()
            .into_vec::<f32>()
            .expect("colony readable as f32");
        assert!(
            colony_vals.iter().any(|&v| v != 0.0),
            "no scout reinit happened; colony still all-zero"
        );
    }

    // Gap (e): a partly-`NaN` objective must not poison the run — the harness
    // sanitize chokepoint (ADR 0034) keeps `best_fitness_ever` finite and flags
    // the broken member via `broken_count`.
    #[test]
    fn nan_fitness_survives_harness() {
        let device = Default::default();
        let strategy = ArtificialBeeColony::<TestBackend>::new();
        let params = AbcConfig::default_for(6, 3);
        let mut harness = EvolutionaryHarness::<TestBackend, _, _>::new(
            strategy,
            params,
            PartialNanFitness,
            4,
            device,
            4,
        )
        .expect("valid params");
        harness.reset();
        while !harness.step(()).done {}
        let m = harness.latest_metrics().unwrap();
        assert!(
            m.best_fitness_ever().is_finite(),
            "best_fitness_ever not finite: {}",
            m.best_fitness_ever()
        );
        assert!(m.broken_count() > 0, "expected a broken (NaN) member");
    }
}