Skip to main content

lp_ip_craft/
model.rs

1//! The validated LP / mixed-integer LP model.
2
3use crate::error::{Result, ensure, ensure_finite};
4use crate::sparse::{Bounds, CsrMatrix};
5
6/// Direction of optimization. Objective values, bounds and duals are always
7/// reported in this original sense; there is no hidden sign change.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9pub enum Sense {
10    /// Minimize the objective.
11    #[default]
12    Minimize,
13    /// Maximize the objective.
14    Maximize,
15}
16
17impl Sense {
18    /// Stable lowercase name, as used by the Python binding.
19    pub fn as_str(self) -> &'static str {
20        match self {
21            Sense::Minimize => "minimize",
22            Sense::Maximize => "maximize",
23        }
24    }
25}
26
27/// Domain of a variable within its bounds.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum VariableKind {
30    /// Any real value.
31    #[default]
32    Continuous,
33    /// An integer value.
34    Integer,
35    /// An integer value with bounds inside `[0, 1]`.
36    Binary,
37}
38
39impl VariableKind {
40    /// Stable lowercase name, as used by the Python binding.
41    pub fn as_str(self) -> &'static str {
42        match self {
43            VariableKind::Continuous => "continuous",
44            VariableKind::Integer => "integer",
45            VariableKind::Binary => "binary",
46        }
47    }
48
49    /// Whether the variable must take an integer value.
50    pub fn is_integral(self) -> bool {
51        self != VariableKind::Continuous
52    }
53}
54
55/// The parts of a model, before validation. Turn it into a [`Model`] with
56/// [`Model::new`].
57///
58/// ```text
59/// minimize or maximize   objective_offset + objective^T x
60/// subject to             rows.lower      <= matrix x <= rows.upper
61///                        variables.lower <=    x     <= variables.upper
62///                        x[j] integer where kinds[j] is Integer or Binary
63/// ```
64#[derive(Clone, Debug, PartialEq)]
65pub struct ModelData {
66    /// Optimization direction.
67    pub sense: Sense,
68    /// Objective coefficients `c`, length `n`.
69    pub objective: Vec<f64>,
70    /// Constant added to the objective.
71    pub objective_offset: f64,
72    /// Variable bounds, length `n`.
73    pub variables: Bounds,
74    /// Variable domains, length `n`.
75    pub kinds: Vec<VariableKind>,
76    /// Constraint matrix `A`, `m x n`.
77    pub matrix: CsrMatrix,
78    /// Row bounds, length `m`.
79    pub rows: Bounds,
80}
81
82/// A validated LP or mixed-integer LP.
83///
84/// A `Model` can only be obtained through [`Model::new`], so every instance
85/// satisfies the invariants below and solvers do not re-validate it. It is
86/// immutable and can be shared (for example behind an `Arc`) by any number of
87/// independent solves.
88///
89/// Invariants: `n >= 1` variables and `m >= 0` rows; finite objective
90/// coefficients, offset and matrix values; valid [`Bounds`] (infinite values
91/// only as `-inf` lower or `+inf` upper bounds); binary bounds inside `[0, 1]`;
92/// a canonical CSR matrix of shape `m x n` (see [`CsrPattern`](crate::CsrPattern)).
93#[derive(Clone, Debug, PartialEq)]
94pub struct Model {
95    data: ModelData,
96}
97
98impl Model {
99    /// Validates and wraps `data`. Errors name the offending field and entry.
100    pub fn new(data: ModelData) -> Result<Self> {
101        let n = data.objective.len();
102        let m = data.rows.len();
103        ensure(n > 0, || "at least one variable is required".into())?;
104        ensure_finite(&data.objective, "objective")?;
105        ensure(data.objective_offset.is_finite(), || {
106            format!("objective offset is {}", data.objective_offset)
107        })?;
108        data.variables.validate(n, "variable bounds")?;
109        ensure(data.kinds.len() == n, || {
110            format!(
111                "variable kinds: expected {n} entries, got {}",
112                data.kinds.len()
113            )
114        })?;
115        for (j, kind) in data.kinds.iter().enumerate() {
116            if *kind == VariableKind::Binary {
117                let (l, u) = (data.variables.lower[j], data.variables.upper[j]);
118                ensure(l >= 0.0 && u <= 1.0, || {
119                    format!("variable {j} is binary but has bounds [{l}, {u}] outside [0, 1]")
120                })?;
121            }
122        }
123        data.rows.validate(m, "row bounds")?;
124        ensure(data.matrix.rows() == m && data.matrix.cols() == n, || {
125            format!(
126                "matrix: shape is {} x {}, expected rows x variables = {m} x {n}",
127                data.matrix.rows(),
128                data.matrix.cols()
129            )
130        })?;
131        data.matrix.validate("matrix")?;
132        Ok(Self { data })
133    }
134
135    /// Number of variables `n`.
136    pub fn n(&self) -> usize {
137        self.data.objective.len()
138    }
139
140    /// Number of rows `m`.
141    pub fn m(&self) -> usize {
142        self.data.rows.len()
143    }
144
145    /// Number of stored matrix entries.
146    pub fn nnz(&self) -> usize {
147        self.data.matrix.nnz()
148    }
149
150    /// Optimization direction.
151    pub fn sense(&self) -> Sense {
152        self.data.sense
153    }
154
155    /// Objective coefficients.
156    pub fn objective(&self) -> &[f64] {
157        &self.data.objective
158    }
159
160    /// Constant objective term.
161    pub fn objective_offset(&self) -> f64 {
162        self.data.objective_offset
163    }
164
165    /// Variable bounds.
166    pub fn variables(&self) -> &Bounds {
167        &self.data.variables
168    }
169
170    /// Variable domains.
171    pub fn kinds(&self) -> &[VariableKind] {
172        &self.data.kinds
173    }
174
175    /// Constraint matrix (`m x n`).
176    pub fn matrix(&self) -> &CsrMatrix {
177        &self.data.matrix
178    }
179
180    /// Row bounds.
181    pub fn rows(&self) -> &Bounds {
182        &self.data.rows
183    }
184
185    /// Whether any variable is integer or binary.
186    pub fn is_mip(&self) -> bool {
187        self.data.kinds.iter().any(|k| k.is_integral())
188    }
189
190    /// The validated parts.
191    pub fn data(&self) -> &ModelData {
192        &self.data
193    }
194
195    /// Gives the parts back, for example to modify and re-validate them.
196    pub fn into_data(self) -> ModelData {
197        self.data
198    }
199}