我正在使用Gurobipy解决一个重新分区的整数线性规划,我想最小化目标函数中两个表达式的总和,每个表达式都涉及绝对值函数。
目标函数所需的变量和常数如下:
# Partisan lean (WLOG, lean to a party) of each precinct; binary variable l_i == 1 if the precinct leans towards a party, 0 otherwise
l = {(i):opt_model.addVar(vtype=gp.GRB.BINARY,
name="l_{0}".format(i))
for i in set_I}
# Decision variable for n precincts assigned to m districts; binary variable x_i_j == 1 means ith precinct assigned to jth district
x = {(i,j):opt_model.addVar(vtype=gp.GRB.BINARY,
name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# Population for each of n precincts; integer variable pp_i
pp ={(i):opt_model.addVar(vtype=gp.GRB.INTEGER,
lb=0,
name="pp_{0}".format(i))
for i in set_I}
# Target population
V = 9900
targ = math.floor(V // m)
# actual proportion of lean
actual_proportion = gp.quicksum(l[i] for i in set_I)/n
这是我的目标函数。
# Define the objective function
obj = gp.quicksum(
gp.quicksum(gp.abs_(pp[i] * x[i, j] - targ) for i in set_I) for j in set_J
) + gp.quicksum(
gp.quicksum(
gp.abs_(
l[i] * x[i, j] / gp.quicksum(x[i, j] for i in set_I) - actual_proportion
)
for i in set_I
)
for j in set_J
)
model.setObjective(obj, GRB.MINIMIZE)
然而,我遇到了错误TypeError: unsupported operand type(s) for +=: 'gurobipy.LinExpr' and 'GenExprAbs'
。我已经另外尝试了在目标函数中先在单独的行中声明要求和的两个单独的表达式,然后在第三行中声明变量obj
=两个表达式相加在一起。然而,我仍然面临着同样的错误。我怎么可能仍然包含绝对值函数而不出现错误呢?
1条答案
按热度按时间xlpyo6sf1#
您应该使用Model.addVars()来添加变量-这比定义自己的字典更简单。
绝对函数需要添加另一个辅助变量来捕获结果,如here所示。