【Python代碼】混合整數規划MIP/線性規划LP+python(ortool庫)實現


相關知識點

LP線性規划問題

  • Linear Problem
  • [百度百科]:研究線性約束條件下線性目標函數的極值問題的數學理論和方法。
    學過運籌學的小伙伴,可以看這個LP問題的標准型來回顧一下:
    在這里插入圖片描述
    不太熟悉的朋友可以看這個例題,再結合上面的標准型,來感受一下:
    在這里插入圖片描述

MIP混合整數規划

  • Mixed Integar Planing
  • 混合整數規划是LP的一種,決策變量部分是整數,不要求全部都是整數的規划問題。
  • 這里MIP的求解器是使用CBC(Corn-or Branch and Cut)
  • CBC (COIN-OR Branch and Cut) is an open-source mixed integer programming solver working with the COIN-OR LP solver CLP and the COIN-OR Cut generator library Cgl. The code has been written primarily by John J. Forrest. 更多詳情看這里,但是筆者認為沒啥必要。

MIP的Python實現(Ortool庫)

我們來看一道簡單的例題:
在這里插入圖片描述
其中x,y都是整數

from ortools.linear_solver import pywraplp
# 首先,調用CBC求解器
# 整數規划使用pywraplp.Solver.GLOP_LINEAR_PROGRAMMING
solver = pywraplp.Solver('SolveIntegerProblem',
	pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
	
# 定義x和y的定義域,這里是從0到正無窮
x = solver.IntVar(0.0, solver.infinity(), 'x')
y = solver.IntVar(0.0, solver.infinity(), 'y')
# 添加約束:x+7y<17.5
constraint1 = solver.Constraint(-solver.infinity(), 17.5)
constraint1.SetCoefficient(x, 1)
constraint1.SetCoefficient(y, 7)
# 添加約束:x <= 3.5
constraint2 = solver.Constraint(-solver.infinity(), 3.5)
constraint2.SetCoefficient(x, 1)
constraint2.SetCoefficient(y, 0)
# 定義目標函數: Maximize x + 10 * y
bjective = solver.Objective()
objective.SetCoefficient(x, 1)
objective.SetCoefficient(y, 10)
objective.SetMaximization()
# 獲取問題的答案
result_status = solver.Solve()
# 判斷結果是否是最優解
assert result_status == pywraplp.Solver.OPTIMAL
# 驗證一下結果是否正確,這一步不是必要但是推薦加上
assert solver.VerifySolution(1e-7, True)
# 輸出結果
print('Number of variables =', solver.NumVariables())
print('Number of constraints =', solver.NumConstraints())
print('Optimal objective value = %d' % solver.Objective().Value())
variable_list = [x, y]
for variable in variable_list:
    print('%s = %d' % (variable.name(), variable.solution_value()))

可以看一下自己運行的結果:
在這里插入圖片描述

assert

這里涉及python 的一個assert的語法,不懂得可以簡單看一下:
Python assert(斷言)用於判斷一個表達式,在表達式條件為 false 的時候觸發異常。
斷言可以在條件不滿足程序運行的情況下直接返回錯誤,而不必等待程序運行后出現崩潰的情況,

在這里插入圖片描述

MIP的Python實現(docplex庫)

混合整數規划MIP/線性規划LP+python(docplex庫)實現 附代碼

參考:
1.assert
2.ortools


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM