Struct grb::Model

source ·
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

source

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
source

pub fn new(modelname: &str) -> Result<Model>

Create a new model with the default environment, which is lazily initialised.

source

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
source

pub fn read_from(filename: &str, env: &Env) -> Result<Model>

👎Deprecated: use Model::from_file_with_env instead

This function has been deprecated in favour of Model::from_file_with_env and Model::from_file

source

pub fn from_file(filename: impl AsRef<Path>) -> Result<Model>

Read a model from a file using the default Env.

source

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.

source

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.

source

pub fn get_env(&self) -> &Env

Get shared reference to the environment associated with the model.

source

pub fn get_env_mut(&mut self) -> &mut Env

Get mutable reference to the environment associated with the model.

source

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());
source

pub fn optimize(&mut self) -> Result<()>

Optimize the model synchronously. This method will always trigger a Model::update.

source

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.

source

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)
}
source

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.

source

pub fn terminate(&self)

Send a request to the model to terminate the current optimization process.

source

pub fn reset(&self) -> Result<()>

Reset the model to an unsolved state.

All solution information previously computed are discarded.

source

pub fn tune(&self) -> Result<()>

Perform an automated search for parameter settings that improve performance on the model. See also references on official manual.

source

pub fn get_tune_result(&self, n: i32) -> Result<()>

Prepare to retrieve the results of tune(). See also references on official manual.

source

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.

source

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.

source

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.

source

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.

source

pub fn add_constr(&mut self, name: &str, con: IneqExpr) -> Result<Constr>

Add a Linear constraint to the model.

The con argument is usually created with the c! macro.

§Examples
let mut m = Model::new("model")?;
let x = add_ctsvar!(m)?;
let y = add_ctsvar!(m)?;
m.add_constr("c1", c!(x <= 1 - y))?;
source

pub fn add_constrs<'a, I, S>( &mut self, constr_with_names: I ) -> Result<Vec<Constr>>
where I: IntoIterator<Item = (&'a S, IneqExpr)>, S: AsRef<str> + 'a,

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
source

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
§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(_))));
source

pub fn add_ranges<'a, I, N>( &mut self, ranges_with_names: I ) -> Result<(Vec<Var>, Vec<Constr>)>
where N: AsRef<str> + 'a, I: IntoIterator<Item = (&'a N, RangeExpr)>,

Add multiple range constraints to the model in a single API call, analagous to Model::add_constrs.

§Errors
source

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
source

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
source

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
source

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
source

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
source

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.

source

pub fn get_obj_attr<A, O, V>(&self, attr: A, obj: &O) -> Result<V>
where A: ObjAttrGet<O, V>, O: ModelObject,

Query a model object attribute (Constr, Var, etc). Available attributes can be found in the attr module, which is imported in the prelude.

source

pub fn get_obj_attr_batch<A, I, O, V>(&self, attr: A, objs: I) -> Result<Vec<V>>
where A: ObjAttrGet<O, V>, I: IntoIterator<Item = O>, O: ModelObject,

Query an attribute of multiple model objects. Available attributes can be found in the attr module, which is imported in the prelude.

source

pub fn set_attr<A: ModelAttrSet<V>, V>(&self, attr: A, value: V) -> Result<()>

Set a model attribute. Attributes (objects with the Attr trait) can be found in the attr module.

§Example
let mut model = Model::new("")?;
model.set_attr(attr::ModelName, "model".to_string())?;
source

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")?;
source

pub fn set_obj_attr_batch<A, O, I, V>( &self, attr: A, obj_val_pairs: I ) -> Result<()>
where A: ObjAttrSet<O, V>, I: IntoIterator<Item = (O, V)>, O: ModelObject,

Set an attribute of multiple Model objects (Const, Var, etc). Attributes (objects with the Attr trait) can be found in the attr module.

source

pub fn set_param<P: ParamSet<V>, V>(&mut self, param: P, value: V) -> Result<()>

Set a model parameter. Parameters (objects with the Param trait) can be found in the param module.

§Example
let mut model = Model::new("")?;
model.set_param(param::OutputFlag, 0)?;
source

pub fn get_param<P: ParamGet<V>, V>(&self, param: P) -> Result<V>

Query a model parameter. Parameters (objects with the Param trait) can be found in the param module.

§Example
let mut model = Model::new("")?;
assert_eq!(model.get_param(param::LazyConstraints)?, 0);
source

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 variantPenalty 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. If true, 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 to true, 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 is true).
  • Slack variables for relaxation and related linear/quadratic constraints.
source

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.

source

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}$.

source

pub fn status(&self) -> Result<Status>

Retrieve the status of the model.

source

pub fn get_vars<'a>(&'a self) -> Result<&'a [Var]>

Retrieve the variables in the model.

§Errors

Returns an error if a model update is needed

source

pub fn get_constrs<'a>(&'a self) -> Result<&'a [Constr]>

Retrieve the constraints in the model.

§Errors

Returns an error if a model update is needed

source

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

source

pub fn get_sos<'a>(&'a self) -> Result<&'a [SOS]>

Retrieve the SOS constraints in the model.

§Errors

Returns an error if a model update is needed

source

pub fn remove<O: ModelObject>(&mut self, item: O) -> Result<()>

Remove a variable or constraint from the model.

source

pub fn get_coeff(&self, var: &Var, constr: &Constr) -> Result<f64>

Retrieve a single constant matrix coefficient of the model.

source

pub fn set_coeff( &mut self, var: &Var, constr: &Constr, value: f64 ) -> Result<()>

Change a single constant matrix coefficient of the model.

source

pub fn set_coeffs( &mut self, coeffs: impl IntoIterator<Item = (Var, Constr, f64)> ) -> Result<()>

Change a set of constant matrix coefficients of the model.

Trait Implementations§

source§

impl Drop for Model

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl From<AsyncModel> for Model

source§

fn from(model: AsyncModel) -> Model

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Model

§

impl RefUnwindSafe for Model

§

impl !Send for Model

§

impl !Sync for Model

§

impl Unpin for Model

§

impl UnwindSafe for Model

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.