forked from rust-or/good_lp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmicrolp.rs
More file actions
172 lines (153 loc) · 4.98 KB
/
microlp.rs
File metadata and controls
172 lines (153 loc) · 4.98 KB
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
//! A solver that uses [microlp](https://docs.rs/microlp), a pure rust solver.
use microlp::Error;
use crate::variable::{UnsolvedProblem, VariableDefinition};
use crate::{
constraint::ConstraintReference,
solvers::{ObjectiveDirection, ResolutionError, Solution, SolutionStatus, SolverModel},
};
use crate::{Constraint, Variable};
/// The [microlp](https://docs.rs/microlp) solver,
/// to be used with [UnsolvedProblem::using].
pub fn microlp(to_solve: UnsolvedProblem) -> MicroLpProblem {
let UnsolvedProblem {
objective,
direction,
variables,
} = to_solve;
let mut problem = microlp::Problem::new(match direction {
ObjectiveDirection::Maximisation => microlp::OptimizationDirection::Maximize,
ObjectiveDirection::Minimisation => microlp::OptimizationDirection::Minimize,
});
let variables: Vec<microlp::Variable> = variables
.iter_variables_with_def()
.map(
|(
var,
&VariableDefinition {
min,
max,
is_integer,
..
},
)| {
let coeff = *objective.linear.coefficients.get(&var).unwrap_or(&0.);
if is_integer {
problem.add_integer_var(coeff, (min as i32, max as i32))
} else {
problem.add_var(coeff, (min, max))
}
},
)
.collect();
MicroLpProblem {
problem,
variables,
n_constraints: 0,
}
}
/// A microlp model
pub struct MicroLpProblem {
problem: microlp::Problem,
variables: Vec<microlp::Variable>,
n_constraints: usize,
}
impl MicroLpProblem {
/// Get the inner microlp model
pub fn as_inner(&self) -> µlp::Problem {
&self.problem
}
}
impl SolverModel for MicroLpProblem {
type Solution = MicroLpSolution;
type Error = ResolutionError;
fn solve(self) -> Result<Self::Solution, Self::Error> {
let solution = self.problem.solve()?;
Ok(MicroLpSolution {
solution,
variables: self.variables,
})
}
fn add_constraint(&mut self, constraint: Constraint) -> ConstraintReference {
let index = self.n_constraints;
let op = match constraint.is_equality {
true => microlp::ComparisonOp::Eq,
false => microlp::ComparisonOp::Le,
};
let constant = -constraint.expression.constant;
let mut linear_expr = microlp::LinearExpr::empty();
for (var, coefficient) in constraint.expression.linear.coefficients {
linear_expr.add(self.variables[var.index()], coefficient);
}
self.problem.add_constraint(linear_expr, op, constant);
self.n_constraints += 1;
ConstraintReference { index }
}
fn name() -> &'static str {
"Microlp"
}
}
impl From<microlp::Error> for ResolutionError {
fn from(microlp_error: Error) -> Self {
match microlp_error {
microlp::Error::Unbounded => Self::Unbounded,
microlp::Error::Infeasible => Self::Infeasible,
microlp::Error::InternalError(s) => Self::Str(s),
microlp::Error::Limit => Self::Other("Execution Limit reached"),
}
}
}
/// The solution to a microlp problem
pub struct MicroLpSolution {
solution: microlp::Solution,
variables: Vec<microlp::Variable>,
}
impl MicroLpSolution {
/// Returns the MicroLP solution object. You can use it to dynamically add new constraints
pub fn into_inner(self) -> microlp::Solution {
self.solution
}
}
impl Solution for MicroLpSolution {
fn status(&self) -> SolutionStatus {
SolutionStatus::Optimal
}
fn value(&self, variable: Variable) -> f64 {
self.solution.var_value(self.variables[variable.index()])
}
}
#[cfg(test)]
mod tests {
use crate::{variable, variables, Solution, SolverModel};
use super::microlp;
#[test]
fn can_solve_easy() {
let mut vars = variables!();
let x = vars.add(variable().clamp(0, 2));
let y = vars.add(variable().clamp(1, 3));
let solution = vars
.maximise(x + y)
.using(microlp)
.with((2 * x + y) << 4)
.solve()
.unwrap();
assert_eq!((solution.value(x), solution.value(y)), (0.5, 3.))
}
#[test]
fn can_solve_milp() {
let mut vars = variables!();
let x = vars.add(variable().clamp(2, f64::INFINITY));
let y = vars.add(variable().clamp(0, 7));
let z = vars.add(variable().integer().clamp(0, f64::INFINITY));
let solution = vars
.maximise(50 * x + 40 * y + 45 * z)
.using(microlp)
.with((3 * x + 2 * y + z) << 20)
.with((2 * x + y + 3 * z) << 15)
.solve()
.unwrap();
assert_eq!(
(solution.value(x), solution.value(y), solution.value(z)),
(2.0, 6.5, 1.0)
)
}
}