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
//! Constraints define the inequalities that must hold in the solution.
use crate::expression::Expression;
use crate::variable::{FormatWithVars, Variable};
use core::fmt::{Debug, Formatter};
use std::ops::{Shl, Shr, Sub};

/// A constraint represents a single (in)equality that must hold in the solution.
pub struct Constraint {
    /// The expression that is constrained to be null or negative
    pub(crate) expression: Expression,
    /// if is_equality, represents expression == 0, otherwise, expression <= 0
    pub(crate) is_equality: bool,
}

impl Constraint {
    fn new(expression: Expression, is_equality: bool) -> Constraint {
        Constraint {
            expression,
            is_equality,
        }
    }
}

impl FormatWithVars for Constraint {
    fn format_with<FUN>(&self, f: &mut Formatter<'_>, variable_format: FUN) -> std::fmt::Result
    where
        FUN: Fn(&mut Formatter<'_>, Variable) -> std::fmt::Result,
    {
        self.expression.linear.format_with(f, variable_format)?;
        write!(f, " {} ", if self.is_equality { "=" } else { "<=" })?;
        write!(f, "{}", -self.expression.constant)
    }
}

impl Debug for Constraint {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.format_debug(f)
    }
}

/// equals
pub fn eq<B, A: Sub<B, Output = Expression>>(a: A, b: B) -> Constraint {
    Constraint::new(a - b, true)
}

/// less than or equal
pub fn leq<B, A: Sub<B, Output = Expression>>(a: A, b: B) -> Constraint {
    Constraint::new(a - b, false)
}

/// greater than or equal
pub fn geq<A, B: Sub<A, Output = Expression>>(a: A, b: B) -> Constraint {
    leq(b, a)
}

macro_rules! impl_shifts {
    ($($t:ty)*) => {$(
        impl< RHS> Shl<RHS> for $t where Self: Sub<RHS, Output=Expression> {
            type Output = Constraint;

            fn shl(self, rhs: RHS) -> Self::Output {
                leq(self, rhs)
            }
        }

        impl< RHS: Sub<Self, Output=Expression>> Shr<RHS> for $t {
            type Output = Constraint;

            fn shr(self, rhs: RHS) -> Self::Output {
                geq(self, rhs)
            }
        }
    )*}
}

impl_shifts!(Expression Variable);

/// This macro allows defining constraints using `a + b <= c + d`
/// instead of `(a + b).leq(c + d)` or `a + b << c + d`
///
/// # Example
///
/// ## Create a constraint
///
/// ```
/// # use good_lp::*;
/// # let mut vars = variables!();
/// # let a = vars.add(variable().max(10));
/// # let b = vars.add(variable());
/// let my_inequality = constraint!(a + b >= 3 * b - a);
/// ```
///
/// ## Full example
///
/// ```
/// # fn assert_float_eq(a:f64, b:f64) {
/// #   assert!((a-b).abs() <= 16. * f64::EPSILON, "{} != {}", a, b);
/// # }
/// use good_lp::*;
///
/// let mut vars = variables!();
/// let a = vars.add(variable().max(10));
/// let b = vars.add(variable());
/// let solution = vars
///     .maximise(a + b)
///     .using(default_solver)
///     .with(constraint!(a - 5 <= b / 2))
///     .with(constraint!(b == a))
///     .solve().unwrap();
/// assert_float_eq(10., solution.value(a));
/// assert_float_eq(10., solution.value(b));
/// ```
#[macro_export]
macro_rules! constraint {
    ([$($left:tt)*] <= $($right:tt)*) => {
        $crate::constraint::leq($($left)*, $($right)*)
    };
    ([$($left:tt)*] >= $($right:tt)*) => {
        $crate::constraint::geq($($left)*, $($right)*)
    };
    ([$($left:tt)*] == $($right:tt)*) => {
        $crate::constraint::eq($($left)*, $($right)*)
    };
    // Stop condition: all token have been processed
    ([$($left:tt)*]) => {
        $($left:tt)*
    };
    // The next token is not a special one
    ([$($left:tt)*] $next:tt $($right:tt)*) => {
        constraint!([$($left)* $next] $($right)*)
    };
    // Initial rule: start the recursive calls
    ($($all:tt)*) => {
        constraint!([] $($all)*)
    };
}

#[cfg(test)]
mod tests {
    use crate::variables;
    #[test]
    fn test_leq() {
        let mut vars = variables!();
        let v0 = vars.add_variable();
        let v1 = vars.add_variable();
        let f = format!("{:?}", (3. - v0) >> v1);
        assert!(vec!["v0 + v1 <= 3", "v1 + v0 <= 3"].contains(&&*f), "{}", f)
    }
}