Note
Go to the end to download the full example code.
Unit commitment¶
A power system made of thermal plants and of a hydro valley must meet an hourly electricity demand over a one day horizon, at the lowest cost. Each thermal plant has a minimum and a maximum power, a start-up cost, a minimum up time, a minimum down time and ramp limits; the hydro valley is a cascade of reservoirs connected by turbines, where the water turbined during an hour reaches the downstream reservoir at the end of that hour. Deciding which plants are running at each hour turns the problem into a mixed integer linear program.
This case is adapted from the notebook
Unit commitment
by Alice Lebrun, graduated from ENSTA Paris (class of 2024).
The NetCDF instance the notebook relies on was provided for an ENSTA Paris
student project and its provenance is not documented, so it is not shipped
with OpenTURNS; this example uses a synthetic instance generated in its
spirit: see the generate_unit_commitment_data.py script shipped with the
use case.
Notations¶
The horizon has hours, the fleet
thermal units, the
valley
reservoirs and
turbines. For the thermal unit
:
is the production cost (currency per MWh) and
the start-up cost;
and
are the minimum and maximum powers (MW);
and
are the minimum up and down times (hours);
and
are the maximum increase and decrease of power between two consecutive hours (MW).
For the hydro valley, is the inflow of the reservoir
(volume per hour),
its capacity,
the
capacity of the turbine
(volume per hour) and
its production coefficient (MW per unit of volume per hour). The turbine
takes its water from the reservoir
and releases it
into the reservoir
; the special value
denotes
the outlet of the valley, where the water is lost.
Finally
is the demand at hour
(MW).
Decision variables¶
: the thermal unit
is on at hour
;
: the thermal unit
starts at hour
;
for
: the power of the thermal unit
at hour
, and
the power delivered by the whole hydro valley at hour
;
: the volume of the reservoir
at hour
;
: the flow of the turbine
at hour
.
Objective¶
The hydro production is free, so only the thermal costs are minimized:
Constraints¶
The demand must be met at every hour, and the power of a unit is either zero when it is off or between its bounds when it is on:
A start-up is detected by comparing the state of the unit with the previous
hour, the state before the first hour being known:
The power cannot vary too fast, and a unit that has just been started (resp. stopped) must stay on (resp. off) long enough:
where is the initial power of the unit, so that a unit
started at the first hour is also constrained by its ramp-up limit.
In the valley, the volume of a reservoir increases with its inflow and with the water released by the upstream turbines, and decreases with the water it turbines itself:
the initial volumes being known, and the volumes and flows
are bounded by the capacities. The water released upstream during an hour
reaches the downstream reservoir at the end of that hour, so it cannot be
turbined there before the next hour: the outflow of a reservoir is capped by
the volume it holds at the beginning of the hour and by its own inflow,
The power delivered by the valley is the power of its turbines:
The resulting program has 14 856 unknowns, 9 600 of them binary, and 31 848 constraints; 110 730 coefficients of its constraint matrix are non-zero, i.e. 0.02%. This is why the sparse form matters.
import os
import struct
import numpy as np
import openturns as ot
import openturns.experimental as otexp
import openturns.viewer as otv
Load the data¶
The four CSV files hold the thermal fleet, the reservoirs, the turbines
and the demand. The gallery executes this file from its own directory
without defining __file__, while the test suite runs it as a script.
try:
here = os.path.dirname(os.path.abspath(__file__))
except NameError:
here = os.getcwd()
data_dir = os.path.join(here, "..", "..", "..", "usecases")
def load(name):
return np.array(ot.Sample.ImportFromCSVFile(os.path.join(data_dir, name), ","))
thermal = load("unit_commitment_thermal.csv")
reservoirs = load("unit_commitment_reservoirs.csv")
turbines = load("unit_commitment_turbines.csv")
demand = load("unit_commitment_demand.csv").ravel()
(p_min, p_max, cost, start_cost, min_up, min_down, p_init, ramp_up, ramp_down) = (
thermal.T
)
min_up = min_up.astype(int)
min_down = min_down.astype(int)
v_max, v_init, inflow = reservoirs.T
start_arc, end_arc, f_max, gamma = turbines.T
start_arc = start_arc.astype(int)
end_arc = end_arc.astype(int)
n_hours = len(demand)
n_units = thermal.shape[0]
n_res = reservoirs.shape[0]
n_tur = turbines.shape[0]
Index the unknowns¶
Once flattened the unknowns form a single vector, addressed through
shifted grids: U[t, i] is the index of ,
P[t, i]
the index of , and so on.
t_grid = np.arange(n_hours)[:, None]
i_grid = np.arange(n_units)[None, :]
U = (t_grid * n_units + i_grid).ravel()
S = n_hours * n_units + U
P = (2 * n_hours * n_units + t_grid * (n_units + 1) + np.arange(n_units + 1)).ravel()
V = (
2 * n_hours * n_units + n_hours * (n_units + 1) + t_grid * n_res + np.arange(n_res)
).ravel()
F = (
2 * n_hours * n_units
+ n_hours * (n_units + 1)
+ n_hours * n_res
+ t_grid * n_tur
+ np.arange(n_tur)
).ravel()
n_var = int(F[-1] + 1)
Bounds and variable types¶
The known initial state of the thermal units is handled with bounds rather than with constraints: a unit that is running before the first hour is on at that hour and produces its initial power.
binary = ot.OptimizationProblemImplementation.BINARY
lower = np.zeros(n_var)
upper = np.full(n_var, 1e30)
finite_upper = np.zeros(n_var, dtype=bool)
types = np.zeros(n_var, dtype=int)
cost_vector = np.zeros(n_var)
upper[U] = 1.0
upper[S] = 1.0
finite_upper[U] = True
finite_upper[S] = True
types[U] = binary
types[S] = binary
u_init = (p_init > 0.0).astype(float)
running = np.flatnonzero(p_init > 0.0)
lower[P[: n_units + 1][running]] = p_init[running]
upper[P[: n_units + 1][running]] = p_init[running]
finite_upper[P[: n_units + 1][running]] = True
lower[U[:n_units][running]] = 1.0
upper[V] = np.tile(v_max, n_hours)
finite_upper[V] = True
upper[F] = np.tile(f_max, n_hours)
finite_upper[F] = True
cost_vector[P] = np.tile(np.append(cost, 0.0), n_hours)
cost_vector[S] = np.tile(start_cost, n_hours)
Assemble the constraint matrix¶
Every constraint is a row of
. The rows are
accumulated as
(row, column, value) triplets and the matrix is built in
a single call: only the non-zero coefficients are ever stored, and no dense
matrix is ever allocated.
ROW, COL, VAL, LB, UB = [], [], [], [], []
INF = 1e30
def add_row(entries, low, high):
index = len(LB)
for column, value in entries:
ROW.append(index)
COL.append(int(column))
VAL.append(float(value))
LB.append(float(low))
UB.append(float(high))
for t in range(n_hours):
# demand, met by the thermal units and by the valley
add_row(
zip(P[t * (n_units + 1) : (t + 1) * (n_units + 1)], np.ones(n_units + 1)),
demand[t],
INF,
)
for i in range(n_units):
power = P[t * (n_units + 1) + i]
state = U[t * n_units + i]
# production bounds
add_row([(power, 1.0), (state, -p_min[i])], 0.0, INF)
add_row([(power, 1.0), (state, -p_max[i])], -INF, 0.0)
# start-up indicator
if t == 0:
add_row([(S[i], -1.0), (U[i], 1.0)], -INF, u_init[i])
else:
add_row(
[
(S[t * n_units + i], -1.0),
(state, 1.0),
(U[(t - 1) * n_units + i], -1.0),
],
-INF,
0.0,
)
# ramp limits, including the transition from the initial power at the
# first hour so that a unit started at the first hour cannot jump
# directly to a power above its ramp-up limit
if t == 0:
add_row([(power, 1.0)], -INF, p_init[i] + ramp_up[i])
add_row([(power, -1.0)], -INF, ramp_down[i] - p_init[i])
else:
add_row(
[(power, 1.0), (P[(t - 1) * (n_units + 1) + i], -1.0)], -INF, ramp_up[i]
)
add_row(
[(power, -1.0), (P[(t - 1) * (n_units + 1) + i], 1.0)],
-INF,
ramp_down[i],
)
for i in range(n_units):
# minimum up time: a start at hour k keeps the unit on for min_up hours,
# or until the horizon end when the window is truncated
for k in range(n_hours):
length = min(min_up[i], n_hours - k)
window = [(U[t * n_units + i], 1.0) for t in range(k, k + length)]
if k == 0:
add_row(window + [(U[i], -length)], -length * u_init[i], INF)
else:
add_row(
window
+ [(U[k * n_units + i], -length), (U[(k - 1) * n_units + i], length)],
0.0,
INF,
)
# minimum down time: a shutdown at hour k keeps the unit off for min_down
# hours, or until the horizon end when the window is truncated
for k in range(n_hours):
length = min(min_down[i], n_hours - k)
window = [(U[t * n_units + i], 1.0) for t in range(k, k + length)]
if k == 0:
add_row(window + [(U[i], -length)], -INF, length * (1.0 - u_init[i]))
else:
add_row(
window
+ [(U[k * n_units + i], -length), (U[(k - 1) * n_units + i], length)],
-INF,
length,
)
# hydro capacities
for t in range(n_hours):
for j in range(n_res):
add_row([(V[t * n_res + j], 1.0)], -INF, v_max[j])
for k in range(n_tur):
add_row([(F[t * n_tur + k], 1.0)], -INF, f_max[k])
# water balance, the volume of the first hour being the initial one plus the
# water entering and minus the water turbined during that hour
for t in range(n_hours):
for j in range(n_res):
entries = [(V[t * n_res + j], 1.0)]
balance = inflow[j] + (v_init[j] if t == 0 else 0.0)
if t > 0:
entries.append((V[(t - 1) * n_res + j], -1.0))
entries += [(F[t * n_tur + k], -1.0) for k in range(n_tur) if end_arc[k] == j]
entries += [(F[t * n_tur + k], 1.0) for k in range(n_tur) if start_arc[k] == j]
add_row(entries, balance, balance)
# the water released by the upstream turbines reaches the reservoir at the end
# of the hour, so it is not available to the turbines of that reservoir before
# the next hour: the outflow is capped by the volume at the beginning of the
# hour plus the reservoir's own inflow, not by the same hour upstream release
for t in range(n_hours):
for j in range(n_res):
entries = [(F[t * n_tur + k], 1.0) for k in range(n_tur) if start_arc[k] == j]
if not entries and t == 0:
continue
available = inflow[j] + (v_init[j] if t == 0 else 0.0)
if t > 0:
entries.append((V[(t - 1) * n_res + j], -1.0))
add_row(entries, -INF, available)
# conversion of the turbined water into power
for t in range(n_hours):
entries = [(P[t * (n_units + 1) + n_units], 1.0)]
entries += [(F[t * n_tur + k], -gamma[k]) for k in range(n_tur)]
add_row(entries, 0.0, 0.0)
A = otexp.SparseMatrix(len(LB), n_var, ot.Indices(ROW), ot.Indices(COL), ot.Point(VAL))
n_rows, n_cols, nnz = A.getNbRows(), A.getNbColumns(), A.getNbNonZeros()
print("unknowns : %d (%d binary)" % (n_var, int(types.sum())))
print("constraints : %d" % n_rows)
print(
"matrix : %d rows x %d columns, %d non-zeros (%.2f%%)"
% (n_rows, n_cols, nnz, 100.0 * nnz / (n_rows * n_cols))
)
unknowns : 14856 (9600 binary)
constraints : 34368
matrix : 34368 rows x 14856 columns, 125755 non-zeros (0.02%)
The size of the constraint matrix is what makes the sparse storage
decisive here. A dense matrix would hold coefficients, each on
8 bytes, although 99.99% of them are zero; the compressed sparse column
form stores the
values, their row indices and one column
pointer per column only. The indices are
UnsignedInteger, i.e.
unsigned long, whose width depends on the platform, so it is measured
instead of assumed.
scalar_width = struct.calcsize("d")
index_width = struct.calcsize("L")
dense_memory = n_rows * n_cols * scalar_width
sparse_memory = nnz * (scalar_width + index_width) + (n_cols + 1) * index_width
print("dense form : %.1f GiB" % (dense_memory / 2**30))
print(
"sparse form : %.1f MiB (%.0f times less)"
% (sparse_memory / 2**20, dense_memory / sparse_memory)
)
dense form : 3.8 GiB
sparse form : 2.0 MiB (1917 times less)
Solve the problem¶
The linear problem receives the sparse matrix directly, and the binary
variables are declared with setVariablesType()
so that HiGHS runs its mixed integer solver.
bounds = ot.Interval(
lower.tolist(), upper.tolist(), [True] * n_var, finite_upper.tolist()
)
constraint_bounds = ot.Interval(
LB, UB, [bound > -INF for bound in LB], [bound < INF for bound in UB]
)
problem = otexp.LinearProgrammingProblem(
cost_vector.tolist(), bounds, A, constraint_bounds
)
problem.setVariablesType(types.tolist())
algo = otexp.HiGHS(problem)
algo.run()
result = algo.getResult()
print("status : %s" % result.getStatusMessage())
print("total cost : %.1f" % result.getOptimalValue()[0])
status : Optimal
total cost : 22375139.8
Analyse the solution¶
The demand is met exactly. The thermal fleet covers most of it and the valley saves its water for the two peaks of the load curve.
x = np.array(result.getOptimalPoint())
u = x[U].reshape(n_hours, n_units)
p = x[P].reshape(n_hours, n_units + 1)
v = x[V].reshape(n_hours, n_res)
f = x[F].reshape(n_hours, n_tur)
thermal_power = p[:, :n_units].sum(axis=1)
hydro_power = p[:, n_units]
starts = np.diff(np.vstack([u_init, u]), axis=0) > 0.5
print("start-ups : %d" % int(starts.sum()))
print("thermal : %.0f MWh" % thermal_power.sum())
print(
"hydro : %.0f MWh (%.0f%% of the demand)"
% (hydro_power.sum(), 100.0 * hydro_power.sum() / demand.sum())
)
print("demand : %.0f MWh" % demand.sum())
start-ups : 77
thermal : 503731 MWh
hydro : 18107 MWh (3% of the demand)
demand : 521838 MWh
Two constraints are easy to violate silently, so the solution is checked against them: the first hour respects the ramp limits counted from the initial power, and no reservoir turbines more water than it holds at the beginning of the hour plus its own inflow, so that the water released upstream during an hour is only used at the next hour.
assert np.all(p[0, :n_units] - p_init <= ramp_up + 1e-4)
assert np.all(p_init - p[0, :n_units] <= ramp_down + 1e-4)
outflow = np.zeros((n_hours, n_res))
for k in range(n_tur):
outflow[:, start_arc[k]] += f[:, k]
available = np.vstack([v_init, v[:-1]]) + inflow
assert np.all(outflow <= available + 1e-4)
The next figure superimposes the demand, the total production, the thermal production and the hydro production: the total production matches the demand, the thermal fleet covers the base of the load curve and the valley follows its two peaks.
hours = np.arange(1, n_hours + 1)
graph = ot.Graph("Production mix", "Time (h)", "Power (MW)", True, "upper left")
demand_curve = ot.Curve(hours, demand, "Demand")
demand_curve.setColor("black")
demand_curve.setLineStyle("dashed")
total_curve = ot.Curve(hours, thermal_power + hydro_power, "Total production")
total_curve.setColor("darkgreen")
thermal_curve = ot.Curve(hours, thermal_power, "Thermal")
thermal_curve.setColor("red")
hydro_curve = ot.Curve(hours, hydro_power, "Hydro")
hydro_curve.setColor("blue")
for curve in [demand_curve, total_curve, thermal_curve, hydro_curve]:
graph.add(curve)
view = otv.View(graph)
The number of running units drops during the night, reaches a plateau during the day when the cheapest units are saturated, and peaks with the demand.
graph_units = ot.Graph(
"Running thermal units", "Time (h)", "Number of units", True, "upper left"
)
units_curve = ot.Curve(hours, u.sum(axis=1), "Running units")
units_curve.setColor("red")
graph_units.add(units_curve)
view = otv.View(graph_units)
The volumes show how the valley is managed: the two upstream reservoirs fill during the night and release their water from the morning to the evening, while the two lowest ones are emptied at the beginning of the day and refilled at its end.
graph_volume = ot.Graph("Reservoir volumes", "Time (h)", "Volume", True, "upper right")
for j in range(n_res):
graph_volume.add(ot.Curve(hours, v[:, j], "Reservoir %d" % j))
view = otv.View(graph_volume)
Finally the flows through the twelve turbines give the detailed operation of the valley.
graph_flow = ot.Graph("Turbine flows", "Time (h)", "Flow", True, "upper left")
for k in range(n_tur):
graph_flow.add(ot.Curve(hours, f[:, k], "Turbine %d" % k))
view = otv.View(graph_flow)
OpenTURNS