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
//! NSGA-II Multi-Objective Optimization Examples
//!
//! This example demonstrates comprehensive usage of NSGA-II (Non-dominated Sorting
//! Genetic Algorithm II) for solving bi-objective optimization problems using the
//! standard ZDT (Zitzler-Deb-Thiele) test suite.
//!
//! # Topics Covered
//!
//! 1. **Basic NSGA-II Usage**: Solving ZDT1 with default configuration
//! 2. **Quality Metrics**: Using spacing, spread, hypervolume indicators
//! 3. **Convergence Analysis**: IGD and GD metrics with reference fronts
//! 4. **Problem Comparison**: Performance across ZDT1, ZDT2, ZDT3
//! 5. **Configuration Options**: Tuning algorithm parameters
//! 6. **Performance Measurement**: Timing and convergence tracking
//!
//! # Test Problems
//!
//! - **ZDT1**: Convex Pareto front - tests convergence
//! - **ZDT2**: Non-convex (concave) Pareto front - tests diversity
//! - **ZDT3**: Disconnected Pareto front - tests diversity maintenance
//!
//! # Quality Metrics
//!
//! - **Hypervolume**: Volume of objective space dominated by Pareto front
//! - **Spacing (S)**: Uniformity of distribution (lower is better)
//! - **Spread (Δ)**: Extent and uniformity of spread (lower is better)
//! - **IGD**: Inverted Generational Distance - convergence and coverage
//! - **GD**: Generational Distance - convergence to reference front
//!
//! Run with: `cargo run --example optimization_nsga2 --release`

#![allow(clippy::type_complexity)]

use numrs2::optimize::nsga2::{nsga2, HypervolumeConfig, NSGA2Config, QualityMetricsConfig};
use numrs2::optimize::test_problems::{TestProblem, ZDT1, ZDT2, ZDT3};
use std::time::Instant;

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

    // Example 1: Basic NSGA-II usage with ZDT1
    example1_basic_usage()?;

    // Example 2: Using quality metrics (spacing, spread, hypervolume)
    example2_quality_metrics()?;

    // Example 3: Convergence analysis with reference front (IGD, GD)
    example3_convergence_analysis()?;

    // Example 4: Comparing performance across different problems
    example4_problem_comparison()?;

    // Example 5: Advanced configuration and parameter tuning
    example5_advanced_configuration()?;

    println!("\n╔═══════════════════════════════════════════════════════════╗");
    println!("║          All NSGA-II Examples Completed Successfully!      ║");
    println!("╚═══════════════════════════════════════════════════════════╝");

    Ok(())
}

/// Example 1: Basic NSGA-II Usage
///
/// Demonstrates the simplest use case of NSGA-II with default configuration
/// on the ZDT1 test problem (convex Pareto front).
fn example1_basic_usage() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 1: Basic NSGA-II Usage (ZDT1)");
    println!("═══════════════════════════════════════════════════════════\n");

    // Create ZDT1 test problem with 30 decision variables
    let problem = ZDT1::new(30);

    // Define objective functions as closures
    // ZDT1 has two objectives: f1(x) = x[0], f2(x) = g(x) * (1 - sqrt(x[0]/g(x)))
    let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = vec![
        Box::new(|x: &[f64]| {
            let obj = problem.evaluate(x);
            obj[0]
        }),
        Box::new(|x: &[f64]| {
            let obj = problem.evaluate(x);
            obj[1]
        }),
    ];

    // Get variable bounds [0, 1] for all variables
    let bounds = problem.bounds();

    // Use default NSGA-II configuration
    // - Population size: 100
    // - Generations: 100
    // - Crossover rate: 0.9
    // - Mutation rate: 0.1
    let config = NSGA2Config::default();

    println!("Configuration:");
    println!("  Population size:  {}", config.pop_size);
    println!("  Max generations:  {}", config.max_generations);
    println!("  Crossover rate:   {:.2}", config.crossover_rate);
    println!("  Mutation rate:    {:.2}", config.mutation_rate);
    println!("  Variables:        {}", bounds.len());
    println!();

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

    // Display results
    println!("Results:");
    println!("  Pareto front size:      {}", result.pareto_front.len());
    println!("  Total population size:  {}", result.population.len());
    println!("  Generations executed:   {}", result.generations);
    println!("  Execution time:         {:?}", duration);
    println!();

    // Show sample solutions from Pareto front
    println!("Sample Pareto-optimal solutions:");
    let samples = if result.pareto_front.len() > 5 {
        vec![
            0,
            result.pareto_front.len() / 4,
            result.pareto_front.len() / 2,
            3 * result.pareto_front.len() / 4,
            result.pareto_front.len() - 1,
        ]
    } else {
        (0..result.pareto_front.len()).collect()
    };

    for idx in samples {
        let individual = &result.pareto_front[idx];
        println!(
            "  Solution {}: f1={:.6}, f2={:.6}",
            idx + 1,
            individual.objectives[0],
            individual.objectives[1]
        );
    }

    println!("\n✓ Basic usage demonstrated successfully\n");
    Ok(())
}

/// Example 2: Quality Metrics
///
/// Demonstrates how to use quality metrics to evaluate the performance
/// and characteristics of the obtained Pareto front.
fn example2_quality_metrics() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 2: Quality Metrics (ZDT2)");
    println!("═══════════════════════════════════════════════════════════\n");

    // ZDT2 has a non-convex (concave) Pareto front
    let problem = ZDT2::new(30);

    let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = vec![
        Box::new(|x: &[f64]| {
            let obj = problem.evaluate(x);
            obj[0]
        }),
        Box::new(|x: &[f64]| {
            let obj = problem.evaluate(x);
            obj[1]
        }),
    ];

    let bounds = problem.bounds();

    // Configure NSGA-II with quality metrics enabled
    let config = NSGA2Config {
        pop_size: 100,
        max_generations: 150,
        quality_metrics_config: Some(QualityMetricsConfig {
            calculate_spacing: true, // Measure distribution uniformity
            calculate_spread: true,  // Measure extent and uniformity
            reference_front: None,   // Will add in next example
        }),
        hypervolume_config: Some(HypervolumeConfig {
            reference_point: vec![2.0, 2.0], // Must dominate all solutions
        }),
        ..Default::default()
    };

    println!("ZDT2 Problem Characteristics:");
    println!("  Type: Non-convex (concave) Pareto front");
    println!("  Tests: Diversity preservation in algorithms");
    println!();

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

    println!("Optimization Results:");
    println!("  Pareto front size: {}", result.pareto_front.len());
    println!("  Execution time:    {:?}", duration);
    println!();

    // Display quality metrics
    println!("Quality Metrics:");

    if let Some(hv) = result.hypervolume {
        println!("  Hypervolume (HV):  {:.6}", hv);
        println!("    - Measures volume of objective space dominated by front");
        println!("    - Higher is better (more coverage)");
    }

    if let Some(spacing) = result.spacing {
        println!("  Spacing (S):       {:.6}", spacing);
        println!("    - Measures uniformity of distribution");
        println!("    - Lower is better (more uniform)");
        println!("    - S=0 means perfectly uniform distribution");
    }

    if let Some(spread) = result.spread {
        println!("  Spread (Δ):        {:.6}", spread);
        println!("    - Measures extent and uniformity of spread");
        println!("    - Lower is better (better spread)");
        println!("    - Δ=0 means perfect spread and uniformity");
    }

    // Analyze objective space coverage
    let mut f1_min = f64::MAX;
    let mut f1_max = f64::MIN;
    let mut f2_min = f64::MAX;
    let mut f2_max = f64::MIN;

    for individual in &result.pareto_front {
        f1_min = f1_min.min(individual.objectives[0]);
        f1_max = f1_max.max(individual.objectives[0]);
        f2_min = f2_min.min(individual.objectives[1]);
        f2_max = f2_max.max(individual.objectives[1]);
    }

    println!();
    println!("Objective Space Coverage:");
    println!("  f1 range: [{:.6}, {:.6}]", f1_min, f1_max);
    println!("  f2 range: [{:.6}, {:.6}]", f2_min, f2_max);

    println!("\n✓ Quality metrics demonstrated successfully\n");
    Ok(())
}

/// Example 3: Convergence Analysis
///
/// Demonstrates convergence analysis using IGD (Inverted Generational Distance)
/// and GD (Generational Distance) metrics with a reference Pareto front.
fn example3_convergence_analysis() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 3: Convergence Analysis (ZDT1)");
    println!("═══════════════════════════════════════════════════════════\n");

    let problem = ZDT1::new(30);

    let objectives: Vec<Box<dyn Fn(&[f64]) -> f64>> = vec![
        Box::new(|x: &[f64]| {
            let obj = problem.evaluate(x);
            obj[0]
        }),
        Box::new(|x: &[f64]| {
            let obj = problem.evaluate(x);
            obj[1]
        }),
    ];

    let bounds = problem.bounds();

    // Generate true Pareto front for ZDT1 as reference
    println!("Generating reference Pareto front (100 points)...");
    let reference_front = problem.generate_pareto_front(100);
    println!(
        "Reference front generated: {} points",
        reference_front.len()
    );
    println!();

    // Configure NSGA-II with reference front for convergence metrics
    let config = NSGA2Config {
        pop_size: 100,
        max_generations: 200,
        quality_metrics_config: Some(QualityMetricsConfig {
            calculate_spacing: true,
            calculate_spread: true,
            reference_front: Some(reference_front.clone()),
        }),
        hypervolume_config: Some(HypervolumeConfig {
            reference_point: vec![2.0, 2.0],
        }),
        ..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();

    println!("Optimization Results:");
    println!("  Pareto front size: {}", result.pareto_front.len());
    println!("  Generations:       {}", result.generations);
    println!("  Execution time:    {:?}", duration);
    println!();

    println!("Convergence Metrics:");

    if let Some(igd) = result.igd {
        println!("  IGD (Inverted Generational Distance): {:.6}", igd);
        println!("    - Measures how well obtained front covers reference front");
        println!("    - Lower is better (better coverage)");
        println!("    - IGD=0 means perfect coverage");
    }

    if let Some(gd) = result.gd {
        println!("  GD (Generational Distance):            {:.6}", gd);
        println!("    - Measures convergence to reference front");
        println!("    - Lower is better (closer to reference)");
        println!("    - GD=0 means perfect convergence");
    }

    println!();
    println!("Diversity Metrics:");

    if let Some(spacing) = result.spacing {
        println!("  Spacing: {:.6}", spacing);
    }

    if let Some(spread) = result.spread {
        println!("  Spread:  {:.6}", spread);
    }

    if let Some(hv) = result.hypervolume {
        println!();
        println!("Coverage Metric:");
        println!("  Hypervolume: {:.6}", hv);
    }

    // Convergence interpretation
    println!();
    println!("Convergence Interpretation:");

    let convergence_quality = if let Some(igd) = result.igd {
        if igd < 0.001 {
            "Excellent convergence - front very close to reference"
        } else if igd < 0.01 {
            "Good convergence - front close to reference"
        } else if igd < 0.1 {
            "Moderate convergence - front approaching reference"
        } else {
            "Poor convergence - consider more generations"
        }
    } else {
        "No convergence metric available"
    };

    println!("  {}", convergence_quality);

    println!("\n✓ Convergence analysis demonstrated successfully\n");
    Ok(())
}

/// Example 4: Problem Comparison
///
/// Compares NSGA-II performance across different problem types:
/// ZDT1 (convex), ZDT2 (non-convex), and ZDT3 (disconnected).
fn example4_problem_comparison() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 4: Problem Comparison (ZDT1, ZDT2, ZDT3)");
    println!("═══════════════════════════════════════════════════════════\n");

    struct ProblemResult {
        name: String,
        description: String,
        pareto_size: usize,
        time: std::time::Duration,
        hypervolume: Option<f64>,
        spacing: Option<f64>,
        spread: Option<f64>,
        igd: Option<f64>,
    }

    let mut results = Vec::new();

    // Common configuration for fair comparison
    let base_config = NSGA2Config {
        pop_size: 100,
        max_generations: 150,
        hypervolume_config: Some(HypervolumeConfig {
            reference_point: vec![2.0, 2.0],
        }),
        ..Default::default()
    };

    // Test ZDT1 (Convex front)
    {
        println!("Testing ZDT1 (Convex Pareto front)...");
        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 {
            quality_metrics_config: Some(QualityMetricsConfig {
                calculate_spacing: true,
                calculate_spread: true,
                reference_front: Some(reference_front),
            }),
            ..base_config.clone()
        };

        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(ProblemResult {
            name: "ZDT1".to_string(),
            description: "Convex front".to_string(),
            pareto_size: result.pareto_front.len(),
            time: duration,
            hypervolume: result.hypervolume,
            spacing: result.spacing,
            spread: result.spread,
            igd: result.igd,
        });
        println!("  ✓ Completed in {:?}\n", duration);
    }

    // Test ZDT2 (Non-convex front)
    {
        println!("Testing ZDT2 (Non-convex Pareto front)...");
        let problem = ZDT2::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 {
            quality_metrics_config: Some(QualityMetricsConfig {
                calculate_spacing: true,
                calculate_spread: true,
                reference_front: Some(reference_front),
            }),
            ..base_config.clone()
        };

        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(ProblemResult {
            name: "ZDT2".to_string(),
            description: "Non-convex front".to_string(),
            pareto_size: result.pareto_front.len(),
            time: duration,
            hypervolume: result.hypervolume,
            spacing: result.spacing,
            spread: result.spread,
            igd: result.igd,
        });
        println!("  ✓ Completed in {:?}\n", duration);
    }

    // Test ZDT3 (Disconnected front)
    {
        println!("Testing ZDT3 (Disconnected Pareto front)...");
        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 {
            quality_metrics_config: Some(QualityMetricsConfig {
                calculate_spacing: true,
                calculate_spread: true,
                reference_front: Some(reference_front),
            }),
            hypervolume_config: Some(HypervolumeConfig {
                reference_point: vec![2.0, 2.0],
            }),
            ..base_config
        };

        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(ProblemResult {
            name: "ZDT3".to_string(),
            description: "Disconnected front".to_string(),
            pareto_size: result.pareto_front.len(),
            time: duration,
            hypervolume: result.hypervolume,
            spacing: result.spacing,
            spread: result.spread,
            igd: result.igd,
        });
        println!("  ✓ Completed in {:?}\n", duration);
    }

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

    println!(
        "{:<8} {:<20} {:<10} {:<12} {:<10}",
        "Problem", "Description", "PF Size", "Time (ms)", "HV"
    );
    println!("{}", "".repeat(70));

    for result in &results {
        println!(
            "{:<8} {:<20} {:<10} {:<12.2} {:<10.4}",
            result.name,
            result.description,
            result.pareto_size,
            result.time.as_secs_f64() * 1000.0,
            result.hypervolume.unwrap_or(0.0)
        );
    }

    println!();
    println!(
        "{:<8} {:<12} {:<12} {:<12}",
        "Problem", "Spacing", "Spread", "IGD"
    );
    println!("{}", "".repeat(50));

    for result in &results {
        println!(
            "{:<8} {:<12.6} {:<12.6} {:<12.6}",
            result.name,
            result.spacing.unwrap_or(0.0),
            result.spread.unwrap_or(0.0),
            result.igd.unwrap_or(0.0)
        );
    }

    println!();
    println!("Observations:");
    println!("  • ZDT1 (convex): Typically easiest to solve with good convergence");
    println!("  • ZDT2 (non-convex): Tests diversity preservation capabilities");
    println!("  • ZDT3 (disconnected): Most challenging, tests diversity in disconnected regions");

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

/// Example 5: Advanced Configuration
///
/// Demonstrates advanced parameter tuning and configuration options
/// to optimize NSGA-II performance for specific problem characteristics.
fn example5_advanced_configuration() -> Result<(), Box<dyn std::error::Error>> {
    println!("═══════════════════════════════════════════════════════════");
    println!("Example 5: Advanced Configuration and Parameter Tuning");
    println!("═══════════════════════════════════════════════════════════\n");

    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);

    // Compare different configurations
    struct ConfigTest {
        name: String,
        config: NSGA2Config<f64>,
    }

    let configs = vec![
        ConfigTest {
            name: "Default Configuration".to_string(),
            config: NSGA2Config {
                quality_metrics_config: Some(QualityMetricsConfig {
                    calculate_spacing: true,
                    calculate_spread: true,
                    reference_front: Some(reference_front.clone()),
                }),
                ..Default::default()
            },
        },
        ConfigTest {
            name: "Large Population".to_string(),
            config: NSGA2Config {
                pop_size: 200,
                max_generations: 100,
                quality_metrics_config: Some(QualityMetricsConfig {
                    calculate_spacing: true,
                    calculate_spread: true,
                    reference_front: Some(reference_front.clone()),
                }),
                ..Default::default()
            },
        },
        ConfigTest {
            name: "High Crossover Rate".to_string(),
            config: NSGA2Config {
                pop_size: 100,
                max_generations: 100,
                crossover_rate: 0.95,
                quality_metrics_config: Some(QualityMetricsConfig {
                    calculate_spacing: true,
                    calculate_spread: true,
                    reference_front: Some(reference_front.clone()),
                }),
                ..Default::default()
            },
        },
        ConfigTest {
            name: "High Mutation Rate".to_string(),
            config: NSGA2Config {
                pop_size: 100,
                max_generations: 100,
                mutation_rate: 0.2,
                quality_metrics_config: Some(QualityMetricsConfig {
                    calculate_spacing: true,
                    calculate_spread: true,
                    reference_front: Some(reference_front.clone()),
                }),
                ..Default::default()
            },
        },
    ];

    println!(
        "{:<25} {:<12} {:<12} {:<12}",
        "Configuration", "IGD", "Spacing", "Time (ms)"
    );
    println!("{}", "".repeat(65));

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

        println!(
            "{:<25} {:<12.6} {:<12.6} {:<12.2}",
            config_test.name,
            result.igd.unwrap_or(0.0),
            result.spacing.unwrap_or(0.0),
            duration.as_secs_f64() * 1000.0
        );
    }

    println!();
    println!("Parameter Tuning Guidelines:");
    println!();
    println!("Population Size:");
    println!("  • Larger populations provide better diversity");
    println!("  • Recommended: 50-200 for most problems");
    println!("  • Trade-off: More evaluations per generation");
    println!();
    println!("Crossover Rate:");
    println!("  • Controls exploitation vs exploration balance");
    println!("  • Typical range: 0.8-0.95");
    println!("  • Higher values: More recombination, faster convergence");
    println!();
    println!("Mutation Rate:");
    println!("  • Maintains diversity and prevents premature convergence");
    println!("  • Typical range: 0.05-0.2");
    println!("  • Higher values: More exploration, slower convergence");
    println!();
    println!("Distribution Indices (eta_c, eta_m):");
    println!("  • Control spread of offspring around parents");
    println!("  • Higher values: Offspring closer to parents");
    println!("  • Typical range: 10-30");

    println!("\n✓ Advanced configuration demonstrated successfully\n");
    Ok(())
}