STER / code /object_properties.py
eduzrh's picture
Upload code/object_properties.py with huggingface_hub
86c018f verified
Raw
History Blame Contribute Delete
8.95 kB
"""
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