milp_types/solver/
mod.rs

1use crate::{MixedEquation, MixedVariable};
2use lp_types::{
3    utils::{DisplayList, DisplayWrapper},
4    LinearSolver, OptimizeDirection,
5};
6use std::{
7    collections::BTreeMap,
8    fmt::{Debug, Formatter},
9};
10
11mod display;
12
13pub struct MixedLinearSolver {
14    variables: BTreeMap<String, MixedVariable>,
15    constraints: Vec<MixedEquation>,
16    direct: OptimizeDirection,
17    epsilon: f64,
18}
19
20impl LinearSolver for MixedLinearSolver {}
21
22impl MixedLinearSolver {
23    pub fn new(maximize: bool) -> Self {
24        Self { variables: BTreeMap::new(), constraints: Vec::new(), direct: OptimizeDirection::from(maximize), epsilon: 1e-6 }
25    }
26    pub fn get_variable(&self, symbol: &str) -> Option<&MixedVariable> {
27        self.variables.get(symbol)
28    }
29    pub fn add_variable(&mut self, variable: MixedVariable) {
30        self.variables.insert(variable.get_symbol().to_string(), variable);
31    }
32    pub fn add_equation(&mut self, equation: MixedEquation) {
33        for variable in equation.variables() {
34            if !self.variables.contains_key(variable) {
35                self.variables.insert(variable.to_string(), MixedVariable::free(variable));
36            }
37        }
38        self.constraints.push(equation);
39    }
40    /// Creates a new solver with the given epsilon value.
41    pub fn set_epsilon(&mut self, epsilon: f64) {
42        self.epsilon = epsilon;
43    }
44}
45
46#[test]
47fn test() {
48    let mut problem = MixedLinearSolver::new(true);
49    let mut e1 = LinearEquation::new(LinearConstraint::le(1.0)).unwrap();
50    e1.add_coefficient(1.0, "x");
51    e1.add_coefficient(1.0, "y");
52    problem.add_equation(e1);
53
54    let mut e2 = LinearEquation::new(LinearConstraint::le(2.0)).unwrap();
55    e2.add_coefficient(1.0, "x");
56    e2.add_coefficient(1.0, "z");
57    problem.add_equation(e2);
58
59    problem.add_variable(LinearVariable::le("x", 1.0));
60    problem.add_variable(LinearVariable::le("y", 1.0));
61    problem.add_variable(LinearVariable::le("z", 1.0));
62
63    println!("{:#?}", problem);
64}