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
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
"""
STER-GI Idea 3: Denoise-to-Sibling (去噪造兄弟)
================================================
- Train unconditional diffusion on ALL building property vectors (no labels)
- Generate "sibling" buildings via SDEdit (partial noise + denoise)
- Contrastive learning on (original, sibling) pairs
- Zero-shot evaluation on test pairs: encode → cosine sim → threshold → match

Baselines:
  - real-only (raw property cosine): no training at all
  - Idea 3 (denoise-to-sibling): diffusion + contrastive
"""

import os, sys, time, warnings, argparse
import numpy as np
import joblib, pickle as pkl
import torch, torch.nn as nn, torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import precision_score, recall_score, f1_score, average_precision_score
from collections import defaultdict

warnings.filterwarnings("ignore")

# ============================================================
# Config
# ============================================================
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"
]

CFG = {
    'diffusion_steps': 1000,
    'diffusion_hidden': 256,
    'diffusion_layers': 4,
    'diffusion_epochs': 500,
    'diffusion_lr': 1e-3,
    'diffusion_batch_size': 512,
    # SDEdit: how much noise to add (0=none, 1000=full)
    'sdedit_t0': 200,
    'num_siblings': 3,
    # Encoder
    'encoder_hidden': 128,
    'encoder_dim': 64,
    'contrastive_epochs': 200,
    'contrastive_lr': 1e-3,
    'contrastive_temp': 0.07,
    'contrastive_batch': 1024,
    # Eval: threshold sweep
    'eval_thresholds': [0.5, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.92, 0.95, 0.97, 0.99],
    'device': 'cuda' if torch.cuda.is_available() else 'cpu',
}

# ============================================================
# Data: Extract property vectors
# ============================================================
def extract_vectors(prop_dict, source, id_list=None):
    """Extract property matrix for given source ('cands'/'index') and optional id filter"""
    first_prop = PROPERTY_NAMES[0]
    all_ids = list(prop_dict[first_prop][source].keys()) if id_list is None else id_list
    X = np.zeros((len(all_ids), len(PROPERTY_NAMES)), dtype=np.float32)
    valid_ids = []
    for i, bid in enumerate(all_ids):
        vec = []
        ok = True
        for pname in PROPERTY_NAMES:
            val = prop_dict[pname][source].get(bid, None)
            if val is None or (isinstance(val, float) and np.isnan(val)):
                val = 0.0
            vec.append(float(val))
        X[i] = vec
        valid_ids.append(bid)
    return X, valid_ids


def load_all_train_vectors(seed):
    """Load property vectors for ALL training buildings (both cands and index)"""
    train_path = (f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_"
                  f"neg_samples_num=2_vector_normalization=True_seed={seed}.joblib")
    prop = joblib.load(train_path)

    X_cands, ids_cands = extract_vectors(prop, 'cands')
    X_index, ids_index = extract_vectors(prop, 'index')
    X = np.concatenate([X_cands, X_index], axis=0)
    all_ids = ids_cands + ids_index
    print(f"Loaded {len(X)} train building vectors ({len(X_cands)} cands + {len(X_index)} index)")
    return X, all_ids, prop


def load_test_pairs(seed):
    """Load test pairs with labels: list of (cand_id, index_id, label)"""
    test_path = (f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_"
                 f"neg_samples_num=2_vector_normalization=True_seed={seed}.joblib")
    prop = joblib.load(test_path)

    partition = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb'))
    test_pairs = partition['test']['matching']['negative_sampling']['medium'][2]

    # Build cand/index ID -> vector mappings
    cand_map = {}
    for bid in prop[PROPERTY_NAMES[0]]['cands'].keys():
        vec = []
        for pname in PROPERTY_NAMES:
            val = prop[pname]['cands'].get(bid, None)
            if val is None or (isinstance(val, float) and np.isnan(val)):
                val = 0.0
            vec.append(float(val))
        cand_map[bid] = np.array(vec, dtype=np.float32)

    index_map = {}
    for bid in prop[PROPERTY_NAMES[0]]['index'].keys():
        vec = []
        for pname in PROPERTY_NAMES:
            val = prop[pname]['index'].get(bid, None)
            if val is None or (isinstance(val, float) and np.isnan(val)):
                val = 0.0
            vec.append(float(val))
        index_map[bid] = np.array(vec, dtype=np.float32)

    cand_vecs, index_vecs, labels = [], [], []
    for cid, iid in test_pairs:
        if cid in cand_map and iid in index_map:
            cand_vecs.append(cand_map[cid])
            index_vecs.append(index_map[iid])
            labels.append(1 if cid == iid else 0)

    cand_vecs = np.array(cand_vecs, dtype=np.float32)
    index_vecs = np.array(index_vecs, dtype=np.float32)
    labels = np.array(labels, dtype=np.int32)

    print(f"Test pairs: {len(labels)} ({labels.sum()} pos, {(1-labels).sum()} neg)")
    return cand_vecs, index_vecs, labels


# ============================================================
# Diffusion Model (DDPM on property vectors)
# ============================================================
class MLPDiffusion(nn.Module):
    def __init__(self, dim, hidden=256, layers=4):
        super().__init__()
        self.time_embed = nn.Sequential(
            nn.Linear(1, hidden), nn.SiLU(), nn.Linear(hidden, hidden))
        net = [nn.Linear(dim + hidden, hidden), nn.SiLU()]
        for _ in range(layers - 1):
            net += [nn.Linear(hidden, hidden), nn.SiLU()]
        net.append(nn.Linear(hidden, dim))
        self.net = nn.Sequential(*net)

    def forward(self, x, t):
        t_emb = self.time_embed(t.unsqueeze(-1).float())
        return self.net(torch.cat([x, t_emb], dim=-1))


class DiffusionScheduler:
    def __init__(self, steps=1000, beta_start=1e-4, beta_end=0.02):
        self.steps = steps
        self.betas = torch.linspace(beta_start, beta_end, steps)
        self.alphas = 1 - self.betas
        self.alpha_bars = torch.cumprod(self.alphas, dim=0)

    def add_noise(self, x0, t):
        ab = self.alpha_bars[t].view(-1, 1)
        noise = torch.randn_like(x0)
        return torch.sqrt(ab) * x0 + torch.sqrt(1 - ab) * noise, noise

    @torch.no_grad()
    def denoise_step(self, model, xt, t):
        """Single DDPM reverse step"""
        a = self.alphas[t].view(-1, 1)
        ab = self.alpha_bars[t].view(-1, 1)
        b = self.betas[t].view(-1, 1)
        eps = model(xt, t.float())
        x0_hat = (xt - torch.sqrt(1 - ab) * eps) / torch.sqrt(a)
        if t.min() == 0:
            return x0_hat
        ab_prev = self.alpha_bars[t - 1].view(-1, 1)
        mean = (torch.sqrt(ab_prev) * b / (1 - ab) * x0_hat +
                torch.sqrt(a) * (1 - ab_prev) / (1 - ab) * xt)
        var = b * (1 - ab_prev) / (1 - ab)
        return mean + torch.sqrt(var) * torch.randn_like(xt)

    @torch.no_grad()
    def sdedit(self, model, x0, t0, device):
        """Add noise to t0, then denoise back → sibling"""
        n = x0.shape[0]
        t0_t = torch.full((n,), t0, device=device, dtype=torch.long)
        ab_t0 = self.alpha_bars[t0]
        noise = torch.randn_like(x0)
        xt = torch.sqrt(ab_t0) * x0 + torch.sqrt(1 - ab_t0) * noise
        for t in range(t0, -1, -1):
            tb = torch.full((n,), t, device=device, dtype=torch.long)
            xt = self.denoise_step(model, xt, tb)
        return xt


# ============================================================
# Contrastive Encoder
# ============================================================
class BuildingEncoder(nn.Module):
    def __init__(self, dim, hidden=128, out_dim=64):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(dim, hidden), nn.BatchNorm1d(hidden), nn.ReLU(),
            nn.Linear(hidden, hidden), nn.BatchNorm1d(hidden), nn.ReLU(),
            nn.Linear(hidden, out_dim))

    def forward(self, x):
        return F.normalize(self.net(x), dim=-1)


def info_nce_loss(embs, temp=0.07):
    """embs: [2B, D] where (0,1), (2,3)... are positives"""
    n = embs.shape[0] // 2
    sim = embs @ embs.T / temp
    # Mask self
    sim = sim.masked_fill(torch.eye(2 * n, device=embs.device, dtype=torch.bool), -1e9)
    # Labels: for row i, positive is i^1 (flip last bit)
    labels = torch.arange(2 * n, device=embs.device)
    labels = labels ^ 1  # (0->1, 1->0, 2->3, 3->2, ...)
    return F.cross_entropy(sim, labels)


# ============================================================
# Training
# ============================================================
def train_diffusion(X, device):
    print("\n" + "=" * 50)
    print("Stage 1: Train Diffusion on Building Vectors")
    print("=" * 50)
    dim = X.shape[1]
    model = MLPDiffusion(dim, CFG['diffusion_hidden'], CFG['diffusion_layers']).to(device)
    sched = DiffusionScheduler(CFG['diffusion_steps'])
    sched.betas = sched.betas.to(device)
    sched.alphas = sched.alphas.to(device)
    sched.alpha_bars = sched.alpha_bars.to(device)

    opt = torch.optim.Adam(model.parameters(), lr=CFG['diffusion_lr'])
    ds = TensorDataset(torch.FloatTensor(X))
    dl = DataLoader(ds, batch_size=CFG['diffusion_batch_size'], shuffle=True)

    model.train()
    for ep in range(CFG['diffusion_epochs']):
        total = 0
        for (xb,) in dl:
            xb = xb.to(device)
            bs = xb.shape[0]
            t = torch.randint(0, CFG['diffusion_steps'], (bs,), device=device)
            xt, noise = sched.add_noise(xb, t)
            loss = F.mse_loss(model(xt, t.float()), noise)
            opt.zero_grad()
            loss.backward()
            opt.step()
            total += loss.item() * bs
        if (ep + 1) % 100 == 0:
            print(f"  Epoch {ep+1}/{CFG['diffusion_epochs']} | Loss: {total/len(ds):.6f}")
    print(f"  Done. Final loss: {total/len(ds):.6f}")
    return model, sched


def generate_siblings(model, sched, X, device):
    print("\n" + "=" * 50)
    print(f"Stage 2: Generate Siblings (t0={CFG['sdedit_t0']})")
    print("=" * 50)
    model.eval()
    origs, sibs = [], []
    bs = CFG['diffusion_batch_size']
    for i in range(0, len(X), bs):
        xb = torch.FloatTensor(X[i:i+bs]).to(device)
        for _ in range(CFG['num_siblings']):
            sib = sched.sdedit(model, xb, CFG['sdedit_t0'], device)
            origs.append(xb.cpu().numpy())
            sibs.append(sib.cpu().numpy())

    origs = np.concatenate(origs, axis=0)
    sibs = np.concatenate(sibs, axis=0)
    l2 = np.mean(np.linalg.norm(origs - sibs, axis=1))
    print(f"  Generated {len(origs)} pairs | Mean L2 diff: {l2:.4f}")
    return origs, sibs


def train_encoder(origs, sibs, device):
    print("\n" + "=" * 50)
    print("Stage 3: Contrastive Encoder Training")
    print("=" * 50)
    dim = origs.shape[1]
    encoder = BuildingEncoder(dim, CFG['encoder_hidden'], CFG['encoder_dim']).to(device)
    opt = torch.optim.Adam(encoder.parameters(), lr=CFG['contrastive_lr'])

    # Interleave: [orig1, sib1, orig2, sib2, ...]
    n = len(origs)
    data = np.zeros((n * 2, dim), dtype=np.float32)
    data[0::2] = origs
    data[1::2] = sibs
    ds = TensorDataset(torch.FloatTensor(data))
    dl = DataLoader(ds, batch_size=CFG['contrastive_batch'], shuffle=True)

    encoder.train()
    for ep in range(CFG['contrastive_epochs']):
        total = 0
        for (xb,) in dl:
            xb = xb.to(device)
            emb = encoder(xb)
            loss = info_nce_loss(emb, CFG['contrastive_temp'])
            opt.zero_grad()
            loss.backward()
            opt.step()
            total += loss.item() * xb.shape[0]
        if (ep + 1) % 50 == 0:
            print(f"  Epoch {ep+1}/{CFG['contrastive_epochs']} | Loss: {total/len(ds):.4f}")
    print(f"  Done. Final loss: {total/len(ds):.4f}")
    return encoder


# ============================================================
# Evaluation
# ============================================================
@torch.no_grad()
def eval_zero_shot(encoder, cand_vecs, index_vecs, labels, device, tag="Model"):
    """Zero-shot pair classification via cosine similarity"""
    encoder.eval()
    ct = torch.FloatTensor(cand_vecs).to(device)
    it = torch.FloatTensor(index_vecs).to(device)
    ce = encoder(ct).cpu().numpy()
    ie = encoder(it).cpu().numpy()

    # Cosine sim for each pair
    sims = np.sum(ce * ie, axis=1)  # [N]

    # Sweep thresholds
    best_f1, best_thresh, best_res = 0, 0.5, None
    for th in CFG['eval_thresholds']:
        pred = (sims >= th).astype(np.int32)
        p = precision_score(labels, pred, zero_division=0)
        r = recall_score(labels, pred, zero_division=0)
        f = f1_score(labels, pred, zero_division=0)
        if f > best_f1:
            best_f1, best_thresh, best_res = f, th, (p, r, f)

    print(f"\n  {tag} (best threshold={best_thresh:.2f}):")
    print(f"    Precision: {best_res[0]:.4f}")
    print(f"    Recall:    {best_res[1]:.4f}")
    print(f"    F1:        {best_res[2]:.4f}")

    # Also AP score
    ap = average_precision_score(labels, sims)
    print(f"    AvgPrecision: {ap:.4f}")

    return {'precision': best_res[0], 'recall': best_res[1], 'f1': best_res[2],
            'ap': ap, 'threshold': best_thresh}


def eval_real_only(cand_vecs, index_vecs, labels):
    """Baseline: raw property cosine similarity, no training"""
    # Normalize
    cn = cand_vecs / (np.linalg.norm(cand_vecs, axis=1, keepdims=True) + 1e-8)
    i_n = index_vecs / (np.linalg.norm(index_vecs, axis=1, keepdims=True) + 1e-8)
    sims = np.sum(cn * i_n, axis=1)

    best_f1, best_thresh, best_res = 0, 0.5, None
    for th in CFG['eval_thresholds']:
        pred = (sims >= th).astype(np.int32)
        p = precision_score(labels, pred, zero_division=0)
        r = recall_score(labels, pred, zero_division=0)
        f = f1_score(labels, pred, zero_division=0)
        if f > best_f1:
            best_f1, best_thresh, best_res = f, th, (p, r, f)

    ap = average_precision_score(labels, sims)
    print(f"\n  Baseline Real-Only (best th={best_thresh:.2f}):")
    print(f"    P={best_res[0]:.4f} R={best_res[1]:.4f} F1={best_res[2]:.4f} AP={ap:.4f}")

    return {'precision': best_res[0], 'recall': best_res[1], 'f1': best_res[2],
            'ap': ap, 'threshold': best_thresh}


# ============================================================
# Main
# ============================================================
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=1)
    parser.add_argument('--t0', type=int, default=200, help='SDEdit noise level')
    parser.add_argument('--skip_diff', action='store_true')
    parser.add_argument('--skip_enc', action='store_true')
    args = parser.parse_args()

    CFG['sdedit_t0'] = args.t0
    device = CFG['device']
    seed = args.seed
    print(f"Device: {device} | t0: {args.t0} | Seed: {seed}")

    # ---- Load data ----
    X_train, train_ids, train_prop = load_all_train_vectors(seed)
    cand_vecs, idx_vecs, labels = load_test_pairs(seed)

    # Normalize (fit on train, apply to test)
    scaler = StandardScaler()
    X_train_s = scaler.fit_transform(X_train)
    cand_s = scaler.transform(cand_vecs)
    idx_s = scaler.transform(idx_vecs)

    # ---- Stage 1+2: Diffusion → Siblings ----
    diff_path = f"saved_model_files/diff_idea3_s{seed}_t{args.t0}.pt"
    sib_path = f"saved_model_files/siblings_idea3_s{seed}_t{args.t0}.npz"

    if args.skip_diff and os.path.exists(diff_path):
        print(f"Loading cached diffusion model: {diff_path}")
        ck = torch.load(diff_path, map_location=device)
        model = MLPDiffusion(X_train_s.shape[1], CFG['diffusion_hidden'],
                            CFG['diffusion_layers']).to(device)
        model.load_state_dict(ck['model'])
        sched = DiffusionScheduler(CFG['diffusion_steps'])
        sched.betas = sched.betas.to(device)
        sched.alphas = sched.alphas.to(device)
        sched.alpha_bars = sched.alpha_bars.to(device)
    else:
        model, sched = train_diffusion(X_train_s, device)
        torch.save({'model': model.state_dict()}, diff_path)

    if os.path.exists(sib_path):
        print(f"Loading cached siblings: {sib_path}")
        data = np.load(sib_path)
        origs, sibs = data['origs'], data['sibs']
    else:
        origs, sibs = generate_siblings(model, sched, X_train_s, device)
        np.savez_compressed(sib_path, origs=origs, sibs=sibs)

    # ---- Stage 3: Contrastive Encoder ----
    enc_path = f"saved_model_files/enc_idea3_s{seed}_t{args.t0}.pt"

    if args.skip_enc and os.path.exists(enc_path):
        print(f"Loading cached encoder: {enc_path}")
        ck = torch.load(enc_path, map_location=device)
        encoder = BuildingEncoder(X_train_s.shape[1], CFG['encoder_hidden'],
                                  CFG['encoder_dim']).to(device)
        encoder.load_state_dict(ck['encoder'])
    else:
        encoder = train_encoder(origs, sibs, device)
        torch.save({'encoder': encoder.state_dict()}, enc_path)

    # ---- Evaluation ----
    print("\n" + "=" * 50)
    print("RESULTS")
    print("=" * 50)

    r_base = eval_real_only(cand_s, idx_s, labels)
    r_idea3 = eval_zero_shot(encoder, cand_s, idx_s, labels, device,
                              f"Idea 3 (t0={args.t0})")

    print("\n" + "=" * 50)
    print(f"SUMMARY (seed={seed}, t0={args.t0})")
    print("=" * 50)
    print(f"  Baseline (real-only):    F1={r_base['f1']:.4f}  AP={r_base['ap']:.4f}")
    print(f"  Idea 3  (denoise-sib):   F1={r_idea3['f1']:.4f}  AP={r_idea3['ap']:.4f}")
    print(f"  ΔF1: {r_idea3['f1'] - r_base['f1']:.4f}  ΔAP: {r_idea3['ap'] - r_base['ap']:.4f}")

    return r_base, r_idea3


if __name__ == '__main__':
    main()