otspot_model/constraint.rs
1//! Constraint types and the `constraint!` macro
2
3use super::expression::Expression;
4
5/// Sense (direction) of a linear constraint.
6#[non_exhaustive]
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub enum ConstraintSense {
9 /// Less-than-or-equal: `lhs <= rhs`
10 Le,
11 /// Greater-than-or-equal: `lhs >= rhs`
12 Ge,
13 /// Equality: `lhs == rhs`
14 Eq,
15}
16
17/// A linear constraint: `lhs sense rhs`.
18///
19/// Stored in normalized form: `lhs` contains only variable terms (no constant),
20/// and `rhs` is a scalar.
21#[derive(Debug, Clone)]
22pub struct Constraint {
23 /// Left-hand side (variable terms only, constant == 0)
24 pub(crate) lhs: Expression,
25 /// Right-hand side scalar
26 pub(crate) rhs: f64,
27 /// Constraint direction
28 pub(crate) sense: ConstraintSense,
29}
30
31/// Build a `Constraint` using inequality syntax: `constraint!(x <= 5.0)` for a
32/// single variable, `constraint!((expr) <= rhs)` for a parenthesised expression.
33///
34/// ```
35/// use otspot_model::{Model, constraint};
36/// let mut model = Model::new("demo");
37/// let x = model.add_var("x", 0.0, f64::INFINITY);
38/// let y = model.add_var("y", 0.0, 10.0);
39/// model.add_constraint(constraint!((2.0 * x + 3.0 * y) <= 12.0));
40/// model.add_constraint(constraint!((x + y) >= 3.0));
41/// ```
42#[macro_export]
43macro_rules! constraint {
44 // Complex LHS in parentheses
45 (($lhs:expr) <= $rhs:expr) => {
46 $crate::expression::Expression::from($lhs).leq($rhs)
47 };
48 (($lhs:expr) >= $rhs:expr) => {
49 $crate::expression::Expression::from($lhs).geq($rhs)
50 };
51 (($lhs:expr) == $rhs:expr) => {
52 $crate::expression::Expression::from($lhs).eq_constraint($rhs)
53 };
54 // Single variable (ident can be followed by <= in macro rules)
55 ($lhs:ident <= $rhs:expr) => {
56 $crate::expression::Expression::from($lhs).leq($rhs)
57 };
58 ($lhs:ident >= $rhs:expr) => {
59 $crate::expression::Expression::from($lhs).geq($rhs)
60 };
61 ($lhs:ident == $rhs:expr) => {
62 $crate::expression::Expression::from($lhs).eq_constraint($rhs)
63 };
64}