File size: 24,607 Bytes
3fff97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63fcb7e
3fff97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

Embedding Space Evaluation β€” Base vs All Fine-tuned ProtT5 XL Models.



Loads the base model + all fine-tuned variants (Here Just: ContraMLM) and produces exactly three publication-quality plots:



  Plot 1 β€” 2Γ—2 t-SNE grid, one panel per model, coloured by PhrogCat.

  Plot 2 β€” 1Γ—3 scatter of pairwise L2 distances (base x-axis, fine-tuned

            y-axis) for the same ~N_PAIRS protein pairs across all subplots.

  Plot 3 β€” Same as Plot 2 but using cosine similarity.

"""

import os
import sys
import json
import glob
import re
import argparse
from itertools import combinations
from typing import Any, Dict, List

import torch
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
from transformers import T5Tokenizer, T5ForConditionalGeneration
from peft import PeftModel

import warnings
warnings.filterwarnings("ignore")

# ============================================================================
# CONFIGURATION
# ============================================================================


VERSIONS: List[str] = ["ContraMLM_v1_1"]
ALL_MODEL_LABELS: List[str] = ["base"] + VERSIONS

DEFAULT_BASE_MODEL_NAME = "Rostlab/prot_t5_xl_uniref50"
DEFAULT_DATA_PATH       = "./data/envhog_phrog2/envhog_test_final_no_leakage.csv"
DEFAULT_MAX_LENGTH      = 512
DEFAULT_SAMPLE_SIZE     = 5000
DEFAULT_BATCH_SIZE      = 2
DEFAULT_RANDOM_STATE    = 42
DEFAULT_N_PAIRS         = 150   # protein pairs used in scatter plots 2 & 3


def parse_args():
    parser = argparse.ArgumentParser(
        description="Multi-model embedding space evaluation for ProtT5 XL"
    )
    parser.add_argument("--base-model",      type=str, default=DEFAULT_BASE_MODEL_NAME)
    parser.add_argument("--data-path",       type=str, default=DEFAULT_DATA_PATH)
    parser.add_argument("--output-dir",      type=str, default="./runs/evaluation_results_EmbeddingSpace")
    parser.add_argument("--max-length",      type=int, default=DEFAULT_MAX_LENGTH)
    parser.add_argument("--sample-size",     type=int, default=DEFAULT_SAMPLE_SIZE)
    parser.add_argument("--batch-size",      type=int, default=DEFAULT_BATCH_SIZE)
    parser.add_argument("--random-state",    type=int, default=DEFAULT_RANDOM_STATE)
    parser.add_argument(
        "--n-pairs",
        type=int,
        default=DEFAULT_N_PAIRS,
        help="Number of protein pairs for L2/cosine scatter plots (100–200 recommended)",
    )
    return parser.parse_args()


args = parse_args()

BASE_MODEL_NAME = args.base_model
DATA_PATH       = args.data_path
OUTPUT_DIR      = args.output_dir
IMAGES_DIR      = os.path.join(OUTPUT_DIR, "images")
TEXT_DIR        = os.path.join(OUTPUT_DIR, "text")
MAX_LENGTH      = args.max_length
SAMPLE_SIZE     = args.sample_size
BATCH_SIZE      = args.batch_size
RANDOM_STATE    = args.random_state
N_PAIRS_TARGET  = max(2, args.n_pairs)

os.makedirs(OUTPUT_DIR, exist_ok=True)
os.makedirs(IMAGES_DIR, exist_ok=True)
os.makedirs(TEXT_DIR,   exist_ok=True)


# ============================================================================
# LOGGING
# ============================================================================

class Tee:
    def __init__(self, *streams):
        self.streams = streams
    def write(self, data):
        for s in self.streams:
            s.write(data)
            s.flush()
    def flush(self):
        for s in self.streams:
            s.flush()


run_log_path = os.path.join(TEXT_DIR, "run_log.txt")
log_file     = open(run_log_path, "w", encoding="utf-8")
sys.stdout   = Tee(sys.__stdout__, log_file)
sys.stderr   = Tee(sys.__stderr__, log_file)

print("=" * 80)
print("MULTI-MODEL EMBEDDING SPACE EVALUATION")
print("=" * 80)
print(f"\nBase model  : {BASE_MODEL_NAME}")
print(f"Versions    : {VERSIONS}")
print(f"Data        : {DATA_PATH}")
print(f"Sample size : {SAMPLE_SIZE}")
print(f"N pairs     : {N_PAIRS_TARGET}")
print(f"Output      : {OUTPUT_DIR}")

# ============================================================================
# DEVICE
# ============================================================================

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"\nDevice: {device}")
if torch.cuda.is_available():
    print(f"GPU   : {torch.cuda.get_device_name(0)}")

# ============================================================================
# LOAD DATA
# ============================================================================

print("\n" + "=" * 80)
print("LOADING DATA")
print("=" * 80)

df = pd.read_csv(DATA_PATH)
print(f"Total proteins: {len(df)}")

if SAMPLE_SIZE > 0 and len(df) > SAMPLE_SIZE:
    df_sample = df.sample(n=SAMPLE_SIZE, random_state=RANDOM_STATE).reset_index(drop=True)
    print(f"Sampled {SAMPLE_SIZE} proteins")
else:
    df_sample = df.reset_index(drop=True)
    print(f"Using all {len(df)} proteins")

sequences   = df_sample["sequence"].tolist()
lengths     = df_sample["length"].tolist()
protein_ids = df_sample["id"].tolist()

# PhrogCat β€” used as colour label in t-SNE
if "PhrogCat" in df_sample.columns:
    phrog_cats = df_sample["PhrogCat"].fillna("unknown").tolist()
else:
    print("WARNING: 'PhrogCat' column not found β€” using 'unknown' for all proteins")
    phrog_cats = ["unknown"] * len(df_sample)


def prepare_t5_seq(seq: str) -> str:
    return " ".join(list(str(seq).replace(" ", "")))


sequences = [prepare_t5_seq(s) for s in sequences]

# ============================================================================
# TOKENIZER
# ============================================================================

print("\n" + "=" * 80)
print("LOADING TOKENIZER")
print("=" * 80)

tokenizer = T5Tokenizer.from_pretrained(
    BASE_MODEL_NAME, do_lower_case=False, legacy=True
)
print(f"Tokenizer loaded: {BASE_MODEL_NAME}")

# ============================================================================
# HELPERS
# ============================================================================

def get_encoder(model):
    """Return the encoder module regardless of wrapper type."""
    if hasattr(model, "encoder"):
        return model.encoder
    fn = getattr(model, "get_encoder", None)
    if callable(fn):
        return fn()
    for attr in ("base_model", "model"):
        inner = getattr(model, attr, None)
        if inner is not None:
            if hasattr(inner, "encoder"):
                return inner.encoder
            fn2 = getattr(inner, "get_encoder", None)
            if callable(fn2):
                return fn2()
    return model


def select_best_adapter_dir(version: str) -> str:
    """Return the first valid (NaN/Inf-free) adapter directory for *version*."""
    finetuned_path  = f"./runs/protrans_XL_Full_lora_envhog_{version}/lora_adapters"
    checkpoint_root = f"./runs/protrans_XL_Full_lora_envhog_{version}"

    candidates = []
    if os.path.isdir(finetuned_path):
        candidates.append(finetuned_path)

    ckpt_paths = sorted(
        glob.glob(os.path.join(checkpoint_root, "checkpoint-*")),
        key=lambda p: int(re.search(r"checkpoint-(\d+)", p).group(1))
        if re.search(r"checkpoint-(\d+)", p) else -1,
        reverse=True,
    )
    for cp in ckpt_paths:
        if os.path.isdir(cp):
            candidates.append(cp)

    def _resolve(candidate):
        for subdir in (candidate, os.path.join(candidate, "lora_adapters")):
            if (os.path.isfile(os.path.join(subdir, "adapter_model.safetensors"))
                    or os.path.isfile(os.path.join(subdir, "adapter_model.bin"))):
                return subdir
        return None

    for candidate in candidates:
        resolved = _resolve(candidate)
        if resolved is None:
            continue
        safe = os.path.join(resolved, "adapter_model.safetensors")
        bin_ = os.path.join(resolved, "adapter_model.bin")
        if os.path.isfile(safe):
            from safetensors.torch import load_file
            state_dict = load_file(safe, device="cpu")
        else:
            state_dict = torch.load(bin_, map_location="cpu")

        has_nan = any(torch.isnan(v).any().item() for v in state_dict.values())
        has_inf = any(torch.isinf(v).any().item() for v in state_dict.values())
        if not has_nan and not has_inf:
            print(f"  [{version}] Using adapter: {resolved}")
            return resolved

    raise RuntimeError(
        f"No valid (NaN/Inf-free) adapter found for version '{version}'. "
        f"Searched: {candidates}"
    )


def get_embeddings(model, seqs: List[str], batch_size: int = 16) -> np.ndarray:
    """Mean-pooled encoder embeddings for a list of pre-formatted sequences."""
    encoder = get_encoder(model)
    encoder.eval()
    all_embs = []

    with torch.no_grad():
        for i in range(0, len(seqs), batch_size):
            batch = seqs[i : i + batch_size]
            inputs = tokenizer(
                batch,
                return_tensors="pt",
                padding=True,
                truncation=True,
                max_length=MAX_LENGTH,
            )
            inputs = {k: v.to(device) for k, v in inputs.items()}
            out    = encoder(
                input_ids=inputs["input_ids"],
                attention_mask=inputs["attention_mask"],
            )
            hidden = out.last_hidden_state
            mask   = inputs["attention_mask"].unsqueeze(-1).to(hidden.dtype)
            pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1.0)
            all_embs.append(pooled.float().cpu().numpy())

            if (i // batch_size) % 10 == 0:
                print(f"  {i}/{len(seqs)} sequences processed...")

    return np.vstack(all_embs)


# ============================================================================
# LOAD BASE MODEL
# ============================================================================

print("\n" + "=" * 80)
print("LOADING BASE MODEL")
print("=" * 80)

model_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

base_model = T5ForConditionalGeneration.from_pretrained(
    BASE_MODEL_NAME, torch_dtype=model_dtype, low_cpu_mem_usage=True
)
base_model = base_model.to(device)
base_model.eval()
print("Base model loaded")

# ============================================================================
# GENERATE BASE EMBEDDINGS
# ============================================================================

print("\n" + "=" * 80)
print("GENERATING BASE EMBEDDINGS")
print("=" * 80)

base_embeddings = get_embeddings(base_model, sequences, BATCH_SIZE)
print(f"Base embeddings shape: {base_embeddings.shape}")

# Free base model GPU memory before loading fine-tuned models one-by-one
# (keep the numpy array β€” it is small)
del base_model
torch.cuda.empty_cache() if torch.cuda.is_available() else None

# ============================================================================
# LOAD FINE-TUNED MODELS AND GENERATE EMBEDDINGS
# ============================================================================

# Stores: { version_name: np.ndarray }
ft_embeddings: Dict[str, np.ndarray] = {}

for version in VERSIONS:
    print("\n" + "=" * 80)
    print(f"LOADING FINE-TUNED MODEL: {version}")
    print("=" * 80)

    adapter_dir = select_best_adapter_dir(version)

    ft_model = T5ForConditionalGeneration.from_pretrained(
        BASE_MODEL_NAME, torch_dtype=model_dtype, low_cpu_mem_usage=True
    )
    ft_model = PeftModel.from_pretrained(ft_model, adapter_dir)

    merge_fn = getattr(ft_model, "merge_and_unload", None)
    if callable(merge_fn):
        ft_model = merge_fn()
        print("  LoRA adapters merged")

    ft_model = ft_model.to(device)
    ft_model.eval()

    print(f"  Generating embeddings for {version}...")
    ft_embeddings[version] = get_embeddings(ft_model, sequences, BATCH_SIZE)
    print(f"  {version} embeddings shape: {ft_embeddings[version].shape}")

    del ft_model
    torch.cuda.empty_cache() if torch.cuda.is_available() else None

# ============================================================================
# SHARED t-SNE COLOUR MAP (PhrogCat)
# ============================================================================

print("\n" + "=" * 80)
print("PREPARING t-SNE COLOUR MAP")
print("=" * 80)

unique_cats   = sorted(set(phrog_cats))
n_cats        = len(unique_cats)
cmap_name     = "tab20" if n_cats > 10 else "tab10"
cmap          = plt.get_cmap(cmap_name, n_cats)
cat_to_idx    = {cat: i for i, cat in enumerate(unique_cats)}
colour_values = np.array([cat_to_idx[c] for c in phrog_cats])

print(f"Unique PhrogCat categories: {n_cats}")
print(f"Categories: {unique_cats}")

# ============================================================================
# t-SNE FOR ALL FOUR MODELS
# ============================================================================

print("\n" + "=" * 80)
print("RUNNING t-SNE (4 MODELS)")
print("=" * 80)

n_tsne     = min(2000, len(sequences))
rng_tsne   = np.random.default_rng(RANDOM_STATE)
tsne_idx   = rng_tsne.choice(len(sequences), n_tsne, replace=False)
perplexity = 30 if n_tsne > 30 else max(5, n_tsne - 1)

# Collect all embedding matrices for the 4 models
all_embeddings_ordered: Dict[str, np.ndarray] = {
    "base": base_embeddings,
    **ft_embeddings,
}

tsne_results: Dict[str, np.ndarray] = {}
tsne_silhouette: Dict[str, float] = {}

for label, emb in all_embeddings_ordered.items():
    print(f"  PCA β†’ t-SNE for [{label}]...")
    pca   = PCA(n_components=50, random_state=RANDOM_STATE)
    emb_pca = pca.fit_transform(emb)
    tsne  = TSNE(n_components=2, random_state=RANDOM_STATE, perplexity=perplexity)
    tsne_results[label] = tsne.fit_transform(emb_pca[tsne_idx])

    # Silhouette index on the 2D t-SNE map using PhrogCat categories as labels.
    labels_tsne = np.array(phrog_cats, dtype=object)[tsne_idx]
    n_label_values = len(set(labels_tsne.tolist()))
    if 2 <= n_label_values < len(labels_tsne):
        try:
            tsne_silhouette[label] = float(silhouette_score(tsne_results[label], labels_tsne))
        except Exception:
            tsne_silhouette[label] = float("nan")
    else:
        tsne_silhouette[label] = float("nan")

    print(f"    Done.")
    if np.isnan(tsne_silhouette[label]):
        print("    Silhouette(PhrogCat): n/a")
    else:
        print(f"    Silhouette(PhrogCat): {tsne_silhouette[label]:.4f}")

colours_tsne = colour_values[tsne_idx]

# ============================================================================
# SHARED PROTEIN PAIRS FOR SCATTER PLOTS
# ============================================================================

print("\n" + "=" * 80)
print("BUILDING SHARED PROTEIN PAIRS")
print("=" * 80)

# We need N_PAIRS_TARGET pairs from a pool of proteins.
# Minimum proteins needed so combinations >= N_PAIRS_TARGET:
#   n*(n-1)/2 >= N_PAIRS_TARGET  β†’  n β‰ˆ ceil((1 + sqrt(1+8k))/2)
import math
n_prot_needed = math.ceil((1 + math.sqrt(1 + 8 * N_PAIRS_TARGET)) / 2)
n_prot_needed = max(n_prot_needed, 2)
n_prot_needed = min(n_prot_needed, len(sequences))

rng_pairs     = np.random.default_rng(RANDOM_STATE + 1)
pair_indices  = rng_pairs.choice(len(sequences), n_prot_needed, replace=False)
pair_indices  = pair_indices.tolist()

all_pairs     = list(combinations(pair_indices, 2))

# Randomly subsample to exactly N_PAIRS_TARGET pairs if we have more
if len(all_pairs) > N_PAIRS_TARGET:
    rng_sub   = np.random.default_rng(RANDOM_STATE + 2)
    chosen    = rng_sub.choice(len(all_pairs), N_PAIRS_TARGET, replace=False)
    all_pairs = [all_pairs[i] for i in chosen]

n_pairs_actual = len(all_pairs)
print(f"Protein pool size : {n_prot_needed}")
print(f"Pairs generated   : {n_pairs_actual}")


def pairwise_l2(emb: np.ndarray, pairs: list) -> np.ndarray:
    return np.array([
        np.linalg.norm(emb[a] - emb[b])
        for a, b in pairs
    ])


def pairwise_cosine(emb: np.ndarray, pairs: list, eps: float = 1e-12) -> np.ndarray:
    sims = []
    for a, b in pairs:
        va, vb = emb[a], emb[b]
        denom  = np.linalg.norm(va) * np.linalg.norm(vb)
        sim    = np.dot(va, vb) / max(denom, eps)
        sims.append(float(np.clip(sim, -1.0, 1.0)))
    return np.array(sims)


# Compute for base
base_pair_l2  = pairwise_l2(base_embeddings,  all_pairs)
base_pair_cos = pairwise_cosine(base_embeddings, all_pairs)

# Compute for each fine-tuned version
ft_pair_l2:  Dict[str, np.ndarray] = {}
ft_pair_cos: Dict[str, np.ndarray] = {}

for version in VERSIONS:
    emb = ft_embeddings[version]
    ft_pair_l2[version]  = pairwise_l2(emb,  all_pairs)
    ft_pair_cos[version] = pairwise_cosine(emb, all_pairs)

# ============================================================================
# PLOT 1 β€” 2Γ—2 t-SNE GRID  (coloured by PhrogCat)
# ============================================================================

print("\n" + "=" * 80)
print("PLOT 1: 2Γ—2 t-SNE GRID")
print("=" * 80)

fig, axes = plt.subplots(2, 2, figsize=(16, 14))
axes_flat  = axes.flatten()

panel_order = ["base", "ContraMLM_v1_0", "Default_v2_1", "MLP_v0"]
panel_titles = {
    "base":           "Base Model",
    "ContraMLM_v1_0": "ContraMLM v1.0",
    "Default_v2_1":   "Default v2.1",
    "MLP_v0":         "MLP v0",
}

for ax, label in zip(axes_flat, panel_order):
    xy   = tsne_results[label]
    sc   = ax.scatter(
        xy[:, 0], xy[:, 1],
        c=colours_tsne,
        cmap=cmap_name,
        vmin=0, vmax=n_cats - 1,
        alpha=0.65,
        s=8,
        linewidths=0,
    )
    sil_txt = (
        f"Silhouette(PhrogCat): {tsne_silhouette[label]:.3f}"
        if not np.isnan(tsne_silhouette[label])
        else "Silhouette(PhrogCat): n/a"
    )
    ax.set_title(
        f"{panel_titles[label]}\n{sil_txt}",
        fontsize=14,
        fontweight="bold",
        pad=8,
    )
    ax.set_xlabel("t-SNE 1", fontsize=10)
    ax.set_ylabel("t-SNE 2", fontsize=10)
    ax.tick_params(labelsize=8)

# Shared legend for PhrogCat categories
legend_handles = [
    mpatches.Patch(color=cmap(cat_to_idx[cat] / max(n_cats - 1, 1)), label=cat)
    for cat in unique_cats
]
fig.legend(
    handles=legend_handles,
    title="PhrogCat",
    title_fontsize=14,
    fontsize=12,
    loc="lower center",
    ncol=min(n_cats, 6),
    bbox_to_anchor=(0.5, -0.02),
    frameon=True,
)

fig.suptitle(
    f"t-SNE Embedding Space β€” Base vs Fine-tuned Models\n"
    f"(n={n_tsne} proteins, coloured by PhrogCat)",
    fontsize=15,
    fontweight="bold",
    y=1.01,
)
plt.tight_layout()

plot1_path = os.path.join(IMAGES_DIR, "plot1_tsne_4models.png")
fig.savefig(plot1_path, dpi=300, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {plot1_path}")

# ============================================================================
# PLOT 2 β€” PAIRWISE L2 SCATTER (base x-axis, fine-tuned y-axis)
# ============================================================================

print("\n" + "=" * 80)
print("PLOT 2: PAIRWISE L2 DISTANCE SCATTER")
print("=" * 80)

fig, axes = plt.subplots(1, 3, figsize=(18, 6))

version_titles = {
    "ContraMLM_v1_0": "ContraMLM v1.0",
    "Default_v2_1":   "Default v2.1",
    "MLP_v0":         "MLP v0",
}

for ax, version in zip(axes, VERSIONS):
    x = base_pair_l2
    y = ft_pair_l2[version]

    # Diagonal reference line
    lim_min = min(x.min(), y.min()) * 0.98
    lim_max = max(x.max(), y.max()) * 1.02
    ax.plot([lim_min, lim_max], [lim_min, lim_max],
            color="gray", linestyle="--", linewidth=1.0, alpha=0.7, label="y = x")

    ax.scatter(x, y, alpha=0.55, s=20, color="#2E86AB", linewidths=0)

    # Pearson r annotation
    r = float(np.corrcoef(x, y)[0, 1])
    ax.text(
        0.05, 0.93, f"r = {r:.3f}",
        transform=ax.transAxes,
        fontsize=10,
        verticalalignment="top",
        bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.7),
    )

    ax.set_xlim(lim_min, lim_max)
    ax.set_ylim(lim_min, lim_max)
    ax.set_xlabel("Base model β€” L2 distance", fontsize=11)
    ax.set_ylabel(f"{version_titles[version]} β€” L2 distance", fontsize=11)
    ax.set_title(f"L2: Base vs {version_titles[version]}", fontsize=13, fontweight="bold")
    ax.set_aspect("equal", adjustable="box")
    ax.grid(True, alpha=0.25)
    ax.legend(fontsize=9)

fig.suptitle(
    f"Pairwise L2 Distance: Base vs Fine-tuned Models\n"
    f"({n_pairs_actual} protein pairs, same pairs across all subplots)",
    fontsize=14,
    fontweight="bold",
)
plt.tight_layout()

plot2_path = os.path.join(IMAGES_DIR, "plot2_pairwise_l2_scatter.png")
fig.savefig(plot2_path, dpi=300, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {plot2_path}")

# ============================================================================
# PLOT 3 β€” PAIRWISE COSINE SIMILARITY SCATTER
# ============================================================================

print("\n" + "=" * 80)
print("PLOT 3: PAIRWISE COSINE SIMILARITY SCATTER")
print("=" * 80)

fig, axes = plt.subplots(1, 3, figsize=(18, 6))

for ax, version in zip(axes, VERSIONS):
    x = base_pair_cos
    y = ft_pair_cos[version]

    lim_min = min(x.min(), y.min()) - 0.02
    lim_max = max(x.max(), y.max()) + 0.02
    ax.plot([lim_min, lim_max], [lim_min, lim_max],
            color="gray", linestyle="--", linewidth=1.0, alpha=0.7, label="y = x")

    ax.scatter(x, y, alpha=0.55, s=20, color="#E84855", linewidths=0)

    r = float(np.corrcoef(x, y)[0, 1])
    ax.text(
        0.05, 0.93, f"r = {r:.3f}",
        transform=ax.transAxes,
        fontsize=10,
        verticalalignment="top",
        bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.7),
    )

    ax.set_xlim(lim_min, lim_max)
    ax.set_ylim(lim_min, lim_max)
    ax.set_xlabel("Base model β€” cosine similarity", fontsize=11)
    ax.set_ylabel(f"{version_titles[version]} β€” cosine similarity", fontsize=11)
    ax.set_title(f"Cosine: Base vs {version_titles[version]}", fontsize=13, fontweight="bold")
    ax.set_aspect("equal", adjustable="box")
    ax.grid(True, alpha=0.25)
    ax.legend(fontsize=9)

fig.suptitle(
    f"Pairwise Cosine Similarity: Base vs Fine-tuned Models\n"
    f"({n_pairs_actual} protein pairs, same pairs across all subplots)",
    fontsize=14,
    fontweight="bold",
)
plt.tight_layout()

plot3_path = os.path.join(IMAGES_DIR, "plot3_pairwise_cosine_scatter.png")
fig.savefig(plot3_path, dpi=300, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {plot3_path}")

# ============================================================================
# SAVE PAIR DATA AS CSV (reproducibility)
# ============================================================================

pair_records = []
for k, (a, b) in enumerate(all_pairs):
    row = {
        "pair_index":    k,
        "protein_id_a":  protein_ids[a],
        "protein_id_b":  protein_ids[b],
        "base_l2":       float(base_pair_l2[k]),
        "base_cosine":   float(base_pair_cos[k]),
    }
    for version in VERSIONS:
        row[f"{version}_l2"]     = float(ft_pair_l2[version][k])
        row[f"{version}_cosine"] = float(ft_pair_cos[version][k])
    pair_records.append(row)

pairs_csv_path = os.path.join(TEXT_DIR, "pairwise_distances_all_models.csv")
pd.DataFrame(pair_records).to_csv(pairs_csv_path, index=False)
print(f"\nPair data saved: {pairs_csv_path}")

# ============================================================================
# DONE
# ============================================================================

print("\n" + "=" * 80)
print("EVALUATION COMPLETE")
print("=" * 80)
print(f"\nOutputs written to : {OUTPUT_DIR}")
print(f"  Plot 1 (t-SNE)   : {plot1_path}")
print(f"  Plot 2 (L2)      : {plot2_path}")
print(f"  Plot 3 (cosine)  : {plot3_path}")
print(f"  Pair CSV         : {pairs_csv_path}")
print(f"  Run log          : {run_log_path}")