Skip to content

Area and AreaBorder Model-DF Generators

AreaModelGenerator

Bases: GeoModelGeneratorBase, AreaMembership

Area model from the area of each node: one row per area.

The model has the node count and a representative point per area. generate_area_model takes the point from the node locations. enhance_with_geometry adds only the area geometries and keeps the existing points.

Attributes:

Name Type Description
node_model_df DataFrame

Node-level data with area assignments

area_column str

Column name containing area identifiers

geo_location_column str

Column name containing geographic Point objects

Examples:

>>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
>>> generator.generate_area_model()
         node_count         projection_point
country
C1              2.0   POINT (6.3888 47.0112)
C2              2.0  POINT (10.3888 47.0112)
Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
  9
 10
 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
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
210
211
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
class AreaModelGenerator(GeoModelGeneratorBase, AreaMembership):
    """Area model from the area of each node: one row per area.

    The model has the node count and a representative point per area.
    `generate_area_model` takes the point from the node locations.
    `enhance_with_geometry` adds only the area geometries and keeps the
    existing points.

    Attributes:
        node_model_df (pd.DataFrame): Node-level data with area assignments
        area_column (str): Column name containing area identifiers
        geo_location_column (str): Column name containing geographic Point objects

    Examples:
        >>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
        >>> generator.generate_area_model()
                 node_count         projection_point
        country
        C1              2.0   POINT (6.3888 47.0112)
        C2              2.0  POINT (10.3888 47.0112)
    """

    def __init__(
        self,
        node_model_df: pd.DataFrame,
        area_column: str,
        geo_location_column: str = None,
    ):
        """Initialize the area model generator.

        Args:
            node_model_df: DataFrame containing node-level data with area assignments.
                Must contain area_column with area identifiers for each node.
                May contain geographic Point objects for spatial analysis.
            area_column: Column name in node_model_df containing area assignments
                (e.g., 'country', 'bidding_zone', 'market_region', 'control_area').
            geo_location_column: Column name containing geographic Point objects
                for representative point calculation. If None, automatically
                detects column containing Point geometries.

        Raises:
            ValueError: If area_column is not found in node_model_df columns.
        """
        self.node_model_df = node_model_df
        self.area_column = area_column
        self.geo_location_column = geo_location_column or self._identify_geo_location_column()
        self._check_area_column()

    def _identify_geo_location_column(self) -> str | None:
        for c in self.node_model_df.columns:
            if all(isinstance(i, Point) or i is None for i in self.node_model_df[c].values):
                return c
        return None

    def generate_base_area_model_from_area_names_in_node_model_df(self) -> pd.DataFrame:
        """Generate base area model DataFrame from unique area names in node data.

        Creates a minimal area model DataFrame containing only the unique area
        identifiers found in the node model data. This forms the foundation
        for building area models.

        Returns:
            pd.DataFrame: Base area model with area identifiers as index.
                Contains no additional columns - serves as starting point
                for enhancement with node counts, geographic data, etc.

        Note:
            Nodes without an area (`AreaMembership.has_area`) add no area
            to the generated model.
        """
        unique_areas = self.get_node_areas().unique()
        area_model_df = pd.DataFrame(index=unique_areas)
        area_model_df.index.name = self.area_column
        return area_model_df

    def ensure_completeness_of_area_model_df(self, area_model_df: pd.DataFrame) -> pd.DataFrame:
        """Ensure area model contains all areas present in node data.

        Validates and extends an existing area model DataFrame to include
        any areas found in the node data that might be missing from the
        provided area model. This is useful when working with predefined
        area models that may not cover all areas in the dataset.

        Args:
            area_model_df: Existing area model DataFrame to validate and extend.

        Returns:
            pd.DataFrame: Complete area model containing all areas from node data.
                Existing data is preserved, new areas are added with NaN values
                for existing columns.

        Examples:
            >>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
            >>> partial = pd.DataFrame({'max_price': [3000.0]}, index=pd.Index(['C1'], name='country'))
            >>> generator.ensure_completeness_of_area_model_df(partial)
                     max_price
            country
            C1          3000.0
            C2             NaN
        """
        complete_set = area_model_df.index.to_list()
        for a in self.get_node_areas().unique():
            if a not in complete_set:
                complete_set.append(a)
        return area_model_df.reindex(complete_set)

    def enhance_area_model_df_by_adding_node_count_per_area(
        self, area_model_df: pd.DataFrame, node_count_column_name: str = 'node_count'
    ) -> pd.DataFrame:
        """Enhance area model by adding node count statistics per area.

        Aggregates the number of nodes assigned to each area and adds this
        information to the area model DataFrame.

        Args:
            area_model_df: Base area model DataFrame to enhance.
            node_count_column_name: Name for the new node count column.
                Defaults to 'node_count'.

        Returns:
            pd.DataFrame: Enhanced area model with node count column added.
                Existing data is preserved, node counts are added for all areas.
                Areas not present in node data will have NaN node counts.
        """
        enhanced_df = area_model_df.copy()
        node_counts = self.get_node_areas().value_counts().to_dict()
        for node, count in node_counts.items():
            if node in enhanced_df.index:
                enhanced_df.loc[node, node_count_column_name] = count
        return enhanced_df

    def enhance_area_model_df_by_adding_representative_geo_point(
        self,
        area_model_df: pd.DataFrame | gpd.GeoDataFrame,
        target_column_name: str = 'projection_point',
        round_point_decimals: int = 4,
    ) -> pd.DataFrame:
        """Enhance area model by adding representative geographic points for
        labeling and KPI printing in map visualizations.

        An area that already has a point keeps it. If the model has a
        `geometry` column, the point comes from the polygon of the area; an
        area without a polygon gets no point. Else the point comes from the
        locations of the nodes of the area (`geo_location_column`).

        Args:
            area_model_df: Area model DataFrame to enhance. Can be regular DataFrame
                or GeoDataFrame with 'geometry' column.
            target_column_name: Name for the new representative point column.
                Defaults to 'projection_point'.
            round_point_decimals: Number of decimal places for coordinate rounding.
                Set to None to disable rounding. Defaults to 4.

        Returns:
            pd.DataFrame: Enhanced area model with representative points added.
                Points are added as Shapely Point objects suitable for mapping
                and spatial analysis.

        Raises:
            TypeError: If geo_location_column contains non-Point objects.
        """
        enhanced_df = area_model_df.copy()

        def round_point(point: Point | None) -> Point | None:
            if point is None or round_point_decimals is None:
                return point
            return type(point)(round(point.x, round_point_decimals), round(point.y, round_point_decimals))

        if target_column_name not in enhanced_df:
            enhanced_df[target_column_name] = None

        for area in enhanced_df.index:
            if pd.notna(enhanced_df.loc[area, target_column_name]):
                continue
            if 'geometry' in enhanced_df.columns:
                geo = enhanced_df.loc[area, 'geometry']
                if pd.notna(geo) and isinstance(geo, (Polygon, MultiPolygon)):
                    enhanced_df.loc[area, target_column_name] = round_point(self.get_representative_area_point(geo))
            elif self.geo_location_column:
                nodes = self.node_model_df.loc[self.node_model_df[self.area_column] == area, self.geo_location_column]
                nodes = nodes.dropna()
                if not nodes.empty:
                    locations = [n for n in nodes.values if n is not None]
                    if not all(isinstance(i, Point) for i in locations):
                        raise TypeError(
                            f'Geographic location column "{self.geo_location_column}" must contain only '
                            f'Point objects. Found: {[type(i).__name__ for i in locations if not isinstance(i, Point)]}'
                        )
                    representative_point = self._compute_representative_point_from_cloud_of_2d_points(locations)
                    enhanced_df.loc[area, target_column_name] = round_point(representative_point)
        return enhanced_df

    def generate_area_model(self) -> pd.DataFrame:
        """Generate complete area model with node counts and representative points.

        One row per area of the node model, with the node count and the
        representative point of the node locations.

        Returns:
            pd.DataFrame: Complete area model. Index contains area identifiers,
                columns are 'node_count' and 'projection_point'.
                'projection_point' is None where no node location is available.
        """
        area_model_df = self.generate_base_area_model_from_area_names_in_node_model_df()
        area_model_df = self.enhance_area_model_df_by_adding_node_count_per_area(area_model_df)
        area_model_df = self.enhance_area_model_df_by_adding_representative_geo_point(area_model_df)
        return area_model_df

    def enhance_with_geometry(self, area_model_df: pd.DataFrame, area_gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
        """Add the area polygons of a GeoDataFrame to the area model.

        Areas are matched by index. The result is a GeoDataFrame.

        Args:
            area_model_df: Area model DataFrame to enhance with geometry.
            area_gdf: GeoDataFrame containing area polygon geometries.
                Must have 'geometry' column with Polygon or MultiPolygon objects.
                Areas are matched by index values.

        Returns:
            gpd.GeoDataFrame: Enhanced area model as GeoDataFrame with geometry column.
                All original data is preserved, geometry column is added for areas
                that exist in both DataFrames. Missing geometries are set to None.

        Examples:
            >>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
            >>> areas = generator.enhance_with_geometry(generator.generate_area_model(), dataset.fetch('Country.Model'))
            >>> areas['geometry'].tolist()
            [<POLYGON ((9 46, 9 50, 5 50, 5 46, 9 46))>, <POLYGON ((13 46, 13 50, 9 50, 9 46, 13 46))>]
        """
        enhanced_df = area_model_df.copy()
        if 'geometry' not in enhanced_df.columns:
            enhanced_df['geometry'] = None
        for area in area_model_df.index:
            if area in area_gdf.index:
                enhanced_df.loc[area, 'geometry'] = area_gdf.loc[area, 'geometry']
        if not isinstance(enhanced_df, gpd.GeoDataFrame):
            enhanced_df = gpd.GeoDataFrame(enhanced_df, geometry='geometry')
        return enhanced_df

__init__

__init__(node_model_df: DataFrame, area_column: str, geo_location_column: str = None)

Initialize the area model generator.

Parameters:

Name Type Description Default
node_model_df DataFrame

DataFrame containing node-level data with area assignments. Must contain area_column with area identifiers for each node. May contain geographic Point objects for spatial analysis.

required
area_column str

Column name in node_model_df containing area assignments (e.g., 'country', 'bidding_zone', 'market_region', 'control_area').

required
geo_location_column str

Column name containing geographic Point objects for representative point calculation. If None, automatically detects column containing Point geometries.

None

Raises:

Type Description
ValueError

If area_column is not found in node_model_df columns.

Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.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
def __init__(
    self,
    node_model_df: pd.DataFrame,
    area_column: str,
    geo_location_column: str = None,
):
    """Initialize the area model generator.

    Args:
        node_model_df: DataFrame containing node-level data with area assignments.
            Must contain area_column with area identifiers for each node.
            May contain geographic Point objects for spatial analysis.
        area_column: Column name in node_model_df containing area assignments
            (e.g., 'country', 'bidding_zone', 'market_region', 'control_area').
        geo_location_column: Column name containing geographic Point objects
            for representative point calculation. If None, automatically
            detects column containing Point geometries.

    Raises:
        ValueError: If area_column is not found in node_model_df columns.
    """
    self.node_model_df = node_model_df
    self.area_column = area_column
    self.geo_location_column = geo_location_column or self._identify_geo_location_column()
    self._check_area_column()

generate_base_area_model_from_area_names_in_node_model_df

generate_base_area_model_from_area_names_in_node_model_df() -> DataFrame

Generate base area model DataFrame from unique area names in node data.

Creates a minimal area model DataFrame containing only the unique area identifiers found in the node model data. This forms the foundation for building area models.

Returns:

Type Description
DataFrame

pd.DataFrame: Base area model with area identifiers as index. Contains no additional columns - serves as starting point for enhancement with node counts, geographic data, etc.

Note

Nodes without an area (AreaMembership.has_area) add no area to the generated model.

Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def generate_base_area_model_from_area_names_in_node_model_df(self) -> pd.DataFrame:
    """Generate base area model DataFrame from unique area names in node data.

    Creates a minimal area model DataFrame containing only the unique area
    identifiers found in the node model data. This forms the foundation
    for building area models.

    Returns:
        pd.DataFrame: Base area model with area identifiers as index.
            Contains no additional columns - serves as starting point
            for enhancement with node counts, geographic data, etc.

    Note:
        Nodes without an area (`AreaMembership.has_area`) add no area
        to the generated model.
    """
    unique_areas = self.get_node_areas().unique()
    area_model_df = pd.DataFrame(index=unique_areas)
    area_model_df.index.name = self.area_column
    return area_model_df

ensure_completeness_of_area_model_df

ensure_completeness_of_area_model_df(area_model_df: DataFrame) -> DataFrame

Ensure area model contains all areas present in node data.

Validates and extends an existing area model DataFrame to include any areas found in the node data that might be missing from the provided area model. This is useful when working with predefined area models that may not cover all areas in the dataset.

Parameters:

Name Type Description Default
area_model_df DataFrame

Existing area model DataFrame to validate and extend.

required

Returns:

Type Description
DataFrame

pd.DataFrame: Complete area model containing all areas from node data. Existing data is preserved, new areas are added with NaN values for existing columns.

Examples:

>>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
>>> partial = pd.DataFrame({'max_price': [3000.0]}, index=pd.Index(['C1'], name='country'))
>>> generator.ensure_completeness_of_area_model_df(partial)
         max_price
country
C1          3000.0
C2             NaN
Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
 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
def ensure_completeness_of_area_model_df(self, area_model_df: pd.DataFrame) -> pd.DataFrame:
    """Ensure area model contains all areas present in node data.

    Validates and extends an existing area model DataFrame to include
    any areas found in the node data that might be missing from the
    provided area model. This is useful when working with predefined
    area models that may not cover all areas in the dataset.

    Args:
        area_model_df: Existing area model DataFrame to validate and extend.

    Returns:
        pd.DataFrame: Complete area model containing all areas from node data.
            Existing data is preserved, new areas are added with NaN values
            for existing columns.

    Examples:
        >>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
        >>> partial = pd.DataFrame({'max_price': [3000.0]}, index=pd.Index(['C1'], name='country'))
        >>> generator.ensure_completeness_of_area_model_df(partial)
                 max_price
        country
        C1          3000.0
        C2             NaN
    """
    complete_set = area_model_df.index.to_list()
    for a in self.get_node_areas().unique():
        if a not in complete_set:
            complete_set.append(a)
    return area_model_df.reindex(complete_set)

enhance_area_model_df_by_adding_node_count_per_area

enhance_area_model_df_by_adding_node_count_per_area(area_model_df: DataFrame, node_count_column_name: str = 'node_count') -> DataFrame

Enhance area model by adding node count statistics per area.

Aggregates the number of nodes assigned to each area and adds this information to the area model DataFrame.

Parameters:

Name Type Description Default
area_model_df DataFrame

Base area model DataFrame to enhance.

required
node_count_column_name str

Name for the new node count column. Defaults to 'node_count'.

'node_count'

Returns:

Type Description
DataFrame

pd.DataFrame: Enhanced area model with node count column added. Existing data is preserved, node counts are added for all areas. Areas not present in node data will have NaN node counts.

Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def enhance_area_model_df_by_adding_node_count_per_area(
    self, area_model_df: pd.DataFrame, node_count_column_name: str = 'node_count'
) -> pd.DataFrame:
    """Enhance area model by adding node count statistics per area.

    Aggregates the number of nodes assigned to each area and adds this
    information to the area model DataFrame.

    Args:
        area_model_df: Base area model DataFrame to enhance.
        node_count_column_name: Name for the new node count column.
            Defaults to 'node_count'.

    Returns:
        pd.DataFrame: Enhanced area model with node count column added.
            Existing data is preserved, node counts are added for all areas.
            Areas not present in node data will have NaN node counts.
    """
    enhanced_df = area_model_df.copy()
    node_counts = self.get_node_areas().value_counts().to_dict()
    for node, count in node_counts.items():
        if node in enhanced_df.index:
            enhanced_df.loc[node, node_count_column_name] = count
    return enhanced_df

enhance_area_model_df_by_adding_representative_geo_point

enhance_area_model_df_by_adding_representative_geo_point(area_model_df: DataFrame | GeoDataFrame, target_column_name: str = 'projection_point', round_point_decimals: int = 4) -> DataFrame

Enhance area model by adding representative geographic points for labeling and KPI printing in map visualizations.

An area that already has a point keeps it. If the model has a geometry column, the point comes from the polygon of the area; an area without a polygon gets no point. Else the point comes from the locations of the nodes of the area (geo_location_column).

Parameters:

Name Type Description Default
area_model_df DataFrame | GeoDataFrame

Area model DataFrame to enhance. Can be regular DataFrame or GeoDataFrame with 'geometry' column.

required
target_column_name str

Name for the new representative point column. Defaults to 'projection_point'.

'projection_point'
round_point_decimals int

Number of decimal places for coordinate rounding. Set to None to disable rounding. Defaults to 4.

4

Returns:

Type Description
DataFrame

pd.DataFrame: Enhanced area model with representative points added. Points are added as Shapely Point objects suitable for mapping and spatial analysis.

Raises:

Type Description
TypeError

If geo_location_column contains non-Point objects.

Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
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
def enhance_area_model_df_by_adding_representative_geo_point(
    self,
    area_model_df: pd.DataFrame | gpd.GeoDataFrame,
    target_column_name: str = 'projection_point',
    round_point_decimals: int = 4,
) -> pd.DataFrame:
    """Enhance area model by adding representative geographic points for
    labeling and KPI printing in map visualizations.

    An area that already has a point keeps it. If the model has a
    `geometry` column, the point comes from the polygon of the area; an
    area without a polygon gets no point. Else the point comes from the
    locations of the nodes of the area (`geo_location_column`).

    Args:
        area_model_df: Area model DataFrame to enhance. Can be regular DataFrame
            or GeoDataFrame with 'geometry' column.
        target_column_name: Name for the new representative point column.
            Defaults to 'projection_point'.
        round_point_decimals: Number of decimal places for coordinate rounding.
            Set to None to disable rounding. Defaults to 4.

    Returns:
        pd.DataFrame: Enhanced area model with representative points added.
            Points are added as Shapely Point objects suitable for mapping
            and spatial analysis.

    Raises:
        TypeError: If geo_location_column contains non-Point objects.
    """
    enhanced_df = area_model_df.copy()

    def round_point(point: Point | None) -> Point | None:
        if point is None or round_point_decimals is None:
            return point
        return type(point)(round(point.x, round_point_decimals), round(point.y, round_point_decimals))

    if target_column_name not in enhanced_df:
        enhanced_df[target_column_name] = None

    for area in enhanced_df.index:
        if pd.notna(enhanced_df.loc[area, target_column_name]):
            continue
        if 'geometry' in enhanced_df.columns:
            geo = enhanced_df.loc[area, 'geometry']
            if pd.notna(geo) and isinstance(geo, (Polygon, MultiPolygon)):
                enhanced_df.loc[area, target_column_name] = round_point(self.get_representative_area_point(geo))
        elif self.geo_location_column:
            nodes = self.node_model_df.loc[self.node_model_df[self.area_column] == area, self.geo_location_column]
            nodes = nodes.dropna()
            if not nodes.empty:
                locations = [n for n in nodes.values if n is not None]
                if not all(isinstance(i, Point) for i in locations):
                    raise TypeError(
                        f'Geographic location column "{self.geo_location_column}" must contain only '
                        f'Point objects. Found: {[type(i).__name__ for i in locations if not isinstance(i, Point)]}'
                    )
                representative_point = self._compute_representative_point_from_cloud_of_2d_points(locations)
                enhanced_df.loc[area, target_column_name] = round_point(representative_point)
    return enhanced_df

generate_area_model

generate_area_model() -> DataFrame

Generate complete area model with node counts and representative points.

One row per area of the node model, with the node count and the representative point of the node locations.

Returns:

Type Description
DataFrame

pd.DataFrame: Complete area model. Index contains area identifiers, columns are 'node_count' and 'projection_point'. 'projection_point' is None where no node location is available.

Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def generate_area_model(self) -> pd.DataFrame:
    """Generate complete area model with node counts and representative points.

    One row per area of the node model, with the node count and the
    representative point of the node locations.

    Returns:
        pd.DataFrame: Complete area model. Index contains area identifiers,
            columns are 'node_count' and 'projection_point'.
            'projection_point' is None where no node location is available.
    """
    area_model_df = self.generate_base_area_model_from_area_names_in_node_model_df()
    area_model_df = self.enhance_area_model_df_by_adding_node_count_per_area(area_model_df)
    area_model_df = self.enhance_area_model_df_by_adding_representative_geo_point(area_model_df)
    return area_model_df

enhance_with_geometry

enhance_with_geometry(area_model_df: DataFrame, area_gdf: GeoDataFrame) -> GeoDataFrame

Add the area polygons of a GeoDataFrame to the area model.

Areas are matched by index. The result is a GeoDataFrame.

Parameters:

Name Type Description Default
area_model_df DataFrame

Area model DataFrame to enhance with geometry.

required
area_gdf GeoDataFrame

GeoDataFrame containing area polygon geometries. Must have 'geometry' column with Polygon or MultiPolygon objects. Areas are matched by index values.

required

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: Enhanced area model as GeoDataFrame with geometry column. All original data is preserved, geometry column is added for areas that exist in both DataFrames. Missing geometries are set to None.

Examples:

>>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
>>> areas = generator.enhance_with_geometry(generator.generate_area_model(), dataset.fetch('Country.Model'))
>>> areas['geometry'].tolist()
[<POLYGON ((9 46, 9 50, 5 50, 5 46, 9 46))>, <POLYGON ((13 46, 13 50, 9 50, 9 46, 13 46))>]
Source code in src/mesqual/energy_data_handling/area_accounting/area_model_generator.py
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
def enhance_with_geometry(self, area_model_df: pd.DataFrame, area_gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
    """Add the area polygons of a GeoDataFrame to the area model.

    Areas are matched by index. The result is a GeoDataFrame.

    Args:
        area_model_df: Area model DataFrame to enhance with geometry.
        area_gdf: GeoDataFrame containing area polygon geometries.
            Must have 'geometry' column with Polygon or MultiPolygon objects.
            Areas are matched by index values.

    Returns:
        gpd.GeoDataFrame: Enhanced area model as GeoDataFrame with geometry column.
            All original data is preserved, geometry column is added for areas
            that exist in both DataFrames. Missing geometries are set to None.

    Examples:
        >>> generator = AreaModelGenerator(dataset.fetch('Node.Model'), 'country')
        >>> areas = generator.enhance_with_geometry(generator.generate_area_model(), dataset.fetch('Country.Model'))
        >>> areas['geometry'].tolist()
        [<POLYGON ((9 46, 9 50, 5 50, 5 46, 9 46))>, <POLYGON ((13 46, 13 50, 9 50, 9 46, 13 46))>]
    """
    enhanced_df = area_model_df.copy()
    if 'geometry' not in enhanced_df.columns:
        enhanced_df['geometry'] = None
    for area in area_model_df.index:
        if area in area_gdf.index:
            enhanced_df.loc[area, 'geometry'] = area_gdf.loc[area, 'geometry']
    if not isinstance(enhanced_df, gpd.GeoDataFrame):
        enhanced_df = gpd.GeoDataFrame(enhanced_df, geometry='geometry')
    return enhanced_df

Border models: the borders between areas from the line topology, with naming conventions and geometry.

AreaBorderNamingConventions

Standardized naming conventions for energy system area borders.

This class provides consistent naming patterns for borders between energy system areas (countries, bidding zones, market regions). It ensures standardized naming across different analysis workflows and supports bidirectional relationship management.

It gives:

  • Border names in both directions (A - B and B - A) and the opposite border of a border.
  • Canonical border names: the area names in alphabetical order.
  • The column names of the border model, configurable per instance.

Attributes:

Name Type Description
area_column str

Name of the area column.

border_identifier str

Name of the border column. Default: '{area_column}_border'.

source_area_identifier str

Name of the source area column. Default: AreaMembership.AREA_FROM ('area_from').

target_area_identifier str

Name of the target area column. Default: AreaMembership.AREA_TO ('area_to').

JOIN_AREA_NAMES_BY str

Separator for area names in border identifiers

OPPOSITE_BORDER_IDENTIFIER str

Column name for opposite border references

CANONICAL_BORDER_IDENTIFIER str

Column name for the canonical border of each border: the border with the area names in alphabetical order

IS_CANONICAL_IDENTIFIER str

Column name for the boolean that is True where the border is its canonical border

Examples:

>>> conventions = AreaBorderNamingConventions('country')
>>> conventions.get_area_border_name('C1', 'C2')
'C1 - C2'
>>> conventions.get_opposite_area_border_name('C1 - C2')
'C2 - C1'
>>> conventions.get_canonical_border('C2 - C1')
'C1 - C2'
>>> conventions.border_identifier
'country_border'
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
 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
class AreaBorderNamingConventions:
    """Standardized naming conventions for energy system area borders.

    This class provides consistent naming patterns for borders between energy
    system areas (countries, bidding zones, market regions). It ensures
    standardized naming across different analysis workflows and supports
    bidirectional relationship management.

    It gives:

    - Border names in both directions (A - B and B - A) and the opposite
      border of a border.
    - Canonical border names: the area names in alphabetical order.
    - The column names of the border model, configurable per instance.

    Attributes:
        area_column (str): Name of the area column.
        border_identifier (str): Name of the border column. Default:
            '{area_column}_border'.
        source_area_identifier (str): Name of the source area column. Default:
            `AreaMembership.AREA_FROM` ('area_from').
        target_area_identifier (str): Name of the target area column. Default:
            `AreaMembership.AREA_TO` ('area_to').
        JOIN_AREA_NAMES_BY (str): Separator for area names in border identifiers
        OPPOSITE_BORDER_IDENTIFIER (str): Column name for opposite border references
        CANONICAL_BORDER_IDENTIFIER (str): Column name for the canonical border
            of each border: the border with the area names in alphabetical order
        IS_CANONICAL_IDENTIFIER (str): Column name for the boolean that is True
            where the border is its canonical border

    Examples:
        >>> conventions = AreaBorderNamingConventions('country')
        >>> conventions.get_area_border_name('C1', 'C2')
        'C1 - C2'
        >>> conventions.get_opposite_area_border_name('C1 - C2')
        'C2 - C1'
        >>> conventions.get_canonical_border('C2 - C1')
        'C1 - C2'
        >>> conventions.border_identifier
        'country_border'
    """

    JOIN_AREA_NAMES_BY = ' - '
    OPPOSITE_BORDER_IDENTIFIER = 'opposite_border'
    CANONICAL_BORDER_IDENTIFIER = 'canonical_border'
    IS_CANONICAL_IDENTIFIER = 'is_canonical'
    PROJECTION_POINT_IDENTIFIER = AreaBorderGeometryCalculator.PROJECTION_POINT_IDENTIFIER
    AZIMUTH_ANGLE_IDENTIFIER = AreaBorderGeometryCalculator.AZIMUTH_ANGLE_IDENTIFIER
    BORDER_AREAS_TOUCH_IDENTIFIER = AreaBorderGeometryCalculator.BORDER_AREAS_TOUCH_IDENTIFIER
    BORDER_LINE_STRING_IDENTIFIER = AreaBorderGeometryCalculator.BORDER_LINE_STRING_IDENTIFIER

    def __init__(
        self,
        area_column: str,
        border_identifier: str = None,
        source_area_identifier: str = None,
        target_area_identifier: str = None,
    ):
        """Initialize border naming conventions.

        Args:
            area_column: Name of the area column (e.g., 'country', 'bidding_zone')
            border_identifier: Custom name for border identifier column.
                Defaults to '{area_column}_border'
            source_area_identifier: Name of the source area column.
                Defaults to `AreaMembership.AREA_FROM` ('area_from').
            target_area_identifier: Name of the target area column.
                Defaults to `AreaMembership.AREA_TO` ('area_to').
        """
        self.area_column = area_column
        self.border_identifier = border_identifier or f'{area_column}_border'
        self.source_area_identifier = source_area_identifier or AreaMembership.AREA_FROM
        self.target_area_identifier = target_area_identifier or AreaMembership.AREA_TO

    def get_area_border_name(self, area_from: str, area_to: str) -> str:
        """Generate standardized border name from source and target areas.

        Args:
            area_from: Source area identifier (e.g., 'DE', 'FR_North')
            area_to: Target area identifier (e.g., 'FR', 'DE_South')

        Returns:
            str: Formatted border name using the configured separator (e.g. 'DE - FR', 'FR_North - DE_South')
        """
        return f'{area_from}{self.JOIN_AREA_NAMES_BY}{area_to}'

    def decompose_area_border_name_to_areas(self, border_name: str) -> Tuple[str, str]:
        """Extract source and target area names from border identifier.

        Args:
            border_name: Border name in standard format (e.g., 'DE - FR')

        Returns:
            Tuple[str, str]: Source and target area names

        Raises:
            ValueError: If border_name doesn't contain the expected separator

        Examples:
            >>> AreaBorderNamingConventions('country').decompose_area_border_name_to_areas('C1 - C2')
            ('C1', 'C2')
        """
        area_from, area_to = border_name.split(self.JOIN_AREA_NAMES_BY)
        return area_from, area_to

    def get_opposite_area_border_name(self, border_name: str) -> str:
        """Generate the opposite direction border name.

        Args:
            border_name: Original border name (e.g., 'DE - FR')

        Returns:
            str: Opposite direction border name (e.g., 'FR - DE')
        """
        area_from, area_to = self.decompose_area_border_name_to_areas(border_name)
        return self.get_area_border_name(area_to, area_from)

    def get_canonical_border(self, border_name: str) -> str:
        """Return the canonical border of a border.

        The canonical border has the area names in alphabetical order. A border
        and its opposite border have the same canonical border. Use it to
        identify a pair of borders regardless of direction, or to match borders
        of opposite direction.

        Args:
            border_name: Border name in any direction (e.g., 'FR - DE' or 'DE - FR')

        Returns:
            str: Canonical border name (e.g., 'DE - FR')
        """
        area_from, area_to = self.decompose_area_border_name_to_areas(border_name)
        return self.get_area_border_name(*list(sorted([area_from, area_to])))

__init__

__init__(area_column: str, border_identifier: str = None, source_area_identifier: str = None, target_area_identifier: str = None)

Initialize border naming conventions.

Parameters:

Name Type Description Default
area_column str

Name of the area column (e.g., 'country', 'bidding_zone')

required
border_identifier str

Custom name for border identifier column. Defaults to '{area_column}_border'

None
source_area_identifier str

Name of the source area column. Defaults to AreaMembership.AREA_FROM ('area_from').

None
target_area_identifier str

Name of the target area column. Defaults to AreaMembership.AREA_TO ('area_to').

None
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    area_column: str,
    border_identifier: str = None,
    source_area_identifier: str = None,
    target_area_identifier: str = None,
):
    """Initialize border naming conventions.

    Args:
        area_column: Name of the area column (e.g., 'country', 'bidding_zone')
        border_identifier: Custom name for border identifier column.
            Defaults to '{area_column}_border'
        source_area_identifier: Name of the source area column.
            Defaults to `AreaMembership.AREA_FROM` ('area_from').
        target_area_identifier: Name of the target area column.
            Defaults to `AreaMembership.AREA_TO` ('area_to').
    """
    self.area_column = area_column
    self.border_identifier = border_identifier or f'{area_column}_border'
    self.source_area_identifier = source_area_identifier or AreaMembership.AREA_FROM
    self.target_area_identifier = target_area_identifier or AreaMembership.AREA_TO

get_area_border_name

get_area_border_name(area_from: str, area_to: str) -> str

Generate standardized border name from source and target areas.

Parameters:

Name Type Description Default
area_from str

Source area identifier (e.g., 'DE', 'FR_North')

required
area_to str

Target area identifier (e.g., 'FR', 'DE_South')

required

Returns:

Name Type Description
str str

Formatted border name using the configured separator (e.g. 'DE - FR', 'FR_North - DE_South')

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def get_area_border_name(self, area_from: str, area_to: str) -> str:
    """Generate standardized border name from source and target areas.

    Args:
        area_from: Source area identifier (e.g., 'DE', 'FR_North')
        area_to: Target area identifier (e.g., 'FR', 'DE_South')

    Returns:
        str: Formatted border name using the configured separator (e.g. 'DE - FR', 'FR_North - DE_South')
    """
    return f'{area_from}{self.JOIN_AREA_NAMES_BY}{area_to}'

decompose_area_border_name_to_areas

decompose_area_border_name_to_areas(border_name: str) -> tuple[str, str]

Extract source and target area names from border identifier.

Parameters:

Name Type Description Default
border_name str

Border name in standard format (e.g., 'DE - FR')

required

Returns:

Type Description
tuple[str, str]

Tuple[str, str]: Source and target area names

Raises:

Type Description
ValueError

If border_name doesn't contain the expected separator

Examples:

>>> AreaBorderNamingConventions('country').decompose_area_border_name_to_areas('C1 - C2')
('C1', 'C2')
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def decompose_area_border_name_to_areas(self, border_name: str) -> Tuple[str, str]:
    """Extract source and target area names from border identifier.

    Args:
        border_name: Border name in standard format (e.g., 'DE - FR')

    Returns:
        Tuple[str, str]: Source and target area names

    Raises:
        ValueError: If border_name doesn't contain the expected separator

    Examples:
        >>> AreaBorderNamingConventions('country').decompose_area_border_name_to_areas('C1 - C2')
        ('C1', 'C2')
    """
    area_from, area_to = border_name.split(self.JOIN_AREA_NAMES_BY)
    return area_from, area_to

get_opposite_area_border_name

get_opposite_area_border_name(border_name: str) -> str

Generate the opposite direction border name.

Parameters:

Name Type Description Default
border_name str

Original border name (e.g., 'DE - FR')

required

Returns:

Name Type Description
str str

Opposite direction border name (e.g., 'FR - DE')

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
121
122
123
124
125
126
127
128
129
130
131
def get_opposite_area_border_name(self, border_name: str) -> str:
    """Generate the opposite direction border name.

    Args:
        border_name: Original border name (e.g., 'DE - FR')

    Returns:
        str: Opposite direction border name (e.g., 'FR - DE')
    """
    area_from, area_to = self.decompose_area_border_name_to_areas(border_name)
    return self.get_area_border_name(area_to, area_from)

get_canonical_border

get_canonical_border(border_name: str) -> str

Return the canonical border of a border.

The canonical border has the area names in alphabetical order. A border and its opposite border have the same canonical border. Use it to identify a pair of borders regardless of direction, or to match borders of opposite direction.

Parameters:

Name Type Description Default
border_name str

Border name in any direction (e.g., 'FR - DE' or 'DE - FR')

required

Returns:

Name Type Description
str str

Canonical border name (e.g., 'DE - FR')

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def get_canonical_border(self, border_name: str) -> str:
    """Return the canonical border of a border.

    The canonical border has the area names in alphabetical order. A border
    and its opposite border have the same canonical border. Use it to
    identify a pair of borders regardless of direction, or to match borders
    of opposite direction.

    Args:
        border_name: Border name in any direction (e.g., 'FR - DE' or 'DE - FR')

    Returns:
        str: Canonical border name (e.g., 'DE - FR')
    """
    area_from, area_to = self.decompose_area_border_name_to_areas(border_name)
    return self.get_area_border_name(*list(sorted([area_from, area_to])))

AreaBorderModelGenerator

Bases: AreaBorderNamingConventions, AreaMembership

Border model from the lines and the area of each node.

line_areas maps the two ends of each line to their areas (AreaMembership.edge_areas), in the columns source_area_identifier and target_area_identifier (default area_from and area_to). A line between two different areas gives two borders, one per direction. A line inside one area, or with an end without area, gives no border. The borders follow the order of the lines. Each border has its source and target area, its opposite border, its canonical border and is_canonical (AreaBorderNamingConventions).

Attributes:

Name Type Description
line_model_df DataFrame

Line model, one row per line.

node_model_df DataFrame

Node model with the area column.

node_from_col str

Column of line_model_df with the first node.

node_to_col str

Column of line_model_df with the second node.

line_areas DataFrame

The source and target area per line.

Examples:

>>> generator = AreaBorderModelGenerator(
...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
... )
>>> generator.generate_area_border_model()
               area_from area_to opposite_border canonical_border  is_canonical
country_border
C1 - C2               C1      C2         C2 - C1          C1 - C2          True
C2 - C1               C2      C1         C1 - C2          C1 - C2         False
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
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
210
211
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
class AreaBorderModelGenerator(AreaBorderNamingConventions, AreaMembership):
    """Border model from the lines and the area of each node.

    `line_areas` maps the two ends of each line to their areas
    (`AreaMembership.edge_areas`), in the columns `source_area_identifier`
    and `target_area_identifier` (default `area_from` and `area_to`). A line
    between two different areas gives two borders, one per direction. A line
    inside one area, or with an end without area, gives no border. The
    borders follow the order of the lines. Each border has its source and
    target area, its opposite border, its canonical border and
    `is_canonical` (`AreaBorderNamingConventions`).

    Attributes:
        line_model_df (pd.DataFrame): Line model, one row per line.
        node_model_df (pd.DataFrame): Node model with the area column.
        node_from_col (str): Column of `line_model_df` with the first node.
        node_to_col (str): Column of `line_model_df` with the second node.
        line_areas (pd.DataFrame): The source and target area per line.

    Examples:
        >>> generator = AreaBorderModelGenerator(
        ...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
        ... )
        >>> generator.generate_area_border_model()
                       area_from area_to opposite_border canonical_border  is_canonical
        country_border
        C1 - C2               C1      C2         C2 - C1          C1 - C2          True
        C2 - C1               C2      C1         C1 - C2          C1 - C2         False
    """

    def __init__(
        self,
        node_model_df: pd.DataFrame,
        line_model_df: pd.DataFrame,
        area_column: str,
        node_from_col: str,
        node_to_col: str,
        border_identifier: str = None,
        source_area_identifier: str = None,
        target_area_identifier: str = None,
    ):
        """Initialize the area border model generator.

        Args:
            node_model_df: DataFrame containing node-level data with area assignments.
                Must contain area_column with area identifiers for each node.
            line_model_df: DataFrame containing transmission line topology data.
                Must contain node_from_col and node_to_col with node identifiers.
            area_column: Column name in node_model_df containing area assignments
                (e.g., 'country', 'bidding_zone', 'market_region')
            node_from_col: Column name in line_model_df for source node identifiers
            node_to_col: Column name in line_model_df for target node identifiers
            border_identifier: Custom border column name (optional)
            source_area_identifier: Name of the source area column.
                Defaults to `AreaMembership.AREA_FROM` ('area_from').
            target_area_identifier: Name of the target area column.
                Defaults to `AreaMembership.AREA_TO` ('area_to').

        Raises:
            ValueError: If required columns are not found in input DataFrames,
                or if `node_model_df` has a node id more than once.
        """
        super().__init__(area_column, border_identifier, source_area_identifier, target_area_identifier)
        self.line_model_df = line_model_df
        self.node_model_df = node_model_df
        self.node_from_col = node_from_col
        self.node_to_col = node_to_col

        self._validate_inputs()
        self.line_areas = self.edge_areas(
            line_model_df,
            node_model_df[area_column],
            node_from_col,
            node_to_col,
            self.source_area_identifier,
            self.target_area_identifier,
        )

    def _validate_inputs(self):
        self._check_area_column()
        if self.node_from_col not in self.line_model_df.columns:
            raise ValueError(
                f"Source node column '{self.node_from_col}' not found in line_model_df. "
                f'Available columns: {list(self.line_model_df.columns)}'
            )
        if self.node_to_col not in self.line_model_df.columns:
            raise ValueError(
                f"Target node column '{self.node_to_col}' not found in line_model_df. "
                f'Available columns: {list(self.line_model_df.columns)}'
            )

    def generate_area_border_model(self) -> pd.DataFrame:
        """Generate the border model.

        Analyzes transmission line topology to identify borders between areas,
        creating a DataFrame with directional relationships,
        naming conventions, and reference data for further analysis.

        The generated model includes:

        - Border identifiers in both directions (A - B and B - A).
        - Source and target area columns.
        - The opposite border of each border.
        - `canonical_border`: the border of the pair with the area names in alphabetical order.
        - `is_canonical`: True where the border is its canonical border.

        Returns:
            pd.DataFrame: Border model indexed by border identifiers (index
                name `border_identifier`). The rows follow the order of the
                lines: first the area pairs in line direction, then the reverse
                pairs. Without borders, it has no rows and the same index name
                and columns.
        """
        border_data = []
        for area_from, area_to in self._identify_borders():
            border_id = self.get_area_border_name(area_from, area_to)
            opposite_id = self.get_opposite_area_border_name(border_id)

            canonical_border = self.get_canonical_border(border_id)

            border_data.append(
                {
                    self.border_identifier: border_id,
                    self.source_area_identifier: area_from,
                    self.target_area_identifier: area_to,
                    self.OPPOSITE_BORDER_IDENTIFIER: opposite_id,
                    self.CANONICAL_BORDER_IDENTIFIER: canonical_border,
                    self.IS_CANONICAL_IDENTIFIER: canonical_border == border_id,
                }
            )

        columns = [
            self.border_identifier,
            self.source_area_identifier,
            self.target_area_identifier,
            self.OPPOSITE_BORDER_IDENTIFIER,
            self.CANONICAL_BORDER_IDENTIFIER,
            self.IS_CANONICAL_IDENTIFIER,
        ]
        border_model_df = pd.DataFrame(border_data, columns=columns).set_index(self.border_identifier)
        border_model_df = border_model_df.astype({self.IS_CANONICAL_IDENTIFIER: bool})

        return border_model_df

    def _identify_borders(self) -> list[tuple]:
        """Return the `(area_from, area_to)` pairs of `line_areas`, in both directions, in line order.

        A line with both ends in one area, or with an end without an area, gives no border.
        """
        pairs = self.line_areas[self.crosses_border(self.line_areas)]
        area_from, area_to = pairs[self.source_area_identifier], pairs[self.target_area_identifier]
        return list(dict.fromkeys([*zip(area_from, area_to), *zip(area_to, area_from)]))

    def get_area_graph(self) -> nx.Graph:
        """Generate NetworkX graph representation of area connectivity.

        Creates an undirected graph where nodes represent areas and edges
        represent borders. This is useful for network analysis, path finding,
        and connectivity studies in multi-area energy systems.

        Returns:
            nx.Graph: Undirected graph with areas as nodes and borders as edges.
                Graph may contain multiple disconnected components if areas
                are not fully interconnected.

        Examples:
            >>> generator = AreaBorderModelGenerator(
            ...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
            ... )
            >>> list(generator.get_area_graph().edges())
            [('C1', 'C2')]
        """
        graph = nx.Graph()
        graph.add_edges_from(self._identify_borders())
        return graph

    def enhance_with_geometry(
        self, border_model_df: pd.DataFrame, area_geometry_calculator: AreaBorderGeometryCalculator
    ) -> pd.DataFrame:
        """Enhance border model with geometric properties for visualization.

        Uses the AreaBorderGeometryCalculator to add a representative point,
        a direction angle and a line geometry to each border.

        Args:
            border_model_df: Border model DataFrame to enhance
            area_geometry_calculator: Configured geometry calculator with area
                polygon data for geometric computations

        Returns:
            pd.DataFrame: The border model with the columns `projection_point`
                (point for labels and arrows), `azimuth_angle` (direction in
                degrees), `areas_touch` (True when the areas touch or overlap)
                and `geo_line_string` (the border line).

        Examples:
            >>> import geopandas as gpd
            >>> from mesqual.energy_data_handling.area_accounting import AreaBorderGeometryCalculator
            >>> generator = AreaBorderModelGenerator(
            ...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
            ... )
            >>> countries = gpd.GeoDataFrame(dataset.fetch('Country.Model'), crs='EPSG:4326')
            >>> borders = generator.enhance_with_geometry(generator.generate_area_border_model(), AreaBorderGeometryCalculator(countries))
            >>> borders[['azimuth_angle', 'areas_touch']]
                            azimuth_angle  areas_touch
            country_border
            C1 - C2                  90.0         True
            C2 - C1                 270.0         True

        Note:
            The geometry may fail for some borders, for example for a missing
            area geometry. Such a border gets NaN in the geometry columns, and
            the failure is logged at `WARNING`. The other borders get their
            geometry. The result always has the geometry columns.
        """
        columns = list(area_geometry_calculator.GEOMETRY_COLUMNS)
        rows = {}
        for border_id, border in border_model_df.iterrows():
            area_from = border[self.source_area_identifier]
            area_to = border[self.target_area_identifier]
            try:
                geometry_info = area_geometry_calculator.calculate_border_geometry(area_from, area_to)
            except Exception as e:
                logger.warning(
                    'Could not calculate the geometry of border %s (%s to %s): %s',
                    border_id,
                    area_from,
                    area_to,
                    e,
                )
                continue
            rows[border_id] = [geometry_info[column] for column in columns]
        geometry = pd.DataFrame.from_dict(rows, orient='index', columns=columns).reindex(border_model_df.index)
        return border_model_df.drop(columns=columns, errors='ignore').join(geometry)

__init__

__init__(node_model_df: DataFrame, line_model_df: DataFrame, area_column: str, node_from_col: str, node_to_col: str, border_identifier: str = None, source_area_identifier: str = None, target_area_identifier: str = None)

Initialize the area border model generator.

Parameters:

Name Type Description Default
node_model_df DataFrame

DataFrame containing node-level data with area assignments. Must contain area_column with area identifiers for each node.

required
line_model_df DataFrame

DataFrame containing transmission line topology data. Must contain node_from_col and node_to_col with node identifiers.

required
area_column str

Column name in node_model_df containing area assignments (e.g., 'country', 'bidding_zone', 'market_region')

required
node_from_col str

Column name in line_model_df for source node identifiers

required
node_to_col str

Column name in line_model_df for target node identifiers

required
border_identifier str

Custom border column name (optional)

None
source_area_identifier str

Name of the source area column. Defaults to AreaMembership.AREA_FROM ('area_from').

None
target_area_identifier str

Name of the target area column. Defaults to AreaMembership.AREA_TO ('area_to').

None

Raises:

Type Description
ValueError

If required columns are not found in input DataFrames, or if node_model_df has a node id more than once.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def __init__(
    self,
    node_model_df: pd.DataFrame,
    line_model_df: pd.DataFrame,
    area_column: str,
    node_from_col: str,
    node_to_col: str,
    border_identifier: str = None,
    source_area_identifier: str = None,
    target_area_identifier: str = None,
):
    """Initialize the area border model generator.

    Args:
        node_model_df: DataFrame containing node-level data with area assignments.
            Must contain area_column with area identifiers for each node.
        line_model_df: DataFrame containing transmission line topology data.
            Must contain node_from_col and node_to_col with node identifiers.
        area_column: Column name in node_model_df containing area assignments
            (e.g., 'country', 'bidding_zone', 'market_region')
        node_from_col: Column name in line_model_df for source node identifiers
        node_to_col: Column name in line_model_df for target node identifiers
        border_identifier: Custom border column name (optional)
        source_area_identifier: Name of the source area column.
            Defaults to `AreaMembership.AREA_FROM` ('area_from').
        target_area_identifier: Name of the target area column.
            Defaults to `AreaMembership.AREA_TO` ('area_to').

    Raises:
        ValueError: If required columns are not found in input DataFrames,
            or if `node_model_df` has a node id more than once.
    """
    super().__init__(area_column, border_identifier, source_area_identifier, target_area_identifier)
    self.line_model_df = line_model_df
    self.node_model_df = node_model_df
    self.node_from_col = node_from_col
    self.node_to_col = node_to_col

    self._validate_inputs()
    self.line_areas = self.edge_areas(
        line_model_df,
        node_model_df[area_column],
        node_from_col,
        node_to_col,
        self.source_area_identifier,
        self.target_area_identifier,
    )

generate_area_border_model

generate_area_border_model() -> DataFrame

Generate the border model.

Analyzes transmission line topology to identify borders between areas, creating a DataFrame with directional relationships, naming conventions, and reference data for further analysis.

The generated model includes:

  • Border identifiers in both directions (A - B and B - A).
  • Source and target area columns.
  • The opposite border of each border.
  • canonical_border: the border of the pair with the area names in alphabetical order.
  • is_canonical: True where the border is its canonical border.

Returns:

Type Description
DataFrame

pd.DataFrame: Border model indexed by border identifiers (index name border_identifier). The rows follow the order of the lines: first the area pairs in line direction, then the reverse pairs. Without borders, it has no rows and the same index name and columns.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def generate_area_border_model(self) -> pd.DataFrame:
    """Generate the border model.

    Analyzes transmission line topology to identify borders between areas,
    creating a DataFrame with directional relationships,
    naming conventions, and reference data for further analysis.

    The generated model includes:

    - Border identifiers in both directions (A - B and B - A).
    - Source and target area columns.
    - The opposite border of each border.
    - `canonical_border`: the border of the pair with the area names in alphabetical order.
    - `is_canonical`: True where the border is its canonical border.

    Returns:
        pd.DataFrame: Border model indexed by border identifiers (index
            name `border_identifier`). The rows follow the order of the
            lines: first the area pairs in line direction, then the reverse
            pairs. Without borders, it has no rows and the same index name
            and columns.
    """
    border_data = []
    for area_from, area_to in self._identify_borders():
        border_id = self.get_area_border_name(area_from, area_to)
        opposite_id = self.get_opposite_area_border_name(border_id)

        canonical_border = self.get_canonical_border(border_id)

        border_data.append(
            {
                self.border_identifier: border_id,
                self.source_area_identifier: area_from,
                self.target_area_identifier: area_to,
                self.OPPOSITE_BORDER_IDENTIFIER: opposite_id,
                self.CANONICAL_BORDER_IDENTIFIER: canonical_border,
                self.IS_CANONICAL_IDENTIFIER: canonical_border == border_id,
            }
        )

    columns = [
        self.border_identifier,
        self.source_area_identifier,
        self.target_area_identifier,
        self.OPPOSITE_BORDER_IDENTIFIER,
        self.CANONICAL_BORDER_IDENTIFIER,
        self.IS_CANONICAL_IDENTIFIER,
    ]
    border_model_df = pd.DataFrame(border_data, columns=columns).set_index(self.border_identifier)
    border_model_df = border_model_df.astype({self.IS_CANONICAL_IDENTIFIER: bool})

    return border_model_df

get_area_graph

get_area_graph() -> Graph

Generate NetworkX graph representation of area connectivity.

Creates an undirected graph where nodes represent areas and edges represent borders. This is useful for network analysis, path finding, and connectivity studies in multi-area energy systems.

Returns:

Type Description
Graph

nx.Graph: Undirected graph with areas as nodes and borders as edges. Graph may contain multiple disconnected components if areas are not fully interconnected.

Examples:

>>> generator = AreaBorderModelGenerator(
...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
... )
>>> list(generator.get_area_graph().edges())
[('C1', 'C2')]
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def get_area_graph(self) -> nx.Graph:
    """Generate NetworkX graph representation of area connectivity.

    Creates an undirected graph where nodes represent areas and edges
    represent borders. This is useful for network analysis, path finding,
    and connectivity studies in multi-area energy systems.

    Returns:
        nx.Graph: Undirected graph with areas as nodes and borders as edges.
            Graph may contain multiple disconnected components if areas
            are not fully interconnected.

    Examples:
        >>> generator = AreaBorderModelGenerator(
        ...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
        ... )
        >>> list(generator.get_area_graph().edges())
        [('C1', 'C2')]
    """
    graph = nx.Graph()
    graph.add_edges_from(self._identify_borders())
    return graph

enhance_with_geometry

enhance_with_geometry(border_model_df: DataFrame, area_geometry_calculator: AreaBorderGeometryCalculator) -> DataFrame

Enhance border model with geometric properties for visualization.

Uses the AreaBorderGeometryCalculator to add a representative point, a direction angle and a line geometry to each border.

Parameters:

Name Type Description Default
border_model_df DataFrame

Border model DataFrame to enhance

required
area_geometry_calculator AreaBorderGeometryCalculator

Configured geometry calculator with area polygon data for geometric computations

required

Returns:

Type Description
DataFrame

pd.DataFrame: The border model with the columns projection_point (point for labels and arrows), azimuth_angle (direction in degrees), areas_touch (True when the areas touch or overlap) and geo_line_string (the border line).

Examples:

>>> import geopandas as gpd
>>> from mesqual.energy_data_handling.area_accounting import AreaBorderGeometryCalculator
>>> generator = AreaBorderModelGenerator(
...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
... )
>>> countries = gpd.GeoDataFrame(dataset.fetch('Country.Model'), crs='EPSG:4326')
>>> borders = generator.enhance_with_geometry(generator.generate_area_border_model(), AreaBorderGeometryCalculator(countries))
>>> borders[['azimuth_angle', 'areas_touch']]
                azimuth_angle  areas_touch
country_border
C1 - C2                  90.0         True
C2 - C1                 270.0         True
Note

The geometry may fail for some borders, for example for a missing area geometry. Such a border gets NaN in the geometry columns, and the failure is logged at WARNING. The other borders get their geometry. The result always has the geometry columns.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_generator.py
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
def enhance_with_geometry(
    self, border_model_df: pd.DataFrame, area_geometry_calculator: AreaBorderGeometryCalculator
) -> pd.DataFrame:
    """Enhance border model with geometric properties for visualization.

    Uses the AreaBorderGeometryCalculator to add a representative point,
    a direction angle and a line geometry to each border.

    Args:
        border_model_df: Border model DataFrame to enhance
        area_geometry_calculator: Configured geometry calculator with area
            polygon data for geometric computations

    Returns:
        pd.DataFrame: The border model with the columns `projection_point`
            (point for labels and arrows), `azimuth_angle` (direction in
            degrees), `areas_touch` (True when the areas touch or overlap)
            and `geo_line_string` (the border line).

    Examples:
        >>> import geopandas as gpd
        >>> from mesqual.energy_data_handling.area_accounting import AreaBorderGeometryCalculator
        >>> generator = AreaBorderModelGenerator(
        ...     dataset.fetch('Node.Model'), dataset.fetch('Line.Model'), 'country', 'node_from', 'node_to'
        ... )
        >>> countries = gpd.GeoDataFrame(dataset.fetch('Country.Model'), crs='EPSG:4326')
        >>> borders = generator.enhance_with_geometry(generator.generate_area_border_model(), AreaBorderGeometryCalculator(countries))
        >>> borders[['azimuth_angle', 'areas_touch']]
                        azimuth_angle  areas_touch
        country_border
        C1 - C2                  90.0         True
        C2 - C1                 270.0         True

    Note:
        The geometry may fail for some borders, for example for a missing
        area geometry. Such a border gets NaN in the geometry columns, and
        the failure is logged at `WARNING`. The other borders get their
        geometry. The result always has the geometry columns.
    """
    columns = list(area_geometry_calculator.GEOMETRY_COLUMNS)
    rows = {}
    for border_id, border in border_model_df.iterrows():
        area_from = border[self.source_area_identifier]
        area_to = border[self.target_area_identifier]
        try:
            geometry_info = area_geometry_calculator.calculate_border_geometry(area_from, area_to)
        except Exception as e:
            logger.warning(
                'Could not calculate the geometry of border %s (%s to %s): %s',
                border_id,
                area_from,
                area_to,
                e,
            )
            continue
        rows[border_id] = [geometry_info[column] for column in columns]
    geometry = pd.DataFrame.from_dict(rows, orient='index', columns=columns).reindex(border_model_df.index)
    return border_model_df.drop(columns=columns, errors='ignore').join(geometry)

AreaBorderGeometryCalculator

Bases: GeoModelGeneratorBase

Geometry of the border between two areas, for maps of border variables.

Areas that touch have a physical border: the shared boundary line. Areas that do not touch, for example across the sea, have a logical border: the straight line between the boundaries of the largest polygons of the two areas, on the line between their representative points. If this line crosses other areas, the line of NonCrossingPathFinder replaces it when the finder finds one; the finder states its rule. For each border, the calculator gives a line, a point for labels and arrows, and the azimuth angle of the direction from the first to the second area.

Attributes:

Name Type Description
area_model_gdf GeoDataFrame

GeoDataFrame with area polygon geometries

non_crossing_path_finder NonCrossingPathFinder

Path finder for logical borders

Examples:

>>> import geopandas as gpd
>>> countries = gpd.GeoDataFrame(dataset.fetch('Country.Model'), crs='EPSG:4326')
>>> calculator = AreaBorderGeometryCalculator(countries)
>>> calculator.calculate_border_geometry('C1', 'C2')
{'projection_point': <POINT (9 48)>, 'azimuth_angle': 90.0, 'geo_line_string': <LINESTRING (9 50, 9 46)>, 'areas_touch': True}

Two areas that do not touch get a logical border:

>>> from shapely.geometry import box
>>> islands = gpd.GeoDataFrame(geometry=[box(0, 0, 1, 1), box(3, 0, 4, 1)], index=['A', 'B'], crs='EPSG:4326')
>>> AreaBorderGeometryCalculator(islands).calculate_border_geometry('A', 'B')['geo_line_string']
<LINESTRING (1 0.5, 3 0.5)>
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
 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
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
210
211
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
445
446
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
566
567
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
597
598
599
600
601
602
603
604
605
606
607
608
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
class AreaBorderGeometryCalculator(GeoModelGeneratorBase):
    """Geometry of the border between two areas, for maps of border variables.

    Areas that touch have a physical border: the shared boundary line.
    Areas that do not touch, for example across the sea, have a logical
    border: the straight line between the boundaries of the largest polygons
    of the two areas, on the line between their representative points. If
    this line crosses other areas, the line of `NonCrossingPathFinder`
    replaces it when the finder finds one; the finder states its rule. For
    each border, the calculator gives a line, a point for labels and arrows,
    and the azimuth angle of the direction from the first to the second area.

    Attributes:
        area_model_gdf (gpd.GeoDataFrame): GeoDataFrame with area polygon geometries
        non_crossing_path_finder (NonCrossingPathFinder): Path finder for logical borders

    Examples:
        >>> import geopandas as gpd
        >>> countries = gpd.GeoDataFrame(dataset.fetch('Country.Model'), crs='EPSG:4326')
        >>> calculator = AreaBorderGeometryCalculator(countries)
        >>> calculator.calculate_border_geometry('C1', 'C2')
        {'projection_point': <POINT (9 48)>, 'azimuth_angle': 90.0, 'geo_line_string': <LINESTRING (9 50, 9 46)>, 'areas_touch': True}

        Two areas that do not touch get a logical border:

        >>> from shapely.geometry import box
        >>> islands = gpd.GeoDataFrame(geometry=[box(0, 0, 1, 1), box(3, 0, 4, 1)], index=['A', 'B'], crs='EPSG:4326')
        >>> AreaBorderGeometryCalculator(islands).calculate_border_geometry('A', 'B')['geo_line_string']
        <LINESTRING (1 0.5, 3 0.5)>
    """

    PROJECTION_POINT_IDENTIFIER = 'projection_point'
    AZIMUTH_ANGLE_IDENTIFIER = 'azimuth_angle'
    BORDER_AREAS_TOUCH_IDENTIFIER = 'areas_touch'
    BORDER_LINE_STRING_IDENTIFIER = 'geo_line_string'
    GEOMETRY_COLUMNS: ClassVar[tuple[str, ...]] = (
        PROJECTION_POINT_IDENTIFIER,
        AZIMUTH_ANGLE_IDENTIFIER,
        BORDER_AREAS_TOUCH_IDENTIFIER,
        BORDER_LINE_STRING_IDENTIFIER,
    )
    """The keys of `calculate_border_geometry`, in this order."""

    def __init__(self, area_model_gdf: gpd.GeoDataFrame, non_crossing_path_finder: 'NonCrossingPathFinder' = None):
        """Initialize the border geometry calculator.

        Args:
            area_model_gdf: GeoDataFrame containing area geometries with polygon
                boundaries. Index should contain area identifiers (e.g., country codes,
                bidding zone names). Must contain valid polygon geometries in 'geometry' column.
                Without a CRS, the polygons are lon/lat coordinates in EPSG:4326.
                The path of a border between areas that do not touch needs the CRS.
            non_crossing_path_finder: Optional custom path finder for logical borders.
                If None, creates default NonCrossingPathFinder with standard parameters.

        Invalid geometries are cleaned with `buffer(0)`. If `area_model_gdf`
        has a CRS, the cleaning changes it in place.
        """
        self.area_model_gdf = area_model_gdf if area_model_gdf.crs is not None else area_model_gdf.set_crs('EPSG:4326')
        self.non_crossing_path_finder = non_crossing_path_finder or NonCrossingPathFinder()
        self._validate_geometries()

        self._centroid_cache: dict[str, Point] = {}
        self._line_cache: dict[Tuple[str, str], LineString] = {}
        crs = self.area_model_gdf.crs
        self._to_lon_lat = None if crs.is_geographic else Transformer.from_crs(crs, 'EPSG:4326', always_xy=True)

    def _validate_geometries(self):
        """Validate and clean area geometries for reliable calculations.

        Applies buffer(0) operation to fix invalid geometries (self-intersections,
        unclosed rings, etc.) that could cause calculation failures. This is
        particularly important for real-world geographic data that may have
        topology issues.

        Note:
            The buffer(0) operation is a common technique for fixing invalid
            polygon geometries without changing their fundamental shape.
        """
        self.area_model_gdf['geometry'] = self.area_model_gdf['geometry'].apply(
            lambda geom: geom if geom.is_valid else geom.buffer(0)
        )

    def calculate_border_geometry(
        self, area_from: str, area_to: str
    ) -> dict[str, Union[Point, float, LineString, bool]]:
        """Calculate the geometric properties of an area border.

        The steps:

        1. Detect if the areas share a physical boundary (touching or intersecting).
        2. For physical borders: extract the shared boundary line.
        3. For logical borders: compute a connection path.
        4. Calculate the representative point for labels and arrows.
        5. Compute the azimuth angle for arrow icons.

        Args:
            area_from: Source area identifier (must exist in area_model_gdf index)
            area_to: Target area identifier (must exist in area_model_gdf index)

        Returns:
            dict: The border geometry with the keys `projection_point` (Point
                for labels and arrows), `azimuth_angle` (float, direction in
                degrees from 0 to 360), `geo_line_string` (LineString, the border
                line) and `areas_touch` (bool, True when the areas touch or
                overlap, False for logical borders).

        Raises:
            KeyError: If area_from or area_to not found in area_model_gdf
        """
        midpoint, angle = self.get_area_border_midpoint_and_angle(area_from, area_to)

        if self.areas_touch(area_from, area_to) or self.areas_intersect(area_from, area_to):
            geom_from = self.get_area_geometry(area_from)
            geom_to = self.get_area_geometry(area_to)
            border_line = self._get_continuous_border_line(geom_from, geom_to)
            areas_touch = True
        else:
            border_line = self.get_straight_line_between_areas(area_from, area_to)
            areas_touch = False

        return {
            self.PROJECTION_POINT_IDENTIFIER: midpoint,
            self.AZIMUTH_ANGLE_IDENTIFIER: angle,
            self.BORDER_LINE_STRING_IDENTIFIER: border_line,
            self.BORDER_AREAS_TOUCH_IDENTIFIER: areas_touch,
        }

    def areas_touch(self, area_from: str, area_to: str) -> bool:
        """Check if two areas share a common physical (geographic) border.

        Uses Shapely's touches() method to determine if area boundaries
        intersect without overlapping. This is the standard definition
        of physical adjacency for energy market regions.

        Args:
            area_from: Source area identifier
            area_to: Target area identifier

        Returns:
            bool: True if areas share a common boundary, False otherwise
        """
        geom_from = self.get_area_geometry(area_from)
        geom_to = self.get_area_geometry(area_to)
        return geom_from.touches(geom_to)

    def areas_intersect(self, area_from: str, area_to: str) -> bool:
        """Check if two areas have any geometric intersection.

        Uses Shapely's intersects() method to check for any form of geometric
        intersection, including touching, overlapping, or containment. This is
        broader than the touches() check and handles edge cases in geographic data.

        Args:
            area_from: Source area identifier
            area_to: Target area identifier

        Returns:
            bool: True if areas have any geometric intersection, False otherwise

        Note:
            This method is used as a fallback for areas_touch() to handle
            geographic data with small overlaps or slight topology inconsistencies
            that are common in real-world boundary datasets.
        """
        geom_from = self.get_area_geometry(area_from)
        geom_to = self.get_area_geometry(area_to)
        return geom_from.intersects(geom_to)

    def get_area_border_midpoint_and_angle(self, area_from: str, area_to: str) -> tuple[Point, float]:
        """Calculate representative point and directional angle for border.

        The point and angle place directional indicators such as arrows and
        labels.

        For a physical border, the point is the midpoint of the shared
        boundary line, and the angle is perpendicular to the boundary, toward
        the target area. For a logical border, the point is the midpoint of
        the connection line, and the angle follows the connection from source
        to target.

        Args:
            area_from: Source area identifier
            area_to: Target area identifier

        Returns:
            tuple[Point, float]: Representative point and directional angle in degrees.
                Angle range: 0-360 degrees, where 0° is North, 90° is East.
        """
        geom_from = self.get_area_geometry(area_from)
        geom_to = self.get_area_geometry(area_to)

        if self.areas_touch(area_from, area_to) or self.areas_intersect(area_from, area_to):
            midpoint, angle = self._get_midpoint_and_angle_for_touching_areas(geom_from, geom_to)
        else:
            straight_line = self.get_straight_line_between_areas(area_from, area_to)
            midpoint, angle = self._get_midpoint_and_angle_from_line(straight_line)

        # Ensure angle points from area_from to area_to
        if not self._angle_points_to_target(geom_from, geom_to, midpoint, angle):
            angle = (angle + 180) % 360

        return midpoint, angle

    def get_area_geometry(self, area: str) -> Union[Polygon, MultiPolygon]:
        """Retrieve and validate geometry for a specified area.

        Args:
            area: Area identifier that must exist in area_model_gdf index

        Returns:
            Union[Polygon, MultiPolygon]: Cleaned geometry with buffer(0) applied
                to ensure validity for geometric operations

        Raises:
            KeyError: If area is not found in area_model_gdf

        Note:
            The buffer(0) operation ensures geometric validity for complex
            calculations, which is essential for reliable border analysis.
        """
        return self.area_model_gdf.loc[area].geometry.buffer(0)

    def get_straight_line_between_areas(self, area_from: str, area_to: str) -> LineString:
        """Return the line of the logical border between two areas that do not touch.

        The line runs on the line between the representative points of the
        largest polygons of the two areas, from boundary to boundary. If it
        crosses other areas, the line of `NonCrossingPathFinder` replaces it
        when the finder finds one; the finder states its rule. The results
        are cached per pair of areas; the line of B to A is the reversed line
        of A to B.

        Args:
            area_from: Source area identifier
            area_to: Target area identifier

        Returns:
            LineString: Connection line between the area boundaries.
                Line endpoints touch the area boundaries, not the centroids.

        Raises:
            ValueError: If areas are touching (should use physical border instead)
        """
        key = tuple(sorted((area_from, area_to)))
        if key not in self._line_cache:
            self._line_cache[key] = self._compute_straight_line(*key)
        line = self._line_cache[key]
        return line if (area_from, area_to) == key else LineString(line.coords[::-1])

    def _compute_straight_line(self, area_from: str, area_to: str) -> LineString:
        if self.areas_touch(area_from, area_to):
            raise ValueError(f'Areas {area_from} and {area_to} touch - use border line instead')

        geom_from = self._get_largest_polygon(self.get_area_geometry(area_from))
        geom_to = self._get_largest_polygon(self.get_area_geometry(area_to))

        centroid_from = self.get_representative_area_point(geom_from)
        centroid_to = self.get_representative_area_point(geom_to)

        line_full = LineString([centroid_from, centroid_to])

        # Find intersection points with area boundaries
        intersection_from = self._get_boundary_intersection(geom_from, line_full, centroid_to)
        intersection_to = self._get_boundary_intersection(geom_to, line_full, centroid_from)

        straight_line = LineString([intersection_from, intersection_to])

        # Check if line crosses other areas
        if self._line_crosses_other_areas(straight_line, area_from, area_to):
            # Try to find alternative path
            better_line = self._find_non_crossing_line(area_from, area_to)
            if better_line is not None:
                straight_line = better_line
        return straight_line

    def _get_midpoint_and_angle_for_touching_areas(
        self, geom_from: Union[Polygon, MultiPolygon], geom_to: Union[Polygon, MultiPolygon]
    ) -> tuple[Point, float]:
        """Calculate midpoint and angle for physically adjacent areas.

        For areas that share a physical boundary: the midpoint of the shared
        border line and the angle perpendicular to it.

        Args:
            geom_from: Source area geometry
            geom_to: Target area geometry

        Returns:
            tuple[Point, float]: Midpoint of shared border and perpendicular angle
                pointing from source toward target area

        Algorithm:
            1. Extract continuous border line from geometric intersection
            2. Find midpoint along border line (50% interpolation)
            3. Calculate border bearing and perpendicular angle
            4. Ensure angle points from source to target area
        """
        border_line = self._get_continuous_border_line(geom_from, geom_to)
        midpoint = border_line.interpolate(0.5, normalized=True)

        # Get angle perpendicular to border
        start_to_end = self._get_straight_line_from_endpoints(border_line)
        border_bearing = self._calculate_bearing(start_to_end)
        perpendicular_angle = (border_bearing + 90) % 360

        return midpoint, perpendicular_angle

    def _get_midpoint_and_angle_from_line(self, line: LineString) -> tuple[Point, float]:
        """Extract midpoint and directional angle from a LineString.

        Args:
            line: Input LineString geometry

        Returns:
            tuple[Point, float]: Midpoint and bearing angle in degrees

        Note:
            Uses 50% interpolation to find the midpoint, ensuring consistent
            positioning regardless of coordinate density along the line.
        """
        midpoint = line.interpolate(0.5, normalized=True)
        angle = self._calculate_bearing(line)
        return midpoint, angle

    def _angle_points_to_target(
        self,
        geom_from: Union[Polygon, MultiPolygon],
        geom_to: Union[Polygon, MultiPolygon],
        midpoint: Point,
        angle: float,
    ) -> bool:
        """Validate that computed angle points from source toward target area.

        Ensures directional consistency by checking if the angle points closer
        to the target area than to the source area. This is essential for
        correct arrow orientation in energy flow visualization.

        Args:
            geom_from: Source area geometry
            geom_to: Target area geometry
            midpoint: Reference point for angle measurement
            angle: Angle to validate (in degrees)

        Returns:
            bool: True if angle points toward target, False if it points toward source

        Algorithm:
            1. Calculate bearings from midpoint to both area centroids
            2. Compute angular differences between proposed angle and both bearings
            3. Return True if angle is closer to target bearing than source bearing
        """
        centroid_from = self.get_representative_area_point(geom_from)
        centroid_to = self.get_representative_area_point(geom_to)

        bearing_to_from = self._calculate_bearing(LineString([midpoint, centroid_from]))
        bearing_to_to = self._calculate_bearing(LineString([midpoint, centroid_to]))

        angle_diff_from = self._angular_difference(bearing_to_from, angle)
        angle_diff_to = self._angular_difference(bearing_to_to, angle)

        return angle_diff_to < angle_diff_from

    def _get_continuous_border_line(
        self, geom_a: Union[Polygon, MultiPolygon], geom_b: Union[Polygon, MultiPolygon]
    ) -> LineString:
        """Extract shared boundary line between touching geometries.

        Computes the geometric intersection between two touching areas and
        converts the result into a continuous LineString representing the
        shared border. Handles complex intersection geometries including
        multiple segments and mixed geometry types.

        Args:
            geom_a: First area geometry
            geom_b: Second area geometry

        Returns:
            LineString: Continuous line representing the shared boundary

        Raises:
            ValueError: If geometries don't touch or intersect
            TypeError: If intersection cannot be converted to LineString

        Algorithm:
            1. Compute geometric intersection of the two areas
            2. Handle GeometryCollection by extracting line components
            3. Convert Polygon boundaries to LineString if needed
            4. Merge multiple LineStrings into continuous representation
            5. Handle MultiLineString by connecting segments optimally

        Note:
            This method handles the complexity of real-world geographic boundaries
            which may result in complex intersection geometries.
        """
        if not (geom_a.touches(geom_b) or geom_a.intersects(geom_b)):
            raise ValueError('Geometries do not touch or intersect')

        border = geom_a.intersection(geom_b)

        if isinstance(border, GeometryCollection):
            extracted_lines = []

            for g in border.geoms:
                if isinstance(g, LineString):
                    extracted_lines.append(g)
                elif isinstance(g, Polygon):
                    extracted_lines.append(g.boundary)
                elif isinstance(g, MultiLineString):
                    extracted_lines.extend(g.geoms)
                elif isinstance(g, MultiPolygon):
                    extracted_lines.extend([p.boundary for p in g.geoms])

            if not extracted_lines:
                raise TypeError(f'GeometryCollection could not be converted into line: {type(border)}')

            border = linemerge(extracted_lines)

        if isinstance(border, MultiPolygon):
            border = linemerge([p.boundary for p in border.geoms])

        if isinstance(border, Polygon):
            border = border.boundary

        if isinstance(border, MultiLineString):
            border = self._merge_multilinestring(border)

        if isinstance(border, LineString):
            return border

        raise TypeError(f'Unexpected border type: {type(border)}')

    def _get_boundary_intersection(self, geom: Polygon, line: LineString, target_point: Point) -> Point:
        """Return the boundary intersection closest to `target_point`.

        Args:
            geom: Polygon whose boundary to intersect with
            line: LineString to intersect with polygon boundary
            target_point: Reference point for choosing among multiple intersections

        Returns:
            Point: Intersection point closest to target_point

        Raises:
            TypeError: If intersection geometry type is unexpected

        Algorithm:
            1. Compute intersection between line and polygon boundary
            2. Handle different intersection geometry types (Point, MultiPoint, LineString)
            3. For multiple options, select point closest to target
            4. Extract coordinates and create Point geometry
        """
        intersection = geom.boundary.intersection(line)

        if isinstance(intersection, Point):
            return intersection
        elif isinstance(intersection, MultiPoint):
            return min(intersection.geoms, key=lambda p: p.distance(target_point))
        elif isinstance(intersection, (LineString, MultiLineString)):
            # Get all coordinates and find closest
            coords = []
            if isinstance(intersection, LineString):
                coords = list(intersection.coords)
            else:
                for line in intersection.geoms:
                    coords.extend(list(line.coords))
            return Point(min(coords, key=lambda c: Point(c).distance(target_point)))
        else:
            raise TypeError(f'Unexpected intersection type: {type(intersection)}')

    def _line_crosses_other_areas(self, line: LineString, *exclude_areas: str) -> bool:
        """Check if a line crosses through any areas except specified exclusions.

        This method is crucial for validating logical border connections to ensure
        they don't inappropriately cross through other energy market areas, which
        would be misleading in visualization.

        Args:
            line: LineString to test for crossings
            *exclude_areas: Area identifiers to exclude from crossing check
                (typically the source and target areas of the line)

        Returns:
            bool: True if line crosses any non-excluded areas, False otherwise
        """
        other_areas = self.area_model_gdf.drop(list(exclude_areas))
        return other_areas.geometry.crosses(line).any()

    def _find_non_crossing_line(self, area_from: str, area_to: str) -> Union[LineString, None]:
        """Shortest line between the largest polygons of two areas that does not cross other areas.

        Uses the `NonCrossingPathFinder` of the calculator.

        Args:
            area_from: Source area identifier
            area_to: Target area identifier

        Returns:
            LineString or None: Non-crossing line, or None if the path finder
                finds none
        """
        poly_from = self._get_largest_polygon(self.get_area_geometry(area_from))
        poly_to = self._get_largest_polygon(self.get_area_geometry(area_to))

        return self.non_crossing_path_finder.find_shortest_path(
            poly_from, poly_to, self.area_model_gdf.drop([area_from, area_to]), f'{area_from} to {area_to}'
        )

    def _get_largest_polygon(self, geom: Union[Polygon, MultiPolygon]) -> Polygon:
        """Extract largest polygon component from MultiPolygon geometry.

        For MultiPolygon geometries (e.g., countries with islands), this method
        returns the largest polygon by area, which is typically the main landmass.
        This simplifies calculations while focusing on the most significant
        geographic component.

        Args:
            geom: Input geometry (Polygon returned as-is, MultiPolygon simplified)

        Returns:
            Polygon: Largest polygon component by area
        """
        if isinstance(geom, Polygon):
            return geom
        return max(geom.geoms, key=lambda p: p.area)

    def _merge_multilinestring(self, mls: MultiLineString) -> LineString:
        """Merge disconnected LineString segments into continuous line.

        Merges the segments with `shapely.ops.linemerge`. Segments that stay
        apart are joined pairwise, closest pair first, in the orientation that
        gives the shortest line.

        Args:
            mls: MultiLineString with potentially disconnected segments

        Returns:
            LineString: Continuous line through all segments
        """
        merged = linemerge(list(mls.geoms))

        if isinstance(merged, LineString):
            return merged

        # Connect disconnected segments
        lines = list(merged.geoms)

        while len(lines) > 1:
            # Find closest pair
            min_dist = float('inf')
            closest_pair = None

            for i, line1 in enumerate(lines):
                for j, line2 in enumerate(lines[i + 1 :], i + 1):
                    p1, p2 = nearest_points(line1, line2)
                    dist = p1.distance(p2)
                    if dist < min_dist:
                        min_dist = dist
                        closest_pair = (i, j)

            # Connect closest pair
            i, j = closest_pair
            line1, line2 = lines[i], lines[j]

            # Create connected line
            coords1 = list(line1.coords)
            coords2 = list(line2.coords)

            # Find best connection direction
            connections = [
                (coords1 + coords2, LineString(coords1 + coords2).length),
                (coords1 + coords2[::-1], LineString(coords1 + coords2[::-1]).length),
                (coords1[::-1] + coords2, LineString(coords1[::-1] + coords2).length),
                (coords1[::-1] + coords2[::-1], LineString(coords1[::-1] + coords2[::-1]).length),
            ]

            best_coords = min(connections, key=lambda x: x[1])[0]
            new_line = LineString(best_coords)

            # Update lines list
            lines = [l for k, l in enumerate(lines) if k not in (i, j)]
            lines.append(new_line)

        return lines[0]

    def _get_straight_line_from_endpoints(self, line: LineString) -> LineString:
        """Create straight line connecting first and last coordinates.

        Args:
            line: Input LineString with potentially complex path

        Returns:
            LineString: Simplified straight line from start to end

        Use Case:
            Useful for computing bearing angles from complex border geometries
            by simplifying to the fundamental start-to-end direction.
        """
        return LineString([line.coords[0], line.coords[-1]])

    def _calculate_bearing(self, line: LineString) -> float:
        """Calculate compass bearing (Azimuth angle) for a LineString.

        Args:
            line: LineString from which to calculate bearing

        Returns:
            float: Compass bearing (Azimuth angle) in degrees (0-360)
                - 0° = North
                - 90° = East
                - 180° = South
                - 270° = West

        Algorithm:
            Uses the forward azimuth formula from geodetic calculations:
            1. Convert coordinates to radians
            2. Apply spherical trigonometry formulas
            3. Convert result to compass bearing (0-360°)

        Note:
            The bearing is computed on lon/lat coordinates. If the areas have
            a projected CRS, the end points are first transformed to EPSG:4326.
        """
        start = line.coords[0]
        end = line.coords[-1]
        if self._to_lon_lat is not None:
            start, end = self._to_lon_lat.transform(*start[:2]), self._to_lon_lat.transform(*end[:2])

        lat1 = math.radians(start[1])
        lat2 = math.radians(end[1])

        diff_lon = math.radians(end[0] - start[0])

        x = math.sin(diff_lon) * math.cos(lat2)
        y = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(diff_lon)

        bearing = math.atan2(x, y)
        bearing = math.degrees(bearing)
        compass_bearing = (bearing + 360) % 360

        return compass_bearing

    def _angular_difference(self, angle1: float, angle2: float) -> float:
        """Calculate minimum angular difference between two compass bearings.

        Handles the circular nature of compass bearings to find the shortest
        angular distance between two directions, accounting for the 0°/360° wraparound.

        Args:
            angle1: First angle in degrees (0-360)
            angle2: Second angle in degrees (0-360)

        Returns:
            float: Minimum angular difference in degrees (0-180)
        """
        diff = abs(angle1 - angle2) % 360
        return min(diff, 360 - diff)

GEOMETRY_COLUMNS class-attribute

GEOMETRY_COLUMNS: tuple[str, ...] = (PROJECTION_POINT_IDENTIFIER, AZIMUTH_ANGLE_IDENTIFIER, BORDER_AREAS_TOUCH_IDENTIFIER, BORDER_LINE_STRING_IDENTIFIER)

The keys of calculate_border_geometry, in this order.

__init__

__init__(area_model_gdf: GeoDataFrame, non_crossing_path_finder: NonCrossingPathFinder = None)

Initialize the border geometry calculator.

Parameters:

Name Type Description Default
area_model_gdf GeoDataFrame

GeoDataFrame containing area geometries with polygon boundaries. Index should contain area identifiers (e.g., country codes, bidding zone names). Must contain valid polygon geometries in 'geometry' column. Without a CRS, the polygons are lon/lat coordinates in EPSG:4326. The path of a border between areas that do not touch needs the CRS.

required
non_crossing_path_finder NonCrossingPathFinder

Optional custom path finder for logical borders. If None, creates default NonCrossingPathFinder with standard parameters.

None

Invalid geometries are cleaned with buffer(0). If area_model_gdf has a CRS, the cleaning changes it in place.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(self, area_model_gdf: gpd.GeoDataFrame, non_crossing_path_finder: 'NonCrossingPathFinder' = None):
    """Initialize the border geometry calculator.

    Args:
        area_model_gdf: GeoDataFrame containing area geometries with polygon
            boundaries. Index should contain area identifiers (e.g., country codes,
            bidding zone names). Must contain valid polygon geometries in 'geometry' column.
            Without a CRS, the polygons are lon/lat coordinates in EPSG:4326.
            The path of a border between areas that do not touch needs the CRS.
        non_crossing_path_finder: Optional custom path finder for logical borders.
            If None, creates default NonCrossingPathFinder with standard parameters.

    Invalid geometries are cleaned with `buffer(0)`. If `area_model_gdf`
    has a CRS, the cleaning changes it in place.
    """
    self.area_model_gdf = area_model_gdf if area_model_gdf.crs is not None else area_model_gdf.set_crs('EPSG:4326')
    self.non_crossing_path_finder = non_crossing_path_finder or NonCrossingPathFinder()
    self._validate_geometries()

    self._centroid_cache: dict[str, Point] = {}
    self._line_cache: dict[Tuple[str, str], LineString] = {}
    crs = self.area_model_gdf.crs
    self._to_lon_lat = None if crs.is_geographic else Transformer.from_crs(crs, 'EPSG:4326', always_xy=True)

calculate_border_geometry

calculate_border_geometry(area_from: str, area_to: str) -> dict[str, Point | float | LineString | bool]

Calculate the geometric properties of an area border.

The steps:

  1. Detect if the areas share a physical boundary (touching or intersecting).
  2. For physical borders: extract the shared boundary line.
  3. For logical borders: compute a connection path.
  4. Calculate the representative point for labels and arrows.
  5. Compute the azimuth angle for arrow icons.

Parameters:

Name Type Description Default
area_from str

Source area identifier (must exist in area_model_gdf index)

required
area_to str

Target area identifier (must exist in area_model_gdf index)

required

Returns:

Name Type Description
dict dict[str, Point | float | LineString | bool]

The border geometry with the keys projection_point (Point for labels and arrows), azimuth_angle (float, direction in degrees from 0 to 360), geo_line_string (LineString, the border line) and areas_touch (bool, True when the areas touch or overlap, False for logical borders).

Raises:

Type Description
KeyError

If area_from or area_to not found in area_model_gdf

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
 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
def calculate_border_geometry(
    self, area_from: str, area_to: str
) -> dict[str, Union[Point, float, LineString, bool]]:
    """Calculate the geometric properties of an area border.

    The steps:

    1. Detect if the areas share a physical boundary (touching or intersecting).
    2. For physical borders: extract the shared boundary line.
    3. For logical borders: compute a connection path.
    4. Calculate the representative point for labels and arrows.
    5. Compute the azimuth angle for arrow icons.

    Args:
        area_from: Source area identifier (must exist in area_model_gdf index)
        area_to: Target area identifier (must exist in area_model_gdf index)

    Returns:
        dict: The border geometry with the keys `projection_point` (Point
            for labels and arrows), `azimuth_angle` (float, direction in
            degrees from 0 to 360), `geo_line_string` (LineString, the border
            line) and `areas_touch` (bool, True when the areas touch or
            overlap, False for logical borders).

    Raises:
        KeyError: If area_from or area_to not found in area_model_gdf
    """
    midpoint, angle = self.get_area_border_midpoint_and_angle(area_from, area_to)

    if self.areas_touch(area_from, area_to) or self.areas_intersect(area_from, area_to):
        geom_from = self.get_area_geometry(area_from)
        geom_to = self.get_area_geometry(area_to)
        border_line = self._get_continuous_border_line(geom_from, geom_to)
        areas_touch = True
    else:
        border_line = self.get_straight_line_between_areas(area_from, area_to)
        areas_touch = False

    return {
        self.PROJECTION_POINT_IDENTIFIER: midpoint,
        self.AZIMUTH_ANGLE_IDENTIFIER: angle,
        self.BORDER_LINE_STRING_IDENTIFIER: border_line,
        self.BORDER_AREAS_TOUCH_IDENTIFIER: areas_touch,
    }

areas_touch

areas_touch(area_from: str, area_to: str) -> bool

Check if two areas share a common physical (geographic) border.

Uses Shapely's touches() method to determine if area boundaries intersect without overlapping. This is the standard definition of physical adjacency for energy market regions.

Parameters:

Name Type Description Default
area_from str

Source area identifier

required
area_to str

Target area identifier

required

Returns:

Name Type Description
bool bool

True if areas share a common boundary, False otherwise

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def areas_touch(self, area_from: str, area_to: str) -> bool:
    """Check if two areas share a common physical (geographic) border.

    Uses Shapely's touches() method to determine if area boundaries
    intersect without overlapping. This is the standard definition
    of physical adjacency for energy market regions.

    Args:
        area_from: Source area identifier
        area_to: Target area identifier

    Returns:
        bool: True if areas share a common boundary, False otherwise
    """
    geom_from = self.get_area_geometry(area_from)
    geom_to = self.get_area_geometry(area_to)
    return geom_from.touches(geom_to)

areas_intersect

areas_intersect(area_from: str, area_to: str) -> bool

Check if two areas have any geometric intersection.

Uses Shapely's intersects() method to check for any form of geometric intersection, including touching, overlapping, or containment. This is broader than the touches() check and handles edge cases in geographic data.

Parameters:

Name Type Description Default
area_from str

Source area identifier

required
area_to str

Target area identifier

required

Returns:

Name Type Description
bool bool

True if areas have any geometric intersection, False otherwise

Note

This method is used as a fallback for areas_touch() to handle geographic data with small overlaps or slight topology inconsistencies that are common in real-world boundary datasets.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def areas_intersect(self, area_from: str, area_to: str) -> bool:
    """Check if two areas have any geometric intersection.

    Uses Shapely's intersects() method to check for any form of geometric
    intersection, including touching, overlapping, or containment. This is
    broader than the touches() check and handles edge cases in geographic data.

    Args:
        area_from: Source area identifier
        area_to: Target area identifier

    Returns:
        bool: True if areas have any geometric intersection, False otherwise

    Note:
        This method is used as a fallback for areas_touch() to handle
        geographic data with small overlaps or slight topology inconsistencies
        that are common in real-world boundary datasets.
    """
    geom_from = self.get_area_geometry(area_from)
    geom_to = self.get_area_geometry(area_to)
    return geom_from.intersects(geom_to)

get_area_border_midpoint_and_angle

get_area_border_midpoint_and_angle(area_from: str, area_to: str) -> tuple[Point, float]

Calculate representative point and directional angle for border.

The point and angle place directional indicators such as arrows and labels.

For a physical border, the point is the midpoint of the shared boundary line, and the angle is perpendicular to the boundary, toward the target area. For a logical border, the point is the midpoint of the connection line, and the angle follows the connection from source to target.

Parameters:

Name Type Description Default
area_from str

Source area identifier

required
area_to str

Target area identifier

required

Returns:

Type Description
tuple[Point, float]

tuple[Point, float]: Representative point and directional angle in degrees. Angle range: 0-360 degrees, where 0° is North, 90° is East.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
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
210
211
212
213
214
215
def get_area_border_midpoint_and_angle(self, area_from: str, area_to: str) -> tuple[Point, float]:
    """Calculate representative point and directional angle for border.

    The point and angle place directional indicators such as arrows and
    labels.

    For a physical border, the point is the midpoint of the shared
    boundary line, and the angle is perpendicular to the boundary, toward
    the target area. For a logical border, the point is the midpoint of
    the connection line, and the angle follows the connection from source
    to target.

    Args:
        area_from: Source area identifier
        area_to: Target area identifier

    Returns:
        tuple[Point, float]: Representative point and directional angle in degrees.
            Angle range: 0-360 degrees, where 0° is North, 90° is East.
    """
    geom_from = self.get_area_geometry(area_from)
    geom_to = self.get_area_geometry(area_to)

    if self.areas_touch(area_from, area_to) or self.areas_intersect(area_from, area_to):
        midpoint, angle = self._get_midpoint_and_angle_for_touching_areas(geom_from, geom_to)
    else:
        straight_line = self.get_straight_line_between_areas(area_from, area_to)
        midpoint, angle = self._get_midpoint_and_angle_from_line(straight_line)

    # Ensure angle points from area_from to area_to
    if not self._angle_points_to_target(geom_from, geom_to, midpoint, angle):
        angle = (angle + 180) % 360

    return midpoint, angle

get_area_geometry

get_area_geometry(area: str) -> Polygon | MultiPolygon

Retrieve and validate geometry for a specified area.

Parameters:

Name Type Description Default
area str

Area identifier that must exist in area_model_gdf index

required

Returns:

Type Description
Polygon | MultiPolygon

Union[Polygon, MultiPolygon]: Cleaned geometry with buffer(0) applied to ensure validity for geometric operations

Raises:

Type Description
KeyError

If area is not found in area_model_gdf

Note

The buffer(0) operation ensures geometric validity for complex calculations, which is essential for reliable border analysis.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def get_area_geometry(self, area: str) -> Union[Polygon, MultiPolygon]:
    """Retrieve and validate geometry for a specified area.

    Args:
        area: Area identifier that must exist in area_model_gdf index

    Returns:
        Union[Polygon, MultiPolygon]: Cleaned geometry with buffer(0) applied
            to ensure validity for geometric operations

    Raises:
        KeyError: If area is not found in area_model_gdf

    Note:
        The buffer(0) operation ensures geometric validity for complex
        calculations, which is essential for reliable border analysis.
    """
    return self.area_model_gdf.loc[area].geometry.buffer(0)

get_straight_line_between_areas

get_straight_line_between_areas(area_from: str, area_to: str) -> LineString

Return the line of the logical border between two areas that do not touch.

The line runs on the line between the representative points of the largest polygons of the two areas, from boundary to boundary. If it crosses other areas, the line of NonCrossingPathFinder replaces it when the finder finds one; the finder states its rule. The results are cached per pair of areas; the line of B to A is the reversed line of A to B.

Parameters:

Name Type Description Default
area_from str

Source area identifier

required
area_to str

Target area identifier

required

Returns:

Name Type Description
LineString LineString

Connection line between the area boundaries. Line endpoints touch the area boundaries, not the centroids.

Raises:

Type Description
ValueError

If areas are touching (should use physical border instead)

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
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
def get_straight_line_between_areas(self, area_from: str, area_to: str) -> LineString:
    """Return the line of the logical border between two areas that do not touch.

    The line runs on the line between the representative points of the
    largest polygons of the two areas, from boundary to boundary. If it
    crosses other areas, the line of `NonCrossingPathFinder` replaces it
    when the finder finds one; the finder states its rule. The results
    are cached per pair of areas; the line of B to A is the reversed line
    of A to B.

    Args:
        area_from: Source area identifier
        area_to: Target area identifier

    Returns:
        LineString: Connection line between the area boundaries.
            Line endpoints touch the area boundaries, not the centroids.

    Raises:
        ValueError: If areas are touching (should use physical border instead)
    """
    key = tuple(sorted((area_from, area_to)))
    if key not in self._line_cache:
        self._line_cache[key] = self._compute_straight_line(*key)
    line = self._line_cache[key]
    return line if (area_from, area_to) == key else LineString(line.coords[::-1])

NonCrossingPathFinder

Shortest line between two polygons that does not cross the buffered other areas.

The finder samples points on the boundaries of both polygons and tests every pair of points. It buffers the other areas by min_clearance and rejects a line that crosses the boundary of a buffered area. A line that lies wholly inside a buffer is accepted, and it can cross that area. The number of tested lines is num_points squared.

Attributes:

Name Type Description
num_points int

Number of boundary points to sample per area

min_clearance float

Buffer distance around other areas, in EPSG:3857 (Web Mercator) units if the areas have a geographic CRS, where one unit is about cos(latitude) meters on the ground, else in the units of their CRS.

show_progress bool

Whether to display progress bars for long operations

Examples:

>>> import geopandas as gpd
>>> from shapely.geometry import box
>>> finder = NonCrossingPathFinder(num_points=20, min_clearance=10_000, show_progress=False)
>>> obstacle = gpd.GeoDataFrame(geometry=[box(1.5, -1, 2.5, 0.5)], crs='EPSG:4326')
>>> path = finder.find_shortest_path(box(0, 0, 1, 1), box(3, 0, 4, 1), obstacle)
>>> [round(value, 1) for value in path.bounds]  # the line passes above the obstacle
[1.0, 0.6, 3.0, 0.6]
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
class NonCrossingPathFinder:
    """Shortest line between two polygons that does not cross the buffered other areas.

    The finder samples points on the boundaries of both polygons and tests
    every pair of points. It buffers the other areas by `min_clearance` and
    rejects a line that crosses the boundary of a buffered area. A line that
    lies wholly inside a buffer is accepted, and it can cross that area. The
    number of tested lines is `num_points` squared.

    Attributes:
        num_points (int): Number of boundary points to sample per area
        min_clearance (float): Buffer distance around other areas, in EPSG:3857
            (Web Mercator) units if the areas have a geographic CRS, where one
            unit is about cos(latitude) meters on the ground, else in the units
            of their CRS.
        show_progress (bool): Whether to display progress bars for long operations

    Examples:
        >>> import geopandas as gpd
        >>> from shapely.geometry import box
        >>> finder = NonCrossingPathFinder(num_points=20, min_clearance=10_000, show_progress=False)
        >>> obstacle = gpd.GeoDataFrame(geometry=[box(1.5, -1, 2.5, 0.5)], crs='EPSG:4326')
        >>> path = finder.find_shortest_path(box(0, 0, 1, 1), box(3, 0, 4, 1), obstacle)
        >>> [round(value, 1) for value in path.bounds]  # the line passes above the obstacle
        [1.0, 0.6, 3.0, 0.6]
    """

    def __init__(self, num_points: int = 100, min_clearance: float = 50000, show_progress: bool = True):
        """Initialize the non-crossing path finder.

        Args:
            num_points: Number of boundary points to sample per polygon.
                Higher values improve path quality but increase computation time.
                Typical range: 50-500 depending on precision requirements.
            min_clearance: Buffer distance around other areas, in EPSG:3857
                (Web Mercator) units if the areas have a geographic CRS, where
                one unit is about cos(latitude) meters on the ground, else in
                the units of their CRS.
            show_progress: Whether to display progress bars during computation.
                Useful for long-running operations with high num_points values.
        """
        self.num_points = num_points
        self.min_clearance = min_clearance
        self.show_progress = show_progress

    def find_shortest_path(
        self, polygon1: Polygon, polygon2: Polygon, other_areas: gpd.GeoDataFrame, name: str = None
    ) -> Union[LineString, None]:
        """Return the shortest line between two polygons that the finder accepts.

        The run time grows with the number of tested lines times the number
        of other areas.

        Args:
            polygon1: Source polygon geometry
            polygon2: Target polygon geometry
            other_areas: GeoDataFrame of the areas to buffer and not cross
            name: Optional name for progress tracking display

        Returns:
            LineString or None: Shortest accepted line, or None if no line is
                accepted

        Raises:
            ValueError: If `other_areas` has no CRS.
        """
        buffered_areas = self._buffer_areas(other_areas, self.min_clearance)
        points1 = self._get_boundary_points(polygon1, self.num_points)
        points2 = self._get_boundary_points(polygon2, self.num_points)

        lines = [LineString([p1, p2]) for p1, p2 in itertools.product(points1, points2)]
        shortest_line = None
        min_length = float('inf')

        iterator = tqdm(lines, desc=f'Finding path for {name or "path"}') if self.show_progress else lines

        for line in iterator:
            if not buffered_areas.geometry.crosses(line).any():
                if line.length < min_length:
                    shortest_line = line
                    min_length = line.length

        return shortest_line

    def _buffer_areas(self, areas: gpd.GeoDataFrame, buffer_distance: float) -> gpd.GeoDataFrame:
        """Return the areas buffered by `buffer_distance`, in their original CRS.

        Args:
            areas: GeoDataFrame containing areas to buffer
            buffer_distance: Buffer distance, in EPSG:3857 (Web Mercator)
                units if the areas have a geographic CRS, where one unit is
                about cos(latitude) meters on the ground, else in the units of
                their CRS.

        Returns:
            gpd.GeoDataFrame: Areas with buffered geometries in original CRS

        Raises:
            ValueError: If `areas` has no CRS.
        """
        areas_copy = areas.copy()
        original_crs = areas_copy.crs

        if original_crs is None:
            raise ValueError('GeoDataFrame must have a valid CRS defined.')

        if original_crs.is_geographic:
            # Use Web Mercator for accurate distance-based buffering
            projected_crs = 'EPSG:3857'
            areas_copy = areas_copy.to_crs(projected_crs)
            areas_copy['geometry'] = areas_copy.buffer(buffer_distance)
            areas_copy = areas_copy.to_crs(original_crs)
        else:
            # Already in projected coordinates
            areas_copy['geometry'] = areas_copy.buffer(buffer_distance)

        return areas_copy

    def _get_boundary_points(self, polygon: Polygon, num_points: int) -> list[Point]:
        """Sample evenly distributed points along polygon boundary.

        Creates a uniform sampling of points along the polygon perimeter using
        interpolation. The points are the candidates of the path finder.

        Args:
            polygon: Input polygon to sample
            num_points: Number of points to sample along boundary

        Returns:
            list[Point]: List of evenly spaced boundary points

        Algorithm:
            1. Calculate total boundary length
            2. Divide into equal segments
            3. Interpolate points at regular intervals
            4. Return as list of Point geometries

        Note:
            Points are distributed proportionally to boundary length,
            ensuring uniform density regardless of polygon complexity.
        """
        boundary = polygon.boundary
        total_length = boundary.length
        # Generate evenly spaced points along boundary
        return [boundary.interpolate((i / num_points) * total_length) for i in range(num_points)]

__init__

__init__(num_points: int = 100, min_clearance: float = 50000, show_progress: bool = True)

Initialize the non-crossing path finder.

Parameters:

Name Type Description Default
num_points int

Number of boundary points to sample per polygon. Higher values improve path quality but increase computation time. Typical range: 50-500 depending on precision requirements.

100
min_clearance float

Buffer distance around other areas, in EPSG:3857 (Web Mercator) units if the areas have a geographic CRS, where one unit is about cos(latitude) meters on the ground, else in the units of their CRS.

50000
show_progress bool

Whether to display progress bars during computation. Useful for long-running operations with high num_points values.

True
Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def __init__(self, num_points: int = 100, min_clearance: float = 50000, show_progress: bool = True):
    """Initialize the non-crossing path finder.

    Args:
        num_points: Number of boundary points to sample per polygon.
            Higher values improve path quality but increase computation time.
            Typical range: 50-500 depending on precision requirements.
        min_clearance: Buffer distance around other areas, in EPSG:3857
            (Web Mercator) units if the areas have a geographic CRS, where
            one unit is about cos(latitude) meters on the ground, else in
            the units of their CRS.
        show_progress: Whether to display progress bars during computation.
            Useful for long-running operations with high num_points values.
    """
    self.num_points = num_points
    self.min_clearance = min_clearance
    self.show_progress = show_progress

find_shortest_path

find_shortest_path(polygon1: Polygon, polygon2: Polygon, other_areas: GeoDataFrame, name: str = None) -> LineString | None

Return the shortest line between two polygons that the finder accepts.

The run time grows with the number of tested lines times the number of other areas.

Parameters:

Name Type Description Default
polygon1 Polygon

Source polygon geometry

required
polygon2 Polygon

Target polygon geometry

required
other_areas GeoDataFrame

GeoDataFrame of the areas to buffer and not cross

required
name str

Optional name for progress tracking display

None

Returns:

Type Description
LineString | None

LineString or None: Shortest accepted line, or None if no line is accepted

Raises:

Type Description
ValueError

If other_areas has no CRS.

Source code in src/mesqual/energy_data_handling/area_accounting/border_model_geometry_calculator.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
def find_shortest_path(
    self, polygon1: Polygon, polygon2: Polygon, other_areas: gpd.GeoDataFrame, name: str = None
) -> Union[LineString, None]:
    """Return the shortest line between two polygons that the finder accepts.

    The run time grows with the number of tested lines times the number
    of other areas.

    Args:
        polygon1: Source polygon geometry
        polygon2: Target polygon geometry
        other_areas: GeoDataFrame of the areas to buffer and not cross
        name: Optional name for progress tracking display

    Returns:
        LineString or None: Shortest accepted line, or None if no line is
            accepted

    Raises:
        ValueError: If `other_areas` has no CRS.
    """
    buffered_areas = self._buffer_areas(other_areas, self.min_clearance)
    points1 = self._get_boundary_points(polygon1, self.num_points)
    points2 = self._get_boundary_points(polygon2, self.num_points)

    lines = [LineString([p1, p2]) for p1, p2 in itertools.product(points1, points2)]
    shortest_line = None
    min_length = float('inf')

    iterator = tqdm(lines, desc=f'Finding path for {name or "path"}') if self.show_progress else lines

    for line in iterator:
        if not buffered_areas.geometry.crosses(line).any():
            if line.length < min_length:
                shortest_line = line
                min_length = line.length

    return shortest_line

GeoModelGeneratorBase

Base class for generating geometric models with representative points.

This class provides common functionality for working with geometric representations of energy system areas, including methods for computing representative points within polygons and multipolygons. It's designed to support energy market analysis where spatial aggregation of nodes into areas is required.

The class supports two methods for computing representative points:

  • 'polylabel': The pole of inaccessibility, the point inside the polygon farthest from its boundary
  • 'representative_point': Uses Shapely's built-in representative point method

Attributes:

Name Type Description
REPRESENTATIVE_POINT_METHOD str

Method used for computing representative points ('polylabel' or 'representative_point')

Source code in src/mesqual/energy_data_handling/area_accounting/model_generator_base.py
  7
  8
  9
 10
 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
class GeoModelGeneratorBase:
    """Base class for generating geometric models with representative points.

    This class provides common functionality for working with geometric representations
    of energy system areas, including methods for computing representative points
    within polygons and multipolygons. It's designed to support energy market
    analysis where spatial aggregation of nodes into areas is required.

    The class supports two methods for computing representative points:

    - 'polylabel': The pole of inaccessibility, the point inside the polygon farthest from its boundary
    - 'representative_point': Uses Shapely's built-in representative point method

    Attributes:
        REPRESENTATIVE_POINT_METHOD (str): Method used for computing representative
            points ('polylabel' or 'representative_point')
    """

    REPRESENTATIVE_POINT_METHOD: Literal['polylabel', 'representative_point'] = 'polylabel'

    def get_representative_area_point(self, geom: Union[Polygon, MultiPolygon]) -> Point:
        """Get a representative point for a polygon or multipolygon geometry.

        This method computes a point that is guaranteed to be inside the geometry
        and is suitable for label placement or other visualization purposes in
        energy system maps. For MultiPolygons, it operates on the largest constituent.

        Args:
            geom: A Shapely Polygon or MultiPolygon geometry representing an
                energy system area (e.g., bidding zone, market region)

        Returns:
            Point: A Shapely Point guaranteed to be inside the input geometry,
                suitable for map labels or representative location analysis

        Raises:
            ValueError: If REPRESENTATIVE_POINT_METHOD is not supported

        Examples:
            >>> from shapely.geometry import box
            >>> GeoModelGeneratorBase().get_representative_area_point(box(0, 0, 10, 10))
            <POINT (5 5)>
        """
        if self.REPRESENTATIVE_POINT_METHOD == 'polylabel':
            return self._get_polylabel_point(geom)
        elif self.REPRESENTATIVE_POINT_METHOD == 'representative_point':
            return geom.representative_point()
        else:
            raise ValueError(f'REPRESENTATIVE_POINT_METHOD {self.REPRESENTATIVE_POINT_METHOD} not supported')

    def _get_polylabel_point(self, geom: Union[Polygon, MultiPolygon]) -> Point:
        """Compute representative point using the polylabel algorithm.

        The polylabel algorithm finds the pole of inaccessibility - the most distant
        internal point from the polygon outline. This is particularly useful for
        placing labels on complex energy system area geometries.

        For MultiPolygons, operates on the largest polygon by area, which is
        typically the main landmass for country/region representations.

        Args:
            geom: A Shapely Polygon or MultiPolygon geometry

        Returns:
            Point: The pole of inaccessibility point, cached for performance

        Note:
            Results are cached using the geometry's WKT representation as key.
            The precision parameter (1.0) provides good balance between accuracy
            and performance for typical energy system area sizes.
        """
        key = geom.wkt
        cache: dict[str, Point] = self.__dict__.setdefault('_polylabel_cache', {})
        if key in cache:
            return cache[key]

        if isinstance(geom, MultiPolygon):
            geom = max(geom.geoms, key=lambda g: g.area)

        exterior = list(geom.exterior.coords)
        holes = [list(ring.coords) for ring in geom.interiors]
        rings = [exterior] + holes

        point = Point(polylabel(rings, 1.0))
        cache[key] = point
        return point

    @staticmethod
    def _compute_representative_point_from_cloud_of_2d_points(points: List[Point]) -> Point:
        """Compute a representative point of a collection of 2D points.

        This method is particularly useful in energy systems analysis for computing
        representative locations of energy assets (e.g., power plants, substations)
        that belong to the same area or region.

        The algorithm adapts based on the number of input points:
        - 1 point: Returns the point itself
        - 2 points: Returns the midpoint
        - 3 or more points: Returns the representative point of their convex
          hull, a point inside the hull (a polygon, or a line for collinear points)

        Args:
            points: List of Shapely Point objects representing energy asset
                locations or other spatial features within an area

        Returns:
            Point: Representative point for the collection of input points

        Raises:
            ValueError: If the input list is empty

        Examples:
            >>> from shapely.geometry import Point
            >>> GeoModelGeneratorBase._compute_representative_point_from_cloud_of_2d_points([Point(0, 0), Point(2, 2)])
            <POINT (1 1)>
        """
        n = len(points)
        if n == 0:
            raise ValueError('Empty point list provided - cannot compute representative point')
        if n == 1:
            return points[0]
        if n == 2:
            return Point((points[0].x + points[1].x) / 2, (points[0].y + points[1].y) / 2)

        return MultiPoint(points).convex_hull.representative_point()

get_representative_area_point

get_representative_area_point(geom: Polygon | MultiPolygon) -> Point

Get a representative point for a polygon or multipolygon geometry.

This method computes a point that is guaranteed to be inside the geometry and is suitable for label placement or other visualization purposes in energy system maps. For MultiPolygons, it operates on the largest constituent.

Parameters:

Name Type Description Default
geom Polygon | MultiPolygon

A Shapely Polygon or MultiPolygon geometry representing an energy system area (e.g., bidding zone, market region)

required

Returns:

Name Type Description
Point Point

A Shapely Point guaranteed to be inside the input geometry, suitable for map labels or representative location analysis

Raises:

Type Description
ValueError

If REPRESENTATIVE_POINT_METHOD is not supported

Examples:

>>> from shapely.geometry import box
>>> GeoModelGeneratorBase().get_representative_area_point(box(0, 0, 10, 10))
<POINT (5 5)>
Source code in src/mesqual/energy_data_handling/area_accounting/model_generator_base.py
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
def get_representative_area_point(self, geom: Union[Polygon, MultiPolygon]) -> Point:
    """Get a representative point for a polygon or multipolygon geometry.

    This method computes a point that is guaranteed to be inside the geometry
    and is suitable for label placement or other visualization purposes in
    energy system maps. For MultiPolygons, it operates on the largest constituent.

    Args:
        geom: A Shapely Polygon or MultiPolygon geometry representing an
            energy system area (e.g., bidding zone, market region)

    Returns:
        Point: A Shapely Point guaranteed to be inside the input geometry,
            suitable for map labels or representative location analysis

    Raises:
        ValueError: If REPRESENTATIVE_POINT_METHOD is not supported

    Examples:
        >>> from shapely.geometry import box
        >>> GeoModelGeneratorBase().get_representative_area_point(box(0, 0, 10, 10))
        <POINT (5 5)>
    """
    if self.REPRESENTATIVE_POINT_METHOD == 'polylabel':
        return self._get_polylabel_point(geom)
    elif self.REPRESENTATIVE_POINT_METHOD == 'representative_point':
        return geom.representative_point()
    else:
        raise ValueError(f'REPRESENTATIVE_POINT_METHOD {self.REPRESENTATIVE_POINT_METHOD} not supported')

Area membership of nodes and edges: the one rule for which node belongs to which area.

AreaMembership

Common parent of the area calculators and the area and border model generators: the area of each node.

A node has an area if has_area is True for the value in its area column. A node without an area belongs to no area and is on no border. edge_areas maps the two ends of each edge to their areas with the same rule. A subclass sets node_model_df and area_column.

Attributes:

Name Type Description
node_model_df DataFrame

Node model, one row per node.

area_column str

Column of node_model_df with the area of each node.

Source code in src/mesqual/energy_data_handling/area_accounting/area_membership.py
  6
  7
  8
  9
 10
 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
class AreaMembership:
    """Common parent of the area calculators and the area and border model generators: the area of each node.

    A node has an area if `has_area` is `True` for the value in its area
    column. A node without an area belongs to no area and is on no border.
    `edge_areas` maps the two ends of each edge to their areas with the same
    rule. A subclass sets `node_model_df` and `area_column`.

    Attributes:
        node_model_df: Node model, one row per node.
        area_column: Column of `node_model_df` with the area of each node.
    """

    AREA_FROM = 'area_from'
    AREA_TO = 'area_to'

    node_model_df: pd.DataFrame
    area_column: str

    @staticmethod
    def has_area(areas: pd.Series) -> pd.Series:
        """Return `True` per object whose area is set: neither `NaN` nor `None` nor an empty string.

        Examples:
            >>> AreaMembership.has_area(pd.Series({'n1': 'A', 'n2': None, 'n3': ''})).tolist()
            [True, False, False]
        """
        return areas.notna() & (areas != '')

    @classmethod
    def edge_areas(
        cls,
        edges: pd.DataFrame,
        area_of_node: pd.Series,
        end_from: str,
        end_to: str,
        area_from: str = AREA_FROM,
        area_to: str = AREA_TO,
    ) -> pd.DataFrame:
        """Return the area of the first end and the area of the second end per edge.

        Args:
            edges: The edge model, one row per edge.
            area_of_node: The area of each node, indexed by node.
            end_from: The column of `edges` with the first end.
            end_to: The column of `edges` with the second end.
            area_from: The name of the result column with the area of the first end.
            area_to: The name of the result column with the area of the second end.

        Returns:
            One row per edge with the two columns `area_from` and `area_to`,
                in this order, of dtype `object`, so that area ids keep their type.
                An end without area, or at a node that is not in `area_of_node`,
                gives `NaN`.

        Raises:
            ValueError: If `area_of_node` has a node id more than once.

        Examples:
            >>> nodes, lines = dataset.fetch('Node.Model'), dataset.fetch('Line.Model')
            >>> AreaMembership.edge_areas(lines, nodes['country'], 'node_from', 'node_to')
                 area_from area_to
            Line
            L1          C1      C2
            L2          C2      C1
            L3          C1      C1
            L4          C1      C2
            L5          C2      C2
        """
        duplicates = area_of_node.index[area_of_node.index.duplicated()].unique()
        if len(duplicates):
            raise ValueError(f'Node ids appear more than once in the node areas: {list(duplicates)}')
        areas = area_of_node[cls.has_area(area_of_node)].to_dict()
        return pd.DataFrame(
            {
                area_from: [areas.get(node, float('nan')) for node in edges[end_from]],
                area_to: [areas.get(node, float('nan')) for node in edges[end_to]],
            },
            index=edges.index,
            dtype=object,
        )

    @staticmethod
    def crosses_border(edge_areas: pd.DataFrame) -> pd.Series:
        """Return `True` per edge that is on a border: both areas are set and differ.

        An edge from area A to area B is on the border A - B, in border
        direction, and on the border B - A, against it.

        Args:
            edge_areas: Two columns per edge, as `edge_areas` gives them: the
                first with the area of the from end, the second with the area
                of the to end.
        """
        area_from, area_to = (edge_areas[column] for column in edge_areas.columns)
        return area_from.notna() & area_to.notna() & (area_from != area_to)

    def get_node_areas(self) -> pd.Series:
        """Return the area of each node that has one, indexed by node.

        Raises:
            ValueError: If `area_column` is not a column of `node_model_df`.
        """
        self._check_area_column()
        areas = self.node_model_df[self.area_column]
        return areas[self.has_area(areas)]

    def _check_area_column(self):
        if self.area_column not in self.node_model_df.columns:
            raise ValueError(
                f"Area column '{self.area_column}' not found in node_model_df. "
                f'Available columns: {list(self.node_model_df.columns)}'
            )

has_area staticmethod

has_area(areas: Series) -> Series

Return True per object whose area is set: neither NaN nor None nor an empty string.

Examples:

>>> AreaMembership.has_area(pd.Series({'n1': 'A', 'n2': None, 'n3': ''})).tolist()
[True, False, False]
Source code in src/mesqual/energy_data_handling/area_accounting/area_membership.py
25
26
27
28
29
30
31
32
33
@staticmethod
def has_area(areas: pd.Series) -> pd.Series:
    """Return `True` per object whose area is set: neither `NaN` nor `None` nor an empty string.

    Examples:
        >>> AreaMembership.has_area(pd.Series({'n1': 'A', 'n2': None, 'n3': ''})).tolist()
        [True, False, False]
    """
    return areas.notna() & (areas != '')

edge_areas classmethod

edge_areas(edges: DataFrame, area_of_node: Series, end_from: str, end_to: str, area_from: str = AREA_FROM, area_to: str = AREA_TO) -> DataFrame

Return the area of the first end and the area of the second end per edge.

Parameters:

Name Type Description Default
edges DataFrame

The edge model, one row per edge.

required
area_of_node Series

The area of each node, indexed by node.

required
end_from str

The column of edges with the first end.

required
end_to str

The column of edges with the second end.

required
area_from str

The name of the result column with the area of the first end.

AREA_FROM
area_to str

The name of the result column with the area of the second end.

AREA_TO

Returns:

Type Description
DataFrame

One row per edge with the two columns area_from and area_to, in this order, of dtype object, so that area ids keep their type. An end without area, or at a node that is not in area_of_node, gives NaN.

Raises:

Type Description
ValueError

If area_of_node has a node id more than once.

Examples:

>>> nodes, lines = dataset.fetch('Node.Model'), dataset.fetch('Line.Model')
>>> AreaMembership.edge_areas(lines, nodes['country'], 'node_from', 'node_to')
     area_from area_to
Line
L1          C1      C2
L2          C2      C1
L3          C1      C1
L4          C1      C2
L5          C2      C2
Source code in src/mesqual/energy_data_handling/area_accounting/area_membership.py
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
@classmethod
def edge_areas(
    cls,
    edges: pd.DataFrame,
    area_of_node: pd.Series,
    end_from: str,
    end_to: str,
    area_from: str = AREA_FROM,
    area_to: str = AREA_TO,
) -> pd.DataFrame:
    """Return the area of the first end and the area of the second end per edge.

    Args:
        edges: The edge model, one row per edge.
        area_of_node: The area of each node, indexed by node.
        end_from: The column of `edges` with the first end.
        end_to: The column of `edges` with the second end.
        area_from: The name of the result column with the area of the first end.
        area_to: The name of the result column with the area of the second end.

    Returns:
        One row per edge with the two columns `area_from` and `area_to`,
            in this order, of dtype `object`, so that area ids keep their type.
            An end without area, or at a node that is not in `area_of_node`,
            gives `NaN`.

    Raises:
        ValueError: If `area_of_node` has a node id more than once.

    Examples:
        >>> nodes, lines = dataset.fetch('Node.Model'), dataset.fetch('Line.Model')
        >>> AreaMembership.edge_areas(lines, nodes['country'], 'node_from', 'node_to')
             area_from area_to
        Line
        L1          C1      C2
        L2          C2      C1
        L3          C1      C1
        L4          C1      C2
        L5          C2      C2
    """
    duplicates = area_of_node.index[area_of_node.index.duplicated()].unique()
    if len(duplicates):
        raise ValueError(f'Node ids appear more than once in the node areas: {list(duplicates)}')
    areas = area_of_node[cls.has_area(area_of_node)].to_dict()
    return pd.DataFrame(
        {
            area_from: [areas.get(node, float('nan')) for node in edges[end_from]],
            area_to: [areas.get(node, float('nan')) for node in edges[end_to]],
        },
        index=edges.index,
        dtype=object,
    )

crosses_border staticmethod

crosses_border(edge_areas: DataFrame) -> Series

Return True per edge that is on a border: both areas are set and differ.

An edge from area A to area B is on the border A - B, in border direction, and on the border B - A, against it.

Parameters:

Name Type Description Default
edge_areas DataFrame

Two columns per edge, as edge_areas gives them: the first with the area of the from end, the second with the area of the to end.

required
Source code in src/mesqual/energy_data_handling/area_accounting/area_membership.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@staticmethod
def crosses_border(edge_areas: pd.DataFrame) -> pd.Series:
    """Return `True` per edge that is on a border: both areas are set and differ.

    An edge from area A to area B is on the border A - B, in border
    direction, and on the border B - A, against it.

    Args:
        edge_areas: Two columns per edge, as `edge_areas` gives them: the
            first with the area of the from end, the second with the area
            of the to end.
    """
    area_from, area_to = (edge_areas[column] for column in edge_areas.columns)
    return area_from.notna() & area_to.notna() & (area_from != area_to)

get_node_areas

get_node_areas() -> Series

Return the area of each node that has one, indexed by node.

Raises:

Type Description
ValueError

If area_column is not a column of node_model_df.

Source code in src/mesqual/energy_data_handling/area_accounting/area_membership.py
103
104
105
106
107
108
109
110
111
def get_node_areas(self) -> pd.Series:
    """Return the area of each node that has one, indexed by node.

    Raises:
        ValueError: If `area_column` is not a column of `node_model_df`.
    """
    self._check_area_column()
    areas = self.node_model_df[self.area_column]
    return areas[self.has_area(areas)]