简体   繁体   English

在PuLP中自动加载约束

[英]Automatically load constraints in PuLP

I'm testing the PuLP optimization library, to solve in a simple problem. 我正在测试PuLP优化库,以解决一个简单的问题。

I have a matrix A that define the constraintments of the problem. 我有一个矩阵A ,它定义了问题的约束条件。 Once I have the matrix, I want to automatically build the constraint functions. 有了矩阵后,我想自动构建约束函数。 Above is an example of the code: 上面是代码示例:

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'

until here, everything is ok. 直到这里,一切都还好。 At this point, I have to define the constraintments, and the standard way of doing it is: 在这一点上,我必须定义约束,而实现约束的标准方法是:

# 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" 

However, the Matrix A have the information of the constraints: 但是,矩阵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.]]),

where the first line corresponds to the first constraint... and so on. 第一行对应于第一约束...,依此类推。

Is is possible to automatize the constraint definition by only consider the matrix A ? 仅考虑矩阵A是否可以使约束定义自动化?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM