.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_numerical_methods/optimization/plot_unit_commitment.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_numerical_methods_optimization_plot_unit_commitment.py: 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 :math:`T` hours, the fleet :math:`N` thermal units, the valley :math:`R` reservoirs and :math:`K` turbines. For the thermal unit :math:`i`: - :math:`c_i` is the production cost (currency per MWh) and :math:`c^s_i` the start-up cost; - :math:`p^{min}_i` and :math:`p^{max}_i` are the minimum and maximum powers (MW); - :math:`T^{up}_i` and :math:`T^{down}_i` are the minimum up and down times (hours); - :math:`\delta^{up}_i` and :math:`\delta^{down}_i` are the maximum increase and decrease of power between two consecutive hours (MW). For the hydro valley, :math:`a_j` is the inflow of the reservoir :math:`j` (volume per hour), :math:`v^{max}_j` its capacity, :math:`f^{max}_k` the capacity of the turbine :math:`k` (volume per hour) and :math:`\gamma_k` its production coefficient (MW per unit of volume per hour). The turbine :math:`k` takes its water from the reservoir :math:`b_k` and releases it into the reservoir :math:`e_k`; the special value :math:`e_k = R` denotes the outlet of the valley, where the water is lost. Finally :math:`d_t` is the demand at hour :math:`t` (MW). Decision variables ------------------ - :math:`u_{t,i}\in\{0,1\}`: the thermal unit :math:`i` is on at hour :math:`t`; - :math:`s_{t,i}\in\{0,1\}`: the thermal unit :math:`i` starts at hour :math:`t`; - :math:`p_{t,i}\geq 0` for :math:`i 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) .. GENERATED FROM PYTHON SOURCE LINES 242-249 Assemble the constraint matrix ------------------------------ Every constraint is a row of :math:`\\vect{lb} \\leq \\mat{A}\\vect{x} \\leq \\vect{ub}`. 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. .. GENERATED FROM PYTHON SOURCE LINES 249-383 .. code-block:: Python 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)) ) .. rst-class:: sphx-glr-script-out .. code-block:: none unknowns : 14856 (9600 binary) constraints : 34368 matrix : 34368 rows x 14856 columns, 125755 non-zeros (0.02%) .. GENERATED FROM PYTHON SOURCE LINES 384-391 The size of the constraint matrix is what makes the sparse storage decisive here. A dense matrix would hold :math:`m n` coefficients, each on 8 bytes, although 99.99% of them are zero; the compressed sparse column form stores the :math:`nnz` 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. .. GENERATED FROM PYTHON SOURCE LINES 391-401 .. code-block:: Python 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) ) .. rst-class:: sphx-glr-script-out .. code-block:: none dense form : 3.8 GiB sparse form : 2.0 MiB (1917 times less) .. GENERATED FROM PYTHON SOURCE LINES 402-407 Solve the problem ----------------- The linear problem receives the sparse matrix directly, and the binary variables are declared with :meth:`~openturns.OptimizationProblem.setVariablesType` so that HiGHS runs its mixed integer solver. .. GENERATED FROM PYTHON SOURCE LINES 407-423 .. code-block:: Python 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]) .. rst-class:: sphx-glr-script-out .. code-block:: none status : Optimal total cost : 22375139.8 .. GENERATED FROM PYTHON SOURCE LINES 424-428 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. .. GENERATED FROM PYTHON SOURCE LINES 428-444 .. code-block:: Python 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()) .. rst-class:: sphx-glr-script-out .. code-block:: none start-ups : 77 thermal : 503731 MWh hydro : 18107 MWh (3% of the demand) demand : 521838 MWh .. GENERATED FROM PYTHON SOURCE LINES 445-450 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. .. GENERATED FROM PYTHON SOURCE LINES 450-458 .. code-block:: Python 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) .. GENERATED FROM PYTHON SOURCE LINES 459-463 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. .. GENERATED FROM PYTHON SOURCE LINES 463-478 .. code-block:: Python 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) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_001.svg :alt: Production mix :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_001.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 479-482 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. .. GENERATED FROM PYTHON SOURCE LINES 482-490 .. code-block:: Python 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) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_002.svg :alt: Running thermal units :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_002.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 491-495 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. .. GENERATED FROM PYTHON SOURCE LINES 495-500 .. code-block:: Python 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) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_003.svg :alt: Reservoir volumes :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_003.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 501-503 Finally the flows through the twelve turbines give the detailed operation of the valley. .. GENERATED FROM PYTHON SOURCE LINES 503-507 .. code-block:: Python 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) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_004.svg :alt: Turbine flows :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_unit_commitment_004.svg :class: sphx-glr-single-img .. _sphx_glr_download_auto_numerical_methods_optimization_plot_unit_commitment.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_unit_commitment.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_unit_commitment.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_unit_commitment.zip `