我正在测试PuLP优化库,以解决一个简单的问题。
我有一个矩阵 A 来定义问题的约束条件。 有了矩阵后,我想自动构建约束函数。上面是代码示例:
from pulp import LpProblem, LpMinimize, LpVariable, LpStatus, value, LpInteger
import numpy as np
# Not important. It only generates the matrix A
def schedule_gen_special(N, Na):
matrix = np.zeros((N,N))
for i in range(Na):
for j in range(N):
if(i < N):
matrix[i][j] = 1
i = i + 1
matrix = matrix[:, :N-Na+2]
return matrix
N = 6
Na = 4
A = schedule_gen_special(N, Na)
# Create the 'prob' variable to contain the problem data
prob = LpProblem("Distribution of shifts", LpMinimize)
# Defines the variables under optimization
x = []
x = [LpVariable("turno"+str(i), 0, None, LpInteger) for i in range(1,5)]
# Defines the objective function
prob2 += sum(x),'number of workers'
直到这里,一切都还好。在这一点上,我必须定义约束,标准的约束方式是:
# The five constraints are entered
prob2 += x[0] >= 1.0, "Primerahora"
prob2 += x[0] + x[1] >= 2.0, "Segundahora"
prob2 += x[0] + x[1] + x[2] >= 4.0, "Tercerahora"
prob2 += x[0] + x[1] + x[2] + x[3] >= 3.0, "Cuartahora"
prob2 += x[1] + x[2] + x[3] >= 2.0, "Quintahora"
prob2 += x[2] + x[3] >= 4.0, "Sextahora"
但是,矩阵 A 具有约束条件的信息:
array([[ 1., 0., 0., 0.],
[ 1., 1., 0., 0.],
[ 1., 1., 1., 0.],
[ 1., 1., 1., 1.],
[ 0., 1., 1., 1.],
[ 0., 0., 1., 1.]]),
其中第一行对应于第一个约束...等等。
是否可以仅考虑矩阵 A 来自动执行约束定义?
答案 0 :(得分:1)
for vec in A:
prob += lpSum(c*xi for c, xi in zip(vec,x))