| import csv |
| import json |
| import os |
| import pickle |
| from collections import defaultdict |
| from typing import Dict, Any |
|
|
| import matplotlib.pyplot as plt |
| from shapely.ops import unary_union |
| from shapely.wkb import dumps as wkb_dumps |
| from shapely.wkb import loads as wkb_loads |
|
|
| UNSD_EU_CSV = "src/fuse_esdac/codebooks/unsd_eu.csv" |
| REGION_ALIAS_JSON = "src/fuse_esdac/codebooks/unsd_eu_alias.json" |
| WORLD_TREE_PKL = "src/fuse_esdac/large_inputs/gadm_tree.pkl" |
| OUT_TREE_PKL = "src/fuse_esdac/outputs/03_photo_gadm/gadm_tree_europe.pkl" |
|
|
|
|
| def load_unsd_europe(csv_path: str): |
| """ |
| Load the UNSD-based Europe CSV we built earlier. |
| |
| Expected columns (0-based index): |
| 0: "001" |
| 1: "World" |
| 2: "150" |
| 3: "Europe" |
| 4: primary region code (039, 151, 154, 155, 153) |
| 5: primary region name ("Western Europe", etc.) |
| 6: secondary region name (e.g. "DACH Region") |
| 7: secondary region ID (e.g. "DACH") |
| 8: country name |
| 9: numeric country code |
| 10: alpha-2 code (e.g. "GB") |
| 11: alpha-3 code (e.g. "GBR") |
| 12+: may be empty |
| """ |
| macro_id_map = { |
| "Northern Europe": "N_EU", |
| "Western Europe": "W_EU", |
| "Eastern Europe": "E_EU", |
| "Southern Europe": "S_EU", |
| "Central Europe": "C_EU", |
| } |
|
|
| countries = {} |
| macro_to_sub = defaultdict(set) |
| sub_to_countries = defaultdict(set) |
|
|
| with open(csv_path, "r", encoding="utf-8") as f: |
| reader = csv.reader(f, delimiter=";") |
| for row in reader: |
| if not row: |
| continue |
| |
| if len(row) < 12: |
| continue |
| |
| if row[0] != "001": |
| continue |
|
|
| macro_name = row[5].strip() |
| sub_name = row[6].strip() |
| sub_id = row[7].strip() |
| country_name = row[8].strip() |
| alpha3 = row[11].strip() |
|
|
| if not alpha3: |
| continue |
|
|
| if macro_name not in macro_id_map: |
| raise ValueError(f"Unknown macro region name in CSV: {macro_name}") |
|
|
| macro_id = macro_id_map[macro_name] |
|
|
| countries[alpha3] = { |
| "name": country_name, |
| "macro_name": macro_name, |
| "macro_id": macro_id, |
| "sub_name": sub_name, |
| "sub_id": sub_id, |
| } |
|
|
| macro_to_sub[(macro_name, macro_id)].add((sub_name, sub_id)) |
| sub_to_countries[(macro_name, macro_id, sub_name, sub_id)].add(alpha3) |
|
|
| return countries, macro_to_sub, sub_to_countries |
|
|
|
|
| def build_europe_subtree(tree_world, countries, macro_to_sub, sub_to_countries): |
| """ |
| Build a new tree that only contains Europe, with new levels: |
| |
| level 0: Europe (EU) |
| level 1: macro regions (N_EU, W_EU, ...) |
| level 2: subregions (BENE, DACH, BRIT, ...) |
| level 3+: original GADM hierarchy (countries and below) with level offset +3 |
| |
| We keep original geometry for GADM nodes and aggregate new levels from those. |
| """ |
| |
| europe_country_gids = set(countries.keys()) |
| tree_eu: Dict[str, Dict[str, Any]] = {} |
|
|
| def copy_subtree(root_gid: str): |
| stack = [root_gid] |
| while stack: |
| gid = stack.pop() |
| if gid in tree_eu: |
| continue |
| if gid not in tree_world: |
| raise KeyError(f"GID {gid} from UNSD CSV not found in GADM tree") |
| node = tree_world[gid] |
| tree_eu[gid] = { |
| "name": node["name"], |
| "level": node["level"], |
| "parent": node["parent"], |
| "children": set(node["children"]), |
| "geometry": node["geometry"], |
| } |
| stack.extend(node["children"]) |
|
|
| for alpha3 in sorted(europe_country_gids): |
| copy_subtree(alpha3) |
|
|
| |
| tree_eu["EU"] = { |
| "name": "Europe", |
| "level": 0, |
| "parent": None, |
| "children": set(), |
| "geometry": None, |
| } |
|
|
| |
| macro_nodes = {} |
| for (macro_name, macro_id) in sorted({(m, mid) for (m, mid) in macro_to_sub.keys()}): |
| gid = macro_id |
| macro_nodes[macro_id] = gid |
| tree_eu[gid] = { |
| "name": macro_name, |
| "level": 1, |
| "parent": "EU", |
| "children": set(), |
| "geometry": None, |
| } |
| tree_eu["EU"]["children"].add(gid) |
|
|
| |
| sub_nodes = {} |
| for (macro_name, macro_id), subregions in macro_to_sub.items(): |
| macro_gid = macro_nodes[macro_id] |
| for (sub_name, sub_id) in sorted(subregions): |
| gid = sub_id |
| sub_nodes[(macro_id, sub_id)] = gid |
| tree_eu[gid] = { |
| "name": sub_name, |
| "level": 2, |
| "parent": macro_gid, |
| "children": set(), |
| "geometry": None, |
| } |
| tree_eu[macro_gid]["children"].add(gid) |
|
|
| |
| |
| country_nodes_in_eu = {gid for gid, node in tree_eu.items() if node["level"] == 0 and gid != "EU"} |
| |
| missing = europe_country_gids - country_nodes_in_eu |
| if missing: |
| raise RuntimeError(f"Countries present in CSV but not in GADM subtree: {missing}") |
|
|
| for alpha3 in sorted(europe_country_gids): |
| node = tree_eu[alpha3] |
| info = countries[alpha3] |
| macro_id = info["macro_id"] |
| sub_id = info["sub_id"] |
| sub_gid = sub_nodes[(macro_id, sub_id)] |
|
|
| |
| node["parent"] = sub_gid |
| tree_eu[sub_gid]["children"].add(alpha3) |
|
|
| |
| reserved_gids = {"EU"} | set(macro_nodes.values()) | set(sub_nodes.values()) |
| for gid, node in tree_eu.items(): |
| if gid in reserved_gids: |
| continue |
| |
| node["level"] = node["level"] + 3 |
|
|
| |
| |
|
|
| |
| for (macro_id, sub_id), sub_gid in sub_nodes.items(): |
| country_alpha3s = sub_to_countries[ |
| (countries[next(iter(sub_to_countries[(macro_id, sub_id)].__iter__()))]["macro_name"], |
| macro_id, |
| tree_eu[sub_gid]["name"], |
| sub_id)] if False else None |
| |
| |
| country_alpha3s = { |
| a3 |
| for (m_name, m_id, s_name, s_id), a3s in sub_to_countries.items() |
| if m_id == macro_id and s_id == sub_id |
| for a3 in a3s |
| } |
|
|
| geoms = [] |
| for alpha3 in country_alpha3s: |
| geom_wkb = tree_eu[alpha3]["geometry"] |
| geoms.append(wkb_loads(geom_wkb)) |
| if not geoms: |
| raise RuntimeError(f"No country geometries for subregion {sub_gid}") |
| merged = unary_union(geoms) |
| tree_eu[sub_gid]["geometry"] = wkb_dumps(merged, hex=False) |
|
|
| |
| for macro_id, macro_gid in macro_nodes.items(): |
| geoms = [] |
| for sub_gid in tree_eu[macro_gid]["children"]: |
| geom_wkb = tree_eu[sub_gid]["geometry"] |
| if geom_wkb is None: |
| raise RuntimeError(f"Missing geometry for subregion {sub_gid}") |
| geoms.append(wkb_loads(geom_wkb)) |
| merged = unary_union(geoms) |
| tree_eu[macro_gid]["geometry"] = wkb_dumps(merged, hex=False) |
|
|
| |
| geoms = [] |
| for macro_gid in tree_eu["EU"]["children"]: |
| geom_wkb = tree_eu[macro_gid]["geometry"] |
| if geom_wkb is None: |
| raise RuntimeError(f"Missing geometry for macro region {macro_gid}") |
| geoms.append(wkb_loads(geom_wkb)) |
| merged = unary_union(geoms) |
| tree_eu["EU"]["geometry"] = wkb_dumps(merged, hex=False) |
|
|
| |
| for gid, node in tree_eu.items(): |
| if node["geometry"] is None: |
| raise RuntimeError(f"No geometry for node {gid} ({node['name']})") |
|
|
| |
| if not os.path.exists(REGION_ALIAS_JSON): |
| raise FileNotFoundError(f"Region alias file not found: {REGION_ALIAS_JSON}") |
|
|
| with open(REGION_ALIAS_JSON, "r", encoding="utf-8") as f: |
| alias_map = json.load(f) |
|
|
| |
| for gid, node in tree_eu.items(): |
| if node["level"] <= 2: |
| if gid not in alias_map: |
| raise KeyError( |
| f"Missing aliases for region GID '{gid}' " |
| f"(level={node['level']}, name='{node['name']}')" |
| ) |
|
|
| |
| for gid, aliases in alias_map.items(): |
| if gid not in tree_eu: |
| raise KeyError(f"Alias GID '{gid}' not found in Europe tree") |
|
|
| |
| tree_eu[gid]["aliases"] = sorted(set(aliases)) |
|
|
| |
| for gid, node in tree_eu.items(): |
| if "aliases" not in node: |
| node["aliases"] = [] |
|
|
| return tree_eu |
|
|
|
|
| def main(): |
| |
| with open(WORLD_TREE_PKL, "rb") as f: |
| tree_world = pickle.load(f) |
|
|
| |
| countries, macro_to_sub, sub_to_countries = load_unsd_europe(UNSD_EU_CSV) |
|
|
| |
| tree_eu = build_europe_subtree(tree_world, countries, macro_to_sub, sub_to_countries) |
|
|
| |
| os.makedirs(os.path.dirname(OUT_TREE_PKL), exist_ok=True) |
| with open(OUT_TREE_PKL, "wb") as f: |
| pickle.dump(tree_eu, f) |
|
|
| print(f"✅ Europe tree built and saved to: {OUT_TREE_PKL}") |
| print(f"Nodes: {len(tree_eu)}") |
| |
| print("Root:", "EU", tree_eu["EU"]["name"]) |
| print("Level-1 children:", tree_eu["EU"]["children"]) |
|
|
|
|
| plot_times = 0 |
|
|
|
|
| def check(): |
| IN_FILE = "src/fuse_esdac/outputs/03_photo_gadm/gadm_tree_europe.pkl" |
|
|
| with open(IN_FILE, "rb") as f: |
| tree = pickle.load(f) |
|
|
| |
| def tree_print(gid, max_level=3, prefix=""): |
| node = tree[gid] |
| name = node["name"] or "?" |
| print(f"{prefix}{gid} ({name})") |
| if node["level"] >= max_level: |
| return |
| |
| for child in sorted(node["children"]): |
| cnode = tree[child] |
| if cnode["level"] <= max_level: |
| tree_print(child, max_level, prefix + "├─") |
|
|
| print("=== Europe Hierarchy (levels 0-3) ===") |
| tree_print("EU", max_level=3) |
|
|
| |
| |
| LEVEL_COLORS = { |
| 0: "black", |
| 1: "red", |
| 2: "green", |
| 3: "blue", |
| 4: "magenta", |
| 5: "cyan", |
| 6: "orange" |
| } |
|
|
| def get_color(time: int): |
| return LEVEL_COLORS[time % len(LEVEL_COLORS)] |
|
|
| def plot_boundary_by_level(geom): |
| global plot_times |
| color = get_color(plot_times) |
| plot_times += 1 |
|
|
| |
| if geom.geom_type == "Polygon": |
| x, y = geom.exterior.xy |
| plt.plot(x, y, color=color, lw=0.5) |
| elif geom.geom_type == "MultiPolygon": |
| for poly in geom.geoms: |
| x, y = poly.exterior.xy |
| plt.plot(x, y, color=color, lw=0.5) |
|
|
| plt.figure() |
|
|
| |
| for gid, node in tree.items(): |
| level = node["level"] |
| if level == 1: |
| print(f"{gid} ({node['name']})") |
| geom = wkb_loads(node["geometry"]) |
| plot_boundary_by_level(geom) |
|
|
| plt.title("Europe boundaries (level-based coloring)") |
| plt.gca().set_aspect("equal", adjustable="datalim") |
| plt.show() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
| check() |
|
|