POLab
2018/12/01
【回到首頁】
import pulp
from pulp import*
較不推薦使用,容易造成衝突,並降低可讀性與維護性 更詳盡的說明請參考這裡
-for迴圈
for i in <some list>:
<do something for each i here>
-if條件句
if <condition>:
<do something if condition is true here>
在建立一個數學規劃時,我們必須加入我們的決策變數、目標函數及限制式,以下是在設定這些變數及式子常用的函數內容介紹, 在pulp中設定目標函數及限制式還有其他不一樣的方式,更進一步的了解請參考pulp網站內的查詢
Problem = pulp.LpProblem(name_str, sense)
sense ∈ {pulp.LpMinimize,pulp.LpMaximize}
- E.g. Maximization problem
problem = pulp.LpProblem('Benefit',pulp.LpMaximize)
變數預設的範圍上限為正無限,下限為負無限,變數型態為連續變數(continuous)
Decision_Variable = pulp.LpVariable(name_str, lowbound, upbound, category)
category ∈ {Continuous, Integer, Binary}
E.g. x ∈ [0,∞]
X = pulp.LpVariable('VarX', 0, None, cat='Continuous')
problem+=linear_constraint, constraint_name_str
E.g. Cost: 2X1 - 3X2 ≤100
problem += 2*X1 – 3*X2 <= 100, 'Cost'
在pulp中,可以透過各種屬性來查詢或更改所建立數學規劃的內容,以下為常用的幾個屬性:
P.S. 更多屬性查詢,可點擊這裡
Attribute Name | Description |
---|---|
solve() | solve the problem |
model.solve()
Attribute Name | Description |
---|---|
status | The return status of the problem from the solver. |
string value | numerical value |
---|---|
"Optimal" | 1 |
"Not Solve" | 0 |
"Infeasible" | -1 |
"Unbounded" | -2 |
"Undefined" | -3 |
model.status
1
pulp.LpStatus[model.status]
'Optimal'
Attribute Name | Description |
---|---|
value(model.objective) | objective value for current solution |
total_cost = pulp.value(model.objective)
Attribute Name | Description |
---|---|
varValue | Value in the current solution |
variables.name | variable name |
for v in prob.variables():
print(v.name, "=", v.varValue)