Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: report mip gap #24

Merged
merged 2 commits into from
Mar 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,12 +591,24 @@ impl HighsPtr {
}

impl SolvedModel {
/// The status of the solution. Should be Optimal if everything went well
/// The status of the solution. Should be Optimal if everything went well.
pub fn status(&self) -> HighsModelStatus {
let model_status = unsafe { Highs_getModelStatus(self.highs.unsafe_mut_ptr()) };
HighsModelStatus::try_from(model_status).unwrap()
}

/// The mip gap of the solution. Should be 0.0 if an optimal solution was
/// found. Will be INFINITY if no variables have an integer constraint.
pub fn mip_gap(&self) -> f64 {
let name = CString::new("mip_gap").unwrap();
let gap: &mut f64 = &mut -1.0;
let status =
unsafe { Highs_getDoubleInfoValue(self.highs.unsafe_mut_ptr(), name.as_ptr(), gap) };
try_handle_status(status, "Highs_getDoubleInfoValue")
.map(|_| *gap)
.unwrap()
}

/// Get the solution to the problem
pub fn get_solution(&self) -> Solution {
let cols = self.num_cols();
Expand Down Expand Up @@ -686,6 +698,8 @@ fn try_handle_status(status: c_int, msg: &str) -> Result<HighsStatus, HighsStatu

#[cfg(test)]
mod test {
use std::f64::INFINITY;

use super::*;

fn test_coefs(coefs: [f64; 2]) {
Expand Down Expand Up @@ -755,4 +769,36 @@ mod test {
assert_eq!(solved.status(), Optimal);
assert_eq!(solved.get_solution().columns(), &[50.0]);
}

#[test]
fn test_mip_gap() {
use crate::status::HighsModelStatus::Optimal;
use crate::{Model, RowProblem, Sense};
let mut p = RowProblem::default();
p.add_integer_column(1., 0..50);
let mut m = Model::new(p);
m.make_quiet();
m.set_sense(Sense::Maximise);
let solved = m.solve();
println!("{:?}", solved.get_solution());
assert_eq!(solved.status(), Optimal);
assert_eq!(solved.mip_gap(), 0.0);
assert_eq!(solved.get_solution().columns(), &[50.0]);
}

#[test]
fn test_inf_mip_gap() {
use crate::status::HighsModelStatus::Optimal;
use crate::{Model, RowProblem, Sense};
let mut p = RowProblem::default();
p.add_column(1., 0..50);
let mut m = Model::new(p);
m.make_quiet();
m.set_sense(Sense::Maximise);
let solved = m.solve();
println!("{:?}", solved.get_solution());
assert_eq!(solved.status(), Optimal);
assert_eq!(solved.mip_gap(), INFINITY);
assert_eq!(solved.get_solution().columns(), &[50.0]);
}
}