autoeq 0.4.24

Automatic equalization for speakers, headphones and rooms!
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
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! AutoEQ - A library for audio equalization and filter optimization
//! Common command-line interface definitions shared across binaries
//!
//! Copyright (C) 2025-2026 Pierre Aubert pierre(at)spinorama(dot)org
//!
//! This program is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! This program is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with this program.  If not, see <https://www.gnu.org/licenses/>.

use super::optim::{AlgorithmType, get_all_algorithms};
use crate::LossType;
use crate::de::Strategy;
use clap::{Parser, ValueEnum};
use std::fmt;
use std::path::PathBuf;
use std::process;

/// PEQ model types that define the structure and constraints of the equalizer
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum PeqModel {
    /// All filters are peak filters
    #[value(name = "pk")]
    Pk,
    /// First filter is highpass, rest are peak filters
    #[value(name = "hp-pk")]
    HpPk,
    /// First filter is highpass, last is lowpass, rest are peak filters
    #[value(name = "hp-pk-lp")]
    HpPkLp,
    /// First filter is low shelve, rest are peak filters
    #[value(name = "ls-pk")]
    LsPk,
    /// First filter is low shelve, last is high shelve, rest are peak filters
    #[value(name = "ls-pk-hs")]
    LsPkHs,
    /// First and last filters are free (any type), rest are peak filters
    #[value(name = "free-pk-free")]
    FreePkFree,
    /// All filters are free to be any type
    #[value(name = "free")]
    Free,
}

impl fmt::Display for PeqModel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PeqModel::Pk => write!(f, "pk"),
            PeqModel::HpPk => write!(f, "hp-pk"),
            PeqModel::LsPk => write!(f, "ls-pk"),
            PeqModel::HpPkLp => write!(f, "hp-pk-lp"),
            PeqModel::LsPkHs => write!(f, "ls-pk-hs"),
            PeqModel::FreePkFree => write!(f, "free-pk-free"),
            PeqModel::Free => write!(f, "free"),
        }
    }
}

impl PeqModel {
    /// Get all available PEQ models
    pub fn all() -> Vec<Self> {
        vec![
            PeqModel::Pk,
            PeqModel::HpPk,
            PeqModel::LsPk,
            PeqModel::HpPkLp,
            PeqModel::LsPkHs,
            PeqModel::FreePkFree,
            PeqModel::Free,
        ]
    }

    /// Get a description of the model
    pub fn description(&self) -> &'static str {
        match self {
            PeqModel::Pk => "All filters are peak/bell filters",
            PeqModel::HpPk => "First filter is highpass, rest are peak filters",
            PeqModel::LsPk => "First filter is low shelve, rest are peak filters",
            PeqModel::HpPkLp => "First filter is highpass, last is lowpass, rest are peak filters",
            PeqModel::LsPkHs => {
                "First filter is low shelve, last is high shelve, rest are peak filters"
            }
            PeqModel::FreePkFree => {
                "First and last filters can be any type, middle filters are peak"
            }
            PeqModel::Free => "All filters can be any type (peak, highpass, lowpass, shelf)",
        }
    }
}

/// Shared CLI arguments for AutoEQ binaries.
#[derive(Parser, Debug, Clone)]
#[command(author, about, long_about = None)]
pub struct Args {
    /// Number of IIR filters to use for optimization.
    #[arg(short = 'n', long, default_value_t = 7)]
    pub num_filters: usize,

    /// Path to the input curve CSV file (format: frequency,spl).
    /// Required unless speaker, version, and measurement are provided for API data.
    #[arg(short, long)]
    pub curve: Option<PathBuf>,

    /// Path to the optional target curve CSV file (format: frequency,spl).
    /// If not provided, a flat 0 dB target is assumed.
    #[arg(short, long)]
    pub target: Option<PathBuf>,

    /// The sample rate for the IIR filters.
    #[arg(short, long, default_value_t = 48000.0)]
    pub sample_rate: f64,

    /// Maximum absolute dB gain allowed for each filter.
    #[arg(long, default_value_t = 3.0, value_parser = parse_nonnegative_f64)]
    pub max_db: f64,

    /// Minimum absolute dB gain allowed for each filter.
    #[arg(long, default_value_t = 1.0, value_parser = parse_strictly_positive_f64)]
    pub min_db: f64,

    /// Maximum Q factor allowed for each filter.
    #[arg(long, default_value_t = 3.0)]
    pub max_q: f64,

    /// Minimum Q factor allowed for each filter.
    #[arg(long, default_value_t = 1.0)]
    pub min_q: f64,

    /// Minimum frequency allowed for each filter.
    #[arg(long, default_value_t = 60.0)]
    pub min_freq: f64,

    /// Maximum frequency allowed for each filter.
    #[arg(long, default_value_t = 16000.0)]
    pub max_freq: f64,

    /// Output PNG file for plotting results.
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Speaker name for API data fetching.
    #[arg(long)]
    pub speaker: Option<String>,

    /// Version for API data fetching.
    #[arg(long)]
    pub version: Option<String>,

    /// Measurement type for API data fetching.
    #[arg(long)]
    pub measurement: Option<String>,

    /// Curve name inside CEA2034 plots to use (only when --measurement CEA2034)
    /// e.g., "Listening Window", "On Axis", "Early Reflections". Default: Listening Window
    #[arg(long, default_value = "Listening Window")]
    pub curve_name: String,

    /// Optimization algorithm to use (e.g., isres, cobyla)
    #[arg(long, default_value = "nlopt:cobyla")]
    pub algo: String,

    /// Optional population size for population-based algorithms (e.g., ISRES)
    #[arg(long, default_value_t = 300)]
    pub population: usize,

    /// Maximum number of evaluations for the optimizer
    #[arg(long, default_value_t = 2_000)]
    pub maxeval: usize,

    /// Whether to run a local refinement after global optimization
    #[arg(long, default_value_t = false)]
    pub refine: bool,

    /// Local optimizer to use for refinement (e.g., cobyla)
    #[arg(long, default_value = "cobyla")]
    pub local_algo: String,

    /// Minimum spacing between filter center frequencies in octaves (0 disables)
    #[arg(long, default_value_t = 0.2)]
    pub min_spacing_oct: f64,

    /// Weight for the spacing penalty in the objective function
    #[arg(long, default_value_t = 20.0)]
    pub spacing_weight: f64,

    /// Enable smoothing (regularization) of the inverted target curve
    #[arg(long, default_value_t = true)]
    pub smooth: bool,

    /// Smoothing level as 1/N octave (N in [1..24]). Example: N=6 => 1/6 octave smoothing
    #[arg(long, default_value_t = 2)]
    pub smooth_n: usize,

    /// Loss function to optimize (flat or score).
    #[arg(long, value_enum, default_value_t = LossType::SpeakerFlat)]
    pub loss: LossType,

    /// PEQ model that defines the filter structure
    #[arg(long, value_enum, default_value_t = PeqModel::Pk)]
    pub peq_model: PeqModel,

    /// Display list of available PEQ models with descriptions and exit.
    #[arg(long, default_value_t = false)]
    pub peq_model_list: bool,

    /// Display list of available optimization algorithms with descriptions and exit.
    #[arg(long, default_value_t = false)]
    pub algo_list: bool,

    /// Optimization tolerance (tol parameter for DE algorithm)
    #[arg(long, default_value_t = 1e-3)]
    pub tolerance: f64,

    /// Absolute tolerance (atol parameter for DE algorithm)
    #[arg(long, default_value_t = 1e-4)]
    pub atolerance: f64,

    /// Recombination probability for DE algorithm (0.0 to 1.0)
    #[arg(long, default_value_t = 0.9, value_parser = parse_recombination_probability)]
    pub recombination: f64,

    /// DE strategy to use (e.g., best1bin, rand1bin, currenttobest1bin, adaptive)
    #[arg(long, default_value = "currenttobest1bin")]
    pub strategy: String,

    /// Display list of available DE strategies and exit.
    #[arg(long, default_value_t = false)]
    pub strategy_list: bool,

    /// Adaptive weight for F parameter (DE adaptive strategies only)
    #[arg(long, default_value_t = 0.9)]
    pub adaptive_weight_f: f64,

    /// Adaptive weight for CR parameter (DE adaptive strategies only)
    #[arg(long, default_value_t = 0.9)]
    pub adaptive_weight_cr: f64,

    /// Disable parallel evaluation for DE algorithm (default: parallel is enabled)
    #[arg(long = "no-parallel", default_value_t = false)]
    pub no_parallel: bool,

    /// Number of threads to use for parallel evaluation (0 = use all available cores)
    #[arg(long, default_value_t = 0)]
    pub parallel_threads: usize,

    /// Random seed for deterministic optimization (default: random seed for each run)
    /// Setting this makes optimization results reproducible
    #[arg(long)]
    pub seed: Option<u64>,

    /// Quality assurance mode with optional threshold: suppress normal output, show summary line and analysis
    /// If a threshold is provided (e.g., --qa 0.4), also perform QA analysis
    #[arg(long, value_name = "THRESHOLD")]
    pub qa: Option<f64>,

    /// Path to first driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
    #[arg(long)]
    pub driver1: Option<PathBuf>,

    /// Path to second driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
    #[arg(long)]
    pub driver2: Option<PathBuf>,

    /// Path to third driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
    #[arg(long)]
    pub driver3: Option<PathBuf>,

    /// Path to fourth driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
    #[arg(long)]
    pub driver4: Option<PathBuf>,

    /// Crossover type for multi-driver optimization (butterworth2, linkwitzriley2, linkwitzriley4)
    #[arg(long, default_value = "linkwitzriley4")]
    pub crossover_type: String,

    /// Use a named preset that sets all optimizer parameters at once.
    /// Available presets: quick, balanced, max-quality, score (speakers only).
    /// Individual parameter flags override preset values when both are specified.
    #[arg(long)]
    pub preset: Option<String>,
}

impl Args {
    /// Get the effective PEQ model
    pub fn effective_peq_model(&self) -> PeqModel {
        self.peq_model
    }

    /// Check if the first filter should be a highpass (for compatibility)
    pub fn uses_highpass_first(&self) -> bool {
        matches!(
            self.effective_peq_model(),
            PeqModel::HpPk | PeqModel::HpPkLp
        )
    }

    /// Create Args with speaker optimization defaults
    ///
    /// These defaults are tuned for typical speaker EQ optimization using
    /// CEA2034 measurements from spinorama.org.
    pub fn speaker_defaults() -> Self {
        Self {
            num_filters: 5,
            sample_rate: 48000.0,
            loss: LossType::SpeakerFlat,
            algo: "autoeq:de".to_string(),
            population: 50,
            maxeval: 2000,
            strategy: "currenttobest1bin".to_string(),
            min_db: -12.0,
            max_db: 12.0,
            min_q: 0.5,
            max_q: 10.0,
            min_freq: 20.0,
            max_freq: 20000.0,
            min_spacing_oct: 0.5,
            spacing_weight: 20.0,
            smooth: true,
            smooth_n: 1,
            refine: false,
            local_algo: "cobyla".to_string(),
            tolerance: 1e-3,
            atolerance: 1e-4,
            recombination: 0.9,
            adaptive_weight_f: 0.8,
            adaptive_weight_cr: 0.7,
            peq_model: PeqModel::Pk,
            curve_name: "Listening Window".to_string(),
            // File paths/flags default to None/false
            curve: None,
            target: None,
            output: None,
            speaker: None,
            version: None,
            measurement: None,
            peq_model_list: false,
            algo_list: false,
            strategy_list: false,
            no_parallel: false,
            parallel_threads: 0,
            seed: None,
            qa: None,
            driver1: None,
            driver2: None,
            driver3: None,
            driver4: None,
            crossover_type: "linkwitzriley4".to_string(),
            preset: None,
        }
    }

    /// Create Args with headphone optimization defaults
    ///
    /// These defaults are tuned for headphone EQ optimization using
    /// frequency response measurements and Harman target curves.
    pub fn headphone_defaults() -> Self {
        Self {
            loss: LossType::HeadphoneScore,
            num_filters: 7,
            ..Self::speaker_defaults()
        }
    }

    /// Create Args with room EQ optimization defaults
    ///
    /// These defaults are tuned for room correction, focusing on
    /// low frequencies where room modes are most problematic.
    pub fn roomeq_defaults() -> Self {
        Self {
            num_filters: 10,
            max_freq: 500.0, // Room EQ focuses on low frequencies
            ..Self::speaker_defaults()
        }
    }

    /// Apply a named preset, setting optimizer parameters to tuned values.
    /// Call this after parsing CLI args. Parameters explicitly set by the user
    /// are not tracked by clap, so this method overwrites all optimizer fields.
    /// The caller should parse args, call `apply_preset()`, then override
    /// any fields they want to customize.
    ///
    /// NOTE: These preset values are intentionally duplicated from
    /// `sotf-player::autoeq::presets` because the `autoeq` crate cannot
    /// depend on `sotf-player`. Keep values in sync when updating presets.
    ///
    /// Available presets:
    /// - `quick`: 5 filters, fast (pop 40, maxeval 2000, no refine)
    /// - `balanced`: 7 filters, good balance (pop 80, maxeval 5000, refine)
    /// - `max-quality`: 10 filters, best results (pop 200, maxeval 20000, ls-pk-hs, refine)
    /// - `score`: 7 filters, listener preference score (speaker-score loss)
    pub fn apply_preset(&mut self) {
        let preset_name = match &self.preset {
            Some(name) => name.clone(),
            None => return,
        };
        match preset_name.as_str() {
            "quick" => {
                self.num_filters = 5;
                self.population = 40;
                self.maxeval = 2000;
                self.refine = false;
                self.min_q = 0.5;
                self.max_q = 6.0;
                self.min_db = -12.0;
                self.max_db = 6.0;
            }
            "balanced" => {
                self.num_filters = 7;
                self.population = 80;
                self.maxeval = 5000;
                self.refine = true;
                self.min_q = 0.5;
                self.max_q = 6.0;
                self.min_db = -12.0;
                self.max_db = 6.0;
            }
            "max-quality" => {
                self.num_filters = 10;
                self.peq_model = PeqModel::LsPkHs;
                self.population = 200;
                self.maxeval = 20000;
                self.refine = true;
                self.min_q = 0.5;
                self.max_q = 6.0;
                self.min_db = -12.0;
                self.max_db = 6.0;
            }
            "score" => {
                self.num_filters = 7;
                self.loss = LossType::SpeakerScore;
                self.population = 100;
                self.maxeval = 10000;
                self.refine = true;
                self.min_q = 0.5;
                self.max_q = 6.0;
                self.min_db = -12.0;
                self.max_db = 6.0;
            }
            other => {
                eprintln!(
                    "Warning: unknown preset '{}'. Available: quick, balanced, max-quality, score",
                    other
                );
            }
        }
    }

    /// Display available presets and exit.
    pub fn display_preset_list() -> ! {
        println!("Available Presets");
        println!("=================\n");
        println!("  quick        5 filters, fast optimization (seconds)");
        println!("  balanced     7 filters, good balance of quality and speed (default)");
        println!("  max-quality  10 filters with shelves, best results (slow)");
        println!("  score        7 filters, listener preference score optimization");
        println!("\nUse: --preset <name>");
        println!("Individual flags (e.g. -n, --max-q) override preset values.");
        process::exit(0);
    }
}

/// Display available optimization algorithms with descriptions and exit
pub fn display_algorithm_list() -> ! {
    println!("Available Optimization Algorithms");
    println!("=================================\n");

    let algorithms = get_all_algorithms();

    // Group algorithms by library
    let mut nlopt_algos = Vec::new();
    let mut metaheuristics_algos = Vec::new();
    let mut autoeq_algos = Vec::new();

    for algo in &algorithms {
        match algo.library {
            "NLOPT" => nlopt_algos.push(algo),
            "Metaheuristics" => metaheuristics_algos.push(algo),
            "AutoEQ" => autoeq_algos.push(algo),
            _ => {} // Skip unknown libraries
        }
    }

    // Display NLOPT algorithms
    if !nlopt_algos.is_empty() {
        println!("📊 NLOPT Library Algorithms:");

        // Separate global and local algorithms
        let mut global = Vec::new();
        let mut local = Vec::new();

        for algo in nlopt_algos {
            match algo.algorithm_type {
                AlgorithmType::Global => global.push(algo),
                AlgorithmType::Local => local.push(algo),
            }
        }

        if !global.is_empty() {
            println!("   🌍 Global Optimizers (best for exploring solution space):");
            for algo in global {
                print!("   - {:<20}", algo.name);
                print!(" | Constraints: ");
                if algo.supports_nonlinear_constraints {
                    print!("✅ Nonlinear");
                } else if algo.supports_linear_constraints {
                    print!("🔶 Linear only");
                } else {
                    print!("❌ None");
                }

                // Add specific descriptions
                let description = match algo.name {
                    "nlopt:isres" => {
                        " | Improved Stochastic Ranking Evolution Strategy (recommended)"
                    }
                    "nlopt:ags" => " | Adaptive Geometric Search",
                    "nlopt:origdirect" => " | DIRECT global optimization (original version)",
                    "nlopt:crs2lm" => " | Controlled Random Search with local mutation",
                    "nlopt:direct" => " | DIRECT global optimization",
                    "nlopt:directl" => " | DIRECT-L (locally biased version)",
                    "nlopt:gmlsl" => " | Global Multi-Level Single-Linkage",
                    "nlopt:gmlsllds" => " | GMLSL with low-discrepancy sequence",
                    "nlopt:stogo" => " | Stochastic Global Optimization",
                    "nlopt:stogorand" => " | StoGO with randomized search",
                    _ => "",
                };
                println!("{}", description);
            }
            println!();
        }

        if !local.is_empty() {
            println!("   🎯 Local Optimizers (fast refinement from good starting points):");
            for algo in local {
                print!("   - {:<20}", algo.name);
                print!(" | Constraints: ");
                if algo.supports_nonlinear_constraints {
                    print!("✅ Nonlinear");
                } else if algo.supports_linear_constraints {
                    print!("🔶 Linear only");
                } else {
                    print!("❌ None");
                }

                let description = match algo.name {
                    "nlopt:cobyla" => {
                        " | Constrained Optimization BY Linear Approximations (recommended for local)"
                    }
                    "nlopt:bobyqa" => " | Bound Optimization BY Quadratic Approximation",
                    "nlopt:neldermead" => " | Nelder-Mead simplex algorithm",
                    "nlopt:sbplx" => " | Subplex (variant of Nelder-Mead)",
                    "nlopt:slsqp" => " | Sequential Least SQuares Programming",
                    _ => "",
                };
                println!("{}", description);
            }
            println!();
        }
    }

    // Display Metaheuristics algorithms
    if !metaheuristics_algos.is_empty() {
        println!("🧬 Metaheuristics Library Algorithms:");
        println!("   Nature-inspired global optimization (penalty-based constraints)\n");

        for algo in metaheuristics_algos {
            print!("   - {:<20}", algo.name);
            let description = match algo.name {
                "mh:de" => " | Differential Evolution (robust, good convergence)",
                "mh:pso" => " | Particle Swarm Optimization (fast exploration)",
                "mh:rga" => " | Real-coded Genetic Algorithm (diverse search)",
                "mh:tlbo" => " | Teaching-Learning-Based Optimization (parameter-free)",
                "mh:firefly" => " | Firefly Algorithm (multi-modal problems)",
                _ => "",
            };
            println!("{}", description);
        }
        println!();
    }

    // Display AutoEQ algorithms
    if !autoeq_algos.is_empty() {
        println!("🎵 AutoEQ Custom Algorithms:");
        println!("   Specialized algorithms developed for audio filter optimization\n");

        for algo in autoeq_algos {
            print!("   - {:<20}", algo.name);
            print!(" | Constraints: ");
            if algo.supports_nonlinear_constraints {
                print!("✅ Nonlinear");
            } else {
                print!("❌ Penalty-based");
            }

            let description = match algo.name {
                "autoeq:de" => " | Adaptive DE with constraint handling (experimental)",
                _ => "",
            };
            println!("{}", description);
        }
        println!();
    }

    println!("Usage Examples:");
    println!("==============\n");
    println!("  # Use ISRES (recommended global optimizer):");
    println!("  autoeq --algo nlopt:isres --curve input.csv\n");
    println!("  # Use COBYLA (fast local optimizer):");
    println!("  autoeq --algo nlopt:cobyla --curve input.csv\n");
    println!("  # Use Differential Evolution from metaheuristics:");
    println!("  autoeq --algo mh:de --curve input.csv\n");
    println!("  # Backward compatibility (maps to nlopt:cobyla):");
    println!("  autoeq --algo cobyla --curve input.csv\n");

    println!("Recommendations:");
    println!("===============\n");
    println!("  🎯 For best results: nlopt:isres (global) + --refine with nlopt:cobyla (local)");
    println!("  ⚡ For speed: nlopt:cobyla (if you have a good initial guess)");
    println!("  🧪 For experimentation: mh:de or mh:pso from metaheuristics library");
    println!(
        "  ⚖️  For constrained problems: Prefer algorithms with ✅ Nonlinear constraint support"
    );

    process::exit(0);
}

/// Display available DE strategies with descriptions and exit
pub fn display_strategy_list() -> ! {
    println!("Available Differential Evolution (DE) Strategies");
    println!("===============================================\n");

    let strategies = [
        (
            "best1bin",
            "Best1Bin",
            "Use best individual + 1 random difference (binomial crossover)",
            "Global exploration with fast convergence",
        ),
        (
            "best1exp",
            "Best1Exp",
            "Use best individual + 1 random difference (exponential crossover)",
            "Similar to best1bin with different crossover",
        ),
        (
            "rand1bin",
            "Rand1Bin",
            "Use random individual + 1 random difference (binomial crossover)",
            "Good diversity, slower convergence",
        ),
        (
            "rand1exp",
            "Rand1Exp",
            "Use random individual + 1 random difference (exponential crossover)",
            "Similar to rand1bin with different crossover",
        ),
        (
            "rand2bin",
            "Rand2Bin",
            "Use random individual + 2 random differences (binomial crossover)",
            "High exploration, may be slower",
        ),
        (
            "rand2exp",
            "Rand2Exp",
            "Use random individual + 2 random differences (exponential crossover)",
            "Similar to rand2bin with different crossover",
        ),
        (
            "currenttobest1bin",
            "CurrentToBest1Bin",
            "Blend current with best + random difference (binomial)",
            "Balanced exploration/exploitation (recommended)",
        ),
        (
            "currenttobest1exp",
            "CurrentToBest1Exp",
            "Blend current with best + random difference (exponential)",
            "Similar to currenttobest1bin",
        ),
        (
            "best2bin",
            "Best2Bin",
            "Use best individual + 2 random differences (binomial crossover)",
            "Fast convergence, may get trapped locally",
        ),
        (
            "best2exp",
            "Best2Exp",
            "Use best individual + 2 random differences (exponential crossover)",
            "Similar to best2bin",
        ),
        (
            "randtobest1bin",
            "RandToBest1Bin",
            "Blend random with best + random difference (binomial)",
            "Good balance of diversity and convergence",
        ),
        (
            "randtobest1exp",
            "RandToBest1Exp",
            "Blend random with best + random difference (exponential)",
            "Similar to randtobest1bin",
        ),
        (
            "adaptivebin",
            "AdaptiveBin",
            "Self-adaptive mutation with top-w% selection (binomial)",
            "Advanced adaptive strategy (experimental)",
        ),
        (
            "adaptiveexp",
            "AdaptiveExp",
            "Self-adaptive mutation with top-w% selection (exponential)",
            "Advanced adaptive strategy (experimental)",
        ),
    ];

    println!("🎯 Classic DE Strategies (well-tested, reliable):");
    for &(name, _enum_name, description, recommendation) in strategies.iter().take(12) {
        if name.starts_with("adaptive") {
            continue;
        }
        println!("   - {:<20} | {}", name, description);
        println!("     {:<20} | 💡 {}", "", recommendation);
        if name == "currenttobest1bin" {
            println!("     {:<20} | ⭐ Recommended default strategy", "");
        }
        println!();
    }

    println!("🧬 Adaptive DE Strategies (experimental, research-based):");
    for &(name, _enum_name, description, recommendation) in strategies.iter() {
        if !name.starts_with("adaptive") {
            continue;
        }
        println!("   - {:<20} | {}", name, description);
        println!("     {:<20} | 💡 {}", "", recommendation);
        println!(
            "     {:<20} | 🔧 Requires --adaptive-weight-f and --adaptive-weight-cr",
            ""
        );
        println!();
    }

    println!("Strategy Naming Conventions:");
    println!("==========================\n");
    println!("  • 'bin' = Binomial (uniform) crossover - each gene has equal probability");
    println!("  • 'exp' = Exponential crossover - contiguous segments are more likely");
    println!("  • Numbers (1, 2) indicate how many difference vectors are used\n");

    println!("Usage Examples:");
    println!("==============\n");
    println!("  # Use recommended default strategy:");
    println!("  autoeq --algo autoeq:de --strategy currenttobest1bin --curve input.csv\n");
    println!("  # Use adaptive strategy with custom weights:");
    println!(
        "  autoeq --algo autoeq:de --strategy adaptivebin --adaptive-weight-f 0.8 --adaptive-weight-cr 0.7\n"
    );
    println!("  # Use classic exploration strategy:");
    println!("  autoeq --algo autoeq:de --strategy rand1bin --curve input.csv\n");

    println!("Recommendations:");
    println!("===============\n");
    println!(
        "  ⭐ For general use: currenttobest1bin (good balance of exploration and exploitation)"
    );
    println!("  🚀 For fast convergence: best1bin or best2bin (may get trapped in local optima)");
    println!("  🌍 For thorough exploration: rand1bin or rand2bin (slower but more robust)");
    println!(
        "  🧪 For research/experimentation: adaptivebin or adaptiveexp (requires parameter tuning)"
    );

    process::exit(0);
}

/// Validate CLI arguments and exit with error message if validation fails
pub fn validate_args(args: &Args) -> Result<(), String> {
    // Check if strategy is valid when using DE algorithm
    if args.algo == "autoeq:de" || args.algo.contains("de") {
        use std::str::FromStr;
        if let Err(err) = Strategy::from_str(&args.strategy) {
            return Err(format!(
                "Invalid DE strategy '{}': {}. Use --strategy-list to see available strategies.",
                args.strategy, err
            ));
        }
    }
    // Check if algorithm is valid
    if crate::optim::find_algorithm_info(&args.algo).is_some() {
        // Algorithm is valid
    } else {
        return Err(format!(
            "Unknown algorithm: '{}'. Use --algo-list to see available algorithms.",
            args.algo
        ));
    }

    // Check if local algorithm is valid (when refine is enabled)
    if args.refine {
        if crate::optim::find_algorithm_info(&args.local_algo).is_some() {
            // Local algorithm is valid
        } else {
            return Err(format!(
                "Unknown local algorithm: '{}'. Use --algo-list to see available algorithms.",
                args.local_algo
            ));
        }
    }

    // Check min/max Q factor constraints
    if args.min_q > args.max_q {
        return Err(format!(
            "Invalid Q factor range: min_q ({}) must be <= max_q ({})",
            args.min_q, args.max_q
        ));
    }

    // Check min/max frequency constraints
    if args.min_freq > args.max_freq {
        return Err(format!(
            "Invalid frequency range: min_freq ({}) must be <= max_freq ({})",
            args.min_freq, args.max_freq
        ));
    }

    // Check min/max dB constraints
    if args.min_db > args.max_db {
        return Err(format!(
            "Invalid dB range: min_db ({}) must be <= max_db ({})",
            args.min_db, args.max_db
        ));
    }

    // Check frequency bounds (reasonable audio range)
    if args.min_freq < 20.0 {
        return Err(format!(
            "Invalid min_freq: {} Hz. Must be >= 20 Hz (reasonable audio range)",
            args.min_freq
        ));
    }

    if args.max_freq > 20000.0 {
        return Err(format!(
            "Invalid max_freq: {} Hz. Must be <= 20,000 Hz (reasonable audio range)",
            args.max_freq
        ));
    }

    // Check that max_freq does not exceed Nyquist frequency
    let nyquist = args.sample_rate / 2.0;
    if args.max_freq > nyquist {
        return Err(format!(
            "max_freq ({:.0} Hz) exceeds Nyquist frequency ({:.0} Hz) at sample rate {:.0} Hz. \
             Biquad filters above Nyquist have undefined behavior.",
            args.max_freq, nyquist, args.sample_rate
        ));
    }

    // Check smoothing parameters
    if args.smooth_n < 1 || args.smooth_n > 24 {
        return Err(format!(
            "Invalid smooth_n: {}. Must be in range [1..24]",
            args.smooth_n
        ));
    }

    // Check that population size is reasonable
    if args.population == 0 {
        return Err("Population size must be > 0".to_string());
    }

    // Check that maxeval is reasonable
    if args.maxeval == 0 {
        return Err("Maximum evaluations must be > 0".to_string());
    }

    // Check that num_filters is reasonable
    if args.num_filters == 0 {
        return Err("Number of filters must be > 0".to_string());
    }

    if args.num_filters > 50 {
        return Err(format!(
            "Number of filters ({}) is very high. Consider using <= 50 filters for reasonable performance",
            args.num_filters
        ));
    }

    // Check tolerance parameters
    if args.tolerance <= 0.0 {
        return Err("Tolerance must be > 0".to_string());
    }

    if args.atolerance < 0.0 {
        return Err("Absolute tolerance must be >= 0".to_string());
    }

    // Check adaptive weight parameters (should be in [0, 1])
    if args.adaptive_weight_f < 0.0 || args.adaptive_weight_f > 1.0 {
        return Err("Adaptive weight for F must be between 0.0 and 1.0".to_string());
    }

    if args.adaptive_weight_cr < 0.0 || args.adaptive_weight_cr > 1.0 {
        return Err("Adaptive weight for CR must be between 0.0 and 1.0".to_string());
    }

    // Validate multi-driver arguments
    if args.loss == LossType::DriversFlat {
        // Check that at least driver1 and driver2 are provided
        if args.driver1.is_none() || args.driver2.is_none() {
            return Err("Multi-driver optimization requires at least --driver1 and --driver2 when using --loss drivers-flat".to_string());
        }

        // Check crossover type
        let valid_crossover_types = ["butterworth2", "linkwitzriley2", "linkwitzriley4"];
        if !valid_crossover_types.contains(&args.crossover_type.as_str()) {
            return Err(format!(
                "Invalid crossover type '{}'. Valid types: {}",
                args.crossover_type,
                valid_crossover_types.join(", ")
            ));
        }

        // Count number of drivers
        let n_drivers = [&args.driver1, &args.driver2, &args.driver3, &args.driver4]
            .iter()
            .filter(|d| d.is_some())
            .count();
        if !(2..=4).contains(&n_drivers) {
            return Err(format!(
                "Multi-driver optimization requires 2-4 drivers, got {}",
                n_drivers
            ));
        }
    } else {
        // If not using drivers-flat loss, driver arguments should not be provided
        if args.driver1.is_some()
            || args.driver2.is_some()
            || args.driver3.is_some()
            || args.driver4.is_some()
        {
            return Err("Driver arguments (--driver1, --driver2, etc.) can only be used with --loss drivers-flat".to_string());
        }
    }

    Ok(())
}

/// Validate arguments and exit with error if validation fails
pub fn validate_args_or_exit(args: &Args) {
    if let Err(error) = validate_args(args) {
        eprintln!("❌ Validation Error: {}", error);
        process::exit(1);
    }
}

/// Display available PEQ models with descriptions and exit
pub fn display_peq_model_list() -> ! {
    println!("Available PEQ Models");
    println!("===================");
    println!();
    println!("The PEQ model defines the structure and constraints of the equalizer filters.");
    println!();

    for model in PeqModel::all() {
        println!("  --peq-model {}", model);
        println!("    {}", model.description());
        println!();
    }

    println!("Examples:");
    println!("  autoeq --peq-model pk           # All peak filters (default)");
    println!("  autoeq --peq-model hp-pk        # Highpass + peaks");
    println!("  autoeq --peq-model hp-pk-lp     # Highpass + peaks + lowpass");

    process::exit(0);
}

// Custom value parser to enforce strictly positive f64
fn parse_strictly_positive_f64(s: &str) -> Result<f64, String> {
    let v: f64 = s.parse().map_err(|_| format!("invalid float: {s}"))?;
    if v > 0.0 {
        Ok(v)
    } else {
        Err("value must be strictly positive (> 0)".to_string())
    }
}

// Custom value parser to enforce non-negative f64 (>= 0)
fn parse_nonnegative_f64(s: &str) -> Result<f64, String> {
    let v: f64 = s.parse().map_err(|_| format!("invalid float: {s}"))?;
    if v >= 0.0 {
        Ok(v)
    } else {
        Err("value must be non-negative (>= 0)".to_string())
    }
}

// Custom value parser to enforce recombination probability (0.0 to 1.0)
fn parse_recombination_probability(s: &str) -> Result<f64, String> {
    let v: f64 = s.parse().map_err(|_| format!("invalid float: {s}"))?;
    if (0.0..=1.0).contains(&v) {
        Ok(v)
    } else {
        Err("recombination probability must be between 0.0 and 1.0".to_string())
    }
}