bio_files 0.5.1

Save and load common biology file formats
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
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
//! GROMACS MDP (Molecular Dynamics Parameters) file types and generation. This is responsible
//! for general MD configuration.
//!
//! See the [GROMACS manual — MDP options](https://manual.gromacs.org/current/user-guide/mdp-options.html).
//! [Example MDP file](https://manual.gromacs.org/2026.1/reference-manual/file-formats.html#mdp)
//!
//! Fields left as `None` are omitted from the generated file, deferring to GROMACS defaults.

use std::{
    collections::HashMap,
    fmt, io,
    io::{Error, ErrorKind},
    path::Path,
};

use crate::gromacs::save_txt_to_file;

/// Abramowitz & Stegun 7.1.26 — max error 1.5×10⁻⁷.
fn erfc_approx(x: f32) -> f32 {
    let t = 1.0 / (1.0 + 0.3275911 * x);
    let p = t
        * (0.254829592
            + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))));
    p * (-x * x).exp()
}

/// Invert erfc by bisection. Only called at parse time so performance is irrelevant.
fn erfc_inv_approx(y: f32) -> f32 {
    let (mut lo, mut hi) = (0.0_f32, 6.0_f32);
    for _ in 0..60 {
        let mid = 0.5 * (lo + hi);
        if erfc_approx(mid) > y {
            lo = mid;
        } else {
            hi = mid;
        }
    }
    0.5 * (lo + hi)
}

/// Helper function to append a key and value to an .mdp file.
fn append_inp<T: ToString>(inp: &mut String, k: &str, v: T) {
    inp.push_str(&format!("{k:<25}= {}\n", v.to_string()));
}

/// Float wrapper that formats with scientific notation when `|v| < 0.001`.
/// This matches GROMACS conventions: `compressibility = 4.5e-5`, `ewald-rtol = 1e-5`, etc.
struct Gf(f32);

impl fmt::Display for Gf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let v = self.0;
        if v != 0.0 && v.abs() < 0.001 {
            write!(f, "{:e}", v)
        } else {
            write!(f, "{v}")
        }
    }
}

struct Gf64(f64);

impl fmt::Display for Gf64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let v = self.0;
        if v != 0.0 && v.abs() < 0.001 {
            write!(f, "{:e}", v)
        } else {
            write!(f, "{v}")
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct PmeConfig {
    /// PME Fourier grid spacing in **nm**.
    pub fourierspacing: f32,
    /// Valid values are 3-12.
    pub order: u8,
    /// Ewald splitting parameter α in **nm⁻¹**.  Controls the balance between
    /// real-space and reciprocal-space work.  When writing an MDP file, this is
    /// converted to `ewald-rtol = erfc(α × rcoulomb)`.
    ///
    /// Default (3.12 nm⁻¹) gives ewald-rtol ≈ 1×10⁻⁵ at the GROMACS default
    /// rcoulomb of 1.0 nm, matching the GROMACS default behaviour.
    pub alpha: f32,
    pub rtol_lj: f32,
    pub epsilon_surface: Option<f32>,
}

impl Default for PmeConfig {
    fn default() -> Self {
        Self {
            fourierspacing: 0.12,
            order: 4,
            alpha: 3.12, // erfc(3.12 × 1.0 nm) ≈ 1e-5 — matches GROMACS default ewald-rtol
            rtol_lj: 1e-3,
            epsilon_surface: None,
        }
    }
}

impl PmeConfig {
    /// Render PME parameters to MDP key-value lines.
    /// `rcoulomb` (nm) is required to derive `ewald-rtol = erfc(alpha × rcoulomb)`.
    pub fn make_inp(&self, rcoulomb: f32) -> String {
        let mut res = String::new();

        append_inp(&mut res, "fourierspacing", Gf(self.fourierspacing));
        append_inp(&mut res, "pme-order", self.order);
        append_inp(
            &mut res,
            "ewald-rtol",
            Gf(erfc_approx(self.alpha * rcoulomb)),
        );
        append_inp(&mut res, "ewald-rtol-lj", Gf(self.rtol_lj));

        if let Some(v) = &self.epsilon_surface {
            append_inp(&mut res, "epsilon-surface", Gf(*v));
        }

        res
    }
}

/// Integration algorithm.
///
/// [GROMACS manual: run-control](https://manual.gromacs.org/current/user-guide/mdp-options.html#run-control)
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Integrator {
    /// Leap-frog MD integrator (default in gromacsαθθs).
    #[default]
    Md,
    /// Velocity Verlet. Slower than `md`, but perhaps more rigorous.
    MdVv,
    MdVvAvek,
    /// Stochastic dynamics (Langevin). `tcoupl` must be `no`; friction is
    /// specified via `tau-t` (the inverse friction constant, ps) per group.
    /// Also known as Langevin, with built-in stochastic thermostat.
    Sd,
    Bd,
    /// Steep-descent energy minimization. (Good default for energy minimization)
    Steep {
        /// (10.0) [kJ mol-1 nm-1] the minimization is converged when the maximum force is smaller than this value
        emtol: f32,
        /// (0.01) [nm] initial step-size
        emstep: f32,
    },
    /// Conjugate gradient energy minimization.
    Cg {
        emtol: f32,
        /// (1000) [steps] interval of performing 1 steepest descent step while doing conjugate gradient energy minimization.
        nstcgsteep: u32,
    },
    LBfgs {
        nbfgscorr: u8,
    },
    Nm,
    Tpi,
    Tpic,
    Mimic,
}

impl Integrator {
    pub fn key(self) -> &'static str {
        use Integrator::*;
        match self {
            Md => "md",
            MdVv => "md-vv",
            MdVvAvek => "md-vv-avek",
            Bd => "bd",
            Sd => "sd",
            Steep { .. } => "steep",
            Cg { .. } => "cg",
            LBfgs { .. } => "l-bfgs",
            Nm => "nm",
            Tpi => "tpi",
            Tpic => "tpic",
            Mimic => "mimic",
        }
    }
}

impl Integrator {
    pub fn make_inp(&self) -> String {
        use Integrator::*;

        let mut res = String::new();
        append_inp(&mut res, "integrator", &self.clone().key());

        match self {
            Steep { emtol, emstep } => {
                append_inp(&mut res, "emtol", emtol);
                append_inp(&mut res, "emstep", emstep);
            }
            Cg { emtol, nstcgsteep } => {
                append_inp(&mut res, "emtol", emtol);
                append_inp(&mut res, "nstcgsteep", nstcgsteep);
            }
            LBfgs { nbfgscorr } => {
                append_inp(&mut res, "nbfgscorr", nbfgscorr);
            }
            _ => (),
        }

        res
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FreeEnergyCalculations {
    #[default]
    No,
    Yes,
    Expanded,
}

impl FreeEnergyCalculations {
    pub fn key(self) -> &'static str {
        match self {
            Self::No => "no",
            Self::Yes => "yes",
            Self::Expanded => "expanded",
        }
    }
}

// /// [https://manual.gromacs.org/current/user-guide/mdp-options.html#energy-minimization](MDP Guide: Energy min)
// #[derive(Clone, Debug, PartialEq)]
// #[cfg_attr(feature = "encode", derive(bincode::Encode, bincode::Decode))]
// pub struct EnergyMinimization {
//     /// (10.0) [kJ mol-1 nm-1] the minimization is converged when the maximum force is smaller
//     /// than this value
//     pub emtol: f32,
//     /// (0.01) [nm] initial step-size
//     /// /
//     pub emstep: f32,
//     /// (1000) [steps] interval of performing 1 steepest descent step while doing conjugate
//     /// gradient energy minimization.
//     pub nstcgsteep: u16,
//     /// (10) Number of correction steps to use for L-BFGS minimization. A higher number
//     /// is (at least theoretically) more accurate, but slower.
//     pub nbfgscorr: u8,
// }

/// Temperature-coupling algorithm.
///
/// [GROMACS manual: temperature-coupling](https://manual.gromacs.org/current/user-guide/mdp-options.html#temperature-coupling)
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Thermostat {
    No,
    /// Nosé–Hoover; canonical ensemble.
    NoseHoover,
    Andersen,
    AndersenMassive,
    /// Velocity-rescaling thermostat; produces the canonical ensemble.
    #[default]
    VRescale,
}

impl Thermostat {
    pub fn key(self) -> &'static str {
        match self {
            Self::No => "no",
            Self::NoseHoover => "nose-hoover",
            Self::Andersen => "andersen",
            Self::AndersenMassive => "andersen-massive",
            Self::VRescale => "v-rescale",
        }
    }
}

impl fmt::Display for Thermostat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.key())
    }
}

/// Pressure-coupling algorithm.
///
/// [GROMACS manual: pressure-coupling](https://manual.gromacs.org/current/user-guide/mdp-options.html#pressure-coupling)
#[derive(Clone, Debug, PartialEq)]
pub enum Barostat {
    No,
    /// Not recommended, by GROMACS.
    Berendsen(BarostatCfg),
    /// Exponential relaxation pressure coupling with time constant tau-p, including a stochastic term to enforce correct volume fluctuations.
    CRescale(BarostatCfg),
    /// Parrinello–Rahman; NPT ensemble.
    ParrinelloRahman(BarostatCfg),
    /// Martyna-Tuckerman-Tobias-Klein implementation, only useable with integrator=md-vv or integrator=md-vv-avek, very similar to Parrinello-Rahman.
    Mtkk(BarostatCfg),
}

impl Default for Barostat {
    fn default() -> Self {
        Self::CRescale(BarostatCfg::default())
    }
}

impl Barostat {
    pub fn make_inp(&self) -> String {
        let mut res = String::new();

        match self {
            Self::No => {
                append_inp(&mut res, "pcoupl", "no");
            }
            Self::Berendsen(cfg) => {
                append_inp(&mut res, "pcoupl", "Berendsen");
                res.push_str(&cfg.make_inp());
            }
            Self::CRescale(cfg) => {
                append_inp(&mut res, "pcoupl", "C-rescale");
                res.push_str(&cfg.make_inp());
            }
            Self::ParrinelloRahman(cfg) => {
                append_inp(&mut res, "pcoupl", "Parrinello-Rahman");
                res.push_str(&cfg.make_inp());
            }
            Self::Mtkk(cfg) => {
                append_inp(&mut res, "pcoupl", "MTTK");
                res.push_str(&cfg.make_inp());
            }
        }

        res
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct BarostatCfg {
    pub pcoupltype: PressureCouplingType,
    /// Pressure coupling time constant (ps).
    pub tau_p: f32,
}

impl BarostatCfg {
    pub fn make_inp(&self) -> String {
        let mut res = String::new();

        res.push_str(&self.pcoupltype.make_inp());
        append_inp(&mut res, "tau-p", self.tau_p);

        res
    }
}

impl Default for BarostatCfg {
    fn default() -> Self {
        Self {
            pcoupltype: Default::default(),
            tau_p: 5.,
        }
    }
}

/// Pressure-coupling algorithm.
///
/// [GROMACS manual: pressure-coupling](https://manual.gromacs.org/current/user-guide/mdp-options.html#pressure-coupling)
#[derive(Clone, Debug, PartialEq)]
pub enum PressureCouplingType {
    Isotropic {
        /// Isothermal compressibility (bar⁻¹), e.g. `4.5e-5` for water.
        compressibility: f64,
        /// Reference pressure (bar).
        ref_p: f32,
    },
    Semiisotropic {
        compressibility_xy: f64,
        compressibility_z: f64,
        ref_p_xy: f32,
        ref_p_z: f32,
    },
    Anisotropic {
        compressibility: [f64; 6],
        ref_p: [f32; 6],
    },
    SurfaceTension {
        compressibility_xy: f64,
        compressibility_z: f64,
        ref_p_sfc_tension: f32,
        ref_p_z: f32,
    },
}

impl Default for PressureCouplingType {
    fn default() -> Self {
        Self::Isotropic {
            ref_p: 1.0,
            compressibility: 4.5e-5,
        }
    }
}

impl PressureCouplingType {
    pub fn make_inp(&self) -> String {
        let mut res = String::new();

        match self {
            Self::Isotropic {
                compressibility,
                ref_p,
            } => {
                append_inp(&mut res, "pcoupltype", "isotropic");
                append_inp(&mut res, "ref-p", ref_p);
                append_inp(&mut res, "compressibility", Gf64(*compressibility));
            }
            Self::Semiisotropic {
                compressibility_xy,
                compressibility_z,
                ref_p_xy,
                ref_p_z,
            } => {
                append_inp(&mut res, "pcoupltype", "semiisotropic");
                append_inp(
                    &mut res,
                    "ref-p",
                    format!("{} {}", Gf(*ref_p_xy), Gf(*ref_p_z)),
                );
                append_inp(
                    &mut res,
                    "compressibility",
                    format!("{} {}", Gf64(*compressibility_xy), Gf64(*compressibility_z)),
                );
            }
            Self::Anisotropic {
                compressibility,
                ref_p,
            } => {
                append_inp(&mut res, "pcoupltype", "anisotropic");
                append_inp(
                    &mut res,
                    "ref-p",
                    ref_p
                        .iter()
                        .map(|v| Gf(*v).to_string())
                        .collect::<Vec<_>>()
                        .join(" "),
                );
                append_inp(
                    &mut res,
                    "compressibility",
                    compressibility
                        .iter()
                        .map(|v| Gf64(*v).to_string())
                        .collect::<Vec<_>>()
                        .join(" "),
                );
            }
            Self::SurfaceTension {
                compressibility_xy,
                compressibility_z,
                ref_p_sfc_tension,
                ref_p_z,
            } => {
                append_inp(&mut res, "pcoupltype", "surface-tension");
                append_inp(
                    &mut res,
                    "ref-p",
                    format!("{} {}", Gf(*ref_p_sfc_tension), Gf(*ref_p_z)),
                );
                append_inp(
                    &mut res,
                    "compressibility",
                    format!("{} {}", Gf64(*compressibility_xy), Gf64(*compressibility_z)),
                );
            }
        }

        res
    }
}

/// Coulomb interaction treatment.
#[derive(Clone, Debug, PartialEq)]
pub enum CoulombType {
    /// Particle Mesh Ewald — default for periodic systems.
    Pme(PmeConfig),
    CutOff,
    ReactionField,
}

impl Default for CoulombType {
    fn default() -> Self {
        Self::Pme(PmeConfig::default())
    }
}

impl CoulombType {
    pub fn make_inp(&self, rcoulomb: f32) -> String {
        let mut res = String::new();

        match self {
            Self::Pme(pme) => {
                append_inp(&mut res, "coulombtype", "PME");
                res.push_str(&pme.make_inp(rcoulomb));
            }
            Self::CutOff => append_inp(&mut res, "coulombtype", "Cut-off"),
            Self::ReactionField => append_inp(&mut res, "coulombtype", "Reaction-Field"),
        }

        res
    }

    pub fn key(&self) -> &'static str {
        match self {
            Self::Pme(_) => "PME",
            Self::CutOff => "Cut-off",
            Self::ReactionField => "Reaction-Field",
        }
    }
}

impl fmt::Display for CoulombType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.key())
    }
}

/// Van der Waals interaction treatment.
/// Note: "Shift", "Switch", and "User" and deprecated, so we skip them here.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum VdwType {
    #[default]
    CutOff,
    Pme,
}

impl VdwType {
    pub fn key(self) -> &'static str {
        match self {
            Self::CutOff => "Cut-off",
            Self::Pme => "PME",
        }
    }

    pub fn from_key(key: &str) -> Option<Self> {
        Some(match key.to_lowercase().as_ref() {
            "cut-off" => Self::CutOff,
            "pme" => Self::Pme,
            _ => return None,
        })
    }
}

/// Van der Waals interaction treatment.
/// Note: "Shift", "Switch", and "User" and deprecated, so we skip them here.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum VdwModifier {
    #[default]
    PotentialShift,
    None,
    ForceSwitch,
    PotentialSwitch,
}

impl VdwModifier {
    pub fn key(self) -> &'static str {
        match self {
            Self::PotentialShift => "Potential-shift",
            Self::None => "None",
            Self::ForceSwitch => "Force-switch",
            Self::PotentialSwitch => "Potential-switch",
        }
    }

    pub fn from_key(key: &str) -> Option<Self> {
        Some(match key.to_lowercase().as_ref() {
            "potential-shift" => Self::PotentialShift,
            "none" => Self::None,
            "force-switch" => Self::ForceSwitch,
            "potential-switch" => Self::PotentialSwitch,
            _ => return None,
        })
    }
}

/// Periodic boundary conditions.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Pbc {
    /// All directions
    #[default]
    Xyz,
    No,
    /// X and Y directions only
    Xy,
}

impl Pbc {
    pub fn key(self) -> &'static str {
        match self {
            Self::Xyz => "xyz",
            Self::No => "no",
            Self::Xy => "xy",
        }
    }

    pub fn from_key(key: &str) -> Option<Self> {
        Some(match key.to_lowercase().as_ref() {
            "xyz" => Self::Xyz,
            "no" => Self::No,
            "xy" => Self::Xy,
            _ => return None,
        })
    }
}

/// Bond constraint algorithm.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ConstraintAlgorithm {
    /// LINCS — recommended for MD.
    Lincs { order: u8, iter: u8 },
    /// SHAKE — slower but supports angle constraints.
    Shake { tol: f32 },
}

impl Default for ConstraintAlgorithm {
    fn default() -> Self {
        Self::Lincs { order: 4, iter: 1 }
        //Note: Shake tol default is 0.0001
    }
}

impl ConstraintAlgorithm {
    pub fn make_inp(self) -> String {
        let mut res = String::new();

        match self {
            Self::Lincs { order, iter } => {
                append_inp(&mut res, "constraint-algorithm", "LINCS");
                append_inp(&mut res, "lincs-order", order);
                append_inp(&mut res, "lincs-iter", iter);
            }
            Self::Shake { tol } => {
                append_inp(&mut res, "constraint-algorithm", "SHAKE");
                append_inp(&mut res, "shake-tol", Gf(tol));
            }
        }

        res
    }
}

/// Which bonds to constrain.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Constraints {
    None,
    /// Constrain bonds involving H atoms; allows longer timesteps.
    HBonds(ConstraintAlgorithm),
    AllBonds(ConstraintAlgorithm),
    HAngles(ConstraintAlgorithm),
    AllAngles(ConstraintAlgorithm),
}

impl Default for Constraints {
    fn default() -> Self {
        Self::HAngles(ConstraintAlgorithm::default())
    }
}

impl Constraints {
    pub fn make_inp(&self) -> String {
        let mut res = String::new();

        match self {
            Self::None => {
                append_inp(&mut res, "constraints", "none");
            }
            Self::HBonds(ca) => {
                append_inp(&mut res, "constraints", "h-bonds");
                res.push_str(&ca.make_inp());
            }
            Self::AllBonds(ca) => {
                append_inp(&mut res, "constraints", "all-bonds");
                res.push_str(&ca.make_inp());
            }
            Self::HAngles(ca) => {
                append_inp(&mut res, "constraints", "h-angles");
                res.push_str(&ca.make_inp());
            }
            Self::AllAngles(ca) => {
                append_inp(&mut res, "constraints", "all-angles");
                res.push_str(&ca.make_inp());
            }
        }

        res
    }
}

#[cfg_attr(feature = "encode", derive(bincode::Encode, bincode::Decode))]
#[derive(Clone, Debug, PartialEq)]
pub struct OutputControl {
    /// Write full-precision coordinates to `.trr` every N steps (0 = never).
    pub nstxout: Option<u32>,
    /// Write velocities to `.trr` every N steps (0 = never).
    pub nstvout: Option<u32>,
    /// Number of steps that elapse between writing forces to the output trajectory file
    pub nstfout: Option<u32>,
    /// Write to `.log` every N steps.
    pub nstlog: Option<u32>,
    /// Calculate energies to `.edr` every N steps.
    pub nstcalcenergy: Option<u32>,
    /// Write energies to `.edr` every N steps.
    pub nstenergy: Option<u32>,
    /// Write compressed coordinates to `.xtc.rs` every N steps (0 = never).
    pub nstxout_compressed: Option<u32>,
    ///  precision with which to write to the compressed trajectory file
    pub compressed_x_precision: u32,
    // pub compressed_x_grps: u32,
}

impl Default for OutputControl {
    fn default() -> Self {
        Self {
            nstxout: None,
            nstvout: None,
            nstfout: None,
            nstlog: Some(1_000),
            nstcalcenergy: Some(100),
            nstenergy: Some(1_000),
            nstxout_compressed: None,
            compressed_x_precision: 1_000,
        }
    }
}

impl OutputControl {
    pub fn make_inp(&self) -> String {
        let mut res = String::new();

        // 0 is the default for these write ratios.
        append_inp(&mut res, "nstxout", self.nstxout.unwrap_or(0));
        append_inp(&mut res, "nstvout", self.nstvout.unwrap_or(0));
        append_inp(&mut res, "nstfout", self.nstfout.unwrap_or(0));
        append_inp(&mut res, "nstlog", self.nstlog.unwrap_or(0));
        append_inp(&mut res, "nstcalcenergy", self.nstcalcenergy.unwrap_or(0));
        append_inp(&mut res, "nstenergy", self.nstenergy.unwrap_or(0));
        append_inp(
            &mut res,
            "nstxout-compressed",
            self.nstxout_compressed.unwrap_or(0),
        );
        append_inp(
            &mut res,
            "compressed-x-precision",
            self.compressed_x_precision,
        );

        res
    }
}

/// Complete set of GROMACS Molecular Dynamics Parameters (MDP) for classical MD.
///
/// All parameters correspond directly to
/// [GROMACS MDP options](https://manual.gromacs.org/current/user-guide/mdp-options.html).
/// Similar in concept to `dyanmics::MdConfig`.
///
/// Units follow GROMACS conventions (ps, nm, kJ/mol, K, bar).
#[derive(Clone, Debug)]
pub struct MdpParams {
    // --- Run control ---
    pub integrator: Integrator,
    /// Total number of integration steps.
    pub nsteps: u64,
    /// Integration timestep in **ps** (e.g. `0.002` = 2 fs).
    pub dt: f32,
    pub output_control: OutputControl,
    // --- Non-bonded interactions ---
    pub coulombtype: CoulombType,
    /// Coulomb cutoff in **nm**.
    pub rcoulomb: f32,
    pub vdwtype: VdwType,
    pub vdw_modifier: VdwModifier,
    /// VdW cutoff in **nm**.
    pub rvdw: f32,
    // --- Temperature coupling ---
    pub thermostat: Thermostat,
    /// Time constant (ps) for each coupling group. Must match length of `ref_t`.
    pub tau_t: Vec<f32>,
    /// Reference temperature (K) for each coupling group.
    pub ref_t: Vec<f32>,
    pub pcoupl: Barostat,

    // --- Periodic boundary ---
    pub pbc: Pbc,

    // --- Velocity generation ---
    /// Generate initial velocities from a Maxwell–Boltzmann distribution.
    pub gen_vel: bool,
    /// Temperature (K) for velocity generation.
    pub gen_temp: f32,
    /// Random seed for velocity generation; `-1` lets GROMACS choose.
    pub gen_seed: Option<i32>,
    // --- Constraints ---
    pub constraints: Constraints,
    // ---
    pub free_energy_calculations: FreeEnergyCalculations,
}

/// We use the GROMACS defaults here.
impl Default for MdpParams {
    fn default() -> Self {
        Self {
            integrator: Integrator::Md,
            nsteps: 0,
            dt: 0.001,
            output_control: OutputControl::default(),
            coulombtype: CoulombType::default(),
            rcoulomb: 1.0,
            vdwtype: VdwType::default(),
            vdw_modifier: VdwModifier::default(),
            rvdw: 1.0,
            thermostat: Thermostat::default(),
            tau_t: vec![1.0], // todo: 0.1?
            ref_t: vec![300.],
            pcoupl: Barostat::default(),
            pbc: Pbc::default(),
            gen_vel: true,
            gen_temp: 300.,
            gen_seed: None,
            constraints: Constraints::default(),
            free_energy_calculations: Default::default(),
        }
    }
}

impl MdpParams {
    /// Render as a GROMACS `.mdp` file string.
    pub fn to_mdp_str(&self) -> String {
        let mut s = String::from("; GROMACS MDP - generated by Bio Files\n\n");

        // Run control
        s.push_str("; Run control\n");

        s.push_str(&self.integrator.make_inp());

        append_inp(&mut s, "nsteps", self.nsteps);
        append_inp(&mut s, "dt", Gf(self.dt));

        // Output
        s.push_str("\n; Output control\n");
        s.push_str(&self.output_control.make_inp());

        // Non-bonded
        s.push_str("\n; Non-bonded interactions\n");
        s.push_str(&self.coulombtype.make_inp(self.rcoulomb));

        append_inp(&mut s, "rcoulomb", Gf(self.rcoulomb));
        append_inp(&mut s, "vdw-type", self.vdwtype.key());
        append_inp(&mut s, "vdw-modifier", self.vdw_modifier.key());
        append_inp(&mut s, "rvdw", Gf(self.rvdw));

        // Temperature coupling
        s.push_str("\n; Temperature coupling\n");
        append_inp(&mut s, "tcoupl", self.thermostat.key());

        // For the `sd` integrator, tcoupl must be `no`, but tc-grps / tau-t / ref-t
        // are still required: tau-t is the inverse friction constant (1/γ, ps).
        let needs_tc_params =
            self.thermostat != Thermostat::No || self.integrator == Integrator::Sd;

        if needs_tc_params {
            let n = self.ref_t.len().max(1);
            let tc_grps = (0..n).map(|_| "System").collect::<Vec<_>>().join(" ");

            let tau_t = self
                .tau_t
                .iter()
                .map(|v| Gf(*v).to_string())
                .collect::<Vec<_>>()
                .join(" ");

            let ref_t = self
                .ref_t
                .iter()
                .map(|v| Gf(*v).to_string())
                .collect::<Vec<_>>()
                .join(" ");
            append_inp(&mut s, "tc-grps", tc_grps);
            append_inp(&mut s, "tau-t", tau_t);
            append_inp(&mut s, "ref-t", ref_t);
        }

        // Pressure coupling
        s.push_str("\n; Pressure coupling\n");
        s.push_str(&self.pcoupl.make_inp());

        // PBC
        s.push_str("\n; Periodic boundary conditions\n");
        append_inp(&mut s, "pbc", self.pbc.key());

        // Velocity generation
        s.push_str("\n; Velocity generation\n");
        append_inp(&mut s, "gen-vel", if self.gen_vel { "yes" } else { "no" });
        if self.gen_vel {
            append_inp(&mut s, "gen-temp", Gf(self.gen_temp));

            if let Some(v) = &self.gen_seed {
                append_inp(&mut s, "gen-seed", v);
            }
        }

        // Constraints
        s.push_str("\n; Constraints\n");
        s.push_str(&self.constraints.make_inp());

        append_inp(&mut s, "free-energy", self.free_energy_calculations.key());

        s
    }

    // todo: This fn is a mess. re-definition of default values, field names etc here in addition to the enums.
    pub fn from_mdp_str(data: &str) -> io::Result<Self> {
        fn inv(k: &str, e: impl fmt::Display) -> io::Error {
            Error::new(ErrorKind::InvalidData, format!("{k}: {e}"))
        }

        fn get_s<'a>(map: &'a HashMap<String, String>, k: &str) -> Option<&'a str> {
            map.get(k).map(String::as_str)
        }

        fn f32_or(map: &HashMap<String, String>, k: &str, d: f32) -> io::Result<f32> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn f64_or(map: &HashMap<String, String>, k: &str, d: f64) -> io::Result<f64> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn u8_or(map: &HashMap<String, String>, k: &str, d: u8) -> io::Result<u8> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn _u16_or(map: &HashMap<String, String>, k: &str, d: u16) -> io::Result<u16> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn u32_or(map: &HashMap<String, String>, k: &str, d: u32) -> io::Result<u32> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn u64_or(map: &HashMap<String, String>, k: &str, d: u64) -> io::Result<u64> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn i32_or(map: &HashMap<String, String>, k: &str, d: i32) -> io::Result<i32> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v.parse().map_err(|e| inv(k, e)),
            }
        }

        fn f32_vec(map: &HashMap<String, String>, k: &str, d: Vec<f32>) -> io::Result<Vec<f32>> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v
                    .split_whitespace()
                    .map(|s| s.parse::<f32>().map_err(|e| inv(k, e)))
                    .collect(),
            }
        }

        fn f64_vec(map: &HashMap<String, String>, k: &str, d: Vec<f64>) -> io::Result<Vec<f64>> {
            match map.get(k) {
                None => Ok(d),
                Some(v) => v
                    .split_whitespace()
                    .map(|s| s.parse::<f64>().map_err(|e| inv(k, e)))
                    .collect(),
            }
        }

        // Parse all key = value pairs; strip inline comments and lowercase keys.
        let mut map = HashMap::<String, String>::new();
        for line in data.lines() {
            let line = line.split(';').next().unwrap_or("").trim();
            if line.is_empty() {
                continue;
            }
            if let Some((k, v)) = line.split_once('=') {
                map.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned());
            }
        }

        let integrator_s = get_s(&map, "integrator")
            .unwrap_or("md")
            .to_ascii_lowercase();

        let integrator = match integrator_s.as_str() {
            "md" => Integrator::Md,
            "md-vv" => Integrator::MdVv,
            "md-vv-avek" => Integrator::MdVvAvek,
            "bd" => Integrator::Bd,
            "sd" => Integrator::Sd,
            "steep" => Integrator::Steep {
                emtol: f32_or(&map, "emtol", 10.0)?,
                emstep: f32_or(&map, "emstep", 0.01)?,
            },
            "cg" => Integrator::Cg {
                emtol: f32_or(&map, "emtol", 10.0)?,
                nstcgsteep: u32_or(&map, "nstcgsteep", 1000)?,
            },
            "l-bfgs" => Integrator::LBfgs {
                nbfgscorr: u8_or(&map, "nbfgscorr", 10)?,
            },
            "nm" => Integrator::Nm,
            "tpi" => Integrator::Tpi,
            "tpic" => Integrator::Tpic,
            "mimic" => Integrator::Mimic,
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown integrator: {o}"),
                ));
            }
        };

        // todo: I do not like these defaulting to duplicates of default values.
        let nsteps = u64_or(&map, "nsteps", 0)?;
        let dt = f32_or(&map, "dt", 0.001)?;
        let nstxout = u32_or(&map, "nstxout", 0)?;
        let nstvout = u32_or(&map, "nstvout", 0)?;
        let nstfout = u32_or(&map, "nstfout", 0)?;
        let nstlog = u32_or(&map, "nstlog", 1_000)?;
        let nstcalcenergy = u32_or(&map, "nstcalcenergy", 100)?;
        let nstenergy = u32_or(&map, "nstenergy", 1_000)?;
        let nstxout_compressed = u32_or(&map, "nstxout-compressed", 0)?;

        let compressed_x_precision = u32_or(&map, "compressed-x-precision", 1_000)?;

        // Parse rcoulomb early — needed to convert ewald-rtol → alpha.
        let rcoulomb = f32_or(&map, "rcoulomb", 1.0)?;

        let coulomb_s = get_s(&map, "coulombtype")
            .unwrap_or("pme")
            .to_ascii_lowercase();

        let coulombtype = match coulomb_s.as_str() {
            "pme" => {
                let d = PmeConfig::default();
                let fourierspacing = f32_or(&map, "fourierspacing", d.fourierspacing)?;
                let order = u8_or(&map, "pme-order", d.order)?;
                // Parse ewald-rtol (GROMACS default 1e-5), then invert to alpha (nm⁻¹).
                let rtol = f32_or(&map, "ewald-rtol", 1e-5_f32)?;
                let rtol_lj = f32_or(&map, "ewald-rtol-lj", d.rtol_lj)?;
                let epsilon_surface = map
                    .get("epsilon-surface")
                    .map(|v| v.parse::<f32>().map_err(|e| inv("epsilon-surface", e)))
                    .transpose()?;
                CoulombType::Pme(PmeConfig {
                    fourierspacing,
                    order,
                    alpha: erfc_inv_approx(rtol) / rcoulomb,
                    rtol_lj,
                    epsilon_surface,
                })
            }
            "cut-off" => CoulombType::CutOff,
            "reaction-field" => CoulombType::ReactionField,
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown coulombtype: {o}"),
                ));
            }
        };

        let vdw_s = get_s(&map, "vdw-type")
            .unwrap_or("cut-off")
            .to_ascii_lowercase();

        let vdwtype = match VdwType::from_key(&vdw_s) {
            Some(v) => v,
            None => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown vdw-type: {vdw_s}"),
                ));
            }
        };

        let vdwm_s = get_s(&map, "vdw-modifier")
            .unwrap_or("Potential-shift")
            .to_ascii_lowercase();

        let vdw_modifier = match VdwModifier::from_key(&vdwm_s) {
            Some(v) => v,
            None => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown vdw-modifier type: {vdwm_s}"),
                ));
            }
        };

        let rvdw = f32_or(&map, "rvdw", 1.0)?;

        let tcoupl_s = get_s(&map, "tcoupl")
            .unwrap_or("v-rescale")
            .to_ascii_lowercase();

        let thermostat = match tcoupl_s.as_str() {
            "no" => Thermostat::No,
            "nose-hoover" => Thermostat::NoseHoover,
            "andersen" => Thermostat::Andersen,
            "andersen-massive" => Thermostat::AndersenMassive,
            "v-rescale" => Thermostat::VRescale,
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown tcoupl: {o}"),
                ));
            }
        };
        let tau_t = f32_vec(&map, "tau-t", vec![0.1])?;
        let ref_t = f32_vec(&map, "ref-t", vec![300.0])?;

        let pcoupl_s = get_s(&map, "pcoupl").unwrap_or("no").to_ascii_lowercase();

        let pcoupltype_s = get_s(&map, "pcoupltype")
            .unwrap_or("isotropic")
            .to_ascii_lowercase();

        let pcoupltype = match pcoupltype_s.as_str() {
            "isotropic" => PressureCouplingType::Isotropic {
                compressibility: f64_or(&map, "compressibility", 4.5e-5)?,
                ref_p: f32_or(&map, "ref-p", 1.0)?,
            },
            "semiisotropic" => {
                let comp = f64_vec(&map, "compressibility", vec![4.5e-5, 4.5e-5])?;
                let rp = f32_vec(&map, "ref-p", vec![1.0, 1.0])?;
                PressureCouplingType::Semiisotropic {
                    compressibility_xy: comp.first().copied().unwrap_or(4.5e-5),
                    compressibility_z: comp.get(1).copied().unwrap_or(4.5e-5),
                    ref_p_xy: rp.first().copied().unwrap_or(1.0),
                    ref_p_z: rp.get(1).copied().unwrap_or(1.0),
                }
            }
            "anisotropic" => {
                let comp = f64_vec(&map, "compressibility", vec![4.5e-5; 6])?;
                let rp = f32_vec(&map, "ref-p", vec![1.0; 6])?;
                let mut compressibility = [4.5e-5f64; 6];
                let mut ref_p = [1.0; 6];

                for (i, v) in comp.iter().enumerate().take(6) {
                    compressibility[i] = *v;
                }
                for (i, v) in rp.iter().enumerate().take(6) {
                    ref_p[i] = *v;
                }
                PressureCouplingType::Anisotropic {
                    compressibility,
                    ref_p,
                }
            }
            "surface-tension" => {
                let comp = f64_vec(&map, "compressibility", vec![4.5e-5, 4.5e-5])?;
                let rp = f32_vec(&map, "ref-p", vec![0.0, 1.0])?;
                PressureCouplingType::SurfaceTension {
                    compressibility_xy: comp.first().copied().unwrap_or(4.5e-5),
                    compressibility_z: comp.get(1).copied().unwrap_or(4.5e-5),
                    ref_p_sfc_tension: rp.first().copied().unwrap_or(0.0),
                    ref_p_z: rp.get(1).copied().unwrap_or(1.0),
                }
            }
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown pcoupltype: {o}"),
                ));
            }
        };

        let tau_p = f32_or(&map, "tau-p", 5.0)?;
        let barostat_cfg = BarostatCfg { pcoupltype, tau_p };

        let pcoupl = match pcoupl_s.as_str() {
            "no" => Barostat::No,
            "berendsen" => Barostat::Berendsen(barostat_cfg),
            "c-rescale" => Barostat::CRescale(barostat_cfg),
            "parrinello-rahman" => Barostat::ParrinelloRahman(barostat_cfg),
            "mttk" => Barostat::Mtkk(barostat_cfg),
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown pcoupl: {o}"),
                ));
            }
        };

        let pbc_s = get_s(&map, "pbc").unwrap_or("xyz").to_ascii_lowercase();
        let pbc = match Pbc::from_key(&pbc_s) {
            Some(pbc) => pbc,
            None => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown pbc: {pbc_s}"),
                ));
            }
        };

        let gen_vel_s = get_s(&map, "gen-vel").unwrap_or("no").to_ascii_lowercase();
        let gen_vel = matches!(gen_vel_s.as_str(), "yes" | "true" | "1");
        let gen_temp = f32_or(&map, "gen-temp", 300.0)?;

        let mut gen_seed = Some(i32_or(&map, "gen-seed", -1)?);
        if gen_seed == Some(-1) {
            gen_seed = None;
        }

        // Handle both the correct spelling and the typo in ConstraintAlgorithm::make_inp.
        let ca_s = map
            .get("constraint-algorithm")
            .or_else(|| map.get("constraint-algorithm"))
            .map(String::as_str)
            .unwrap_or("lincs")
            .to_ascii_lowercase();

        let constraint_algorithm = match ca_s.as_str() {
            "lincs" => ConstraintAlgorithm::Lincs {
                order: u8_or(&map, "lincs-order", 4)?,
                iter: u8_or(&map, "lincs-iter", 1)?,
            },
            "shake" => ConstraintAlgorithm::Shake {
                tol: f32_or(&map, "shake-tol", 0.0001)?,
            },
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown constraint-algorithm: {o}"),
                ));
            }
        };

        let constr_s = get_s(&map, "constraints")
            .unwrap_or("h-bonds")
            .to_ascii_lowercase();

        let constraints = match constr_s.as_str() {
            "none" => Constraints::None,
            "h-bonds" => Constraints::HBonds(constraint_algorithm),
            "all-bonds" => Constraints::AllBonds(constraint_algorithm),
            "h-angles" => Constraints::HAngles(constraint_algorithm),
            "all-angles" => Constraints::AllAngles(constraint_algorithm),
            o => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("unknown constraints: {o}"),
                ));
            }
        };

        let free_energy_calculations = match get_s(&map, "free-energy").unwrap_or("no") {
            "yes" => FreeEnergyCalculations::Yes,
            "expanded" => FreeEnergyCalculations::Expanded,
            _ => FreeEnergyCalculations::No,
        };

        Ok(Self {
            integrator,
            nsteps,
            dt,
            output_control: OutputControl {
                nstxout: Some(nstxout),
                nstvout: Some(nstvout),
                nstfout: Some(nstfout),
                nstxout_compressed: Some(nstxout_compressed),
                nstenergy: Some(nstenergy),
                nstcalcenergy: Some(nstcalcenergy),
                nstlog: Some(nstlog),
                compressed_x_precision,
            },
            coulombtype,
            rcoulomb,
            vdwtype,
            vdw_modifier,
            rvdw,
            thermostat,
            tau_t,
            ref_t,
            pcoupl,
            pbc,
            gen_vel,
            gen_temp,
            gen_seed,
            constraints,
            free_energy_calculations,
        })
    }

    /// Save to a .mdp file
    pub fn save(&self, path: &Path) -> io::Result<()> {
        save_txt_to_file(path, &self.to_mdp_str())
    }

    pub fn load(path: &Path) -> io::Result<Self> {
        Self::from_mdp_str(&std::fs::read_to_string(path)?)
    }
}