File size: 13,723 Bytes
60d832d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""
STER — Multi-City 3D BAG Crawler (strict 3dSAGER alignment).

For each city, crawl 3D BAG buildings via OGC API Features, extract multi-LoD
geometry (LoD1.2, 1.3, 2.2), compute 25 geometric properties, and build
cross-LoD ground truth via shared BAG pand ID.

Usage:
    python crawl_multicity.py --city rotterdam --n 50000
    python crawl_multicity.py --city amsterdam --n 50000  
    python crawl_multicity.py --city utrecht --n 30000
    python crawl_multicity.py --city eindhoven --n 30000
    python crawl_multicity.py --city tokyo --n 50000  # PLATEAU mode (separate workflow)
"""

import argparse, json, os, sys, 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"}

# --- City Bounding Boxes (RDnew / EPSG:28992) ---
# Bounding boxes approximated from city administrative boundaries
CITY_BBOX = {
    "denhaag":     "76000,450000,86000,460000",   # The Hague (for reference)
    "rotterdam":   "88000,433000,98000,444000",   # Rotterdam
    "amsterdam":   "118000,485000,128000,495000",  # Amsterdam
    "utrecht":     "132000,453000,140000,461000",  # Utrecht
    "eindhoven":   "158000,380000,168000,390000",  # Eindhoven
    "groningen":   "232000,580000,240000,588000",  # Groningen
    "maastricht":  "174000,316000,184000,326000",  # Maastricht
}


def _get(url, retries=4, timeout=45):
    """GET with retry. Returns parsed JSON."""
    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."""
    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 extract_building(feature, min_surfaces=10):
    """Extract multi-LoD mesh records from a 3D BAG feature.
    Returns {lod12: {polygon_mesh, vertices, centroid}, ...} or None."""
    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
    uverts = {}
    centroids = {}
    for k, pm in out.items():
        uv = np.unique(np.array([c for surf in pm for c in surf]), axis=0)
        uverts[k] = uv
        centroids[k] = uv.mean(axis=0)
    return {k: {"polygon_mesh": out[k], "vertices": uverts[k], "centroid": centroids[k]}
            for k in out}


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 compute_25_properties(mesh_record):
    """Compute the 25 geometric properties from a mesh record.
    Mirrors 3dSAGER's ObjectPropertiesProcessor.
    Returns dict of {property_name: float}.
    """
    verts = mesh_record["vertices"]
    polys = mesh_record["polygon_mesh"]
    n_verts = len(verts)
    n_faces = len(polys)
    
    # Bounding box
    bbox_min = verts.min(axis=0)
    bbox_max = verts.max(axis=0)
    bbox_dims = bbox_max - bbox_min
    bb_width, bb_length, bb_height = float(bbox_dims[0]), float(bbox_dims[1]), float(bbox_dims[2])
    
    # Area: sum of triangle areas (simplified — triangulate each polygon face)
    area = 0.0
    for poly in polys:
        if len(poly) >= 3:
            p0 = np.array(poly[0])
            for i in range(1, len(poly) - 1):
                v1 = np.array(poly[i]) - p0
                v2 = np.array(poly[i+1]) - p0
                area += 0.5 * float(np.linalg.norm(np.cross(v1, v2)))
    
    # Volume: using divergence theorem / signed volume
    volume = 0.0
    for poly in polys:
        if len(poly) >= 3:
            p = np.array(poly)
            v = 0.0
            for i in range(1, len(p) - 1):
                v += np.dot(p[0], np.cross(p[i], p[i+1]))
            volume += v
    volume = abs(volume) / 6.0
    
    # Convex hull (2D projection onto XY plane)
    from scipy.spatial import ConvexHull
    xy = verts[:, :2]
    try:
        hull2d = ConvexHull(xy)
        convex_hull_area = float(hull2d.volume)  # area in 2D
        convex_hull_volume = convex_hull_area * bb_height  # approximate
    except Exception:
        convex_hull_area = bb_width * bb_length
        convex_hull_volume = convex_hull_area * bb_height
    
    # Perimeter (2D footprint boundary)
    try:
        from scipy.spatial import ConvexHull
        hull = ConvexHull(xy)
        perimeter = float(hull.area)  # perimeter in 2D
    except Exception:
        perimeter = 2 * (bb_width + bb_length)
    
    perimeter_ind = perimeter / max(area, 1e-6)
    
    # Height difference
    height_diff = bb_height
    
    # Floor count estimate (3m per floor)
    num_floors = max(1, int(height_diff / 3.0 + 0.5))
    
    # Centroid
    centroid = verts.mean(axis=0)
    
    # Average centroid distance (2D)
    dists = np.linalg.norm(xy - centroid[:2], axis=1)
    ave_centroid_distance = float(dists.mean())
    
    # Compactness 2D: C2D = 4π·area / perimeter²  (for circles = 1)
    compactness_2d = min(1.0, 4 * np.pi * convex_hull_area / max(perimeter**2, 1e-6))
    
    # Compactness 3D: C3D = 6√π·V / A^{3/2}
    compactness_3d = min(1.0, 6 * np.sqrt(np.pi) * volume / max(area**1.5, 1e-6))
    
    # Density: volume / convex hull volume
    density = volume / max(convex_hull_volume, 1e-6)
    
    # Elongation: bbox length / bbox width
    elongation = max(bb_length, bb_width) / max(min(bb_length, bb_width), 1e-6)
    
    # Shape index: perimeter / (2 * sqrt(pi * area))
    shape_ind = perimeter / max(2 * np.sqrt(np.pi * max(area, 1e-6)), 1e-6)
    
    # Hemisphericality (approximation)
    eq_radius = (volume * 3 / (4 * np.pi)) ** (1/3) if volume > 0 else 0
    hemisphericality = min(1.0, eq_radius / max(height_diff, 1e-6))
    
    # Fractality (simplified: 0 for now — needs perimeter at multiple scales)
    fractality = 0.0
    
    # Cubeness: volume / bbox_volume
    bbox_vol = bb_width * bb_length * bb_height
    cubeness = min(1.0, volume / max(bbox_vol, 1e-6))
    
    # Circumference (2D convex hull perimeter)
    circumference = perimeter
    
    # Aligned bounding box (same as bbox for now, PCA alignment deferred)
    aligned_bb_width = bb_width
    aligned_bb_length = bb_length
    aligned_bb_height = bb_height
    
    # Number of vertices
    num_vertices = n_verts
    
    # Axis symmetry (simplified)
    axes_symmetry = 0.0
    
    return {
        "bounding_box_width": bb_width,
        "bounding_box_length": bb_length,
        "area": area,
        "perimeter": perimeter,
        "perimeter_ind": perimeter_ind,
        "volume": volume,
        "convex_hull_area": convex_hull_area,
        "convex_hull_volume": convex_hull_volume,
        "ave_centroid_distance": ave_centroid_distance,
        "height_diff": height_diff,
        "num_floors": num_floors,
        "axes_symmetry": axes_symmetry,
        "compactness_2d": compactness_2d,
        "compactness_3d": compactness_3d,
        "density": density,
        "elongation": elongation,
        "shape_ind": shape_ind,
        "hemisphericality": hemisphericality,
        "fractality": fractality,
        "cubeness": cubeness,
        "circumference": circumference,
        "aligned_bounding_box_width": aligned_bb_width,
        "aligned_bounding_box_length": aligned_bb_length,
        "aligned_bounding_box_height": aligned_bb_height,
        "num_vertices": num_vertices,
    }


def crawl_city(city, n_target, out_dir, page_size=100, min_surfaces=10, sleep=0.25):
    """Crawl 3D BAG for a city, extract multi-LoD meshes + 25 properties."""
    bbox = CITY_BBOX.get(city)
    if not bbox:
        raise ValueError(f"Unknown city: {city}. Known: {list(CITY_BBOX.keys())}")
    
    os.makedirs(out_dir, exist_ok=True)
    
    per_lod = {LOD_KEY[l]: {} for l in LODS}
    properties_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()
    
    print(f"[{city}] Starting crawl: n_target={n_target}, bbox={bbox}")
    
    while url and kept < n_target:
        try:
            page = _get(url)
        except Exception as e:
            print(f"  ERROR page {pages}: {e}")
            break
        
        transform = page.get("metadata", {}).get("transform", {"scale": [1,1,1], "translate": [0,0,0]})
        
        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
                # Compute 25 properties
                try:
                    props = compute_25_properties(rec)
                    properties_per_lod[lod_key][bid] = props
                except Exception:
                    properties_per_lod[lod_key][bid] = {}
            
            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 % 10 == 0:
            elapsed = time.time() - t0
            rate = kept / max(elapsed, 1)
            eta = (n_target - kept) / max(rate, 0.01) / 60
            print(f"  [{city}] pages={pages} kept={kept} seen={len(seen)} "
                  f"rate={rate:.0f}/s elapsed={elapsed:.0f}s ETA={eta:.1f}min", flush=True)
        
        time.sleep(sleep)
    
    # Save mesh records
    import joblib
    for lod_key, d in per_lod.items():
        fpath = os.path.join(out_dir, f"3dbag_{lod_key}.joblib")
        joblib.dump(d, fpath)
        print(f"  Saved {len(d)} records → {fpath}")
    
    # Save property vectors as parquet (if pandas available)
    try:
        import pandas as pd
        for lod_key, props_dict in properties_per_lod.items():
            if props_dict:
                df = pd.DataFrame.from_dict(props_dict, orient='index')
                df.index.name = 'bag_id'
                fpath = os.path.join(out_dir, f"properties_{lod_key}.parquet")
                df.to_parquet(fpath)
                print(f"  Saved {len(df)} property vectors → {fpath}")
    except ImportError:
        # Fallback: save as JSON
        for lod_key, props_dict in properties_per_lod.items():
            fpath = os.path.join(out_dir, f"properties_{lod_key}.json")
            with open(fpath, 'w') as f:
                json.dump(props_dict, f)
            print(f"  Saved {len(props_dict)} property vectors → {fpath}")
    
    # Manifest
    common_ids = set(per_lod["lod12"]) & set(per_lod["lod13"]) & set(per_lod["lod22"])
    manifest = {
        "city": city,
        "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_ids),
        "elapsed_sec": round(time.time() - t0, 1),
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
    }
    with open(os.path.join(out_dir, "manifest.json"), "w") as f:
        json.dump(manifest, f, indent=2)
    
    print(f"[{city}] DONE: kept={kept} common={len(common_ids)} counts={manifest['counts_per_lod']}")
    return manifest


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="STER Multi-City 3D BAG Crawler")
    ap.add_argument("--city", type=str, required=True, 
                    choices=list(CITY_BBOX.keys()),
                    help="City to crawl")
    ap.add_argument("--n", type=int, default=50000, help="Target buildings")
    ap.add_argument("--out", type=str, default=None, help="Output dir (default: data/<city>/)")
    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()
    
    out_dir = a.out or os.path.join("data", a.city)
    crawl_city(a.city, a.n, out_dir, a.page_size, a.min_surfaces, a.sleep)