coin-or / python-mip

Python-MIP: collection of Python tools for the modeling and solution of Mixed-Integer Linear programs
Eclipse Public License 2.0
518 stars 92 forks source link

Can't solve: finding the maximum value under the condition of equality constraints #186

Closed RoeeXu closed 3 years ago

RoeeXu commented 3 years ago

Describe the bug The python3.7 code show as below: version: mip == 1.13.0

from mip import Model, xsum, BINARY, INTEGER, CONTINUOUS, minimize, maximize
import numpy as np

def solve(C, Aub, Bub, Aeq, Beq):
    col = len(C)
    question = Model()
    x = [question.add_var('x({})'.format(j), var_type=INTEGER) for j in range(col)]
    for i in range(len(Aub)):
        question += xsum(Aub[i][j] * x[j] for j in range(col)) <= Bub[i]
    for i in range(len(Aeq)):
        question += xsum(Aeq[i][j] * x[j] for j in range(col)) == Beq[i]
    question.objective = maximize(xsum(C[i] * x[j] for j in range(col)))
    flag = question.optimize().value
    res = [int(x[i].x) for i in range(col)]
    if flag == 0:
        value = np.dot(C, res)
        return value, res
    else:
        return None, None

Aeq = [[1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0], [88, 0, 9, 0, 24, 0, 19, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 88, 0, 9, 0, 24, 0, 19, 0, 0, 0, 0, 0, 1, 0, 0], [22, 0, 26, 0, 3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 22, 0, 26, 0, 3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 1]]
Beq = [1, 2, 2, 1, 100, 80, 90, 70]
C = [110, 110, 35, 35, 27, 27, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0]
Aub = []
Bub = []
print(solve(C, Aub, Bub, Aeq, Beq))

The code result is:

(0, [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 1, 100, 80, 90, 70])

But we can find the best result is:

(258, [1, 0, 1, 1, 0, 2, 0, 1, 0, 0, 0, 0, 3, 4, 42, 33])

The result is not as expected ... Did I use it wrong? Thanks Reply

RoeeXu commented 3 years ago

Sorry, my fault. C[i] -> C[j], and it's right