lucas-mega / src /fuse_esdac /x_02_gadm_eu_gen.py
Kuangdai
Initial release of LUCAS-MEGA
9bc98d9
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 = {} # alpha3 -> dict
macro_to_sub = defaultdict(set) # (macro_name, macro_id) -> {(sub_name, sub_id), ...}
sub_to_countries = defaultdict(set) # (macro_name, macro_id, sub_name, sub_id) -> {alpha3, ...}
with open(csv_path, "r", encoding="utf-8") as f:
reader = csv.reader(f, delimiter=";")
for row in reader:
if not row:
continue
# skip obviously invalid rows
if len(row) < 12:
continue
# very simple heuristic: first field should be "001" for our data; if not, skip
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.
"""
# 1) Copy only European countries and their entire subtrees
europe_country_gids = set(countries.keys()) # these are ISO alpha-3, matching GADM GID_0
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"], # temporary, will be shifted later
"parent": node["parent"],
"children": set(node["children"]),
"geometry": node["geometry"], # WKB bytes
}
stack.extend(node["children"])
for alpha3 in sorted(europe_country_gids):
copy_subtree(alpha3)
# 2) Create Europe root
tree_eu["EU"] = {
"name": "Europe",
"level": 0,
"parent": None,
"children": set(),
"geometry": None,
}
# 3) Create macro-region nodes (level 1)
macro_nodes = {} # macro_id -> gid (=macro_id)
for (macro_name, macro_id) in sorted({(m, mid) for (m, mid) in macro_to_sub.keys()}):
gid = macro_id # use macro_id as GID
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)
# 4) Create subregion nodes (level 2)
sub_nodes = {} # (macro_id, sub_id) -> gid (=sub_id)
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 # use sub_id as GID
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)
# 5) Attach country nodes under subregions; they will be level 3 after shift
# First, identify which nodes are countries in the copied GADM tree: level == 0
country_nodes_in_eu = {gid for gid, node in tree_eu.items() if node["level"] == 0 and gid != "EU"}
# By construction, these should be exactly europe_country_gids
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)]
# Re-parent this country from None -> subregion
node["parent"] = sub_gid
tree_eu[sub_gid]["children"].add(alpha3)
# 6) Shift levels of all original GADM nodes by +3
reserved_gids = {"EU"} | set(macro_nodes.values()) | set(sub_nodes.values())
for gid, node in tree_eu.items():
if gid in reserved_gids:
continue
# This includes all GADM-derived nodes: countries and below
node["level"] = node["level"] + 3
# 7) Compute geometry for subregions, macro-regions, and Europe
# All existing GADM nodes already have WKB geometry
# Subregions: union of country geometries
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"], # ugly, ignore
macro_id,
tree_eu[sub_gid]["name"],
sub_id)] if False else None # placeholder to avoid confusion
# simpler: recompute country set for this (macro_id, sub_id)
# to avoid the above monstrosity:
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)
# Macro-regions: union of subregion geometries
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)
# Europe: union of macro-region geometries
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)
# 8) Final sanity: all nodes must have geometry
for gid, node in tree_eu.items():
if node["geometry"] is None:
raise RuntimeError(f"No geometry for node {gid} ({node['name']})")
# 9) Attach aliases to nodes (EU / macro / sub)
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)
# First: enforce that all level <= 2 nodes have aliases defined
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']}')"
)
# Second: attach aliases to nodes
for gid, aliases in alias_map.items():
if gid not in tree_eu:
raise KeyError(f"Alias GID '{gid}' not found in Europe tree")
# normalize: store as sorted unique list
tree_eu[gid]["aliases"] = sorted(set(aliases))
# Third: ensure lower-level nodes have an aliases field (empty list)
for gid, node in tree_eu.items():
if "aliases" not in node:
node["aliases"] = []
return tree_eu
def main():
# Load world tree
with open(WORLD_TREE_PKL, "rb") as f:
tree_world = pickle.load(f)
# Load UNSD Europe table
countries, macro_to_sub, sub_to_countries = load_unsd_europe(UNSD_EU_CSV)
# Build Europe tree
tree_eu = build_europe_subtree(tree_world, countries, macro_to_sub, sub_to_countries)
# Save to disk
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)}")
# Small debug output
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)
# 1) print first 4 levels as tree: EU -> macro -> subregion -> country
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
# sort children by gid
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)
# 2) plot level<=2 boundaries
# Level→Color mapping (explicit because user asked)
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
# Only outer rings
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()
# Draw all nodes at level <= 2
for gid, node in tree.items():
level = node["level"]
if level == 1: # Europe, macro, subregions
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()