use crate::math::integer_linear::{ILPSolution, ILPSolver, ILPStatus, IntegerLinearProgram};
use crate::math::optimization::simplex::{minimize, LinearProgram};
use crate::math::optimization::OptimizationConfig;
use std::error::Error;
pub struct BranchAndBoundSolver {
max_iterations: usize,
tolerance: f64,
}
impl BranchAndBoundSolver {
pub fn new(max_iterations: usize, tolerance: f64) -> Self {
Self {
max_iterations,
tolerance,
}
}
fn is_integer(&self, value: f64) -> bool {
(value - value.round()).abs() < f64::max(self.tolerance, 1e-4)
}
fn solve_relaxation(
&self,
problem: &IntegerLinearProgram,
) -> Result<ILPSolution, Box<dyn Error>> {
let lp = LinearProgram {
objective: problem.objective.iter().map(|x| -x).collect(),
constraints: problem.constraints.clone(),
rhs: problem.bounds.clone(),
};
let config = OptimizationConfig {
max_iterations: self.max_iterations,
tolerance: self.tolerance,
learning_rate: 1.0,
};
let result = minimize(&lp, &config);
if !result.converged
|| result.optimal_point.is_empty()
|| result.optimal_value.is_infinite()
|| result.optimal_value.is_nan()
{
return Ok(ILPSolution {
values: vec![],
objective_value: f64::NEG_INFINITY,
status: ILPStatus::Infeasible,
});
}
for (constraint, &b) in problem.constraints.iter().zip(problem.bounds.iter()) {
let lhs: f64 = constraint
.iter()
.zip(&result.optimal_point)
.map(|(a, &x)| a * x)
.sum();
if lhs > b + self.tolerance {
return Ok(ILPSolution {
values: vec![],
objective_value: f64::NEG_INFINITY,
status: ILPStatus::Infeasible,
});
}
}
Ok(ILPSolution {
values: result.optimal_point.clone(),
objective_value: -result.optimal_value,
status: ILPStatus::Optimal,
})
}
fn branch(
&self,
problem: &IntegerLinearProgram,
var_idx: usize,
value: f64,
) -> (IntegerLinearProgram, IntegerLinearProgram) {
let mut lower_branch = problem.clone();
let mut upper_branch = problem.clone();
let mut lower_constraint = vec![0.0; problem.objective.len()];
lower_constraint[var_idx] = 1.0;
lower_branch.constraints.push(lower_constraint);
lower_branch.bounds.push(value.floor());
let mut upper_constraint = vec![0.0; problem.objective.len()];
upper_constraint[var_idx] = -1.0;
upper_branch.constraints.push(upper_constraint);
upper_branch.bounds.push(-value.ceil());
(lower_branch, upper_branch)
}
}
impl ILPSolver for BranchAndBoundSolver {
fn solve(&self, problem: &IntegerLinearProgram) -> Result<ILPSolution, Box<dyn Error>> {
let mut best_solution = None;
let mut best_objective = f64::NEG_INFINITY;
let mut stack = vec![problem.clone()];
let mut iterations = 0;
while let Some(node) = stack.pop() {
iterations += 1;
if iterations > self.max_iterations {
break;
}
let relaxation = match self.solve_relaxation(&node) {
Ok(sol) if sol.status == ILPStatus::Optimal => sol,
_ => continue,
};
if relaxation.objective_value <= best_objective {
continue;
}
let mut all_integer = true;
let mut most_fractional = None;
let mut max_frac_diff = 0.0;
for (i, &v) in relaxation.values.iter().enumerate() {
if node.integer_vars.contains(&i) && !self.is_integer(v) {
all_integer = false;
let frac = v - v.floor();
let gap = if frac <= 0.5 { frac } else { 1.0 - frac };
if gap > max_frac_diff {
max_frac_diff = gap;
most_fractional = Some((i, v));
}
}
}
if all_integer {
if relaxation.objective_value > best_objective {
best_objective = relaxation.objective_value;
best_solution = Some(relaxation);
}
} else if let Some((idx, val)) = most_fractional {
let (lower, upper) = self.branch(&node, idx, val);
stack.push(lower);
stack.push(upper);
}
}
Ok(best_solution.unwrap_or(ILPSolution {
values: vec![],
objective_value: f64::NEG_INFINITY,
status: ILPStatus::Infeasible,
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_ilp() -> Result<(), Box<dyn Error>> {
let problem = IntegerLinearProgram {
objective: vec![2.0, 1.0], constraints: vec![
vec![1.0, 1.0], vec![1.0, 0.0], ],
bounds: vec![4.0, 2.0],
integer_vars: vec![0, 1],
};
let solver = BranchAndBoundSolver::new(100, 1e-6);
let solution = solver.solve(&problem)?;
assert_eq!(solution.status, ILPStatus::Optimal);
assert!((solution.objective_value - 6.0).abs() < 1e-6);
for &v in &solution.values {
assert!((v - v.round()).abs() < 1e-6);
assert!(v >= 0.0); }
Ok(())
}
#[test]
fn test_infeasible_ilp() -> Result<(), Box<dyn Error>> {
let problem = IntegerLinearProgram {
objective: vec![1.0, 1.0],
constraints: vec![
vec![1.0, 1.0], vec![-1.0, -1.0], vec![-1.0, 0.0], vec![0.0, -1.0], ],
bounds: vec![5.0, -6.0, 0.0, 0.0],
integer_vars: vec![0, 1],
};
let solver = BranchAndBoundSolver::new(100, 1e-6);
let solution = solver.solve(&problem)?;
assert_eq!(solution.status, ILPStatus::Infeasible);
Ok(())
}
}