簡體   English   中英

在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)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM