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

Hold a SCIP pointer to prevent freeing the model while the constraint is still in use #158

Merged
merged 2 commits into from
Oct 21, 2024
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
26 changes: 26 additions & 0 deletions src/constraint.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use crate::ffi;
use crate::scip::ScipPtr;
use std::rc::Rc;

/// A constraint in an optimization problem.
#[derive(Debug)]
#[allow(dead_code)]
pub struct Constraint {
/// A pointer to the underlying `SCIP_CONS` C struct.
pub(crate) raw: *mut ffi::SCIP_CONS,
/// A reference to the SCIP instance that owns this constraint (to prevent freeing the model while the constraint is live).
pub(crate) scip: Rc<ScipPtr>,
}

impl Constraint {
Expand All @@ -22,3 +27,24 @@ impl Constraint {
}
}
}

#[cfg(test)]
mod tests {
use crate::prelude::*;

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

let x1 = model.add_var(0., f64::INFINITY, 3., "x1", VarType::Integer);
let cons = model.add_cons(vec![x1], &[1.], 4., 4., "cons");
drop(model);

assert_eq!(cons.name(), "cons");
}
}
50 changes: 42 additions & 8 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,18 @@
let scip = self.scip.clone();
scip.read_prob(filename)?;
let vars = Rc::new(RefCell::new(self.scip.vars()));
let conss = Rc::new(RefCell::new(self.scip.conss()));
let conss = Rc::new(RefCell::new(
self.scip
.conss()
.iter()

Check warning on line 112 in src/model.rs

View check run for this annotation

Codecov / codecov/patch

src/model.rs#L111-L112

Added lines #L111 - L112 were not covered by tests
.map(|c| {
Rc::new(Constraint {
raw: *c,
scip: self.scip.clone(),
})
})
.collect(),

Check warning on line 119 in src/model.rs

View check run for this annotation

Codecov / codecov/patch

src/model.rs#L119

Added line #L119 was not covered by tests
));
let new_model = Model {
scip: self.scip,
state: ProblemCreated { vars, conss },
Expand Down Expand Up @@ -835,7 +846,12 @@
name,
)
.expect("Failed to create constraint in state ProblemCreated");
let cons = Rc::new(cons);
let cons = Rc::new(
Constraint {
raw: cons,
scip: self.scip.clone(),
}
);
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand Down Expand Up @@ -872,7 +888,10 @@
.scip
.create_cons(vars, coefs, lhs, rhs, name)
.expect("Failed to create constraint in state ProblemCreated");
let cons = Rc::new(cons);
let cons = Rc::new( Constraint {
raw: cons,
scip: self.scip.clone(),
});
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand All @@ -897,7 +916,10 @@
.scip
.create_cons_set_part(vars, name)
.expect("Failed to add constraint set partition in state ProblemCreated");
let cons = Rc::new(cons);
let cons = Rc::new( Constraint {
raw: cons,
scip: self.scip.clone(),
});
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand All @@ -922,7 +944,10 @@
.scip
.create_cons_set_cover(vars, name)
.expect("Failed to add constraint set cover in state ProblemCreated");
let cons = Rc::new(cons);
let cons = Rc::new( Constraint {
raw: cons,
scip: self.scip.clone(),
});
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand All @@ -947,7 +972,10 @@
.scip
.create_cons_set_pack(vars, name)
.expect("Failed to add constraint set packing in state ProblemCreated");
let cons = Rc::new(cons);
let cons = Rc::new( Constraint {
raw: cons,
scip: self.scip.clone(),
});
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand All @@ -972,7 +1000,10 @@
.scip
.create_cons_cardinality(vars, cardinality, name)
.expect("Failed to add cardinality constraint");
let cons = Rc::new(cons);
let cons = Rc::new( Constraint {
raw: cons,
scip: self.scip.clone(),
});
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand Down Expand Up @@ -1008,7 +1039,10 @@
.scip
.create_cons_indicator(bin_var, vars, coefs, rhs, name)
.expect("Failed to create constraint in state ProblemCreated");
let cons = Rc::new(cons);
let cons = Rc::new( Constraint {
raw: cons,
scip: self.scip.clone(),
});
self.state.conss.borrow_mut().push(cons.clone());
cons
}
Expand Down
35 changes: 17 additions & 18 deletions src/scip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
};
use crate::{scip_call, HeurTiming, Heuristic};
use core::panic;
use scip_sys::SCIP_SOL;
use scip_sys::{SCIP_Cons, SCIP_SOL};
use std::collections::BTreeMap;
use std::ffi::{c_int, CStr, CString};
use std::mem::MaybeUninit;
Expand Down Expand Up @@ -152,7 +152,7 @@ impl ScipPtr {
vars
}

pub(crate) fn conss(&self) -> Vec<Rc<Constraint>> {
pub(crate) fn conss(&self) -> Vec<*mut SCIP_Cons> {
// NOTE: this method should only be called once per SCIP instance
let n_conss = self.n_conss();
let mut conss = Vec::with_capacity(n_conss);
Expand All @@ -162,8 +162,7 @@ impl ScipPtr {
unsafe {
ffi::SCIPcaptureCons(self.raw, scip_cons);
}
let cons = Rc::new(Constraint { raw: scip_cons });
conss.push(cons);
conss.push(scip_cons);
}
conss
}
Expand Down Expand Up @@ -279,7 +278,7 @@ impl ScipPtr {
lhs: f64,
rhs: f64,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
assert_eq!(vars.len(), coefs.len());
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();
Expand All @@ -298,15 +297,15 @@ impl ScipPtr {
scip_call! { ffi::SCIPaddCoefLinear(self.raw, scip_cons, var.raw, coefs[i]) };
}
scip_call! { ffi::SCIPaddCons(self.raw, scip_cons) };
Ok(Constraint { raw: scip_cons })
Ok(scip_cons)
}

/// Create set partitioning constraint
pub(crate) fn create_cons_set_part(
&self,
vars: Vec<Rc<Variable>>,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();
scip_call! { ffi::SCIPcreateConsBasicSetpart(
Expand All @@ -321,15 +320,15 @@ impl ScipPtr {
scip_call! { ffi::SCIPaddCoefSetppc(self.raw, scip_cons, var.raw) };
}
scip_call! { ffi::SCIPaddCons(self.raw, scip_cons) };
Ok(Constraint { raw: scip_cons })
Ok(scip_cons)
}

/// Create set cover constraint
pub(crate) fn create_cons_set_cover(
&self,
vars: Vec<Rc<Variable>>,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();
scip_call! { ffi::SCIPcreateConsBasicSetcover(
Expand All @@ -344,7 +343,7 @@ impl ScipPtr {
scip_call! { ffi::SCIPaddCoefSetppc(self.raw, scip_cons, var.raw) };
}
scip_call! { ffi::SCIPaddCons(self.raw, scip_cons) };
Ok(Constraint { raw: scip_cons })
Ok(scip_cons)
}

pub(crate) fn create_cons_quadratic(
Expand All @@ -357,7 +356,7 @@ impl ScipPtr {
lhs: f64,
rhs: f64,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
assert_eq!(lin_vars.len(), lin_coefs.len());
assert!(
lin_vars.len() <= c_int::MAX as usize,
Expand Down Expand Up @@ -398,15 +397,15 @@ impl ScipPtr {

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

/// Create set packing constraint
pub(crate) fn create_cons_set_pack(
&self,
vars: Vec<Rc<Variable>>,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();
scip_call! { ffi::SCIPcreateConsBasicSetpack(
Expand All @@ -421,7 +420,7 @@ impl ScipPtr {
scip_call! { ffi::SCIPaddCoefSetppc(self.raw, scip_cons, var.raw) };
}
scip_call! { ffi::SCIPaddCons(self.raw, scip_cons) };
Ok(Constraint { raw: scip_cons })
Ok(scip_cons)
}

/// Create cardinality constraint
Expand All @@ -430,7 +429,7 @@ impl ScipPtr {
vars: Vec<Rc<Variable>>,
cardinality: usize,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();
scip_call! { ffi::SCIPcreateConsBasicCardinality(
Expand All @@ -449,7 +448,7 @@ impl ScipPtr {
}
scip_call! { ffi:: SCIPchgCardvalCardinality(self.raw, scip_cons, cardinality as i32) };
scip_call! { ffi::SCIPaddCons(self.raw, scip_cons) };
Ok(Constraint { raw: scip_cons })
Ok(scip_cons)
}

pub(crate) fn create_cons_indicator(
Expand All @@ -459,7 +458,7 @@ impl ScipPtr {
coefs: &mut [f64],
rhs: f64,
name: &str,
) -> Result<Constraint, Retcode> {
) -> Result<*mut SCIP_Cons, Retcode> {
assert_eq!(vars.len(), coefs.len());
let c_name = CString::new(name).unwrap();
let mut scip_cons = MaybeUninit::uninit();
Expand All @@ -479,7 +478,7 @@ impl ScipPtr {

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

/// Create solution
Expand Down
Loading