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

Add support for indicator constraints #120

Merged
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## untracked
### Added
- Add support for indicator constraints
### Fixed
- Fixed Windows MSVC build.
### Changed
Expand Down
100 changes: 100 additions & 0 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,32 @@ pub trait ProblemOrSolving {
cardinality: usize,
name: &str,
) -> Rc<Constraint>;

/// Adds a new indicator constraint to the model with the given variables, coefficients, right-hand side, and name.
///
/// # Arguments
///
/// * `bin_var` - The binary variable in the constraint.
/// * `vars` - The variables of the constraints.
/// * `coefs` - The coefficients of the variables in the constraint.
/// * `rhs` - The right-hand side of the constraint.
/// * `name` - The name of the constraint.
///
/// # Returns
///
/// A reference-counted pointer to the new constraint.
///
/// # Panics
///
/// This method panics if the constraint cannot be created in the current state.
fn add_cons_indicator(
&mut self,
bin_var: Rc<Variable>,
vars: Vec<Rc<Variable>>,
coefs: &mut [f64],
rhs: f64,
name: &str,
) -> Rc<Constraint>;
}

macro_rules! impl_ProblemOrSolving {
Expand Down Expand Up @@ -927,6 +953,41 @@ macro_rules! impl_ProblemOrSolving {
cons
}

/// Adds a new indicator constraint to the model with the given variables, coefficients, right-hand side, and name.
///
/// # Arguments
///
/// * `bin_var` - The binary variable in the constraint.
/// * `vars` - The variables of the constraints.
/// * `coefs` - The coefficients of the variables in the constraint.
/// * `rhs` - The right-hand side of the constraint.
/// * `name` - The name of the constraint.
///
/// # Returns
///
/// A reference-counted pointer to the new constraint.
///
/// # Panics
///
/// This method panics if the constraint cannot be created in the current state.
fn add_cons_indicator(
&mut self,
bin_var: Rc<Variable>,
vars: Vec<Rc<Variable>>,
coefs: &mut [f64],
rhs: f64,
name: &str,
) -> Rc<Constraint> {
assert_eq!(vars.len(), coefs.len());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be good to have an assert here that the bin_var is indeed binary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the assert.

assert_eq!(bin_var.var_type(), VarType::Binary);
let cons = self
.scip
.create_cons_indicator(bin_var, vars, coefs, rhs, name)
.expect("Failed to create constraint in state ProblemCreated");
let cons = Rc::new(cons);
self.state.conss.borrow_mut().push(cons.clone());
cons
}
})*
}
}
Expand Down Expand Up @@ -1449,6 +1510,45 @@ mod tests {
assert_eq!(solution.val(x3), 10.);
}

#[test]
fn indicator_constraint() {
let mut model = Model::new()
.hide_output()
.include_default_plugins()
.create_prob("test")
.set_obj_sense(ObjSense::Maximize);

// set up two integers variables with weight 1 and a binary variable with weight 0
let x1 = model.add_var(0., 10., 1., "x1", VarType::Integer);
let x2 = model.add_var(0., 10., 1., "x2", VarType::Integer);
let b = model.add_var(0., 1., 0., "b", VarType::Binary);

// Indicator constraint: `b == 1` implies `x1 - x2 <= -1`
model.add_cons_indicator(
b.clone(),
vec![x1.clone(), x2.clone()],
&mut [1., -1.],
-1.,
"indicator"
);

// Force `b` to be exactly 1 and later make sure that the constraint `x1 - x2 <= -1` is
// indeed active
model.add_cons(vec![b.clone()], &[1.], 1., 1., "c1");

let solved_model = model.solve();
let status = solved_model.status();
assert_eq!(status, Status::Optimal);
assert_eq!(solved_model.obj_val(), 19.);

let solution = solved_model.best_sol().unwrap();

// Indeed `x1 - x2 <= -1` when `b == 1`
assert_eq!(solution.val(x1), 9.);
assert_eq!(solution.val(x2), 10.);
assert_eq!(solution.val(b), 1.);
}

#[test]
fn create_sol() {
let mut model = Model::new()
Expand Down
30 changes: 30 additions & 0 deletions src/scip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,36 @@
Ok(Constraint { raw: scip_cons })
}

pub(crate) fn create_cons_indicator(
&mut self,
bin_var: Rc<Variable>,
vars: Vec<Rc<Variable>>,
coefs: &mut [f64],
rhs: f64,
name: &str,
) -> Result<Constraint, Retcode> {
assert_eq!(vars.len(), coefs.len());
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();

scip_call! { ffi::SCIPcreateConsBasicIndicator(

Check warning on line 468 in src/scip.rs

View check run for this annotation

Codecov / codecov/patch

src/scip.rs#L468

Added line #L468 was not covered by tests
self.raw,
scip_cons.as_mut_ptr(),

Check warning on line 470 in src/scip.rs

View check run for this annotation

Codecov / codecov/patch

src/scip.rs#L470

Added line #L470 was not covered by tests
c_name.as_ptr(),
bin_var.raw,
vars.len() as c_int,
(vars.into_iter()
.map(|var_rc| var_rc.raw)
.collect::<Vec<_>>()).as_mut_ptr(),
coefs.as_mut_ptr(),
rhs,

Check warning on line 478 in src/scip.rs

View check run for this annotation

Codecov / codecov/patch

src/scip.rs#L476-L478

Added lines #L476 - L478 were not covered by tests
) };

let scip_cons = unsafe { scip_cons.assume_init() };
scip_call! { ffi::SCIPaddCons(self.raw, scip_cons) };
Ok(Constraint { raw: scip_cons })
}

/// Create solution
pub(crate) fn create_sol(&self) -> Result<Solution, Retcode> {
let mut sol = MaybeUninit::uninit();
Expand Down
Loading