File size: 8,946 Bytes
86c018f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ObjectPropertiesProcessor — 3dSAGER 25 geometric property computation.

Given a dict of {building_id: mesh_record} for each side (cands/index),
computes exactly the 25 properties used in the SIGMOD 2026 paper and
applies log(1+x) normalisation if requested.

mesh_record format (from crawl_3dbag_multilod.py):
    {'polygon_mesh': [[[x,y,z],...], ...],  # list of surfaces
     'vertices': np.array unique vertices,
     'centroid': np.array([x,y,z])}
"""
import time, numpy as np
from scipy.spatial import ConvexHull

PROP_NAMES = [
    "bounding_box_width", "bounding_box_length", "area", "perimeter",
    "perimeter_ind", "volume", "convex_hull_area", "convex_hull_volume",
    "ave_centroid_distance", "height_diff", "num_floors", "axes_symmetry",
    "compactness_2d", "compactness_3d", "density", "elongation",
    "shape_ind", "hemisphericality", "fractality", "cubeness",
    "circumference", "aligned_bounding_box_width",
    "aligned_bounding_box_length", "aligned_bounding_box_height",
    "num_vertices"
]


def _extract_faces(mesh_rec):
    """Return (list-of-face-vertex-arrays, all-vertices-array)."""
    pm = mesh_rec.get("polygon_mesh", [])
    faces = []
    all_pts = []
    for surf in pm:
        if len(surf) < 3:
            continue
        verts = np.asarray(surf, dtype=np.float64)
        faces.append(verts)
        all_pts.append(verts)
    if not faces:
        all_v = mesh_rec.get("vertices", np.zeros((0, 3)))
        return [], np.asarray(all_v, dtype=np.float64)
    all_v = np.concatenate(all_pts, axis=0)
    return faces, all_v


def _footprint_vertices(all_v):
    """Return 2D vertices (x,y only) for the building footprint."""
    if len(all_v) < 3:
        return all_v[:, :2]
    return all_v[:, :2]


def _unique_2d(pts):
    """Deduplicate 2D points."""
    if len(pts) <= 1:
        return pts
    _, idx = np.unique(np.round(pts, 6), axis=0, return_index=True)
    return pts[np.sort(idx)]


def _triangle_area(a, b, c):
    """Area of triangle a-b-c."""
    return 0.5 * np.linalg.norm(np.cross(b - a, c - a))


def _face_area(verts):
    """Area of a planar polygon (triangulation from first vertex)."""
    if len(verts) < 3:
        return 0.0
    a = 0.0
    p0 = verts[0]
    for j in range(1, len(verts) - 1):
        a += _triangle_area(p0, verts[j], verts[j + 1])
    return a


def _face_perimeter(verts):
    """Perimeter of a polygon."""
    if len(verts) < 2:
        return 0.0
    p = 0.0
    for j in range(len(verts)):
        p += np.linalg.norm(verts[j] - verts[(j + 1) % len(verts)])
    return p


def _mesh_volume(faces):
    """Signed volume via divergence theorem: V = 1/3 * sum over faces
    of (face centroid · face normal) * face area. Works for closed meshes."""
    vol = 0.0
    for fv in faces:
        if len(fv) < 3:
            continue
        p0 = fv[0]
        c = fv.mean(axis=0)
        for j in range(1, len(fv) - 1):
            n = np.cross(fv[j] - p0, fv[j + 1] - p0)
            vol += np.dot(c, n)
    return abs(vol) / 6.0


def _convex_hull_volume(all_v):
    """Volume of 3D convex hull."""
    if len(all_v) < 4:
        return 0.0
    try:
        hull = ConvexHull(all_v)
        return hull.volume
    except Exception:
        return 0.0


def _convex_hull_area_2d(pts_2d):
    """Area of 2D convex hull (footprint)."""
    pts_u = _unique_2d(pts_2d)
    if len(pts_u) < 3:
        return np.ptp(pts_u[:, 0]) * np.ptp(pts_u[:, 1]) if len(pts_u) > 1 else 0.0
    try:
        hull = ConvexHull(pts_u)
        return hull.volume  # in 2D, hull.volume = area
    except Exception:
        return 0.0


def _footprint_perimeter_and_area(pts_2d):
    """Footprint (2D convex hull) perimeter and area."""
    pts_u = _unique_2d(pts_2d)
    if len(pts_u) < 3:
        return 0.0, 0.0
    try:
        hull = ConvexHull(pts_u)
        return hull.area, hull.volume  # perimeter = hull.area, area = hull.volume
    except Exception:
        return 0.0, 0.0


def _pca_axes(all_v):
    """Return sorted eigenvalues (variances along principal axes)."""
    if len(all_v) < 3:
        return np.array([1.0, 1.0, 1.0])
    c = all_v.mean(axis=0)
    X = all_v - c
    cov = X.T @ X / (len(X) - 1 + 1e-12)
    try:
        w, _ = np.linalg.eigh(cov)
        return np.sort(np.maximum(w, 0))[::-1]
    except Exception:
        return np.array([1.0, 1.0, 1.0])


def _compute_all(all_v, faces, mesh_rec):
    """Compute all 25 property values from vertices and faces."""
    eps = 1e-9
    props = {}

    # bbox in world coords
    if len(all_v) == 0:
        return {p: 0.0 for p in PROP_NAMES}

    bmin, bmax = all_v.min(axis=0), all_v.max(axis=0)
    bbox_dims = bmax - bmin  # [width_x, width_y, height]
    bbw, bbl, bbh = float(bbox_dims[0]), float(bbox_dims[1]), float(bbox_dims[2])

    props["bounding_box_width"]  = max(bbw, eps)
    props["bounding_box_length"] = max(bbl, eps)
    props["aligned_bounding_box_width"]  = max(bbw, eps)
    props["aligned_bounding_box_length"] = max(bbl, eps)
    props["aligned_bounding_box_height"] = max(bbh, eps)
    props["height_diff"] = max(bbh, eps)
    props["num_floors"]   = max(bbh / 3.0, eps)  # ~3m per floor

    # area = sum of face areas
    area = sum(_face_area(f) for f in faces)
    props["area"] = max(area, eps)

    # perimeter = sum of face perimeters
    perim = sum(_face_perimeter(f) for f in faces)
    props["perimeter"] = max(perim, eps)

    # volume via divergence theorem
    vol = _mesh_volume(faces)
    props["volume"] = max(vol, eps)

    # convex hull
    pts_2d = _footprint_vertices(all_v)
    props["convex_hull_area"] = max(_convex_hull_area_2d(pts_2d), eps)
    props["convex_hull_volume"] = max(_convex_hull_volume(all_v), eps)

    # footprint perimeter & area (for compactness / perimeter_ind)
    fp_perim, fp_area = _footprint_perimeter_and_area(pts_2d)
    props["perimeter_ind"] = max(fp_perim / (2.0 * np.sqrt(np.pi * max(fp_area, eps)) + eps), eps)
    props["circumference"] = max(fp_perim, eps)

    # centroid distance
    centroid = np.asarray(mesh_rec.get("centroid", all_v.mean(axis=0)), dtype=np.float64)
    dists = np.linalg.norm(all_v - centroid, axis=1)
    props["ave_centroid_distance"] = max(float(dists.mean()), eps)

    # PCA axes
    axes = _pca_axes(all_v)  # sorted descending
    props["elongation"]  = max(float(axes[0] / (axes[2] + eps)), eps)
    props["axes_symmetry"] = max(float((axes[1] + axes[2]) / (2.0 * max(axes[0], eps))), eps)

    # compactness
    props["compactness_2d"] = max(float(4.0 * np.pi * max(fp_area, eps) / (max(fp_perim, eps) ** 2 + eps)), eps)
    # 3D compactness: V^2 / A^3 * 36π  (sphere = 1)
    area_safe = max(area, eps)
    vol_safe = max(vol, eps)
    props["compactness_3d"] = max(float(36.0 * np.pi * vol_safe * vol_safe / (area_safe * area_safe * area_safe + eps)), eps)

    # density
    props["density"] = max(float(vol_safe / max(fp_area, eps)), eps)

    # shape index
    props["shape_ind"] = max(float(bbh / (np.sqrt(max(fp_area, eps)) + eps)), eps)

    # hemisphericality: how close to a hemisphere (min height vs max height)
    props["hemisphericality"] = max(float(1.0 - (all_v[:, 2].min() - bmin[2]) / (max(bbh, eps))), eps)

    # fractality: log(area) / log(perimeter) as a rough fractal dimension proxy
    props["fractality"] = max(float(np.log(max(area, 1.0)) / np.log(max(perim, 1.0))), eps)

    # cubeness: V / bbox_volume
    bbox_vol = max(bbw * bbl * bbh, eps)
    props["cubeness"] = max(float(vol_safe / bbox_vol), eps)

    # num_vertices
    props["num_vertices"] = max(len(all_v), eps)

    return props


class ObjectPropertiesProcessor:
    def __init__(self, object_dict, vector_normalization=True):
        self.od = object_dict
        self.vector_normalization = vector_normalization
        self.property_dict_generation_time = 0.0
        t0 = time.time()
        self.prop_vals_dict = self._compute()
        self.property_dict_generation_time = time.time() - t0

    def _resolve_sides(self):
        """Object dict may use {'cands':..., 'index':...} or arbitrary side keys.
        Each side value must be {building_id: mesh_record}."""
        if "cands" in self.od and "index" in self.od:
            return ["cands", "index"], self.od
        # Use whatever keys the dict already has as side names
        return list(self.od.keys()), self.od

    def _compute(self):
        sides, od = self._resolve_sides()
        result = {p: {s: {} for s in sides} for p in PROP_NAMES}

        for side in sides:
            for bid, rec in od[side].items():
                faces, all_v = _extract_faces(rec)
                vals = _compute_all(all_v, faces, rec)
                for p in PROP_NAMES:
                    raw = vals.get(p, 0.0)
                    if self.vector_normalization and p not in ("num_vertices", "num_floors"):
                        raw = np.log1p(raw)
                    result[p][side][bid] = float(raw)

        return result