File size: 9,029 Bytes
1fb1c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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)}")

    # Re-filter
    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

    # Batch-compute properties
    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")