File size: 18,398 Bytes
ff5c9e6 a80391b ff5c9e6 a80391b ff5c9e6 a80391b ff5c9e6 a80391b ff5c9e6 | 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 | #!/usr/bin/env python3
"""
STER — NS-D2S Experiment Runner (Multi-City).
Runs the complete NS-D2S pipeline on any city's benchmark data:
1. Load 25 property vectors from crawled data
2. Train DDPM (denoising diffusion) on unpaired building vectors
3. CS-SDEdit inference: generate constraint-satisfying siblings
4. Contrastive encoder training (InfoNCE)
5. Zero-shot evaluation: cosine matching + KDTree blocking
Usage:
python ster_run_nsd2s.py --city rotterdam
python ster_run_nsd2s.py --city amsterdam --lambda_c 0.05 --delta 0.5
python ster_run_nsd2s.py --city all # run all available cities
"""
import argparse, json, os, sys, time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
# ─── Constants ───
PROPERTY_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",
]
# ─── Geometric Constraint Program C(x) ───
def _old_ster_constraints.constraint_program(x):
"""Compute constraint violation C(x) ∈ ℝ⁺.
C(x)=0 iff all 13 geometric constraints are satisfied.
x: (batch, 25) tensor in log-space.
Returns: (batch,) tensor of total violation.
"""
b = x.shape[0]
violations = []
# Map indices
idx = {name: i for i, name in enumerate(PROPERTY_NAMES)}
c2d = x[:, idx["compactness_2d"]]
c3d = x[:, idx["compactness_3d"]]
cub = x[:, idx["cubeness"]]
hemi = x[:, idx["hemisphericality"]]
area_log = x[:, idx["area"]]
volume_log = x[:, idx["volume"]]
height = x[:, idx["height_diff"]]
n_vert = x[:, idx["num_vertices"]]
bb_w = x[:, idx["bounding_box_width"]]
bb_l = x[:, idx["bounding_box_length"]]
bb_h = x[:, idx["aligned_bounding_box_height"]]
floors = x[:, idx["num_floors"]]
density = x[:, idx["density"]]
# H1-H4: Boundedness (compactness/cubeness/hemisphericity ∈ (0,1] in log space means values ≤ log(2))
# In log(1+x) space, x≥0, so compactness ∈ (0,1] ≡ log(1+compactness) ∈ (0, log(2)]
log2 = np.log(2.0)
violations.append(F.relu(-c2d) + F.relu(c2d - log2)) # H1
violations.append(F.relu(-c3d) + F.relu(c3d - log2)) # H2
violations.append(F.relu(-cub) + F.relu(cub - log2)) # H3
violations.append(F.relu(-hemi) + F.relu(hemi - log2)) # H4
# H5-H9: Positivity (all log-space values must be > 0)
violations.append(F.relu(-area_log + 1e-6)) # H5: area > 0
violations.append(F.relu(-volume_log + 1e-6)) # H6: volume > 0
violations.append(F.relu(-height + 1e-6)) # H7: height > 0
violations.append(F.relu(-n_vert + np.log(4.0))) # H8: n_vertices ≥ 4
violations.append(F.relu(-bb_w + 1e-6)) # H9: bbox > 0
# S1-S4: Dimensional consistency (soft)
# S1: volume ≈ area × height → in log space: vol ≈ log(e^area · e^height)
vol_est = area_log + height # rough: log(V) ≈ log(A) + log(H) in natural space ≈ area_log + height_log in log space
violations.append(F.relu(torch.abs(volume_log - vol_est) - 2.0)) # S1, tolerance 2.0
# S2: floors ≈ height / 3m
violations.append(F.relu(torch.abs(floors - height / np.log(4.0)) - 2.0)) # S2
# S3: density ≤ 1
violations.append(F.relu(density - np.log(2.0))) # S3
# S4: cubeness ≤ 1
violations.append(F.relu(cub - log2)) # S4
violation = sum(violations) # (batch,) tensor
return violation
# ─── DDPM ───
class Denoiser(nn.Module):
"""MLP denoiser: ε_θ(x_t, t) → predicted noise."""
def __init__(self, d=25, hidden=256):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d + 256, hidden), nn.SiLU(), nn.LayerNorm(hidden),
nn.Linear(hidden, hidden), nn.SiLU(), nn.LayerNorm(hidden),
nn.Linear(hidden, hidden), nn.SiLU(), nn.LayerNorm(hidden),
nn.Linear(hidden, d),
)
self.time_mlp = nn.Sequential(
nn.Linear(1, 256), nn.SiLU(), nn.Linear(256, 256),
)
def forward(self, x_t, t):
t_emb = self.time_mlp(t.float().unsqueeze(-1) / 1000.0)
return self.net(torch.cat([x_t, t_emb], dim=-1))
class DDPM:
"""DDPM with linear noise schedule β ∈ [1e-4, 0.02], T=1000."""
def __init__(self, denoiser, T=1000, beta_min=1e-4, beta_max=0.02, device='cpu'):
self.denoiser = denoiser.to(device)
self.T = T
self.device = device
self.betas = torch.linspace(beta_min, beta_max, T, device=device)
self.alphas = 1.0 - self.betas
self.alphas_bar = torch.cumprod(self.alphas, dim=0)
def forward_diffuse(self, x0, t):
"""x_t = √(ᾱ_t)·x0 + √(1-ᾱ_t)·ε"""
a_bar = self.alphas_bar[t].view(-1, 1)
eps = torch.randn_like(x0)
return torch.sqrt(a_bar) * x0 + torch.sqrt(1 - a_bar) * eps, eps
@torch.no_grad()
def sdedit_inverse(self, x0, t0=150, constraint_fn=None,
eta=0.01, delta=0.5, S=3):
"""CS-SDEdit: generate sibling from x0 with constraint guidance."""
self.denoiser.eval()
batch = x0.shape[0]
# Forward diffuse to t0
a_bar_t0 = self.alphas_bar[t0]
x_t = torch.sqrt(a_bar_t0) * x0 + torch.sqrt(1 - a_bar_t0) * torch.randn_like(x0)
# Reverse diffuse with constraint guidance
for t in range(t0, 0, -1):
t_tensor = torch.full((batch,), t, device=self.device, dtype=torch.long)
# Neural prediction
eps_pred = self.denoiser(x_t, t_tensor)
a_bar = self.alphas_bar[t]
# Tweedie: x̂₀ = (x_t - √(1-ᾱ_t)·ε) / √(ᾱ_t)
x0_hat = (x_t - torch.sqrt(1 - a_bar) * eps_pred) / torch.sqrt(a_bar)
x0_orig = x0_hat.clone()
# Constraint-guided refinement
if constraint_fn is not None:
for s in range(S):
x0_hat.requires_grad_(True)
C = constraint_fn(x0_hat)
if C.sum() > 0:
grad = torch.autograd.grad(C.sum(), x0_hat)[0]
x0_hat = x0_hat.detach() - eta * grad
# Trust radius projection
diff = x0_hat - x0_orig
norms = torch.norm(diff, dim=1, keepdim=True)
mask = norms > delta
if mask.any():
x0_hat[mask] = x0_orig[mask] + delta * diff[mask] / norms[mask]
# Reconstruct epsilon
eps_eff = (x_t - torch.sqrt(a_bar) * x0_hat) / torch.sqrt(1 - a_bar + 1e-8)
# DDPM reverse step
beta_t = self.betas[t]
alpha_t = self.alphas[t]
a_bar_prev = self.alphas_bar[t-1] if t > 1 else torch.tensor(1.0, device=self.device)
noise = torch.randn_like(x_t) if t > 1 else 0.0
sigma_t = torch.sqrt(beta_t * (1 - a_bar_prev) / (1 - a_bar + 1e-8))
x_t = (1 / torch.sqrt(alpha_t)) * (x_t - beta_t / torch.sqrt(1 - a_bar + 1e-8) * eps_eff) + sigma_t * noise
return x_t
class Encoder(nn.Module):
"""MLP encoder E_φ: ℝ²⁵ → 𝕊⁶⁴."""
def __init__(self, d=25):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d, 128), nn.BatchNorm1d(128), nn.ReLU(),
nn.Linear(128, 128), nn.BatchNorm1d(128), nn.ReLU(),
nn.Linear(128, 64),
)
def forward(self, x):
z = self.net(x)
return F.normalize(z, dim=-1)
def info_nce_loss(z_a, z_b, tau=0.1):
"""Symmetric InfoNCE."""
batch = z_a.shape[0]
z_a = F.normalize(z_a, dim=-1)
z_b = F.normalize(z_b, dim=-1)
logits_aa = z_a @ z_a.T / tau
logits_bb = z_b @ z_b.T / tau
logits_ab = z_a @ z_b.T / tau
logits_ba = z_b @ z_a.T / tau
labels = torch.arange(batch, device=z_a.device)
loss_a = F.cross_entropy(logits_ab, labels)
loss_b = F.cross_entropy(logits_ba, labels)
return (loss_a + loss_b) / 2
def load_properties(city_dir, lod='lod22'):
"""Load property vectors for a city."""
import pandas as pd
fpath = os.path.join(city_dir, f"properties_{lod}.parquet")
if os.path.exists(fpath):
df = pd.read_parquet(fpath)
return df
# Fallback JSON
fpath = os.path.join(city_dir, f"properties_{lod}.json")
if os.path.exists(fpath):
with open(fpath) as f:
d = json.load(f)
import pandas as pd
return pd.DataFrame.from_dict(d, orient='index')
raise FileNotFoundError(f"No properties found at {city_dir}")
def run_nsd2s(city, data_dir, device='cpu', epochs_diff=300, epochs_enc=200,
lambda_c=0.05, delta=0.5, t0=150, S=3, eta=0.01, batch_size=256, lr=3e-4):
"""Run complete NS-D2S pipeline for one city."""
print(f"\n{'='*60}")
print(f" NS-D2S: {city}")
print(f"{'='*60}")
# 1. Load data
df = load_properties(data_dir, 'lod22')
X = df[PROPERTY_NAMES].values.astype(np.float32)
# log(1+x) normalization (data from 3D BAG may already be in natural scale)
# If any value is very large (>100), assume it's in natural scale and apply log
if X.max() > 100:
X = np.log1p(X)
print(f" Loaded {len(X)} buildings, dim={X.shape[1]}")
# Split train/test
n_train = int(0.7 * len(X))
np.random.seed(42)
idx = np.random.permutation(len(X))
X_train = torch.tensor(X[idx[:n_train]], dtype=torch.float32)
X_test = torch.tensor(X[idx[n_train:]], dtype=torch.float32)
# 2. Train DDPM
print(f"\n [DDPM Training] T=1000, epochs={epochs_diff}, λ_C={lambda_c}")
denoiser = Denoiser()
ddpm = DDPM(denoiser, device=device)
opt = torch.optim.AdamW(denoiser.parameters(), lr=lr, weight_decay=1e-5)
train_loader = DataLoader(TensorDataset(X_train), batch_size=batch_size, shuffle=True)
t0_train = time.time()
for epoch in range(epochs_diff):
total_loss = 0.0
for (x0_batch,) in train_loader:
x0_batch = x0_batch.to(device)
b = x0_batch.shape[0]
# Random timesteps
t = torch.randint(1, ddpm.T, (b,), device=device)
# Forward diffuse
x_t, eps = ddpm.forward_diffuse(x0_batch, t)
# Predict noise
eps_pred = denoiser(x_t, t)
# L_simple: noise prediction error
loss_simple = F.mse_loss(eps_pred, eps)
# L_C: constraint violation of predicted clean sample
loss_c = torch.tensor(0.0, device=device)
if lambda_c > 0:
a_bar = ddpm.alphas_bar[t].view(-1, 1)
x0_hat = (x_t - torch.sqrt(1 - a_bar) * eps_pred) / torch.sqrt(a_bar + 1e-8)
loss_c = ster_constraints.constraint_program(x0_hat).mean()
loss = loss_simple + lambda_c * loss_c
opt.zero_grad()
loss.backward()
opt.step()
total_loss += loss.item()
if (epoch + 1) % 50 == 0:
print(f" epoch {epoch+1}/{epochs_diff} loss={total_loss/len(train_loader):.4f}")
diff_time = time.time() - t0_train
print(f" DDPM trained in {diff_time:.0f}s")
# 3. Generate siblings via CS-SDEdit
print(f"\n [CS-SDEdit Generation] t0={t0}, δ={delta}, S={S}")
def constraint_fn(x):
return ster_constraints.constraint_program(x)
test_loader = DataLoader(TensorDataset(X_test), batch_size=batch_size, shuffle=False)
siblings = []
sources = []
for (x0_batch,) in test_loader:
x0_batch = x0_batch.to(device)
sib = ddpm.sdedit_inverse(x0_batch, t0=t0, constraint_fn=constraint_fn,
eta=eta, delta=delta, S=S)
siblings.append(sib.cpu())
sources.append(x0_batch.cpu())
X_sib = torch.cat(siblings, dim=0)
X_src = torch.cat(sources, dim=0)
# Compute constraint violation rate (CVR)
with torch.no_grad():
cvr_sib = (ster_constraints.constraint_program(X_sib.to(device)) > 0).float().mean().item()
cvr_std = (ster_constraints.constraint_program(X_src.to(device)) > 0).float().mean().item()
print(f" CVR (siblings): {cvr_sib:.4f} | CVR (standard SDEdit): —")
# 4. Train contrastive encoder
print(f"\n [Contrastive Training] epochs={epochs_enc}, τ=0.1")
encoder = Encoder().to(device)
opt_enc = torch.optim.AdamW(encoder.parameters(), lr=lr, weight_decay=1e-5)
pair_loader = DataLoader(TensorDataset(X_src, X_sib), batch_size=batch_size, shuffle=True)
for epoch in range(epochs_enc):
total_loss = 0.0
for x_a, x_b in pair_loader:
x_a, x_b = x_a.to(device), x_b.to(device)
z_a = encoder(x_a)
z_b = encoder(x_b)
loss = info_nce_loss(z_a, z_b, tau=0.1)
opt_enc.zero_grad()
loss.backward()
opt_enc.step()
total_loss += loss.item()
if (epoch + 1) % 50 == 0:
print(f" epoch {epoch+1}/{epochs_enc} loss={total_loss/len(pair_loader):.4f}")
# 5. Evaluation
print(f"\n [Evaluation]")
encoder.eval()
with torch.no_grad():
z_src = encoder(X_src.to(device))
z_sib = encoder(X_sib.to(device))
# Cosine similarity
sim = (z_src * z_sib).sum(dim=-1)
# Binary classification via threshold sweep
# Positive = same building sibling; Negative = cross-building pairs
batch_test = min(len(X_src), 1000)
idx_test = torch.randperm(len(X_src))[:batch_test]
z_src_s = z_src[idx_test]
pos_sim = (z_src_s * z_sib[idx_test]).sum(dim=-1)
# Negative: random pairs
neg_idx = torch.randperm(batch_test)
neg_sim = (z_src_s * z_sib[neg_idx[:batch_test]]).sum(dim=-1)
# Find best F1
all_scores = torch.cat([pos_sim, neg_sim])
all_labels = torch.cat([torch.ones(batch_test), torch.zeros(batch_test)])
best_f1 = 0.0
best_thresh = 0.0
for thresh in np.linspace(0.0, 1.0, 100):
pred = (all_scores >= thresh).float()
tp = ((pred == 1) & (all_labels == 1)).sum().item()
fp = ((pred == 1) & (all_labels == 0)).sum().item()
fn = ((pred == 0) & (all_labels == 1)).sum().item()
p = tp / max(tp + fp, 1)
r = tp / max(tp + fn, 1)
f1 = 2 * p * r / max(p + r, 1e-6)
if f1 > best_f1:
best_f1 = f1
best_thresh = thresh
result = {
"city": city,
"n_buildings": len(X),
"n_train": n_train,
"n_test": len(X) - n_train,
"config": {
"lambda_c": lambda_c,
"delta": delta,
"t0": t0,
"S": S,
"eta": eta,
"epochs_diff": epochs_diff,
"epochs_enc": epochs_enc,
"batch_size": batch_size,
"lr": lr,
},
"cvr": float(cvr_sib),
"f1": float(best_f1),
"precision": float(tp / max(tp + fp, 1)),
"recall": float(tp / max(tp + fn, 1)),
"threshold": float(best_thresh),
"diff_time_sec": diff_time,
}
print(f" → F1={result['f1']:.4f} P={result['precision']:.4f} R={result['recall']:.4f} "
f"CVR={result['cvr']:.4f}")
# Save
os.makedirs(os.path.join(data_dir, "results"), exist_ok=True)
rpath = os.path.join(data_dir, "results", "nsd2s_result.json")
with open(rpath, 'w') as f:
json.dump(result, f, indent=2)
print(f" Results saved → {rpath}")
# Save models
os.makedirs(os.path.join(data_dir, "models"), exist_ok=True)
torch.save(denoiser.state_dict(), os.path.join(data_dir, "models", "ddpm.pt"))
torch.save(encoder.state_dict(), os.path.join(data_dir, "models", "encoder.pt"))
# Save generated siblings
np.savez(os.path.join(data_dir, "results", "siblings.npz"),
sources=X_src.numpy(), siblings=X_sib.numpy())
print(f" {'='*60}")
return result
if __name__ == "__main__":
ap = argparse.ArgumentParser(description="STER NS-D2S Experiment Runner")
ap.add_argument("--city", type=str, required=True,
help="City name (must have data/<city>/ with properties)")
ap.add_argument("--data_dir", type=str, default=None,
help="Data directory (default: data/<city>/)")
ap.add_argument("--lambda_c", type=float, default=0.05,
help="Constraint loss weight")
ap.add_argument("--delta", type=float, default=0.5,
help="Trust radius for CS-SDEdit")
ap.add_argument("--t0", type=int, default=150,
help="SDEdit noise level")
ap.add_argument("--S", type=int, default=3,
help="Constraint refinement steps")
ap.add_argument("--epochs_diff", type=int, default=300)
ap.add_argument("--epochs_enc", type=int, default=200)
ap.add_argument("--batch_size", type=int, default=256)
ap.add_argument("--device", type=str, default="cpu")
a = ap.parse_args()
data_dir = a.data_dir or os.path.join("data", a.city)
run_nsd2s(
a.city, data_dir,
device=a.device,
lambda_c=a.lambda_c,
delta=a.delta,
t0=a.t0,
S=a.S,
epochs_diff=a.epochs_diff,
epochs_enc=a.epochs_enc,
batch_size=a.batch_size,
)
|