STER / code /crawl_3dbag_multilod.py
eduzrh's picture
Organize code/ directory + code README
a525891 verified
Raw
History Blame Contribute Delete
6.08 kB
"""
STER — 3DBAG multi-LoD crawler & extractor (v2).
Each 3DBAG building's BuildingPart embeds LoD1.2 / 1.3 / 2.2 Solid geometries.
This yields a natural "same identity, different geometric realisation" dataset:
same BAG id across LoDs -> positive (match) ; different ids -> negative.
Selection rule: keep a building iff its finest LoD (2.2) has >= min_surfaces
surfaces (the paper's >=10-polygon complexity filter). ALL available LoDs of a
kept building are retained (LoD1.2 boxes have few faces but we still want them
for cross-LoD experiments).
Output: object_dict-compatible per-LoD dicts, so the official
ObjectPropertiesProcessor can compute the exact same 25 properties.
"""
import argparse, json, os, time, urllib.request
import numpy as np
API = "https://api.3dbag.nl"
LODS = ["1.2", "1.3", "2.2"]
LOD_KEY = {"1.2": "lod12", "1.3": "lod13", "2.2": "lod22"}
HAGUE_BBOX = "76000,450000,86000,460000" # RD / EPSG:28992 (default CRS of the API)
def _get(url, retries=4, timeout=45):
last = None
for i in range(retries):
try:
req = urllib.request.Request(url, headers={"User-Agent": "STER-research/1.0",
"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.load(r)
except Exception as e:
last = e
time.sleep(1.5 * (i + 1))
raise RuntimeError(f"GET failed after {retries}: {url}\n{last}")
def transform_vertices(verts, transform):
s = np.asarray(transform["scale"], dtype=np.float64)
t = np.asarray(transform["translate"], dtype=np.float64)
return np.asarray(verts, dtype=np.float64) * s + t
def solid_to_polygon_mesh(geom, real_verts):
"""CityJSON Solid -> list of surfaces (each = list of [x,y,z]); mirrors the
repo's _get_polygon_mesh (first shell, flatten rings). No filtering here."""
if geom.get("type") != "Solid":
return None
boundaries = geom.get("boundaries")
if not boundaries:
return None
shell = boundaries[0]
pm = []
for surface in shell:
pts = [real_verts[i] for ring in surface for i in ring]
pm.append([list(map(float, p)) for p in pts])
return pm
def _mesh_record(pm):
uverts = np.unique(np.array([c for surf in pm for c in surf]), axis=0)
return {"polygon_mesh": pm, "vertices": uverts, "centroid": uverts.mean(axis=0)}
def extract_building(feature, min_surfaces=10):
"""Return {lod_key: mesh_record} for a building, iff LoD2.2 exists and has
>= min_surfaces surfaces. All available LoDs are kept."""
real_verts = transform_vertices(feature["vertices"], feature["_transform"])
lod_geoms = {}
for oid, obj in feature["CityObjects"].items():
if obj.get("type") != "BuildingPart":
continue
for g in obj.get("geometry", []):
if g.get("lod") in LODS:
lod_geoms[g["lod"]] = g
if "2.2" not in lod_geoms:
return None
out = {}
for lod, g in lod_geoms.items():
pm = solid_to_polygon_mesh(g, real_verts)
if pm:
out[LOD_KEY[lod]] = pm
if "lod22" not in out or len(out["lod22"]) < min_surfaces:
return None
return {k: _mesh_record(pm) for k, pm in out.items()}
def bag_id_from_feature(feature):
fid = feature.get("id", "")
if "NL.IMBAG.Pand." in fid:
return fid.split("NL.IMBAG.Pand.")[1].split("-")[0]
return fid
def crawl(n_target, out_dir, bbox=HAGUE_BBOX, page_size=100, min_surfaces=10, sleep=0.25):
os.makedirs(out_dir, exist_ok=True)
per_lod = {LOD_KEY[l]: {} for l in LODS}
seen = set()
url = f"{API}/collections/pand/items?limit={page_size}"
if bbox:
url += f"&bbox={bbox}"
pages = kept = 0
t0 = time.time()
while url and kept < n_target:
page = _get(url)
transform = page["metadata"]["transform"]
for feat in page.get("features", []):
bid = bag_id_from_feature(feat)
if bid in seen:
continue
seen.add(bid)
feat["_transform"] = transform
try:
blds = extract_building(feat, min_surfaces)
except Exception:
continue
if not blds:
continue
for lod_key, rec in blds.items():
per_lod[lod_key][bid] = rec
kept += 1
if kept >= n_target:
break
pages += 1
nxt = [l["href"] for l in page.get("links", []) if l.get("rel") == "next"]
url = nxt[0] if nxt else None
if pages % 5 == 0:
print(f" pages={pages} kept={kept} seen={len(seen)} elapsed={time.time()-t0:.0f}s", flush=True)
time.sleep(sleep)
import joblib
for lod_key, d in per_lod.items():
joblib.dump(d, os.path.join(out_dir, f"3dbag_{lod_key}.joblib"))
common = set(per_lod["lod12"]) & set(per_lod["lod13"]) & set(per_lod["lod22"])
manifest = {"n_kept": kept, "pages": pages, "bbox": bbox, "min_surfaces": min_surfaces,
"counts_per_lod": {k: len(v) for k, v in per_lod.items()},
"n_common_all_lods": len(common), "common_ids": sorted(common),
"elapsed_sec": round(time.time() - t0, 1)}
with open(os.path.join(out_dir, "manifest.json"), "w") as f:
json.dump(manifest, f, indent=2)
print(f"DONE kept={kept} common_all_lods={len(common)} counts={manifest['counts_per_lod']} -> {out_dir}",
flush=True)
return manifest
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=800)
ap.add_argument("--out", type=str, required=True)
ap.add_argument("--bbox", type=str, default=HAGUE_BBOX)
ap.add_argument("--page_size", type=int, default=100)
ap.add_argument("--min_surfaces", type=int, default=10)
ap.add_argument("--sleep", type=float, default=0.25)
a = ap.parse_args()
crawl(a.n, a.out, a.bbox, a.page_size, a.min_surfaces, a.sleep)