File size: 7,876 Bytes
b8bc5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
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
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
import pickle
from typing import Dict, Any, Optional, Union, List

import numpy as np
from shapely.geometry import Point
from shapely.strtree import STRtree
from shapely.wkb import loads


class GADMHandler:
    """
    Handler for querying GADM hierarchy and geometry, built from preprocessed .gpkg files.
    """

    def __init__(self, path: str = "data_api/gadm_tree_europe.pkl") -> None:
        """
        Load the GADM tree and construct a spatial index on leaf geometries.

        Args:
            path (str): Path to the pickled tree file.
        """
        with open(path, "rb") as f:
            raw_tree = pickle.load(f)

        self.tree: Dict[str, Dict[str, Any]] = {}
        for gid, node in raw_tree.items():
            node = node.copy()
            if node["geometry"] is not None:
                node["geometry"] = loads(node["geometry"])
            self.tree[gid] = node

        leaf_items = [
            (gid, node["geometry"])
            for gid, node in self.tree.items()
            if node["geometry"] is not None and not node["children"]
        ]
        self.leaf_polys = [geom for _, geom in leaf_items]
        self.leaf_gid_map = {id(geom): gid for gid, geom in leaf_items}
        self.leaf_tree = STRtree(self.leaf_polys)

    def find_gid(
            self, lat: float, lon: float, bbox_area: float = None, return_all: bool = False
    ) -> Union[str, List[str], None]:
        """
        Find the best GADM GID that contains the given point (lat, lon),
        optionally selecting the closest match by bounding box area.

        Args:
            lat (float): Latitude in degrees.
            lon (float): Longitude in degrees.
            bbox_area (float, optional): Area to match against polygon bounding box area (in degrees²);
                                         if not provided, return the smallest region.
            return_all (bool, optional): If True, return all matched GIDs up the tree; else return best match.

        Returns:
            str or list[str] or None: Best matching GID(s), or None if no polygon contains the point.
        """
        point = Point(lon, lat)
        gids = []
        areas = []

        for poly_id in self.leaf_tree.query(point):
            poly = self.leaf_polys[poly_id]
            if poly.contains(point):
                leaf_gid = self.leaf_gid_map[id(poly)]

                # Traverse upward to collect candidates
                current_gid = leaf_gid
                while current_gid:
                    node = self.tree.get(current_gid)
                    if node["geometry"] is not None:
                        minx, miny, maxx, maxy = node["geometry"].bounds
                        if minx > maxx:  # Wraparound correction
                            maxx += 360.0
                        poly_bbox_area = abs((maxx - minx) * (maxy - miny))
                        areas.append(poly_bbox_area)
                        gids.append(current_gid)

                    current_gid = node["parent"]

                break  # Use only the first containing leaf polygon

        if not gids:
            return None
        if return_all:
            return gids  # Ordered from leaf to root
        if bbox_area is None:
            bbox_area = 0.0
        areas = np.array(areas)
        return gids[np.argmin(np.abs(areas - bbox_area))]

    def get_polygon(self, gid: str) -> Optional[Any]:
        """
        Get the shapely geometry for a given GADM ID.
        """
        node = self.tree.get(gid)
        return node["geometry"] if node else None

    def get_full_name(self, gid: str) -> Optional[str]:
        """
        Get the full hierarchical name of a GADM region.
        """
        if gid not in self.tree:
            return None

        names = []
        while gid in self.tree:
            node = self.tree[gid]
            names.append(node["name"] or "UNKNOWN")
            gid = node["parent"]
            if gid is None:
                break

        return "; ".join(names)

    def get_geometry_info(self, gid: str) -> Optional[Dict[str, Any]]:
        """
        Get geometric metadata for the polygon of a GADM region.
        """
        polygon = self.get_polygon(gid)
        if polygon is None:
            return None

        centroid = polygon.centroid
        lon_c, lat_c = centroid.x, centroid.y
        minx, miny, maxx, maxy = polygon.bounds
        if minx > maxx:
            maxx += 360.0

        return {
            "latitude": lat_c,
            "longitude": lon_c,
            "bbox_bounds": (miny, maxy, minx, maxx),  # (lat_min, lat_max, lon_min, lon_max)
            "polygon_area": polygon.area,
            "bbox_area": abs((maxx - minx) * (maxy - miny))
        }

    def get_tree_info(self, gid: str) -> Optional[Dict[str, Any]]:
        """
        Get hierarchical metadata for a GADM region.
        """
        node = self.tree.get(gid)
        if node is None:
            return None

        parent = node["parent"]
        own_polygon = node.get("geometry")
        siblings = []

        if own_polygon and not own_polygon.is_empty:
            if parent is None:
                # Level-0: compare with other level-0 regions
                candidates = [
                    (gid2, node2["geometry"])
                    for gid2, node2 in self.tree.items()
                    if node2["level"] == 0 and gid2 != gid and node2.get("geometry")
                ]
            else:
                # Use other children of the same parent
                candidates = [
                    (sibling_gid, self.tree[sibling_gid]["geometry"])
                    for sibling_gid in self.tree[parent]["children"]
                    if sibling_gid != gid and self.tree[sibling_gid].get("geometry")
                ]

            for gid2, poly2 in candidates:
                try:
                    if own_polygon.touches(poly2) or own_polygon.intersects(poly2):
                        siblings.append(gid2)
                except Exception:  # noqa
                    continue  # Catch topology errors etc.

        siblings = sorted(siblings)

        return {
            "level": node["level"],
            "parent": parent,
            "children": sorted(node["children"]),
            "siblings": siblings
        }

    def get_full_info(self, gid: str) -> Optional[Dict[str, Any]]:
        """
        Get complete metadata for a GADM region, including name, geometry, and hierarchy.
        """
        if gid not in self.tree:
            return None
        return {
            "full_name": self.get_full_name(gid),
            "geometry": self.get_geometry_info(gid),
            "tree": self.get_tree_info(gid)
        }

    def quick_summary(self, gid: str) -> str:
        """
        Produce a human-readable summary of a GADM region.
        Useful for GPT-based tools and debugging.
        """
        info = self.get_full_info(gid)
        if not info:
            return f"Invalid GID: {gid}"
        name = info["full_name"] or "UNKNOWN"
        level = info["tree"]["level"]
        lat = info["geometry"]["latitude"]
        lon = info["geometry"]["longitude"]
        return f"{name} (GID={gid}, level={level}, lat={lat:.4f}, lon={lon:.4f})"


def main():
    from geo_utils import resolve_place
    handler = GADMHandler()

    place_info = resolve_place("Cowley, Oxford", gadm_handler=handler)

    gid = place_info["gid"]
    info = handler.get_full_info(gid)
    if info is None:
        print(f"GID '{gid}' not found.")
        return

    print("\n--- GADM Metadata ---")
    for key, val in info.items():
        if isinstance(val, dict):
            print(f"{key}:")
            for sub_key, sub_val in val.items():
                print(f"  {sub_key}: {sub_val}")
        else:
            print(f"{key}: {val}")


if __name__ == "__main__":
    main()