8.6.21. Model

class Model

Represents a mathematical optimization model.

Methods

__init__()

Construct a Model

addConstr()

Add a constraint

addConstrs()

Add a set of constraints

addGenConstrIndicator()

Add a new indicator constraint to model

addLConstr()

Add a linear constraint

addMConstr()

Add a set of constraints in form Ax <= B

addMVar()

Add an MVar

addPsdVar()

Add a PsdVar

addRange()

Add a range constraint

addSOS()

Add a new SOS constraint to model

addVar()

Add a variable

addVars()

Add a set of variables

cbBranch()

Indicate a new branching by specifying a variable and a split point between the lower and upper bounds of this variable

cbCut()

Add a new cutting plane to the MIP model

cbGet()

Retrieve additional data about the optimization progress

cbGetNodeRel()

Retrieve solution values of the current relaxed problem

cbGetSolution()

Retrieve values of the best solution so far

cbSetSolution()

Provide a new feasible solution for a MIP model

cbUseSolution()

If you have already provided solution by cbSetSolution, you can optionally call this method to immediately submit solution to MIP solver

chgCoeff()

Modify a coefficient value in the constraint matrix

computeIIS()

Compute an IIS(Irreducible Inconsistent Subsystem)

copy()

Return a copy of a Model

dispose()

Release the resources associated with the Model

getA()

Obtain the constraint matrix

getAttr()

Obtain the value of an attribute

getCoeff()

Obtain a coefficient value in the constraint matrix

getCol()

Obtain the Column corresponding to a variable

getConstrByName()

Obtain the constraint object by its name

getConstrs()

Obtain a list of all constraints in the Model

getGenConstrIndicator()

Retrieve an indicator constraint from model by its object

getGenConstrs()

Retrieve all general constraints in this model

getObjective()

Get the expression of the objective function

getParamInfo()

You can call this method to obtain information about parameter

getPsdConstrs()

Obtain a list of all PsdConstrs in the Model

getPsdVars()

Obtain a list of all PsdVars in the Model

getRow()

Get the expression of the constraint

getSOS()

Retrieve information about a SOS constraint

getSOSs()

Retrieve all SOS constraints in model

getVarByName()

Obtain a variable object by its name

getVars()

Obtain a list of all variables in the Model

message()

Print a string into log

optimize()

Start model optimization

read()

Read data from a file

remove()

Remove some variables or constraints from the Model

reset()

Set the model to the unsolved state and clear all data related to the solution

resetParams()

Reset all parameters to their default values

setAttr()

Set an attribute value

setObjective()

Set the objective function

setParam()

Set the value of a parameter

terminate()

Send a stop request to solver in a MIP callback function

write()

Write data of model to a file

__init__(name='', env=None)

Construct a Model

Parameters
  • name='' – The name of the Model.

  • env=None – The Environment corresponding to the Model. If env is None, the default Environment is used.

example:

Model()
Model("DietProblem")
env = Env("env.log")
Model("", env)
addConstr(tmpConstr, name='')

Add a constraint. The return value may be a Constr or PsdConstr, or MConstr, depending on the value of the TempConstr.

Parameters
  • tmpConstr

    The TempConstr to be added. TempConstr are usually obtained by using comparison operators among the following types:

    • Var

    • MVar

    • LinExpr

    • MLinExpr

    • QuadExpr

    • MQuadExpr

    • PsdExpr

  • name='' – The name of the constraint. If a MConstr is returned, a subscript is appended to the name of each constraint as a suffix.

example:

x = m.addVar()
mat = m.addMVar((2, 2))
m.addConstr(x + 1 <= 2, name="Constr")
m.addConstr(mat + 1 <= 2, name="MConstr")
coeff = numpy.array([[2, 1], [1, 2]])
px = m.addPsdVar(dim = 2)
m.addConstr(coeff * px == 2, name="PsdConstr")
addConstrs(generator, name='')

Add a set of constraints. Return a tupledict. Key is the index of the constraint, which is generated by the generator. Value is a constraint

Parameters
  • generator – Constraint generator

  • name='' – The name of the constraint. If the name is not None or ‘’, a subscript is appended to the name of each constraint as a suffix.

example:

v = m.addMVar((2, 2))
c = m.addConstrs((v[i, j].item() <= 1 for i in range(2) for j in range(2)), name='c')

Note

If the generator does not generate a subscript, an exception is thrown.

addGenConstrIndicator(Var binvar, bool binval, lhs, str sense=None, float rhs=None)

Add a new indicator constraint to model.

Parameters
  • binvar (Var) – The binary variable of new indicator constraint.

  • binval (bool) – The binary value when indicator constraint take effect.

  • lhs – Can be one of type float , Var , LinExpr or TempConstr . It is the left-hand-side value of new indicator constraint.

  • sense=None (str) –

    The sense of new constraint. Possible values are:

    • MDO.LESS_EQUAL(‘<’)

    • MDO.GREATER_EQUAL(‘>’)

    • MDO.EQUAL(‘=’)

  • rhs=None (float) – The right-hand-side value of new constraint.

Note

If lhs is of type TempConstr , argument sense and rhs should be None.

addLConstr(lhs, sense=None, rhs=None, name='')

Add a linear constraint

Parameters
  • lhs – The left part of the constraint. Can be TempConstr, in which case sense and rhs are ignored. It can also be a number, a variable, or a linear expression.

  • sense=None

    The sense of the constraint. Possible values are:

    • MDO.LESS_EQUAL(‘<’)

    • MDO.GREATER_EQUAL(‘>’)

    • MDO.EQUAL(‘=’)

    Default value is MDO.LESS_EQUAL

  • rhs=None – The right part of the constraint. Can be a number, a variable, or a linear expression

  • name='' – The name of the expression.

example:

m.addLConstr(linExpr, '>', 0)
addMConstr(A, x, sense, b, name='')

Add a set of constraints in form Ax <= B. Return a MConstr object.

Parameters
  • A – A two-dimensional array or numpy.ndarray. Coefficient matrix

  • x – The variable vector, which can be a one-dimensional array or numpy.ndarray. All variables of the model are used when None is set.

  • sense

    It can be a character, a one-dimensional array, or a numpy.ndarray, indicating a comparison character in a constraint. A comparison charater can be one of:

    • MDO.LESS_EQUAL(‘<’)

    • MDO.GREATER_EQUAL(‘>’)

    • MDO.EQUAL(‘=’)

  • b – The right value of the constraint. It can be a one-dimensional array or numpy.ndarray.

  • name='' – The name of the constraint. If the name is not None, a subscript is appended to the name of the constraint as the suffix.

addMVar(shape, lb=0.0, ub=float('inf'), obj=0.0, vtype='C', name='')

Add an MVar

Parameters
  • shape – Specifies the shape of the MVar to be added.

  • lb=0.0 – The lower bound of all variables in MVar, It can be a single number, array, or numpy.ndarray. If it is numpy.ndarray, the corresponding shape is required.

  • ub=float('inf') – The upper bound of all variables in MVar. It can be a single number, array, or numpy.ndarray. If it is numpy.ndarray, the corresponding shape is required.

  • obj=0.0 – The coefficients of all variables in MVar in the objective function. It can be a single number, array, or numpy.ndarray. If it is numpy.ndarray, the corresponding shape is required.

  • vtype='C'

    The type of all variables in MVar, which can be a single character, array, or numpy.ndarray. If numpy.ndarray is set, the corresponding shape is required. The type of variable includes:

    • MDO.CONTINUOUS(‘C’) for continuous variable

    • MDO.BINARY(‘B’) for binary variable

    • MDO.INTEGER(‘I’) for integral variable

    • MDO.SEMICONT(‘S’) for semi-continuous variable

    • and MDO.SEMIINT(‘N’) for semi-integral variable

  • name='' – The names of all variables in MVar. If it is not None, the variable name is name plus the corresponding subscript.

example:

m.addMVar((2, 2))
m.addMVar((2, 2), lb = 0)
m.addMVar((2, 2), lb = [1, 2, 3, 4])
addPsdVar(dim=0, obj=None, name='')

Add a PsdVar.

Parameters
  • dim=0 – Matrix dimension of the PsdVar

  • obj=None – The objective coefficient of the PsdVar, it is a symmetric square matrix.

  • name='' – The name of the PsdVar.

example:

m.addPsdVar(dim = 2, "X0")
m.addPsdVar(obj = mat)

Note

Arguments dim and obj , you must specify exactly one.

addRange(expr, lower, upper, name='')

Add a range constraint

Parameters
  • expr – The expression in the constraint. Can be a Var or a LinExpr, or a PsdExpr.

  • lower – The lower bound for expr . It can only be a number or None. None indicates a negative infinity.

  • upper – The upper bound for expr . It can only be a number or None. None indicates a positive infinity.

  • name='' – The name of the constraint.

example:

m.addRange(x * 2 + y * 3, 1, 10)
m.addRange(mat1 * px1, 0, 1)
addSOS(type, vars, wts=None)

Add a new SOS constraint to model.

Parameters
  • type

    Type for new SOS constraint. Valid types includes:

    • MDO.SOS_TYPE1

    • MDO.SOS_TYPE2

  • vars – The list of variables associated with new SOS constraint.

  • wts=None – The list of weights of each participating variable. Default value: [1, 2, …]

example:

m = Model()
x = m.addVars(3)
m.addSOS(MDO.SOS_TYPE1, list(x.values()))
addVar(lb=0, ub=float('inf'), obj=0, vtype='C', name='', column=None)

Add a variable

Parameters
  • lb=0 – Variable lower bound

  • ub=float('inf') – Variable upper bound

  • obj=0 – Coefficient of variable in objective function

  • vtype='C'

    The type of variable includes:

    • MDO.CONTINUOUS(‘C’) for continuous variable

    • MDO.BINARY(‘B’) for binary variable

    • MDO.INTEGER(‘I’) for integral variable

    • MDO.SEMICONT(‘S’) for semi-continuous variable

    • and MDO.SEMIINT(‘N’) for semi-integral variable

  • name='' – The name of the variable.

  • column=None – Sets the coefficient of a variable in an existing constraint.

example:

m.addVar()
m.addVar(vtype=MDO.INTEGER)
m.addVar(name='x')
addVars(*indices, lb=0.0, ub=float('inf'), obj=0.0, vtype='C', name='')

Add a set of variables. Return a tupledict with key as the index and value as the variable.

Parameters
  • *indices

    Index of variables

  • lb=0.0 – The lower bound of all variables, which can be a single number, array, or numpy.ndarray. If it is numpy.ndarray, its shape must be equal to indices

  • ub=float('inf') – The upper bound of all variables, which can be a single number, array, or numpy.ndarray. If it is numpy.ndarray, its shape must be equal to indices

  • obj=0.0 – The coefficients of all variables in objective function, which can be a single number, array, or numpy.ndarray. If it is numpy.ndarray, its shape must be equal to indices

  • vtype='C'

    The type of all variables, which can be a single character, array, or numpy.ndarray. If it is numpy.ndarray, its shape must be equal to indices The type of variable includes:

    • MDO.CONTINUOUS(‘C’) for continuous variable

    • MDO.BINARY(‘B’) for binary variable

    • MDO.INTEGER(‘I’) for integral variable

    • MDO.SEMICONT(‘S’) for semi-continuous variable

    • and MDO.SEMIINT(‘N’) for semi-integral variable

  • name='' – The names of all variables. If it is not None or ‘’, the variable name is name , plus a subscript as its suffix.

example:

m.addVars(2, 2)
m.addVars(2, 2, lb=0)
m.addVars(2, 2, lb=[1, 2, 3, 4])
m.addVars(2, 2, lb=numpy.array([1, 2, 3, 4]).reshape(2,2))
td = m.addVars(2, 2)
linExpr = td.sum()
cbBranch(var, value, way)

Indicate a new branching by specifying a variable and a split point between the lower and upper bounds of this variable. Method returns:

  • 0: Successful submission

  • 1: Submission is valid but incorrect (infeasible, etc)

  • 2: Submission is correct but not being accepted.

Parameters
  • var – The variable.

  • value – The split point. It should be between the lower and upper bounds of variable.

  • way

    The branch to consider first. Valid options are:

    • <0: the down-way branch is considered first.

    • >0: the up-way branch is considered first.

Note

Method can only be called within callback function.

cbCut(lhs, sense, rhs)

Add a new cutting plane to the MIP model. Method returns:

  • 0: Successful submission

  • 1: Submission is valid but incorrect (infeasible, etc)

  • 2: Submission is correct but not being accepted.

Parameters
  • lhs – Left-hand-side value for new cutting plane. Can be Var or LinExpr

  • sense – Sense for new cutting plane.

  • rhs – Right-hand-side value for new cutting plane. Can be Var or LinExpr

Note

Method can only be called within callback function.

cbGet(what)

Retrieve additional data about the optimization progress.

Parameters

what – The data ID requested by the user callback.

Note

Method can only be called within callback function.

cbGetNodeRel(vars)

Retrieve solution values of the current relaxed problem.

Parameters

vars – Var object or a list of Var object to indicate variables to retrieve solution value.

Note

Method can only be called within callback function.

cbGetSolution(vars)

Retrieve values of the best solution so far.

Parameters

vars – Var object or a list of Var object to indicate variables to retrieve solution value.

Note

Method can only be called within callback function.

cbSetSolution(vars, sol)

Provide a new feasible solution for a MIP model. Objective value corresponding to new solution will be returned if it is feasible.

Parameters
  • vars – A Var or list of Var object to indicate variable(s) to be provide solution value(s).

  • sol – A double value or list of double value to indicate new feasible solution value(s) to be provided.

Note

Method can only be called within callback function.

cbUseSolution()

If you have already provided solution by cbSetSolution , you can optionally call this method to immediately submit solution to MIP solver. Method returns a tuple of 2 elements: status and objective value. Status can be:

  • 0: Successful submission

  • 1: Submission is valid but incorrect (infeasible, etc)

  • 2: Submission is correct but not being accepted.

Note

Method can only be called within callback function.

chgCoeff(constr, var, newvalue)

Modify a coefficient value in the constraint matrix

Parameters
  • constr – Corresponding constraint

  • var – Corresponding variable

  • newvalue – New coefficient value

example:

coeff = m.getCoeff(constr, var)
m.chgCoeff(constr, var, coeff + 1)
computeIIS(callback=None)
Compute an IIS(Irreducible Inconsistent Subsystem). IIS is a subset of variable bounds and constraint bounds, this subset satisfies:
  1. The subproblem corresponding to the subset is still infeasible. 2. After delete any bound in this subset, the subproblem becomes feasible.

Check IIS related attributes for variable and constraint for more details.

Parameters

callback=None – Set up a user defined callback function.

Note

The cardinality of the subsystem is supposed to be small. Note that the problem is supposed to be infeasible.

copy()

Return a copy of a Model.

example:

another = model.copy()

Note

Copying a Model will consume more memory resources.

dispose()

Release the resources associated with the Model.

example:

model.dispose()
getA()

Obtain the constraint matrix. A sparse matrix in the scipy.sparse package is returned.

example:

m.getA()
getAttr(attrname, objs=None)

Obtain the value of an attribute.

Parameters
  • attrname – The name of the attribute.

  • objs=None – The list of variables or constraints, which indicates a variable attribute or constraint attribute should be retrieved. If the value is None, a Model attribute will be returned

example:

v = m.addMVar((3,))
print(m.getAttr("ModelName"))
print(m.modelname)
print(m.getAttr("VarName", v.tolist()))
print(v.varname)

Note

Attribute can also be read and written directly through object attributes, in this case, the attribute name is case-insensitive

getCoeff(constr, var)

Obtain a coefficient value in the constraint matrix.

Parameters
  • constr – Corresponding constraint

  • var – Corresponding variable

example:

coeff = m.getCoeff(constr, var)
m.chgCoeff(constr, var, coeff + 1)
getCol(var)

Obtain the Column corresponding to a variable.

Parameters

var – Corresponding variable

example:

column = m.getCol(x)
getConstrByName(name)

Obtain the constraint object by its name

Parameters

name – The name of the constraint.

example:

c.constrname = 'myconstr'
print(c.sameAs(m.getConstrByName('myconstr')))
getConstrs()

Obtain a list of all constraints in the Model.

example:

m.getConstrs()
getGenConstrIndicator(GenConstr genconstr)

Retrieve an indicator constraint from model by its object. A tuple with 5 elements will be returned:

  1. Binary variable of this indicator constraint.

  2. Binary value when indicator constraint take effect.

  3. Linear expression of this indicator constraint.

  4. Constraint sense of this indicator constraint.

  5. Right-hand-side value of this indicator constraint.

Parameters

genconstr (GenConstr) – The indicator constraint object.

getGenConstrs()

Retrieve all general constraints in this model

getObjective()

Get the expression of the objective function.

example:

expr = m.getObjective()
getParamInfo(paramname)

You can call this method to obtain information about parameter. Return a tuple containing six elements:

  1. The name of the parameter.

  2. Type of parameter

  3. The current value of the parameter.

  4. The minimum allowed value of the parameter. When the parameter is string type, the field is always ‘’

  5. The maximum allowed value of the parameter. When the parameter is string type, the field is always ‘’

  6. Default value of the parameter

Parameters

paramname – The name of the parameter.

example:

pname, ptype, pval, pmin, pmax, pdef = m.getParamInfo('MaxTime')

Note

Parameter names may contain ‘*’ and ‘?’ wildcard characters. When more than one parameter name is matched, all matching parameters are printed.

getPsdConstrs()

Obtain a list of all PsdConstrs in the Model.

example:

m.getPsdConstrs()
getPsdVars()

Obtain a list of all PsdVars in the Model.

example:

m.getPsdVars()
getRow(constr)

Get the expression of the constraint.

Parameters

constr – Corresponding constraints

example:

m.getRow(c)
getSOS(sos)

Retrieve information about a SOS constraint. This method returns a triple:

  1. An integer indicating sos type.

  2. List of participating variables.

  3. List of weights for each participating variable.

Parameters

sos – The SOS constraint to retrieve information about.

example:

m = Model()
m.addVars(3)
sos = m.addSOS(MDO.SOS_TYPE1, m.getVars())
type, vars, wts = m.getSOS(sos)
getSOSs()

Retrieve all SOS constraints in model.

example:

m = Model()
x = m.addVars()
m.addSOS(MDO.SOS_TYPE1, list(x.values()))
print(m.getSOSs())
getVarByName(name)

Obtain a variable object by its name

Parameters

name – The name of the variable.

example:

v.varname = 'myvar'
print(v.sameAs(m.getVarByName('myvar')))
getVars()

Obtain a list of all variables in the Model.

example:

m.getVars()
message(message)

Print a string into log

Parameters

message – The string to be printed.

example:

m.message("Start to optimize")
m.optimize()
m.message("OK")
optimize(callback=None)

Start model optimization. It may take some time, depends on the complexity of the problem.

Parameters

callback=None

Set up a user defined callback function. A user defined function takes 2 arguments model and where , where model can be used for context passing:

def callback(model, where):
    model._calls += 1

model = read("prob.mps")
model._calls = 0
model.optimize(callback)
print(model._calls)

Note only member variable with name prefix “_” can be added to model for context passing.

example:

m.optimize()
read(filename)

Read data from a file. The data type depends on the suffix of the file name.

Parameters

filename – The name of the file. The suffix implies the data type. For example, “.prm” indicates that load a parameter setting from file. “.mst” indicates that load MIP starts from file.

example:

m.read("trial1.prm")
remove(item)

Remove some variables or constraints from the Model

Parameters

item

The object to be deleted. Can be one of the following types:

  • Var, the variable to be deleted

  • PsdVar, the PSD variable to be deleted

  • MVar, the variable matrix to be deleted. All variables in the matrix will be deleted from the Model

  • Constr, the constraint to be deleted

  • PsdConstr, the PSD constraint to be deleted

  • SOS, the SOS constraint to be deleted

  • GenConstr, the general constraint to be deleted

  • MConstr, the constraint matrix to be deleted, all constraints in the matrix will be removed from the Model

  • list or tuple, all the above objects in the collection will be deleted from the Model

  • dict, all the above objects contained in all values will be deleted from the Model, and all keys will be ignored.

example:

m.remove(x)
m.remove(c)
m.remove([x0, x1, x2])
m.remove({'x0': x0, 'x1': x1})
reset(clearall=0)

Set the model to the unsolved state and clear all data related to the solution.

Parameters

clearall=0 – When the value is 0, only the solution is cleared; When the value is 1, all relevant data is cleared.

example:

m.optimize()
m.reset(1)
m.optimize()
resetParams()

Reset all parameters to their default values

example:

m.resetParams()
setAttr(attrname, objs, newvalues=None)

Set an attribute value

Parameters
  • attrname – The name of the attribute.

  • objs – Can be a list of variables or constraints, indicating that set an attribute value of variable or constraint. When the newvalues is None, objs is used as a new attribute value.

  • newvalues=None – An array containing attribute new values. The length of the array should be the same as that of objs.

example:

m.modelname = "DietProblem"
m.setAttr("ModelName", "DietProblem")
vars = m.addMVar((3,))
vars.varname = ["x0", "x1", "x2"]
name_list = ["x3", "x1", "x2"]
var_list = vars.tolist()
for i in range(len(var_list)):
    var_list[i].setAttr("VarName", name_list[i])

Note

Attribute can also be read and written directly through object attributes, in this case, the attribute name is case-insensitive

setObjective(expr, sense=0)

Set the objective function

Parameters
  • expr – The expression of the objective function.

  • sense=0

    The optimization sense of the objective function, including:

    • MDO.MINIMIZE(1) for minimization

    • MDO.MAXIMIZE(-1) for maximization

    Other value won’t change the current optimization sense. The default optimization sense is MDO_MINIMIZE.

example:

m.setObjective(x + 2 * y, MDO.MINIMIZE)
setParam(paramname, paramvalue)

Set the value of a parameter

Parameters
  • paramname – The name of the parameter to be set.

  • paramvalue – Parameter value

example:

m.setParam("MaxTime", 10)
m.setParam("MaxTi*", 10)
m.setParam("MaxTi*", "default")

Note

  1. Parameter names can contain ‘*’ and ‘?’ wildcard. If more than one parameter name is matched, the parameter value is not modified.

  2. When the parameter value is ‘default’, you can reset the parameter to its default value.

terminate()

Send a stop request to solver in a MIP callback function. After solver terminated, an error code ABORT_CTRL_C will be returned from Model.optimize .

Note

Method can only be called within callback function.

write(filename)

Write data of model to a file. The data type depends on the suffix of the file name.

Parameters

filename

The name of the file to be written. Valid suffixes include:

  • ’.lp’

  • ’.mps’

  • ’.qps’

These will write the model itself into a file. if suffix is one of

  • ’.sol’

  • ’.bas’

  • ’.prm’

  • ’.mst’

solution, basis, parameter setting or MIP starts will be written to the file. In addition, after valid suffix specified above, you can add another ‘.gz’ or ‘.bz2’ suffix to specify the compression format.

example:

m.write("prob.mps")
m.write("settings.prm.gz")