Python에서 Google 또는 도구를 사용한 간단한 선형 프로그래밍

다른 게시물에서 나는 어떻게 해결할 수 있는지 보여주었습니다. Python에서 SciPy 및 PuLP와 같은 모듈을 사용하는 선형 최적화 문제. R에서 나는 또한 예를 들어 시연했습니다. lpSolve 패키지.

이 게시물에서는 Python의 ortools 모듈에서 Google의 GLOP 솔버를 사용하는 방법을 보여주고 싶습니다.

해결해야 할 문제는 다음과 같습니다.

Google의 GLOP 솔버로 문제를 해결할 수 있으려면 먼저 Python에 ortools 모듈을 설치해야합니다. ortools는 Python으로 된 Google의 OR 도구 모듈입니다.

ortools를 설치 한 후 Python의 ortools.linear_solver에서 pywraplp 하위 모듈을 가져옵니다.

from ortools.linear_solver import pywraplp

다음으로 솔버 인스턴스 (GLOP 솔버 사용)를 만들고 참조 핸들러에 대한 참조를 저장합니다.

solver = pywraplp.Solver.CreateSolver('linear_programming_examples', 'GLOP')

이제 관련 최적화 변수를 선언해야합니다. 이 예에서 최적화 변수는 x, y 및 z입니다.

# 하한이 0이고 상한이없는 변수 x 선언
x = solver.NumVar(0, solver.infinity(), "x")
# 하한이 0이고 상한이없는 변수 y 선언
y = solver.NumVar(0, solver.infinity(), "y")
# 하한이 0이고 상한이없는 변수 z 선언
z = solver.NumVar(0, solver.infinity(), "z")

위의 주석에서 설명했듯이 최적화 변수를 선언 할 때 하한과 상한을 지정해야합니다. 따라서 최적화 변수를 선언 한 후 솔버에서 이미 음이 아닌 제약 조건을 고려합니다.

최적화 변수를 선언 했으므로 이제 목적 함수를 선언 할 수 있습니다.

# 솔버에 목표 추가
objective = solver.Objective()
# 목적 함수가 그로부터 발생하도록 목적에 용어 추가
objective.SetCoefficient(x, 1)
objective.SetCoefficient(y, 2)
objective.SetCoefficient(z, 3)
# 문제를 최대화 문제로 선언
objective.SetMaximization()

목적 함수를 정의한 후 이제 솔버에 관련 제약 조건을 추가해야합니다.

# 제약 추가: 2x + y + z <= 20
constraint = solver.Constraint(-solver.infinity(), 20)
constraint.SetCoefficient(x, 2)
constraint.SetCoefficient(y, 1)
constraint.SetCoefficient(z, 1)
# 제약 추가: x + y + z <= 15
constraint = solver.Constraint(-solver.infinity(),15)
constraint.SetCoefficient(x, 1)
constraint.SetCoefficient(y, 1)
constraint.SetCoefficient(z, 1)
# 제약 추가: x - y - z >= 0 
constraint = solver.Constraint(0,solver.infinity())
constraint.SetCoefficient(x, 1)
constraint.SetCoefficient(y, -1)
constraint.SetCoefficient(z, -1)

이제 모델이 완성되었습니다.

문제 해결을 진행할 수 있습니다. 이것은 아래 코드 줄에서 수행됩니다.

solver.Solve()
0

x에 대한 최적의 솔루션은 다음과 같습니다.

print("x_opt: ", x.solution_value())
x_opt:  6.666666666666667

y에 대한 최적의 솔루션은 다음과 같습니다.

print("y_opt: ", y.solution_value())
y_opt:  0.0

z에 대한 최적의 솔루션은 다음과 같습니다.

print("z_opt: ", z.solution_value())
z_opt:  6.666666666666667

최적의 목적 함수 값은 다음과 같습니다.

print("optimal value: " + str(x.solution_value()+2*y.solution_value()+3*z.solution_value()))
optimal value: 26.666666666666668

You May Also Like

Leave a Reply

Leave a Reply

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.