pub struct Model { /* private fields */ }
Expand description
Gurobi Model object.
This will be where the bulk of interactions with Gurobi occur.
Implementations§
source§impl Model
impl Model
sourcepub fn with_env(modelname: &str, env: impl Borrow<Env>) -> Result<Model>
pub fn with_env(modelname: &str, env: impl Borrow<Env>) -> Result<Model>
Create a new model with the given environment. The original environment is
copied by Gurobi. To modify the environment of the model, use Model::get_env_mut
.
§Examples
let mut env = Env::new("")?;
env.set(param::OutputFlag, 0)?;
let mut model = Model::with_env("Model", &env)?;
assert_eq!(model.get_param(param::OutputFlag)?, 0);
// Equivalent to model.set_param(param::OutputFlag, 1)?
model.get_env_mut().set(param::OutputFlag, 1)?;
assert_eq!(env.get(param::OutputFlag).unwrap(), 0); // original env is unchanged
sourcepub fn new(modelname: &str) -> Result<Model>
pub fn new(modelname: &str) -> Result<Model>
Create a new model with the default environment, which is lazily initialised.
sourcepub fn try_clone(&self) -> Result<Model>
pub fn try_clone(&self) -> Result<Model>
Create a copy of the model. This method is fallible due to the lazy update approach and the underlying
Gurobi C API, so a Clone
implementation is not provided.
§Errors
Error::FromAPI
if a Gurobi error occursError::ModelUpdateNeeded
if model objects have been added to the model since the last update.
sourcepub fn read_from(filename: &str, env: &Env) -> Result<Model>
👎Deprecated: use Model::from_file_with_env
instead
pub fn read_from(filename: &str, env: &Env) -> Result<Model>
Model::from_file_with_env
insteadThis function has been deprecated in favour of Model::from_file_with_env
and Model::from_file
sourcepub fn from_file(filename: impl AsRef<Path>) -> Result<Model>
pub fn from_file(filename: impl AsRef<Path>) -> Result<Model>
Read a model from a file using the default Env
.
sourcepub fn from_file_with_env(
filename: impl AsRef<Path>,
env: &Env
) -> Result<Model>
pub fn from_file_with_env( filename: impl AsRef<Path>, env: &Env ) -> Result<Model>
Read a model from a file. See the manual for accepted file formats.
sourcepub fn fixed(&mut self) -> Result<Model>
pub fn fixed(&mut self) -> Result<Model>
Create the fixed model associated with the current MIP model.
The model must be MIP and have a solution loaded. In the fixed model, each integer variable is fixed to the value that it takes in the current MIP solution.
sourcepub fn get_env(&self) -> &Env
pub fn get_env(&self) -> &Env
Get shared reference to the environment associated with the model.
sourcepub fn get_env_mut(&mut self) -> &mut Env
pub fn get_env_mut(&mut self) -> &mut Env
Get mutable reference to the environment associated with the model.
sourcepub fn update(&mut self) -> Result<()>
pub fn update(&mut self) -> Result<()>
Apply all queued modification of the model and update internal lookups.
Some operations like Model::try_clone
require this method to be called.
§Examples
let mut m = Model::new("model")?;
let x = add_ctsvar!(m);
assert_eq!(m.try_clone().err().unwrap(), grb::Error::ModelUpdateNeeded);
m.update();
assert!(m.try_clone().is_ok());
sourcepub fn optimize(&mut self) -> Result<()>
pub fn optimize(&mut self) -> Result<()>
Optimize the model synchronously. This method will always trigger a Model::update
.
sourcepub fn optimize_with_callback<F>(&mut self, callback: &mut F) -> Result<()>where
F: Callback,
pub fn optimize_with_callback<F>(&mut self, callback: &mut F) -> Result<()>where
F: Callback,
Optimize the model with a callback. The callback is any type that implements the
Callback
trait. Closures, and anything else that implements FnMut(CbCtx) -> Result<()>
implement the Callback
trait automatically. This method will always trigger a Model::update
.
See crate::callback
for details on how to use callbacks.
§Panics
This function panics if Gurobi errors on clearing the callback.
sourcepub fn compute_iis(&mut self) -> Result<()>
pub fn compute_iis(&mut self) -> Result<()>
Compute an Irreducible Inconsistent Subsystem (IIS) of the model. The constraints in the IIS can be identified
by checking their IISConstr
attribute
§Example
fn compute_iis_constraints(m: &mut Model) -> grb::Result<Vec<Constr>> {
m.compute_iis()?;
let constrs = m.get_constrs()?; // all constraints in model
let iis_constrs = m.get_obj_attr_batch(attr::IISConstr, constrs.iter().copied())?
.into_iter()
.zip(constrs)
// IISConstr is 1 if constraint is in the IIS, 0 otherwise
.filter_map(|(is_iis, c)| if is_iis > 0 { Some(*c)} else { None })
.collect();
Ok(iis_constrs)
}
sourcepub fn compute_iis_with_callback<F>(&mut self, callback: &mut F) -> Result<()>where
F: Callback,
pub fn compute_iis_with_callback<F>(&mut self, callback: &mut F) -> Result<()>where
F: Callback,
Compute an IIS of the model with a callback. Only the only variant of Where
will be Where::IIS
.
sourcepub fn terminate(&self)
pub fn terminate(&self)
Send a request to the model to terminate the current optimization process.
sourcepub fn reset(&self) -> Result<()>
pub fn reset(&self) -> Result<()>
Reset the model to an unsolved state.
All solution information previously computed are discarded.
sourcepub fn tune(&self) -> Result<()>
pub fn tune(&self) -> Result<()>
Perform an automated search for parameter settings that improve performance on the model. See also references on official manual.
sourcepub fn get_tune_result(&self, n: i32) -> Result<()>
pub fn get_tune_result(&self, n: i32) -> Result<()>
Prepare to retrieve the results of tune()
.
See also references on official
manual.
sourcepub fn message(&self, message: &str)
pub fn message(&self, message: &str)
Insert a message into log file.
§Panics
Panics when message
cannot be converted to a nul-terminated C string.
sourcepub fn read(&mut self, filename: &str) -> Result<()>
pub fn read(&mut self, filename: &str) -> Result<()>
Import optimization data from a file. This routine is the general entry point for importing data from a file into a model. It can be used to read start vectors for MIP models, basis files for LP models, or parameter settings. The type of data read is determined by the file suffix. File formats are described in the manual.
If you wish to construct a model from an format like MPS
or LP
, use Model::from_file
.
sourcepub fn write(&self, filename: &str) -> Result<()>
pub fn write(&self, filename: &str) -> Result<()>
Export a model to a file.
The file type is encoded in the file name suffix. Valid suffixes are .mps
, .rew
, .lp
, or .rlp
for
writing the model itself, .ilp
for writing just the IIS associated with an infeasible model,
.sol
for writing the current solution, .mst
for writing
a start vector, .hnt
for writing a hint file, .bas
for writing an LP basis, .prm
for writing modified
parameter settings, .attr
for writing model attributes, or .json
for writing solution information in
JSON format. If your system has compression utilities installed (e.g., 7z or zip for Windows, and gzip,
bzip2, or unzip for Linux or Mac OS), then the files can be compressed, so additional suffixes of .gz
,
.bz2
, or .7z
are accepted.
sourcepub fn add_var(
&mut self,
name: &str,
vtype: VarType,
obj: f64,
lb: f64,
ub: f64,
col_coeff: impl IntoIterator<Item = (Constr, f64)>
) -> Result<Var>
pub fn add_var( &mut self, name: &str, vtype: VarType, obj: f64, lb: f64, ub: f64, col_coeff: impl IntoIterator<Item = (Constr, f64)> ) -> Result<Var>
Add a decision variable to the model. This method allows the user to give the entire column (constraint coefficients).
The add_var!
macro and its friends are usually easier to use.
sourcepub fn add_constrs<'a, I, S>(
&mut self,
constr_with_names: I
) -> Result<Vec<Constr>>
pub fn add_constrs<'a, I, S>( &mut self, constr_with_names: I ) -> Result<Vec<Constr>>
Add multiple linear constraints to the model in a single Gurobi API call.
Accepts anything that can be turned into an iterator of (name, constraint)
pairs
where name : AsRef<str>
(eg &str
or String
) and constraint
is a linear IneqExpr
.
§Examples
let mut m = Model::new("model")?;
let x = add_ctsvar!(m)?;
let y = add_ctsvar!(m)?;
let constraints = vec![
(&"c1", c!(x <= 1 - y )),
(&"c2", c!(x == 0.5*y )),
];
m.add_constrs(constraints)?;
// store owned names in Vec to ensure they live long enough
let more_constraints_names : Vec<_> = (0..10).map(|i| format!("r{}", i)).collect();
// A Map iterator of (&String, IneqConstr)
let more_constraints = (0..10).map(|i| (&more_constraints_names[i], c!(x >= i*y )));
m.add_constrs(more_constraints)?;
§Errors
Error::AlgebraicError
if a nonlinear constraint is given.Error::ModelObjectPending
if some variables haven’t yet been added to the model.Error::ModelObjectRemoved
if some variables have been removed from the model.Error::ModelObjectMismatch
if some variables are from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn add_range(
&mut self,
name: &str,
expr: RangeExpr
) -> Result<(Var, Constr)>
pub fn add_range( &mut self, name: &str, expr: RangeExpr ) -> Result<(Var, Constr)>
Add a range constraint to the model.
This operation adds a decision variable with lower/upper bound, and a linear
equality constraint which states that the value of variable must equal to expr
.
As with Model::add_constr
, the c!
macro is usually used to construct
the second argument.
§Errors
Error::AlgebraicError
if the expression in the range constraint is not linear.Error::ModelObjectPending
if some variables haven’t yet been added to the model.Error::ModelObjectRemoved
if some variables have been removed from the model.Error::ModelObjectMismatch
if some variables are from a different model.Error::FromAPI
if a Gurobi API error occurs.
§Examples
let mut m = Model::new("model")?;
let x = add_ctsvar!(m)?;
let y = add_ctsvar!(m)?;
m.add_range("", c!(x - y in 0..1))?;
let r = m.add_range("", c!(x*y in 0..1));
assert!(matches!(r, Err(grb::Error::AlgebraicError(_))));
sourcepub fn add_ranges<'a, I, N>(
&mut self,
ranges_with_names: I
) -> Result<(Vec<Var>, Vec<Constr>)>
pub fn add_ranges<'a, I, N>( &mut self, ranges_with_names: I ) -> Result<(Vec<Var>, Vec<Constr>)>
Add multiple range constraints to the model in a single API call, analagous to
Model::add_constrs
.
§Errors
Error::AlgebraicError
if the expression a the range constraint is not linear.Error::ModelObjectPending
if some variables haven’t yet been added to the model.Error::ModelObjectRemoved
if some variables have been removed from the model.Error::ModelObjectMismatch
if some variables are from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn add_qconstr(
&mut self,
name: &str,
constraint: IneqExpr
) -> Result<QConstr>
pub fn add_qconstr( &mut self, name: &str, constraint: IneqExpr ) -> Result<QConstr>
Add a quadratic constraint to the model. See the manual for which quadratic expressions are accepted by Gurobi.
§Errors
Error::ModelObjectPending
if some variables haven’t yet been added to the model.Error::ModelObjectRemoved
if some variables have been removed from the model.Error::ModelObjectMismatch
if some variables are from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn add_sos(
&mut self,
var_weight_pairs: impl IntoIterator<Item = (Var, f64)>,
sostype: SOSType
) -> Result<SOS>
pub fn add_sos( &mut self, var_weight_pairs: impl IntoIterator<Item = (Var, f64)>, sostype: SOSType ) -> Result<SOS>
Add a single Special Order Set (SOS) constraint to the model.
§Errors
Error::ModelObjectPending
if some variables haven’t yet been added to the model.Error::ModelObjectRemoved
if some variables have been removed from the model.Error::ModelObjectMismatch
if some variables are from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn set_objective(
&mut self,
expr: impl Into<Expr>,
sense: ModelSense
) -> Result<()>
pub fn set_objective( &mut self, expr: impl Into<Expr>, sense: ModelSense ) -> Result<()>
Set the objective function of the model and optimisation direction (min or max).
Because this requires setting a Var
attribute (the Obj
attribute), this method
always triggers a model update.
§Errors
Error::ModelObjectPending
if some variables haven’t yet been added to the model.Error::ModelObjectRemoved
if some variables have been removed from the model.Error::ModelObjectMismatch
if some variables are from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn get_constr_by_name(&self, name: &str) -> Result<Option<Constr>>
pub fn get_constr_by_name(&self, name: &str) -> Result<Option<Constr>>
Get a constraint by name. Returns either a constraint if one was found, or None
if none were found.
If multiple constraints match, the method returns an arbitary one.
§Usage
let mut m = Model::new("model")?;
let x = add_binvar!(m)?;
let y = add_binvar!(m)?;
let c = m.add_constr("constraint", c!(x + y == 1))?;
assert_eq!(m.get_constr_by_name("constraint").unwrap_err(), grb::Error::ModelUpdateNeeded);
m.update()?;
assert_eq!(m.get_constr_by_name("constraint")?, Some(c));
assert_eq!(m.get_constr_by_name("foo")?, None);
§Errors
Error::NulError
if thename
cannot be converted to a C-stringError::ModelUpdateNeeded
if a model update is needed.Error::ModelObjectRemoved
if the constraint has been removed from the model.Error::ModelObjectMismatch
if the constraint is from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn get_var_by_name(&self, name: &str) -> Result<Option<Var>>
pub fn get_var_by_name(&self, name: &str) -> Result<Option<Var>>
Get a variable object by name. See Model::get_constr_by_name
for details
§Errors
Error::NulError
if thename
cannot be converted to a C-stringError::ModelUpdateNeeded
if a model update is needed.Error::ModelObjectRemoved
if the variable has been removed from the model.Error::ModelObjectMismatch
if the variable is from a different model.Error::FromAPI
if a Gurobi API error occurs.
sourcepub fn get_attr<A: ModelAttrGet<V>, V>(&self, attr: A) -> Result<V>
pub fn get_attr<A: ModelAttrGet<V>, V>(&self, attr: A) -> Result<V>
Query a Model attribute. Model attributes (objects with the ModelAttr
trait) can be found in the attr
module.
sourcepub fn get_obj_attr<A, O, V>(&self, attr: A, obj: &O) -> Result<V>where
A: ObjAttrGet<O, V>,
O: ModelObject,
pub fn get_obj_attr<A, O, V>(&self, attr: A, obj: &O) -> Result<V>where
A: ObjAttrGet<O, V>,
O: ModelObject,
sourcepub fn get_obj_attr_batch<A, I, O, V>(&self, attr: A, objs: I) -> Result<Vec<V>>
pub fn get_obj_attr_batch<A, I, O, V>(&self, attr: A, objs: I) -> Result<Vec<V>>
sourcepub fn set_attr<A: ModelAttrSet<V>, V>(&self, attr: A, value: V) -> Result<()>
pub fn set_attr<A: ModelAttrSet<V>, V>(&self, attr: A, value: V) -> Result<()>
sourcepub fn set_obj_attr<A, O, V>(&self, attr: A, obj: &O, val: V) -> Result<()>where
A: ObjAttrSet<O, V>,
O: ModelObject,
pub fn set_obj_attr<A, O, V>(&self, attr: A, obj: &O, val: V) -> Result<()>where
A: ObjAttrSet<O, V>,
O: ModelObject,
Set an attribute of a Model object (Const, Var, etc). Attributes (objects with the Attr
trait) can be found
in the attr
module.
§Example
let mut model = Model::new("")?;
let x = add_ctsvar!(model)?;
let c = model.add_constr("", c!(x <= 1))?;
model.set_obj_attr(attr::VarName, &x, "x")?;
model.set_obj_attr(attr::ConstrName, &c, "c")?;
Trying to set an attribute on a model object that belongs to another model object type will fail to compile:
model.set_obj_attr2(attr::ConstrName, &x, "c")?;
sourcepub fn set_obj_attr_batch<A, O, I, V>(
&self,
attr: A,
obj_val_pairs: I
) -> Result<()>
pub fn set_obj_attr_batch<A, O, I, V>( &self, attr: A, obj_val_pairs: I ) -> Result<()>
Set an attribute of multiple Model objects (Const, Var, etc). Attributes (objects with the Attr
trait) can be
found in the attr
module.
sourcepub fn feas_relax(
&mut self,
ty: RelaxType,
minrelax: bool,
lb_pen: impl IntoIterator<Item = (Var, f64)>,
ub_pen: impl IntoIterator<Item = (Var, f64)>,
constr_pen: impl IntoIterator<Item = (Constr, f64)>
) -> Result<(Option<f64>, Vec<Var>, Vec<Constr>, Vec<QConstr>)>
pub fn feas_relax( &mut self, ty: RelaxType, minrelax: bool, lb_pen: impl IntoIterator<Item = (Var, f64)>, ub_pen: impl IntoIterator<Item = (Var, f64)>, constr_pen: impl IntoIterator<Item = (Constr, f64)> ) -> Result<(Option<f64>, Vec<Var>, Vec<Constr>, Vec<QConstr>)>
Modify the model to create a feasibility relaxation.
Given a Model
whose objective function is $f(x)$, the feasibility relaxation seeks to minimise
$$
\text{min}\quad f(x) + \sum_{j} w_j \cdot p(s_j)
$$
where $s_j > 0$ is the slack variable of $j$ -th constraint or bound, $w_j$ is the $j$-th weight
and $p(s)$ is the penalty function.
The ty
argument sets the penalty function:
RelaxType variant | Penalty function |
---|---|
Quadratic | $ p(s) = {s}^2 $ |
Linear | $ p(s) = {s} $ |
Cardinality | $ p(s) = \begin{cases} 1 & \text{if } s > 0 \\ 0 & \text{otherwise} \end{cases} $ |
This method will modify the model - if this is not desired copy the model before invoking
this method with Model::try_clone()
.
§Arguments
-
ty
: The type of cost function used when finding the minimum cost relaxation. -
minrelax
: How the objective should be minimised.If
false
, optimizing the returned model gives a solution that minimizes the cost of the violation. Iftrue
, optimizing the returned model finds a solution that minimizes the original objective, but only from among those solutions that minimize the cost of the violation. Note that this method must solve an optimization problem to find the minimum possible relaxation when set totrue
, which can be quite expensive. -
lb_pen
: Variables whose lower bounds are allowed to be violated, and their penalty weights. -
ub_pen
: Variables whose upper bounds are allowed to be violated, and their penalty weights. -
constr_pen
: Constraints which are allowed to be violated, and their penalty weights.
§Returns
- The objective value for the relaxation performed (if
minrelax
istrue
). - Slack variables for relaxation and related linear/quadratic constraints.
sourcepub fn single_scenario_model(&mut self) -> Result<Model>
pub fn single_scenario_model(&mut self) -> Result<Model>
Capture a single scenario from a multi-scenario model. Use the ScenarioNumber parameter to indicate which scenario to capture. See the manual for details on multi-scenario models.
sourcepub fn set_pwl_obj(
&mut self,
var: &Var,
points: impl IntoIterator<Item = (f64, f64)>
) -> Result<()>
pub fn set_pwl_obj( &mut self, var: &Var, points: impl IntoIterator<Item = (f64, f64)> ) -> Result<()>
Set a piecewise-linear objective function for the variable.
Given a sequence of points $(x_1, y_1), \dots, (x_n, y_n)$, the piecewise-linear objective function $f(x)$ is defined as follows: $$ f(x) = \begin{cases} y_1 + \dfrac{y_2 - y_1}{x_2 - x_1} \, (x - x_1) & \text{if $x \leq x_1$}, \\ \\ y_i + \dfrac{y_{i+1} - y_i}{x_{i+1}-x_i} \, (x - x_i) & \text{if $x_i \leq x \leq x_{i+1}$}, \\ \\ y_n + \dfrac{y_n - y_{n-1}}{x_n-x_{n-1}} \, (x - x_n) & \text{if $x \geq x_n$}, \end{cases} $$
The Obj
attribute of the Var
object will be set to 0. To delete the piecewise-linear function on the
variable, set the value of Obj
attribute to non-zero.
The points
argument contains the pairs $(x_i,y_i)$ and must satisfy $x_i < x_{i+1}$.
sourcepub fn get_constrs<'a>(&'a self) -> Result<&'a [Constr]>
pub fn get_constrs<'a>(&'a self) -> Result<&'a [Constr]>
sourcepub fn get_qconstrs<'a>(&'a self) -> Result<&'a [QConstr]>
pub fn get_qconstrs<'a>(&'a self) -> Result<&'a [QConstr]>
Retrieve the quadratic constraints in the model.
§Errors
Returns an error if a model update is needed
sourcepub fn remove<O: ModelObject>(&mut self, item: O) -> Result<()>
pub fn remove<O: ModelObject>(&mut self, item: O) -> Result<()>
Remove a variable or constraint from the model.
sourcepub fn get_coeff(&self, var: &Var, constr: &Constr) -> Result<f64>
pub fn get_coeff(&self, var: &Var, constr: &Constr) -> Result<f64>
Retrieve a single constant matrix coefficient of the model.
sourcepub fn set_coeff(
&mut self,
var: &Var,
constr: &Constr,
value: f64
) -> Result<()>
pub fn set_coeff( &mut self, var: &Var, constr: &Constr, value: f64 ) -> Result<()>
Change a single constant matrix coefficient of the model.
sourcepub fn set_coeffs(
&mut self,
coeffs: impl IntoIterator<Item = (Var, Constr, f64)>
) -> Result<()>
pub fn set_coeffs( &mut self, coeffs: impl IntoIterator<Item = (Var, Constr, f64)> ) -> Result<()>
Change a set of constant matrix coefficients of the model.