Struct grb::Model[][src]

pub struct Model { /* fields omitted */ }
Expand description

Gurobi Model object.

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

Implementations

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

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

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

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

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.

Get shared reference to the environment associated with the model.

Get mutable reference to the environment associated with the model.

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

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

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.

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

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

Reset the model to an unsolved state.

All solution information previously computed are discarded.

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

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

Insert a message into log file.

Panics

Panics when message cannot be converted to a nul-terminated C string.

Import a model from a file. See Model::write for details on valid file types.

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.

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.

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

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

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

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

Errors

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

Errors

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

Errors

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

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

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

Errors

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

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

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

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

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

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

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

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

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.

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

Retrieve the status of the model.

Retrieve the variables in the model.

Errors

Returns an error if a model update is needed

Retrieve the constraints in the model.

Errors

Returns an error if a model update is needed

Retrieve the quadratic constraints in the model.

Errors

Returns an error if a model update is needed

Retrieve the SOS constraints in the model.

Errors

Returns an error if a model update is needed

Remove a variable or constraint from the model.

Retrieve a single constant matrix coefficient of the model.

Change a single constant matrix coefficient of the model.

Change a set of constant matrix coefficients of the model.

Trait Implementations

Executes the destructor for this type. Read more

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.