use rayon::prelude::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Instant;
use crate::core::{EvalFn, Problem, Solution};
use crate::genetic_operators::mutation::MutationManager;
use crate::genetic_operators::crossover::CrossoverManager;
use crate::genetic_operators::selectors::CrowdingTournamentSelector;
use crate::dominance::{ParetoDominance, fast_non_dominated_sort, crowding_distance};
use rand::rngs::SmallRng;
use rand::SeedableRng;
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ExecutionMode {
Sequential,
MultiThreaded,
GPU,
}
impl Default for ExecutionMode {
fn default() -> Self {
ExecutionMode::MultiThreaded
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct GenerationTimes {
pub variation: f64,
pub evaluation: f64,
pub selection: f64,
pub archive: f64,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ExecutionInfo {
pub requested: ExecutionMode,
pub effective: ExecutionMode,
pub cpu_threads: Option<usize>,
pub device: Option<String>,
pub note: Option<String>,
}
impl ExecutionInfo {
pub(crate) fn cpu(requested: ExecutionMode, effective: ExecutionMode, note: Option<String>) -> Self {
let cpu_threads = Some(if effective == ExecutionMode::Sequential { 1 } else { rayon::current_num_threads() });
ExecutionInfo { requested, effective, cpu_threads, device: None, note }
}
}
fn unevaluated_indices(population: &[Solution]) -> Vec<usize> {
population
.iter()
.enumerate()
.filter(|(_, s)| !s.evaluated)
.map(|(i, _)| i)
.collect()
}
fn apply_batch_outputs(population: &mut [Solution], idx: &[usize], outputs: Vec<Vec<f64>>) {
assert_eq!(
outputs.len(),
idx.len(),
"batch objective returned {} rows for {} solutions — it must return one row per input, in order",
outputs.len(),
idx.len()
);
for (&global, objectives) in idx.iter().zip(outputs) {
population[global].objective_fitness_values = objectives.into();
population[global].evaluated = true;
let cv = population[global].evaluate_constraints();
population[global].constraint_values = cv.into();
population[global].constraint_violation = population[global].calculate_constraint_violation();
population[global].constraint_violation_magnitude =
population[global].calculate_constraint_violation_magnitude();
population[global].feasible = population[global].is_feasible();
}
}
pub(crate) fn evaluate_population_shared(
population: &mut Vec<Solution>,
problem: &Problem,
execution_mode: ExecutionMode,
gpu_batch: Option<&dyn Fn(&Vec<Vec<f64>>) -> Vec<Vec<f64>>>,
) -> usize {
if let EvalFn::Batch(batch_fn) = problem.eval_fn {
let idx = unevaluated_indices(population);
if idx.is_empty() {
return 0;
}
let inputs: Vec<Vec<f64>> = idx.iter().map(|&i| population[i].solution.clone()).collect();
let outputs = batch_fn(&inputs);
apply_batch_outputs(population, &idx, outputs);
return idx.len();
}
if execution_mode == ExecutionMode::GPU {
if let Some(gpu) = gpu_batch {
let idx = unevaluated_indices(population);
if idx.is_empty() {
return 0;
}
let inputs: Vec<Vec<f64>> = idx.iter().map(|&i| population[i].solution.clone()).collect();
let outputs = gpu(&inputs);
apply_batch_outputs(population, &idx, outputs);
return idx.len();
}
static GPU_FALLBACK_WARNING: std::sync::Once = std::sync::Once::new();
GPU_FALLBACK_WARNING.call_once(|| {
eprintln!(
"puggles warning: ExecutionMode::GPU selected but no GpuEvaluator attached. \
Falling back to MultiThreaded. Build with --features gpu and attach one via \
with_gpu_evaluator() to enable GPU."
);
});
}
match execution_mode {
ExecutionMode::Sequential => population
.iter_mut()
.filter(|s| !s.evaluated)
.map(|s| {
s.evaluate();
1
})
.sum(),
ExecutionMode::MultiThreaded | ExecutionMode::GPU => population
.par_iter_mut()
.filter(|s| !s.evaluated)
.map(|s| {
s.evaluate();
1
})
.sum(),
}
}
pub struct NSGAII {
pub problem: Arc<Problem>,
pub population_size: usize,
pub population: Vec<Solution>,
pub nfe: AtomicUsize,
pub execution_mode: ExecutionMode,
pub selector: CrowdingTournamentSelector,
pub dominance: ParetoDominance,
pub mutation_manager: MutationManager,
pub crossover_manager: CrossoverManager,
pub archive: Vec<Solution>,
rng: SmallRng,
ranks: Vec<usize>,
crowding_distances: Vec<f64>,
generation_times: GenerationTimes,
#[cfg(feature = "gpu")]
pub gpu_evaluator: Option<crate::gpu_evaluator::GpuEvaluator>,
}
impl NSGAII {
pub fn new(
problem: Arc<Problem>,
population_size: usize,
execution_mode: ExecutionMode,
) -> Self {
assert!(
population_size > 0,
"population_size must be > 0 (a zero population produces no offspring, so a run \
can never spend its evaluation budget)"
);
let n = problem.solution_length;
let mutation_manager = MutationManager::new(n);
Self {
problem,
population_size,
population: Vec::with_capacity(population_size),
nfe: AtomicUsize::new(0),
execution_mode,
selector: CrowdingTournamentSelector::new(2, None),
dominance: ParetoDominance,
mutation_manager,
crossover_manager: CrossoverManager::new(),
archive: Vec::new(),
rng: SmallRng::from_entropy(),
ranks: Vec::new(),
crowding_distances: Vec::new(),
generation_times: GenerationTimes::default(),
#[cfg(feature = "gpu")]
gpu_evaluator: None,
}
}
pub fn with_seed(mut self, seed: u64) -> Self {
self.rng = SmallRng::seed_from_u64(seed);
self.selector = CrowdingTournamentSelector::new(2, Some(seed));
self
}
#[cfg(feature = "gpu")]
pub fn with_gpu_evaluator(mut self, evaluator: crate::gpu_evaluator::GpuEvaluator) -> Self {
self.gpu_evaluator = Some(evaluator);
self
}
fn assign_fitness(&mut self) {
let n = self.population.len();
self.ranks.resize(n, 0);
self.crowding_distances.resize(n, 0.0);
let fronts = fast_non_dominated_sort(&self.population, &self.dominance);
for (rank, front) in fronts.iter().enumerate() {
let cd = crowding_distance(&self.population, front);
for (local_idx, &global_idx) in front.iter().enumerate() {
self.ranks[global_idx] = rank;
self.crowding_distances[global_idx] = cd[local_idx];
}
}
}
fn environmental_selection(&mut self, combined: Vec<Solution>, target_size: usize) -> Vec<Solution> {
let fronts = fast_non_dominated_sort(&combined, &self.dominance);
let n = combined.len();
let mut keep = vec![false; n];
let mut rank_of = vec![0usize; n];
let mut crowd_of = vec![0.0f64; n];
let mut count = 0;
for (rank, front) in fronts.iter().enumerate() {
if count + front.len() <= target_size {
let cd = crowding_distance(&combined, front);
for (local_idx, &global_idx) in front.iter().enumerate() {
keep[global_idx] = true;
rank_of[global_idx] = rank;
crowd_of[global_idx] = cd[local_idx];
}
count += front.len();
} else {
let remaining = target_size - count;
let cd = crowding_distance(&combined, front);
let mut indexed_cd: Vec<(usize, f64)> = cd.into_iter().enumerate().collect();
indexed_cd.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
for &(local_idx, cdist) in indexed_cd.iter().take(remaining) {
let global_idx = front[local_idx];
keep[global_idx] = true;
rank_of[global_idx] = rank;
crowd_of[global_idx] = cdist;
}
break;
}
}
self.ranks.clear();
self.crowding_distances.clear();
let mut selected: Vec<Solution> = Vec::with_capacity(target_size);
for (i, sol) in combined.into_iter().enumerate() {
if keep[i] {
self.ranks.push(rank_of[i]);
self.crowding_distances.push(crowd_of[i]);
selected.push(sol);
}
}
selected
}
pub fn update_archive(&mut self) {
let started = Instant::now();
self.update_archive_untimed();
self.generation_times.archive = started.elapsed().as_secs_f64();
}
fn update_archive_untimed(&mut self) {
let ranks_valid = self.ranks.len() == self.population.len();
let ranks = &self.ranks;
let feasible: Vec<Solution> = self
.population
.iter()
.enumerate()
.filter(|(i, s)| s.feasible && s.evaluated && (!ranks_valid || ranks[*i] == 0))
.map(|(_, s)| s.clone())
.collect();
if feasible.is_empty() {
return;
}
let mut combined = std::mem::take(&mut self.archive);
combined.extend(feasible);
let fronts = fast_non_dominated_sort(&combined, &self.dominance);
let front0 = match fronts.first() {
Some(f) => crate::core::first_of_each_genome(&combined, f),
None => Vec::new(),
};
let keep: Vec<usize> = if front0.len() <= self.population_size {
front0
} else {
let cd = crowding_distance(&combined, &front0);
let mut indexed: Vec<(usize, f64)> = front0.iter().copied().zip(cd).collect();
indexed.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
indexed.truncate(self.population_size);
indexed.into_iter().map(|(i, _)| i).collect()
};
let mut slots: Vec<Option<Solution>> = combined.into_iter().map(Some).collect();
self.archive = keep.into_iter().map(|i| slots[i].take().expect("unique index")).collect();
}
pub fn take_archive(&mut self) -> Vec<Solution> {
std::mem::take(&mut self.archive)
}
pub fn get_archive(&self) -> &[Solution] {
&self.archive
}
pub fn get_nfe(&self) -> usize {
self.nfe.load(Ordering::Relaxed)
}
pub fn save_state(&self) -> crate::checkpoint::GaState {
use crate::checkpoint::{GaState, SolutionRecord};
GaState {
population: self.population.iter().map(SolutionRecord::from_solution).collect(),
archive: self.archive.iter().map(SolutionRecord::from_solution).collect(),
nfe: self.get_nfe(),
}
}
pub fn load_state(&mut self, state: crate::checkpoint::GaState) {
let problem = &self.problem;
self.population = state.population.into_iter().map(|r| r.into_solution(Arc::clone(problem))).collect();
self.archive = state.archive.into_iter().map(|r| r.into_solution(Arc::clone(problem))).collect();
self.nfe = AtomicUsize::new(state.nfe);
}
pub fn effective_mode(&self) -> ExecutionMode {
if matches!(self.problem.eval_fn, EvalFn::Batch(_)) {
return ExecutionMode::Sequential;
}
if self.execution_mode == ExecutionMode::GPU {
#[cfg(feature = "gpu")]
let gpu_ready = self.gpu_evaluator.is_some();
#[cfg(not(feature = "gpu"))]
let gpu_ready = false;
return if gpu_ready { ExecutionMode::GPU } else { ExecutionMode::MultiThreaded };
}
self.execution_mode
}
pub fn execution_info(&self) -> ExecutionInfo {
let effective = self.effective_mode();
#[cfg(feature = "gpu")]
if effective == ExecutionMode::GPU {
let gpu = self.gpu_evaluator.as_ref().expect("effective GPU implies an evaluator");
return ExecutionInfo {
requested: self.execution_mode,
effective,
cpu_threads: None,
device: Some(gpu.device_description()),
note: None,
};
}
let note = if matches!(self.problem.eval_fn, EvalFn::Batch(_)) {
Some("batch objective: called once per generation on the calling thread".to_string())
} else if self.execution_mode == ExecutionMode::GPU {
Some(if cfg!(feature = "gpu") {
"GPU requested but no GpuEvaluator attached; evaluating on CPU threads".to_string()
} else {
"GPU requested but puggles was built without the `gpu` feature; evaluating on CPU threads".to_string()
})
} else {
None
};
ExecutionInfo::cpu(self.execution_mode, effective, note)
}
pub fn gpu_evaluations(&self) -> Option<usize> {
#[cfg(feature = "gpu")]
if let Some(gpu) = &self.gpu_evaluator {
return Some(gpu.evaluated_count());
}
None
}
pub fn iterate_n(&mut self, max_offspring: usize) {
let started = Instant::now();
if self.ranks.len() != self.population.len() {
self.assign_fitness();
}
let parent_indices = self.selector.select_indices(
self.population_size,
&self.ranks,
&self.crowding_distances,
);
let np = parent_indices.len();
let mut offspring: Vec<Solution> = Vec::with_capacity(max_offspring);
let mut i = 0;
while offspring.len() < max_offspring {
let p1 = &self.population[parent_indices[i % np]];
let p2 = &self.population[parent_indices[(i + 1) % np]];
i += 2;
let (c1, c2) = self.crossover_manager.perform_crossover_pair(p1, p2, &mut self.rng);
for child in [c1, c2] {
let mutated = self.mutation_manager.mutate_owned(child, &mut self.rng);
if offspring.len() < max_offspring {
offspring.push(mutated);
}
}
}
let varied = Instant::now();
self.evaluate_population(&mut offspring);
let evaluated = Instant::now();
let mut combined = std::mem::take(&mut self.population);
combined.extend(offspring);
self.population = self.environmental_selection(combined, self.population_size);
let t = &mut self.generation_times;
t.variation = (varied - started).as_secs_f64();
t.evaluation = (evaluated - varied).as_secs_f64();
t.selection = evaluated.elapsed().as_secs_f64();
}
pub fn last_generation_times(&self) -> GenerationTimes {
self.generation_times
}
fn prime(&mut self) {
if self.population.is_empty() {
self.initialize();
}
let mut pop = std::mem::take(&mut self.population);
self.evaluate_population(&mut pop);
self.population = pop;
self.assign_fitness();
self.update_archive();
}
pub fn run_timed(&mut self, max_nfe: usize, time_limit: std::time::Duration) {
self.prime();
let start = std::time::Instant::now();
while self.nfe.load(Ordering::Relaxed) < max_nfe && start.elapsed() < time_limit {
let remaining = max_nfe - self.nfe.load(Ordering::Relaxed);
self.iterate_n(remaining.min(self.population_size));
self.update_archive();
}
}
fn front_in_minimization_space(&self) -> Vec<Vec<f64>> {
let n_obj = self.problem.number_of_objectives;
let dirs = self.problem.direction.clone().unwrap_or_else(|| vec![-1; n_obj]);
let src = if self.archive.is_empty() { &self.population } else { &self.archive };
src.iter()
.map(|s| {
(0..n_obj)
.map(|i| {
let v = s.objective_fitness_values[i];
if dirs[i] == 1 { -v } else { v }
})
.collect()
})
.collect()
}
pub fn archive_hypervolume(&self, reference: [f64; 2]) -> f64 {
crate::metrics::hypervolume_2d(&self.front_in_minimization_space(), reference)
}
pub fn run_until_hv_converged(
&mut self,
max_nfe: usize,
patience: usize,
epsilon: f64,
reference: [f64; 2],
) -> usize {
assert_eq!(
self.problem.number_of_objectives, 2,
"run_until_hv_converged needs exactly 2 objectives (exact hypervolume is 2-D only); \
use run_until_converged for other objective counts"
);
self.prime();
let mut best_hv = f64::NEG_INFINITY;
let mut stale = 0usize;
let mut gens = 0usize;
while self.nfe.load(Ordering::Relaxed) < max_nfe {
let remaining = max_nfe - self.nfe.load(Ordering::Relaxed);
self.iterate_n(remaining.min(self.population_size));
self.update_archive();
gens += 1;
let hv = self.archive_hypervolume(reference);
if hv > best_hv + epsilon {
best_hv = hv;
stale = 0;
} else {
stale += 1;
if stale >= patience {
break;
}
}
}
gens
}
pub fn run_until_converged(&mut self, max_nfe: usize, patience: usize, epsilon: f64) -> usize {
self.prime();
let n_obj = self.problem.number_of_objectives;
let dirs = self.problem.direction.clone().unwrap_or_else(|| vec![-1; n_obj]);
let mut best = vec![f64::INFINITY; n_obj]; let mut stale = 0usize;
let mut gens = 0usize;
while self.nfe.load(Ordering::Relaxed) < max_nfe {
let remaining = max_nfe - self.nfe.load(Ordering::Relaxed);
self.iterate_n(remaining.min(self.population_size));
self.update_archive();
gens += 1;
let src = if self.archive.is_empty() { &self.population } else { &self.archive };
let mut improved = false;
for (i, d) in dirs.iter().enumerate() {
let cur = src
.iter()
.map(|s| if *d == 1 { -s.objective_fitness_values[i] } else { s.objective_fitness_values[i] })
.fold(f64::INFINITY, f64::min);
if cur < best[i] - epsilon {
best[i] = cur;
improved = true;
}
}
if improved {
stale = 0;
} else {
stale += 1;
if stale >= patience {
break;
}
}
}
gens
}
}
impl NSGAII {
pub fn initialize(&mut self) {
let problem = Arc::clone(&self.problem);
let mut pop = Vec::with_capacity(self.population_size);
for _ in 0..self.population_size {
let solution = problem.generate_solution(&mut self.rng);
pop.push(Solution {
problem: Arc::clone(&problem),
solution,
objective_fitness_values: Default::default(),
constraint_values: Default::default(),
evaluated: false,
constraint_violation: 0,
constraint_violation_magnitude: 0.0,
feasible: false,
});
}
self.population = pop;
}
pub fn evaluate_population(&mut self, population: &mut Vec<Solution>) {
#[cfg(feature = "gpu")]
{
if let Some(gpu) = self.gpu_evaluator.as_ref() {
let run_gpu = |inputs: &Vec<Vec<f64>>| gpu.evaluate_batch(inputs);
let n = evaluate_population_shared(
population,
&self.problem,
self.execution_mode,
Some(&run_gpu),
);
self.nfe.fetch_add(n, Ordering::Relaxed);
return;
}
}
let n = evaluate_population_shared(population, &self.problem, self.execution_mode, None);
self.nfe.fetch_add(n, Ordering::Relaxed);
}
pub fn iterate(&mut self) {
self.iterate_n(self.population_size);
}
pub fn run(&mut self, max_nfe: usize) {
self.run_with(max_nfe, |_| true);
}
pub fn run_with(&mut self, max_nfe: usize, mut on_generation: impl FnMut(&mut Self) -> bool) {
self.prime();
while self.nfe.load(Ordering::Relaxed) < max_nfe {
let remaining = max_nfe - self.nfe.load(Ordering::Relaxed);
self.iterate_n(remaining.min(self.population_size));
self.update_archive();
if !on_generation(self) {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{EvalFn, Problem};
use crate::gatypes::SolutionDataTypes;
use crate::gatypes::{BitBinary, Integer, Real};
use crate::benchmark_objective_functions::parabloid_5_loc;
use std::collections::HashSet;
use std::sync::{LazyLock, Mutex};
use std::thread::{self, ThreadId};
use std::time::Duration;
static EVALUATION_THREADS: LazyLock<Mutex<HashSet<ThreadId>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
fn record_evaluation_thread(x: &Vec<f64>) -> Vec<f64> {
EVALUATION_THREADS
.lock()
.expect("evaluation thread recorder was poisoned")
.insert(thread::current().id());
thread::sleep(Duration::from_millis(2));
vec![x.iter().sum()]
}
fn setup_thread_recording_problem() -> Problem {
Problem {
solution_length: 1,
number_of_objectives: 1,
objective_constraint: None,
objective_constraint_operands: None,
direction: Some(vec![-1]),
solution_data_types: vec![SolutionDataTypes::Real(Real::new(Some(-1.0), Some(1.0)))],
variable_constraints: None,
encoding: crate::core::Encoding::PerGene,
eval_fn: EvalFn::Single(record_evaluation_thread),
}
}
fn clear_evaluation_threads() {
EVALUATION_THREADS
.lock()
.expect("evaluation thread recorder was poisoned")
.clear();
}
fn recorded_thread_count() -> usize {
EVALUATION_THREADS
.lock()
.expect("evaluation thread recorder was poisoned")
.len()
}
fn setup_single_objective_problem() -> Problem {
Problem {
solution_length: 5,
number_of_objectives: 1,
objective_constraint: None,
objective_constraint_operands: None,
direction: Some(vec![-1]), solution_data_types: vec![
SolutionDataTypes::Real(Real::new(Some(-10.0), Some(10.0))),
SolutionDataTypes::Real(Real::new(Some(-10.0), Some(10.0))),
SolutionDataTypes::Real(Real::new(Some(-10.0), Some(10.0))),
SolutionDataTypes::Real(Real::new(Some(-10.0), Some(10.0))),
SolutionDataTypes::Real(Real::new(Some(-10.0), Some(10.0))),
],
variable_constraints: None,
encoding: crate::core::Encoding::PerGene,
eval_fn: EvalFn::Single(parabloid_5_loc),
}
}
fn setup_multi_objective_problem() -> Problem {
Problem {
solution_length: 3,
number_of_objectives: 2,
objective_constraint: None,
objective_constraint_operands: None,
direction: Some(vec![-1, -1]),
solution_data_types: vec![
SolutionDataTypes::Real(Real::new(Some(-10.0), Some(10.0))),
SolutionDataTypes::Integer(Integer::new(Some(-10), Some(10))),
SolutionDataTypes::BitBinary(BitBinary::new()),
],
variable_constraints: None,
encoding: crate::core::Encoding::PerGene,
eval_fn: EvalFn::Single(|x| vec![
x[0] * x[0] + x[1] as f64,
(x[0] - 2.0).powi(2) + x[2],
]),
}
}
fn setup_mixed_type_problem() -> Problem {
Problem {
solution_length: 5,
number_of_objectives: 1,
objective_constraint: Some(vec![Some(10.0)]),
objective_constraint_operands: Some(vec![Some("<".to_string())]),
direction: Some(vec![1]),
solution_data_types: vec![
SolutionDataTypes::BitBinary(BitBinary::new()),
SolutionDataTypes::Integer(Integer::new(Some(10), Some(2000))),
SolutionDataTypes::Real(Real::new(Some(10.0), Some(1000.0))),
SolutionDataTypes::Real(Real::new(Some(10.0), Some(1000.0))),
SolutionDataTypes::Real(Real::new(Some(10.0), Some(1000.0))),
],
variable_constraints: None,
encoding: crate::core::Encoding::PerGene,
eval_fn: EvalFn::Single(|x| vec![x.iter().sum()]),
}
}
#[test]
fn test_nsgaii_initialize_sequential() {
let problem = Arc::new(setup_single_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
ga.initialize();
assert_eq!(ga.population.len(), 20);
}
#[test]
fn test_nsgaii_initialize_multithreaded() {
let problem = Arc::new(setup_single_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 50, ExecutionMode::MultiThreaded);
ga.initialize();
assert_eq!(ga.population.len(), 50);
}
#[test]
fn test_execution_modes_use_expected_evaluation_threads() {
let problem = Arc::new(setup_thread_recording_problem());
clear_evaluation_threads();
let mut sequential = NSGAII::new(Arc::clone(&problem), 64, ExecutionMode::Sequential);
sequential.run(64);
assert_eq!(
recorded_thread_count(),
1,
"sequential mode must use one evaluation thread"
);
clear_evaluation_threads();
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(2)
.build()
.unwrap();
let mut parallel = NSGAII::new(problem, 64, ExecutionMode::MultiThreaded);
pool.install(|| parallel.run(64));
assert_eq!(
recorded_thread_count(),
2,
"parallel mode must use both Rayon workers"
);
}
#[test]
fn test_nsgaii_single_objective_run() {
let problem = Arc::new(setup_single_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 30, ExecutionMode::MultiThreaded);
ga.initialize();
ga.run(500);
assert!(ga.get_nfe() >= 500);
assert_eq!(ga.population.len(), 30);
for sol in &ga.population {
assert!(sol.evaluated);
}
}
#[test]
fn test_nsgaii_multi_objective_run() {
let problem = Arc::new(setup_multi_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 40, ExecutionMode::MultiThreaded);
ga.initialize();
ga.run(1000);
assert!(ga.get_nfe() >= 1000);
assert_eq!(ga.population.len(), 40);
for sol in &ga.archive {
assert!(sol.evaluated);
}
}
#[test]
fn test_nsgaii_mixed_types() {
let problem = Arc::new(setup_mixed_type_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
ga.initialize();
ga.run(200);
assert!(ga.get_nfe() >= 200);
assert_eq!(ga.population.len(), 20);
}
#[test]
fn test_nsgaii_iterate_preserves_population_size() {
let problem = Arc::new(setup_multi_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
ga.run(20); for _ in 0..5 {
ga.iterate();
assert_eq!(ga.population.len(), 20, "Population size must stay constant across iterations");
}
}
#[test]
fn test_execution_mode_default() {
assert_eq!(ExecutionMode::default(), ExecutionMode::MultiThreaded);
}
#[test]
fn test_effective_mode() {
let problem = Arc::new(setup_single_objective_problem());
let ga = NSGAII::new(Arc::clone(&problem), 10, ExecutionMode::Sequential);
assert_eq!(ga.effective_mode(), ExecutionMode::Sequential);
let ga = NSGAII::new(Arc::clone(&problem), 10, ExecutionMode::GPU);
assert_eq!(ga.effective_mode(), ExecutionMode::MultiThreaded);
let batch_problem = Arc::new(Problem {
solution_length: 3,
number_of_objectives: 1,
objective_constraint: None,
objective_constraint_operands: None,
direction: Some(vec![-1]),
solution_data_types: vec![
SolutionDataTypes::Real(Real::new(Some(-1.0), Some(1.0))),
SolutionDataTypes::Real(Real::new(Some(-1.0), Some(1.0))),
SolutionDataTypes::Real(Real::new(Some(-1.0), Some(1.0))),
],
variable_constraints: None,
encoding: crate::core::Encoding::PerGene,
eval_fn: EvalFn::Batch(|batch| batch.iter().map(|x| vec![x.iter().sum::<f64>()]).collect()),
});
let ga = NSGAII::new(batch_problem, 10, ExecutionMode::MultiThreaded);
assert_eq!(ga.effective_mode(), ExecutionMode::Sequential);
}
#[test]
fn test_nsgaii_gpu_fallback_to_multithreaded() {
let problem = Arc::new(setup_multi_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 40, ExecutionMode::GPU);
ga.initialize();
ga.run(1000);
assert!(ga.get_nfe() >= 1000);
assert_eq!(ga.population.len(), 40);
for sol in &ga.population {
assert!(sol.evaluated);
}
}
#[test]
fn test_nsgaii_multithreaded_archive_nonempty() {
let problem = Arc::new(setup_multi_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 40, ExecutionMode::MultiThreaded);
ga.initialize();
ga.run(1000);
assert!(ga.get_nfe() >= 1000);
assert_eq!(ga.population.len(), 40);
assert!(!ga.archive.is_empty(), "archive should contain non-dominated solutions");
for sol in &ga.population {
assert!(sol.evaluated);
}
}
#[test]
fn test_nsgaii_auto_initialize_on_run() {
let problem = Arc::new(setup_single_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
ga.run(100);
assert!(ga.get_nfe() >= 100);
assert_eq!(ga.population.len(), 20);
}
#[test]
fn test_checkpoint_roundtrip() {
let problem = Arc::new(setup_multi_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential).with_seed(7);
ga.run(400);
let nfe = ga.get_nfe();
let before: Vec<_> = ga.get_archive().iter().map(|s| s.objective_fitness_values.clone()).collect();
let state = ga.save_state();
let mut ga2 = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
ga2.load_state(state);
assert_eq!(ga2.get_nfe(), nfe);
let after: Vec<_> = ga2.get_archive().iter().map(|s| s.objective_fitness_values.clone()).collect();
assert_eq!(before, after, "restored archive must match");
ga2.run(800);
assert!(ga2.get_nfe() >= 800);
}
#[test]
fn test_seeded_runs_are_reproducible() {
let problem = Arc::new(setup_multi_objective_problem());
let run = || {
let mut ga = NSGAII::new(Arc::clone(&problem), 30, ExecutionMode::Sequential).with_seed(123);
ga.run(600);
ga.get_archive()
.iter()
.map(|s| s.objective_fitness_values.clone())
.collect::<Vec<_>>()
};
let a = run();
let b = run();
assert!(!a.is_empty());
assert_eq!(a, b, "same seed must produce an identical archive");
}
#[test]
fn test_run_until_converged_stops_early() {
let problem = Arc::new(setup_single_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
let gens = ga.run_until_converged(1_000_000, 10, 1e-6);
assert!(ga.get_nfe() < 1_000_000, "should stop on plateau, not exhaust NFE");
assert!(gens > 0);
assert_eq!(ga.population.len(), 20);
}
#[test]
fn test_nsgaii_run_timed() {
let problem = Arc::new(setup_multi_objective_problem());
let mut ga = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
ga.run_timed(200, std::time::Duration::from_secs(60));
assert!(ga.get_nfe() >= 200);
assert_eq!(ga.population.len(), 20);
}
#[test]
fn test_run_with_matches_run_and_stops_early() {
let problem = Arc::new(setup_multi_objective_problem());
let front = |ga: &NSGAII| {
ga.get_archive().iter().map(|s| s.objective_fitness_values.clone()).collect::<Vec<_>>()
};
let mut plain = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential).with_seed(7);
plain.run(600);
let mut observed = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential).with_seed(7);
let mut generations = 0;
observed.run_with(600, |_| {
generations += 1;
true
});
assert_eq!(front(&plain), front(&observed), "observing a run must not change it");
assert!(generations > 0);
let mut stopped = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential);
stopped.run_with(1_000_000, |ga| ga.get_nfe() < 200);
assert!(stopped.get_nfe() < 1_000, "returning false must stop the run");
}
#[test]
fn test_execution_info_reports_fallback() {
let problem = Arc::new(setup_multi_objective_problem());
let seq = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::Sequential).execution_info();
assert_eq!((seq.effective, seq.cpu_threads, seq.note.is_none()), (ExecutionMode::Sequential, Some(1), true));
let gpu = NSGAII::new(Arc::clone(&problem), 20, ExecutionMode::GPU);
let info = gpu.execution_info();
assert_eq!(info.requested, ExecutionMode::GPU);
assert_eq!(info.effective, ExecutionMode::MultiThreaded);
assert!(info.device.is_none() && info.cpu_threads.is_some());
assert!(info.note.unwrap().contains("GPU requested"));
assert_eq!(gpu.gpu_evaluations(), None);
}
#[test]
fn test_archive_has_no_repeated_genomes() {
use crate::gatypes::BitBinary;
fn obj(x: &Vec<f64>) -> Vec<f64> {
let ones: f64 = x.iter().sum();
vec![ones, x.len() as f64 - ones + x[0]]
}
let problem = Arc::new(Problem::new(12, 2, None, None, Some(vec![-1, -1]),
vec![SolutionDataTypes::BitBinary(BitBinary::new()); 12], obj));
let mut ga = NSGAII::new(problem, 40, ExecutionMode::Sequential).with_seed(3);
ga.run(4_000);
let keys: HashSet<_> = ga.get_archive().iter().map(|s| crate::core::GenomeKey(&s.solution)).collect();
assert_eq!(keys.len(), ga.get_archive().len(), "archive must not repeat a genome");
}
}