numrs2 0.3.3

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
//! Multi-Objective Test Problems Showcase
//!
//! This example demonstrates all available multi-objective test problems in NumRS2,
//! including the ZDT (bi-objective) and DTLZ (many-objective) suites. It showcases
//! problem characteristics, true Pareto fronts, and algorithm performance comparison.
//!
//! # Test Problem Suites
//!
//! ## ZDT Suite (Bi-objective)
//! - **ZDT1**: Convex Pareto front
//! - **ZDT2**: Non-convex (concave) Pareto front
//! - **ZDT3**: Disconnected Pareto front (5 regions)
//!
//! ## DTLZ Suite (Scalable Many-objective)
//! - **DTLZ1**: Linear Pareto front, highly multi-modal (3^k local fronts)
//! - **DTLZ2**: Concave/spherical Pareto front, unimodal
//! - **DTLZ3**: Concave Pareto front, highly multi-modal (3^k local fronts)
//! - **DTLZ7**: Disconnected Pareto regions, mixed shape
//!
//! # Topics Covered
//!
//! 1. **Problem Characteristics**: Understanding each test problem
//! 2. **True Pareto Fronts**: Generating and visualizing optimal fronts
//! 3. **Algorithm Comparison**: NSGA-II vs NSGA-III performance
//! 4. **Problem Selection**: Choosing the right problem for benchmarking
//! 5. **Validation**: Verifying algorithm correctness
//!
//! Run with: `cargo run --example optimization_test_problems --release`

#![allow(clippy::type_complexity)]

use numrs2::optimize::nsga2::{nsga2, NSGA2Config, QualityMetricsConfig};
use numrs2::optimize::nsga3::{nsga3, NSGA3Config};
use numrs2::optimize::test_problems::{TestProblem, DTLZ1, DTLZ2, DTLZ3, DTLZ7, ZDT1, ZDT2, ZDT3};
use std::time::Instant;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("╔═══════════════════════════════════════════════════════════╗");
    println!("║        Multi-Objective Test Problems Showcase             ║");
    println!("║                   NumRS2 v0.2.0                           ║");
    println!("╚═══════════════════════════════════════════════════════════╝\n");

    // Example 1: ZDT test suite overview
    example1_zdt_suite()?;

    // Example 2: DTLZ test suite overview
    example2_dtlz_suite()?;

    // Example 3: Pareto front generation and validation
    example3_pareto_fronts()?;

    // Example 4: Algorithm performance comparison
    example4_algorithm_comparison()?;

    // Example 5: Problem selection guide
    example5_problem_selection_guide()?;

    println!("\n╔═══════════════════════════════════════════════════════════╗");
    println!("║     All Test Problem Examples Completed Successfully!     ║");
    println!("╚═══════════════════════════════════════════════════════════╝");

    Ok(())
}

/// Example 1: ZDT Test Suite Overview
///
/// Demonstrates all ZDT problems and their characteristics.
fn example1_zdt_suite() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 1: ZDT Test Suite (Bi-objective Problems)");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("The ZDT suite consists of bi-objective problems designed to test");
    println!("different aspects of multi-objective optimization algorithms.\n");

    // ZDT1: Convex front
    {
        println!("ZDT1: Convex Pareto Front");
        println!("─────────────────────────");
        println!("Characteristics:");
        println!("  • Objectives:    2 (minimize both)");
        println!("  • Variables:     30 (standard)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Convex, continuous");
        println!("  • Difficulty:    Easy (good convergence test)");
        println!();

        let problem = ZDT1::new(30);
        println!("Mathematical formulation:");
        println!("  f1(x) = x1");
        println!("  g(x)  = 1 + 9 * sum(x2...x30) / 29");
        println!("  f2(x) = g(x) * [1 - sqrt(f1/g)]");
        println!();
        println!("Pareto-optimal solutions:");
        println!("  x1 ∈ [0, 1], xi = 0 for i > 1");
        println!("  Pareto front: f2 = 1 - sqrt(f1) for f1 ∈ [0, 1]");
        println!();

        // Generate and display sample Pareto front
        let pareto_front: Vec<Vec<f64>> = problem.generate_pareto_front(5);
        println!("Sample true Pareto front points:");
        for (i, point) in pareto_front.iter().enumerate() {
            println!("  Point {}: f1={:.4}, f2={:.4}", i + 1, point[0], point[1]);
        }
        println!();
    }

    // ZDT2: Non-convex front
    {
        println!("ZDT2: Non-convex (Concave) Pareto Front");
        println!("───────────────────────────────────────");
        println!("Characteristics:");
        println!("  • Objectives:    2 (minimize both)");
        println!("  • Variables:     30 (standard)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Non-convex (concave), continuous");
        println!("  • Difficulty:    Moderate (tests diversity preservation)");
        println!();

        let problem = ZDT2::new(30);
        println!("Mathematical formulation:");
        println!("  f1(x) = x1");
        println!("  g(x)  = 1 + 9 * sum(x2...x30) / 29");
        println!("  f2(x) = g(x) * [1 - (f1/g)²]");
        println!();
        println!("Pareto front: f2 = 1 - f1² for f1 ∈ [0, 1]");
        println!();

        let pareto_front: Vec<Vec<f64>> = problem.generate_pareto_front(5);
        println!("Sample true Pareto front points:");
        for (i, point) in pareto_front.iter().enumerate() {
            println!("  Point {}: f1={:.4}, f2={:.4}", i + 1, point[0], point[1]);
        }
        println!();
    }

    // ZDT3: Disconnected front
    {
        println!("ZDT3: Disconnected Pareto Front");
        println!("───────────────────────────────");
        println!("Characteristics:");
        println!("  • Objectives:    2 (minimize both)");
        println!("  • Variables:     30 (standard)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Disconnected (5 separate regions)");
        println!("  • Difficulty:    Hard (tests diversity in disconnected regions)");
        println!();

        let problem = ZDT3::new(30);
        println!("Mathematical formulation:");
        println!("  f1(x) = x1");
        println!("  g(x)  = 1 + 9 * sum(x2...x30) / 29");
        println!("  f2(x) = g(x) * [1 - sqrt(f1/g) - (f1/g)*sin(10π*f1)]");
        println!();
        println!("The sine term creates 5 disconnected Pareto-optimal regions.");
        println!();

        let pareto_front: Vec<Vec<f64>> = problem.generate_pareto_front(10);
        println!("Sample true Pareto front points (showing disconnected regions):");
        for (i, point) in pareto_front.iter().enumerate() {
            println!("  Point {}: f1={:.4}, f2={:.4}", i + 1, point[0], point[1]);
        }
        println!();
    }

    println!("✓ ZDT suite overview completed\n");
    Ok(())
}

/// Example 2: DTLZ Test Suite Overview
///
/// Demonstrates all DTLZ problems and their characteristics.
fn example2_dtlz_suite() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 2: DTLZ Test Suite (Many-objective Problems)");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("The DTLZ suite consists of scalable multi-objective problems");
    println!("that can be configured for any number of objectives (M ≥ 2).\n");

    // DTLZ1: Linear front
    {
        println!("DTLZ1: Linear Pareto Front");
        println!("──────────────────────────");
        let n_obj = 3;
        let n_vars = n_obj + 5 - 1; // Using k=5 for example
        let problem = DTLZ1::new(n_obj, n_vars);

        println!("Characteristics:");
        println!("  • Objectives:    Scalable (M ≥ 2)");
        println!("  • Variables:     n = M + k - 1 (typically k=5)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Linear (simplex)");
        println!("  • Difficulty:    Very hard - 3^k local Pareto fronts");
        println!(
            "  • Example (M=3, k=5): {} variables, 243 local fronts",
            n_vars
        );
        println!();

        println!("Pareto-optimal solutions:");
        println!("  Sum of objectives = 0.5");
        println!("  Linear hyperplane in objective space");
        println!();

        let pareto_front = problem.generate_pareto_front(5);
        println!("Sample Pareto front (3 objectives):");
        for (i, point) in pareto_front.iter().enumerate() {
            print!("  Point {}: ", i + 1);
            for (j, &obj) in point.iter().enumerate() {
                print!("f{}={:.4}", j + 1, obj);
                if j < point.len() - 1 {
                    print!(", ");
                }
            }
            let sum: f64 = point.iter().sum();
            println!(" (sum={:.4})", sum);
        }
        println!();
    }

    // DTLZ2: Concave front
    {
        println!("DTLZ2: Concave/Spherical Pareto Front");
        println!("─────────────────────────────────────");
        let n_obj = 3;
        let n_vars = n_obj + 10 - 1;
        let problem = DTLZ2::new(n_obj, n_vars);

        println!("Characteristics:");
        println!("  • Objectives:    Scalable (M ≥ 2)");
        println!("  • Variables:     n = M + k - 1 (typically k=10)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Concave (spherical with radius 1)");
        println!("  • Difficulty:    Moderate - unimodal, good baseline");
        println!("  • Example (M=3, k=10): {} variables", n_vars);
        println!();

        println!("Pareto-optimal solutions:");
        println!("  Sum of objective squares = 1");
        println!("  Spherical surface in objective space");
        println!();

        let pareto_front: Vec<Vec<f64>> = problem.generate_pareto_front(5);
        println!("Sample Pareto front (3 objectives):");
        for (i, point) in pareto_front.iter().enumerate() {
            print!("  Point {}: ", i + 1);
            for (j, &obj) in point.iter().enumerate() {
                print!("f{}={:.4}", j + 1, obj);
                if j < point.len() - 1 {
                    print!(", ");
                }
            }
            let radius_sq: f64 = point.iter().map(|&x: &f64| x * x).sum();
            println!(" (r²={:.4})", radius_sq);
        }
        println!();
    }

    // DTLZ3: Multi-modal concave
    {
        println!("DTLZ3: Multi-modal Concave Pareto Front");
        println!("───────────────────────────────────────");
        let n_obj = 3;
        let n_vars = n_obj + 10 - 1;

        println!("Characteristics:");
        println!("  • Objectives:    Scalable (M ≥ 2)");
        println!("  • Variables:     n = M + k - 1 (typically k=10)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Concave (same as DTLZ2)");
        println!("  • Difficulty:    Very hard - 3^k local fronts (like DTLZ1)");
        println!(
            "  • Example (M=3, k=10): {} variables, 59,049 local fronts!",
            n_vars
        );
        println!();

        println!("DTLZ3 = DTLZ2 shape + DTLZ1 multi-modality");
        println!("Most challenging problem in the DTLZ suite.");
        println!();
    }

    // DTLZ7: Disconnected regions
    {
        println!("DTLZ7: Disconnected Pareto Regions");
        println!("──────────────────────────────────");
        let n_obj = 3;
        let n_vars = n_obj + 20 - 1;

        println!("Characteristics:");
        println!("  • Objectives:    Scalable (M ≥ 2)");
        println!("  • Variables:     n = M + k - 1 (typically k=20)");
        println!("  • Bounds:        [0, 1] for all variables");
        println!("  • Front shape:   Disconnected, mixed");
        println!("  • Difficulty:    Hard - tests diversity in disconnected regions");
        println!(
            "  • Example (M=3, k=20): {} variables, 2^(M-1) regions",
            n_vars
        );
        println!();

        println!("The Pareto front consists of 2^(M-1) disconnected regions.");
        println!("For M=3: 4 disconnected regions in objective space.");
        println!();
    }

    println!("✓ DTLZ suite overview completed\n");
    Ok(())
}

/// Example 3: Pareto Front Generation
///
/// Demonstrates generating true Pareto fronts and their properties.
fn example3_pareto_fronts() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 3: True Pareto Front Generation and Validation");
    println!("═══════════════════════════════════════════════════════════\n");

    // Generate fronts with different resolutions
    let resolutions = vec![10, 50, 100];

    println!("ZDT1 Pareto Front Generation:");
    println!("─────────────────────────────");
    let problem = ZDT1::new(30);

    for &n_points in &resolutions {
        let start = Instant::now();
        let pareto_front = problem.generate_pareto_front(n_points);
        let duration = start.elapsed();

        println!("  {} points: generated in {:?}", n_points, duration);

        // Validate properties
        let mut min_f1 = f64::MAX;
        let mut max_f1 = f64::MIN;
        let mut min_f2 = f64::MAX;
        let mut max_f2 = f64::MIN;

        for point in &pareto_front {
            min_f1 = min_f1.min(point[0]);
            max_f1 = max_f1.max(point[0]);
            min_f2 = min_f2.min(point[1]);
            max_f2 = max_f2.max(point[1]);
        }

        println!("    f1 range: [{:.4}, {:.4}]", min_f1, max_f1);
        println!("    f2 range: [{:.4}, {:.4}]", min_f2, max_f2);
    }
    println!();

    // DTLZ2 with different objective counts
    println!("DTLZ2 Pareto Front Generation (Different Objectives):");
    println!("──────────────────────────────────────────────────────");

    for n_obj in 2..=5 {
        let n_vars = n_obj + 10 - 1;
        let problem = DTLZ2::new(n_obj, n_vars);

        let start = Instant::now();
        let pareto_front: Vec<Vec<f64>> = problem.generate_pareto_front(50);
        let duration = start.elapsed();

        println!(
            "  {} objectives: {} points, {:?}",
            n_obj,
            pareto_front.len(),
            duration
        );

        // Validate spherical constraint (sum of squares = 1)
        let mut total_error = 0.0;
        for point in &pareto_front {
            let radius_sq: f64 = point.iter().map(|&x: &f64| x * x).sum();
            total_error += (radius_sq - 1.0).abs();
        }
        let avg_error = total_error / pareto_front.len() as f64;

        println!(
            "    Sphere constraint error: {:.6} (should be ~0)",
            avg_error
        );
    }
    println!();

    // Verify non-domination property
    println!("Pareto Front Validation:");
    println!("────────────────────────");
    let problem = ZDT2::new(30);
    let pareto_front: Vec<Vec<f64>> = problem.generate_pareto_front(20);

    println!("Checking non-domination property for ZDT2...");
    let mut dominated_count = 0;

    for i in 0..pareto_front.len() {
        for j in 0..pareto_front.len() {
            if i != j {
                // Check if point i dominates point j
                let dominates = pareto_front[i][0] <= pareto_front[j][0]
                    && pareto_front[i][1] <= pareto_front[j][1]
                    && (pareto_front[i][0] < pareto_front[j][0]
                        || pareto_front[i][1] < pareto_front[j][1]);

                if dominates {
                    dominated_count += 1;
                }
            }
        }
    }

    if dominated_count == 0 {
        println!("  ✓ All points are non-dominated (valid Pareto front)");
    } else {
        println!(
            "  ✗ Found {} dominated points (should be 0)",
            dominated_count
        );
    }

    println!("\n✓ Pareto front generation demonstrated successfully\n");
    Ok(())
}

/// Example 4: Algorithm Performance Comparison
///
/// Compares NSGA-II and NSGA-III on different problem types.
fn example4_algorithm_comparison() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 4: Algorithm Performance Comparison");
    println!("═══════════════════════════════════════════════════════════\n");

    struct BenchmarkResult {
        problem: String,
        algorithm: String,
        objectives: usize,
        pareto_size: usize,
        time: std::time::Duration,
        igd: Option<f64>,
    }

    let mut results = Vec::new();

    // Test 1: NSGA-II on ZDT1
    {
        println!("Testing NSGA-II on ZDT1...");
        let problem = ZDT1::new(30);
        let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = vec![
            Box::new(|x: &[f64]| problem.evaluate(x)[0]),
            Box::new(|x: &[f64]| problem.evaluate(x)[1]),
        ];
        let bounds = problem.bounds();
        let reference_front = problem.generate_pareto_front(100);

        let config = NSGA2Config {
            pop_size: 100,
            max_generations: 150,
            quality_metrics_config: Some(QualityMetricsConfig {
                calculate_spacing: false,
                calculate_spread: false,
                reference_front: Some(reference_front),
            }),
            ..Default::default()
        };

        let start = Instant::now();
        let result = nsga2(
            &objectives.iter().map(|f| f.as_ref()).collect::<Vec<_>>(),
            &bounds,
            Some(config),
        )?;
        let duration = start.elapsed();

        results.push(BenchmarkResult {
            problem: "ZDT1".to_string(),
            algorithm: "NSGA-II".to_string(),
            objectives: 2,
            pareto_size: result.pareto_front.len(),
            time: duration,
            igd: result.igd,
        });
        println!("  ✓ Completed\n");
    }

    // Test 2: NSGA-II on ZDT3 (challenging)
    {
        println!("Testing NSGA-II on ZDT3...");
        let problem = ZDT3::new(30);
        let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = vec![
            Box::new(|x: &[f64]| problem.evaluate(x)[0]),
            Box::new(|x: &[f64]| problem.evaluate(x)[1]),
        ];
        let bounds = problem.bounds();
        let reference_front = problem.generate_pareto_front(100);

        let config = NSGA2Config {
            pop_size: 100,
            max_generations: 150,
            quality_metrics_config: Some(QualityMetricsConfig {
                calculate_spacing: false,
                calculate_spread: false,
                reference_front: Some(reference_front),
            }),
            ..Default::default()
        };

        let start = Instant::now();
        let result = nsga2(
            &objectives.iter().map(|f| f.as_ref()).collect::<Vec<_>>(),
            &bounds,
            Some(config),
        )?;
        let duration = start.elapsed();

        results.push(BenchmarkResult {
            problem: "ZDT3".to_string(),
            algorithm: "NSGA-II".to_string(),
            objectives: 2,
            pareto_size: result.pareto_front.len(),
            time: duration,
            igd: result.igd,
        });
        println!("  ✓ Completed\n");
    }

    // Test 3: NSGA-III on DTLZ2 (3 objectives)
    {
        println!("Testing NSGA-III on DTLZ2 (3 objectives)...");
        let problem = DTLZ2::new(3, 12);
        let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = (0..3)
            .map(|i| {
                let prob = problem.clone();
                Box::new(move |x: &[f64]| prob.evaluate(x)[i]) as Box<dyn Fn(&[f64]) -> f64>
            })
            .collect();
        let bounds = problem.bounds();

        let config = NSGA3Config {
            pop_size: 92,
            max_generations: 150,
            n_divisions: 12,
            ..Default::default()
        };

        let start = Instant::now();
        let result = nsga3(
            &objectives.iter().map(|f| f.as_ref()).collect::<Vec<_>>(),
            &bounds,
            Some(config),
        )?;
        let duration = start.elapsed();

        results.push(BenchmarkResult {
            problem: "DTLZ2-3".to_string(),
            algorithm: "NSGA-III".to_string(),
            objectives: 3,
            pareto_size: result.pareto_front.len(),
            time: duration,
            igd: None,
        });
        println!("  ✓ Completed\n");
    }

    // Test 4: NSGA-III on DTLZ2 (5 objectives)
    {
        println!("Testing NSGA-III on DTLZ2 (5 objectives)...");
        let problem = DTLZ2::new(5, 14);
        let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = (0..5)
            .map(|i| {
                let prob = problem.clone();
                Box::new(move |x: &[f64]| prob.evaluate(x)[i]) as Box<dyn Fn(&[f64]) -> f64>
            })
            .collect();
        let bounds = problem.bounds();

        let config = NSGA3Config {
            pop_size: 126,
            max_generations: 200,
            n_divisions: 6,
            ..Default::default()
        };

        let start = Instant::now();
        let result = nsga3(
            &objectives.iter().map(|f| f.as_ref()).collect::<Vec<_>>(),
            &bounds,
            Some(config),
        )?;
        let duration = start.elapsed();

        results.push(BenchmarkResult {
            problem: "DTLZ2-5".to_string(),
            algorithm: "NSGA-III".to_string(),
            objectives: 5,
            pareto_size: result.pareto_front.len(),
            time: duration,
            igd: None,
        });
        println!("  ✓ Completed\n");
    }

    // Display comparison table
    println!("═══════════════════════════════════════════════════════════");
    println!("Performance Comparison Results");
    println!("═══════════════════════════════════════════════════════════\n");

    println!(
        "{:<12} {:<12} {:<10} {:<12} {:<12}",
        "Problem", "Algorithm", "Obj", "PF Size", "Time (sec)"
    );
    println!("{}", "".repeat(65));

    for result in &results {
        println!(
            "{:<12} {:<12} {:<10} {:<12} {:<12.2}",
            result.problem,
            result.algorithm,
            result.objectives,
            result.pareto_size,
            result.time.as_secs_f64()
        );
    }

    println!();
    println!("Observations:");
    println!("  • NSGA-II excels at bi-objective problems (2 objectives)");
    println!("  • NSGA-III required for many-objective problems (3+ objectives)");
    println!("  • Computational cost increases with objectives");
    println!("  • ZDT3 (disconnected) more challenging than ZDT1 (convex)");

    println!("\n✓ Algorithm comparison demonstrated successfully\n");
    Ok(())
}

/// Example 5: Problem Selection Guide
///
/// Provides guidance on selecting appropriate test problems for different
/// benchmarking scenarios.
fn example5_problem_selection_guide() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 5: Test Problem Selection Guide");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("Selecting the Right Test Problem:");
    println!();

    println!("FOR ALGORITHM DEVELOPMENT:");
    println!("──────────────────────────");
    println!("  1. Start with ZDT1 or DTLZ2");
    println!("     - Unimodal, moderate difficulty");
    println!("     - Good for initial development and debugging");
    println!("     - Fast convergence allows quick iteration");
    println!();
    println!("  2. Add ZDT2 for diversity testing");
    println!("     - Non-convex front tests diversity preservation");
    println!("     - Ensures algorithm handles various front shapes");
    println!();
    println!("  3. Use ZDT3 or DTLZ7 for disconnected regions");
    println!("     - Tests ability to maintain diversity in gaps");
    println!("     - Critical for real-world problems");
    println!();

    println!("FOR ALGORITHM COMPARISON:");
    println!("─────────────────────────");
    println!("  1. Use complete ZDT suite (ZDT1-3)");
    println!("     - Standard benchmark for bi-objective algorithms");
    println!("     - Well-studied with known characteristics");
    println!();
    println!("  2. Add DTLZ2 and DTLZ3 for robustness");
    println!("     - DTLZ2: Baseline performance");
    println!("     - DTLZ3: Multi-modal challenge");
    println!();
    println!("  3. Include DTLZ1 or DTLZ7 for completeness");
    println!("     - DTLZ1: Linear front + high multi-modality");
    println!("     - DTLZ7: Disconnected + mixed shape");
    println!();

    println!("FOR SCALABILITY TESTING:");
    println!("────────────────────────");
    println!("  1. Use DTLZ2 with varying objectives");
    println!("     - Test: M = 3, 5, 8, 10, 15");
    println!("     - Evaluate computational scaling");
    println!();
    println!("  2. Add DTLZ3 for stress testing");
    println!("     - Same as DTLZ2 but much harder");
    println!("     - Tests robustness under difficulty");
    println!();

    println!("RECOMMENDED MINIMAL BENCHMARK SET:");
    println!("───────────────────────────────────");
    println!("  Bi-objective:    ZDT1, ZDT2, ZDT3");
    println!("  Many-objective:  DTLZ2 (M=3,5), DTLZ3 (M=3)");
    println!("  Total runtime:   ~5-10 minutes on modern hardware");
    println!();

    println!("PROBLEM CHARACTERISTICS SUMMARY:");
    println!("────────────────────────────────");
    println!();
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "Problem", "Objectives", "Difficulty", "Tests"
    );
    println!("{}", "".repeat(65));
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "ZDT1", "2", "Easy", "Convergence"
    );
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "ZDT2", "2", "Moderate", "Diversity"
    );
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "ZDT3", "2", "Hard", "Disconnected"
    );
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "DTLZ1", "Scalable", "Very Hard", "Multi-modal"
    );
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "DTLZ2", "Scalable", "Moderate", "Baseline"
    );
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "DTLZ3", "Scalable", "Very Hard", "Robustness"
    );
    println!(
        "{:<10} {:<15} {:<20} {:<15}",
        "DTLZ7", "Scalable", "Hard", "Mixed"
    );

    println!("\n✓ Problem selection guide completed\n");
    Ok(())
}