| """ |
| STER — Multi-City Benchmark Builder v5 (parallel tile download). |
| |
| 1. Parallel download (ThreadPool, 16 workers) + extract 3DBAG CityJSON tiles |
| 2. Batch-compute 25 properties (5000/batch) → parquet |
| 3. Per-LoD joblib object_dicts + manifest.json |
| """ |
| import argparse, json, os, sys, time, logging, gzip |
| from pathlib import Path |
| from collections import defaultdict |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| import numpy as np |
| import pandas as pd |
| from urllib.request import urlretrieve |
| import flatgeobuf as fgb |
|
|
| CITY_BBOX = { |
| "rotterdam": (88000, 433000, 98000, 444000), |
| "amsterdam": (118000, 485000, 128000, 495000), |
| "utrecht": (132000, 453000, 140000, 461000), |
| "eindhoven": (158000, 380000, 168000, 390000), |
| "groningen": (232000, 580000, 240000, 588000), |
| "maastricht": (174000, 316000, 184000, 326000), |
| "hague": (76000, 450000, 86000, 460000), |
| } |
| CITY_BBOX["denhaag"] = CITY_BBOX["hague"] |
| BATCH_SIZE = 5000 |
| DL_WORKERS = 16 |
|
|
| logger = logging.getLogger("build") |
| logger.setLevel(logging.INFO) |
| h = logging.StreamHandler(sys.stdout) |
| h.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')) |
| logger.addHandler(h) |
|
|
|
|
| def real_vertex(vi, vertices, transform): |
| s = transform["scale"]; t = transform["translate"] |
| vtx = vertices[vi] |
| return [s[0]*vtx[0]+t[0], s[1]*vtx[1]+t[1], s[2]*vtx[2]+t[2]] |
|
|
| def solid_to_polygon_mesh(boundaries, vertices, transform): |
| surfaces = [] |
| for shell in boundaries: |
| for surf in shell: |
| if not surf: continue |
| ext = surf[0] |
| if len(ext) < 3: continue |
| surfaces.append([real_vertex(vi, vertices, transform) for vi in ext]) |
| return surfaces |
|
|
| def extract_bag_pand_id(cityobj_id): |
| s = cityobj_id.replace("NL.IMBAG.Pand.", "") |
| parts = s.split("-") |
| return parts[0] if len(parts)>1 and parts[-1].isdigit() else s |
|
|
| def get_tile_index(bbox): |
| return fgb.HTTPReader('https://data.3dbag.nl/latest/tile_index.fgb', bbox=bbox) |
|
|
| def download_and_extract(tid, tiles_dir, min_surfaces): |
| """Download ONE tile and extract buildings. Returns {bag_id: lod_data}.""" |
| url = tid.properties['cj_download'] |
| fname = Path(tiles_dir) / url.split('/')[-1] |
| if not fname.exists(): |
| try: |
| urlretrieve(url, str(fname)) |
| except Exception: |
| return {} |
| try: |
| with gzip.open(fname, 'rt') as f: |
| cj = json.load(f) |
| except Exception: |
| try: |
| with open(fname, 'r') as f: |
| cj = json.load(f) |
| except Exception: |
| return {} |
|
|
| vertices = cj.get("vertices", []) |
| transform = cj.get("transform", {"scale":[1,1,1],"translate":[0,0,0]}) |
| buildings = defaultdict(lambda: {"lod12":[],"lod13":[],"lod22":[]}) |
| for oid, obj in cj.get("CityObjects", {}).items(): |
| if obj.get("type") != "BuildingPart": continue |
| bid = extract_bag_pand_id(oid) |
| for g in obj.get("geometry", []): |
| if g.get("type") == "Solid" and g.get("lod") in ("1.2","1.3","2.2"): |
| lk = f"lod{g['lod'].replace('.','')}" |
| pm = solid_to_polygon_mesh(g.get("boundaries",[]), vertices, transform) |
| if pm: buildings[bid][lk].extend(pm) |
| result = {} |
| for bid, lod in buildings.items(): |
| c = lod["lod12"] + lod["lod13"] + lod["lod22"] |
| if len(c) >= min_surfaces: |
| result[bid] = {"lod12":lod["lod12"], "lod13":lod["lod13"], "lod22":lod["lod22"], "combined":c} |
| return result |
|
|
| def merge_buildings(target, source): |
| for bid, lod in source.items(): |
| if bid in target: |
| for k in ("lod12","lod13","lod22"): |
| target[bid][k].extend(lod[k]) |
| else: |
| target[bid] = lod |
|
|
| def mesh_record(surfaces): |
| if not surfaces: return None |
| uverts = np.unique(np.array([c for surf in surfaces for c in surf]), axis=0) |
| return {"polygon_mesh": surfaces, "vertices": uverts, "centroid": uverts.mean(axis=0)} |
|
|
| |
| def build_city(city, bbox, outdir, min_surfaces=10): |
| t0 = time.time() |
| logger.info(f"=== [{city}] bbox={bbox} ===") |
| outdir = Path(outdir) |
| tiles_dir = outdir / city / "tiles_cityjson" |
| tiles_dir.mkdir(parents=True, exist_ok=True) |
|
|
| tile_ids = list(get_tile_index(bbox)) |
| n_total = len(tile_ids) |
| logger.info(f"[{city}] {n_total} tiles, {DL_WORKERS} parallel workers") |
|
|
| all_b = {} |
| done = 0 |
|
|
| with ThreadPoolExecutor(max_workers=DL_WORKERS) as pool: |
| futures = {pool.submit(download_and_extract, tid, tiles_dir, min_surfaces): tid |
| for tid in tile_ids} |
| for fut in as_completed(futures): |
| try: |
| blds = fut.result() |
| merge_buildings(all_b, blds) |
| except Exception as e: |
| logger.warning(f"[{city}] tile failed: {e}") |
| done += 1 |
| if done % 10 == 0: |
| logger.info(f"[{city}] tiles={done}/{n_total} blds={len(all_b)}") |
|
|
| |
| all_b = {bid: d for bid, d in all_b.items() |
| if len(d["lod12"]+d["lod13"]+d["lod22"]) >= min_surfaces} |
| logger.info(f"[{city}] {len(all_b)} buildings after filter ({time.time()-t0:.0f}s)") |
|
|
| if not all_b: |
| logger.error("No buildings!") |
| return None |
|
|
| |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| from object_properties import ObjectPropertiesProcessor, PROP_NAMES |
|
|
| ids = sorted(all_b.keys()) |
| all_rows = [] |
| n_batches = (len(ids) + BATCH_SIZE - 1) // BATCH_SIZE |
| logger.info(f"[{city}] Computing properties in {n_batches} batches...") |
| t_prop = time.time() |
| for bi in range(n_batches): |
| batch_ids = ids[bi*BATCH_SIZE:(bi+1)*BATCH_SIZE] |
| od = {"obj": {bid: mesh_record(all_b[bid]["combined"]) for bid in batch_ids}} |
| proc = ObjectPropertiesProcessor(od, vector_normalization=True) |
| side = proc.prop_vals_dict |
| for bid in batch_ids: |
| row = {"bag_id": bid, |
| "n_surfaces_lod12": len(all_b[bid]["lod12"]), |
| "n_surfaces_lod13": len(all_b[bid]["lod13"]), |
| "n_surfaces_lod22": len(all_b[bid]["lod22"]), |
| "n_surfaces_combined": len(all_b[bid]["combined"])} |
| for p in PROP_NAMES: |
| row[p] = side.get(p, {}).get("obj", {}).get(bid, None) |
| all_rows.append(row) |
| if (bi+1) % 10 == 0: |
| logger.info(f"[{city}] batch {bi+1}/{n_batches} ({time.time()-t_prop:.0f}s)") |
|
|
| prop_time = time.time() - t_prop |
| logger.info(f"[{city}] Properties done in {prop_time:.0f}s") |
|
|
| df = pd.DataFrame(all_rows) |
| out_city = outdir / city |
| out_city.mkdir(parents=True, exist_ok=True) |
| df.to_parquet(out_city / "buildings.parquet", index=False) |
| logger.info(f"[{city}] Saved {len(df)} rows -> buildings.parquet") |
|
|
| import joblib |
| for lk in ("lod12","lod13","lod22"): |
| od = {bid: mesh_record(all_b[bid][lk]) for bid in ids if all_b[bid][lk]} |
| joblib.dump(od, out_city / f"object_dict_{lk}.joblib") |
| joblib.dump({bid: mesh_record(all_b[bid]["combined"]) for bid in ids}, |
| out_city / "object_dict_combined.joblib") |
|
|
| manifest = { |
| "city": city, "bbox_epsg28992": list(bbox), |
| "min_surfaces_filter": min_surfaces, |
| "n_buildings": len(all_b), "n_tiles": n_total, |
| "property_names": PROP_NAMES, |
| "prop_compute_sec": round(prop_time, 1), |
| "elapsed_sec": round(time.time()-t0, 1), |
| "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), |
| "lod_counts": { |
| "lod12": sum(1 for d in all_b.values() if d["lod12"]), |
| "lod13": sum(1 for d in all_b.values() if d["lod13"]), |
| "lod22": sum(1 for d in all_b.values() if d["lod22"]), |
| }, |
| } |
| json.dump(manifest, open(out_city / "manifest.json","w"), indent=2, ensure_ascii=False) |
| logger.info(f"[{city}] DONE {time.time()-t0:.0f}s — {len(all_b)} blds") |
|
|
|
|
| if __name__ == "__main__": |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--city", type=str, default="all") |
| ap.add_argument("--outdir", type=str, default="data") |
| ap.add_argument("--min-surfaces", type=int, default=10) |
| ap.add_argument("--cities", type=str, nargs="*") |
| args = ap.parse_args() |
|
|
| if args.cities: |
| cities = args.cities |
| elif args.city == "all": |
| cities = ["amsterdam", "utrecht"] |
| else: |
| cities = [args.city] |
|
|
| outdir = Path(args.outdir) |
| if not outdir.is_absolute(): |
| outdir = Path(__file__).resolve().parent / outdir |
|
|
| for city in cities: |
| bbox = CITY_BBOX.get(city.lower()) |
| if bbox is None: |
| logger.error(f"Unknown: {city}") |
| continue |
| try: |
| build_city(city, bbox, outdir, args.min_surfaces) |
| except Exception as e: |
| logger.error(f"[{city}] FAILED: {e}", exc_info=True) |
|
|
| logger.info("ALL DONE") |
|
|