파일:Karmarkar.svg

문서 내용이 다른 언어로는 지원되지 않습니다.
위키백과, 우리 모두의 백과사전.

원본 파일(SVG 파일, 실제 크기 720 × 540 픽셀, 파일 크기: 43 KB)

파일 설명

설명
English: Solution of example LP in Karmarkar's algorithm. Blue lines show the constraints, Red shows each iteration of the algorithm.
날짜
출처 자작
저자 Gjacquenot

라이선스

나는 아래 작품의 저작권자로서, 이 저작물을 다음과 같은 라이선스로 배포합니다:
w:ko:크리에이티브 커먼즈
저작자표시 동일조건변경허락
이용자는 다음의 권리를 갖습니다:
  • 공유 및 이용 – 저작물의 복제, 배포, 전시, 공연 및 공중송신
  • 재창작 – 저작물의 개작, 수정, 2차적저작물 창작
다음과 같은 조건을 따라야 합니다:
  • 저작자표시 – 적절한 저작자 표시를 제공하고, 라이센스에 대한 링크를 제공하고, 변경사항이 있는지를 표시해야 합니다. 당신은 합리적인 방식으로 표시할 수 있지만, 어떤 방식으로든 사용권 허가자가 당신 또는 당신의 사용을 지지하는 방식으로 표시할 수 없습니다.
  • 동일조건변경허락 – 만약 당신이 이 저작물을 리믹스 또는 변형하거나 이 저작물을 기반으로 제작하는 경우, 당신은 당신의 기여물을 원저작물과 동일하거나 호환 가능한 라이선스에 따라 배포하여야 합니다.

Source code (Python)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Python script to illustrate the convergence of Karmarkar's algorithm on
# a linear programming problem.
#
# http://en.wikipedia.org/wiki/Karmarkar%27s_algorithm
#
# Karmarkar's algorithm is an algorithm introduced by Narendra Karmarkar in 1984
# for solving linear programming problems. It was the first reasonably efficient
# algorithm that solves these problems in polynomial time.
#
# Karmarkar's algorithm falls within the class of interior point methods: the
# current guess for the solution does not follow the boundary of the feasible
# set as in the simplex method, but it moves through the interior of the feasible
# region, improving the approximation of the optimal solution by a definite
# fraction with every iteration, and converging to an optimal solution with
# rational data.
#
# Guillaume Jacquenot
# 2015-05-03
# CC-BY-SA

import numpy as np
import matplotlib
from matplotlib.pyplot import figure, show, rc, grid

class ProblemInstance():
    def __init__(self):
        n = 2
        m = 11
        self.A = np.zeros((m,n))
        self.B = np.zeros((m,1))
        self.C = np.array([[1],[1]])
        self.A[:,1] = 1
        for i in range(11):
            p = 0.1*i
            self.A[i,0] = 2.0*p
            self.B[i,0] = p*p + 1.0

class KarmarkarAlgorithm():
    def __init__(self,A,B,C):
        self.maxIterations = 100
        self.A = np.copy(A)
        self.B = np.copy(B)
        self.C = np.copy(C)
        self.n = len(C)
        self.m = len(B)
        self.AT = A.transpose()
        self.XT = None

    def isConvergeCriteronSatisfied(self, epsilon = 1e-8):
        if np.size(self.XT,1)<2:
            return False
        if np.linalg.norm(self.XT[:,-1]-self.XT[:,-2],2) < epsilon:
            return True

    def solve(self, X0=None):
        # No check is made for unbounded problem
        if X0 is None:
            X0 = np.zeros((self.n,1))
        k = 0
        X = np.copy(X0)
        self.XT = np.copy(X0)
        gamma = 0.5
        for _ in range(self.maxIterations):
            if self.isConvergeCriteronSatisfied():
                break
            V = self.B-np.dot(self.A,X)
            VM2 = np.linalg.matrix_power(np.diagflat(V),-2)
            hx = np.dot(np.linalg.matrix_power(np.dot(np.dot(self.AT,VM2),self.A),-1),self.C)
            hv = -np.dot(self.A,hx)
            coeff = np.infty
            for p in range(self.m):
                if hv[p,0]<0:
                    coeff = np.min((coeff,-V[p,0]/hv[p,0]))
            alpha = gamma * coeff
            X += alpha*hx
            self.XT = np.concatenate((self.XT,X),axis=1)

    def makePlot(self,outputFilename = r'Karmarkar.svg', xs=-0.05, xe=+1.05):
        rc('grid', linewidth = 1, linestyle = '-', color = '#a0a0a0')
        rc('xtick', labelsize = 15)
        rc('ytick', labelsize = 15)
        rc('font',**{'family':'serif','serif':['Palatino'],'size':15})
        rc('text', usetex=True)

        fig = figure()
        ax = fig.add_axes([0.12, 0.12, 0.76, 0.76])
        grid(True)
        ylimMin = -0.05
        ylimMax = +1.05
        xsOri = xs
        xeOri = xe
        for i in range(np.size(self.A,0)):
            xs = xsOri
            xe = xeOri
            a = -self.A[i,0]/self.A[i,1]
            b = +self.B[i,0]/self.A[i,1]
            ys = a*xs+b
            ye = a*xe+b
            if ys>ylimMax:
                ys = ylimMax
                xs = (ylimMax-b)/a
            if ye<ylimMin:
                ye = ylimMin
                xe = (ylimMin-b)/a
            ax.plot([xs,xe], [ys,ye], \
                    lw = 1, ls = '--', color = 'b')
        ax.set_xlim((xs,xe))
        ax.plot(self.XT[0,:], self.XT[1,:], \
                lw = 1, ls = '-', color = 'r', marker = '.')
        ax.plot(self.XT[0,-1], self.XT[1,-1], \
                lw = 1, ls = '-', color = 'r', marker = 'o')
        ax.set_xlim((ylimMin,ylimMax))
        ax.set_ylim((ylimMin,ylimMax))
        ax.set_aspect('equal')
        ax.set_xlabel('$x_1$',rotation = 0)
        ax.set_ylabel('$x_2$',rotation = 0)
        ax.set_title(r'$\max x_1+x_2\textrm{ s.t. }2px_1+x_2\le p^2+1\textrm{, }\forall p \in [0.0,0.1,...,1.0]$',
                     fontsize=15)
        fig.savefig(outputFilename)
        fig.show()

if __name__ == "__main__":
    p = ProblemInstance()
    k = KarmarkarAlgorithm(p.A,p.B,p.C)
    k.solve(X0 = np.zeros((2,1)))
    k.makePlot(outputFilename = r'Karmarkar.svg', xs=-0.05, xe=+1.05)

설명

이 파일이 나타내는 바에 대한 한 줄 설명을 추가합니다

이 파일에 묘사된 항목

다음을 묘사함

파일 역사

날짜/시간 링크를 클릭하면 해당 시간의 파일을 볼 수 있습니다.

날짜/시간섬네일크기사용자설명
현재2017년 11월 23일 (목) 00:342017년 11월 23일 (목) 00:34 판의 섬네일720 × 540 (43 KB)DutchCanadianThe right hand side for the constraints appears to be p<sup>2</sup>+1, rather than p<sup>2</sup>, going by both the plot and the code (note the line <tt>self.B[i,0] = p*p + 1.0</tt>). Updated the header line.
2015년 5월 4일 (월) 04:292015년 5월 4일 (월) 04:29 판의 섬네일720 × 540 (41 KB)GjacquenotUpdated constraint display
2015년 5월 4일 (월) 04:262015년 5월 4일 (월) 04:26 판의 섬네일720 × 540 (41 KB)GjacquenotUpdated constraint display
2015년 5월 4일 (월) 04:172015년 5월 4일 (월) 04:17 판의 섬네일720 × 540 (41 KB)GjacquenotUpdated constraint display
2015년 5월 4일 (월) 03:542015년 5월 4일 (월) 03:54 판의 섬네일720 × 540 (41 KB)GjacquenotUser created page with UploadWizard

다음 문서 1개가 이 파일을 사용하고 있습니다:

이 파일을 사용하고 있는 모든 위키의 문서 목록

다음 위키에서 이 파일을 사용하고 있습니다:

메타데이터