在 PuLP 中自动加载约束

Automatically load constraints in PuLP

我正在测试 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 来自动化约束定义?

 for vec in A:
     prob += lpSum(c*xi for c, xi in zip(vec,x))