如何用Python在Cplex中表示线性规划问题

如何用Python在Cplex中表示线性规划问题,python,linear-programming,cplex,Python,Linear Programming,Cplex,我试图使用IBM的Cplex解决一个线性编程问题,同时从Python调用它 问题是最小化a+c 受Ax'=m'的约束 其中x=[a,b,c] A=[[20,0,0],[0,20,30]] m=[20,30] a,b,c在0和1之间 该问题的一个正确解决方案是a=1、b=0和c=1。但是Cplex给出了解决方案,a=1,b=1,c=0。这个问题的表述有错误,但我不知道在哪里。代码如下 import cplex from cplex.exceptions import CplexError impo

我试图使用IBM的Cplex解决一个线性编程问题,同时从Python调用它

问题是最小化a+c

受Ax'=m'的约束

其中x=[a,b,c]

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

m=[20,30]

a,b,c在0和1之间

该问题的一个正确解决方案是a=1、b=0和c=1。但是Cplex给出了解决方案,a=1,b=1,c=0。这个问题的表述有错误,但我不知道在哪里。代码如下

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

约束的行和列的定义有错误,下面的更正现在起作用

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