nunodsousa
nunodsousa

Reputation: 2805

Automatically load constraints in PuLP

I'm testing the PuLP optimization library, to solve in a simple problem.

I have a matrix A that define the constraintments of the problem. 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:

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?

Upvotes: 0

Views: 366

Answers (1)

Stuart Mitchell
Stuart Mitchell

Reputation: 1059

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

Upvotes: 2

Related Questions