File size: 16,537 Bytes
d027051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Prospective family-profile readout under TRAIN-CONSISTENT physics conditioning.

The paper's frozen-benchmarks evaluator (evaluate_frozen_benchmarks.py) scores the
40 held-out prospective formulas with the physics tensor ZEROED at eval time β€” a
deliberately conservative "perceptual-only" readout (one molecule, one timestep,
zeroed physics). A review panel demands the same readout re-scored under the
physics conditioning the model was actually trained on: the full (T, S) formula
token grid with REAL time-resolved physical states from the Dortmund-UNIFAC engine.

For each prospective formula this script:
  1. Runs the cached Dortmund-UNIFAC evaporation engine on the FULL formula
     (all ingredients together, as in training) to get per-(timestep, component)
     states: [x_liquid, log10(OAV)].
  2. Builds the train-consistent input grid: tokens (S, E) from the arm-matched
     embedding engine, physics (T, S, state_dim) from the engine trajectory.
  3. Forward through model + heads β†’ objective tiers (3, 138) β†’ mean over tiers.
  4. Projects the 138-dim prediction onto family tag-space β†’ cosine vs the
     sequestered intended family profile (SAME scoring code as the frozen eval).
  5. Also emits the ZEROED-physics full-grid cosine (sensitivity reference):
     same grid, same forward, physics zeroed β€” isolating the physics contribution
     at the full-grid architecture.

Engine trajectories are cached (artifacts/engine_traj_cache.json) so reruns are cheap.

Output JSON:
  {arm, checkpoint sha256, n_formulas,
   mean_family_profile_cosine_physics_on,
   mean_family_profile_cosine_zeroed_fullgrid,
   details: [{formula_id, genre, cosine_physics_on, cosine_zeroed_fullgrid, delta, ...}]}
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import sys
from pathlib import Path

import numpy as np
import torch
from scipy.spatial.distance import cosine

# Ensure src/ is importable
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
# Also make the scripts dir importable so we can reuse the frozen-eval scoring code
sys.path.insert(0, str(ROOT / "scripts"))

from pino.embeddings import OlfactoryEmbeddingEngine  # noqa: E402
from pino.heads import PIMTHeads  # noqa: E402
from pino.pimt_model import PhysicsInformedMixtureTransformer  # noqa: E402

# Reuse the exact scoring code from the frozen-benchmarks evaluator
from evaluate_frozen_benchmarks import (  # noqa: E402
    FAMS,
    FAMILY_TAGS,
    _family_projection,
    infer_model_dims,
    load_model,
    sha256_file,
)


# ---------------------------------------------------------------------------
# Engine trajectory computation
# ---------------------------------------------------------------------------

def _load_verifier():
    from pino.verifier import FragrancePipelineVerifier
    return FragrancePipelineVerifier()


def _run_formula_trajectory(verifier, formula: dict, duration_seconds: float = 8 * 3600.0,
                            interval_seconds: float = 600.0) -> dict | None:
    """Run the evaporation engine on a FULL prospective formula.

    Returns a dict with:
        species:   [cas, ...]   (resolved ingredient CAS order)
        t_s:       [times]
        x_liquid:  (T, S) array
        log_oav:   (T, S) array
    or None if the engine could not solve the formula.
    """
    ings = []
    for ing in formula["ingredients"]:
        ings.append({
            "cas": ing["cas"],
            "smiles": ing.get("smiles", ""),
            "weight_fraction": ing["weight_fraction"],
        })

    # Patch any registry records that have smiles=None but the formula provides
    # a valid SMILES β€” otherwise _ingredient_from_record raises a TypeError that
    # skip_unresolved does not catch (it's not an IngredientResolutionError).
    for ing in ings:
        cas = ing["cas"]
        smiles = ing.get("smiles", "")
        if not smiles:
            continue
        try:
            rec = verifier.resolver.registry.get(cas)
            if rec and not rec.get("smiles"):
                verifier.resolver.registry.add({
                    **rec, "smiles": smiles, "cas": cas,
                })
        except Exception:  # noqa: BLE001
            pass

    try:
        sim = verifier.run_sim(ings, duration_seconds=duration_seconds,
                               interval_seconds=interval_seconds,
                               method="BDF", skip_ifra=True, skip_unresolved=True)
        traj = sim.get("trajectory", [])
        if not traj:
            return None
        # Determine the resolved species order from the first timestep
        first = traj[0]
        species = list(first["x_liquid"].keys())
        T = len(traj)
        S = len(species)
        x_liquid = np.zeros((T, S), dtype=np.float32)
        log_oav = np.zeros((T, S), dtype=np.float32)
        times = []
        for t, step in enumerate(traj):
            times.append(step["t_s"])
            for j, cas in enumerate(species):
                x_liquid[t, j] = float(step["x_liquid"].get(cas, 0.0))
                oav = float(step["OAV"].get(cas, 0.0))
                log_oav[t, j] = np.log10(max(oav, 1e-10))
        return {"species": species, "t_s": times,
                "x_liquid": x_liquid.tolist(), "log_oav": log_oav.tolist()}
    except Exception:
        return None


def get_trajectory_cache(formula_id: str, verifier, formula: dict,
                         cache: dict, cache_path: Path) -> dict | None:
    """Return cached trajectory for a formula, or compute + cache it."""
    if formula_id in cache:
        entry = cache[formula_id]
        return entry if entry else None  # empty dict = previously failed
    traj = _run_formula_trajectory(verifier, formula)
    if traj is None:
        cache[formula_id] = {}
        cache_path.write_text(json.dumps(cache))
        return None
    cache[formula_id] = traj
    cache_path.write_text(json.dumps(cache))
    return traj


# ---------------------------------------------------------------------------
# Forward pass
# ---------------------------------------------------------------------------

def build_formula_grid(formula: dict, traj: dict, engine: OlfactoryEmbeddingEngine,
                       state_dim: int) -> tuple[torch.Tensor, torch.Tensor] | None:
    """Build the (T, S, E) token grid and (T, S, state_dim) physics grid.

    Returns (tokens, physics) ready for model(), or None on failure.
    The engine trajectory may resolve fewer ingredients than the formula
    (skip_unresolved=True). We align tokens to the resolved species.
    """
    species = traj["species"]
    # Map resolved CAS back to the formula ingredients for embeddings
    ing_by_cas = {}
    for ing in formula["ingredients"]:
        ing_by_cas[ing["cas"]] = ing

    tokens_list = []
    for cas in species:
        ing = ing_by_cas.get(cas, {})
        smiles = ing.get("smiles", "")
        z = engine.get_embedding(smiles, cas=cas)
        tokens_list.append(torch.from_numpy(z).float())

    if not tokens_list:
        return None

    tokens = torch.stack(tokens_list, dim=0)  # (S, E)
    S = tokens.shape[0]
    E = tokens.shape[1]
    x_liquid = np.asarray(traj["x_liquid"], dtype=np.float32)  # (T, S)
    T = x_liquid.shape[0]

    # Physics: (T, S, state_dim) β€” [x_liquid, log10(OAV)]
    if state_dim < 2:
        raise ValueError(f"state_dim must be >= 2 for physics-on eval, got {state_dim}")
    physics = np.zeros((T, S, state_dim), dtype=np.float32)
    physics[:, :, 0] = x_liquid
    physics[:, :, 1] = np.asarray(traj["log_oav"], dtype=np.float32)
    # If state_dim == 3 (gamma channel), leave it as zeros β€” gamma is not
    # available from the prospective engine trajectory without P_sat lookup.
    # This is documented in the script's output notes.
    physics_tensor = torch.from_numpy(physics)

    return tokens, physics_tensor


def forward_formula(model, heads, tokens_2d: torch.Tensor, physics_3d: torch.Tensor) -> np.ndarray:
    """Full-grid forward: (S,E) + (T,S,state_dim) -> 138-dim prediction.

    model expects tokens (B, S, E) and states (B, T, S, state_dim).
    heads expects latent (B, T, S, H) and physics (B, T, S, state_dim).
    """
    S = tokens_2d.shape[0]
    tokens = tokens_2d.unsqueeze(0)  # (1, S, E)
    physics = physics_3d.unsqueeze(0)  # (1, T, S, state_dim)
    mask = torch.zeros(1, S, dtype=torch.bool)
    with torch.no_grad():
        latent = model(tokens, physics)  # (1, T, S, H)
        out = heads(latent, physics, mask)
        pyramid = out["objective"][0].cpu().numpy()  # (3, 138)
    return pyramid.mean(axis=0)  # (138,)


def forward_formula_zeroed(model, heads, tokens_2d: torch.Tensor, physics_3d: torch.Tensor) -> np.ndarray:
    """Same as forward_formula but with physics zeroed (sensitivity reference)."""
    physics_zero = torch.zeros_like(physics_3d)
    return forward_formula(model, heads, tokens_2d, physics_zero)


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

ARM_TO_STRUCTURAL_SOURCE = {
    "morgan": "morgan",
    "morgan_2048_rp": "morgan_2048_rp",
    "morgan_2048_direct": "morgan_2048_direct",
    "openpom_256": "openpom_256",
    "disjoint_256": "disjoint_256",
}


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--checkpoint", required=True, help="Path to PIMT checkpoint .pt")
    ap.add_argument("--arm", required=True,
                    choices=list(ARM_TO_STRUCTURAL_SOURCE),
                    help="A/B arm name (determines embedding engine structural_source)")
    ap.add_argument("--max-formulas", type=int, default=None,
                    help="Limit to first N formulas (smoke testing)")
    ap.add_argument("--output", required=True)
    ap.add_argument("--cache", default=str(ROOT / "artifacts" / "engine_traj_cache.json"))
    ap.add_argument("--vocab", default=str(ROOT / "data" / "pyrfume_vocabulary.json"))
    ap.add_argument("--formulas",
                    default=str(ROOT / "data" / "benchmarks" / "prospective_formulas" / "formulas.jsonl"))
    ap.add_argument("--labels",
                    default=str(ROOT / "data" / "benchmarks" / "prospective_formulas" / "labels.sequestered.json"))
    ap.add_argument("--skip-download", action="store_true",
                    help="Don't download checkpoint from HF; use local --checkpoint path only")
    args = ap.parse_args()

    structural_source = ARM_TO_STRUCTURAL_SOURCE[args.arm]

    # --- Load model ---
    ckpt_path = Path(args.checkpoint)
    if not ckpt_path.exists():
        if args.skip_download:
            print(f"ERROR: checkpoint not found: {ckpt_path}", file=sys.stderr)
            return 1
        print(f"Downloading checkpoint from HuggingFace: {args.checkpoint}")
        from huggingface_hub import hf_hub_download
        ckpt_path = Path(hf_hub_download(
            repo_id="mattbitzesty/pino-pimt-representation-ab",
            filename=ckpt_path.name,
        ))

    objective_dim = 138  # family projection is 138-vocab specific
    model, heads, dims = load_model(ckpt_path, objective_dim=objective_dim)
    state_dim = dims["state_dim"]
    model.eval()
    heads.eval()

    # --- Load embedding engine ---
    engine = OlfactoryEmbeddingEngine(structural_source=structural_source)

    # --- Load data ---
    vocab = json.loads(Path(args.vocab).read_text())["vocabulary"]
    formulas = [json.loads(l) for l in Path(args.formulas).read_text().splitlines() if l.strip()]
    if args.max_formulas:
        formulas = formulas[:args.max_formulas]
    labels_raw = json.loads(Path(args.labels).read_text())["labels"]
    labels = {l["formula_id"]: l["target_family_profile"] for l in labels_raw}

    # --- Cache ---
    cache_path = Path(args.cache)
    cache_path.parent.mkdir(parents=True, exist_ok=True)
    cache = json.loads(cache_path.read_text()) if cache_path.exists() else {}

    # --- Verifier (lazy) ---
    verifier = None

    # --- Evaluate ---
    sims_on, sims_off = [], []
    details = []

    for form in formulas:
        fid = form["formula_id"]
        if verifier is None:
            verifier = _load_verifier()
        traj = get_trajectory_cache(fid, verifier, form, cache, cache_path)
        if traj is None:
            print(f"  [{fid}] engine trajectory failed β€” skipping", file=sys.stderr)
            details.append({
                "formula_id": fid, "genre": form["genre"],
                "cosine_physics_on": None, "cosine_zeroed_fullgrid": None,
                "delta": None, "n_engine_species": 0, "n_timesteps": 0,
                "status": "engine_failed",
            })
            continue

        grid = build_formula_grid(form, traj, engine, state_dim)
        if grid is None:
            details.append({
                "formula_id": fid, "genre": form["genre"],
                "cosine_physics_on": None, "cosine_zeroed_fullgrid": None,
                "delta": None, "n_engine_species": 0, "n_timesteps": len(traj["t_s"]),
                "status": "token_build_failed",
            })
            continue
        tokens_2d, physics_3d = grid

        # Physics ON (train-consistent)
        pred_on = forward_formula(model, heads, tokens_2d, physics_3d)
        # Physics OFF (zeroed, same full-grid architecture)
        pred_off = forward_formula_zeroed(model, heads, tokens_2d, physics_3d)

        tgt_profile = labels.get(fid, {})
        tgt = np.array([tgt_profile.get(f, 0.0) for f in FAMS])

        def _score(pred_138: np.ndarray) -> float:
            fam_proj = _family_projection(vocab, pred_138)
            if fam_proj.sum():
                fam_proj = fam_proj / fam_proj.sum()
            if pred_138.any() and tgt.any():
                return float(1.0 - cosine(fam_proj, tgt))
            return 0.0

        sim_on = _score(pred_on)
        sim_off = _score(pred_off)
        sims_on.append(sim_on)
        sims_off.append(sim_off)

        details.append({
            "formula_id": fid,
            "genre": form["genre"],
            "n_engine_species": len(traj["species"]),
            "n_timesteps": len(traj["t_s"]),
            "cosine_physics_on": round(sim_on, 4),
            "cosine_zeroed_fullgrid": round(sim_off, 4),
            "delta_on_minus_off": round(sim_on - sim_off, 4),
            "status": "ok",
        })
        print(f"  [{fid}] on={sim_on:.4f} off={sim_off:.4f} delta={sim_on-sim_off:+.4f}")

    n_ok = len(sims_on)
    result = {
        "arm": args.arm,
        "structural_source": structural_source,
        "checkpoint": str(ckpt_path),
        "checkpoint_sha256": sha256_file(ckpt_path),
        "model_dims": dims,
        "state_dim": state_dim,
        "n_formulas": len(formulas),
        "n_evaluated": n_ok,
        "n_skipped": len(formulas) - n_ok,
        "mean_family_profile_cosine_physics_on": round(float(np.mean(sims_on)), 4) if sims_on else None,
        "mean_family_profile_cosine_zeroed_fullgrid": round(float(np.mean(sims_off)), 4) if sims_off else None,
        "mean_delta_on_minus_off": round(float(np.mean(np.array(sims_on) - np.array(sims_off))), 4) if sims_on else None,
        "conditioning": "train_consistent_full_grid_physics_on",
        "notes": [
            "Physics ON: real time-resolved [x_liquid, log10(OAV)] from Dortmund-UNIFAC engine on the full formula.",
            "Zeroed full-grid: same (T,S) architecture, physics tensor zeroed (sensitivity reference isolating physics contribution).",
            "State_dim=3 checkpoints have gamma channel zeroed (gamma not available from prospective trajectory without P_sat lookup).",
        ],
        "details": details,
    }

    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(result, indent=2))

    print("\n" + "=" * 70)
    print(f"PROSPECTIVE TRAIN-CONSISTENT EVAL β€” arm={args.arm}")
    print("=" * 70)
    print(f"Formulas: {len(formulas)} | evaluated: {n_ok} | skipped: {len(formulas) - n_ok}")
    print(f"Mean cosine (physics ON):     {result['mean_family_profile_cosine_physics_on']}")
    print(f"Mean cosine (zeroed fullgrid): {result['mean_family_profile_cosine_zeroed_fullgrid']}")
    print(f"Mean delta (on - off):        {result['mean_delta_on_minus_off']}")
    print(f"Output: {out}")
    print("=" * 70)
    return 0


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