Skip to main content

autoeq_optim/cli/
args.rs

1use super::parse::parse_finite_f64;
2use super::parse::parse_nonnegative_f64;
3use super::parse::parse_recombination_probability;
4use super::peq_model::PeqModel;
5use crate::LossType;
6use clap::Parser;
7use std::path::PathBuf;
8use std::process;
9
10/// Shared CLI arguments for AutoEQ binaries.
11#[derive(Parser, Debug, Clone)]
12#[command(author, about, long_about = None)]
13pub struct Args {
14    /// Number of IIR filters to use for optimization.
15    #[arg(short = 'n', long, default_value_t = 7)]
16    pub num_filters: usize,
17
18    /// Path to the input curve CSV file (format: frequency,spl).
19    /// Required unless speaker, version, and measurement are provided for API data.
20    #[arg(short, long)]
21    pub curve: Option<PathBuf>,
22
23    /// Path to the optional target curve CSV file (format: frequency,spl).
24    /// If not provided, a flat 0 dB target is assumed.
25    #[arg(short, long)]
26    pub target: Option<PathBuf>,
27
28    /// The sample rate for the IIR filters.
29    #[arg(short, long, default_value_t = 48000.0)]
30    pub sample_rate: f64,
31
32    /// Maximum absolute dB gain allowed for each filter.
33    #[arg(long, default_value_t = 3.0, value_parser = parse_nonnegative_f64)]
34    pub max_db: f64,
35
36    /// Minimum signed dB gain allowed for each filter (the cut bound).
37    #[arg(long, default_value_t = -12.0, value_parser = parse_finite_f64)]
38    pub min_db: f64,
39
40    /// Maximum Q factor allowed for each filter.
41    #[arg(long, default_value_t = 3.0)]
42    pub max_q: f64,
43
44    /// Minimum Q factor allowed for each filter.
45    #[arg(long, default_value_t = 1.0)]
46    pub min_q: f64,
47
48    /// Minimum frequency allowed for each filter.
49    #[arg(long, default_value_t = 60.0)]
50    pub min_freq: f64,
51
52    /// Maximum frequency allowed for each filter.
53    #[arg(long, default_value_t = 16000.0)]
54    pub max_freq: f64,
55
56    /// Output PNG file for plotting results.
57    #[arg(short, long)]
58    pub output: Option<PathBuf>,
59
60    /// Speaker name for API data fetching.
61    #[arg(long)]
62    pub speaker: Option<String>,
63
64    /// Version for API data fetching.
65    #[arg(long)]
66    pub version: Option<String>,
67
68    /// Measurement type for API data fetching.
69    #[arg(long)]
70    pub measurement: Option<String>,
71
72    /// Curve name inside CEA2034 plots to use (only when --measurement CEA2034)
73    /// e.g., "Listening Window", "On Axis", "Early Reflections". Default: Listening Window
74    #[arg(long, default_value = "Listening Window")]
75    pub curve_name: String,
76
77    /// Optimization algorithm to use (e.g., autoeq:isres, autoeq:cobyla)
78    #[arg(long, default_value = "autoeq:cobyla")]
79    pub algo: String,
80
81    /// Optional population size for population-based algorithms (e.g., ISRES)
82    #[arg(long, default_value_t = 300)]
83    pub population: usize,
84
85    /// Maximum number of evaluations for the optimizer
86    #[arg(long, default_value_t = 2_000)]
87    pub maxeval: usize,
88
89    /// Whether to run a local refinement after global optimization
90    #[arg(long, default_value_t = false)]
91    pub refine: bool,
92
93    /// Local optimizer to use for refinement (e.g., cobyla)
94    #[arg(long, default_value = "cobyla")]
95    pub local_algo: String,
96
97    /// Bayesian optimization Sobol hot-start samples (0 = automatic)
98    #[arg(long, default_value_t = 0)]
99    pub bo_initial_samples: usize,
100
101    /// Bayesian optimization batch size for parallel expensive evaluations (0 = automatic)
102    #[arg(long, default_value_t = 0)]
103    pub bo_batch_size: usize,
104
105    /// Bayesian optimization posterior-std threshold for local-refiner handoff (0 disables)
106    #[arg(long, default_value_t = 0.0)]
107    pub bo_posterior_std_threshold: f64,
108
109    /// Bayesian optimization acquisition: ei, qei, or thompson
110    #[arg(long, default_value = "qei")]
111    pub bo_acquisition: String,
112
113    /// Use Monte-Carlo qEHVI Bayesian optimization for multi-objective data
114    #[arg(long, default_value_t = false)]
115    pub bo_ehvi: bool,
116
117    /// Minimum spacing between filter center frequencies in octaves (0 disables)
118    #[arg(long, default_value_t = 0.2)]
119    pub min_spacing_oct: f64,
120
121    /// Weight for the spacing penalty in the objective function
122    #[arg(long, default_value_t = 20.0)]
123    pub spacing_weight: f64,
124
125    /// Second-difference penalty weight on the correction curve (dB/decade^2).
126    /// 0 disables. Suggested starting point: 0.05.
127    #[arg(long, default_value_t = 0.0)]
128    pub smoothness_weight: f64,
129
130    /// L_p exponent for smoothness penalty (1.0 = TV^2/sparsifier, 2.0 = L2).
131    #[arg(long, default_value_t = 1.0)]
132    pub smoothness_exponent: f64,
133
134    /// Schroeder cutoff for relaxed smoothness in the modal region.
135    #[arg(long)]
136    pub smoothness_schroeder_hz: Option<f64>,
137
138    /// Modal-region weight multiplier (0 = exempt modal region entirely).
139    #[arg(long, default_value_t = 0.1)]
140    pub smoothness_modal_scale: f64,
141
142    /// Enable smoothing (regularization) of the inverted target curve
143    #[arg(long, default_value_t = true)]
144    pub smooth: bool,
145
146    /// Smoothing level as 1/N octave (N in [1..24]). Example: N=6 => 1/6 octave smoothing
147    #[arg(long, default_value_t = 2)]
148    pub smooth_n: usize,
149
150    /// Loss function to optimize (flat or score).
151    #[arg(long, value_enum, default_value_t = LossType::SpeakerFlat)]
152    pub loss: LossType,
153
154    /// PEQ model that defines the filter structure
155    #[arg(long, value_enum, default_value_t = PeqModel::Pk)]
156    pub peq_model: PeqModel,
157
158    /// Display list of available PEQ models with descriptions and exit.
159    #[arg(long, default_value_t = false)]
160    pub peq_model_list: bool,
161
162    /// Display list of available optimization algorithms with descriptions and exit.
163    #[arg(long, default_value_t = false)]
164    pub algo_list: bool,
165
166    /// Optimization tolerance (tol parameter for DE algorithm)
167    #[arg(long, default_value_t = 1e-3)]
168    pub tolerance: f64,
169
170    /// Absolute tolerance (atol parameter for DE algorithm)
171    #[arg(long, default_value_t = 1e-4)]
172    pub atolerance: f64,
173
174    /// Recombination probability for DE algorithm (0.0 to 1.0)
175    #[arg(long, default_value_t = 0.9, value_parser = parse_recombination_probability)]
176    pub recombination: f64,
177
178    /// DE strategy to use (e.g., best1bin, rand1bin, currenttobest1bin, adaptive)
179    #[arg(long, default_value = "currenttobest1bin")]
180    pub strategy: String,
181
182    /// Display list of available DE strategies and exit.
183    #[arg(long, default_value_t = false)]
184    pub strategy_list: bool,
185
186    /// Adaptive weight for F parameter (DE adaptive strategies only)
187    #[arg(long, default_value_t = 0.9)]
188    pub adaptive_weight_f: f64,
189
190    /// Adaptive weight for CR parameter (DE adaptive strategies only)
191    #[arg(long, default_value_t = 0.9)]
192    pub adaptive_weight_cr: f64,
193
194    /// Disable parallel evaluation for DE algorithm (default: parallel is enabled)
195    #[arg(long = "no-parallel", default_value_t = false)]
196    pub no_parallel: bool,
197
198    /// Number of threads to use for parallel evaluation (0 = use all available cores)
199    #[arg(long, default_value_t = 0)]
200    pub parallel_threads: usize,
201
202    /// Random seed for deterministic optimization (default: random seed for each run)
203    /// Setting this makes optimization results reproducible
204    #[arg(long)]
205    pub seed: Option<u64>,
206
207    /// Quality assurance mode with optional threshold: suppress normal output, show summary line and analysis
208    /// If a threshold is provided (e.g., --qa 0.4), also perform QA analysis
209    #[arg(long, value_name = "THRESHOLD")]
210    pub qa: Option<f64>,
211
212    /// Path to first driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
213    #[arg(long)]
214    pub driver1: Option<PathBuf>,
215
216    /// Path to second driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
217    #[arg(long)]
218    pub driver2: Option<PathBuf>,
219
220    /// Path to third driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
221    #[arg(long)]
222    pub driver3: Option<PathBuf>,
223
224    /// Path to fourth driver measurement CSV file (for multi-driver optimization with --loss drivers-flat)
225    #[arg(long)]
226    pub driver4: Option<PathBuf>,
227
228    /// Crossover type for multi-driver optimization (butterworth2, linkwitzriley2, linkwitzriley4)
229    #[arg(long, default_value = "linkwitzriley4")]
230    pub crossover_type: String,
231
232    /// Use a named preset that sets all optimizer parameters at once.
233    /// Available presets: quick, balanced, max-quality, score (speakers only).
234    /// Individual parameter flags override preset values when both are specified.
235    #[arg(long)]
236    pub preset: Option<String>,
237}
238
239impl Args {
240    /// Get the effective PEQ model
241    pub fn effective_peq_model(&self) -> PeqModel {
242        self.peq_model
243    }
244
245    /// Check if the first filter should be a highpass (for compatibility)
246    pub fn uses_highpass_first(&self) -> bool {
247        matches!(
248            self.effective_peq_model(),
249            PeqModel::HpPk | PeqModel::HpPkLp
250        )
251    }
252
253    /// Create Args with speaker optimization defaults
254    ///
255    /// These defaults are tuned for typical speaker EQ optimization using
256    /// CEA2034 measurements from spinorama.org.
257    pub fn speaker_defaults() -> Self {
258        Self {
259            num_filters: 5,
260            sample_rate: 48000.0,
261            loss: LossType::SpeakerFlat,
262            algo: "autoeq:de".to_string(),
263            // Bumped from the previous (population=50, maxeval=2000,
264            // strategy="currenttobest1bin") defaults after some runs
265            // failed to converge. L-SHADE adapts its mutation and
266            // crossover rates per generation, so it handles noisy
267            // room-EQ loss landscapes much better than the fixed-rate
268            // strategies. 300/50000 is conservative for a 7-filter
269            // problem — cheaper runs can still pick `--preset quick`.
270            population: 300,
271            maxeval: 50000,
272            strategy: "lshade".to_string(),
273            min_db: -12.0,
274            max_db: 12.0,
275            min_q: 0.5,
276            max_q: 10.0,
277            min_freq: 20.0,
278            max_freq: 20000.0,
279            min_spacing_oct: 0.5,
280            spacing_weight: 20.0,
281            smoothness_weight: 0.0,
282            smoothness_exponent: 1.0,
283            smoothness_schroeder_hz: None,
284            smoothness_modal_scale: 0.1,
285            smooth: true,
286            smooth_n: 1,
287            refine: false,
288            local_algo: "cobyla".to_string(),
289            bo_initial_samples: 0,
290            bo_batch_size: 0,
291            bo_posterior_std_threshold: 0.0,
292            bo_acquisition: "qei".to_string(),
293            bo_ehvi: false,
294            tolerance: 1e-3,
295            atolerance: 1e-4,
296            recombination: 0.9,
297            adaptive_weight_f: 0.8,
298            adaptive_weight_cr: 0.7,
299            peq_model: PeqModel::Pk,
300            curve_name: "Listening Window".to_string(),
301            // File paths/flags default to None/false
302            curve: None,
303            target: None,
304            output: None,
305            speaker: None,
306            version: None,
307            measurement: None,
308            peq_model_list: false,
309            algo_list: false,
310            strategy_list: false,
311            no_parallel: false,
312            parallel_threads: 0,
313            seed: None,
314            qa: None,
315            driver1: None,
316            driver2: None,
317            driver3: None,
318            driver4: None,
319            crossover_type: "linkwitzriley4".to_string(),
320            preset: None,
321        }
322    }
323
324    /// Create Args with headphone optimization defaults
325    ///
326    /// These defaults are tuned for headphone EQ optimization using
327    /// frequency response measurements and Harman target curves.
328    pub fn headphone_defaults() -> Self {
329        Self {
330            loss: LossType::HeadphoneScore,
331            num_filters: 7,
332            ..Self::speaker_defaults()
333        }
334    }
335
336    /// Create Args with room EQ optimization defaults
337    ///
338    /// These defaults are tuned for room correction, focusing on
339    /// low frequencies where room modes are most problematic.
340    pub fn roomeq_defaults() -> Self {
341        Self {
342            num_filters: 10,
343            max_freq: 500.0, // Room EQ focuses on low frequencies
344            ..Self::speaker_defaults()
345        }
346    }
347
348    /// Apply a named preset, setting optimizer parameters to tuned values.
349    /// Call this after parsing CLI args. Parameters explicitly set by the user
350    /// are not tracked by clap, so this method overwrites all optimizer fields.
351    /// The caller should parse args, call `apply_preset()`, then override
352    /// any fields they want to customize.
353    ///
354    /// NOTE: These preset values are intentionally duplicated from
355    /// `sotf-player::autoeq::presets` because the `autoeq` crate cannot
356    /// depend on `sotf-player`. Keep values in sync when updating presets.
357    ///
358    /// Available presets:
359    /// - `quick`: 5 filters, fast (pop 40, maxeval 2000, no refine)
360    /// - `balanced`: 7 filters, good balance (pop 80, maxeval 5000, refine)
361    /// - `max-quality`: 10 filters, best results (pop 200, maxeval 20000, ls-pk-hs, refine)
362    /// - `score`: 7 filters, listener preference score (speaker-score loss)
363    pub fn apply_preset(&mut self) {
364        let preset_name = match &self.preset {
365            Some(name) => name.clone(),
366            None => return,
367        };
368        match preset_name.as_str() {
369            "quick" => {
370                self.num_filters = 5;
371                self.population = 40;
372                self.maxeval = 2000;
373                self.refine = false;
374                self.min_q = 0.5;
375                self.max_q = 6.0;
376                self.min_db = -12.0;
377                self.max_db = 6.0;
378            }
379            "balanced" => {
380                self.num_filters = 7;
381                self.population = 80;
382                self.maxeval = 5000;
383                self.refine = true;
384                self.min_q = 0.5;
385                self.max_q = 6.0;
386                self.min_db = -12.0;
387                self.max_db = 6.0;
388            }
389            "max-quality" => {
390                self.num_filters = 10;
391                self.peq_model = PeqModel::LsPkHs;
392                self.population = 200;
393                self.maxeval = 20000;
394                self.refine = true;
395                self.min_q = 0.5;
396                self.max_q = 6.0;
397                self.min_db = -12.0;
398                self.max_db = 6.0;
399            }
400            "score" => {
401                self.num_filters = 7;
402                self.loss = LossType::SpeakerScore;
403                self.population = 100;
404                self.maxeval = 10000;
405                self.refine = true;
406                self.min_q = 0.5;
407                self.max_q = 6.0;
408                self.min_db = -12.0;
409                self.max_db = 6.0;
410            }
411            other => {
412                eprintln!(
413                    "Warning: unknown preset '{}'. Available: quick, balanced, max-quality, score",
414                    other
415                );
416            }
417        }
418    }
419
420    /// Display available presets and exit.
421    pub fn display_preset_list() -> ! {
422        println!("Available Presets");
423        println!("=================\n");
424        println!("  quick        5 filters, fast optimization (seconds)");
425        println!("  balanced     7 filters, good balance of quality and speed (default)");
426        println!("  max-quality  10 filters with shelves, best results (slow)");
427        println!("  score        7 filters, listener preference score optimization");
428        println!("\nUse: --preset <name>");
429        println!("Individual flags (e.g. -n, --max-q) override preset values.");
430        process::exit(0);
431    }
432}
433
434#[cfg(test)]
435mod tests {
436    use super::super::peq_model::PeqModel;
437    use super::Args;
438    use crate::LossType;
439    use clap::Parser;
440
441    fn parsed_base() -> Args {
442        Args::try_parse_from::<&[&str], _>(&["prog"]).unwrap()
443    }
444
445    #[test]
446    fn speaker_defaults_match_expected_values() {
447        let args = Args::speaker_defaults();
448        assert_eq!(args.num_filters, 5);
449        assert_eq!(args.sample_rate, 48000.0);
450        assert_eq!(args.loss, LossType::SpeakerFlat);
451        assert_eq!(args.algo, "autoeq:de");
452        assert_eq!(args.population, 300);
453        assert_eq!(args.maxeval, 50000);
454        assert_eq!(args.strategy, "lshade");
455        assert_eq!(args.min_db, -12.0);
456        assert_eq!(args.max_db, 12.0);
457        assert_eq!(args.min_q, 0.5);
458        assert_eq!(args.max_q, 10.0);
459        assert_eq!(args.min_freq, 20.0);
460        assert_eq!(args.max_freq, 20000.0);
461        assert_eq!(args.min_spacing_oct, 0.5);
462        assert_eq!(args.smoothness_weight, 0.0);
463        assert_eq!(args.smoothness_exponent, 1.0);
464        assert_eq!(args.smoothness_modal_scale, 0.1);
465        assert!(args.smooth);
466        assert_eq!(args.smooth_n, 1);
467        assert!(!args.refine);
468        assert_eq!(args.peq_model, PeqModel::Pk);
469    }
470
471    #[test]
472    fn parsed_cli_uses_canonical_cobyla_default() {
473        assert_eq!(parsed_base().algo, "autoeq:cobyla");
474    }
475
476    #[test]
477    fn headphone_defaults_use_headphone_score_loss() {
478        let args = Args::headphone_defaults();
479        assert_eq!(args.loss, LossType::HeadphoneScore);
480        assert_eq!(args.num_filters, 7);
481        assert_eq!(args.sample_rate, 48000.0);
482    }
483
484    #[test]
485    fn roomeq_defaults_set_num_filters_and_max_freq() {
486        let args = Args::roomeq_defaults();
487        assert_eq!(args.num_filters, 10);
488        assert_eq!(args.max_freq, 500.0);
489    }
490
491    #[test]
492    fn apply_preset_quick_sets_expected_fields() {
493        let mut args = parsed_base();
494        args.preset = Some("quick".to_string());
495        args.apply_preset();
496        assert_eq!(args.num_filters, 5);
497        assert_eq!(args.population, 40);
498        assert_eq!(args.maxeval, 2000);
499        assert!(!args.refine);
500        assert_eq!(args.min_q, 0.5);
501        assert_eq!(args.max_q, 6.0);
502        assert_eq!(args.min_db, -12.0);
503        assert_eq!(args.max_db, 6.0);
504    }
505
506    #[test]
507    fn apply_preset_balanced_sets_expected_fields() {
508        let mut args = parsed_base();
509        args.preset = Some("balanced".to_string());
510        args.apply_preset();
511        assert_eq!(args.num_filters, 7);
512        assert_eq!(args.population, 80);
513        assert_eq!(args.maxeval, 5000);
514        assert!(args.refine);
515        assert_eq!(args.min_q, 0.5);
516        assert_eq!(args.max_q, 6.0);
517    }
518
519    #[test]
520    fn apply_preset_max_quality_sets_expected_fields() {
521        let mut args = parsed_base();
522        args.preset = Some("max-quality".to_string());
523        args.apply_preset();
524        assert_eq!(args.num_filters, 10);
525        assert_eq!(args.peq_model, PeqModel::LsPkHs);
526        assert_eq!(args.population, 200);
527        assert_eq!(args.maxeval, 20000);
528        assert!(args.refine);
529    }
530
531    #[test]
532    fn apply_preset_score_sets_expected_fields() {
533        let mut args = parsed_base();
534        args.preset = Some("score".to_string());
535        args.apply_preset();
536        assert_eq!(args.num_filters, 7);
537        assert_eq!(args.loss, LossType::SpeakerScore);
538        assert_eq!(args.population, 100);
539        assert_eq!(args.maxeval, 10000);
540        assert!(args.refine);
541    }
542
543    #[test]
544    fn apply_preset_unknown_does_not_panic() {
545        let result = std::panic::catch_unwind(|| {
546            let mut args = parsed_base();
547            args.preset = Some("unknown-preset".to_string());
548            args.apply_preset();
549            args.num_filters
550        });
551        assert!(result.is_ok());
552    }
553
554    #[test]
555    fn audit_cli_min_db_is_signed_lower_gain_bound() {
556        assert_eq!(Args::speaker_defaults().min_db, -12.0);
557
558        for preset in ["quick", "balanced", "max-quality", "score"] {
559            let mut args = parsed_base();
560            args.preset = Some(preset.to_string());
561            args.apply_preset();
562            assert_eq!(args.min_db, -12.0, "preset {preset}");
563        }
564
565        let parsed = Args::try_parse_from(["autoeq", "--min-db=-12"]).unwrap();
566        assert_eq!(parsed.min_db, -12.0);
567    }
568}