Note
You can download this example as a Jupyter notebook or try it out directly in Google Colab.
10. Introduction to Demand-Side Agents and Flexibility in the ASSUME Framework#
This tutorial introduces demand-side agents and shows how a steel plant can participate in a day-ahead electricity market. It also uses a simplified two-node network to illustrate power flows and redispatch.
The steel plant combines an electrolyser, a direct reduced iron (DRI) plant and an electric arc furnace (EAF). Its modeled consumption depends on its production target, technology parameters, forecasts and flexibility settings.
The tutorial covers three use cases:
Use Case 1: Submit the steel plant’s baseline optimized demand to the day-ahead market.
Use Case 2: Submit its flexible optimized demand and compare the results with Use Case 1.
Use Case 3: Run a redispatch example with power plants and demand units, including the steel plant as a fixed load.
The input profiles, plant fleet and two-node network are illustrative. They are not a calibrated representation of an actual electricity system or historical market period.
Demand-side management adjusts electricity consumption in response to signals such as prices or network needs. An industrial plant can provide flexibility by moving some consumption between hours while still meeting its production requirements. In ASSUME, demand-side agents participate in markets through bidding strategies and model their operational limits and technology components.
Setting Up the ASSUME Framework#
Before diving into DSA and Flexibility, ensure that you have the ASSUME framework installed and set up correctly. If you haven’t done so already, follow the steps below to install the ASSUME core package.
If working in colab, we will install the necessary packages to run the ASSUME framework along with other dependencies. The process is similar to the other tutorials on ASSUME.
The following commands will install ASSUME and its network dependencies, along with additional libraries such as Plotly for visualization.
Local users may skip this step if you have the current development state installed and input files are therefore available in the project directory. Make sure to have plotly, cartopy and seaborn installed.
[ ]:
import importlib.util
import os
from pathlib import Path
# Check whether notebook is run in google colab
IN_COLAB = importlib.util.find_spec("google.colab") is not None
if IN_COLAB or os.getenv("GITHUB_ACTIONS"):
# Install the ASSUME framework with the PyPSA library for network optimization
# Colab currently has issues with pyomo version 6.8.2, causing the notebook to crash
# Installing an older version resolves this issue. This should only be considered a temporary fix.
!git clone --depth=1 https://github.com/assume-framework/assume.git assume-repo
!pip install ./assume-repo[network] pyomo==6.8.0
# Install some additional packages for plotting
!pip install plotly cartopy seaborn "requests>=2.32.2"
Let’s also import some basic libraries that we will use throughout the tutorial.
[ ]:
import os
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import pyomo as pyo
import pypsa
import seaborn as sns
import yaml
# Function to display DataFrame in Jupyter
from IPython.display import display
3. Modeling Demand-Side Agents (DSAs) and Flexibility#
The Steel Plant is an example of an industrial demand-side agent in the ASSUME framework. This agent has specific characteristics such as rated power, flexibility, and the ability to adjust its electricity consumption based on price signals. We will now explore how to define the Steel Plant in the framework.
Let’s first import the necessary classes and functions from the ASSUME framework to create the Steel Plant agent.
[ ]:
from assume import World
from assume.common.base import (
MarketConfig,
Orderbook,
Product,
SupportsMinMax,
)
from assume.common.utils import set_random_seed
from assume.scenario.loader_csv import load_scenario_folder
from assume.units.dsm_load_shift import DSMFlex
# Set random seed for reproducibility
set_random_seed(42)
3.1 Creating a Steel Plant as a Demand-Side Agent#
The Steel Plant is an industrial agent that consists of several key components (e.g., DRI plant, electrolyser, EAF, etc.). These components consume electricity and can be modeled to react dynamically to market conditions.
In the ASSUME framework, the steel plant agent is created by defining its characteristics, components, and objectives. Let’s start by defining the Steel Plant with its core characteristics:
[ ]:
class SteelPlant(SupportsMinMax, DSMFlex):
"""
Class to define the Steel Plant as a demand-side agent in the ASSUME framework.
"""
def __init__(
self,
id: str,
unit_operator: str,
bidding_strategies: dict,
technology: str = "steel_plant",
node: str = "node0",
index: pd.DatetimeIndex = None,
location: tuple[float, float] = (0.0, 0.0),
components: dict[str, dict] = None,
objective: str = None,
flexibility_measure: str = "cost_based_load_shift",
demand: float = 0,
cost_tolerance: float = 10,
**kwargs,
):
super().__init__(
id=id,
unit_operator=unit_operator,
technology=technology,
bidding_strategies=bidding_strategies,
index=index,
node=node,
location=location,
**kwargs,
)
Key characteristics include the unit identifier, operator, bidding strategies, technology and grid node. The flexibility_measure and cost_tolerance select and parameterize the flexibility calculation; demand is the plant’s production target.
The main attributes are:
ididentifies the unit andunit_operatoridentifies its operator.bidding_strategiesmaps markets to the strategies used to submit orders.technologyidentifies the type of industrial unit;nodeidentifies its grid connection.componentsdescribes the technologies in the production process.flexibility_measureselects the flexibility formulation, andcost_tolerancecontrols its permitted additional cost.demandspecifies the production target; it is not an hourly electricity demand profile.
Bringing ``dst_components`` into the Steel Plant Process
In the steel plant, we use components like the electrolyser and hydrogen storage to model the production and storage of hydrogen, which plays a critical role in decarbonized steel production. These components are imported from dst_components.py and integrated into the plant’s process.
In this section, we will showcase how to model these components, define their characteristics, and integrate them into the overall process of the steel plant.
1. Electrolyser
The electrolyser produces hydrogen through electrolysis, using electricity as the input. The electrolyser’s constraints ensure that it operates within its rated power capacity, follows ramp rates for power changes, and has operational limits like minimum operating time and efficiency.
We will use the create_electrolyser function from dst_components.py to add the electrolyser to the steel plant’s Pyomo model.
2. Hydrogen Storage
The hydrogen storage component is used to store hydrogen produced by the electrolyser. It helps manage the supply and ensures that hydrogen is available when needed. The hydrogen storage has parameters like maximum capacity, storage loss rate, and charge/discharge rates.
We will use the create_hydrogen_storage function from dst_components.py to integrate hydrogen storage into the model.
3.2 Modeling Components in the ASSUME Framework#
In the ASSUME framework, components like the electrolyser and hydrogen storage are modeled using Pyomo, a Python-based optimization modeling tool. The framework supports detailed modeling of each component by specifying their characteristics and operational constraints.
For each component, attributes such as rated power, ramp rates, and efficiency are defined. These attributes are essential for simulating the component’s behavior in the energy system.
Example: Electrolyser Model The electrolyser is a crucial component in hydrogen production. In this framework, the electrolyser is modeled with various characteristics, including power limits, operational efficiency, and ramp rates. These attributes ensure that the electrolyser operates within its technical and economic boundaries.
Here’s how we define the electrolyser’s model:
[ ]:
def create_electrolyser(
model,
max_power,
min_power,
ramp_up,
ramp_down,
min_operating_time,
min_down_time,
efficiency,
time_steps,
**kwargs,
):
"""
Creates the electrolyser component in the Pyomo model with defined characteristics.
"""
# Define a Pyomo Block for the electrolyser component
model_part = pyo.Block()
# Define the attributes of the electrolyser component
model_part.max_power = pyo.Param(initialize=max_power)
model_part.min_power = pyo.Param(initialize=min_power)
model_part.ramp_up = pyo.Param(initialize=ramp_up)
model_part.ramp_down = pyo.Param(initialize=ramp_down)
model_part.efficiency = pyo.Param(initialize=efficiency)
# Define the Pyomo variables for operational behavior
model_part.power = pyo.Var(time_steps, bounds=(0, max_power))
model_part.hydrogen_out = pyo.Var(time_steps, domain=pyo.NonNegativeReals)
# Define the Pyomo constraints
@model.Constraint(time_steps)
def min_operating_time_constraint(m, t):
"""
Ensures that the electrolyser operates at or above its minimum power.
"""
return model_part.power[t] >= model_part.min_power
@model.Constraint(time_steps)
def ramp_rate_constraints(m, t):
"""
Ensures that the electrolyser respects the ramp up and ramp down constraints.
"""
if t > 0:
return (
model_part.power[t] - model_part.power[t - 1] <= model_part.ramp_up,
model_part.power[t - 1] - model_part.power[t] <= model_part.ramp_down,
)
# Define hydrogen output based on the efficiency
@model.Constraint(time_steps)
def hydrogen_production_constraint(m, t):
"""
Ensures that hydrogen output is proportional to the power input based on efficiency.
"""
return model_part.hydrogen_out[t] == model_part.power[t] * model_part.efficiency
3.3. Initializing the Components and Process Sequence of the Steel Plant#
The steel plant consists of multiple components, such as the DRI plant, electrolyser, Electric Arc Furnace (EAF), and hydrogen storage. These components are initialized and connected into a process sequence to define how the steel plant operates.
Mapping of Component Type Identifiers to Their Respective Classes
Before initializing the components and process sequences, the steel plant needs to map the component types to their respective functions. This is done using the following dictionary, which links the component type identifiers (e.g., "electrolyser", "eaf") to the respective creation functions in the dst_components.py file:
[ ]:
from assume.units import demand_side_technologies
print(demand_side_technologies)
# you can also create your own DST component class and add it to the world like follows
# world = World()
# world.dst_components["YourComponent"] = YourComponent
The
def initialize_components(components)function calls the Pyomo models of the respective components.The
def initialize_process_sequence()function handles the connection of the entire process, ensuring that the plant operates in a defined sequence.
To initialize the components of the steel plant, we use the initialize_components() function. This function iterates through the list of components, calls the corresponding factory method for each component (as mapped in dst_components), and transfers the necessary attributes to the Pyomo model.
[ ]:
# Initialize components of the steel plant
def initialize_components(self, components: dict[str, dict]):
"""
Initializes the components of the steel plant.
Args:
components (dict[str, dict]): The components of the steel plant.
model (pyomo.ConcreteModel): The Pyomo model.
"""
self.model.dsm_blocks = pyo.Block(list(components.keys()))
for technology, component_data in components.items():
if technology in demand_side_technologies:
factory_method = demand_side_technologies[technology]
self.model.dsm_blocks[technology].transfer_attributes_from(
factory_method(
self.model, time_steps=self.model.time_steps, **component_data
)
)
In this function:
The
componentsargument is a dictionary where the keys are the component types (e.g.,"electrolyser","eaf") and the values are dictionaries of component-specific parameters.For each component, the factory method corresponding to the component type is called (e.g.,
create_electrolyserfor an electrolyser).The attributes of the initialized component are then transferred to the Pyomo model using the
transfer_attributes_from()function.
3.4 Initializing the Process Sequence for the Steel Plant#
The initialize_process_sequence() function is responsible for defining how the different components of the steel plant are connected to form a complete process. This function ensures that the flow of materials (such as hydrogen and direct reduced iron (DRI)) between components, such as the electrolyser, hydrogen storage, DRI plant, and Electric Arc Furnace (EAF), is properly constrained.
[ ]:
# Initialize components of the steel plant
def initialize_process_sequence(self):
"""
Initializes the process sequence and constraints for the steel plant. Here, the components/ technologies are connected to establish a process for steel production
"""
# Assuming the presence of 'hydrogen_storage' indicates the desire for dynamic flow management
has_h2storage = "hydrogen_storage" in self.model.dsm_blocks.keys()
# Constraint for direct hydrogen flow from Electrolyser to dri plant
@self.model.Constraint(self.model.time_steps)
def direct_hydrogen_flow_constraint(m, t):
"""
Ensures the direct hydrogen flow from the electrolyser to the DRI plant or storage.
"""
# This constraint allows part of the hydrogen produced by the dri plant to go directly to the EAF
# The actual amount should ensure that it does not exceed the capacity or demand of the EAF
if has_h2storage:
return (
self.model.dsm_blocks["electrolyser"].hydrogen_out[t]
+ self.model.dsm_blocks["hydrogen_storage"].discharge[t]
== self.model.dsm_blocks["dri_plant"].hydrogen_in[t]
+ self.model.dsm_blocks["hydrogen_storage"].charge[t]
)
else:
return (
self.model.dsm_blocks["electrolyser"].hydrogen_out[t]
>= self.model.dsm_blocks["dri_plant"].hydrogen_in[t]
)
# Assuming the presence of dristorage' indicates the desire for dynamic flow management
has_dristorage = "dri_storage" in self.model.dsm_blocks.keys()
# Constraint for direct hydrogen flow from Electrolyser to dri plant
@self.model.Constraint(self.model.time_steps)
def direct_dri_flow_constraint(m, t):
"""
Ensures the direct DRI flow from the DRI plant to the EAF or DRI storage.
"""
# This constraint allows part of the dri produced by the dri plant to go directly to the dri storage
# The actual amount should ensure that it does not exceed the capacity or demand of the EAF
if has_dristorage:
return (
self.model.dsm_blocks["dri_plant"].dri_output[t]
+ self.model.dsm_blocks["dri_storage"].discharge[t]
== self.model.dsm_blocks["eaf"].dri_input[t]
+ self.model.dsm_blocks["dri_storage"].charge[t]
)
else:
return (
self.model.dsm_blocks["dri_plant"].dri_output[t]
== self.model.dsm_blocks["eaf"].dri_input[t]
)
# Constraint for material flow from dri plant to Electric Arc Furnace
@self.model.Constraint(self.model.time_steps)
def shaft_to_arc_furnace_material_flow_constraint(m, t):
"""
Ensures the material flow from the DRI plant to the Electric Arc Furnace.
"""
return (
self.model.dsm_blocks["dri_plant"].dri_output[t]
== self.model.dsm_blocks["eaf"].dri_input[t]
)
Key Process Sequence Steps:
Hydrogen Flow:
The
direct_hydrogen_flow_constraint()ensures that hydrogen produced by the electrolyser flows to the DRI plant or hydrogen storage.If hydrogen storage is present, it can charge or discharge hydrogen, ensuring that the electrolyser’s output is properly distributed.
DRI Flow:
The
direct_dri_flow_constraint()manages the flow of direct reduced iron (DRI) from the DRI plant to the EAF or DRI storage.If DRI storage is present, it can charge or discharge DRI, ensuring that the DRI output from the plant is managed efficiently.
Material Flow to EAF:
The
shaft_to_arc_furnace_material_flow_constraint()ensures that the material produced by the DRI plant flows directly into the Electric Arc Furnace (EAF) for further steel production.
These constraints ensure the proper flow of materials between the steel plant’s components, supporting efficient steel production while maintaining the operational constraints of each technology.
3.5. Executing the Optimization#
To execute the optimization process, the function determine_optimal_operation_without_flex() is called. This function computes the optimal operation for the steel plant under the defined objectives.
[ ]:
def determine_optimal_operation_without_flex(self):
"""
Execute the optimization for the steel plant based on the current market conditions.
This function will simulate the plant's operation without considering flexibility.
"""
4. Flexibility in the ASSUME Framework#
In the ASSUME framework, Demand-Side Flexibility allows agents, such as the steel plant, to adjust their energy consumption in response to price signals or grid conditions. This flexibility is achieved by shifting loads or adjusting operations based on the agent’s cost tolerance and predefined flexibility measures.
Flexibility is especially important for industrial agents, as it enables them to optimize operational costs by reacting to market signals. Two important functions are used to implement and determine the impact of flexibility: ``flexibility_cost_tolerance()`` and ``determine_optimal_operation_with_flex()``.
4.1 Defining Cost Tolerance for Flexibility#
The ``flexibility_cost_tolerance`` function defines how much additional cost the agent is willing to tolerate for the flexibility it can provide. This tolerance allows the agent to shift its load or adjust operations without exceeding the cost limitations.
[ ]:
def flexibility_cost_tolerance(self, model):
"""
Defines the cost tolerance for demand-side flexibility.
Args:
model (Pyomo model): The Pyomo model for the steel plant.
"""
# Set up the cost tolerance parameter for flexibility
model.flexibility_cost_tolerance = pyo.Param(initialize=self.cost_tolerance)
@model.Constraint(model.time_steps)
def cost_tolerance_constraint(m, t):
"""
Ensures that the cost of shifting does not exceed the allowed tolerance.
This constraint limits the cost associated with shifting loads or adjusting operations.
"""
return (
m.shifted_load[t] * model.energy_price[t]
<= model.flexibility_cost_tolerance
)
[ ]:
def determine_optimal_operation_with_flex(self):
"""
Determines the optimal operation of the agent while considering flexibility.
This function calculates how the agent can adjust its load and operations within
the defined flexibility constraints to minimize costs.
"""
# Implementation of the optimization algorithm considering flexibility constraints
The examples above illustrate how a cost tolerance can restrict the additional operating cost of flexibility. In the cost_based_load_shift formulation used later, the baseline operation is optimized first; a second optimization finds a flexible load profile subject to the configured cost limit. The flexible case submits that profile to the market using a notebook-local bidding strategy.
The preceding code is a simplified illustration of a tolerance constraint, not the complete steel-plant implementation. Conceptually, the first optimization establishes a cost-optimal baseline that meets the production and component constraints. The second optimization determines a flexible schedule within the allowed cost tolerance. The resulting electricity requirement can differ by hour while remaining subject to the plant model’s constraints.
Use Case 1: Steel plant Without Flexibility- bidding in a Day-Ahead market#
In this use case, we will simulate the energy system without demand-side flexibility. This involves setting up the power plant units, demand units, and DSM units. We will then run the simulation to understand how the market behaves without the flexibility mechanism.
1. Setting Up Power Plant Units#
Power plant units represent energy generation sources. These units are connected to specific nodes in the grid and have characteristics such as maximum power, efficiency, and operational costs. Below is the creation of the Power Plant Units DataFrame.
[ ]:
# @title Setting Up Power Plant Units
# Illustrative supply fleet for both DSM cases. Gas CCGT is an aggregated fleet.
powerplant_units_data = {
"name": [
"Wind onshore",
"Wind offshore",
"Solar",
"Hydro",
"Biomass",
"Lignite",
"Hard coal",
"Gas OCGT",
"Gas CCGT",
],
"technology": [
"wind_onshore",
"wind_offshore",
"solar",
"hydro",
"biomass",
"lignite",
"hard_coal",
"gas_ocgt",
"natural gas",
],
"bidding_EOM": ["powerplant_energy_naive"] * 9,
"fuel_type": [
"renewable",
"renewable",
"renewable",
"renewable",
"renewable",
"lignite",
"hard_coal",
"natural_gas",
"natural_gas",
],
# Emission factors are tCO2/MWh of fuel; efficiency is electrical output/fuel.
"emission_factor": [0, 0, 0, 0, 0, 0.4, 0.34, 0.2, 0.2],
"max_power": [40, 10, 50, 30, 50, 100, 100, 100, 400],
"min_power": [0] * 9, # Simplified aggregate supply: all units can reach zero.
"efficiency": [1, 1, 1, 1, 1, 0.38, 0.4, 0.38, 0.55],
"ramp_up": [None, None, None, None, 30, 30, 40, 80, 120],
"ramp_down": [None, None, None, None, 30, 30, 40, 80, 120],
"additional_cost": [0, 0, 0, 0, 6, 2, 3, 2, 0],
"node": ["north"] * 5 + ["south"] * 4,
"unit_operator": ["renewables_operator"] * 5 + ["conventional_operator"] * 4,
}
powerplant_units = pd.DataFrame(powerplant_units_data)
print("Power Plant Units DataFrame:")
display(powerplant_units)
Power plant inputs
The illustrative fleet contains wind, solar, hydro, biomass, lignite, hard coal and gas. All power plants have a minimum output of zero; this simplifies individual plants’ technical limits. Capacities, costs and emissions are simplified assumptions, not a reconstruction of Germany in 2019. Both DSM cases use the same supply inputs.
The hourly market-clearing and redispatch examples do not enforce a full inter-hour unit-commitment model, so the inputs and output should be treated as a simplified demonstration.
Each row of powerplant_units describes a supply unit. Its maximum power and availability determine its available output; efficiency, fuel prices, emissions and additional costs affect its operating costs and bids. The node locates the unit in the network. Ramp rates are also inputs, but the market-clearing results should not be interpreted as a fully ramp-constrained schedule.
2. Setting Up Demand Units#
Demand units represent the consumers of electricity in the system. These units have specific characteristics such as maximum power demand, node (location), and operator. These characteristics influence how the demand is distributed across the grid and how it interacts with the market.
Below is the creation of the Demand Units DataFrame.
[ ]:
# @title Setting Up Demand Units
# Define the list of demand units with their characteristics
demand_units_data = {
"name": ["demand_EOM1", "demand_EOM2"],
"technology": ["inflex_demand", "inflex_demand"],
"bidding_EOM": ["demand_energy_naive", "demand_energy_naive"],
"max_power": [500, 650], # Max demand in MW
"min_power": [0, 0], # Min demand in MW
"node": ["north", "south"], # Node or zone where the demand is located
"unit_operator": ["eom_de1", "eom_de1"],
}
# Create the DataFrame
demand_units = pd.DataFrame(demand_units_data)
# Display the Demand Units DataFrame
print("Demand Units DataFrame:")
display(demand_units.head())
The example defines two inflexible demand units using demand_energy_naive: demand_EOM1 in the north, with a 500 MW maximum, and demand_EOM2 in the south, with a 650 MW maximum. Their time-varying demand profiles are prepared below.
3. Preparing Demand Data#
The demand_df DataFrame provides the expected electricity demand for each demand unit over a period of time. In this use case, we will create a demand dataset for 3 days, with demand recorded every 15 minutes. This data will drive the consumption behavior of the demand units and impact the market simulation.
Below is the creation of the demand_df for 3 days.
[ ]:
# @title Prepare demand data
# Define the time range for 3 days, with demand recorded every 15 minutes
time_index = pd.date_range(
start="2019-01-01 00:00", end="2019-01-03 23:45", freq="15min"
)
# Simulate demand data for 'demand_EOM1' and 'demand_EOM2' (example demand pattern)
# For simplicity, we'll create a fluctuating demand pattern using a sinusoidal function
# The shared illustrative load peaks around 15:00 and is lowest around 03:00.
# Total demand varies from 150 to 450 MW before the steel plant is added.
hour_of_day = time_index.hour + time_index.minute / 60
daily_shape = 0.5 + 0.5 * np.sin(2 * np.pi * (hour_of_day - 9) / 24)
demand_values1 = 130 + 280 * daily_shape # north: load centre
demand_values2 = 20 + 20 * daily_shape # south: mostly generation
# Create the DataFrame with both 'demand_EOM1' and 'demand_EOM2'
demand_df = pd.DataFrame(
{
"datetime": time_index,
"demand_EOM1": demand_values1,
"demand_EOM2": demand_values2,
}
)
# Set 'datetime' as the index
demand_df.set_index("datetime", inplace=True)
# Display the first few rows of the demand DataFrame
print("Demand DataFrame for 3 Days:")
display(demand_df.head())
Explanation of the Above Code
In the above code:
We generate demand data for 3 days, with demand recorded every 15 minutes.
The demand pattern fluctuates between 150 MW and 450 MW, using a sinusoidal function to simulate variations in electricity consumption over time.
The demand_df DataFrame will be used as an input for the demand units in the market simulation, determining how much electricity is required at each time step.
This DataFrame serves as the input for the demand profile.
4. Setting Up Industrial DSM Units#
Industrial DSM Units represent the demand-side agents, such as the steel plant, which can adjust their electricity consumption and participate in the market using different flexibility strategies. Below, we will create the industrial_dsm_units DataFrame with relevant attributes for the steel plant.
[ ]:
# @title Setting Up DSM Units
# Define the list of industrial DSM units (for steel plant) with their characteristics
industrial_dsm_units_data = {
"name": ["A360", "A360", "A360"],
"unit_type": ["steel_plant", "steel_plant", "steel_plant"],
"technology": ["electrolyser", "dri_plant", "eaf"],
"node": ["south", "south", "south"],
"bidding_EOM": ["industry_energy_optimization", "", ""],
"unit_operator": ["dsm_operator_1", "dsm_operator_1", "dsm_operator_1"],
"objective": ["min_variable_cost", "", ""],
"flexibility_measure": [None, "", ""], # cost_based_load_shift
"cost_tolerance": [20, None, None],
"demand": [1500, None, None], # MW
"fuel_type": ["hydrogen", "hydrogen", "hydrogen"],
"max_power": [100, 100, 100], # MW
"min_power": [0, 0, 0], # MW
"ramp_up": [100, 100, 100], # MW/hr
"ramp_down": [100, 100, 100], # MW/hr
"min_operating_time": [0, 1, 0],
"min_down_time": [0, 0, 0],
"efficiency": [0.8, None, None],
"specific_dri_demand": [None, None, 1.09],
"specific_electricity_consumption": [None, 0.3, 0.44],
"specific_natural_gas_consumption": [None, 1.9, None],
"specific_hydrogen_consumption": [None, 1.83, None],
"specific_iron_ore_consumption": [None, 1.43, None],
"specific_lime_demand": [None, None, 0.046],
"lime_co2_factor": [None, None, 0.1],
"start_price": [5, None, None],
"max_capacity": [None, None, None],
"min_capacity": [None, None, None],
"initial_soc": [None, None, None],
"storage_loss_rate": [None, None, None],
"charge_loss_rate": [None, None, None],
"discharge_loss_rate": [None, None, None],
}
# Create the DataFrame
industrial_dsm_units = pd.DataFrame(industrial_dsm_units_data)
# Display the Industrial DSM Units DataFrame
print("Industrial DSM Units DataFrame:")
display(industrial_dsm_units.head())
Explanation of the Above Code
In the above code:
The steel plant is represented by three technologies: electrolyser, DRI plant, and EAF (Electric Arc Furnace).
Each unit is associated with specific operational parameters such as rated power, minimum power, ramp rates, and fuel type.
The bidding_EOM columns specify the bidding strategies used by the steel plant in the market.
Additional operational characteristics include specific hydrogen consumption, specific electricity consumption, and specific natural gas consumption for each of the units.
This DataFrame serves as the input for the steel plant, and these characteristics will influence the market simulation.
Bidding strategy for the steel plant
The following code illustrates the shape of a DSM bidding strategy. The actual simulations use the framework’s industry_energy_optimization strategy for the baseline and a notebook-local subclass for the flexible case. The framework strategy submits the baseline optimized power requirement at a fixed willingness to pay of 3,000 EUR/MWh; the subclass submits the flexible requirement instead.
[ ]:
from assume.common.base import MinMaxStrategy
class DsmEnergyOptimizationStrategy(MinMaxStrategy):
def calculate_bids(
self,
unit: SupportsMinMax,
market_config: MarketConfig,
product_tuples: list[Product],
**kwargs,
) -> Orderbook:
bids = []
# Calculate the optimal operation for the steel plant
unit.determine_optimal_operation_with_flex()
for product in product_tuples:
"""
For each product, calculate the marginal cost of the unit at the start time of the product
and the volume of the product. Dispatch the order to the market.
"""
start = product[0]
volume = unit.opt_power_requirement.loc[
start
] # Power requirement for the unit at the start time
marginal_price = unit.calculate_marginal_cost(
start, volume
) # Calculate the marginal cost
bids.append(
{
"start_time": product[0], # Start time of the bid
"end_time": product[1], # End time of the bid
"only_hours": product[2], # Relevant hours for the bid
"price": marginal_price, # Marginal price for the bid
"volume": -volume, # Volume of electricity
}
)
return bids
The illustrative strategy above shows how a unit can construct a bid for each delivery period. It is a standalone example and is not registered as the strategy used in the simulations below. The calculate_marginal_cost example that follows is also illustrative; the actual strategies use a fixed bid price, as explained above.
For each delivery product, the illustrative strategy:
Calculates an operating profile for the unit.
Reads the baseline power requirement at the product’s start time and calls the illustrative marginal-cost function.
Creates an order with the product’s start and end times, applicable hours, price and volume. A negative volume represents electricity demand.
Although this example calls the flexible optimization, it reads opt_power_requirement, the baseline requirement. The strategy used in Use Case 2 explicitly substitutes the flexible requirement in its orders.
[ ]:
def calculate_marginal_cost(self, start: pd.Timestamp, power: float) -> float:
"""
Calculate the marginal cost of the unit based on the provided time and power.
Args:
start (pandas.Timestamp): The start time of the dispatch.
power (float): The power output of the unit.
Returns:
float: the marginal cost of the unit for the given power.
"""
# Initialize marginal cost
marginal_cost = 0
# If the unit requires power at the given time, calculate the marginal cost
if self.opt_power_requirement[start] > 0:
marginal_cost = (
self.variable_cost_series[start] / self.opt_power_requirement[start]
)
return marginal_cost
The illustrative function divides a period’s variable cost by its baseline power requirement when that requirement is nonzero. This example is not the bid price used in the simulations below.
In the example, the returned value is variable_cost_series[start] / opt_power_requirement[start], or zero if the requirement is zero. It is shown to explain a possible calculation; it should not be confused with the fixed willingness-to-pay bid or with the market-clearing price.
5 Defining Buses#
Buses represent nodes in the network where energy can be injected or withdrawn. Each bus is assigned to a zone, which groups buses into market areas.
Below is the buses DataFrame, which defines the two main nodes in our system: north and south.
[ ]:
# @title Setting Up Buses
# Define the buses DataFrame with two nodes: north and south
buses = pd.DataFrame(
{
"name": ["north", "south"], # Bus names (zones)
"v_nom": [380.0, 380.0], # Nominal voltage levels (kV)
"carrier": ["AC", "AC"], # Carrier type (AC)
"x": [9.598, 13.607], # Geographical coordinates (x-coordinate)
"y": [53.5585, 51.0769], # Geographical coordinates (y-coordinate)
}
)
# Display the buses DataFrame
print("Buses DataFrame:")
display(buses)
Explanation
``name``: Identifier for each bus. In this case, we have two buses named north and south representing zones in the network.
``v_nom``: The nominal voltage level (in kV) of each bus. Here, both buses have a voltage of 380 kV.
``carrier``: The type of carrier associated with the bus. In this case, the carrier is AC (alternating current).
``x``, ``y``: Geographical coordinates that can be used for mapping or spatial analysis. These coordinates define the location of each bus on a map (optional but useful for visualization).
6 Configuring Transmission Lines#
Transmission Lines connect buses, allowing energy to flow between them. Each line has a specified capacity and electrical parameters, such as reactance and resistance.
Below is the lines DataFrame, which defines the line between the north and south buses.
[ ]:
# @title Setting Up Transmission lines
# Define the transmission lines DataFrame
lines = pd.DataFrame(
{
"name": ["Line_N_S"], # Name of the transmission line
"bus0": ["north"], # Starting bus (north)
"bus1": ["south"], # Ending bus (south)
"s_nom": [200.0], # Nominal power capacity (MVA)
"s_max_pu": [1.0], # Maximum loading as a fraction of s_nom
"x": [0.01], # Reactance (in per unit)
"r": [0.001], # Resistance (in per unit)
}
)
# Display the transmission lines DataFrame
print("Transmission Lines DataFrame:")
display(lines)
Explanation
``name``: The identifier for the transmission line, in this case, Line_N_S, which connects the north and south buses.
``bus0``, ``bus1``: The two buses that the transmission line connects. Here, bus0 is north and bus1 is south.
``s_nom``: The nominal apparent power capacity of the transmission line, given in MVA (megavolt-amperes). In this case, the capacity is 200 MVA.
``s_max_pu``: Maximum loading as a fraction of s_nom. In this case 1.
``x``: The reactance of the transmission line (in per unit). This defines the impedance of the line, and we set it to 0.01.
``r``: The resistance of the transmission line (in per unit), which represents the electrical resistance. This is set to 0.001 for the line.
7. Integrating with ASSUME#
7.1 Saving input files#
The generated files are written to inputs/tutorial_10. They include the power plants, demand units and profiles, industrial DSM units, buses, lines and availability_df.csv. The availability file gives the wind and solar plants time-varying capacity factors between zero and one; solar availability is zero at night.
The following cells also write fuel_prices_df.csv, forecasts_df.csv and config.yaml. Use Cases 1 and 2 share these supply inputs. Use Case 3 later copies and adjusts them in a separate folder.
The files have different roles: powerplant_units.csv and demand_units.csv define the market participants; demand_df.csv provides the inflexible demand time series; industrial_dsm_units.csv defines the industrial participant and its components. buses.csv and lines.csv describe the grid. The renewable availability file scales the corresponding plants’ maximum power over time.
[ ]:
# Define the input directory
input_dir = "inputs"
scenario = "tutorial_10"
scenario_path = Path(input_dir) / scenario
# Create the directory if it doesn't exist
scenario_path.mkdir(parents=True, exist_ok=True)
# Extend the demand_df for the 3-day simulation (as we need to simulate for 3 days)
demand_df_extended = pd.concat([demand_df] * 3)
demand_df_extended.index = pd.date_range(
start="2019-01-01", periods=len(demand_df_extended), freq="15min"
)
# Save the DataFrames to CSV files
powerplant_units.to_csv(f"{scenario_path}/powerplant_units.csv", index=False)
demand_units.to_csv(f"{scenario_path}/demand_units.csv", index=False)
demand_df_extended.to_csv(f"{scenario_path}/demand_df.csv")
# Illustrative weather profiles shared by both cases, covering the complete
# simulation. Solar is zero at night; wind varies over time. The CSV columns
# match plant names and contain capacity factors rather than MW values.
availability_index = pd.date_range("2019-01-01", "2019-01-05", freq="15min")
availability_hour = availability_index.hour + availability_index.minute / 60
elapsed_hours = np.arange(len(availability_index)) / 4
solar_shape = np.where(
(availability_hour >= 8) & (availability_hour < 16),
np.sin(np.pi * (availability_hour - 8) / 8),
0.0,
)
availability_df = pd.DataFrame(
{
"Wind onshore": 0.64
+ 0.22 * np.sin(2 * np.pi * elapsed_hours / 48)
+ 0.08 * np.sin(2 * np.pi * elapsed_hours / 24),
"Wind offshore": 0.72 + 0.16 * np.sin(2 * np.pi * (elapsed_hours + 6) / 48),
"Solar": solar_shape,
},
index=availability_index,
).clip(lower=0, upper=1)
availability_df.to_csv(f"{scenario_path}/availability_df.csv")
industrial_dsm_units.to_csv(f"{scenario_path}/industrial_dsm_units.csv", index=False)
buses.to_csv(f"{scenario_path}/buses.csv", index=False)
lines.to_csv(f"{scenario_path}/lines.csv", index=False)
print(f"Input CSV files have been saved to the directory: {scenario_path}")
Create fuel_prices_df.csv
The following cell saves illustrative lignite, hard-coal, natural-gas and CO₂ prices. Fuel prices are in EUR/MWh of fuel and the CO₂ price is in EUR/tCO₂.
[ ]:
# @title Setting Up Fuel Prices
# Illustrative fuel prices in EUR/MWh of fuel and CO2 price in EUR/tCO2.
fuel_prices = {
"fuel": ["lignite", "hard_coal", "natural_gas", "co2"],
"price": [5, 12, 35, 25],
}
fuel_prices_df = pd.DataFrame(fuel_prices).T
fuel_prices_df.to_csv(f"{scenario_path}/fuel_prices_df.csv", index=True, header=False)
print(f"Fuel prices saved to {scenario_path}/fuel_prices_df.csv")
Checking Fuel Types for Power Plants
Now, let’s check which fuels are required for our power plant units, ensuring that the correct prices are applied:
[ ]:
# Display the unique fuel types used in the powerplant_units DataFrame
unique_fuel_types = powerplant_units["fuel_type"].unique()
print(f"Fuel types required for power plants: {unique_fuel_types}")
7.2 Creating ``forecasts_df`` for the steel plant#
The following cell creates illustrative hourly forecasts, including an EOM price signal and prices for natural gas, iron ore, lime and CO₂. The EOM forecast is an input to the steel-plant optimization; it is not the market-clearing price produced by the simulation.
Forecasts give the plant information for its own operational optimization. For example, the electricity-price forecast influences the timing of electricity use, while the other prices represent inputs to the industrial process. In this example the forecasts are synthetic and most non-electricity prices are constant.
[ ]:
# @title Setting Up Forecasts
# Define the time range for the forecast (matching the 3-day simulation)
time_index = pd.date_range(start="2019-01-01 00:00", end="2019-01-04 23:45", freq="h")
# Define the base price for the diurnal electricity price and amplitude for fluctuations
base_price = 10
price_amplitude = 60 # Max fluctuation range
hours_in_day = 24
# Use a sine wave to simulate the diurnal price cycle
price_EOM = base_price + price_amplitude * np.sin(
2 * np.pi * (time_index.hour / hours_in_day)
)
# Define the forecast data for required parameters (example values)
forecasts_data = {
"datetime": time_index,
"fuel_price_natural_gas": [25] * len(time_index), # Fixed price for natural gas
"price_EOM": price_EOM, # Diurnal electricity price based on the sine wave
"iron_ore_price": [80] * len(time_index), # Varying iron ore price
"lime_price": [15] * len(time_index), # Varying lime price
"co2_price": [50] * len(time_index), # Varying CO2 price
}
# Create the DataFrame
forecasts_df = pd.DataFrame(forecasts_data)
# Set 'datetime' as the index
forecasts_df.set_index("datetime", inplace=True)
# Save the DataFrame as CSV
forecasts_df.to_csv(f"{scenario_path}/forecasts_df.csv")
print(
f"Forecasts DataFrame has been created and saved to: {scenario_path}/forecasts_df.csv"
)
7.3 Creating the Configuration YAML File#
For our simulation, we will define the configuration in a YAML format, which specifies the time range, market setup, and other parameters. This configuration will be saved as a config.yaml file.
Below is the creation of the configuration dictionary and saving it to a YAML file.
[ ]:
# @title Configuring Market
# Define the configuration dictionary
config = {
"steel_plant_Day_Ahead": {
"start_date": "2019-01-01 00:00",
"end_date": "2019-01-04 23:00",
"time_step": "1h",
"save_frequency_hours": 24,
"markets_config": {
"EOM": {
"operator": "EOM_operator",
"product_type": "energy",
"products": [
{
"duration": "1h", # Each product lasts for 1 hour
"count": 24, # Number of products per day (24 hours)
"first_delivery": "1h", # First delivery is 1 hour after the market opens
}
],
"opening_frequency": "24h", # Market opens once every 24 hours
"opening_duration": "1h", # Market stays open for 1 hour
"volume_unit": "MWh", # Market volume is measured in MWh
"maximum_bid_volume": 100000, # Maximum bid volume allowed
"maximum_bid_price": 3000, # Maximum allowed bid price
"minimum_bid_price": -500, # Minimum allowed bid price
"price_unit": "EUR/MWh", # Bid price unit is EUR per MWh
"market_mechanism": "pay_as_clear", # Market clears with pay-as-clear mechanism
}
},
}
}
# Define the path for the config file
config_path = scenario_path / "config.yaml"
# Save the configuration to a YAML file
with open(config_path, "w") as file:
yaml.dump(config, file, sort_keys=False)
print(f"Configuration YAML file has been saved to '{config_path}'.")
The steel_plant_Day_Ahead configuration runs from 2019-01-01 00:00 to 2019-01-04 23:00 with an hourly simulation step. The EOM opens daily, accepts bids for one hour, and clears 24 one-hour products beginning one hour after opening using pay-as-clear pricing.
The configured price limits are −500 and 3,000 EUR/MWh. save_frequency_hours is set to 24, although periodic saving is disabled when the notebook exports CSV files; those files are written at the end of the simulation. The dates, market schedule and parameters are illustrative, and the cleared delivery window may be shorter than the steel plant’s full optimization horizon.
Key settings in markets_config are:
operatoridentifies the market operator, andproduct_typespecifies energy trading.duration,countandfirst_deliverydescribe the delivery periods offered at each opening. Here there are 24 products, each one hour long, beginning one hour after opening.opening_frequencyandopening_durationdefine how often the market opens and how long it accepts orders.maximum_bid_volume,minimum_bid_priceandmaximum_bid_priceset order limits;volume_unitandprice_unitlabel the configured units.market_mechanismselects pay-as-clear clearing, in which accepted orders for a product receive the clearing price.
The units’ bidding_EOM entries connect their bidding strategies to this EOM configuration.
7.4 Running the Simulation#
Now that we have prepared the input files and configuration, we can proceed to run the simulation using the ASSUME framework. In this step, we will load the scenario and execute the simulation.
[ ]:
# Define paths for input and output data
csv_path = "outputs"
# Define the data format and database URI
# Use "local_db" for SQLite database or "timescale" for TimescaleDB in Docker
# Create directories if they don't exist
Path(csv_path).mkdir(parents=True, exist_ok=True)
Path("local_db").mkdir(parents=True, exist_ok=True)
# Choose the data format: either local SQLite database or TimescaleDB
data_format = "local_db" # Options: "local_db" or "timescale"
# Set the database URI based on the selected data format
if data_format == "local_db":
db_uri = "sqlite:///local_db/assume_db.db" # SQLite database
elif data_format == "timescale":
db_uri = "postgresql://assume:assume@localhost:5432/assume" # TimescaleDB
# Create the World instance
world = World(database_uri=db_uri, export_csv_path=csv_path)
# Load the scenario by providing the world instance
# The path to the inputs folder and the scenario name (subfolder in inputs)
# and the study case name (which config to use for the simulation)
load_scenario_folder(
world,
inputs_path=input_dir,
scenario=scenario, # Scenario folder for our case
study_case="steel_plant_Day_Ahead", # The config we defined earlier
)
# Run the simulation
world.run()
# Keep the full optimized schedule for comparison with the flexible case.
steel_unit_uc1 = world.unit_operators["dsm_operator_1"].units["A360"]
profile_uc1 = pd.Series(
steel_unit_uc1.opt_power_requirement.data.copy(),
index=steel_unit_uc1.index.get_date_list(),
name="Baseline",
)
print("Simulation has completed.")
7.5 Visualizing the steel plant’s accepted market demand#
The following cells plot the steel plant’s accepted EOM demand and submitted bid price from market_orders.csv. The fixed bid price expresses willingness to pay; it is not the market-clearing price or the plant’s marginal cost.
The accepted hourly demand profile is also saved for the comparison with Use Case 2.
[ ]:
output_dir = f"outputs/{scenario}_steel_plant_Day_Ahead"
# ---- Load the market_orders CSV file ----
market_orders = pd.read_csv(f"{output_dir}/market_orders.csv")
# Filter the data for the steel plant (unit_id 'A360')
steel_plant_orders = market_orders.loc[market_orders["unit_id"] == "A360"].copy()
# Convert 'start_time' column to datetime
steel_plant_orders["time"] = pd.to_datetime(steel_plant_orders["start_time"])
# Use the accepted demand rather than the submitted bid volume.
steel_plant_orders["volume"] = pd.to_numeric(
steel_plant_orders["accepted_volume"], errors="coerce"
)
# Make the volume values positive (assuming negative values represent consumption)
steel_plant_orders["volume"] = steel_plant_orders["volume"].abs()
# ---- Handle missing time steps ----
# Define the full time range based on the simulation step (e.g., 1-hour intervals)
full_time_range = pd.date_range(
start=steel_plant_orders["time"].min(),
end=steel_plant_orders["time"].max(),
freq="h",
)
# Reindex the DataFrame to have a row for every time step
steel_plant_orders = steel_plant_orders.set_index("time").reindex(full_time_range)
# Fill NaN values in 'volume' and 'price' with 0 for the missing time steps
steel_plant_orders = steel_plant_orders.fillna({"volume": 0, "price": 0})
# Reset the index back to 'time'
steel_plant_orders = steel_plant_orders.reset_index().rename(columns={"index": "time"})
# ---- Save the DataFrame for future use ----
# Save the updated DataFrame with complete time steps
steel_plant_orders.to_csv(
"outputs/steel_plant_market_orders_use_case_1.csv",
index=False,
)
print(
"Saved the accepted electricity demand and bid price profile with complete time steps to CSV."
)
[ ]:
# ---- Plotting ----
# Use Seaborn to set plot style
sns.set(style="whitegrid")
# Create the figure and axis for plotting
fig, ax1 = plt.subplots(figsize=(10, 6))
# Plot electricity consumption (volume) on the first y-axis
sns.lineplot(
x="time",
y="volume",
data=steel_plant_orders,
label="Accepted Demand",
color="b",
ax=ax1,
)
# Set labels for the first y-axis
ax1.set_xlabel("Time", fontsize=12)
ax1.set_ylabel("Power (MW)", fontsize=12, color="b")
# Create the second y-axis for bid price with transparency and dashed line
ax2 = ax1.twinx()
# Make bid price plot semi-transparent and use a different linestyle
sns.lineplot(
x="time",
y="price",
data=steel_plant_orders,
label="Bid Price",
color="g",
ax=ax2,
linestyle="--", # Dashed line for better distinction
alpha=0.7, # Set transparency to make the lines less overwhelming
)
# Set labels for the second y-axis
ax2.set_ylabel("Bid price (EUR/MWh)", fontsize=12, color="g")
# Set plot title
plt.title("Electricity Consumption and Bid Price of Steel Plant", fontsize=14)
# Rotate x-axis ticks for better readability
ax1.tick_params(axis="x", rotation=45)
# Add grid for better readability
ax1.grid(True)
# Add legends for both plots
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
# Save the plot as a PNG file
plt.savefig(f"{output_dir}/steel_plant_consumption_marginal_cost.png")
# Show the plot
plt.tight_layout() # Adjust layout to avoid clipping of labels
plt.show()
[ ]:
# Load the market_meta.csv file
market_meta = pd.read_csv(
f"{output_dir}/market_meta.csv", index_col="time", parse_dates=True
)
# drop the first column
market_meta = market_meta.drop(columns=market_meta.columns[0])
# Display a sample of the data
print("Sample of market_meta.csv:")
display(market_meta.head())
[ ]:
# Load the market_meta CSV file (for Use Case 1)
market_meta_uc1 = pd.read_csv(f"{output_dir}/market_meta.csv")
# Convert 'time' column to datetime if it's not already in the correct format
market_meta_uc1["time"] = pd.to_datetime(market_meta_uc1["time"])
# ---- Save the DataFrame for future use ----
# Save the clearing price data as a CSV for future comparison
market_meta_uc1[["time", "price"]].to_csv(
f"{output_dir}/clearing_price_use_case_1.csv",
index=False,
)
print("Saved the clearing price data of Use Case 1 to CSV.")
# ---- Plotting ----
# Create a Plotly figure for the clearing price
fig = go.Figure()
# Add a scatter plot trace for the price over time
fig.add_trace(
go.Scatter(
x=market_meta_uc1["time"],
y=market_meta_uc1["price"],
mode="lines",
name="Clearing Price",
line=dict(color="blue"),
)
)
# Set the layout for the figure
fig.update_layout(
title="Clearing Price Over Time",
xaxis_title="Time",
yaxis_title="Price (EUR/MWh)",
xaxis=dict(showgrid=True),
yaxis=dict(showgrid=True),
)
# Display the figure
fig.show()
Explanation
Saving the DataFrame:
The clearing price data is saved to a CSV file with the following line:
[ ]:
market_meta_uc1[["time", "price"]].to_csv(
"outputs/clearing_price_use_case_1.csv", index=False
)
7.6 Setting up the grid network#
The following cells construct a two-node PyPSA network using the example’s power-plant, steel-plant and demand schedules. They calculate linear power flows over the transmission line to illustrate potential congestion. This calculation does not establish a fully constrained inter-hour operating schedule.
The network consists of buses, generators, loads and a transmission line. Generators inject power at their assigned nodes, while the steel plant and other demand units withdraw it. After assigning the market schedules to these components, the linear power-flow calculation estimates the flow on the line. Comparing the magnitude of that flow with its capacity identifies potential congestion.
[ ]:
# Create a new PyPSA network
network = pypsa.Network()
snapshots = pd.date_range(start="2019-01-01 00:00", end="2019-01-02 23:00", freq="h")
network.set_snapshots(snapshots)
solver_name = "highs"
7.6.1 Add buses to the network#
[ ]:
# @title adding buses to the network
network.add(
"Bus",
name=buses["name"].to_list(), # Bus names
v_nom=buses["v_nom"].to_list(), # Nominal voltage levels
carrier=buses["carrier"].to_list(), # Carrier types
x=buses["x"].to_list(), # x-coordinates
y=buses["y"].to_list(), # y-coordinates
)
network.buses
7.6.2 Add generators to the network#
[ ]:
# @title adding generators to the network
# Adding generators in the same format as the bus-adding code
market_dispatch = pd.read_csv(f"{output_dir}/market_dispatch.csv", parse_dates=True)
market_dispatch.head()
[ ]:
gen_p_set = market_dispatch.pivot(index="datetime", columns="unit_id", values="power")
gen_p_set = gen_p_set.rename_axis("snapshot", axis="index")
power_p_set = gen_p_set.drop(columns=["A360", "demand_EOM1", "demand_EOM2"])
power_p_set.index = pd.to_datetime(power_p_set.index)
power_p_set.index = power_p_set.index - pd.Timedelta(hours=1)
power_p_set = power_p_set.fillna(0)
power_p_set.head()
7.6.3 Add DSM Units to the network#
[ ]:
# @title adding powerplants to the network
network.add(
"Load",
name=powerplant_units.name,
bus=list(powerplant_units["node"]),
carrier=list(powerplant_units["technology"]),
sign=1,
)
network.loads_t.p_set = power_p_set
network.loads
[ ]:
dsm_p_set = gen_p_set[["A360"]]
dsm_p_set.index = pd.to_datetime(dsm_p_set.index)
dsm_p_set = dsm_p_set.rename_axis("snapshot", axis="index")
dsm_p_set.index = dsm_p_set.index - pd.Timedelta(hours=1)
dsm_p_set = dsm_p_set.fillna(0)
dsm_p_set = np.abs(dsm_p_set)
dsm_p_set.head(3)
[ ]:
# @title adding DSU to the network
# Add DSU Units as generators
ind_dsm_units = industrial_dsm_units[
industrial_dsm_units["technology"] == "electrolyser"
]
network.add(
"Load",
name=list(ind_dsm_units["name"]),
bus=list(ind_dsm_units["node"]),
carrier=list(ind_dsm_units["technology"]),
p_set=dsm_p_set, # accepted volume of power
sign=-1,
)
network.loads
7.6.4 Add Loads to the network#
[ ]:
demand_p_set = gen_p_set[["demand_EOM1", "demand_EOM2"]]
demand_p_set = demand_p_set.rename_axis("snapshot", axis="index")
demand_p_set.index = pd.to_datetime(demand_p_set.index)
demand_p_set.index = demand_p_set.index - pd.Timedelta(hours=1)
demand_p_set = demand_p_set.fillna(0)
demand_p_set = demand_p_set.abs()
demand_p_set.head(10)
[ ]:
# @title adding demand load to the network
network.add(
"Load",
name=demand_units.name,
bus=list(demand_units["node"]),
carrier=list(demand_units["technology"]),
p_set=demand_p_set, # accepted volume of power
sign=-1,
)
network.loads_t.p_set.head(3)
7.6.5 Add Lines to the network#
[ ]:
# @title adding transmission line to the network
network.add(
"Line",
name=lines.name,
bus0=list(lines.bus0),
bus1=list(lines.bus1),
s_nom=list(lines.s_nom),
s_max_pu=list(lines.s_max_pu),
s_nom_extendable=False,
x=list(lines.x),
r=list(lines.r),
)
7.6.6 Congestion identification#
[ ]:
network.lpf()
[ ]:
congestion_df = pd.DataFrame(
{
"line_loading": np.abs(network.lines_t.p0.values.flatten()),
"line_name": network.lines.index.repeat(len(network.snapshots)),
"timestamp": pd.Series(network.snapshots).repeat(len(network.lines)),
}
)
[ ]:
s_nom_values = network.lines.s_nom
congestion_df["s_nom"] = congestion_df["line_name"].map(s_nom_values)
s_max_pu_values = network.lines.s_max_pu
congestion_df["s_max_pu"] = congestion_df["line_name"].map(s_max_pu_values)
congestion_df["congestion_status"] = congestion_df["line_loading"] > (
congestion_df["s_nom"] * congestion_df["s_max_pu"]
)
congested_lines = congestion_df[congestion_df["congestion_status"]]
congested_lines
The next plot displays the line loading at a selected snapshot. Blue indicates loading at or below the line limit; red indicates an overload. The status of a particular snapshot depends on the simulated inputs and results.
[ ]:
now = network.snapshots[12]
loading = network.lines_t.p0.loc[now] / (network.lines.s_nom * network.lines.s_max_pu)
congestion_threshold = 1
line_colors = np.where(abs(loading) > congestion_threshold, "red", "blue")
# Create the figure and the axis using Cartopy's PlateCarree projection
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={"projection": ccrs.PlateCarree()})
# Plot the network using the built-in network plot function
network.plot(
ax=ax,
line_colors=line_colors,
title="Line Loading",
bus_sizes=1e-2, # Size of bus markers
bus_alpha=0.7, # Transparency of bus markers
)
# Adjust layout and display the plot
fig.tight_layout()
plt.show()
Use Case 2: Steel plant with flexibility in the day-ahead market#
This case uses the same steel-plant components, demand, forecasts and supply inputs as Use Case 1. It submits the optimized flexible power profile to the EOM using a small notebook-local bidding strategy; Use Case 1 submits the baseline optimized profile. The plant’s component model and flexibility formulation remain unchanged.
1. Enabling flexibility#
The following cell updates the industrial unit’s flexibility_measure to cost_based_load_shift and selects the notebook-local strategy for EOM bidding. The plant first determines its baseline operation, then calculates a flexible profile subject to its cost tolerance. Comparing the two cases helps show how shifting the timing of demand can affect the accepted orders and market results.
The built-in day-ahead strategy bids opt_power_requirement, the baseline profile. For this comparison, the notebook-local strategy below first invokes that strategy’s optimization and then submits flex_power_requirement. This allows the market results to show the model’s flexible schedule without modifying ASSUME’s core strategy.
[ ]:
# @title setting up DSM units with a bidding strategy
# Load the industrial_dsm_units CSV file
industrial_dsm_units = pd.read_csv(
f"{scenario_path}/industrial_dsm_units.csv",
dtype={"flexibility_measure": str, "bidding_EOM": str},
)
# Update the 'flexibility_measure'
industrial_dsm_units.loc[
industrial_dsm_units["technology"] == "electrolyser", "flexibility_measure"
] = "cost_based_load_shift"
# Update the 'bidding strategy'
industrial_dsm_units.loc[
industrial_dsm_units["technology"] == "electrolyser", "bidding_EOM"
] = "tutorial_flexible_dsm"
# Save the updated industrial_dsm_units file
industrial_dsm_units.to_csv(f"{scenario_path}/industrial_dsm_units.csv", index=False)
print("Enabled the flexible profile bidding strategy for Use Case 2.")
2. Running the Simulation with Flexibility#
Once the input file has been updated, you can run the simulation just as in Use Case 1, but now with the flexibility enabled for the steel plant.
[ ]:
# Use the framework's DSM optimization unchanged, but bid its flexible profile
# in this tutorial's second case rather than the baseline optimal profile.
from assume.strategies.naive_strategies import (
DsmEnergyOptimizationStrategy as BaseDsmEnergyOptimizationStrategy,
)
class TutorialFlexibleDsmStrategy(BaseDsmEnergyOptimizationStrategy):
def calculate_bids(self, unit, market_config, product_tuples, **kwargs):
bids = super().calculate_bids(unit, market_config, product_tuples, **kwargs)
for bid in bids:
bid["volume"] = -unit.flex_power_requirement.at[bid["start_time"]]
return bids
world = World(database_uri=db_uri, export_csv_path=csv_path)
# Copy the registry so this tutorial-local strategy does not mutate global state.
world.bidding_strategies = dict(world.bidding_strategies)
world.bidding_strategies["tutorial_flexible_dsm"] = TutorialFlexibleDsmStrategy
# Load the scenario folder with the updated inputs
load_scenario_folder(
world,
inputs_path=input_dir, # Path to the updated inputs folder
scenario=scenario, # Scenario folder remains the same
study_case="steel_plant_Day_Ahead", # Study case remains the same
)
# Run the simulation (which now includes flexibility bidding)
world.run()
steel_unit_uc2 = world.unit_operators["dsm_operator_1"].units["A360"]
profile_uc2 = pd.Series(
steel_unit_uc2.flex_power_requirement.data.copy(),
index=steel_unit_uc2.index.get_date_list(),
name="Flexible",
)
print("Simulation with flexibility completed.")
3. Visualizing the steel plant’s accepted market demand#
The following cells plot the steel plant’s accepted EOM demand and submitted bid price for the flexible case. The bid price is not the market-clearing price.
[ ]:
# ---- Load the market_orders CSV file for Use Case 2 ----
market_orders_uc2 = pd.read_csv(f"{output_dir}/market_orders.csv")
# Filter the data for the steel plant (unit_id 'A360')
steel_plant_orders_uc2 = market_orders_uc2.loc[
market_orders_uc2["unit_id"] == "A360"
].copy()
# Convert 'start_time' column to datetime
steel_plant_orders_uc2["time"] = pd.to_datetime(steel_plant_orders_uc2["start_time"])
# Use the accepted demand rather than the submitted bid volume.
steel_plant_orders_uc2["volume"] = pd.to_numeric(
steel_plant_orders_uc2["accepted_volume"], errors="coerce"
)
# Make the volume values positive (assuming negative values represent consumption)
steel_plant_orders_uc2["volume"] = steel_plant_orders_uc2["volume"].abs()
# ---- Handle missing time steps ----
# Define the full time range based on the simulation step (e.g., 1-hour intervals)
full_time_range = pd.date_range(
start=steel_plant_orders_uc2["time"].min(),
end=steel_plant_orders_uc2["time"].max(),
freq="h",
)
# Reindex the DataFrame to have a row for every time step
steel_plant_orders_uc2 = steel_plant_orders_uc2.set_index("time").reindex(
full_time_range
)
# Fill NaN values in 'volume' and 'price' with 0 for the missing time steps
steel_plant_orders_uc2 = steel_plant_orders_uc2.fillna({"volume": 0, "price": 0})
# Reset the index back to 'time'
steel_plant_orders_uc2 = steel_plant_orders_uc2.reset_index().rename(
columns={"index": "time"}
)
# ---- Save the DataFrame for future use ----
# Save the updated DataFrame with complete time steps
steel_plant_orders_uc2.to_csv(
"outputs/steel_plant_market_orders_use_case_2.csv",
index=False,
)
print(
"Saved the accepted electricity demand and bid price profile of Use Case 2 with complete time steps to CSV."
)
[ ]:
# ---- Plotting ----
# Use Seaborn to set plot style
sns.set(style="whitegrid")
# Create the figure and axis for plotting
fig, ax1 = plt.subplots(figsize=(10, 6))
# Plot electricity consumption (volume) on the first y-axis
sns.lineplot(
x="time",
y="volume",
data=steel_plant_orders_uc2,
label="Accepted Demand",
color="b",
ax=ax1,
)
# Set labels for the first y-axis
ax1.set_xlabel("Time", fontsize=12)
ax1.set_ylabel("Power (MW)", fontsize=12, color="b")
# Create the second y-axis for bid price with transparency and dashed line
ax2 = ax1.twinx()
# Make bid price plot semi-transparent and use a different linestyle
sns.lineplot(
x="time",
y="price",
data=steel_plant_orders_uc2,
label="Bid Price",
color="g",
ax=ax2,
linestyle="--", # Dashed line for better distinction
alpha=0.7, # Set transparency to make the lines less overwhelming
)
# Set labels for the second y-axis
ax2.set_ylabel("Bid price (EUR/MWh)", fontsize=12, color="g")
# Set plot title
plt.title(
"Electricity Consumption and Bid Price of Steel Plant - Flexibility",
fontsize=14,
)
# Rotate x-axis ticks for better readability
ax1.tick_params(axis="x", rotation=45)
# Add grid for better readability
ax1.grid(True)
# Add legends for both plots
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
# Save the plot as a PNG file
plt.savefig(f"{output_dir}/steel_plant_consumption_marginal_cost_flexibility.png")
# Show the plot
plt.tight_layout() # Adjust layout to avoid clipping of labels
plt.show()
Explanation
Saving the DataFrame:
The clearing price data is saved to a CSV file with the following line:
[ ]:
# Load the market_meta CSV file for Use Case 2
market_meta_uc2 = pd.read_csv(f"{output_dir}/market_meta.csv")
# Convert 'time' column to datetime if it's not already in the correct format
market_meta_uc2["time"] = pd.to_datetime(market_meta_uc2["time"])
# ---- Save the DataFrame for future use ----
# Save the clearing price data as a CSV for future comparison
market_meta_uc2[["time", "price"]].to_csv(
"outputs/clearing_price_use_case_2.csv", index=False
)
print("Saved the clearing price data of Use Case 2 to CSV.")
# ---- Plotting ----
# Create a Plotly figure for the clearing price
fig = go.Figure()
# Add a scatter plot trace for the price over time
fig.add_trace(
go.Scatter(
x=market_meta_uc2["time"],
y=market_meta_uc2["price"],
mode="lines",
name="Clearing Price - Flexibility",
line=dict(color="blue"),
)
)
# Set the layout for the figure
fig.update_layout(
title="Clearing Price with Flexibility Over Time",
xaxis_title="Time",
yaxis_title="Price (EUR/MWh)",
xaxis=dict(showgrid=True),
yaxis=dict(showgrid=True),
)
# Display the figure
fig.show()
Explanation
Saving the DataFrame:
The clearing price data is saved to a CSV file with the following line:
[ ]:
market_meta_uc2[["time", "price"]].to_csv(
"outputs/clearing_price_use_case_2.csv", index=False
)
4. Setting up grid network with infrastructure#
Since we have added all generators, demand units and dsm units as loads, we replace the timeseries of demands, dsm units and dispatches from generators as one file
[ ]:
# Reading the dispatch data from the output results
market_dispatch = pd.read_csv(f"{output_dir}/market_dispatch.csv", parse_dates=True)
market_dispatch.head()
[ ]:
# cleaning dispatch data from the simulation to feed it to the PyPSA network
p_set = market_dispatch.pivot(index="datetime", columns="unit_id", values="power")
p_set = p_set.rename_axis("snapshot", axis="index")
p_set.index = pd.to_datetime(p_set.index)
p_set.index = p_set.index - pd.Timedelta(hours=1)
p_set = p_set.fillna(0)
p_set = np.abs(p_set)
p_set.head(3)
[ ]:
# Replacing p_set values in the same network which was created for Use case 1
network.loads_t.p_set = p_set
network.loads_t.p_set.head()
5. Congestion identification#
Solving linear power flow to identify congestion in lines
[ ]:
network.lpf()
[ ]:
congestion_df = pd.DataFrame(
{
"line_loading": np.abs(network.lines_t.p0.values.flatten()),
"line_name": network.lines.index.repeat(len(network.snapshots)),
"timestamp": pd.Series(network.snapshots).repeat(len(network.lines)),
}
)
[ ]:
s_nom_values = network.lines.s_nom
congestion_df["s_nom"] = congestion_df["line_name"].map(s_nom_values)
s_max_pu_values = network.lines.s_max_pu
congestion_df["s_max_pu"] = congestion_df["line_name"].map(s_max_pu_values)
congestion_df["congestion_status"] = congestion_df["line_loading"] > (
congestion_df["s_nom"] * congestion_df["s_max_pu"]
)
congested_lines = congestion_df[congestion_df["congestion_status"]]
congested_lines
The next plot displays the line loading at a selected snapshot for Use Case 2. Blue indicates loading at or below the line limit; red indicates an overload. Compare the calculated loading rather than assuming a particular snapshot is congested.
[ ]:
# Creating a plot to see the nodes and congestion in the lines
now = network.snapshots[12]
loading = network.lines_t.p0.loc[now] / (network.lines.s_nom * network.lines.s_max_pu)
congestion_threshold = 1
line_colors = np.where(abs(loading) > congestion_threshold, "red", "blue")
# Create the figure and the axis using Cartopy's PlateCarree projection
fig, ax = plt.subplots(figsize=(4, 4), subplot_kw={"projection": ccrs.PlateCarree()})
# Plot the network using the built-in network plot function
network.plot(
ax=ax,
line_colors=line_colors,
title="Line Loading",
bus_sizes=5e-2, # Size of bus markers
bus_alpha=1, # Transparency of bus markers
)
# Adjust layout and display the plot
fig.tight_layout()
plt.show()
6. Comparison of Electricity Consumption and Clearing Prices: Use Case 1 vs Use Case 2#
In this section, we will compare the results of the electricity consumption profile and clearing prices between Use Case 1 (without flexibility) and Use Case 2 (with flexibility). This comparison will provide insights into how enabling flexibility affects the power consumption and market-clearing prices for the steel plant.
Electricity Consumption Profile Comparison
We first compare the electricity consumption profile of the steel plant (A360) for both use cases. The goal is to observe the changes in the plant’s consumption when flexibility is enabled.
[ ]:
# ---- Load the CSV files for both use cases ----
# Use Case 1
uc1_orders = pd.read_csv("outputs/steel_plant_market_orders_use_case_1.csv")
# Use Case 2
uc2_orders = pd.read_csv("outputs/steel_plant_market_orders_use_case_2.csv")
# Convert 'time' column to datetime for both use cases
uc1_orders["time"] = pd.to_datetime(uc1_orders["time"])
uc2_orders["time"] = pd.to_datetime(uc2_orders["time"])
# Make the volume values positive for both use cases
uc1_orders["volume"] = uc1_orders["volume"].abs()
uc2_orders["volume"] = uc2_orders["volume"].abs()
# Compare the full optimized schedules as well as the cleared-market window.
# The framework uses a one-hour simulation time step in these scenarios.
profile_comparison = pd.concat([profile_uc1, profile_uc2], axis=1)
print("Optimized schedule over the full simulation horizon:")
print(f"Baseline energy: {profile_comparison['Baseline'].sum():.1f} MWh")
print(f"Flexible energy: {profile_comparison['Flexible'].sum():.1f} MWh")
print(
"Hours with different consumption: "
f"{(profile_comparison['Baseline'] - profile_comparison['Flexible']).abs().gt(0.01).sum()}"
)
# ---- Plotting Comparison ----
# Use Seaborn to set plot style
sns.set(style="whitegrid")
# Create the plot for comparison with Seaborn and Matplotlib
plt.figure(figsize=(10, 6))
# Plot Use Case 1 data (solid line)
sns.lineplot(
x="time",
y="volume",
data=uc1_orders,
label="Power Consumption - Use Case 1",
color="b",
linestyle="-", # Solid line for Use Case 1
)
# Plot Use Case 2 data (dotted line)
sns.lineplot(
x="time",
y="volume",
data=uc2_orders,
label="Power Consumption - Use Case 2 (Flexibility)",
color="g",
linestyle="--", # Dotted line for Use Case 2
)
# Set plot title and labels
plt.title(
"Comparison of Electricity Consumption Profiles of the Steel Plant (A360)",
fontsize=14,
)
plt.xlabel("Time", fontsize=12)
plt.ylabel("Power (MW)", fontsize=12)
# Reduce the number of x-axis ticks to avoid crowding
plt.gca().xaxis.set_major_locator(plt.MaxNLocator(nbins=10))
# Rotate x-axis ticks for better readability
plt.xticks(rotation=45)
# Add a grid for better readability
plt.grid(True)
# Save the comparison plot as a PNG file
plt.savefig(f"{output_dir}/steel_plant_comparison_consumption.png")
# Show the plot
plt.tight_layout() # Adjust layout to avoid clipping of labels
plt.show()
Electricity consumption comparison
The chart compares accepted EOM demand over the hours cleared by both simulations. The flexible case uses the plant’s flexible optimized profile; the baseline uses its optimal profile. Both schedules cover the same full optimization horizon and the same steel-production target, but the market clears only part of that horizon, so the charted energy totals need not match. The price forecast used by the plant is illustrative and is not the market-clearing price.
To read the comparison, look for hours in which the flexible plant consumes more or less than the baseline. A higher or lower accepted volume in one hour does not by itself show the full amount shifted: inspect the complete optimized profiles as well as the market delivery window.
[ ]:
# Load the saved clearing price data for both use cases
df_price_uc1 = pd.read_csv("outputs/clearing_price_use_case_1.csv")
df_price_uc2 = pd.read_csv("outputs/clearing_price_use_case_2.csv")
# Convert 'time' to datetime for both datasets
df_price_uc1["time"] = pd.to_datetime(df_price_uc1["time"])
df_price_uc2["time"] = pd.to_datetime(df_price_uc2["time"])
# Plot both Use Case 1 and Use Case 2 clearing prices on the same plot
plt.figure(figsize=(10, 6))
# Plot Use Case 1
plt.plot(
df_price_uc1["time"],
df_price_uc1["price"],
label="Use Case 1 - Clearing Price",
color="b",
)
# Plot Use Case 2 (with flexibility)
plt.plot(
df_price_uc2["time"],
df_price_uc2["price"],
label="Use Case 2 - Clearing Price (Flexibility)",
color="g",
)
# Set plot title and labels
plt.title("Clearing Price Comparison: Use Case 1 vs Use Case 2", fontsize=14)
plt.xlabel("Time", fontsize=12)
plt.ylabel("Price (EUR/MWh)", fontsize=12)
# Rotate x-axis ticks for better readability
plt.xticks(rotation=45)
# Add a grid for better readability
plt.grid(True)
# Add a legend to differentiate between Use Case 1 and Use Case 2
plt.legend()
# Save the comparison plot as a PNG file
plt.savefig(f"{output_dir}/clearing_price_comparison.png")
# Show the plot
plt.tight_layout() # Adjust layout to avoid clipping of labels
plt.show()
Clearing price comparison
Both simulations use the same synthetic demand, generation fleet, fuel prices and renewable availability. Differences in their market prices result from their different accepted steel-plant bids and the merit order in each hour. They need not imply that flexibility reduces the price in every hour, or that the plant’s forecast matches the resulting market price.
The market results cover only the cleared delivery hours; the full optimized schedules above cover the simulation horizon. The example therefore illustrates the mechanism rather than a calibrated comparison of real market outcomes.
The clearing price is set by the market’s accepted supply and demand bids. A change in the steel plant’s demand can change which supply bid is marginal, but the size and direction of that effect depend on the rest of the system.
The comparison shows how the accepted demand profile and clearing prices change in this particular synthetic scenario. The optimized flexible profile is subject to the plant model’s cost tolerance; the example does not establish that flexibility always lowers market prices or total costs.
Use Case 3: Redispatch#
This separate example clears the day-ahead EOM and then runs redispatch for the same delivery periods. Power plants provide their day-ahead schedules, available output limits and marginal costs through a redispatch bidding strategy. The steel plant participates in the EOM, and its cleared demand is included as a fixed load in the redispatch network. The redispatch market role uses the two-node PyPSA network to select adjustments when a line is congested; the configuration uses pay-as-bid settlement.
The example illustrates the direction and volume of scheduled adjustments, including possible wind curtailment and increased southern generation. It is a simplified cost-based model, not a complete implementation of German Redispatch 2.0 or a guarantee of operational security. The optimizer checks the 24-hour batch for congestion and, if any hour is congested, optimizes the whole batch; it can therefore also adjust uncongested hours. It does not enforce inter-hour ramp constraints.
The sequence is:
The EOM clears generation and demand for the delivery periods.
Participants submit redispatch information, including their location and available operating range.
The network operator uses the network model and submitted costs to determine scheduled changes to generation and demand where applicable.
The results show how those scheduled changes affect the congested network.
Reducing output on the exporting side and increasing it on the importing side can reduce the flow over a constrained line. The example uses the framework’s existing redispatch mechanism to demonstrate this principle.
1. Prepare input files#
Use Case 3 copies the shared inputs to inputs/redispatch/tutorial_10 and adjusts the scenario independently. Wind generation remains in the north with a small local load; solar, hydro, biomass, conventional generation and the steel plant are placed in the south with the larger load. Onshore wind capacity is increased to 220 MW. When northern wind generation exceeds local demand and the 200 MW line capacity, redispatch can curtail wind and increase southern generation.
The conventional fleet contains lignite, hard coal and gas rather than nuclear. All power plants have a minimum output of zero; this is a simplification, not the technical minimum of an individual thermal plant. Fuel prices, plant parameters, demand, weather profiles and the network are illustrative. The 2019 timestamps are retained for compatibility with the earlier examples; this is not a historical reconstruction or a calibrated representation of a specific year.
[ ]:
# ---- Prepare separate inputs for the Use Case 3 redispatch demo ----
# Keep the availability profiles and other redispatch changes out of the
# original scenario, including when the notebook is run more than once.
from shutil import copyfile
source_scenario_path = Path(input_dir) / scenario
redispatch_input_dir = Path(input_dir) / "redispatch"
scenario_path = redispatch_input_dir / scenario
scenario_path.mkdir(parents=True, exist_ok=True)
for filename in (
"powerplant_units.csv",
"demand_units.csv",
"demand_df.csv",
"industrial_dsm_units.csv",
"buses.csv",
"lines.csv",
"fuel_prices_df.csv",
"forecasts_df.csv",
):
copyfile(source_scenario_path / filename, scenario_path / filename)
# ---- Power plant units ----
powerplant_units = pd.read_csv(f"{scenario_path}/powerplant_units.csv")
# Reuse the shared conventional fleet and fuel prices from the first two cases.
# Only the redispatch scenario's locations and capacities are changed below.
# Place wind in the north and the remaining plants in the south.
node_by_name = {
"Wind onshore": "north",
"Wind offshore": "north",
"Solar": "south",
"Hydro": "south",
"Biomass": "south",
"Lignite": "south",
"Hard coal": "south",
"Gas OCGT": "south",
"Gas CCGT": "south",
}
# Wind capacity is scaled up for this small, illustrative congestion scenario.
max_power_by_name = {
"Wind onshore": 220,
"Wind offshore": 100,
"Solar": 50,
"Hydro": 30,
"Biomass": 50,
"Lignite": 100,
"Hard coal": 100,
"Gas OCGT": 100,
"Gas CCGT": 400,
}
powerplant_units["node"] = powerplant_units["name"].map(node_by_name)
powerplant_units["max_power"] = powerplant_units["name"].map(max_power_by_name)
# every plant also bids into the redispatch market
powerplant_units["bidding_redispatch"] = "powerplant_energy_naive_redispatch"
powerplant_units.to_csv(f"{scenario_path}/powerplant_units.csv", index=False)
# ---- Demand units ----
demand_units = pd.read_csv(f"{scenario_path}/demand_units.csv")
demand_units["bidding_redispatch"] = "demand_energy_naive_redispatch"
demand_units.to_csv(f"{scenario_path}/demand_units.csv", index=False)
# ---- Demand time series: small in the north, large in the south ----
uc3_index = pd.date_range(
start="2019-01-01 00:00", end="2019-01-05 00:00", freq="15min"
)
hour_of_day = uc3_index.hour + uc3_index.minute / 60
daily_shape = 0.5 + 0.5 * np.sin(2 * np.pi * (hour_of_day - 9) / 24)
demand_df_uc3 = pd.DataFrame(
{
"demand_EOM1": 30
+ 20 * daily_shape, # north: small local load -> exports its wind
"demand_EOM2": 510 + 80 * daily_shape, # south: the load centre
},
index=uc3_index,
)
demand_df_uc3.to_csv(f"{scenario_path}/demand_df.csv")
# Illustrative capacity factors, not historical weather data. The profiles
# cover the full simulation and use the exact power plant names as columns.
elapsed_hours = np.arange(len(uc3_index)) / 4
solar_shape = np.where(
(hour_of_day >= 8) & (hour_of_day < 16),
np.sin(np.pi * (hour_of_day - 8) / 8),
0.0,
)
availability_df_uc3 = pd.DataFrame(
{
"Wind onshore": 0.64
+ 0.22 * np.sin(2 * np.pi * elapsed_hours / 48)
+ 0.08 * np.sin(2 * np.pi * elapsed_hours / 24),
"Wind offshore": 0.72 + 0.16 * np.sin(2 * np.pi * (elapsed_hours + 6) / 48),
"Solar": solar_shape,
},
index=uc3_index,
).clip(lower=0, upper=1)
availability_df_uc3.to_csv(f"{scenario_path}/availability_df.csv")
print(
"Use Case 3 grid reconfigured: wind in the north, "
"other plants and most demand in the south."
)
display(powerplant_units[["name", "node", "max_power", "additional_cost"]])
2. Include the steel plant as a fixed redispatch load#
The steel plant submits its flexible optimized demand to the day-ahead market, as in Use Case 2. For redispatch, the network needs the cleared day-ahead demand at the plant’s south-node connection. A notebook-local strategy submits that schedule as a fixed load; the steel plant does not offer an adjustment to its demand in this example.
The redispatch network reads its load list separately from the scenario’s market participants. The next cell creates a separate grid input directory and adds the steel plant to that network’s load list. It does not create a second market participant or add the demand twice. The original inputs for Use Cases 1 and 2 remain unchanged.
[ ]:
# Keep the steel plant in the EOM and register its cleared demand for redispatch.
dsm_path = scenario_path / "industrial_dsm_units.csv"
industrial_dsm_units_uc3 = pd.read_csv(dsm_path)
steel_rows = industrial_dsm_units_uc3["name"] == "A360"
steel_entry = steel_rows & (industrial_dsm_units_uc3["technology"] == "electrolyser")
industrial_dsm_units_uc3.loc[steel_entry, "bidding_EOM"] = "tutorial_flexible_dsm"
industrial_dsm_units_uc3.loc[steel_entry, "bidding_redispatch"] = (
"tutorial_fixed_steel_load"
)
industrial_dsm_units_uc3.to_csv(dsm_path, index=False)
# The redispatch grid has its own load list; do not add the steel plant to the
# scenario's demand_units.csv, which would create a duplicate market unit.
grid_path = scenario_path / "redispatch_grid"
grid_path.mkdir(parents=True, exist_ok=True)
for filename in ("buses.csv", "lines.csv", "powerplant_units.csv", "demand_units.csv"):
copyfile(scenario_path / filename, grid_path / filename)
grid_loads = pd.read_csv(grid_path / "demand_units.csv")
steel_load = grid_loads.iloc[0].copy()
steel_load["name"] = "A360"
steel_load["node"] = industrial_dsm_units_uc3.loc[steel_entry, "node"].iloc[0]
grid_loads = pd.concat([grid_loads, pd.DataFrame([steel_load])], ignore_index=True)
grid_loads.to_csv(grid_path / "demand_units.csv", index=False)
class TutorialFixedSteelLoad(MinMaxStrategy):
"""Report the cleared EOM schedule as a fixed load for redispatch."""
def calculate_bids(self, unit, market_config, product_tuples, **kwargs):
# Only generator orders provide redispatch flexibility in this model.
# The remaining numeric fields satisfy the redispatch order format.
return [
{
"start_time": start,
"end_time": end,
"only_hours": only_hours,
"price": 0.0,
"volume": float(unit.outputs["energy"].at[start]),
"min_power": 0.0,
"max_power": 0.0,
"p_nom": 1.0,
"node": unit.node,
}
for start, end, only_hours in product_tuples
]
3. Create the market configuration#
The configuration uses the same 24 hourly delivery products in both markets. The EOM opens first and clears after 20 hours; redispatch opens 21 hours after the EOM and clears two hours later, before the first delivery. The redispatch optimizer receives the day-ahead schedules and uses submitted marginal costs with pay-as-bid settlement.
Both markets open daily. Each offers 24 one-hour products, and the different opening times and first-delivery offsets align those products. The additional redispatch fields provide the node and operating limits needed by the network model; network_path identifies the separate grid inputs, including the fixed steel load and solver_name selects the optimizer. backup_marginal_cost sets the cost of the model’s backup option.
[ ]:
# Define the configuration dictionary
config = {
"redispatch_case": {
"start_date": "2019-01-01 00:00",
"end_date": "2019-01-04 23:00",
"time_step": "1h",
"save_frequency_hours": 24,
"markets_config": {
"EOM": {
"start_date": "2019-01-01 00:00",
"operator": "EOM_operator",
"product_type": "energy",
"products": [
{
"duration": "1h", # Each product lasts for 1 hour
"count": 24, # Number of products per day (24 hours)
"first_delivery": "24h", # First delivery is 24 hours after the market opens
}
],
"opening_frequency": "24h", # Market opens once every 24 hours
"opening_duration": "20h", # EOM clears 20 hours after opening
"volume_unit": "MWh", # Market volume is measured in MWh
"maximum_bid_volume": 100000, # Maximum bid volume allowed
"maximum_bid_price": 3000, # Maximum allowed bid price
"minimum_bid_price": -500, # Minimum allowed bid price
"price_unit": "EUR/MWh", # Bid price unit is EUR per MWh
"market_mechanism": "pay_as_clear", # Pay-as-clear mechanism
},
"redispatch": {
"start_date": "2019-01-01 21:00",
"operator": "network_operator",
"product_type": "energy",
"products": [
{
"duration": "1h",
"count": 24,
"first_delivery": "3h",
}
],
"opening_frequency": "24h",
"opening_duration": "2h",
"volume_unit": "MWh",
"maximum_bid_volume": 100000,
"maximum_bid_price": 3000,
"minimum_bid_price": -500,
"price_unit": "EUR/MWh",
"market_mechanism": "redispatch",
"additional_fields": ["node", "min_power", "max_power"],
"param_dict": {
"network_path": "redispatch_grid",
"solver_name": "highs",
"payment_mechanism": "pay_as_bid",
"backup_marginal_cost": 10000,
},
},
},
}
}
# Define the path for the config file
config_path = scenario_path / "config.yaml"
# Save the configuration to a YAML file
with open(config_path, "w") as file:
yaml.dump(config, file, sort_keys=False)
print(f"Configuration YAML file has been saved to '{config_path}'.")
4. Run the redispatch simulation#
The notebook loads the separate scenario and runs the simulation. It also schedules a final dispatch export after the last redispatch delivery ends, so the unit operators write the remaining delivered hours even when no later market clearing occurs.
[ ]:
# Create the World instance
world = World(database_uri=db_uri, export_csv_path=csv_path)
world.bidding_strategies = dict(world.bidding_strategies)
world.bidding_strategies["tutorial_flexible_dsm"] = TutorialFlexibleDsmStrategy
world.bidding_strategies["tutorial_fixed_steel_load"] = TutorialFixedSteelLoad
# Load the scenario with Redispatch setup
load_scenario_folder(
world,
inputs_path=redispatch_input_dir,
scenario=scenario, # Folder where our scenario inputs are located
study_case="redispatch_case", # Config for Redispatch we defined earlier
)
# Dispatch is normally exported when a market clears. Schedule one final
# export after the last redispatch delivery so the final hours are not missed.
from assume.common.utils import datetime2timestamp, get_available_products
redispatch_market = world.markets["redispatch"]
longest_delivery = max(
product.first_delivery + product.duration * product.count
for product in redispatch_market.market_products
)
last_opening = redispatch_market.opening_hours.before(
world.end - longest_delivery, inc=True
)
if last_opening is None:
raise ValueError("The redispatch market has no opening within the simulation.")
final_delivery_end = max(
end
for _, end, _ in get_available_products(
redispatch_market.market_products, last_opening
)
)
async def export_remaining_dispatch(operator):
operator.write_actual_dispatch("energy")
def schedule_final_dispatch_export():
# This callback runs on the simulation event loop, where scheduling is safe.
for operator in world.unit_operators.values():
operator.context.schedule_timestamp_task(
export_remaining_dispatch(operator), datetime2timestamp(final_delivery_end)
)
world.loop.call_soon(schedule_final_dispatch_export)
world.run()
print("Simulation with redispatch completed.")
5. Inspect the redispatch results#
market_orders.csv contains the cleared orders, while market_dispatch.csv contains their exported market dispatch. The chart and table below aggregate the cleared redispatch adjustments over the complete delivery horizon. They are scheduled adjustments; the separate unit_dispatch.csv records executed unit output. The steel plant contributes its fixed cleared demand to the network but is not included in the power-plant adjustment chart.
[ ]:
outputs_path = "outputs/tutorial_10_redispatch_case"
market_dispatch_total = pd.read_csv(
f"{outputs_path}/market_dispatch.csv", parse_dates=True
)
market_dispatch_total.head()
[ ]:
# Prepare the exported redispatch data using its delivery-start timestamps.
redispatches = market_dispatch_total[
market_dispatch_total["market_id"].str.contains("redispatch", case=False, na=False)
]
redisp_p_set = redispatches.pivot(index="datetime", columns="unit_id", values="power")
redisp_p_set = redisp_p_set.drop(columns=["demand_EOM1", "demand_EOM2"])
redisp_p_set = redisp_p_set.rename_axis("snapshot", axis="index")
redisp_p_set.index = pd.to_datetime(redisp_p_set.index)
redisp_p_set = redisp_p_set.fillna(0)
redisp_p_set.sort_index(inplace=True)
redisp_p_set.head(3)
[ ]:
# Use cleared orders to include the full redispatch horizon. The accepted
# volume is a power adjustment in MW; multiply by product duration for MWh.
redispatch_orders = pd.read_csv(
f"{outputs_path}/market_orders.csv", parse_dates=["start_time", "end_time"]
)
redispatch_orders = redispatch_orders.loc[
redispatch_orders["market_id"] == "redispatch"
].copy()
power_plant_info = pd.read_csv(f"{scenario_path}/powerplant_units.csv").set_index(
"name"
)
redispatch_orders = redispatch_orders.loc[
redispatch_orders["unit_id"].isin(power_plant_info.index)
].copy()
duration_hours = (
redispatch_orders["end_time"] - redispatch_orders["start_time"]
).dt.total_seconds() / 3600
redispatch_orders["energy_mwh"] = redispatch_orders["accepted_volume"] * duration_hours
# Aggregate upward and downward actions separately, including plants with
# no accepted redispatch so that they are visible in the comparison.
redispatch_summary = power_plant_info[["node", "technology"]].rename(
columns={"node": "Node", "technology": "Technology"}
)
redispatch_summary["Upward / ramp-up (MWh)"] = (
redispatch_orders["energy_mwh"]
.clip(lower=0)
.groupby(redispatch_orders["unit_id"])
.sum()
.reindex(redispatch_summary.index, fill_value=0)
)
redispatch_summary["Downward / curtailment (MWh)"] = (
redispatch_orders["energy_mwh"]
.clip(upper=0)
.groupby(redispatch_orders["unit_id"])
.sum()
.reindex(redispatch_summary.index, fill_value=0)
)
redispatch_summary["Net (MWh)"] = (
redispatch_summary["Upward / ramp-up (MWh)"]
+ redispatch_summary["Downward / curtailment (MWh)"]
)
# Horizontal bars show curtailment to the left and upward regulation to the right.
plot_data = redispatch_summary.copy()
plot_data["activity"] = (
plot_data["Upward / ramp-up (MWh)"] - plot_data["Downward / curtailment (MWh)"]
)
plot_data = plot_data.sort_values("activity", ascending=True)
labels = [
f"{name} ({row['Technology']}, {row['Node']})" for name, row in plot_data.iterrows()
]
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(
labels,
plot_data["Downward / curtailment (MWh)"],
color="#d95f50",
label="Downward / curtailment",
)
ax.barh(
labels,
plot_data["Upward / ramp-up (MWh)"],
color="#32865b",
label="Upward regulation",
)
ax.axvline(0, color="black", linewidth=0.8)
ax.set_title("Cleared redispatch by power plant")
ax.set_xlabel("Redispatch energy over the cleared horizon (MWh)")
ax.set_ylabel("Power plant (technology, node)")
ax.grid(axis="x", alpha=0.25)
ax.set_axisbelow(True)
ax.legend()
fig.tight_layout()
plt.show()
[ ]:
# Summarize the same cleared orders and full horizon used in the chart above.
summary_table = redispatch_summary.copy()
summary_table.loc["TOTAL", ["Node", "Technology"]] = ["", "ALL UNITS"]
for column in [
"Upward / ramp-up (MWh)",
"Downward / curtailment (MWh)",
"Net (MWh)",
]:
summary_table.loc["TOTAL", column] = redispatch_summary[column].sum()
print("Cleared redispatch energy by power plant (MWh):")
display(summary_table.round(1))
Interpreting the redispatch results: Bars to the left show generation reduced from the day-ahead schedule; bars to the right show generation increased. Plants with no accepted redispatch remain visible. The chart and table sum each direction separately over the cleared products.
These are scheduled market adjustments. Executed unit output can differ when operational constraints are applied later, so a balanced cleared schedule alone does not establish that the executed schedule is physically balanced.
For the intended congestion pattern, look for downward adjustments of northern wind and upward adjustments of southern dispatchable generation. The table reports each plant’s total in MWh, so it is useful for comparing the size of the adjustments across the modeled delivery periods. Actual participation and totals depend on the input profiles and clearing results.
Early gas reductions can occur because the day-ahead bids reflect initial ramp limits, while the redispatch optimization does not enforce inter-hour ramps. When any hour in a 24-hour batch is congested, it optimizes the whole batch, including uncongested hours.