官网给出的解释:简言之,就是将变量和对应的系数相乘并求和。下面以三个例子来说明:
例1: 变量xi为一维的(这时的coffe可以写成列表的形式,不一定需要字典形式,但规范起见,最好还是写成字典的形式)
import gurobipy
from gurobipy import *
from numpy import *
m = Model()
coffe = [1,2,3,4,5]
xi = m.addVars(5, vtype = GRB.BINARY, name = "xi")
m.setObjective(xi.prod(coffe), GRB.MINIMIZE)
m.update()
m.write("prod_1.lp")
输出:
\ LP format - for model browsing. Use MPS format to capture full model detail.
Minimize
xi[0] + 2 xi[1] + 3 xi[2] + 4 xi[3] + 5 xi[4]
Subject To
Bounds
Binaries
xi[0] xi[1] xi[2] xi[3] xi[4]
End
例2:xij为一个二维变量 (从生成的.lp文件来看,将coffe写成一个矩阵的形式是错误的)
m = Model()
coffe = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
xij = m.addVars(2,5, vtype = GRB.BINARY, name = "xij")
m.setObjective(xij.prod(coffe), GRB.MINIMIZE)
m.update()
m.write("prod_2.lp")
输出:
\ LP format - for model browsing. Use MPS format to capture full model detail.
Minimize
0 xij[0,0] + 0 xij[0,1] + 0 xij[0,2] + 0 xij[0,3] + 0 xij[0,4]
+ 0 xij[1,0] + 0 xij[1,1] + 0 xij[1,2] + 0 xij[1,3] + 0 xij[1,4]
Subject To
Bounds
Binaries
xij[0,0] xij[0,1] xij[0,2] xij[0,3] xij[0,4] xij[1,0] xij[1,1] xij[1,2]
xij[1,3] xij[1,4]
End
例3:例2的正确写法(coffe应当写成字典的形式,键:变量的索引, 值:变量的系数)
m = Model()
# coffe = {(0,0):1, (0,1):2, (0,2):3, (0,3):4, (0,4):5,
# (1,0):6, (1,1):7, (1,2):8, (1,3):9, (1,4):10}
coffe = dict([((0,0),1), ((0,1),2), ((0,2),3), ((0,3),4), ((0,4),5),
((1,0),6), ((1,1),7), ((1,2),8), ((1,3),9), ((1,4),10)])
xij = m.addVars(2,5, vtype = GRB.BINARY, name = "xij")
m.setObjective(xij.prod(coffe), GRB.MINIMIZE)
m.update()
m.write("prod_3.lp")
输出:
\ LP format - for model browsing. Use MPS format to capture full model detail.
Minimize
xij[0,0] + 2 xij[0,1] + 3 xij[0,2] + 4 xij[0,3] + 5 xij[0,4] + 6 xij[1,0]
+ 7 xij[1,1] + 8 xij[1,2] + 9 xij[1,3] + 10 xij[1,4]
Subject To
Bounds
Binaries
xij[0,0] xij[0,1] xij[0,2] xij[0,3] xij[0,4] xij[1,0] xij[1,1] xij[1,2]
xij[1,3] xij[1,4]
End