File size: 33,357 Bytes
11ef0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
"""
STER-GI: Train ALL 6 ideas on synthetic cross-LoD data.
Uses aggressive noise model to simulate LoD1.2 ↔ LoD2.2 differences.

Baseline: F1≈0.66 (raw cosine, cross-LoD)
Target:  F1≥0.80 (+20%)

Usage:
  python ster_train_synth.py --idea 3  --epochs 200
  python ster_train_synth.py --idea 3p --epochs 200 --t0 200
  python ster_train_synth.py --idea 1  --epochs 200
  python ster_train_synth.py --idea 2  --epochs 200
  python ster_train_synth.py --idea 4  --epochs 200 --t0 200 --keep_frac 0.5
  python ster_train_synth.py --idea 5  --epochs 100 --rounds 3
  python ster_train_synth.py --idea 6  --epochs 200 --knn 5
"""
import os, sys, json, time, argparse
import numpy as np
from collections import OrderedDict
import warnings
warnings.filterwarnings('ignore')

import torch, torch.nn as nn, torch.nn.functional as F
import joblib
from ddpm import DDPM, BetaSchedule

DEV = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Device: {DEV}")
torch.set_num_threads(1)
import os as _os
_os.environ['OMP_NUM_THREADS'] = '1'
_os.environ['MKL_NUM_THREADS'] = '1'

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"]

# ============================================================
# Encoder (25→128→128→64, L2-normalized output)
# ============================================================
class Encoder(nn.Module):
    def __init__(self, d=25, h=128, o=64):
        super().__init__()
        self.net = nn.Sequential(OrderedDict([
            ('0', nn.Linear(d, h)), ('1', nn.BatchNorm1d(h)), ('2', nn.ReLU()),
            ('3', nn.Linear(h, h)), ('4', nn.BatchNorm1d(h)), ('5', nn.ReLU()),
            ('6', nn.Linear(h, o))
        ]))
    def forward(self, x):
        z = self.net(x)
        return z / (torch.norm(z, dim=-1, keepdim=True).clamp(min=1e-8))

# ============================================================
# InfoNCE Loss
# ============================================================
def infonce_loss(z_a, z_b, tau=0.1):
    B = z_a.shape[0]
    z_a = F.normalize(z_a, dim=-1)
    z_b = F.normalize(z_b, dim=-1)
    sim = torch.mm(z_a, z_b.T) / tau
    labels = torch.arange(B, device=z_a.device)
    return (F.cross_entropy(sim, labels) + F.cross_entropy(sim.T, labels)) / 2

# ============================================================
# Data: Aggressive LoD Noise
# ============================================================
def aggressive_lod_noise(props, seed=42):
    """Simulate LoD1.2 → LoD2.2 transformation."""
    rng = np.random.RandomState(seed)
    p = props.copy().astype(np.float64)
    N, D = p.shape
    for j, pn in enumerate(PROP_NAMES):
        if pn in ['volume', 'convex_hull_volume']:
            p[:, j] *= rng.uniform(0.3, 3.0, N)
        elif pn in ['area', 'convex_hull_area', 'perimeter', 'circumference']:
            p[:, j] *= rng.uniform(0.5, 2.0, N)
        elif pn in ['height_diff', 'aligned_bounding_box_height']:
            p[:, j] += rng.randn(N) * 5.0
            p[:, j] = np.maximum(0.1, p[:, j])
        elif pn == 'num_vertices':
            p[:, j] *= rng.uniform(0.3, 0.8, N)
        elif pn == 'num_floors':
            p[:, j] += rng.randint(-2, 3, N).astype(np.float64)
            p[:, j] = np.maximum(1, p[:, j])
        else:
            p[:, j] *= rng.uniform(0.5, 1.5, N)
    p += rng.randn(N, D) * 0.1
    return p.astype(np.float32)

def load_and_split_data():
    """Load all building properties, split into train/test, apply LoD noise."""
    all_mats, all_ids = [], []
    for suf in ['Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1',
                'Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1']:
        pdict = joblib.load(f'data/property_dicts/{suf}.joblib')
        for side in ['cands', 'index']:
            ids = list(pdict[PROP_NAMES[0]][side].keys())
            mat = np.zeros((len(ids), len(PROP_NAMES)), dtype=np.float32)
            for j, pn in enumerate(PROP_NAMES):
                for i, bid in enumerate(ids):
                    val = pdict[pn][side].get(bid)
                    if val is not None:
                        mat[i, j] = float(val)
            mat = np.nan_to_num(mat, nan=0.0, posinf=1e6, neginf=-1e6)
            all_mats.append(mat)
            all_ids.extend(ids)
    
    X = np.vstack(all_mats)
    N = len(X)
    rng = np.random.RandomState(42)
    perm = rng.permutation(N)
    n_train = int(N * 0.6)
    train_props = X[perm[:n_train]]
    test_props = X[perm[n_train:]]
    test_ids = [all_ids[i] for i in perm[n_train:]]
    
    train_coarse = aggressive_lod_noise(train_props, seed=1)
    test_coarse = aggressive_lod_noise(test_props, seed=123)
    
    # Z-score standardize (fit on train only)
    all_cat = np.vstack([train_props, train_coarse])
    mean = all_cat.mean(axis=0, keepdims=True)
    std = all_cat.std(axis=0, keepdims=True)
    std[std < 1e-8] = 1.0
    
    train_fine_n = (train_props - mean) / std
    train_coarse_n = (train_coarse - mean) / std
    test_fine_n = (test_props - mean) / std
    test_coarse_n = (test_coarse - mean) / std
    
    print(f"Train: {len(train_fine_n)} pairs, Test: {len(test_fine_n)} pairs")
    return (train_fine_n, train_coarse_n), (test_fine_n, test_coarse_n, test_ids)


# ============================================================
# Contrastive Trainer
# ============================================================
class ContrastiveTrainer:
    def __init__(self, d=25, h=128, o=64, lr=3e-4, tau=0.1):
        self.encoder = Encoder(d, h, o).to(DEV)
        self.optimizer = torch.optim.AdamW(self.encoder.parameters(), lr=lr, weight_decay=1e-5)
        self.tau = tau
    
    def train_epoch(self, pairs_a, pairs_b, batch_size=256):
        N = len(pairs_a)
        idx = np.random.permutation(N)
        total_loss = 0
        n_batches = 0
        for start in range(0, N, batch_size):
            batch_idx = idx[start:start+batch_size]
            ba = torch.tensor(pairs_a[batch_idx], dtype=torch.float32).to(DEV)
            bb = torch.tensor(pairs_b[batch_idx], dtype=torch.float32).to(DEV)
            z_a = self.encoder(ba)
            z_b = self.encoder(bb)
            loss = infonce_loss(z_a, z_b, self.tau)
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()
            total_loss += loss.item()
            n_batches += 1
        return total_loss / max(n_batches, 1)
    
    def save(self, path):
        torch.save({'e': self.encoder.state_dict()}, path)

# ============================================================
# Evaluation
# ============================================================
def evaluate_encoder(enc, test_fine, test_coarse):
    fine_t = torch.tensor(test_fine, dtype=torch.float32).to(DEV)
    coarse_t = torch.tensor(test_coarse, dtype=torch.float32).to(DEV)
    N = len(test_fine)
    bs = 512
    emb_fine, emb_coarse = [], []
    with torch.no_grad():
        for start in range(0, N, bs):
            emb_fine.append(enc(fine_t[start:start+bs]).cpu().numpy())
            emb_coarse.append(enc(coarse_t[start:start+bs]).cpu().numpy())
    emb_fine = np.vstack(emb_fine)
    emb_coarse = np.vstack(emb_coarse)
    pos_sims = np.sum(emb_fine * emb_coarse, axis=1)
    rng = np.random.RandomState(42)
    neg_idx = rng.permutation(N)
    neg_sims = np.sum(emb_fine * emb_coarse[neg_idx], axis=1)
    all_sims = np.concatenate([pos_sims, neg_sims])
    all_labels = np.concatenate([np.ones(N, dtype=np.int32), np.zeros(N, dtype=np.int32)])
    best_f1 = 0.0
    for t in np.linspace(0.1, 0.999, 100):
        pred = (all_sims >= t).astype(np.int32)
        tp = float(((pred == 1) & (all_labels == 1)).sum())
        fp = float(((pred == 1) & (all_labels == 0)).sum())
        fn = float(((pred == 0) & (all_labels == 1)).sum())
        p = tp / (tp + fp + 1e-9)
        r = tp / (tp + fn + 1e-9)
        f1 = 2.0 * p * r / (p + r + 1e-9)
        if f1 > best_f1: best_f1 = f1
    return float(best_f1)

def baseline_f1(test_fine, test_coarse):
    fn = test_fine / (np.linalg.norm(test_fine, axis=1, keepdims=True) + 1e-8)
    cn = test_coarse / (np.linalg.norm(test_coarse, axis=1, keepdims=True) + 1e-8)
    pos = np.sum(fn * cn, axis=1)
    rng = np.random.RandomState(42)
    neg_idx = rng.permutation(len(cn))
    neg = np.sum(fn * cn[neg_idx], axis=1)
    all_sims = np.concatenate([pos, neg])
    all_labels = np.concatenate([np.ones(len(pos), dtype=np.int32), np.zeros(len(neg), dtype=np.int32)])
    best_f1 = 0.0
    for t in np.linspace(0.1, 0.999, 100):
        pred = (all_sims >= t).astype(np.int32)
        tp = float(((pred == 1) & (all_labels == 1)).sum())
        fp = float(((pred == 1) & (all_labels == 0)).sum())
        fn = float(((pred == 0) & (all_labels == 1)).sum())
        p = tp / (tp + fp + 1e-9)
        r = tp / (tp + fn + 1e-9)
        f1 = 2.0 * p * r / (p + r + 1e-9)
        if f1 > best_f1: best_f1 = f1
    return float(best_f1)

# ============================================================
# Idea 1: Detail-Spectrum Imagination (Conditional Diffusion)
# ============================================================
class ConditionalDenoiser(nn.Module):
    def __init__(self, d=25, h=256, T=1000):
        super().__init__()
        self.t_emb = nn.Embedding(T, h)
        self.net = nn.Sequential(OrderedDict([
            ('in', nn.Linear(d + d + h, h)),
            ('n1', nn.LayerNorm(h)), ('a1', nn.SiLU()),
            ('h1', nn.Linear(h, h)),
            ('n2', nn.LayerNorm(h)), ('a2', nn.SiLU()),
            ('h2', nn.Linear(h, h)),
            ('n3', nn.LayerNorm(h)), ('a3', nn.SiLU()),
            ('out', nn.Linear(h, d)),
        ]))
    def forward(self, x, t, condition):
        te = self.t_emb(t)
        return self.net(torch.cat([x, condition, te], dim=-1))

class ConditionalDDPM:
    def __init__(self, d=25, h=256, T=1000):
        self.d, self.h, self.T = d, h, T
        self.schedule = BetaSchedule(T)
        self.denoiser = ConditionalDenoiser(d, h, T).to(DEV)
        self.optimizer = torch.optim.AdamW(self.denoiser.parameters(), lr=3e-4)
    
    def train_step(self, x_src, x_tgt):
        B = x_tgt.shape[0]
        t = torch.randint(0, self.T, (B,), device=DEV)
        x_t, noise = self.schedule.forward_diffuse(x_tgt, t)
        pred = self.denoiser(x_t, t, x_src)
        loss = F.mse_loss(pred, noise)
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()
        return loss.item()
    
    @torch.no_grad()
    def sample(self, x_src, steps=None):
        if steps is None: steps = min(self.T, 100)
        self.denoiser.eval()
        n = x_src.shape[0]
        x = torch.randn(n, self.d, device=DEV)
        step_size = self.T // steps
        for t_idx in reversed(range(0, self.T, step_size)):
            t = torch.full((n,), t_idx, device=DEV, dtype=torch.long)
            pred_noise = self.denoiser(x, t, x_src)
            alpha = self.schedule.alphas[t_idx]
            alpha_bar = self.schedule.alpha_bars[t_idx]
            beta = self.schedule.betas[t_idx]
            if t_idx > 0:
                noise = torch.randn_like(x)
                x = (1.0/torch.sqrt(alpha)) * (
                    x - (beta/torch.sqrt(1.0-alpha_bar)) * pred_noise
                ) + torch.sqrt(beta) * noise
            else:
                x = (1.0/torch.sqrt(alpha)) * (
                    x - (beta/torch.sqrt(1.0-alpha_bar)) * pred_noise
                )
        self.denoiser.train()
        return x
    
    def save(self, path):
        torch.save({'denoiser': self.denoiser.state_dict(),
                     'd': self.d, 'h': self.h, 'T': self.T}, path)
    
    @classmethod
    def load(cls, path):
        state = torch.load(path, map_location=DEV)
        model = cls(d=state['d'], h=state['h'], T=state['T'])
        model.denoiser.load_state_dict(state['denoiser'])
        model.denoiser.to(DEV)
        return model

def train_idea1_synth(train_fine, train_coarse, test_fine, test_coarse,
                       epochs=200, batch_size=256):
    """
    Idea 1: Detail-Spectrum Imagination
    - Train conditional DDPM on (train_fine → train_coarse) to learn LoD transformation
    - Generate cross-LoD views for train buildings (conditioned on train_fine)
    - Interpolate: tau*src + (1-tau)*generated = intermediate detail levels
    - Train InfoNCE encoder on (original, interpolated) pairs
    """
    print(f"Idea 1: Detail-Spectrum Imagination ({len(train_fine)} pairs)")
    
    print("  Training conditional DDPM (fine→coarse)...")
    cddpm = ConditionalDDPM(d=train_fine.shape[1])
    N_train = len(train_fine)
    for ep in range(300):
        perm = torch.randperm(N_train)
        ep_loss = 0
        n_batches = 0
        for start in range(0, N_train, batch_size):
            idx = perm[start:start+batch_size]
            src = torch.tensor(train_fine[idx], dtype=torch.float32).to(DEV)
            tgt = torch.tensor(train_coarse[idx], dtype=torch.float32).to(DEV)
            ep_loss += cddpm.train_step(src, tgt)
            n_batches += 1
        if ep % 100 == 0:
            print(f"    C-DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
    cddpm.save('saved_model_files/cdiff_synth.pt')
    
    # Generate coarse-detail views for all train buildings
    print("  Generating detail-spectrum views via C-DDPM...")
    train_fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
    gen_views = []
    for start in range(0, len(train_fine), batch_size):
        batch = train_fine_t[start:start+batch_size]
        gen = cddpm.sample(batch)
        gen_views.append(gen.cpu().numpy())
    gen_views = np.vstack(gen_views)
    
    # Create interpolated views at multiple tau levels
    combined_a, combined_b = [], []
    for tau in [0.3, 0.7]:
        interpolated = tau * train_fine[:len(gen_views)] + (1 - tau) * gen_views
        combined_a.append(train_fine[:len(gen_views)])
        combined_b.append(interpolated)
    
    combined_a = np.vstack(combined_a)
    combined_b = np.vstack(combined_b)
    print(f"  Combined: {len(combined_a)} pairs (x2 tau levels)")
    
    # Train InfoNCE
    trainer = ContrastiveTrainer(d=train_fine.shape[1])
    best_f1 = 0.0
    for ep in range(epochs):
        loss = trainer.train_epoch(combined_a, combined_b, batch_size)
        if ep % 20 == 0:
            f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
            print(f"  Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
            if f1 > best_f1:
                best_f1 = f1
                trainer.save('saved_model_files/enc_synth_i1.pt')
    
    return {'encoder_path': 'saved_model_files/enc_synth_i1.pt',
            'best_test_f1': best_f1, 'method': 'conditional_ddpm+interpolation'}

# ============================================================
# Idea 2: Identity-Realization Disentanglement (VAE)
# ============================================================
class DisentangledVAE(nn.Module):
    def __init__(self, d=25, id_dim=32, style_dim=64):
        super().__init__()
        self.shared = nn.Sequential(
            nn.Linear(d, 128), nn.ReLU(),
            nn.Linear(128, 128), nn.ReLU()
        )
        self.id_mu = nn.Linear(128, id_dim)
        self.id_logvar = nn.Linear(128, id_dim)
        self.style_mu = nn.Linear(128, style_dim)
        self.style_logvar = nn.Linear(128, style_dim)
        self.decoder = nn.Sequential(
            nn.Linear(id_dim + style_dim, 128), nn.ReLU(),
            nn.Linear(128, 128), nn.ReLU(),
            nn.Linear(128, d)
        )
    
    def encode(self, x):
        h = self.shared(x)
        return self.id_mu(h), self.id_logvar(h), self.style_mu(h), self.style_logvar(h)
    
    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + eps * std
    
    def decode(self, z_id, z_style):
        return self.decoder(torch.cat([z_id, z_style], dim=-1))
    
    def forward(self, x):
        im, il, sm, sl = self.encode(x)
        z_id = self.reparameterize(im, il)
        z_style = self.reparameterize(sm, sl)
        recon = self.decode(z_id, z_style)
        return recon, im, il, sm, sl, z_id, z_style

def train_idea2_synth(train_fine, train_coarse, test_fine, test_coarse,
                       epochs=200, batch_size=256):
    """
    Idea 2: Identity-Realization Disentanglement
    - Train VAE on paired (fine, coarse) data
    - Same building → same identity, different LoD → different style
    - Generate new views by resampling style
    """
    print(f"Idea 2: Identity-Realization VAE ({len(train_fine)} pairs)")
    
    d = train_fine.shape[1]
    vae = DisentangledVAE(d=d).to(DEV)
    vae_opt = torch.optim.AdamW(vae.parameters(), lr=3e-4)
    
    print("  Training VAE...")
    N = len(train_fine)
    for ep in range(500):
        idx = np.random.permutation(N)[:batch_size]
        x1 = torch.tensor(train_fine[idx], dtype=torch.float32).to(DEV)
        x2 = torch.tensor(train_coarse[idx], dtype=torch.float32).to(DEV)
        
        recon1, im1, il1, sm1, sl1, zi1, zs1 = vae(x1)
        recon2, im2, il2, sm2, sl2, zi2, zs2 = vae(x2)
        
        recon_loss = F.mse_loss(recon1, x1) + F.mse_loss(recon2, x2)
        
        kl_loss = 0
        for mu, lv in [(im1, il1), (sm1, sl1), (im2, il2), (sm2, sl2)]:
            kl_loss += (-0.5 * (1 + lv - mu.pow(2) - lv.exp()).sum(-1)).mean()
        
        id_cons_loss = F.mse_loss(zi1, zi2)
        total_loss = recon_loss + 0.0001 * kl_loss + 0.05 * id_cons_loss
        
        vae_opt.zero_grad()
        total_loss.backward()
        torch.nn.utils.clip_grad_norm_(vae.parameters(), 1.0)
        vae_opt.step()
        
        if ep % 100 == 0:
            print(f"  VAE ep {ep}: recon={recon_loss:.4f}, kl={kl_loss:.4f}, id={id_cons_loss:.4f}")
    
    # Generate style-augmented views
    print("  Generating style-augmented views...")
    train_fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
    gen_views = []
    with torch.no_grad():
        for start in range(0, len(train_fine), batch_size):
            batch = train_fine_t[start:start+batch_size]
            _, im, _, _, _, _, _ = vae(batch)
            zi = vae.reparameterize(im, torch.zeros_like(im))
            for _ in range(3):
                zs = torch.randn(len(batch), 64).to(DEV) * 0.5
                gen_views.append(vae.decode(zi, zs).cpu().numpy())
    gen_views = np.vstack(gen_views)
    anchors = np.tile(train_fine, (3, 1))[:len(gen_views)]
    print(f"  Generated {len(gen_views)} style-augmented views")
    
    # Train InfoNCE
    trainer = ContrastiveTrainer(d=d)
    best_f1 = 0.0
    for ep in range(epochs):
        loss = trainer.train_epoch(anchors, gen_views, batch_size)
        if ep % 20 == 0:
            f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
            print(f"  Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
            if f1 > best_f1:
                best_f1 = f1
                trainer.save('saved_model_files/enc_synth_i2.pt')
    
    torch.save({'vae': vae.state_dict()}, 'saved_model_files/vae_synth.pt')
    return {'encoder_path': 'saved_model_files/enc_synth_i2.pt',
            'best_test_f1': best_f1, 'method': 'vae+style_sampling'}

# ============================================================
# Idea 3: Denoise-to-Sibling (Direct InfoNCE on cross-LoD pairs)
# ============================================================
def train_idea3_synth(train_fine, train_coarse, test_fine, test_coarse,
                       epochs=200, batch_size=256):
    """Train on (fine, coarse) cross-LoD pairs directly."""
    print(f"Idea 3 (Synth): Direct training on {len(train_fine)} cross-LoD pairs")
    trainer = ContrastiveTrainer()
    best_f1 = 0.0
    for ep in range(epochs):
        loss = trainer.train_epoch(train_fine, train_coarse, batch_size)
        if ep % 20 == 0:
            f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
            print(f"  Ep {ep}: loss={loss:.4f}, test F1={f1:.4f}")
            if f1 > best_f1:
                best_f1 = f1
                trainer.save('saved_model_files/enc_synth_i3.pt')
    return {'encoder_path': 'saved_model_files/enc_synth_i3.pt',
            'best_test_f1': best_f1}

# ============================================================
# Idea 3+: SDEdit augmentation (DDPM → siblings → contrastive)
# ============================================================
def train_idea3_ddpm_synth(train_fine, train_coarse, test_fine, test_coarse,
                            epochs=200, batch_size=256, t0=200):
    """Train DDPM on fine props, generate siblings, combine with cross-LoD pairs."""
    print(f"Idea 3+DDPM: SDEdit t0={t0}")
    bsd = min(batch_size, 256)
    
    ddpm = DDPM(d=train_fine.shape[1])
    all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV)
    N_all = all_props_t.shape[0]
    
    print("  Training DDPM...")
    for ep in range(300):
        perm = torch.randperm(N_all)
        ep_loss = 0
        n_batches = 0
        for start in range(0, N_all, bsd):
            batch = all_props_t[perm[start:start+bsd]]
            ep_loss += ddpm.train_step(batch)
            n_batches += 1
        if ep % 100 == 0:
            print(f"    DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
    
    print("  Generating SDEdit siblings...")
    fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
    sibs = []
    for start in range(0, len(train_fine), bsd):
        batch = fine_t[start:start+bsd]
        sib = ddpm.sdedit(batch, t0=t0)
        sibs.append(sib.cpu().numpy())
    sibs = np.vstack(sibs)
    
    combined_a = np.vstack([train_fine, train_fine[:len(sibs)]])
    combined_b = np.vstack([train_coarse, sibs])
    print(f"  Combined: {len(combined_a)} pairs ({len(train_fine)} cross-LoD + {len(sibs)} SDEdit)")
    
    trainer = ContrastiveTrainer()
    best_f1 = 0.0
    for ep in range(epochs):
        loss = trainer.train_epoch(combined_a, combined_b, batch_size)
        if ep % 20 == 0:
            f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
            print(f"  Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
            if f1 > best_f1:
                best_f1 = f1
                trainer.save(f'saved_model_files/enc_synth_i3p_t{t0}.pt')
    
    ddpm.save(f'saved_model_files/diff_synth.pt')
    return {'encoder_path': f'saved_model_files/enc_synth_i3p_t{t0}.pt',
            'best_test_f1': best_f1, 't0': t0}

# ============================================================
# Idea 4: Grammar Score Guard (DDPM score filter)
# ============================================================
def train_idea4_synth(train_fine, train_coarse, test_fine, test_coarse,
                       epochs=200, batch_size=256, t0=200, keep_frac=0.5):
    """
    Idea 4: Grammar Score Guard
    - Train DDPM → generate SDEdit siblings → score by DDPM → filter
    """
    print(f"Idea 4: Grammar Guard, t0={t0}, keep={keep_frac}")
    bsd = min(batch_size, 256)
    
    ddpm = DDPM(d=train_fine.shape[1])
    all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV)
    N_all = all_props_t.shape[0]
    
    print("  Training DDPM...")
    for ep in range(300):
        perm = torch.randperm(N_all)
        ep_loss = 0
        n_batches = 0
        for start in range(0, N_all, bsd):
            batch = all_props_t[perm[start:start+bsd]]
            ep_loss += ddpm.train_step(batch)
            n_batches += 1
        if ep % 100 == 0:
            print(f"    DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
    
    print("  Generating SDEdit siblings...")
    fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
    sibs = []
    for start in range(0, len(train_fine), bsd):
        batch = fine_t[start:start+bsd]
        sib = ddpm.sdedit(batch, t0=t0)
        sibs.append(sib.cpu().numpy())
    sibs = np.vstack(sibs)
    
    print("  Scoring siblings...")
    sibs_t = torch.tensor(sibs, dtype=torch.float32).to(DEV)
    scores = ddpm.score(sibs_t)  # (N, 5 time scales)
    mean_score = scores.mean(dim=-1).cpu().numpy()
    
    n_keep = int(len(mean_score) * keep_frac)
    keep_idx = np.argsort(mean_score)[:n_keep]
    print(f"  Kept {n_keep}/{len(mean_score)} (score {mean_score.min():.3f}-{mean_score.max():.3f})")
    
    filtered_origs = train_fine[keep_idx]
    filtered_sibs = sibs[keep_idx]
    
    trainer = ContrastiveTrainer()
    best_f1 = 0.0
    for ep in range(epochs):
        loss = trainer.train_epoch(filtered_origs, filtered_sibs, batch_size)
        if ep % 20 == 0:
            f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
            print(f"  Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
            if f1 > best_f1:
                best_f1 = f1
                trainer.save(f'saved_model_files/enc_synth_i4_t{t0}_k{keep_frac}.pt')
    
    return {'encoder_path': f'saved_model_files/enc_synth_i4_t{t0}_k{keep_frac}.pt',
            'best_test_f1': best_f1, 'n_kept': n_keep, 't0': t0, 'keep_frac': keep_frac}

# ============================================================
# Idea 5: Adversarial Hard-Positive
# ============================================================
def train_idea5_synth(train_fine, train_coarse, test_fine, test_coarse,
                       epochs=100, batch_size=256, rounds=3):
    """
    Idea 5: Adversarial Hard-Positive
    - Progressive rounds with increasing SDEdit difficulty (t0=100,200,300)
    """
    print(f"Idea 5: Adversarial Hard-Positive, rounds={rounds}")
    bsd = min(batch_size, 256)
    
    ddpm = DDPM(d=train_fine.shape[1])
    all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV)
    N_all = all_props_t.shape[0]
    
    print("  Training DDPM...")
    for ep in range(300):
        perm = torch.randperm(N_all)
        ep_loss = 0
        n_batches = 0
        for start in range(0, N_all, bsd):
            batch = all_props_t[perm[start:start+bsd]]
            ep_loss += ddpm.train_step(batch)
            n_batches += 1
        if ep % 100 == 0:
            print(f"    DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
    
    trainer = ContrastiveTrainer()
    best_f1_overall = 0.0
    best_round = 0
    
    for r in range(rounds):
        t0 = 100 + r * 100
        print(f"\n  --- Round {r+1}/{rounds} (t0={t0}) ---")
        
        fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
        sibs = []
        for start in range(0, len(train_fine), bsd):
            batch = fine_t[start:start+bsd]
            sib = ddpm.sdedit(batch, t0=t0)
            sibs.append(sib.cpu().numpy())
        sibs = np.vstack(sibs)
        
        for ep in range(epochs):
            loss = trainer.train_epoch(train_fine, sibs, batch_size)
            if ep % 20 == 0:
                f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
                print(f"    Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
                if f1 > best_f1_overall:
                    best_f1_overall = f1
                    best_round = r + 1
                    trainer.save('saved_model_files/enc_synth_i5.pt')
    
    return {'encoder_path': 'saved_model_files/enc_synth_i5.pt',
            'best_test_f1': best_f1_overall, 'best_round': best_round, 'rounds': rounds}

# ============================================================
# Idea 6: Cross-Building Transformation Transfer
# ============================================================
def train_idea6_synth(train_fine, train_coarse, test_fine, test_coarse,
                       epochs=200, batch_size=256, knn=5):
    """
    Idea 6: Cross-Building Transformation Transfer
    - Learn (fine→coarse) delta vectors from train pairs
    - For each train building, find k nearest neighbors' deltas → average
    - Apply averaged delta to create synthetic views
    """
    print(f"Idea 6: Cross-Building Transform, k={knn}")
    from sklearn.neighbors import NearestNeighbors
    
    deltas = train_coarse - train_fine  # (N_train, 25)
    print(f"  Delta stats: mean_norm={np.linalg.norm(deltas.mean(axis=0)):.3f}, std_norm={np.linalg.norm(deltas.std(axis=0)):.3f}")
    
    nn = NearestNeighbors(n_neighbors=min(knn+1, len(train_fine)), metric='cosine')
    nn.fit(train_fine)
    
    dist, idx = nn.kneighbors(train_fine)
    
    avg_deltas = np.zeros_like(train_fine)
    for i in range(len(train_fine)):
        neighbor_idx = idx[i][idx[i] != i][:knn]
        if len(neighbor_idx) > 0:
            avg_deltas[i] = deltas[neighbor_idx].mean(axis=0)
        else:
            avg_deltas[i] = deltas[i]
    
    synthetic_views = train_fine + avg_deltas
    print(f"  Generated {len(synthetic_views)} cross-building views")
    
    trainer = ContrastiveTrainer()
    best_f1 = 0.0
    for ep in range(epochs):
        loss = trainer.train_epoch(train_fine, synthetic_views, batch_size)
        if ep % 20 == 0:
            f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
            print(f"  Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
            if f1 > best_f1:
                best_f1 = f1
                trainer.save(f'saved_model_files/enc_synth_i6_k{knn}.pt')
    
    return {'encoder_path': f'saved_model_files/enc_synth_i6_k{knn}.pt',
            'best_test_f1': best_f1, 'k': knn}

# ============================================================
# Main
# ============================================================
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--idea', type=str, required=True,
                       choices=['1','2','3','3p','4','5','6'],
                       help='Which STER-GI idea to train')
    parser.add_argument('--epochs', type=int, default=200)
    parser.add_argument('--batch_size', type=int, default=256)
    parser.add_argument('--t0', type=int, default=200, help='t0 for SDEdit (Idea 3p,4)')
    parser.add_argument('--keep_frac', type=float, default=0.5, help='Keep fraction for Idea 4')
    parser.add_argument('--rounds', type=int, default=3, help='Adversarial rounds for Idea 5')
    parser.add_argument('--knn', type=int, default=5, help='k for Idea 6')
    parser.add_argument('--out', type=str, default='experiments/synth_train_results.json')
    args = parser.parse_args()
    
    os.makedirs('saved_model_files', exist_ok=True)
    os.makedirs('experiments', exist_ok=True)
    
    print("Loading and splitting data...")
    (train_fine, train_coarse), (test_fine, test_coarse, test_ids) = load_and_split_data()
    
    bl_f1 = baseline_f1(test_fine, test_coarse)
    print(f"\nCross-LoD Baseline F1: {bl_f1:.4f}")
    
    t0_time = time.time()
    
    if os.path.exists(args.out):
        result = json.load(open(args.out))
    else:
        result = {'baseline_f1': bl_f1}
    
    idea_map = {
        '1': lambda: train_idea1_synth(train_fine, train_coarse, test_fine, test_coarse,
                                        epochs=args.epochs, batch_size=args.batch_size),
        '2': lambda: train_idea2_synth(train_fine, train_coarse, test_fine, test_coarse,
                                        epochs=args.epochs, batch_size=args.batch_size),
        '3': lambda: train_idea3_synth(train_fine, train_coarse, test_fine, test_coarse,
                                        epochs=args.epochs, batch_size=args.batch_size),
        '3p': lambda: train_idea3_ddpm_synth(train_fine, train_coarse, test_fine, test_coarse,
                                            epochs=args.epochs, batch_size=args.batch_size, t0=args.t0),
        '4': lambda: train_idea4_synth(train_fine, train_coarse, test_fine, test_coarse,
                                        epochs=args.epochs, batch_size=args.batch_size,
                                        t0=args.t0, keep_frac=args.keep_frac),
        '5': lambda: train_idea5_synth(train_fine, train_coarse, test_fine, test_coarse,
                                        epochs=args.epochs, batch_size=args.batch_size, rounds=args.rounds),
        '6': lambda: train_idea6_synth(train_fine, train_coarse, test_fine, test_coarse,
                                        epochs=args.epochs, batch_size=args.batch_size, knn=args.knn),
    }
    
    idea_key = f'idea{args.idea}'
    res = idea_map[args.idea]()
    result[idea_key] = res
    
    delta = res['best_test_f1'] - result.get('baseline_f1', bl_f1)
    result[idea_key]['delta'] = round(delta, 6)
    print(f"\nIdea {args.idea}: Best F1={res['best_test_f1']:.4f} (Δ={delta:+.4f})")
    
    result['total_time'] = round(time.time() - t0_time, 1)
    json.dump(result, open(args.out, 'w'), indent=2)
    print(f"Results saved to {args.out}")
    print(f"Total time: {result['total_time']:.1f}s")