File size: 34,193 Bytes
db32e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
#!/usr/bin/env python
"""
Retrieval + generation: Variants A (SMI-TED only), B (ChemBERTa retrieval + SMI-TED gen), C (ChemBERTa only).
Plan §3. Input: MGF or binned spectra. Output: candidate SMILES per spectrum.
"""
from __future__ import annotations

import argparse
import json
import sys
from functools import lru_cache
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

import numpy as np
import torch

from spec_rag.embeddings import SMILESEmbedder, SpectrumEmbedder, l2_normalize
from spec_rag.faiss_index import load_index, index_search


def _bin_peaks(mz, intensity, num_bins: int, max_mz: float):
    """Bin peaks to fixed-length spectrum.

    Accepts list or numpy arrays and converts to torch tensors.
    """
    if not isinstance(mz, torch.Tensor):
        mz = torch.tensor(mz, dtype=torch.float32)
    if not isinstance(intensity, torch.Tensor):
        intensity = torch.tensor(intensity, dtype=torch.float32)
    bins = torch.zeros(num_bins, dtype=torch.float32)
    if mz.numel() == 0:
        return bins.numpy()
    idx = torch.clamp((mz / max_mz) * num_bins, min=0, max=num_bins - 1e-6).long()
    idx = torch.clamp(idx, max=num_bins - 1)
    bins.index_add_(0, idx, intensity)
    return bins.numpy()


def load_mgf_spectra(mgf_path: str, spec_bins: int = 2048, max_mz: float = 2000.0, max_peaks: int = 60):
    try:
        from pyteomics import mgf
    except ImportError:
        raise ImportError("pyteomics required")
    out = []
    with mgf.MGF(mgf_path) as reader:
        for spec in reader:
            params = spec.get("params", {})
            smi_gt = (params.get("SMILES") or params.get("smiles") or "").strip()
            formula_gt = (params.get("FORMULA") or params.get("formula") or "").strip()
            mz = spec.get("m/z array", [])
            inten = spec.get("intensity array", [])
            if len(mz) == 0 or len(inten) == 0:
                continue
            binned = _bin_peaks(mz, inten, num_bins=spec_bins, max_mz=max_mz)
            peaks = [[float(m), float(i)] for m, i in zip(mz, inten)]
            if max_peaks and peaks:
                peaks = sorted(peaks, key=lambda x: x[1], reverse=True)[:max_peaks]
            out.append({"binned": binned, "peaks": peaks, "smiles_gt": smi_gt, "formula": formula_gt})
    return out


def build_meta_peaks(records, max_peaks: int):
    if not records or "peaks" not in records[0]:
        return {}
    peaks_list = [r["peaks"] for r in records]
    max_len = min(max(len(p) for p in peaks_list), max_peaks) if max_peaks else max(len(p) for p in peaks_list)
    arr = np.zeros((len(peaks_list), max_len, 2), dtype=np.float32)
    for i, p in enumerate(peaks_list):
        for j, pair in enumerate(p[:max_len]):
            arr[i, j, 0] = pair[0]
            arr[i, j, 1] = pair[1]
    return {"peaks": torch.tensor(arr)}


def load_meta(library_dir: Path):
    meta_path = library_dir / "meta.parquet"
    if meta_path.exists():
        import pandas as pd
        try:
            df = pd.read_parquet(meta_path, columns=["smiles", "formula"])
        except Exception:
            df = pd.read_parquet(meta_path)
        return df
    meta_path = library_dir / "meta.jsonl"
    if meta_path.exists():
        rows = []
        with open(meta_path) as f:
            for line in f:
                if line.strip():
                    rows.append(json.loads(line))
        import pandas as pd
        return pd.DataFrame(rows)
    raise FileNotFoundError(f"No meta.parquet or meta.jsonl in {library_dir}")


def _normalize_formula(value) -> str:
    if value is None:
        return ""
    text = str(value).strip()
    return "" if text.lower() == "nan" else text


def _build_query_formula_index(formulas, target_formulas):
    if formulas is None or not target_formulas:
        return {}
    lookup = {formula: [] for formula in target_formulas}
    for i, value in enumerate(formulas):
        bucket = lookup.get(_normalize_formula(value))
        if bucket is not None:
            bucket.append(i)
    return {
        formula: np.asarray(indices, dtype=np.int64)
        for formula, indices in lookup.items()
        if indices
    }


def _exact_subset_search(query, candidate_idx, k: int, vector_store):
    if candidate_idx is None or vector_store is None:
        return None
    candidate_idx = np.asarray(candidate_idx, dtype=np.int64)
    if candidate_idx.size == 0:
        return None
    vectors = np.asarray(vector_store[candidate_idx], dtype=np.float32)
    vectors = l2_normalize(vectors)
    q = np.asarray(query, dtype=np.float32).reshape(-1)
    top_k = min(int(k), int(candidate_idx.shape[0]))
    if top_k <= 0:
        return []
    scores = vectors @ q
    if top_k >= scores.shape[0]:
        order = np.argsort(-scores, kind="mergesort")
    else:
        part = np.argpartition(-scores, top_k - 1)[:top_k]
        order = part[np.argsort(-scores[part], kind="mergesort")]
    return candidate_idx[order].astype(np.int64).tolist()


def _exact_formula_subset_search(query, k: int, target_formula: str, formula_lookup, vector_store):
    target = _normalize_formula(target_formula)
    if not target or not formula_lookup:
        return None
    return _exact_subset_search(query, formula_lookup.get(target), k, vector_store)


def _normalize_candidate_key(value) -> str:
    if value is None:
        return ""
    return str(value).strip()


@lru_cache(maxsize=200000)
def _canonicalize_smiles(smiles: str) -> str:
    text = str(smiles or "").strip()
    if not text:
        return ""
    try:
        from rdkit import Chem
    except ImportError:
        return text
    mol = Chem.MolFromSmiles(text)
    if mol is None:
        return text
    return Chem.MolToSmiles(mol, canonical=True)


def _load_candidate_map(path: str):
    with open(path) as f:
        data = json.load(f)
    if not isinstance(data, dict):
        raise SystemExit(f"Candidate map must be a JSON object: {path}")
    out = {}
    for key, values in data.items():
        if not isinstance(values, list):
            continue
        norm_key = _normalize_candidate_key(key)
        if not norm_key:
            continue
        out[norm_key] = [_normalize_candidate_key(v) for v in values if _normalize_candidate_key(v)]
    return out


@lru_cache(maxsize=200000)
def _smiles_to_formula(smiles: str) -> str:
    text = str(smiles or "").strip()
    if not text:
        return ""
    try:
        from rdkit import Chem
        from rdkit.Chem import rdMolDescriptors
    except ImportError:
        return ""
    mol = Chem.MolFromSmiles(text)
    if mol is None:
        return ""
    return rdMolDescriptors.CalcMolFormula(mol)


def _looks_like_formula(text: str) -> bool:
    if not text:
        return False
    try:
        import re
    except ImportError:
        return False
    return bool(re.fullmatch(r"(?:[A-Z][a-z]?\d*)+", text))


def _coerce_candidate_map_to_formula(candidate_map: dict) -> dict:
    """Convert a candidate map keyed by SMILES or formula into a formula-keyed map."""

    out = {}
    for key, values in candidate_map.items():
        formula_key = _normalize_formula(key)
        if not _looks_like_formula(formula_key):
            formula_key = _smiles_to_formula(formula_key)
        if not formula_key:
            continue
        bucket = out.setdefault(formula_key, [])
        seen = set(bucket)
        for smi in values:
            clean = _normalize_candidate_key(smi)
            if not clean or clean in seen:
                continue
            seen.add(clean)
            bucket.append(clean)
    return out


def _build_partial_smiles_index(smiles_values, target_smiles):
    if not target_smiles:
        return {}
    remaining = set(target_smiles)
    found = {}
    for i, value in enumerate(smiles_values):
        smi = str(value)
        if smi not in remaining:
            continue
        found[smi] = i
        remaining.remove(smi)
        if not remaining:
            break
    return found


def _build_query_candidate_index(candidate_map, query_keys, smiles_values):
    active_keys = [_normalize_candidate_key(k) for k in query_keys if _normalize_candidate_key(k) in candidate_map]
    if not active_keys:
        return {}
    required_smiles = set()
    for key in active_keys:
        required_smiles.update(candidate_map.get(key, []))
    smiles_to_index = _build_partial_smiles_index(smiles_values, required_smiles)
    lookup = {}
    for key in active_keys:
        idx = [
            smiles_to_index[smi]
            for smi in candidate_map.get(key, [])
            if smi in smiles_to_index
        ]
        if idx:
            lookup[key] = np.asarray(idx, dtype=np.int64)
    return lookup


def _build_formula_canonical_index(target_formula: str, formula_lookup, smiles_values, cache):
    target = _normalize_formula(target_formula)
    if not target or not formula_lookup:
        return {}
    cached = cache.get(target)
    if cached is not None:
        return cached
    idx = formula_lookup.get(target)
    if idx is None or len(idx) == 0:
        cache[target] = {}
        return cache[target]
    canon_map = {}
    for lib_idx in idx.tolist():
        smi = str(smiles_values[int(lib_idx)])
        canon = _canonicalize_smiles(smi)
        if not canon:
            continue
        canon_map.setdefault(canon, []).append(int(lib_idx))
    cache[target] = canon_map
    return canon_map


def _candidate_pool_indices(
    query_key: str,
    target_formula: str,
    candidate_lookup,
    candidate_map,
    formula_lookup,
    smiles_values,
    formula_canonical_cache,
):
    raw_idx = candidate_lookup.get(query_key)
    raw_list = raw_idx.tolist() if raw_idx is not None else []
    if not candidate_map or query_key not in candidate_map:
        return raw_list or None

    canon_map = _build_formula_canonical_index(target_formula, formula_lookup, smiles_values, formula_canonical_cache)
    if not canon_map:
        return raw_list or None

    merged = []
    seen = set()
    for lib_idx in raw_list:
        lib_idx = int(lib_idx)
        if lib_idx in seen:
            continue
        seen.add(lib_idx)
        merged.append(lib_idx)

    for candidate_smiles in candidate_map.get(query_key, []):
        canon = _canonicalize_smiles(candidate_smiles)
        if not canon:
            continue
        for lib_idx in canon_map.get(canon, []):
            lib_idx = int(lib_idx)
            if lib_idx in seen:
                continue
            seen.add(lib_idx)
            merged.append(lib_idx)

    return merged or None


def _rank_candidate_smiles_direct(
    query_vec: np.ndarray,
    candidate_smiles: list,
    k: int,
    variant: str,
    device: str,
    chemberta_model: str,
    despecbridge_path: str | None,
    candidate_embedding_cache: dict,
    chem_candidate_embedder,
    smi_candidate_encoder,
):
    ordered = []
    seen = set()
    for smi in candidate_smiles:
        clean = _normalize_candidate_key(smi)
        if not clean or clean in seen:
            continue
        seen.add(clean)
        ordered.append(clean)
    if not ordered:
        return None, chem_candidate_embedder, smi_candidate_encoder

    missing = [smi for smi in ordered if smi not in candidate_embedding_cache]
    if missing:
        if variant in ("B", "C"):
            if chem_candidate_embedder is None:
                chem_candidate_embedder = SMILESEmbedder(
                    model_name=chemberta_model,
                    device=device,
                    batch_size=256,
                    normalize=False,
                )
            emb = chem_candidate_embedder.encode(missing)
            emb = l2_normalize(emb).astype(np.float32)
        else:
            if smi_candidate_encoder is None:
                from spec_rag.smited_encoder import load_smited_encoder

                smi_candidate_encoder = load_smited_encoder(
                    despecbridge_path=despecbridge_path,
                    device=device,
                )
                if smi_candidate_encoder is None:
                    return None, chem_candidate_embedder, smi_candidate_encoder
            emb = smi_candidate_encoder(missing, batch_size=256)
            emb = l2_normalize(emb).astype(np.float32)

        for smi, vec in zip(missing, emb):
            candidate_embedding_cache[smi] = vec

    vectors = np.stack([candidate_embedding_cache[smi] for smi in ordered], axis=0).astype(np.float32)
    q = np.asarray(query_vec, dtype=np.float32).reshape(-1)
    top_k = min(int(k), len(ordered))
    if top_k <= 0:
        return [], chem_candidate_embedder, smi_candidate_encoder
    scores = vectors @ q
    if top_k >= scores.shape[0]:
        order = np.argsort(-scores, kind="mergesort")
    else:
        part = np.argpartition(-scores, top_k - 1)[:top_k]
        order = part[np.argsort(-scores[part], kind="mergesort")]
    ranked = []
    for pos in order[:top_k]:
        smi = ordered[int(pos)]
        ranked.append({"smiles": smi, "formula": _smiles_to_formula(smi)})
    return ranked, chem_candidate_embedder, smi_candidate_encoder


def _search_with_formula_backfill(
    index,
    query: np.ndarray,
    k: int,
    formulas,
    target_formula: str,
    min_fetch: int,
    max_fetch: int,
    fetch_multiplier: int,
):
    target = _normalize_formula(target_formula)
    if not target or formulas is None:
        _, idx = index_search(index, query, k)
        return idx[0].tolist()

    ntotal = min(int(getattr(index, "ntotal", len(formulas))), len(formulas))
    if ntotal <= 0:
        return []

    fetch_k = min(ntotal, max(int(k), int(min_fetch), int(k) * int(fetch_multiplier)))
    filtered = []
    filtered_seen = set()
    fallback = []
    fallback_seen = set()

    while True:
        _, idx = index_search(index, query, fetch_k)
        filtered = []
        filtered_seen.clear()
        fallback = []
        fallback_seen.clear()

        for raw_j in idx[0].tolist():
            j = int(raw_j)
            if j < 0 or j >= len(formulas):
                continue
            if j not in fallback_seen:
                fallback_seen.add(j)
                fallback.append(j)
            if _normalize_formula(formulas[j]) != target or j in filtered_seen:
                continue
            filtered_seen.add(j)
            filtered.append(j)
            if len(filtered) >= k:
                return filtered

        if fetch_k >= ntotal or fetch_k >= max_fetch:
            break
        next_fetch = min(ntotal, max(fetch_k * 2, fetch_k + int(k)))
        if next_fetch <= fetch_k:
            break
        fetch_k = next_fetch

    for j in fallback:
        if j in filtered_seen:
            continue
        filtered.append(j)
        if len(filtered) >= k:
            break
    return filtered[:k]


def _load_global_index_or_die(index_path: Path, ef_search: int | None = None):
    if not index_path.exists():
        raise SystemExit(f"Missing retrieval index: {index_path}")
    try:
        return load_index(index_path, ef_search=ef_search)
    except ModuleNotFoundError as exc:
        raise SystemExit(
            f"FAISS python module is not available, so {index_path.name} cannot be loaded for global ANN fallback. "
            f"Use --formula-filter and/or --candidate-json so retrieval stays in exact subset mode, or install faiss."
        ) from exc


def parse_args():
    p = argparse.ArgumentParser(description="Retrieve + generate (Variants A/B/C)")
    p.add_argument("--mgf-path", required=True, help="Query MGF (e.g. MassSpecGym test)")
    p.add_argument("--library-dir", required=True, help="vectors_smi, vectors_chem, meta, indices")
    p.add_argument(
        "--mapper-dir",
        default=None,
        help="Directory with mappers.pt (Spec-RAG-trained M_smi/M_chem). Optional when using pretrained mappers.",
    )
    p.add_argument("--specbridge-ckpt", required=True)
    p.add_argument("--dreams-ckpt", default=None)
    p.add_argument("--variant", choices=["A", "B", "C"], required=True)
    p.add_argument("--K", type=int, default=100, help="Number of candidates to retrieve per spectrum")
    p.add_argument(
        "--ef-search",
        type=int,
        default=512,
        help="FAISS HNSW ef_search at retrieval time; higher improves recall (default 512).",
    )
    p.add_argument("--out-jsonl", required=True, help="Output: one JSON object per spectrum")
    p.add_argument("--spec-bins", type=int, default=2048)
    p.add_argument("--max-mz", type=float, default=2000.0)
    p.add_argument("--max-peaks", type=int, default=60)
    p.add_argument("--chemberta-model", default="Derify/ChemBERTa_augmented_pubchem_13m")
    p.add_argument(
        "--formula-filter",
        action="store_true",
        help="Prefer same-formula candidates by adaptively over-fetching from the global index.",
    )
    p.add_argument(
        "--formula-min-fetch",
        type=int,
        default=512,
        help="Minimum FAISS fetch size when --formula-filter is enabled.",
    )
    p.add_argument(
        "--formula-max-fetch",
        type=int,
        default=32768,
        help="Maximum FAISS fetch size when --formula-filter is enabled before falling back to global hits.",
    )
    p.add_argument(
        "--formula-fetch-multiplier",
        type=int,
        default=16,
        help="Initial fetch size multiplier for --formula-filter (fetch = max(K*multiplier, formula-min-fetch)).",
    )
    p.add_argument(
        "--candidate-json",
        default=None,
        help="Optional JSON mapping query key -> candidate SMILES list; exact rerank happens inside that pool.",
    )
    p.add_argument(
        "--candidate-key-field",
        choices=["smiles_gt", "formula"],
        default="formula",
        help="Record field used to look up candidate pools in --candidate-json. Use `formula` for non-oracle retrieval; `smiles_gt` is oracle-only benchmarking.",
    )
    p.add_argument("--device", default="cuda")
    p.add_argument("--limit", type=int, default=None)
    p.add_argument(
        "--smited-mapper-ckpt",
        default=None,
        help="Optional De-SpecBridge SMI-TED mapper checkpoint (e.g. runs/smited_mapper_final/mapper_best.pt).",
    )
    p.add_argument(
        "--despecbridge-path",
        default=None,
        help="Path to De-SpecBridge repo when using --smited-mapper-ckpt.",
    )
    return p.parse_args()


def main():
    args = parse_args()
    if args.device == "cuda" and not torch.cuda.is_available():
        args.device = "cpu"
    device = torch.device(args.device)
    lib = Path(args.library_dir)

    use_pretrained_smited = args.smited_mapper_ckpt is not None

    # Spec-RAG mappers.pt only needed for Variant A when not using pretrained SMI-TED mapper.
    M_smi = None
    M_chem = None
    d_spec = d_smi = d_chem = None
    if args.variant == "A" and not use_pretrained_smited:
        if args.mapper_dir is None:
            raise SystemExit("mapper-dir is required for Variant A when --smited-mapper-ckpt is not provided.")
        mapper_dir = Path(args.mapper_dir)
        try:
            ckpt = torch.load(mapper_dir / "mappers.pt", map_location="cpu", weights_only=False)
        except TypeError:
            ckpt = torch.load(mapper_dir / "mappers.pt", map_location="cpu")
        d_spec = ckpt["d_spec"]
        d_smi = ckpt["d_smi"]
        d_chem = ckpt["d_chem"]

        class MapperHead(torch.nn.Module):
            def __init__(self, d_in, d_out):
                super().__init__()
                self.proj = torch.nn.Linear(d_in, d_out)

            def forward(self, x):
                return self.proj(x)

        M_smi = MapperHead(d_spec, d_smi)
        M_chem = MapperHead(d_spec, d_chem)
        M_smi.load_state_dict(ckpt["M_smi"])
        M_chem.load_state_dict(ckpt["M_chem"])
        M_smi.to(device).eval()
        M_chem.to(device).eval()

    # E_mist / ChemBERTa (SpecBridge mapper to ChemBERTa space)
    # NOTE: For Variant A with a pretrained SMI-TED mapper, we do NOT need SpectrumEmbedder at all.
    spec_embedder = None

    # Optional spec -> SMI-TED mapper from De-SpecBridge (DreamsToSmiTed, uses existing mapper_best.pt)
    smited_mapper_model = None
    if use_pretrained_smited:
        despec_root = Path(args.despecbridge_path or "/cluster/tufts/liulab/yiwan01/De-SpecBridge").resolve()
        if str(despec_root) not in sys.path:
            sys.path.insert(0, str(despec_root))
        from despecbridge.models.dreams_to_smited import (
            build_dreams_adapter_for_smited,
            build_mapper,
            DreamsToSmiTed,
        )
        from despecbridge.models.smited_decoder import load_smited

        mapper_ckpt_path = Path(args.smited_mapper_ckpt)
        ckpt = torch.load(mapper_ckpt_path, map_location="cpu")
        ckpt_args = ckpt.get("args", {})
        if not ckpt_args:
            raise SystemExit(f"Mapper checkpoint {mapper_ckpt_path} missing 'args' dict.")

        cond_dim = int(ckpt_args.get("cond_dim", 512))
        spec_bins = int(ckpt_args.get("spec_bins", 2048))
        dreams_ckpt = ckpt_args.get(
            "dreams_ckpt", "/cluster/tufts/liulab/yiwan01/SpecBridge/data/ssl_model.ckpt"
        )

        # Build spec encoder (DreaMS adapter) as in De-SpecBridge eval scripts
        spec_encoder = build_dreams_adapter_for_smited(
            dreams_ckpt=dreams_ckpt,
            cond_dim=cond_dim,
            spec_bins=spec_bins,
        )
        if "spec_encoder" in ckpt:
            spec_encoder.load_state_dict(ckpt["spec_encoder"], strict=False)

        d_smited = int(ckpt_args.get("d_smited", 768))
        mapper = build_mapper(
            cond_dim,
            d_smited,
            n_blocks=int(ckpt_args.get("mapper_blocks", 2)),
            hidden=int(ckpt_args.get("mapper_hidden", 512)),
        )
        mapper_state = ckpt["mapper"]
        if mapper_state and list(mapper_state.keys())[0].startswith("module."):
            mapper_state = {k.replace("module.", ""): v for k, v in mapper_state.items()}
        mapper.load_state_dict(mapper_state, strict=True)

        smited_wrapper = load_smited(
            model_name=ckpt_args.get("smited_model", "ibm-research/materials.smi-ted"),
            device=device,
            use_original_weights=bool(ckpt_args.get("use_original_weights", False)),
        )
        smited_wrapper.eval()

        smited_mapper_model = DreamsToSmiTed(
            spec_encoder=spec_encoder,
            mapper=mapper,
            smited=smited_wrapper,
            freeze_spec=True,
            freeze_decoder=True,
        ).to(device)
        smited_mapper_model.eval()

    # Library meta and vectors
    meta_df = load_meta(lib)
    smiles_values = meta_df["smiles"].to_numpy(copy=False)
    formula_values = meta_df["formula"].to_numpy(copy=False) if "formula" in meta_df.columns else None
    index_smi_path = lib / "index_smi.faiss"
    index_chem_path = lib / "index_chem.faiss"
    index_smi = None
    index_chem = None

    candidate_map = _load_candidate_map(args.candidate_json) if args.candidate_json else None
    if candidate_map and args.candidate_key_field == "formula":
        raw_key_count = len(candidate_map)
        raw_formula_key_count = sum(1 for key in candidate_map if _looks_like_formula(_normalize_formula(key)))
        candidate_map = _coerce_candidate_map_to_formula(candidate_map)
        if raw_formula_key_count != raw_key_count:
            print(
                f"Coerced candidate map from {raw_key_count} raw keys to {len(candidate_map)} formula buckets "
                f"for non-oracle retrieval."
            )
        else:
            print(f"Loaded formula-keyed candidate map with {len(candidate_map)} formula buckets.")
    elif candidate_map and args.candidate_key_field == "smiles_gt":
        print(
            "Warning: --candidate-key-field smiles_gt is oracle-only; it uses ground-truth SMILES "
            "to choose the candidate pool."
        )

    records = load_mgf_spectra(
        args.mgf_path, spec_bins=args.spec_bins, max_mz=args.max_mz, max_peaks=args.max_peaks
    )
    if args.limit:
        records = records[: args.limit]
    if not records:
        raise SystemExit(f"No usable spectra found in {args.mgf_path}")
    spectra_binned = np.stack([r["binned"] for r in records], axis=0).astype(np.float32)
    meta = build_meta_peaks(records, args.max_peaks)

    # Instantiate SpectrumEmbedder only when needed (avoid double-loading DreaMS for Variant A + pretrained SMI-TED)
    if args.variant in ("B", "C") or (args.variant == "A" and smited_mapper_model is None):
        spec_embedder = SpectrumEmbedder(
            specbridge_ckpt=args.specbridge_ckpt,
            dreams_ckpt=args.dreams_ckpt,
            device=args.device,
            normalize=False,
            use_lightweight=False,
            chemberta_model=getattr(args, "chemberta_model", "Derify/ChemBERTa_augmented_pubchem_13m"),
        )
    else:
        spec_embedder = None

    # ChemBERTa queries: use SpecBridge chemberta mapper directly (no M_chem needed)
    if args.variant in ("B", "C"):
        if spec_embedder is None:
            raise SystemExit("Internal error: SpectrumEmbedder missing for ChemBERTa variants.")
        q_chem = spec_embedder.encode(spectra_binned, meta, batch_size=32)
        q_chem = l2_normalize(q_chem)
    else:
        q_chem = None

    # SMI-TED queries (Variant A only)
    q_smi = None
    if args.variant == "A":
        if smited_mapper_model is not None:
            # Use existing De-SpecBridge DreamsToSmiTed mapper directly on spectra + meta,
            # but in manageable batches to avoid GPU OOM.
            all_latents = []
            batch_size = 32
            total = spectra_binned.shape[0]
            with torch.no_grad():
                for start in range(0, total, batch_size):
                    end = min(total, start + batch_size)
                    spectra_t = torch.tensor(
                        spectra_binned[start:end], dtype=torch.float32, device=device
                    )
                    meta_t: dict[str, torch.Tensor] = {}
                    for k, v in meta.items():
                        if isinstance(v, torch.Tensor) and v.shape[0] == total:
                            meta_t[k] = v[start:end].to(device)
                        else:
                            meta_t[k] = v
                    z_smited = smited_mapper_model(spectra_t, meta_t)
                    all_latents.append(z_smited.detach().cpu().numpy().astype(np.float32))
            if all_latents:
                q_smi = np.concatenate(all_latents, axis=0)
            else:
                q_smi = np.zeros((0, 0), dtype=np.float32)
        else:
            if M_smi is None or d_spec is None or spec_embedder is None:
                raise SystemExit("Variant A requires either --smited-mapper-ckpt or Spec-RAG M_smi in mappers.pt (with SpectrumEmbedder).")
            x_spec = spec_embedder.encode_spec_only(spectra_binned, meta, batch_size=32)
            with torch.no_grad():
                x = torch.tensor(x_spec, dtype=torch.float32, device=device)
                q_smi = M_smi(x).cpu().numpy()
        q_smi = l2_normalize(q_smi)

    use_direct_candidate_pool = candidate_map is not None and args.variant in ("B", "C")
    exact_vectors = None
    vector_path = lib / ("vectors_smi.npy" if args.variant == "A" else "vectors_chem.npy")
    if (args.formula_filter or (candidate_map and not use_direct_candidate_pool)) and vector_path.exists():
        exact_vectors = np.load(vector_path, mmap_mode="r")

    candidate_lookup = {}
    if candidate_map:
        query_keys = [
            _normalize_candidate_key(rec.get(args.candidate_key_field, ""))
            for rec in records
        ]
        if use_direct_candidate_pool:
            covered = sum(1 for key in query_keys if key in candidate_map)
            print(
                f"Using direct candidate-pool reranking from {args.candidate_json} "
                f"with `{args.candidate_key_field}` for {covered}/{len(query_keys)} queries."
            )
        else:
            print(f"Building candidate lookup from {args.candidate_json} using `{args.candidate_key_field}`...")
            candidate_lookup = _build_query_candidate_index(candidate_map, query_keys, smiles_values)
            covered = sum(1 for key in query_keys if key in candidate_lookup)
            print(f"Candidate pools available for {covered}/{len(query_keys)} queries.")
            if exact_vectors is None:
                print(f"{vector_path.name} not found; candidate pool reranking is disabled.")

    formula_lookup = {}
    formula_canonical_cache = {}
    if args.formula_filter and formula_values is not None:
        target_formulas = {
            _normalize_formula(rec.get("formula", ""))
            for rec in records
            if _normalize_formula(rec.get("formula", ""))
        }
        if target_formulas and exact_vectors is not None:
            print(f"Building formula lookup for {len(target_formulas)} query formulas...")
            formula_lookup = _build_query_formula_index(formula_values, target_formulas)
            print(f"Using exact same-formula reranking via {vector_path.name} (memory-mapped).")
        elif target_formulas:
            print(f"{vector_path.name} not found; formula filter will fall back to adaptive FAISS over-fetch.")

    out_path = Path(args.out_jsonl)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    mode_counts = {"candidate_pool_direct": 0, "candidate_pool": 0, "formula_exact": 0, "global_faiss": 0}
    candidate_embedding_cache = {}
    chem_candidate_embedder = None
    smi_candidate_encoder = None
    with open(out_path, "w") as f:
        for i, rec in enumerate(records):
            res = {"smiles_gt": rec.get("smiles_gt", ""), "candidates": [], "variant": args.variant}
            target_formula = rec.get("formula", "") if args.formula_filter else ""
            query_vec = q_smi[i] if args.variant == "A" else q_chem[i]
            query_batch = q_smi[i : i + 1] if args.variant == "A" else q_chem[i : i + 1]
            idx = None
            retrieval_mode = None

            query_key = _normalize_candidate_key(rec.get(args.candidate_key_field, "")) if candidate_map else ""
            if candidate_map and use_direct_candidate_pool:
                candidate_smiles = candidate_map.get(query_key)
                if candidate_smiles:
                    direct_candidates, chem_candidate_embedder, smi_candidate_encoder = _rank_candidate_smiles_direct(
                        query_vec=query_vec,
                        candidate_smiles=candidate_smiles,
                        k=args.K,
                        variant=args.variant,
                        device=args.device,
                        chemberta_model=args.chemberta_model,
                        despecbridge_path=args.despecbridge_path,
                        candidate_embedding_cache=candidate_embedding_cache,
                        chem_candidate_embedder=chem_candidate_embedder,
                        smi_candidate_encoder=smi_candidate_encoder,
                    )
                    if direct_candidates is not None:
                        res["candidates"].extend(direct_candidates)
                        retrieval_mode = "candidate_pool_direct"
                        idx = []

            if idx is None and candidate_lookup:
                candidate_idx = _candidate_pool_indices(
                    query_key=query_key,
                    target_formula=target_formula,
                    candidate_lookup=candidate_lookup,
                    candidate_map=candidate_map,
                    formula_lookup=formula_lookup,
                    smiles_values=smiles_values,
                    formula_canonical_cache=formula_canonical_cache,
                )
                idx = _exact_subset_search(query_vec, candidate_idx, args.K, exact_vectors)
                if idx is not None:
                    retrieval_mode = "candidate_pool"

            if idx is None:
                idx = _exact_formula_subset_search(query_vec, args.K, target_formula, formula_lookup, exact_vectors)
                if idx is not None:
                    retrieval_mode = "formula_exact"

            if idx is None:
                if args.variant == "A":
                    if index_smi is None:
                        index_smi = _load_global_index_or_die(index_smi_path, ef_search=getattr(args, "ef_search", None))
                else:
                    if index_chem is None:
                        index_chem = _load_global_index_or_die(index_chem_path, ef_search=getattr(args, "ef_search", None))
                idx = _search_with_formula_backfill(
                    index=index_smi if args.variant == "A" else index_chem,
                    query=query_batch,
                    k=args.K,
                    formulas=formula_values,
                    target_formula=target_formula,
                    min_fetch=args.formula_min_fetch,
                    max_fetch=args.formula_max_fetch,
                    fetch_multiplier=args.formula_fetch_multiplier,
                )
                retrieval_mode = "global_faiss"
            mode_counts[retrieval_mode] = mode_counts.get(retrieval_mode, 0) + 1
            res["retrieval_mode"] = retrieval_mode
            if retrieval_mode != "candidate_pool_direct":
                for j in idx:
                    j = int(j)
                    if j < 0 or j >= len(smiles_values):
                        continue
                    smi = str(smiles_values[j])
                    formula = _normalize_formula(formula_values[j]) if formula_values is not None else ""
                    res["candidates"].append({"smiles": smi, "formula": formula})
            f.write(json.dumps(res, ensure_ascii=False) + "\n")
    print(f"Wrote {out_path} ({len(records)} spectra)")
    print("Retrieval mode counts:", json.dumps(mode_counts, sort_keys=True))


if __name__ == "__main__":
    main()