Skip to main content

cnvx_core/
constraint.rs

1use crate::LinExpr;
2use std::fmt::Display;
3
4/// Comparison operators used in constraints.
5#[derive(Copy, Clone, Debug)]
6pub enum Cmp {
7    /// Equality: `==`
8    Eq,
9
10    /// Less than or equal: `<=`
11    Leq,
12
13    /// Greater than or equal: `>=`
14    Geq,
15}
16
17/// A linear constraint of the form `expr cmp rhs`.
18///
19/// # Examples
20///
21/// ```rust
22/// # use cnvx_core::{LinExpr, Constraint, VarId};
23/// let x = VarId(0);
24/// let expr = LinExpr::new(x, 2.0) + 3.0;
25///
26/// let c1 = Constraint::leq(expr.clone(), 5.0);  // 2*x0 + 3 <= 5
27/// let c2 = Constraint::geq(expr.clone(), 1.0);  // 2*x0 + 3 >= 1
28/// let c3 = Constraint::eq(expr, 4.0);           // 2*x0 + 3 == 4
29/// ```
30#[derive(Clone, Debug)]
31pub struct Constraint {
32    /// The left-hand side linear expression of the constraint.
33    pub expr: LinExpr,
34
35    /// The right-hand side value of the constraint.
36    pub rhs: f64,
37
38    /// The comparison operator (==, <=, >=).
39    pub cmp: Cmp,
40}
41
42impl Constraint {
43    /// Creates a `<=` constraint: `lhs <= rhs`.
44    pub fn leq(lhs: LinExpr, rhs: f64) -> Self {
45        Self { expr: lhs, rhs, cmp: Cmp::Leq }
46    }
47
48    /// Creates a `>=` constraint: `lhs >= rhs`.
49    pub fn geq(lhs: LinExpr, rhs: f64) -> Self {
50        Self { expr: lhs, rhs, cmp: Cmp::Geq }
51    }
52
53    /// Creates a `==` constraint: `lhs == rhs`.
54    pub fn eq(lhs: LinExpr, rhs: f64) -> Self {
55        Self { expr: lhs, rhs, cmp: Cmp::Eq }
56    }
57}
58
59impl Display for Constraint {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        let cmp_str = match self.cmp {
62            Cmp::Eq => "==",
63            Cmp::Leq => "<=",
64            Cmp::Geq => ">=",
65        };
66        write!(f, "{} {} {}", self.expr, cmp_str, self.rhs)
67    }
68}