Python API Reference

The Cardinal Optimizer provides a Python API library. This chapter documents all COPT Python constants and API functions for python applications.

Constants

Python Constants are necessary to solve a problem using the Python interface. There are four types of constants defined in COPT Python API library. They are general constants, information constants, parameters and attributes.

General Constants

For the contents of Python general constants, see General Constants.

General constants are those commonly used in modeling, such as optimization directions, variable types, and solving status, etc. Users may refer to general constants with a 'COPT' prefix. For instance, COPT.VERSION_MAJOR is the major version number of the Cardinal Optimizer.

Attributes

For the contents of Python attribute constants, see Attributes.

In the Python API, users may refer to attributes using a 'COPT.Attr' prefix. For instance, COPT.Attr.Cols is the number of variables or columns in the model.

In the Python API, user can get the attribute value by specifying the attribute name. Attributes are mostly used in Model.getAttr() method to query properties of the model, please refer to Python API: Model Class for details. Here is an example:

  • Model.getAttr(): Model.getAttr("Cols") obtain the number of variables or columns in the model.

Information

For the contents of Python API information class constants, see Information.

In the Python API, user can access the information through the COPT.Info prefix. For instance, COPT.Info.Obj is the objective function coefficients for variables (columns).

In the Python API, user can get or set the information value of the object by specifying the information name:

  • Get the value of variable or constraint information: Model.getInfo() / Var.getInfo() / Constraint.getInfo()

  • Set the value of variable or constraint information: Model.setInfo() / Var.setInfo() / Constraint.setInfo()

Callback Information

For the content of Python API callback information class constants, see Callback Information.

In the Python API, callback-related information constants are defined in the CbInfo class. User can access the callback information via COPT.CbInfo. prefix.

For instance, COPT.CbInfo.BestObj is the current best objective.

In the Python API, user can get the value of callback information by specifying the information name.

For instance, CallbackBase.getInfo(COPT.CbInfo.BestObj) : get the value of the current best objective.

Parameters

For the contents of Python API Parameters class constants, see Parameters.

Parameters control the operation of the Cardinal Optimizer. They can be modified before the optimization begins.

In the Python API, user can access parameters through the COPT.Param prefix. For instance, COPT.Param.TimeLimit is time limit in seconds of the optimization.

In the Python API, user can get and set the parameter value by specifying the parameter name. The provided functions are as follows, please refer to Python API: Model Class for details.

  • Get detailed information of the specified parameter (current value/max/min): Model.getParamInfo()

  • Get the current value of the specified parameter: Model.getParam()

  • Set the specified parameter value: Model.setParam()

Python Modeling Classes

Python modeling classes are essential for the Python interface of Cardinal Optimizer. It provides plentiful easy-to-use methods to quickly build optimization models in complex practical scenarios. This section will explains these functions and their usage.

EnvrConfig Class

EnvrConfig object contains operations related to client configuration, and provides the following methods:

EnvrConfig()

Synopsis

EnvrConfig()

Description

Constructor of EnvrConfig class. This method creates and returns an EnvrConfig Class object.

Example

# Create client configuration
envconfig = EnvrConfig()

EnvrConfig.set()

Synopsis

set(name, value)

Description

Set client configuration.

Arguments

name

Name of configuration parameter. Please refer to Client configuration for possible values.

value

Value of configuration parameter.

Example

# Set client configuration
envconfig.set(COPT.CLIENT_WAITTIME, 600)
envconfig.set(COPT.CLIENT_CLUSTER, "127.0.0.1")
# Turn off the banner output when creating COPT environment (such as version, etc.)
envconfig.set("nobanner", "1")

Envr Class

Envr object contains operations related to COPT optimization environment, and provides the following methods:

Envr()

Synopsis

Envr(arg=None)

Description

Function for constructing Envr object. This method creates and returns an Envr Class object.

Arguments

arg

Path of license file or client configuration. Optional argument, defaults to None.

Example

# Create solving environment
env = Envr()

Envr.createModel()

Synopsis

createModel(name="")

Description

Create optimization model and return a Model Class object.

Arguments

name

The name of the Model object to be created. Optional, "" by default.

Example

# Create optimization model
model = env.createModel("coptprob")

Envr.close()

Synopsis

close()

Description

Close connection to remote server.

Example

# Close connection to remote server
env.close()

Model Class

For easy access to model’s attributes and optimization parameters, Model object provides methods such as Model.Rows. The full list of attributes can be found in Attributes section. For convenience, attributes can be accessed by their names in capital or lower case.

Note that for LP or MIP, both the objective value and the solution status can be accessed through Model.objval and Model.status.

For optimization parameters, they can be set in the form "Model.Param.TimeLimit = 10". For details of the parameter names supported, please refer to Parameters section.

Class Model contains COPT model-related operations and provides the following methods:

Model.addVar()

Synopsis

addVar(lb=0.0, ub=COPT.INFINITY, obj=0.0, vtype=COPT.CONTINUOUS, name="", column=None)

Description

Add a decision variable to model and return the added Var Class object.

Arguments

lb

Lower bound for new variable. Optional, 0.0 by default.

ub

Upper bound for new variable. Optional, COPT.INFINITY by default.

obj

Objective parameter for new variable. Optional, 0.0 by default.

vtype

Variable type. Optional, COPT.CONTINUOUS by default. Please refer to Variable types for possible types.

name

Name for new variable. Optional, "" by default, which is automatically generated by solver.

column

Column corresponds to the variable. Optional, None by default.

Example

# Add a continuous variable
x = m.addVar()
# Add a binary variable
y = m.addVar(vtype=COPT.BINARY)
# Add an integer variable with lowerbound -1.0, upperbound 1.0, objective coefficient 1.0 and variable name "z"
z = m.addVar(-1.0, 1.0, 1.0, COPT.INTEGER, "z")

Model.addVars()

Synopsis

addVars(*indices, lb=0.0, ub=COPT.INFINITY, obj=0.0, vtype=COPT.CONTINUOUS, nameprefix="C")

Description

Add multiple new variables to a model. Return a tupledict Class, whose key is indice of the variable and value is the Var Class object.

Arguments

*indices

Indices for accessing the new variables.

lb

Lower bounds for new variables. Optional, 0.0 by default.

ub

Upper bounds for new variables. Optional, COPT.INFINITY by default.

obj

Objective costs for new variables. Optional, 0.0 by default.

vtype

Variable types. Optional, COPT.CONTINUOUS by default. Please refer to Variable types for possible types.

nameprefix

Name prefix for new variables. Optional, "C" by default. The actual name and the index of the variables are automatically generated by COPT.

Example

# Add three-dimensional integer variable, 6 variables in total
x = m.addVars(1, 2, 3, vtype=COPT.INTEGER)
# Add two continuous variable y, whose indice is designated by elements in tuplelist and prefix is "tl"
tl = tuplelist([(0, 1), (1, 2)])
y  = m.addVars(tl, nameprefix="tl")

Model.addMVar()

Synopsis

addMVar(shape, lb=0.0, ub=COPT.INFINITY, obj=0.0, vtype=COPT.CONTINUOUS, nameprefix="")

Description

Add MVar Class object to the model. It is used in matrix modeling and can be operated like a multidimensional array in NumPy, its shape and dimensions are similarly defined.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of a MVar Class object.

lb

The lower bound of the variable. Optional parameter, defaults to 0.0.

ub

The upper bound of the variable. Optional parameter, defaults to COPT.INFINITY.

obj

The objective function coefficients for the variables. Optional parameter, defaults to 0.0.

vtype

The type of the variable. Optional parameter, the default is COPT.CONTINUOUS, see the possible values in Variable types.

nameprefix

Variable name prefix. Optional parameter, the default is "", its actual name is automatically generated by combining the subscript of the variable.

Return value

Returns a MVar Class object

Example

model.addMVar((2, 3), lb=0.0, nameprefix="mx")

Model.addConstr()

Synopsis

addConstr(lhs, sense=None, rhs=None, name="")

Description

Add a linear constraint to the model, return Constraint Class object;

Add a semidefinite constraint to the model, return PsdConstraint Class object;

Add an indicator constraint to the model and return the GenConstr Class object;

Adds a LMI constraint to the model, returning a LmiConstraint Class object.

If a linear constraint added, then the parameter lhs can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object; If a positive semi-definite constraint added, then the parameter lhs can take the value of PsdExpr Class object, or PsdConstrBuilder Class object; If an indicator constraint added, then the parameter lhs is GenConstrBuilder Class object, ignoring other parameters. If a LMI constraint added, then the parameter lhs can take the value of LmiExpr Class object.

Arguments

lhs

Left-hand side expression for new linear constraint or constraint builder.

sense

Sense for the new constraint. Optional, None by default. Please refer to Constraint type for possible values.

rhs

Right-hand side expression for the new constraint. Optional, None by default. It can be a constant, or Var Class object, or LinExpr Class object.

name

Name for new constraint. Optional, "" by default, generated by solver automatically.

Example

# Add a linear constraint: x + y == 2
m.addConstr(x + y, COPT.EQUAL, 2)
# Add a linear constraint: x + 2*y >= 3
m.addConstr(x + 2*y >= 3.0)
# Add an indicator constraint
m.addConstr((x == 1) >> (2*y + 3*z <= 4))

Model.addBoundConstr()

Synopsis

addBoundConstr(expr, lb=-COPT.INFINITY, ub=COPT.INFINITY, name="")

Description

Add a constraint with a lower bound and an upper bound to a model and return the added Constraint Class object.

Arguments

expr

Expression for the new constraint, which can be Var Class object or LinExpr Class object.

lb

Lower bound for the new constraint. Optional, -COPT.INFINITY by default.

ub

Upper bound for the new constraint. Optional, COPT.INFINITY by default.

name

Name for new constraint. Optional, "" by default, automatically generated by solver.

Example

# Add linear bilateral constraint: -1 <= x + y <= 1
m.addBoundConstr(x + y, -1.0, 1.0)

Model.addConstrs()

Synopsis

addConstrs(generator, nameprefix="R")

Description

Add a set of linear constraints to a model.

If paramter generator is integer, the return a ConstrArray Class object consisting of generator number of empty Constraint Class objects, and users need to specify these constraints.

If parameter generator is expression generator, then return a tupledict Class object whose key is the indice of linear constraint and value is the corresponding Constraint Class object. Every iteration generates a Constraint Class object.

If the parameter generator is a matrix expression generator, return a MConstr Class object.

If the parameter generator is an indicator expression generator, return a GenConstrArray Class object.

Arguments

generator

A generator expression, where each iteration produces a Constraint Class object, or a matrix expression builder, or an indicator expression generator.

nameprefix

Name prefix for new constraints. Optional, "R" by default. The actual name and the index of the constraints are automatically generated by COPT.

Example

# Add 10 linear constraints, each constraint shaped like: x[0] + y[0] >= 2.0
m.addConstrs(x[i] + y[i] >= 2.0 for i in range(10))

Model.addMConstr()

Synopsis

addMConstr(A, x, sense, b, nameprefix="")

Description

By means of matrix modeling, a set of linear constraints are added to the model. If the value of sense here is COPT.LESS_EQUAL , the added constraint is \(Ax <= b\).

It is more convenient to generate MLinExpr Class objects by matrix multiplication, and then use overloaded comparison operators to generate MConstrBuilder Class object, which can be used as input of Model.addConstrs() to generate a set of linear constraints.

Arguments

A

Parameter A is a two-dimensional NumPy matrix, SciPy compressed sparse column matrix ( csc_matrix ) or compressed sparse row matrix ( csr_matrix ).

x

The variable corresponding to the linear term can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object. If it is empty, but the parameter c is not empty, all variables in the model are taken.

sense

The type of constraint. Possible values refer to Constraint type.

b

The value on the right side of the constraint, usually a floating point number, can also be a set of numbers, or a one-dimensional array of NumPy.

nameprefix

Constraint name prefix.

Return value

Returns a MConstr Class object

Example

A = np.full((2, 3), 1)
mx = model.addMVar(3, nameprefix="mx")
mc = model.addMConstr(A, mx, 'L', 1.0, nameprefix="mc")

Model.addSOS()

Synopsis

addSOS(sostype, vars, weights=None)

Description

Add a SOS constraint to model and return the added SOS Class object.

If param sostype is SOSBuilder Class object, then the values of param vars and param``weights`` will be ignored;

If param sostype is SOS constraint type, it can be valued as SOS-constraint types, then param vars represents variables of SOS constraint, taking the value of VarArray Class object, list, dict or tupledict Class object;

If param weights is None, then variable weights of SOS constraints will be automatically generated by solver. Otherwise take the input from user as weights, possible values can be list, dictionary or tupledict Class object.

Arguments

sostype

SOS contraint type or SOS constraint builder.

vars

Variables of SOS constraints.

weights

Weights of variables in SOS constraints, optional, None by default.

Example

# Add an SOS1 constraint, including variable x and y, weights of 1 and 2.
m.addSOS(COPT.SOS_TYPE1, [x, y], [1, 2])

Model.addGenConstrIndicator()

Synopsis

addGenConstrIndicator(binvar, binval, lhs, sense=None, rhs=None, type=COPT.INDICATOR_IF, name="")

Description

Add an indicator constraint with the specified type to a model and return the added GenConstr Class object.

If the parameter lhs is ConstrBuilder Class object, then the values of parameter sense and parameter rhs will be ignored.

If parameter lhs represents Left-hand side expression, it can take value of Var Class object or LinExpr Class object.

Arguments

binvar

Indicator variable.

binval

Value of indicator variable, can be True or False.

lhs

Left-hand side expression for the linear constraint triggered by the indicator or linear constraint builder.

sense

Sense for the linear constraint. Optional, None by default. Please refer to Constraint type for possible values.

rhs

Right-hand-side value for the linear constraint triggered by the indicator. Optional, None by default, value type is constant.

type

Type of the indicator constraint. Optional, COPT.INDICATOR_IF by default. Please refer to Indicator Constraint type for possible values.

name

Name for new indicator constraint. Optional, "" by default, generated by solver automatically.

Example

# Add an indicator constraint, if x is True, then the linear constraint y + 2*z >= 3 should hold
m.addGenConstrIndicator(x, True, y + 2*z >= 3)
# Add an indicator constraint, if the linear constraint y + 2*z >= 3 hold, then x should be True
m.addGenConstrIndicator(x, True, y + 2*z >= 3, type=COPT.INDICATOR_ONLYIF)

Model.addGenConstrIndicators()

Synopsis

addGenConstrIndicators(builders, nameprefix="")

Description

Add a set of indicator constraints with the specified type to a model and return the added GenConstrArray Class object.

Arguments

builders

A set of indicator constraint builders. The possible values could be GenConstrBuilderArray Class object, a list or dictionary of GenConstrBuilder Class object.

nameprefix

Nameprefix of indicator variable. Optional, "" by default, generated by solver automatically.

Model.addGenConstrMin()

Synopsis

addGenConstrMin(resvar, vars, constant=None, name="")

Description

Add a constraint of the form \(y=\min\{x_1, x_2, \cdots, x_n, c\}\) to the model.

Arguments

resvar

The term y on the left side of the equation and can be an object of class Var.

vars

The variable of the \(\min\{\}\) function on the right side of the equation,

Possible values are list class objects.

constant

The constant term in the \(\min\{\}\) function on the right side of the equation,

Optional parameter, the possible value is a floating number,

The default value is None.

name

Constraint name, optional parameter, default value is "" .

Return value

It returns a GenConstrX Class object.

Model.addGenConstrMax()

Synopsis

addGenConstrMax(resvar, vars, constant=None, name="")

Description

Add a constraint of the form \(y=\max\{x_1, x_2, \cdots, x_n, c\}\) to the model.

Arguments

resvar

The term y on the left side of the equation and can be an object of class Var .

vars

The variable of the \(\max\{\}\) function on the right side of the equation.

Possible values are list class objects.

constant

The constant term in the \(\max\{\}\) function on the right side of the equation.

Optional parameter, the possible value is a floating number.

The default value is None .

name

Constraint name, optional parameter, default value is "" .

Return value

It returns a GenConstrX Class object.

Model.addGenConstrAbs()

Synopsis

addGenConstrAbs(resvar, argvar, name="")

Description

Add a constraint of the form \(cy+d=|ax+b|\) to the model.

Arguments

resvar

\(y\) , possible values are objects of class Var or class LinExpr.

argvar

\(x\) , the possible value is object of class Var or class LinExpr.

name

Constraint name, optional parameter, default value is "" .

Return value

It returns a GenConstrX Class object.

Model.addGenConstrAnd()

Synopsis

addGenConstrAnd(resvar, vars, name="")

Description

Add a logical and constraint of the form \(y = x_1 \text{ and } x_2 \cdots \text{ and } x_n\) to the model.

Arguments

resvar

The term y on the left side of the equation and can be an object of class Var .

vars

Elements connected by logical operator and \(x_i, \text{for } i \in \{1,2,\cdots,n\}\)

Possible values are List class (where the elements are binary Var class objects).

name

Constraint name, optional parameter, default value is "" .

Return value

It returns a GenConstrX Class object.

Model.addGenConstrOr()

Synopsis

addGenConstrOr(resvar, vars, name="")

Description

Add a logical or constraint of the form \(y = x_1 \text{ or } x_2 \cdots \text{ or } x_n\) to the model.

Arguments

resvar

The term y on the left side of the equation and can be an object of class Var .

vars

Elements connected by logical operator or \(x_i, \text{for } i \in \{1,2,\cdots,n\}\)

Possible values are List class (where the elements are binary Var class objects).

name

Constraint name, optional parameter, default value is "" .

Return value

It returns a GenConstrX Class object.

Model.addGenConstrPWL()

Synopsis

addGenConstrPWL(xvar, yvar, xpts, ypts, name="")

Description

Add a constraint of the form \(y=f(x)\), where a piecewise linear function is defined as:

(57)\[\begin{split}f(v) = \begin{cases} \tilde{y}_1 + \frac{\tilde{y}_2-\tilde{y}_1}{\tilde{x}_2-\tilde{x}_1} (v-\tilde{x}_1),\quad &\text{if } v\leq x_1 \\ \tilde{y}_i + \frac{\tilde{y}_{i+1} - \tilde{y}_i}{\tilde{x}_{i+1} - \tilde{x}_i} (v-\tilde{x}_i),\quad &\text{if } \tilde{x}_i\leq v\leq \tilde{x}_{i+1} \\ \tilde{y}_n + \frac{\tilde{y}_n - \tilde{y}_{n-1}}{\tilde{x}_n - \tilde{x}_{n-1}}(v-\tilde{x}_n),\quad &\text{if } v\geq \tilde{x}_n \end{cases}\notag\end{split}\]

Arguments

xvar

x, which can be an object of class Var.

yvar

The term y on the left side of the equation,

Possible values are objects of class Var or class LinExpr.

xpts

\(\tilde{\boldsymbol{x}}\), the abscissa of the segmentation point.

It should be arranged in ascending order of values, possible values are List class.

ypts

\(\tilde{\boldsymbol{y}}\) , the vertical coordinate of the segmentation point,

Possible values are List class.

name

Constraint name, optional parameter, default value is "" .

Return value

It returns a GenConstrX Class object.

Model.addConeByDim()

Synopsis

addConeByDim(dim, ctype, vtype, nameprefix="ConeV")

Description

Add a Second-Order-Cone (SOC) constraint with given dimension, and return the added Cone Class object.

Arguments

dim

Dimension of SOC constraint.

ctype

Type of SOC constraint.

vtype

Variable types of SOC constraint.

nameprefix

Name prefix of variables in SOC constraint. Optional, default to "ConeV".

Example

# Add a 5 dimension rotated SOC constraint
m.addConeByDim(5, COPT.CONE_RQUAD, None)

Model.addExpConeByDim()

Synopsis

addExpConeByDim(ctype, vtype, nameprefix="ExpConeV")

Description

Add an exponential cone constraint and return the added ExpCone Class object.

Arguments

ctype

Type of exponential cone constraint.

vtype

Variable types of exponential cone constraint.

nameprefix

Name prefix of variables in exponential cone constraint. Optional, default to "ExpConeV" .

Example

# Add a primal exponential cone
m.addExpConeByDim(COPT.EXPCONE_PRIMAL, None)

Model.addCone()

Synopsis

addCone(vars, ctype)

Description

Add a Second-Order-Cone (SOC) constraint with given variables.

If argument vars is a ConeBuilder Class object, then the value of argument ctype will be ignored; If argument vars are variables, the optional values are VarArray Class objects, Python list, Python dictionary or tupledict Class objects, argument ctype is the type of SOC constraint.

Arguments

vars

Variables of SOC constraint.

ctype

Type of SOC constraint.

Example

# Add a SOC constraint with [z, x, y] as variables
m.addCone([z, x, y], COPT.CONE_QUAD)

Model.addExpCone()

Synopsis

addExpCone(vars, ctype)

Description

Add an exponential cone with given variables. For example, the primal exponential cone defined by the \(\boldsymbol{x}\in \mathbb{R}^3\) :

(58)\[\begin{align*} K_{exp}= \mathrm{cl}\left\{ \boldsymbol{x}\in \mathbb{R}^3 \mid x_0 \geq x_1\ \mathrm{exp}\left(\frac{x_2}{x_1} \right),\ x_1 > 0 \right\} \end{align*}\]

Please refer to Exponential Cone type for more details.

If argument vars is a ExpConeBuilder Class object, then the value of argument ctype will be ignored; If argument vars are variables, the optional values are VarArray Class objects, Python list, Python dictionary or tupledict Class objects, argument ctype is the type of exponential cone.

Arguments

vars

Variables of exponential cone.

ctype

Type of exponential cone. Please refer to Exponential Cone type for possible values.

Example

# Add an exponential cone with [x0, x1, x2] as variables.
# The order of variables corresponds to the mathematical form in the description
m.addExpCone([x0, x1, x2], COPT.EXPCONE_PRIMAL)

Model.addQConstr()

Synopsis

addQConstr(lhs, sense=None, rhs=None, name="")

Description

Add a linear or quadratic constraint, and return the added Constraint Class object or QConstraint Class object.

If the constraint is linear, then value of parameter lhs can be taken Var Class object, LinExpr Class object or ConstrBuilder Class object; If the constraint is quadratic, then value of parameter lhs can be taken QConstrBuilder Class object, or MQConstrBuilder Class object and other parameters will be ignored.

Arguments

lhs

Left-hand side expression for new constraint or constraint builder.

sense

Sense for the new constraint. Optional, None by default. Please refer to Constraint type for possible values.

rhs

Right-hand side expression for the new constraint. Optional, None by default. It can be a constant, Var Class object, LinExpr Class object or QuadExpr Class object.

name

Name for new constraint. Optional, "" by default, generated by solver automatically.

Example

# add a linear equality: x + y == 2
m.addQConstr(x + y, COPT.EQUAL, 2)
# add a quadratic inequality: x*x + y*y <= 3
m.addQConstr(x*x + y*y <= 3.0)

Model.addMQConstr()

Synopsis

addMQConstr(Q, c, sense, rhs, xQ_L=None, xQ_R=None, xc=None, name="")

Description

By means of matrix modeling, a quadratic constraint is added to the model. If the value of sense here is COPT.LESS_EQUAL , the added constraint is \(x_{Q_L} Q x_{Q_R} + c x_c <= rhs\).

It is more convenient to generate MQuadExpr Class objects by matrix multiplication, and then use overloaded comparison operators to generate MQConstrBuilder Class object, which can be used as input of Model.addQConstr() to generate quadratic constraints.

Arguments

Q

If the quadratic term is not empty, the parameter Q needs to be provided, which is a two-dimensional NumPy matrix, SciPy compressed sparse column matrix ( csc_matrix ) or compressed sparse row matrix ( csr_matrix ).

c

If the item is non-empty, you need to provide the parameter c, which is a one-dimensional NumPy array, or a Python list.

sense

The type of constraint. Possible values refer to Constraint type.

rhs

The value on the right side of the constraint, usually a floating point number.

xQ_L

The variable on the left side of the quadratic term, can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object.

If empty, all variables in the model are taken.

xQ_R

The variable on the right side of the quadratic term, can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object.

If empty, all variables in the model are taken.

xc

The variable corresponding to the linear term can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object.

If it is empty, but the parameter c is not empty, all variables in the model are taken.

name

constraint name.

Return value

Returns a QConstraint Class object

Example

Q = np.full((3, 3), 1)
mx = model.addMVar(3, nameprefix="mx")
mqc = model.addMQConstr(Q, None, 'L', 1.0, mx, mx, None, name="mqc")

Model.addPsdVar()

Synopsis

addPsdVar(dim, name="")

Description

Add a positive semi-definite variable.

Arguments

dim

Dimension for the positive semi-definite variable.

name

Name for the positive semi-definite variable.

Example

# Add a three-dimensional positive semi-definite variable, "X"
m.addPsdVar(3, "X")

Model.addPsdVars()

Synopsis

addPsdVars(dims, nameprefix="PSDV")

Description

Add multiple new positive semi-definite variables to a model.

Arguments

dim

Dimensions for new positive semi-definite variables.

nameprefix

Name prefix for new positive semi-definite variables.

Example

# Add two three-dimensional positive semi-definite variables
m.addPsdVars([3, 3])

Model.addUserCut()

Synopsis

addUserCut(lhs, sense = None, rhs = None, name="")

Description

Add a user cut to the MIP model.

Arguments

lhs

Left-hand side expression for the new user cut. It can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object.

sense

The sense of the new user cut. Please refer to Constraint type for possible values.

Optional. None by default.

rhs

Right-hand side expression for the new user cut.

Optional. None by default.

It can be a constant, or Var Class object, or LinExpr Class object.

name

Name for the new user cut. Optional, "" by default, automatically generated by solver.

Example

model.addUserCut(x+y <= 1)

model.addUserCut(x+y == [0, 1])

Model.addUserCuts()

Synopsis

addUserCuts(generator, nameprefix="U")

Description

Add a set of user cuts to the MIP model.

Arguments

generator

A generator expression, where each iteration produces a Constraint Class object, or MConstrBuilder Class object.

nameprefix

Name prefix for new user cuts. Optional, "U" by default. The actual name and the index of the constraints are automatically generated by COPT.

Example

model.addUserCuts(x[i]+y[i] <= 1 for i in range(10))

Model.addLazyConstr()

Synopsis

addLazyConstr(lhs, sense = None, rhs = None, name="")

Description

Add a lazy constraint to the MIP model.

Arguments

lhs

Left-hand side expression for the new lazy constraint. It can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object.

sense

The sense of the lazy constraint. Please refer to Constraint type for possible values.

Optional. None by default.

rhs

Right-hand side expression for the new lazy constraint.

Optional. None by default.

It can be a constant, or Var Class object, or LinExpr Class object.

name

Name for the new lazy constraint. Optional, "" by default, automatically generated by solver.

Example

model.addLazyConstr(x+y <= 1)
model.addLazyConstr(x+y == [0, 1])

Model.addLazyConstrs()

Synopsis

addLazyConstrs(generator, nameprefix="L")

Description

Add a set of lazy constraints to the MIP model.

Arguments

generator

A generator expression, where each iteration produces a Constraint Class object, or MConstrBuilder Class object.

nameprefix

Name prefix for new lazy constraints. Optional, "L" by default. The actual name and the index of the constraints are automatically generated by COPT.

Example

model.addLazyConstrs(x[i]+y[i] <= 1 for i in range(10))

Model.addSparseMat()

Synopsis

addSparseMat(dim, rows, cols=None, vals=None)

Description

Add a sparse symmetric matrix in triplet format

Arguments

dim

Dimension for the matrix.

rows

Row indices for accessing rows of non-zero elements.

cols

Column indices for accessing columns of non-zero elements.

vals

Coefficient values for non-zero elements

Example

# Add a three-dimentional symmetric matrix
m.addSparseMat(3, [0, 1, 2], [0, 1, 2], [2.0, 5.0, 8.0])
# Add a two-dimentional symmetric matrix
m.addSparseMat(2, [(0, 0, 3.0), (1, 0, 1.0)])

Model.addDenseMat()

Synopsis

addDenseMat(dim, vals)

Description

Add a dense symmetric matrix

Arguments

dim

Dimension for the matrix.

vals

Coefficient values, which can be a constant or a list.

Example

# Add a tree-dimentional matrix (filled with ones)
m.addDenseMat(3, 1.0)

Model.addDiagMat()

Synopsis

addDiagMat(dim, vals, offset=None)

Description

Add a diagnal symmetric matrix

Arguments

dim

Dimension for the matrix.

vals

Coefficient values, which can be a constant or a list.

offset

Offset of diagnal elements. Positive: above the diagnal; Negative: below the diagnal

Example

# Add a tree-dimentional identity matrix
m.addDiagMat(3, 1.0)

Model.addOnesMat()

Synopsis

addOnesMat(dim)

Description

Add a matrix filled with ones.

Arguments

dim

Dimension for the matrix.

Example

# Add a tree-dimentional matrix (filled with ones)
m.addOnesMat(3)

Model.addEyeMat()

Synopsis

addEyeMat(dim)

Description

Add an identity matrix

Arguments

dim

Dimension for the matrix.

Example

# Add a tree-dimentional identity matrix
m.addEyeMat(3)

Model.setObjective()

Synopsis

setObjective(expr, sense=None)

Description

Set the model objective.

Arguments

expr

Objective expression. Argument can be a constant, Var Class object, LinExpr Class object, QuadExpr Class object, MLinExpr Class object, or MQuadExpr Class object.

Note: If expr is a LinExpr Class object, the linear term in the objective will be updated; If it is a QuadExpr Class object, both the quadratic and linear terms in the objective will be updated.

sense

Optimization sense. Optional, None by default, which means no change to objective sense. Users can get access to current objective sense by attribute ObjSense . Please refer to Optimization directions for possible values.

Example

# Set objective function = x+y, optimization sense is maximization.
m.setObjective(x + y, COPT.MAXIMIZE)

Model.setMObjective()

Synopsis

setMObjective(Q, c, constant, xQ_L=None, xQ_R=None, xc=None, sense=None)

Description

Set the secondary objective of the model by matrix modeling. Objective functions of the form \(x_{Q_L} Q x_{Q_R} + c x_c + constant\) can be added.

Even more convenient is to generate a MQuadExpr Class object via matrix multiplication, available as the input to setObjective() to set the objective function.

Arguments

Q

If the quadratic term is not empty, the parameter Q needs to be provided, which is a two-dimensional NumPy matrix, SciPy compressed sparse column matrix ( csc_matrix ) or compressed sparse row matrix ( csr_matrix ).

c

If the item is non-empty, you need to provide the parameter c, which is a one-dimensional NumPy array, or a Python list.

constant

Constant term, usually a floating point number.

xQ_L

The variable on the left side of the quadratic term, can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object.

If empty, all variables in the model are taken.

xQ_R

The variable on the right side of the quadratic term, can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object.

If empty, all variables in the model are taken.

xc

The variable corresponding to the linear term can be a MVar Class object, VarArray Class object, list, dictionary or tupledict Class object.

If it is empty, but the parameter c is not empty, all variables in the model are taken.

sense

The optimization direction of the objective function. Optional parameter, the default is None, which means that the optimization direction of the model will not be changed. The current optimization direction of the model is viewed through the property ObjSense. See Optimization Direction for possible values.

Example

Q = np.full((3, 3), 1)
mx = model.addMVar(3, nameprefix="mx")
my = model.addVars(3, nameprefix="my")
mqc = model.setMObjective(Q, None, 0.0, mx, my, None, sense=COPT.MINIMIZE)

Model.setObjSense()

Synopsis

setObjSense(sense)

Description

Set optimization sense.

Arguments

sense

Optimization sense. Please refer to Optimization directions for possible values.

Example

# Set optimization sense as maximization
m.setObjSense(COPT.MAXIMIZE)

Model.setObjConst()

Synopsis

setObjConst(const)

Description

Set constant objective offset.

Arguments

const

Constant objective offset.

Example

# Set constant objective offset 1.0
m.setObjConst(1.0)

Model.getObjective()

Synopsis

getObjective()

Description

Retrieve current model objective. Return a LinExpr Class object.

Example

# Retrieve the optimization objective.
obj = m.getObjective()

Model.delQuadObj()

Synopsis

delQuadObj()

Description

Deletes the quadratic terms from the quadratic objective function.

Example

# Deletes the quadratic terms from the quadratic objective function
m.delQuadObj()

Model.delPsdObj()

Synopsis

delPsdObj()

Description

Delete the positive semi-definite terms from the objective function

Example

# Delete the positive semi-definite terms from the objective function
m.delPsdObj()

Model.getCol()

Synopsis

getCol(var)

Description

Retrieve the list of constraints in which a variable participates, Return value is a Column Class object that captures the set of constraints in which the variable participates.

Example

# Get column that captures the set of constraints in which x participates.
col = m.getCol(x)

Model.getRow()

Synopsis

getRow(constr)

Description

Retrieve the list of variables that participate in a specific constraint and return a LinExpr Class object.

Example

# Return variables that participate in conx.
linexpr = m.getRow(conx)

Model.getQuadRow()

Synopsis

getQuadRow(qconstr)

Description

Retrieve the list of variables that participate in a specific quadratic constraint and return a QuadExpr Class object.

Example

# Return variables that participate in qconx
quadexpr = m.getQuadRow(qconx)

Model.getPsdRow()

Synopsis

getPsdRow(constr)

Description

Retrieve the list of variables that participate in a specific positive semi-definite constraint and return a PsdExpr Class object.

Example

# Retrieve the row corresponding to a specific positive semi-definite constraint
psdexpr = m.getPsdRow(psdcon)

Model.getVar()

Synopsis

getVar(idx)

Description

Retrieve a variable according to its index in the coefficient matrix. Return a Var Class object.

Arguments

idx

Index of the desired variable in the coefficient matrix, starting with 0.

Example

# Retrive variable with indice of 1.
 x = m.getVar(1)

Model.getVarByName()

Synopsis

getVarByName(name)

Description

Retrieves a variable by name. Return a Var Class object.

Arguments

name

Name of the desired variable.

Example

#  Retrive variable with name "x".
x = m.getVarByName("x")

Model.getVars()

Synopsis

getVars()

Description

Retrieve all variables in the model. Return a VarArray Class object.

Example

# Retrieve all variables in the model
vars = m.getVars()

Model.getConstr()

Synopsis

getConstr(idx)

Description

Retrieve a constraint by its indice in the coefficient matrix. Return a Constraint Class object.

Arguments

idx

Index of the desired constraint in the coefficient matrix, starting with 0.

Example

# Retrive linear constraint with indice of 1.
r = m.getConstr(1)

Model.getConstrByName()

Synopsis

getConstrByName(name)

Description

Retrieves a linear constraint by name. Return a Constraint Class object.

Arguments

name

The name of the constraint.

Example

# Retrieve linear constraint with name "r".
r = m.getConstrByName("r")

Model.getConstrs()

Synopsis

getConstrs()

Description

Retrieve all constraints in the model. Return a ConstrArray Class object.

Example

# Retrieve all constraints in the model
cons = m.getConstrs()

Model.getConstrBuilders()

Synopsis

getConstrBuilders(constrs=None)

Description

Retrieve linear constraint builders in current model.

If parameter constrs is None, then return a ConstrBuilderArray Class object composed of all linear constraint builders.

If parameter constrs is Constraint Class object, then return the ConstrBuilder Class object corresponding to the specific constraint.

If parameter constrs is a list or a ConstrArray Class object, then return a ConstrBuilderArray Class object composed of specified constraints’ builders.

If parameter constrs is dictionary or tupledict Class object, then the indice of the specified constraint is returned as key, the value is a tupledict Class object composed of the specified constraints’ builders.

Arguments

constrs

The specified linear constraint. Optional, None by default.

Example

# Retrieve all of linear constraint builders.
conbuilders = m.getConstrBuilders()
# Retrive the builder corresponding to linear contstraint x.
conbuilders = m.getConstrBuilders(x)
# Retrieve builders corresponding to linear constraint x and y.
conbuilders = m.getConstrBuilders([x, y])
# Retrieve builders corresponding to linear constraint in tupledict object xx.
conbuilders = m.getConstrBuilders(xx)

Model.getSOS(sos)

Synopsis

getSOS(sos)

Description

Retrieve the SOS constraint builder corresponding to specific SOS constraint. Return a SOSBuilder Class object

Arguments

sos

The specified SOS constraint.

Example

# Retrieve the builder corresponding to SOS constraint sosx.
sosbuilder = m.getSOS(sosx)

Model.getSOSs()

Synopsis

getSOSs()

Description

Retrieve all SOS constraints in model and return a SOSArray Class object.

Example

#  Retrieve all SOS constraints in model.
soss = m.getSOSs()

Model.getSOSBuilders()

Synopsis

getSOSBuilders(soss=None)

Description

Retrieve the SOS constraint builder corresponding to the specified SOS constraint.

If parameter soss is None, then return a SOSBuilderArray Class object consisting of builders corresponding to all SOS constraints.

If parameter soss is SOS Class object, then return a SOSBuilder Class corresponding to the specified SOS constraint.

If parameter soss is list or SOSArray Class object, then return a SOSBuilderArray Class object consisting of builders corresponding to the specific SOS constraints.

Arguments

soss

The specific SOS constraint. Optional, None by default.

Example

# Retrieve builders corresponding to all SOS constraints in the model.
soss = m.getSOSBuilders()

Model.getGenConstrIndicator()

Synopsis

getGenConstrIndicator(genconstr)

Description

Retrieve the builder corresponding to specific indicator constraint. Return a GenConstrBuilder Class object.

Arguments

genconstr

The specified indicator constraint.

Example

# Retrieve the builder corresponding to indicator constraint genx.
indic = m.getGenConstrIndicator(genx)

Model.getGenConstr()

Synopsis

getGenConstr(idx)

Description

Retrieve an indicator constraint by its indice in the model. Return a GenConstr Class object.

Arguments

idx

Index of the desired constraint in the model, starting with 0.

Example

# Retrive indicator constraint with indice of 0
genx = m.getGenConstr(0)

Model.getGenConstrs()

Synopsis

getGenConstrs()

Description

Retrieve all indicator constraints in the model. Return a GenConstrArray Class object.

Example

# Retrieve all indicator constraints in the model
cons = m.getGenConstrs()

Model.getGenConstrByName()

Synopsis

getGenConstrByName(name)

Description

Retrieves an indicator constraint by the specified name. Return a GenConstr Class object.

Arguments

name

The name of the indicator constraint.

Example

# Retrieve indicator constraint with name "r"
r = m.getGenConstrByName("r")

Model.getGenConstrIndicators()

Synopsis

getGenConstrIndicators(genconstrs=None)

Description

Retrieve the specified indicator constraints’ builders in the model. All indicator constraints will be retrieved in default. Return a GenConstrBuilder Class or GenConstrBuilderArray Class object.

Example

# Retrieve all indicator constraints' builders in the model
cons = m.getGenConstrIndicators()

Model.getCones()

Synopsis

getCones()

Description

Retrieve all Second-Order-Cone (SOC) constraints in model, and return a ConeArray Class object.

Example

# Retrieve all SOC constraints
cones = m.getCones()

Model.getExpCones()

Synopsis

getExpCones()

Description

Retrieve all exponential cone constraints in model, and return a ExpConeArray Class object.

Example

# Retrieve all exponential cone constraints
cones = m.getExpCones()

Model.getConeBuilders()

Synopsis

getConeBuilders(cones=None)

Description

Retrieve Second-Order-Cone (SOC) constraint builders for given SOC constraints.

If argument cones is None, then return a ConeBuilderArray Class object consists of all SOC constraints’ builders; If argument cones is Cone Class object, then return a ConeBuilder Class object of given SOC constraint; If cones is Python list or ConeArray Class object, then return a ConeBuilderArray Class object consists of builders of given SOC constraints.

Arguments

cones

Given SOC constraints. Optional, default to None.

Example

# Retrieve all SOC constraints' builders
cones = m.getConeBuilders()

Model.getExpConeBuilders()

Synopsis

getExpConeBuilders(cones=None)

Description

Retrieve the exponential cone constraint builders corresponding to the specified exponential cone constraint.

If argument cones is None, then return a ExpConeBuilderArray Class object consists of all exponential cone constraints’ builders; If argument cones is ExpCone Class object, then return a ExpConeBuilder Class object of given exponential cone constraints; If cones is Python list or ExpConeArray Class object, then return a ExpConeBuilderArray Class object consists of builders of given exponential cone constraints.

Arguments

cones

Given exponential cone constraints. Optional, default to None.

Example

# Retrieve all exponential cone constraints' builders
cones = m.getConeBuilders()

Model.getQConstr()

Synopsis

getQConstr(idx)

Description

Retrieve a quadratic constraint by its indice, and return a QConstraint Class object.

Arguments

idx

Index of the desired quadratic constraint, starting with 0.

Example

# Retrieve a quadratic constraint with indice of 1
qr = m.getQConstr(1)

Model.getQConstrByName()

Synopsis

getQConstrByName(name)

Description

Retrieve a quadratic constraint by its name, and return a QConstraint Class object.

Arguments

name

Name of the desired quadratic constraint.

Example

# Retrieve a quadratic constraint with name "qr"
qr = m.getQConstrByName("qr")

Model.getQConstrs()

Synopsis

getQConstrs()

Description

Retrieve all quadratic constraints in the model. Return a QConstrArray Class object.

Example

# Retrieve all quadratic constraints in the model
qcons = m.getQConstrs()

Model.getQConstrBuilders()

Synopsis

getQConstrBuilders(qconstrs=None)

Description

Retrieve quadratic constraint builders in current model.

If parameter qconstrs is None, then return a QConstrBuilderArray Class object composed of all quadratic constraint builders.

If parameter qconstrs is QConstraint Class object, then return the QConstrBuilder Class object corresponding to the specific quadratic constraint.

If parameter qconstrs is a list or a QConstrArray Class object, then return a QConstrBuilderArray Class object composed of specified quadratic constraints’ builders.

If parameter qconstrs is dictionary or tupledict Class object, then the indice of the specified quadratic constraint is returned as key, the value is a tupledict Class object composed of the specified quadratic constraints’ builders.

Arguments

qconstrs

The specified quadratic constraint. Optional, None by default.

Example

# Retrieve all of quadratic constraint builders.
qconbuilders = m.getQConstrBuilders()
# Retrive the builder corresponding to quadratic contstraint qx.
qconbuilders = m.getQConstrBuilders(qx)
# Retrieve builders corresponding to quadratic constraint qx and qy.
qconbuilders = m.getQConstrBuilders([qx, qy])
# Retrieve builders corresponding to quadratic constraint in tupledict object qxx.
qconbuilders = m.getQConstrBuilders(qxx)

Model.getPsdVar()

Synopsis

getPsdVar(idx)

Description

Retrieve a positive semi-definite variable according to its index in the model. Return a PsdVar Class object.

Arguments

idx

Index of the desired positive semi-definite variable in the model, starting with 0.

Example

# Retrieve a positive semi-definite variable with index of 1
x = m.getPsdVar(1)

Model.getPsdVarByName()

Synopsis

getPsdVarByName(name)

Description

Retrieve a positive semi-definite variable by name. Return a PsdVar Class object.

Arguments

name

The name of the positive semi-definite variable.

Example

# Retrieve a positive semi-definite variable with name "x".
x = m.getPsdVarByName("x")

Model.getPsdVars()

Synopsis

getPsdVars()

Description

Retrieve all positive semi-definite variables in the model, and return a PsdVarArray Class object.

Example

# Retrieve all positive semi-definite variables in the model.
vars = m.getPsdVars()

Model.getPsdConstr()

Synopsis

getPsdConstr(idx)

Description

Retrieve the positive semi-definite constraint according to its index in the model. Return a PsdConstraint Class object.

Arguments

idx

Index for the positive semi-definite constraint, starting with 0.

Example

# Retrieve the positive semi-definite constraint with index of 1
r = m.getPsdConstr(1)

Model.getPsdConstrByName()

Synopsis

getPsdConstrByName(name)

Description

Retrieve a positive semi-definite constraint by name. Return a PsdConstraint Class object.

Arguments

name

The name of the positive semi-definite constraint.

Example

# Retrieve the positive semi-definite constraint with name "r".
r = m.getPsdConstrByName("r")

Model.getPsdConstrs()

Synopsis

getPsdConstrs()

Description

Retrieve all positive semi-definite constraints in the model. Return a PsdConstrArray Class object.

Example

# Retrieve all positive semi-definite constraints in the model
cons = m.getPsdConstrs()

Model.getPsdConstrBuilders()

Synopsis

getPsdConstrBuilders(constrs=None)

Description

Retrieve positive semi-definite constraint builders in current model.

If parameter constrs is None, then return a PsdConstrBuilderArray Class object composed of all positive semi-definite constraint builders.

If parameter constrs is PsdConstraint Class object, then return the PsdConstrBuilder Class object corresponding to the specific positive semi-definite constraint.

If parameter constrs is a list or a PsdConstrArray Class object, then return a PsdConstrBuilderArray Class object composed of specified positive semi-definite constraints’ builders.

If parameter constrs is dictionary or tupledict Class object, then the indice of the specified positive semi-definite constraint is returned as key, the value is a tupledict Class object composed of the specified positive semi-definite constraints’ builders.

Arguments

constrs

The specified positive semi-definite constraint. Optional, None by default.

Example

# Retrieve all of positive semi-definite constraint builders.
conbuilders = m.getPsdConstrBuilders()
# Retrive the builder corresponding to positive semi-definite contstraint x.
conbuilders = m.getPsdConstrBuilders(x)
# Retrieve builders corresponding to positive semi-definite constraint x and y.
conbuilders = m.getPsdConstrBuilders([x, y])
# Retrieve builders corresponding to positive semi-definite constraint in tupledict object xx.
conbuilders = m.getPsdConstrBuilders(xx)

Model.getLmiRow()

Synopsis

getLmiRow(constr)

Description

Get the LMI expression involved in the specified LMI constraint, including variables and corresponding coefficient matrices.

Arguments

constr

The specified LMI constraint.

Example

# Get the expression in LMI constraint c
expr = m.getLmiRow(c)

Model.getLmiConstr()

Synopsis

getLmiConstr(idx)

Description

Get the LMI constraint corresponding to the specified index in the model.

Arguments

idx

The index of the LMI constraint in the model. Starts with 0.

Example

# Get the 1st LMI constraint in the model
coeff = m.getLmiConstr(1)

Model.getLmiConstrByName()

Synopsis

getLmiConstrByName(name)

Description

Get the LMI constraint of the specified name in the model.

Arguments

name

The specified name of the LMI constraint.

Example

# Get the LMI constraint named r1 in the model
name = m.getLmiConstrByName("r1")

Model.getLmiConstrs()

Synopsis

getLmiConstrs()

Description

Get all LMI constraints in the model. Returns a LmiConstrArray Class object composed of LMI constraints.

Model.getLmiRhs()

Synopsis

getLmiRhs(constr)

Description

Get the constant term of the specified LMI constraint. Returns a SymMatrix Class object.

Arguments

constr

The specified LMI constraint.

Model.setLmiRhs()

Synopsis

setLmiRhs(constr, mat)

Description

Set the constant term of the specified LMI constraint.

Arguments

constr

The specified LMI constraint.

mat

The new constant-term symmetric to set.

Example

# Set the constant-term symmetric of the LMI constraint con to D
m.setLmiRhs(con, D)

Model.getLmiSolution()

Synopsis

getLmiSolution()

Description

Get the value and dual value of the LMI constraint.

Model.getLmiSlacks()

Synopsis

getLmiSlacks()

Description

Get the values of all slack variables of LMI constraints. Returns a list object.

Model.getLmiDuals()

Synopsis

getLmiDuals()

Description

Get the values of all dual variables of the LMI constraint. Returns a list object.

Model.getCoeff()

Synopsis

getCoeff(constr, var)

Description

Get the coefficient of variable in linear constraint, PSD constraint or LMI constraint.

Arguments

constr

The requested linear constraint, PSD constraint or LMI constraint.

var

The requested variable or PSD variable.

Example

# Get the coefficient of variable x in linear constraint c1
coeff1 = m.getCoeff(c1, x)
# Get the coefficient of PSD variable X in PSD constraint c2
coeff2 = m.getCoeff(c2, X)

Model.setCoeff()

Synopsis

setCoeff(constr, var, newval)

Description

Set the coefficient of variable in linear constraint, PSD constraint or LMI constraint.

Arguments

constr

The requested linear constraint, PSD constraint or LMI constraint.

var

The requested variable or PSD variable.

newval

New coefficient or symmetric matrix coefficient.

Example

# Set the coefficient of variable x in linear constraint c to 1.0
m.setCoeff(c, x, 1.0)

Model.setCoeffs()

Synopsis

setCoeffs(constrs, vars, vals)

Description

Set the coefficients of variables in the linear constraints in batches.

Note The constraint and variable pair cannot repeat with the same or different coefficient to be set.

Arguments

constrs

Specifies the constraints related to the coefficients to be set, which could be a dictionary, tupledict Class , ConstrArray Class or a list of Constraint Class objects.

vars

Specifies the variables related to the coefficients to be set, which could be a dictionary, tupledict Class , VarArray Class or a list of Var Class objects.

vals

The new coefficient values to be set, which could be a constant, or the list/dictionary corresponding to the constrs .

Model.getA()

Synopsis

getA()

Description

Get the coefficient matrix of model, returns a scipy.sparse.csc_matrix object. This method requires the scipy package.

Example

# Get the coefficient matrix
A = model.getA()

Model.loadMatrix()

Synopsis

loadMatrix(c, A, lhs, rhs, lb, ub, vtype=None)

Description

Load matrix and vector data to build model. This method requires the scipy package.

Arguments

c

Objective costs. If None, the objective costs are all zeros.

A

Coefficient matrix. Must be of type scipy.sparse.csc_matrix.

lhs

Lower bounds of constraints.

rhs

Upper bounds of constraints.

lb

Lower bounds of variables. If None, the lower bounds are all zeros.

ub

Upper bounds of variables. If None, the upper bounds are all COPT.INFINITY.

vtype

Variable types. Default to None, which means all variables are continuous.

Example

# Build model by problem matrix
m.loadMatrix(c, A, lhs, rhs, lb, ub)

Model.loadCone()

Synopsis

loadCone(ncone, types, dims, indices)

Description

Load Second-Order-Cones (SOC) to the model.

Arguments

ncone

Number of SOC.

types

Type of SOC, please refer to SOC constraint types for possible values.

dims

Dimension of SOC.

indices

Array of subscripts for the variables that constitute the SOC.

Model.loadExpCone()

Synopsis

loadExpCone(ncone, types, indices)

Description

Load exponential cones to the model.

Arguments

ncone

Number of exponential cones.

types

Type of exponential cones, please refer to Exponential Cone type for possible values.

indices

Array of subscripts for the variables that constitute the exponential cones.

Model.getLpSolution()

Synopsis

getLpSolution()

Description

Retrieve the values of variables, slack variables, dual variables and reduced cost of variables. Return a quad tuple object, in which each element is a list.

Example

# Retrieve solutions of linear model.
values, slacks, duals, redcosts = m.getLpSolution()

Model.setLpSolution()

Synopsis

setLpSolution(values, slack, duals, redcost)

Description

Set LP solution.

Arguments

values

Solution of variables.

slack

Solution of slack variables.

duals

Solution of dual variables.

redcost

Reduced costs of variables.

Example

# Set LP solution
m.setLpSolution(values, slack, duals, redcost)

Model.getValues()

Synopsis

getValues()

Description

Retrieve solution values of all variables in a LP or MIP. Return a Python list.

Example

values = m.getValues()

Model.getRedcosts()

Synopsis

getRedcosts()

Description

Retrieve reduced costs of all variables in a LP. Return a list.

Example

# Retrieve reduced cost of all variables in model.
redcosts = m.getRedcosts()

Model.getSlacks()

Synopsis

getSlacks()

Description

Retrieve values of all slack variables in a LP. Return a Python list.

Example

# Retrieve value of all slack variables in model.
 slacks = m.getSlacks()

Model.getDuals()

Synopsis

getDuals()

Description

Obtain values of all dual variables in a LP. Return a Python list.

Example

# Retrieve value of all dual variables in model.
duals = m.getDuals()

Model.getVarBasis()

Synopsis

getVarBasis(vars=None)

Description

Obtain basis status of specified variables.

If parameter vars is None, then return a list object consistinf of all variables’ basis status. If parameter vars is Var Class object, then return basis status of the specified variable. If parameter vars is list or VarArray Class object, then return a list object consisting of the specified variables’ basis status. If parameter vars is dictionary or tupledict Class object, then return indice of the specified variable as key and tupledict Class object consisting of the specified variables’ basis status as value.

Arguments

vars

The specified variables. Optional, None by default,

Example

# Retrieve all variables' basis status in model.
varbasis = m.getVarBasis()
# Retrieve basis status of variable x and y.
varbasis = m.getVarBasis([x, y])
# Retrieve basis status of tupledict object xx.
varbasis = m.getVarBasis(xx)

Model.getConstrBasis()

Synopsis

getConstrBasis(constrs=None)

Description

Obtain the basis status of linear constraints in LP.

If parameter constrs is None, then return a list object consisting of all linear constraints’ basis status. If parameter constrs is Constraint Class object, then return basis status of the specified linear constraint. If parameter constrs is list or ConstrArray Class object, then return a list object consisting of the specified linear constraints’ basis status. If parameter constrs is dictionary or tupledict Class object, then return the indice of the specified linear constraint as key and return tupledict Class object consisting of the specified linear constraints’ basis status as value.

Arguments

constrs

The specified linear constraint. Optional, None by default.

Example

# Retrieve all linear constraints' basis status in model.
conbasis = m.getConstrBasis()
# Retrieve basis status corresponding to linear constraint r0 and r1 in model.
conbasis = m.getConstrBasis([r0, r1])
# Retrieve basis status of linear constraints in tupledict rr.
conbasis = m.getConstrBasis(rr)

Model.getPoolObjVal()

Synopsis

getPoolObjVal(isol)

Description

Obtain the isol -th objective value in solution pool, return a constant.

Arguments

isol

Index of solution.

Example

# Obtain the second objective value
objval = m.getPoolObjVal(2)

Model.getPoolSolution()

Synopsis

getPoolSolution(isol, vars)

Description

Obtain variable values in the isol -th solution of solution pool.

If parameter vars is Var Class object, then return values of the specified variable. If parameter vars is list or VarArray Class object, then return a list object consisting of the specified variables’ values. If parameter vars is dictionary or tupledict Class object, then return indice of the specified variable as key and tupledict Class object consisting of the specified variables’ values as value.

Arguments

isol

Index of solution

vars

The specified variables.

Example

# Get value of x in the second solution
xval = m.getPoolSolution(2, x)

Model.getVarLowerIIS()

Synopsis

getVarLowerIIS(vars)

Description

Obtain IIS status of lower bounds of variables.

If parameter vars is Var Class object, then return IIS status of lower bound of variable. If parameter vars is list or VarArray Class object, then return a list object consisting of the IIS status of lower bounds of variables. If parameter vars is dictionary or tupledict Class object, then return indice of the specified variable as key and tupledict Class object consisting of the IIS status of lower bounds of variables as value.

Arguments

vars

The specified variables.

Example

# Retrieve IIS status of lower bounds of variable x and y.
lowerIIS = m.getVarLowerIIS([x, y])
# Retrieve IIS status of lower bounds of variables in tupledict object xx.
lowerIIS = m.getVarLowerIIS(xx)

Model.getVarUpperIIS()

Synopsis

getVarUpperIIS(vars)

Description

Obtain IIS status of upper bounds of variables.

If parameter vars is Var Class object, then return IIS status of upper bound of variable. If parameter vars is list or VarArray Class object, then return a list object consisting of the IIS status of upper bounds of variables. If parameter vars is dictionary or tupledict Class object, then return indice of the specified variable as key and tupledict Class object consisting of the IIS status of upper bounds of variables as value.

Arguments

vars

The specified variables.

Example

# Retrieve IIS status of upper bounds of variable x and y.
upperIIS = m.getVarUpperIIS([x, y])
# Retrieve IIS status of upper bounds of variables in tupledict object xx.
upperIIS = m.getVarUpperIIS(xx)

Model.getConstrLowerIIS()

Synopsis

getConstrLowerIIS(constrs)

Description

Obtain the IIS status of lower bounds of constraints.

If parameter constrs is Constraint Class object, then return IIS status of lower bound of constraint. If parameter constrs is list or ConstrArray Class object, then return a list object consisting of the IIS status of lower bounds of constraints. If parameter constrs is dictionary or tupledict Class object, then return the indice of the specified linear constraint as key and return tupledict Class object consisting of the IIS status of lower bounds of constraints.

Arguments

constrs

The specified linear constraint.

Example

# Retrieve IIS status corresponding to lower bounds of linear constraint r0 and r1 in model.
lowerIIS = m.getConstrLowerIIS([r0, r1])
# Retrieve IIS status of lower bounds of linear constraints in tupledict rr.
lowerIIS = m.getConstrLowerIIS(rr)

Model.getConstrUpperIIS()

Synopsis

getConstrUpperIIS(constrs)

Description

Obtain the IIS status of upper bounds of constraints.

If parameter constrs is Constraint Class object, then return IIS status of upper bound of constraint. If parameter constrs is list or ConstrArray Class object, then return a list object consisting of the IIS status of upper bounds of constraints. If parameter constrs is dictionary or tupledict Class object, then return the indice of the specified linear constraint as key and return tupledict Class object consisting of the IIS status of upper bounds of constraints.

Arguments

constrs

The specified linear constraint.

Example

# Retrieve IIS status corresponding to upper bounds of linear constraint r0 and r1 in model.
upperIIS = m.getConstrUpperIIS([r0, r1])
# Retrieve IIS status of upper bounds of linear constraints in tupledict rr.
upperIIS = m.getConstrUpperIIS(rr)

Model.getSOSIIS()

Synopsis

getSOSIIS(soss)

Description

Obtain the IIS status of SOS constraints.

If parameter soss is SOS Class object, then return IIS status of SOS constraint. If parameter soss is list or SOSArray Class object, then return a list object consisting of the IIS status of SOS constraints. If parameter soss is dictionary or tupledict Class object, then return the indice of the specified SOS constraint as key and return tupledict Class object consisting of the IIS status of SOS constraints.

Arguments

soss

The specified SOS constraint.

Example

# Retrieve IIS status corresponding to SOS constraint r0 and r1 in model.
sosIIS = m.getSOSIIS([r0, r1])
# Retrieve IIS status of SOS constraints in tupledict rr.
sosIIS = m.getSOSIIS(rr)

Model.getIndicatorIIS()

Synopsis

getIndicatorIIS(genconstrs)

Description

Obtain the IIS status of indicator constraints.

If parameter genconstrs is GenConstr Class object, then return IIS status of indicator constraint. If parameter genconstrs is list or GenConstrArray Class object, then return a list object consisting of the IIS status of indicator constraints. If parameter genconstrs is dictionary or tupledict Class object, then return the indice of the specified indicator constraint as key and return tupledict Class object consisting of the IIS status of indicator constraints.

Arguments

genconstrs

The specified indicator constraint.

Example

# Retrieve IIS status corresponding to indicator constraint r0 and r1 in model.
indicatorIIS = m.getIndicatorIIS([r0, r1])
# Retrieve IIS status of indicator constraints in tupledict rr.
indicatorIIS = m.getIndicatorIIS(rr)

Model.getAttr()

Synopsis

getAttr(attrname)

Description

Get the value of an attribute of model. Return a constant.

Arguments

attrname

The specified attribute name. The full list of available attributes can be found in Attributes section.

Example

# Retrieve the constant terms of objective.
objconst = m.getAttr(COPT.Attr.ObjConst)

Model.getInfo()

Synopsis

getInfo(infoname, args)

Description

Retrieve specified information.

If parameter args is Var Class object or Constraint Class object, then return info of the specified variable or constraint.

If parameter args is list or VarArray Class object or ConstrArray Class object, then return a list consisting of the specified variables or constraints.

If parameter args is dictionary or tupledict Class object, then return the indice of the specified variables or constraints as key and return tupledict Class object consisting of info corresponding to the specified variables or constraints as value.

If parameter args is MVar Class object or MConstr Class object, then return a numpy.ndarray consisting of the specified variables or constraints.

Arguments

infoname

The specified information name. The full list of available attributes can be found in Information section.

args

Variables and constraints to get information.

Example

# Retrieve lower bound information of all linear constraints in model.
lb = m.getInfo(COPT.Info.LB, m.getConstrs())
# Retrieve value information of variables x and y.
sol = m.getInfo(COPT.Info.Value, [x, y])
# Retrieve the dual variable value corresponding to linear constraint in tupledict object shipconstr.
dual = m.getInfo(COPT.Info.Dual, shipconstr)

Model.getParam()

Synopsis

getParam(paramname)

Description

Retrive the current value of the specified parameter. Return a constant.

Arguments

paramname

The name of the parameter to get access to. The full list of available attributes can be found in Parameters section.

Example

# Retrieve current value of time limit.
timelimit = m.getParam(COPT.Param.TimeLimit)

Model.getParamInfo()

Synopsis

getParamInfo(paramname)

Description

Retrieve information of the specified optimization parameter. Return a tuple object, consisiting of param name, current value, default value, minimum value, maximum value.

Arguments

paramname

Name of the specified parameter. The full list of available values can be found in Parameters section.

Example

# Retrieve information of time limit.
pname, pcur, pdef, pmin, pmax = m.getParamInfo(COPT.Param.TimeLimit)

Model.setBasis()

Synopsis

setBasis(varbasis, constrbasis)

Description

Set basis status for all variables and linear constraints in LP. The parameters varbasis and constrbasis are list objects whose number of elements is the total number of variables or linear constraints.

Arguments

varbasis

The basis status of variables.

constrbasis

The basis status of constraints.

Example

# Set basis status for all variables and linear constraints in the model.
m.setBasis(varbasis, constrbasis)

Model.setSlackBasis()

Synopsis

setSlackBasis()

Description

Set LP basis to be slack.

Example

#  Set LP basis to be slack.
m.setSlackBasis()

Model.setVarType()

Synopsis

setVarType(vars, vartypes)

Description

Set the type of specific variable.

If parameter vars is Var Class object, then parameter vartypes is Variable types constant;

If parameter vars is dictionary or tupledict Class object, then parameter vartypes can be Variable types constart, dictionary or tupledict Class object;

If parameter vars is list or VarArray Class object, then parameter vartypes can be Variable types constart or list object.

Arguments

vars

The specified variable.

vartypes

Type of the specified variable.

Example

# Set variable x as integer variable.
m.setVarType(x, COPT.INTEGER)
# Set variables x and y as binary variables.
m.setVarType([x, y], COPT.BINARY)
# Set the variables in tupledict object xdict as continuous variables.
m.setVarType(xdict, COPT.CONTINUOUS)

Model.setNames()

Synopsis

setNames(args, names)

Description

Sets the name(s) of the specified variable(s) or constraint(s).

Arguments

args

The specified variable(s) or constraint(s), which could be: Var Class , Constraint Class , QConstraint Class , PsdVar Class , PsdConstraint Class , LmiConstraint Class and GenConstr Class object, or the dictionary/list they constitute.

names

The name(s) of the specified variable(s) or constraint(s), which could be a single string or the list/dictionary corresponding to the args .

Example

# Set the name of x to "var"
m.setNames(x, "var")
#Set the name of constr1 to "c1" and the name of constr2 to "c2"
m.setNames([constr1, constr2], ["c1", "c2"])

Model.setMipStart()

Synopsis

setMipStart(vars, startvals)

Description

Set initial value for specified variables, valid only for integer programming.

If parameter vars is Var Class object, then parameter startvals is constant; If parameter vars is dictionary or tupledict Class object, then parameter startvals can be constant, dictionary or tupledict Class object; If parameter vars is list or VarArray Class object, then parameter startvals can be constant or list object.

Notice: You may want to call this method several times to input the MIP start. Please call loadMipStart() once when the input is done.

Arguments

vars

The specified variable.

startvals

Initial value of the specified variable

Example

# Set initial value of x as 1.
m.setMipStart(x, 1)
# Set initial value of x, y as 2, 3.
m.setMipStart([x, y], [2, 3])
# Set initial value of all variables in tupledict xdict as 1.
m.setMipStart(xdict, 1)

# Load initial solution to model
m.loadMipStart()

Model.loadMipStart()

Synopsis

loadMipStart()

Description

Load the currently specified initial values into model.

Notice: After calling this method, the previously initial values will be cleared, and users can continue to set initial values for specified variables.

Model.setInfo()

Synopsis

setInfo(infoname, args, newvals)

Description

Set new information value for specific variables or constraints.

If parameter args is Var Class object or Constraint Class object, then parameter newvals is constant; If parameter args is dictionary or tupledict Class object, then parameter newvals can be constant, dictionary or tupledict Class object; If parameter args is list, VarArray Class object or ConstrArray Class object, then parameter newvals can be constant or list; If parameter args is MVar Class object or MConstr Class object, then parameter newvals can be constant or numpy.ndarray.

Arguments

infoname

The specified information name. The full list of available names can be found in Information section.

args

The specified variables of constraints.

newvals

Value of the specified information.

Example

m.setInfo(COPT.Info.LB, [x, y], [1.0, 2.0])

# Set the upperbound of variable x as 1.0
m.setInfo(COPT.Info.UB, x, 1.0)
# Set the lowerbound of variables x and y as 1.0, 2.0, respectively.
m.setInfo(COPT.Info.LB, [x, y], [1.0, 2.0])
# Set the objective of all variables in tupledict xdict as 0.
m.setInfo(COPT.Info.OBJ, xdict, 0.0)

Model.setParam()

Synopsis

setParam(paramname, newval)

Description

Set the value of a parameter to a specific value.

Arguments

paramname

The name of parameter to be set. The list of available names can be found in Parameters section.

newval

New value of parameter.

Example

# Set time limit of solving to 1 hour.
 m.setParam(COPT.Param.TimeLimit, 3600)

Model.resetParam()

Synopsis

resetParam()

Description

Reset all parameters to their default values.

Example

# Reset all parameters to their default values.
m.resetParam()

Model.read()

Synopsis

read(filename)

Description

Determine the type of data by the file suffix and read it into a model.

Currently, it supports MPS files (suffix '.mps' or '.mps.gz'), LP files (suffix '.lp' or '.lp.gz'), SDPA files (suffix '.dat-s' or '.dat-s.gz'), CBF files (suffix '.cbf' or '.cbf.gz'), COPT binary format files (suffix '.bin'), basis files (suffix '.bas'), result files (suffix '.sol'), start files (suffix '.mst'), and parameter files (suffix '.par').

Arguments

filename

Name of the file to be read.

Example

# Read MPS format model file
m.read('test.mps.gz')
# Read LP format model file
m.read('test.lp.gz')
# Read COPT binary format model file
m.read('test.bin')
# Read basis file
m.read('testlp.bas')
# Read solution file
m.read('testmip.sol')
# Read start file
m.read('testmip.mst')
# Read paramter file
m.read('test.par')

Model.readMps()

Synopsis

readMps(filename)

Description

Read MPS file to model.

Arguments

filename

The name of the MPS file to be read.

Example

# Read file "test.mps.gz" according to mps file format
m.readMps('test.mps.gz')
# Read file "test.lp.gz" according mps file format
m.readMps('test.lp.gz')

Model.readLp()

Synopsis

readLp(filename)

Description

Read a file to model according to LP file format.

Arguments

filename

Name of the LP file to be read.

Example

# Read file"test.mps.gz" according to LP file format
m.readLp('test.mps.gz')
# Read file"test.lp.gz" according to LP file format
m.readLp('test.lp.gz')

Model.readSdpa()

Synopsis

readSdpa(filename)

Description

Read a file to model according to SDPA file format.

Arguments

filename

Name of the SDPA file to be read.

Example

# Read file"test.dat-s" according to SDPA file format
m.readSdpa('test.dat-s')

Model.readCbf()

Synopsis

readCbf(filename)

Description

Read a file to model according to CBF file format.

Arguments

filename

Name of the CBF file to be read.

Example

# Read file"test.cbf" according to CBF file format
m.readCbf('test.cbf')

Model.readBin()

Synopsis

readBin(filename)

Description

Read COPT binary format file to model.

Arguments

filename

The name of the COPT binary format file to be read.

Example

# Read file "test.bin" according COPT binary file format
m.readBin('test.bin')

Model.readSol()

Synopsis

readSol(filename)

Description

Read a file to model according to solution file format.

Notice: The default solution value is 0, i.e. a partial solution will be automatically filled in with zeros. If read successfully, then the values read can be act as initial solution for integer programming.

Arguments

filename

Name of file to be read.

Example

# Read file "testmip.sol" according to solution file format.
m.readSol('testmip.sol')
# Read file testmip.txt" according to solution file format.
m.readSol('testmip.txt')

Model.readBasis()

Synopsis

readBasis(filename)

Description

Read basis status of variables and linear constraints to model accoring to basis solution format, valid only for linear programming.

Arguments

filename

The name of the basis file to be read.

Example

# Read file "testmip.bas" to basis solution format
m.readBasis('testmip.bas')
# Read file "testmip.txt" to basis solution format
m.readBasis('testmip.txt')

Model.readMst()

Synopsis

readMst(filename)

Description

Read initial solution data to model according to initial solution file format.

Notice: If read successfully, the read value will be act as initial solution for integer programming model. Variable values may not be specified completely, if the value of variable is specified for multiple times, the last specified value is used.

Arguments

filename

Name of the file to be read.

Example

# Read file "testmip.mst" according to initial solution file format.
m.readMst('testmip.mst')
# Read file "testmip.txt" according to initial solution file format.
m.readMst('testmip.txt')

Model.readParam()

Synopsis

readParam(filename)

Description

Read optimization parameters to model according to parameter file format.

Notice: If any optimization parameter is specified multiple times, the last spcified value is used.

Arguments

filename

The name of the parameter file to be read.

Example

# Read file "testmip.par" according to parameter file format.
m.readParam('testmip.par')
# Read file "testmip.txt" according to parameter file format.
m.readParam('testmip.txt')

Model.readTune()

Synopsis

readTune(filename)

Description

Read the tuning parameters and combine them into the model according to the tuning file format.

Arguments

filename

The name of the file to be read.

Example

Model.write()

Synopsis

write(filename)

Description

Currently, COPT supports writing of MPS files (suffix '.mps' ), LP files (suffix '.lp'), CBF files (suffix '.cbf'), COPT binary format files (suffix '.bin'), basis files (suffix '.bas'), LP solution files (suffix '.sol'), initial solution files (suffix '.mst'), and parameter files (suffix '.par').

Arguments

filename

The file name to be written.

Example

# Write MPS file
m.write('test.mps')
# Write LP file
m.write('test.lp')
# Write COPT binary format file
m.write('test.bin')
# Write basis file
m.write('testlp.bas')
# Write solution file
m.write('testmip.sol')
# Write initial solution file
m.write('testmip.mst')
# Write parameter file
m.write('test.par')

Model.writeMps()

Synopsis

writeMps(filename)

Description

Write current model into an MPS file.

Arguments

filename

The name of the MPS file to be written.

Example

# Write MPS model file "test.mps"
m.writeMps('test.mps')

Model.writeMpsStr()

Synopsis

writeMpsStr()

Description

Write current model into a buffer as MPS format.

Example

# Write model to buffer 'buff' and print model
buff = m.writeMpsStr()
print(buff.getData())

Model.writeLp()

Synopsis

writeLp(filename)

Description

Write current optimization model to a LP file.

Arguments

filename

The name of the LP file to be written.

Example

# Write LP model file "test.lp"
m.writeLp('test.lp')

Model.writeCbf()

Synopsis

writeCbf(filename)

Description

Write current optimization model to a CBF file.

Arguments

filename

The name of the CBF file to be written.

Example

# Write CBF model file "test.cbf"
m.writeCbf('test.cbf')

Model.writeBin()

Synopsis

writeBin(filename)

Description

Write current model into an COPT binary format file.

Arguments

filename

The name of the COPT binary format file to be written.

Example

# Write COPT binary format model file "test.bin"
m.writeBin('test.bin')

Model.writeIIS()

Synopsis

writeIIS(filename)

Description

Write current irreducible inconsistent subsystem into an IIS file.

Arguments

filename

The name of the IIS file to be written.

Example

# Write IIS file "test.iis"
m.writeIIS('test.iis')

Model.writeRelax()

Synopsis

writeRelax(filename)

Description

Write the feasibility relaxation model into a Relax file.

Arguments

filename

The name of the Relax file to be written.

Example

# Write Relax file "test.relax"
m.writeRelax('test.relax')

Model.writeSol()

Synopsis

writeSol(filename)

Description

Output the model solution to a solution file.

Arguments

filename

The name of the solution file to be written.

Example

# Write solution file "test.sol"
m.writeSol('test.sol')

Model.writePoolSol()

Synopsis

writePoolSol(isol, filename)

Description

Output selected pool solution to a solution file.

Arguments

isol

Index of pool solution.

filename

The name of the solution file to be written.

Example

# Write 1-th pool solution to solution file "poolsol_1.sol"
m.writePoolSol('poolsol_1.sol')

Model.writeBasis()

Synopsis

writeBasis(filename)

Description

Write the LP basic solution to a basis file.

Arguments

filename

The name of the basis file to be written.

Example

# Write the basis file "testlp.bas"
m.writeBasis('testlp.bas')

Model.writeMst()

Synopsis

writeMst(filename)

Description

For integer programming models, write the best integer solution currently to the initial solution file. If there are no integer solutions, then the first set of initial solution stored in model is output.

Arguments

filename

Name of the file to be written.

Example

# Output initial solution file "testmip.mst"
m.writeMst('testmip.mst')

Model.writeParam()

Synopsis

writeParam(filename)

Description

Output modified parameters to a parameter file.

Arguments

filename

The name of the parameter file to be written.

Example

# Output parameter file "testmip.par"
m.writeParam('testmip.par')

Model.writeTuneParam()

Synopsis

writeTuneParam(idx, filename)

Description

Output the parameter tuning result of the specified number to the parameter file.

Arguments

idx

Parameter tuning result number.

filename

The name of the parameter file to be output.

Example

Model.setLogFile()

Synopsis

setLogFile(logfile)

Description

Set the optimizer log file.

Arguments

logfile

The log file.

Example

# Set the log file as "copt.log"
m.setLogFile('copt.log')

Model.setLogCallback()

Synopsis

setLogCallback(logcb)

Description

Set the call back function of log.

Arguments

logcb

Call back function of log.

Example

# Set the call back function of log as a python function 'logcbfun'.
m.setLogCallback(logcbfun)

Model.solve()

Synopsis

solve()

Description

Solve an optimization problem.

Example

# Solve the model.
m.solve()

Model.solveLP()

Synopsis

solveLP()

Description

Solve LP model. If the model is integer programming, then the model will be solved as LP.

Example

# Solve a model calling LP solver.
m.solveLP()

Model.computeIIS()

Synopsis

computeIIS()

Description

Compute IIS for infeasible model.

Example

# Compute IIS for infeasible model.
m.computeIIS()

Model.feasRelax()

Synopsis

feasRelax(vars, lbpen, ubpen, constrs, rhspen, uppen=None)

Description

Compute the feasibilty relaxation of an infeasible model

Arguments

vars

Variables to relax.

lbpen

The penalty relating to lower bounds. If None, no lower bound violations are allowed. If a variable’s penalty is COPT.INFINITY, lower bound violation is not allowed on it.

ubpen

The penalty relating to upper bounds. If None, no upper bound violations are allowed. If a variable’s penalty is COPT.INFINITY, upper bound violation is not allowed on it.

constrs

Constraints to relax.

rhspen

The penalty relating to constraints. If None, no constraint violations are allowed. If a constraint’s penalty is COPT.INFINITY, it’s not allowed to be violated.

uppen

The penalty relating to the upper bound of bilateral constraints. If None, specified by rhspen; If a constraint’s penalty is COPT.INFINITY, constraint upper bound violation is not allowed on it.

Example

# compute feasibility relaxation for model m
m.feasRelax(vars, lbpen, ubpen, constrs, rhspen)

Model.feasRelaxS()

Synopsis

feasRelaxS(vrelax, crelax)

Description

Compute the feasibilty relaxation of an infeasible model

Arguments

vrelax

Whether to relax variables.

crelax

Whether to relax constraints.

Example

# Compute the feasibilty relaxation of model m
m.feasRelaxS(True, True)

Model.tune()

Synopsis

tune()

Description

Parameter tuning of the model.

Example

Model.loadTuneParam()

Synopsis

loadTuneParam(idx)

Description

Load the parameter tuning results of the specified number into the model.

Example

Model.interrupt()

Synopsis

interrupt()

Description

Interrupt solving process of current problem.

Example

# Interrupt the solving process.
m.interrupt()

Model.remove()

Synopsis

remove(args)

Description

Remove variables or constraints from a model.

To remove variable, then parameter args can be Var Class object, VarArray Class object, list, dictionary or tupledict Class object.

To remove linear constraint, then parameter args can be Constraint Class object, ConstrArray Class object, list, dictionary or tupledict Class object.

To remove SOS constraint, then parameter args can be SOS Class object, SOSArray Class object, list, dictionary or tupledict Class object.

To remove Second-Order-Cone constraints, then parameter args can be Cone Class object, ConeArray Class object, list, dictionary or tupledict Class object.

To remove exponential cone constraints, then parameter args can be ExpCone Class object, ExpConeArray Class object, list, dictionary or tupledict Class object.

To remove quadratic constraints, then parameter args can be QConstraint Class object, QConstrArray Class object, list, dictionary or tupledict Class object.

To remove positive semi-definite constraints, then parameter args can be PsdConstraint Class object, PsdConstrArray Class object, list, dictionary or tupledict Class object.

To remove indicator constraint, then parameter args can be GenConstr Class object, GenConstrArray Class object, list, dictionary or tupledict Class object.

To remove LMI constraint, then parameter args can be LmiConstraint Class object, LmiConstrArray Class object, list, dictionary or tupledict Class object.

To remove matrix variables or matrix constriants, then parameter args can be MVar Class object, MConstr Class object.

Arguments

args

Variables or constraints to be removed.

Example

# Remove linear constraint conx
m.remove(conx)
# Remove variables x and y
m.remove([x, y])

Model.reset()

Synopsis

reset()

Description

Reset the result information of the model.

Example

# Reset the result information in model.
m.reset()

Model.resetAll()

Synopsis

resetAll()

Description

Reset the result and other additional information of the model, such as MIP start, IIS, etc. By executing this function, the information that needs to be calculated of the model will be all cleared, only the original model itself will be kept.

Example

# Reset the result and other additional information of the model
m.reset()

Model.clear()

Synopsis

clear()

Description

Clear all content of the whole model. By executing this function, all content of the whole model will be cleared, including the added variables, objective, and constraints.

Example

# Clear all content of the model.
m.clear()

Model.clone()

Synopsis

clone()

Description

Create a deep copy of an existing model. Return a Model Class object.

Example

# Create a deep copy of model
mcopy = m.clone()

Model.setCallback()

Synopsis

setCallback(cb, cbctx)

Description

Set the callback function of the model.

Arguments

cb

Callback Class object.

cbctx

Callback context. Please refer to Callback context .

Example

cb = CoptCallback()
model.setCallback(cb, COPT.CBCONTEXT_MIPSOL)

Var Class

For easy access to information of variables, Var object provides methods such as Var.LB. The full list of information can be found in the Information section. For convenience, information can be accessed by names in original case or lowercase.

In addition, you can also access the value of the variable through Var.x, the variable type through Var.vtype, the name of the variable through Var.name, the Reduced cost value of the variable in LP through Var.rc, the basis status through Var.basis, and the index of the variable in the coefficient matrix through Var.index the Reduced cost value of the variable in LP through Var.rc, the basis status through Var.basis, and the index of the variable in the coefficient matrix through Var.index.

For the model-related information of the variables, as well as the variable type and name, the user can set the corresponding information value in the form of "Var.LB = 0.0".

Var object contains related operations of COPT variables and provides the following methods:

Var.getType()

Synopsis

getType()

Description

Retrieve the type of variable.

Example

# Retrieve the type of variable v
vtype = v.getType()

Var.getName()

Synopsis

getName()

Description

Retrieve the name of variable.

Example

# Retrieve the name of variable v
varname = v.getName()

Var.getBasis()

Synopsis

getBasis()

Description

Retrieve the basis status of variable.

Example

# Retrieve the basis status of variable v
varbasis = v.getBasis()

Var.getLowerIIS()

Synopsis

getLowerIIS()

Description

Retrieve the IIS status of lower bound of variable.

Example

# Retrieve the IIS status of lower bound of variable v
lowerIIS = v.getLowerIIS()

Var.getUpperIIS()

Synopsis

getUpperIIS()

Description

Retrieve the IIS status of upper bound of variable.

Example

# Retrieve the IIS status of upper bound of variable v
upperIIS = v.getUpperIIS()

Var.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of the variable in the coefficient matrix.

Example

#  Retrieve the subscript of variable v
vindex = v.getIdx()

Var.setType()

Synopsis

setType(newtype)

Description

Set the type of variable.

Arguments

newtype

The type of variable to be set. Please refer to Variable types section for possible values.

Example

# Set the type of variable v
v.setType(COPT.BINARY)

Var.setName()

Synopsis

setName(newname)

Description

Set the name of variable.

Arguments

newname

The name of variable to be set.

Example

# Set the name of variable v
v.setName(COPT.BINARY)

Var.getInfo()

Synopsis

getInfo(infoname)

Description

Retrieve specified information. Return a constant.

Arguments

infoname

The name of the information. Please refer to Information for possible values.

Example

# Get lowerbound of variable x
x.getInfo(COPT.Info.LB)

Var.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Set new information value for a variable.

Arguments

infoname

The name of the information to be set. Please refer to Information section for possible values.

newval

New information value to set.

Example

# Set the lower bound of variable x
x.setInfo(COPT.Info.LB, 1.0)

Var.remove()

Synopsis

remove()

Description

Delete the variable from model.

Example

# Delete variable 'x'
x.remove()

VarArray Class

To facilitate users to operate on multiple Var Class objects, the Python interface of COPT provides VarArray object with the following methods:

VarArray()

Synopsis

VarArray(vars=None)

Description

Create a VarArray Class object.

If parameter vars is None, then create an empty VarArray Class object, otherwise initialize the new created VarArray Class object based on vars.

Arguments

vars

Variables to be added. Optional, None by default. vars can be Var Class object, VarArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty VarArray object
vararr = VarArray()
# Create an empty VarArray object and initialize variables x, y.
vararr = VarArray([x, y])

VarArray.pushBack()

Synopsis

pushBack(vars)

Description

Add single or multiple Var Class objects.

Arguments

vars

Variables to be applied. vars can be Var Class object, VarArray Class object, list, dictionary or tupledict Class object.

Example

# Add variable x to vararr
vararr.pushBack(x)
# Add variables x and y to vararr
vararr.pushBack([x, y])

VarArray.getVar()

Synopsis

getVar(idx)

Description

Retrieve a variable from an index in a VarArray Class object. Return a Var Class object.

Arguments

idx

Subscript of the specified variable in VarArray Class object, starting with 0.

Example

# Get the variable with subscript of 1 in vararr
 vararr.getVar(1)

VarArray.getAll()

Synopsis

getAll()

Description

Retrieve all variables in VarArray Class object. Returns a list object.

Example

# Get all variables in 'vararr'
varall = vararr.getAll()

VarArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of variables in VarArray Class object.

Example

# Retrieve the number of variables in vararr.
arrsize = vararr.getSize()

PsdVar Class

PsdVar object contains related operations of COPT positive semi-definite variables and provides the following methods:

PsdVar.getName()

Synopsis

getName()

Description

Retrieve the name of positive semi-definite variable.

Example

# Retrieve the name of variable v
varname = v.getName()

PsdVar.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of the variable in the model.

Example

# Retrieve the subscript of variable v
vindex = v.getIdx()

PsdVar.getDim()

Synopsis

getDim()

Description

Retrieve the dimension of positive semi-definite variable.

Example

# Retrieve the dimension of variable "v"
vdim = v.getDim()

PsdVar.getLen()

Synopsis

getLen()

Description

Retrieve the length of the expanded positive semi-definite variable.

Example

# Retrieve the length of the expanded positive semi-definite variable "v"
vlen = v.getLen()

PsdVar.setName()

Synopsis

setName(newname)

Description

Set the name of positive semi-definite variable.

Arguments

newname

The name of positive semi-definite variable to be set.

Example

# Set the name of variable v
v.setName('v')

PsdVar.getInfo()

Synopsis

getInfo(infoname)

Description

Retrieve specified information of positive semi-definite variable. Return a list.

Arguments

infoname

The name of the information. Please refer to Information for possible values.

Example

# Get solution values of positive semi-definite variable x
sol = x.getInfo(COPT.Info.Value)

PsdVar.remove()

Synopsis

remove()

Description

Delete the positive semi-definite variable from model.

Example

# Delete variable 'x
x.remove()

PsdVar.shape

Synopsis

shape

Description

Shape of the PsdVar object.

Return value

Integer tuple.

PsdVar.size

Synopsis

size

Description

Size of the PsdVar object.

Return value

Integer tuple.

PsdVar.dim

Synopsis

dim

Description

Dimension of the PsdVar object.

Return value

Integer.

PsdVar.len

Synopsis

len

Description

Flattened length of the PsdVar object.

Return value

Integer.

PsdVarArray Class

To facilitate users to operate on multiple PsdVar Class objects, the Python interface of COPT provides PsdVarArray object with the following methods:

PsdVarArray()

Synopsis

PsdVarArray(vars=None)

Description

Create a PsdVarArray Class object.

If parameter vars is None, then create an empty PsdVarArray Class object, otherwise initialize the new created PsdVarArray Class object based on vars.

Arguments

vars

Positive semi-definite variables to be added. Optional, None by default. vars can be PsdVar Class object, PsdVarArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty PsdVarArray object
vararr = PsdVarArray()
# Create a PsdVarArray object containing positive semi-definite variables x, y.
vararr = PsdVarArray([x, y])

PsdVarArray.pushBack()

Synopsis

pushBack(var)

Description

Add single or multiple PsdVar Class objects.

Arguments

var

Postive semi-definite variables to be applied. vars can be PsdVar Class object, PsdVarArray Class object, list, dictionary or tupledict Class object.

Example

# Add variable x to vararr
vararr.pushBack(x)
# Add variables x and y to vararr
vararr.pushBack([x, y])

PsdVarArray.getPsdVar()

Synopsis

getPsdVar(idx)

Description

Retrieve a positive semi-definite variable from an index in a PsdVarArray Class object. Return a PsdVar Class object.

Arguments

idx

Subscript of the specified positive semi-definite variable in PsdVarArray Class object, starting with 0.

Example

# Get the positive semi-definite variable with subscript of 1 in vararr
var = vararr.getPsdVar(1)

PsdVarArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of positive semi-definite variables in PsdVarArray Class object.

Example

# Retrieve the number of variables in vararr.
arrsize = vararr.getSize()

SymMatrix Class

SymMatrix object contains related operations of COPT symmetric matrices and provides the following methods:

SymMatrix.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of the symmetric matrix in the model.

Example

# Retrieve the subscript of symmetric matrix mat
matidx = mat.getIdx()

SymMatrix.getDim()

Synopsis

getDim()

Description

Retrieve the dimension of symmetric matrix.

Example

# Retrieve the dimension of symmetric matrix "mat".
matdim = mat.getDim()

SymMatrixArray Class

To facilitate users to operate on multiple SymMatrix Class objects, the Python interface of COPT provides SymMatrixArray object with the following methods:

SymMatrixArray()

Synopsis

SymMatrixArray(mats=None)

Description

Create a SymMatrixArray Class object.

If parameter mats is None, then create an empty SymMatrixArray Class object, otherwise initialize the new created SymMatrixArray Class object based on mats.

Arguments

mats

mats can be SymMatrix Class object, SymMatrixArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty SymMatrixArray object
matarr = SymMatrixArray()
# Create a SymMatrixArray object containing matx, maty.
matarr = SymMatrixArray([matx, maty])

SymMatrixArray.pushBack()

Synopsis

pushBack(mat)

Description

Add single or multiple SymMatrix Class objects.

Arguments

mat

Symmetric matrices to be applied. mat can be SymMatrix Class object, SymMatrixArray Class object, list, dictionary or tupledict Class object.

Example

# Add symmetric matrix matx to matarr
matarr.pushBack(matx)
# Add symmetric matrices matx and maty to matarr
matarr.pushBack([matx, maty])

SymMatrixArray.getMatrix()

Synopsis

getMatrix(idx)

Description

Retrieve a symmetric matrix from an index in a SymMatrixArray Class object. Return a SymMatrix Class object.

Arguments

idx

Subscript of the specified symmetric matrix in SymMatrixArray Class object, starting with 0.

Example

# Get the symmetric matrix with subscript of 1 in matarr
mat = matarr.getMatrix(1)

SymMatrixArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of symmetric matrices in SymMatrixArray Class object.

Example

# Retrieve the number of symmetric matrices in matarr.
arrsize = matarr.getSize()

Constraint Class

For easy access to information of constraints, Constraint class provides methods such as Constraint.LB. The supported information can be found in Information section. For convenience, information can be queried by names in original case or lowercase.

In addition, you can access the name of the constraint through Constraint.name, the dual value of the constraint in LP through Constraint.pi, the basis status of the constraint through Constraint.basis, and the index in the coefficient matrix through Constraint.index.

For the model-related information and constraint name, the user can also set the corresponding information in the form of "Constraint.lb = -100".

Constraint object contains related operations of COPT constraints and provides the following methods:

Constraint.getName()

Synopsis

getName()

Description

Retrieve the name of linear constraint.

Example

# Retrieve the name of linear constraint 'con'.
conname = con.getName()

Constraint.getBasis()

Synopsis

getBasis()

Description

Retrieve the basis status of linear constraint.

Example

# Retrieve the basis status of linear constraint 'con'.
conbasis = con.getBasis()

Constraint.getLowerIIS()

Synopsis

getLowerIIS()

Description

Retrieve the IIS status of lower bound of linear constraint.

Example

# Retrieve the IIS status of lower bound of linear constraint 'con'.
lowerIIS = con.getLowerIIS()

Constraint.getUpperIIS()

Synopsis

getUpperIIS()

Description

Retrieve the IIS status of upper bound of linear constraint.

Example

# Retrieve the IIS status of upper bound of linear constraint 'con'.
upperIIS = con.getUpperIIS()

Constraint.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of linear constraint in coefficient matrix.

Example

# Retrieve the subscript of linear constraint con.
conidx = con.getIdx()

Constraint.setName()

Synopsis

setName(newname)

Description

Set the name of linear constraint.

Arguments

newname

The name of constraint to be set.

Example

# Set the name of linear constraint 'con'.
con.setName('con')

Constraint.getInfo()

Synopsis

getInfo(infoname)

Description

Retrieve specified information. Return a constant.

Arguments

infoname

Name of the information to be obtained. Please refer to Information section for possible values.

Example

# Get the lower bound of linear constraint con
conlb = con.getInfo(COPT.Info.LB)

Constraint.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Set new information value to the specified constraint.

Arguments

infoname

The name of the information to be set. Please refer to Information section for possible values.

newval

New information value to be set.

Example

# Set the lower bound of linear constraint con
con.setInfo(COPT.Info.LB, 1.0)

Constraint.remove()

Synopsis

remove()

Description

Delete the linear constraint from model.

Example

# Delete the linear constraint 'conx'
conx.remove()

ConstrArray Class

To facilitate users to operate on multiple Constraint Class objects, the Python interface of COPT provides ConstrArray class with the following methods:

ConstrArray()

Synopsis

ConstrArray(constrs=None)

Description

Create a ConstrArray Class object.

If parameter constrs is None, the create an empty ConstrArray Class object, otherwise initialize the newly created ConstrArray Class object with parameter constrs

Arguments

constrs

Linear constraints to be added. None by default.

constrs can be Constraint Class object, ConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty ConstrArray object
conarr = ConstrArray()
# Create an ConstrArray object initialized with linear constraint conx and cony
conarr = ConstrArray([conx, cony])

ConstrArray.pushBack()

Synopsis

pushBack(constrs)

Description

Add single or multiple Constraint Class objects.

Arguments

constrs

Linear constraints to be applied. constrs can be Constraint Class object, ConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Add linear constraint r to conarr
conarr.pushBack(r)
# Add linear constraint r0 and r1 to conarr
conarr.pushBack([r0, r1])

ConstrArray.getConstr()

Synopsis

getConstr(idx)

Description

Retrieve the linear constraint according to its subscript in ConstrArray Class object. Return a Constraint Class object.

Arguments

idx

Subscript of the desired constraint in ConstrArray Class object, starting with 0.

Example

# Retrieve the linear constraint with subscript 1  in conarr
conarr.getConstr(1)

ConstrArray.getAll()

Synopsis

getAll()

Description

Retrieve all linear constraints in ConstrArray Class object. Returns a list object.

Example

# Get all linear constraints in 'conarr'
cons = conarr.getAll()

ConstrArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in ConstrArray Class object.

Example

# Get the number of linear constraints in conarr
arrsize = conarr.getSize()

ConstrBuilder Class

ConstrBuilder object contains operations related to temporary constraints when building constraints, and provides the following methods:

ConstrBuilder()

Synopsis

ConstrBuilder()

Description

Create an empty ConstrBuilder Class object

Example

# Create an empty linear constraint builder
constrbuilder = ConstrBuilder()

ConstrBuilder.setBuilder()

Synopsis

setBuilder(expr, sense, rhs)

Description

Set expression and constraint type for linear constraint builder.

Arguments

expr

The expression to be set, which can be Var Class expression or LinExpr Class expression.

sense

Sense of constraint. The full list of available tyeps can be found in Constraint type section.

rhs

Right hand side of constraint.

Example

# Set the expresson of linear constraint builder as: x+y==1
constrbuilder.setBuilder(x + y, COPT.EQUAL, 1)

ConstrBuilder.getExpr()

Synopsis

getExpr()

Description

Retrieve the expression of a linear constraint builder object.

Example

#  Retrieve the expression of a linear constraint builder
linexpr = constrbuilder.getExpr()

ConstrBuilder.getSense()

Synopsis

getSense()

Description

Retrieve the constraint sense of linear constraint builder object.

Example

# Retrieve the constraint sense of linear constraint builder object.
consense = constrbuilder.getSense()

ConstrBuilderArray Class

To facilitate users to operate on multiple ConstrBuilder Class objects, the Python interface of COPT provides ConstrArray object with the following methods:

ConstrBuilderArray()

Synopsis

ConstrBuilderArray(constrbuilders=None)

Description

Create a ConstrBuilderArray Class object.

If parameter constrbuilders is None, then create an empty ConstrBuilderArray Class object, otherwise initialize the newly created ConstrBuilderArray Class object by parameter constrbuilders.

Arguments

constrbuilders

Linear constraint builder to be added. Optional, None by default. It can be ConstrBuilder Class object, ConstrBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty ConstrBuilderArray object.
conbuilderarr = ConstrBuilderArray()
# Create a ConstrBuilderArray object and initialize it with builders: conbuilderx and conbuildery
conbuilderarr = ConstrBuilderArray([conbuilderx, conbuildery])

ConstrBuilderArray.pushBack()

Synopsis

pushBack(constrbuilder)

Description

Add single or multiple ConstrBuilder Class objects.

Arguments

constrbuilder

Builder of linear constraint to be added, which can be ConstrBuilder Class object, ConstrBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Add linear constraint builder conbuilderx to conbuilderarr
conbuilderarr.pushBack(conbuilderx)
# Add linear constraint builders conbuilderx and conbuildery to conbuilderarr
conbuilderarr.pushBack([conbuilderx, conbuildery])

ConstrBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve a temporary constraint from its index in ConstrBuilderArray Class object. Return a ConstrBuilder Class object.

Retrieve the corresponding builder object according to the subscript of linear constraint builder in ConstrBuilderArray Class object.

Arguments

idx

Subscript of the linear constraint builder in the ConstrBuilderArray Class object, starting with 0.

Example

# Retrieve the builder with subscript 1 in conbuilderarr
conbuilder = conbuilderarr.getBuilder(1)

ConstrBuilderArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in ConstrBuilderArray Class object.

Example

# Get the number of builders in conbuilderarr
arrsize = conbuilderarr.getSize()

QConstraint Class

For easy access to information of quadratic constraints, QConstraint class provides methods such as QConstraint.index. The supported information can be found in Information section. For convenience, information can be queried by names in original case or lowercase.

In addition, you can access the name of the quadratic constraint through QConstraint.name, and the index in the model through QConstraint.index.

For the model-related information and constraint name, the user can also set the corresponding information in the form of "QConstraint.rhs = -100".

QConstraint object contains related operations of COPT quadratic constraints and provides the following methods:

QConstraint.getName()

Synopsis

getName()

Description

Retrieve the name of quadratic constraint.

Example

# Retrieve the name of quadratic constraint 'qcon'
qconname = qcon.getName()

QConstraint.getRhs()

Synopsis

getRhs()

Description

Retrieve the right hand side of quadratic constraint.

Example

# Retrieve the RHS of quadratic constraint 'qcon'
qconrhs = qcon.getRhs()

QConstraint.getSense()

Synopsis

getSense()

Description

Retrieve the type of quadratic constraint.

Example

# Retrieve the type of quadratic constraint 'qcon'
qconsense = qcon.getSense()

QConstraint.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of quadratic constraint.

Example

# Retrieve the subscript of quadratic constraint 'qcon'
qconidx = qcon.getIdx()

QConstraint.setName()

Synopsis

setName(newname)

Description

Set the name of quadratic constraint.

Arguments

newname

The name of quadratic constraint to be set.

Example

# Set the name of quadratic constraint 'qcon'.
qcon.setName('qcon')

QConstraint.setRhs()

Synopsis

setRhs(rhs)

Description

Set the right hand side of quadratic constraint.

Arguments

rhs

The right hand side of quadratic constraint to be set.

Example

# Set the RHS of quadratic constraint 'qcon' to 0.0
qcon.setRhs(0.0)

QConstraint.setSense()

Synopsis

setSense(sense)

Description

Set the sense of quadratic constraint.

Arguments

sense

The sense of quadratic constraint to be set.

Example

# Set the sense of quadratic constraint 'qcon' to <=
qcon.setSense(COPT.LESS_EQUAL)

QConstraint.getInfo()

Synopsis

getInfo(infoname)

Description

Retrieve specified information. Return a constant.

Arguments

infoname

Name of the information to be obtained. Please refer to Information section for possible values.

Example

# Get the row activity of quadratic constraint 'qcon'
qconlb = qcon.getInfo(COPT.Info.Slack)

QConstraint.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Set new information value to the specified quadratic constraint.

Arguments

infoname

The name of the information to be set. Please refer to Information section for possible values.

newval

New information value to be set.

Example

# Set the lower bound of quadratic constraint 'qcon'
qcon.setInfo(COPT.Info.LB, 1.0)

Constraint.remove()

Synopsis

remove()

Description

Delete the quadratic constraint from model.

Example

# Delete the quadratic constraint 'qconx'
qconx.remove()

QConstrArray Class

To facilitate users to operate on multiple QConstraint Class objects, the Python interface of COPT provides QConstrArray class with the following methods:

QConstrArray()

Synopsis

QConstrArray(qconstrs=None)

Description

Create a QConstrArray Class object.

If parameter qconstrs is None, the create an empty QConstrArray Class object, otherwise initialize the newly created QConstrArray Class object with parameter qconstrs

Arguments

qconstrs

Quadratic constraints to be added. None by default.

qconstrs can be QConstraint Class object, QConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty QConstrArray object
qconarr = QConstrArray()
# Create an QConstrArray object initialized with quadratic constraint qconx and qcony
qconarr = QConstrArray([qconx, qcony])

QConstrArray.pushBack()

Synopsis

pushBack(constr)

Description

Add single or multiple QConstraint Class object.

Arguments

constr

Quadratic constraints to be added. None by default.

qconstrs can be QConstraint Class object, QConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Add quadratic constraint qr to conarr
qconarr.pushBack(qr)
# Add quadratic constraint qr0 and qr1 to qconarr
qconarr.pushBack([qr0, qr1])

QConstrArray.getQConstr()

Synopsis

getQConstr(idx)

Description

Retrieve the quadratic constraint according to its subscript in QConstrArray Class object. Return a QConstraint Class object.

Arguments

idx

Subscript of the desired quadratic constraint in QConstrArray Class object, starting with 0.

Example

# Retrieve the quadratic constraint with subscript 1  in qconarr
qcon = qconarr.getQConstr(1)

QConstrArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in QConstrArray Class object.

Example

# Get the number of quadratic constraints in qconarr
qarrsize = qconarr.getSize()

QConstrBuilder Class

QConstrBuilder object contains operations related to temporary constraints when building quadratic constraints, and provides the following methods:

QConstrBuilder()

Synopsis

QConstrBuilder()

Description

Create an empty QConstrBuilder Class object.

Example

# Create an empty quadratic constraint builder
qconstrbuilder = QConstrBuilder()

QConstrBuilder.setBuilder()

Synopsis

setBuilder(expr, sense, rhs)

Description

Set expression, constraint type and RHS for quadratic constraint builder.

Arguments

expr

The expression to be set, which can be Var Class object, LinExpr Class object or QuadExpr Class object.

sense

Sense of quadratic constraint. The full list of available tyeps can be found in Constraint type section.

rhs

Right hand side of quadratic constraint.

Example

# Set the expresson of quadratic constraint builder as: x+y, sense of constraint as equal and RHS as 1
qconstrbuilder.setBuilder(x + y, COPT.LESS_EQUAL, 1.0)

QConstrBuilder.getQuadExpr()

Synopsis

getQuadExpr()

Description

Retrieve the expression of a quadratic constraint builder object.

Example

#  Retrieve the expression of a quadratic constraint builder
quadexpr = constrbuilder.getQuadExpr()

QConstrBuilder.getSense()

Synopsis

getSense()

Description

Retrieve the constraint sense of quadratic constraint builder object.

Example

# Retrieve the constraint sense of quadratic constraint builder object.
qconsense = qconstrbuilder.getSense()

QConstrBuilderArray Class

To facilitate users to operate on multiple QConstrBuilder Class objects, the Python interface of COPT provides QConstrArray object with the following methods:

QConstrBuilderArray()

Synopsis

QConstrBuilderArray(qconstrbuilders=None)

Description

Create a QConstrBuilderArray Class object.

If parameter qconstrbuilders is None, then create an empty QConstrBuilderArray Class object, otherwise initialize the newly created QConstrBuilderArray Class object by parameter qconstrbuilders.

Arguments

qconstrbuilders

Quadratic constraint builder to be added. Optional, None by default. It can be QConstrBuilder Class object, QConstrBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty QConstrBuilderArray object.
qconbuilderarr = QConstrBuilderArray()
# Create a QConstrBuilderArray object and initialize it with builders: qconbuilderx and qconbuildery
qconbuilderarr = QConstrBuilderArray([qconbuilderx, qconbuildery])

QConstrBuilderArray.pushBack()

Synopsis

pushBack(qconstrbuilder)

Description

Add single or multiple QConstrBuilder Class objects.

Arguments

qconstrbuilder

Builder of quadratic constraint to be added, which can be QConstrBuilder Class object, QConstrBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Add quadratic constraint builder qconbuilderx to qconbuilderarr
qconbuilderarr.pushBack(qconbuilderx)
# Add quadratic constraint builders qconbuilderx and qconbuildery to qconbuilderarr
qconbuilderarr.pushBack([qconbuilderx, qconbuildery])

QConstrBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve the corresponding builder object according to the subscript of quadratic constraint builder in QConstrBuilderArray Class object.

Arguments

idx

Subscript of the quadratic constraint builder in the QConstrBuilderArray Class object, starting with 0.

Example

# Retrieve the builder with subscript 1 in qconbuilderarr
qconbuilder = qconbuilderarr.getBuilder(1)

QConstrBuilderArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in QConstrBuilderArray Class object.

Example

# Get the number of builders in qconbuilderarr
qarrsize = qconbuilderarr.getSize()

PsdConstraint Class

PsdConstraint object contains related operations of COPT positive semi-definite constraints and provides the following methods:

PsdConstraint.getName()

Synopsis

getName()

Description

Retrieve the name of positive semi-definite constraint.

Example

# Retrieve the name of positive semi-definite constraint 'con'.
conname = con.getName()

PsdConstraint.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of positive semi-definite constraint in the model.

Example

# Retrieve the subscript of positive semi-definite constraint con.
conidx = con.getIdx()

PsdConstraint.setName()

Synopsis

setName(newname)

Description

Set the name of positive semi-definite constraint.

Arguments

newname

The name of positive semi-definite constraint to be set.

Example

# Set the name of positive semi-definite constraint 'con'.
con.setName('con')

PsdConstraint.getInfo()

Synopsis

getInfo(infoname)

Description

Retrieve specified information. Return a constant.

Arguments

infoname

Name of the information to be obtained. Please refer to Information section for possible values.

Example

# Get the lower bound of positive semi-definite constraint con
conlb = con.getInfo(COPT.Info.LB)

PsdConstraint.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Set new information value to the specified positive semi-definite constraint.

Arguments

infoname

The name of the information to be set. Please refer to Information section for possible values.

newval

New information value to be set.

Example

# Set the lower bound of positive semi-definite constraint con
con.setInfo(COPT.Info.LB, 1.0)

PsdConstraint.remove()

Synopsis

remove()

Description

Delete the positive semi-definite constraint from model.

Example

# Delete the positive semi-definite constraint 'conx'
conx.remove()

PsdConstrArray Class

To facilitate users to operate on multiple PsdConstraint Class objects, the Python interface of COPT provides PsdConstrArray class with the following methods:

PsdConstrArray()

Synopsis

PsdConstrArray(constrs=None)

Description

Create a PsdConstrArray Class object.

If parameter constrs is None, the create an empty PsdConstrArray Class object, otherwise initialize the newly created PsdConstrArray Class object with parameter constrs .

Arguments

constrs

Positive semi-definite constraints to be added. None by default.

constrs can be PsdConstraint Class object, PsdConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty PsdConstrArray object
conarr = PsdConstrArray()
# Create an PsdConstrArray object containing positive semi-definite constraint conx and cony
conarr = PsdConstrArray([conx, cony])

PsdConstrArray.pushBack()

Synopsis

pushBack(constr)

Description

Add single or multiple PsdConstraint Class objects.

Arguments

constr

Positive semi-definite constraints to be applied. constrs can be PsdConstraint Class object, PsdConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Add positive semi-definite constraint r to conarr
conarr.pushBack(r)
# Add positive semi-definite constraint r0 and r1 to conarr
conarr.pushBack([r0, r1])

PsdConstrArray.getPsdConstr()

Synopsis

getPsdConstr(idx)

Description

Retrieve the positive semi-definite constraint according to its subscript in PsdConstrArray Class object. Return a PsdConstraint Class object.

Arguments

idx

Subscript of the desired positive semi-definite constraint in PsdConstrArray Class object, starting with 0.

Example

# Retrieve the positive semi-definite constraint with subscript 1  in conarr
con = conarr.getPsdConstr(1)

PsdConstrArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in PsdConstrArray Class object.

Example

# Get the number of positive semi-definite constraints in conarr
arrsize = conarr.getSize()

PsdConstrBuilder Class

PsdConstrBuilder object contains operations related to temporary constraints when building positive semi-definite constraints, and provides the following methods:

PsdConstrBuilder()

Synopsis

PsdConstrBuilder()

Description

Create an empty PsdConstrBuilder Class object

Example

# Create an empty positive semi-definite constraint builder
constrbuilder = PsdConstrBuilder()

PsdConstrBuilder.setBuilder()

Synopsis

setBuilder(expr, sense, rhs)

Description

Set expression, constraint type and right hand side for positive semi-definite constraint builder.

Arguments

expr

The expression to be set, which can be PsdVar Class expression or PsdExpr Class expression.

sense

Sense of constraint. The full list of available tyeps can be found in Constraint type section.

rhs

The right hand side of constraint.

Example

# Set the expresson of positive semi-definite constraint builder as: x + y == 1, and sense of constraint as equal
constrbuilder.setBuilder(x + y, COPT.EQUAL, 1)

PsdConstrBuilder.setRange()

Synopsis

setRange(expr, range)

Description

Set a range positive semi-definite constraint builder where expr is less than or equals to 0 and greater than or equals to - range.

Arguments

expr

The expression to be set, which can be PsdVar Class expression or PsdExpr Class expression.

range

Range of constraint, nonnegative constant.

Example

# Set a range positive semi-definite constraint builder: -1 <= x + y - 1 <= 0
constrbuilder.setRange(x + y - 1, 1)

PsdConstrBuilder.getPsdExpr()

Synopsis

getPsdExpr()

Description

Retrieve the expression of a positive semi-definite constraint builder object.

Example

#  Retrieve the expression of a positive semi-definite constraint builder
psdexpr = constrbuilder.getPsdExpr()

PsdConstrBuilder.getSense()

Synopsis

getSense()

Description

Retrieve the constraint sense of positive semi-definite constraint builder object.

Example

# Retrieve the constraint sense of positive semi-definite constraint builder object.
consense = constrbuilder.getSense()

PsdConstrBuilder.getRange()

Synopsis

getRange()

Description

Retrieve the range of positive semi-definite constraint builder object, i.e. length from lower bound to upper bound of the constraint

Example

# Retrieve the range of positive semi-definite constraint builder object
rngval = constrbuilder.getRange()

PsdConstrBuilderArray Class

To facilitate users to operate on multiple PsdConstrBuilder Class objects, the Python interface of COPT provides PsdConstrBuilderArray object with the following methods:

PsdConstrBuilderArray()

Synopsis

PsdConstrBuilderArray(builders=None)

Description

Create a PsdConstrBuilderArray Class object.

If parameter builders is None, then create an empty PsdConstrBuilderArray Class object, otherwise initialize the newly created PsdConstrBuilderArray Class object by parameter builders.

Arguments

builders

Positive semi-definite constraint builder to be added. Optional, None by default. It can be PsdConstrBuilder Class object, PsdConstrBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty PsdConstrBuilderArray object.
conbuilderarr = PsdConstrBuilderArray()
# Create a PsdConstrBuilderArray object containing builders: conbuilderx and conbuildery
conbuilderarr = PsdConstrBuilderArray([conbuilderx, conbuildery])

PsdConstrBuilderArray.pushBack()

Synopsis

pushBack(builder)

Description

Add single or multiple PsdConstrBuilder Class objects.

Arguments

builder

Builder of positive semi-definite constraint to be added, which can be PsdConstrBuilder Class object, PsdConstrBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Add positive semi-definite constraint builder conbuilderx to conbuilderarr
conbuilderarr.pushBack(conbuilderx)
# Add positive semi-definite constraint builders conbuilderx and conbuildery to conbuilderarr
conbuilderarr.pushBack([conbuilderx, conbuildery])

PsdConstrBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve the corresponding builder object according to the subscript of positive semi-definite constraint builder in PsdConstrBuilderArray Class object.

Arguments

idx

Subscript of the positive semi-definite constraint builder in the PsdConstrBuilderArray Class object, starting with 0.

Example

# Retrieve the builder with subscript 1 in conbuilderarr
conbuilder = conbuilderarr.getBuilder(1)

PsdConstrBuilderArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in PsdConstrBuilderArray Class object.

Example

# Get the number of builders in conbuilderarr
arrsize = conbuilderarr.getSize()

LmiConstraint Class

LmiConstraint object contains related operations of COPT LMI (Linear Matrix Inequality) constraints and provides the following methods:

LmiConstraint.getName()

Synopsis

getName()

Description

Retrieve the name of the LmiConstraint Class object.

Example

# Get name of the LmiConstraint con
conname = con.getName()

LmiConstraint.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of the LMI constraint in the model.

Example

# Retrieve the subscript of the LMI constraint
conidx = con.getIdx()

LmiConstraint.getDim()

Synopsis

getDim()

Description

Retrieve the dimension of the LMI constraint.

Example

# Retrieve the dimension of the LMI constraint
conidx = con.getDim()

LmiConstraint.getLen()

Synopsis

getLen()

Description

Retrieve the flattened length of the LMI constraint.

Example

# Retrieve the flattened length of the LMI constraint
conidx = con.getDim()

LmiConstraint.setName()

Synopsis

setName(newname)

Description

Set the name of the LMI constraint to newname .

Arguments

newname

The name of the LMI constraint to be set.

Example

# Set the name of the LMI constraint
con.setName('con')

LmiConstraint.setRhs()

Synopsis

setRhs(mat)

Description

Set the constant-term symmetric matrix of the LMI constraint.

Arguments

mat

The constant-term symmetric matrix of the LMI constraint to be set. It should be SymMatrix Class .

Example

# Set the constant-term symmetric of the LMI constraint
D = m.addSparseMat(2, [0, 1], [0, 1], [1.0, 1.0])
con.setRhs(D)

LmiConstraint.getInfo()

Synopsis

getInfo(infoname)

Description

Retrieve the specified information with the name infoname .

Arguments

infoname

Name of the information to be obtained. Please refer to Information section for possible values.

Example

# Get slack of the LMI constraint con
conlb = con.getInfo(COPT.Info.Slack)

LmiConstraint.remove()

Synopsis

remove()

Description

Remove the current LMI constraint from the model.

Example

# Remove the LMI constraint conx
conx.remove()

LmiConstraint.shape

Synopsis

shape

Description

Shape of the LmiConstraint object.

Return value

Integer tuple.

LmiConstraint.size

Synopsis

size

Description

Size of the LmiConstraint object.

Return value

Integer tuple.

LmiConstraint.dim

Synopsis

dim

Description

Dimension of the LmiConstraint object.

Return value

Integer.

LmiConstraint.len

Synopsis

len

Description

Flattened length of the LmiConstraint object.

Return value

Integer.

LmiConstrArray Class

To facilitate users to operate on multiple LmiConstraint Class objects, the Python interface of COPT provides LmiConstrArray class with the following methods:

LmiConstrArray()

Synopsis

LmiConstrArray(constrs=None)

Description

Create a LmiConstrArray Class object.

If parameter constrs is None, the create an empty LmiConstrArray Class object, otherwise initialize the newly created LmiConstrArray Class object with parameter constrs .

Arguments

constrs

Can be LmiConstraint Class object, LmiConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty LmiConstrArray class object
conarr = LmiConstrArray()
# Create a LmiConstrArray class object and initialize it with the LMI constraints conx and cony
conarr = LmiConstrArray([conx, cony])

LmiConstrArray.pushBack()

Synopsis

pushBack(constr)

Description

Add single or multiple LmiConstraint Class objects.

Arguments

constr

constrs can be LmiConstraint Class object, LmiConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Add LMI constraint r to conarr
conarr.pushBack(r)
# Add LMI constraint r0 and r1 to conarr
conarr.pushBack([r0, r1])

LmiConstrArray.getLmiConstr()

Synopsis

getLmiConstr(idx)

Description

Retrieve the LMI constraint according to its subscript in LmiConstrArray Class object. Return a LmiConstraint Class object.

Arguments

idx

Subscript of the desired LMI constraint in LmiConstrArray Class object, starting with 0.

Example

# Get the LMI constraint with subscript 1 in conarr
con = conarr.getLmiConstr(1)

LmiConstrArray.getSize()

Synopsis

getSize()

Description

Get the number of elements in LmiConstrArray Class object.

Example

# Get the number of LMI constraints in conarr
arrsize = conarr.getSize()

LmiConstrArray.reserve()

Synopsis

reserve(n)

Description

Reserve space for LmiConstrArray Class objects of size n.

Arguments

n

The number of elements in the object LmiConstrArray Class .

SOS Class

SOS object contains related operations of COPT SOS constraints. The following methods are provided:

SOS.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of SOS constraint in model.

Example

# Retrieve the subscript of SOS constraint sosx.
sosidx = sosx.getIdx()

SOS.remove()

Synopsis

remove()

Description

Delete the SOS constraint from model.

Example

# Delete the SOS constraint 'sosx'
sosx.remove()

SOSArray Class

To facilitate users to operate on a set of SOS Class objects, COPT designed SOSArray class in Python interface. The following methods are provided:

SOSArray()

Synopsis

SOSArray(soss=None)

Description

Create a SOSArray Class object.

If parameter soss is None, then build an empty SOSArray Class object, otherwise initialize the newly created SOSArray Class object with soss.

Arguments

soss

SOS constraint to be added. Optional, None by default. It can be SOS Class object, SOSArray Class object, list, dictionary or tupledict Class object.

Example

# Create a new SOSArray object
sosarr = SOSArray()
# Create a SOSArray object, and initialize it with SOS constraints sosx and sosy.
sosarr = SOSArray([sosx, sosy])

SOSArray.pushBack()

Synopsis

pushBack(sos)

Description

Add one or multiple SOS Class objects.

Arguments

sos

SOS constraints to be added, which can be SOS Class object, SOSArray Class object, list, dictionary or tupledict Class object.

Example

# Add SOS constraint sosx to sosarr
sosarr.pushBack(sosx)
# Add SOS constraints sosx and sosy to sosarr
sosarr.pushBack([sosx, sosy])

SOSArray.getSOS()

Synopsis

getSOS(idx)

Description

Retrieve the corresponding SOS constraint according to its subscript in SOSArray Class object and return a SOS Class object.

Arguments

idx

Indice of the SOS constraint in SOSArray Class object, starting with 0.

Example

# Retrieve the SOS constraint with indice of 1 in sosarr
sos = sosarr.getSOS(1)

SOSArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in SOSArray Class object.

Example

# Retrieve the number of SOS constraints in sosarr.
arrsize = sosarr.getSize()

SOSBuilder Class

For easy access builders of SOS constraints, SOSBuilder class provides the following methods:

SOSBuilder()

Synopsis

SOSBuilder()

Description

Create an empty SOSBuilder Class object.

Example

# Create an empty SOSBuilder object.
sosbuilder = SOSBuilder()

SOSBuilder.setBuilder()

Synopsis

setBuilder(sostype, vars, weights=None)

Description

Set type, variable, weight of variable on SOSBuilder Class object.

Arguments

sostype

SOS constraint type. Full list of available types can be found in SOS-constraint types.

vars

Variables of SOS constarint, which can be VarArray Class object, list, dictionary or tupledict Class object.

weights

Weights of variables in SOS constraint. Optional, None by default. Could be list, dictionary or tupledict Class object.

Example

# Set the type of SOS constraint builder as SOS1, variables x and y, weights of variables as 1 and 2 respectively.
sosbuilder.setBuilder(COPT.SOS_TYPE1, [x, y], [1, 2])

SOSBuilder.getType()

Synopsis

getType()

Description

Retrieve the SOS constraint type of SOSBuilder Class object.

Example

# Retrieve the type of SOS constraint builder sosx.
sostype = sosbuilder.getType(sosx)

SOSBuilder.getVar()

Synopsis

getVar(idx)

Description

Retrieve the corresponding variables according to its indice in SOSBuilder Class object, and return a Var Class object.

Arguments

idx

Indice of the variable in SOSBuilder Class object, starting with 0.

Example

# Retrieve the variable in SOS constraint builder sosx with indice of 1
sosvar = sosx.getVar(1)

SOSBuilder.getVars()

Synopsis

getVars()

Description

Retrieve all variables in SOSBuilder Class objects, and return a VarArray Class object.

Example

# Retrieve all variables in SOS constraint builder sosx.
sosvars = sosx.getVars()

SOSBuilder.getWeight()

Synopsis

getWeight(idx)

Description

Retrieve the corresponding weight of variable according to its indice in SOSBuilder Class object.

Arguments

idx

Indice of the variable in SOSBuilder Class object, starting with 0.

Example

# Retrieve the corresponding weight of variable according to its indice in the SOS constraint builder sosx.
sosweight = sosx.getWeight(1)

SOSBuilder.getWeights()

Synopsis

getWeights()

Description

Retrieve weights of all the variables in SOSBuilder Class object.

Example

# Retrieve weights of all the variables in SOS constraint builder sosx.
sosweights = sosx.getWeights()

SOSBuilder.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in SOSBuilder Class object.

Example

# Retrieve the number of elements in SOS constraint builder sosx.
sossize = sosx.getSize()

SOSBuilderArray Class

In order to facilitate users to operate on a set of SOSBuilder Class objects, COPT provides SOSBuilderArray class in Python interface, providing the following methods:

SOSBuilderArray()

Synopsis

SOSBuilderArray(sosbuilders=None)

Description

Create a SOSBuilderArray Class object.

If parameter sosbuilders is None, then create an empty SOSBuilderArray Class object, otherwise initialize the newly created SOSBuilderArray Class object with parameter sosbuilders.

Arguments

sosbuilders

SOS constraint builder to be added. Optional, None by default. Could be SOSBuilder Class object, SOSBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty SOSBuilderArray object.
sosbuilderarr = SOSBuilderArray()
# Create a SOSBuilderArray object and initialize it with SOS constraint builder sosx and sosy
sosbuilderarr = SOSBuilderArray([sosx, sosy])

SOSBuilderArray.pushBack()

Synopsis

pushBack(sosbuilder)

Description

Add one or multiple SOSBuilder Class objects.

Arguments

sosbuilder

SOS constraint builderto be added. Cound be SOSBuilder Class object, SOSBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Add SOS constraint builder sosx to sosbuilderarr
sosbuilderarr.pushBack(sosx)

SOSBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve the corresponding builder according to the indice of SOS constraint builder in SOSBuilderArray Class object.

Arguments

idx

Indice of the SOS constraint builder in SOSBuilderArray Class object, starting with 0.

Example

# Retrieve the SOS constraint builder with indice of 1 in sosbuilderarr
sosbuilder = sosbuilderarr.getBuilder(1)

SOSBuilderArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in SOSBuilderArray Class object.

Example

# Retrieve the number of elements in sosbuilderarr
sosbuildersize = sosbuilderarr.getSize()

Cone Class

Cone object contains related operations of COPT Second-Order-Cone (SOC) constraints. The following methods are provided:

Cone.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of SOC constraint in model.

Example

# Retrieve the subscript of SOC constraint cone.
coneidx = cone.getIdx()

Cone.remove()

Synopsis

remove()

Description

Delete the SOC constraint from model.

Example

# Delete the SOC constraint 'cone'
cone.remove()

ConeArray Class

To facilitate users to operate on a set of Cone Class objects, COPT designed ConeArray class in Python interface. The following methods are provided:

ConeArray()

Synopsis

ConeArray(cones=None)

Description

Create a ConeArray Class object.

If parameter cones is None, then build an empty ConeArray Class object, otherwise initialize the newly created ConeArray Class object with cones.

Arguments

cones

Second-Order-Cone constraint to be added. Optional, None by default. It can be Cone Class object, ConeArray Class object, list, dictionary or tupledict Class object.

Example

# Create a new ConeArray object
conearr = ConeArray()
# Create a ConeArray object, and initialize it with SOC constraints conex and coney.
conearr = ConeArray([conex, coney])

ConeArray.pushBack()

Synopsis

pushBack(cone)

Description

Add one or multiple Cone Class objects.

Arguments

cone

Second-Order-Cone constraints to be added, which can be Cone Class object, ConeArray Class object, list, dictionary or tupledict Class object.

Example

# Add SOC constraint conex to conearr
conearr.pushBack(conex)
# Add SOC constraints conex and coney to conearr
conearr.pushBack([conex, coney])

ConeArray.getCone()

Synopsis

getCone(idx)

Description

Retrieve the corresponding Second-Order-Cone (SOC) constraint according to its subscript in ConeArray Class object and return a Cone Class object.

Arguments

idx

Indice of the SOC constraint in ConeArray Class object, starting with 0.

Example

# Retrieve the SOC constraint with indice of 1 in conearr
cone = conearr.getCone(1)

ConeArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in ConeArray Class object.

Example

# Retrieve the number of SOC constraints in conearr.
arrsize = conearr.getSize()

ConeBuilder Class

For easy access builders of Second-Order-Cone (SOC) constraints, ConeBuilder class provides the following methods:

ConeBuilder()

Synopsis

ConeBuilder()

Description

Create an empty ConeBuilder Class object.

Example

# Create an empty ConeBuilder object.
conebuilder = ConeBuilder()

ConeBuilder.setBuilder()

Synopsis

setBuilder(conetype, vars)

Description

Set type, variables of ConeBuilder Class object.

Arguments

conetype

Type of Second-Order-Cone (SOC) constraint. Full list of available types can be found in SOC-constraint types.

vars

Variables of SOC constarint, which can be VarArray Class object, list, dictionary or tupledict Class object.

Example

# Set type as regular, variables as [z, x, y] for SOC constraint builder
conebuilder.setBuilder(COPT.CONE_QUAD, [z, x, y])

ConeBuilder.getType()

Synopsis

getType()

Description

Retrieve the Second-Order-Cone (SOC) constraint type of ConeBuilder Class object.

Example

# Retrieve the type of SOC constraint builder conex.
conetype = conebuilder.getType(conex)

ConeBuilder.getVar()

Synopsis

getVar(idx)

Description

Retrieve the corresponding variables according to its indice in ConeBuilder Class object, and return a Var Class object.

Arguments

idx

Indice of the variable in ConeBuilder Class object, starting with 0.

Example

# Retrieve the variable in SOC constraint builder conex with indice of 1
conevar = conex.getVar(1)

ConeBuilder.getVars()

Synopsis

getVars()

Description

Retrieve all variables in ConeBuilder Class objects, and return a VarArray Class object.

Example

# Retrieve all variables in SOC constraint builder conex.
conevars = conex.getVars()

ConeBuilder.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in ConeBuilder Class object.

Example

# Retrieve the number of elements in SOC constraint builder conex.
conesize = conex.getSize()

ConeBuilderArray Class

In order to facilitate users to operate on a set of ConeBuilder Class objects, COPT provides ConeBuilderArray class in Python interface, providing the following methods:

ConeBuilderArray()

Synopsis

ConeBuilderArray(conebuilders=None)

Description

Create a ConeBuilderArray Class object.

If parameter conebuilders is None, then create an empty ConeBuilderArray Class object, otherwise initialize the newly created ConeBuilderArray Class object with parameter conebuilders.

Arguments

conebuilders

SOC constraint builder to be added. Optional, None by default. Could be ConeBuilder Class object, ConeBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty ConeBuilderArray object.
conebuilderarr = ConeBuilderArray()
# Create a ConeBuilderArray object and initialize it with SOC constraint builder conex and coney
conebuilderarr = ConeBuilderArray([conex, coney])

ConeBuilderArray.pushBack()

Synopsis

pushBack(conebuilder)

Description

Add one or multiple ConeBuilder Class objects.

Arguments

conebuilder

SOC constraint builder to be added. Could be ConeBuilder Class object, ConeBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Add SOC constraint builder conex to conebuilderarr
conebuilderarr.pushBack(conex)

ConeBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve the corresponding builder according to the indice of SOC constraint builder in ConeBuilderArray Class object.

Arguments

idx

Indice of the SOC constraint builder in ConeBuilderArray Class object, starting with 0.

Example

# Retrieve the SOC constraint builder with indice of 1 in conebuilderarr
ConeBuilder = conebuilderarr.getBuilder(1)

ConeBuilderArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in ConeBuilderArray Class object.

Example

# Retrieve the number of elements in conebuilderarr
conebuildersize = conebuilderarr.getSize()

ExpCone Class

ExpCone object contains related operations of COPT exponential cone constraints. The following methods are provided:

ExpCone.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of exponential cone constraint in model.

Example

# Retrieve the subscript of exponential cone constraint cone.
coneidx = cone.getIdx()

ExpCone.remove()

Synopsis

remove()

Description

Delete the exponential cone constraint from model.

Example

# Delete the exponential cone constraint 'cone'
cone.remove()

ExpConeArray Class

To facilitate users to operate on a set of ExpCone Class objects, COPT designed ExpConeArray class in Python interface. The following methods are provided:

ExpConeArray()

Synopsis

ExpConeArray(cones=None)

Description

Create a ExpConeArray Class object.

If parameter cones is None, then build an empty ExpConeArray Class object, otherwise initialize the newly created ExpConeArray Class object with cones.

Arguments

cones

Exponential cone constraint to be added. Optional, None by default. It can be ExpCone Class object, ExpConeArray Class object, list, dictionary or tupledict Class object.

Example

# Create a new ExpConeArray object
conearr = ExpConeArray()
# Create a ExpConeArray object, and initialize it with exponential cone constraints conex and coney.
conearr = ExpConeArray([conex, coney])

ExpConeArray.pushBack()

Synopsis

pushBack(cone)

Description

Add one or multiple ExpCone Class objects.

Arguments

cone

Exponential cone constraints to be added, which can be ExpCone Class object, ExpConeArray Class object, list, dictionary or tupledict Class object.

Example

# Add exponential cone constraint conex to conearr
conearr.pushBack(conex)
# Add exponential cone constraints conex and coney to conearr
conearr.pushBack([conex, coney])

ExpConeArray.getCone()

Synopsis

getCone(idx)

Description

Retrieve the corresponding exponential cone constraint according to its subscript in ExpConeArray Class object and return a ExpCone Class object.

Arguments

idx

Indice of the exponential cone constraint in ExpConeArray Class object, starting with 0.

Example

# Retrieve the exponential cone constraint with indice of 1 in conearr
cone = conearr.getCone(1)

ExpConeArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in ExpConeArray Class object.

Example

# Retrieve the number of exponential cone constraints in conearr.
arrsize = conearr.getSize()

ExpConeBuilder Class

For easy access builders of exponential cone constraints, ExpConeBuilder class provides the following methods:

ExpConeBuilder()

Synopsis

ExpConeBuilder()

Description

Create an empty ExpConeBuilder Class object.

Example

# Create an empty ExpConeBuilder object.
ExpConeBuilder = ExpConeBuilder()

ExpConeBuilder.setBuilder()

Synopsis

setBuilder(conetype, vars)

Description

Set type of variables of ExpConeBuilder Class object.

Arguments

conetype

Type of exponential cone constraint. Full list of available types can be found in exponential cone types.

vars

Variables of exponential cone constarint, which can be VarArray Class object, list, dictionary or tupledict Class object.

Example

# Set type as regular, variables as [z, x, y] for exponential cone constraint builder
ExpConeBuilder.setBuilder(COPT.EXPCONE_PRIMAL, [z, x, y])

ExpConeBuilder.getType()

Synopsis

getType()

Description

Retrieve the exponential cone constraint type of ExpConeBuilder Class object.

Example

# Retrieve the type of exponential cone constraint builder conex.
conetype = ExpConeBuilder.getType(conex)

ExpConeBuilder.getVar()

Synopsis

getVar(idx)

Description

Retrieve the corresponding variables according to its indice in ExpConeBuilder Class object, and return a Var Class object.

Arguments

idx

Indice of the variable in ExpConeBuilder Class object, starting with 0.

Example

# Retrieve the variable in exponential cone constraint builder conex with indice of 1
conevar = conex.getVar(1)

ExpConeBuilder.getVars()

Synopsis

getVars()

Description

Retrieve all variables in ExpConeBuilder Class objects, and return a VarArray Class object.

Example

# Retrieve all variables in exponential cone constraint builder conex.
conevars = conex.getVars()

ExpConeBuilder.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in ExpConeBuilder Class object.

Example

# Retrieve the number of elements in exponential cone constraint builder conex.
conesize = conex.getSize()

ExpConeBuilderArray Class

In order to facilitate users to operate on a set of ExpConeBuilder Class objects, COPT provides ExpConeBuilderArray class in Python interface, providing the following methods:

ExpConeBuilderArray()

Synopsis

ExpConeBuilderArray(ExpConeBuilders=None)

Description

Create a ExpConeBuilderArray Class object.

If parameter ExpConeBuilders is None, then create an empty ExpConeBuilderArray Class object, otherwise initialize the newly created ExpConeBuilderArray Class object with parameter ExpConeBuilders.

Arguments

ExpConeBuilders

Exponential cone constraint builder to be added. Optional, None by default. Could be ExpConeBuilder Class object, ExpConeBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Create an empty ExpConeBuilderArray object.
ExpConeBuilderarr = ExpConeBuilderArray()
# Create a ExpConeBuilderArray object and initialize it with exponential cone constraint builder conex and coney
ExpConeBuilderarr = ExpConeBuilderArray([conex, coney])

ExpConeBuilderArray.pushBack()

Synopsis

pushBack(conebuilder)

Description

Add one or multiple ExpConeBuilder Class objects.

Arguments

conebuilder

Exponential cone constraint builder to be added. Could be ExpConeBuilder Class object, ExpConeBuilderArray Class object, list, dictionary or tupledict Class object.

Example

# Add exponential cone constraint builder conex to ExpConeBuilderarr
ExpConeBuilderarr.pushBack(conex)

ExpConeBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve the corresponding builder according to the indice of exponential cone constraint builder in ExpConeBuilderArray Class object.

Arguments

idx

Indice of the exponential cone constraint builder in ExpConeBuilderArray Class object, starting with 0.

Example

# Retrieve the exponential cone constraint builder with indice of 1 in ExpConeBuilderarr
ExpExpConeBuilder = ExpConeBuilderarr.getBuilder(1)

ExpConeBuilderArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in ExpConeBuilderArray Class object.

Example

# Retrieve the number of elements in ExpConeBuilderarr
ExpConeBuildersize = ExpConeBuilderarr.getSize()

GenConstr Class

For easy access to indicator constraints, COPT provides GenConstr class which containing the following methods:

GenConstr.getName()

Synopsis

getName()

Description

Retrieve the name of the indicator constraint in model.

Example

# Retrieve the name of indicator constraint indicx
indiname = indicx.getName()

GenConstr.setName()

Synopsis

setName(newname)

Description

Set the name of the indicator constraint in model with newname .

Example

# Set the name of the indicator constraint indicx with "if"
indicx.setName("if")

GenConstr.getIdx()

Synopsis

getIdx()

Description

Retrieve the subscript of indicator constraint in model.

Example

# Retrieve the indice of indicator constraint indicx
indidx = indicx.getIdx()

GenConstr.remove()

Synopsis

remove()

Description

Delete the indicator constraint from model.

Example

# Delete indicator constraint 'indx'
indx.remove()

GenConstrArray Class

In order to facilitate users to operate on a set of GenConstr Class objects, COPT provides GenConstrArray class in Python interface, providing the following methods:

GenConstrArray()

Synopsis

GenConstrArray(genconstrs=None)

Description

Create a GenConstrArray Class object.

If parameter genconstrs is None, then create an empty GenConstrArray Class object, otherwise initialize the newly created GenConstrArray Class object with parameter genconstrs.

Arguments

genconstrs

Indicator constraint to be added. Optional, None by default. Could be GenConstr Class object, GenConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Create a new GenConstrArray object
genconstrarr = GenConstrArray()
# Create a GenConstrArray object and user indicator constraints genx and geny to initialize it.
genconstrarr = GenConstrArray([genx, geny])

GenConstrArray.pushBack()

Synopsis

pushBack(genconstr)

Description

Add one or multiple GenConstr Class objects.

Arguments

constrs

The indicator constraint to be added. Cound be GenConstr Class object, GenConstrArray Class object, list, dictionary or tupledict Class object.

Example

# Aff indicator constraint genx to genconarr
genconarr.pushBack(genx)
# Add indicator constraint genx and geny to genconarr
genconarr.pushBack([genx, geny])

GenConstrArray.getGenConstr()

Synopsis

getGenConstr(idx)

Description

Retrieve the corresponding indicator constraint according to the indice of indicator constraint in GenConstrArray Class object, and return a GenConstr Class object.

Arguments

idx

Indice of the indicator constraint in GenConstrArray Class, starting with 0.

Example

# Retrieve the indicator constraint with indice of 1 in genconarr
genconstr = genconarr.getGenConstr(1)

GenConstrArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in GenConstrArray Class object.

Example

# Retrieve the number of elements in genconarr
genconsize = genconarr.getSize()

GenConstrBuilder Class

GenConstrBuilder object contains operations for building indicator constraints, and provides the following methods:

GenConstrBuilder()

Synopsis

GenConstrBuilder()

Description

Create an empty GenConstrBuilder Class object.

Example

# Create an empty GenConstrBuilder object
genconbuilder = GenConstrBuilder()

GenConstrBuilder.setBuilder()

Synopsis

setBuilder(var, val, expr, sense, type=COPT.INDICATOR_IF)

Description

Set indicator variable, the value of indicator variable, the expression/sense of constraint, and the type of indicator constraint of the GenConstrBuilder Class object.

Arguments

var

Indicator variable.

val

Value of an indicator variable.

expr

Expression of linear constraint, which can be Var Class object or LinExpr Class object.

sense

Sense for the linear constraint. Please refer to Constraint type for possible values.

type

Type of the indicator constraint. The default value is COPT.INDICATOR_IF (If-Then). Please refer to Indicator constraint type for possible values.

Example

# Set indicator variable of indicator constraint builder to x. When x is true, the linear constraint x + y == 1 holds
genconbuilder.setBuilder(x, True, x + y - 1, COPT.EQUAL)

GenConstrBuilder.getBinVar()

Synopsis

getBinVar()

Description

Retrieve the indicator variable of a GenConstrBuilder Class object.

Example

# Retrieve the indicator variable of indicator constraint builder genbuilderx
indvar = genbuilderx.getBinVar()

GenConstrBuilder.getBinVal()

Synopsis

getBinVal()

Description

Retrieve the value of indicator variable of a GenConstrBuilder Class object.

Example

# Retrieve the value when the indicator variable of indicator constraint builder genbuilderx is valid
indval = genbuilderx.getBinVal()

GenConstrBuilder.getExpr()

Synopsis

getExpr()

Description

Retrieve the linear expression of a GenConstrBuilder Class object.

Example

# Retrieve the linear expression of indicator constraint builder genbuilderx
linexpr = genbuilderx.getExpr()

GenConstrBuilder.getSense()

Synopsis

getSense()

Description

Retrieve the sense for the linear constraint of a GenConstrBuilder Class object.

Example

# Retrieve the sense for the linear constraint of indicator constraint builder genbuilderx
linsense = genbuilderx.getSense()

GenConstrBuilder.getIndType()

Synopsis

getIndType()

Description

Retrieve the type for the indicator constraint of a GenConstrBuilder Class object.

Example

# Retrieve the type for the indicator constraint of indicator constraint builder genbuilderx
linsense = genbuilderx.getIndType()

GenConstrBuilderArray Class

To facilitate users to operate on multiple GenConstrBuilder Class objects, the Python interface of COPT provides GenConstrBuilderArray object with the following methods:

GenConstrBuilderArray()

Synopsis

GenConstrBuilderArray(genconstrbuilders=None)

Description

Create a GenConstrBuilderArray Class object.

If argument genconstrbuilders is None, then create an empty GenConstrBuilderArray Class object; otherwise use the argument genconstrbuilders to initialize the newly created GenConstrBuilderArray Class object.

Arguments

genconstrbuilders

Indicator constraint builder to add. Optional, None by default. It can be GenConstrBuilder Class object, GenConstrBuilderArray Class object, list, dict, or tupledict Class object.

Example

# Create an empty GenConstrBuilderArray object
genbuilderarr = GenConstrBuilderArray()
# Create a GenConstrBuilderArray object and use indicator constraint builder genbuilderx and genbuildery to initialize it.
genbuilderarr = GenConstrBuilderArray([genbuilderx, genbuildery])

GenConstrBuilderArray.pushBack()

Synopsis

pushBack(genconstrbuilder)

Description

Add single or multiple GenConstrBuilder Class objects.

Arguments

genconstrbuilder

Indicator constraint builders to add, which can be GenConstrBuilder Class object, GenConstrBuilderArray Class object, list, dict, or tupledict Class object.

Example

# Add an indicator constraint builder to genbuilderarr
genbuilderarr.pushBack(genbuilderx)
# Add indicator constraint builders genbuilderx and genbuildery to genbuilderarr
genbuilderarr.pushBack([genbuilderx, genbuildery])

GenConstrBuilderArray.getBuilder()

Synopsis

getBuilder(idx)

Description

Retrieve the indicator constraint builder according to its index in the GenConstrBuilderArray Class object, and return a GenConstrBuilder Class object.

Arguments

idx

Index of the indicator constraint builder in the GenConstrBuilderArray Class object, starting with 0.

Example

# Retrieve the indicator constraint builder whose index in genbuilderarr is 1
genbuilder = genbuilderarr.getBuilder(1)

GenConstrBuilderArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in the GenConstrBuilderArray Class object.

Example

# Retrieve the number of elements in genbuilderarr
genbuildersize = genbuilderarr.getSize()

Column Class

To facilitate users to model by column, the Python interface of COPT provides Column object with the following methods:

Column()

Synopsis

Column(constrs=0.0, coeffs=None)

Description

Create an Column Class object.

If argument constrs is None and argument coeffs is None, then create an empty Column Class object; otherwise use the argument constrs and coeffs to initialize the newly created Column Class object. If argument constrs is a Constraint Class or Column Class object, then argument coeffs is a constant. If argument coeffs is None, then it is considered to be constant 1.0; If argument constrs is a list and argument coeffs is None, then the elements of argument constrs are constraint-coefficient pairs; For other forms of arguments, call method addTerms to initialize the newly created Column Class object.

Arguments

constrs

Linear constraint.

coeffs

Coefficient for variables in the linear constraint.

Example

# Create an empty Column object
col = Column()
# Create a Column object and add two terms: coefficient is 2 in constraint conx and 3 in constraint cony
col = Column([(conx, 2), (cony, 3)])
# Create a Column object and add two terms: coefficient is 1 in constraint conxx and 2 in constraint conyy
col = Column([conxx, conyy], [1, 2])

Column.getCoeff()

Synopsis

getCoeff(idx)

Description

Retrieve the coefficient according to its index in the Column Class object.

Arguments

idx

Index for the element, starting with 0.

Example

# Retrieve the coefficient whose index is 0 in col
coeff = col.getCoeff(0)

Column.getConstr()

Synopsis

getConstr(idx)

Description

Retrieve the linear constraint according to its index in the Column Class object.

Arguments

idx

Index for the element, starting with 0.

Example

# Retrieve the linear constraint whose index is 1 in col
constr = col.getConstr(1)

Column.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in the Column Class object.

Example

# Retrieve the number of elements in col
colsize = col.getSize()

Column.addTerm()

Synopsis

addTerm(constr, coeff=1.0)

Description

Add a new term.

Arguments

constr

The linear constraint for the term to add.

coeff

The coefficient for the term to add. Optional, 1.0 by default.

Example

# Add an term to col, whose constraint is cony and coefficient is 2.0
col.addTerm(cony, 2.0)
# Add an term to col, whose constraint is conx and coefficient is 1.0
col.addTerm(conx)

Column.addTerms()

Synopsis

addTerms(constrs, coeffs)

Description

Add single or multiple terms.

If argument constrs is Constraint Class object, then argument coeffs is constant; If argument constrs is ConstrArray Class object or list, then argument coeffs is constant or list; If argument constrs is dictionary or tupledict Class object, then argument coeffs is constant, dict, or tupledict Class object.

Arguments

constrs

The linear constraints for terms to add.

coeffs

The coefficients for terms to add.

Example

# Add two terms: constraint conx with coefficient 2.0, constraint cony with coefficient 3.0
col.addTerms([conx, cony], [2.0, 3.0])

Column.addColumn()

Synopsis

addColumn(col, mult=1.0)

Description

Add a new column to current column.

Arguments

col

Column to add.

mult

Magnification coefficient for added column. Optional, 1.0 by default.

Example

# Add column coly to column colx. The magnification coefficient for coly is 2.0
colx.addColumn(coly, 2.0)

Column.clone()

Synopsis

clone()

Description

Create a deep copy of a column.

Example

# Create a deep copy of column col
colcopy = col.clone()

Column.remove()

Synopsis

remove(item)

Description

Remove a term from a column.

If argument item is a constant, then remove the term by its index; otherwise argument item is a Constraint Class object.

Arguments

item

Constant index or the linear constraint for the term to be removed.

Example

# Remove the term whose index is 2 from column col
col.remove(2)
# Remove the term of the linear constraint conx from col
col.remove(conx)

Column.clear()

Synopsis

clear()

Description

Remove all terms from a column.

Example

# Remove all terms from column col
col.clear()

ColumnArray Class

To facilitate users to operate on multiple Column Class objects, the Python interface of COPT provides ColumnArray object with the following methods:

ColumnArray()

Synopsis

ColumnArray(columns=None)

Description

Create a ColumnArray Class object.

If argument columns is None, then create an empty ColumnArray Class object; otherwise use argument columns to initialize the newly created ColumnArray Class object.

Arguments

columns

Columns to add. Optional, None by default. It can be Column Class object, ColumnArray Class object, list, dict, or tupledict Class object.

Example

# Create an empty ColumnArray object
colarr = ColumnArray()
# Create a ColumnArray object and use columns colx and coly to initialize it
colarr = ColumnArray([colx, coly])

ColumnArray.pushBack()

Synopsis

pushBack(column)

Description

Add single or multiple Column Class objects.

Arguments

column

Columns to add, which can be Column Class object, ColumnArray Class object, list, dict, or tupledict Class object.

Example

# Add column colx to colarr
colarr.pushBack(colx)
# Add columns colx and coly to colarr
colarr.pushBack([colx, coly])

ColumnArray.getColumn()

Synopsis

getColumn(idx)

Description

Retrieve the column according to its index in a ColumnArray Class object. Return a Column Class object.

Arguments

idx

Index of the column in the ColumnArray Class object, starting with 0.

Example

# Retrieve the column whose index is 1 in colarr
col = colarr.getColumn(1)

ColumnArray.getSize()

Synopsis

getSize()

Description

Retrieve the number of elements in a ColumnArray Class object.

Example

# Retrieve the number of element in colarr
colsize = colarr.getSize()

ColumnArray.clear()

Synopsis

clear()

Description

Remove all terms from a ColumnArray Class object.

Example

# Remove all terms from colarr
colarr.clear()

MVar Class

The MVar class is used in COPT to build multi-dimensional variables and supports NumPy’s multi-dimensional array operations. We recommend to generate it through the method addVars or addMVar of the model class, although it can also be converted and generated through the two built-in class methods fromlist and fromvar . The following member methods are provided:

MVar.fromlist()

Synopsis

fromlist(vars)

Description

Generate a MVar Class object from a set of Var Class objects. This is the class generation method and can be called directly without MVar object.

Arguments

vars

A set of Var objects, which can be a multi-dimensional list or ndarray.

Return value

new MVar object whose dimensions depend on the dimensions of the arguments vars.

Example

vars = model.addVars(4)
mx_1d = MVar.fromlist(vars)
mx_2d = MVar.fromlist([vars[0], vars[1]], [vars[2], vars[3]])

MVar.fromvar()

Synopsis

fromvar(var)

Description

Generate a 0-dimensional MVar Class object from a Var Class object. This is the class generation method and can be called directly without MVar object.

Arguments

var

A Var object.

Return value

The new 0-dimensional MVar object.

Example

x = model.addVar()
mx_0d = MVar.fromvar(x)

MVar.clone()

Synopsis

clone()

Description

Deep-copy a MVar Class object.

Return value

new MVar object

Example

# Create a 2-D variable and make a copy. Note that the actual variable is not incremented.
mx = model.addMVar((3, 2), nameprefix="mx")
mx_copy = mx.clone()

MVar.diagonal()

Synopsis

diagonal(offset=0, axis1=0, axis2=1)

Description

Generate a MVar Class object whose elements are the elements on the diagonal of the original MVar object.

Arguments

offset

Optional parameter, indicating the offset of the diagonal, the default value is 0. If the value is greater than 0, it means the diagonal upward offset; if the value is less than 0, it means the diagonal downward offset.

axis1

Optional parameter, the axis to use as the first axis of the 2D sub MVar, from where the diagonal should start. The default first axis is 0.

axis2

Optional parameter, the axis to use as the second axis of the 2D sub MVar, from where the diagonal should start. The default second axis is 1.

Return value

new MVar object

Example

mx = model.addMVar((5, 5), nameprefix="mx")
diag_m0 = mx.diagonal()
diag_a1 = mx.diagonal(1)
diag_b1 = mx.diagonal(-1)

MVar.getInfo()

Synopsis

getInfo(infoname)

Description

Get the information value of each variable inside MVar.

Arguments

infoname

The name of the information being queried. Please refer to Information Section for possible values.

Return value

Returns a NumPy ndarray with the same dimension as the MVar object, whose elements are the information values of the corresponding variable.

Example

mx = model.addMVar(3)
print(mx.getInfo("LB"))

MVar.item()

Synopsis

item()

Description

Get the Var variable inside the 0-dimensional MVar. Raises a ValueError exception if the MVar object is not 0-dimensional.

Return value

Returns the Var object.

Example

mx = model.addMVar(3)
var = mx[0].item()

MVar.reshape()

Synopsis

reshape(shape, order='C')

Description

Returns a new MVar object whose elements remain unchanged but whose shape is transformed by the parameter shape.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MVar object.

order

Optional parameter, the default is the character ‘C’, which means it is compatible with the C language, that is, it is stored in rows; it can also be set to the character ‘F’, that is, it is stored in columns, and it is compatible with the Fortune language.

Return value

Returns a new MVar object with the same elements as the original MVar object but with a different shape.

Example

mx = model.addMVar(6)
mx_2x3 = mx.reshape((2, 3))

MVar.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Sets the information value of each variable inside the MVar.

Arguments

infoname

The name of the information being queried. Please refer to Information Section for possible values.

newval

The information value to be set.

Example

mx = model.addMVar(3)
mx.setInfo("ub", 9.0)
mx.setInfo(COPT.Info.LB, 0.0)

MVar.sum()

Synopsis

sum(axis=None)

Description

Sum the variables in the MVar, returning a new MLinExpr Class object.

Arguments

axis

Optional integer parameter, the default value is None, that is, to sum up variables one by one. Otherwise, sum over the given axis.

Return value

Returns an MLinExpr object representing the sum of the corresponding variables.

Example

mx = model.addMVar((3, 5))
sum_all = mx.sum() #Return 0-dimensional MLinExpr object
sum_row = mx.sum(axis = 0) #Return a 1-dimensional MLinExpr object with a shape of (5, )

MVar.tolist()

Synopsis

tolist()

Description

Convert an MVar object to a one-dimensional list of Var objects.

Return value

Returns a one-dimensional list containing Var objects.

Example

mx = model.addMVar((3, 5))
print(mx.tolist())

MVar.transpose()

Synopsis

transpose()

Description

Generates a new MVar object that is the transpose of the original MVar object.

Return value

Return the new MVar object.

Example

mx = model.addMVar((3, 5))
print(mx.transpose().shape) #its shape is (5, 3)

MVar.ndim

Synopsis

ndim

Description

Dimensions of the MVar object.

Return value

Integer value.

Example

mx = model.addMVar((3, 5))
print(mx.ndim) #ndim = 2

MVar.shape

Synopsis

shape

Description

The shape of the MVar object.

Return value

Integer tuple.

Example

mx = model.addMVar((3,))
print(mx.shape) # shape = (3, )

MVar.size

Synopsis

size

Description

The number of Var variables in the MVar object.

Return value

Integer value.

Example

mx = model.addMVar((3, 4))
print(mx.size) # size = 12

MVar.T

Synopsis

T

Description

Transpose of the MVar object. Similar to the class method transpose().

Return value

Returns the transposed MVar object.

Example

mx = model.addMVar((3, 4))
print(mx.T.shape) # shape = (4, 3)

MConstr Class

The MConstr class holds multi-dimensional linear constraints in COPT and supports NumPy’s multi-dimensional array operations. It is generated by the method addConstrs or addMConstr of the model class. The following member methods are provided:

MConstr.getInfo()

Synopsis

getInfo(infoname)

Description

Get the information value of each constraint within MConstr.

Arguments

infoname

The name of the information being queried. Please refer to Information Section for possible values.

Return value

Returns a NumPy ndarray with the same dimension as the MConstr object, whose elements are the attribute values of the corresponding constraint.

Example

a = np.random.rand(4)
mx = m.addMVar((4, 3), nameprefix="mx")
b = np.random.rand(3)
mc = m.addConstrs(a @ mx <= b)
print(mc.getInfo("pi"))

MConstr.item()

Synopsis

item()

Description

Get the constraint object in 0-dimensional MConstr. If the MConstr object is not 0-dimensional, a ValueError exception is raised.

Return value

Returns the linear constraint object.

Example

mc = m.addConstrs(a @ mx <= b)
print(mc[0].item())

MConstr.reshape()

Synopsis

reshape(shape, order='C')

Description

Returns a new MConstr object whose elements remain unchanged but whose shape is transformed by the argument shape.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MConstr object.

order

Optional parameter, the default is the character ‘C’, which means it is compatible with the C language, that is, it is stored in rows; it can also be set to the character ‘F’, that is, it is stored in columns, and it is compatible with the Fortune language.

Return value

Returns a new MConstr object with the same elements as the original MConstr object but with a different shape.

Example

mc = m.addConstrs(a @ mx <= b)
mc_2x2 = mc.reshape((2, 2))

MConstr.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Set information values for each constraint within MConstr.

Arguments

infoname

The name of the information to be set. Please refer to Information Section for possible values.

newval

The new value to be set.

Example

mc = model.addConstrs(a @ mx <= b)
mc.setInfo("obj", 9.0)

MConstr.tolist()

Synopsis

tolist()

Description

Convert the MConstr object to a one-dimensional list of constraints.

Return value

Returns a one-dimensional list containing Constraint objects.

Example

mc = m.addConstrs(a @ mx <= b)
print(mc.tolist())

MConstr.transpose()

Synopsis

transpose()

Description

Generates a new MConstr object that is the transpose of the original MConstr object.

Return value

Returns the transposed MConstr object.

Example

mc = m.addConstrs(a @ mx <= b)
print(mc.transpose())

MConstr.ndim

Synopsis

ndim

Description

Dimensions of the MConstr object.

Return value

Integer value.

Example

mc = m.addConstrs(a @ mx <= b)
print(mc.ndim)

MConstr.shape

Synopsis

shape

Description

The shape of the MConstr object.

Return value

Integer tuple.

Example

mc = m.addConstrs(a @ mx <= b)
print(mc.shape)

MConstr.size

Synopsis

size

Description

The number of constraints of the MConstr object.

Return value

Integer value.

Example

mc = m.addConstrs(a @ mx <= b)
print(mc.size)

MConstr.T

Synopsis

T

Description

Transpose of the MConstr object. Similar to the class method transpose().

Return value

Returns the transposed MConstr object.

Example

A = np.ones([2, 4])
mx = m.addMVar((4, 3), nameprefix="mx")
mc = m.addConstrs(A @ X == 0.0)
print(mc.T.shape) # shape = (3, 2)

MConstrBuilder Class

The MConstrBuilder class is used to build multi-dimensional linear constraints in COPT and supports NumPy’s multi-dimensional array operations. Users might create a MConstrBuilder object by its constructor with a list of ConstrBuilder Class objects, or simply by overloaded comparison operator of MLinExpr Class. The following member methods are provided:

MConstrBuilder()

Synopsis

MConstrBuilder(args, shape=None)

Description

construtor of MConstrBuilder.

Arguments

args

one or a set of ConstrBuilder Class objects, in form of Python list or NumPy ndarray.

shape

an integer, or tuple of integers, which is the shape of new MConstrBuilder object.

Example

vars = m.addVars(4)
builders = [x <= 1.0 for x in vars]
mcb = MConstrBuilder(builders, (2, 2))

# or by overloaded comparison operator of MVar
mx = m.addMVar((3, 2))
mcb = mx >= 1.0

# or immediately passed to addConstrs()
model.addConstrs(mx >= 1.0)

MQConstr Class

The MQConstr class holds multi-dimensional quadratic constraints in COPT and supports NumPy’s multi-dimensional array operations. In experimental version of matrix modeling, it is generated by the method addQConstr or addMQConstr of the model class. The following member methods are provided:

MQConstr.getInfo()

Synopsis

getInfo(infoname)

Description

Get the information value of each quadratic constraint within MQConstr.

Arguments

infoname

The name of the information being queried. Please refer to Information Section for possible values.

Return value

Returns a built-in NdArray with the same shape as the MQConstr object, whose elements are the information values of the corresponding constraints.

Example

mx = m.addMVar((1, 3), nameprefix="mx")
mc = m.addQConstr(mx @ mx.T <= 1.0)
print(mc.getInfo("x"))

MQConstr.item()

Synopsis

item()

Description

Get the quadratic constraint object in MQConstr object. If the MQConstr object has more than one item, an exception of ValueError is raised.

Return value

Returns the quadratic constraint object.

Example

mc = m.addQConstr(mx @ mx.T <= 1.0)
print(mc.item())

MQConstr.reshape()

Synopsis

reshape(shape, order='C')

Description

Returns a new MQConstr object whose elements remain unchanged but whose shape is transformed by the argument shape.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MQConstr object.

order

Optional parameter, the default is the character ‘C’, which means it is compatible with the C language. The other option ‘F’ is not implemented yet.

Return value

Returns a new MQConstr object with the same elements as the original MQConstr object but with a different shape.

Example

mc = m.addQConstr(mx.T @ mx <= 1.0)
mc_1x9 = mc.reshape((1, 9))

MQConstr.setInfo()

Synopsis

setInfo(infoname, newval)

Description

Set information values for each quadratic constraint within MQConstr.

Arguments

infoname

The name of the information to be set. Please refer to Information Section for possible values.

newval

The new value to be set.

Example

mc = model.addQConstr(mx @ mx.T <= 1.0)
mc.setInfo("LB", 9.0)

MQConstr.tolist()

Synopsis

tolist()

Description

Convert the MQConstr object to a one-dimensional list of quadratic constraints.

Return value

Returns a one-dimensional list containing QConstraint Class objects.

Example

mc = m.addQConstr(mx.T @ mx <= 1.0)
print(mc.tolist())

MQConstr.transpose()

Synopsis

transpose()

Description

Generates a new MQConstr object that is the transpose of the original MQConstr object.

Return value

Returns the transposed MQConstr object.

Example

mc = m.addQConstr(mx.T @ mx <= 1.0)
print(mc.transpose())

MQConstr.ndim

Synopsis

ndim

Description

Dimensions of the MQConstr object.

Return value

Integer value.

Example

mc = m.addQConstr(mx.T @ mx <= 1.0)
print(mc.ndim)

MQConstr.shape

Synopsis

shape

Description

The shape of the MQConstr object.

Return value

Integer tuple.

Example

mc = m.addQConstr(mx.T @ mx <= 1.0)
print(mc.shape)

MQConstr.size

Synopsis

size

Description

The number of constraints of the MQConstr object.

Return value

Integer value.

Example

mc = m.addQConstr(mx.T @ mx <= 1.0)
print(mc.size)

MQConstr.T

Synopsis

T

Description

Transpose of the MQConstr object. Similar to the class method transpose() .

Return value

Returns the transposed MQConstr object.

Example

A = np.ones([4, 3])
mx = model.addMVar((3, 4), nameprefix="mx")
mc = model.addQConstr(mx @ A @ mx == 0.0)
print(mc.shape) # shape = (3, 4)
print(mc.T.shape) # shape = (4, 3)

MQConstrBuilder Class

The MQConstrBuilder class is used to build multi-dimensional quadratic constraints in COPT and supports NumPy’s multi-dimensional array operations. Users might create a MQConstrBuilder object by its constructor with a list of QConstrBuilder Class objects, or simply by overloaded comparison operator of MQuadExpr Class. The following member methods are provided:

MQConstrBuilder()

Synopsis

MQConstrBuilder(args, shape=None)

Description

construtor of MQConstrBuilder.

Arguments

args

one or a set of QConstrBuilder Class objects, in form of Python list or NumPy ndarray.

shape

an integer, or tuple of integers, which is the shape of new MQConstrBuilder object.

Example

x = model.addVar()
mqcb = MQConstrBuilder(x * x <= 9.0)

# or by overloaded comparison operator of MQuadExpr
mx = model.addMVar(3, 3)
mqcb = mx @ mx >= 1.0

# or immediately passed to addConstrs()
ma = model.addMVar(2)
A = np.full((2,3), 1)
mb = model.addMVar(3)
model.addQConstr(ma @ A @ mb <= 1.0)

MLinExpr Class

The MLinExpr class is used in COPT to build multi-dimensional linear expressions and supports NumPy’s multi-dimensional array operations. The MLinExpr object with an initial value of 0.0 can be generated by the class generation method zeros() , or by MVar Class object to generate a linear combination. The following member methods are provided:

MLinExpr.zeros()

Synopsis

zeros(shape)

Description

This is the class generation method and can be called directly without the MLinExpr object.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MLinExpr object.

Return value

new MLinExpr object.

Example

mexpr = MLinExpr.zeros((2,3))
x = model.addVar()
mexpr += x

MLinExpr.clear()

Synopsis

clear()

Description

Resets each element of the MLinExpr Class object to 0.0.

Example

mexpr = 2.0 * model.addMVar(3)
mexpr.clear()

MLinExpr.clone()

Synopsis

clone()

Description

Deep-copy a MLinExpr Class object.

Return value

new MLinExpr object

Example

mexpr = 2.0 * model.addMVar(3)
mexpr_copy = mexpr.clone()

MLinExpr.getValue()

Synopsis

getValue()

Description

Get the evaluation of each linear expression within the MLinExpr Class object.

Return value

Returns a NumPy ndarray of the same dimensions as the MLinExpr object whose elements are the evaluations of the corresponding expression.

Example

a = np.random.rand(4)
mx = m.addMVar((4, 3), nameprefix="mx")
mexpr = a @ mx
mc = m.addConstrs(mexpr <= 1.0)
model.solve()
print(mc.getValue())

MLinExpr.item()

Synopsis

item()

Description

Get the constraint object in 0-dimensional MLinExpr. Raises a ValueError exception if the MLinExpr object is not 0-dimensional.

Return value

Returns the linear constraint object.

Example

mexpr = 2.0 * model.addMVar(3)
print(mexpr[0].item())

MLinExpr.reshape()

Synopsis

reshape(shape, order='C')

Description

Returns a new MLinExpr object whose elements remain unchanged but whose shape is transformed by the argument shape.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MLinExpr object.

order

Optional parameter, the default is the character ‘C’, which means it is compatible with the C language, that is, it is stored in rows; it can also be set to the character ‘F’, that is, it is stored in columns, and it is compatible with the Fortune language.

Return value

Returns a new MLinExpr object with the same elements as the original MLinExpr object but with a different shape.

Example

mc = m.addConstrs(a @ mx <= b)
mc_2x2 = mc.reshape((2, 2))

MLinExpr.sum()

Synopsis

sum(axis=None)

Description

Sum the variables in the MLinExpr object, returning a new MLinExpr Class object.

Arguments

axis

Optional integer parameter, the default value is None, that is, to sum up variables one by one. Otherwise, sum over the given axis.

Return value

Returns an MLinExpr object representing the sum of the corresponding linear expressions.

Example

mexpr = 2.0 * model.addMVar((3, 5))
sum_all = mexpr.sum() #return 0-dimensional MLinExpr object
sum_row = mexpr.sum(axis = 0) #Return a 1-dimensional MLinExpr object with a shape of (5, )

MLinExpr.tolist()

Synopsis

tolist()

Description

Converts an MLinExpr object to a one-dimensional list whose elements are linear expressions.

Return value

Return a 1D list containing LinExpr Class.

Example

mexpr = 2.0 * model.addMVar((3, 5))
print(mexpr.tolist())

MLinExpr.transpose()

Synopsis

transpose()

Description

Generates a new MLinExpr object that is the transpose of the original MLinExpr object.

Return value

Returns the transposed MLinExpr object.

Example

mexpr = 2.0 * model.addMVar((3, 5))
print(mexpr.transpose())

MLinExpr.ndim

Synopsis

ndim

Description

MLinExpr Class Dimensions of the object.

Return value

Integer value.

Example

mexpr = 2.0 * model.addMVar((3, 5))
print(mexpr.ndim)

MLinExpr.shape

Synopsis

shape

Description

MLinExpr Class The shape of the object.

Return value

Integer tuple.

Example

mexpr = 2.0 * model.addMVar((3, 5))
print(mexpr.shape)

MLinExpr.size

Synopsis

size

Description

The number of elements of MLinExpr Class object.

Return value

Integer value.

Example

mexpr = 2.0 * model.addMVar((3, 5))
print(mexpr.size)

MLinExpr.T

Synopsis

T

Description

Transpose of MLinExpr Class object. Similar to the class method transpose().

Return value

Returns the transposed MLinExpr object.

Example

mexpr = 2.0 * model.addMVar((3, 5))
print(mexpr.T.shape) # The transposed shape is (5, 3)

MLinExpr.__eq__()

Synopsis

__eq__()

Description

Overload the == operator to build a MConstrBuilder Class object, which can be passed as the first argument to Model.addConstrs.

Return value

Example

model.addConstrs(A @ x == 1.0)

MLinExpr.__ge__()

Synopsis

__ge__()

Description

Overload the >= operator to build a MConstrBuilder Class object, which can be passed as the first argument to Model.addConstrs.

Return value

Example

model.addConstrs(A @ x >= 1.0)

MLinExpr.__le__()

Synopsis

__le__()

Description

Overload the <= operator to build a MConstrBuilder Class object, which can be passed as the first argument to Model.addConstrs.

Return value

Example

model.addConstrs(A @ x <= 1.0)

MQuadExpr Class

The MQuadExpr class is used in COPT to construct multi-dimensional quadratic expressions and supports NumPy’s multi-dimensional array operations. The MQuadExpr object with an initial value of 0.0 can be generated by the class generation method zeros() , or by pairing two MVar Class objects are generated by (matrix) multiplication. The following member methods are provided:

MQuadExpr.zeros()

Synopsis

zeros(shape)

Description

This is the class generation method and can be called directly without an MQuadExpr object.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MQuadExpr object.

Return value

new MQuadExpr object.

Example

mqx = MQuadExpr.zeros((2,3)) # shape = (2, 3)
x = model.addVar()
mqx += 2.0 * x * x           # broadcast scalar
mqx += model.addMVar(3)      # broadcast MVar of shape (3,)

MQuadExpr.clear()

Synopsis

clear()

Description

Resets each element of the MQuadExpr Class object to 0.0.

Example

ma = model.addMVar(3, nameprefix='a')
mb = model.addMVar(3, nameprefix='b')
mqx = ma * mb    # elementwise multiply, shape = (3,)
mqx.clear()
print(mqx)       # result is [0.0, 0.0, 0.0]

MQuadExpr.clone()

Synopsis

clone()

Description

Deep-copy a MQuadExpr Class object.

Return value

new MQuadExpr object

Example

mx = model.addMVar((3, 3), nameprefix='mx')
mqx = 2.0 * mx @ mx      # matrix multiply, shape = (3, 3)
mqx_copy = mqx.clone()
mqx_copy.clear()
print(mqx)               # mqx is untouched

MQuadExpr.getValue()

Synopsis

getValue()

Description

Get the evaluation of each linear expression within the MQuadExpr Class object.

Return value

Returns a NumPy ndarray of the same dimensions as the MQuadExpr object whose elements are the evaluations of the corresponding expression.

Example

A = np.eye(3)
mx = m.addMVar(3, nameprefix="mx")
mqx = mx @ A @ mx        # 0-D MQuadExpr, shape = ()
m.addQConstr(mqx <= 9.0)
m.solve()
print(mqx.getValue())

MQuadExpr.item()

Synopsis

item()

Description

Get the constraint object in the 0-dimensional MQuadExpr. Raises a ValueError exception if the MQuadExpr object is not 0-dimensional.

Return value

Returns the linear constraint object.

Example

x = m.addVar()
mqx = MQuadExpr.zeros(3) + x * x
print(mqx[1].item()) # Return QuadExpr(x * x)

MQuadExpr.reshape()

Synopsis

reshape(shape, order='C')

Description

Returns a new MQuadExpr object whose elements are unchanged but whose shape is transformed by the argument shape.

Arguments

shape

The value is an integer, or a tuple of integers. which represents the shape of the new MQuadExpr object.

order

Optional parameter, the default is the character ‘C’, which means it is compatible with the C language, that is, it is stored in rows; it can also be set to the character ‘F’, that is, it is stored in columns, and it is compatible with the Fortune language.

Return value

Returns a new MQuadExpr object with the same elements as the original MQuadExpr object but with a different shape.

Example

mqx = MQuadExpr.zeros(6)
mqx_2x3 = mqx.reshape((2, 3))

MQuadExpr.sum()

Synopsis

sum(axis=None)

Description

Sums the variables in the MQuadExpr object, returning a new MQuadExpr Class object.

Arguments

axis

Optional integer parameter, the default value is None, that is, to sum up variables one by one. Otherwise, sum over the given axis.

Return value

Returns an MQuadExpr object representing the sum of the corresponding linear expressions.

Example

ma = model.addMVar((2, 3), nameprefix='ma')
mb = model.addMVar((3, 2), nameprefix='mb')
mqx = ma @ mb
sum_all = mqx.sum() # Return 0-dimensional MQuadExpr object
sum_row = mqx.sum(axis = 0) # Return a 1-dimensional MQuadExpr object with a shape of (2, )

MQuadExpr.tolist()

Synopsis

tolist()

Description

Converts an MQuadExpr object to a one-dimensional list whose elements are linear expressions.

Return value

Return a 1D list containing LinExpr Class.

Example

print(MQuadExpr.zeros((2,3)).tolist()) # a list of length 6

MQuadExpr.transpose()

Synopsis

transpose()

Description

Generates a new MQuadExpr object that is the transpose of the original MQuadExpr object.

Return value

Returns the transposed MQuadExpr object.

Example

mqx = MQuadExpr.zeros((2,3))
print(mqx.transpose().shape) # shape = (3, 2)

MQuadExpr.ndim

Synopsis

ndim

Description

MQuadExpr Class Dimensions of the object.

Return value

Integer value.

Example

mqx = MQuadExpr.zeros((2,3))
print(mqx.ndim)  # ndim = 2

MQuadExpr.shape

Synopsis

shape

Description

MQuadExpr Class The shape of the object.

Return value

Integer tuple.

Example

print(MQuadExpr.zeros((2,3)).shape) # shape = (2, 3)

MQuadExpr.size

Synopsis

size

Description

The number of elements of MQuadExpr Class object.

Return value

Integer value.

Example

mqx = MQuadExpr.zeros((2,3))
print(mqx.size)  # size= 6

MQuadExpr.T

Synopsis

T

Description

Transpose of MQuadExpr Class object. Similar to the class method transpose().

Return value

Returns the transposed MQuadExpr object.

Example

mqx = MQuadExpr.zeros((2,3))
print(mqx.T.shape) # shape = (3, 2)

MQuadExpr.__eq__()

Synopsis

__eq__()

Description

Overload the == operator to build a MQConstrBuilder Class object, which can be passed as the first argument to Model.addQConstr.

Return value

Example

model.addQConstr(x @ Q @ y == 1.0)

MQuadExpr.__ge__()

Synopsis

__ge__()

Description

Overload the >= operator to build a MQConstrBuilder Class object, which can be passed as the first argument to Model.addQConstr.

Return value

Example

model.addQConstr(x @ Q @ y >= 1.0)

MQuadExpr.__le__()

Synopsis

__le__()

Description

Overload the <= operator to build a MQConstrBuilder Class object, which can be passed as the first argument to Model.addQConstr.

Return value

Example

model.addQConstr(x @ Q @ y <= 1.0)

NdArray Class

The NdArray class is a built-in multi-dimensional array class in COPT. It represents a table of elements of the same type, indexed by a tuple of integers. The following methods are provided:

NdArray()

Synopsis

NdArray(args=None, dtype=None, shape=None)

Description

Create a NdArray Class object.

Return value

Returns a NdArray object.

Example

# Create a NdArray object with a shape of 3x3 and initialize its elements to 0
ndmat = NdArray(shape=(3, 3))

NdArray.item()

Synopsis

item()

Description

Gets the single element within a 0-dimensional NdArray object. If the NdArray object is not 0-dimensional, a ValueError exception will be triggered.

Return value

Returns the type of the elements in the 0-dimensional NdArray object. (For example: "float" or "int", etc.)

Example

ndmat = NdArray(args=1.1, shape=(1,))
# Type of value is "float"
value = ndmat.item()

NdArray.reshape()

Synopsis

reshape(shape, order='C')

Description

Returns a new NdArray object whose elements remain unchanged where shape is transformed according to the shape in the arguments.

Arguments

shape

The value could be an integer or a tuple of integers, representing the shape of the new NdArray object.

order

Optional. The default is the character ‘C’, which means it is compatible with C language (stored in rows). The current version does not yet support the character ‘F’ (stored in columns).

Return value

Returns a new NdArray object with the same elements as the original one but a different shape.

Example

ndmat = NdArray(shape=(6,))
ndmat_2x3 = ndmat.reshape((2, 3))

NdArray.sum()

Synopsis

sum(axis=None)

Description

Sum the elements in NdArray according to given axis.

Arguments

axis

Optional integer argument. The default value is None, which means summing all elements. Otherwise, it will sum according to the given axis.

Return value

If axis is empty, returns a new 0-dimensional NdArray object, in which element is the sum of the corresponding elements.

If axis is non-empty, returns a new N-1-dimensional NdArray object, in which elements are the sum of the elements on the given axis.

Example

ndmat = NdArray(args=1.1, shape=(2, 2))
# Sum all elements in ndmat and return a 0-dimensional NdArray object
sum_all = ndmat.sum()
# Sum the elements in ndmat row by row and return a 1-dimensional NdArray object with a shape of (2, )
sum_row = ndmat.sum(axis=0)

NdArray.tolist()

Synopsis

tolist()

Description

Convert a NdArray object into a list.

Return value

Returns a list object.

Example

# Type of object mat_tolist is "list"
mat_tolist = ndmat.tolist()

NdArray.tonumpy()

Synopsis

tonumpy()

Description

Convert a NdArray object to a NumPy ndarray object.

Return value

Returns a numpy ndarray object.

Example

# Type of object mat_tolist is "numpy.ndarray"
mat_tonumpy = ndmat.tonumpy()

NdArray.fill()

Synopsis

fill(value)

Description

Fills each element in the NdArray object with the specified value.

Arguments

value

The new value of each element in the NdArray object.

Return value

Returns a NdArray object.

Example

mat_fillvalue = ndmat.fill(100.0)

NdArray.expand()

Synopsis

expand(axis=0)

Description

Expand the NdArray object into an N+1 dimensional shape on the axis.

Arguments

axis

The specified dimension, which defaults to 0 (the first dimension).

Return value

Returns a N+1 dimensional NdArray object.

Example

mat_1 = ndmat.expand()

NdArray.squeeze()

Synopsis

squeeze(axis=0)

Description

Reduce the NdArray object to an N-1 dimensional shape on the axis.

Arguments

axis

The specified dimension, default to 0 (the first dimension).

Return value

Returns a N-1 dimensional NdArray object.

Example

mat_1 = ndmat.squeeze()

NdArray.flatten()

Synopsis

flatten()

Description

Expand a NdArray object into a one-dimensional shape.

Return value

Returns a new one-dimensional NdArray object.

Example

ndmat = NdArray(shape=(2, 2))
# The shape of mat_1 is (4,)
mat_1 = ndmat.flatten()

NdArray.setItem()

Synopsis

setItem(idx, value)

Description

Sets the value of the element according to the given index in the NdArray object.

Arguments

idx

The specified one-dimensional index is the corresponding one after flattening NdArray into one dimension.

value

The new value of the specified element.

Return value

Returns a NdArray object in which the element value of idx is set to value.

Example

# Set the value of the element at index 0 to 100
mat_1 = ndmat.setItem(0, 100)

NdArray.transpose()

Synopsis

transpose()

Description

Generates a new NdArray object, which is the transpose of the original one.

Return value

Returns a new NdArray object.

Example

ndmat = NdArray(shape=(3, 5))
print(ndmat.transpose().shape) #shape=(5, 3)

NdArray.diagonal()

Synopsis

diagonal(offset=0, axis1=0, axis2=1)

Description

Generate a NdArray Class object, in which elements are the ones on the diagonal of the original NdArray object.

Arguments

offset

Optional argument, indicating the offset of the diagonal, the default value is 0. If the value is greater than 0, it represents the upward offset of the diagonal. If the value is less than 0, it represents the downward offset of the diagonal.

axis1

Optional argument. Axis to be used as the first axis of the 2-D sub-NdArrays from which the diagonals should be taken. Defaults to first axis (0).

axis2

Optional argument. Axis to be used as the second axis of the 2-D sub-NdArrays from which the diagonals should be taken. Defaults to second axis (1).

Return value

A new NdArray object.

Example

ndmat = NdArray(shape=(3, 3),args=[[1,1,1],[2,2,2],[3,3,3]])

diag_m0 = ndmat.diagonal(0)
diag_a1 = ndmat.diagonal(1)
diag_b1 = ndmat.diagonal(-1)

NdArray.ndim

Synopsis

ndim

Description

The dimensions of the NdArray object.

Return value

An integer Value

Example

ndmat = NdArray((3, 5))
print(ndmat.ndim) # ndim = 2

NdArray.shape

Synopsis

shape

Description

The shape of the NdArray object.

Return value

An integer tuple.

Example

ndmat = NdArray((3, 5))
print(ndmat.shape) # shape = (3, 5)

NdArray.size

Synopsis

size

Description

The number of elements in the NdArray object.

Return value

An integer value.

Example

ndmat = NdArray((3, 5))
print(ndmat.size) # size = 15

NdArray.T

Synopsis

T

Description

Transpose of NdArray objects, similar to the method NdArray.transpose() .

Return value

Returns the transposed NdArray object.

Example

ndmat = NdArray(shape=(3, 5))
print(ndmat.T.shape) # shape = (5, 3)

ExprBuilder Class

ExprBuilder object contains operations related to building linear expressions, and provides the following methods:

ExprBuilder()

Synopsis

ExprBuilder(arg1=0.0, arg2=None)

Description

Create a ExprBuilder Class object.

If argument arg1 is constant, argument arg2 is None, then create a ExprBuilder Class object and initialize it using argument arg1. If argument arg1 is Var Class or ExprBuilder Class object, and argument arg2 is constant or considered to be constant 1.0 when argument arg2 is None, then initialize the newly created ExprBuilder Class object using arguments arg1 and arg2. If argument arg1 and arg2 are list objects, then they are variables and coefficients used to initialize the newly created ExprBuilder Class object.

Arguments

arg1

Optional, 0.0 by default.

arg2

Optional, None by default.

Example

# Create a new ExprBuilder object and initialize it to 0.0
expr0 = ExprBuilder()
# Create a ExprBuilder object and initialize it to x + 2*y
expr2 = ExprBuilder([x, y], [1, 2])

ExprBuilder.getSize()

Synopsis

getSize()

Description

Retrieve the number of terms in an expression builder.

Example

# Retrieve the number of terms in expression builder 'expr'
exprsize = expr.getSize()

ExprBuilder.getCoeff()

Synopsis

getCoeff(idx)

Description

Retrieve the coefficient of a variable by its index from an expression builder.

Arguments

idx

Index of the variable in the expression builder, starting with 0.

Example

# Retrieve the coefficient for the term at index 1 from expression builder 'expr'
coeff = expr.getCoeff(1)

ExprBuilder.getVar()

Synopsis

getVar(idx)

Description

Retrieve the variable by its index from an expression builder. Return a Var Class object.

Arguments

idx

Index of the variable in the expression builder, starting with 0.

Example

# Retrieve the variable for the term at index 1 from expression builder 'expr'
x = expr.getVar(1)

ExprBuilder.getConstant()

Synopsis

getConstant()

Description

Retrieve the constant term from an expression builder.

Example

# Retrieve the constant term from linear expression builder 'expr'
constant = expr.getConstant()

ExprBuilder.addTerm()

Synopsis

addTerm(var, coeff=1.0)

Description

Add a new term to current expression builder.

Arguments

var

Variable to add.

coeff

Magnification coefficient for added term. Optional, 1.0 by default.

Example

# Add term 2*x to linear expression builder 'expr'
expr.addTerm(x, 2.0)

ExprBuilder.addExpr()

Synopsis

addExpr(expr, coeff=1.0)

Description

Add new expression builder to the current one.

Arguments

expr

Expression builder to add.

coeff

Magnification coefficients for the added expression builder. Optional, 1.0 by default.

Example

# Add linear expression builder 2*x + 2*y to 'expr'
expr.addExpr(x + y, 2.0)

ExprBuilder.clone()

Synopsis

clone()

Description

Create a deep copy of the expression builder.

Example

# Create a deep copy of expression builder 'expr'
exprcopy = expr.clone()

ExprBuilder.getExpr()

Synopsis

getExpr()

Description

Create a linear expression related to the expression builder. Returns a LinExpr Class object.

Example

# Get the linear expression object related to expression builder 'exprbuilder'
expr = exprbuilder.getExpr()

LinExpr Class

LinExpr object contains operations related to variables for building linear constraints, and provides the following methods:

LinExpr()

Synopsis

LinExpr(arg1=0.0, arg2=None)

Description

Create a LinExpr Class object.

If argument arg1 is constant, argument arg2 is None, then create a LinExpr Class object and initialize it using argument arg1. If argument arg1 is Var Class or LinExpr Class object, and argument arg2 is constant or considered to be constant 1.0 when argument arg2 is None, then initialize the newly created LinExpr Class object using arguments arg1 and arg2. If argument arg1 is list object and argument arg2 is None, then argument arg1 contains a list of variable-coefficient pairs and initialize the newly created LinExpr Class object using arguments arg1 and arg2. For other forms of arguments, call method addTerms to initialize the newly created LinExpr Class object.

Arguments

arg1

Optional, 0.0 by default.

arg2

Optional, None by default.

Example

# Create a new LinExpr object and initialize it to 0.0
expr0 = LinExpr()
# Create a LinExpr object and initialize it to 2*x + 3*y
expr1 = LinExpr([(x, 2), (y, 3)])
# Create a LinExpr object and initialize it to x + 2*y
expr2 = LinExpr([x, y], [1, 2])

LinExpr.setCoeff()

Synopsis

setCoeff(idx, newval)

Description

Set new coefficient value of a variable based on its index in an expression.

Arguments

idx

Index of the variable in the expression, starting with 0.

newval

New coefficient value of the variable.

Example

# Set the coefficient for the term at index 0 in expression expr to 1.0
expr.setCoeff(0, 1.0)

LinExpr.getCoeff()

Synopsis

getCoeff(idx)

Description

Retrieve the coefficient of a variable by its index from an expression.

Arguments

idx

Index of the variable in the expression, starting with 0.

Example

# Retrieve the coefficient for the term at index 1 from expression expr
coeff = expr.getCoeff(1)

LinExpr.getVar()

Synopsis

getVar(idx)

Description

Retrieve the variable by its index from an expression. Return a Var Class object.

Arguments

idx

Index of the variable in the expression, starting with 0.

Example

# Retrieve the variable for the term at index 1 from expression expr
x = expr.getVar(1)

LinExpr.getConstant()

Synopsis

getConstant()

Description

Retrieve the constant term from an expression.

Example

# Retrieve the constant term from linear expression expr
constant = expr.getConstant()

LinExpr.getValue()

Synopsis

getValue()

Description

Retrieve the value of an expression computed using the current solution.

Example

# Retrieve the value of expression expr for the current solution.
val = expr.getValue()

LinExpr.getSize()

Synopsis

getSize()

Description

Retrieve the number of terms in an expression.

Example

# Retrieve the number of terms in expression expr
exprsize = expr.getSize()

LinExpr.setConstant()

Synopsis

setConstant(newval)

Description

Set the constant term of linear expression.

Arguments

newval

Constant term to be set.

Example

# Set constant term of linear expression 'expr' to 2.0
expr.setConstant(2.0)

LinExpr.addConstant()

Synopsis

addConstant(newval)

Description

Add a constant to an expression.

Arguments

newval

Constant to add.

Example

# Add constant 2.0 to linear expression 'expr'
expr.addConstant(2.0)

LinExpr.addTerm()

Synopsis

addTerm(var, coeff=1.0)

Description

Add a new term to current expression.

Arguments

var

Variable to add.

coeff

Magnification coefficient for added term. Optional, 1.0 by default.

Example

# Add term x to linear expression 'expr'
expr.addTerm(x)

LinExpr.addTerms()

Synopsis

addTerms(vars, coeffs)

Description

Add a single term or multiple terms into an expression.

If argument vars is Var Class object, then argument coeffs is constant; If argument vars is VarArray Class object or list, then argument coeffs is constant or list; If argument vars is dictionary or tupledict Class object, then argument coeffs is constant, dict, or tupledict Class object.

Arguments

vars

Variables to add.

coeffs

Coefficients for variables.

Example

# Add term 2*x + 2*y to linear expression 'expr'
expr.addTerms([x, y], [2.0, 3.0])

LinExpr.addExpr()

Synopsis

addExpr(expr, coeff=1.0)

Description

Add new expression to the current one.

Arguments

expr

Expression or expression builder to add.

coeff

Magnification coefficients for the added expression. Optional, 1.0 by default.

Example

# Add linear expression 2*x + 2*y to 'expr'
expr.addExpr(x + y, 2.0)

LinExpr.clone()

Synopsis

clone()

Description

Create a deep copy of the expression.

Example

# Create a deep copy of expression expr
exprcopy = expr.clone()

LinExpr.reserve()

Synopsis

reserve(n)

Description

Pre-allocate space for linear expression object.

Arguments

n

Number of terms to be allocated.

Example

# Allocate 100 terms for linear expression 'expr'
expr.reserve(100)

LinExpr.remove()

Synopsis

remove(item)

Description

Remove a term from a linear expression.

If argument item is constant, then remove the term stored at index i of the expression; otherwise argument item is Var Class object.

Arguments

item

Constant index or variable of the term to be removed.

Example

# Remove the term whose index is 2 from linear expression expr
expr.remove(2)
# Remove the term whose variable is x from linear expression expr
expr.remove(x)

QuadExpr Class

QuadExpr object contains operations related to variables for building linear constraints, and provides the following methods:

QuadExpr()

Synopsis

QuadExpr(expr=0.0)

Description

Create a QuadExpr Class object.

Argument expr is constant, Var Class, LinExpr Class object or QuadExpr Class object.

Arguments

expr

Optional, 0.0 by default.

Example

# Create a new QuadExpr object and initialize it to 0.0
quadexpr0 = QuadExpr()
# Create a QuadExpr object and initialize it to 2*x + 3*y
quadexpr1 = QuadExpr([(x, 2), (y, 3)])
# Create a QuadExpr object and initialize it to x*x + 2*x*y
quadexpr2 = QuadExpr(x*x + 2*x*y)

QuadExpr.setCoeff()

Synopsis

setCoeff(idx, newval)

Description

Set new coefficient value of a term based on its index in a quadratic expression.

Arguments

idx

Index of the term in the quadratic expression, starting with 0.

newval

New coefficient value of the term.

Example

# Set the coefficient for the term at index 0 in quadratic expression quadexpr to 1.0
quadexpr.setCoeff(0, 1.0)

QuadExpr.getCoeff()

Synopsis

getCoeff(idx)

Description

Retrieve the coefficient of a term by its index from a quadratic expression.

Arguments

idx

Index of the term in the quadratic expression, starting with 0.

Example

# Retrieve the coefficient for the term at index 1 from quadratic expression quadexpr
coeff = quadexpr.getCoeff(1)

QuadExpr.getVar1()

Synopsis

getVar1(idx)

Description

Retrieve the first variable of a quadratic term by its index from an expression. Return a Var Class object.

Arguments

idx

Index of the quadratic term in the expression, starting with 0.

Example

# Retrieve the first variable of a quadratic term at index 1 from quadratic expression quadexpr
x = quadexpr.getVar1(1)

QuadExpr.getVar2()

Synopsis

getVar2(idx)

Description

Retrieve the second variable of a quadratic term by its index from an expression. Return a Var Class object.

Arguments

idx

Index of the quadratic term in the expression, starting with 0.

Example

# Retrieve the first variable of a quadratic term at index 1 from quadratic expression quadexpr
y = quadexpr.getVar2(1)

QuadExpr.getLinExpr()

Synopsis

getLinExpr()

Description

Retrieve the linear terms (if exist) fronm quadratic expression. Return a LinExpr Class object.

Example

# Retrieve the linear terms from a quadratic expression quadexpr
linexpr = quadexpr.getLinExpr()

QuadExpr.getConstant()

Synopsis

getConstant()

Description

Retrieve the constant term from a quadratic expression.

Example

# Retrieve the constant term from quadratic expression quadexpr
constant = quadexpr.getConstant()

QuadExpr.getValue()

Synopsis

getValue()

Description

Retrieve the value of a quadratic expression computed using the current solution.

Example

# Retrieve the value of quadratic expression quadexpr for the current solution.
val = quadexpr.getValue()

QuadExpr.getSize()

Synopsis

getSize()

Description

Retrieve the number of terms in a quadratic expression.

Example

# Retrieve the number of terms in quadratic expression quadexpr
exprsize = quadexpr.getSize()

QuadExpr.setConstant()

Synopsis

setConstant(newval)

Description

Set the constant term of quadratic expression.

Arguments

newval

Constant to set.

Example

# Set constant term of quadratic expression 'quadexpr' to 2.0
quadexpr.setConstant(2.0)

QuadExpr.addConstant()

Synopsis

addConstant(newval)

Description

Add a constant to a quadratic expression.

Arguments

newval

Constant to add.

Example

# Add constant 2.0 to quadratic expression 'quadexpr'
quadexpr.addConstant(2.0)

QuadExpr.addTerm()

Synopsis

addTerm(coeff, var1, var2=None)

Description

Add a new term to current quadratic expression.

Arguments

coeff

Magnification coefficient for added term. Optional, 1.0 by default.

var1

The first variable for added term.

var2

The second variable for added term, defaults to None, i.e. add a linear term.

Example

# Add term x to quadratic expression 'quadexpr'
quadexpr.addTerm(1.0, x)

QuadExpr.addTerms()

Synopsis

addTerms(coeffs, vars1, vars2=None)

Description

Add a single term or multiple terms into a quadratic expression.

If argument vars is Var Class object, then argument vars2 is Var Class object or None, argument coeffs is constant; If argument vars is VarArray Class object or list, then argument vars2 is VarArray Class object, list or None, argument coeffs is constant or list; If argument vars is dictionary or tupledict Class object, then argument vars2 is dictionary, tupledict Class object or None, argument coeffs is constant, dictionary, or tupledict Class object.

Arguments

coeffs

Coefficients for terms.

vars1

The first variable of each term.

vars2

The second variable of each term, defaults to None, i.e. add a linear term.

Example

# Add term 2*x + 3y + 2*x*x + 3*x*y to quadratic expression 'quadexpr'
# Note: Mixed format is supported by addTerms yet.
quadexpr.addTerms([2.0, 3.0], [x, y])
quadexpr.addTerms([2.0, 3.0], [x, x], [x, y])

QuadExpr.addLinExpr()

Synopsis

addLinExpr(expr, mult=1.0)

Description

Add new linear expression to the current quadratic expression.

Arguments

expr

Linear expression or linear expression builder to add.

mult

Magnification coefficient for the added expression. Optional, 1.0 by default.

Example

# Add linear expression 2*x + 2*y to 'quadexpr'
quadexpr.addLinExpr(x + y, 2.0)

QuadExpr.addQuadExpr()

Synopsis

addQuadExpr(expr, mult=1.0)

Description

Add new quadratic expression to the current one.

Arguments

expr

Expression or expression builder to add.

mult

Magnification coefficients for the added expression. Optional, 1.0 by default.

Example

# Add quadratic expression x*x + 2*y to 'quadexpr'
quadexpr.addQuadExpr(x*x + 2*y, 2.0)

QuadExpr.clone()

Synopsis

clone()

Description

Create a deep copy of the expression.

Example

# Create a deep copy of quadratic expression quadexpr
exprcopy = quadexpr.clone()

QuadExpr.reserve()

Synopsis

reserve(n)

Description

Pre-allocate space for quadratic expression object.

Arguments

n

Number of terms to be allocated.

Example

# Allocate 100 terms for quadratic expression 'expr'
expr.reserve(100)

QuadExpr.remove()

Synopsis

remove(item)

Description

Remove a term from a quadratic expression.

If argument item is constant, then remove the term stored at index i of the expression; otherwise argument item is Var Class object.

Arguments

item

Constant index or variable of the term to be removed.

Example

# Remove the term whose index is 2 from quadratic expression quadexpr
quadexpr.remove(2)
# Remove the terms one of which variable is x from quadratic expression quadexpr
quadexpr.remove(x)

PsdExpr Class

PsdExpr object contains operations related to variables for building positive semi-definite constraints, and provides the following methods:

PsdExpr()

Synopsis

PsdExpr(expr=0.0)

Description

Create a PsdExpr Class object.

Arguments

expr

Optional, 0.0 by default, which can be a constant, Var Class, LinExpr Class object or PsdExpr Class object.

Example

# Create a new PsdExpr object and initialize it to 0.0
expr0 = PsdExpr()
# Create a PsdExpr object and initialize it to 2*x + 3*y
expr1 = PsdExpr(2*x + 3*y)

PsdExpr.setCoeff()

Synopsis

setCoeff(idx, mat)

Description

Set the coefficient symmetric matrix corresponding to the specified index value idx in the LMI expression.

Arguments

idx

Index of the positive semi-definite variable in the expression, starting with 0.

mat

New symmetric matrix coefficient of the positive semi-definite variable.

Example

# Set symmetric matrix for the positive semi-definite variable at index 0 in expression "expr" to mat
expr.setCoeff(0, mat)

PsdExpr.getCoeff()

Synopsis

getCoeff(idx)

Description

Retrieve the symmetric matrix coefficient of a positive semi-definite variable by its index from the expression.

Arguments

idx

Index of the positive semi-definite variable in the expression, starting with 0.

Example

# Retrieve the symmetric matrix coefficient for the positive semi-definite variable at index 1 from expression expr
mat = expr.getCoeff(1)

PsdExpr.getPsdVar()

Synopsis

getPsdVar(idx)

Description

Retrieve a positive semi-definite variable by its index from the expression. Return a PsdVar Class object.

Arguments

idx

Index of the positive semi-definite variable in the expression, starting with 0.

Example

# Retrieve the positive semi-definite variable at index 1 from expression expr
x = expr.getPsdVar(1)

PsdExpr.getLinExpr()

Synopsis

getLinExpr()

Description

Retrieve the linear terms (if exist) from positive semi-definite expression. Return a LinExpr Class object.

Example

# Retrieve the linear terms from a positive semi-definite expression expr
linexpr = expr.getLinExpr()

PsdExpr.getConstant()

Synopsis

getConstant()

Description

Retrieve the constant term from a positive semi-definite expression.

Example

# Retrieve the constant term from expression expr
constant = expr.getConstant()

PsdExpr.getValue()

Synopsis

getValue()

Description

Retrieve the value of a positive semi-definite expression computed using the current solution.

Example

# Retrieve the value of positive semi-definite expression expr for the current solution.
val = expr.getValue()

PsdExpr.getSize()

Synopsis

getSize()

Description

Retrieve the number of terms in a positive semi-definite expression.

Example

# Retrieve the number of terms in expression expr
exprsize = expr.getSize()

PsdExpr.setConstant()

Synopsis

setConstant(newval)

Description

Set the constant term of positive semi-definite expression.

Arguments

newval

Constant to set.

Example

# Set constant term of expression 'expr' to 2.0
expr.setConstant(2.0)

PsdExpr.addConstant()

Synopsis

addConstant(newval)

Description

Add a constant to a positive semi-definite expression.

Arguments

newval

Constant to add.

Example

# Add constant 2.0 to expression 'expr'
expr.addConstant(2.0)

PsdExpr.addTerm()

Synopsis

addTerm(var, mat)

Description

Add a new term to current positive semi-definite expression.

Arguments

var

The positive semi-definite variable to add.

mat

The symmetric matrix coefficient for the positive semi-definite variable.

Example

# Add positive semi-definite term C1 * X to expression 'expr'
expr.addTerm(X, C1)

PsdExpr.addTerms()

Synopsis

addTerms(vars, mats)

Description

Add a single term or multiple positive semi-definite terms into a positive semi-definite expression.

If argument vars is PsdVar Class object, then argument mats is SymMatrix Class object; If argument vars is PsdVarArray Class object or list, then argument mats is SymMatrixArray Class or list;

Arguments

vars

The positive semi-definite variables to add.

mats

The symmetric matrices of the positive semi-definite terms.

Example

# Add terms C1 * X1 + C2 * X2 to expression 'expr'
expr.addTerms([X1, X2], [C1, C2])

PsdExpr.addLinExpr()

Synopsis

addLinExpr(expr, mult=1.0)

Description

Add new linear expression to the current positive semi-definite expression.

Arguments

expr

Linear expression or linear expression builder to add.

mult

Magnification coefficient for the added expression. Optional, 1.0 by default.

Example

# Add linear expression 2*x + 2*y to 'expr'
expr.addLinExpr(x + y, 2.0)

PsdExpr.addPsdExpr()

Synopsis

addPsdExpr(expr, mult=1.0)

Description

Add new positive semi-definite expression to the current one.

Arguments

expr

Positive semi-definite expression or positive semi-definite expression builder to add.

mult

Magnification coefficient for the added positive semi-definite expression. Optional, 1.0 by default.

Example

# Add positive semi-definite expression C * X to 'expr'
expr.addPsdExpr(C*X)

PsdExpr.clone()

Synopsis

clone()

Description

Create a deep copy of the expression.

Example

# Create a deep copy of expression expr
exprcopy = expr.clone()

PsdExpr.reserve()

Synopsis

reserve(n)

Description

Pre-allocate space for positive semi-definite expression object.

Arguments

n

Number of terms to be allocated.

Example

# Allocate 100 terms for positive semi-definite expression 'expr'
expr.reserve(100)

PsdExpr.remove()

Synopsis

remove(item)

Description

Remove a term from a positive semi-definite expression.

If argument item is constant, then remove the term stored at index i of the expression; otherwise argument item is PsdVar Class object.

Arguments

item

Constant index or PsdVar Class variable of the term to be removed.

Example

# Remove the term whose index is 2 from positive semi-definite expression expr
expr.remove(2)
# Remove the terms one of which variable is x from positive semi-definite expression expr
expr.remove(x)

LmiExpr Class

LmiExpr object contains operations related to variables for building LMI constraints, and provides the following methods:

LmiExpr()

Synopsis

LmiExpr(arg1=None, arg2=None)

Description

Create a LmiExpr Class object.

Arguments

The default value of arg1 is None, and the possible values are: Var Class object, or SymMatrix Class object.

If the argument arg1 is a Var Class object, then the argument arg2 is a SymMatrix Class object.

LmiExpr.setCoeff()

Synopsis

setCoeff(idx, mat)

Description

Set the coefficient matrix for the entry corresponding to the specified index idx in the LMI expression.

Arguments

idx

The specified the index value. Starts with 0.

mat

The new coefficient symmetric matrix of the variable to be set, which must be a SymMatrix Class class object.

Example

# Set the coefficient of the 0-th term of the LMI expression expr to the symmetric matrix mat
expr.setCoeff(0, mat)

LmiExpr.getCoeff()

Synopsis

getCoeff(idx)

Description

Get the coefficient matrix for the entry corresponding to the specified index idx in the LMI expression.

Arguments

idx

The specified the index value. Starts with 0.

Example

# Get the symmetric matrix coefficient of the 1st term of the LMI expression expr
mat = expr.getCoeff(1)

LmiExpr.getVar()

Synopsis

getVar(idx)

Description

Get the variable in the entry corresponding to the specified index idx in the LMI expression.

Arguments

idx

The specified the index value. Starts with 0.

Example

# Get the variable of the 1st item of the LMI expression expr
mat = expr.getVar(1)

LmiExpr.getConstant()

Synopsis

getConstant()

Description

Get the constant-term symmetric matrix in the LMI expression.

Example

# Get the constant term of the LMI expression expr
constant = expr.getConstant()

LmiExpr.getSize()

Synopsis

getSize()

Description

Retrieve the number of terms in the LMI expression.

Example

# Retrieve the number of terms in the LMI expression expr.
val = expr.getSize()

LmiExpr.setConstant()

Synopsis

setConstant(mat)

Description

Set the constant-term symmetric matrix of the LMI expression.

Arguments

mat

The symmetric matrix corresponding to the constant item, must be a SymMatrix Class object.

Example

# Sets the constant term of the LMI expression expr to the symmetric matrix D1
expr.setConstant(D1)

LmiExpr.addConstant()

Synopsis

addConstant(mat)

Description

Add the symmetric matrix to constant term of the LMI expression.

Arguments

mat

Matrix expression object added to constant term.

Example

# Add to the constant term of the LMI expression expr with symmetric matrix D2
expr.addConstant(D2)

LmiExpr.addTerm()

Synopsis

addTerm(var, mat)

Description

Add a new term to current LMI expression.

Arguments

var

The variable in the new item.

mat

The symmetric matrix as variable coefficients in the new term.

Example

# Add the term C1 * X to expression 'expr'
expr.addTerm(x, C1)

PsdExpr.addTerms()

Synopsis

addTerms(vars, mats)

Description

Adds multiple new terms to the LMI expression.

If argument vars is PsdVar Class object, then argument mats is SymMatrix Class object; If argument vars is PsdVarArray Class object or list, then argument mats is SymMatrixArray Class or list;

Arguments

vars

Array of variables to add new items to.

mats

The symmetric array of matrices to add new items to.

Example

# Add terms x1 * C1 + x2 * C2 to expression 'expr'
expr.addTerms([x1, x2], [C1, C2])

LmiExpr.addLmiExpr()

Synopsis

addLmiExpr(expr, mult=1.0)

Description

Add a new LMI expression to the current LMI expression.

Arguments

expr

LMI expression to add.

mult

Magnification coefficient for the added LMI expression. Optional, 1.0 by default.

Example

# Add linear expression 2 * x * C to 'expr'
expr.addLinExpr(x * C, 2.0)

LmiExpr.clone()

Synopsis

clone()

Description

Create a deep copy of the expression.

Example

# Create a deep copy of expression expr
exprcopy = expr.clone()

LmiExpr.reserve()

Synopsis

reserve(n)

Description

Pre-allocate space for LMI expression object.

Arguments

n

Number of terms to be allocated.

Example

# Allocate 100 terms for LMI expression 'expr'
expr.reserve(100)

LmiExpr.remove()

Synopsis

remove(item)

Description

Remove a term from the LMI expression.

If argument item is constant, then remove the term stored at index i of the expression; otherwise argument item is Var Class object.

Arguments

item

Constant index or Var Class variable of the term to be removed.

Example

# Remove the term whose index is 2 from positive semi-definite expression expr
expr.remove(2)
# Remove the terms one of which variable is x from LMI expression expr
expr.remove(x)

CallbackBase Class

COPT CallbackBase class. This is an abstract class, the user needs to implement the function CallbackBase.callback() to create an instance. The instance is passed in as the first argument of the method Model.setCallback()

CallbackBase.where()

Synopsis

where()

Description

Get context in callback.

Return value

Returns an integer value.

CallbackBase.callback()

Synopsis

callback()

Description

The callback function is a pure virtual function which needs to be implemented by the user. The user can describe the information that needs to be obtained or the operation that needs to be performed during the solution process.

Example

class CoptCallback(CallbackBase):
    def __init__(self):
        super().__init__()
    def callback(self):
        # Get the objective value when finding a feasible MIP solution
        if self.where() == COPT.CBCONTEXT_MIPSOL:
            db = self.getInfo(COPT.CBInfo.MipCandObj)

CallbackBase.interrupt()

Synopsis

interrupt()

Description

Interrupt the callback process.

CallbackBase.addUserCut()

Synopsis

addUserCut(lhs, sense = None, rhs = None)

Description

Add a user cut to the MIP model from within the callback function.

Arguments

lhs

Left-hand side expression for the new user cut. It can take the value of Var Class object, LinExpr Class object, or ConstrBuilder Class .

sense

The sense of the new user cut. It supports for LESS_EQUAL, GREATER_EQUAL, EQUAL and FREE .

Optional. None by default.

The user cut added from within callback can only have a single comparison operator.

rhs

Right-hand side expression for the new user cut.

Optional. None by default.

It can be a constant, or Var Class object, or LinExpr Class object.

Example

self.addUserCut(x+y <= 1)

CallbackBase.addUserCuts()

Synopsis

addUserCuts(generator)

Description

Add a set of user cuts to the MIP model from within the callback function.

Arguments

generator

Array of builders for user cuts. It can be ConstrBuilderArray Class object or MConstrBuilder Class object.

Example

self.addUserCuts(x[i]+y[i] <= 1 for i in range(10))

CallbackBase.addLazyConstr()

Synopsis

addLazyConstr(lhs, sense = None, rhs = None)

Description

Add a lazy constraint to the MIP model from within the callback function.

Arguments

lhs

Left-hand side expression for the new lazy constraint. It can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object.

sense

The sense of the lazy constraint. It supports for LESS_EQUAL, GREATER_EQUAL, EQUAL and FREE .

Optional. None by default.

The lazy constraint added from within callback can only have a single comparison operator.

rhs

Right-hand side expression for the new lazy constraint.

Optional. None by default.

It can be a constant, or Var Class object, or LinExpr Class object.

Example

self.addLazyConstr(x+y <= 1)

CallbackBase.addLazyConstrs()

Synopsis

addLazyConstrs(generator)

Description

Add a set of lazy constraints to the MIP model from within the callback function.

Arguments

generator

Array of builders for lazy constraints. It can be ConstrBuilderArray Class object or MConstrBuilder Class object.

Example

self.addLazyConstrs(x[i] + y[i] <= 1 for i in range(10))

CallbackBase.getInfo()

Synopsis

getInfo(cbinfo)

Description

Retrieve the value of the specified callback information.

Arguments

cbinfo

The name of the callback information. Please refer to Callback Information for possible values.

Return value

Returns a constant(int-valued or double-valued).

Example

db = self.getInfo(COPT.CBInfo.BestBnd)

CallbackBase.getRelaxSol()

Synopsis

getRelaxSol(vars)

Description

Retrieve the LP-relaxation solution of the specified variables at the current node.

Note that this method can only be invoked if CallbackBase.where() == COPT.CBCONTEXT_MIPRELAX.

Arguments

vars

The variables to retrieve the LP-relaxation solution values.

Return value

When parameter vars is Var Class object, it returns a constant, which is the LP-relaxation solution value of the specified variable.

When parameter vars is list or VarArray Class object, it returns a list of constants, consisting of the solution of the specified variables.

When parameter args is dictionary or tupledict Class object, it returns tupledict Class object(the indices of specified variables as key, the solutions of the specified variables as value).

When parameter args is None , it returns the LP-relaxation solution values of all variables.

Example

vals = self.getRelaxSol(vars)

CallbackBase.getIncumbent()

Synopsis

getIncumbent(vars)

Description

Retrieve values from the best feasible solution of the specified variables.

Arguments

vars

The variables whose solution values to retrieve.

Return value

When parameter vars is Var Class object, it returns a constant, which is the solution value of the specified variable.

When parameter vars is list or VarArray Class object, it returns a list of constants, consisting of the solution of the specified variables.

When parameter args is dictionary or tupledict Class object, it returns tupledict Class object(the indices of specified variables as key, the solutions of the specified variables as value).

When parameter args is None , it returns the incumbent values of all variables.

Example

vals = self.getIncumbent(vars)

CallbackBase.getSolution()

Synopsis

getSolution(vars)

Description

Retrieve values from the current solution of the specified variables.

Note that this method can only be invoked if CallbackBase.where() == COPT.CBCONTEXT_MIPSOL.

Arguments

vars

The variables whose solution values to retrieve.

Return value

When parameter vars is Var Class object, it returns a constant, which is the solution value of the specified variable.

When parameter vars is list or VarArray Class object, it returns a list of constants, consisting of the solution of the specified variables.

When parameter args is dictionary or tupledict Class object, it returns tupledict Class object(the indices of specified variables as key, the solutions of the specified variables as value).

When parameter args is None , it returns the solution values of all variables.

Example

vals = self.getSolution(vars)

CallbackBase.setSolution()

Synopsis

setSolution(vars, vals)

Description

Set feasible solution values for the specified variables.

When parameter vars is Var Class object, parameter vals is constant;

When parameter vars is dictionary or tupledict Class object, parameter vals can be constant, dictionary or tupledict Class object;

When parameter vars is list, VarArray Class object, parameter vals can be constant or list.

Arguments

vars

The variables to be set value.

vals

The values of the variables in the solution.

Example

self.setSolution(x, 1)

CallbackBase.loadSolution()

Synopsis

loadSolution()

Description

Load the currently feasible solution into model.

Note that a complete solution is required here.

Example

self.loadSolution()

GenConstrX Class

In the Model class, the constraints added by addGenConstrXXX (such as: addGenConstrMax) will return a GenConstrX object.

GenConstrX.getAttr()

Synopsis

getAttr(attrname)

Description

Get the attribute value of the GenConstrX class object, support to get the type and name of the GenConstrX class object.

Example

# Get the name of con_max
con_max.getAttr("name")
# Get the type of con_max
con_max.getAttr("type")

GenConstrX.setAttr()

Synopsis

setAttr(attrname)

Arguments

Set the attribute value of the GenConstrX class object, and support setting the name of the GenConstrX class object.

Example

# Set the name of con_max
con_max.setAttr("name")

CoptError Class

CoptError Class provides operations on error. An exception of the CoptError is thrown when error occurs in a method call corresponding to the underlying interface of solver. The following attributes are provided to retrieve error information:

  • CoptError.retcode

    Error code.

  • CoptError.message

    Error message.

Helper Functions and Utilities

Helper functions and utilities are encapsulated based on Python’s basic data types, providing easy-to-use data types to facilitate the rapid construction of complex optimization models. This section will explain its functions and usages.

Helper Functions

multidict()

Synopsis

multidict(data)

Description

Split a single dictionary into keys and multiple dictionaries. Return keys and dictionaries.

Arguments

data

A Python dictionary to be applied. Each key should map to a list of \(n\) values.

Example

keys, dict1, dict2 = multidict({
  "hello": [0, 1],
  "world": [2, 3]})

quicksum()

Synopsis

quicksum(data)

Description

Build expressions efficiently. Return a LinExpr Class object.

Arguments

data

Terms to add.

Example

expr = quicksum(m.getVars())

tuplelist Class

The tuplelist object is an encapsulation based on Python lists, and provides the following methods:

tuplelist()

Synopsis

tuplelist(list)

Description

Create and return a tuplelist Class object.

Arguments

list

A Python list.

Example

tl = tuplelist([(0, 1), (1, 2)])
tl = tuplelist([('a', 'b'), ('b', 'c')])

tuplelist.add()

Synopsis

add(item)

Description

Add an item to a tuplelist Class object

Arguments

item

Item to add, which can be a Python tuple.

Example

tl = tuplelist([(0, 1), (1, 2)])
tl.add((2, 3))

tuplelist.select()

Synopsis

select(pattern)

Description

Get all terms that match the specified pattern. Return a tuplelist Class object.

Arguments

pattern

Specified pattern.

Example

tl = tuplelist([(0, 1), (0, 2), (1, 2)])
tl.select(0, '*')

tupledict Class

The tupledict class is an encapsulation based on Python dictionaries, and provides the following methods:

tupledict()

Synopsis

tupledict(args, kwargs)

Description

Create and return a tupledict Class object.

Arguments

args

Positional arguments.

kwargs

Named arguments.

Example

d = tupledict([(0, "hello"), (1, "world")])

tupledict.select()

Synopsis

select(pattern)

Description

Get all terms that match the specified pattern. Return a tupledict Class object.

Arguments

pattern

Specified pattern.

Example

d = tupledict([(0, "hello"), (1, "world")])
d.select()

tupledict.sum()

Synopsis

sum(pattern)

Description

Sum all terms that match the specified pattern. Return a LinExpr Class object.

Arguments

pattern

Specified pattern.

Example

expr = x.sum()

tupledict.prod()

Synopsis

prod(coeff, pattern)

Description

Filter terms that match the specified pattern and multiply by coefficients. Return a LinExpr Class object.

Arguments

coeff

Coefficients, which can be a dict or a tupledict Class object.

pattern

Specified pattern.

Example

coeff = dict([(1, 0.1), (2, 0.2)])
expr  = x.prod(coeff)

ProbBuffer Class

The ProbBuffer is an encapsulation of buffer of string stream, and provides the following methods:

ProbBuffer()

Synopsis

ProbBuffer(buff)

Description

Create and return a ProbBuffer Class object.

Arguments

buff

Size of buffer, defaults to None, i.e. the buffer size is 0.

Example

# Create a buffer of size 100
buff = ProbBuffer(100)

ProbBuffer.getData()

Synopsis

getData()

Description

Get the contents of buffer.

Example

# Print the contents in buffer
print(buff.getData())

ProbBuffer.getSize()

Synopsis

getSize()

Description

Get the size of the buffer.

Example

# Get the size of the buffer
print(buff.getSize())

ProbBuffer.resize()

Synopsis

resize(sz)

Description

Resize the size of the buffer.

Arguments

sz

New size of buffer.

Example

# Resize the size of buffer to 100
buff.resize(100)