Skip to content

Geo Utils

geo_from_string

Conversion of WKT strings to shapely geometries.

convert_wkt_series

convert_wkt_series(series: Series) -> Series

Convert a pandas Series of WKT (Well-Known Text) strings to Shapely geometry objects.

Handles None and empty string values gracefully by returning None. If a value cannot be parsed, it is left unchanged and a warning is printed if any parsing fails.

Source code in src/mesqual/utils/geo_utils/geo_from_string.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def convert_wkt_series(series: pd.Series) -> pd.Series:
    """
    Convert a pandas Series of WKT (Well-Known Text) strings to Shapely geometry objects.

    Handles None and empty string values gracefully by returning None.
    If a value cannot be parsed, it is left unchanged and a warning is printed if any parsing fails.
    """

    def safe_load(value: Optional[str]) -> Optional[base.BaseGeometry]:
        if value is None or value == '':
            return None
        try:
            return wkt.loads(value)
        except Exception:
            return value

    result = series.apply(safe_load)

    if not result.apply(lambda x: x is None or isinstance(x, base.BaseGeometry)).all():
        logger.warning('Not all values could be converted to geometries.')

    return result

largest_polygon

The largest polygon of a multipolygon.

get_largest_sub_polygon

get_largest_sub_polygon(multi_polygon: MultiPolygon) -> Polygon

Return the polygon with the largest area of a multipolygon.

Parameters:

Name Type Description Default
multi_polygon MultiPolygon

A MultiPolygon, or a Polygon, which is returned as it is.

required
Source code in src/mesqual/utils/geo_utils/largest_polygon.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def get_largest_sub_polygon(multi_polygon: MultiPolygon) -> Polygon:
    """Return the polygon with the largest area of a multipolygon.

    Args:
        multi_polygon: A `MultiPolygon`, or a `Polygon`, which is returned as it is.
    """

    if isinstance(multi_polygon, Polygon):
        return multi_polygon

    largest_sub_polygon = max(multi_polygon.geoms, key=lambda polygon: polygon.area)

    return largest_sub_polygon

point_to_lat_lon

Latitude and longitude of a shapely point.

get_lat_lon_from_point

get_lat_lon_from_point(point: Point) -> tuple[float, float]

Return latitude and longitude of a point with x as longitude and y as latitude.

Returns:

Type Description
tuple[float, float]

(lat, lon), the order that folium uses.

Source code in src/mesqual/utils/geo_utils/point_to_lat_lon.py
 6
 7
 8
 9
10
11
12
13
14
def get_lat_lon_from_point(point: Point) -> tuple[float, float]:
    """Return latitude and longitude of a point with x as longitude and y as latitude.

    Returns:
        `(lat, lon)`, the order that folium uses.
    """
    coords = list(point.coords)
    lon, lat = coords[0][0], coords[0][1]
    return lat, lon

graph_node_coordinate_interpolator

Positions of graph nodes estimated from the positions of their neighbours.

InterpolationConfig dataclass

Settings of GraphNodeCoordinateInterpolator.

Attributes:

Name Type Description
move_percentage float

After the iterations, each node that shares its position with another node moves by this share of the vector to the mean of its neighbours at other positions.

max_iterations int

Maximum number of iterations. Each iteration moves each node without known position to the mean position of its neighbours.

tolerance float

The iterations stop when each node moves less than this distance.

Source code in src/mesqual/utils/geo_utils/graph_node_coordinate_interpolator.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@dataclass
class InterpolationConfig:
    """Settings of `GraphNodeCoordinateInterpolator`.

    Attributes:
        move_percentage: After the iterations, each node that shares its
            position with another node moves by this share of the vector to
            the mean of its neighbours at other positions.
        max_iterations: Maximum number of iterations. Each iteration moves each
            node without known position to the mean position of its neighbours.
        tolerance: The iterations stop when each node moves less than this distance.
    """

    move_percentage: float = 0.01
    max_iterations: int = 100
    tolerance: float = 1e-5

GraphNodeCoordinateInterpolator

Estimates the positions of graph nodes without known position from the positions of their neighbours.

compute places each node without known position at the center of the bounding box of the known positions, then moves it in iterations to the mean position of its neighbours (see InterpolationConfig). After the iterations, each node that shares its position with another node, known nodes included, moves by move_percentage toward the mean of its neighbours at other positions. Nodes with the same neighbours stay together. A component without a known node stays at the center of the bounding box.

Parameters:

Name Type Description Default
edges list[tuple[Hashable, Hashable]]

Node pairs of the graph.

required
known_node_positions dict[Hashable, Point]

Known position per node. The iterations do not change them. The dict itself is not changed.

required
config InterpolationConfig

Settings of the iterations.

InterpolationConfig()

Examples:

>>> from shapely.geometry import Point
>>> interpolator = GraphNodeCoordinateInterpolator(
...     [('A', 'B'), ('B', 'C')], {'A': Point(0, 0), 'C': Point(2, 0)}
... )
>>> interpolator.compute()
>>> interpolator.get_position_for_node('B')
<POINT (1 0)>
Source code in src/mesqual/utils/geo_utils/graph_node_coordinate_interpolator.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
 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
class GraphNodeCoordinateInterpolator:
    """Estimates the positions of graph nodes without known position from the positions of their neighbours.

    `compute` places each node without known position at the center of the
    bounding box of the known positions, then moves it in iterations to the
    mean position of its neighbours (see `InterpolationConfig`). After the
    iterations, each node that shares its position with another node, known
    nodes included, moves by `move_percentage` toward the mean of its
    neighbours at other positions. Nodes with the same neighbours stay
    together. A component without a known node stays at the center of the
    bounding box.

    Args:
        edges: Node pairs of the graph.
        known_node_positions: Known position per node. The iterations do not
            change them. The dict itself is not changed.
        config: Settings of the iterations.

    Examples:
        >>> from shapely.geometry import Point
        >>> interpolator = GraphNodeCoordinateInterpolator(
        ...     [('A', 'B'), ('B', 'C')], {'A': Point(0, 0), 'C': Point(2, 0)}
        ... )
        >>> interpolator.compute()
        >>> interpolator.get_position_for_node('B')
        <POINT (1 0)>
    """

    def __init__(
        self,
        edges: list[tuple[Hashable, Hashable]],
        known_node_positions: dict[Hashable, Point],
        config: InterpolationConfig = InterpolationConfig(),
    ):
        self._graph = nx.Graph()
        self._graph.add_edges_from(edges)
        self._known_node_positions = known_node_positions
        self._all_node_positions: dict[Hashable, Point] = known_node_positions.copy()
        self._has_computed: bool = False
        self._config = config

    def compute(self):
        """Compute the positions of all nodes. Before this call, only the known positions are available."""
        self._initialize_unknown_positions()
        self._iterate_to_find_positions()
        self._resolve_node_overlaps()
        self._has_computed = True

    def _initialize_unknown_positions(self):
        min_x, max_x, min_y, max_y = self._get_known_positions_bounding_box()
        for node in self._graph.nodes:
            if node not in self._all_node_positions:
                self._all_node_positions[node] = Point((min_x + max_x) / 2, (min_y + max_y) / 2)

    def _iterate_to_find_positions(self):
        for _ in range(self._config.max_iterations):
            max_change = 0
            new_positions = self._all_node_positions.copy()
            for node in self._graph.nodes:
                if node not in self._known_node_positions:
                    new_pos, change = self._compute_average_position(node)
                    new_positions[node] = new_pos
                    max_change = max(max_change, change)
            self._all_node_positions = new_positions
            if max_change < self._config.tolerance:
                break

    def _compute_average_position(self, node: Hashable) -> tuple[Point, float]:
        neighbors = list(self._graph.neighbors(node))
        avg_x = sum(self._all_node_positions[neighbor].x for neighbor in neighbors) / len(neighbors)
        avg_y = sum(self._all_node_positions[neighbor].y for neighbor in neighbors) / len(neighbors)
        new_pos = Point(avg_x, avg_y)
        change = self._all_node_positions[node].distance(new_pos)
        return new_pos, change

    def _resolve_node_overlaps(self):
        positions = self._all_node_positions
        move_percentage = self._config.move_percentage
        node_positions = {}
        for node, pos in positions.items():
            node_positions.setdefault(pos, []).append(node)
        for pos, nodes in node_positions.items():
            if len(nodes) > 1:
                for node in nodes:
                    movement_vector = self._calculate_movement_vector(node, pos)
                    new_pos = Point(
                        pos.x + move_percentage * movement_vector.x, pos.y + move_percentage * movement_vector.y
                    )
                    positions[node] = new_pos
        self._all_node_positions = positions

    def _calculate_movement_vector(self, node, pos):
        adjacent_nodes = list(self._graph.neighbors(node))
        movement_vector = Point(0, 0)
        count = 0
        for adj in adjacent_nodes:
            if self._all_node_positions[adj] != pos:
                movement_vector = Point(
                    movement_vector.x + (self._all_node_positions[adj].x - pos.x),
                    movement_vector.y + (self._all_node_positions[adj].y - pos.y),
                )
                count += 1
        if count > 0:
            movement_vector = Point(movement_vector.x / count, movement_vector.y / count)
        return movement_vector

    def _get_known_positions_bounding_box(self) -> tuple[float, float, float, float]:
        min_x = min(point.x for point in self._known_node_positions.values())
        max_x = max(point.x for point in self._known_node_positions.values())
        min_y = min(point.y for point in self._known_node_positions.values())
        max_y = max(point.y for point in self._known_node_positions.values())
        return min_x, max_x, min_y, max_y

    def get_position_for_node(self, node: Hashable) -> Point:
        """Return the position of a node.

        Raises:
            KeyError: The node has no position, for example a node without
                known position before `compute`.
        """
        return self._all_node_positions[node]

    def get_all_node_positions(self) -> dict[Hashable, Point]:
        """Return the position per node. The dict is the internal one until the next `compute`, which replaces it."""
        return self._all_node_positions

compute

compute()

Compute the positions of all nodes. Before this call, only the known positions are available.

Source code in src/mesqual/utils/geo_utils/graph_node_coordinate_interpolator.py
68
69
70
71
72
73
def compute(self):
    """Compute the positions of all nodes. Before this call, only the known positions are available."""
    self._initialize_unknown_positions()
    self._iterate_to_find_positions()
    self._resolve_node_overlaps()
    self._has_computed = True

get_position_for_node

get_position_for_node(node: Hashable) -> Point

Return the position of a node.

Raises:

Type Description
KeyError

The node has no position, for example a node without known position before compute.

Source code in src/mesqual/utils/geo_utils/graph_node_coordinate_interpolator.py
140
141
142
143
144
145
146
147
def get_position_for_node(self, node: Hashable) -> Point:
    """Return the position of a node.

    Raises:
        KeyError: The node has no position, for example a node without
            known position before `compute`.
    """
    return self._all_node_positions[node]

get_all_node_positions

get_all_node_positions() -> dict[Hashable, Point]

Return the position per node. The dict is the internal one until the next compute, which replaces it.

Source code in src/mesqual/utils/geo_utils/graph_node_coordinate_interpolator.py
149
150
151
def get_all_node_positions(self) -> dict[Hashable, Point]:
    """Return the position per node. The dict is the internal one until the next `compute`, which replaces it."""
    return self._all_node_positions