File size: 12,604 Bytes
0fbeb89 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | #!/usr/bin/env python3
"""
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 ward dataset IDs (latest version, 2023/2024)
# ============================================================
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",
}
# Morphology-selected wards (diverse urban typologies)
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
# ============================================================
# CityJSON -> polygon_mesh conversion
# ============================================================
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
# ============================================================
# Property computation (batched)
# ============================================================
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
# ============================================================
# Save outputs
# ============================================================
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)
# Build merged DataFrame
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)")
# Save per-LOD object_dicts as joblib
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")
# Combined (cands=lod1, index=lod2 for cross-LoD matching)
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
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)}")
# Cross-LoD pairs (all pos pairs for matching task)
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
# ============================================================
# Main pipeline
# ============================================================
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()
# Step 1-2: Download + prebuild + export CityJSON
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}")
# Step 3: Extract polygon meshes
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
# Step 4-5: Compute properties
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')
# Step 6: Save
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
# ============================================================
# CLI
# ============================================================
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.")
|