使用Gurobi optimizer求解线性规划(LP)问题…
$$ max f(X) = 2x_1 + 3x_2 $$
s.t.
$$ x_1 + 2x_2 \leq 8 $$
$$ 4x_1 \leq 16 $$
$$ 4x_2 \leq 12 $$
$$ x_1, x_2 \geq 0 $$
1 | # Import lib |
Academic license - for non-commercial use only
Optimize a model with 3 rows, 2 columns and 4 nonzeros
Coefficient statistics:
Matrix range [1e+00, 4e+00]
Objective range [2e+00, 3e+00]
Bounds range [0e+00, 0e+00]
RHS range [8e+00, 2e+01]
Presolve removed 2 rows and 0 columns
Presolve time: 0.01s
Presolved: 1 rows, 2 columns, 2 nonzeros
Iteration Objective Primal Inf. Dual Inf. Time
0 1.6000000e+01 2.000000e+00 0.000000e+00 0s
1 1.4000000e+01 0.000000e+00 0.000000e+00 0s
Solved in 1 iterations and 0.02 seconds
Optimal objective 1.400000000e+01
=========================
==> objVal: 14.0
==> x1: <gurobi.Var x1 (value 4.0)> x2: <gurobi.Var x2 (value 2.0)>
$$ minf(X) = -3x_1 + x_2 + x_3 $$
s.t.
$$ x_1 - 2x_2 + x_3 \leq 11 $$
$$ -4x_1 + x_2 + 2x_3 \geq 3 $$
$$ -2x_1 + x_3 = 1 $$
$$ x_1, x_2, x_3 \geq 0 $$
Note:
- Add decision variables to a model in a loop.
- Build a linear expression by using
quicksum()
function.
1 | # Create model |
Optimize a model with 3 rows, 3 columns and 8 nonzeros
Coefficient statistics:
Matrix range [1e+00, 4e+00]
Objective range [1e+00, 3e+00]
Bounds range [0e+00, 0e+00]
RHS range [1e+00, 1e+01]
Presolve removed 3 rows and 3 columns
Presolve time: 0.01s
Presolve: All rows and columns removed
Iteration Objective Primal Inf. Dual Inf. Time
0 -2.0000000e+00 0.000000e+00 0.000000e+00 0s
Solved in 0 iterations and 0.01 seconds
Optimal objective -2.000000000e+00
=========================
==> Objective function: <gurobi.LinExpr: -3.0 x1 + x2 + x3>
==> ObjVal: -2.0
==> x1: <gurobi.Var x1 (value 4.0)> x2: <gurobi.Var x2 (value 1.0)> x3: <gurobi.Var x3 (value 9.0)>
$$ minf(X) = 2x_1 + 3x_2 + 5x_3 + 2x_4 + 3x_5 $$
s.t.
$$ x_1 + x_2 + 2x_3 + x_4 + 3x_5 \geq 4 $$
$$ 2x_1 - x_2 + 3x_3 + x_4 + x_5 \geq 3 $$
$$ x_1, x_2, x_3, x_4, x_5 \geq 0 $$
Note:
- Add decision variables to a model by using
Model.addVars()
function. - Build a linear expression by using
quicksum()
function.
1 | # Creatw model |
Optimize a model with 2 rows, 5 columns and 10 nonzeros
Coefficient statistics:
Matrix range [1e+00, 3e+00]
Objective range [2e+00, 5e+00]
Bounds range [0e+00, 0e+00]
RHS range [3e+00, 4e+00]
Presolve removed 0 rows and 1 columns
Presolve time: 0.01s
Presolved: 2 rows, 4 columns, 8 nonzeros
Iteration Objective Primal Inf. Dual Inf. Time
0 0.0000000e+00 1.750000e+00 0.000000e+00 0s
2 5.0000000e+00 0.000000e+00 0.000000e+00 0s
Solved in 2 iterations and 0.01 seconds
Optimal objective 5.000000000e+00
=========================
==> Objective function: <gurobi.LinExpr: 2.0 x1 + 3.0 x2 + 5.0 x3 + 2.0 x4 + 3.0 x5>
==> ObjVal: 5.0
==> ('x1', 1.0)
==> ('x2', 0.0)
==> ('x3', 0.0)
==> ('x4', 0.0)
==> ('x5', 1.0)