python笔记:Gurobipy

1 介绍

Gurobi优化器是一个数学优化软件库,用于解决混合整数线性和二次优化问题。

2 简单举例

假设我们要解决这样的一个线性规划问题:

python笔记:Gurobipy_第1张图片

 我们可以使用gurobipy

2.1 大致流程

2.1.1 导入库

#导入库
import gurobipy as gp

2.1.2  创建模型

#创建新模型
m = gp.Model()

2.1.3 创建变量

x = m.addVar(vtype='B', name="x")
y = m.addVar(vtype='B', name="y")
z = m.addVar(vtype='B', name="z")

2.1.4 设置目标函数

# Set objective function
m.setObjective(x + y + 2 * z, gp.GRB.MAXIMIZE)

2.1.5 添加限制条件

# Add constraints
m.addConstr(x + 2 * y + 3 * z <= 4)
m.addConstr(x + y >= 1)

2.1.6 解决之

# Solve it!
m.optimize()

'''
Gurobi Optimizer version 9.5.0 build v9.5.0rc5 (win64)
Thread count: 6 physical cores, 12 logical processors, using up to 12 threads
Optimize a model with 2 rows, 3 columns and 5 nonzeros
Model fingerprint: 0x98886187
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.01 seconds (0.00 work units)
Thread count was 1 (of 12 available processors)

Solution count 2: 3 2 

Optimal solution found (tolerance 1.00e-04)
Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0000%
'''

2.1.7 查看最优解&各参数

print(f"Optimal objective value: {m.objVal}")
print(f"Solution values: x={x.X}, y={y.X}, z={z.X}")
'''
Optimal objective value: 3.0
Solution values: x=1.0, y=0.0, z=1.0
'''

你可能感兴趣的:(python库整理,python,开发语言,后端)