L P
博客专区 > ludlows 的博客 > 博客详情
L P
ludlows 发表于3年前
L P
  • 发表于 3年前
  • 阅读 0
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

 

# solves *bounded* LPs of the form:
        # max cx
        # sub to: Ax <= b
from sympy import *
from itertools import combinations
        # enumerates all the vertices of {x | Ax <= b}
def enumeratevertices(A, b):
    m, n = A.rows, A.cols     
    for rowlist in combinations(range(m), n):
        Ap = A.extract(rowlist, range(n))
        bp = b.extract(rowlist, [0])
        if Ap.det() != 0:
            xp = Ap.LUsolve(bp)
            d = A * xp - b
            feasible = True
            for i in range(m):
                if d[i] > 0:
                    feasible = False
            if feasible:
                yield xp       
        # finds the optimum using vertex enumeration
def findoptimum(A, b, c):
    m, n = A.rows, A.cols
    bestvalue, bestvertex = None, None
    for vertex in enumeratevertices(A, b):
        if bestvalue is None or (vertex.T*c)[0] > bestvalue:
            bestvalue = (vertex.T * c)[0]
            bestvertex = vertex
    return bestvertex
def solve(A, b, c):
    x = findoptimum(A, b, c)
    if not x:
        print 'LP is infeasible'
    else:
        print 'Vertex', x.T, 'is optimal'
        print 'Optimal value is', c.T*x
if __name__ == '__main__':
    A = Matrix([[-10,  -6, -9, -10],
                [  8,  -6, -5,  -5],
                [ -7,  -1, -9,   3],
                [ -1,  -4,  5,  10],
                [  1,   2,  0,  10],
                [  2,  -9,  3,  -8],
                [ -8,  -1, -8,   1],
                [  7, -10,  4,  -4],
                [-10,   2,  5,   8],
                [ -7,   9,  4,  -4],
                [ -1,   0,  0,   0],
                [  0,  -1,  0,   0],
                [  0,   0, -1,   0],
                [  0,   0,  0,  -1]])
    b = Matrix([9, 7, 3, 4, 8, 0, 3, 2, 4, 8, 0, 0, 0, 0])
    c = Matrix([2, -2, -3, 8])
    solve(A, b, c)

共有 人打赏支持
粉丝 0
博文 15
码字总数 4195
×
ludlows
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: