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()