| |
| """ |
| STER — PLATEAU (Japan) Benchmark Builder. |
| |
| Downloads PLATEAU CityGML data for specified cities/wards, converts to CityJSON, |
| extracts LOD1 + LOD2 building geometries, computes 25 geometric properties via |
| the official ObjectPropertiesProcessor, and saves per-city parquet + joblib + manifest. |
| |
| Cross-LoD paradigm: LOD1 = coarse source (cands), LOD2 = detailed source (index). |
| Same building ID across LODs = positive match (automatic ground truth). |
| |
| Usage: |
| python3 build_plateau.py --city chiyoda |
| python3 build_plateau.py --all |
| """ |
| import argparse, json, os, sys, time, logging |
| from collections import defaultdict |
| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
| import joblib |
|
|
| sys.path.insert(0, '/root/autodl-tmp') |
|
|
| import plateaukit as pk |
| from object_properties import ObjectPropertiesProcessor, PROP_NAMES |
|
|
| logger = logging.getLogger("plateau_build") |
| logger.setLevel(logging.INFO) |
| h = logging.StreamHandler(sys.stdout) |
| h.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')) |
| logger.addHandler(h) |
|
|
| |
| |
| |
| TOKYO_WARDS = { |
| "chiyoda": "plateau-13101-chiyoda-ku-2023", |
| "chuo": "plateau-13102-chuo-ku-2023", |
| "minato": "plateau-13103-minato-ku-2023", |
| "shinjuku": "plateau-13104-shinjuku-ku-2023", |
| "bunkyo": "plateau-13105-bunkyo-ku-2023", |
| "taito": "plateau-13106-taito-ku-2024", |
| "sumida": "plateau-13107-sumida-ku-2024", |
| "koto": "plateau-13108-koto-ku-2023", |
| "shinagawa": "plateau-13109-shinagawa-ku-2024", |
| "meguro": "plateau-13110-meguro-ku-2023", |
| "ota": "plateau-13111-ota-ku-2023", |
| "setagaya": "plateau-13112-setagaya-ku-2023", |
| "shibuya": "plateau-13113-shibuya-ku-2023", |
| "nakano": "plateau-13114-nakano-ku-2023", |
| "suginami": "plateau-13115-suginami-ku-2024", |
| "toshima": "plateau-13116-toshima-ku-2023", |
| "kita": "plateau-13117-kita-ku-2023", |
| "arakawa": "plateau-13118-arakawa-ku-2023", |
| "itabashi": "plateau-13119-itabashi-ku-2023", |
| "nerima": "plateau-13120-nerima-ku-2023", |
| "adachi": "plateau-13121-adachi-ku-2023", |
| "katsushika": "plateau-13122-katsushika-ku-2023", |
| "edogawa": "plateau-13123-edogawa-ku-2023", |
|
|
| "osaka": "plateau-27100-osaka-shi-2024", |
| "kyoto": "plateau-26100-kyoto-shi-2024", |
| "sakai": "plateau-27140-sakai-shi-2024", |
| } |
|
|
| |
| DEFAULT_WARDS = ["chiyoda", "shinjuku", "setagaya", "chuo", "ota"] |
|
|
| DATA_DIR = Path("/root/autodl-tmp/data") |
| PLATEAU_TMP = Path("/root/autodl-tmp/plateau_data") |
| BATCH_SIZE = 5000 |
| MIN_FACES = 10 |
|
|
| |
| |
| |
| def extract_polygon_mesh(geometry_list, vertices, lod_target): |
| """ |
| Extract polygon_mesh surfaces from CityJSON geometry for a given LOD. |
| Solid: boundaries = [shell] = [[face]] = [[[ring]]] |
| MultiSurface: boundaries = [surface] = [[ring]] |
| """ |
| surfaces = [] |
| for geom in geometry_list: |
| if str(geom.get('lod')) != str(lod_target): |
| continue |
| gtype = geom.get('type') |
| boundaries = geom.get('boundaries', []) |
| |
| if gtype == 'Solid': |
| for shell in boundaries: |
| for face in shell: |
| if not face: continue |
| ring = face[0] |
| if len(ring) < 3: continue |
| surfaces.append([list(vertices[vi]) for vi in ring]) |
| |
| elif gtype == 'MultiSurface': |
| for surf in boundaries: |
| if not surf: continue |
| ring = surf[0] |
| if len(ring) < 3: continue |
| surfaces.append([list(vertices[vi]) for vi in ring]) |
| |
| return surfaces |
|
|
|
|
| def extract_building_meshes(cityjson_path): |
| """Parse PLATEAU CityJSON -> {building_id: {lod1_mesh, lod2_mesh, attrs}}.""" |
| with open(cityjson_path) as f: |
| cj = json.load(f) |
| |
| vertices = cj.get('vertices', []) |
| cobjs = cj.get('CityObjects', {}) |
| |
| records = {} |
| skipped_no_lod1 = 0 |
| skipped_no_lod2 = 0 |
| skipped_few_faces = 0 |
| |
| for key, obj in cobjs.items(): |
| geoms = obj.get('geometry', []) |
| attrs = obj.get('attributes', {}) |
| building_id = attrs.get('building_id', key) |
| |
| lod1_mesh = extract_polygon_mesh(geoms, vertices, '1') |
| lod2_mesh = extract_polygon_mesh(geoms, vertices, '2') |
| |
| if not lod1_mesh: |
| skipped_no_lod1 += 1; continue |
| if not lod2_mesh: |
| skipped_no_lod2 += 1; continue |
| if len(lod1_mesh) < MIN_FACES or len(lod2_mesh) < MIN_FACES: |
| skipped_few_faces += 1; continue |
| |
| records[building_id] = { |
| 'lod1_mesh': lod1_mesh, |
| 'lod2_mesh': lod2_mesh, |
| 'attrs': attrs, |
| } |
| |
| return records, skipped_no_lod1, skipped_no_lod2, skipped_few_faces |
|
|
|
|
| |
| |
| |
| def compute_properties_for_side(records, side_key='lod1_mesh'): |
| """Compute 25 properties for one LOD side (batched).""" |
| all_ids = list(records.keys()) |
| n_buildings = len(all_ids) |
| n_batches = (n_buildings + BATCH_SIZE - 1) // BATCH_SIZE |
| |
| accum = {p: {} for p in PROP_NAMES} |
| |
| for bi in range(n_batches): |
| batch_ids = all_ids[bi*BATCH_SIZE:(bi+1)*BATCH_SIZE] |
| batch_od = {"obj": {}} |
| for bid in batch_ids: |
| batch_od["obj"][bid] = {"polygon_mesh": records[bid][side_key]} |
| |
| proc = ObjectPropertiesProcessor(batch_od, vector_normalization=True) |
| side = proc.prop_vals_dict |
| |
| for p in PROP_NAMES: |
| p_side = side.get(p, {}).get("obj", {}) |
| for bid in batch_ids: |
| val = p_side.get(bid) |
| if val is not None: |
| accum[p][bid] = val |
| |
| if (bi + 1) % 20 == 0 or bi == n_batches - 1: |
| logger.info(f" [{side_key}] batch {bi+1}/{n_batches} ({len(batch_ids)} bldgs)") |
| |
| return accum |
|
|
|
|
| |
| |
| |
| def save_city_output(city_name, records, lod1_props, lod2_props): |
| """Save parquet + joblib + manifest.""" |
| out_dir = DATA_DIR / city_name |
| out_dir.mkdir(parents=True, exist_ok=True) |
| |
| |
| rows = [] |
| for bid in records: |
| row = {"building_id": bid} |
| for p in PROP_NAMES: |
| row[f"lod1_{p}"] = lod1_props.get(p, {}).get(bid, None) |
| row[f"lod2_{p}"] = lod2_props.get(p, {}).get(bid, None) |
| row["attrs"] = json.dumps(records[bid]["attrs"], ensure_ascii=False) |
| row["n_faces_lod1"] = len(records[bid]["lod1_mesh"]) |
| row["n_faces_lod2"] = len(records[bid]["lod2_mesh"]) |
| rows.append(row) |
| |
| df = pd.DataFrame(rows) |
| parquet_path = out_dir / "buildings.parquet" |
| df.to_parquet(parquet_path) |
| logger.info(f"Saved {parquet_path} ({len(df)} rows)") |
| |
| |
| lod1_od = {"obj": {}} |
| lod2_od = {"obj": {}} |
| for bid in records: |
| lod1_od["obj"][bid] = records[bid]["lod1_mesh"] |
| lod2_od["obj"][bid] = records[bid]["lod2_mesh"] |
| |
| joblib.dump(lod1_od, out_dir / "object_dict_lod1.joblib") |
| joblib.dump(lod2_od, out_dir / "object_dict_lod2.joblib") |
| |
| |
| comb_od = {"cands": {}, "index": {}} |
| for bid in records: |
| comb_od["cands"][bid] = records[bid]["lod1_mesh"] |
| comb_od["index"][bid] = records[bid]["lod2_mesh"] |
| joblib.dump(comb_od, out_dir / "object_dict_combined.joblib") |
| |
| |
| manifest = { |
| "city": city_name, |
| "source": "PLATEAU (Japan MLIT)", |
| "dataset_id": TOKYO_WARDS.get(city_name, ""), |
| "n_buildings": len(records), |
| "n_lod1_faces": sum(len(r["lod1_mesh"]) for r in records.values()), |
| "n_lod2_faces": sum(len(r["lod2_mesh"]) for r in records.values()), |
| "properties": PROP_NAMES, |
| "lod1_label": "LOD1 (Solid, coarse block model)", |
| "lod2_label": "LOD2 (MultiSurface, detailed roof model)", |
| "coordinate_system": "JGD2011 (EPSG:6697)", |
| "min_faces_filter": MIN_FACES, |
| "batch_size": BATCH_SIZE, |
| } |
| with open(out_dir / "manifest.json", "w") as f: |
| json.dump(manifest, f, indent=2, ensure_ascii=False) |
| |
| logger.info(f"Manifest: n_buildings={len(records)}") |
| |
| |
| pairs = [] |
| bldg_ids = list(records.keys()) |
| for i, bid in enumerate(bldg_ids): |
| pairs.append({"cand_idx": i, "index_idx": i, "label": 1, |
| "cand_id": bid, "index_id": bid}) |
| pairs_df = pd.DataFrame(pairs) |
| pairs_df.to_parquet(out_dir / "crosslod_pairs.parquet") |
| |
| return out_dir |
|
|
|
|
| |
| |
| |
| def build_city(city_name, skip_download=False): |
| """Full pipeline for one city.""" |
| dataset_id = TOKYO_WARDS[city_name] |
| cj_path = PLATEAU_TMP / f"{city_name}_alllod.city.json" |
| |
| t0 = time.time() |
| |
| |
| if not skip_download or not cj_path.exists(): |
| logger.info(f"[{city_name}] Installing {dataset_id}...") |
| pk.install_dataset(dataset_id) |
| |
| logger.info(f"[{city_name}] Prebuilding...") |
| os.system(f"plateaukit prebuild {dataset_id} 2>&1") |
| |
| logger.info(f"[{city_name}] Exporting CityJSON (all LODs)...") |
| ds = pk.load_dataset(dataset_id) |
| PLATEAU_TMP.mkdir(parents=True, exist_ok=True) |
| ds.to_cityjson(str(cj_path), types=['bldg'], lod_mode='all', seq=False, split=1) |
| logger.info(f"[{city_name}] CityJSON: {cj_path.stat().st_size/1e6:.1f} MB") |
| else: |
| logger.info(f"[{city_name}] Using cached CityJSON: {cj_path}") |
| |
| |
| logger.info(f"[{city_name}] Extracting building meshes...") |
| records, no_lod1, no_lod2, few_faces = extract_building_meshes(str(cj_path)) |
| logger.info(f"[{city_name}] {len(records)} buildings with both LODs " |
| f"(skipped: no_lod1={no_lod1}, no_lod2={no_lod2}, <{MIN_FACES}faces={few_faces})") |
| |
| if len(records) == 0: |
| logger.error(f"[{city_name}] No valid buildings!") |
| return None |
| |
| |
| logger.info(f"[{city_name}] Computing LOD1 properties...") |
| lod1_props = compute_properties_for_side(records, 'lod1_mesh') |
| |
| logger.info(f"[{city_name}] Computing LOD2 properties...") |
| lod2_props = compute_properties_for_side(records, 'lod2_mesh') |
| |
| |
| logger.info(f"[{city_name}] Saving outputs...") |
| out_dir = save_city_output(city_name, records, lod1_props, lod2_props) |
| |
| elapsed = time.time() - t0 |
| logger.info(f"[{city_name}] DONE in {elapsed:.0f}s -> {out_dir}") |
| |
| return out_dir |
|
|
|
|
| |
| |
| |
| if __name__ == '__main__': |
| parser = argparse.ArgumentParser(description='PLATEAU Benchmark Builder') |
| parser.add_argument('--city', type=str, help='City name (key in TOKYO_WARDS)') |
| parser.add_argument('--all', action='store_true', help='Build all default wards') |
| parser.add_argument('--skip-download', action='store_true', help='Reuse cached CityJSON') |
| args = parser.parse_args() |
| |
| if args.city: |
| cities = [args.city] |
| elif args.all: |
| cities = DEFAULT_WARDS |
| else: |
| cities = DEFAULT_WARDS |
| logger.info(f"Using defaults: {cities}") |
| |
| for city in cities: |
| if city not in TOKYO_WARDS: |
| logger.error(f"Unknown city: {city}. Available: {list(TOKYO_WARDS.keys())}") |
| continue |
| try: |
| build_city(city, skip_download=args.skip_download) |
| except Exception as e: |
| logger.exception(f"[{city}] FAILED: {e}") |
| |
| logger.info("All done.") |
|
|