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
nameName of configuration parameter. Please refer to Client configuration for possible values.
valueValue 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
argPath 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
nameThe 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. (For floating or cluster license)
Example
# Close connection to remote server
env.close()
Envr.bindNumaCpu()
Synopsis
bindNumaCpu(numaNode)Description
Bind the CPUs for the current process to a NUMA node.
Arguments
numaNodeID of a NUMA node.
Example
env.bindNumaCpu(0)
Envr.bindNumaMem()
Synopsis
bindNumaMem(numaNode)Description
Bind memory for the current process to a NUMA node (Linux only).
Arguments
numaNodeID of a NUMA node.
Example
env.bindNumaMem(0)
Envr.getCpuAffinity()
Synopsis
getCpuAffinity()Description
Get CPU affinity for the current process, which is saved in an integer array.
Example
cpu_list = env.getCpuAffinity()
Envr.getNumaNodeCount()
Synopsis
getNumaNodeCount()Description
Get count of NUMA nodes.
Example
count = env.getNumaNodeCount()
Envr.setCpuAffinity()
Synopsis
setCpuAffinity(hexMask)Description
Set CPU affinity with given mask string.
Arguments
hexMaskCPU mask string of hexadecimal characters.
Example
env.setCpuAffinity("0f")
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
lbLower bound for new variable. Optional, 0.0 by default.
ubUpper bound for new variable. Optional,
COPT.INFINITYby default.
objObjective parameter for new variable. Optional, 0.0 by default.
vtypeVariable type. Optional,
COPT.CONTINUOUSby default. Please refer to Variable types for possible types.
nameName for new variable. Optional,
""by default, which is automatically generated by solver.
columnColumn corresponds to the variable. Optional,
Noneby 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
*indicesIndices for accessing the new variables.
lbLower bounds for new variables. Optional, 0.0 by default.
ubUpper bounds for new variables. Optional,
COPT.INFINITYby default.
objObjective costs for new variables. Optional, 0.0 by default.
vtypeVariable types. Optional,
COPT.CONTINUOUSby default. Please refer to Variable types for possible types.
nameprefixName 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
shapeThe value is an integer, or a tuple of integers. which represents the shape of a MVar Class object.
lbThe lower bound of the variable. Optional parameter, defaults to 0.0.
ubThe upper bound of the variable. Optional parameter, defaults to
COPT.INFINITY.
objThe objective function coefficients for the variables. Optional parameter, defaults to 0.0.
vtypeThe type of the variable. Optional parameter, the default is
COPT.CONTINUOUS, see the possible values in Variable types.
nameprefixVariable 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 or MConstr Class object;
Add a semidefinite constraint to the model, return PsdConstraint Class object or MPsdConstr 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
lhscan take the value of Var Class object, LinExpr Class object, ConstrBuilder Class object or MConstrBuilder Class .If a positive semi-definite constraint added, then the parameter
lhscan take the value of PsdExpr Class object, PsdConstrBuilder Class object or MPsdConstrBuilder Class .If an indicator constraint added, then the parameter
lhsis GenConstrBuilder Class object, ignoring other parameters.If a LMI constraint added, then the parameter
lhscan take the value of LmiExpr Class object.Arguments
lhsLeft-hand side expression for new linear constraint or constraint builder.
senseSense for the new constraint. Optional, None by default. Please refer to Constraint type for possible values.
rhsRight-hand side expression for the new constraint. Optional, None by default. It can be a constant, or Var Class object, or LinExpr Class object.
nameName 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
exprExpression for the new constraint, which can be Var Class object or LinExpr Class object.
lbLower bound for the new constraint. Optional,
-COPT.INFINITYby default.
ubUpper bound for the new constraint. Optional,
COPT.INFINITYby default.
nameName 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, semidefinite constraints, or indicator constraints to the model.
If paramter
generatoris integer, the return a ConstrArray Class object consisting ofgeneratornumber of empty Constraint Class objects, and users need to specify these constraints.If parameter
generatoris 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
generatoris a matrix expression generator, return a MConstr Class object or a MPsdConstr Class object.If the parameter
generatoris an indicator expression generator, return a GenConstrArray Class object.Arguments
generatorA generator expression, where each iteration produces a Constraint Class object, or a matrix expression builder, or an indicator expression generator.
nameprefixName 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
sensehere isCOPT.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
AParameter A is a two-dimensional NumPy matrix, SciPy compressed sparse column matrix (
csc_matrix) or compressed sparse row matrix (csr_matrix).
xThe 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.
senseThe type of constraint. Possible values refer to Constraint type.
bThe 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.
nameprefixConstraint 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
sostypeis SOSBuilder Class object, then the values of paramvarsand param``weights`` will be ignored;If param
sostypeis SOS constraint type, it can be valued as SOS-constraint types, then paramvarsrepresents variables of SOS constraint, taking the value of VarArray Class object, list, dict or tupledict Class object;If param
weightsisNone, 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
sostypeSOS contraint type or SOS constraint builder.
varsVariables of SOS constraints.
weightsWeights of variables in SOS constraints, optional,
Noneby 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
lhsis ConstrBuilder Class object, then the values of parametersenseand parameterrhswill be ignored.If parameter
lhsrepresents Left-hand side expression, it can take value of Var Class object or LinExpr Class object.Arguments
binvarIndicator variable.
binvalValue of indicator variable, can be
TrueorFalse.
lhsLeft-hand side expression for the linear constraint triggered by the indicator or linear constraint builder.
senseSense for the linear constraint. Optional,
Noneby default. Please refer to Constraint type for possible values.
rhsRight-hand-side value for the linear constraint triggered by the indicator. Optional,
Noneby default, value type is constant.
typeType of the indicator constraint. Optional,
COPT.INDICATOR_IFby default. Please refer to Indicator Constraint type for possible values.
nameName 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
buildersA set of indicator constraint builders. The possible values could be GenConstrBuilderArray Class object, a list or dictionary of GenConstrBuilder Class object.
nameprefixNameprefix 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
resvarThe term
yon the left side of the equation and can be an object of classVarorMVar.
varsThe variable of the \(\min\{\}\) function on the right side of the equation,
Possible values are
listclass objects.
constantThe 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.
nameConstraint name, optional parameter, default value is
"".Return value
It returns a
GenConstrXClass 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
resvarThe term
yon the left side of the equation and can be an object of classVarorMVar.
varsThe variable of the \(\max\{\}\) function on the right side of the equation.
Possible values are
listclass objects.
constantThe 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.
nameConstraint name, optional parameter, default value is
"".Return value
It returns a
GenConstrXClass object.
Model.addGenConstrAbs()
Synopsis
addGenConstrAbs(resvar, argvar, name="")Description
Add a constraint of the form \(cy+d=|ax+b|\) to the model.
Arguments
resvar\(cy+d\) , possible values are objects of class
Var/MVaror classLinExpr/MLinExpr.
argvar\(ax+b\) , the possible value is object of class
Var/MVaror classLinExpr/MLinExpr.
nameConstraint name, optional parameter, default value is
"".Return value
It returns a
GenConstrXClass object.
Model.addGenConstrAnd()
Synopsis
addGenConstrAnd(resvar, vars, name="")Description
Add a logical
andconstraint of the form \(y = x_1 \text{ and } x_2 \cdots \text{ and } x_n\) to the model.Arguments
resvarThe term
yon the left side of the equation and can be an object of classVarorMVar.
varsElements connected by logical operator
and\(x_i, \text{for } i \in \{1,2,\cdots,n\}\)Possible values are
Listclass (where the elements are binaryVarclass orMVarclass objects).
nameConstraint name, optional parameter, default value is
"".Return value
It returns a
GenConstrXClass object.
Model.addGenConstrOr()
Synopsis
addGenConstrOr(resvar, vars, name="")Description
Add a logical
orconstraint of the form \(y = x_1 \text{ or } x_2 \cdots \text{ or } x_n\) to the model.Arguments
resvarThe term
yon the left side of the equation and can be an object of classVarorMVar.
varsElements connected by logical operator
or\(x_i, \text{for } i \in \{1,2,\cdots,n\}\)Possible values are
Listclass (where the elements are binaryVarclass orMVarobjects).
nameConstraint name, optional parameter, default value is
"".Return value
It returns a
GenConstrXClass 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:
(67)\[\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 classVaror classMVar.
yvarThe term
yon the left side of the equation,Possible values are objects of class
Var/MVaror classLinExpr/MLinExpr.
xpts\(\tilde{\boldsymbol{x}}\), the abscissa of the segmentation point.
It should be arranged in ascending order of values, possible values are
Listclass.
ypts\(\tilde{\boldsymbol{y}}\) , the vertical coordinate of the segmentation point,
Possible values are
Listclass.
nameConstraint name, optional parameter, default value is
"".Return value
It returns a
GenConstrXClass 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
dimDimension of SOC constraint.
ctypeType of SOC constraint.
vtypeVariable types of SOC constraint.
nameprefixName 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
ctypeType of exponential cone constraint.
vtypeVariable types of exponential cone constraint.
nameprefixName 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
varsis a ConeBuilder Class object, then the value of argumentctypewill be ignored; If argumentvarsare variables, the optional values are VarArray Class objects, Python list, Python dictionary or tupledict Class objects, argumentctypeis the type of SOC constraint.Arguments
varsVariables of SOC constraint.
ctypeType of SOC constraint. Please refer SOC constraint types for possible values.
Example
# Add a SOC constraint with [z, x, y] as variables
m.addCone([z, x, y], COPT.CONE_QUAD)
Model.addCones()
Synopsis
addCones(vars, ctype)Description
Add a set of Second-Order-Cone (SOC) constraint with given variables.
If argument
varsis a ConeBuilder Class object or ConeBuilderArray Class object, then the value of argumentctypewill be ignored; If argumentvarsare MVar Class , the argumentctypeis the type of SOC constraint, and it must be specified.Arguments
varsVariables of SOC constraint.
ctypeType of SOC constraint. Please refer SOC constraint types for possible values.
Model.addExpCone()
Synopsis
addExpCone(vars, ctype)Description
Add an exponential cone to the model.
For example, the primal exponential cone defined by the \(\boldsymbol{x}\in \mathbb{R}^3\) :
(68)\[\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
varsis a ExpConeBuilder Class object, then the value of argumentctypewill be ignored.If argument
varsare variables, the optional values are VarArray Class objects, a one-dimensional MVar Class object, tupledict Class object, dictionary or list, the argumentctypespecifies the type of the exponential cone and must be explicitly provided.Arguments
varsThe variables forming the exponential cone.
Possible values are ExpConeBuilder Class object, VarArray Class object, one-dimensional MVar Class object, tupledict Class object, dictionary or list.
ctypeType of the exponential cone. Please refer to Exponential Cone type for possible values.
Example
# Add a primal exponential cone formed by mx
mx = m.addMVar(3)
model.addExpCone(mx, ctype=COPT.EXPCONE_PRIMAL)
Model.addExpCones()
Synopsis
addExpCones(vars, ctype)Description
Add a batch of exponential cones to the model. Return a ExpConeArray Class object.
If argument
varsis a ExpConeBuilder Class object, then the value of argumentctypewill be ignored.If argument
varsis a MVar Class object, thectypeargument specifies the type of the exponential cones and must be explicitly provided.Arguments
varsVariables forming the exponential cones. Possible values are ExpConeBuilderArray Class object, 2-dimensional MVar Class object.
ctypeType of the exponential cone. Please refer to Exponential Cone type for possible values.
Example
# Add two primal exponential cones formed by my
model.matrixmodelmode = 'experimental'
my = model.addMVar(shape=(2, 3))
model.addExpCones(my, COPT.EXPCONE_PRIMAL)
Model.addAffineCone()
Synopsis
addAffineCone(exprs, ctype=None, name="")Description
Adds an affine cone to the model.
If the argument
exprsis a AffineConeBuilder Class object, the value of the argumentctypewill be ignored.If the argument
exprsis an MLinExpr Class object or an MPsdExpr Class object, the argumentctypespecifies the type of the affine cone and must be explicitly provided.Arguments
exprsAn affine cone generator or a multi-dimensional array expression that forms the affine cone.
ctypeThe type of the affine cone. Possible values are detailed in SOC constraint types or Exponential Cone type.
Example
# Add a standard second-order affine cone formed by Ax+b and c^Tx+d
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
b = 10
c = np.array([1, -1, 2])
d = 5
x = model.addMVar(3)
model.addAffineCone(cp.vstack(c @ x + d, A @ x + b), ctype=COPT.CONE_QUAD)
Model.addAffineCones()
Synopsis
addAffineCones(exprs, ctype=None, nameprefix="AffineConV")Description
Adds a set of affine cones to the model.
If the argument
exprsis a AffineConeBuilder Class object or a AffineConeBuilderArray Class object, the value of the argumentctypeis ignored.If the argument
exprsis an MLinExpr Class object or an MPsdExpr Class object, the argumentctypespecifies the type of the affine cones and must be explicitly provided.Arguments
exprsAffine cone generators or multi-dimensional array expressions that form the affine cones.
ctypeThe type of the affine cone. Possible values are detailed in SOC constraint types or Exponential Cone type.
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
lhscan be taken Var Class object, LinExpr Class object or ConstrBuilder Class object; If the constraint is quadratic, then value of parameterlhscan be taken QConstrBuilder Class object, or MQConstrBuilder Class object and other parameters will be ignored.Arguments
lhsLeft-hand side expression for new constraint or constraint builder.
senseSense for the new constraint. Optional, None by default. Please refer to Constraint type for possible values.
rhsRight-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.
nameName 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
sensehere isCOPT.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
QIf 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).
cIf the item is non-empty, you need to provide the parameter c, which is a one-dimensional NumPy array, or a Python list.
senseThe type of constraint. Possible values refer to Constraint type.
rhsThe value on the right side of the constraint, usually a floating point number.
xQ_LThe 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_RThe 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.
xcThe 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.
nameconstraint 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.addNlConstr()
Synopsis
addNlConstr(lhs, sense=None, rhs=None, name="")Description
Add a nonlinear constraint to the model.
If
lhsis a nonlinear expression type, bothsenseandrhsmust be provided to specify the constraint direction and right-hand side.If
lhsis a NlConstrBuilder Class object, the constraint is created using the builder content. Other arguments are ignored.If
lhsis a ConstrBuilder Class object, a linear constraint is added. The return value is Constraint Class.If
lhsis a QConstrBuilder Class object, a quadratic constraint is added. The return value is QConstraint Class.Arguments
lhsThe left-hand side expression or constraint builder.
senseThe constraint type. Optional. Defaults to
None.See Constraint Types for valid values.
rhsThe right-hand side of the constraint. Optional. Defaults to
None.Can be a constant or a NlExpr Class object.
nameThe name of the constraint. Optional.
Defaults to
"", and a name will be generated automatically by the solver.
Model.addNlConstrs()
Synopsis
addNlConstrs(generator, nameprefix="NR")Description
Add a set of nonlinear constraints to the model.
Arguments
generatorA constraint builder or a sequence of nonlinear constraint builders.
Possible values include: a single NlConstrBuilder Class, QConstrBuilder Class, or ConstrBuilder Class object, or an iterable of NlConstrBuilder Class objects.
nameprefixThe prefix used for naming constraints.
Optional. Defaults to
"NR".
Model.addPsdVar()
Synopsis
addPsdVar(dim, name="")Description
Add a positive semi-definite variable.
Arguments
dimDimension for the positive semi-definite variable.
nameName 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
dimDimensions for new positive semi-definite variables.
nameprefixName 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
lhsLeft-hand side expression for the new user cut. It can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object.
senseThe sense of the new user cut. Please refer to Constraint type for possible values.
Optional. None by default.
rhsRight-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.
nameName 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
generatorA generator expression, where each iteration produces a Constraint Class object, or MConstrBuilder Class object.
nameprefixName 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
lhsLeft-hand side expression for the new lazy constraint. It can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object.
senseThe sense of the lazy constraint. Please refer to Constraint type for possible values.
Optional. None by default.
rhsRight-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.
nameName 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
generatorA generator expression, where each iteration produces a Constraint Class object, or MConstrBuilder Class object.
nameprefixName 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
dimDimension for the matrix.
rowsRow indices for accessing rows of non-zero elements.
colsColumn indices for accessing columns of non-zero elements.
valsCoefficient 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
dimDimension for the matrix.
valsCoefficient 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
dimDimension for the matrix.
valsCoefficient values, which can be a constant or a list.
offsetOffset 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
dimDimension 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
dimDimension 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
exprObjective expression. Argument can be a constant, Var Class object, LinExpr Class object, QuadExpr Class object, MLinExpr Class object, or MQuadExpr Class object, or NlExpr Class object.
Note: If
expris 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.
senseOptimization sense. Optional,
Noneby default, which means no change to objective sense. Users can get access to current objective sense by attributeObjSense. 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.setObjectiveN()
Synopsis
setObjectiveN(idx, expr, sense=None, priority=0.0, weight=1.0, abstol=1e-6, reltol=0.0)Description
Specify the objective function for multi-objective optimization.
Arguments
idxThe index of the objective function. Argument can be an integer constant.
exprThe expression of the objective function. Argument can be a linear expression.
senseOptimization sense.
Optional,
Noneby default, which means no change to objective sense. Please refer to Optimization directions for possible values.
priorityThe priority of the objective function.
Optional, default is 0.0.
weightThe weight of the objective function.
Optional, default is 1.0.
abstolThe absolute tolerance for degradation.
Optional, default is 1e-6.
reltolThe relative tolerance for degradation.
Optional, default is 0.0.
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
QIf 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).
cIf the item is non-empty, you need to provide the parameter c, which is a one-dimensional NumPy array, or a Python list.
constantConstant term, usually a floating point number.
xQ_LThe 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_RThe 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.
xcThe 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.
senseThe 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 propertyObjSense. 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
senseOptimization 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
constConstant 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.getObjectiveN()
Synopsis
getObjectiveN(idx)Description
Retrieve the expression of the objective function with the specified index in multi-objective optimization.
Arguments
idxThe index of the objective function.
Return Value
Returns a LinExpr Class object.
Model.delObjN()
Synopsis
delObjN(idx)Description
Delete the linear part of the objective with the specified index from the multi-objective model.
Arguments
idxThe index of the objective function.
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.delNlObj()
Synopsis
delNlObj()Description
Delete all nonlinear terms from the nonlinear objective function.
Example
# Delete nonlinear terms from the objective
m.delNlObj()
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.getNlRow()
Synopsis
getNlRow(constr)Description
Retrieve the row expression associated with the specified nonlinear constraint. Returns a NlExpr Class object.
Example
# Retrieve the row expression of nonlinear constraint
nlexpr = m.getNlRow(nlcon)
Model.getVar()
Synopsis
getVar(idx)Description
Retrieve a variable according to its index in the coefficient matrix. Return a Var Class object.
Arguments
idxIndex 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
nameName 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
idxIndex 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
nameThe 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
constrsisNone, then return a ConstrBuilderArray Class object composed of all linear constraint builders.If parameter
constrsis Constraint Class object, then return the ConstrBuilder Class object corresponding to the specific constraint.If parameter
constrsis a list or a ConstrArray Class object, then return a ConstrBuilderArray Class object composed of specified constraints’ builders.If parameter
constrsis 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
constrsThe specified linear constraint. Optional,
Noneby 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.getNlConstr()
Synopsis
getNlConstr(idx)Description
Retrieve a nonlinear constraint by its index in the model. Return a NlConstraint Class object.
Arguments
idxIndex of the nonlinear constraint in the model, starting with
0.Example
# Retrieve nonlinear constraint with index 1
r = m.getNlConstr(1)
Model.getNlConstrByName()
Synopsis
getNlConstrByName(name)Description
Retrieve a nonlinear constraint by its name. Return a NlConstraint Class object.
Arguments
nameName of the nonlinear constraint.
Example
# Retrieve nonlinear constraint with name "r"
r = m.getNlConstrByName("r")
Model.getNlConstrs()
Synopsis
getNlConstrs()Description
Retrieve all nonlinear constraints in the model. Return a NlConstrArray Class object.
Example
# Retrieve all nonlinear constraints in the model
cons = m.getNlConstrs()
Model.getNlConstrBuilders()
Synopsis
getNlConstrBuilders(constrs=None)Description
Retrieve nonlinear constraint builders in the current model.
If parameter
constrsisNone, return a NlConstrBuilderArray Class object composed of all nonlinear constraint builders.If parameter
constrsis a NlConstraint Class object, return the NlConstrBuilder Class object corresponding to the specified constraint.If parameter
constrsis a list or a NlConstrArray Class object, return a NlConstrBuilderArray Class object composed of the specified constraints’ builders.If parameter
constrsis a dictionary or tupledict Class object, return a tupledict Class where keys are the same as the input, and values are the corresponding nonlinear constraint builders.Arguments
constrsThe specified nonlinear constraint(s).
Optional,
Noneby default.Example
# Retrieve all nonlinear constraint builders
conbuilders = m.getNlConstrBuilders()
# Retrieve the builder corresponding to nonlinear constraint nl
conbuilder = m.getNlConstrBuilders(nl)
# Retrieve builders corresponding to nonlinear constraints nl1 and nl2
conbuilders = m.getNlConstrBuilders([nl1, nl2])
# Retrieve builders corresponding to nonlinear constraints in a tupledict
conbuilders = m.getNlConstrBuilders(td)
Model.getSOS(sos)
Synopsis
getSOS(sos)Description
Retrieve the SOS constraint builder corresponding to specific SOS constraint. Return a SOSBuilder Class object
Arguments
sosThe 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
sossisNone, then return a SOSBuilderArray Class object consisting of builders corresponding to all SOS constraints.If parameter
sossis SOS Class object, then return a SOSBuilder Class corresponding to the specified SOS constraint.If parameter
sossis list or SOSArray Class object, then return a SOSBuilderArray Class object consisting of builders corresponding to the specific SOS constraints.Arguments
sossThe specific SOS constraint. Optional,
Noneby 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
genconstrThe 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
idxIndex 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
nameThe 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.getCone()
Synopsis
getCone(idx)Description
Retrieves the second-order cone at the specified index in the model. Returns a Cone Class object.
Arguments
idxThe specified index. Indexing starts at 0.
Example
# Retrieve the second-order cone at index 1 in the model
cones = m.getCone(1)
Model.getExpCone()
Synopsis
getExpCone(idx)Description
Retrieves the exponential cone at the specified index in the model. Returns an ExpCone Class object.
Arguments
idxThe specified index. Indexing starts at 0.
Example
# Retrieve the exponential cone at index 1 in the model
cones = m.getExpCone(1)
Model.getAffineCone()
Synopsis
getAffineCone(idx)Description
Retrieves the affine cone at the specified index in the model. Returns an AffineCone Class object.
Arguments
idxThe specified index. Indexing starts at 0.
Example
# Retrieve the affine cone at index 1 in the model
cones = m.getAffineCone(1)
Model.getAffineConeByName()
Synopsis
getAffineConeByName(name)Description
Retrieves the affine cone with the specified name in the model. Returns a AffineCone Class object.
Arguments
nameThe specified name.
Example
# Retrieve the affine cone with the name "afcone" in the model
cones = m.getAffineConeByName("afcone")
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.getAffineCones()
Synopsis
getAffineCones()Description
Retrieves all affine cones in the model. Returns a AffineConeArray Class object.
Example
# Retrieve all affine cones in the model
cones = m.getAffineCones()
Model.getConeBuilders()
Synopsis
getConeBuilders(cones=None)Description
Retrieve Second-Order-Cone (SOC) constraint builders for given SOC constraints.
If argument
conesisNone, then return a ConeBuilderArray Class object consists of all SOC constraints’ builders; If argumentconesis Cone Class object, then return a ConeBuilder Class object of given SOC constraint; Ifconesis Python list or ConeArray Class object, then return a ConeBuilderArray Class object consists of builders of given SOC constraints.Arguments
conesGiven 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
conesisNone, then return a ExpConeBuilderArray Class object consists of all exponential cone constraints’ builders; If argumentconesis ExpCone Class object, then return a ExpConeBuilder Class object of given exponential cone constraints; Ifconesis Python list or ExpConeArray Class object, then return a ExpConeBuilderArray Class object consists of builders of given exponential cone constraints.Arguments
conesGiven exponential cone constraints. Optional, default to
None.Example
# Retrieve all exponential cone constraints' builders
cones = m.getExpConeBuilders()
Model.getAffineConeBuilders()
Synopsis
getAffineConeBuilders(cones=None)Description
Retrieves the affine cone builders corresponding to the specified affine cones.
If the argument
conesisNone, returns a AffineConeBuilderArray Class object containing the builders for all affine cones in the model.If the argument
conesis a AffineCone Class object, returns the corresponding AffineConeBuilder Class object.If the argument
conesis a list or a AffineConeArray Class object, returns a AffineConeBuilderArray Class object containing the builders for the specified affine cones.Arguments
conesThe specified affine cones. Optional, defaulting to
None.Example
# Retrieve the builders for all affine cones in the model
cones = m.getAffineConeBuilders()
Model.getQConstr()
Synopsis
getQConstr(idx)Description
Retrieve a quadratic constraint by its indice, and return a QConstraint Class object.
Arguments
idxIndex 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
nameName 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
qconstrsisNone, then return a QConstrBuilderArray Class object composed of all quadratic constraint builders.If parameter
qconstrsis QConstraint Class object, then return the QConstrBuilder Class object corresponding to the specific quadratic constraint.If parameter
qconstrsis a list or a QConstrArray Class object, then return a QConstrBuilderArray Class object composed of specified quadratic constraints’ builders.If parameter
qconstrsis 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
qconstrsThe specified quadratic constraint. Optional,
Noneby 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
idxIndex 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
nameThe 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
idxIndex 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
nameThe 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
constrsisNone, then return a PsdConstrBuilderArray Class object composed of all positive semi-definite constraint builders.If parameter
constrsis PsdConstraint Class object, then return the PsdConstrBuilder Class object corresponding to the specific positive semi-definite constraint.If parameter
constrsis a list or a PsdConstrArray Class object, then return a PsdConstrBuilderArray Class object composed of specified positive semi-definite constraints’ builders.If parameter
constrsis 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
constrsThe specified positive semi-definite constraint. Optional,
Noneby 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
constrThe 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
idxThe 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
nameThe 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
constrThe specified LMI constraint.
Model.setLmiRhs()
Synopsis
setLmiRhs(constr, mat)Description
Set the constant term of the specified LMI constraint.
Arguments
constrThe specified LMI constraint.
matThe 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
constrThe requested linear constraint, PSD constraint or LMI constraint.
varThe 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
constrThe requested linear constraint, PSD constraint or LMI constraint.
varThe requested variable or PSD variable.
newvalNew 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
constrsSpecifies 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.
varsSpecifies 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.
valsThe 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_matrixobject. This method requires thescipypackage.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
scipypackage.Arguments
cObjective costs. If
None, the objective costs are all zeros.
ACoefficient matrix. Must be of type
scipy.sparse.csc_matrix.
lhsLower bounds of constraints.
rhsUpper bounds of constraints.
lbLower bounds of variables. If
None, the lower bounds are all zeros.
ubUpper bounds of variables. If
None, the upper bounds are allCOPT.INFINITY.
vtypeVariable 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
nconeNumber of SOC.
typesType of SOC, please refer to SOC constraint types for possible values.
dimsDimension of SOC.
indicesArray of subscripts for the variables that constitute the SOC.
Model.loadExpCone()
Synopsis
loadExpCone(ncone, types, indices)Description
Load exponential cones to the model.
Arguments
nconeNumber of exponential cones.
typesType of exponential cones, please refer to Exponential Cone type for possible values.
indicesArray 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
valuesSolution of variables.
slackSolution of slack variables.
dualsSolution of dual variables.
redcostReduced 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
varsisNone, then return a list object consistinf of all variables’ basis status. If parametervarsis Var Class object, then return basis status of the specified variable. If parametervarsis list or VarArray Class object, then return a list object consisting of the specified variables’ basis status. If parametervarsis 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
varsThe specified variables. Optional,
Noneby 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
constrsisNone, then return a list object consisting of all linear constraints’ basis status. If parameterconstrsis Constraint Class object, then return basis status of the specified linear constraint. If parameterconstrsis list or ConstrArray Class object, then return a list object consisting of the specified linear constraints’ basis status. If parameterconstrsis 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
constrsThe specified linear constraint. Optional,
Noneby 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
isolIndex 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
varsis Var Class object, then return values of the specified variable. If parametervarsis list or VarArray Class object, then return a list object consisting of the specified variables’ values. If parametervarsis 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
isolIndex of solution
varsThe specified variables.
Example
# Get value of x in the second solution
xval = m.getPoolSolution(2, x)
Model.getPoolObjValN()
Synopsis
getPoolObjValN(idx, isol)Description
In a multi-objective model, retrieve the objective value of the specified objective at the given solution index in the solution pool.
Arguments
idxIndex of the target objective in the multi-objective model.
isolIndex of the solution in the solution pool.
Return Value
Returns a double value.
Model.getVarLowerIIS()
Synopsis
getVarLowerIIS(vars)Description
Obtain IIS status of lower bounds of variables.
If parameter
varsis Var Class object, then return IIS status of lower bound of variable. If parametervarsis list or VarArray Class object, then return a list object consisting of the IIS status of lower bounds of variables. If parametervarsis 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
varsThe 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
varsis Var Class object, then return IIS status of upper bound of variable. If parametervarsis list or VarArray Class object, then return a list object consisting of the IIS status of upper bounds of variables. If parametervarsis 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
varsThe 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
constrsis Constraint Class object, then return IIS status of lower bound of constraint. If parameterconstrsis list or ConstrArray Class object, then return a list object consisting of the IIS status of lower bounds of constraints. If parameterconstrsis 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
constrsThe 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
constrsis Constraint Class object, then return IIS status of upper bound of constraint. If parameterconstrsis list or ConstrArray Class object, then return a list object consisting of the IIS status of upper bounds of constraints. If parameterconstrsis 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
constrsThe 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
sossis SOS Class object, then return IIS status of SOS constraint. If parametersossis list or SOSArray Class object, then return a list object consisting of the IIS status of SOS constraints. If parametersossis 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
sossThe 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
genconstrsis GenConstr Class object, then return IIS status of indicator constraint. If parametergenconstrsis list or GenConstrArray Class object, then return a list object consisting of the IIS status of indicator constraints. If parametergenconstrsis 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
genconstrsThe 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
attrnameThe 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
argsis Var Class object, Constraint Class object, QConstraint Class object, or NlConstraint Class object, then return info of the specified variable or constraint.If parameter
argsis list or VarArray Class object, ConstrArray Class object, iterable QConstraint Class objects, or NlConstraint Class objects, then return a list consisting of the specified variables or constraints.If parameter
argsis 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
argsis MVar Class object, MConstr Class object, MQConstr Class object or MPsdConstr Class object, then return anumpy.ndarrayconsisting of the specified variables or constraints.Arguments
infonameThe specified information name. The full list of available attributes can be found in Information section.
argsVariables 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.getAttrN()
Synopsis
getAttrN(idx, attrname)Description
Get the attribute value of the specified objective in multi-objective optimization.
Arguments
Return Value
A double or integer value.
Model.getParam()
Synopsis
getParam(paramname)Description
Retrive the current value of the specified parameter. Return a constant.
Arguments
paramnameThe 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
paramnameName 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.getObjParamN()
Synopsis
getObjParamN(idx, paramname)Description
Get the value of a parameter for the specified objective in multi-objective optimization.
Arguments
idxIndex of the objective function.
paramnameName of the objective parameter.
Possible values are MultiObjPriority, MultiObjWeight, MultiObjRelTol, MultiObjAbsTol.
Return Value
A double or integer value.
Model.getParamN()
Synopsis
getParamN(idx, paramname)Description
Get the value of a solver parameter for the model associated with the specified objective in multi-objective optimization.
Arguments
idxIndex of the objective function.
paramnameName of the solver parameter.
See Parameters for possible values.
Return Value
A double or integer value.
Model.setBasis()
Synopsis
setBasis(varbasis, constrbasis)Description
Set basis status for all variables and linear constraints in LP. The parameters
varbasisandconstrbasisare list objects whose number of elements is the total number of variables or linear constraints.Arguments
varbasisThe basis status of variables.
constrbasisThe 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
varsis Var Class object, then parametervartypesis Variable types constant;If parameter
varsis dictionary or tupledict Class object, then parametervartypescan be Variable types constart, dictionary or tupledict Class object;If parameter
varsis list or VarArray Class object, then parametervartypescan be Variable types constart or list object.Arguments
varsThe specified variable.
vartypesType 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
argsThe specified variable(s) or constraint(s), which could be: Var Class , Constraint Class , QConstraint Class , PsdVar Class , PsdConstraint Class , LmiConstraint Class , GenConstr Class object, AffineCone Class or the dictionary/list they constitute.
namesThe 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
varsis Var Class object, then parameterstartvalsis constant; If parametervarsis dictionary or tupledict Class object, then parameterstartvalscan be constant, dictionary or tupledict Class object; If parametervarsis list or VarArray Class object, then parameterstartvalscan 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
varsThe specified variable.
startvalsInitial 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.setNlPrimalStart()
Synopsis
setNlPrimalStart(vars, startvals)Description
Set the initial values of variables in a nonlinear model.
Arguments
varsThe variables to be assigned initial values to.
Acceptable values include: a single Var Class object, a VarArray Class or any iterable of variables, a dictionary mapping arbitrary keys to Var Class objects, or a MVar Class multidimensional variable.
startvalsThe corresponding start values. Can be a double value, a list, array, or a mapping structure consistent with the shape or keys of the variables.
Model.setInfo()
Synopsis
setInfo(infoname, args, newvals)Description
Set new information value for specific variables or constraints.
If parameter
argsis Var Class object or Constraint Class object, then parameternewvalsis constant; If parameterargsis dictionary or tupledict Class object, then parameternewvalscan be constant, dictionary or tupledict Class object; If parameterargsis list, VarArray Class object or ConstrArray Class object, then parameternewvalscan be constant or list; If parameterargsis MVar Class object, MConstr Class object, MQConstr Class object or MPsdConstr Class object. then parameternewvalscan be constant ornumpy.ndarray.Arguments
infonameThe specified information name. The full list of available names can be found in Information section.
argsThe specified variables of constraints.
newvalsValue 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
paramnameThe name of parameter to be set. The list of available names can be found in Parameters section.
newvalNew 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.setObjParamN()
Synopsis
setObjParamN(idx, paramname, newval)Description
Set a parameter of the specified objective in multi-objective optimization.
Arguments
idxIndex of the objective function.
paramnameName of the objective parameter.
Possible values are MultiObjPriority, MultiObjWeight, MultiObjRelTol, MultiObjAbsTol.
newvalNew value for the specified objective function parameter.
Model.setParamN()
Synopsis
setParamN(idx, paramname, newval)Description
Set a solver parameter for the model associated with the specified objective in multi-objective optimization.
Arguments
idxIndex of the objective function.
paramnameName of the solver parameter.
See Parameters for possible values.
newvalNew value of the specified solver parameter.
Model.resetObjParamN()
Synopsis
resetObjParamN(idx)Description
Reset all parameters of the specified objective in multi-objective optimization to their default values.
Arguments
idxIndex of the objective function.
Model.resetParamN()
Synopsis
resetParamN(idx)Description
Reset all solver parameters associated with the specified objective in multi-objective optimization to their default values.
Arguments
idxIndex of the objective function.
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'), branching order files (suffix'.ord'), and parameter files (suffix'.par').Arguments
filenameName 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
filenameThe 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
filenameName 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
filenameName 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
filenameName 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
filenameThe 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
filenameName 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.readJsonSol()
Synopsis
readJsonSol(filename)Description
Read the complete solution in JSON format from a file.
Arguments
filenameName of file to be read.
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
filenameThe 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
filenameName 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
filenameThe 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
filenameThe name of the file to be read.
Example
Model.readOrd()
Synopsis
readOrd(filename)Description
Read a branching order file (ORD format) into the current model to reuse a predefined branching strategy.
Arguments
filenameName of the branching order file to be read.
Example
# Read branching order information from "testmip.ord" m.readOrd("testmip.ord")
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'), branching order files (suffix'.ord'), and parameter files (suffix'.par').Arguments
filenameThe 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
filenameThe 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
filenameThe 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
filenameThe 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
filenameThe 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
filenameThe 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
filenameThe 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
filenameThe name of the solution file to be written.
Example
# Write solution file "test.sol"
m.writeSol('test.sol')
Model.writeJsonSol()
Synopsis
writeJsonSol(filename)Description
Write the solution of the model to a
".json"format result file.Arguments
filenameThe name of the solution file to be written.
Model.writePoolSol()
Synopsis
writePoolSol(isol, filename)Description
Output selected pool solution to a solution file.
Arguments
isolIndex of pool solution.
filenameThe 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
filenameThe 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
filenameName 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
filenameThe 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
idxParameter tuning result number.
filenameThe name of the parameter file to be output.
Example
Model.writeOrd()
Synopsis
writeOrd(filename)Description
Write the branching order information of the current model into an ORD-format file, so that the branching strategy can be saved and reused.
Arguments
filenameName of the branching order file to be written.
Example
# Write branching order information of the current model into "testmip.ord" m.writeOrd("testmip.ord")
Model.setLogFile()
Synopsis
setLogFile(logfile)Description
Set the optimizer log file.
Arguments
logfileThe 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
logcbCall 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 feasibility relaxation of an infeasible model.
Arguments
varsThe variables to relax.
Possible values are Var Class objects, VarArray Class objects, arrays, lists, dictionaries, or tupledict Class objects.
If
varsis a Var Class object, thenlbpen/ubpencan be constant.If
varsis a VarArray Class object, an array or a list. thenlbpen/ubpencan correspondingly be array, list or constant.If
varsis a tupledict Class object or a dictionary, thenlbpen/ubpencan be dictionary or constant.
lbpenThe penalty factor for the lower bound of the variables.
If
lbpenisNone, no relaxation of the variables’ lower bound is allowed.If
lbpenisCOPT.INFINITY, the lower bound of the corresponding variable invarsis not relaxed.
ubpenThe penalty factor for the upper bound of the variables.
If
ubpenisNone, no relaxation of the variables’ lower bound is allowed.If
ubpenisCOPT.INFINITY, the upper bound of the corresponding variable invarsis not relaxed.
constrsThe constraints to relax.
Possible values are Constraint Class objects, ConstrArray Class objects, arrays, lists, or dictionaries.
If
constrsis a Constraint Class object, thenrhspen/uppencan be constant.If
constrsis a ConstrArray Class object, an array, or a list, thenrhspen/uppencan correspondingly be array, list, or constant.If
constrsis a dictionary, thenrhspen/uppencan be dictionary or constant.
rhspenThe penalty factor for the right-hand side of the constraints.
If
rhspenisNone, no relaxation of the constraint boundaries is applied.If
rhspenisCOPT.INFINITY, the constraint’s right-hand side is not relaxed.
uppenThe penalty factor for the upper bound of bilateral constraints.
If
uppenisNone, the penalty factor is specified byrhspen.If
uppenisCOPT.INFINITY, the upper bound of the constraint is not relaxed.Example
# Compute the feasibility relaxation for an infeasible model
x = model.addVars(3, ub=1)
y = model.addVars(3, ub=2)
c = model.addConstrs(x[i] + y[i] <= 1 for i in range(3))
model.feasRelax([x[0], x[1]], [0.5, 1], [COPT.INFINITY, 2], c, 1)
Model.feasRelaxS()
Synopsis
feasRelaxS(vrelax, crelax)Description
Compute the feasibilty relaxation of an infeasible model in a simplified moode.
Arguments
vrelaxWhether to relax variables.
crelaxWhether to relax constraints.
Example
# Compute the feasibilty relaxation of model m
m.feasRelaxS(True, True)
Model.feasRelaxN()
Synopsis
feasRelaxN(vars, lbpen, ubpen, constrs, rhspen, uppen=None)Description
Computes the feasibility relaxation of an infeasible model formulated by matrix modeling.
Either
varsorconstrsmust be a matrix modeling object; that is, at least one of the following conditions must hold:
varsis a MVar Class object.
constrsis a MConstr Class object.Arguments
varsThe variables to relax.
Possible values are MVar Class objects, Var Class objects, VarArray Class objects, arrays, lists, dictionaries, or tupledict Class objects.
If
varsis a MVar Class object, thenlbpen/ubpencan be a NdArray Class object, array, list, dictionary, or constant.If
varsis a Var Class object, thenlbpen/ubpencan be constant.If
varsis a VarArray Class object, an array, or a list, thenlbpen/ubpencan be array, list, or constant.If
varsis a tupledict Class object or dictionary, thenlbpen/ubpencan be dictionary or constant.
lbpenThe penalty factor for the lower bound of the variables.
If
lbpenisNone, no relaxation of the variables’ lower bound is allowed.If
lbpenisCOPT.INFINITY, the lower bound of the corresponding variable invarsis not relaxed.
ubpenThe penalty factor for the upper bound of the variables.
If
ubpenisNone, no relaxation of the variables’ lower bound is allowed.If
ubpenisCOPT.INFINITY, the upper bound of the corresponding variable invarsis not relaxed.
constrsThe constraints to relax.
Possible values are MConstr Class objects, Constraint Class objects, ConstrArray Class objects, arrays, lists, or dictionaries.
If
constrsis a MConstr Class object, thenrhspen/uppencan be a NdArray Class object, array, list, dictionary, or constant.If
constrsis a Constraint Class object, thenrhspen/uppencan be constant.If
constrsis a ConstrArray Class object, an array, or a list, thenrhspen/uppencan correspondingly be array, list, or constant.If
constrsis a dictionary, thenrhspen/uppencan be dictionary or constant.
rhspenThe penalty factor for the right-hand side of the constraints.
If
rhspenisNone, no relaxation of the constraint boundaries is applied.If
rhspenisCOPT.INFINITY, the constraint’s right-hand side is not relaxed.
uppenThe penalty factor for the upper bound of bilateral constraints.
If
uppenisNone, the penalty factor is specified byrhspen.If
uppenisCOPT.INFINITY, the upper bound of the constraint is not relaxed.Example
# Compute the feasibility relaxation for an infeasible model formulated using matrix modeling
mx = model.addMVar(shape=3, nameprefix="x")
# Define constraints
A = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20])
mc = model.addConstr(A @ x <= b, name="constrs")
# Define relaxation penalty factors
# The lower bound of the 2nd element of mx is not relaxed
lbpen = [1.0, COPT.INFINITY, 0.5]
# The upper bound of the 3rd element of mx is not relaxed
ubpen = NdArray([0.8, 1.5, COPT.INFINITY])
# Relaxation penalty factor for mc
rhspen = 2.0
# Compute feasibility relaxation for mx and mc in matrix modeling
model.feasRelaxN(mx, lbpen, ubpen, mc, rhspen)
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
argscan be Var Class object, VarArray Class object, list, dictionary or tupledict Class object.To remove linear constraint, then parameter
argscan be Constraint Class object, ConstrArray Class object, list, dictionary or tupledict Class object.To remove SOS constraint, then parameter
argscan be SOS Class object, SOSArray Class object, list, dictionary or tupledict Class object.To remove Second-Order-Cone constraints, then parameter
argscan be Cone Class object, ConeArray Class object, list, dictionary or tupledict Class object.To remove exponential cone constraints, then parameter
argscan be ExpCone Class object, ExpConeArray Class object, list, dictionary or tupledict Class object.To remove affine cone constraints, then parameter
argscan be AffineCone Class object, AffineConeArray Class object, list, dictionary or tupledict Class object.To remove quadratic constraints, then parameter
argscan be QConstraint Class object, QConstrArray Class object, list, dictionary or tupledict Class object.To remove positive semi-definite constraints, then parameter
argscan be PsdConstraint Class object, PsdConstrArray Class object, list, dictionary or tupledict Class object.To remove indicator constraint, then parameter
argscan be GenConstr Class object, GenConstrArray Class object, list, dictionary or tupledict Class object.To remove LMI constraint, then parameter
argscan be LmiConstraint Class object, LmiConstrArray Class object, list, dictionary or tupledict Class object.To remove matrix variables or matrix constriants, then parameter
argscan be MVar Class object, MConstr Class object, MQConstr Class object or MPsdConstr Class object.Arguments
argsVariables 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.resetAll()
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
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
newtypeThe 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
newnameThe 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
infonameThe 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
infonameThe name of the information to be set. Please refer to Information section for possible values.
newvalNew 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
varsisNone, then create an empty VarArray Class object, otherwise initialize the new created VarArray Class object based onvars.Arguments
varsVariables to be added. Optional,
Noneby default.varscan 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
varsVariables to be applied.
varscan 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
idxSubscript 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()
# 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
newnameThe 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
infonameThe 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.diag()
Synopsis
diag(offset=0)Description
Retrieves the diagonal elements of the PSD variable.
Arguments
offsetThe diagonal offset, default is 0.
If
offset> 0, it represents a downward diagonal offset. Ifoffset< 0, it represents an upward diagonal offset.Return Value
A PsdExpr object.
Example
# Retrieve the main diagonal elements of the PSD variable
v.diag(offset=0)
PsdVar.pick()
Synopsis
pick(indexes)Description
Retrieves a PSD expression composed of the elements at the specified indices of the PSD variable.
Arguments
indexesThe array of specified indices.
Return Value
A PsdExpr object.
Example
# Retrieve a PSD expression composed of the element at index 0
barX = model.addPsdVars(3, "BAR_X")
barX.pick([0])
PsdVar.sum()
Synopsis
sum()Description
Retrieves a PSD expression composed of the sum of all elements in the PSD variable.
Return Value
A PsdExpr object.
PsdVar.toexpr()
Synopsis
toexpr()Description
Retrieves the PSD expression equivalent to the PSD variable.
Return Value
A PsdExpr object.
PsdVar.shape
Synopsis
shapeDescription
Shape of the
PsdVarobject.Return value
Integer tuple.
PsdVar.size
Synopsis
sizeDescription
Size of the
PsdVarobject.Return value
Integer tuple.
PsdVar.dim
Synopsis
dimDescription
Dimension of the
PsdVarobject.Return value
Integer.
PsdVar.len
Synopsis
lenDescription
Flattened length of the
PsdVarobject.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
varsisNone, then create an empty PsdVarArray Class object, otherwise initialize the new created PsdVarArray Class object based onvars.Arguments
varsPositive semi-definite variables to be added. Optional,
Noneby default.varscan 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
varPostive semi-definite variables to be applied.
varscan 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
idxSubscript 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
matsisNone, then create an empty SymMatrixArray Class object, otherwise initialize the new created SymMatrixArray Class object based onmats.Arguments
mats
matscan 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
matSymmetric matrices to be applied.
matcan 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
idxSubscript 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
newnameThe 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
infonameName 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
infonameThe name of the information to be set. Please refer to Information section for possible values.
newvalNew 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
constrsisNone, the create an empty ConstrArray Class object, otherwise initialize the newly created ConstrArray Class object with parameterconstrsArguments
constrsLinear constraints to be added.
Noneby default.
constrscan 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
constrsLinear constraints to be applied.
constrscan 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
idxSubscript 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()
# 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()
# 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
exprThe expression to be set, which can be Var Class expression or LinExpr Class expression.
senseSense of constraint. The full list of available tyeps can be found in Constraint type section.
rhsRight 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
constrbuildersisNone, then create an empty ConstrBuilderArray Class object, otherwise initialize the newly created ConstrBuilderArray Class object by parameterconstrbuilders.Arguments
constrbuildersLinear constraint builder to be added. Optional,
Noneby 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
constrbuilderBuilder 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
idxSubscript 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
newnameThe 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
rhsThe 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
senseThe 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
infonameName 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
infonameThe name of the information to be set. Please refer to Information section for possible values.
newvalNew 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
qconstrsisNone, the create an empty QConstrArray Class object, otherwise initialize the newly created QConstrArray Class object with parameterqconstrsArguments
qconstrsQuadratic constraints to be added.
Noneby default.
qconstrscan 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
constrQuadratic constraints to be added.
Noneby default.
qconstrscan 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
idxSubscript 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()
# 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()
# 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
exprThe expression to be set, which can be Var Class object, LinExpr Class object or QuadExpr Class object.
senseSense of quadratic constraint. The full list of available tyeps can be found in Constraint type section.
rhsRight 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
qconstrbuildersisNone, then create an empty QConstrBuilderArray Class object, otherwise initialize the newly created QConstrBuilderArray Class object by parameterqconstrbuilders.Arguments
qconstrbuildersQuadratic constraint builder to be added. Optional,
Noneby 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
qconstrbuilderBuilder 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
idxSubscript 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
newnameThe 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
infonameName 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
infonameThe name of the information to be set. Please refer to Information section for possible values.
newvalNew 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
constrsisNone, the create an empty PsdConstrArray Class object, otherwise initialize the newly created PsdConstrArray Class object with parameterconstrs.Arguments
constrsPositive semi-definite constraints to be added.
Noneby default.
constrscan 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
constrPositive semi-definite constraints to be applied.
constrscan 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
idxSubscript 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()
# 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()
# 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
exprThe expression to be set, which can be PsdVar Class expression or PsdExpr Class expression.
senseSense of constraint. The full list of available tyeps can be found in Constraint type section.
rhsThe 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
expris less than or equals to 0 and greater than or equals to -range.Arguments
exprThe expression to be set, which can be PsdVar Class expression or PsdExpr Class expression.
rangeRange 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
buildersisNone, then create an empty PsdConstrBuilderArray Class object, otherwise initialize the newly created PsdConstrBuilderArray Class object by parameterbuilders.Arguments
buildersPositive semi-definite constraint builder to be added. Optional,
Noneby 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
builderBuilder 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
idxSubscript 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()
# 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
newnameThe 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
matThe 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
infonameName 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
shapeDescription
Shape of the
LmiConstraintobject.Return value
Integer tuple.
LmiConstraint.size
Synopsis
sizeDescription
Size of the
LmiConstraintobject.Return value
Integer tuple.
LmiConstraint.dim
Synopsis
dimDescription
Dimension of the
LmiConstraintobject.Return value
Integer.
LmiConstraint.len
Synopsis
lenDescription
Flattened length of the
LmiConstraintobject.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
constrsisNone, the create an empty LmiConstrArray Class object, otherwise initialize the newly created LmiConstrArray Class object with parameterconstrs.Arguments
constrsCan 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
constrscan 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
idxSubscript 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()
# 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
nThe number of elements in the object LmiConstrArray Class .
NlConstraint Class
The NlConstraint class provides an interface for operations
on nonlinear constraints in the COPT. It offers the following member functions:
NlConstraint.getName()
Synopsis
getName()Description
Retrieve the name of the nonlinear constraint.
Return Value
A string.
NlConstraint.getIdx()
Synopsis
getIdx()Description
Retrieve the index of the nonlinear constraint in the model.
Return Value
An integer.
NlConstraint.setName()
Synopsis
setName(newname)Description
Set the name of the nonlinear constraint.
Arguments
newnameThe new name of the constraint.
NlConstraint.getRhs()
Synopsis
getRhs()Description
Retrieve the right hand side of nonlinear constraint.
Return Value
A double value.
NlConstraint.getSense()
Synopsis
getSense()Description
Retrieve the type of nonlinear constraint.
Return Value
A string.
NlConstraint.setRhs()
Synopsis
setRhs(rhs)Description
Set the right hand side value of the nonlinear constraint.
Arguments
rhsThe new right hand side value.
NlConstraint.setSense()
Synopsis
setSense(sense)Description
Set the sense of nonlinear constraint.
Arguments
senseThe sense of nonlinear constraint to be set.
NlConstraint.getInfo()
Synopsis
getInfo(infoname)Description
Retrieve specified information of the nonlinear constraint.
Arguments
infonameName of the information to be retrieved.
See Information for possible values.
Return Value
A double value.
NlConstraint.setInfo()
Synopsis
setInfo(infoname, newval)Description
Set the specified information value of the nonlinear constraint.
Arguments
infonameName of the information to be set.
See Information for possible values.
newvalThe new information value.
NlConstraint.remove()
Synopsis
remove()Description
Remove the current nonlinear constraint from the model.
NlConstrArray Class
The NlConstrArray class is used to manage and operate on a
collection of nonlinear constraints. The following methods are provided:
NlConstrArray()
Synopsis
NlConstrArray(constrs=None)Description
Construct a new nonlinear constraint array object.
The argument
constrscan be a single NlConstraint Class object, an iterable of NlConstraint Class objects, or a mapping from arbitrary keys to constraint objects.Arguments
constrsOptional. Defaults to
None.
NlConstrArray.pushBack()
Synopsis
pushBack(constr)Description
Append one or more NlConstraint Class objects to the current array.
Arguments
qconstrsCould be a single NlConstraint Class object, an iterable of such objects, or a mapping from keys to constraints.
NlConstrArray.getNlConstr()
Synopsis
getNlConstr(idx)Description
Retrieve the constraint object at the specified index.
Arguments
idxThe index of the constraint.
Return Value
The corresponding NlConstraint Class object.
NlConstrArray.getSize()
Synopsis
getSize()Description
Obtain the number of elements in NlConstrArray Class object.
Return Value
An integer value.
NlConstrBuilder Class
The NlConstrBuilder class provides a builder interface for defining nonlinear
constraints in the COPT. It provides the following functions:
NlConstrBuilder()
Synopsis
NlConstrBuilder()Description
Construct a new nonlinear constraint builder object.
NlConstrBuilder.setBuilder()
Synopsis
setBuilder(expr, sense, rhs)Description
Define the nonlinear expression, constraint sense, and right hand side for the builder.
Arguments
exprThe nonlinear expression.
senseThe constraint sense.
rhsThe right hand side.
NlConstrBuilder.getNlExpr()
Synopsis
getNlExpr()Description
Retrieve the nonlinear expression in the builder.
Return Value
A NlExpr Class object.
NlConstrBuilder.getSense()
Synopsis
getSense()Description
Retreive the constraint sense of the nonlinear constraint builder.
Return Value
A string.
NlConstrBuilderArray Class
The NlConstrBuilderArray class is used to manage a collection of nonlinear constraint builders.
It provides the following member functions:
NlConstrBuilderArray()
Synopsis
NlConstrBuilderArray(constrs=None)Description
Construct a new nonlinear constraint builder array.
The argument
constrscan be a single NlConstrBuilder Class object, an iterable of builder objects, or a mapping from arbitrary keys to builder objects.Arguments
constrsOptional. Defaults to
None.
NlConstrBuilderArray.pushBack()
Synopsis
pushBack(constrbuilder)Description
Append one or more NlConstrBuilder Class objects to the array.
Arguments
constrbuilderThe builder(s) to append.
Can be a single NlConstrBuilder Class object, a NlConstrBuilderArray Class, a list, a dictionary, or a tupledict Class.
NlConstrBuilderArray.getBuilder()
Synopsis
getBuilder(idx)Description
Retrieve the builder object at the specified index.
Arguments
idxThe index of the builder.
Return Value
The corresponding NlConstrBuilder Class object.
NlConstrBuilderArray.getSize()
Synopsis
getSize()Description
Retrieve the number of elements in the NlConstrBuilderArray Class object.
Return Value
An integer.
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
sossisNone, then build an empty SOSArray Class object, otherwise initialize the newly created SOSArray Class object withsoss.Arguments
sossSOS constraint to be added. Optional,
Noneby 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
sosSOS 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
idxIndice 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()
# 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()
# 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
sostypeSOS constraint type. Full list of available types can be found in SOS-constraint types.
varsVariables of SOS constarint, which can be VarArray Class object, list, dictionary or tupledict Class object.
weightsWeights of variables in SOS constraint. Optional,
Noneby 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()
# 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
idxIndice 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
idxIndice 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()
# 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
sosbuildersisNone, then create an empty SOSBuilderArray Class object, otherwise initialize the newly created SOSBuilderArray Class object with parametersosbuilders.Arguments
sosbuildersSOS constraint builder to be added. Optional,
Noneby 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
sosbuilderSOS 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
idxIndice 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
conesisNone, then build an empty ConeArray Class object, otherwise initialize the newly created ConeArray Class object withcones.Arguments
conesSecond-Order-Cone constraint to be added. Optional,
Noneby 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
coneSecond-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
idxIndice 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()
# 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()
# Create an empty ConeBuilder object.
conebuilder = ConeBuilder()
ConeBuilder.setBuilder()
Synopsis
setBuilder(conetype, vars)Description
Set type, variables of ConeBuilder Class object.
Arguments
conetypeType of Second-Order-Cone (SOC) constraint. Full list of available types can be found in SOC-constraint types.
varsVariables 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
idxIndice 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()
# 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
conebuildersisNone, then create an empty ConeBuilderArray Class object, otherwise initialize the newly created ConeBuilderArray Class object with parameterconebuilders.Arguments
conebuildersSOC constraint builder to be added. Optional,
Noneby 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
conebuilderSOC 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
idxIndice 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
conesisNone, then build an empty ExpConeArray Class object, otherwise initialize the newly created ExpConeArray Class object withcones.Arguments
conesExponential cone constraint to be added. Optional,
Noneby 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
coneExponential 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
idxIndice 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()
# Create an empty ExpConeBuilder object.
ExpConeBuilder = ExpConeBuilder()
ExpConeBuilder.setBuilder()
Synopsis
setBuilder(conetype, vars)Description
Set type of variables of ExpConeBuilder Class object.
Arguments
conetypeType of exponential cone constraint. Full list of available types can be found in exponential cone types.
varsVariables 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
idxIndice 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
ExpConeBuildersisNone, then create an empty ExpConeBuilderArray Class object, otherwise initialize the newly created ExpConeBuilderArray Class object with parameterExpConeBuilders.Arguments
ExpConeBuildersExponential cone constraint builder to be added. Optional,
Noneby 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
conebuilderExponential 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
idxIndice 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()
AffineCone Class
The AffineCone class encapsulates operations related to affine cone in COPT. The following methods are provided:
AffineCone.getIdx()
Synopsis
getIdx()Description
Retrieve the index of the affine cone in the model.
Example
# Retrieve the index of the afcone
afconeidx = afcone.getIdx()
AffineCone.getName()
Synopsis
getName()Description
Retrieve the name of the affine cone.
Example
# Retrieve the name of the afcone
afconename = afcone.getName()
AffineCone.setName()
Synopsis
setName(newname)Description
Set the name of the affine cone.
Arguments
newnameThe name to set for the affine cone.
Example
# Set the name of the afcone
afcone.setName("afcone")
AffineCone.remove()
Synopsis
remove()Description
Remove the current affine cone from the model.
Example
# Remove the current afcone from the model
afcone.remove()
AffineConeArray Class
To facilitate user operations on a group of AffineCone Class objects, COPT introduces the AffineConeArray class. The following methods are provided:
AffineConeArray()
Synopsis
AffineConeArray(cones=None)Description
Creates an AffineConeArray Class object.
If the argument
conesisNone, an empty AffineConeArray Class object is created. Otherwise, the new AffineConeArray Class object is initialized with the argumentcones.Arguments
conesAffine cone constraints to be added. This is an optional parameter, the default value is
None.Acceptable values include AffineCone Class objects, AffineConeArray Class objects, lists, dictionaries, or tupledict Class objects.
Example
# Create an empty AffineConeArray object
afconearr = AffineConeArray()
# Create an AffineConeArray object initialized with afconex and afconey
afconearr = AffineConeArray([afconex, afconey])
AffineConeArray.pushBack()
Synopsis
pushBack(cone)Description
Adds one or more AffineCone Class objects.
Arguments
coneAffine cone constraints to be added. Possible values include AffineCone Class objects, AffineConeArray Class objects, lists, dictionaries, or tupledict Class objects.
Example
# Add afconex to afconearr
afconearr.pushBack(afconex)
# Add afconex and afconey to afconearr
afconearr.pushBack([afconex, afconey])
dict_cone = {'AC': afcone1, 'CA': afcone2}
afconearr2 = AffineConeArray({'AC': afcone1, 'CA': afcone2})
AffineConeArray.getCone()
Synopsis
getCone(idx)Description
Retrieves the affine cone at the specified index in the AffineConeArray Class object. Returns an AffineCone Class object.
Arguments
idxIndex of the affine cone constraint in the AffineConeArray Class object. Indexing starts at 0.
Example
# Retrieve the affine cone at index 1 in afconearr
afcone = afconearr.getCone(1)
AffineConeArray.getSize()
Synopsis
getSize()Description
Retrieves the number of elements in the AffineConeArray Class object.
Example
# Get the number of affine cone in afconearr
arrsize = afconearr.getSize()
AffineConeBuilder Class
The AffineConeBuilder class is an encapsulation of the builder for constructing affine cone in COPT. The following methods are provided:
AffineConeBuilder()
# Create an empty AffineConeBuilder object
afconebuilder = AffineConeBuilder()
AffineConeBuilder.setBuilder()
Synopsis
setBuilder(conetype, exprs)Description
Sets up the affine cone builder according to
conetypeandexprs.Arguments
conetypeThe type of affine cone. For possible values, refer to Second-Order Cone Constraint Types and Exponential Cone Constraint Types.
exprsMathematical expressions forming the affine cone. Possible values include linear expressions or semidefinite expressions.
Example
# Set the affine cone builder's type to standard second-order cone,
# composed of z, x+y, y
afconebuilder = AffineConeBuilder()
afconebuilder.setBuilder(COPT.CONE_QUAD, [z, x+y, y])
AffineConeBuilder.hasPsdTerm()
Synopsis
hasPsdTerm()Description
Checks if the affine cone builder contains any semidefinite terms.
Return Value
Bool. If
False, the affine cone contains no semidefinite terms, and linear expressions can be directly retrieved.
AffineConeBuilder.getType()
Synopsis
getType()Description
Retrieves the affine cone type of the AffineConeBuilder Class object.
Example
# Retrieve the type of afconex
afconetype = afconebuilder.getType(afconex)
AffineConeBuilder.getExpr()
Synopsis
getExpr(idx)Description
Retrieves the expression at the specified index in the affine cone builder.
Arguments
idxThe index of the expression in the affine cone builder, starting with
0.Return Value
If semidefinite terms exist, returns a PsdExpr object; otherwise, returns a LinExpr object.
Example
# Retrieve the expression at index 0 in the affine cone builder
expr = afconstrbuilder.getExpr(0)
AffineConeBuilder.getPsdExpr()
Synopsis
getPsdExpr(idx)Description
Retrieves the semidefinite expression at the specified index in the affine cone builder.
Arguments
idxThe index of the semidefinite expression in the affine cone builder, , starting with
0.Return Value
Returns a PsdExpr object.
Example
# Retrieve the semidefinite expression at index 0 in the afconstrbuilder
psdexpr = afconstrbuilder.getPsdExpr(0)
AffineConeBuilder.getExprs()
Synopsis
getExprs(idx=None)Description
Retrieves a group of expressions from the affine cone builder at the specified indices.
Arguments
idxThe indices of the expressions in the affine cone builder.
If
idxisNone, all expressions in the affine cone are returned. Ifidxis a Python list, the expressions at the specified indices are returned.Return Value
If semidefinite terms exist, returns PsdExpr objects; otherwise, returns LinExpr objects.
Example
# Retrieve all expressions in the affine cone builder
allexprs = afconstrbuilder.getExprs()
AffineConeBuilder.getPsdExprs()
Synopsis
getPsdExprs(idx=None)Description
Retrieves a group of semidefinite expressions from the affine cone builder at the specified indices.
Arguments
idxThe indices of the semidefinite expressions in the affine cone builder.
If
idxisNone, all semidefinite expressions in the affine cone are returned. Ifidxis a Python list, the semidefinite expressions at the specified indices are returned.Return Value
Returns PsdExpr objects.
Example
# Retrieve all semidefinite expressions in the afconstrbuilder
allpsdexprs = afconstrbuilder.getPsdExprs()
AffineConeBuilder.getSize()
Synopsis
getSize()Description
Retrieves the number of expressions in the affine cone builder.
Example
# Retrieve the number of expressions in the afconebuilder
afconesize = afconebuilder.getSize()
AffineConeBuilderArray Class
To facilitate user operations on a group of AffineConeBuilder Class objects, COPT introduces the AffineConeBuilderArray class, providing the following methods:
AffineConeBuilderArray()
Synopsis
AffineConeBuilderArray(conebuilders=None)Description
Creates an AffineConeBuilderArray Class object.
If the argument
conebuildersisNone, an empty AffineConeBuilderArray Class object is created. Otherwise, the new AffineConeBuilderArray Class object is initialized with the argumentconebuilders.Arguments
conebuildersAffine cone constraint builders to add. This is an optional argument, defaulting to
None. Acceptable values include AffineConeBuilder Class objects, AffineConeBuilderArray Class objects, lists, dictionaries, or tupledict Class objects.Example
# Create an empty AffineConeBuilderArray object
conebuilderarr = AffineConeBuilderArray()
# Create an AffineConeBuilderArray object initialized with conex and coney
conebuilderarr = AffineConeBuilderArray([conex, coney])
AffineConeBuilderArray.pushBack()
Synopsis
pushBack(AffineConeBuilder)Description
Adds one or more AffineConeBuilder Class objects.
Arguments
AffineConeBuilderAffine cone builders to add. Acceptable values include AffineConeBuilder Class objects, AffineConeBuilderArray Class objects, lists, dictionaries, or tupledict Class objects.
Example
# Add affine cone builder afconex to afconebuilderarr
afconebuilderarr.pushBack(afconex)
AffineConeBuilderArray.getBuilder()
Synopsis
getBuilder(idx)Description
Retrieves the affine cone builder at the specified index in the AffineConeBuilderArray Class object.
Arguments
idxThe index of the affine cone builder in the AffineConeBuilderArray Class object. Indexing starts at 0.
Example
# Retrieve the second-order affine cone builder at index 1 in afconebuilderarr
affineConeBuilder = afconebuilderarr.getBuilder(1)
AffineConeBuilderArray.getSize()
Synopsis
getSize()Description
Retrieves the number of elements in the AffineConeBuilderArray Class object.
Example
# Get the number of elements in afconebuilderarr
afconebuildersize = afconebuilderarr.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
genconstrsisNone, then create an empty GenConstrArray Class object, otherwise initialize the newly created GenConstrArray Class object with parametergenconstrs.Arguments
genconstrsIndicator constraint to be added. Optional,
Noneby 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
constrsThe 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
idxIndice 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()
# 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
varIndicator variable.
valValue of an indicator variable.
exprExpression of linear constraint, which can be Var Class object or LinExpr Class object.
senseSense for the linear constraint. Please refer to Constraint type for possible values.
typeType 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
genconstrbuildersisNone, then create an empty GenConstrBuilderArray Class object; otherwise use the argumentgenconstrbuildersto initialize the newly created GenConstrBuilderArray Class object.Arguments
genconstrbuildersIndicator constraint builder to add. Optional,
Noneby 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
genconstrbuilderIndicator 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
idxIndex 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
constrsisNoneand argumentcoeffsisNone, then create an empty Column Class object; otherwise use the argumentconstrsandcoeffsto initialize the newly created Column Class object. If argumentconstrsis a Constraint Class or Column Class object, then argumentcoeffsis a constant. If argumentcoeffsisNone, then it is considered to be constant 1.0; If argumentconstrsis a list and argumentcoeffsisNone, then the elements of argumentconstrsare constraint-coefficient pairs; For other forms of arguments, call methodaddTermsto initialize the newly created Column Class object.Arguments
constrsLinear constraint.
coeffsCoefficient 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
idxIndex 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
idxIndex for the element, starting with 0.
Example
# Retrieve the linear constraint whose index is 1 in col
constr = col.getConstr(1)
Column.getSize()
# Retrieve the number of elements in col
colsize = col.getSize()
Column.addTerm()
Synopsis
addTerm(constr, coeff=1.0)Description
Add a new term.
Arguments
constrThe linear constraint for the term to add.
coeffThe 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
constrsis Constraint Class object, then argumentcoeffsis constant; If argumentconstrsis ConstrArray Class object or list, then argumentcoeffsis constant or list; If argumentconstrsis dictionary or tupledict Class object, then argumentcoeffsis constant, dict, or tupledict Class object.Arguments
constrsThe linear constraints for terms to add.
coeffsThe 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
colColumn to add.
multMagnification 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
itemis a constant, then remove the term by its index; otherwise argumentitemis a Constraint Class object.Arguments
itemConstant 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
columnsisNone, then create an empty ColumnArray Class object; otherwise use argumentcolumnsto initialize the newly created ColumnArray Class object.Arguments
columnsColumns to add. Optional,
Noneby 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
columnColumns 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
idxIndex 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()
# 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
varsA 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
varA 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
offsetOptional 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.
axis1Optional 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.
axis2Optional 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
infonameThe name of the information being queried. Please refer to Information Section for possible values.
Return value
Returns a
NumPyndarray with the same dimension as theMVarobject, 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
shapeThe value is an integer, or a tuple of integers. which represents the shape of the new MVar object.
orderOptional 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
infonameThe name of the information being queried. Please refer to Information Section for possible values.
newvalThe 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
axisOptional 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
ndimDescription
Dimensions of the MVar object.
Return value
Integer value.
Example
mx = model.addMVar((3, 5)) print(mx.ndim) #ndim = 2
MVar.shape
Synopsis
shapeDescription
The shape of the MVar object.
Return value
Integer tuple.
Example
mx = model.addMVar((3,)) print(mx.shape) # shape = (3, )
MVar.size
Synopsis
sizeDescription
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
TDescription
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
infonameThe 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
shapeThe value is an integer, or a tuple of integers. which represents the shape of the new MConstr object.
orderOptional 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
infonameThe name of the information to be set. Please refer to Information Section for possible values.
newvalThe 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
ndimDescription
Dimensions of the MConstr object.
Return value
Integer value.
Example
mc = m.addConstrs(a @ mx <= b) print(mc.ndim)
MConstr.shape
Synopsis
shapeDescription
The shape of the MConstr object.
Return value
Integer tuple.
Example
mc = m.addConstrs(a @ mx <= b) print(mc.shape)
MConstr.size
Synopsis
sizeDescription
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
TDescription
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
argsone or a set of ConstrBuilder Class objects, in form of Python list or NumPy ndarray.
shapean 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
infonameThe 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
shapeThe value is an integer, or a tuple of integers. which represents the shape of the new MQConstr object.
orderOptional 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
infonameThe name of the information to be set. Please refer to Information Section for possible values.
newvalThe 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
ndimDescription
Dimensions of the MQConstr object.
Return value
Integer value.
Example
mc = m.addQConstr(mx.T @ mx <= 1.0) print(mc.ndim)
MQConstr.shape
Synopsis
shapeDescription
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
sizeDescription
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
TDescription
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
argsone or a set of QConstrBuilder Class objects, in form of Python list or NumPy ndarray.
shapean 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)
MPsdConstr Class
The MPsdConstr class in the COPT is used to construct multi-dimensional semidefinite constraints. It is created via the addConstr or addConstrs methods of the model class. The following member methods are provided:
MPsdConstr.getInfo()
Synopsis
getInfo(infoname)Description
Retrieves the information value for each semidefinite constraint in the MPsdConstr.
Arguments
infonameThe name of the information to retrieve. Possible values are detailed in Information Section.
Return Value
Returns the information value as a multi-dimensional array.
Example
mpsdcon = model.addConstr(barX[:-1, :-1].sum() == 1) print(mpsdcon.UB) print(mpsdcon.getInfo("UB"))
MPsdConstr.setInfo()
Synopsis
setInfo(infoname, newval)Description
Sets the information value for each semidefinite constraint in the MPsdConstr.
Arguments
infonameThe name of the information to set. Possible values are detailed in Information Section.
newvalThe new value to set for the information.
Example
barX = model.addPsdVars(3, "BAR_X") mY = model.addMVar(2, nameprefix="M_X") mpsdCon = model.addConstrs(barX[:-1, :-1].diagonal() == mY) mpsdCon.UB = 10 mpsdCon.setInfo("UB", 10)
MPsdConstr.item()
Synopsis
item()Description
Retrieves the semidefinite constraint object in a 0-dimensional MPsdConstr. If the MPsdConstr object is not 0-dimensional, raises a ValueError.
Return Value
Returns a PsdConstraint object.
Example
barX = model.addPsdVars(3, "BAR_X") mY = model.addMVar(2, nameprefix="M_X") mpsdCon = model.addConstrs(barX[:-1, :-1].diagonal() == mY) psdCon = mpsdCon[1].item()
MPsdConstr.clone()
Synopsis
clone()Description
Creates a deep copy of an MPsdConstr Class object.
Return Value
Returns a new MPsdConstr object.
Example
barX = model.addPsdVars(3, "BAR_X") mY = model.addMVar(2, nameprefix="M_X") mpsdCon = model.addConstrs(barX[:-1, :-1].diagonal() == mY) mpsdCon_copy = mpsdCon.clone()
MPsdConstrBuilder Class
The MPsdConstrBuilder class in COPT is used as a generator for multi-dimensional semidefinite constraints. It can be generated from a group of PsdConstrBuilder Class objects or by overloading the comparison operators of MVar Class and MPsdExpr Class objects. The following methods are provided:
MPsdConstrBuilder()
# Create an empty semidefinite constraint builder
constrbuilder = MPsdConstrBuilder()
MPsdConstrBuilder.setBuilder()
Synopsis
setBuilder(expr, sense, rhs)Description
Sets the expression and constraint type for the multi-dimensional semidefinite constraint builder.
Arguments
exprThe expression to set. Possible values include constants, MVar Class objects, MLinExpr Class objects, or MPsdExpr Class objects.
senseThe constraint type. Possible values are detailed in Constraint Types.
rhsThe right-hand side of the constraint. Possible values include constants, MVar Class objects, MLinExpr Class objects, or MPsdExpr Class objects.
Example
# Set the expression for the multi-dimensional PSD constraint builder: x + y == 1
constrbuilder.setBuilder(x + y, COPT.EQUAL, 1)
MPsdConstrBuilder.setRange()
Synopsis
setRange(expr, range)Description
Sets the expression and the range for the multi-dimensional PSD constraint builder. The format is expr less than or equal to 0, and greater than or equal to -range.
Arguments
exprThe expression to set. Possible values include MPsdExpr Class objects.
rangeThe right-hand side of the range constraint. Must be non-negative.
Example
# Set the expression for the multi-dimensional PSD constraint builder: x + y - 1, with range 1
constrbuilder.setRange(x + y - 1, 1)
MPsdConstrBuilder.getPsdExpr()
Synopsis
getPsdExpr()Description
Retrieves the expression of the multi-dimensional PSD constraint builder.
Example
# Retrieve the expression of the multi-dimensional PSD constraint builder
psdexpr = constrbuilder.getPsdExpr()
MPsdConstrBuilder.getSense()
Synopsis
getSense()Description
Retrieves the constraint type of the multi-dimensional PSD constraint builder.
Example
# Retrieve the constraint type of the multi-dimensional PSD constraint builder
consense = constrbuilder.getSense()
MPsdConstrBuilder.getRange()
Synopsis
getRange()Description
Retrieves the range right-hand side of the multi-dimensional PSD constraint builder, representing the range between the upper and lower bounds.
Example
# Retrieve the range right-hand side of the multi-dimensional PSD constraint builder
rngval = constrbuilder.getRange()
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
shapeThe 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
shapeThe value is an integer, or a tuple of integers. which represents the shape of the new MLinExpr object.
orderOptional 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
axisOptional 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
ndimDescription
MLinExpr Class Dimensions of the object.
Return value
Integer value.
Example
mexpr = 2.0 * model.addMVar((3, 5)) print(mexpr.ndim)
MLinExpr.shape
Synopsis
shapeDescription
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
sizeDescription
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
TDescription
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
a MConstrBuilder Class object.
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
a MConstrBuilder Class object.
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
a MConstrBuilder Class object.
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
shapeThe 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
shapeThe value is an integer, or a tuple of integers. which represents the shape of the new MQuadExpr object.
orderOptional 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
axisOptional 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
ndimDescription
MQuadExpr Class Dimensions of the object.
Return value
Integer value.
Example
mqx = MQuadExpr.zeros((2,3)) print(mqx.ndim) # ndim = 2
MQuadExpr.shape
Synopsis
shapeDescription
MQuadExpr Class The shape of the object.
Return value
Integer tuple.
Example
print(MQuadExpr.zeros((2,3)).shape) # shape = (2, 3)
MQuadExpr.size
Synopsis
sizeDescription
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
TDescription
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
a MQConstrBuilder Class object.
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
a MQConstrBuilder Class object.
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
a MQConstrBuilder Class object.
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
ValueErrorexception 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
shapeThe value could be an integer or a tuple of integers, representing the shape of the new NdArray object.
orderOptional. 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
axisOptional integer argument. The default value is None, which means summing all elements. Otherwise, it will sum according to the given axis.
Return value
If
axisis empty, returns a new 0-dimensional NdArray object, in which element is the sum of the corresponding elements.If
axisis 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
valueThe 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
axisThe 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
axisThe 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
idxThe specified one-dimensional index is the corresponding one after flattening NdArray into one dimension.
valueThe new value of the specified element.
Return value
Returns a NdArray object in which the element value of
idxis set tovalue.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
offsetOptional 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.
axis1Optional 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).
axis2Optional 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
ndimDescription
The dimensions of the NdArray object.
Return value
An integer Value
Example
ndmat = NdArray((3, 5)) print(ndmat.ndim) # ndim = 2
NdArray.shape
Synopsis
shapeDescription
The shape of the NdArray object.
Return value
An integer tuple.
Example
ndmat = NdArray((3, 5)) print(ndmat.shape) # shape = (3, 5)
NdArray.pick()
Synopsis
pick(indexes)Description
Retrieves a new multi-dimensional array from the NdArray object according to the specified indices.
Arguments
indexesThe specified indices.
Return Value
Returns a new NdArray object.
NdArray.hstack()
Synopsis
hstack(other)Description
Stacks another NdArray object along the horizontal dimension (last dimension) to form a new NdArray object.
Arguments
otherAnother NdArray object.
Return Value
Returns a new NdArray object.
NdArray.vstack()
Synopsis
vstack(other)Description
Stacks another NdArray object along the vertical dimension to form a new NdArray object.
Arguments
otherAnother NdArray object.
Return Value
Returns a new NdArray object.
NdArray.stack()
Synopsis
stack(other, axis)Description
Stacks another NdArray object along the specified axis to form a new NdArray object.
Arguments
otherAnother NdArray object.
axisThe specified axis index.
Return Value
Returns a new NdArray object.
NdArray.size
Synopsis
sizeDescription
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
TDescription
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
arg1is constant, argumentarg2isNone, then create a ExprBuilder Class object and initialize it using argumentarg1. If argumentarg1is Var Class or ExprBuilder Class object, and argumentarg2is constant or considered to be constant 1.0 when argumentarg2isNone, then initialize the newly created ExprBuilder Class object using argumentsarg1andarg2. If argumentarg1andarg2are list objects, then they are variables and coefficients used to initialize the newly created ExprBuilder Class object.Arguments
arg1Optional, 0.0 by default.
arg2Optional,
Noneby 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
idxIndex 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
idxIndex 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
varVariable to add.
coeffMagnification 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
exprExpression builder to add.
coeffMagnification 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
arg1is constant, argumentarg2isNone, then create a LinExpr Class object and initialize it using argumentarg1. If argumentarg1is Var Class or LinExpr Class object, and argumentarg2is constant or considered to be constant 1.0 when argumentarg2isNone, then initialize the newly created LinExpr Class object using argumentsarg1andarg2. If argumentarg1is list object and argumentarg2isNone, then argumentarg1contains a list of variable-coefficient pairs and initialize the newly created LinExpr Class object using argumentsarg1andarg2. For other forms of arguments, call methodaddTermsto initialize the newly created LinExpr Class object.Arguments
arg1Optional, 0.0 by default.
arg2Optional,
Noneby 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
idxIndex of the variable in the expression, starting with 0.
newvalNew 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
idxIndex 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
idxIndex 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
newvalConstant 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
newvalConstant 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
varVariable to add.
coeffMagnification 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
varsis Var Class object, then argumentcoeffsis constant; If argumentvarsis VarArray Class object or list, then argumentcoeffsis constant or list; If argumentvarsis dictionary or tupledict Class object, then argumentcoeffsis constant, dict, or tupledict Class object.Arguments
varsVariables to add.
coeffsCoefficients 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
exprExpression or expression builder to add.
coeffMagnification 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
nNumber 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
itemis constant, then remove the term stored at index i of the expression; otherwise argumentitemis Var Class object.Arguments
itemConstant 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 quadratic constraints, and provides the following methods:
QuadExpr()
Synopsis
QuadExpr(expr=0.0)Description
Create a QuadExpr Class object.
Argument
expris constant, Var Class, LinExpr Class object or QuadExpr Class object.Arguments
exprOptional, 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
idxIndex of the term in the quadratic expression, starting with 0.
newvalNew 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
idxIndex 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
idxIndex 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
idxIndex 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
newvalConstant 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
newvalConstant 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
coeffMagnification coefficient for added term. Optional, 1.0 by default.
var1The first variable for added term.
var2The 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
varsis Var Class object, then argumentvars2is Var Class object orNone, argumentcoeffsis constant; If argumentvarsis VarArray Class object or list, then argumentvars2is VarArray Class object, list orNone, argumentcoeffsis constant or list; If argumentvarsis dictionary or tupledict Class object, then argumentvars2is dictionary, tupledict Class object orNone, argumentcoeffsis constant, dictionary, or tupledict Class object.Arguments
coeffsCoefficients for terms.
vars1The first variable of each term.
vars2The 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
exprLinear expression or linear expression builder to add.
multMagnification 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
exprExpression or expression builder to add.
multMagnification 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
nNumber 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
itemis constant, then remove the term stored at index i of the expression; otherwise argumentitemis Var Class object.Arguments
itemConstant 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
exprOptional, 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
idxin the LMI expression.Arguments
idxIndex of the positive semi-definite variable in the expression, starting with 0.
matNew 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
idxIndex 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
idxIndex 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
newvalConstant 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
newvalConstant 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
varThe positive semi-definite variable to add.
matThe 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
varsis PsdVar Class object, then argumentmatsis SymMatrix Class object; If argumentvarsis PsdVarArray Class object or list, then argumentmatsis SymMatrixArray Class or list;Arguments
varsThe positive semi-definite variables to add.
matsThe 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
exprLinear expression or linear expression builder to add.
multMagnification 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
exprPositive semi-definite expression or positive semi-definite expression builder to add.
multMagnification 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.addMExpr()
Synopsis
addMExpr(expr, mult=1.0)Description
Add a new multi-dimensional expression to the current PSD expression.
Arguments
exprThe multi-dimensional array expression or expression builder object to add.
multThe scaling factor for the multi-dimensional array expression. Optional, defaulting to 1.0.
Example
# Add a multi-dimensional linear expression: 2.0 * A @ x to the PSD expression expr
expr.addMExpr(A @ x, 2.0)
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
nNumber 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
itemis constant, then remove the term stored at index i of the expression; otherwise argumentitemis PsdVar Class object.Arguments
itemConstant 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)
MPsdExpr Class
The MPsdExpr class in COPT is used for operations that combine PSD variables into multi-dimensional PSD expressions. The following methods are provided:
MPsdExpr.addTerm()
Synopsis
addTerm(var, mat)Description
Adds a new PSD term to the current multi-dimensional PSD expression.
Arguments
varThe semidefinite variable in the term to be added.
matThe symmetric matrix in the term to be added.
Example
# Add the PSD term C1 * X to mexpr
mexpr.addTerm(X, C1)
MPsdExpr.addTerms()
Synopsis
addTerms(vars, coeffs)Description
Adds new terms to the multi-dimensional PSD expression object.
Arguments
varsMulti-dimensional array variable objects. Possible value could be MVar.
coeffsCoefficient matrices for the terms. Possible values could be a floating number or NdArray.
Example
# Add terms: mA @ mX to mpsdexpr
mX = model.addMVar((3,3), nameprefix="M_X")
mA = cp.NdArray(np.ones(shape=(3,3)))
mpsdexpr.addTerms(mX, mA)
MPsdExpr.addLinExpr()
Synopsis
addLinExpr(expr, mult=1.0)Description
Adds a new linear expression to the current multi-dimensional PSD expression.
Arguments
exprThe linear expression or expression builder object to add. Possible values could be LinExpr or ExprBuilder.
multThe scaling factor for the linear expression. Optional, defaulting to 1.0.
Example
# Add a linear expression: 2*x + 2*y to mexpr
mexpr.addLinExpr(x + y, 2.0)
MPsdExpr.addPsdExpr()
Synopsis
addPsdExpr(expr, mult=1.0)Description
Adds a new semidefinite expression to the current multi-dimensional PSD expression.
Arguments
exprThe semidefinite expression to add.
multThe scaling factor for the PSD expression. Optional, defaulting to 1.0.
Example
# Add a PSD expression: C * X to mexpr
mexpr.addPsdExpr(C * X)
MPsdExpr.addMExpr()
Synopsis
addMExpr(expr, mult=1.0)Description
Add a new multi-dimensional expression to the current multi-dimensional PSD expression.
Arguments
exprThe multi-dimensional expression or expression builder object to add.
multThe scaling factor for the multi-dimensional expression. Optional, defaulting to 1.0.
Example
# Add a multi-dimensional linear expression: 2.0 * A @ x to mexpr
mexpr.addMExpr(A @ x, 2.0)
MPsdExpr.addMLinExpr()
Synopsis
addMLinExpr(exprs, mult=1.0)Description
Add corresponding linear expressions to each PSD expression in the
MPsdExprobject.Arguments
exprsThe multi-dimensional linear expressions or expression builder objects to add.
multThe same scaling factor for all linear expressions to add. Optional, defaulting to 1.0.
Example
# Add a linear expression A @ x to each PSD expression in mexpr
mexpr.addMLinExpr(A @ x)
MPsdExpr.addMPsdExpr()
Synopsis
addMPsdExpr(exprs, mult=1.0)Description
Adds corresponding new PSD expressions to each PSD expression in the
MPsdExprobject.Arguments
exprsThe new semidefinite expressions to add.
multThe same scaling factor for all PSD expressions to add. Optional, defaulting to 1.0.
Example
# Add a PSD expression: C * X to each PSD expression in mexpr
mexpr.addMPsdExpr(C * X)
MPsdExpr.item()
Synopsis
item()Description
Retrieves the PsdExpr in a 0-dimensional semidefinite expression. If the MPsdExpr object is not 0-dimensional, raises a ValueError.
Return Value
Returns a PsdExpr object.
Example
barX = model.addPsdVars(3, "BAR_X")
mpsdexpr = barX[:-1, :-1]
psdexpr1 = mpsdexpr[0,0].item()
psdexpr2 = mpsdexpr.sum().item()
MPsdExpr.sum()
Synopsis
sum(axis=None)Description
Computes the sum of the semidefinite terms along the specified axis in the MPsdExpr object.
Arguments
axisOptional. Defaults to None, which sums over all variables. Otherwise, sums along the specified axis.
Return Value
Returns an MPsdExpr Class object representing the sum of the corresponding multi-dimensional PSD expressions.
MPsdExpr.clear()
barX = model.addPsdVars(3, "BAR_X")
mpsdexpr = barX[:-1, :-1]
mpsdexpr.clear()
MPsdExpr.clone()
Synopsis
clone()Description
Creates a deep copy of an MPsdExpr Class object.
Return Value
Returns a new MPsdExpr object.
Example
barX = model.addPsdVars(3, "BAR_X")
mpsdexpr = barX[:-1, :-1]
newmpsdexpr = mpsdexpr.clone()
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
arg1isNone, and the possible values are: Var Class object, or SymMatrix Class object.If the argument
arg1is a Var Class object, then the argumentarg2is a SymMatrix Class object.
LmiExpr.setCoeff()
Synopsis
setCoeff(idx, mat)Description
Set the coefficient matrix for the entry corresponding to the specified index
idxin the LMI expression.Arguments
idxThe specified the index value. Starts with 0.
matThe 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
idxin the LMI expression.Arguments
idxThe 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
idxin the LMI expression.Arguments
idxThe 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
matThe 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
matMatrix 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
varThe variable in the new item.
matThe 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
varsis PsdVar Class object, then argumentmatsis SymMatrix Class object; If argumentvarsis PsdVarArray Class object or list, then argumentmatsis SymMatrixArray Class or list;Arguments
varsArray of variables to add new items to.
matsThe 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
exprLMI expression to add.
multMagnification 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
nNumber of terms to be allocated.
Example
# Allocate 100 terms for LMI expression 'expr'
expr.reserve(100)
LmiExpr.remove()
# 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)
NlExpr Class
The NlExpr class provides interfaces for constructing nonlinear expressions
in the COPT. It supports variable combination operations and offers the following member functions:
NlExpr()
Synopsis
NlExpr(arg1=0.0, arg2=None)Description
Creates a NlExpr Class object.
If
arg1is a float andarg2isNone, a constant nonlinear expression is created with valuearg1.If
arg1is a Var Class, LinExpr Class, QuadExpr Class, or ExprBuilder Class, thenarg2can be a float orNone, indicating that the expression is scaled byarg2(default is 1.0).Arguments
arg1Optional argument. Default is 0.0.
Acceptable types include float, Var Class, LinExpr Class, QuadExpr Class, or ExprBuilder Class.
arg2Coefficient of the expression.
Optional argument. Default is
None, which is interpreted as 1.0.Example
# Variable term with coefficient: 2 * x
expr1 = NlExpr(x, 2)
# Linear expression: 2 * x + 3 * y
lin = 2 * x + 3 * y
expr2 = NlExpr(lin)
NlExpr.getConstant()
Synopsis
getConstant()Description
Returns the constant term in the nonlinear expression.
Example
# Get the constant term of nexpr
constant = nexpr.getConstant()
NlExpr.getSize()
Synopsis
getSize()Description
Returns the number of terms in the nonlinear expression.
Example
# Get the number of elements in nexpr
exprsize = nexpr.getSize()
NlExpr.getValue()
Synopsis
getValue()Description
Returns the value of the nonlinear expression based on the current values of the variables.
Example
# Get the current value of the nonlinear expression nlexpr
val = nlexpr.getValue()
NlExpr.setConstant()
Synopsis
setConstant(newval)Description
Sets the constant term of the nonlinear expression.
Arguments
newvalThe constant value to set.
Example
# Set constant of nexpr to 2.0
nexpr.setConstant(2.0)
NlExpr.addConstant()
Synopsis
addConstant(newval)Description
Adds a constant term to the nonlinear expression.
Arguments
newvalThe constant value to add.
Example
# Add constant 2.0 to nexpr
nexpr.addConstant(2.0)
NlExpr.addTerm()
Synopsis
addTerm(var, coeff=1.0)Description
Adds a single linear term to the nonlinear expression.
Arguments
varVariable in the new term.
coeffCoefficient of the new term. Optional, default is 1.0.
Example
# Add term 2*x to nexpr
nexpr.addTerm(x, 2)
NlExpr.addTerms()
Synopsis
addTerms(vars, coeffs)Description
Adds one or more linear terms to the nonlinear expression.
If
varsis a Var Class object,coeffsmay be a single constant.If
varsis a VarArray Class or an iterable of Var Class objects,coeffsmay be a single constant or a list of constants corresponding to each variable.If
varsis a mapping from arbitrary keys to variables,coeffsmay be a single constant or a mapping with the same keys specifying individual coefficients.Arguments
varsVariables to add.
coeffsCoefficients for the terms.
Example
# Add terms 2*x + 3*y to nexpr
nexpr.addTerms([x, y], [2.0, 3.0])
NlExpr.addLinExpr()
Synopsis
addLinExpr(expr, mult=1.0)Description
Adds a linear expression
exprto the current nonlinear expression, scaling all terms by the given multipliermult.Arguments
exprLinear expression to be added.
Must be a ExprBuilder Class or LinExpr Class object.
multScaling factor applied to all terms in
expr.Optional argument. Default is 1.0.
Example
# Add a scaled linear expression to nexpr
lexpr = LinExpr(x, 2.0) + y * 3.0
nexpr = NlExpr()
nexpr.addLinExpr(lexpr)
nexpr.addLinExpr(lexpr, mult=0.5)
NlExpr.addQuadExpr()
Synopsis
addQuadExpr(expr, mult=1.0)Description
Adds a quadratic expression
exprto the current nonlinear expression, with all terms scaled bymult.Arguments
exprQuadratic expression to add.
Must be a QuadExpr Class object.
multScaling factor for all terms.
Optional. Default is 1.0.
NlExpr.addNlExpr()
Synopsis
addNlExpr(expr, mult=1.0)Description
Adds another nonlinear expression
exprto the current expression, with all terms scaled bymult.Arguments
exprNonlinear expression to add.
Must be a NlExpr Class object.
multScaling factor.
Optional. Default is 1.0.
NlExpr.clear()
Synopsis
clear()Description
Clears all contents of the nonlinear expression.
NlExpr.clone()
Synopsis
clone()Description
Creates a deep copy of the current nonlinear expression.
Return Value
A new NlExpr Class object.
NlExpr.negate()
Synopsis
negate()Description
Negates the current nonlinear expression by flipping the sign of each term.
NlExpr.reserve()
Synopsis
reserve(n)Description
Preallocates space for
nterms in the expression.Arguments
nNumber of terms to reserve.
NlExpr.size()
Synopsis
size()Description
Returns the number of nonlinear terms in the expression.
Return Value
An integer.
nl Namespace
nl.abs()
Synopsis
NlExpr abs(expr)Description
Calculate the absolute value of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.acos()
Synopsis
NlExpr acos(expr)Description
Calculate the arc cosine of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.acosh()
Synopsis
NlExpr acosh(expr)Description
Calculate the inverse hyperbolic cosine of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.asin()
Synopsis
NlExpr asin(expr)Description
Calculate the arc sine of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.asinh()
Synopsis
NlExpr asinh(expr)Description
Calculate the inverse hyperbolic sine of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.atan()
Synopsis
NlExpr atan(expr)Description
Calculate the arc tangent of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.atan2()
Synopsis
NlExpr atan2(y, x)Description
Calculate the arc tangent of
y/x, considering the quadrant of the point (x, y).Arguments
yThe numerator (y-coordinate) object.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
xThe denominator (x-coordinate) object.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.atanh()
Synopsis
NlExpr atanh(expr)Description
Calculate the inverse hyperbolic tangent of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.neg()
Synopsis
NlExpr neg(expr)Description
Calculate the negation of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.pow()
Synopsis
NlExpr pow(base, expo)Description
Calculate the exponentiation of the base raised to the power of the exponent.
Arguments
baseThe expression object to be used as the base.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
expoThe expression object to be used as the exponent.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.sin()
Synopsis
NlExpr sin(expr)Description
Calculate the sine of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.sinh()
Synopsis
NlExpr sinh(expr)Description
Calculate the hyperbolic sine of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.sqrt()
Synopsis
NlExpr sqrt(expr)Description
Calculate the square root of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.sum()
Synopsis
NlExpr sum(op1, op2=None, op3=None, op4=None)Description
Calculate the sum of nonlinear expression objects.
Arguments
op1Required argument.
The expression object(s) to be summed.
Possible values include a NlExpr Class object or an iterable/mapping of NlExpr Class objects.
op2,op3,op4Optional arguments.
Additional expression objects to be summed.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.tan()
Synopsis
NlExpr tan(expr)Description
Calculate the tangent of the input object.
Arguments
exprThe object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
nl.tanh()
Synopsis
NlExpr tanh(expr)Description
Calculate the hyperbolic tangent of the input object.
Arguments
exprThe expression object to be calculated.
Possible values include: constant, Var Class object, LinExpr Class, QuadExpr Class, NlExpr Class object, or ExprBuilder Class object.
Return Value
Returns a NlExpr Class object.
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
lhsLeft-hand side expression for the new user cut. It can take the value of Var Class object, LinExpr Class object, or ConstrBuilder Class .
senseThe sense of the new user cut. It supports for
LESS_EQUAL,GREATER_EQUAL,EQUALandFREE.Optional. None by default.
The user cut added from within callback can only have a single comparison operator.
rhsRight-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
generatorArray 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
lhsLeft-hand side expression for the new lazy constraint. It can take the value of Var Class object, LinExpr Class object or ConstrBuilder Class object.
senseThe sense of the lazy constraint. It supports for
LESS_EQUAL,GREATER_EQUAL,EQUALandFREE.Optional. None by default.
The lazy constraint added from within callback can only have a single comparison operator.
rhsRight-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
generatorArray 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
cbinfoThe 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
varsThe variables to retrieve the LP-relaxation solution values.
Return value
When parameter
varsis Var Class object, it returns a constant, which is the LP-relaxation solution value of the specified variable.When parameter
varsis list or VarArray Class object, it returns a list of constants, consisting of the solution of the specified variables.When parameter
argsis 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
argsisNone, 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
varsThe variables whose solution values to retrieve.
Return value
When parameter
varsis Var Class object, it returns a constant, which is the solution value of the specified variable.When parameter
varsis list or VarArray Class object, it returns a list of constants, consisting of the solution of the specified variables.When parameter
argsis 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
argsisNone, 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
varsThe variables whose solution values to retrieve.
Return value
When parameter
varsis Var Class object, it returns a constant, which is the solution value of the specified variable.When parameter
varsis list or VarArray Class object, it returns a list of constants, consisting of the solution of the specified variables.When parameter
argsis 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
argsisNone, 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
varsis Var Class object, parametervalsis constant;When parameter
varsis dictionary or tupledict Class object, parametervalscan be constant, dictionary or tupledict Class object;When parameter
varsis list, VarArray Class object, parametervalscan be constant or list.Arguments
varsThe variables to be set value.
valsThe 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
GenConstrXclass object, support to get the type and name of theGenConstrXclass 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
GenConstrXclass object, and support setting the name of theGenConstrXclass 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
dataA 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
dataTerms 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
listA 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
itemItem 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
patternSpecified pattern.
Example
tl = tuplelist([(0, 1), (0, 2), (1, 2)])
tl.select(0, '*')
repeat()
Synopsis
repeat(obj, repeats)Description
Repeats the specified object a given number of times.
Arguments
objA Python object.
repeatsThe number of repetitions.
hstack()
Synopsis
hstack(left, right)Description
Horizontally stacks the input objects.
Arguments
leftA Python object.
rightA Python object.
vstack()
Synopsis
vstack(left, right)Description
Vertically stacks the input objects.
Arguments
leftA Python object.
rightA Python object.
stack()
Synopsis
stack(left, right, axis)Description
Stacks the input objects along the specified axis.
Arguments
leftA Python object.
rightA Python object.
axisThe specified axis index.
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
argsPositional arguments.
kwargsNamed 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
patternSpecified 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
patternSpecified 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
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
buffSize 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
szNew size of buffer.
Example
# Resize the size of buffer to 100
buff.resize(100)