简体   繁体   English

如何使用 Python 在 Cplex 中制定线性规划问题

[英]How to formulate linear programming problem in Cplex using Python

I am trying to solve a linear programming problem using IBM's Cplex, while calling it from Python.我正在尝试使用 IBM 的 Cplex 解决线性规划问题,同时从 Python 调用它。

The problem is to minimize a+c,问题是最小化 a+c,

subject to the constraint that Ax'=m',受 Ax'=m' 的约束,

where x=[a,b,c]其中 x=[a,b,c]

A = [[20,0,0],[0,20,30]] A = [[20,0,0],[0,20,30]]

m = [20,30] m = [20,30]

with a,b,c between 0 and 1. a,b,c 介于 0 和 1 之间。

One correct solution to the problem is a=1, b=0, and c=1.该问题的一种正确解决方案是 a=1、b=0 和 c=1。 But Cplex gives solutions, a=1, b=1, and c=0.但是 Cplex 给出了解决方案,a=1、b=1 和 c=0。 There is an error in formulating the problem but I cannot figure out where.制定问题时有错误,但我不知道在哪里。 Code below下面的代码

import cplex
from cplex.exceptions import CplexError
import sys



my_obj      = [1.0, 0.0, 1.0]
my_ub       = [1.0] * len(my_obj)
my_lb       = [0.0] * len(my_obj)
my_colnames = ["a", "b", "c"]
my_rhs      = [20.0, 30.0]
my_rownames = ["c1", "c2"]
my_sense    = "E" * len(my_rownames)


def populatebynonzero(prob):
    prob.objective.set_sense(prob.objective.sense.minimize)

    prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)

    prob.variables.add(obj = my_obj, ub = my_ub, lb = my_lb ,names = my_colnames)


    rows = [0,1]
    cols = [0,1]
    vals = [20.0,30.0]

    prob.linear_constraints.set_coefficients(zip(rows, cols, vals))


def lpex1():
    try:
        my_prob = cplex.Cplex()
        handle = populatebynonzero(my_prob)
        my_prob.solve()
    except CplexError, exc:
        print exc
        return

    numrows = my_prob.linear_constraints.get_num()
    numcols = my_prob.variables.get_num()

    print
    # solution.get_status() returns an integer code
    print "Solution status = " , my_prob.solution.get_status(), ":",
    # the following line prints the corresponding string
    print my_prob.solution.status[my_prob.solution.get_status()]
    print "Solution value  = ", my_prob.solution.get_objective_value()
    slack = my_prob.solution.get_linear_slacks()
    pi    = my_prob.solution.get_dual_values()
    x     = my_prob.solution.get_values()
    dj    = my_prob.solution.get_reduced_costs()
    for i in range(numrows):
        print "Row %d:  Slack = %10f  Pi = %10f" % (i, slack[i], pi[i])
    for j in range(numcols):
        print "Column %d:  Value = %10f Reduced cost = %10f" % (j, x[j], dj[j])

    my_prob.write("lpex1.lp")




    print x, "SOLUTIONS"

lpex1()

There was an error in definition of rows and columns of the constraint, corrections below, works now约束的行和列的定义出错,下面更正,现在可以使用

rows = [0,1,1] 
cols = [0,1,2]
vals = [20.0,20.0,30.0]

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

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