我想建立一个谷歌或工具模型使用linear_solver
的CBC_MIXED_INTEGER_PROGRAMMING
。 继谷歌教程中我学会了热建的约束,但我有一个问题... 是有必要手工编写每一个约束? 我的意思是,我有以下的数据帧df_constraint
含有以下形式的约束系数ax+by<=c
。
+---+---+---+
| A | B | C |
+---+---+---+
| 1 | 5 | 7 |
| 2 | 9 | 3 |
| 3 | 0 | 4 |
+---+---+---+
该表可以转化成以下约束上
# 1x+5y<=7
constraint1 = solver.Constraint(-solver.infinity(), 7)
constraint1.SetCoefficient(x, 1)
constraint1.SetCoefficient(y, 5)
# 2x+9y<=3
constraint2 = solver.Constraint(-solver.infinity(), 3)
constraint2.SetCoefficient(x, 2)
constraint2.SetCoefficient(y, 9)
# 3x<=4
constraint3 = solver.Constraint(-solver.infinity(), 4)
constraint3.SetCoefficient(x, 3)
而不是每行写的,我想是这样的:
for index, row in df.iterrows():
constraint = solver.Constraint(-solver.infinity(), row['C'])
constraint.SetCoefficient(x, row['A'])
constraint.SetCoefficient(y, row['B'])
我的片断将无法正常工作,因为每个约束必须有一个不同的名称(如constraint1
, constraint2
,...)。
这样做,解决您的问题?
df_constraints = pd.DataFrame({
'A': pd.Series([1, 2, 3]),
'B': pd.Series([5, 9, 0]),
'C': pd.Series([7, 3, 4]),
})
for row in df_constraints.itertuples():
#print("row {}".format(row))
#print("A {}".format(row[0]))
#print("B {}".format(row[1]))
#print("C {}".format(row[2]))
constraint = solver.Constraint(-solver.infinity(), row[2])
constraint.SetCoefficient(x, row[0])
constraint.SetCoefficient(y, row[1])
事实上,OR-工具并不要求每个约束有一个唯一的名称。 但无论如何下面给他们唯一的名称。 正如上面提到的,如果你需要存储的限制,可以在阵列中做到如下。 在这里,我采用了比较常见的符号(A为约束系数,B是约束右手边,C是客观系数)。 但它会适应你的熊猫设置。
from ortools.linear_solver import pywraplp # adapted from one of the examples
inf = float("inf")
AB = [
[1, 0, 1], # x <= 1
[0, 1, 2], # y <= 2
[1, 1, 2], # x + y <= 2
[-1, -1, 0] # x + y >= 0
]
c = [3, 1]
def main():
solver = pywraplp.Solver('simple_lp_program',
pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)
x = solver.NumVar(-inf, inf, 'x') # no UB or LB on x, y
y = solver.NumVar(-inf, inf, 'y')
cts = []
for i, (*a, b) in enumerate(AB):
ct = solver.Constraint(-inf, b, 'ct' + str(i))
ct.SetCoefficient(x, a[0])
ct.SetCoefficient(y, a[1])
cts.append(ct)
print('Number of constraints =', solver.NumConstraints())
objective = solver.Objective()
objective.SetCoefficient(x, c[0])
objective.SetCoefficient(y, c[1])
objective.SetMaximization()
solver.Solve()
print('Solution:')
print('Objective value =', objective.Value())
print('x =', x.solution_value())
print('y =', y.solution_value())
if __name__ == '__main__':
main()