From f1a6bbdb829d78985c738ddd16184fde2690ccff Mon Sep 17 00:00:00 2001 From: Rutherther Date: Fri, 5 Dec 2025 21:34:04 +0100 Subject: [PATCH] fix: use two objectives in nsga_constr --- codes/constr_hw02/src/main.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/codes/constr_hw02/src/main.rs b/codes/constr_hw02/src/main.rs index 2805509b3c2d38a05a418d97f51c29193b35f3c9..a3ab28d4b3c4118cc0e3f6e1230c673c9ecd9ebe 100644 --- a/codes/constr_hw02/src/main.rs +++ b/codes/constr_hw02/src/main.rs @@ -831,7 +831,7 @@ pub fn solve_with_nsga_constr( iterations: usize, mutation_std_dev: f64, rng: &mut dyn RngCore, -) -> Result<(EvolutionResult, [f64; 1]>, Vec, Vec), Box> { +) -> Result<(EvolutionResult, [f64; 2]>, Vec, Vec), Box> { // Create initial population let initializer = RandomInitializer::new( Box::new(BoundedOVector::new(problem.bounds.0, problem.bounds.1)) @@ -853,9 +853,25 @@ pub fn solve_with_nsga_constr( // Clone the problem to access its fields let cloned_problem = problem.clone(); - // Create objectives array - let objectives: [Box, Out = f64, Err = Infallible>>; 1] = [ + let constraint_weights = [1.0; CONSTRAINTS]; + + // Convert constraint array references + let constraint_refs = problem.constraints.iter().collect::>().try_into() + .map_err(|_| "Failed to convert constraint references")?; + + let zero_fitness = ArbitraryFitness::zero(); + + // Second objective: constraint violation only (zero fitness + constraints) + let constrained_fitness_obj2 = ConstrainedFitnessFunction { + fitness: &zero_fitness, + constraints: constraint_refs, + constraint_weights, + capped: true + }; + + let objectives: [Box, Out = f64, Err = Infallible>>; 2] = [ Box::new(cloned_problem.objective), + Box::new(constrained_fitness_obj2), ]; // Convert constraints to boxed trait objects @@ -866,7 +882,7 @@ pub fn solve_with_nsga_constr( let mut feasible_fractions = Vec::with_capacity(iterations); let mut avg_constraint_violations = Vec::with_capacity(iterations); - let result = constrained_nsga_2::<1, CONSTRAINTS, SVector, f64, Infallible, 2, _, _, _>( + let result = constrained_nsga_2::<2, CONSTRAINTS, SVector, f64, Infallible, 2, _, _, _>( initial_population, parents_count, objectives,