General constraints
The Xpress Python interface allows the user to use the mathematical operators min, max, abs, and the logical operators and, or without having to explicitly introduce extra variables. The Xpress Optimizer handles such operators by automatically reformulating them as MIP constraints. These constraints are called general constraints by the Optimizer's library.
The min (resp. max) general operators impose that a variable be the minimum (resp. maximum) of two or more variables in a list of arguments. The abs constraints link a variable y to another variable x so that y = |x|.
The And and Or operators express a logical link between two or more binary variables x1,x2, ..., xk. The result of this function is itself a binary expression that can take on value 0 (false) or 1 (true).
The most efficient way, in terms of modelling speed, to formulate a model using the aforementioned operator is through the function problem.addgencons, which adds a general constraint. In the following example, variables y1, y2, and y3 are constrained to be, respectively, the maximum among the set {x[0], x[1], 46}, the absolute value of x[3], and the logical and of x[4], x[5], and x[6].
x = [xp.var() for _ in range(7)] y1 = xp.var() y2 = xp.var() y3 = xp.var() type = [xpress.gencons_max, xpress.gencons_abs, xpress.gencons_and] resultant = [y1, y2, y3] colstart = [0, 2, 3] col = [x[0], x[1], x[3], x[4], x[5], x[6]] valstart = [0,1,1] val = [46] p = xp.problem(x, y1, y2, y3) prob.addgencons(type, resultant, colstart, col, valstart, val); prob.solve()
A more intuitive way to create problems containing these operators is by using the methods max, min, abs, And, and Or of the xpress module.
x = [xp.var() for _ in range(4)] y1 = xp.var() y2 = xp.var() p = xp.problem(x,y1,y2) p.addConstraint(y1 == xp.max(x[0], x[1], 46)) # max() accepts a tuple of arguments p.addConstraint(y2 == xp.abs(x[3])) p.addConstraint(y3 == xp.And(x[4], x[5], x[6])) p.solve()
The methods And and Or can be replaced by the Python binary operators & and |, as in the following example
y = [xp.var(vartype=xp.binary) for _ in range(5)] p = xp.problem(y) p.addConstraint((y[0] & y[1]) + (y[2] | y[3]) + 2*y[4] >= 2)
Note that And and Or have a capital initial as the lower-case correspondents are reserved Python keywords, and that the & and | operators have a lower precedence than arithmetic operators such as + and should hence be used with parentheses.
We also point out that because the & and | operator have lower operator precedence in Python than other arithmetic operators (+, *, etc.) and even comparison operators (≤, etc.), all uses of & and | should be enclosed in brackets. as shown in the examples above.