File size: 10,149 Bytes
d126496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Figure completion retrieval benchmark.

Leave-one-out: for each patent, mask one view (by default the top plan view,
or the hardest available). Given embeddings of N-1 sibling views as context,
retrieve the correct masked view from a pool of 100 candidates.

Baselines:
  random     — chance (1%)
  single     — embed only the perspective view, retrieve
  multi      — average CLIP embeddings of all N-1 context views, retrieve
  vlm        — (future) use VLM to describe missing view, embed description

Usage:
    python scripts/eval/retrieval_eval.py \
        --embeddings data/embeddings/embeddings_2022_vitl14.parquet \
        --enriched   data/enriched/enriched_2022.parquet \
        --n          500 \
        --pool-size  100 \
        --out        results/retrieval_eval.json
"""

import argparse
import json
import random
import re
from collections import defaultdict
from pathlib import Path

import faiss
import numpy as np
import pandas as pd
from tqdm import tqdm


# ── viewpoint helpers ─────────────────────────────────────────────────────────

def parse_viewpoint(drawing_desc: str, fig_num: int) -> str:
    pat = re.compile(
        rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
        re.IGNORECASE,
    )
    m = pat.search(drawing_desc or "")
    return m.group(1).strip().lower() if m else ""


TARGET_PRIORITY = [
    # (label_fragment, difficulty)
    ("cross-sectional", "very_hard"),
    ("cross section",   "very_hard"),
    ("enlarged",        "hard"),
    ("detail",          "hard"),
    ("top plan",        "hard"),
    ("bottom plan",     "medium"),
    ("rear elevation",  "medium"),
    ("rear elev",       "medium"),
    ("side elev",       "easy"),
    ("front elev",      "easy"),
    ("perspective",     "baseline"),
]


def pick_target_view(viewpoints: list[str]) -> tuple[int, str]:
    """Pick the highest-priority masking target. Returns (index, difficulty)."""
    for frag, difficulty in TARGET_PRIORITY:
        for i, vp in enumerate(viewpoints):
            if frag in vp:
                return i, difficulty
    # Fallback: pick any non-first view
    return 1 if len(viewpoints) > 1 else 0, "unknown"


# ── retrieval ─────────────────────────────────────────────────────────────────

def build_faiss_index(vectors: np.ndarray) -> faiss.IndexFlatIP:
    """Build an inner-product FAISS index (cosine sim on L2-normed vectors)."""
    dim = vectors.shape[1]
    index = faiss.IndexFlatIP(dim)
    index.add(vectors.astype(np.float32))
    return index


def retrieve(
    query_vec: np.ndarray,        # (dim,)
    candidate_indices: list[int], # indices into the full embedding matrix
    all_vectors: np.ndarray,
    correct_idx: int,             # index into candidate_indices
) -> dict:
    """Score retrieval: rank correct candidate among candidates by cosine sim."""
    cand_vecs = all_vectors[candidate_indices].astype(np.float32)
    q = query_vec.astype(np.float32).reshape(1, -1)
    sims = (cand_vecs @ q.T).squeeze()
    ranks = np.argsort(-sims)  # descending
    rank_of_correct = int(np.where(ranks == correct_idx)[0][0]) + 1  # 1-indexed
    return {
        "rank": rank_of_correct,
        "r1":   int(rank_of_correct <= 1),
        "r5":   int(rank_of_correct <= 5),
        "r10":  int(rank_of_correct <= 10),
        "sim_correct": float(sims[correct_idx]),
        "sim_top1":    float(sims[ranks[0]]),
    }


# ── main eval ─────────────────────────────────────────────────────────────────

def run_eval(
    embeddings_path: str,
    enriched_path:   str,
    n: int,
    pool_size: int,
    out_path: str,
    seed: int = 42,
):
    rng = random.Random(seed)

    print("Loading embeddings...")
    emb_df = pd.read_parquet(embeddings_path)
    fig_id_to_idx = {fid: i for i, fid in enumerate(emb_df["figure_id"])}
    all_vecs = np.vstack(emb_df["embedding"].tolist()).astype(np.float32)
    # Ensure unit norm for cosine sim
    norms = np.linalg.norm(all_vecs, axis=1, keepdims=True)
    all_vecs = all_vecs / np.maximum(norms, 1e-8)
    print(f"Embeddings: {all_vecs.shape}")

    print("Loading enriched metadata...")
    df = pd.read_parquet(enriched_path)
    df["viewpoint_parsed"] = df.apply(
        lambda r: parse_viewpoint(r.get("drawing_description", ""), r["figure_number"]),
        axis=1,
    )

    # Keep only figures with embeddings
    df = df[df["figure_id"].isin(fig_id_to_idx)].copy()
    df["_vec_idx"] = df["figure_id"].map(fig_id_to_idx)

    # Group by patent
    patent_groups = {
        pid: g.sort_values("figure_number")
        for pid, g in df.groupby("patent_id")
        if len(g) >= 3
    }

    # Build Locarno-class → figure_id list for distractor sampling
    class_to_fids = defaultdict(list)
    for _, row in df.iterrows():
        cls = row.get("class") or row.get("locarno_class") or "unknown"
        class_to_fids[str(cls)].append(row["figure_id"])

    # Sample eligible patents
    all_pids = list(patent_groups.keys())
    rng.shuffle(all_pids)
    eval_pids = all_pids[:n]
    print(f"Evaluating {len(eval_pids)} patents (pool_size={pool_size})")

    by_difficulty = defaultdict(lambda: {"r1": 0, "r5": 0, "r10": 0, "n": 0})
    results = []

    for pid in tqdm(eval_pids):
        group = patent_groups[pid]
        fids = group["figure_id"].tolist()
        vps  = group["viewpoint_parsed"].tolist()
        vec_idxs = group["_vec_idx"].tolist()
        cls = str(group["class"].iloc[0] if "class" in group.columns else "unknown")

        # Pick target view to mask
        target_pos, difficulty = pick_target_view(vps)
        target_fid = fids[target_pos]
        target_vec_idx = vec_idxs[target_pos]

        context_idxs = [vi for i, vi in enumerate(vec_idxs) if i != target_pos]
        if not context_idxs:
            continue

        # Build query: average of context embeddings
        query_vec = all_vecs[context_idxs].mean(axis=0)
        query_vec /= max(np.linalg.norm(query_vec), 1e-8)

        # Build candidate pool: target + (pool_size - 1) distractors from same class
        distractors_pool = [
            f for f in class_to_fids.get(cls, [])
            if f not in set(fids) and f in fig_id_to_idx
        ]
        rng.shuffle(distractors_pool)
        distractors = distractors_pool[: pool_size - 1]
        if len(distractors) < pool_size - 1:
            # Fill from any other patent
            other_fids = [
                f for f in df["figure_id"].tolist()
                if f not in set(fids) and f not in set(distractors) and f in fig_id_to_idx
            ]
            rng.shuffle(other_fids)
            distractors += other_fids[: pool_size - 1 - len(distractors)]

        if len(distractors) < 3:
            continue

        candidates = distractors[: pool_size - 1]
        # Insert correct answer at random position
        insert_pos = rng.randint(0, len(candidates))
        candidates.insert(insert_pos, target_fid)
        candidate_vec_idxs = [fig_id_to_idx[f] for f in candidates]

        # Multi-view retrieval
        score = retrieve(query_vec, candidate_vec_idxs, all_vecs, insert_pos)
        # Single-view retrieval (perspective only, if available)
        persp_pos = next((i for i, v in enumerate(vps) if "perspective" in v and i != target_pos), None)
        if persp_pos is not None:
            single_score = retrieve(all_vecs[vec_idxs[persp_pos]], candidate_vec_idxs, all_vecs, insert_pos)
        else:
            single_score = score  # fallback

        for bucket in [difficulty, "all"]:
            by_difficulty[bucket]["r1"]  += score["r1"]
            by_difficulty[bucket]["r5"]  += score["r5"]
            by_difficulty[bucket]["r10"] += score["r10"]
            by_difficulty[bucket]["n"]   += 1

        results.append({
            "patent_id":      pid,
            "target_view":    vps[target_pos],
            "difficulty":     difficulty,
            "pool_size":      len(candidates),
            "multi_view":     score,
            "single_view":    single_score,
        })

    # Summary
    print("\n" + "=" * 60)
    print("RETRIEVAL EVAL RESULTS")
    print(f"{'Difficulty':<16} {'N':>5}  {'R@1':>6}  {'R@5':>6}  {'R@10':>6}  {'Chance R@1':>10}")
    print("-" * 60)
    for diff in ["all", "baseline", "easy", "medium", "hard", "very_hard"]:
        b = by_difficulty[diff]
        if b["n"] == 0:
            continue
        chance = 100.0 / pool_size
        print(
            f"{diff:<16} {b['n']:>5}  "
            f"{b['r1']/b['n']:>5.1%}  "
            f"{b['r5']/b['n']:>5.1%}  "
            f"{b['r10']/b['n']:>5.1%}  "
            f"{chance:>9.1f}%"
        )

    output = {
        "summary": {d: {k: v/b["n"] if k != "n" else v for k, v in b.items()}
                    for d, b in by_difficulty.items()},
        "pool_size": pool_size,
        "n_patents": len(results),
        "results":   results,
    }
    Path(out_path).parent.mkdir(parents=True, exist_ok=True)
    with open(out_path, "w") as f:
        json.dump(output, f, indent=2)
    print(f"\nFull results → {out_path}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--embeddings", default="data/embeddings/embeddings_2022_vitl14.parquet")
    parser.add_argument("--enriched",   default="data/enriched/enriched_2022.parquet")
    parser.add_argument("--n",          type=int, default=500)
    parser.add_argument("--pool-size",  type=int, default=100)
    parser.add_argument("--out",        default="results/retrieval_eval.json")
    parser.add_argument("--seed",       type=int, default=42)
    args = parser.parse_args()
    run_eval(args.embeddings, args.enriched, args.n, args.pool_size, args.out, args.seed)


if __name__ == "__main__":
    main()