math-sonify 1.4.0

Real-time procedural audio from mathematical dynamical systems (Lorenz, Rossler, Double Pendulum, and more)
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
// Config types are used in the binary but appear unused in the lib (plugin) build context.
#![allow(dead_code)]

use crate::sonification::{Scale, SonifMode};
use serde::{Deserialize, Serialize};

/// Top-level application configuration, loaded from `config.toml`.
///
/// All fields have defaults via [`Default`]; call [`Config::validate`] after
/// loading from disk to clamp every value to a physically sensible range.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Config {
    pub system: SystemConfig,
    pub sonification: SonificationConfig,
    pub audio: AudioConfig,
    pub lorenz: LorenzConfig,
    pub rossler: RosslerConfig,
    pub double_pendulum: DoublePendulumConfig,
    pub geodesic_torus: GeodesicTorusConfig,
    pub kuramoto: KuramotoConfig,
    pub viz: VizConfig,
    pub duffing: DuffingConfig,
    pub van_der_pol: VanDerPolConfig,
    pub halvorsen: HalvorsenConfig,
    pub aizawa: AizawaConfig,
    pub chua: ChuaConfig,
    pub hindmarsh_rose: HindmarshRoseConfig,
    pub coupled_map_lattice: CmlConfig,
    pub mackey_glass: MackeyGlassConfig,
    pub nose_hoover: NoseHooverConfig,
    pub henon_map: HenonMapConfig,
    pub lorenz96: Lorenz96Config,
    pub logistic_map: LogisticMapConfig,
    pub standard_map: StandardMapConfig,
    pub stochastic_lorenz: StochasticLorenzConfig,
    pub delayed_map: DelayedMapConfig,
    pub oregonator: OregonatorConfig,
    pub mathieu: MathieuConfig,
    pub kuramoto_driven: KuramotoDrivenConfig,
    pub thomas: ThomasConfig,
    pub burke_shaw: BurkeShawConfig,
    pub chen: ChenConfig,
    pub dadras: DadrasConfig,
    pub rucklidge: RucklidgeConfig,
    pub lorenz84: Lorenz84Config,
    pub rabinovich_fabrikant: RabinovichFabrikantConfig,
    pub rikitake: RikitakeConfig,
    pub fractional_lorenz: FractionalLorenzConfig,
    pub bouali: BoualiConfig,
    pub newton_leipnik: NewtonLeipnikConfig,
    pub shimizu_morioka: ShimizuMoriokaConfig,
    pub genesio_tesi: GenesioTesiConfig,
    pub liu: LiuConfig,
    pub windmi: WindmiConfig,
    pub finance: FinanceConfig,
    pub hyperchaos: HyperchaosConfig,
    pub tinkerbell: TinkerbellConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            system: SystemConfig::default(),
            sonification: SonificationConfig::default(),
            audio: AudioConfig::default(),
            lorenz: LorenzConfig::default(),
            rossler: RosslerConfig::default(),
            double_pendulum: DoublePendulumConfig::default(),
            geodesic_torus: GeodesicTorusConfig::default(),
            kuramoto: KuramotoConfig::default(),
            viz: VizConfig::default(),
            duffing: DuffingConfig::default(),
            van_der_pol: VanDerPolConfig::default(),
            halvorsen: HalvorsenConfig::default(),
            aizawa: AizawaConfig::default(),
            chua: ChuaConfig::default(),
            hindmarsh_rose: HindmarshRoseConfig::default(),
            coupled_map_lattice: CmlConfig::default(),
            mackey_glass: MackeyGlassConfig::default(),
            nose_hoover: NoseHooverConfig::default(),
            henon_map: HenonMapConfig::default(),
            lorenz96: Lorenz96Config::default(),
            logistic_map: LogisticMapConfig::default(),
            standard_map: StandardMapConfig::default(),
            stochastic_lorenz: StochasticLorenzConfig::default(),
            delayed_map: DelayedMapConfig::default(),
            oregonator: OregonatorConfig::default(),
            mathieu: MathieuConfig::default(),
            kuramoto_driven: KuramotoDrivenConfig::default(),
            thomas: ThomasConfig::default(),
            burke_shaw: BurkeShawConfig::default(),
            chen: ChenConfig::default(),
            dadras: DadrasConfig::default(),
            rucklidge: RucklidgeConfig::default(),
            lorenz84: Lorenz84Config::default(),
            rabinovich_fabrikant: RabinovichFabrikantConfig::default(),
            rikitake: RikitakeConfig::default(),
            fractional_lorenz: FractionalLorenzConfig::default(),
            bouali: BoualiConfig::default(),
            newton_leipnik: NewtonLeipnikConfig::default(),
            shimizu_morioka: ShimizuMoriokaConfig::default(),
            genesio_tesi: GenesioTesiConfig::default(),
            liu: LiuConfig::default(),
            windmi: WindmiConfig::default(),
            finance: FinanceConfig::default(),
            hyperchaos: HyperchaosConfig::default(),
            tinkerbell: TinkerbellConfig::default(),
        }
    }
}

/// Phase-portrait visualization settings.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct VizConfig {
    pub trail_length: usize,
    pub projection: String,
    pub glow: bool,
    pub theme: String,
}

impl Default for VizConfig {
    fn default() -> Self {
        Self {
            trail_length: 800,
            projection: "xy".into(),
            glow: true,
            theme: "neon".into(),
        }
    }
}

/// Dynamical system selection and integration parameters.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SystemConfig {
    pub name: String,
    pub dt: f64,
    pub speed: f64,
}

impl Default for SystemConfig {
    fn default() -> Self {
        Self {
            name: "lorenz".into(),
            dt: 0.001,
            speed: 1.0,
        }
    }
}

/// Sonification mapping parameters: mode, scale, pitch, and per-voice settings.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SonificationConfig {
    pub mode: String,
    pub scale: String,
    pub base_frequency: f64,
    pub octave_range: f64,
    pub transpose_semitones: f32,
    pub chord_mode: String,
    pub voice_levels: [f32; 4],
    pub portamento_ms: f32,
    pub voice_shapes: [String; 4],
}

impl Default for SonificationConfig {
    fn default() -> Self {
        Self {
            mode: "direct".into(),
            scale: "pentatonic".into(),
            base_frequency: 220.0,
            octave_range: 3.0,
            transpose_semitones: 0.0,
            chord_mode: "none".into(),
            voice_levels: [1.0, 0.8, 0.6, 0.4],
            portamento_ms: 80.0,
            voice_shapes: ["sine".into(), "sine".into(), "sine".into(), "sine".into()],
        }
    }
}

/// Audio engine and effects chain parameters.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct AudioConfig {
    pub sample_rate: u32,
    pub buffer_size: u32,
    pub reverb_wet: f32,
    pub delay_ms: f32,
    pub delay_feedback: f32,
    pub master_volume: f32,
    pub bit_depth: f32,
    pub rate_crush: f32,
    pub chorus_mix: f32,
    pub chorus_rate: f32,
    pub chorus_depth: f32,
    pub waveshaper_drive: f32,
    pub waveshaper_mix: f32,
    /// Simulation control rate in Hz. Default 120 Hz. Range: [30, 960].
    pub control_rate_hz: f64,
}

impl Default for AudioConfig {
    fn default() -> Self {
        Self {
            sample_rate: 44100,
            buffer_size: 512,
            reverb_wet: 0.4,
            delay_ms: 300.0,
            delay_feedback: 0.3,
            master_volume: 0.7,
            bit_depth: 16.0,
            rate_crush: 0.0,
            chorus_mix: 0.0,
            chorus_rate: 0.5,
            chorus_depth: 3.0,
            waveshaper_drive: 1.0,
            waveshaper_mix: 0.0,
            control_rate_hz: 120.0,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct LorenzConfig {
    pub sigma: f64,
    pub rho: f64,
    pub beta: f64,
}
impl Default for LorenzConfig {
    fn default() -> Self {
        Self {
            sigma: 10.0,
            rho: 28.0,
            beta: 2.6667,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct RosslerConfig {
    pub a: f64,
    pub b: f64,
    pub c: f64,
}
impl Default for RosslerConfig {
    fn default() -> Self {
        Self {
            a: 0.2,
            b: 0.2,
            c: 5.7,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DoublePendulumConfig {
    pub m1: f64,
    pub m2: f64,
    pub l1: f64,
    pub l2: f64,
}
impl Default for DoublePendulumConfig {
    fn default() -> Self {
        Self {
            m1: 1.0,
            m2: 1.0,
            l1: 1.0,
            l2: 1.0,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct GeodesicTorusConfig {
    #[serde(rename = "R")]
    pub big_r: f64,
    pub r: f64,
}
impl Default for GeodesicTorusConfig {
    fn default() -> Self {
        Self { big_r: 3.0, r: 1.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct KuramotoConfig {
    pub n_oscillators: usize,
    pub coupling: f64,
}
impl Default for KuramotoConfig {
    fn default() -> Self {
        Self {
            n_oscillators: 8,
            coupling: 1.5,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DuffingConfig {
    pub delta: f64,
    pub alpha: f64,
    pub beta: f64,
    pub gamma: f64,
    pub omega: f64,
}
impl Default for DuffingConfig {
    fn default() -> Self {
        Self {
            delta: 0.3,
            alpha: -1.0,
            beta: 1.0,
            gamma: 0.5,
            omega: 1.2,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct VanDerPolConfig {
    pub mu: f64,
}
impl Default for VanDerPolConfig {
    fn default() -> Self {
        Self { mu: 2.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct HalvorsenConfig {
    pub a: f64,
}
impl Default for HalvorsenConfig {
    fn default() -> Self {
        Self { a: 1.89 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct AizawaConfig {
    pub a: f64,
    pub b: f64,
    pub c: f64,
    pub d: f64,
    pub e: f64,
    pub f: f64,
}
impl Default for AizawaConfig {
    fn default() -> Self {
        Self {
            a: 0.95,
            b: 0.7,
            c: 0.6,
            d: 3.5,
            e: 0.25,
            f: 0.1,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ChuaConfig {
    pub alpha: f64,
    pub beta: f64,
    pub m0: f64,
    pub m1: f64,
}
impl Default for ChuaConfig {
    fn default() -> Self {
        Self {
            alpha: 15.6,
            beta: 28.0,
            m0: -1.143,
            m1: -0.714,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct HindmarshRoseConfig {
    pub current_i: f64, // external drive current — main control parameter
    pub r: f64,         // slow adaptation timescale
}
impl Default for HindmarshRoseConfig {
    fn default() -> Self {
        Self {
            current_i: 3.0,
            r: 0.006,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct CmlConfig {
    pub r: f64,   // logistic growth rate (3.7–4.0 for chaos)
    pub eps: f64, // coupling strength (0=independent, 1=synchrony)
}
impl Default for CmlConfig {
    fn default() -> Self {
        Self { r: 3.9, eps: 0.35 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct MackeyGlassConfig {
    pub beta: f64,
    pub gamma: f64,
    pub tau: f64,
    pub n: f64,
}
impl Default for MackeyGlassConfig {
    fn default() -> Self {
        Self {
            beta: 0.2,
            gamma: 0.1,
            tau: 17.0,
            n: 10.0,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct NoseHooverConfig {
    pub a: f64,
}
impl Default for NoseHooverConfig {
    fn default() -> Self {
        Self { a: 3.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct HenonMapConfig {
    pub a: f64,
    pub b: f64,
}
impl Default for HenonMapConfig {
    fn default() -> Self {
        Self { a: 1.4, b: 0.3 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Lorenz96Config {
    pub f: f64,
}
impl Default for Lorenz96Config {
    fn default() -> Self {
        Self { f: 8.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct LogisticMapConfig {
    /// Bifurcation parameter r. Chaotic regime: r > 3.57. Default: 3.9.
    pub r: f64,
}
impl Default for LogisticMapConfig {
    fn default() -> Self {
        Self { r: 3.9 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct StandardMapConfig {
    /// Stochasticity parameter k. Global chaos for k > 0.97. Default: 1.5.
    pub k: f64,
}
impl Default for StandardMapConfig {
    fn default() -> Self {
        Self { k: 1.5 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct StochasticLorenzConfig {
    pub sigma: f64,
    pub rho: f64,
    pub beta: f64,
    pub noise_strength: f64,
}
impl Default for StochasticLorenzConfig {
    fn default() -> Self {
        Self { sigma: 10.0, rho: 28.0, beta: 2.6667, noise_strength: 0.5 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DelayedMapConfig {
    pub r: f64,
    pub tau: usize,
}
impl Default for DelayedMapConfig {
    fn default() -> Self {
        Self { r: 3.9, tau: 5 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct OregonatorConfig {
    pub f: f64,
}
impl Default for OregonatorConfig {
    fn default() -> Self {
        Self { f: 1.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct MathieuConfig {
    pub a: f64,
    pub q: f64,
}
impl Default for MathieuConfig {
    fn default() -> Self {
        Self { a: 0.0, q: 0.5 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct KuramotoDrivenConfig {
    pub coupling: f64,
    pub drive_amp: f64,
    pub drive_freq: f64,
}
impl Default for KuramotoDrivenConfig {
    fn default() -> Self {
        Self { coupling: 1.0, drive_amp: 0.5, drive_freq: 1.2 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ThomasConfig {
    /// Dissipation parameter. b ≈ 0.208186 gives a strange attractor.
    pub b: f64,
}
impl Default for ThomasConfig {
    fn default() -> Self {
        Self { b: 0.208186 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct BurkeShawConfig {
    /// Contraction rate (σ). Default 10.0 gives robust chaos.
    pub sigma: f64,
    /// Second parameter (ρ). Default 4.272 maintains the two-scroll attractor.
    pub rho: f64,
}
impl Default for BurkeShawConfig {
    fn default() -> Self {
        Self { sigma: 10.0, rho: 4.272 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ChenConfig {
    /// First parameter (a). Default 40 gives chaotic double-scroll.
    pub a: f64,
    /// Second parameter (b). Default 3.
    pub b: f64,
    /// Third parameter (c). Default 28 (same as Lorenz rho).
    pub c: f64,
}
impl Default for ChenConfig {
    fn default() -> Self {
        Self { a: 40.0, b: 3.0, c: 28.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DadrasConfig {
    pub a: f64,
    pub b: f64,
    pub c: f64,
    pub d: f64,
    pub e: f64,
}
impl Default for DadrasConfig {
    fn default() -> Self {
        Self { a: 3.0, b: 2.7, c: 1.7, d: 2.0, e: 9.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct RucklidgeConfig {
    /// Dissipation (κ). Default 2.0.
    pub kappa: f64,
    /// Forcing amplitude (λ). Default 6.7 gives chaos.
    pub lambda: f64,
}
impl Default for RucklidgeConfig {
    fn default() -> Self {
        Self { kappa: 2.0, lambda: 6.7 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Lorenz84Config {
    /// Thermal relaxation rate. Default 0.25.
    pub a: f64,
    /// Rotational forcing. Default 4.0.
    pub b: f64,
    /// Symmetric heating forcing. Default 8.0.
    pub f: f64,
    /// Wave (seasonal) forcing. Default 1.23.
    pub g: f64,
}
impl Default for Lorenz84Config {
    fn default() -> Self {
        Self { a: 0.25, b: 4.0, f: 8.0, g: 1.23 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct RabinovichFabrikantConfig {
    /// Damping parameter (α). Default 0.14.
    pub alpha: f64,
    /// Excitation parameter (γ). Default 0.1.
    pub gamma: f64,
}
impl Default for RabinovichFabrikantConfig {
    fn default() -> Self {
        Self { alpha: 0.14, gamma: 0.1 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct RikitakeConfig {
    /// Dissipation rate (μ). Default 1.0.
    pub mu: f64,
    /// Coupling offset (a). Default 5.0.
    pub a: f64,
}
impl Default for RikitakeConfig {
    fn default() -> Self {
        Self { mu: 1.0, a: 5.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FractionalLorenzConfig {
    /// Fractional order α ∈ (0, 1]. α=1 recovers the standard Lorenz system.
    pub alpha: f64,
    /// σ parameter (same role as in standard Lorenz). Default 10.0.
    pub sigma: f64,
    /// ρ parameter (same role as in standard Lorenz). Default 28.0.
    pub rho: f64,
    /// β parameter (same role as in standard Lorenz). Default 8/3 ≈ 2.667.
    pub beta: f64,
}
impl Default for FractionalLorenzConfig {
    fn default() -> Self {
        Self { alpha: 0.99, sigma: 10.0, rho: 28.0, beta: 8.0 / 3.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct BoualiConfig {
    /// z-coupling coefficient (a). Default 0.3.
    pub a: f64,
    /// z-feedback coefficient (s). Default 1.0.
    pub s: f64,
}
impl Default for BoualiConfig {
    fn default() -> Self {
        Self { a: 0.3, s: 1.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct NewtonLeipnikConfig {
    /// Damping of x (a). Default 0.4.
    pub a: f64,
    /// z growth rate (b). Default 0.175.
    pub b: f64,
}
impl Default for NewtonLeipnikConfig {
    fn default() -> Self {
        Self { a: 0.4, b: 0.175 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ShimizuMoriokaConfig {
    /// Damping coefficient (a). Default 0.75 gives chaos.
    pub a: f64,
    /// Linear decay of z (b). Default 0.45 gives chaos.
    pub b: f64,
}
impl Default for ShimizuMoriokaConfig {
    fn default() -> Self {
        Self { a: 0.75, b: 0.45 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct GenesioTesiConfig {
    /// Linear damping coefficient a. Default 1.2 gives chaos.
    pub a: f64,
    /// Quadratic frequency coefficient b. Default 2.92 gives chaos.
    pub b: f64,
    /// Restoring force coefficient c. Default 6.0 gives chaos.
    pub c: f64,
}
impl Default for GenesioTesiConfig {
    fn default() -> Self {
        Self { a: 1.2, b: 2.92, c: 6.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct LiuConfig {
    pub a: f64,
    pub b: f64,
    pub c: f64,
    pub e: f64,
    pub k: f64,
    pub m: f64,
}
impl Default for LiuConfig {
    fn default() -> Self {
        Self { a: 1.0, b: 2.5, c: 5.0, e: 1.0, k: 4.0, m: 4.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct WindmiConfig {
    pub a: f64,
    pub b: f64,
}
impl Default for WindmiConfig {
    fn default() -> Self {
        Self { a: 0.9, b: 2.5 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct FinanceConfig {
    pub a: f64,
    pub b: f64,
    pub c: f64,
}
impl Default for FinanceConfig {
    fn default() -> Self {
        Self { a: 3.0, b: 0.1, c: 1.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct HyperchaosConfig {
    /// Coupling strength. Default 35.0.
    pub a: f64,
    /// z damping. Default 3.0.
    pub b: f64,
    /// y growth. Default 28.0.
    pub c: f64,
    /// w feedback. Default -7.0 (negative gives hyperchaos).
    pub d: f64,
}
impl Default for HyperchaosConfig {
    fn default() -> Self {
        Self { a: 35.0, b: 3.0, c: 28.0, d: -7.0 }
    }
}

/// Tinkerbell map parameters.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct TinkerbellConfig {
    /// Quadratic feedback coefficient. Default 0.9.
    pub a: f64,
    /// Cross-coupling coefficient. Default -0.6013.
    pub b: f64,
    /// x-coupling in y-equation. Default 2.0.
    pub c: f64,
    /// y-linear term. Default 0.5.
    pub d: f64,
}
impl Default for TinkerbellConfig {
    fn default() -> Self {
        Self { a: 0.9, b: -0.6013, c: 2.0, d: 0.5 }
    }
}

impl Config {
    /// Clamp all parameters to physically sensible bounds.
    /// Call this after deserializing from user-supplied config files.
    pub fn validate(&mut self) {
        // System
        Self::clamp_log_f64(&mut self.system.dt, 0.0001, 0.1, "system.dt");
        Self::clamp_log_f64(&mut self.system.speed, 0.0, 100.0, "system.speed");

        // Lorenz
        Self::clamp_log_f64(&mut self.lorenz.sigma, 0.1, 100.0, "lorenz.sigma");
        Self::clamp_log_f64(&mut self.lorenz.rho, 0.1, 200.0, "lorenz.rho");
        Self::clamp_log_f64(&mut self.lorenz.beta, 0.01, 20.0, "lorenz.beta");

        // Rossler
        Self::clamp_log_f64(&mut self.rossler.a, 0.0, 20.0, "rossler.a");
        Self::clamp_log_f64(&mut self.rossler.b, 0.0, 20.0, "rossler.b");
        Self::clamp_log_f64(&mut self.rossler.c, 0.0, 20.0, "rossler.c");

        // Audio
        Self::clamp_log_f32(&mut self.audio.reverb_wet, 0.0, 1.0, "audio.reverb_wet");
        Self::clamp_log_f32(&mut self.audio.delay_ms, 1.0, 5000.0, "audio.delay_ms");
        Self::clamp_log_f32(
            &mut self.audio.delay_feedback,
            0.0,
            0.99,
            "audio.delay_feedback",
        );
        Self::clamp_log_f32(
            &mut self.audio.master_volume,
            0.0,
            1.0,
            "audio.master_volume",
        );
        if self.audio.sample_rate != 44100 && self.audio.sample_rate != 48000 {
            tracing::warn!(
                field = "audio.sample_rate",
                value = self.audio.sample_rate as f64,
                min = 44100.0_f64,
                max = 48000.0_f64,
                "config value clamped to valid range"
            );
            self.audio.sample_rate = 44100;
        }
        Self::clamp_log_f32(&mut self.audio.chorus_mix, 0.0, 1.0, "audio.chorus_mix");
        Self::clamp_log_f32(&mut self.audio.chorus_rate, 0.01, 20.0, "audio.chorus_rate");
        Self::clamp_log_f32(
            &mut self.audio.chorus_depth,
            0.0,
            50.0,
            "audio.chorus_depth",
        );
        Self::clamp_log_f32(
            &mut self.audio.waveshaper_drive,
            0.0,
            100.0,
            "audio.waveshaper_drive",
        );
        Self::clamp_log_f32(
            &mut self.audio.waveshaper_mix,
            0.0,
            1.0,
            "audio.waveshaper_mix",
        );
        Self::clamp_log_f32(&mut self.audio.rate_crush, 0.0, 1.0, "audio.rate_crush");
        Self::clamp_log_f32(&mut self.audio.bit_depth, 1.0, 32.0, "audio.bit_depth");
        Self::clamp_log_f64(
            &mut self.audio.control_rate_hz,
            30.0,
            960.0,
            "audio.control_rate_hz",
        );

        // Sonification
        Self::clamp_log_f64(
            &mut self.sonification.base_frequency,
            20.0,
            2000.0,
            "sonification.base_frequency",
        );
        Self::clamp_log_f64(
            &mut self.sonification.octave_range,
            0.1,
            8.0,
            "sonification.octave_range",
        );
        Self::clamp_log_f32(
            &mut self.sonification.portamento_ms,
            1.0,
            5000.0,
            "sonification.portamento_ms",
        );
        for v in &mut self.sonification.voice_levels {
            let old = *v;
            *v = v.clamp(0.0, 1.0);
            if (*v - old).abs() > 1e-9 {
                tracing::warn!(
                    field = "sonification.voice_levels",
                    value = old as f64,
                    min = 0.0_f64,
                    max = 1.0_f64,
                    "config value clamped to valid range"
                );
            }
        }

        // Double pendulum – lengths and masses must be positive
        Self::clamp_log_f64(
            &mut self.double_pendulum.m1,
            0.01,
            100.0,
            "double_pendulum.m1",
        );
        Self::clamp_log_f64(
            &mut self.double_pendulum.m2,
            0.01,
            100.0,
            "double_pendulum.m2",
        );
        Self::clamp_log_f64(
            &mut self.double_pendulum.l1,
            0.01,
            100.0,
            "double_pendulum.l1",
        );
        Self::clamp_log_f64(
            &mut self.double_pendulum.l2,
            0.01,
            100.0,
            "double_pendulum.l2",
        );

        // Geodesic torus – radii must be positive
        Self::clamp_log_f64(
            &mut self.geodesic_torus.big_r,
            0.1,
            100.0,
            "geodesic_torus.big_r",
        );
        Self::clamp_log_f64(&mut self.geodesic_torus.r, 0.01, 50.0, "geodesic_torus.r");

        // Kuramoto
        let old_n = self.kuramoto.n_oscillators;
        self.kuramoto.n_oscillators = self.kuramoto.n_oscillators.max(2).min(256);
        if self.kuramoto.n_oscillators != old_n {
            tracing::warn!(
                field = "kuramoto.n_oscillators",
                value = old_n as f64,
                min = 2.0_f64,
                max = 256.0_f64,
                "config value clamped to valid range"
            );
        }
        Self::clamp_log_f64(&mut self.kuramoto.coupling, 0.0, 50.0, "kuramoto.coupling");

        // Duffing
        Self::clamp_log_f64(&mut self.duffing.delta, 0.0, 10.0, "duffing.delta");
        Self::clamp_log_f64(&mut self.duffing.gamma, 0.0, 10.0, "duffing.gamma");
        Self::clamp_log_f64(&mut self.duffing.omega, 0.001, 100.0, "duffing.omega");

        // Van der Pol
        Self::clamp_log_f64(&mut self.van_der_pol.mu, 0.0, 100.0, "van_der_pol.mu");

        // Halvorsen
        Self::clamp_log_f64(&mut self.halvorsen.a, 0.0, 10.0, "halvorsen.a");

        // Aizawa
        Self::clamp_log_f64(&mut self.aizawa.a, 0.0, 5.0, "aizawa.a");
        Self::clamp_log_f64(&mut self.aizawa.b, 0.0, 5.0, "aizawa.b");
        Self::clamp_log_f64(&mut self.aizawa.c, 0.0, 5.0, "aizawa.c");
        Self::clamp_log_f64(&mut self.aizawa.d, 0.0, 10.0, "aizawa.d");
        Self::clamp_log_f64(&mut self.aizawa.e, 0.0, 5.0, "aizawa.e");
        Self::clamp_log_f64(&mut self.aizawa.f, 0.0, 5.0, "aizawa.f");

        // Chua
        Self::clamp_log_f64(&mut self.chua.alpha, 0.0, 100.0, "chua.alpha");
        Self::clamp_log_f64(&mut self.chua.beta, 0.0, 100.0, "chua.beta");

        // Hindmarsh-Rose
        Self::clamp_log_f64(
            &mut self.hindmarsh_rose.current_i,
            -5.0,
            10.0,
            "hindmarsh_rose.current_i",
        );
        Self::clamp_log_f64(&mut self.hindmarsh_rose.r, 1e-6, 1.0, "hindmarsh_rose.r");

        // CML
        Self::clamp_log_f64(
            &mut self.coupled_map_lattice.r,
            0.0,
            4.0,
            "coupled_map_lattice.r",
        );
        Self::clamp_log_f64(
            &mut self.coupled_map_lattice.eps,
            0.0,
            1.0,
            "coupled_map_lattice.eps",
        );

        // Mackey-Glass
        Self::clamp_log_f64(&mut self.mackey_glass.beta, 0.0, 10.0, "mackey_glass.beta");
        Self::clamp_log_f64(
            &mut self.mackey_glass.gamma,
            0.0,
            10.0,
            "mackey_glass.gamma",
        );
        Self::clamp_log_f64(&mut self.mackey_glass.tau, 1.0, 300.0, "mackey_glass.tau");
        Self::clamp_log_f64(&mut self.mackey_glass.n, 1.0, 20.0, "mackey_glass.n");

        // Nose-Hoover
        Self::clamp_log_f64(&mut self.nose_hoover.a, 0.1, 20.0, "nose_hoover.a");

        // Henon map
        Self::clamp_log_f64(&mut self.henon_map.a, 0.0, 2.0, "henon_map.a");
        Self::clamp_log_f64(&mut self.henon_map.b, -1.0, 1.0, "henon_map.b");

        // Lorenz96
        Self::clamp_log_f64(&mut self.lorenz96.f, 0.0, 50.0, "lorenz96.f");

        // New systems added after initial release
        Self::clamp_log_f64(&mut self.logistic_map.r, 0.0, 4.0, "logistic_map.r");
        Self::clamp_log_f64(&mut self.standard_map.k, 0.0, 20.0, "standard_map.k");
        Self::clamp_log_f64(&mut self.stochastic_lorenz.sigma, 0.1, 100.0, "stochastic_lorenz.sigma");
        Self::clamp_log_f64(&mut self.stochastic_lorenz.rho, 0.1, 200.0, "stochastic_lorenz.rho");
        Self::clamp_log_f64(&mut self.stochastic_lorenz.beta, 0.01, 20.0, "stochastic_lorenz.beta");
        Self::clamp_log_f64(&mut self.stochastic_lorenz.noise_strength, 0.0, 10.0, "stochastic_lorenz.noise_strength");
        Self::clamp_log_f64(&mut self.delayed_map.r, 0.0, 4.0, "delayed_map.r");
        self.delayed_map.tau = self.delayed_map.tau.clamp(1, 50);
        Self::clamp_log_f64(&mut self.oregonator.f, 0.1, 10.0, "oregonator.f");
        Self::clamp_log_f64(&mut self.mathieu.a, -5.0, 5.0, "mathieu.a");
        Self::clamp_log_f64(&mut self.mathieu.q, 0.0, 5.0, "mathieu.q");
        Self::clamp_log_f64(&mut self.kuramoto_driven.coupling, 0.0, 20.0, "kuramoto_driven.coupling");
        Self::clamp_log_f64(&mut self.kuramoto_driven.drive_amp, 0.0, 10.0, "kuramoto_driven.drive_amp");
        Self::clamp_log_f64(&mut self.kuramoto_driven.drive_freq, 0.0, 100.0, "kuramoto_driven.drive_freq");
        // Thomas attractor: b controls dissipation (strange attractor near 0.208186)
        Self::clamp_log_f64(&mut self.thomas.b, 0.05, 0.5, "thomas.b");
        // Burke-Shaw
        Self::clamp_log_f64(&mut self.burke_shaw.sigma, 1.0, 50.0, "burke_shaw.sigma");
        Self::clamp_log_f64(&mut self.burke_shaw.rho, 0.1, 20.0, "burke_shaw.rho");
        // Chen
        Self::clamp_log_f64(&mut self.chen.a, 1.0, 100.0, "chen.a");
        Self::clamp_log_f64(&mut self.chen.b, 0.1, 20.0, "chen.b");
        Self::clamp_log_f64(&mut self.chen.c, 1.0, 100.0, "chen.c");
        // Dadras
        Self::clamp_log_f64(&mut self.dadras.a, 0.1, 10.0, "dadras.a");
        Self::clamp_log_f64(&mut self.dadras.b, 0.1, 10.0, "dadras.b");
        Self::clamp_log_f64(&mut self.dadras.c, 0.1, 10.0, "dadras.c");
        Self::clamp_log_f64(&mut self.dadras.d, 0.1, 10.0, "dadras.d");
        Self::clamp_log_f64(&mut self.dadras.e, 0.1, 30.0, "dadras.e");
        // Rucklidge
        Self::clamp_log_f64(&mut self.rucklidge.kappa, 0.1, 20.0, "rucklidge.kappa");
        Self::clamp_log_f64(&mut self.rucklidge.lambda, 0.1, 20.0, "rucklidge.lambda");
        // Lorenz-84
        Self::clamp_log_f64(&mut self.lorenz84.a, 0.01, 5.0, "lorenz84.a");
        Self::clamp_log_f64(&mut self.lorenz84.b, 0.1, 20.0, "lorenz84.b");
        Self::clamp_log_f64(&mut self.lorenz84.f, 0.0, 20.0, "lorenz84.f");
        Self::clamp_log_f64(&mut self.lorenz84.g, 0.0, 10.0, "lorenz84.g");
        // Rabinovich-Fabrikant
        Self::clamp_log_f64(&mut self.rabinovich_fabrikant.alpha, 0.01, 2.0, "rabinovich_fabrikant.alpha");
        Self::clamp_log_f64(&mut self.rabinovich_fabrikant.gamma, 0.01, 1.0, "rabinovich_fabrikant.gamma");
        // Rikitake
        Self::clamp_log_f64(&mut self.rikitake.mu, 0.1, 10.0, "rikitake.mu");
        Self::clamp_log_f64(&mut self.rikitake.a, 0.1, 20.0, "rikitake.a");
        // Fractional Lorenz
        Self::clamp_log_f64(&mut self.fractional_lorenz.alpha, 0.5, 1.0, "fractional_lorenz.alpha");
        Self::clamp_log_f64(&mut self.fractional_lorenz.sigma, 0.1, 100.0, "fractional_lorenz.sigma");
        Self::clamp_log_f64(&mut self.fractional_lorenz.rho, 0.1, 200.0, "fractional_lorenz.rho");
        Self::clamp_log_f64(&mut self.fractional_lorenz.beta, 0.01, 20.0, "fractional_lorenz.beta");
        // Bouali
        Self::clamp_log_f64(&mut self.bouali.a, 0.0, 2.0, "bouali.a");
        Self::clamp_log_f64(&mut self.bouali.s, 0.1, 5.0, "bouali.s");
        // Newton-Leipnik
        Self::clamp_log_f64(&mut self.newton_leipnik.a, 0.1, 2.0, "newton_leipnik.a");
        Self::clamp_log_f64(&mut self.newton_leipnik.b, 0.01, 1.0, "newton_leipnik.b");
        // Shimizu-Morioka
        Self::clamp_log_f64(&mut self.shimizu_morioka.a, 0.1, 2.0, "shimizu_morioka.a");
        Self::clamp_log_f64(&mut self.shimizu_morioka.b, 0.1, 1.5, "shimizu_morioka.b");
        // Genesio-Tesi
        Self::clamp_log_f64(&mut self.genesio_tesi.a, 0.5, 3.0, "genesio_tesi.a");
        Self::clamp_log_f64(&mut self.genesio_tesi.b, 1.0, 6.0, "genesio_tesi.b");
        Self::clamp_log_f64(&mut self.genesio_tesi.c, 2.0, 12.0, "genesio_tesi.c");
        // Liu
        Self::clamp_log_f64(&mut self.liu.a, 0.1, 5.0, "liu.a");
        Self::clamp_log_f64(&mut self.liu.b, 0.5, 8.0, "liu.b");
        Self::clamp_log_f64(&mut self.liu.c, 1.0, 15.0, "liu.c");
        Self::clamp_log_f64(&mut self.liu.e, 0.1, 5.0, "liu.e");
        Self::clamp_log_f64(&mut self.liu.k, 0.5, 10.0, "liu.k");
        Self::clamp_log_f64(&mut self.liu.m, 0.5, 10.0, "liu.m");
        // WINDMI
        Self::clamp_log_f64(&mut self.windmi.a, 0.1, 3.0, "windmi.a");
        Self::clamp_log_f64(&mut self.windmi.b, 0.5, 5.0, "windmi.b");
        // Finance
        Self::clamp_log_f64(&mut self.finance.a, 0.5, 8.0, "finance.a");
        Self::clamp_log_f64(&mut self.finance.b, 0.01, 1.0, "finance.b");
        Self::clamp_log_f64(&mut self.finance.c, 0.1, 5.0, "finance.c");
        // Hyperchaos
        Self::clamp_log_f64(&mut self.hyperchaos.a, 10.0, 60.0, "hyperchaos.a");
        Self::clamp_log_f64(&mut self.hyperchaos.b, 1.0, 8.0, "hyperchaos.b");
        Self::clamp_log_f64(&mut self.hyperchaos.c, 10.0, 50.0, "hyperchaos.c");
        self.hyperchaos.d = self.hyperchaos.d.clamp(-15.0, -0.5); // must stay negative
    }

    /// Clamp a `f64` field to `[min, max]`, emitting a tracing warning if clamped.
    fn clamp_log_f64(value: &mut f64, min: f64, max: f64, field: &'static str) {
        let old = *value;
        *value = old.clamp(min, max);
        if (*value - old).abs() > f64::EPSILON {
            tracing::warn!(
                field = field,
                value = old,
                min = min,
                max = max,
                "config value clamped to valid range"
            );
        }
    }

    /// Clamp a `f32` field to `[min, max]`, emitting a tracing warning if clamped.
    fn clamp_log_f32(value: &mut f32, min: f32, max: f32, field: &'static str) {
        let old = *value;
        *value = old.clamp(min, max);
        if (*value - old).abs() > f32::EPSILON {
            tracing::warn!(
                field = field,
                value = old as f64,
                min = min as f64,
                max = max as f64,
                "config value clamped to valid range"
            );
        }
    }
}

// --- Conversions from string config to enums ---

impl From<&str> for SonifMode {
    fn from(s: &str) -> Self {
        match s {
            "orbital" => Self::Orbital,
            "granular" => Self::Granular,
            "spectral" => Self::Spectral,
            "fm" => Self::FM,
            "am" => Self::AM,
            "vocal" => Self::Vocal,
            "waveguide" => Self::Waveguide,
            "resonator" => Self::Resonator,
            _ => Self::Direct,
        }
    }
}

impl From<String> for SonifMode {
    fn from(s: String) -> Self {
        Self::from(s.as_str())
    }
}

impl From<&str> for Scale {
    fn from(s: &str) -> Self {
        match s {
            "chromatic" => Self::Chromatic,
            "just_intonation" => Self::JustIntonation,
            "microtonal" => Self::Microtonal,
            "edo19" => Self::Edo19,
            "edo31" => Self::Edo31,
            "edo24" => Self::Edo24,
            "whole_tone" => Self::WholeTone,
            "phrygian" => Self::Phrygian,
            "lydian" => Self::Lydian,
            "harmonic_series" => Self::HarmonicSeries,
            "hirajoshi" => Self::Hirajoshi,
            "blues" => Self::Blues,
            "dorian" => Self::Dorian,
            "mixolydian" => Self::Mixolydian,
            "hungarian_minor" => Self::HungarianMinor,
            "locrian" => Self::Locrian,
            "octatonic" => Self::Octatonic,
            "natural_minor" => Self::NaturalMinor,
            "harmonic_minor" => Self::HarmonicMinor,
            _ => Self::Pentatonic,
        }
    }
}

impl From<String> for Scale {
    fn from(s: String) -> Self {
        Self::from(s.as_str())
    }
}

/// Loads a `Config` from a TOML file, falling back to defaults on any error.
///
/// # Parameters
/// - `path`: Path to the TOML configuration file.
///
/// # Returns
/// A validated `Config`; defaults are used for any missing or invalid fields.
pub fn load_config(path: &std::path::Path) -> Config {
    let mut config = match std::fs::read_to_string(path) {
        Ok(text) => toml::from_str(&text).unwrap_or_else(|e| {
            log::warn!("Config parse error: {e}. Using defaults.");
            Config::default()
        }),
        Err(_) => {
            log::info!("No config.toml found, using defaults.");
            Config::default()
        }
    };
    config.validate();
    config
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_config_default_valid() {
        // Default config should survive a validate() call with all values unchanged
        // (i.e. all defaults are already within their valid ranges).
        let mut config = Config::default();
        let before = format!("{:?}", config);
        config.validate();
        let after = format!("{:?}", config);
        assert_eq!(before, after, "validate() mutated a default Config value");
    }

    #[test]
    fn test_validate_clamps_lorenz_sigma_below_min() {
        let mut c = Config::default();
        c.lorenz.sigma = -5.0;
        c.validate();
        assert!(c.lorenz.sigma >= 0.1, "sigma should be clamped to min: {}", c.lorenz.sigma);
    }

    #[test]
    fn test_validate_clamps_lorenz_sigma_above_max() {
        let mut c = Config::default();
        c.lorenz.sigma = 999.0;
        c.validate();
        assert!(c.lorenz.sigma <= 100.0, "sigma should be clamped to max: {}", c.lorenz.sigma);
    }

    #[test]
    fn test_validate_clamps_audio_reverb_wet() {
        let mut c = Config::default();
        c.audio.reverb_wet = 5.0;
        c.validate();
        assert!(c.audio.reverb_wet <= 1.0, "reverb_wet should be clamped to 1.0: {}", c.audio.reverb_wet);
    }

    #[test]
    fn test_validate_clamps_master_volume() {
        let mut c = Config::default();
        c.audio.master_volume = -1.0;
        c.validate();
        assert!(c.audio.master_volume >= 0.0, "master_volume should not be negative: {}", c.audio.master_volume);
    }

    #[test]
    fn test_validate_invalid_sample_rate_resets_to_44100() {
        let mut c = Config::default();
        c.audio.sample_rate = 22050;
        c.validate();
        assert_eq!(c.audio.sample_rate, 44100, "invalid sample_rate should reset to 44100");
    }

    #[test]
    fn test_validate_accepts_48000_sample_rate() {
        let mut c = Config::default();
        c.audio.sample_rate = 48000;
        c.validate();
        assert_eq!(c.audio.sample_rate, 48000, "48000 Hz should be accepted unchanged");
    }

    #[test]
    fn test_validate_clamps_delay_feedback() {
        let mut c = Config::default();
        c.audio.delay_feedback = 2.0; // runaway feedback
        c.validate();
        assert!(c.audio.delay_feedback <= 0.99, "delay_feedback should be clamped to < 1: {}", c.audio.delay_feedback);
    }

    #[test]
    fn test_validate_clamps_rossler_c_above_max() {
        let mut c = Config::default();
        c.rossler.c = 999.0;
        c.validate();
        assert!(c.rossler.c <= 20.0, "rossler.c should be clamped to max 20: {}", c.rossler.c);
    }

    #[test]
    fn test_config_round_trip() {
        let original = Config::default();
        let serialized = toml::to_string(&original).expect("serialization failed");
        let mut deserialized: Config = toml::from_str(&serialized).expect("deserialization failed");
        deserialized.validate();
        // Compare key scalar fields to verify round-trip fidelity
        assert!((original.lorenz.sigma - deserialized.lorenz.sigma).abs() < 1e-9);
        assert!((original.lorenz.rho - deserialized.lorenz.rho).abs() < 1e-9);
        assert!((original.lorenz.beta - deserialized.lorenz.beta).abs() < 1e-9);
        assert!((original.rossler.a - deserialized.rossler.a).abs() < 1e-9);
        assert!((original.rossler.c - deserialized.rossler.c).abs() < 1e-9);
        assert!(
            (original.audio.master_volume as f64 - deserialized.audio.master_volume as f64).abs()
                < 1e-6
        );
        assert_eq!(original.system.name, deserialized.system.name);
    }
}