oximo-gams 0.1.0

GAMS writer and backend for oximo
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
//! Per-solver typed option structs and [`GamsSolverConfig`].
// TODO: Add more SolverConfig variants for other solvers when we add NLP/MINLP support

use std::fmt::Write as FmtWrite;

use crate::options::GamsSolver;

// - Config enum

/// Selects a GAMS sub-solver and optionally carries typed options written to
/// a `<solver>.opt` file before invoking GAMS.
///
/// Use [`GamsSolverConfig::Named`] to select a solver by name with no extra
/// options.
///
/// A [`From<GamsSolver>`] impl allows passing a bare `GamsSolver` wherever
/// a `GamsSolverConfig` is expected.
///
/// References:
/// - "GAMS Solver Manuals," GAMS Development Corporation.
///   <https://www.gams.com/latest/docs/S_MAIN.html#SOLVERS_MODEL_TYPES> (accessed May 14, 2026).
#[derive(Clone, Debug)]
pub enum GamsSolverConfig {
    Baron(GamsBaronOptions),
    Cbc(GamsCbcOptions),
    Cplex(GamsCplexOptions),
    Gurobi(GamsGurobiOptions),
    Highs(GamsHighsOptions),
    Ipopt(GamsIpoptOptions),
    Knitro(GamsKnitroOptions),
    Mosek(GamsMosekOptions),
    Scip(GamsScipOptions),
    Xpress(GamsXpressOptions),
    /// Any solver selectable by name with no typed option file.
    Named(GamsSolver),
}

impl GamsSolverConfig {
    /// GAMS solver keyword for `option {LP|MIP} = ...;`.
    #[must_use]
    pub fn gams_name(&self) -> &str {
        match self {
            Self::Baron(_) => "BARON",
            Self::Cbc(_) => "CBC",
            Self::Cplex(_) => "CPLEX",
            Self::Gurobi(_) => "GUROBI",
            Self::Highs(_) => "HIGHS",
            Self::Ipopt(_) => "IPOPT",
            Self::Knitro(_) => "KNITRO",
            Self::Mosek(_) => "MOSEK",
            Self::Scip(_) => "SCIP",
            Self::Xpress(_) => "XPRESS",
            Self::Named(s) => s.name(),
        }
    }

    /// Write options to `buf`. Returns `true` if anything was written.
    /// When `true`, the caller should write `buf` to `<solver_lowercase>.opt`
    /// in the GAMS working directory and set `model.optfile = 1`.
    #[must_use]
    pub fn write_opt_file(&self, buf: &mut String) -> bool {
        match self {
            Self::Baron(o) => o.write(buf),
            Self::Cbc(o) => o.write(buf),
            Self::Cplex(o) => o.write(buf),
            Self::Gurobi(o) => o.write(buf),
            Self::Highs(o) => o.write(buf),
            Self::Ipopt(o) => o.write(buf),
            Self::Knitro(o) => o.write(buf),
            Self::Mosek(o) => o.write(buf),
            Self::Scip(o) => o.write(buf),
            Self::Xpress(o) => o.write(buf),
            Self::Named(_) => false,
        }
    }
}

impl From<GamsSolver> for GamsSolverConfig {
    fn from(s: GamsSolver) -> Self {
        Self::Named(s)
    }
}

// - Helpers

fn kv(buf: &mut String, key: &str, val: impl std::fmt::Display) {
    writeln!(buf, "{key} {val}").unwrap();
}

fn kv_eq(buf: &mut String, key: &str, val: impl std::fmt::Display) {
    writeln!(buf, "{key} = {val}").unwrap();
}

// - BARON

/// Options for the BARON global solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_BARON.html>
#[derive(Clone, Debug, Default)]
pub struct GamsBaronOptions {
    /// Max wall-clock time in seconds (`MaxTime`)
    pub max_time: Option<f64>,
    /// Max branch-and-reduce iterations (`MaxIter`)
    pub max_iter: Option<i64>,
    /// Relative optimality gap (`EpsR`)
    pub eps_r: Option<f64>,
    /// Absolute optimality gap (`EpsA`)
    pub eps_a: Option<f64>,
    /// Absolute constraint feasibility tolerance (`AbsConFeasTol`)
    pub abs_con_feas_tol: Option<f64>,
    /// Absolute integrality tolerance (`AbsIntFeasTol`)
    pub abs_int_feas_tol: Option<f64>,
    /// Threads for MIP subproblems (`Threads`)
    pub threads: Option<u32>,
    /// Local searches in preprocessing (`NumLoc`)
    pub num_loc: Option<i32>,
    /// Number of feasible solutions to find (`NumSol`)
    pub num_sol: Option<i32>,
    /// Objective cutoff (`CutOff`)
    pub cut_off: Option<f64>,
}

impl GamsBaronOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("MaxTime", self.max_time);
        w!("MaxIter", self.max_iter);
        w!("EpsR", self.eps_r);
        w!("EpsA", self.eps_a);
        w!("AbsConFeasTol", self.abs_con_feas_tol);
        w!("AbsIntFeasTol", self.abs_int_feas_tol);
        w!("Threads", self.threads);
        w!("NumLoc", self.num_loc);
        w!("NumSol", self.num_sol);
        w!("CutOff", self.cut_off);
        n > 0
    }
}

// - CBC

/// `presolve` setting for CBC.
#[derive(Clone, Debug)]
pub enum GamsCbcPresolve {
    On,
    Off,
    More,
}

/// `cuts` setting for CBC.
#[derive(Clone, Debug)]
pub enum GamsCbcCuts {
    Off,
    On,
    Root,
    IfMove,
    ForceOn,
}

/// Options for the CBC LP/MIP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_CBC.html>
#[derive(Clone, Debug, Default)]
pub struct GamsCbcOptions {
    pub threads: Option<u32>,
    /// Relative MIP gap (`optcr`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`optca`)
    pub mip_abs_gap: Option<f64>,
    /// Max branch-and-bound nodes (`nodlim`)
    pub node_limit: Option<u64>,
    pub presolve: Option<GamsCbcPresolve>,
    pub cuts: Option<GamsCbcCuts>,
    /// Enable MIP heuristics (`heuristics`)
    pub heuristics: Option<bool>,
}

impl GamsCbcOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("threads", self.threads);
        w!("optcr", self.mip_rel_gap);
        w!("optca", self.mip_abs_gap);
        w!("nodlim", self.node_limit);
        if let Some(p) = &self.presolve {
            kv(
                buf,
                "presolve",
                match p {
                    GamsCbcPresolve::On => "on",
                    GamsCbcPresolve::Off => "off",
                    GamsCbcPresolve::More => "more",
                },
            );
            n += 1;
        }
        if let Some(c) = &self.cuts {
            kv(
                buf,
                "cuts",
                match c {
                    GamsCbcCuts::Off => "off",
                    GamsCbcCuts::On => "on",
                    GamsCbcCuts::Root => "root",
                    GamsCbcCuts::IfMove => "ifmove",
                    GamsCbcCuts::ForceOn => "forceOn",
                },
            );
            n += 1;
        }
        if let Some(h) = self.heuristics {
            kv(buf, "heuristics", i32::from(h));
            n += 1;
        }
        n > 0
    }
}

// - CPLEX

/// `mipemphasis` strategy for CPLEX.
#[derive(Clone, Debug)]
pub enum GamsCplexMipEmphasis {
    /// Balanced: feasibility and optimality (0)
    Balanced,
    /// Emphasize feasibility (1)
    Feasibility,
    /// Emphasize proving optimality (2)
    Optimality,
    /// Emphasize best bound (3)
    BestBound,
    /// Emphasize hidden feasibility (4)
    HiddenFeasibility,
}

/// Options for the CPLEX LP/MIP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_CPLEX.html>
#[derive(Clone, Debug, Default)]
pub struct GamsCplexOptions {
    pub threads: Option<u32>,
    /// Relative MIP gap (`epgap`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`epagap`)
    pub mip_abs_gap: Option<f64>,
    /// Max B&B nodes (`nodelim`)
    pub node_limit: Option<u64>,
    /// Limit on integer solutions found (`intsollim`)
    pub int_sol_limit: Option<u32>,
    /// Enable presolve (`preind`)
    pub presolve: Option<bool>,
    /// MIP solution tactics (`mipemphasis`)
    pub mip_emphasis: Option<GamsCplexMipEmphasis>,
    /// Node selection (`nodesel`)
    pub node_select: Option<i32>,
    /// Variable selection (`varsel`)
    pub var_select: Option<i32>,
    /// Integrality tolerance (`epint`)
    pub int_tol: Option<f64>,
    /// Feasibility tolerance (`eprhs`)
    pub feasibility_tol: Option<f64>,
    /// Optimality tolerance (`epopt`)
    pub optimality_tol: Option<f64>,
    /// LP algorithm (`lpmethod`)
    pub lp_method: Option<i32>,
}

impl GamsCplexOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("threads", self.threads);
        w!("epgap", self.mip_rel_gap);
        w!("epagap", self.mip_abs_gap);
        w!("nodelim", self.node_limit);
        w!("intsollim", self.int_sol_limit);
        if let Some(pre) = self.presolve {
            kv(buf, "preind", i32::from(pre));
            n += 1;
        }
        if let Some(e) = &self.mip_emphasis {
            kv(
                buf,
                "mipemphasis",
                match e {
                    GamsCplexMipEmphasis::Balanced => 0,
                    GamsCplexMipEmphasis::Feasibility => 1,
                    GamsCplexMipEmphasis::Optimality => 2,
                    GamsCplexMipEmphasis::BestBound => 3,
                    GamsCplexMipEmphasis::HiddenFeasibility => 4,
                },
            );
            n += 1;
        }
        w!("nodesel", self.node_select);
        w!("varsel", self.var_select);
        w!("epint", self.int_tol);
        w!("eprhs", self.feasibility_tol);
        w!("epopt", self.optimality_tol);
        w!("lpmethod", self.lp_method);
        n > 0
    }
}

// - GUROBI

/// `mipfocus` strategy for Gurobi.
#[derive(Clone, Debug)]
pub enum GamsGurobiMipFocus {
    /// Balanced (0)
    Balanced,
    /// Emphasize feasible solutions (1)
    Feasibility,
    /// Emphasize proving optimality (2)
    Optimality,
    /// Emphasize improving best bound (3)
    BestBound,
}

/// Options for the Gurobi LP/MIP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_GUROBI.html>
#[derive(Clone, Debug, Default)]
pub struct GamsGurobiOptions {
    pub threads: Option<u32>,
    /// Relative MIP gap (`mipgap`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`mipgapabs`)
    pub mip_abs_gap: Option<f64>,
    /// Max nodes (`nodelimit`).
    pub node_limit: Option<u64>,
    /// Presolve level (`presolve`)
    pub presolve: Option<i32>,
    /// Cut generation (`cuts`)
    pub cuts: Option<i32>,
    /// MIP heuristics effort (`heuristics`)
    pub heuristics: Option<f64>,
    /// Algorithm (`method`)
    pub method: Option<i32>,
    /// MIP solution focus (`mipfocus`)
    pub mip_focus: Option<GamsGurobiMipFocus>,
    /// Primal feasibility tolerance (`feasibilitytol`)
    pub feasibility_tol: Option<f64>,
    /// Integer feasibility tolerance (`intfeastol`)
    pub int_feas_tol: Option<f64>,
    /// Dual feasibility tolerance (`optimalitytol`)
    pub optimality_tol: Option<f64>,
}

impl GamsGurobiOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("threads", self.threads);
        w!("mipgap", self.mip_rel_gap);
        w!("mipgapabs", self.mip_abs_gap);
        w!("nodelimit", self.node_limit);
        w!("presolve", self.presolve);
        w!("cuts", self.cuts);
        w!("heuristics", self.heuristics);
        w!("method", self.method);
        if let Some(f) = &self.mip_focus {
            kv(
                buf,
                "mipfocus",
                match f {
                    GamsGurobiMipFocus::Balanced => 0,
                    GamsGurobiMipFocus::Feasibility => 1,
                    GamsGurobiMipFocus::Optimality => 2,
                    GamsGurobiMipFocus::BestBound => 3,
                },
            );
            n += 1;
        }
        w!("feasibilitytol", self.feasibility_tol);
        w!("intfeastol", self.int_feas_tol);
        w!("optimalitytol", self.optimality_tol);
        n > 0
    }
}

// - HiGHS

/// `presolve` setting for HiGHS.
#[derive(Clone, Debug)]
pub enum GamsHighsPresolve {
    On,
    Off,
    Choose,
}

/// LP algorithm for HiGHS.
#[derive(Clone, Debug)]
pub enum GamsHighsSolver {
    Simplex,
    Ipm,
    Ipx,
    Pdlp,
    Choose,
}

/// Options for the HiGHS LP/MIP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_HIGHS.html>
#[derive(Clone, Debug, Default)]
pub struct GamsHighsOptions {
    pub threads: Option<u32>,
    /// Relative MIP gap (`mip_rel_gap`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`mip_abs_gap`)
    pub mip_abs_gap: Option<f64>,
    /// Max nodes (`nodlim`)
    pub node_limit: Option<u64>,
    pub presolve: Option<GamsHighsPresolve>,
    pub solver: Option<GamsHighsSolver>,
    pub primal_feasibility_tol: Option<f64>,
    pub dual_feasibility_tol: Option<f64>,
    pub optimality_tol: Option<f64>,
}

impl GamsHighsOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv_eq(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("threads", self.threads);
        w!("mip_rel_gap", self.mip_rel_gap);
        w!("mip_abs_gap", self.mip_abs_gap);
        w!("nodlim", self.node_limit);
        if let Some(p) = &self.presolve {
            kv_eq(
                buf,
                "presolve",
                match p {
                    GamsHighsPresolve::On => "on",
                    GamsHighsPresolve::Off => "off",
                    GamsHighsPresolve::Choose => "choose",
                },
            );
            n += 1;
        }
        if let Some(s) = &self.solver {
            kv_eq(
                buf,
                "solver",
                match s {
                    GamsHighsSolver::Simplex => "simplex",
                    GamsHighsSolver::Ipm => "ipm",
                    GamsHighsSolver::Ipx => "ipx",
                    GamsHighsSolver::Pdlp => "pdlp",
                    GamsHighsSolver::Choose => "choose",
                },
            );
            n += 1;
        }
        w!("primal_feasibility_tolerance", self.primal_feasibility_tol);
        w!("dual_feasibility_tolerance", self.dual_feasibility_tol);
        w!("optimality_tolerance", self.optimality_tol);
        n > 0
    }
}

// - IPOPT

/// Linear solver for IPOPT.
#[derive(Clone, Debug)]
pub enum GamsIpoptLinearSolver {
    Mumps,
    Ma27,
    Ma57,
    Ma86,
    Ma97,
    PardisoMkl,
}

/// Barrier parameter update strategy for IPOPT.
#[derive(Clone, Debug)]
pub enum GamsIpoptMuStrategy {
    Monotone,
    Adaptive,
}

/// Options for the IPOPT NLP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_IPOPT.html>
#[derive(Clone, Debug, Default)]
pub struct GamsIpoptOptions {
    /// Max iterations (`max_iter`)
    pub max_iter: Option<u32>,
    /// Primary optimality tolerance (`tol`)
    pub tol: Option<f64>,
    /// Constraint violation tolerance (`constr_viol_tol`)
    pub constr_viol_tol: Option<f64>,
    /// Dual infeasibility tolerance (`dual_inf_tol`)
    pub dual_inf_tol: Option<f64>,
    /// Complementarity tolerance (`compl_inf_tol`)
    pub compl_inf_tol: Option<f64>,
    /// Relaxed convergence tolerance (`acceptable_tol`)
    pub acceptable_tol: Option<f64>,
    pub linear_solver: Option<GamsIpoptLinearSolver>,
    /// Print level 0–12 (`print_level`)
    pub print_level: Option<u32>,
    pub mu_strategy: Option<GamsIpoptMuStrategy>,
}

impl GamsIpoptOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("max_iter", self.max_iter);
        w!("tol", self.tol);
        w!("constr_viol_tol", self.constr_viol_tol);
        w!("dual_inf_tol", self.dual_inf_tol);
        w!("compl_inf_tol", self.compl_inf_tol);
        w!("acceptable_tol", self.acceptable_tol);
        if let Some(ls) = &self.linear_solver {
            kv(
                buf,
                "linear_solver",
                match ls {
                    GamsIpoptLinearSolver::Mumps => "mumps",
                    GamsIpoptLinearSolver::Ma27 => "ma27",
                    GamsIpoptLinearSolver::Ma57 => "ma57",
                    GamsIpoptLinearSolver::Ma86 => "ma86",
                    GamsIpoptLinearSolver::Ma97 => "ma97",
                    GamsIpoptLinearSolver::PardisoMkl => "pardisomkl",
                },
            );
            n += 1;
        }
        w!("print_level", self.print_level);
        if let Some(mu) = &self.mu_strategy {
            kv(
                buf,
                "mu_strategy",
                match mu {
                    GamsIpoptMuStrategy::Monotone => "monotone",
                    GamsIpoptMuStrategy::Adaptive => "adaptive",
                },
            );
            n += 1;
        }
        n > 0
    }
}

// - KNITRO

/// NLP algorithm for KNITRO.
#[derive(Clone, Debug)]
pub enum GamsKnitroAlgorithm {
    /// Automatic (0)
    Auto,
    /// Interior-point / Direct (1)
    InteriorDirect,
    /// Interior-point / CG (2)
    InteriorCg,
    /// Active-set (3)
    ActiveSet,
    /// SQP (4)
    Sqp,
}

/// Options for the KNITRO NLP/MIP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_KNITRO.html>
#[derive(Clone, Debug, Default)]
pub struct GamsKnitroOptions {
    pub algorithm: Option<GamsKnitroAlgorithm>,
    /// Max iterations (`maxit`)
    pub max_iter: Option<u32>,
    /// Relative KKT optimality tolerance (`opttol`)
    pub opt_tol: Option<f64>,
    /// Absolute KKT optimality tolerance (`opttol_abs`)
    pub opt_tol_abs: Option<f64>,
    /// Relative feasibility tolerance (`feastol`)
    pub feas_tol: Option<f64>,
    /// Absolute feasibility tolerance (`feastol_abs`)
    pub feas_tol_abs: Option<f64>,
    pub threads: Option<u32>,
    /// Max B&B nodes (`mip_maxnodes`)
    pub mip_max_nodes: Option<u64>,
    /// Relative MIP gap (`mip_opt_gap_rel`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`mip_opt_gap_abs`)
    pub mip_abs_gap: Option<f64>,
}

impl GamsKnitroOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        if let Some(alg) = &self.algorithm {
            kv(
                buf,
                "nlp_algorithm",
                match alg {
                    GamsKnitroAlgorithm::Auto => 0,
                    GamsKnitroAlgorithm::InteriorDirect => 1,
                    GamsKnitroAlgorithm::InteriorCg => 2,
                    GamsKnitroAlgorithm::ActiveSet => 3,
                    GamsKnitroAlgorithm::Sqp => 4,
                },
            );
            n += 1;
        }
        w!("maxit", self.max_iter);
        w!("opttol", self.opt_tol);
        w!("opttol_abs", self.opt_tol_abs);
        w!("feastol", self.feas_tol);
        w!("feastol_abs", self.feas_tol_abs);
        w!("threads", self.threads);
        w!("mip_maxnodes", self.mip_max_nodes);
        w!("mip_opt_gap_rel", self.mip_rel_gap);
        w!("mip_opt_gap_abs", self.mip_abs_gap);
        n > 0
    }
}

// - MOSEK

/// Options for the MOSEK LP/MIP/NLP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_MOSEK.html>
#[derive(Clone, Debug, Default)]
pub struct GamsMosekOptions {
    /// Threads (`MSK_IPAR_NUM_THREADS`)
    pub threads: Option<u32>,
    /// Relative MIP gap (`MSK_DPAR_MIO_TOL_REL_GAP`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`MSK_DPAR_MIO_TOL_ABS_GAP`)
    pub mip_abs_gap: Option<f64>,
    /// Max relaxations in B&B (`MSK_IPAR_MIO_MAX_NUM_RELAXS`)
    pub max_relaxations: Option<i64>,
    /// Max branches (`MSK_IPAR_MIO_MAX_NUM_BRANCHES`)
    pub max_branches: Option<i64>,
    /// Primal feasibility tolerance (`MSK_DPAR_INTPNT_TOL_PFEAS`)
    pub primal_feas_tol: Option<f64>,
    /// Dual feasibility tolerance (`MSK_DPAR_INTPNT_TOL_DFEAS`)
    pub dual_feas_tol: Option<f64>,
    /// MIO feasibility tolerance (`MSK_DPAR_MIO_TOL_FEAS`)
    pub mio_feas_tol: Option<f64>,
    /// Integer relaxation tolerance (`MSK_DPAR_MIO_TOL_ABS_RELAX_INT`)
    pub int_relax_tol: Option<f64>,
}

impl GamsMosekOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("MSK_IPAR_NUM_THREADS", self.threads);
        w!("MSK_DPAR_MIO_TOL_REL_GAP", self.mip_rel_gap);
        w!("MSK_DPAR_MIO_TOL_ABS_GAP", self.mip_abs_gap);
        w!("MSK_IPAR_MIO_MAX_NUM_RELAXS", self.max_relaxations);
        w!("MSK_IPAR_MIO_MAX_NUM_BRANCHES", self.max_branches);
        w!("MSK_DPAR_INTPNT_TOL_PFEAS", self.primal_feas_tol);
        w!("MSK_DPAR_INTPNT_TOL_DFEAS", self.dual_feas_tol);
        w!("MSK_DPAR_MIO_TOL_FEAS", self.mio_feas_tol);
        w!("MSK_DPAR_MIO_TOL_ABS_RELAX_INT", self.int_relax_tol);
        n > 0
    }
}

// - SCIP

/// Options for the SCIP LP/MIP/NLP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_SCIP.html>
#[derive(Clone, Debug, Default)]
pub struct GamsScipOptions {
    /// Max nodes (`limits/nodes`)
    pub node_limit: Option<i64>,
    /// Relative MIP gap (`limits/gap`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`limits/gapabs`)
    pub mip_abs_gap: Option<f64>,
    /// Stop after N feasible solutions (`limits/solutions`)
    pub sol_limit: Option<u32>,
    /// Primal feasibility tolerance (`numerics/feastol`)
    pub feas_tol: Option<f64>,
    /// Dual feasibility tolerance (`numerics/dualfeastol`)
    pub dual_feas_tol: Option<f64>,
    /// Max presolve rounds (`presolving/maxrounds`)
    pub presolve_rounds: Option<i32>,
    /// Separation rounds at root (`separating/maxroundsroot`)
    pub sep_rounds_root: Option<u32>,
}

impl GamsScipOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv_eq(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("limits/nodes", self.node_limit);
        w!("limits/gap", self.mip_rel_gap);
        w!("limits/gapabs", self.mip_abs_gap);
        w!("limits/solutions", self.sol_limit);
        w!("numerics/feastol", self.feas_tol);
        w!("numerics/dualfeastol", self.dual_feas_tol);
        w!("presolving/maxrounds", self.presolve_rounds);
        w!("separating/maxroundsroot", self.sep_rounds_root);
        n > 0
    }
}

// - XPRESS

/// Options for the XPRESS LP/MIP solver.
///
/// Reference: <https://www.gams.com/latest/docs/S_XPRESS.html>
#[derive(Clone, Debug, Default)]
pub struct GamsXpressOptions {
    pub threads: Option<u32>,
    /// Relative MIP gap (`mipRelStop`)
    pub mip_rel_gap: Option<f64>,
    /// Absolute MIP gap (`mipAbsStop`)
    pub mip_abs_gap: Option<f64>,
    /// Max nodes (`maxNode`)
    pub node_limit: Option<u64>,
    /// Enable presolve (`presolve`)
    pub presolve: Option<bool>,
    /// Cut strategy (`cutStrategy`)
    pub cut_strategy: Option<i32>,
    /// Primal feasibility tolerance (`feasTol`)
    pub feas_tol: Option<f64>,
    /// Dual optimality tolerance (`optimalityTol`)
    pub optimality_tol: Option<f64>,
    /// MIP integrality tolerance (`mipTol`)
    pub mip_tol: Option<f64>,
    /// LP algorithm (`defaultAlg`)
    pub lp_algorithm: Option<i32>,
}

impl GamsXpressOptions {
    fn write(&self, buf: &mut String) -> bool {
        let mut n = 0usize;
        macro_rules! w {
            ($key:expr, $opt:expr) => {
                if let Some(v) = $opt {
                    kv(buf, $key, v);
                    n += 1;
                }
            };
        }
        w!("threads", self.threads);
        w!("mipRelStop", self.mip_rel_gap);
        w!("mipAbsStop", self.mip_abs_gap);
        w!("maxNode", self.node_limit);
        if let Some(p) = self.presolve {
            kv(buf, "presolve", i32::from(p));
            n += 1;
        }
        w!("cutStrategy", self.cut_strategy);
        w!("feasTol", self.feas_tol);
        w!("optimalityTol", self.optimality_tol);
        w!("mipTol", self.mip_tol);
        w!("defaultAlg", self.lp_algorithm);
        n > 0
    }
}

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

    #[test]
    fn baron_writes_space_separated() {
        let cfg = GamsSolverConfig::Baron(GamsBaronOptions {
            threads: Some(4),
            eps_r: Some(0.01),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("Threads 4\n"), "got: {buf}");
        assert!(buf.contains("EpsR 0.01\n"), "got: {buf}");
    }

    #[test]
    fn highs_writes_eq_separated() {
        let cfg = GamsSolverConfig::Highs(GamsHighsOptions {
            mip_rel_gap: Some(0.05),
            threads: Some(2),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("mip_rel_gap = 0.05\n"), "got: {buf}");
        assert!(buf.contains("threads = 2\n"), "got: {buf}");
    }

    #[test]
    fn highs_presolve_and_solver_enum() {
        let cfg = GamsSolverConfig::Highs(GamsHighsOptions {
            presolve: Some(GamsHighsPresolve::Off),
            solver: Some(GamsHighsSolver::Simplex),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("presolve = off\n"), "got: {buf}");
        assert!(buf.contains("solver = simplex\n"), "got: {buf}");
    }

    #[test]
    fn scip_writes_eq_separated() {
        let cfg = GamsSolverConfig::Scip(GamsScipOptions {
            mip_rel_gap: Some(0.01),
            node_limit: Some(1000),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("limits/gap = 0.01\n"), "got: {buf}");
        assert!(buf.contains("limits/nodes = 1000\n"), "got: {buf}");
    }

    #[test]
    fn gurobi_writes_space_separated() {
        let cfg = GamsSolverConfig::Gurobi(GamsGurobiOptions {
            threads: Some(8),
            mip_focus: Some(GamsGurobiMipFocus::Feasibility),
            presolve: Some(2),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("threads 8\n"), "got: {buf}");
        assert!(buf.contains("mipfocus 1\n"), "got: {buf}");
        assert!(buf.contains("presolve 2\n"), "got: {buf}");
    }

    #[test]
    fn cplex_bool_as_int_and_emphasis() {
        let cfg = GamsSolverConfig::Cplex(GamsCplexOptions {
            presolve: Some(false),
            mip_emphasis: Some(GamsCplexMipEmphasis::Feasibility),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("preind 0\n"), "got: {buf}");
        assert!(buf.contains("mipemphasis 1\n"), "got: {buf}");
    }

    #[test]
    fn cbc_enum_options() {
        let cfg = GamsSolverConfig::Cbc(GamsCbcOptions {
            presolve: Some(GamsCbcPresolve::On),
            cuts: Some(GamsCbcCuts::Root),
            heuristics: Some(true),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("presolve on\n"), "got: {buf}");
        assert!(buf.contains("cuts root\n"), "got: {buf}");
        assert!(buf.contains("heuristics 1\n"), "got: {buf}");
    }

    #[test]
    fn ipopt_string_options() {
        let cfg = GamsSolverConfig::Ipopt(GamsIpoptOptions {
            linear_solver: Some(GamsIpoptLinearSolver::Ma57),
            mu_strategy: Some(GamsIpoptMuStrategy::Adaptive),
            max_iter: Some(500),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("linear_solver ma57\n"), "got: {buf}");
        assert!(buf.contains("mu_strategy adaptive\n"), "got: {buf}");
        assert!(buf.contains("max_iter 500\n"), "got: {buf}");
    }

    #[test]
    fn knitro_algorithm_enum() {
        let cfg = GamsSolverConfig::Knitro(GamsKnitroOptions {
            algorithm: Some(GamsKnitroAlgorithm::Sqp),
            mip_rel_gap: Some(0.001),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("nlp_algorithm 4\n"), "got: {buf}");
        assert!(buf.contains("mip_opt_gap_rel 0.001\n"), "got: {buf}");
    }

    #[test]
    fn mosek_long_key_names() {
        let cfg = GamsSolverConfig::Mosek(GamsMosekOptions {
            threads: Some(2),
            mip_rel_gap: Some(1e-4),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("MSK_IPAR_NUM_THREADS 2\n"), "got: {buf}");
        assert!(buf.contains("MSK_DPAR_MIO_TOL_REL_GAP 0.0001\n"), "got: {buf}");
    }

    #[test]
    fn xpress_bool_presolve_and_gap() {
        let cfg = GamsSolverConfig::Xpress(GamsXpressOptions {
            presolve: Some(false),
            mip_rel_gap: Some(0.02),
            ..Default::default()
        });
        let mut buf = String::new();
        assert!(cfg.write_opt_file(&mut buf));
        assert!(buf.contains("presolve 0\n"), "got: {buf}");
        assert!(buf.contains("mipRelStop 0.02\n"), "got: {buf}");
    }

    #[test]
    fn empty_options_writes_nothing() {
        let cfg = GamsSolverConfig::Baron(GamsBaronOptions::default());
        let mut buf = String::new();
        assert!(!cfg.write_opt_file(&mut buf));
        assert!(buf.is_empty());
    }

    #[test]
    fn named_writes_nothing() {
        let cfg = GamsSolverConfig::Named(GamsSolver::Baron);
        let mut buf = String::new();
        assert!(!cfg.write_opt_file(&mut buf));
        assert!(buf.is_empty());
    }

    #[test]
    fn gams_name_matches_variant() {
        assert_eq!(GamsSolverConfig::Baron(GamsBaronOptions::default()).gams_name(), "BARON");
        assert_eq!(GamsSolverConfig::Cbc(GamsCbcOptions::default()).gams_name(), "CBC");
        assert_eq!(GamsSolverConfig::Cplex(GamsCplexOptions::default()).gams_name(), "CPLEX");
        assert_eq!(GamsSolverConfig::Gurobi(GamsGurobiOptions::default()).gams_name(), "GUROBI");
        assert_eq!(GamsSolverConfig::Highs(GamsHighsOptions::default()).gams_name(), "HIGHS");
        assert_eq!(GamsSolverConfig::Ipopt(GamsIpoptOptions::default()).gams_name(), "IPOPT");
        assert_eq!(GamsSolverConfig::Knitro(GamsKnitroOptions::default()).gams_name(), "KNITRO");
        assert_eq!(GamsSolverConfig::Mosek(GamsMosekOptions::default()).gams_name(), "MOSEK");
        assert_eq!(GamsSolverConfig::Scip(GamsScipOptions::default()).gams_name(), "SCIP");
        assert_eq!(GamsSolverConfig::Xpress(GamsXpressOptions::default()).gams_name(), "XPRESS");
        assert_eq!(GamsSolverConfig::Named(GamsSolver::Cplex).gams_name(), "CPLEX");
        assert_eq!(
            GamsSolverConfig::Named(GamsSolver::Custom("MYMIP".into())).gams_name(),
            "MYMIP"
        );
    }

    #[test]
    fn from_gams_solver_becomes_named() {
        let cfg: GamsSolverConfig = GamsSolver::Gurobi.into();
        assert!(matches!(cfg, GamsSolverConfig::Named(GamsSolver::Gurobi)));
        assert_eq!(cfg.gams_name(), "GUROBI");
    }
}