1026 lines
34 KiB
Python
1026 lines
34 KiB
Python
#!/usr/bin/env python3
|
|
"""Restored offline experiment: semantic_topic_fallback_v1.
|
|
|
|
Historical exploratory evaluation-only variant (NOT production).
|
|
Restored from agent transcript after cleanup deletion; never committed to git.
|
|
|
|
CLI (via evaluate_author_patent_search.py):
|
|
python evaluate_author_patent_search.py experiment-semantic-topic-fallback
|
|
|
|
Does not modify:
|
|
- filter_patents_by_ipc_topic_mapping
|
|
- gold labels
|
|
- Elasticsearch indexes
|
|
- API / production paths
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import csv
|
|
import json
|
|
import sys
|
|
from collections import Counter
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
DATA_DIR = SCRIPT_DIR / "data" / "author_patent_evaluation"
|
|
AGGREGATE_DIR = DATA_DIR / "aggregate_field_analysis"
|
|
DIAGNOSIS_DIR = AGGREGATE_DIR / "field_error_analysis"
|
|
|
|
# Ensure service src is importable for embedding model (same as evaluate script).
|
|
sys.path.insert(0, str(SCRIPT_DIR.parent.parent / "src" / "main"))
|
|
|
|
_FIELD_NEARBY = {
|
|
"Medicine / Health Sciences": {
|
|
"Biology / Biotechnology",
|
|
"Chemistry",
|
|
"Health Professions",
|
|
"Neuroscience",
|
|
"Immunology and Microbiology",
|
|
"Pharmacology, Toxicology and Pharmaceutics",
|
|
"Nursing",
|
|
"Dentistry",
|
|
"Agricultural and Biological Sciences",
|
|
},
|
|
"Biology / Biotechnology": {
|
|
"Medicine / Health Sciences",
|
|
"Chemistry",
|
|
"Agricultural and Biological Sciences",
|
|
"Immunology and Microbiology",
|
|
"Environmental Science",
|
|
},
|
|
"Physics": {"Chemistry", "Engineering", "Materials Science", "Computer Science"},
|
|
"Chemistry": {
|
|
"Biology / Biotechnology",
|
|
"Medicine / Health Sciences",
|
|
"Materials Science",
|
|
"Physics",
|
|
"Pharmacology, Toxicology and Pharmaceutics",
|
|
},
|
|
"Engineering": {
|
|
"Physics",
|
|
"Computer Science",
|
|
"Materials Science",
|
|
"Energy",
|
|
"Mathematics",
|
|
},
|
|
"Other": {
|
|
"Medicine / Health Sciences",
|
|
"Biology / Biotechnology",
|
|
"Chemistry",
|
|
"Engineering",
|
|
"Physics",
|
|
},
|
|
}
|
|
|
|
|
|
def _utc_stamp() -> str:
|
|
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
|
|
|
|
def _load_json(path: Path) -> dict[str, Any]:
|
|
return json.loads(path.read_text(encoding="utf-8-sig"))
|
|
|
|
|
|
def _write_json(path: Path, payload: Any) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
|
|
|
|
def _write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str]) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open("w", encoding="utf-8", newline="") as fh:
|
|
w = csv.DictWriter(fh, fieldnames=fieldnames, extrasaction="ignore")
|
|
w.writeheader()
|
|
for row in rows:
|
|
w.writerow(row)
|
|
|
|
|
|
def _format_metric(value: Any) -> str:
|
|
if value is None:
|
|
return "—"
|
|
if isinstance(value, float):
|
|
return f"{value:.3f}"
|
|
return str(value)
|
|
|
|
|
|
def _prf_from_counts(tp: int, fp: int, fn: int, tn: int) -> dict[str, Any]:
|
|
precision = tp / (tp + fp) if (tp + fp) else None
|
|
recall = tp / (tp + fn) if (tp + fn) else None
|
|
f1 = (
|
|
2 * precision * recall / (precision + recall)
|
|
if precision is not None and recall is not None and (precision + recall) > 0
|
|
else None
|
|
)
|
|
return {
|
|
"tp": tp,
|
|
"fp": fp,
|
|
"fn": fn,
|
|
"tn": tn,
|
|
"precision": precision,
|
|
"recall": recall,
|
|
"f1": f1,
|
|
}
|
|
|
|
|
|
def _outcome(gold: bool, kept: bool) -> str:
|
|
if gold and kept:
|
|
return "TP"
|
|
if (not gold) and kept:
|
|
return "FP"
|
|
if gold and (not kept):
|
|
return "FN"
|
|
return "TN"
|
|
|
|
|
|
def _metrics_from_rows(rows: list[dict[str, Any]], kept_key: str) -> dict[str, Any]:
|
|
tp = fp = fn = tn = 0
|
|
for row in rows:
|
|
gold = row.get("gold")
|
|
kept = row.get(kept_key)
|
|
if gold is None or kept is None:
|
|
continue
|
|
outcome = _outcome(bool(gold), bool(kept))
|
|
if outcome == "TP":
|
|
tp += 1
|
|
elif outcome == "FP":
|
|
fp += 1
|
|
elif outcome == "FN":
|
|
fn += 1
|
|
elif outcome == "TN":
|
|
tn += 1
|
|
return _prf_from_counts(tp, fp, fn, tn)
|
|
|
|
|
|
def _mode_name(values: list[str | None]) -> str | None:
|
|
cleaned = [v for v in values if v]
|
|
if not cleaned:
|
|
return None
|
|
return Counter(cleaned).most_common(1)[0][0]
|
|
|
|
|
|
def _field_compatible(author_field: str | None, topic_field: str | None) -> bool:
|
|
if not author_field or not topic_field:
|
|
return False
|
|
if author_field == topic_field:
|
|
return True
|
|
return topic_field in _FIELD_NEARBY.get(author_field, set())
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Experiment: semantic_topic_fallback_v1 (evaluation-path only)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
SEMANTIC_FALLBACK_DIR = AGGREGATE_DIR / "experiments" / "semantic_topic_fallback_v1"
|
|
SEMANTIC_FALLBACK_THRESHOLDS = (0.70, 0.75, 0.80)
|
|
SEMANTIC_FALLBACK_DEFAULT_THRESHOLD = 0.75
|
|
SEMANTIC_FALLBACK_VALIDATION = "exploratory_replay_on_diagnosed_fixed_sample"
|
|
|
|
_SEM_MEDICINE = frozenset(
|
|
{
|
|
"medicine",
|
|
"medicine / health sciences",
|
|
"health sciences",
|
|
"health professions",
|
|
"nursing",
|
|
"dentistry",
|
|
}
|
|
)
|
|
_SEM_TELECOM = frozenset(
|
|
{
|
|
"engineering",
|
|
"computer science",
|
|
"electrical and electronic engineering",
|
|
}
|
|
)
|
|
_SEM_CHEMISTRY = frozenset(
|
|
{
|
|
"chemistry",
|
|
"chemical engineering",
|
|
"materials science",
|
|
"pharmacology, toxicology and pharmaceutics",
|
|
}
|
|
)
|
|
_SEM_BIOLOGY = frozenset(
|
|
{
|
|
"biology / biotechnology",
|
|
"biology",
|
|
"biotechnology",
|
|
"agricultural and biological sciences",
|
|
"immunology and microbiology",
|
|
}
|
|
)
|
|
_SEM_PHYSICS = frozenset({"physics", "materials science"})
|
|
_SEM_FOREIGN = frozenset(
|
|
{
|
|
"arts and humanities",
|
|
"social sciences",
|
|
"business, management and accounting",
|
|
"economics, econometrics and finance",
|
|
"psychology",
|
|
}
|
|
)
|
|
|
|
|
|
def _sem_norm_field(value: Any) -> str:
|
|
return " ".join(str(value or "").strip().casefold().split())
|
|
|
|
|
|
def _sem_topic_embed_text(topic: dict[str, Any] | None) -> str:
|
|
if not topic:
|
|
return ""
|
|
parts: list[str] = []
|
|
name = topic.get("topic") or topic.get("topic_display_name") or ""
|
|
if name:
|
|
parts.append(str(name))
|
|
keywords = topic.get("keywords")
|
|
if isinstance(keywords, list):
|
|
kw = ", ".join(str(k).strip() for k in keywords if str(k).strip())
|
|
if kw:
|
|
parts.append(f"Keywords: {kw}")
|
|
elif keywords:
|
|
parts.append(f"Keywords: {keywords}")
|
|
for key in ("subfield", "field", "domain"):
|
|
if topic.get(key):
|
|
parts.append(f"{key}: {topic[key]}")
|
|
return " | ".join(parts)
|
|
|
|
|
|
def _sem_family_from_field(field: Any) -> str | None:
|
|
f = _sem_norm_field(field)
|
|
if not f:
|
|
return None
|
|
if f in _SEM_MEDICINE or "medicine" in f or "health" in f:
|
|
return "medicine"
|
|
if f in _SEM_BIOLOGY or "biology" in f or "biotechnolog" in f:
|
|
return "biology"
|
|
if f in _SEM_CHEMISTRY or f == "chemistry":
|
|
return "chemistry"
|
|
if f in _SEM_PHYSICS or f == "physics":
|
|
return "physics"
|
|
if f in _SEM_TELECOM or f == "engineering" or "computer" in f:
|
|
return "telecom_or_engineering"
|
|
if f in _SEM_FOREIGN or "arts" in f or "social sciences" in f:
|
|
return "foreign"
|
|
return "other"
|
|
|
|
|
|
def _sem_families_from_ipc(codes: list[str] | None) -> set[str]:
|
|
families: set[str] = set()
|
|
for code in codes or []:
|
|
sym = str(code).upper().replace(" ", "")
|
|
if sym.startswith(("H03", "H04")):
|
|
families.add("telecom_or_engineering")
|
|
if sym.startswith(("A61", "G16H")):
|
|
families.add("medicine")
|
|
if sym.startswith(("C07", "C08", "C09")):
|
|
families.add("chemistry")
|
|
if sym.startswith("C12"):
|
|
families.add("biology")
|
|
if sym.startswith(("G01", "G02")):
|
|
families.add("physics")
|
|
if sym.startswith("H01"):
|
|
families.add("telecom_or_engineering")
|
|
return families
|
|
|
|
|
|
def _sem_patent_families(cand: dict[str, Any]) -> set[str]:
|
|
families = _sem_families_from_ipc(list(cand.get("ipc_cpc_codes") or []))
|
|
for topic in cand.get("mapped_topics") or []:
|
|
fam = _sem_family_from_field(topic.get("field"))
|
|
if fam:
|
|
families.add(fam)
|
|
return families
|
|
|
|
|
|
def _sem_author_families(cand: dict[str, Any]) -> set[str]:
|
|
families: set[str] = set()
|
|
for topic in cand.get("author_topics") or []:
|
|
fam = _sem_family_from_field(topic.get("field"))
|
|
if fam:
|
|
families.add(fam)
|
|
for field in (
|
|
cand.get("author_openalex_primary_field"),
|
|
cand.get("evaluation_field"),
|
|
):
|
|
fam = _sem_family_from_field(field)
|
|
if fam:
|
|
families.add(fam)
|
|
return families
|
|
|
|
|
|
def _sem_lookup_topic_field(
|
|
topics: list[dict[str, Any]], topic_name: str | None
|
|
) -> str | None:
|
|
if not topic_name:
|
|
return None
|
|
for topic in topics:
|
|
name = topic.get("topic") or topic.get("topic_display_name")
|
|
if name == topic_name:
|
|
return topic.get("field")
|
|
return None
|
|
|
|
|
|
def _sem_author_anchor_field(cand: dict[str, Any]) -> str | None:
|
|
for value in (
|
|
cand.get("author_openalex_primary_field"),
|
|
cand.get("evaluation_field"),
|
|
):
|
|
if value:
|
|
return str(value)
|
|
fields = [
|
|
t.get("field") for t in (cand.get("author_topics") or []) if t.get("field")
|
|
]
|
|
return _mode_name(fields)
|
|
|
|
|
|
def _normalize_eval_field(field: str | None) -> str | None:
|
|
if not field:
|
|
return None
|
|
if field in _FIELD_NEARBY:
|
|
return field
|
|
f = _sem_norm_field(field)
|
|
aliases = {
|
|
"medicine": "Medicine / Health Sciences",
|
|
"health sciences": "Medicine / Health Sciences",
|
|
"biology": "Biology / Biotechnology",
|
|
"biotechnology": "Biology / Biotechnology",
|
|
"biology / biotechnology": "Biology / Biotechnology",
|
|
"chemistry": "Chemistry",
|
|
"physics": "Physics",
|
|
"engineering": "Engineering",
|
|
}
|
|
return aliases.get(f, field)
|
|
|
|
|
|
def _semantic_pair_field_compatible(
|
|
cand: dict[str, Any],
|
|
*,
|
|
best_patent_topic: str | None,
|
|
) -> bool:
|
|
"""Require author field ↔ best patent-topic field compatibility (nearby ok)."""
|
|
author_field = _normalize_eval_field(_sem_author_anchor_field(cand))
|
|
patent_field = _normalize_eval_field(
|
|
_sem_lookup_topic_field(list(cand.get("mapped_topics") or []), best_patent_topic)
|
|
)
|
|
if not author_field or not patent_field:
|
|
return False
|
|
if author_field == patent_field:
|
|
return True
|
|
author_fam = _sem_family_from_field(author_field)
|
|
patent_fam = _sem_family_from_field(patent_field)
|
|
if author_fam and patent_fam and author_fam == patent_fam:
|
|
return True
|
|
compatible = {
|
|
"biology": {"medicine", "chemistry"},
|
|
"medicine": {"biology", "chemistry"},
|
|
"chemistry": {"biology", "medicine", "physics"},
|
|
"physics": {"chemistry", "telecom_or_engineering"},
|
|
"telecom_or_engineering": {"physics"},
|
|
}
|
|
if author_fam and patent_fam and patent_fam in compatible.get(author_fam, set()):
|
|
return True
|
|
return _field_compatible(author_field, patent_field)
|
|
|
|
|
|
def _semantic_domain_conflict(cand: dict[str, Any]) -> tuple[bool, str | None]:
|
|
"""General domain-conflict check (no patent/author/topic-id hardcoding)."""
|
|
patent = _sem_patent_families(cand)
|
|
author = _sem_author_families(cand)
|
|
author_field = _normalize_eval_field(_sem_author_anchor_field(cand))
|
|
author_fam = _sem_family_from_field(author_field) if author_field else None
|
|
|
|
if not patent:
|
|
return False, None
|
|
|
|
life = {"biology", "chemistry", "medicine"}
|
|
# Author-field anchored conflicts (catches Biology TNs with engineering patents).
|
|
if author_fam == "biology" and "telecom_or_engineering" in patent and not (
|
|
life & patent
|
|
):
|
|
return True, "engineering_telecom_patent_vs_biology_author"
|
|
if author_fam == "medicine" and "telecom_or_engineering" in patent and not (
|
|
life & patent
|
|
):
|
|
return True, "telecom_patent_vs_medical_author_profile"
|
|
if author_fam == "telecom_or_engineering" and "medicine" in patent:
|
|
if not (life & author):
|
|
return True, "medical_patent_vs_rf_telecom_author_profile"
|
|
|
|
if not author:
|
|
return False, None
|
|
|
|
if "telecom_or_engineering" in patent and "medicine" in author:
|
|
if not ({"telecom_or_engineering", "physics"} & author):
|
|
return True, "telecom_patent_vs_medical_author_profile"
|
|
|
|
if "medicine" in patent and "telecom_or_engineering" in author:
|
|
if not (life & author):
|
|
return True, "medical_patent_vs_rf_telecom_author_profile"
|
|
|
|
if "chemistry" in patent:
|
|
non_foreign = author - {"foreign", "other"}
|
|
if not non_foreign and "foreign" in author:
|
|
return True, "chemistry_patent_vs_foreign_author_profile"
|
|
if author <= {"foreign"}:
|
|
return True, "chemistry_patent_vs_foreign_author_profile"
|
|
|
|
if "foreign" in patent and "chemistry" in author and not (
|
|
{"chemistry", "biology", "medicine", "physics"} & patent
|
|
):
|
|
return True, "foreign_patent_topics_vs_chemistry_author"
|
|
|
|
return False, None
|
|
|
|
|
|
def _exact_topic_or_subfield_match(cand: dict[str, Any]) -> bool:
|
|
if cand.get("topic_overlap") is True or cand.get("subfield_overlap") is True:
|
|
return True
|
|
if cand.get("shared_topic_ids"):
|
|
return True
|
|
if cand.get("shared_subfield_ids"):
|
|
return True
|
|
return False
|
|
|
|
|
|
def decide_semantic_topic_fallback_v1(
|
|
cand: dict[str, Any],
|
|
*,
|
|
semantic_similarity: float | None,
|
|
best_patent_topic: str | None,
|
|
best_author_topic: str | None,
|
|
threshold: float = SEMANTIC_FALLBACK_DEFAULT_THRESHOLD,
|
|
) -> dict[str, Any]:
|
|
"""Exact topic/subfield keep, else semantic fallback with domain guard."""
|
|
domain_conflict, conflict_reason = _semantic_domain_conflict(cand)
|
|
|
|
if _exact_topic_or_subfield_match(cand):
|
|
return {
|
|
"best_patent_topic": best_patent_topic,
|
|
"best_author_topic": best_author_topic,
|
|
"semantic_similarity": semantic_similarity,
|
|
"domain_conflict": domain_conflict,
|
|
"semantic_fallback_kept": True,
|
|
"semantic_fallback_reason": "exact_topic_or_subfield_id_overlap",
|
|
"domain_conflict_reason": conflict_reason,
|
|
}
|
|
|
|
if domain_conflict:
|
|
return {
|
|
"best_patent_topic": best_patent_topic,
|
|
"best_author_topic": best_author_topic,
|
|
"semantic_similarity": semantic_similarity,
|
|
"domain_conflict": True,
|
|
"semantic_fallback_kept": False,
|
|
"semantic_fallback_reason": f"rejected_domain_conflict:{conflict_reason}",
|
|
"domain_conflict_reason": conflict_reason,
|
|
}
|
|
|
|
if semantic_similarity is None:
|
|
return {
|
|
"best_patent_topic": best_patent_topic,
|
|
"best_author_topic": best_author_topic,
|
|
"semantic_similarity": None,
|
|
"domain_conflict": False,
|
|
"semantic_fallback_kept": False,
|
|
"semantic_fallback_reason": "rejected_missing_semantic_similarity",
|
|
"domain_conflict_reason": None,
|
|
}
|
|
|
|
if not _semantic_pair_field_compatible(cand, best_patent_topic=best_patent_topic):
|
|
return {
|
|
"best_patent_topic": best_patent_topic,
|
|
"best_author_topic": best_author_topic,
|
|
"semantic_similarity": semantic_similarity,
|
|
"domain_conflict": True,
|
|
"semantic_fallback_kept": False,
|
|
"semantic_fallback_reason": "rejected_incompatible_topic_fields",
|
|
"domain_conflict_reason": "best_pair_field_mismatch",
|
|
}
|
|
|
|
if semantic_similarity >= threshold:
|
|
return {
|
|
"best_patent_topic": best_patent_topic,
|
|
"best_author_topic": best_author_topic,
|
|
"semantic_similarity": semantic_similarity,
|
|
"domain_conflict": False,
|
|
"semantic_fallback_kept": True,
|
|
"semantic_fallback_reason": f"semantic_similarity>={threshold:.2f}",
|
|
"domain_conflict_reason": None,
|
|
}
|
|
|
|
return {
|
|
"best_patent_topic": best_patent_topic,
|
|
"best_author_topic": best_author_topic,
|
|
"semantic_similarity": semantic_similarity,
|
|
"domain_conflict": False,
|
|
"semantic_fallback_kept": False,
|
|
"semantic_fallback_reason": f"rejected_semantic_similarity<{threshold:.2f}",
|
|
"domain_conflict_reason": None,
|
|
}
|
|
|
|
|
|
def _pairwise_best_semantic_similarity(
|
|
patent_topics: list[dict[str, Any]],
|
|
author_topics: list[dict[str, Any]],
|
|
vectors_by_text: dict[str, Any],
|
|
) -> tuple[float | None, str | None, str | None]:
|
|
import numpy as np
|
|
|
|
best = -1.0
|
|
best_pt: str | None = None
|
|
best_at: str | None = None
|
|
for pt in patent_topics:
|
|
ptext = _sem_topic_embed_text(pt)
|
|
pvec = vectors_by_text.get(ptext)
|
|
if pvec is None or not ptext:
|
|
continue
|
|
for at in author_topics:
|
|
atext = _sem_topic_embed_text(at)
|
|
avec = vectors_by_text.get(atext)
|
|
if avec is None or not atext:
|
|
continue
|
|
score = float(np.dot(pvec, avec))
|
|
if score > best:
|
|
best = score
|
|
best_pt = str(pt.get("topic") or pt.get("topic_display_name") or "")
|
|
best_at = str(at.get("topic") or at.get("topic_display_name") or "")
|
|
if best < 0:
|
|
return None, None, None
|
|
return round(best, 6), best_pt, best_at
|
|
|
|
|
|
def _build_semantic_vectors(candidates: list[dict[str, Any]]) -> dict[str, Any]:
|
|
import numpy as np
|
|
from inse.util import get_model
|
|
|
|
texts: list[str] = []
|
|
seen: set[str] = set()
|
|
for cand in candidates:
|
|
for topic in list(cand.get("mapped_topics") or []) + list(
|
|
cand.get("author_topics") or []
|
|
):
|
|
text = _sem_topic_embed_text(topic)
|
|
if text and text not in seen:
|
|
seen.add(text)
|
|
texts.append(text)
|
|
if not texts:
|
|
return {}
|
|
model = get_model()
|
|
raw = model.encode(
|
|
texts,
|
|
batch_size=64,
|
|
show_progress_bar=True,
|
|
convert_to_numpy=True,
|
|
normalize_embeddings=True,
|
|
)
|
|
matrix = np.asarray(raw, dtype=np.float32)
|
|
return {text: matrix[i] for i, text in enumerate(texts)}
|
|
|
|
|
|
def _sem_field_label(cand: dict[str, Any]) -> str:
|
|
field = cand.get("evaluation_field") or "Other"
|
|
known = {
|
|
"Biology / Biotechnology",
|
|
"Chemistry",
|
|
"Engineering",
|
|
"Medicine / Health Sciences",
|
|
"Physics",
|
|
"Other",
|
|
}
|
|
return field if field in known else "Other"
|
|
|
|
|
|
def cmd_experiment_semantic_topic_fallback(args: argparse.Namespace) -> int:
|
|
"""Offline semantic topic fallback on the fixed 131 diagnosed candidates."""
|
|
del args # mode has no extra flags yet
|
|
diagnosis_path = DIAGNOSIS_DIR / "field_error_analysis.json"
|
|
if not diagnosis_path.is_file():
|
|
print(f"Missing diagnosis file: {diagnosis_path}", file=sys.stderr)
|
|
return 1
|
|
|
|
diagnosis = _load_json(diagnosis_path)
|
|
candidates = list(diagnosis.get("candidates") or [])
|
|
if len(candidates) != 131:
|
|
print(
|
|
f"Expected 131 fixed candidates, found {len(candidates)}",
|
|
file=sys.stderr,
|
|
)
|
|
return 1
|
|
|
|
print(f"Encoding topic texts for {len(candidates)} candidates...")
|
|
vectors = _build_semantic_vectors(candidates)
|
|
|
|
scored_rows: list[dict[str, Any]] = []
|
|
threshold_metrics: dict[str, dict[str, Any]] = {}
|
|
|
|
for cand in candidates:
|
|
sim, best_pt, best_at = _pairwise_best_semantic_similarity(
|
|
list(cand.get("mapped_topics") or []),
|
|
list(cand.get("author_topics") or []),
|
|
vectors,
|
|
)
|
|
row = {
|
|
"track": cand.get("track"),
|
|
"author_id": cand.get("author_id"),
|
|
"author_name": cand.get("author_name"),
|
|
"patent_id": cand.get("patent_id"),
|
|
"title": cand.get("title"),
|
|
"candidate_key": cand.get("candidate_key"),
|
|
"evaluation_field": _sem_field_label(cand),
|
|
"gold": cand.get("gold"),
|
|
"production_kept": cand.get("production_kept"),
|
|
"topic_only_kept": cand.get("topic_only_kept"),
|
|
"topic_overlap": cand.get("topic_overlap"),
|
|
"subfield_overlap": cand.get("subfield_overlap"),
|
|
"best_patent_topic": best_pt,
|
|
"best_author_topic": best_at,
|
|
"semantic_similarity": sim,
|
|
}
|
|
# Primary variant at default threshold
|
|
decision = decide_semantic_topic_fallback_v1(
|
|
cand,
|
|
semantic_similarity=sim,
|
|
best_patent_topic=best_pt,
|
|
best_author_topic=best_at,
|
|
threshold=SEMANTIC_FALLBACK_DEFAULT_THRESHOLD,
|
|
)
|
|
row.update(decision)
|
|
row["kept_production_baseline"] = bool(cand.get("production_kept"))
|
|
row["kept_semantic_topic_fallback_v1"] = bool(
|
|
decision["semantic_fallback_kept"]
|
|
)
|
|
# Threshold sweep columns
|
|
for thr in SEMANTIC_FALLBACK_THRESHOLDS:
|
|
dthr = decide_semantic_topic_fallback_v1(
|
|
cand,
|
|
semantic_similarity=sim,
|
|
best_patent_topic=best_pt,
|
|
best_author_topic=best_at,
|
|
threshold=thr,
|
|
)
|
|
key = f"kept_semantic_thr_{thr:.2f}".replace(".", "_")
|
|
row[key] = bool(dthr["semantic_fallback_kept"])
|
|
row[f"reason_thr_{thr:.2f}".replace(".", "_")] = dthr[
|
|
"semantic_fallback_reason"
|
|
]
|
|
scored_rows.append(row)
|
|
|
|
SEMANTIC_FALLBACK_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
variants = {
|
|
"production_baseline": "kept_production_baseline",
|
|
"semantic_topic_fallback_v1": "kept_semantic_topic_fallback_v1",
|
|
}
|
|
for thr in SEMANTIC_FALLBACK_THRESHOLDS:
|
|
variants[f"semantic_thr_{thr:.2f}"] = (
|
|
f"kept_semantic_thr_{thr:.2f}".replace(".", "_")
|
|
)
|
|
|
|
pooled: dict[str, Any] = {}
|
|
per_field: dict[str, dict[str, Any]] = {}
|
|
for variant, kept_key in variants.items():
|
|
pooled[variant] = _metrics_from_rows(scored_rows, kept_key)
|
|
field_block: dict[str, Any] = {}
|
|
for field in (
|
|
"Biology / Biotechnology",
|
|
"Chemistry",
|
|
"Engineering",
|
|
"Medicine / Health Sciences",
|
|
"Physics",
|
|
"Other",
|
|
):
|
|
subset = [r for r in scored_rows if r.get("evaluation_field") == field]
|
|
field_block[field] = _metrics_from_rows(subset, kept_key)
|
|
per_field[variant] = field_block
|
|
threshold_metrics[variant] = pooled[variant]
|
|
|
|
# Weigel FP check (identity collision cases already exact-topic kept)
|
|
weigel_fps = [
|
|
r
|
|
for r in scored_rows
|
|
if r.get("gold") is False
|
|
and str(r.get("author_name") or "").casefold().find("weigel") >= 0
|
|
and r.get("kept_production_baseline")
|
|
]
|
|
weigel_report = []
|
|
for r in weigel_fps:
|
|
weigel_report.append(
|
|
{
|
|
"patent_id": r.get("patent_id"),
|
|
"production_kept": r.get("kept_production_baseline"),
|
|
"semantic_fallback_kept": r.get("kept_semantic_topic_fallback_v1"),
|
|
"semantic_fallback_reason": r.get("semantic_fallback_reason"),
|
|
"topic_overlap": r.get("topic_overlap"),
|
|
"domain_conflict": r.get("domain_conflict"),
|
|
}
|
|
)
|
|
|
|
bio = per_field["semantic_topic_fallback_v1"]["Biology / Biotechnology"]
|
|
base = pooled["production_baseline"]
|
|
sem = pooled["semantic_topic_fallback_v1"]
|
|
|
|
# Threshold recommendation: best recall gain without large precision drop
|
|
recommendation = _recommend_semantic_threshold(
|
|
pooled=pooled,
|
|
per_field=per_field,
|
|
weigel_report=weigel_report,
|
|
bio=bio,
|
|
)
|
|
|
|
payload = {
|
|
"created_at": _utc_stamp(),
|
|
"validation_label": SEMANTIC_FALLBACK_VALIDATION,
|
|
"variant": "semantic_topic_fallback_v1",
|
|
"default_threshold": SEMANTIC_FALLBACK_DEFAULT_THRESHOLD,
|
|
"thresholds_tested": list(SEMANTIC_FALLBACK_THRESHOLDS),
|
|
"candidate_count": len(scored_rows),
|
|
"pooled": pooled,
|
|
"per_field": per_field,
|
|
"weigel_false_positives": weigel_report,
|
|
"biology_check": {
|
|
"semantic_TP": bio.get("tp"),
|
|
"semantic_FP": bio.get("fp"),
|
|
"baseline_biology": per_field["production_baseline"][
|
|
"Biology / Biotechnology"
|
|
],
|
|
},
|
|
"recommendation": recommendation,
|
|
"notes": [
|
|
"Exact topic/subfield ID overlap still keeps candidates before semantic fallback.",
|
|
"No new Elasticsearch index; diagnosis enrichments only.",
|
|
"Production filter code and gold labels were not modified.",
|
|
],
|
|
}
|
|
_write_json(SEMANTIC_FALLBACK_DIR / "experimental_metrics.json", payload)
|
|
_write_json(
|
|
SEMANTIC_FALLBACK_DIR / "candidate_decisions.json",
|
|
{
|
|
"validation_label": SEMANTIC_FALLBACK_VALIDATION,
|
|
"candidates": scored_rows,
|
|
},
|
|
)
|
|
|
|
# CSV per field
|
|
field_rows = []
|
|
for variant in ("production_baseline", "semantic_topic_fallback_v1"):
|
|
for field, m in per_field[variant].items():
|
|
field_rows.append(
|
|
{
|
|
"variant": variant,
|
|
"field": field,
|
|
"TP": m.get("tp"),
|
|
"FP": m.get("fp"),
|
|
"FN": m.get("fn"),
|
|
"TN": m.get("tn"),
|
|
"precision": m.get("precision"),
|
|
"recall": m.get("recall"),
|
|
"f1": m.get("f1"),
|
|
}
|
|
)
|
|
for thr in SEMANTIC_FALLBACK_THRESHOLDS:
|
|
vname = f"semantic_thr_{thr:.2f}"
|
|
for field, m in per_field[vname].items():
|
|
field_rows.append(
|
|
{
|
|
"variant": vname,
|
|
"field": field,
|
|
"TP": m.get("tp"),
|
|
"FP": m.get("fp"),
|
|
"FN": m.get("fn"),
|
|
"TN": m.get("tn"),
|
|
"precision": m.get("precision"),
|
|
"recall": m.get("recall"),
|
|
"f1": m.get("f1"),
|
|
}
|
|
)
|
|
_write_csv(
|
|
SEMANTIC_FALLBACK_DIR / "per_field_metrics.csv",
|
|
field_rows,
|
|
[
|
|
"variant",
|
|
"field",
|
|
"TP",
|
|
"FP",
|
|
"FN",
|
|
"TN",
|
|
"precision",
|
|
"recall",
|
|
"f1",
|
|
],
|
|
)
|
|
|
|
thr_rows = []
|
|
for thr in SEMANTIC_FALLBACK_THRESHOLDS:
|
|
vname = f"semantic_thr_{thr:.2f}"
|
|
m = pooled[vname]
|
|
thr_rows.append(
|
|
{
|
|
"threshold": thr,
|
|
"TP": m.get("tp"),
|
|
"FP": m.get("fp"),
|
|
"FN": m.get("fn"),
|
|
"TN": m.get("tn"),
|
|
"precision": m.get("precision"),
|
|
"recall": m.get("recall"),
|
|
"f1": m.get("f1"),
|
|
}
|
|
)
|
|
_write_csv(
|
|
SEMANTIC_FALLBACK_DIR / "threshold_sweep.csv",
|
|
thr_rows,
|
|
["threshold", "TP", "FP", "FN", "TN", "precision", "recall", "f1"],
|
|
)
|
|
|
|
md_lines = [
|
|
"# semantic_topic_fallback_v1",
|
|
"",
|
|
f"Validation: `{SEMANTIC_FALLBACK_VALIDATION}`",
|
|
"",
|
|
"## Pooled",
|
|
"",
|
|
"| Variant | TP | FP | FN | TN | P | R | F1 |",
|
|
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
|
|
]
|
|
for variant in (
|
|
"production_baseline",
|
|
"semantic_topic_fallback_v1",
|
|
"semantic_thr_0.70",
|
|
"semantic_thr_0.75",
|
|
"semantic_thr_0.80",
|
|
):
|
|
m = pooled[variant]
|
|
md_lines.append(
|
|
f"| {variant} | {m.get('tp')} | {m.get('fp')} | {m.get('fn')} | {m.get('tn')} | "
|
|
f"{_format_metric(m.get('precision'))} | {_format_metric(m.get('recall'))} | "
|
|
f"{_format_metric(m.get('f1'))} |"
|
|
)
|
|
md_lines.extend(
|
|
[
|
|
"",
|
|
"## Recommendation",
|
|
"",
|
|
f"**Threshold:** {recommendation['recommended_threshold']}",
|
|
"",
|
|
recommendation["reason"],
|
|
"",
|
|
]
|
|
)
|
|
(SEMANTIC_FALLBACK_DIR / "experimental_metrics.md").write_text(
|
|
"\n".join(md_lines) + "\n", encoding="utf-8"
|
|
)
|
|
(SEMANTIC_FALLBACK_DIR / "recommendation.md").write_text(
|
|
"\n".join(
|
|
[
|
|
"# Recommendation — semantic_topic_fallback_v1",
|
|
"",
|
|
f"**Recommended threshold:** {recommendation['recommended_threshold']}",
|
|
"",
|
|
f"**Verdict:** {recommendation['verdict']}",
|
|
"",
|
|
recommendation["reason"],
|
|
"",
|
|
"## Checks",
|
|
"",
|
|
*[f"- {c}" for c in recommendation.get("checks", [])],
|
|
"",
|
|
f"Validation label: `{SEMANTIC_FALLBACK_VALIDATION}`",
|
|
"",
|
|
]
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
|
|
print("\n=== SEMANTIC TOPIC FALLBACK V1 ===")
|
|
print(f"validation_label={SEMANTIC_FALLBACK_VALIDATION}")
|
|
for variant in ("production_baseline", "semantic_topic_fallback_v1"):
|
|
m = pooled[variant]
|
|
print(
|
|
f"{variant}: TP={m.get('tp')} FP={m.get('fp')} FN={m.get('fn')} TN={m.get('tn')} "
|
|
f"P={_format_metric(m.get('precision'))} R={_format_metric(m.get('recall'))} "
|
|
f"F1={_format_metric(m.get('f1'))}"
|
|
)
|
|
print("Threshold sweep:")
|
|
for row in thr_rows:
|
|
print(
|
|
f" thr={row['threshold']:.2f}: TP={row['TP']} FP={row['FP']} "
|
|
f"R={_format_metric(row['recall'])} P={_format_metric(row['precision'])}"
|
|
)
|
|
print(f"recommended_threshold={recommendation['recommended_threshold']}")
|
|
print(f"outputs: {SEMANTIC_FALLBACK_DIR}")
|
|
return 0
|
|
|
|
|
|
def _recommend_semantic_threshold(
|
|
*,
|
|
pooled: dict[str, Any],
|
|
per_field: dict[str, dict[str, Any]],
|
|
weigel_report: list[dict[str, Any]],
|
|
bio: dict[str, Any],
|
|
) -> dict[str, Any]:
|
|
base = pooled["production_baseline"]
|
|
checks: list[str] = []
|
|
# Prefer simplest threshold with recall gain and precision not collapsing.
|
|
ranked: list[tuple[float, float, float, dict[str, Any]]] = []
|
|
for thr in SEMANTIC_FALLBACK_THRESHOLDS:
|
|
m = pooled[f"semantic_thr_{thr:.2f}"]
|
|
base_r = float(base.get("recall") or 0.0)
|
|
base_p = float(base.get("precision") or 0.0)
|
|
r = float(m.get("recall") or 0.0)
|
|
p = float(m.get("precision") or 0.0)
|
|
recall_gain = r - base_r
|
|
precision_drop = base_p - p
|
|
# score: reward recall gain, penalize precision drop and extra FPs
|
|
score = recall_gain - 0.75 * max(0.0, precision_drop) - 0.01 * int(m.get("fp") or 0)
|
|
ranked.append((score, recall_gain, -precision_drop, {"threshold": thr, **m}))
|
|
|
|
ranked.sort(key=lambda item: (item[0], item[1], item[2]), reverse=True)
|
|
# Prefer the requested default 0.75 when metrics are tied across thresholds.
|
|
tied = [
|
|
item[3]
|
|
for item in ranked
|
|
if item[3].get("tp") == ranked[0][3].get("tp")
|
|
and item[3].get("fp") == ranked[0][3].get("fp")
|
|
]
|
|
preferred = next(
|
|
(item for item in tied if item.get("threshold") == SEMANTIC_FALLBACK_DEFAULT_THRESHOLD),
|
|
None,
|
|
)
|
|
best = preferred or (ranked[0][3] if ranked else {"threshold": SEMANTIC_FALLBACK_DEFAULT_THRESHOLD})
|
|
thr = best.get("threshold", SEMANTIC_FALLBACK_DEFAULT_THRESHOLD)
|
|
|
|
med_base = per_field["production_baseline"]["Medicine / Health Sciences"]
|
|
med_sem = per_field[f"semantic_thr_{thr:.2f}"]["Medicine / Health Sciences"]
|
|
phy_base = per_field["production_baseline"]["Physics"]
|
|
phy_sem = per_field[f"semantic_thr_{thr:.2f}"]["Physics"]
|
|
chem_base = per_field["production_baseline"]["Chemistry"]
|
|
chem_sem = per_field[f"semantic_thr_{thr:.2f}"]["Chemistry"]
|
|
|
|
checks.append(
|
|
f"Biology FP semantic@default={bio.get('fp')} (want 0); TP={bio.get('tp')}"
|
|
)
|
|
checks.append(
|
|
f"Medicine recall {med_base.get('recall')} → {med_sem.get('recall')}"
|
|
)
|
|
checks.append(
|
|
f"Physics recall {phy_base.get('recall')} → {phy_sem.get('recall')}"
|
|
)
|
|
checks.append(
|
|
f"Chemistry recall {chem_base.get('recall')} → {chem_sem.get('recall')}"
|
|
)
|
|
weigel_still_kept = sum(1 for w in weigel_report if w.get("semantic_fallback_kept"))
|
|
checks.append(
|
|
f"Weigel production FPs still kept by semantic fallback: {weigel_still_kept}/"
|
|
f"{len(weigel_report)} (exact topic overlap precedes fallback)"
|
|
)
|
|
|
|
base_r = float(base.get("recall") or 0.0)
|
|
best_r = float(best.get("recall") or 0.0)
|
|
if best_r > base_r and int(best.get("fp") or 0) <= int(base.get("fp") or 0) + 2:
|
|
verdict = "weiter untersuchen"
|
|
reason = (
|
|
f"Threshold {thr} raises pooled recall "
|
|
f"{_format_metric(base.get('recall'))} → {_format_metric(best.get('recall'))} "
|
|
f"with precision {_format_metric(best.get('precision'))} "
|
|
f"(baseline {_format_metric(base.get('precision'))}). "
|
|
"Exploratory on diagnosed sample only; holdout required before production."
|
|
)
|
|
elif best_r > base_r:
|
|
verdict = "weiter untersuchen"
|
|
reason = (
|
|
f"Threshold {thr} improves recall but increases FP risk "
|
|
f"(FP {base.get('fp')} → {best.get('fp')}). "
|
|
"Use only with additional identity guards."
|
|
)
|
|
else:
|
|
verdict = "Variante verwerfen oder anders ansetzen"
|
|
reason = (
|
|
"No threshold improved recall over production_baseline on this fixed sample "
|
|
"without unacceptable precision loss."
|
|
)
|
|
|
|
return {
|
|
"recommended_threshold": thr,
|
|
"verdict": verdict,
|
|
"reason": reason,
|
|
"checks": checks,
|
|
"pooled_at_recommended": {
|
|
k: best.get(k) for k in ("tp", "fp", "fn", "tn", "precision", "recall", "f1")
|
|
},
|
|
}
|
|
|
|
|
|
|
|
def run_experiment(args: argparse.Namespace | None = None) -> int:
|
|
"""Entry point used by evaluate_author_patent_search CLI."""
|
|
if args is None:
|
|
args = argparse.Namespace()
|
|
return cmd_experiment_semantic_topic_fallback(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(run_experiment())
|