ommx 3.0.0-beta.1

Open Mathematical prograMming eXchange (OMMX)
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
use super::*;
use crate::constraint_type::ConstraintCollection;

/// Builder for creating [`Instance`] with validation.
///
/// This builder allows constructing an `Instance` step by step,
/// with optional fields that can be set before calling `build()`.
///
/// # Example
/// ```
/// use ommx::{Instance, Sense, Function};
/// use std::collections::BTreeMap;
///
/// let instance = Instance::builder()
///     .sense(Sense::Minimize)
///     .objective(Function::Zero)
///     .decision_variables(BTreeMap::new())
///     .constraints(BTreeMap::new())
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone, Default)]
pub struct InstanceBuilder {
    sense: Option<Sense>,
    objective: Option<Function>,
    decision_variables: Option<BTreeMap<VariableID, DecisionVariable>>,
    variable_labels: VariableLabelStore,
    fixed_decision_variable_values: BTreeMap<VariableID, f64>,
    constraints: Option<BTreeMap<ConstraintID, Constraint>>,
    constraint_context: ConstraintContextStore<ConstraintID>,
    named_functions: BTreeMap<NamedFunctionID, NamedFunction>,
    named_function_labels: crate::named_function::NamedFunctionLabelStore,
    removed_constraints: BTreeMap<ConstraintID, (Constraint, crate::constraint::RemovedReason)>,
    indicator_constraints: BTreeMap<crate::IndicatorConstraintID, crate::IndicatorConstraint>,
    indicator_constraint_context: ConstraintContextStore<crate::IndicatorConstraintID>,
    removed_indicator_constraints: BTreeMap<
        crate::IndicatorConstraintID,
        (crate::IndicatorConstraint, crate::constraint::RemovedReason),
    >,
    one_hot_constraints: BTreeMap<crate::OneHotConstraintID, crate::OneHotConstraint>,
    one_hot_constraint_context: ConstraintContextStore<crate::OneHotConstraintID>,
    sos1_constraints: BTreeMap<crate::Sos1ConstraintID, crate::Sos1Constraint>,
    sos1_constraint_context: ConstraintContextStore<crate::Sos1ConstraintID>,
    decision_variable_dependency: AcyclicAssignments,
    parameters: Option<v1::Parameters>,
    description: Option<v1::instance::Description>,
}

impl InstanceBuilder {
    /// Creates a new `InstanceBuilder` with all fields unset.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the optimization sense (minimize or maximize).
    pub fn sense(mut self, sense: Sense) -> Self {
        self.sense = Some(sense);
        self
    }

    /// Sets the objective function.
    pub fn objective(mut self, objective: Function) -> Self {
        self.objective = Some(objective);
        self
    }

    /// Sets the decision variables.
    pub fn decision_variables(
        mut self,
        decision_variables: BTreeMap<VariableID, DecisionVariable>,
    ) -> Self {
        self.decision_variables = Some(decision_variables);
        self
    }

    /// Sets the per-variable modeling labels.
    pub fn variable_labels(mut self, variable_labels: VariableLabelStore) -> Self {
        self.variable_labels = variable_labels;
        self
    }

    /// Sets table-owned fixed decision-variable values.
    pub fn fixed_decision_variable_values(
        mut self,
        fixed_decision_variable_values: BTreeMap<VariableID, f64>,
    ) -> Self {
        self.fixed_decision_variable_values = fixed_decision_variable_values;
        self
    }

    /// Sets the constraints.
    pub fn constraints(mut self, constraints: BTreeMap<ConstraintID, Constraint>) -> Self {
        self.constraints = Some(constraints);
        self
    }

    /// Sets the per-regular-constraint context.
    pub fn constraint_context(
        mut self,
        constraint_context: ConstraintContextStore<ConstraintID>,
    ) -> Self {
        self.constraint_context = constraint_context;
        self
    }

    /// Sets the named functions.
    pub fn named_functions(
        mut self,
        named_functions: BTreeMap<NamedFunctionID, NamedFunction>,
    ) -> Self {
        self.named_functions = named_functions;
        self
    }

    /// Sets the per-named-function modeling labels.
    pub fn named_function_labels(
        mut self,
        named_function_labels: crate::named_function::NamedFunctionLabelStore,
    ) -> Self {
        self.named_function_labels = named_function_labels;
        self
    }

    /// Sets the removed constraints.
    pub fn removed_constraints(
        mut self,
        removed_constraints: BTreeMap<ConstraintID, (Constraint, crate::constraint::RemovedReason)>,
    ) -> Self {
        self.removed_constraints = removed_constraints;
        self
    }

    /// Sets the indicator constraints.
    pub fn indicator_constraints(
        mut self,
        indicator_constraints: BTreeMap<crate::IndicatorConstraintID, crate::IndicatorConstraint>,
    ) -> Self {
        self.indicator_constraints = indicator_constraints;
        self
    }

    /// Sets the per-indicator-constraint context.
    pub fn indicator_constraint_context(
        mut self,
        indicator_constraint_context: ConstraintContextStore<crate::IndicatorConstraintID>,
    ) -> Self {
        self.indicator_constraint_context = indicator_constraint_context;
        self
    }

    /// Sets the removed indicator constraints.
    pub fn removed_indicator_constraints(
        mut self,
        removed_indicator_constraints: BTreeMap<
            crate::IndicatorConstraintID,
            (crate::IndicatorConstraint, crate::constraint::RemovedReason),
        >,
    ) -> Self {
        self.removed_indicator_constraints = removed_indicator_constraints;
        self
    }

    /// Sets the one-hot constraints.
    pub fn one_hot_constraints(
        mut self,
        one_hot_constraints: BTreeMap<crate::OneHotConstraintID, crate::OneHotConstraint>,
    ) -> Self {
        self.one_hot_constraints = one_hot_constraints;
        self
    }

    /// Sets the per-one-hot-constraint context.
    pub fn one_hot_constraint_context(
        mut self,
        one_hot_constraint_context: ConstraintContextStore<crate::OneHotConstraintID>,
    ) -> Self {
        self.one_hot_constraint_context = one_hot_constraint_context;
        self
    }

    /// Sets the SOS1 constraints.
    pub fn sos1_constraints(
        mut self,
        sos1_constraints: BTreeMap<crate::Sos1ConstraintID, crate::Sos1Constraint>,
    ) -> Self {
        self.sos1_constraints = sos1_constraints;
        self
    }

    /// Sets the per-SOS1-constraint context.
    pub fn sos1_constraint_context(
        mut self,
        sos1_constraint_context: ConstraintContextStore<crate::Sos1ConstraintID>,
    ) -> Self {
        self.sos1_constraint_context = sos1_constraint_context;
        self
    }

    /// Sets the decision variable dependency.
    pub fn decision_variable_dependency(
        mut self,
        decision_variable_dependency: AcyclicAssignments,
    ) -> Self {
        self.decision_variable_dependency = decision_variable_dependency;
        self
    }

    /// Sets the parameters.
    pub fn parameters(mut self, parameters: v1::Parameters) -> Self {
        self.parameters = Some(parameters);
        self
    }

    /// Sets the description.
    pub fn description(mut self, description: v1::instance::Description) -> Self {
        self.description = Some(description);
        self
    }

    /// Builds the `Instance` with validation.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Required fields (`sense`, `objective`, `decision_variables`, `constraints`) are not set
    /// - Named-function labels reference IDs not present in the named-function table
    /// - The objective function, constraints, or named functions reference undefined variable IDs
    /// - The keys of `constraints` and `removed_constraints` are not disjoint
    /// - Label/context stores contain IDs that are not owned by the
    ///   corresponding decision-variable, named-function, or constraint collection
    /// - The keys of `decision_variable_dependency` are not in `decision_variables`
    /// - Construction-time `used`, `fixed`, and `dependent` sets are not pairwise disjoint
    pub fn build(self) -> crate::Result<Instance> {
        let sense = self
            .sense
            .ok_or_else(|| crate::error!("Required field is missing: sense"))?;
        let objective = self
            .objective
            .ok_or_else(|| crate::error!("Required field is missing: objective"))?;
        let decision_variables = self
            .decision_variables
            .ok_or_else(|| crate::error!("Required field is missing: decision_variables"))?;
        let constraints = self
            .constraints
            .ok_or_else(|| crate::error!("Required field is missing: constraints"))?;

        let decision_variables = DecisionVariableTable::with_fixed_values(
            decision_variables,
            self.variable_labels,
            self.fixed_decision_variable_values,
            crate::ATol::default(),
        )?;

        // Collect all variable IDs for host-level validation.
        let variable_ids: VariableIDSet = decision_variables.keys().cloned().collect();

        // Validate that all variable IDs in objective and constraints are defined
        for id in objective.required_ids() {
            if !variable_ids.contains(&id) {
                crate::bail!({ ?id }, "Undefined variable ID is used: {id:?}");
            }
        }
        for constraint in constraints.values() {
            for id in constraint.required_ids() {
                if !variable_ids.contains(&id) {
                    crate::bail!({ ?id }, "Undefined variable ID is used: {id:?}");
                }
            }
        }
        // Validate that all variable IDs in removed_constraints are defined
        // (removed_constraints may contain fixed or dependent variable IDs)
        for (constraint, _reason) in self.removed_constraints.values() {
            for id in constraint.required_ids() {
                if !variable_ids.contains(&id) {
                    crate::bail!({ ?id }, "Undefined variable ID is used: {id:?}");
                }
            }
        }

        // Validate named_functions: map keys own IDs, and all referenced variable IDs must exist.
        for nf in self.named_functions.values() {
            for id in nf.function.required_ids() {
                if !variable_ids.contains(&id) {
                    crate::bail!({ ?id }, "Undefined variable ID is used: {id:?}");
                }
            }
        }
        let named_functions =
            NamedFunctionTable::new(self.named_functions, self.named_function_labels)?;

        // Validate indicator constraints
        for value in self.indicator_constraints.values() {
            // Check that indicator_variable exists and is binary
            let indicator_id = value.indicator_variable;
            let Some(dv) = decision_variables.get(&indicator_id) else {
                crate::bail!(
                    { ?indicator_id },
                    "Indicator variable {indicator_id:?} is not defined in decision_variables",
                );
            };
            if dv.kind() != crate::decision_variable::Kind::Binary {
                crate::bail!(
                    { ?indicator_id },
                    "Indicator variable {indicator_id:?} must be binary",
                );
            }
            // Check that all variable IDs in function are defined
            for id in value.required_ids() {
                if !variable_ids.contains(&id) {
                    crate::bail!({ ?id }, "Undefined variable ID is used: {id:?}");
                }
            }
        }
        for (ic, _reason) in self.removed_indicator_constraints.values() {
            // Check that indicator_variable exists and is binary
            let indicator_id = ic.indicator_variable;
            let Some(dv) = decision_variables.get(&indicator_id) else {
                crate::bail!(
                    { ?indicator_id },
                    "Indicator variable {indicator_id:?} is not defined in decision_variables",
                );
            };
            if dv.kind() != crate::decision_variable::Kind::Binary {
                crate::bail!(
                    { ?indicator_id },
                    "Indicator variable {indicator_id:?} must be binary",
                );
            }
            for id in ic.required_ids() {
                if !variable_ids.contains(&id) {
                    crate::bail!({ ?id }, "Undefined variable ID is used: {id:?}");
                }
            }
        }
        // Validate disjointness of indicator active/removed
        for id in self.removed_indicator_constraints.keys() {
            if self.indicator_constraints.contains_key(id) {
                crate::bail!(
                    { ?id },
                    "Indicator constraint ID {id:?} is in both indicator_constraints and removed_indicator_constraints, but they must be disjoint",
                );
            }
        }

        // Validate one-hot constraints
        for (id, value) in &self.one_hot_constraints {
            if value.variables.is_empty() {
                crate::bail!(
                    { ?id },
                    "One-hot constraint {id:?} has no variables; one-hot constraints must contain at least one variable",
                );
            }
            for var_id in &value.variables {
                let Some(dv) = decision_variables.get(var_id) else {
                    crate::bail!(
                        { ?var_id },
                        "One-hot variable {var_id:?} is not defined in decision_variables",
                    );
                };
                if dv.kind() != crate::decision_variable::Kind::Binary {
                    crate::bail!({ ?var_id }, "One-hot variable {var_id:?} must be binary");
                }
            }
        }

        // Validate SOS1 constraints
        for (id, value) in &self.sos1_constraints {
            if value.variables.is_empty() {
                crate::bail!(
                    { ?id },
                    "SOS1 constraint {id:?} has no variables; SOS1 constraints must contain at least one variable",
                );
            }
            for var_id in &value.variables {
                if !variable_ids.contains(var_id) {
                    crate::bail!(
                        { ?var_id },
                        "SOS1 variable {var_id:?} is not defined in decision_variables",
                    );
                }
            }
        }

        // Validate that constraints and removed_constraints keys are disjoint
        for id in self.removed_constraints.keys() {
            if constraints.contains_key(id) {
                crate::bail!(
                    { ?id },
                    "Constraint ID {id:?} is in both constraints and removed_constraints, but they must be disjoint",
                );
            }
        }

        // Validate that decision_variable_dependency keys are in decision_variables
        // (dependent variables must exist as decision variables to get kind/bound info)
        for id in self.decision_variable_dependency.keys() {
            if !variable_ids.contains(&id) {
                crate::bail!(
                    { ?id },
                    "Variable ID {id:?} in decision_variable_dependency is not in decision_variables",
                );
            }
        }

        // Construction invariant: raw used, fixed, and dependent sets must be pairwise disjoint.
        // - used: IDs appearing in objective or constraints
        // - fixed: IDs in the decision-variable table's fixed-value column
        // - dependent: keys of decision_variable_dependency
        let mut used: VariableIDSet = objective.required_ids().into_iter().collect();
        for constraint in constraints.values() {
            used.extend(constraint.required_ids());
        }
        for ic in self.indicator_constraints.values() {
            used.extend(ic.required_ids());
        }
        for oh in self.one_hot_constraints.values() {
            used.extend(oh.required_ids());
        }
        for sos1 in self.sos1_constraints.values() {
            used.extend(sos1.required_ids());
        }
        let fixed: VariableIDSet = decision_variables.fixed_values().keys().copied().collect();
        let dependent: VariableIDSet = self.decision_variable_dependency.keys().collect();

        // Check used ∩ dependent = ∅
        if let Some(id) = used.intersection(&dependent).next() {
            crate::bail!(
                { ?id },
                "Dependent variable cannot be used in objectives or constraints: {id:?}",
            );
        }

        // Check used ∩ fixed = ∅
        if let Some(id) = used.intersection(&fixed).next() {
            crate::bail!(
                { ?id },
                "Fixed variable {id:?} cannot be used in objectives or constraints",
            );
        }

        // Check fixed ∩ dependent = ∅
        if let Some(id) = fixed.intersection(&dependent).next() {
            crate::bail!(
                { ?id },
                "Variable {id:?} cannot be both fixed and dependent",
            );
        }

        Ok(Instance {
            sense,
            objective,
            decision_variables,
            constraint_collection: ConstraintCollection::with_context(
                constraints,
                self.removed_constraints,
                self.constraint_context,
            )?,
            indicator_constraint_collection: ConstraintCollection::with_context(
                self.indicator_constraints,
                self.removed_indicator_constraints,
                self.indicator_constraint_context,
            )?,
            one_hot_constraint_collection: ConstraintCollection::with_context(
                self.one_hot_constraints,
                BTreeMap::new(),
                self.one_hot_constraint_context,
            )?,
            sos1_constraint_collection: ConstraintCollection::with_context(
                self.sos1_constraints,
                BTreeMap::new(),
                self.sos1_constraint_context,
            )?,
            named_functions,
            decision_variable_dependency: self.decision_variable_dependency,
            parameters: self.parameters,
            description: self.description,
            annotations: Default::default(),
        })
    }
}

impl Instance {
    /// Creates a new `InstanceBuilder`.
    pub fn builder() -> InstanceBuilder {
        InstanceBuilder::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{coeff, linear};
    use std::collections::BTreeSet;

    #[test]
    fn test_builder_basic() {
        let instance = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .build()
            .unwrap();

        assert_eq!(instance.sense(), Sense::Minimize);
        assert!(instance.decision_variables().is_empty());
        assert!(instance.constraints().is_empty());
    }

    #[test]
    fn test_builder_missing_required_field() {
        // Missing sense
        let err = Instance::builder()
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .build()
            .unwrap_err();
        assert!(
            err.to_string().contains("missing: sense"),
            "unexpected error: {err}"
        );

        // Missing objective
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .build()
            .unwrap_err();
        assert!(
            err.to_string().contains("missing: objective"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_builder_with_optional_fields() {
        let params = v1::Parameters::default();
        let desc = v1::instance::Description::default();

        let instance = Instance::builder()
            .sense(Sense::Maximize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .parameters(params.clone())
            .description(desc.clone())
            .build()
            .unwrap();

        assert_eq!(instance.sense(), Sense::Maximize);
        assert!(instance.parameters.is_some());
        assert!(instance.description.is_some());
    }

    #[test]
    fn test_builder_preserves_labels_and_context() {
        let var_id = VariableID::from(1);
        let constraint_id = ConstraintID::from(2);
        let mut variable_labels = VariableLabelStore::default();
        variable_labels.set_name(var_id, "x");
        variable_labels.set_subscripts(var_id, vec![0]);
        let mut constraint_context = ConstraintContextStore::default();
        constraint_context.set_name(constraint_id, "balance");

        let instance = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::from([(var_id, DecisionVariable::binary())]))
            .variable_labels(variable_labels)
            .constraints(BTreeMap::from([(
                constraint_id,
                Constraint::equal_to_zero(Function::Zero),
            )]))
            .constraint_context(constraint_context)
            .build()
            .unwrap();

        assert_eq!(instance.variable_labels().name(var_id), Some("x"));
        assert_eq!(instance.variable_labels().subscripts(var_id), &[0]);
        assert_eq!(
            instance.constraint_context().name(constraint_id),
            Some("balance")
        );
    }

    #[test]
    fn test_builder_preserves_special_constraint_contexts() {
        let var_id = VariableID::from(1);
        let indicator_id = crate::IndicatorConstraintID::from(10);
        let one_hot_id = crate::OneHotConstraintID::from(11);
        let sos1_id = crate::Sos1ConstraintID::from(12);

        let mut indicator_context = ConstraintContextStore::default();
        indicator_context.set_name(indicator_id, "activation");
        let mut one_hot_context = ConstraintContextStore::default();
        one_hot_context.set_name(one_hot_id, "choice");
        let mut sos1_context = ConstraintContextStore::default();
        sos1_context.set_name(sos1_id, "exclusive");

        let instance = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::from([(var_id, DecisionVariable::binary())]))
            .constraints(BTreeMap::new())
            .indicator_constraints(BTreeMap::from([(
                indicator_id,
                crate::IndicatorConstraint::new(
                    var_id,
                    crate::Equality::LessThanOrEqualToZero,
                    Function::Zero,
                ),
            )]))
            .indicator_constraint_context(indicator_context)
            .one_hot_constraints(BTreeMap::from([(
                one_hot_id,
                crate::OneHotConstraint::new(BTreeSet::from([var_id])).unwrap(),
            )]))
            .one_hot_constraint_context(one_hot_context)
            .sos1_constraints(BTreeMap::from([(
                sos1_id,
                crate::Sos1Constraint::new(BTreeSet::from([var_id])).unwrap(),
            )]))
            .sos1_constraint_context(sos1_context)
            .build()
            .unwrap();

        assert_eq!(
            instance.indicator_constraint_context().name(indicator_id),
            Some("activation")
        );
        assert_eq!(
            instance.one_hot_constraint_context().name(one_hot_id),
            Some("choice")
        );
        assert_eq!(
            instance.sos1_constraint_context().name(sos1_id),
            Some("exclusive")
        );
    }

    #[test]
    fn test_builder_rejects_orphan_variable_labels() {
        let mut variable_labels = VariableLabelStore::default();
        variable_labels.set_name(VariableID::from(99), "orphan");

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .variable_labels(variable_labels)
            .constraints(BTreeMap::new())
            .build()
            .unwrap_err();

        assert!(
            err.to_string().contains("unknown decision variable ID")
                && err.to_string().contains("VariableID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_builder_rejects_orphan_named_function_labels() {
        let mut named_function_labels = crate::named_function::NamedFunctionLabelStore::default();
        named_function_labels.set_name(NamedFunctionID::from(99), "orphan");

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .named_function_labels(named_function_labels)
            .build()
            .unwrap_err();

        assert!(
            err.to_string().contains("unknown named function ID")
                && err.to_string().contains("NamedFunctionID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_builder_rejects_orphan_constraint_context() {
        let mut constraint_context = ConstraintContextStore::default();
        constraint_context.set_name(ConstraintID::from(99), "orphan");

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .constraint_context(constraint_context)
            .build()
            .unwrap_err();

        assert!(
            err.to_string().contains("unknown constraint ID")
                && err.to_string().contains("ConstraintID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_builder_rejects_orphan_special_constraint_contexts() {
        let mut indicator_context = ConstraintContextStore::default();
        indicator_context.set_name(crate::IndicatorConstraintID::from(99), "orphan");
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .indicator_constraint_context(indicator_context)
            .build()
            .unwrap_err();
        assert!(
            err.to_string().contains("unknown constraint ID")
                && err.to_string().contains("IndicatorConstraintID(99)"),
            "unexpected error: {err}"
        );

        let mut one_hot_context = ConstraintContextStore::default();
        one_hot_context.set_name(crate::OneHotConstraintID::from(99), "orphan");
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .one_hot_constraint_context(one_hot_context)
            .build()
            .unwrap_err();
        assert!(
            err.to_string().contains("unknown constraint ID")
                && err.to_string().contains("OneHotConstraintID(99)"),
            "unexpected error: {err}"
        );

        let mut sos1_context = ConstraintContextStore::default();
        sos1_context.set_name(crate::Sos1ConstraintID::from(99), "orphan");
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .sos1_constraint_context(sos1_context)
            .build()
            .unwrap_err();
        assert!(
            err.to_string().contains("unknown constraint ID")
                && err.to_string().contains("Sos1ConstraintID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_sidecar_setters_reject_unknown_ids() {
        let mut instance = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .build()
            .unwrap();

        let err = instance
            .set_variable_label(VariableID::from(99), ModelingLabel::default())
            .unwrap_err();
        assert!(err.to_string().contains("unknown decision variable ID"));

        let err = instance
            .set_constraint_context(ConstraintID::from(99), ConstraintContext::default())
            .unwrap_err();
        assert!(err.to_string().contains("unknown constraint ID"));

        let err = instance
            .set_one_hot_constraint_context(
                crate::OneHotConstraintID::from(99),
                ConstraintContext::default(),
            )
            .unwrap_err();
        assert!(err.to_string().contains("unknown one-hot constraint ID"));
    }

    #[test]
    fn test_builder_undefined_variable_in_objective() {
        // Create objective function that uses undefined variable ID 999
        let objective = (linear!(999) + coeff!(1.0)).into();

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(objective)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("Undefined variable ID") && msg.contains("999"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_overlapping_constraint_ids() {
        use crate::Constraint;
        use maplit::btreemap;

        let constraint_id = ConstraintID::from(1);
        let constraint = Constraint::equal_to_zero(Function::Zero);
        let removed_constraint = Constraint::equal_to_zero(Function::Zero);
        let _ = constraint_id;
        let removed_reason = crate::constraint::RemovedReason {
            reason: "test".to_string(),
            parameters: Default::default(),
        };

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(btreemap! { constraint_id => constraint })
            .removed_constraints(
                btreemap! { constraint_id => (removed_constraint, removed_reason) },
            )
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("both constraints and removed_constraints")
                && msg.contains(&format!("{:?}", constraint_id)),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_rejects_empty_one_hot() {
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let empty_one_hot = crate::OneHotConstraint {
            variables: std::collections::BTreeSet::new(),
            stage: crate::OneHotCreatedData,
        };

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(btreemap! {
                var_id => DecisionVariable::binary(),
            })
            .constraints(BTreeMap::new())
            .one_hot_constraints(btreemap! {
                crate::OneHotConstraintID::from(42) => empty_one_hot,
            })
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("no variables") && msg.contains("42"),
            "expected empty one-hot error mentioning the id, got: {msg}"
        );
    }

    #[test]
    fn test_builder_undefined_variable_dependency() {
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let undefined_var_id = VariableID::from(999);
        let decision_variables = btreemap! {
            var_id => DecisionVariable::binary(),
        };

        // Create a dependency that references a variable not in decision_variables
        let dependency = AcyclicAssignments::new(btreemap! {
            undefined_var_id => Function::Zero,
        })
        .unwrap();

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(decision_variables)
            .constraints(BTreeMap::new())
            .decision_variable_dependency(dependency)
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("decision_variable_dependency is not in decision_variables")
                && msg.contains(&format!("{:?}", undefined_var_id)),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_valid_variable_dependency() {
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let decision_variables = btreemap! {
            var_id => DecisionVariable::binary(),
        };

        // Create a dependency for a variable that IS in decision_variables (this is valid)
        let dependency = AcyclicAssignments::new(btreemap! {
            var_id => Function::Zero,
        })
        .unwrap();

        // This should succeed because dependent variable must be in decision_variables
        // and is not used in objective/constraints
        let instance = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(decision_variables)
            .constraints(BTreeMap::new())
            .decision_variable_dependency(dependency)
            .build();

        assert!(instance.is_ok());
    }

    #[test]
    fn test_builder_dependent_variable_used_in_objective() {
        use crate::linear;
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let decision_variables = btreemap! {
            var_id => DecisionVariable::binary(),
        };

        // Create a dependency for var_id
        let dependency = AcyclicAssignments::new(btreemap! {
            var_id => Function::Zero,
        })
        .unwrap();

        // Objective uses var_id, which is also a dependent variable - this should fail
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::from(linear!(1)))
            .decision_variables(decision_variables)
            .constraints(BTreeMap::new())
            .decision_variable_dependency(dependency)
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("Dependent variable cannot be used")
                && msg.contains(&format!("{:?}", var_id)),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_dependent_variable_used_in_constraint() {
        use crate::linear;
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let constraint_id = ConstraintID::from(1);
        let decision_variables = btreemap! {
            var_id => DecisionVariable::binary(),
        };

        // Create a dependency for var_id
        let dependency = AcyclicAssignments::new(btreemap! {
            var_id => Function::Zero,
        })
        .unwrap();

        // Constraint uses var_id, which is also a dependent variable - this should fail
        let constraint = Constraint::equal_to_zero(Function::from(linear!(1)));
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(decision_variables)
            .constraints(btreemap! { constraint_id => constraint })
            .decision_variable_dependency(dependency)
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("Dependent variable cannot be used")
                && msg.contains(&format!("{:?}", var_id)),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_fixed_and_dependent_variable() {
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let dv = DecisionVariable::binary();
        let decision_variables = btreemap! {
            var_id => dv,
        };

        // Create a dependency for the same var_id (now both fixed and dependent)
        let dependency = AcyclicAssignments::new(btreemap! {
            var_id => Function::Zero,
        })
        .unwrap();

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(decision_variables)
            .fixed_decision_variable_values(btreemap! {
                var_id => 1.0,
            })
            .constraints(BTreeMap::new())
            .decision_variable_dependency(dependency)
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("cannot be both fixed") && msg.contains(&format!("{:?}", var_id)),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_undefined_variable_in_removed_constraint() {
        use maplit::btreemap;

        let constraint_id = ConstraintID::from(1);
        // Create a removed constraint that references undefined variable ID 999
        let removed_constraint =
            Constraint::equal_to_zero(Function::from(linear!(999) + coeff!(1.0)));
        let removed_reason = crate::constraint::RemovedReason {
            reason: "test".to_string(),
            parameters: Default::default(),
        };

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .removed_constraints(
                btreemap! { constraint_id => (removed_constraint, removed_reason) },
            )
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("Undefined variable ID") && msg.contains("999"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_fixed_variable_used_in_objective() {
        use maplit::btreemap;

        let var_id = VariableID::from(1);
        let dv = DecisionVariable::binary();
        let decision_variables = btreemap! {
            var_id => dv,
        };

        // Objective uses var_id, which is fixed - this should fail
        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::from(linear!(1)))
            .decision_variables(decision_variables)
            .fixed_decision_variable_values(btreemap! {
                var_id => 1.0,
            })
            .constraints(BTreeMap::new())
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("Fixed variable") && msg.contains(&format!("{:?}", var_id)),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_builder_undefined_variable_in_named_function() {
        use crate::{NamedFunction, NamedFunctionID};
        use maplit::btreemap;

        // Create a named function that references undefined variable ID 999
        let named_function = NamedFunction {
            function: Function::from(linear!(999) + coeff!(1.0)),
        };

        let err = Instance::builder()
            .sense(Sense::Minimize)
            .objective(Function::Zero)
            .decision_variables(BTreeMap::new())
            .constraints(BTreeMap::new())
            .named_functions(btreemap! {
                NamedFunctionID::from(1) => named_function,
            })
            .build()
            .unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("Undefined variable ID") && msg.contains("999"),
            "unexpected error: {msg}"
        );
    }
}