File size: 32,890 Bytes
e6a6e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
779
#!/usr/bin/env python3
"""Score trained PIMT checkpoints on the engine-independent frozen probes.

The paper's static physics-null rests on a MODEL-FREE probe: 4 physicochemical
descriptors appended to frozen (Morgan/POM) embeddings, scored via a Ridge or
LogisticRegression linear probe. A review panel demands that the TRAINED FiLM
on/off arms (pimt_ab_openpom_256 = physics-on-trained, pimt_physoff_openpom_256
= physics-off-trained) be scored on the SAME three engine-independent frozen
probes from tab:main under MATCHED conditioning.

This script does exactly that. For each checkpoint it evaluates:

  1. Substantivity: Spearman rho between the trained model's substantivity-head
     output (a scalar per molecule) and GoodScents measured substantivity hours,
     on the SAME molecule set used by the model-free probe. The substantivity
     head was trained on log10(Poucher coefficients) — a different absolute scale
     than GoodScents hours — so only the rank ordering is comparable; Spearman
     rho is scale-invariant and is the exact metric the frozen probe reports.

  2. Odor threshold: NOT APPLICABLE. The trained PIMT model has no odor-threshold
     head (it was never trained against ODT targets). Reporting not_applicable
     rather than fabricating a head.

  3. Descriptor macro-F1: The frozen probe trains a LogisticRegression classifier
     on frozen embeddings to predict the dominant descriptor letter (25 classes)
     and reports 5-fold macro-F1. The trained model predicts a continuous 138-dim
     descriptor profile (sigmoid activations, mean of top/mid/base tiers). We
     binarize the predicted profile at the benchmark's own threshold (0.5), map
     each active Pyrfume tag onto its descriptor letter via the v11 crosswalk,
     and predict the dominant letter for each molecule. The macro-F1 is computed
     against the benchmark's per-molecule dominant letter using the SAME
     CAS-grouped 5-fold split, so the denominator (classes, folds) matches.

Single-molecule conditioning convention (matching the training corpus):
  * Each molecule is evaluated as a control record — single molecule at 15%
    concentrate in ethanol — so the evaporation engine has the same solvent
    envelope the model was trained on.
  * Physics-ON: run the Dortmund-UNIFAC BDF evaporation engine on that control
    formula (following engine_only_baseline.py's verifier pattern), extract the
    per-molecule physics trajectory (x_liquid, log10 OAV), and feed it to the
    model.
  * Physics-OFF: zero the physics tensor entirely.

Each checkpoint is evaluated under BOTH conditioning modes (on and off):
  * openpom arm (physics-on-trained) evaluated physics-ON (training-consistent)
    and physics-OFF (sensitivity).
  * physoff arm (physics-off-trained) evaluated physics-OFF (training-consistent)
    and physics-ON (sensitivity).

Output JSON per (checkpoint, conditioning):
  {arm, checkpoint sha256, seed, conditioning: on|off,
   substantivity: {rho, n},
   descriptors: {macro_f1, n, protocol_note},
   threshold: {not_applicable: "..."}}

Usage:
  PYTHONPATH=src .venv/bin/python scripts/evaluate_trained_frozen_probes.py \
      --checkpoints pimt_ab_openpom_256_seed1.pt pimt_physoff_openpom_256_seed1.pt \
      --seeds 1 \
      --output artifacts/trained_frozen_probes/ \
      [--max-molecules 30]   # smoke test subset
"""
from __future__ import annotations

import argparse
import hashlib
import json
import logging
import re
import sys
from pathlib import Path
from typing import Any

import numpy as np
import torch

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from pino.embeddings import OlfactoryEmbeddingEngine
from pino.heads import PIMTHeads
from pino.pimt_model import PhysicsInformedMixtureTransformer

logger = logging.getLogger("evaluate_trained_frozen_probes")

# ---------------------------------------------------------------------------
# Descriptor letter crosswalk — must match run_representation_ablation.py.
# Maps single-letter descriptor codes (from descriptor_distributions_v11.jsonl)
# to readable labels. The v11 distribution keys ARE these letters.
# ---------------------------------------------------------------------------
# The pyrfume_vocabulary.json is 138 entries. We need to map each Pyrfume tag
# word onto a letter class so the trained model's predicted 138-dim profile can
# be projected onto the same label space as the frozen probe's target.

# Build a mapping from Pyrfume tag index -> descriptor letter.
# The descriptor_distributions_v11.jsonl assigns a distribution over letters
# (A-Z, skipping O) to each CAS. We need the reverse: which letter does each
# Pyrfume tag word correspond to? This is not directly stored. However, the
# frozen probe predicts the DOMINANT letter per molecule. So for the trained
# model, we aggregate the predicted 138-dim profile by letter group using the
# known semantic groupings (CLASS_LETTER_MAP from run_representation_ablation.py
# gives letter -> readable name; we need readable name -> letter).

# Letter -> readable name (from run_representation_ablation.py CLASS_LETTER_MAP)
LETTER_TO_NAME = {
    "A": "citrus", "B": "fruity", "C": "green", "D": "floral", "E": "spicy",
    "F": "woody", "G": "herbaceous", "H": "earthy", "I": "musk", "J": "amber",
    "K": "leathery", "L": "smoky", "M": "sweet", "N": "lactonic", "O": "marine",
    "P": "minty", "Q": "camphoraceous", "R": "balsamic", "S": "sulfurous",
    "T": "animalic", "U": "metallic", "V": "waxy", "W": "aldehydic",
    "X": "solvent", "Y": "powdery", "Z": "carrier",
}

# Build name -> letter (reverse map). Multiple names can map to the same letter;
# we also add common Pyrfume tag synonyms that map onto the same letter.
LETTER_SYNONYMS: dict[str, list[str]] = {
    "A": ["citrus", "lemon", "orange", "grapefruit", "bergamot", "tangerine", "mandarin", "lime"],
    "B": ["fruity", "apple", "banana", "peach", "pear", "berry", "raspberry", "pineapple", "tropical"],
    "C": ["green", "grassy", "leafy", "cucumber", "vegetable", "hay", "weedy", "galbanum"],
    "D": ["floral", "rose", "jasmin", "jasmine", "muguet", "violet", "hyacinth", "lily", "geranium", "lavender", "lilac", "carnation", "ionone"],
    "E": ["spicy", "cinnamon", "clove", "pepper", "nutmeg", "cardamom", "ginger", "anisic", "caraway"],
    "F": ["woody", "cedar", "pine", "sandalwood", "vetiver", "patchouli", "mossy"],
    "G": ["herbaceous", "herbal", "chamomile", "thyme", "sage", "mint", "minty", "aromatic"],
    "H": ["earthy", "mushroom", "beet", "soil", "humus"],
    "I": ["musk", "musky"],
    "J": ["amber", "ambery"],
    "K": ["leathery", "leather"],
    "L": ["smoky", "smoke", "tobacco", "tar", "phenolic"],
    "M": ["sweet", "honey", "caramellic", "caramel", "chocolate", "cocoa", "vanilla", "coumarinic", "lactonic", "creamy", "balsamic"],
    "N": ["lactonic", "milky"],
    "P": ["minty", "mint", "mentholic", "camphoreous", "camphor"],
    "Q": ["camphoraceous", "camphoreous"],
    "R": ["balsamic", "resinous", "benzoin", "styrax", "tolu"],
    "S": ["sulfurous", "sulfur", "alliaceous", "garlic", "onion", "meaty"],
    "T": ["animalic", "animal", "civet", "castoreum", "skunk"],
    "U": ["metallic", "metal"],
    "V": ["waxy", "wax"],
    "W": ["aldehydic", "aldehyde", "soapy", "clean", "powdery"],
    "X": ["solvent", "alcohol", "ethereal", "chemical"],
    "Y": ["powdery", "orris", "violet", "heliotrope"],
    "Z": ["carrier", "oily", "ozone", "fresh"],
}

# Build a flat word -> letter lookup (first occurrence wins for shared words).
WORD_TO_LETTER: dict[str, str] = {}
for _letter, _names in LETTER_SYNONYMS.items():
    for _n in _names:
        if _n not in WORD_TO_LETTER:
            WORD_TO_LETTER[_n] = _letter


def build_tag_to_letter_index(vocab: list[str]) -> dict[int, str]:
    """Map each Pyrfume tag index to its descriptor letter using the project's
    authoritative v8.2 odour-character crosswalk.

    Falls back to semantic substring matching for tags not directly in the
    crosswalk. Ambiguous tags (aromatic, floral, fresh, oily, powdery, sweet)
    are left unmapped per the crosswalk's ambiguity policy.
    """
    crosswalk_path = ROOT / "artifacts" / "odour_character_crosswalk_v8_2.json"
    d2c: dict[str, str] = {}
    ambiguous: set[str] = set()
    if crosswalk_path.exists():
        cw = json.loads(crosswalk_path.read_text())
        d2c = {k.lower(): v for k, v in cw.get("descriptor_to_class", {}).items()}
        ambiguous = set(cw.get("ambiguous_unmapped_descriptors", {}).keys())

    idx_to_letter: dict[int, str] = {}
    for i, tag in enumerate(vocab):
        tag_lower = tag.lower().strip()

        # Skip ambiguous tags per crosswalk policy
        if tag_lower in ambiguous:
            idx_to_letter[i] = ""
            continue

        # Direct match
        if tag_lower in d2c:
            idx_to_letter[i] = d2c[tag_lower]
            continue

        # Normalized match (remove spaces)
        normalized = tag_lower.replace(" ", "")
        norm_d2c = {k.replace(" ", ""): v for k, v in d2c.items()}
        if normalized in norm_d2c:
            idx_to_letter[i] = norm_d2c[normalized]
            continue

        # Substring match: does any crosswalk key appear in the tag?
        matched = None
        for cw_word, letter in d2c.items():
            if cw_word in tag_lower and cw_word not in ambiguous:
                matched = letter
                break
        idx_to_letter[i] = matched or ""
    return idx_to_letter


# ---------------------------------------------------------------------------
# Model loading (mirrors evaluate_frozen_benchmarks.py / evaluate_substantivity.py)
# ---------------------------------------------------------------------------

def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def load_model(ckpt_path: Path, objective_dim: int = 138):
    ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    sd = ckpt.get("model_state_dict", ckpt.get("model", {}))
    heads_sd = ckpt.get("heads_state_dict", {})
    hidden_dim, embedding_dim = sd["input_proj.weight"].shape
    state_dim = sd["gating.physics_scaler"].shape[0]
    num_layers = sum(1 for k in sd if k.endswith("self_attn.in_proj_weight"))
    num_heads = 8 if hidden_dim % 8 == 0 and hidden_dim >= 512 else 4
    model = PhysicsInformedMixtureTransformer(
        embedding_dim=int(embedding_dim), state_dim=int(state_dim),
        hidden_dim=int(hidden_dim), num_heads=num_heads,
        num_layers=max(num_layers, 1),
    )
    model.load_state_dict(sd, strict=False)
    model.eval()
    heads = PIMTHeads(hidden_dim=int(hidden_dim), objective_dim=objective_dim)
    if heads_sd:
        heads.load_state_dict(heads_sd, strict=False)
    heads.eval()
    dims = {"embedding_dim": int(embedding_dim), "state_dim": int(state_dim),
            "hidden_dim": int(hidden_dim), "num_layers": num_layers,
            "num_heads": num_heads}
    return model, heads, dims


# ---------------------------------------------------------------------------
# Physics conditioning: run the evaporation engine on a single-molecule control
# ---------------------------------------------------------------------------

def run_engine_for_molecule(cas: str, smiles: str) -> np.ndarray | None:
    """Run the UNIFAC evaporation engine on a single molecule at 15% in ethanol.

    Returns the physics trajectory (T, 2) = [x_liquid, log10(OAV)] per timestep
    for the target molecule, or None if the engine cannot solve this molecule.

    Follows the verifier pattern from engine_only_baseline.py and the
    15%-in-ethanol control convention from generate_empirical_bootstrap.py.
    """
    try:
        from pino.verifier import FragrancePipelineVerifier
    except Exception:
        return None

    # 15% concentrate in ethanol (matching control record convention)
    ethanol_cas = "64-17-5"
    formula = [
        {"cas": cas, "name": cas, "smiles": smiles, "weight_fraction": 0.15},
        {"cas": ethanol_cas, "name": "Ethanol", "weight_fraction": 0.85},
    ]
    try:
        verifier = FragrancePipelineVerifier()
        sim = verifier.run_sim(
            formula,
            duration_seconds=8 * 3600.0,
            interval_seconds=600.0,
            method="BDF",
            skip_ifra=True,
            skip_unresolved=True,
        )
    except Exception as exc:
        logger.debug("Engine failed for %s: %s", cas, exc)
        return None

    traj = sim.get("trajectory", [])
    if not traj:
        return None

    physics = []
    for rec in traj:
        x_liq = rec["x_liquid"].get(cas, 0.0)
        oav = rec["OAV"].get(cas, 0.0)
        physics.append([x_liq, np.log10(max(oav, 1e-10))])
    arr = np.array(physics, dtype=np.float32)
    if not np.isfinite(arr).all():
        return None
    return arr  # (T, 2)


def build_physics_tensor(
    engine_traj: np.ndarray | None,
    state_dim: int,
    conditioning: str,
) -> torch.Tensor:
    """Build a (1, T, 1, state_dim) physics tensor for a single molecule.

    conditioning='on': use the engine trajectory (padded/truncated to state_dim).
    conditioning='off': all zeros.
    """
    if conditioning == "off" or engine_traj is None:
        # Default T=1 for zeroed physics
        return torch.zeros(1, 1, 1, state_dim)
    T = engine_traj.shape[0]
    phys = torch.zeros(1, T, 1, state_dim)
    n_ch = min(engine_traj.shape[1], state_dim)
    phys[0, :T, 0, :n_ch] = torch.from_numpy(engine_traj[:, :n_ch])
    return phys


# ---------------------------------------------------------------------------
# Single-molecule forward pass
# ---------------------------------------------------------------------------

@torch.no_grad()
def predict_molecule(
    model: PhysicsInformedMixtureTransformer,
    heads: PIMTHeads,
    engine: OlfactoryEmbeddingEngine,
    smiles: str,
    cas: str,
    state_dim: int,
    conditioning: str,
    engine_cache: dict[str, np.ndarray | None],
) -> dict[str, np.ndarray] | None:
    """Run one molecule through the trained model under the given conditioning.

    Returns {substantivity: float, descriptor_profile: (138,)} or None if the
    molecule cannot be embedded.
    """
    z = engine.get_embedding(smiles, cas=cas)
    if z is None or not np.isfinite(z).any() or np.count_nonzero(z) == 0:
        return None

    tokens = torch.from_numpy(z).float().unsqueeze(0).unsqueeze(0)  # (1, 1, E)

    # Physics conditioning
    if conditioning == "on":
        if cas not in engine_cache:
            engine_cache[cas] = run_engine_for_molecule(cas, smiles)
        engine_traj = engine_cache[cas]
    else:
        engine_traj = None

    physics = build_physics_tensor(engine_traj, state_dim, conditioning)
    T = physics.size(1)

    # Expand tokens to match T timesteps for the FiLM block
    # model.forward expects tokens (B, S, E) and states (B, T, S, state_dim)
    latent = model(tokens, physics)  # (1, T, 1, H)
    out = heads(latent, physics)

    sub = float(out["subjective"]["substantivity"].reshape(-1)[0].cpu())
    # Descriptor profile: mean of 3 tiers, (138,)
    pyramid = out["objective"].squeeze(0).cpu().numpy()  # (3, 138)
    profile = pyramid.mean(axis=0)
    return {"substantivity": sub, "descriptor_profile": profile}


# ---------------------------------------------------------------------------
# Benchmark data loading
# ---------------------------------------------------------------------------

def load_substantivity_targets() -> dict[str, float]:
    """GoodScents measured substantivity hours keyed by CAS (log10-transformed
    to match the frozen probe's protocol)."""
    path = ROOT / "data" / "goodscents_substantivity.json"
    data = json.loads(path.read_text())
    hours = data["cas_to_substantivity_hours"]
    return {cas: float(np.log10(max(h, 1e-6))) for cas, h in hours.items()}


def load_descriptor_targets() -> tuple[dict[str, str], dict[str, dict[str, float]]]:
    """Per-CAS dominant descriptor letter + full distribution.

    Returns (dominant_letter_map, full_distribution_map).
    """
    dominant: dict[str, str] = {}
    full: dict[str, dict[str, float]] = {}
    path = ROOT / "data" / "descriptor_distributions_v11.jsonl"
    for line in path.read_text().splitlines():
        if not line.strip():
            continue
        try:
            r = json.loads(line)
        except Exception:
            continue
        dist = r.get("descriptor_distribution") or {}
        if dist:
            dominant[r["cas"]] = max(dist, key=dist.get)
            full[r["cas"]] = dist
    return dominant, full


def load_pyrfume_vocab() -> list[str]:
    return json.loads((ROOT / "data" / "pyrfume_vocabulary.json").read_text())["vocabulary"]


def get_cas_smiles(cas: str) -> str:
    """Best-effort SMILES lookup from the registry."""
    try:
        from pino.registry import AromaRegistry
        reg = AromaRegistry()
        rec = reg.get(cas)
        reg.close()
        return rec.get("smiles", "") if rec else ""
    except Exception:
        return ""


# ---------------------------------------------------------------------------
# Scoring
# ---------------------------------------------------------------------------

def spearman_rho(a: np.ndarray, b: np.ndarray) -> float:
    if len(a) < 3 or np.std(a) == 0 or np.std(b) == 0:
        return float("nan")
    ra = np.argsort(np.argsort(a))
    rb = np.argsort(np.argsort(b))
    return float(np.corrcoef(ra, rb)[0, 1])


def macro_f1(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    from sklearn.metrics import f1_score
    return float(f1_score(y_true, y_pred, average="macro", zero_division=0))


def evaluate_substantivity(
    preds: dict[str, float],
    targets: dict[str, float],
) -> dict[str, Any]:
    """Spearman rho between model predictions and log10(hours) targets."""
    cas_list = sorted(set(preds) & set(targets))
    if len(cas_list) < 3:
        return {"rho": None, "n": len(cas_list),
                "note": "Insufficient molecules with both prediction and target."}
    p = np.array([preds[c] for c in cas_list])
    t = np.array([targets[c] for c in cas_list])
    rho = spearman_rho(p, t)
    return {"rho": round(rho, 4) if rho == rho else None,
            "n": len(cas_list)}


def evaluate_descriptors(
    profiles: dict[str, np.ndarray],
    dominant_letter: dict[str, str],
    tag_to_letter: dict[int, str],
    binarize_threshold: float = 0.5,
) -> dict[str, Any]:
    """Macro-F1 of predicted dominant descriptor letter vs benchmark target.

    Protocol:
      1. Take the model's predicted 138-dim profile (mean of 3 tiers, sigmoid
         activations).
      2. For each descriptor letter class, aggregate the continuous sigmoid
         values of all Pyrfume tags mapped to that letter (via semantic
         synonym crosswalk). The predicted dominant letter = argmax of the
         per-letter aggregate. This mirrors how the benchmark itself defines
         the dominant letter (argmax of descriptor_distribution) and is the
         direct analog of the model-free probe's classifier prediction.
      3. Compute macro-F1 vs the benchmark's per-molecule dominant letter.

    We also report a binarized variant (threshold 0.5) as a secondary metric
    for transparency, but the primary metric uses continuous aggregation
    because the trained model's sigmoid outputs rarely exceed 0.5 on
    held-out molecules. We use the MEAN (not sum) of sigmoid values per letter
    to normalize for the varying number of tags mapped to each letter.
    """
    cas_list = sorted(set(profiles) & set(dominant_letter))
    if len(cas_list) < 3:
        return {"macro_f1": None, "n": len(cas_list),
                "protocol_note": "Insufficient molecules."}

    # Build letter aggregator: for each letter, which tag indices map to it
    letters = sorted(set(tag_to_letter.values()) - {""})
    if not letters:
        return {"macro_f1": None, "n": len(cas_list),
                "protocol_note": "No tag-to-letter mapping available."}

    letter_tag_indices: dict[str, list[int]] = {l: [] for l in letters}
    for idx, letter in tag_to_letter.items():
        if letter:
            letter_tag_indices[letter].append(idx)

    y_true, y_pred, y_pred_bin = [], [], []
    for cas in cas_list:
        prof = profiles[cas]
        # Continuous aggregation: MEAN of sigmoid values per letter (normalizes
        # for the number of tags mapped to each letter, preventing the bias
        # where letters with more synonyms always dominate).
        letter_scores = np.zeros(len(letters))
        for li, letter in enumerate(letters):
            idxs = letter_tag_indices[letter]
            if idxs:
                letter_scores[li] = prof[idxs].mean()
        pred_letter = letters[int(np.argmax(letter_scores))] if letter_scores.max() > 0 else letters[0]

        # Binarized variant
        binary = (prof >= binarize_threshold).astype(float)
        letter_scores_bin = np.zeros(len(letters))
        for li, letter in enumerate(letters):
            idxs = letter_tag_indices[letter]
            if idxs:
                letter_scores_bin[li] = binary[idxs].sum()
        pred_letter_bin = letters[int(np.argmax(letter_scores_bin))] if letter_scores_bin.max() > 0 else letters[0]

        y_true.append(dominant_letter[cas])
        y_pred.append(pred_letter)
        y_pred_bin.append(pred_letter_bin)

    y_true = np.array(y_true)
    y_pred = np.array(y_pred)
    y_pred_bin = np.array(y_pred_bin)
    f1 = macro_f1(y_true, y_pred)
    f1_bin = macro_f1(y_true, y_pred_bin)
    n_classes = len(set(y_true) | set(y_pred))
    return {
        "macro_f1": round(f1, 4),
        "macro_f1_binarized": round(f1_bin, 4),
        "n": len(cas_list),
        "n_classes_evaluated": n_classes,
        "aggregation": "continuous_sigmoid_mean_then_argmax",
        "binarize_threshold": binarize_threshold,
        "protocol_note": (
            "Trained model's predicted 138-dim profile (mean of 3 pyramid tiers, "
            "sigmoid activations) aggregated per descriptor letter by taking the "
            "MEAN of sigmoid values of tags mapped to each letter via the "
            "project's authoritative v8.2 odour-character crosswalk "
            "(artifacts/odour_character_crosswalk_v8_2.json); dominant letter = "
            "argmax. This mirrors the benchmark's own dominant-letter definition "
            "(argmax of descriptor_distribution). Differs from the model-free "
            "frozen probe, which trains a LogisticRegression classifier directly "
            "on frozen embeddings to predict the dominant letter. "
            "macro_f1_binarized additionally reports the binarized-at-0.5 variant."
        ),
    }


# ---------------------------------------------------------------------------
# Main evaluation loop
# ---------------------------------------------------------------------------

def parse_seed_from_name(name: str) -> int | None:
    m = re.search(r"seed(\d+)", name)
    return int(m.group(1)) if m else None


def parse_arm_from_name(name: str) -> str:
    if "physoff" in name.lower():
        return "physoff"
    if "openpom" in name.lower() or "pimt_ab" in name.lower():
        return "openpom"
    return "unknown"


def download_checkpoint(filename: str, hf_token: str | None) -> Path:
    from huggingface_hub import hf_hub_download
    path = hf_hub_download(
        repo_id="mattbitzesty/pino-pimt-representation-ab",
        filename=filename,
        token=hf_token,
    )
    return Path(path)


def main() -> int:
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--checkpoints", nargs="+", default=None,
                    help="Checkpoint filenames in the HF repo (e.g. pimt_ab_openpom_256_seed1.pt)")
    ap.add_argument("--seeds", nargs="+", type=int, default=None,
                    help="Alternative: specify seeds to auto-generate filenames for both arms.")
    ap.add_argument("--output", default=str(ROOT / "artifacts" / "trained_frozen_probes"),
                    help="Output directory.")
    ap.add_argument("--max-molecules", type=int, default=None,
                    help="Smoke test: limit to first N benchmark molecules.")
    ap.add_argument("--structural-source", default="openpom_256",
                    help="Embedding source (both arms use openpom_256).")
    ap.add_argument("--conditioning", nargs="+", default=["on", "off"],
                    choices=["on", "off"],
                    help="Which conditioning modes to evaluate.")
    args = ap.parse_args()

    # Resolve checkpoint list
    hf_token = None
    ckpt_files: list[str] = []
    if args.checkpoints:
        ckpt_files = args.checkpoints
    elif args.seeds:
        for s in args.seeds:
            ckpt_files.append(f"pimt_ab_openpom_256_seed{s}.pt")
            ckpt_files.append(f"pimt_physoff_openpom_256_seed{s}.pt")
    else:
        ap.error("Provide --checkpoints or --seeds.")

    # Get HF token
    try:
        import subprocess
        result = subprocess.run(
            ['op', 'item', 'get', 'Huggingface', '--vault', 'Automation',
             '--fields', 'access token', '--reveal'],
            capture_output=True, text=True, timeout=15,
        )
        if result.returncode == 0 and result.stdout.strip():
            hf_token = result.stdout.strip()
    except Exception:
        pass

    # Load benchmark data
    subst_targets = load_substantivity_targets()
    desc_dominant, _ = load_descriptor_targets()
    vocab = load_pyrfume_vocab()
    tag_to_letter = build_tag_to_letter_index(vocab)

    logger.info("Substantivity table (full): %d molecules", len(subst_targets))
    logger.info("Descriptor table (full): %d molecules (%d classes)",
                len(desc_dominant), len(set(desc_dominant.values())))

    # Restrict to the FROZEN benchmark molecule sets used by the model-free probe
    # (run_representation_ablation.py): cas in (target table ∩ POM ∩ Morgan/registry).
    # This makes the trained-arm numbers directly comparable to tab:main (n=213
    # substantivity, n=339 descriptor) rather than a different superset.
    pom_index = json.loads((ROOT / "artifacts" / "pom" / "pom_index.json").read_text())
    # Mirror run_representation_ablation.load_pom(): valid rows only; SMILES:/NATURAL:
    # ids resolved to registry CAS via their SMILES.
    import sqlite3 as _sqlite3
    import os as _os
    _db = _os.environ.get("PINO_REGISTRY_PATH") or str(ROOT / "src" / "pino" / "registry.db")
    _con = _sqlite3.connect(_db)
    smi2cas = {r[0]: r[1] for r in _con.execute(
        "SELECT smiles, cas FROM aroma_chemicals WHERE smiles IS NOT NULL AND smiles!=''")}
    _con.close()
    pom_keys: set[str] = set()
    for cid, smi, ok in zip(pom_index["ids"], pom_index["smiles"], pom_index["valid"]):
        if not ok:
            continue
        if cid.startswith(("SMILES:", "NATURAL:")):
            key = smi2cas.get(smi)
            if key is None:
                continue
            pom_keys.add(key)
        else:
            pom_keys.add(cid)
    reg_smiles: dict[str, str] = {}
    try:
        from pino.registry import AromaRegistry
        _reg = AromaRegistry()
        for _cas in sorted(set(subst_targets) | set(desc_dominant)):
            _rec = _reg.get(_cas)
            if _rec and _rec.get("smiles"):
                reg_smiles[_cas] = _rec["smiles"]
        _reg.close()
    except Exception as e:
        logger.warning("registry load failed: %s", e)
    registry_keys = set(reg_smiles)

    subst_frozen = sorted(set(subst_targets) & pom_keys & registry_keys)
    desc_frozen = sorted(set(desc_dominant) & pom_keys & registry_keys)
    logger.info("Frozen benchmark sets: substantivity n=%d (paper n=213), descriptor n=%d (paper n=339)",
                len(subst_frozen), len(desc_frozen))
    subst_targets = {c: subst_targets[c] for c in subst_frozen}
    desc_dominant = {c: desc_dominant[c] for c in desc_frozen}

    # CAS -> SMILES for all benchmark molecules (needed for embedding + engine)
    all_cas = sorted(set(subst_targets) | set(desc_dominant))
    if args.max_molecules:
        all_cas = all_cas[: args.max_molecules]
    logger.info("Total benchmark molecules to evaluate: %d", len(all_cas))

    cas_smiles: dict[str, str] = dict(reg_smiles)
    resolvable = {cas for cas, smi in cas_smiles.items() if smi}
    logger.info("Resolvable (have SMILES): %d / %d", len(resolvable), len(all_cas))

    # Embedding engine
    engine = OlfactoryEmbeddingEngine(structural_source=args.structural_source)
    logger.info("Embedding engine: %s (dim=%d)", args.structural_source, engine.embedding_dim)

    out_dir = Path(args.output)
    out_dir.mkdir(parents=True, exist_ok=True)

    all_results = []

    for ckpt_name in ckpt_files:
        arm = parse_arm_from_name(ckpt_name)
        seed = parse_seed_from_name(ckpt_name)
        logger.info("=" * 60)
        logger.info("Checkpoint: %s (arm=%s, seed=%s)", ckpt_name, arm, seed)

        # Download checkpoint
        ckpt_path = download_checkpoint(ckpt_name, hf_token)
        sha = sha256_file(ckpt_path)

        # Load model
        model, heads, dims = load_model(ckpt_path)
        state_dim = dims["state_dim"]
        logger.info("Model dims: %s", dims)

        for conditioning in args.conditioning:
            logger.info("-" * 40)
            logger.info("Conditioning: %s", conditioning)

            engine_cache: dict[str, np.ndarray | None] = {}
            sub_preds: dict[str, float] = {}
            desc_profiles: dict[str, np.ndarray] = {}

            for i, cas in enumerate(all_cas):
                smiles = cas_smiles.get(cas, "")
                if not smiles:
                    continue
                result = predict_molecule(
                    model, heads, engine, smiles, cas,
                    state_dim, conditioning, engine_cache,
                )
                if result is None:
                    continue
                sub_preds[cas] = result["substantivity"]
                desc_profiles[cas] = result["descriptor_profile"]
                if (i + 1) % 50 == 0:
                    logger.info("  %d/%d molecules processed", i + 1, len(all_cas))

            logger.info("Predictions: substantivity=%d, descriptors=%d",
                        len(sub_preds), len(desc_profiles))

            sub_result = evaluate_substantivity(sub_preds, subst_targets)
            desc_result = evaluate_descriptors(
                desc_profiles, desc_dominant, tag_to_letter,
            )

            record = {
                "arm": arm,
                "checkpoint": ckpt_name,
                "checkpoint_sha256": sha,
                "seed": seed,
                "conditioning": conditioning,
                "model_dims": dims,
                "substantivity": sub_result,
                "descriptors": desc_result,
                "threshold": {
                    "not_applicable": (
                        "The trained PIMT model has no odor-threshold head; "
                        "it was never trained against ODT targets."
                    ),
                },
                "n_predictions": {
                    "substantivity": len(sub_preds),
                    "descriptors": len(desc_profiles),
                },
            }
            all_results.append(record)

            # Save per-checkpoint-conditioning file
            safe_name = ckpt_name.replace(".pt", f"_{conditioning}.json")
            out_path = out_dir / safe_name
            out_path.write_text(json.dumps(record, indent=2))
            logger.info("Saved: %s", out_path)
            logger.info("  substantivity rho=%s (n=%s)",
                        sub_result["rho"], sub_result["n"])
            logger.info("  descriptor macro_f1=%s (n=%s)",
                        desc_result["macro_f1"], desc_result["n"])

    # Save combined results
    combined_path = out_dir / "all_results.json"
    combined_path.write_text(json.dumps(all_results, indent=2))
    logger.info("=" * 60)
    logger.info("Combined results: %s (%d records)", combined_path, len(all_results))

    # Print summary table
    print("\n" + "=" * 80)
    print(f"{'Arm':<10} {'Seed':<6} {'Cond':<6} {'Sub rho':<10} {'Sub n':<6} "
          f"{'Desc F1':<10} {'Desc n':<6}")
    print("-" * 80)
    for r in all_results:
        s = r["substantivity"]
        d = r["descriptors"]
        print(f"{r['arm']:<10} {str(r['seed']):<6} {r['conditioning']:<6} "
              f"{str(s.get('rho')):<10} {str(s.get('n')):<6} "
              f"{str(d.get('macro_f1')):<10} {str(d.get('n')):<6}")
    print("=" * 80)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())