MIP example-1

4777 ワード

前の位置にインストールされているGurobipyを使用して、次の質問に答えます.
Problem
Maximize
x + y + 2z
Subject to
x + 2y + 3z <= 4
x + y >= 1
x, y, z binary
Solution
トラブルシューティング用のPythonコードを次に示します
import gurobipy as gp
from gurobipy import GRB

# 모델 선언
model = gp.Model("MIP")

# 변수 선언
# 제약식에 binary 조건이 있으므로 type을 binary로 설정
x = model.addVar(vtype=GRB.BINARY, name="x")
y = model.addVar(vtype=GRB.BINARY, name="y")
z = model.addVar(vtype=GRB.BINARY, name="z")

# 목적식 세팅
model.setObjective(x + y + 2 * z, GRB.MAXIMIZE)


# 제약식 세팅
model.addConstr(x + 2 * y + 3 * z <= 4, "c0")
model.addConstr(x + y >= 1, "c1")

# 최적화
model.optimize()
実行時に以下の出力結果が得られます.
Gurobi Optimizer version 9.0.3 build v9.0.3rc0 (linux64)
Optimize a model with 2 rows, 3 columns and 5 nonzeros
Model fingerprint: 0xf43f5bdf
Variable types: 0 continuous, 3 integer (3 binary)
Coefficient statistics:
Matrix range [1e+00, 3e+00]
Objective range [1e+00, 2e+00]
Bounds range [1e+00, 1e+00]
RHS range [1e+00, 4e+00]
Found heuristic solution: objective 2.0000000
Presolve removed 2 rows and 3 columns
Presolve time: 0.00s
Presolve: All rows and columns removed
Explored 0 nodes (0 simplex iterations) in 0.00 seconds
Thread count was 1 (of 8 available processors)
Solution count 2: 3
Optimal solution found (tolerance 1.00e-04)
Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0000%
変数と年に近づきたいなら、次のようにします.
# 해
print(model.objVal)
for v in model.getVars():
    print(v.varName, v.x)
3.0
x 1.0
y 0.0
z 1.0
Reference
mip1.py