Linear Programming Mini Example#
Linear programming (linear optimization) is a mathematical technique that uses a set of linear equations to find the optimal solution to a problem. It’s an effective type of mathematical programming that’s used to solve complex real-world problems, e.g. in energy systems.
1. Load packages
We are using the gurobipy package to formulate a mathematical model and solve it.
import gurobipy as gp
from gurobipy import GRB
import numpy as np
2. Define parameters
G: Number of generators 2
\(\overline{P}_i\): Production limit [6,4] in MW
\(c_i\): Cost [0.015,0.03] in $/kWh
D: Load demand 8 in MW
n_generators = 2 # G
p_lim = np.array([6,4]) # MW
cost = np.array([0.015,0.03]) # $/kWh
D = 8 # MW
3. Define mathematical model
Objective function:
Minimize the sum cost \(c_i\), which depends on the production \(p_i\) amount of each generator i.
Decision variables:
\(p_i\) output of generator i.
Constraints:
The sum of generation \(p_i\) for each generator i needs to equal the load D.
The output of each generator \(p_i\) has to greater equal to \(0\) and cannot exceed \(\overline{P}_i\).
# Create model object
m = gp.Model()
m.setParam("OutputFlag", 0)
# Create the variables
p = m.addVars(n_generators, lb=0, ub=GRB.INFINITY, name="p")
# Add constraints:
# Total production
m.addConstr(p.sum() == D)
# Generator limits
for i in range(n_generators):
m.addConstr(p[i] <= p_lim[i])
# Add objective
m.setObjective(sum(p[i]*cost[i]*1000 for i in range(n_generators)), GRB.MINIMIZE)
# Solve
m.optimize()
Set parameter Username
Academic license - for non-commercial use only - expires 2025-11-15
4. Inspect the solution
# Check the status of the solver
status = m.Status
if status == GRB.OPTIMAL:
print("The model is optimal.")
elif status == GRB.INFEASIBLE:
print("The model is infeasible.")
elif status == GRB.UNBOUNDED:
print("The model is unbounded.")
else:
print(f"Optimization ended with status {status}.")
print()
# Objective value
objective = m.ObjVal
print(f"Objective value {objective:.1f}.\n")
print("Variables values:")
# Print the values of all variables
for v in m.getVars():
print(f"{v.VarName} = {v.X}")
The model is optimal.
Objective value 150.0.
Variables values:
p[0] = 6.0
p[1] = 2.0