Struct grb::Model[][src]

pub struct Model { /* fields omitted */ }

Gurobi Model object.

This will be where the bulk of interactions with Gurobi occur.

Implementations

impl Model[src]

pub fn with_env(modelname: &str, env: impl Borrow<Env>) -> Result<Model>[src]

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

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

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

pub fn try_clone(&self) -> Result<Model>[src]

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

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

Read a model from a file. See the manual for accepted file formats.

pub fn fixed(&mut self) -> Result<Model>[src]

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.

pub fn get_env(&self) -> &Env[src]

Get shared reference of the environment associated with the model.

pub fn get_env_mut(&mut self) -> &mut Env[src]

Get mutable reference of the environment associated with the model.

pub fn update(&mut self) -> Result<()>[src]

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

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

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

pub fn optimize_with_callback<F>(&mut self, callback: &mut F) -> Result<()> where
    F: Callback
[src]

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.

pub fn compute_iis(&mut self) -> Result<()>[src]

Compute an Irreducible Inconsistent Subsystem (IIS) of the model.

pub fn terminate(&self)[src]

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

pub fn reset(&self) -> Result<()>[src]

Reset the model to an unsolved state.

All solution information previously computed are discarded.

pub fn tune(&self) -> Result<()>[src]

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

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

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

pub fn message(&self, message: &str)[src]

Insert a message into log file.

When message cannot convert to raw C string, a panic is occurred.

pub fn read(&mut self, filename: &str) -> Result<()>[src]

Import optimization data of the model from a file.

pub fn write(&self, filename: &str) -> Result<()>[src]

Export optimization data of the model to a file.

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>
[src]

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.

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

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

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, 
[src]

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

pub fn add_range(
    &mut self,
    name: &str,
    expr: RangeExpr
) -> Result<(Var, Constr)>
[src]

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

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)>, 
[src]

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

Errors

pub fn add_qconstr(
    &mut self,
    name: &str,
    constraint: IneqExpr
) -> Result<QConstr>
[src]

Add a quadratic constraint to the model. See the manual for which quadratic expressions are accepted by Gurobi.

Errors

pub fn add_sos(
    &mut self,
    var_weight_pairs: impl IntoIterator<Item = (Var, f64)>,
    sostype: SOSType
) -> Result<SOS>
[src]

Add a single Special Order Set (SOS) constraint to the model.

Errors

pub fn set_objective(
    &mut self,
    expr: impl Into<Expr>,
    sense: ModelSense
) -> Result<()>
[src]

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

pub fn get_constr_by_name(&self, name: &str) -> Result<Option<Constr>>[src]

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

pub fn get_var_by_name(&self, name: &str) -> Result<Option<Var>>[src]

Get a variable object by name. See Model::get_constr_by_name for details

Errors

pub fn get_attr<A: ModelAttrGet<V>, V>(&self, attr: A) -> Result<V>[src]

Query a Model attribute. Model attributes (objects with the ModelAttr trait) can be found in the attr module.

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

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

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
[src]

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

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

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

pub fn set_obj_attr<A, O, V>(&self, attr: A, obj: &O, val: V) -> Result<()> where
    A: ObjAttrSet<O, V>,
    O: ModelObject
[src]

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

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
[src]

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

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

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

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

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

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>)>
[src]

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.

pub fn set_pwl_obj(
    &mut self,
    var: &Var,
    points: impl IntoIterator<Item = (f64, f64)>
) -> Result<()>
[src]

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

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

Retrieve the status of the model.

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

Retrieve the variables in the model.

Errors

Returns an error if a model update is needed

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

Retrieve the constraints in the model.

Errors

Returns an error if a model update is needed

pub fn get_qconstrs<'a>(&'a self) -> Result<&'a [QConstr]>[src]

Retrieve the quadratic constraints in the model.

Errors

Returns an error if a model update is needed

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

Retrieve the SOS constraints in the model.

Errors

Returns an error if a model update is needed

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

Remove a variable or constraint from the model.

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

Retrieve a single constant matrix coefficient of the model.

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

Change a single constant matrix coefficient of the model.

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

Change a set of constant matrix coefficients of the model.

Trait Implementations

impl Drop for Model[src]

impl From<AsyncModel> for Model[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.