~ruther/ctu-fee-eoa

ref: ea435de82c9283cddd530980627e7b101f405259 ctu-fee-eoa/codes/constr_hw02/src/main.rs -rw-r--r-- 34.1 KiB
ea435de8 — Rutherther Lots of changes I lost track of 6 days ago
                                                                                
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
use std::{convert::Infallible, env, fs, io::Write, rc::Rc};

use eoa_lib::{
    bounded::BoundedOVector, comparison::MinimizingOperator, constraints::{stochastic_ranking_evolution_algorithm, ConstrainedEvalFitness, ConstrainedFitnessFunction, ConstraintFunction, LowerThanConstraintFunction}, crossover::{ArithmeticCrossover, BoundedCrossover, BoundedCrossoverStrategy}, evolution::{EvolutionCandidate, EvolutionResult, EvolutionStats}, fitness::FitnessFunction, initializer::{Initializer, RandomInitializer}, multi_objective_evolution::nsga_2, pairing::AdjacentPairing, perturbation::{BoundedPerturbation, BoundedPerturbationStrategy, MutationPerturbation, RandomDistributionPerturbation}, population::{EvaluatedChromosome, EvaluatedPopulation, Population}, replacement::{BestReplacement, GenerationalReplacement}, selection::{BestSelection, TournamentSelection}
};
use nalgebra::{ArrayStorage, Const, Matrix, SVector};
use rand::RngCore;
use rand_distr::Normal;
use chrono::prelude::*;

pub struct ArbitraryFitness<const SIZE: usize> {
    fun: Box<dyn Fn(SVector<f64, SIZE>) -> f64>
}

impl<const SIZE: usize> ArbitraryFitness<SIZE> {
    pub fn new(fun: Box<dyn Fn(SVector<f64, SIZE>) -> f64>) -> Self {
        Self {
            fun
        }
    }

    pub fn zero() -> Self {
        Self {
            fun: Box::new(|_| 0.0)
        }
    }
}

impl<const SIZE: usize> FitnessFunction for ArbitraryFitness<SIZE> {
    type In = SVector<f64, SIZE>;
    type Out = f64;
    type Err = Infallible;

    fn fit(&self, inp: &Self::In) -> Result<Self::Out, Self::Err> {
        Ok((self.fun)(*inp))
    }
}

/// A constrained optimization problem with clear field definitions
pub struct ConstrainedProblem<const DIM: usize, const CONSTRAINTS: usize> {
    pub name: String,
    pub objective: ArbitraryFitness<DIM>,
    pub constraints: [LowerThanConstraintFunction<SVector<f64, DIM>, f64>; CONSTRAINTS],
    pub bounds: (SVector<f64, DIM>, SVector<f64, DIM>), // (min, max)
    pub optimal_value: f64,
    pub instantiate_fn: Option<Rc<dyn Fn() -> ConstrainedProblem<DIM, CONSTRAINTS>>>
}

impl<const DIM: usize, const CONSTRAINTS: usize> ConstrainedProblem<DIM, CONSTRAINTS> {
    pub fn new(instantiate: Rc<dyn Fn() -> ConstrainedProblem<DIM, CONSTRAINTS>>) -> Self {
        let mut problem = instantiate();
        problem.instantiate_fn = Some(instantiate);
        problem
    }

    pub fn clone(&self) -> Self {
        Self::new(self.instantiate_fn.clone().unwrap())
    }
}

/// Configuration for stochastic ranking method
pub struct StochasticRankingConfig {
    pub population_size: usize,
    pub parents_count: usize,
    pub iterations: usize,
    pub n_param: usize,  // N parameter for stochastic ranking
    pub p_param: f64,    // p parameter for stochastic ranking
    pub mutation_std_dev: f64,
}

/// Configuration for NSGA-II method
pub struct NsgaConfig {
    pub population_size: usize,
    pub parents_count: usize,
    pub iterations: usize,
    pub mutation_std_dev: f64,
}

fn problem_g06() -> ConstrainedProblem<2, 2> {
    ConstrainedProblem::new(Rc::new(||
        ConstrainedProblem {
            name: "g06".to_string(),
            objective: ArbitraryFitness::new(
                Box::new(|vec| (vec[0] - 10.0).powi(3) + (vec[1] - 20.0).powi(3))
            ),
            constraints: [
                LowerThanConstraintFunction::new(
                    Box::new(|vec| -(vec[0] - 5.0).powi(2) - (vec[1] - 5.0).powi(2) + 100.0)
                ),
                LowerThanConstraintFunction::new(
                    Box::new(|vec| (vec[0] - 6.0).powi(2) + (vec[1] - 5.0).powi(2) - 82.81)
                ),
            ],
            bounds: (
                SVector::<f64, 2>::new(0.0, 0.0),     // min bounds
                SVector::<f64, 2>::new(50.0, 50.0)  // max bounds
            ),
            optimal_value: -6961.8137558015,
            instantiate_fn: None
        }))
}

fn problem_g08() -> ConstrainedProblem<2, 2> {
    ConstrainedProblem::new(Rc::new(|| ConstrainedProblem {
        name: "g08".to_string(),
        objective: ArbitraryFitness::new(
            Box::new(|vec| {
                let num = (2.0 * std::f64::consts::PI * vec[0]).sin().powi(3)
                    * (2.0 * std::f64::consts::PI * vec[1]).sin();
                let den = vec[0].powi(3) * (vec[0] + vec[1]);
                -num / den
            })
        ),
        constraints: [
            LowerThanConstraintFunction::new(
                Box::new(move |vec| {
                    let x1 = vec[0];
                    let x2 = vec[1];
                    x1.powi(2) - x2 + 1.0
                })
            ),
            LowerThanConstraintFunction::new(
                Box::new(move |vec| {
                    let x1 = vec[0];
                    let x2 = vec[1];
                    1.0 - x1 + (x2 - 4.0).powi(2)
                })
            ),
        ],
        bounds: (
            SVector::<f64, 2>::new(0.0, 0.0),   // min bounds
            SVector::<f64, 2>::new(10.0, 10.0)  // max bounds
        ),
        optimal_value: -0.0958250414180359,
        instantiate_fn: None
    }))
}

pub fn problem_g11(eps: f64) -> ConstrainedProblem<2, 1> {
    let problem = ConstrainedProblem::new(Rc::new(move || ConstrainedProblem {
        name: "g11".to_string(),
        objective: ArbitraryFitness::new(
            Box::new(|vec| {
                // Minimize f(x) = x1^2 + (x2 - 1)^2
                vec[0].powi(2) + (vec[1] - 1.0).powi(2)
            })
        ),
        constraints: [
            // Equality h(x) = x2 - x1^2 = 0
            // |h| - eps >= 0.0
            LowerThanConstraintFunction::new(
                Box::new(move |vec| {
                    let h = vec[1] - vec[0].powi(2);
                    h.abs() - eps
                })
            ),
        ],
        bounds: (
            SVector::<f64, 2>::new(-50.0, -50.0),  // min bounds
            SVector::<f64, 2>::new(50.0, 50.0)     // max bounds
        ),
        optimal_value: 0.7499, // Best known optimum
        instantiate_fn: None
    }));

    problem
}

pub fn problem_g24() -> ConstrainedProblem<2, 2> {
    ConstrainedProblem::new(Rc::new(|| ConstrainedProblem {
        name: "g24".to_string(),
        objective: ArbitraryFitness::new(
            Box::new(|vec| {
                // Minimize f(x) = -x1 - x2
                -vec[0] - vec[1]
            })
        ),
        constraints: [
            // g1(x) = -2x1^4 + 8x1^3 - 8x1^2 + x2 - 2 <= 0
            LowerThanConstraintFunction::new(
                Box::new(|vec| {
                    -2.0 * vec[0].powi(4) + 8.0 * vec[0].powi(3) - 8.0 * vec[0].powi(2) + vec[1] - 2.0
                })
            ),
            // g2(x) = -4x1^4 + 32x1^3 - 88x1^2 + 96x1 + x2 - 36 <= 0
            LowerThanConstraintFunction::new(
                Box::new(|vec| {
                    -4.0 * vec[0].powi(4) + 32.0 * vec[0].powi(3) - 88.0 * vec[0].powi(2) + 96.0 * vec[0] + vec[1] - 36.0
                })
            ),
        ],
        bounds: (
            SVector::<f64, 2>::new(0.0, 0.0),  // min bounds
            SVector::<f64, 2>::new(3.0, 4.0)   // max bounds
        ),
        optimal_value: -5.50801327159536, // Best known optimum
        instantiate_fn: None
    }))
}

/// Solve a constrained optimization problem using stochastic ranking
///
/// Returns the evolution result with feasible fractions for each iteration
pub fn solve_with_stochastic_ranking<const DIM: usize, const CONSTRAINTS: usize>(
    mut problem: ConstrainedProblem<DIM, CONSTRAINTS>,
    population_size: usize,
    parents_count: usize,
    iterations: usize,
    stochastic_params: (usize, f64), // (N, p) for stochastic ranking
    mutation_std_dev: f64,
    rng: &mut dyn RngCore,
) -> Result<(EvolutionResult<SVector<f64, DIM>, f64>, Vec<f64>), Box<dyn std::error::Error>> {
    // Create initial population
    let initializer = RandomInitializer::new(
        Box::new(BoundedOVector::new(problem.bounds.0, problem.bounds.1))
    );
    let initial_population = Population::from_vec(
        initializer.initialize(nalgebra::Const::<DIM>, population_size, rng)
    );

    // Setup components as specified
    // let mut selection = TournamentSelection::new(5, 0.9);
    let mut selection = TournamentSelection::new(5, 0.95);
    let mut replacement = GenerationalReplacement;
    let mut pairing = AdjacentPairing::new();
    let mut crossover = ArithmeticCrossover::new();
    // let mut crossover = BoundedCrossover::<nalgebra::Const<2>, 2, _>::new(
    //     ArithmeticCrossover::new(),
    //     problem.bounds.0,
    //     problem.bounds.1,
    //     BoundedCrossoverStrategy::Retry(5)
    // );

    // Setup bounded random distribution perturbation with Normal distribution
    let normal_perturbation = RandomDistributionPerturbation::<DIM, Normal<f64>>::normal(mutation_std_dev)?;
    let mut perturbation = normal_perturbation;
    // let perturbation = BoundedPerturbation::new(
    //     normal_perturbation,
    //     problem.bounds.0,
    //     problem.bounds.1,
    //     BoundedPerturbationStrategy::Retry(5)
    // );
    let mut mutation = MutationPerturbation::new(Box::new(perturbation), 0.1);

    // The weight is so large mainly because of the g11 that has very small values.
    // Somehow the higher weights do seem to help, even though I am unsure why exactly.
    let constraint_weights = [1.0; CONSTRAINTS];

    let (N, p) = stochastic_params;
    let better_than = MinimizingOperator::new();

    // Convert constraint array references
    let constraint_refs = problem.constraints.iter().collect::<Vec<_>>().try_into()
        .map_err(|_| "Failed to convert constraint references")?;

    stochastic_ranking_evolution_algorithm(
        initial_population,
        parents_count,
        N,
        p,
        &mut problem.objective,
        constraint_refs,
        constraint_weights,
        &mut pairing,
        &mut selection,
        &mut crossover,
        &mut mutation,
        &mut replacement,
        &better_than,
        iterations,
        rng)
}

/// Helper function to check if a chromosome is feasible
fn check_feasibility<const DIM: usize, const CONSTRAINTS: usize>(
    chromosome: &SVector<f64, DIM>,
    constraints: &[LowerThanConstraintFunction<SVector<f64, DIM>, f64>; CONSTRAINTS],
) -> bool {
    constraints.iter().all(|constraint| {
        constraint.is_feasible(chromosome).unwrap_or(false)
    })
}

/// Individual constraint fitness function - wraps a single constraint to act as a fitness function
pub struct SingleConstraintFitness<const DIM: usize, TConstraint: ConstraintFunction<Chromosome = SVector<f64, DIM>, Out = f64>> {
    constraint: TConstraint,
    capped: bool
}

impl<const DIM: usize, TConstraint: ConstraintFunction<Chromosome = SVector<f64, DIM>, Out = f64>> SingleConstraintFitness<DIM, TConstraint> {
    pub fn new(constraint: TConstraint, capped: bool) -> Self {
        Self { constraint, capped }
    }
}

impl<const DIM: usize, TConstraint: ConstraintFunction<Chromosome = SVector<f64, DIM>, Out = f64>> FitnessFunction for SingleConstraintFitness<DIM, TConstraint> {
    type In = SVector<f64, DIM>;
    type Out = f64;
    type Err = Infallible;

    fn fit(&self, inp: &Self::In) -> Result<Self::Out, Self::Err> {
        Ok(if self.constraint.is_feasible(inp).unwrap() && self.capped {
            0.0
        } else {
            self.constraint.evaluate(inp).unwrap()
        })
    }
}

/// Solve a constrained optimization problem using NSGA-II
pub fn solve_with_nsga_ii<const DIM: usize, const CONSTRAINTS: usize>(
    problem: ConstrainedProblem<DIM, CONSTRAINTS>,
    population_size: usize,
    parents_count: usize,
    iterations: usize,
    mutation_std_dev: f64,
    rng: &mut dyn RngCore,
) -> Result<(EvolutionResult<SVector<f64, DIM>, [f64; 2]>, Vec<f64>), Box<dyn std::error::Error>> {
    // Create initial population
    let initializer = RandomInitializer::new(
        Box::new(BoundedOVector::new(problem.bounds.0, problem.bounds.1))
    );
    let initial_population = Population::from_vec(
        initializer.initialize(nalgebra::Const::<DIM>, population_size, rng)
    );

    // Setup components
    let mut pairing = AdjacentPairing::new();
    let mut crossover = ArithmeticCrossover::new();

    // Setup bounded random distribution perturbation with Normal distribution
    let normal_perturbation = RandomDistributionPerturbation::<DIM, Normal<f64>>::normal(mutation_std_dev)?;
    let mut mutation = MutationPerturbation::new(Box::new(normal_perturbation), 0.1);

    let better_than = MinimizingOperator::new();

    // Create objectives: both using ConstrainedFitnessFunction with different fitness components
    let constraint_weights = [1.0e9; CONSTRAINTS];
    let constraint_refs = problem.constraints.iter().collect::<Vec<_>>().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<dyn FitnessFunction<In = SVector<f64, DIM>, Out = f64, Err = Infallible>>; 2] = [
        Box::new(problem.objective),
        Box::new(constrained_fitness_obj2),
    ];

    let mut feasible_fractions = Vec::with_capacity(iterations);

    let result = nsga_2(
        initial_population,
        parents_count,
        objectives,
        &mut pairing,
        &mut crossover,
        &mut mutation,
        &better_than,
        iterations,
        rng,
        |_iteration: usize, _stats: &EvolutionStats<SVector<f64, DIM>, _>, population: &EvaluatedPopulation<SVector<f64, DIM>, _>| {
            // Calculate feasible fraction based on second objective being close to zero
            let feasible_count = population.population
                .iter()
                .filter(|individual| {
                    individual.evaluation.evaluations[1] <= 0.0
                })
                .count();

            // let min_constraint_violation = population.population
            //     .iter()
            //     .map(|individual| {
            //         individual.evaluation.evaluations[1]
            //     })
            //     .min_by(|a, b| a.total_cmp(b)).unwrap();
            // println!("{}", min_constraint_violation);

            let feasible_fraction = feasible_count as f64 / population.population.len() as f64;
            feasible_fractions.push(feasible_fraction);
        },
        |_, evaluation, best_candidate| {
            // Do not save infeasible solutions!
            if evaluation.evaluations[1] > 0.0 {
                return false;
            }

            if best_candidate.is_none() {
                return true;
            }

            evaluation.evaluations[0] < best_candidate.as_ref().unwrap().evaluated_chromosome.evaluation.evaluations[0]
        }
    )?;

    Ok((result, feasible_fractions))
}

/// Solve a constrained optimization problem using NSGA-II with individual constraint objectives
/// For simplicity, this function only works with 2-constraint problems
pub fn solve_with_nsga_multi<const DIM: usize, const CONSTRAINTS: usize, const CONSTRS_PLUS_ONE: usize>(
    problem: ConstrainedProblem<DIM, CONSTRAINTS>,
    population_size: usize,
    parents_count: usize,
    iterations: usize,
    mutation_std_dev: f64,
    rng: &mut dyn RngCore,
    capped: bool
) -> Result<(EvolutionResult<SVector<f64, DIM>, [f64; CONSTRS_PLUS_ONE]>, Vec<f64>), Box<dyn std::error::Error>> {
    // Unfortunately Rustc doesn't support addition in generics...
    assert_eq!(CONSTRAINTS + 1, CONSTRS_PLUS_ONE);

    // Clone the problem to get bounds info first
    let bounds = (problem.bounds.0, problem.bounds.1);

    // Create initial population
    let initializer = RandomInitializer::new(
        Box::new(BoundedOVector::new(bounds.0, bounds.1))
    );
    let initial_population = Population::from_vec(
        initializer.initialize(nalgebra::Const::<DIM>, population_size, rng)
    );

    // Setup components
    let mut pairing = AdjacentPairing::new();
    let mut crossover = ArithmeticCrossover::new();
    let normal_perturbation = RandomDistributionPerturbation::<DIM, Normal<f64>>::normal(mutation_std_dev)?;
    let mut mutation = MutationPerturbation::new(Box::new(normal_perturbation), 0.1);
    let better_than = MinimizingOperator::new();

    // Create objectives: fitness + individual constraints using cloned problem
    let mut objective = Some(problem.objective);
    let mut constraints = problem.constraints.into_iter();

    let objectives: [Box<dyn FitnessFunction<In = SVector<f64, DIM>, Out = f64, Err = Infallible>>; CONSTRS_PLUS_ONE] = std::array::from_fn(move |i| {
        let val: Box<dyn FitnessFunction<In = SVector<f64, DIM>, Out = f64, Err = Infallible>> = if i == 0 {
            let obj = objective.take().expect("Taken already!");
            Box::new(obj)
        } else {
            Box::new(SingleConstraintFitness::new(constraints.next().unwrap(), capped))
        };

        val
    });

    let mut feasible_fractions = Vec::with_capacity(iterations);

    let result = nsga_2(
        initial_population,
        parents_count,
        objectives,
        &mut pairing,
        &mut crossover,
        &mut mutation,
        &better_than,
        iterations,
        rng,
        |_iteration: usize, _stats: &EvolutionStats<SVector<f64, DIM>, _>, population: &EvaluatedPopulation<SVector<f64, DIM>, _>| {
            // Calculate feasible fraction - all constraints (objectives 1 and 2) must be <= 0
            let feasible_count: f64 =
                population.population.iter().filter(
                    |individual| {
                        individual.evaluation.evaluations
                            .iter()
                            .skip(1)
                            .all(|&eval| eval <= 0.0)
                    }
                ).count() as f64;

            let feasible_fraction = feasible_count as f64 / population.population.len() as f64;
            feasible_fractions.push(feasible_fraction);
        },
        |_, evaluation, best_candidate| {
            // Only save feasible solutions (all constraints satisfied)
            if (1..3).any(|i| evaluation.evaluations[i] > 0.0) {
                return false;
            }

            if best_candidate.is_none() {
                return true;
            }

            // Compare based on fitness (first objective)
            evaluation.evaluations[0] < best_candidate.as_ref().unwrap().evaluated_chromosome.evaluation.evaluations[0]
        }
    )?;

    Ok((result, feasible_fractions))
}

const ITERATIONS: usize = 1000;
const POPULATION: usize = 500;
const PARENTS_COUNT: usize = 500;
const G11_EPS: f64 = 0.00015;

fn handle_g06_srank() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g06();
    let config = StochasticRankingConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        n_param: 2 * POPULATION,
        p_param: 0.45,
        mutation_std_dev: 1.0,
    };
    run_stochastic_ranking(problem, config)
}

fn handle_g08_srank() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g08();
    let config = StochasticRankingConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        n_param: 2 * POPULATION,
        p_param: 0.45,
        mutation_std_dev: 0.5,
    };
    run_stochastic_ranking(problem, config)
}

fn handle_g11_srank() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g11(G11_EPS);
    let config = StochasticRankingConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        n_param: POPULATION * 2,

        // population_size: POPULATION,
        // parents_count: PARENTS_COUNT,
        // iterations: ITERATIONS,
        // n_param: 2 * POPULATION,

        p_param: 0.05,
        mutation_std_dev: 0.01 / 50.0,
    };
    run_stochastic_ranking(problem, config)
}

fn handle_g24_srank() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g24();
    let config = StochasticRankingConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        n_param: 2 * POPULATION,
        p_param: 0.45,
        mutation_std_dev: 0.1,
    };
    run_stochastic_ranking(problem, config)
}

/// Generic function to save evolution results to CSV files with date-based naming
fn save_evolution_results<const DIM: usize, const CONSTRAINTS: usize, TEval: std::fmt::Debug>(
    method: &str,
    problem: &ConstrainedProblem<DIM, CONSTRAINTS>,
    evolution_result: &EvolutionResult<SVector<f64, DIM>, TEval>,
    feasible_fractions: &[f64],
) -> Result<(), Box<dyn std::error::Error>> {
    // Get current date and time for unique file naming
    let now = Local::now();
    let timestamp = now.format("%Y%m%d_%H%M%S").to_string();

    // Create output directories
    let output_dir = format!("solutions/{}/{}", method, problem.name);
    let feasible_dir = format!("{}/feasible_fraction", output_dir);
    fs::create_dir_all(&output_dir)?;
    fs::create_dir_all(&feasible_dir)?;

    // Write best candidates CSV with timestamp
    let best_candidates_path = format!("{}/best_candidates_{}.csv", output_dir, timestamp);
    let mut best_file = fs::File::create(&best_candidates_path)?;
    writeln!(best_file, "iteration,evaluation,fitness")?;

    // Write evolution stats (best candidates through iterations)
    for candidate in &evolution_result.stats.best_candidates {
        writeln!(best_file, "{},{:?}", candidate.evaluation, candidate.evaluated_chromosome.evaluation)?;
    }

    // Write final best candidate and total evaluations
    if let Some(ref best_candidate) = evolution_result.best_candidate {
        writeln!(best_file, "{},{:?}", evolution_result.evaluations, best_candidate.evaluation)?;
    }

    // Write feasible fractions CSV with timestamp
    let feasible_path = format!("{}/feasible_fractions_{}.csv", feasible_dir, timestamp);
    let mut feasible_file = fs::File::create(&feasible_path)?;
    writeln!(feasible_file, "iteration,feasible_fraction")?;

    for (i, fraction) in feasible_fractions.iter().enumerate() {
        writeln!(feasible_file, "{},{}", i, fraction)?;
    }

    println!("Results saved to:");
    println!("  Best candidates: {}", best_candidates_path);
    println!("  Feasible fractions: {}", feasible_path);

    Ok(())
}

fn run_stochastic_ranking<const DIM: usize, const CONSTRAINTS: usize>(
    problem: ConstrainedProblem<DIM, CONSTRAINTS>,
    config: StochasticRankingConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::rng();

    let result = solve_with_stochastic_ranking(
        problem.clone(),
        config.population_size,
        config.parents_count,
        config.iterations,
        (config.n_param, config.p_param),
        config.mutation_std_dev,
        &mut rng,
    )?;

    let (evolution_result, feasible_fractions) = result;

    // Save results to CSV files
    save_evolution_results("srank", &problem, &evolution_result, &feasible_fractions)?;

    if let Some(best_candidate) = evolution_result.best_candidate {
        println!("Best solution found:");
        println!("  Chromosome: {:?}", best_candidate.chromosome);
        println!(
            "  Fitness: {} ({} %)",
            best_candidate.evaluation,
            ((best_candidate.evaluation - problem.optimal_value) / problem.optimal_value).abs() * 100.0);
        println!("  Iterations: {}", evolution_result.iterations);
        println!("  Evaluations: {}", evolution_result.evaluations);
        println!("  Final feasible fraction: {:.2}%", feasible_fractions.last().unwrap_or(&0.0) * 100.0);

        // Sanity check: verify the best candidate is feasible
        let best_chromosome = &best_candidate.chromosome;

        println!("\nFeasibility check for best solution:");
        for (i, constraint) in problem.constraints.iter().enumerate() {
            match constraint.evaluate(best_chromosome) {
                Ok(value) => {
                    let is_feasible = value <= 0.0;
                    println!("  Constraint {}: {} ({})", i+1, value, if is_feasible { "FEASIBLE" } else { "INFEASIBLE" });
                }
                Err(e) => {
                    println!("  Constraint {}: Error evaluating - {}", i+1, e);
                }
            }
        }
    } else {
        println!("Could not find any feasible solution!")
    }

    Ok(())
}

fn run_nsga_ii<const DIM: usize, const CONSTRAINTS: usize>(
    problem: ConstrainedProblem<DIM, CONSTRAINTS>,
    config: NsgaConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::rng();

    let result = solve_with_nsga_ii(
        problem.clone(),
        config.population_size,
        config.parents_count,
        config.iterations,
        config.mutation_std_dev,
        &mut rng,
    )?;

    let (evolution_result, feasible_fractions) = result;

    // Save results to CSV files
    save_evolution_results("nsga", &problem, &evolution_result.clone().map(|x| x[0]), &feasible_fractions)?;

    if let Some(best_candidate) = evolution_result.best_candidate {
        println!("Best solution found:");
        println!("  Chromosome: {:?}", best_candidate.chromosome);
        println!("  Objectives: {:?} ({} %)", best_candidate.evaluation, ((best_candidate.evaluation[0] - problem.optimal_value) / problem.optimal_value).abs() * 100.0);
        println!("  Iterations: {}", evolution_result.iterations);
        println!("  Evaluations: {}", evolution_result.evaluations);
        println!("  Final feasible fraction: {:.2}%", feasible_fractions.last().unwrap_or(&0.0) * 100.0);

        // Sanity check: verify the best candidate is feasible
        let best_chromosome = &best_candidate.chromosome;

        println!("\nFeasibility check for best solution:");
        for (i, constraint) in problem.constraints.iter().enumerate() {
            match constraint.evaluate(best_chromosome) {
                Ok(value) => {
                    let is_feasible = value <= 0.0;
                    println!("  Constraint {}: {} ({})", i+1, value, if is_feasible { "FEASIBLE" } else { "INFEASIBLE" });
                }
                Err(e) => {
                    println!("  Constraint {}: Error evaluating - {}", i+1, e);
                }
            }
        }
    } else {
        println!("Could not find any feasible solution!")
    }

    Ok(())
}

fn run_nsga_multi<const DIM: usize, const CONSTRAINTS: usize, const CONSTRS_PLUS_ONE: usize>(
    problem: ConstrainedProblem<DIM, CONSTRAINTS>,
    evolution_result: EvolutionResult<SVector<f64, DIM>, [f64; CONSTRS_PLUS_ONE]>,
    feasible_fractions: Vec<f64>,
    capped: bool
) -> Result<(), Box<dyn std::error::Error>> {
    // Unfortunately Rustc doesn't support addition in generics...
    assert_eq!(CONSTRAINTS + 1, CONSTRS_PLUS_ONE);

    // Save results to CSV files
    if capped {
        save_evolution_results("nsga_multi", &problem, &evolution_result.clone().map(|x| x[0]), &feasible_fractions)?;
    } else {
        save_evolution_results("nsga_multi_noncapped", &problem, &evolution_result.clone().map(|x| x[0]), &feasible_fractions)?;
    }

    if let Some(best_candidate) = evolution_result.best_candidate {
        println!("Best solution found:");
        println!("  Chromosome: {:?}", best_candidate.chromosome);
        println!("  Objectives: {:?} ({} %)", best_candidate.evaluation, ((best_candidate.evaluation[0] - problem.optimal_value) / problem.optimal_value).abs() * 100.0);
        println!("  Iterations: {}", evolution_result.iterations);
        println!("  Evaluations: {}", evolution_result.evaluations);
        println!("  Final feasible fraction: {:.2}%", feasible_fractions.last().unwrap_or(&0.0) * 100.0);

        // Sanity check: verify the best candidate is feasible
        let best_chromosome = &best_candidate.chromosome;

        println!("\nFeasibility check for best solution:");
        for (i, constraint) in problem.constraints.iter().enumerate() {
            match constraint.evaluate(best_chromosome) {
                Ok(value) => {
                    let is_feasible = value <= 0.0;
                    println!("  Constraint {}: {} ({})", i+1, value, if is_feasible { "FEASIBLE" } else { "INFEASIBLE" });
                }
                Err(e) => {
                    println!("  Constraint {}: Error evaluating - {}", i+1, e);
                }
            }
        }
    } else {
        println!("Could not find any feasible solution!")
    }

    Ok(())
}

// NSGA-II handler functions
fn handle_g06_nsga() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g06();
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 1.0,
    };
    run_nsga_ii(problem, config)
}

fn handle_g08_nsga() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g08();
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.5,
    };
    run_nsga_ii(problem, config)
}

fn handle_g11_nsga() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g11(G11_EPS);
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.01 / 50.0,
    };
    run_nsga_ii(problem, config)
}

fn handle_g24_nsga() -> Result<(), Box<dyn std::error::Error>> {
    let problem = problem_g24();
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.1,
    };
    run_nsga_ii(problem, config)
}

// NSGA-Multi handler functions for individual problems
fn handle_nsga_multi_g06(capped: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::rng();
    let problem = problem_g06();
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.5,
    };

    let result = solve_with_nsga_multi::<2, 2, 3>(
        problem.clone(),
        config.population_size,
        config.parents_count,
        config.iterations,
        config.mutation_std_dev,
        &mut rng,
        capped
    )?;

    let (evolution_result, feasible_fractions) = result;
    run_nsga_multi(problem, evolution_result, feasible_fractions, capped)
}

fn handle_nsga_multi_g08(capped: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::rng();
    let problem = problem_g08();
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.5,
    };

    let result = solve_with_nsga_multi::<2, 2, 3>(
        problem.clone(),
        config.population_size,
        config.parents_count,
        config.iterations,
        config.mutation_std_dev,
        &mut rng,
        capped
    )?;

    let (evolution_result, feasible_fractions) = result;
    run_nsga_multi(problem, evolution_result, feasible_fractions, capped)
}

fn handle_nsga_multi_g11(capped: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::rng();
    let problem = problem_g11(G11_EPS);
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.01 / 50.0,
    };

    let result = solve_with_nsga_multi::<2, 1, 2>(
        problem.clone(),
        config.population_size,
        config.parents_count,
        config.iterations,
        config.mutation_std_dev,
        &mut rng,
        capped
    )?;

    let (evolution_result, feasible_fractions) = result;
    run_nsga_multi(problem, evolution_result, feasible_fractions, capped)
}

fn handle_nsga_multi_g24(capped: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::rng();
    let problem = problem_g24();
    let config = NsgaConfig {
        population_size: POPULATION,
        parents_count: PARENTS_COUNT,
        iterations: ITERATIONS,
        mutation_std_dev: 0.1,
    };

    let result = solve_with_nsga_multi::<2, 2, 3>(
        problem.clone(),
        config.population_size,
        config.parents_count,
        config.iterations,
        config.mutation_std_dev,
        &mut rng,
        capped
    )?;

    let (evolution_result, feasible_fractions) = result;
    run_nsga_multi(problem, evolution_result, feasible_fractions, capped)
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() != 3 {
        eprintln!("Usage: {} <method> <problem>", args[0]);
        eprintln!("Methods: srank, nsga, nsga_multi, nsga_multi_noncapped");
        eprintln!("Problems: g06, g08, g11, g24");
        std::process::exit(1);
    }

    let method = &args[1];
    let problem = &args[2];

    let result = match (method.as_str(), problem.as_str()) {
        ("srank", "g06") => handle_g06_srank(),
        ("srank", "g08") => handle_g08_srank(),
        ("srank", "g11") => handle_g11_srank(),
        ("srank", "g24") => handle_g24_srank(),
        ("nsga", "g06") => handle_g06_nsga(),
        ("nsga", "g08") => handle_g08_nsga(),
        ("nsga", "g11") => handle_g11_nsga(),
        ("nsga", "g24") => handle_g24_nsga(),
        ("nsga_multi", "g06") => handle_nsga_multi_g06(true),
        ("nsga_multi", "g08") => handle_nsga_multi_g08(true),
        ("nsga_multi", "g11") => handle_nsga_multi_g11(true),
        ("nsga_multi", "g24") => handle_nsga_multi_g24(true),
        ("nsga_multi_noncapped", "g06") => handle_nsga_multi_g06(false),
        ("nsga_multi_noncapped", "g08") => handle_nsga_multi_g08(false),
        ("nsga_multi_noncapped", "g11") => handle_nsga_multi_g11(false),
        ("nsga_multi_noncapped", "g24") => handle_nsga_multi_g24(false),
        (_, _) => {
            eprintln!("Invalid method '{}' or problem '{}'", method, problem);
            eprintln!("Methods: srank, nsga, nsga_multi, nsga_multi_noncapped");
            eprintln!("Problems: g06, g08, g11, g24");
            std::process::exit(1);
        }
    };

    if let Err(e) = result {
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}