Skip to content

Synthetic test data

The examples in the API reference run on this platform, with the shared names of StudyManager References.

testing

Synthetic scenarios for tests and examples, without an external platform package.

The platform is also the reference implementation of a platform package: flag specs with variants, parameters and memberships, a flag family, derived flags, area and border layers, availability from a source inventory, and default attributes.

What DummyDataset gives for the default DummyScenario:

  • Model flags Country.Model, Node.Model, Line.Model, Generator.Model and Demand.Model, with points for the nodes and square polygons for the countries, so map code runs without geodata.
  • Time series: node price, demand per product (total, hourly, quarter_hourly), both with the parameter solution, generation, line flow Line.Results.flow_{side}_{direction} and line capacity. The source has the total demand, the sent net flow and the up capacity. The other variants derive from them through parent_dataset.fetch, so an override of a source variant reaches them.
  • Derived flags that list their inputs in INPUT_FLAGS: line loading, node demand, and generation per node and fuel (a flag family).
  • The area layer Country and the border layer CountryBorder, with area price, demand and generation, and border flows, capacities and price spread.
  • Availability: a spec reads one raw table (SPEC_TABLE) or derives from input flags (INPUT_FLAGS). missing_tables of a DummyScenario removes raw tables, so the flags that need them are unavailable.

make_dummy_study() builds a ready study with comparisons; examples/quickstart.py runs on it.

Examples:

>>> dataset = DummyDataset(DummyScenario(name='base', days=2))
>>> dataset.fetch('Country.Results.price').columns.tolist()
['C1', 'C2']

DummyConfig dataclass

Bases: DatasetConfig

Config of DummyDataset.

Attributes:

Name Type Description
price_offset float

Value in EUR/MWh added to every node price. Default: 0.0.

Source code in src/mesqual/testing/dataset.py
45
46
47
48
49
50
51
52
53
@dataclass
class DummyConfig(DatasetConfig):
    """Config of `DummyDataset`.

    Attributes:
        price_offset: Value in EUR/MWh added to every node price. Default: 0.0.
    """

    price_offset: float = config_field(0.0, 'Value in EUR/MWh added to every node price.')

DummyDataset

Bases: PlatformDataset[DummyInterpreter, DummyConfig, str, FlagIndex]

Platform dataset of one synthetic scenario.

Flags: the model tables 'Country.Model', 'Node.Model', 'Line.Model', 'Generator.Model' and 'Demand.Model'; time series of node prices, demand, generation, line flows and line capacities; the derived line loading, node demand and generation per node and fuel; the area layer 'Country' on 'Node.Model' and the border layer 'CountryBorder' on 'Line.Model'. describe_class_flags() lists each spec with its unit, variants, parameters and description.

A flag whose raw table the scenario lists in missing_tables is unavailable, and so is each flag that reads it. fetch raises FlagUnavailableError, a ValueError, for it. Without the table 'countries', the geometry columns of the border model are NaN.

Default attributes: 'first_date', 'last_date' and 'days' from the scenario. Explicit attributes win.

Parameters:

Name Type Description Default
scenario DummyScenario

The scenario spec.

required
name str | None

Dataset name. Default: the scenario name.

None
attributes dict | None

Extra attributes.

None
cache Cache | None

Optional cache of fetch results.

None
config DummyConfig | None

Optional instance config.

None

Examples:

>>> from mesqual.testing import DummyScenario
>>> dataset = DummyDataset(DummyScenario(name='base', days=3))
>>> prices = dataset.fetch('Node.Results.price')
Source code in src/mesqual/testing/dataset.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
class DummyDataset(PlatformDataset[DummyInterpreter, DummyConfig, str, FlagIndex]):
    """Platform dataset of one synthetic scenario.

    Flags: the model tables 'Country.Model', 'Node.Model', 'Line.Model',
    'Generator.Model' and 'Demand.Model'; time series of node prices,
    demand, generation, line flows and line capacities; the derived line
    loading, node demand and generation per node and fuel; the area layer
    'Country' on 'Node.Model' and the border layer 'CountryBorder' on
    'Line.Model'. `describe_class_flags()` lists each spec with its unit,
    variants, parameters and description.

    A flag whose raw table the scenario lists in `missing_tables` is
    unavailable, and so is each flag that reads it. `fetch` raises
    `FlagUnavailableError`, a `ValueError`, for it. Without the table
    'countries', the geometry columns of the border model are NaN.

    Default attributes: 'first_date', 'last_date' and 'days' from the scenario.
    Explicit attributes win.

    Args:
        scenario: The scenario spec.
        name: Dataset name. Default: the scenario name.
        attributes: Extra attributes.
        cache: Optional cache of fetch results.
        config: Optional instance config.

    Examples:
        >>> from mesqual.testing import DummyScenario
        >>> dataset = DummyDataset(DummyScenario(name='base', days=3))
        >>> prices = dataset.fetch('Node.Results.price')
    """

    SOURCE_TYPE: ClassVar[type[DummySource]] = DummySource

    def __init__(
        self,
        scenario: DummyScenario,
        name: str | None = None,
        attributes: dict | None = None,
        cache: Cache | None = None,
        config: DummyConfig | None = None,
    ):
        self.scenario = scenario
        self.source = self.SOURCE_TYPE(scenario)
        super().__init__(
            name=name or scenario.name,
            attributes=attributes,
            cache=cache,
            config=config,
            source=self.source,
        )

    def build_source_inventory(self) -> DummyInventory:
        """Return the inventory of the synthetic source: its fingerprint and raw tables."""
        return self.source.inventory

    def _default_attributes(self) -> dict:
        return {
            'first_date': self.scenario.first_day.strftime('%Y-%m-%d'),
            'last_date': self.scenario.last_day.strftime('%Y-%m-%d'),
            'days': self.scenario.days,
        }

    @classmethod
    def get_config_type(cls) -> type[DummyConfig]:
        """Return `DummyConfig`."""
        return DummyConfig

    @classmethod
    def get_child_dataset_type(cls) -> type[DummyInterpreter]:
        """Return `DummyInterpreter`, the base of all interpreters of this dataset."""
        return DummyInterpreter

build_source_inventory

build_source_inventory() -> DummyInventory

Return the inventory of the synthetic source: its fingerprint and raw tables.

Source code in src/mesqual/testing/dataset.py
190
191
192
def build_source_inventory(self) -> DummyInventory:
    """Return the inventory of the synthetic source: its fingerprint and raw tables."""
    return self.source.inventory

get_config_type classmethod

get_config_type() -> type[DummyConfig]

Return DummyConfig.

Source code in src/mesqual/testing/dataset.py
201
202
203
204
@classmethod
def get_config_type(cls) -> type[DummyConfig]:
    """Return `DummyConfig`."""
    return DummyConfig

get_child_dataset_type classmethod

get_child_dataset_type() -> type[DummyInterpreter]

Return DummyInterpreter, the base of all interpreters of this dataset.

Source code in src/mesqual/testing/dataset.py
206
207
208
209
@classmethod
def get_child_dataset_type(cls) -> type[DummyInterpreter]:
    """Return `DummyInterpreter`, the base of all interpreters of this dataset."""
    return DummyInterpreter

DummyPeriodDataset

Bases: DummyDataset

A DummyDataset with a time level of (run, period) tuples instead of a DatetimeIndex.

It inherits the interpreters of DummyDataset. See DummyPeriodSource for the run and period numbers.

Source code in src/mesqual/testing/dataset.py
599
600
601
602
603
604
605
606
class DummyPeriodDataset(DummyDataset):
    """A `DummyDataset` with a time level of (run, period) tuples instead of a DatetimeIndex.

    It inherits the interpreters of `DummyDataset`. See `DummyPeriodSource` for
    the run and period numbers.
    """

    SOURCE_TYPE: ClassVar[type[DummySource]] = DummyPeriodSource

DummyNetwork

Model tables of a synthetic network.

Countries are squares side by side from west to east. Nodes are placed round robin in the countries, and each node lies inside the square of its country. Node k connects by line to node k-1 and to node k-2, in this order. Generator k and demand k sit at node k // 2, two generators and two demands per node. More nodes, lines, generators or demands only append rows, so existing rows stay the same.

Parameters:

Name Type Description Default
scenario DummyScenario

The scenario spec.

required
Source code in src/mesqual/testing/network.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class DummyNetwork:
    """Model tables of a synthetic network.

    Countries are squares side by side from west to east. Nodes are placed round
    robin in the countries, and each node lies inside the square of its country.
    Node k connects by line to node k-1 and to node k-2, in this order. Generator
    k and demand k sit at node k // 2, two generators and two demands per node.
    More nodes, lines, generators or demands only append rows, so existing rows
    stay the same.

    Args:
        scenario: The scenario spec.
    """

    COUNTRY_SIZE_DEG = 4.0
    COUNTRY_ORIGIN = (5.0, 46.0)
    FUELS = ('nuclear', 'coal', 'gas', 'wind', 'solar')
    SECTORS = ('industry', 'households', 'services')
    LINE_CAPACITY_MW = 1000.0
    GENERATOR_CAPACITY_MW = 800.0
    ORPHAN_NODE = 'N0'
    GENERATORS_PER_NODE = 2
    DEMANDS_PER_NODE = 2

    def __init__(self, scenario: DummyScenario):
        self._scenario = scenario
        tables = {
            'countries': self._build_countries(),
            'nodes': self._build_nodes(),
            'lines': self._build_lines(),
            'generators': self._build_generators(),
            'demands': self._build_demands(),
        }
        tables = self._remove_objects(tables, scenario.removed_objects)
        self.tables: dict[str, pd.DataFrame] = self._apply_text_changes(tables, scenario.text_changes)

    @property
    def countries(self) -> pd.DataFrame:
        """Country table, index 'Country', columns name and geometry (square polygons)."""
        return self.tables['countries']

    @property
    def nodes(self) -> pd.DataFrame:
        """Node table, index 'Node', columns country, voltage, base_price and location (points)."""
        return self.tables['nodes']

    @property
    def lines(self) -> pd.DataFrame:
        """Line table, index 'Line', columns node_from, node_to, capacity and voltage."""
        return self.tables['lines']

    @property
    def generators(self) -> pd.DataFrame:
        """Generator table, index 'Generator', columns node, fuel and capacity."""
        return self.tables['generators']

    @property
    def demands(self) -> pd.DataFrame:
        """Demand table, index 'Demand', columns node, sector and base_demand."""
        return self.tables['demands']

    def _build_countries(self) -> pd.DataFrame:
        n = self._scenario.n_countries
        x0, y0 = self.COUNTRY_ORIGIN
        size = self.COUNTRY_SIZE_DEG
        return pd.DataFrame(
            {
                'name': [f'Country {i + 1}' for i in range(n)],
                'geometry': [box(x0 + i * size, y0, x0 + (i + 1) * size, y0 + size) for i in range(n)],
            },
            index=pd.Index([f'C{i + 1}' for i in range(n)], name='Country'),
        )

    def _build_nodes(self) -> pd.DataFrame:
        s = self._scenario
        rows = [self._node_row(i, i % s.n_countries) for i in range(s.n_nodes)]
        index = [f'N{i + 1}' for i in range(s.n_nodes)]
        if s.node_without_country:
            rows.append(self._node_row(-1, None))
            index.append(self.ORPHAN_NODE)
        return pd.DataFrame(rows, index=pd.Index(index, name='Node'))

    def _node_row(self, i: int, country_number: int | None) -> dict:
        x0, y0 = self.COUNTRY_ORIGIN
        size = self.COUNTRY_SIZE_DEG
        x_country = x0 + country_number * size if country_number is not None else x0 - size
        rank = i // self._scenario.n_countries
        return {
            'country': f'C{country_number + 1}' if country_number is not None else None,
            'voltage': 380.0 if i % 2 == 0 else 220.0,
            'base_price': 40.0 + 5.0 * i,
            'location': Point(
                x_country + size * (0.1 + 0.8 * (rank * 0.618 % 1)), y0 + size * (0.1 + 0.8 * (rank * 0.382 % 1))
            ),
        }

    def _build_lines(self) -> pd.DataFrame:
        pairs = self._line_pairs()
        return pd.DataFrame(
            {
                'node_from': [f'N{a + 1}' for a, _ in pairs],
                'node_to': [f'N{b + 1}' for _, b in pairs],
                'capacity': [self.LINE_CAPACITY_MW + 100.0 * i for i in range(len(pairs))],
                'voltage': [380.0 if i % 2 == 0 else 220.0 for i in range(len(pairs))],
            },
            index=pd.Index([f'L{i + 1}' for i in range(len(pairs))], name='Line'),
        )

    def _line_pairs(self) -> list[tuple[int, int]]:
        n = self._scenario.n_nodes
        pairs = [(k - step, k) for k in range(1, n) for step in (1, 2) if k - step >= 0]
        if self._scenario.n_lines > len(pairs):
            raise ValueError(f'{n} nodes support at most {len(pairs)} lines.')
        return pairs[: self._scenario.n_lines]

    def _build_generators(self) -> pd.DataFrame:
        s = self._scenario
        max_generators = self.GENERATORS_PER_NODE * s.n_nodes
        if s.n_generators > max_generators:
            raise ValueError(f'{s.n_nodes} nodes support at most {max_generators} generators.')
        return pd.DataFrame(
            {
                'node': [f'N{i // self.GENERATORS_PER_NODE + 1}' for i in range(s.n_generators)],
                'fuel': [self.FUELS[i % len(self.FUELS)] for i in range(s.n_generators)],
                'capacity': [self.GENERATOR_CAPACITY_MW + 100.0 * i for i in range(s.n_generators)],
            },
            index=pd.Index([f'G{i + 1}' for i in range(s.n_generators)], name='Generator'),
        )

    def _build_demands(self) -> pd.DataFrame:
        s = self._scenario
        max_demands = self.DEMANDS_PER_NODE * s.n_nodes
        if s.n_demands > max_demands:
            raise ValueError(f'{s.n_nodes} nodes support at most {max_demands} demands.')
        return pd.DataFrame(
            {
                'node': [f'N{i // self.DEMANDS_PER_NODE + 1}' for i in range(s.n_demands)],
                'sector': [self.SECTORS[i % len(self.SECTORS)] for i in range(s.n_demands)],
                'base_demand': [500.0 + 50.0 * i for i in range(s.n_demands)],
            },
            index=pd.Index([f'D{i + 1}' for i in range(s.n_demands)], name='Demand'),
        )

    @staticmethod
    def _remove_objects(tables: dict[str, pd.DataFrame], removed: tuple[str, ...]) -> dict[str, pd.DataFrame]:
        removed = set(removed)
        lines = tables['lines']
        generators = tables['generators']
        demands = tables['demands']
        nodes = tables['nodes'].drop(index=removed, errors='ignore')
        nodes.loc[nodes['country'].isin(removed), 'country'] = None
        return {
            'countries': tables['countries'].drop(index=removed, errors='ignore'),
            'nodes': nodes,
            'lines': lines.loc[
                ~lines.index.isin(removed) & ~lines.node_from.isin(removed) & ~lines.node_to.isin(removed)
            ],
            'generators': generators.loc[~generators.index.isin(removed) & ~generators.node.isin(removed)],
            'demands': demands.loc[~demands.index.isin(removed) & ~demands.node.isin(removed)],
        }

    @staticmethod
    def _apply_text_changes(
        tables: dict[str, pd.DataFrame],
        changes: tuple[tuple[str, str, str, str], ...],
    ) -> dict[str, pd.DataFrame]:
        tables = {key: table.copy() for key, table in tables.items()}
        for table_name, object_id, column, value in changes:
            if object_id not in tables[table_name].index:
                raise KeyError(f'Object {object_id!r} not in table {table_name!r}.')
            tables[table_name].loc[object_id, column] = value
        return tables

countries property

countries: DataFrame

Country table, index 'Country', columns name and geometry (square polygons).

nodes property

nodes: DataFrame

Node table, index 'Node', columns country, voltage, base_price and location (points).

lines property

lines: DataFrame

Line table, index 'Line', columns node_from, node_to, capacity and voltage.

generators property

generators: DataFrame

Generator table, index 'Generator', columns node, fuel and capacity.

demands property

demands: DataFrame

Demand table, index 'Demand', columns node, sector and base_demand.

DummyScenario dataclass

Spec of one synthetic scenario.

The generator derives the network, the model tables and the time series from these fields. Equal specs give equal data. The values of an object on a day depend only on the seed, the date, the object id and its model properties. So a scenario split into parts gives the same values as the unsplit scenario, and more objects (for example a higher n_nodes) or removed objects leave the other objects unchanged.

Attributes:

Name Type Description
name str

Scenario name. It becomes the dataset name.

start str

First day, for example '2024-03-30'.

days int

Number of days.

tz str | None

Time zone of the time index, or None for naive timestamps.

resolution str

Time step at the start, for example '60min'.

resolution_change tuple[str, str] | None

Optional (date, resolution): from that date on the series use the new time step, for example ('2024-03-31', '15min').

seed int

Seed of the random noise.

profile str

'daily' for realistic daily, weekly and seasonal profiles with noise (see DummySource), 'constant' for constant values, so that tests can compute expected values by hand.

demand_factor float

Factor on the demand of every demand object.

n_countries int

Number of countries, at least 1. Nodes are placed round robin in the countries, so a change of n_countries changes the country and the location of existing nodes.

n_nodes int

Number of nodes, placed round robin in the countries.

n_lines int

Number of lines. Line k connects the nodes in a fixed sequence: each new node connects to the previous node and to the node before that.

n_generators int

Number of generators. Generators k and k+1 (k even) sit at node k/2+1, so at most two generators per node. The fuels repeat in the order of DummyNetwork.FUELS; the default gives one generator per fuel.

n_demands int

Number of demands, placed like the generators: demands k and k+1 (k even) sit at node k/2+1. The default gives every node two demands.

node_without_country bool

If True, adds the node 'N0' without country, lines and demands.

removed_objects tuple[str, ...]

Object ids to remove. A removed node also removes its lines, generators and demands. The nodes of a removed country keep their place with no country (country is None).

text_changes tuple[tuple[str, str, str, str], ...]

(model table, object, column, value) entries that change text properties, for example ('generators', 'G1', 'fuel', 'gas').

missing_tables tuple[str, ...]

Raw tables the source does not provide, for example ('demand_load',). See DummySource.TABLES.

nan_gaps tuple[tuple[str, str], ...]

(start, end) windows where all time series values are NaN. The end is exclusive. A timestamp without offset is local time in tz; one with offset, for example '2024-10-27 02:00+01:00', selects one of the two hours of a DST fall-back day.

missing_rows tuple[tuple[str, str], ...]

(start, end) windows where the time series have no rows.

duplicate_rows int

Number of rows at the start of each time series that appear twice. The copies are appended at the end, so the raw index is not monotonic.

Source code in src/mesqual/testing/scenario.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
@dataclass(frozen=True)
class DummyScenario:
    """Spec of one synthetic scenario.

    The generator derives the network, the model tables and the time series from
    these fields. Equal specs give equal data. The values of an object on a day
    depend only on the seed, the date, the object id and its model properties. So
    a scenario split into parts gives the same values as the unsplit scenario,
    and more objects (for example a higher `n_nodes`) or removed objects leave
    the other objects unchanged.

    Attributes:
        name: Scenario name. It becomes the dataset name.
        start: First day, for example '2024-03-30'.
        days: Number of days.
        tz: Time zone of the time index, or None for naive timestamps.
        resolution: Time step at the start, for example '60min'.
        resolution_change: Optional (date, resolution): from that date on the
            series use the new time step, for example ('2024-03-31', '15min').
        seed: Seed of the random noise.
        profile: 'daily' for realistic daily, weekly and seasonal profiles with
            noise (see `DummySource`), 'constant' for constant values, so that
            tests can compute expected values by hand.
        demand_factor: Factor on the demand of every demand object.
        n_countries: Number of countries, at least 1. Nodes are placed round
            robin in the countries, so a change of `n_countries` changes the
            country and the location of existing nodes.
        n_nodes: Number of nodes, placed round robin in the countries.
        n_lines: Number of lines. Line k connects the nodes in a fixed sequence:
            each new node connects to the previous node and to the node before that.
        n_generators: Number of generators. Generators k and k+1 (k even) sit at
            node k/2+1, so at most two generators per node. The fuels repeat in
            the order of `DummyNetwork.FUELS`; the default gives one generator per fuel.
        n_demands: Number of demands, placed like the generators: demands k and
            k+1 (k even) sit at node k/2+1. The default gives every node two demands.
        node_without_country: If True, adds the node 'N0' without country, lines
            and demands.
        removed_objects: Object ids to remove. A removed node also removes its
            lines, generators and demands. The nodes of a removed country keep
            their place with no country (`country` is None).
        text_changes: (model table, object, column, value) entries that change
            text properties, for example ('generators', 'G1', 'fuel', 'gas').
        missing_tables: Raw tables the source does not provide, for example
            ('demand_load',). See `DummySource.TABLES`.
        nan_gaps: (start, end) windows where all time series values are NaN.
            The end is exclusive. A timestamp without offset is local time in
            `tz`; one with offset, for example '2024-10-27 02:00+01:00', selects
            one of the two hours of a DST fall-back day.
        missing_rows: (start, end) windows where the time series have no rows.
        duplicate_rows: Number of rows at the start of each time series that
            appear twice. The copies are appended at the end, so the raw index
            is not monotonic.
    """

    name: str = 'base'
    start: str = '2024-01-01'
    days: int = 2
    tz: str | None = 'Europe/Berlin'
    resolution: str = '60min'
    resolution_change: tuple[str, str] | None = None
    seed: int = 0
    profile: str = 'daily'
    demand_factor: float = 1.0
    n_countries: int = 2
    n_nodes: int = 4
    n_lines: int = 5
    n_generators: int = 5
    n_demands: int = 8
    node_without_country: bool = False
    removed_objects: tuple[str, ...] = ()
    text_changes: tuple[tuple[str, str, str, str], ...] = ()
    missing_tables: tuple[str, ...] = ()
    nan_gaps: tuple[tuple[str, str], ...] = ()
    missing_rows: tuple[tuple[str, str], ...] = ()
    duplicate_rows: int = 0

    PROFILES = ('daily', 'constant')

    def __post_init__(self):
        if self.days < 1:
            raise ValueError(f'days must be at least 1, got {self.days}.')
        if self.profile not in self.PROFILES:
            raise ValueError(f'Unknown profile {self.profile!r}. Use one of {self.PROFILES}.')
        if self.n_countries < 1:
            raise ValueError(f'n_countries must be at least 1, got {self.n_countries}.')
        if self.n_nodes < self.n_countries:
            raise ValueError('n_nodes must be at least n_countries.')

    @property
    def first_day(self) -> pd.Timestamp:
        """First day as a naive timestamp at midnight."""
        return pd.Timestamp(self.start).normalize()

    @property
    def last_day(self) -> pd.Timestamp:
        """Last day as a naive timestamp at midnight."""
        return self.first_day + pd.Timedelta(days=self.days - 1)

    @property
    def day_list(self) -> list[pd.Timestamp]:
        """All days of the scenario as naive timestamps at midnight."""
        return list(pd.date_range(self.first_day, self.last_day, freq='D'))

    def resolution_on(self, day: pd.Timestamp) -> str:
        """Time step of the series on the given day."""
        if self.resolution_change is not None:
            change_day, new_resolution = self.resolution_change
            if day >= pd.Timestamp(change_day):
                return new_resolution
        return self.resolution

    def timestamp(self, value: str) -> pd.Timestamp:
        """Parse a timestamp string in the time zone of the scenario.

        A string without offset is local time in `tz`. A string with offset is
        converted to `tz`.
        """
        parsed = pd.Timestamp(value)
        if parsed.tzinfo is None:
            return parsed.tz_localize(self.tz) if self.tz else parsed
        if self.tz is None:
            raise ValueError(f'Timestamp {value!r} has an offset, but the scenario has no time zone.')
        return parsed.tz_convert(self.tz)

    def replace(self, **changes) -> DummyScenario:
        """Return a copy with the given fields changed."""
        return dataclasses.replace(self, **changes)

    def split(self, at: str) -> tuple[DummyScenario, DummyScenario]:
        """Split the scenario into two parts with consecutive date ranges.

        Args:
            at: First day of the second part. It must lie after the first day
                and not after the last day.

        Returns:
            The parts '<name>.1' and '<name>.2'. Together they give the same data
                as the unsplit scenario.
        """
        split_day = pd.Timestamp(at).normalize()
        days_first = (split_day - self.first_day).days
        if not 0 < days_first < self.days:
            raise ValueError(f'Split day {at} must lie after {self.start} and within the {self.days} days.')
        first = self.replace(name=f'{self.name}.1', days=days_first)
        second = self.replace(name=f'{self.name}.2', start=split_day.strftime('%Y-%m-%d'), days=self.days - days_first)
        return first, second

first_day property

first_day: Timestamp

First day as a naive timestamp at midnight.

last_day property

last_day: Timestamp

Last day as a naive timestamp at midnight.

day_list property

day_list: list[Timestamp]

All days of the scenario as naive timestamps at midnight.

resolution_on

resolution_on(day: Timestamp) -> str

Time step of the series on the given day.

Source code in src/mesqual/testing/scenario.py
114
115
116
117
118
119
120
def resolution_on(self, day: pd.Timestamp) -> str:
    """Time step of the series on the given day."""
    if self.resolution_change is not None:
        change_day, new_resolution = self.resolution_change
        if day >= pd.Timestamp(change_day):
            return new_resolution
    return self.resolution

timestamp

timestamp(value: str) -> Timestamp

Parse a timestamp string in the time zone of the scenario.

A string without offset is local time in tz. A string with offset is converted to tz.

Source code in src/mesqual/testing/scenario.py
122
123
124
125
126
127
128
129
130
131
132
133
def timestamp(self, value: str) -> pd.Timestamp:
    """Parse a timestamp string in the time zone of the scenario.

    A string without offset is local time in `tz`. A string with offset is
    converted to `tz`.
    """
    parsed = pd.Timestamp(value)
    if parsed.tzinfo is None:
        return parsed.tz_localize(self.tz) if self.tz else parsed
    if self.tz is None:
        raise ValueError(f'Timestamp {value!r} has an offset, but the scenario has no time zone.')
    return parsed.tz_convert(self.tz)

replace

replace(**changes) -> DummyScenario

Return a copy with the given fields changed.

Source code in src/mesqual/testing/scenario.py
135
136
137
def replace(self, **changes) -> DummyScenario:
    """Return a copy with the given fields changed."""
    return dataclasses.replace(self, **changes)

split

split(at: str) -> tuple[DummyScenario, DummyScenario]

Split the scenario into two parts with consecutive date ranges.

Parameters:

Name Type Description Default
at str

First day of the second part. It must lie after the first day and not after the last day.

required

Returns:

Type Description
tuple[DummyScenario, DummyScenario]

The parts '.1' and '.2'. Together they give the same data as the unsplit scenario.

Source code in src/mesqual/testing/scenario.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def split(self, at: str) -> tuple[DummyScenario, DummyScenario]:
    """Split the scenario into two parts with consecutive date ranges.

    Args:
        at: First day of the second part. It must lie after the first day
            and not after the last day.

    Returns:
        The parts '<name>.1' and '<name>.2'. Together they give the same data
            as the unsplit scenario.
    """
    split_day = pd.Timestamp(at).normalize()
    days_first = (split_day - self.first_day).days
    if not 0 < days_first < self.days:
        raise ValueError(f'Split day {at} must lie after {self.start} and within the {self.days} days.')
    first = self.replace(name=f'{self.name}.1', days=days_first)
    second = self.replace(name=f'{self.name}.2', start=split_day.strftime('%Y-%m-%d'), days=self.days - days_first)
    return first, second

DummyPeriodSource

Bases: DummySource

A DummySource with a time level of (run, period) tuples instead of timestamps.

The run is the calendar day as an integer YYYYMMDD, for example 20240330, so the parts of a split scenario keep their run numbers. The period counts the time steps within the day, starting at 1.

Source code in src/mesqual/testing/source.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
class DummyPeriodSource(DummySource):
    """A `DummySource` with a time level of (run, period) tuples instead of timestamps.

    The run is the calendar day as an integer YYYYMMDD, for example 20240330, so
    the parts of a split scenario keep their run numbers. The period counts the
    time steps within the day, starting at 1.
    """

    def _convert_time_index(self, df: pd.DataFrame) -> pd.DataFrame:
        day_starts = df.index.normalize()
        local_days = day_starts.tz_localize(None) if day_starts.tz is not None else day_starts
        steps = pd.to_timedelta([self.scenario.resolution_on(day) for day in local_days])
        runs = local_days.strftime('%Y%m%d').astype(int)
        periods = ((df.index - day_starts) / steps).astype(int) + 1
        df = df.copy()
        df.index = pd.Index(list(zip(runs, periods)), tupleize_cols=False, name=self.TIME_LEVEL)
        return df

DummySource

Raw tables of one synthetic scenario, as a simulation platform would write them.

Model tables come from DummyNetwork. Time series tables have a time index named 'time' and one column per object. The values of an object on a day depend only on the seed, the date, the object id and its model properties. Adding or removing other objects leaves them unchanged.

With profile='daily' the series look like those of a real power system: solar output is 0 at night and peaks around noon, longer and higher in summer; wind output varies slowly and is higher in winter; demand has a morning and an evening peak and is lower at night, on weekends and in summer; nuclear runs flat, coal and gas follow the net demand (demand minus solar and wind output); prices follow the net demand. All shapes are taken at the middle of each time step, and the noise is constant within an hour, so values at 15 minutes match those at 60 minutes. With profile='constant' every series is constant.

Time series tables:

  • 'node_price': EUR/MWh per node.
  • 'generator_generation': MWh per period and generator.
  • 'demand_load': MW per demand, times demand_factor.
  • 'line_flow': MW per line, net flow where it enters the line, positive from node_from to node_to.
  • 'line_capacity': MW per line in line direction. The capacity against the line direction is DOWN_CAPACITY_FACTOR times this value.

Parameters:

Name Type Description Default
scenario DummyScenario

The scenario spec.

required
Source code in src/mesqual/testing/source.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class DummySource:
    """Raw tables of one synthetic scenario, as a simulation platform would write them.

    Model tables come from `DummyNetwork`. Time series tables have a time index
    named 'time' and one column per object. The values of an object on a day
    depend only on the seed, the date, the object id and its model properties.
    Adding or removing other objects leaves them unchanged.

    With `profile='daily'` the series look like those of a real power system:
    solar output is 0 at night and peaks around noon, longer and higher in
    summer; wind output varies slowly and is higher in winter; demand has a
    morning and an evening peak and is lower at night, on weekends and in
    summer; nuclear runs flat, coal and gas follow the net demand (demand minus
    solar and wind output); prices follow the net demand. All shapes are taken
    at the middle of each time step, and the noise is constant within an hour,
    so values at 15 minutes match those at 60 minutes. With `profile='constant'`
    every series is constant.

    Time series tables:

    - 'node_price': EUR/MWh per node.
    - 'generator_generation': MWh per period and generator.
    - 'demand_load': MW per demand, times `demand_factor`.
    - 'line_flow': MW per line, net flow where it enters the line, positive
      from node_from to node_to.
    - 'line_capacity': MW per line in line direction. The capacity against the
      line direction is `DOWN_CAPACITY_FACTOR` times this value.

    Args:
        scenario: The scenario spec.
    """

    MODEL_TABLES = ('countries', 'nodes', 'lines', 'generators', 'demands')
    TIME_SERIES_TABLES = ('node_price', 'generator_generation', 'demand_load', 'line_flow', 'line_capacity')
    TABLES = MODEL_TABLES + TIME_SERIES_TABLES
    LINE_LOSS_FACTOR = 0.02
    DOWN_CAPACITY_FACTOR = 0.9
    TIME_LEVEL = 'time'

    def __init__(self, scenario: DummyScenario):
        unknown = set(scenario.missing_tables) - set(self.TABLES)
        if unknown:
            raise ValueError(f'Unknown tables in missing_tables: {sorted(unknown)}. Use names of {self.TABLES}.')
        self.scenario = scenario
        self.network = DummyNetwork(scenario)
        self._tables: dict[str, pd.DataFrame] = {}

    @cached_property
    def inventory(self) -> DummyInventory:
        """Fingerprint and raw tables of this source."""
        fingerprint = hashlib.sha256(repr(self.scenario).encode()).hexdigest()[:16]
        variables = tuple(t for t in self.TABLES if t not in self.scenario.missing_tables)
        return DummyInventory(fingerprint=fingerprint, variables=variables)

    def has_table(self, table: str) -> bool:
        """True if the source provides the raw table."""
        return table in self.inventory.variables

    def read(self, table: str) -> pd.DataFrame:
        """Return a copy of a raw table.

        Raises:
            KeyError: If the source does not provide the table.
        """
        if not self.has_table(table):
            raise KeyError(f'Source of scenario {self.scenario.name!r} does not provide table {table!r}.')
        if table not in self._tables:
            self._tables[table] = self._build_table(table)
        return self._tables[table].copy()

    def _build_table(self, table: str) -> pd.DataFrame:
        if table in self.MODEL_TABLES:
            return self.network.tables[table]
        series = _SeriesBuilder(self.scenario, self.network).build(table)
        return self._apply_edge_cases(series)

    def _apply_edge_cases(self, df: pd.DataFrame) -> pd.DataFrame:
        s = self.scenario
        for start, end in s.nan_gaps:
            df.loc[self._window_mask(df.index, start, end)] = np.nan
        for start, end in s.missing_rows:
            df = df.loc[~self._window_mask(df.index, start, end)]
        if s.duplicate_rows:
            df = pd.concat([df, df.iloc[: s.duplicate_rows]])
        return self._convert_time_index(df)

    def _window_mask(self, index: pd.DatetimeIndex, start: str, end: str) -> np.ndarray:
        start, end = self.scenario.timestamp(start), self.scenario.timestamp(end)
        return (index >= start) & (index < end)

    def _convert_time_index(self, df: pd.DataFrame) -> pd.DataFrame:
        """Hook for sources with another time level. The default keeps the DatetimeIndex."""
        return df

inventory cached property

inventory: DummyInventory

Fingerprint and raw tables of this source.

has_table

has_table(table: str) -> bool

True if the source provides the raw table.

Source code in src/mesqual/testing/source.py
85
86
87
def has_table(self, table: str) -> bool:
    """True if the source provides the raw table."""
    return table in self.inventory.variables

read

read(table: str) -> DataFrame

Return a copy of a raw table.

Raises:

Type Description
KeyError

If the source does not provide the table.

Source code in src/mesqual/testing/source.py
89
90
91
92
93
94
95
96
97
98
99
def read(self, table: str) -> pd.DataFrame:
    """Return a copy of a raw table.

    Raises:
        KeyError: If the source does not provide the table.
    """
    if not self.has_table(table):
        raise KeyError(f'Source of scenario {self.scenario.name!r} does not provide table {table!r}.')
    if table not in self._tables:
        self._tables[table] = self._build_table(table)
    return self._tables[table].copy()

make_dummy_dataset

make_dummy_dataset(scenario: DummyScenario | tuple[DummyScenario, ...], name: str | None = None) -> Dataset

Build the dataset of one scenario or of a scenario split into parts.

Parameters:

Name Type Description Default
scenario DummyScenario | tuple[DummyScenario, ...]

One scenario, or the parts of DummyScenario.split.

required
name str | None

Dataset name. Default: the scenario name, or for parts their name without the '.N' suffix ('base' for 'base.1' and 'base.2').

None

Returns:

Type Description
Dataset

A DummyDataset for one scenario. A DatasetMergeCollection of one DummyDataset per part for parts, with the attributes of the whole: 'first_date' of the first part, 'last_date' of the last part and the sum of 'days'.

Raises:

Type Description
ValueError

If no part is given, or if the parts have different names without the suffix and no name is given.

Source code in src/mesqual/testing/dataset.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def make_dummy_dataset(scenario: DummyScenario | tuple[DummyScenario, ...], name: str | None = None) -> Dataset:
    """Build the dataset of one scenario or of a scenario split into parts.

    Args:
        scenario: One scenario, or the parts of `DummyScenario.split`.
        name: Dataset name. Default: the scenario name, or for parts their
            name without the '.N' suffix ('base' for 'base.1' and 'base.2').

    Returns:
        A `DummyDataset` for one scenario. A `DatasetMergeCollection` of one
            `DummyDataset` per part for parts, with the attributes of the whole:
            'first_date' of the first part, 'last_date' of the last part and the
            sum of 'days'.

    Raises:
        ValueError: If no part is given, or if the parts have different names
            without the suffix and no `name` is given.
    """
    if isinstance(scenario, DummyScenario):
        return DummyDataset(scenario, name=name)
    if not scenario:
        raise ValueError('make_dummy_dataset needs at least one part.')
    parts = [DummyDataset(part) for part in scenario]
    if name is None:
        base_names = {re.sub(r'\.\d+$', '', part.name) for part in parts}
        if len(base_names) != 1:
            raise ValueError(f'Parts {[p.name for p in parts]} have no common name. Pass `name`.')
        name = base_names.pop()
    attributes = {
        'first_date': parts[0].attributes['first_date'],
        'last_date': parts[-1].attributes['last_date'],
        'days': sum(part.attributes['days'] for part in parts),
    }
    return DatasetMergeCollection(parts, name=name, attributes=attributes)

make_dummy_study

make_dummy_study(start: str = '2024-03-28', days: int = 5, tz: str | None = 'Europe/Berlin', seed: int = 0, study_folder: str | Path | None = None) -> StudyManager

Build a study of four synthetic scenarios with comparisons against 'base'.

Scenarios:

  • 'base': split into two consecutive periods at the middle day, one DummyDataset per period, merged into one dataset. The series switch from 60 to 15 minutes at the same day (resolution_change).
  • 'high_demand': 'base' with 20% more demand, one dataset.
  • 'without_N4': 'base' without node N4 and its lines, generators and demands.
  • 'short': 'base' one day shorter.

Comparisons: each other scenario against 'base', named ' vs base' by DatasetComparison.

Every scenario has the attributes 'first_date', 'last_date', 'days', 'demand_factor' and 'periods' (number of merged period datasets).

The default horizon from Thursday 2024-03-28 has a weekend and the DST change on 2024-03-31 in Europe/Berlin.

Parameters:

Name Type Description Default
start str

First day.

'2024-03-28'
days int

Number of days, at least 2.

5
tz str | None

Time zone of the time index, or None for naive timestamps.

'Europe/Berlin'
seed int

Seed of the random noise.

0
study_folder str | Path | None

Optional folder of the study, passed to StudyManager.

None

Returns:

Type Description
StudyManager

The study, with the scenarios in study.scen and the comparisons in study.comp.

Raises:

Type Description
ValueError

If days is less than 2.

Examples:

>>> study = make_dummy_study()
>>> deltas = study.comp.fetch('Node.Results.price')
Source code in src/mesqual/testing/study.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def make_dummy_study(
    start: str = '2024-03-28',
    days: int = 5,
    tz: str | None = 'Europe/Berlin',
    seed: int = 0,
    study_folder: str | Path | None = None,
) -> StudyManager:
    """Build a study of four synthetic scenarios with comparisons against 'base'.

    Scenarios:

    - 'base': split into two consecutive periods at the middle day, one
      `DummyDataset` per period, merged into one dataset. The series switch
      from 60 to 15 minutes at the same day (`resolution_change`).
    - 'high_demand': 'base' with 20% more demand, one dataset.
    - 'without_N4': 'base' without node N4 and its lines, generators and demands.
    - 'short': 'base' one day shorter.

    Comparisons: each other scenario against 'base', named '<scenario> vs base'
    by `DatasetComparison`.

    Every scenario has the attributes 'first_date', 'last_date', 'days',
    'demand_factor' and 'periods' (number of merged period datasets).

    The default horizon from Thursday 2024-03-28 has a weekend and the DST
    change on 2024-03-31 in Europe/Berlin.

    Args:
        start: First day.
        days: Number of days, at least 2.
        tz: Time zone of the time index, or None for naive timestamps.
        seed: Seed of the random noise.
        study_folder: Optional folder of the study, passed to `StudyManager`.

    Returns:
        The study, with the scenarios in `study.scen` and the comparisons in `study.comp`.

    Raises:
        ValueError: If `days` is less than 2.

    Examples:
        >>> study = make_dummy_study()
        >>> deltas = study.comp.fetch('Node.Results.price')
    """
    if days < 2:
        raise ValueError(f'make_dummy_study needs at least 2 days, got {days}.')
    split_day = (pd.Timestamp(start) + pd.Timedelta(days=days // 2)).strftime('%Y-%m-%d')
    base = DummyScenario(
        name='base',
        start=start,
        days=days,
        tz=tz,
        seed=seed,
        resolution='60min',
        resolution_change=(split_day, '15min'),
    )
    variations = [
        base.replace(name='high_demand', demand_factor=1.2),
        base.replace(name='without_N4', removed_objects=('N4',)),
        base.replace(name='short', days=days - 1),
    ]
    scenarios = [make_dummy_dataset(base.split(split_day))] + [DummyDataset(v) for v in variations]
    for dataset, scenario in zip(scenarios, [base, *variations]):
        dataset.set_attributes(demand_factor=scenario.demand_factor, periods=2 if dataset.name == 'base' else 1)
    return StudyManager.factory_from_scenarios(
        scenarios=scenarios,
        comparisons=[(v.name, base.name) for v in variations],
        study_folder=study_folder,
    )

Interpreters and inventory

The interpreters of DummyDataset and the inventory of its source. A study subclasses DummyInterpreter for its own flags, or an interpreter to override it.

Synthetic platform dataset with its interpreters.

DummyInterpreter

Bases: Dataset[DummyConfig, str, FlagIndex]

Base of the interpreters of DummyDataset.

A subclass declares its flags in flag_specs. A spec that reads a raw table names it in SPEC_TABLE. A derived spec lists the flags it fetches through the parent dataset in INPUT_FLAGS. An input flag may use the variant placeholders of the spec, for example 'Demand.Results.demand_{product}'. _is_available reads one of the two, so every spec must be in exactly one. A subclass that breaks this, or whose input flag has a placeholder that is no variant of its spec, raises ValueError at class creation.

Parameters:

Name Type Description Default
source DummySource

The raw tables of the scenario.

required
parent_dataset Dataset | None

The platform dataset that holds this interpreter.

None
Source code in src/mesqual/testing/dataset.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class DummyInterpreter(Dataset[DummyConfig, str, FlagIndex]):
    """Base of the interpreters of `DummyDataset`.

    A subclass declares its flags in `flag_specs`. A spec that reads a raw
    table names it in `SPEC_TABLE`. A derived spec lists the flags it
    fetches through the parent dataset in `INPUT_FLAGS`. An input flag may
    use the variant placeholders of the spec, for example
    `'Demand.Results.demand_{product}'`. `_is_available` reads one of the
    two, so every spec must be in exactly one. A subclass that breaks this,
    or whose input flag has a placeholder that is no variant of its spec,
    raises `ValueError` at class creation.

    Args:
        source: The raw tables of the scenario.
        parent_dataset: The platform dataset that holds this interpreter.
    """

    SPEC_TABLE: ClassVar[dict[str, str]] = {}
    INPUT_FLAGS: ClassVar[dict[str, tuple[str, ...]]] = {}

    def __init__(self, source: DummySource, parent_dataset: Dataset | None = None):
        super().__init__(parent_dataset=parent_dataset)
        self.source = source

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        both = set(cls.SPEC_TABLE) & set(cls.INPUT_FLAGS)
        if both:
            raise ValueError(f'{cls.__name__}: specs {sorted(both)} are in SPEC_TABLE and in INPUT_FLAGS.')
        declared = cls.SPEC_TABLE.keys() | cls.INPUT_FLAGS.keys()
        missing = [spec.name for spec in cls.flag_specs if spec.name not in declared]
        if missing:
            raise ValueError(f'{cls.__name__}: specs {missing} are in neither SPEC_TABLE nor INPUT_FLAGS.')
        for spec in cls.flag_specs:
            for input_flag in cls.INPUT_FLAGS.get(spec.name, ()):
                fields = {name for _, name, _, _ in string.Formatter().parse(input_flag) if name is not None}
                unknown = fields - {dimension.name for dimension in spec.variants}
                if unknown:
                    raise ValueError(
                        f'{cls.__name__}: input flag {input_flag!r} of {spec.name!r} has placeholders '
                        f'{sorted(unknown)} that are no variants of the spec.'
                    )

    @classmethod
    def get_config_type(cls) -> type[DummyConfig]:
        """Return `DummyConfig`."""
        return DummyConfig

    def _is_available(self, flag: str) -> Availability:
        """Availability from the raw table in the source inventory, or from the input flags.

        A spec in `SPEC_TABLE` is available if the source inventory lists its
        table; the reason names the table. For a spec in `INPUT_FLAGS`,
        `Availability.of_inputs` combines the availability of the input flags.
        """
        spec_name = self.flag_index.get_spec(flag).name
        if spec_name in self.SPEC_TABLE:
            table = self.SPEC_TABLE[spec_name]
            has_table = self.source.has_table(table)
            return Availability(has_table, f'table {table!r} {"in" if has_table else "not in"} the source')
        return Availability.of_inputs({f: self.parent_dataset.availability(f) for f in self._input_flags(flag)})

    def _input_flags(self, flag: str) -> list[str]:
        """The `INPUT_FLAGS` of the spec of `flag`, with the variant values of `flag` filled in."""
        spec = self.flag_index.get_spec(flag)
        variant = spec.variant_of(flag).as_dict()
        return [input_flag.format(**variant) for input_flag in self.INPUT_FLAGS[spec.name]]

    def _fetch_inputs(self, flag: str, config: DummyConfig, params: dict) -> list[pd.DataFrame]:
        """Fetch the `INPUT_FLAGS` of the spec of `flag` through the parent dataset, so overrides reach them.

        Each input gets the parameters of `params` that its spec declares.
        """
        inputs = []
        for input_flag in self._input_flags(flag):
            declared = {dimension.name for dimension in self.flag_index.get_spec(input_flag).params}
            inputs.append(
                self.parent_dataset.fetch(input_flag, config, **{k: v for k, v in params.items() if k in declared})
            )
        return inputs

get_config_type classmethod

get_config_type() -> type[DummyConfig]

Return DummyConfig.

Source code in src/mesqual/testing/dataset.py
 99
100
101
102
@classmethod
def get_config_type(cls) -> type[DummyConfig]:
    """Return `DummyConfig`."""
    return DummyConfig

DummyModelInterpreter

Bases: DummyInterpreter

Model tables of countries, nodes, lines, generators and demands.

Source code in src/mesqual/testing/dataset.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
@DummyDataset.register_interpreter
class DummyModelInterpreter(DummyInterpreter):
    """Model tables of countries, nodes, lines, generators and demands."""

    LINE_MODEL_SPEC = ModelFlagSpec(
        name='Line.Model',
        description='Lines between two nodes. The line direction runs from node_from to node_to.',
        index='Line',
        topology_type=TopologyTypeEnum.Edge,
        memberships={'node_from': 'Node.Model', 'node_to': 'Node.Model'},
        edge_ends=('node_from', 'node_to'),
    )
    flag_specs = (
        ModelFlagSpec(
            name='Country.Model',
            description='Countries, each with a square polygon.',
            index='Country',
            topology_type=TopologyTypeEnum.Area,
        ),
        ModelFlagSpec(
            name='Node.Model',
            description='Nodes of the network, each with a point and a country.',
            index='Node',
            topology_type=TopologyTypeEnum.Node,
            memberships={'country': 'Country.Model'},
        ),
        LINE_MODEL_SPEC,
        ModelFlagSpec(
            name='Generator.Model',
            description='Generators, each at one node and with one fuel.',
            index='Generator',
            topology_type=TopologyTypeEnum.NodeConnectedElement,
            memberships={'node': 'Node.Model'},
        ),
        ModelFlagSpec(
            name='Demand.Model',
            description='Demands, each at one node and with one sector.',
            index='Demand',
            topology_type=TopologyTypeEnum.NodeConnectedElement,
            memberships={'node': 'Node.Model'},
        ),
    )
    SPEC_TABLE: ClassVar[dict[str, str]] = {
        'Country.Model': 'countries',
        'Node.Model': 'nodes',
        'Line.Model': 'lines',
        'Generator.Model': 'generators',
        'Demand.Model': 'demands',
    }

    def _fetch(self, flag: str, effective_config: DummyConfig, **params) -> pd.DataFrame:
        return self.source.read(self.SPEC_TABLE[flag])

DummyTimeSeriesInterpreter

Bases: DummyInterpreter

Node prices, generation, demand, line flows and line capacities, each from one raw table.

Source code in src/mesqual/testing/dataset.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
@DummyDataset.register_interpreter
class DummyTimeSeriesInterpreter(DummyInterpreter):
    """Node prices, generation, demand, line flows and line capacities, each from one raw table."""

    PRODUCT_SHARES: ClassVar[dict[str, float]] = {'total': 1.0, 'hourly': 0.75, 'quarter_hourly': 0.25}
    SOLUTION_PRICE_STEP: ClassVar[dict[str, float]] = {'first': -1.0, 'final': 0.0}
    """EUR/MWh added to the final node price per solution, times the number in the node id (N3: 3)."""
    SOLUTION_DEMAND_FACTOR: ClassVar[dict[str, float]] = {'first': 0.98, 'final': 1.0}
    """Factor on the final total demand, per solution."""
    PRICE_SPEC = TimeSeriesFlagSpec(
        name='Node.Results.price',
        description='Price at the node.',
        model_flag='Node.Model',
        unit=Units.EUR_per_MWh,
        params=(SOLUTION,),
    )
    GENERATION_SPEC = TimeSeriesFlagSpec(
        name='Generator.Results.generation',
        description='Energy generated in each period.',
        model_flag='Generator.Model',
        unit=Units.MWh,
        fill_value=0,
    )
    DEMAND_SPEC = TimeSeriesFlagSpec(
        name='Demand.Results.demand_{product}',
        description='Demand of the demand object.',
        model_flag='Demand.Model',
        unit=Units.MW,
        fill_value=0,
        variants=(Dimension('product', 'Order products to include.', _product_values(PRODUCT_SHARES)),),
        params=(SOLUTION,),
    )
    CAPACITY_SPEC = TimeSeriesFlagSpec(
        name='Line.Constraints.capacity_{direction}',
        description='Transfer capacity of the line.',
        model_flag='Line.Model',
        unit=Units.MW,
        fill_value=0,
        variants=(
            Dimension(
                'direction',
                'Direction of the capacity.',
                {
                    'up': 'from node_from to node_to',
                    'down': 'from node_to to node_from, 90% of up',
                },
            ),
        ),
    )
    FLOW_SPEC = TimeSeriesFlagSpec(
        name='Line.Results.flow_{side}_{direction}',
        description='Power flow on the line.',
        model_flag='Line.Model',
        unit=Units.MW,
        fill_value=0,
        variants=(
            Dimension(
                'side',
                'Where the flow is measured.',
                {
                    'sent': 'where the flow enters the line, before losses',
                    'received': 'where the flow leaves the line, after losses',
                },
            ),
            Dimension(
                'direction',
                'Flow direction.',
                {
                    'up': 'from node_from to node_to, zero otherwise',
                    'down': 'from node_to to node_from, zero otherwise',
                    'net': 'up minus down',
                },
            ),
        ),
    )
    flag_specs = (PRICE_SPEC, GENERATION_SPEC, DEMAND_SPEC, CAPACITY_SPEC, FLOW_SPEC)
    SPEC_TABLE: ClassVar[dict[str, str]] = {
        PRICE_SPEC.name: 'node_price',
        GENERATION_SPEC.name: 'generator_generation',
        DEMAND_SPEC.name: 'demand_load',
        CAPACITY_SPEC.name: 'line_capacity',
        FLOW_SPEC.name: 'line_flow',
    }

    def _fetch(self, flag: str, effective_config: DummyConfig, **params) -> pd.DataFrame:
        spec = self.flag_index.get_spec(flag)
        variant = spec.variant_of(flag)
        results = {
            self.PRICE_SPEC.name: lambda: self._price(effective_config, params['solution']),
            self.GENERATION_SPEC.name: lambda: self._table(spec),
            self.DEMAND_SPEC.name: lambda: self._demand(variant, effective_config, params['solution']),
            self.CAPACITY_SPEC.name: lambda: self._line_capacity(variant, effective_config),
            self.FLOW_SPEC.name: lambda: self._line_flow(variant, effective_config),
        }
        return results[spec.name]()

    def _table(self, spec: TimeSeriesFlagSpec) -> pd.DataFrame:
        return self.source.read(self.SPEC_TABLE[spec.name])

    def _price(self, config: DummyConfig, solution: str) -> pd.DataFrame:
        prices = self._table(self.PRICE_SPEC) + config.price_offset
        node_numbers = [int(re.search(r'\d+$', node).group()) for node in prices.columns]
        return prices + self.SOLUTION_PRICE_STEP[solution] * pd.Series(node_numbers, index=prices.columns, dtype=float)

    def _demand(self, variant: VariantValues, config: DummyConfig, solution: str) -> pd.DataFrame:
        """'total' is the raw table. 'hourly' and 'quarter_hourly' are shares of 'total' through the parent dataset."""

        def share() -> pd.DataFrame:
            total = self._variant(self.DEMAND_SPEC, config, {'product': 'total'}, solution=solution)
            return total * self.PRODUCT_SHARES[variant.product]

        products = {
            'total': lambda: self._table(self.DEMAND_SPEC) * self.SOLUTION_DEMAND_FACTOR[solution],
            'hourly': share,
            'quarter_hourly': share,
        }
        return products[variant.product]()

    def _line_capacity(self, variant: VariantValues, config: DummyConfig) -> pd.DataFrame:
        """'up' is the raw table, 'down' derives from 'up' through the parent dataset."""
        capacities = {
            'up': lambda: self._table(self.CAPACITY_SPEC),
            'down': lambda: (
                self._variant(self.CAPACITY_SPEC, config, {'direction': 'up'}) * self.source.DOWN_CAPACITY_FACTOR
            ),
        }
        return capacities[variant.direction]()

    def _line_flow(self, variant: VariantValues, config: DummyConfig) -> pd.DataFrame:
        """'sent' 'net' is the raw table. The other variants derive from it through the parent dataset.

        'sent' 'up' and 'down' are the positive and the negative part of
        'sent' 'net'. A 'received' variant is the 'sent' variant minus the
        line losses.
        """
        sent_flows = {
            'net': lambda: self._table(self.FLOW_SPEC),
            'up': lambda: self._sent_flow('net', config).clip(lower=0),
            'down': lambda: (-self._sent_flow('net', config)).clip(lower=0),
        }
        sides = {
            'sent': lambda: sent_flows[variant.direction](),
            'received': lambda: self._sent_flow(variant.direction, config) * (1.0 - self.source.LINE_LOSS_FACTOR),
        }
        return sides[variant.side]()

    def _sent_flow(self, direction: str, config: DummyConfig) -> pd.DataFrame:
        return self._variant(self.FLOW_SPEC, config, {'side': 'sent', 'direction': direction})

    def _variant(
        self,
        spec: TimeSeriesFlagSpec,
        config: DummyConfig,
        variant: dict[str, str],
        **params,
    ) -> pd.DataFrame:
        """Fetch another variant of `spec` through the parent dataset, so an override of it reaches this one."""
        return self.parent_dataset.fetch(spec.name.format(**variant), config, **params)

SOLUTION_PRICE_STEP class-attribute

SOLUTION_PRICE_STEP: dict[str, float] = {'first': -1.0, 'final': 0.0}

EUR/MWh added to the final node price per solution, times the number in the node id (N3: 3).

SOLUTION_DEMAND_FACTOR class-attribute

SOLUTION_DEMAND_FACTOR: dict[str, float] = {'first': 0.98, 'final': 1.0}

Factor on the final total demand, per solution.

DummyDerivedInterpreter

Bases: DummyInterpreter

Line loading, node demand and generation per node and fuel, from their INPUT_FLAGS.

Nodes without demands or generators have no column.

Source code in src/mesqual/testing/dataset.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
@DummyDataset.register_interpreter
class DummyDerivedInterpreter(DummyInterpreter):
    """Line loading, node demand and generation per node and fuel, from their `INPUT_FLAGS`.

    Nodes without demands or generators have no column.
    """

    LOADING_SPEC = TimeSeriesFlagSpec(
        name='Line.Results.loading',
        description='Absolute net flow where it enters the line, divided by the capacity in flow direction.',
        model_flag='Line.Model',
        unit=Units.per_unit,
    )
    NODE_DEMAND_SPEC = TimeSeriesFlagSpec(
        name='Node.Results.demand_{product}',
        description='Sum of the demand of the demands at the node.',
        model_flag='Node.Model',
        unit=Units.MW,
        fill_value=0,
        variants=DummyTimeSeriesInterpreter.DEMAND_SPEC.variants,
        params=DummyTimeSeriesInterpreter.DEMAND_SPEC.params,
    )
    GENERATION_BY_FUEL_SPEC = TimeSeriesFlagSpec(
        name='Node.Results.generation_{fuel}',
        description='Generation per node.',
        model_flag='Node.Model',
        unit=Units.MWh,
        fill_value=0,
        variants=(Dimension('fuel', 'Fuel of the generators.', lambda ds: DummyDerivedInterpreter._fuels(ds)),),
    )
    flag_specs = (LOADING_SPEC, NODE_DEMAND_SPEC, GENERATION_BY_FUEL_SPEC)
    INPUT_FLAGS: ClassVar[dict[str, tuple[str, ...]]] = {
        LOADING_SPEC.name: (
            'Line.Results.flow_sent_net',
            'Line.Constraints.capacity_up',
            'Line.Constraints.capacity_down',
        ),
        NODE_DEMAND_SPEC.name: ('Demand.Model', 'Demand.Results.demand_{product}'),
        GENERATION_BY_FUEL_SPEC.name: ('Generator.Model', 'Generator.Results.generation'),
    }

    def _fetch(self, flag: str, effective_config: DummyConfig, **params) -> pd.DataFrame:
        inputs = self._fetch_inputs(flag, effective_config, params)
        results = {
            self.LOADING_SPEC.name: lambda: self._loading(*inputs),
            self.NODE_DEMAND_SPEC.name: lambda: self._demand_per_node(*inputs),
            self.GENERATION_BY_FUEL_SPEC.name: lambda: self._generation_per_node(flag, *inputs),
        }
        return results[self.flag_index.get_spec(flag).name]()

    @staticmethod
    def _fuels(dataset: Dataset) -> dict[str, str]:
        """The fuels of the generator model."""
        return {f: f'from {f} generators' for f in sorted(dataset.fetch('Generator.Model')['fuel'].unique())}

    @staticmethod
    def _loading(flow: pd.DataFrame, capacity_up: pd.DataFrame, capacity_down: pd.DataFrame) -> pd.DataFrame:
        capacity = capacity_up.where(flow >= 0, capacity_down)
        return flow.abs() / capacity

    def _demand_per_node(self, demands: pd.DataFrame, demand: pd.DataFrame) -> pd.DataFrame:
        return self._sum_per_node(demand, demands['node'])

    def _generation_per_node(self, flag: str, generators: pd.DataFrame, generation: pd.DataFrame) -> pd.DataFrame:
        ids = generators.index[generators['fuel'] == self.GENERATION_BY_FUEL_SPEC.variant_of(flag).fuel]
        return self._sum_per_node(generation[ids], generators.loc[ids, 'node'])

    @staticmethod
    def _sum_per_node(series: pd.DataFrame, node_of_column: pd.Series) -> pd.DataFrame:
        per_node = series.T.groupby(node_of_column).sum(min_count=1).T
        return per_node.rename_axis(columns='Node')

DummyAreaFlags

Bases: AreaFlagInterpreter

Flags on the area layer 'Country'.

The layer model is the declared 'Country.Model', so there is no area model spec.

Source code in src/mesqual/testing/dataset.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
@DummyDataset.register_interpreter
class DummyAreaFlags(AreaFlagInterpreter):
    """Flags on the area layer 'Country'.

    The layer model is the declared 'Country.Model', so there is no area model spec.
    """

    PRICE_SPEC = AreaFlagSpec(
        name='{area_layer}.Results.price',
        base=DummyTimeSeriesInterpreter.PRICE_SPEC,
        aggregation=WeightedMean(weight='Node.Results.demand_total'),
        description='Mean of the node prices of the area, weighted by the total node demand.',
    )
    DEMAND_SPEC = AreaFlagSpec(
        name='{area_layer}.Results.demand_{product}',
        base=DummyDerivedInterpreter.NODE_DEMAND_SPEC,
        aggregation=Sum(),
        description='Sum of the node demand of the area.',
    )
    GENERATION_BY_FUEL_SPEC = AreaFlagSpec(
        name='{area_layer}.Results.generation_{fuel}',
        base=DummyDerivedInterpreter.GENERATION_BY_FUEL_SPEC,
        aggregation=Sum(),
        description='Sum of the node generation of the area.',
    )
    flag_specs = (PRICE_SPEC, DEMAND_SPEC, GENERATION_BY_FUEL_SPEC)

DummyBorderFlags

Bases: BorderFlagInterpreter

Flags on the border layer 'CountryBorder'.

Source code in src/mesqual/testing/dataset.py
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
@DummyDataset.register_interpreter
class DummyBorderFlags(BorderFlagInterpreter):
    """Flags on the border layer 'CountryBorder'."""

    MODEL_SPEC = BorderFlagSpec(
        name='{border_layer}.Model',
        base=DummyModelInterpreter.LINE_MODEL_SPEC,
        aggregation=BorderModel(),
        description='One row per border: area_from, area_to, the lines in and against border direction, geometry.',
    )
    FLOW_SPEC = BorderFlagSpec(
        name='{border_layer}.Results.flow_{side}_{direction}',
        base=DummyTimeSeriesInterpreter.FLOW_SPEC,
        aggregation=BorderFlowSum(),
        description='Sum of the line flows across the border, in border direction.',
    )
    CAPACITY_SPEC = BorderFlagSpec(
        name='{border_layer}.Constraints.capacity_{direction}',
        base=DummyTimeSeriesInterpreter.CAPACITY_SPEC,
        aggregation=BorderCapacitySum(),
        description='Sum of the line capacities across the border, in border direction.',
    )
    PRICE_SPREAD_SPEC = BorderFlagSpec(
        name='{border_layer}.Results.price_spread',
        base=DummyAreaFlags.PRICE_SPEC,
        aggregation=PriceSpread(),
        description='Area price at area_to minus the area price at area_from.',
    )
    flag_specs = (MODEL_SPEC, FLOW_SPEC, CAPACITY_SPEC, PRICE_SPREAD_SPEC)

DummyInventory dataclass

Bases: SourceInventory

What a synthetic source holds.

Attributes:

Name Type Description
fingerprint str

Hash of the scenario spec. Equal specs give equal fingerprints.

variables tuple[str, ...]

Names of the raw tables the source provides.

Source code in src/mesqual/testing/source.py
19
20
21
22
23
24
25
26
27
28
@dataclass(frozen=True)
class DummyInventory(SourceInventory):
    """What a synthetic source holds.

    Attributes:
        fingerprint: Hash of the scenario spec. Equal specs give equal fingerprints.
        variables: Names of the raw tables the source provides.
    """

    variables: tuple[str, ...]