autoeq-optim 0.5.58

AutoEQ objectives, constraints, and optimizer backends
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
use super::parse::parse_finite_f64;
use super::parse::parse_nonnegative_f64;
use super::parse::parse_recombination_probability;
use super::peq_model::PeqModel;
use crate::LossType;
use clap::Parser;
use std::path::PathBuf;
use std::process;

/// 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 signed dB gain allowed for each filter (the cut bound).
    #[arg(long, default_value_t = -12.0, value_parser = parse_finite_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., autoeq:isres, autoeq:cobyla)
    #[arg(long, default_value = "autoeq: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,

    /// Bayesian optimization Sobol hot-start samples (0 = automatic)
    #[arg(long, default_value_t = 0)]
    pub bo_initial_samples: usize,

    /// Bayesian optimization batch size for parallel expensive evaluations (0 = automatic)
    #[arg(long, default_value_t = 0)]
    pub bo_batch_size: usize,

    /// Bayesian optimization posterior-std threshold for local-refiner handoff (0 disables)
    #[arg(long, default_value_t = 0.0)]
    pub bo_posterior_std_threshold: f64,

    /// Bayesian optimization acquisition: ei, qei, or thompson
    #[arg(long, default_value = "qei")]
    pub bo_acquisition: String,

    /// Use Monte-Carlo qEHVI Bayesian optimization for multi-objective data
    #[arg(long, default_value_t = false)]
    pub bo_ehvi: bool,

    /// 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,

    /// Second-difference penalty weight on the correction curve (dB/decade^2).
    /// 0 disables. Suggested starting point: 0.05.
    #[arg(long, default_value_t = 0.0)]
    pub smoothness_weight: f64,

    /// L_p exponent for smoothness penalty (1.0 = TV^2/sparsifier, 2.0 = L2).
    #[arg(long, default_value_t = 1.0)]
    pub smoothness_exponent: f64,

    /// Schroeder cutoff for relaxed smoothness in the modal region.
    #[arg(long)]
    pub smoothness_schroeder_hz: Option<f64>,

    /// Modal-region weight multiplier (0 = exempt modal region entirely).
    #[arg(long, default_value_t = 0.1)]
    pub smoothness_modal_scale: 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(),
            // Bumped from the previous (population=50, maxeval=2000,
            // strategy="currenttobest1bin") defaults after some runs
            // failed to converge. L-SHADE adapts its mutation and
            // crossover rates per generation, so it handles noisy
            // room-EQ loss landscapes much better than the fixed-rate
            // strategies. 300/50000 is conservative for a 7-filter
            // problem — cheaper runs can still pick `--preset quick`.
            population: 300,
            maxeval: 50000,
            strategy: "lshade".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,
            smoothness_weight: 0.0,
            smoothness_exponent: 1.0,
            smoothness_schroeder_hz: None,
            smoothness_modal_scale: 0.1,
            smooth: true,
            smooth_n: 1,
            refine: false,
            local_algo: "cobyla".to_string(),
            bo_initial_samples: 0,
            bo_batch_size: 0,
            bo_posterior_std_threshold: 0.0,
            bo_acquisition: "qei".to_string(),
            bo_ehvi: false,
            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);
    }
}

#[cfg(test)]
mod tests {
    use super::super::peq_model::PeqModel;
    use super::Args;
    use crate::LossType;
    use clap::Parser;

    fn parsed_base() -> Args {
        Args::try_parse_from::<&[&str], _>(&["prog"]).unwrap()
    }

    #[test]
    fn speaker_defaults_match_expected_values() {
        let args = Args::speaker_defaults();
        assert_eq!(args.num_filters, 5);
        assert_eq!(args.sample_rate, 48000.0);
        assert_eq!(args.loss, LossType::SpeakerFlat);
        assert_eq!(args.algo, "autoeq:de");
        assert_eq!(args.population, 300);
        assert_eq!(args.maxeval, 50000);
        assert_eq!(args.strategy, "lshade");
        assert_eq!(args.min_db, -12.0);
        assert_eq!(args.max_db, 12.0);
        assert_eq!(args.min_q, 0.5);
        assert_eq!(args.max_q, 10.0);
        assert_eq!(args.min_freq, 20.0);
        assert_eq!(args.max_freq, 20000.0);
        assert_eq!(args.min_spacing_oct, 0.5);
        assert_eq!(args.smoothness_weight, 0.0);
        assert_eq!(args.smoothness_exponent, 1.0);
        assert_eq!(args.smoothness_modal_scale, 0.1);
        assert!(args.smooth);
        assert_eq!(args.smooth_n, 1);
        assert!(!args.refine);
        assert_eq!(args.peq_model, PeqModel::Pk);
    }

    #[test]
    fn parsed_cli_uses_canonical_cobyla_default() {
        assert_eq!(parsed_base().algo, "autoeq:cobyla");
    }

    #[test]
    fn headphone_defaults_use_headphone_score_loss() {
        let args = Args::headphone_defaults();
        assert_eq!(args.loss, LossType::HeadphoneScore);
        assert_eq!(args.num_filters, 7);
        assert_eq!(args.sample_rate, 48000.0);
    }

    #[test]
    fn roomeq_defaults_set_num_filters_and_max_freq() {
        let args = Args::roomeq_defaults();
        assert_eq!(args.num_filters, 10);
        assert_eq!(args.max_freq, 500.0);
    }

    #[test]
    fn apply_preset_quick_sets_expected_fields() {
        let mut args = parsed_base();
        args.preset = Some("quick".to_string());
        args.apply_preset();
        assert_eq!(args.num_filters, 5);
        assert_eq!(args.population, 40);
        assert_eq!(args.maxeval, 2000);
        assert!(!args.refine);
        assert_eq!(args.min_q, 0.5);
        assert_eq!(args.max_q, 6.0);
        assert_eq!(args.min_db, -12.0);
        assert_eq!(args.max_db, 6.0);
    }

    #[test]
    fn apply_preset_balanced_sets_expected_fields() {
        let mut args = parsed_base();
        args.preset = Some("balanced".to_string());
        args.apply_preset();
        assert_eq!(args.num_filters, 7);
        assert_eq!(args.population, 80);
        assert_eq!(args.maxeval, 5000);
        assert!(args.refine);
        assert_eq!(args.min_q, 0.5);
        assert_eq!(args.max_q, 6.0);
    }

    #[test]
    fn apply_preset_max_quality_sets_expected_fields() {
        let mut args = parsed_base();
        args.preset = Some("max-quality".to_string());
        args.apply_preset();
        assert_eq!(args.num_filters, 10);
        assert_eq!(args.peq_model, PeqModel::LsPkHs);
        assert_eq!(args.population, 200);
        assert_eq!(args.maxeval, 20000);
        assert!(args.refine);
    }

    #[test]
    fn apply_preset_score_sets_expected_fields() {
        let mut args = parsed_base();
        args.preset = Some("score".to_string());
        args.apply_preset();
        assert_eq!(args.num_filters, 7);
        assert_eq!(args.loss, LossType::SpeakerScore);
        assert_eq!(args.population, 100);
        assert_eq!(args.maxeval, 10000);
        assert!(args.refine);
    }

    #[test]
    fn apply_preset_unknown_does_not_panic() {
        let result = std::panic::catch_unwind(|| {
            let mut args = parsed_base();
            args.preset = Some("unknown-preset".to_string());
            args.apply_preset();
            args.num_filters
        });
        assert!(result.is_ok());
    }

    #[test]
    fn audit_cli_min_db_is_signed_lower_gain_bound() {
        assert_eq!(Args::speaker_defaults().min_db, -12.0);

        for preset in ["quick", "balanced", "max-quality", "score"] {
            let mut args = parsed_base();
            args.preset = Some(preset.to_string());
            args.apply_preset();
            assert_eq!(args.min_db, -12.0, "preset {preset}");
        }

        let parsed = Args::try_parse_from(["autoeq", "--min-db=-12"]).unwrap();
        assert_eq!(parsed.min_db, -12.0);
    }
}