lp_parser_rs 4.1.0

A Rust parser for the LP file format.
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
//! MPS file writing and formatting utilities.
//!
//! This module writes an [`LpProblem`](crate::problem::LpProblem) back out in
//! MPS (Mathematical Programming System) format, mirroring the conventions of
//! the LP writer ([`crate::writer`]): a small options struct,
//! [`write_mps_string`](crate::mps::writer::write_mps_string) /
//! [`write_mps_string_with_options`](crate::mps::writer::write_mps_string_with_options)
//! entry points, and
//! a private tree of per-section builder functions. Output produced here is
//! designed to be read back by [`crate::mps::parse_mps`].
//!
//! # Formatting
//!
//! Output is **free-format** MPS: fields are whitespace-separated and padded
//! for readability rather than aligned to the strict fixed-column positions
//! of historical MPS. The reader (like most modern MPS parsers) only ever
//! splits on whitespace, so this is a purely cosmetic choice.
//!
//! # Sections emitted
//!
//! `NAME`, `OBJSENSE` (only when the sense is `Maximize` -- `Minimize` is the
//! MPS default and is left implicit), `ROWS`, `COLUMNS` (integer/general/binary
//! variables wrapped in `'MARKER'` `INTORG`/`INTEND` blocks), `RHS`, `RANGES`
//! (see below), `BOUNDS`, `SOS`, `ENDATA`.
//!
//! # RANGES
//!
//! [`LpProblem`](crate::problem::LpProblem) has no first-class notion of a
//! ranged constraint: the MPS reader flattens each `RANGES` row `X` into two
//! ordinary constraints -- `X` (`>=` lower) and `X_rng` (`<=` upper) with
//! identical coefficients. This writer reverses that flattening: when a
//! constraint pair matches the reader's exact pattern (`X` is `>=`, `X_rng`
//! is `<=`, identical coefficient vectors, upper >= lower, both RHS finite),
//! it is re-emitted as a single `G` row with a `RANGES` entry of
//! `upper - lower`, so `MPS -> LpProblem -> MPS` preserves the section. An
//! LP-authored pair that happens to match the pattern is merged the same way;
//! that is semantically lossless (the feasible region and the re-parsed
//! constraint pair are identical), it only changes the MPS text shape.
//!
//! # Objectives
//!
//! MPS represents exactly one objective (a single `N` row). If the problem
//! has more than one objective, [`write_mps_string`](crate::mps::writer::write_mps_string)
//! returns an error unless
//! [`allow_multiple_objectives`](crate::mps::writer::MpsWriterOptions::allow_multiple_objectives)
//! opts in to writing only the first objective (in insertion order). If the
//! problem has **no** objectives, a single empty `N` row is written under the
//! name [`EMPTY_OBJECTIVE_ROW_NAME`](crate::mps::writer::EMPTY_OBJECTIVE_ROW_NAME)
//! -- this is what [`parse_mps`](crate::mps::parse_mps) itself falls back to
//! when a file has no `N` rows, so the round trip is stable, but note that
//! re-parsing such a file yields a problem with **one** empty objective
//! rather than zero: an unavoidable asymmetry given MPS always has an
//! objective row.
//!
//! # Known round-trip limitations
//!
//! - [`General`](crate::model::VariableType::General) and
//!   [`Integer`](crate::model::VariableType::Integer) are both written
//!   identically (an `INTORG`/`INTEND` marker block plus an explicit `LO 0`
//!   bound, to avoid falling back to the MPS default integer bounds of
//!   `[0, 1]`). Re-parsing always yields `Integer`; the `General` designation
//!   is an LP-format-only distinction that has no MPS analogue.
//! - [`SemiContinuous`](crate::model::VariableType::SemiContinuous) carries no
//!   explicit upper bound in this model, but the MPS `SC` bound type requires
//!   one. A sentinel value (`SEMI_CONTINUOUS_SENTINEL_UPPER`, `1e30`)
//!   is written instead, and the reader resolves any `SC` bound back to
//!   `SemiContinuous`, so the type round trips. The flip side: an `SC` bound
//!   in an *external* MPS file with a meaningful finite upper bound has that
//!   bound dropped on parse (with a warning on stderr), because the model cannot
//!   carry both the semi-continuity flag and a bound value.
//! - Strict inequalities (`ComparisonOp::LT` / `ComparisonOp::GT`) have no MPS
//!   representation (only `L`/`G`/`E` rows exist); writing a problem with such
//!   a constraint returns an error.
//! - [`UpperBound`](crate::model::VariableType::UpperBound) with a negative
//!   value is written as an explicit `LO 0` followed by `UP`, rather than a
//!   bare `UP`. Per the MPS (CPLEX) convention the reader implements, a bare
//!   negative `UP` with no preceding `LO` implies a lower bound of `-inf`,
//!   which would silently change the feasible region; the explicit `LO 0`
//!   keeps it correct at the cost of re-parsing as `DoubleBound(0, ub)`
//!   rather than `UpperBound(ub)` (the same feasible region, a different
//!   variant).
//! - **Free-default conversion caveat**: [`LpProblem`](crate::problem::LpProblem) defaults an
//!   undeclared variable that only appears in constraints (never in a
//!   `Bounds`/`Free`/etc. section, and never given an explicit bound) to
//!   [`VariableType::Free`](crate::model::VariableType::Free), which this writer faithfully emits as an `FR`
//!   bound. LP format's own default for such a variable is `[0, +inf)`, not
//!   free -- so converting an LP file straight through this writer without
//!   ever having declared the variable's bounds widens its feasible region
//!   to include negative values. This is not a writer bug (the LP-side
//!   default is deliberately preserved rather than silently narrowed back
//!   down), but it is a real semantic difference to be aware of when the
//!   MPS output feeds another solver: declare bounds explicitly in the LP
//!   source (even a redundant `x >= 0`) if the distinction matters.

use std::fmt::Write;

use indexmap::IndexMap;
use rustc_hash::{FxHashMap, FxHashSet};

use crate::error::{LpParseError, LpResult};
use crate::interner::NameId;
use crate::model::{Coefficient, ComparisonOp, Constraint, Objective, Sense, VariableType};
use crate::problem::LpProblem;
use crate::writer::write_number;

/// Row name used for the objective when the problem has zero objectives.
///
/// See the "Objectives" section of the module documentation.
pub const EMPTY_OBJECTIVE_ROW_NAME: &str = "OBJ";

/// Sentinel upper bound written for [`VariableType::SemiContinuous`] variables,
/// which carry no explicit upper bound in this model. `1e30` is the
/// conventional "infinity" sentinel used by CPLEX/Gurobi-style MPS files.
pub(crate) const SEMI_CONTINUOUS_SENTINEL_UPPER: f64 = 1e30;

/// Fixed vector label written in the RHS section (the first field of each
/// RHS data line). The MPS reader accepts any label; only the first
/// encountered vector is honoured, so a single constant label is sufficient.
const RHS_VECTOR_LABEL: &str = "RHS";

/// Fixed vector label written in the BOUNDS section, analogous to
/// [`RHS_VECTOR_LABEL`].
const BOUNDS_VECTOR_LABEL: &str = "BOUND";

/// Options for controlling MPS file output format.
#[derive(Debug, Clone)]
pub struct MpsWriterOptions {
    /// Number of decimal places for numeric values (coefficients, RHS, bounds).
    pub decimal_precision: usize,
    /// If the problem has more than one objective, write only the first
    /// (in insertion order) instead of returning an error.
    pub allow_multiple_objectives: bool,
}

impl Default for MpsWriterOptions {
    fn default() -> Self {
        Self { decimal_precision: 6, allow_multiple_objectives: false }
    }
}

/// Write an `LpProblem` to a string in MPS format.
///
/// # Errors
///
/// Returns an error if the problem has more than one objective (see
/// [`MpsWriterOptions::allow_multiple_objectives`]) or contains a constraint
/// with a strict inequality operator (`<` or `>`), neither of which MPS can
/// represent.
pub fn write_mps_string(problem: &LpProblem) -> LpResult<String> {
    write_mps_string_with_options(problem, &MpsWriterOptions::default())
}

/// Write an `LpProblem` to a string in MPS format with custom options.
///
/// # Errors
///
/// See [`write_mps_string`].
pub fn write_mps_string_with_options(problem: &LpProblem, options: &MpsWriterOptions) -> LpResult<String> {
    let mut output = String::new();
    build_mps(&mut output, problem, options)?;
    Ok(output)
}

/// Build the full MPS document into `output`.
fn build_mps(output: &mut String, problem: &LpProblem, options: &MpsWriterOptions) -> LpResult<()> {
    let objective = select_objective(problem, options)?;
    let obj_row_name: &str = objective.map_or(EMPTY_OBJECTIVE_ROW_NAME, |o| problem.resolve(o.name));
    let range_pairs = detect_range_pairs(problem);

    write_name_line(output, problem).expect("fmt::Write to String is infallible");

    if problem.sense == Sense::Maximize {
        writeln!(output, "OBJSENSE").expect("fmt::Write to String is infallible");
        writeln!(output, "    MAX").expect("fmt::Write to String is infallible");
    }

    write_rows_section(output, problem, obj_row_name, &range_pairs)?;

    let columns = build_columns(problem, objective, obj_row_name, &range_pairs);
    write_columns_section(output, problem, &columns, options).expect("fmt::Write to String is infallible");

    write_rhs_section(output, problem, objective, obj_row_name, options, &range_pairs).expect("fmt::Write to String is infallible");
    write_ranges_section(output, problem, options, &range_pairs).expect("fmt::Write to String is infallible");
    write_bounds_section(output, problem, options)?;
    write_sos_section(output, problem, options).expect("fmt::Write to String is infallible");

    writeln!(output, "ENDATA").expect("fmt::Write to String is infallible");
    Ok(())
}

/// Constraint pairs that fold back into MPS `RANGES` entries.
///
/// See the "RANGES" section of the module documentation: `ranges` maps a base
/// constraint (`>=` lower) to its range value `upper - lower`, and `skip`
/// holds the `_rng` companion rows (`<=` upper) that must be omitted from the
/// `ROWS`, `COLUMNS`, and `RHS` sections because the single ranged row already
/// represents them.
#[derive(Default)]
struct RangePairs {
    ranges: FxHashMap<NameId, f64>,
    skip: FxHashSet<NameId>,
}

/// Return `true` if two coefficient vectors are equal as (variable, value)
/// sets. Values compare exactly: pairs produced by the reader's RANGES
/// flattening are bit-identical clones, and a near-miss simply doesn't pair.
fn coefficients_match(a: &[Coefficient], b: &[Coefficient]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let map: FxHashMap<NameId, f64> = a.iter().map(|c| (c.name, c.value)).collect();
    b.iter().all(|c| map.get(&c.name) == Some(&c.value))
}

/// Detect constraint pairs matching the reader's RANGES flattening pattern:
/// `X` (`>=` lower) plus `X_rng` (`<=` upper) with identical coefficients,
/// finite RHS values, and `upper >= lower`.
fn detect_range_pairs(problem: &LpProblem) -> RangePairs {
    let mut pairs = RangePairs::default();

    for (name_id, constraint) in &problem.constraints {
        let Constraint::Standard { name, coefficients, operator: ComparisonOp::LTE, rhs: upper_rhs, .. } = constraint else {
            continue;
        };
        let Some(base_name) = problem.resolve(*name).strip_suffix("_rng") else {
            continue;
        };
        let Some(base_id) = problem.name_id(base_name) else {
            continue;
        };
        let Some(Constraint::Standard { coefficients: base_coefficients, operator: ComparisonOp::GTE, rhs: lower_rhs, .. }) =
            problem.constraints.get(&base_id)
        else {
            continue;
        };
        if !upper_rhs.is_finite() || !lower_rhs.is_finite() || upper_rhs < lower_rhs {
            continue;
        }
        if !coefficients_match(base_coefficients, coefficients) {
            continue;
        }

        pairs.ranges.insert(base_id, upper_rhs - lower_rhs);
        pairs.skip.insert(*name_id);
    }

    debug_assert_eq!(pairs.ranges.len(), pairs.skip.len(), "every range entry must have exactly one skipped companion row");
    pairs
}

/// Select the objective to write, applying the single-objective rule.
///
/// # Errors
///
/// Returns an error if the problem has more than one objective and
/// `options.allow_multiple_objectives` is `false`.
fn select_objective<'p>(problem: &'p LpProblem, options: &MpsWriterOptions) -> LpResult<Option<&'p Objective>> {
    match problem.objectives.len() {
        0 => Ok(None),
        1 => Ok(problem.objectives.values().next()),
        count if options.allow_multiple_objectives => {
            debug_assert!(count > 1, "count > 1 guaranteed by preceding match arms");
            Ok(problem.objectives.values().next())
        }
        count => Err(LpParseError::validation_error(format!(
            "MPS format supports a single objective, but the problem has {count} objectives; \
             set MpsWriterOptions::allow_multiple_objectives to write only the first"
        ))),
    }
}

/// Write the `NAME` section header line.
fn write_name_line(output: &mut String, problem: &LpProblem) -> std::fmt::Result {
    match problem.name() {
        Some(name) => writeln!(output, "NAME          {name}"),
        None => writeln!(output, "NAME"),
    }
}

/// Map a comparison operator to its MPS row type letter.
///
/// # Errors
///
/// Returns an error for strict inequalities (`<`, `>`), which MPS cannot
/// represent (only `L`/`G`/`E` rows exist).
fn row_type_letter(operator: ComparisonOp, constraint_name: &str) -> LpResult<char> {
    match operator {
        ComparisonOp::LTE => Ok('L'),
        ComparisonOp::GTE => Ok('G'),
        ComparisonOp::EQ => Ok('E'),
        ComparisonOp::LT | ComparisonOp::GT => Err(LpParseError::validation_error(format!(
            "constraint '{constraint_name}' uses strict inequality '{operator}', which MPS cannot represent"
        ))),
    }
}

/// Write the `ROWS` section: the objective's `N` row followed by one row per
/// standard constraint. Ranged companion rows are omitted (see [`RangePairs`]).
fn write_rows_section(output: &mut String, problem: &LpProblem, obj_row_name: &str, range_pairs: &RangePairs) -> LpResult<()> {
    writeln!(output, "ROWS").expect("fmt::Write to String is infallible");
    writeln!(output, " N  {obj_row_name}").expect("fmt::Write to String is infallible");

    for (name_id, constraint) in &problem.constraints {
        if range_pairs.skip.contains(name_id) {
            continue;
        }
        if let Constraint::Standard { name, operator, .. } = constraint {
            let resolved_name = problem.resolve(*name);
            let letter = row_type_letter(*operator, resolved_name)?;
            writeln!(output, " {letter}  {resolved_name}").expect("fmt::Write to String is infallible");
        }
    }

    Ok(())
}

/// Whether a variable type must be wrapped in an `INTORG`/`INTEND` marker
/// block in the `COLUMNS` section.
const fn needs_marker(var_type: &VariableType) -> bool {
    matches!(var_type, VariableType::Integer | VariableType::General | VariableType::Binary)
}

/// Per-variable list of (row name, coefficient) pairs, in the order rows are
/// encountered (objective first, then constraints in insertion order).
type ColumnEntries<'p> = IndexMap<NameId, Vec<(&'p str, f64)>>;

/// Build the per-variable COLUMNS entries.
///
/// Iterates the objective and constraints once (rather than probing every
/// (variable, row) pair) and groups coefficients by variable, preserving
/// [`LpProblem::variables`] insertion order.
///
/// Variables that require a marker block ([`needs_marker`]) but have no
/// coefficients anywhere (isolated integer/general/binary variables) still
/// need at least one COLUMNS entry to be registered as a column and picked
/// up by the reader's `INTORG`/`INTEND` tracking -- a zero-valued entry
/// against the objective row is synthesised for them.
fn build_columns<'p>(
    problem: &'p LpProblem,
    objective: Option<&'p Objective>,
    obj_row_name: &'p str,
    range_pairs: &RangePairs,
) -> ColumnEntries<'p> {
    let mut columns: ColumnEntries<'p> = IndexMap::with_capacity(problem.variables.len());
    for name_id in problem.variables.keys() {
        columns.insert(*name_id, Vec::new());
    }

    if let Some(obj) = objective {
        for coeff in &obj.coefficients {
            debug_assert!(problem.variables.contains_key(&coeff.name), "objective coefficient must reference a registered variable");
            columns.entry(coeff.name).or_default().push((obj_row_name, coeff.value));
        }
    }

    for (constraint_id, constraint) in &problem.constraints {
        if range_pairs.skip.contains(constraint_id) {
            continue; // The base row already carries these coefficients.
        }
        if let Constraint::Standard { name, coefficients, .. } = constraint {
            let row_name = problem.resolve(*name);
            for coeff in coefficients {
                debug_assert!(problem.variables.contains_key(&coeff.name), "constraint coefficient must reference a registered variable");
                columns.entry(coeff.name).or_default().push((row_name, coeff.value));
            }
        }
    }

    for (name_id, variable) in &problem.variables {
        if needs_marker(&variable.var_type) {
            let entries = columns.entry(*name_id).or_default();
            if entries.is_empty() {
                entries.push((obj_row_name, 0.0));
            }
        }
    }

    columns
}

/// Write the `COLUMNS` section, wrapping integer/general/binary variables in
/// `'MARKER'` `INTORG`/`INTEND` blocks.
fn write_columns_section(
    output: &mut String,
    problem: &LpProblem,
    columns: &ColumnEntries<'_>,
    options: &MpsWriterOptions,
) -> std::fmt::Result {
    writeln!(output, "COLUMNS")?;

    for (name_id, variable) in &problem.variables {
        let entries = columns.get(name_id).map_or([].as_slice(), Vec::as_slice);
        if entries.is_empty() {
            // No row references this variable and it doesn't need a marker
            // block: nothing to emit (it is still registered via BOUNDS).
            continue;
        }

        let var_name = problem.resolve(*name_id);
        let wrap = needs_marker(&variable.var_type);

        if wrap {
            writeln!(output, "    MARKER                 'MARKER'                 'INTORG'")?;
        }
        for &(row_name, value) in entries {
            write!(output, "    {var_name:<10} {row_name:<10} ")?;
            write_number(output, value, options.decimal_precision)?;
            writeln!(output)?;
        }
        if wrap {
            writeln!(output, "    MARKER                 'MARKER'                 'INTEND'")?;
        }
    }

    Ok(())
}

/// Write the `RHS` section. Zero-valued RHS entries are omitted -- the reader
/// already defaults missing rows to an RHS of zero. Ranged companion rows are
/// omitted (their upper RHS is carried by the `RANGES` section). An objective
/// constant is written as a negated RHS entry on the objective row, per the
/// CPLEX MPS specification.
fn write_rhs_section(
    output: &mut String,
    problem: &LpProblem,
    objective: Option<&Objective>,
    obj_row_name: &str,
    options: &MpsWriterOptions,
    range_pairs: &RangePairs,
) -> std::fmt::Result {
    debug_assert!(!obj_row_name.is_empty(), "obj_row_name must not be empty");
    writeln!(output, "RHS")?;

    if let Some(obj) = objective {
        if obj.constant != 0.0 {
            write!(output, "    {RHS_VECTOR_LABEL:<10} {obj_row_name:<10} ")?;
            write_number(output, -obj.constant, options.decimal_precision)?;
            writeln!(output)?;
        }
    }

    for (constraint_id, constraint) in &problem.constraints {
        if range_pairs.skip.contains(constraint_id) {
            continue;
        }
        if let Constraint::Standard { name, rhs, .. } = constraint {
            if *rhs == 0.0 {
                continue;
            }
            let resolved_name = problem.resolve(*name);
            write!(output, "    {RHS_VECTOR_LABEL:<10} {resolved_name:<10} ")?;
            write_number(output, *rhs, options.decimal_precision)?;
            writeln!(output)?;
        }
    }

    Ok(())
}

/// Fixed vector label written in the RANGES section, analogous to
/// [`RHS_VECTOR_LABEL`].
const RANGES_VECTOR_LABEL: &str = "RNG";

/// Write the `RANGES` section for detected constraint pairs (see
/// [`RangePairs`]). Omitted entirely when there are no pairs.
fn write_ranges_section(
    output: &mut String,
    problem: &LpProblem,
    options: &MpsWriterOptions,
    range_pairs: &RangePairs,
) -> std::fmt::Result {
    if range_pairs.ranges.is_empty() {
        return Ok(());
    }
    writeln!(output, "RANGES")?;

    // Iterate constraints (not the hash map) for deterministic output order.
    for constraint_id in problem.constraints.keys() {
        if let Some(range_value) = range_pairs.ranges.get(constraint_id) {
            let resolved_name = problem.resolve(*constraint_id);
            write!(output, "    {RANGES_VECTOR_LABEL:<10} {resolved_name:<10} ")?;
            write_number(output, *range_value, options.decimal_precision)?;
            writeln!(output)?;
        }
    }

    Ok(())
}

/// Write a single BOUNDS line with a numeric value.
fn write_bound_value(output: &mut String, bound_type: &str, var_name: &str, value: f64, precision: usize) -> std::fmt::Result {
    write!(output, " {bound_type} {BOUNDS_VECTOR_LABEL:<9} {var_name:<10} ")?;
    write_number(output, value, precision)?;
    writeln!(output)
}

/// Write a single BOUNDS line without a numeric value (`FR`, `BV`).
fn write_bound_flag(output: &mut String, bound_type: &str, var_name: &str) -> std::fmt::Result {
    writeln!(output, " {bound_type} {BOUNDS_VECTOR_LABEL:<9} {var_name}")
}

/// Build the validation error returned for a bound value that MPS cannot
/// represent (`NaN`, or an infinite value on the "wrong" side of a bound
/// that MPS has no flag for).
fn invalid_bound_error(var_name: &str, message: &str) -> LpParseError {
    LpParseError::validation_error(format!("variable '{var_name}' {message}"))
}

/// Write the bound line(s) for a single variable's [`VariableType`].
///
/// See the module documentation for the `Integer`/`General`/`SemiContinuous`
/// mapping caveats, and for the `Free`-default conversion caveat.
///
/// # Errors
///
/// Returns an error if a bound value is `NaN`, or is an infinite value MPS
/// has no flag for (e.g. `UpperBound(-inf)`, `LowerBound(+inf)`) -- see
/// [`write_upper_bound`], [`write_lower_bound`] and [`write_double_bound`].
fn write_variable_bound(output: &mut String, var_name: &str, var_type: &VariableType, precision: usize) -> LpResult<()> {
    match *var_type {
        VariableType::Free => {
            write_bound_flag(output, "FR", var_name).expect("fmt::Write to String is infallible");
            Ok(())
        }
        VariableType::LowerBound(lb) => write_lower_bound(output, var_name, lb, precision),
        VariableType::UpperBound(ub) => write_upper_bound(output, var_name, ub, precision),
        VariableType::DoubleBound(lb, ub) => write_double_bound(output, var_name, lb, ub, precision),
        VariableType::Binary => {
            write_bound_flag(output, "BV", var_name).expect("fmt::Write to String is infallible");
            Ok(())
        }
        // General has no MPS analogue: both collapse to an integer column
        // with an explicit LO 0 (see module docs).
        VariableType::Integer | VariableType::General => {
            write_bound_value(output, "LO", var_name, 0.0, precision).expect("fmt::Write to String is infallible");
            Ok(())
        }
        VariableType::SemiContinuous => {
            write_bound_value(output, "SC", var_name, SEMI_CONTINUOUS_SENTINEL_UPPER, precision)
                .expect("fmt::Write to String is infallible");
            Ok(())
        }
        // SOS-membership is not an explicit bound; leave the MPS default
        // ([0, +inf)) in place, matching the LP writer's treatment.
        VariableType::SOS => Ok(()),
    }
}

/// Write the bound line for a `LowerBound(lb)` variable.
///
/// The MPS reader maps a bare `MI`-only bound to `LowerBound(-inf)`, so that
/// case is written back as `MI` rather than fed to [`write_number`] (which
/// requires a finite value).
///
/// # Errors
///
/// Returns an error if `lb` is `NaN`, or `+inf` (a lower bound of `+inf` is
/// nonsensical -- it would leave the variable with an empty feasible region
/// unless the upper bound is also `+inf`, which is not representable as a
/// plain `LowerBound`).
fn write_lower_bound(output: &mut String, var_name: &str, lb: f64, precision: usize) -> LpResult<()> {
    if lb.is_nan() {
        return Err(invalid_bound_error(var_name, "has a NaN lower bound, which MPS cannot represent"));
    }
    if lb == f64::INFINITY {
        return Err(invalid_bound_error(var_name, "has a lower bound of +inf, which MPS cannot represent"));
    }
    if lb == f64::NEG_INFINITY {
        write_bound_flag(output, "MI", var_name).expect("fmt::Write to String is infallible");
        return Ok(());
    }
    write_bound_value(output, "LO", var_name, lb, precision).expect("fmt::Write to String is infallible");
    Ok(())
}

/// Write the bound line for an `UpperBound(ub)` variable.
///
/// When `ub` is negative, an explicit `LO 0` is written first. Per the MPS
/// (CPLEX) convention implemented by the reader, a bare `UP` with a negative
/// value and no preceding `LO` implies a lower bound of `-inf`, not the `0`
/// that `UpperBound` means in this model -- without the explicit `LO 0` the
/// round trip would silently widen the feasible region.
///
/// The MPS reader maps a bare `PL`-only bound to `UpperBound(+inf)`, so that
/// case is written back as `PL` rather than fed to [`write_number`] (which
/// requires a finite value).
///
/// # Errors
///
/// Returns an error if `ub` is `NaN`, or `-inf` (an upper bound of `-inf` is
/// nonsensical -- it would leave the variable with an empty feasible region
/// unless the lower bound is also `-inf`, which is not representable as a
/// plain `UpperBound`).
fn write_upper_bound(output: &mut String, var_name: &str, ub: f64, precision: usize) -> LpResult<()> {
    if ub.is_nan() {
        return Err(invalid_bound_error(var_name, "has a NaN upper bound, which MPS cannot represent"));
    }
    if ub == f64::NEG_INFINITY {
        return Err(invalid_bound_error(var_name, "has an upper bound of -inf, which MPS cannot represent"));
    }
    if ub == f64::INFINITY {
        write_bound_flag(output, "PL", var_name).expect("fmt::Write to String is infallible");
        return Ok(());
    }
    if ub < 0.0 {
        write_bound_value(output, "LO", var_name, 0.0, precision).expect("fmt::Write to String is infallible");
    }
    write_bound_value(output, "UP", var_name, ub, precision).expect("fmt::Write to String is infallible");
    Ok(())
}

/// Write the bound line(s) for a `DoubleBound(lb, ub)` variable, collapsing
/// to `FX`/`FR`/`MI`/`LO`+`PL` where the general two-line `LO`+`UP` form is
/// unnecessary.
///
/// A finite lower bound paired with an infinite upper bound is written as
/// `LO` + an explicit `PL` (rather than just `LO` alone): `PL` sets the
/// accumulated upper bound to `+inf` on read-back, so the pair round-trips
/// as `DoubleBound(lb, +inf)` again. Omitting `PL` would leave the upper
/// bound unset, and the reader would collapse the result to a plain
/// `LowerBound(lb)` -- semantically identical, but a different variant.
///
/// # Errors
///
/// Returns an error if either bound is `NaN`, or if `lb` is `+inf` or `ub`
/// is `-inf` (nonsensical combinations that MPS's `FR`/`MI`/`PL` flags
/// cannot represent).
fn write_double_bound(output: &mut String, var_name: &str, lb: f64, ub: f64, precision: usize) -> LpResult<()> {
    if lb.is_nan() || ub.is_nan() {
        return Err(invalid_bound_error(var_name, "has a NaN double bound, which MPS cannot represent"));
    }
    if lb == f64::INFINITY || ub == f64::NEG_INFINITY {
        return Err(invalid_bound_error(var_name, &format!("has a nonsensical double bound ({lb}, {ub}), which MPS cannot represent")));
    }

    #[allow(clippy::float_cmp)]
    if lb == ub {
        write_bound_value(output, "FX", var_name, lb, precision).expect("fmt::Write to String is infallible");
        return Ok(());
    }
    match (lb.is_infinite() && lb < 0.0, ub.is_infinite() && ub > 0.0) {
        (true, true) => write_bound_flag(output, "FR", var_name).expect("fmt::Write to String is infallible"),
        (true, false) => {
            write_bound_flag(output, "MI", var_name).expect("fmt::Write to String is infallible");
            write_bound_value(output, "UP", var_name, ub, precision).expect("fmt::Write to String is infallible");
        }
        (false, true) => {
            write_bound_value(output, "LO", var_name, lb, precision).expect("fmt::Write to String is infallible");
            write_bound_flag(output, "PL", var_name).expect("fmt::Write to String is infallible");
        }
        (false, false) => {
            write_bound_value(output, "LO", var_name, lb, precision).expect("fmt::Write to String is infallible");
            write_bound_value(output, "UP", var_name, ub, precision).expect("fmt::Write to String is infallible");
        }
    }
    Ok(())
}

/// Write the `BOUNDS` section, one entry per variable (in declaration order).
///
/// # Errors
///
/// See [`write_variable_bound`].
fn write_bounds_section(output: &mut String, problem: &LpProblem, options: &MpsWriterOptions) -> LpResult<()> {
    if problem.variables.is_empty() {
        return Ok(());
    }

    writeln!(output, "BOUNDS").expect("fmt::Write to String is infallible");
    for (name_id, variable) in &problem.variables {
        let var_name = problem.resolve(*name_id);
        write_variable_bound(output, var_name, &variable.var_type, options.decimal_precision)?;
    }

    Ok(())
}

/// Write the `SOS` section, if the problem has any SOS constraints.
fn write_sos_section(output: &mut String, problem: &LpProblem, options: &MpsWriterOptions) -> std::fmt::Result {
    let has_sos = problem.constraints.values().any(|c| matches!(c, Constraint::SOS { .. }));
    if !has_sos {
        return Ok(());
    }

    writeln!(output, "SOS")?;
    for constraint in problem.constraints.values() {
        if let Constraint::SOS { name, sos_type, weights, .. } = constraint {
            writeln!(output, " {sos_type} {}", problem.resolve(*name))?;
            for weight in weights {
                write!(output, "    {:<10} ", problem.resolve(weight.name))?;
                write_number(output, weight.value, options.decimal_precision)?;
                writeln!(output)?;
            }
        }
    }

    Ok(())
}

#[cfg(test)]
// Coefficients/bounds must round-trip bit-exactly through the writer and
// reader, so these tests intentionally compare floats strictly.
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;
    use crate::model::{Coefficient, ComparisonOp, SOSType};
    use crate::mps::parse_mps;

    fn build_problem_with_bounds_and_sos() -> LpProblem {
        let mut problem = LpProblem::new().with_problem_name(String::from("Sample")).with_sense(Sense::Maximize);

        let profit_id = problem.intern("profit");
        let x1_id = problem.intern("x1");
        let x2_id = problem.intern("x2");
        let x3_id = problem.intern("x3");
        let capacity_id = problem.intern("capacity");
        let sos1_id = problem.intern("sos1");

        problem.add_objective(Objective {
            name: profit_id,
            coefficients: vec![
                Coefficient { name: x1_id, value: 3.0 },
                Coefficient { name: x2_id, value: 2.0 },
                Coefficient { name: x3_id, value: 1.0 },
            ],
            constant: 0.0,
            byte_offset: None,
        });

        problem.add_constraint(Constraint::Standard {
            name: capacity_id,
            coefficients: vec![
                Coefficient { name: x1_id, value: 1.0 },
                Coefficient { name: x2_id, value: 1.0 },
                Coefficient { name: x3_id, value: 1.0 },
            ],
            operator: ComparisonOp::LTE,
            rhs: 100.0,
            byte_offset: None,
        });

        problem.update_variable_type("x1", VariableType::Integer).unwrap();
        problem.update_variable_type("x2", VariableType::DoubleBound(0.0, 50.0)).unwrap();
        problem.update_variable_type("x3", VariableType::Binary).unwrap();

        problem.add_constraint(Constraint::SOS {
            name: sos1_id,
            sos_type: SOSType::S1,
            weights: vec![Coefficient { name: x1_id, value: 1.0 }, Coefficient { name: x2_id, value: 2.0 }],
            byte_offset: None,
        });

        problem
    }

    #[test]
    fn test_write_empty_problem() {
        let problem = LpProblem::new();
        let result = write_mps_string(&problem).unwrap();

        assert!(result.contains("NAME"));
        assert!(result.contains(&format!(" N  {EMPTY_OBJECTIVE_ROW_NAME}")));
        assert!(result.contains("ENDATA"));

        // Documented asymmetry: zero objectives in, one (empty) objective out.
        let reparsed = LpProblem::parse_mps(&result).unwrap();
        assert_eq!(reparsed.objective_count(), 1);
    }

    #[test]
    fn test_write_simple_problem_and_reparse() {
        let mut problem = LpProblem::new().with_problem_name(String::from("Test Problem")).with_sense(Sense::Maximize);

        let profit_id = problem.intern("profit");
        let x1_id = problem.intern("x1");
        let x2_id = problem.intern("x2");
        let capacity_id = problem.intern("capacity");

        problem.add_objective(Objective {
            name: profit_id,
            coefficients: vec![Coefficient { name: x1_id, value: 3.0 }, Coefficient { name: x2_id, value: 2.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.add_constraint(Constraint::Standard {
            name: capacity_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }, Coefficient { name: x2_id, value: 1.0 }],
            operator: ComparisonOp::LTE,
            rhs: 100.0,
            byte_offset: None,
        });

        let output = write_mps_string(&problem).unwrap();
        assert!(output.contains("OBJSENSE"));
        assert!(output.contains("MAX"));
        assert!(output.contains(" N  profit"));
        assert!(output.contains(" L  capacity"));

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        assert_eq!(reparsed.sense, Sense::Maximize);
        assert_eq!(reparsed.objective_count(), 1);
        assert_eq!(reparsed.constraint_count(), 1);
        assert_eq!(reparsed.variable_count(), 2);

        let capacity = reparsed.constraints.get(&reparsed.name_id("capacity").unwrap()).unwrap();
        if let Constraint::Standard { rhs, operator, .. } = capacity {
            assert_eq!(*rhs, 100.0);
            assert_eq!(*operator, ComparisonOp::LTE);
        } else {
            panic!("expected Standard constraint");
        }
    }

    #[test]
    fn test_write_bounds_and_integrality_round_trip() {
        let problem = build_problem_with_bounds_and_sos();
        let output = write_mps_string(&problem).unwrap();

        assert!(output.contains("MARKER"));
        assert!(output.contains("INTORG"));
        assert!(output.contains("INTEND"));
        assert!(output.contains("BV"));
        assert!(output.contains("SOS"));

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        assert_eq!(reparsed.variable_count(), 3);
        assert_eq!(reparsed.constraint_count(), 2); // 1 standard + 1 SOS

        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::Integer);

        let x2 = &reparsed.variables[&reparsed.name_id("x2").unwrap()];
        assert_eq!(x2.var_type, VariableType::DoubleBound(0.0, 50.0));

        let x3 = &reparsed.variables[&reparsed.name_id("x3").unwrap()];
        assert_eq!(x3.var_type, VariableType::Binary);

        let sos = reparsed.constraints.get(&reparsed.name_id("sos1").unwrap()).unwrap();
        if let Constraint::SOS { sos_type, weights, .. } = sos {
            assert_eq!(*sos_type, SOSType::S1);
            assert_eq!(weights.len(), 2);
        } else {
            panic!("expected SOS constraint");
        }
    }

    #[test]
    fn test_double_bound_infinite_upper_round_trips_as_double_bound() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::DoubleBound(5.5, f64::INFINITY)).unwrap();

        let output = write_mps_string(&problem).unwrap();
        assert!(output.contains("PL"));

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::DoubleBound(5.5, f64::INFINITY));
    }

    #[test]
    fn test_negative_upper_bound_keeps_zero_lower_bound() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::UpperBound(-5.0)).unwrap();

        let output = write_mps_string(&problem).unwrap();

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        // Documented variant collapse: same feasible region (lower 0), but
        // DoubleBound rather than UpperBound (see module docs).
        assert_eq!(x1.var_type, VariableType::DoubleBound(0.0, -5.0));
    }

    #[test]
    fn test_multiple_objectives_error_by_default() {
        let mut problem = LpProblem::new();
        let a = problem.intern("a");
        let b = problem.intern("b");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: a,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.add_objective(Objective {
            name: b,
            coefficients: vec![Coefficient { name: x1_id, value: 2.0 }],
            constant: 0.0,
            byte_offset: None,
        });

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn test_multiple_objectives_allowed_writes_first() {
        let mut problem = LpProblem::new();
        let a = problem.intern("a");
        let b = problem.intern("b");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: a,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.add_objective(Objective {
            name: b,
            coefficients: vec![Coefficient { name: x1_id, value: 2.0 }],
            constant: 0.0,
            byte_offset: None,
        });

        let options = MpsWriterOptions { allow_multiple_objectives: true, ..MpsWriterOptions::default() };
        let output = write_mps_string_with_options(&problem, &options).unwrap();

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        assert_eq!(reparsed.objective_count(), 1);
        assert!(reparsed.name_id("a").is_some());
    }

    #[test]
    fn test_strict_inequality_returns_error() {
        let mut problem = LpProblem::new();
        let x1_id = problem.intern("x1");
        let c1 = problem.intern("c1");
        problem.add_constraint(Constraint::Standard {
            name: c1,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            operator: ComparisonOp::LT,
            rhs: 5.0,
            byte_offset: None,
        });

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn test_isolated_integer_variable_registers_as_column() {
        // A general/integer variable with no coefficients anywhere must still
        // round-trip as Integer, not fall back to the MPS [0, 1] default.
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        problem.add_objective(Objective { name: obj_id, coefficients: vec![], constant: 0.0, byte_offset: None });
        let x1_id = problem.intern("x1");
        problem.add_variable(crate::model::Variable::new(x1_id).with_var_type(VariableType::General));

        let output = write_mps_string(&problem).unwrap();
        let reparsed = LpProblem::parse_mps(&output).unwrap();
        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::Integer);
    }

    #[test]
    fn test_ranges_round_trip() {
        // A RANGES row is flattened by the reader into `X` (>=) plus `X_rng`
        // (<=); the writer must fold the pair back into a single row with a
        // RANGES entry so the section survives MPS -> LpProblem -> MPS.
        let input = "\
NAME        rngtest
ROWS
 N  obj
 G  lim1
 L  lim2
COLUMNS
    x1        obj       1
    x1        lim1      1
    x1        lim2      2
RHS
    RHS       lim1      2
    RHS       lim2      10
RANGES
    RNG       lim1      4
    RNG       lim2      3
ENDATA
";
        let problem = LpProblem::parse_mps(input).unwrap();
        assert_eq!(problem.constraint_count(), 4, "two ranged rows must flatten into four constraints");

        let output = write_mps_string(&problem).unwrap();
        assert!(output.contains("RANGES"), "RANGES section must be re-emitted:\n{output}");
        assert!(!output.contains("lim1_rng"), "companion rows must fold back into the RANGES entry:\n{output}");

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        assert_eq!(reparsed.constraint_count(), problem.constraint_count());
        for (name, expected_op, expected_rhs) in [
            ("lim1", ComparisonOp::GTE, 2.0),
            ("lim1_rng", ComparisonOp::LTE, 6.0),
            ("lim2", ComparisonOp::GTE, 7.0),
            ("lim2_rng", ComparisonOp::LTE, 10.0),
        ] {
            let id = reparsed.name_id(name).unwrap_or_else(|| panic!("constraint '{name}' missing after round trip"));
            let Some(Constraint::Standard { operator, rhs, .. }) = reparsed.constraints.get(&id) else {
                panic!("constraint '{name}' must be a standard constraint");
            };
            assert_eq!(*operator, expected_op, "operator mismatch for '{name}'");
            assert_eq!(*rhs, expected_rhs, "rhs mismatch for '{name}'");
        }
    }

    #[test]
    fn test_user_authored_rng_suffix_not_merged_when_structurally_different() {
        // A user constraint that merely ends in `_rng` must NOT be folded into
        // a RANGES entry unless it exactly matches the reader's flattening
        // pattern (identical coefficients, >=/<= pairing, upper >= lower).
        let input = "\
Minimize
 obj: x + y
Subject To
 c1: x + y >= 1
 c1_rng: x + 2 y <= 5
End
";
        let problem = LpProblem::parse(input).unwrap();
        let output = write_mps_string(&problem).unwrap();
        assert!(!output.contains("RANGES"), "structurally different pair must not merge:\n{output}");
        assert!(output.contains("c1_rng"), "companion row must be written as an ordinary row:\n{output}");
    }

    #[test]
    fn test_semi_continuous_round_trips() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        problem.add_objective(Objective { name: obj_id, coefficients: vec![], constant: 0.0, byte_offset: None });
        let x1_id = problem.intern("x1");
        problem.add_variable(crate::model::Variable::new(x1_id).with_var_type(VariableType::SemiContinuous));

        let output = write_mps_string(&problem).unwrap();
        assert!(output.contains("SC"));

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::SemiContinuous);
    }

    #[test]
    fn pl_only_bound_round_trips_as_upper_bound_infinity() {
        // A `PL`-only bound (no `LO`) resolves to `UpperBound(+inf)` on
        // parse; the writer must emit it back as a bare `PL`, not feed
        // `+inf` to `write_number` (regression test for the panic/invalid
        // `UP BOUND x inf` output this used to produce).
        let input = "\
NAME        pltest
ROWS
 N  obj
 L  c1
COLUMNS
    x1        obj       1
    x1        c1        1
RHS
    RHS_V     c1        10
BOUNDS
 PL BOUND     x1
ENDATA
";
        let problem = LpProblem::parse_mps(input).unwrap();
        let x1 = &problem.variables[&problem.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::UpperBound(f64::INFINITY));

        let output = write_mps_string(&problem).unwrap();
        assert!(output.contains(" PL BOUND"));
        assert!(!output.contains("inf"), "must not leak a raw `inf` literal into the bounds line");

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::UpperBound(f64::INFINITY));
    }

    #[test]
    fn mi_only_bound_round_trips_as_lower_bound_negative_infinity() {
        // Mirror of the `PL`-only case: an `MI`-only bound resolves to
        // `LowerBound(-inf)` on parse and must be written back as a bare
        // `MI`.
        let input = "\
NAME        mitest
ROWS
 N  obj
 L  c1
COLUMNS
    x1        obj       1
    x1        c1        1
RHS
    RHS_V     c1        10
BOUNDS
 MI BOUND     x1
ENDATA
";
        let problem = LpProblem::parse_mps(input).unwrap();
        let x1 = &problem.variables[&problem.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::LowerBound(f64::NEG_INFINITY));

        let output = write_mps_string(&problem).unwrap();
        assert!(output.contains(" MI BOUND"));
        assert!(!output.contains("inf"), "must not leak a raw `inf` literal into the bounds line");

        let reparsed = LpProblem::parse_mps(&output).unwrap();
        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::LowerBound(f64::NEG_INFINITY));
    }

    #[test]
    fn nan_upper_bound_returns_validation_error() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::UpperBound(f64::NAN)).unwrap();

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn nan_lower_bound_returns_validation_error() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::LowerBound(f64::NAN)).unwrap();

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn nonsensical_upper_bound_negative_infinity_returns_validation_error() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::UpperBound(f64::NEG_INFINITY)).unwrap();

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn nonsensical_lower_bound_positive_infinity_returns_validation_error() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::LowerBound(f64::INFINITY)).unwrap();

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn nan_double_bound_returns_validation_error() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        problem.update_variable_type("x1", VariableType::DoubleBound(f64::NAN, 5.0)).unwrap();

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn nonsensical_double_bound_returns_validation_error() {
        let mut problem = LpProblem::new();
        let obj_id = problem.intern("obj");
        let x1_id = problem.intern("x1");
        problem.add_objective(Objective {
            name: obj_id,
            coefficients: vec![Coefficient { name: x1_id, value: 1.0 }],
            constant: 0.0,
            byte_offset: None,
        });
        // Lower bound of +inf paired with a finite upper bound is an empty,
        // unrepresentable feasible region.
        problem.update_variable_type("x1", VariableType::DoubleBound(f64::INFINITY, 5.0)).unwrap();

        let err = write_mps_string(&problem).unwrap_err();
        assert!(matches!(err, LpParseError::ValidationError { .. }));
    }

    #[test]
    fn mps_round_trip_preserves_mps_fixture() {
        let input = "\
NAME        test
ROWS
 N  obj
 L  c1
 G  c2
 E  c3
COLUMNS
    x1        obj       1
    x1        c1        2
    x1        c2        1
    x1        c3        1
    x2        obj       2
    x2        c1        1
RHS
    RHS_V     c1        10
    RHS_V     c2        1
    RHS_V     c3        4
BOUNDS
 LO BOUND     x1        0
 UP BOUND     x1        20
ENDATA
";
        let original = parse_mps(input).unwrap();
        let problem = LpProblem::parse_mps(input).unwrap();
        let output = write_mps_string(&problem).unwrap();
        let reparsed = LpProblem::parse_mps(&output).unwrap();

        assert_eq!(reparsed.variable_count(), problem.variable_count());
        assert_eq!(reparsed.constraint_count(), problem.constraint_count());
        assert_eq!(reparsed.objective_count(), problem.objective_count());
        assert_eq!(reparsed.sense, problem.sense);
        assert_eq!(original.constraints.len(), reparsed.constraint_count());

        let x1 = &reparsed.variables[&reparsed.name_id("x1").unwrap()];
        assert_eq!(x1.var_type, VariableType::DoubleBound(0.0, 20.0));
    }

    #[test]
    fn snapshot_representative_problem() {
        let problem = build_problem_with_bounds_and_sos();
        let output = write_mps_string(&problem).unwrap();
        insta::assert_snapshot!(output);
    }
}