Files
smartguide/service/scripts/patents/evaluate_author_patent_search.py
taguesokoudjou 4701f1ee87
LocationBasedServices/smartguide/pipeline/head This commit looks good
Finalize patent search with semantic fallback and identity guard
2026-08-25 03:36:51 +02:00

5579 lines
211 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
evaluate_author_patent_search.py — Field-based evaluation of author-to-patent search.
Preferred fixed-candidate workflow (no live author/patent discovery):
python scripts/patents/evaluate_author_patent_search.py import-fixed-experiments \\
--source-dir <path-to-four-json-files>
python scripts/patents/evaluate_author_patent_search.py import-fixed-experiments \\
--source-dir <path> --confirm-import
python scripts/patents/evaluate_author_patent_search.py replay-fixed --track experiment_1
python scripts/patents/evaluate_author_patent_search.py evaluate --track experiment_1
python scripts/patents/evaluate_author_patent_search.py aggregate
Variants (replay / evaluate):
1. name_matching — keep all frozen candidates
2. topic_only — mapped_topics_match_author_strict
3. production — filter_patents_by_ipc_topic_mapping
Exploratory (frozen diagnosed sample only; no production integration):
experiment-semantic-topic-fallback (restored historical offline experiment)
Legacy live modes ``select`` / ``freeze`` remain available but must not be used
for the three fixed historical experiments.
``bootstrap`` aliases ``freeze``; ``eval`` aliases ``evaluate``.
"""
from __future__ import annotations
import argparse
import asyncio
import csv
import hashlib
import importlib.util
import json
import logging
import random
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
current_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir.parent.parent / "src" / "main"))
from dotenv import load_dotenv
load_dotenv(current_dir.parent.parent / "src" / "main" / "inse" / ".env")
from inse.integrations import elasticsearch
from inse.models.openalex.author import Author
from inse.patents.authors.identity import is_ambiguous_name
from inse.patents.authors.ipc_openalex_mapping import (
author_openalex_topic_refs,
mapped_topic_refs,
mapped_topics_match_author_strict,
)
from inse.patents.authors.name_matching import filter_patents_by_author_name
from inse.patents.authors.name_variants import parse_person_name
from inse.patents.authors.search_pagination import search_author_patents_adaptive
from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
enrich_patents_classifications,
expand_matched_epo_application_families,
parse_epo_hits,
parse_uspto_hits,
patent_map_key,
)
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.keywords.eval_metrics import normalize_patent_id
from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver
from inse.patents.search_client import PatentSearchClient
from inse.persons import logic as person_logic
logger = logging.getLogger(__name__)
DATA_DIR = current_dir / "data" / "author_patent_evaluation"
SERVICE_DIR = current_dir.parent.parent
USED_AUTHORS_FILE = DATA_DIR / "used_author_ids.json"
AGGREGATE_DIR = DATA_DIR / "aggregate_field_analysis"
METHODICAL_EVAL_DIR = current_dir / "data" / "methodical_eval"
HISTORICAL_DIR = DATA_DIR / "historical"
FILTER_NAME = "filter_patents_by_ipc_topic_mapping"
TOPIC_ONLY_NAME = "mapped_topics_match_author_strict"
VARIANTS = ("name_matching", "topic_only", "production")
# Mapping: experiment track → historical methodical_eval run.
# Import uses only frozen authors/candidates/human gold — never live search.
HISTORICAL_RUNS: dict[str, dict[str, Any]] = {
"experiment_1": {
"label": "Phase-2 Batch 1",
"run_id": "20260724T044959Z",
"selection_method": "historical_fixed_sample",
"expected_from_protocol": {
"authors": 6,
"candidates": 45,
"note": "Phase-2 protocol deviations document batch1_candidates=45",
},
"source_roots": ("_archive_legacy", "."),
"authors_files": ("author_selected_authors_20260724T044959Z.json",),
"candidates_files": (
"author_selected_candidates_20260724T044959Z.json",
"author_labels_for_review_20260724T044959Z.json",
),
"gold_files": (
"author_human_gold_labels_20260724T044959Z.json",
"author_labels_for_review_20260724T044959Z.json",
),
"metrics_files": ("author_evaluation_metrics_20260724T044959Z.json",),
"decisions_files": (
"author_filter_decisions_20260724T044959Z.json",
),
"topic_only_expected": TOPIC_ONLY_NAME,
"historical_production_expected": "combined_e_v1_or_production_v1_compare",
},
"experiment_2": {
"label": "Phase-2 Batch 2",
"run_id": "20260724T061732Z",
"selection_method": "historical_fixed_sample",
"expected_from_protocol": {
"authors": 6,
"candidates": 41,
"positive_labels": 32,
"negative_labels": 9,
"authors_named": [
{"display_name": "Mark Obermann", "author_id": "A5035127271"},
{"display_name": "Hendrik Milting", "author_id": "A5054895539"},
{"display_name": "Jörg Steinmann", "author_id": "A5109170577"},
{"display_name": "Manfred Berroth", "author_id": "A5008182166"},
{"display_name": "Sebastian Schlücker", "author_id": "A5031103932"},
{
"display_name": "S. Ranil Wickramasinghe",
"author_id": "A5027988292",
},
],
"note": "Counts taken from completed human review notes (transcript).",
},
"source_roots": ("_archive_legacy", "."),
"authors_files": ("author_selected_authors_20260724T061732Z.json",),
"candidates_files": (
"author_selected_candidates_20260724T061732Z.json",
"author_labels_for_review_20260724T061732Z.json",
),
"gold_files": (
"author_human_gold_labels_20260724T061732Z.json",
"author_labels_for_review_20260724T061732Z.json",
),
"metrics_files": ("author_evaluation_metrics_20260724T061732Z.json",),
"decisions_files": (
"author_filter_decisions_20260724T061732Z.json",
),
"topic_only_expected": TOPIC_ONLY_NAME,
"historical_production_expected": "combined_e_v1",
},
"experiment_3": {
"label": "Compact evaluation",
"run_id": "20260723T105607Z",
"selection_method": "historical_fixed_sample",
"expected_from_protocol": {
"note": "Compact independent evaluation run 20260723T105607Z",
},
"source_roots": (".", "_archive_legacy"),
"authors_files": ("author_selected_authors_20260723T105607Z.json",),
"candidates_files": (
"author_selected_candidates_20260723T105607Z.json",
"author_labels_for_review_20260723T105607Z.json",
),
"gold_files": (
"author_human_gold_labels_20260723T105607Z.json",
"author_labels_for_review_20260723T105607Z.json",
),
"metrics_files": (
"author_evaluation_metrics_20260723T105607Z.json",
"compact_evaluation_run_20260723T105607Z.json",
),
"decisions_files": (
"author_filter_decisions_20260723T105607Z.json",
),
"topic_only_expected": TOPIC_ONLY_NAME,
"historical_production_expected": "production_and_or_combined_e",
},
}
EXPERIMENT_TRACKS = ("experiment_1", "experiment_2", "experiment_3")
# Content-based mapping for restored labelled candidate dumps (not filenames).
FIXED_EXPERIMENT_SPECS: dict[str, dict[str, Any]] = {
"experiment_1": {
"created_at": "20260724T044959Z",
"validation_type": "independent_validation_phase2_batch1",
"source_run": "20260724T044959Z",
"batch_number": 1,
"expected_authors": 6,
"expected_candidates": 45,
"expected_positive": 27,
"expected_negative": 18,
},
"experiment_2": {
"created_at": "20260724T061732Z",
"validation_type": "independent_validation_phase2_batch2",
"source_run": "20260724T061732Z",
"batch_number": 2,
"expected_authors": 6,
"expected_candidates": 41,
"expected_positive": 32,
"expected_negative": 9,
},
"experiment_3": {
"created_at": "20260723T105607Z",
"validation_type": "compact_methodical_evaluation",
"source_run": "20260723T105607Z",
"batch_number": None,
"expected_authors": 6,
"expected_candidates": 45,
"expected_positive": 30,
"expected_negative": 15,
},
}
FIXED_HOLDOUT_SPEC: dict[str, Any] = {
"track_dir": "holdout_20260723T211529Z",
"created_at": "20260723T211529Z",
"validation_type": "independent_holdout",
"source_run": "20260723T211529Z",
"batch_number": None,
}
LABEL_SOURCE_FIXED = "ai_assisted_independent_review"
SELECT_COUNT = 6
MIN_PRODUCTION_KEPT = 5
MAX_PRODUCTION_KEPT = 10
IDEAL_PRODUCTION_KEPT = 7
MAX_SAME_LAST_NAME = 1
MAX_AUTHORS_PER_FIELD_IN_EXPERIMENT = 2
TARGET_DISTINCT_FIELDS = 6
MIN_DISTINCT_FIELDS = 4
SELECTION_SEED = 307
SCREEN_LIMIT_PER_FIELD = 20
UDE_SCREEN_LIMIT = 50
MAX_GOLD_REVIEW_CANDIDATES = 15
OPENALEX_AUTHORS_INDEX = "openalex-authors"
MIN_WORKS_COUNT = 25
MAX_WORKS_COUNT = 2000
UDE_INSTITUTION_ID = "https://openalex.org/I62318514"
UDE_INSTITUTION_ID_SHORT = "I62318514"
STATUS_NEEDS_REVIEW = "author_selection_needs_review"
STATUS_READY_TO_FREEZE = "frozen_before_labeling"
# Older historical evaluation authors — prefer excluding unless selection is impossible.
HISTORICAL_EXCLUDE_AUTHOR_IDS = frozenset(
{
"A5100603203",
"A5100373745",
"A5007170803",
"A5034365278",
"A5005196385",
"A5110282865",
"A5058282825",
"A5113541511",
"A5070760948",
}
)
# Previous experiment_1 cohort — discarded; do not auto-reuse.
PREVIOUS_EXPERIMENT_1_AUTHOR_IDS = frozenset(
{
"A5033321689",
"A5071491614",
"A5075404776",
"A5003571345",
"A5049296994",
"A5085560065",
}
)
# Preferred OpenAlex fields for field-diversity selection.
PREFERRED_FIELDS: dict[str, str] = {
"https://openalex.org/fields/22": "Engineering",
"https://openalex.org/fields/17": "Computer Science",
"https://openalex.org/fields/27": "Medicine",
"https://openalex.org/fields/16": "Chemistry",
"https://openalex.org/fields/25": "Materials Science",
"https://openalex.org/fields/31": "Physics and Astronomy",
"https://openalex.org/fields/13": "Biochemistry, Genetics and Molecular Biology",
"https://openalex.org/fields/23": "Environmental Science",
"https://openalex.org/fields/21": "Energy",
"https://openalex.org/fields/11": "Agricultural and Biological Sciences",
"https://openalex.org/fields/36": "Health Professions",
"https://openalex.org/fields/14": "Business, Management and Accounting",
}
DISCOVERY_LAST_NAMES = (
"Steinmann", "Schubert", "Hoffmann", "Bauer", "Nguyen", "Singh",
"Garcia", "Rossi", "Moreau", "Andersson", "Tanaka", "Schulz",
"Keller", "Ding", "Weber", "Schmidt", "Meyer", "Chen", "Wang",
"Kim", "Park", "Müller", "Schneider", "Wagner", "Becker",
"Richter", "Klein", "Wolf", "Neumann", "Schwarz", "Zimmermann",
"Braun", "Krüger", "Hofmann", "Hartmann", "Lange", "Schmitt",
"Werner", "Krause", "Meier", "Lehmann", "Schmid", "Schulze",
"Maier", "Köhler", "Herrmann", "König", "Walter", "Mayer",
"Huber", "Kaiser", "Fuchs", "Peters", "Lang", "Scholz",
"Möller", "Weiß", "Jung", "Hahn", "Schubert", "Vogel",
"Friedrich", "Keller", "Günther", "Frank", "Berger", "Winkler",
"Roth", "Beck", "Lorenz", "Baumann", "Franke", "Albrecht",
"Schuster", "Simon", "Ludwig", "Böhm", "Winter", "Kraus",
"Martin", "Krämer", "Vogel", "Stein", "Jäger", "Otto",
"Sommer", "Groß", "Seidel", "Heinrich", "Brandt", "Haas",
"Schreiber", "Graf", "Schulte", "Dietrich", "Ziegler", "Kuhn",
"Kühn", "Pohl", "Engel", "Horn", "Busch", "Bergmann",
"Thomas", "Voigt", "Sauer", "Arnold", "Wolff", "Pfeiffer",
)
def _author_from_es_hit(hit: dict[str, Any]) -> Author | None:
source = dict(hit.get("_source", {}))
source["id"] = source.get("id") or hit.get("_id", "")
ids = source.get("ids")
if isinstance(ids, dict):
ids_copy: dict[str, Any] = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source["ids"] = ids_copy
return Author.from_dict(source)
def _display_path(path: Path) -> str:
try:
return path.relative_to(SERVICE_DIR).as_posix()
except ValueError:
return path.as_posix()
def _load_json(path: Path) -> dict[str, Any]:
with path.open(encoding="utf-8-sig") as handle:
return json.load(handle)
def _write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2, ensure_ascii=False)
handle.write("\n")
def _utc_stamp() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def _short_author_id(author_id: str) -> str:
return author_id.replace("https://openalex.org/", "").strip()
def _track_dir(track: str) -> Path:
return DATA_DIR / track
def _track_paths(track: str) -> dict[str, Path]:
root = _track_dir(track)
return {
"authors": root / "authors.json",
"selection_report": root / "author_selection_report.md",
"gold": root / "gold_labels.json",
"frozen": root / "frozen_candidate_pool.json",
"decisions": root / "filter_decisions.json",
"result": root / "evaluation_result.json",
"report": root / "evaluation_report.md",
}
def _apply_track_paths(args: argparse.Namespace) -> None:
if args.mode in {
"aggregate",
"inventory-historical",
"import-historical",
"import-fixed-experiments",
"experiment-semantic-topic-fallback",
}:
return
if not args.track:
raise SystemExit("--track is required for select/freeze/replay-fixed/evaluate")
if args.track not in EXPERIMENT_TRACKS:
raise SystemExit(f"Unknown track: {args.track}")
paths = _track_paths(args.track)
args.authors = args.authors or paths["authors"]
args.gold = args.gold or paths["gold"]
args.frozen = args.frozen or paths["frozen"]
args.decisions = args.decisions or paths["decisions"]
args.result = args.result or paths["result"]
args.report = args.report or paths["report"]
args.selection_report = paths["selection_report"]
def _load_used_authors() -> dict[str, Any]:
if USED_AUTHORS_FILE.exists():
return _load_json(USED_AUTHORS_FILE)
return {"author_ids": [], "by_track": {t: [] for t in EXPERIMENT_TRACKS}}
def _save_used_authors(payload: dict[str, Any]) -> None:
_write_json(USED_AUTHORS_FILE, payload)
def _rebuild_used_authors_from_tracks() -> dict[str, Any]:
"""Rebuild used_author_ids.json from authors.json of existing tracks only."""
by_track: dict[str, list[str]] = {}
for track in EXPERIMENT_TRACKS:
path = _track_paths(track)["authors"]
ids: list[str] = []
if path.exists():
payload = _load_json(path)
for author in payload.get("authors") or []:
aid = author.get("author_id")
if aid:
ids.append(_short_author_id(str(aid)))
by_track[track] = ids
flat = sorted({aid for ids in by_track.values() for aid in ids})
return {
"author_ids": flat,
"by_track": by_track,
"updated_at": _utc_stamp(),
}
def _used_author_id_set(used: dict[str, Any], *, exclude_track: str | None = None) -> set[str]:
ids: set[str] = set()
by_track = used.get("by_track") or {}
for track, track_ids in by_track.items():
if exclude_track and track == exclude_track:
continue
ids.update(_short_author_id(x) for x in track_ids)
ids.update(_short_author_id(x) for x in used.get("author_ids") or [])
return ids
async def _get_author(author_id: str) -> Author | None:
short_id = _short_author_id(author_id)
result = await person_logic.search_persons(author_id=short_id)
return result.results[0] if result.results else None
def _author_topic_profile(author: Author) -> dict[str, Any]:
for topic in author.topics or []:
field_obj = getattr(topic, "var_field", None) or getattr(topic, "field", None)
subfield = getattr(topic, "subfield", None)
domain = getattr(topic, "domain", None)
return {
"primary_topic_id": topic.id,
"primary_topic_display_name": topic.display_name,
"primary_field_id": getattr(field_obj, "id", None) if field_obj else None,
"primary_field_display_name": (
getattr(field_obj, "display_name", None) if field_obj else None
),
"primary_subfield_id": getattr(subfield, "id", None) if subfield else None,
"primary_subfield_display_name": (
getattr(subfield, "display_name", None) if subfield else None
),
"primary_domain": getattr(domain, "display_name", None) if domain else None,
"primary_domain_id": getattr(domain, "id", None) if domain else None,
}
return {
"primary_topic_id": None,
"primary_topic_display_name": None,
"primary_field_id": None,
"primary_field_display_name": None,
"primary_subfield_id": None,
"primary_subfield_display_name": None,
"primary_domain": None,
"primary_domain_id": None,
}
def _author_has_topic_profile(author: Author) -> bool:
refs = author_openalex_topic_refs(author)
return bool(refs.topic_ids or refs.subfield_ids or refs.field_ids)
def _institution_id(inst: Any) -> str | None:
raw = getattr(inst, "id", None)
if not raw:
return None
return str(raw).replace("https://openalex.org/", "").upper()
def _ude_affiliation_evidence(author: Author) -> dict[str, Any] | None:
for inst in author.last_known_institutions or []:
if _institution_id(inst) == UDE_INSTITUTION_ID_SHORT:
return {
"ude_institution_id": UDE_INSTITUTION_ID,
"affiliation_source": "last_known_institutions",
"last_known_institution": inst.display_name,
}
for affiliation in author.affiliations or []:
inst = getattr(affiliation, "institution", None)
if inst is not None and _institution_id(inst) == UDE_INSTITUTION_ID_SHORT:
return {
"ude_institution_id": UDE_INSTITUTION_ID,
"affiliation_source": "affiliations",
"last_known_institution": getattr(inst, "display_name", None),
}
return None
def _is_full_openalex_display_name(display_name: str | None) -> bool:
if not display_name or not display_name.strip():
return False
parsed = parse_person_name(display_name)
if parsed is None or parsed.is_single_token:
return False
tokens = parsed.tokens
if len(tokens) >= 2 and len(tokens) % 2 == 0:
mid = len(tokens) // 2
if tuple(t.casefold() for t in tokens[:mid]) == tuple(
t.casefold() for t in tokens[mid:]
):
return False
primary_given = parsed.primary_given_name
if primary_given and primary_given.casefold() == parsed.last_name.casefold():
return False
return True
def _family_name(display_name: str | None) -> str | None:
parsed = parse_person_name(display_name) if display_name else None
return parsed.last_name.casefold() if parsed else None
def _patent_summary(patent: model.PatentEntry) -> dict[str, Any]:
return {
"patent_id": patent.patent_id,
"title": patent.title,
"source": patent.source,
"application_number": patent.application_number,
"publication_year": patent.publication_year,
"ipc": (patent.ipc or [])[:8],
"cpc": (patent.cpc or [])[:8],
}
@dataclass
class NameMatchedPool:
author_id: str
author_name: str | None
error: str | None
search_hit_count: int
search_completeness: str | None
candidates: list[model.PatentEntry]
is_ambiguous: bool | None
openalex_full_name_count: int | None
openalex_last_name_count: int | None
@dataclass
class VariantDecisions:
kept_ids: set[str]
removed_ids: set[str]
decisions: dict[str, dict[str, Any]]
@dataclass
class AuthorScreen:
author_id: str
openalex_id: str | None
display_name: str | None
display_name_alternatives: list[str] | None
error: str | None
exclusion_reason: str | None
name_matched_count: int
production_kept_count: int
is_ambiguous: bool | None
has_topic_profile: bool
is_ude: bool
ude_affiliation_confirmed: bool
ude_affiliation_source: str | None
ude_institution_id: str | None
last_known_institution: str | None
primary_topic_id: str | None
primary_topic_display_name: str | None
primary_field_id: str | None
primary_field_display_name: str | None
primary_subfield_id: str | None
primary_subfield_display_name: str | None
primary_domain: str | None
primary_domain_id: str | None
family_name: str | None
search_completeness: str | None
discovery_source: str | None
selection_reason: str | None = None
async def build_name_matched_pool(
author_id: str,
*,
search_client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> NameMatchedPool:
search_client = search_client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
short_id = _short_author_id(author_id)
author = await _get_author(short_id)
if not author:
return NameMatchedPool(
author_id=short_id,
author_name=None,
error="author_not_found",
search_hit_count=0,
search_completeness=None,
candidates=[],
is_ambiguous=None,
openalex_full_name_count=None,
openalex_last_name_count=None,
)
author_name = author.display_name
if not author_name or not author_name.strip():
return NameMatchedPool(
author_id=short_id,
author_name=author_name,
error="empty_author_name",
search_hit_count=0,
search_completeness=None,
candidates=[],
is_ambiguous=None,
openalex_full_name_count=None,
openalex_last_name_count=None,
)
try:
search_result = await search_author_patents_adaptive(search_client, author_name)
except MissingApiKeyError as exc:
return NameMatchedPool(
author_id=short_id,
author_name=author_name,
error=f"missing_api_key: {exc}",
search_hit_count=0,
search_completeness=None,
candidates=[],
is_ambiguous=None,
openalex_full_name_count=None,
openalex_last_name_count=None,
)
except Exception as exc:
logger.exception("Patent search failed for %s", author_name)
return NameMatchedPool(
author_id=short_id,
author_name=author_name,
error=f"search_failed: {exc}",
search_hit_count=0,
search_completeness=None,
candidates=[],
is_ambiguous=None,
openalex_full_name_count=None,
openalex_last_name_count=None,
)
all_patents = search_result.patents
patent_hit_count = len(all_patents)
matched_patents = filter_patents_by_author_name(all_patents, author_name)
try:
matched_patents = await expand_matched_epo_application_families(
matched_patents,
search_client,
)
except Exception:
logger.exception(
"EPO family expansion failed for %s; continuing with name-matched patents only",
author_name,
)
full_name_count = await person_logic.count_authors_by_display_name(author_name)
parsed_for_last = parse_person_name(author_name)
last_name_count: int | None = None
if parsed_for_last and not parsed_for_last.is_single_token:
last_name_count = await person_logic.count_authors_by_last_name(
parsed_for_last.last_name
)
ambiguous = is_ambiguous_name(
author_name,
patent_hit_count=patent_hit_count,
openalex_full_name_count=full_name_count,
openalex_last_name_count=last_name_count,
)
if matched_patents:
await enrich_patents_classifications(matched_patents, ipc_search_client)
return NameMatchedPool(
author_id=short_id,
author_name=author_name,
error=None,
search_hit_count=patent_hit_count,
search_completeness=search_result.completeness.value,
candidates=matched_patents,
is_ambiguous=ambiguous,
openalex_full_name_count=full_name_count,
openalex_last_name_count=last_name_count,
)
async def _resolve_topic_map(
candidates: list[model.PatentEntry],
) -> dict[str, list] | None:
try:
resolver = PatentOpenAlexMappingResolver()
return await resolver.resolve_topics_for_patents(candidates)
except Exception:
logger.exception("OpenAlex topic resolution failed")
return None
def _variant_name_matching(pool: NameMatchedPool) -> VariantDecisions:
decisions: dict[str, dict[str, Any]] = {}
kept_ids: set[str] = set()
for patent in pool.candidates:
pid = normalize_patent_id(patent.patent_id)
kept_ids.add(pid)
row = _patent_summary(patent)
row.update(
{
"variant": "name_matching",
"production_kept": True,
"decision": "kept",
"keep_reason": "name_matched_pool",
}
)
decisions[pid] = row
return VariantDecisions(kept_ids=kept_ids, removed_ids=set(), decisions=decisions)
def _variant_topic_only(
pool: NameMatchedPool,
author: Author,
patent_topic_map: dict[str, list] | None,
) -> VariantDecisions:
"""Strict topic/subfield ID overlap only — no institution/assignee/co-inventor."""
decisions: dict[str, dict[str, Any]] = {}
kept_ids: set[str] = set()
removed_ids: set[str] = set()
for patent in pool.candidates:
pid = normalize_patent_id(patent.patent_id)
mapped = []
if patent_topic_map is not None:
mapped = patent_topic_map.get(patent_map_key(patent), [])
keep = mapped_topics_match_author_strict(mapped, author)
row = _patent_summary(patent)
if keep:
kept_ids.add(pid)
row.update(
{
"variant": "topic_only",
"production_kept": True,
"decision": "kept",
"keep_reason": "strict_topic_or_subfield_overlap",
}
)
else:
removed_ids.add(pid)
row.update(
{
"variant": "topic_only",
"production_kept": False,
"decision": "removed",
"keep_reason": None,
}
)
decisions[pid] = row
return VariantDecisions(kept_ids=kept_ids, removed_ids=removed_ids, decisions=decisions)
def _variant_production(
pool: NameMatchedPool,
author: Author,
patent_topic_map: dict[str, list] | None,
) -> VariantDecisions:
results = filter_patents_by_ipc_topic_mapping(
pool.candidates,
author,
is_ambiguous=bool(pool.is_ambiguous),
patent_topic_map=patent_topic_map,
)
kept_ids = {normalize_patent_id(r.patent.patent_id) for r in results}
decisions: dict[str, dict[str, Any]] = {}
removed_ids: set[str] = set()
by_id = {normalize_patent_id(r.patent.patent_id): r for r in results}
for patent in pool.candidates:
pid = normalize_patent_id(patent.patent_id)
row = _patent_summary(patent)
if pid in kept_ids:
result = by_id[pid]
row.update(
{
"variant": "production",
"production_kept": True,
"decision": result.decision,
"keep_reason": result.keep_reason,
"matched_via_mapping": result.matched_via_mapping,
"institution_match": result.institution_match,
"personal_assignee_match": result.personal_assignee_match,
"name_match_kind": result.name_match_kind,
}
)
else:
removed_ids.add(pid)
row.update(
{
"variant": "production",
"production_kept": False,
"decision": "removed",
"keep_reason": None,
}
)
decisions[pid] = row
return VariantDecisions(kept_ids=kept_ids, removed_ids=removed_ids, decisions=decisions)
async def run_all_variants(author_id: str) -> dict[str, Any]:
pool = await build_name_matched_pool(author_id)
author = await _get_author(author_id)
empty = {
"pool": pool,
"author": author,
"variants": {
name: VariantDecisions(set(), set(), {}) for name in VARIANTS
},
}
if pool.error or not pool.candidates or not author:
return empty
patent_topic_map = await _resolve_topic_map(pool.candidates)
return {
"pool": pool,
"author": author,
"variants": {
"name_matching": _variant_name_matching(pool),
"topic_only": _variant_topic_only(pool, author, patent_topic_map),
"production": _variant_production(pool, author, patent_topic_map),
},
}
def _classification_metrics(
kept_ids: set[str],
labels: dict[str, dict[str, Any]],
*,
candidate_ids: set[str],
) -> dict[str, Any]:
tp = fp = fn = tn = 0
reviewed = 0
unresolved = 0
positive = negative = 0
false_positives: list[dict[str, Any]] = []
false_negatives: list[dict[str, Any]] = []
for patent_id, label in labels.items():
pid = normalize_patent_id(patent_id)
if pid not in candidate_ids:
continue
if not label.get("reviewed"):
continue
relevant = label.get("relevant")
if relevant is None:
unresolved += 1
continue
reviewed += 1
is_pos = bool(relevant)
if is_pos:
positive += 1
else:
negative += 1
predicted = pid in kept_ids
if is_pos and predicted:
tp += 1
elif not is_pos and predicted:
fp += 1
false_positives.append({"patent_id": pid, "notes": label.get("notes")})
elif is_pos and not predicted:
fn += 1
false_negatives.append({"patent_id": pid, "notes": label.get("notes")})
else:
tn += 1
precision = tp / (tp + fp) if (tp + fp) else None
recall = tp / (tp + fn) if (tp + fn) else None
if precision is not None and recall is not None and (precision + recall) > 0:
f1 = 2 * precision * recall / (precision + recall)
else:
f1 = None
return {
"reviewed_labeled": reviewed,
"unresolved_labeled": unresolved,
"positive_labels": positive,
"negative_labels": negative,
"label_coverage": (
round(reviewed / len(candidate_ids), 4) if candidate_ids else None
),
"tp": tp,
"fp": fp,
"fn": fn,
"tn": tn,
"precision": round(precision, 4) if precision is not None else None,
"recall": round(recall, 4) if recall is not None else None,
"f1": round(f1, 4) if f1 is not None else None,
"false_positives": false_positives,
"false_negatives": false_negatives,
"integrity": {
"confusion_sum_equals_reviewed": (tp + fp + tn + fn) == reviewed,
"positive_equals_tp_fn": positive == (tp + fn),
"negative_equals_fp_tn": negative == (fp + tn),
},
}
def _aggregate_variant_metrics(author_metrics: list[dict[str, Any]]) -> dict[str, Any]:
scored = [m for m in author_metrics if m.get("reviewed_labeled", 0) > 0]
if not scored:
return {"authors_with_labels": 0, "micro": {}, "macro": {}}
tp = sum(m["tp"] for m in scored)
fp = sum(m["fp"] for m in scored)
fn = sum(m["fn"] for m in scored)
tn = sum(m["tn"] for m in scored)
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 {
"authors_with_labels": len(scored),
"micro": {
"tp": tp,
"fp": fp,
"fn": fn,
"tn": tn,
"precision": round(precision, 4) if precision is not None else None,
"recall": round(recall, 4) if recall is not None else None,
"f1": round(f1, 4) if f1 is not None else None,
},
"macro": {
"precision": round(
sum(m["precision"] or 0 for m in scored) / len(scored), 4
),
"recall": round(sum(m["recall"] or 0 for m in scored) / len(scored), 4),
"f1": round(sum(m["f1"] or 0 for m in scored) / len(scored), 4),
"n": len(scored),
},
}
# ---------------------------------------------------------------------------
# Discovery / select
# ---------------------------------------------------------------------------
async def _discover_ude_author_ids(*, limit: int = UDE_SCREEN_LIMIT) -> list[str]:
"""Discover UDE authors via OpenAlex institution id I62318514."""
query = {
"bool": {
"should": [
{
"nested": {
"path": "last_known_institutions",
"query": {
"term": {"last_known_institutions.id": UDE_INSTITUTION_ID}
},
}
},
{
"nested": {
"path": "affiliations",
"query": {
"term": {
"affiliations.institution.id": UDE_INSTITUTION_ID
}
},
}
},
],
"minimum_should_match": 1,
"filter": [
{
"range": {
"works_count": {
"gte": MIN_WORKS_COUNT,
"lte": MAX_WORKS_COUNT,
}
}
}
],
}
}
body = {
"size": limit,
"query": query,
"sort": [{"works_count": {"order": "desc"}}, {"id": {"order": "asc"}}],
}
ordered: list[str] = []
try:
response = await elasticsearch.search(index=OPENALEX_AUTHORS_INDEX, body=body)
except Exception:
logger.exception("UDE institution discovery failed")
return ordered
for hit in response.get("hits", {}).get("hits", []):
author = _author_from_es_hit(hit)
if not author or not author.id:
continue
if not _is_full_openalex_display_name(author.display_name):
continue
if not _author_has_topic_profile(author):
continue
ordered.append(_short_author_id(author.id))
return ordered
async def _discover_field_batch(
field_id: str,
*,
exclude: set[str],
limit: int,
rng: random.Random,
) -> list[str]:
query = {
"bool": {
"must": [
{
"nested": {
"path": "topics",
"query": {"term": {"topics.field.id": field_id}},
}
}
],
"filter": [
{
"range": {
"works_count": {
"gte": MIN_WORKS_COUNT,
"lte": MAX_WORKS_COUNT,
}
}
}
],
}
}
body = {
"size": max(limit * 4, 40),
"query": query,
"sort": [{"works_count": {"order": "asc"}}, {"id": {"order": "asc"}}],
}
hits: list[str] = []
try:
response = await elasticsearch.search(index=OPENALEX_AUTHORS_INDEX, body=body)
except Exception:
logger.exception("Field batch discovery failed for %s", field_id)
return hits
for hit in response.get("hits", {}).get("hits", []):
author = _author_from_es_hit(hit)
if not author or not author.id:
continue
if not _is_full_openalex_display_name(author.display_name):
continue
if not _author_has_topic_profile(author):
continue
aid = _short_author_id(author.id)
if aid in exclude:
continue
hits.append(aid)
rng.shuffle(hits)
return hits[:limit]
async def _discover_candidates_by_field(
exclude: set[str],
) -> list[tuple[str, str]]:
"""Return (discovery_source, author_id) pairs.
Field diversity is primary. UDE discovery is included as an equal source,
not a preferred ranking signal. Order within sources is seeded (SELECTION_SEED).
"""
rng = random.Random(SELECTION_SEED)
ordered: list[tuple[str, str]] = []
seen: set[str] = set(exclude)
field_ids = list(PREFERRED_FIELDS.keys())
rng.shuffle(field_ids)
for field_id in field_ids:
batch = await _discover_field_batch(
field_id, exclude=seen, limit=SCREEN_LIMIT_PER_FIELD, rng=rng
)
for aid in batch:
seen.add(aid)
ordered.append(("field_discovery", aid))
last_name_hits: list[str] = []
for last_name in DISCOVERY_LAST_NAMES:
try:
response = await person_logic.search_persons_by_name(
author_name=last_name, limit=6
)
except Exception:
continue
for author in response.results:
if not author.id or not _is_full_openalex_display_name(author.display_name):
continue
aid = _short_author_id(author.id)
if aid in seen:
continue
seen.add(aid)
last_name_hits.append(aid)
rng.shuffle(last_name_hits)
for aid in last_name_hits[:80]:
ordered.append(("last_name_seed", aid))
ude_hits = [
aid
for aid in await _discover_ude_author_ids()
if aid not in seen
]
rng.shuffle(ude_hits)
for aid in ude_hits:
seen.add(aid)
ordered.append(("ude_institution", aid))
return ordered
async def _refill_underrepresented_fields(
screens: list[AuthorScreen],
*,
hard_exclude: set[str],
soft_exclude: set[str],
) -> list[AuthorScreen]:
"""Screen extra authors from preferred fields that still lack eligible hits."""
rng = random.Random(SELECTION_SEED + 17)
eligible = [s for s in screens if _screen_eligible(s)]
fields_with_eligible = {
s.primary_field_id for s in eligible if s.primary_field_id
}
seen = {s.author_id for s in screens} | hard_exclude | soft_exclude
missing_fields = [
fid for fid in PREFERRED_FIELDS if fid not in fields_with_eligible
]
rng.shuffle(missing_fields)
for field_id in missing_fields:
if len([s for s in screens if _screen_eligible(s)]) >= SELECT_COUNT + 8:
fields_now = {
s.primary_field_id
for s in screens
if _screen_eligible(s) and s.primary_field_id
}
if len(fields_now) >= TARGET_DISTINCT_FIELDS:
break
batch = await _discover_field_batch(
field_id, exclude=seen, limit=25, rng=rng
)
logger.info(
"Refill field %s with %d candidates",
PREFERRED_FIELDS.get(field_id, field_id),
len(batch),
)
for aid in batch:
if aid in seen:
continue
seen.add(aid)
screen = await screen_author(aid, discovery_source="field_refill")
screens.append(screen)
if screen.exclusion_reason:
logger.info(
"skip %s (%s): %s",
screen.author_id,
screen.display_name,
screen.exclusion_reason,
)
else:
logger.info(
"ok %s (%s): field=%s kept=%s ude=%s",
screen.author_id,
screen.display_name,
screen.primary_field_display_name,
screen.production_kept_count,
screen.is_ude,
)
eligible = [s for s in screens if _screen_eligible(s)]
fields_now = {s.primary_field_id for s in eligible if s.primary_field_id}
if len(eligible) >= SELECT_COUNT and len(fields_now) >= MIN_DISTINCT_FIELDS:
if field_id in fields_now:
break
return screens
def _screen_eligible(screen: AuthorScreen) -> bool:
return (
not screen.error
and not screen.exclusion_reason
and screen.has_topic_profile
and _is_full_openalex_display_name(screen.display_name)
and bool(screen.primary_field_id)
and bool(screen.primary_subfield_id)
and MIN_PRODUCTION_KEPT <= screen.production_kept_count <= MAX_PRODUCTION_KEPT
)
async def screen_author(author_id: str, *, discovery_source: str) -> AuthorScreen:
author = await _get_author(author_id)
empty_kwargs = dict(
author_id=_short_author_id(author_id),
openalex_id=None,
display_name=None,
display_name_alternatives=None,
error="author_not_found",
exclusion_reason="author_not_found",
name_matched_count=0,
production_kept_count=0,
is_ambiguous=None,
has_topic_profile=False,
is_ude=False,
ude_affiliation_confirmed=False,
ude_affiliation_source=None,
ude_institution_id=None,
last_known_institution=None,
primary_topic_id=None,
primary_topic_display_name=None,
primary_field_id=None,
primary_field_display_name=None,
primary_subfield_id=None,
primary_subfield_display_name=None,
primary_domain=None,
primary_domain_id=None,
family_name=None,
search_completeness=None,
discovery_source=discovery_source,
)
if not author:
return AuthorScreen(**empty_kwargs)
topic = _author_topic_profile(author)
ude = _ude_affiliation_evidence(author)
display_name = author.display_name
base = AuthorScreen(
author_id=_short_author_id(author_id),
openalex_id=author.id or f"https://openalex.org/{_short_author_id(author_id)}",
display_name=display_name,
display_name_alternatives=list(author.display_name_alternatives or []) or None,
error=None,
exclusion_reason=None,
name_matched_count=0,
production_kept_count=0,
is_ambiguous=None,
has_topic_profile=_author_has_topic_profile(author),
is_ude=ude is not None,
ude_affiliation_confirmed=ude is not None,
ude_affiliation_source=ude.get("affiliation_source") if ude else None,
ude_institution_id=ude.get("ude_institution_id") if ude else None,
last_known_institution=(
(ude.get("last_known_institution") if ude else None)
or next(
(
i.display_name
for i in (author.last_known_institutions or [])
if i.display_name
),
None,
)
),
primary_topic_id=topic["primary_topic_id"],
primary_topic_display_name=topic["primary_topic_display_name"],
primary_field_id=topic["primary_field_id"],
primary_field_display_name=topic["primary_field_display_name"],
primary_subfield_id=topic["primary_subfield_id"],
primary_subfield_display_name=topic["primary_subfield_display_name"],
primary_domain=topic["primary_domain"],
primary_domain_id=topic["primary_domain_id"],
family_name=_family_name(display_name),
search_completeness=None,
discovery_source=discovery_source,
)
if not _is_full_openalex_display_name(display_name):
base.exclusion_reason = "incomplete_openalex_display_name"
return base
if not base.has_topic_profile or not base.primary_field_id or not base.primary_subfield_id:
base.exclusion_reason = "missing_field_or_subfield"
return base
# Production-count only — do not use eval metrics / topic-only for selection.
pool = await build_name_matched_pool(author_id)
base.name_matched_count = len(pool.candidates)
base.is_ambiguous = pool.is_ambiguous
base.search_completeness = pool.search_completeness
base.error = pool.error
base.display_name = display_name
if pool.error or not pool.candidates:
base.exclusion_reason = f"pipeline_error:{pool.error or 'no_candidates'}"
return base
patent_topic_map = await _resolve_topic_map(pool.candidates)
production = _variant_production(pool, author, patent_topic_map)
base.production_kept_count = len(production.kept_ids)
if base.production_kept_count < MIN_PRODUCTION_KEPT:
base.exclusion_reason = f"production_kept_below_min:{base.production_kept_count}"
elif base.production_kept_count > MAX_PRODUCTION_KEPT:
base.exclusion_reason = f"production_kept_above_max:{base.production_kept_count}"
return base
def _prior_field_counts() -> dict[str, int]:
counts: dict[str, int] = defaultdict(int)
for track in EXPERIMENT_TRACKS:
path = _track_paths(track)["authors"]
if not path.exists():
continue
payload = _load_json(path)
for author in payload.get("authors") or []:
fid = author.get("primary_field_id")
if fid:
counts[str(fid)] += 1
return counts
def _pick_six_field_diverse(
screens: list[AuthorScreen],
*,
prior_field_counts: dict[str, int],
rng: random.Random,
) -> tuple[list[AuthorScreen], dict[str, Any]]:
"""Pick six authors: valid 5–10 patents first, then maximize distinct fields.
UDE/external is documented only — never a ranking signal.
"""
eligible = [s for s in screens if _screen_eligible(s)]
rng.shuffle(eligible)
def rank(screen: AuthorScreen) -> tuple:
fid = screen.primary_field_id or ""
preferred = 0 if fid in PREFERRED_FIELDS else 1
prior = prior_field_counts.get(fid, 0)
kept_dist = abs(screen.production_kept_count - IDEAL_PRODUCTION_KEPT)
# Stable tie-break by author_id only — no UDE preference.
return (preferred, prior, kept_dist, screen.author_id)
ranked = sorted(eligible, key=rank)
selected: list[AuthorScreen] = []
field_counts: dict[str, int] = defaultdict(int)
subfields_by_field: dict[str, set[str]] = defaultdict(set)
domains: set[str] = set()
family_counts: dict[str, int] = defaultdict(int)
# Pass 1: one author per field when possible (target 6 distinct fields).
for screen in ranked:
if len(selected) >= SELECT_COUNT:
break
fid = screen.primary_field_id or ""
sid = screen.primary_subfield_id or ""
fam = screen.family_name or ""
if family_counts[fam] >= MAX_SAME_LAST_NAME:
continue
if field_counts[fid] >= 1:
continue
selected.append(screen)
screen.selection_reason = (
f"field_diversity_primary:{screen.primary_field_display_name}/"
f"{screen.primary_subfield_display_name}; "
f"production_patent_count={screen.production_kept_count}"
)
field_counts[fid] += 1
subfields_by_field[fid].add(sid)
if screen.primary_domain_id:
domains.add(screen.primary_domain_id)
family_counts[fam] += 1
# Pass 2: fill remaining with different subfields / domains; allow field reuse.
if len(selected) < SELECT_COUNT:
for screen in ranked:
if len(selected) >= SELECT_COUNT:
break
if screen in selected:
continue
fid = screen.primary_field_id or ""
sid = screen.primary_subfield_id or ""
fam = screen.family_name or ""
if family_counts[fam] >= MAX_SAME_LAST_NAME:
continue
if field_counts[fid] >= MAX_AUTHORS_PER_FIELD_IN_EXPERIMENT:
continue
if field_counts[fid] >= 1 and sid in subfields_by_field[fid]:
continue
selected.append(screen)
screen.selection_reason = (
f"fill_slot_distinct_subfield:{screen.primary_field_display_name}/"
f"{screen.primary_subfield_display_name}; "
f"production_patent_count={screen.production_kept_count}"
)
field_counts[fid] += 1
subfields_by_field[fid].add(sid)
if screen.primary_domain_id:
domains.add(screen.primary_domain_id)
family_counts[fam] += 1
# Pass 3: relax subfield uniqueness if still short.
if len(selected) < SELECT_COUNT:
for screen in ranked:
if len(selected) >= SELECT_COUNT:
break
if screen in selected:
continue
fid = screen.primary_field_id or ""
fam = screen.family_name or ""
if family_counts[fam] >= MAX_SAME_LAST_NAME:
continue
if field_counts[fid] >= MAX_AUTHORS_PER_FIELD_IN_EXPERIMENT:
continue
selected.append(screen)
screen.selection_reason = (
f"fill_slot_relaxed:{screen.primary_field_display_name}; "
f"production_patent_count={screen.production_kept_count}"
)
field_counts[fid] += 1
family_counts[fam] += 1
meta = {
"eligible_count": len(eligible),
"selected_field_counts": {
PREFERRED_FIELDS.get(fid, fid): count
for fid, count in field_counts.items()
},
"prior_field_counts": {
PREFERRED_FIELDS.get(fid, fid): count
for fid, count in prior_field_counts.items()
},
"ude_selected": sum(1 for s in selected if s.is_ude),
"external_selected": sum(1 for s in selected if not s.is_ude),
"unique_fields": len(field_counts),
"unique_domains": len(domains),
}
return selected[:SELECT_COUNT], meta
def _screen_to_author_payload(screen: AuthorScreen) -> dict[str, Any]:
return {
"author_id": screen.author_id,
"openalex_id": screen.openalex_id,
"display_name": screen.display_name,
"display_name_alternatives": screen.display_name_alternatives,
"group": "UDE" if screen.is_ude else "external",
"ude_affiliation_confirmed": screen.ude_affiliation_confirmed,
"ude_affiliation_source": screen.ude_affiliation_source,
"ude_institution_id": screen.ude_institution_id,
"last_known_institution": screen.last_known_institution,
"primary_topic_id": screen.primary_topic_id,
"primary_topic_display_name": screen.primary_topic_display_name,
"primary_field_id": screen.primary_field_id,
"primary_field_display_name": screen.primary_field_display_name,
"primary_subfield_id": screen.primary_subfield_id,
"primary_subfield_display_name": screen.primary_subfield_display_name,
"primary_domain_id": screen.primary_domain_id,
"primary_domain_display_name": screen.primary_domain,
"family_name": screen.family_name,
"name_matched_candidate_count": screen.name_matched_count,
"production_patent_count": screen.production_kept_count,
"selection_reason": screen.selection_reason,
"is_ambiguous": screen.is_ambiguous,
"has_topic_profile": screen.has_topic_profile,
"search_completeness": screen.search_completeness,
"discovery_source": screen.discovery_source,
}
def _render_selection_report(payload: dict[str, Any]) -> str:
sel = payload.get("selection") or {}
lines = [
f"# Author selection — {payload.get('evaluation_track')}",
"",
f"- Status: `{payload.get('selection_status')}`",
f"- Selected at: `{sel.get('selected_at')}`",
f"- Selection seed: `{sel.get('selection_seed')}`",
f"- Priority: valid 5–10 production patents → distinct fields → "
f"distinct subfields/domains → unique last names (UDE is metadata only)",
f"- Distinct fields: {sel.get('actual_distinct_fields')} "
f"(target {sel.get('target_distinct_fields')})",
"",
"## Selected authors",
"",
"| Author | Group | Field | Subfield | Name-matched | Production |",
"| --- | --- | --- | --- | ---: | ---: |",
]
for a in payload.get("authors", []):
lines.append(
"| {name} | {group} | {field} | {sub} | {nm} | {prod} |".format(
name=a.get("display_name"),
group=a.get("group"),
field=a.get("primary_field_display_name"),
sub=a.get("primary_subfield_display_name"),
nm=a.get("name_matched_candidate_count"),
prod=a.get("production_patent_count"),
)
)
lines.extend(
[
"",
"## Field distribution",
"",
json.dumps(sel.get("field_distribution"), indent=2, ensure_ascii=False),
"",
"## Group distribution",
"",
json.dumps(sel.get("actual_group_distribution"), indent=2, ensure_ascii=False),
"",
"## Notes",
"",
"- Selection completed before any gold labels.",
"- Metrics (P/R/F1) must not influence author choice.",
"",
]
)
if sel.get("historical_exclude_exceptions"):
lines.extend(
[
"## Historical exclude exceptions",
"",
json.dumps(
sel.get("historical_exclude_exceptions"),
indent=2,
ensure_ascii=False,
),
"",
]
)
return "\n".join(lines)
def _safe_print(message: str) -> None:
try:
print(message)
except UnicodeEncodeError:
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
sys.stdout.buffer.write((message + "\n").encode(encoding, errors="replace"))
async def cmd_select(args: argparse.Namespace) -> int:
used = _rebuild_used_authors_from_tracks()
# Hard excludes: other tracks + discarded previous experiment_1 cohort.
exclude = _used_author_id_set(used, exclude_track=args.track)
exclude |= set(PREVIOUS_EXPERIMENT_1_AUTHOR_IDS)
# Soft excludes: historical evaluation authors (may be waived if needed).
soft_exclude = set(HISTORICAL_EXCLUDE_AUTHOR_IDS) - exclude
exclude_with_history = set(exclude) | soft_exclude
prior_fields = _prior_field_counts()
this_authors_path = args.authors
if this_authors_path.exists():
prev = _load_json(this_authors_path)
for author in prev.get("authors") or []:
fid = author.get("primary_field_id")
if fid and prior_fields.get(str(fid), 0) > 0:
prior_fields[str(fid)] -= 1
candidates = await _discover_candidates_by_field(exclude_with_history)
logger.info(
"Track %s: screening up to %d candidates "
"(%d hard-excluded, %d soft-excluded historical)",
args.track,
len(candidates),
len(exclude),
len(soft_exclude),
)
screens: list[AuthorScreen] = []
for discovery_source, author_id in candidates:
screen = await screen_author(author_id, discovery_source=discovery_source)
screens.append(screen)
if screen.exclusion_reason:
logger.info(
"skip %s (%s): %s",
screen.author_id,
screen.display_name,
screen.exclusion_reason,
)
else:
logger.info(
"ok %s (%s): field=%s kept=%s ude=%s",
screen.author_id,
screen.display_name,
screen.primary_field_display_name,
screen.production_kept_count,
screen.is_ude,
)
eligible_so_far = [s for s in screens if _screen_eligible(s)]
fields = {s.primary_field_id for s in eligible_so_far}
if (
len(eligible_so_far) >= SELECT_COUNT + 12
and len(fields) >= TARGET_DISTINCT_FIELDS
):
logger.info(
"Early-stop after %d screens (%d eligible, %d fields)",
len(screens),
len(eligible_so_far),
len(fields),
)
break
# Targeted refill for preferred fields still missing eligible authors.
eligible = [s for s in screens if _screen_eligible(s)]
fields_eligible = {s.primary_field_id for s in eligible}
if len(eligible) < SELECT_COUNT or len(fields_eligible) < MIN_DISTINCT_FIELDS:
screens = await _refill_underrepresented_fields(
screens,
hard_exclude=exclude,
soft_exclude=soft_exclude,
)
historical_exceptions: list[str] = []
eligible = [s for s in screens if _screen_eligible(s)]
fields_eligible = {s.primary_field_id for s in eligible}
need_more = len(eligible) < SELECT_COUNT or len(fields_eligible) < MIN_DISTINCT_FIELDS
if need_more and soft_exclude:
logger.warning(
"Eligible=%d fields=%d with soft excludes; "
"retrying historical soft-exclude pool only if needed",
len(eligible),
len(fields_eligible),
)
extra_candidates = await _discover_candidates_by_field(exclude)
seen_ids = {s.author_id for s in screens}
for discovery_source, author_id in extra_candidates:
if author_id in seen_ids or author_id not in soft_exclude:
continue
screen = await screen_author(author_id, discovery_source=discovery_source)
screens.append(screen)
if _screen_eligible(screen):
historical_exceptions.append(author_id)
logger.info(
"historical soft-exclude exception %s (%s): kept=%s field=%s",
screen.author_id,
screen.display_name,
screen.production_kept_count,
screen.primary_field_display_name,
)
eligible = [s for s in screens if _screen_eligible(s)]
fields_eligible = {s.primary_field_id for s in eligible}
if len(eligible) >= SELECT_COUNT and len(fields_eligible) >= MIN_DISTINCT_FIELDS:
break
rng = random.Random(SELECTION_SEED)
selected, pick_meta = _pick_six_field_diverse(
screens, prior_field_counts=prior_fields, rng=rng
)
actual_fields = len({s.primary_field_id for s in selected if s.primary_field_id})
ready = (
len(selected) == SELECT_COUNT
and all(_screen_eligible(s) for s in selected)
and actual_fields >= MIN_DISTINCT_FIELDS
)
status = STATUS_READY_TO_FREEZE if ready else STATUS_NEEDS_REVIEW
stamp = _utc_stamp()
field_distribution: dict[str, int] = defaultdict(int)
for screen in selected:
name = screen.primary_field_display_name or screen.primary_field_id or "unknown"
field_distribution[name] += 1
group_dist = {
"UDE": sum(1 for s in selected if s.is_ude),
"external": sum(1 for s in selected if not s.is_ude),
}
excluded_ids = sorted(exclude_with_history)
payload = {
"version": 4,
"evaluation_track": args.track,
"selection_status": status,
"selection_seed": SELECTION_SEED,
"target_distinct_fields": TARGET_DISTINCT_FIELDS,
"actual_distinct_fields": actual_fields,
"field_diversity_target_met": actual_fields >= TARGET_DISTINCT_FIELDS,
"actual_group_distribution": group_dist,
"description": (
"Field-diversity author selection for production filter evaluation. "
"UDE is metadata only. Metrics must not influence selection."
),
"selection": {
"selected_at": stamp,
"track": args.track,
"selection_seed": SELECTION_SEED,
"target_count": SELECT_COUNT,
"selection_status": status,
"screened_count": len(screens),
"eligible_count": pick_meta["eligible_count"],
"target_distinct_fields": TARGET_DISTINCT_FIELDS,
"actual_distinct_fields": actual_fields,
"field_diversity_target_met": actual_fields >= TARGET_DISTINCT_FIELDS,
"min_distinct_fields": MIN_DISTINCT_FIELDS,
"actual_group_distribution": group_dist,
"screening_statistics": {
"screened_count": len(screens),
"eligible_count": pick_meta["eligible_count"],
"excluded_hard_count": len(exclude),
"excluded_soft_count": len(soft_exclude),
"unique_domains_selected": pick_meta.get("unique_domains"),
},
"excluded_author_ids": excluded_ids,
"historical_exclude_exceptions": historical_exceptions,
"criteria": {
"min_production_kept": MIN_PRODUCTION_KEPT,
"max_production_kept": MAX_PRODUCTION_KEPT,
"requires_full_display_name": True,
"requires_field_and_subfield": True,
"field_diversity_primary": True,
"max_authors_per_field_in_experiment": MAX_AUTHORS_PER_FIELD_IN_EXPERIMENT,
"max_same_last_name": MAX_SAME_LAST_NAME,
"ude_is_metadata_only": True,
"preferred_fields": PREFERRED_FIELDS,
"variants_planned": list(VARIANTS),
"topic_only_definition": TOPIC_ONLY_NAME,
"production_filter": FILTER_NAME,
"gold_labels_used_for_selection": False,
},
"field_distribution": dict(field_distribution),
"prior_field_counts": pick_meta["prior_field_counts"],
},
"authors": [_screen_to_author_payload(s) for s in selected],
}
_write_json(args.authors, payload)
args.selection_report.write_text(_render_selection_report(payload), encoding="utf-8")
used = _rebuild_used_authors_from_tracks()
used["by_track"][args.track] = [s.author_id for s in selected]
flat: list[str] = []
for track in EXPERIMENT_TRACKS:
flat.extend(used["by_track"].get(track) or [])
used["author_ids"] = sorted(set(flat))
used["updated_at"] = stamp
_save_used_authors(used)
_safe_print(f"track={args.track} selection_status={status}")
_safe_print(f"Selected {len(selected)} authors -> {args.authors}")
_safe_print(f"Selection report: {args.selection_report}")
_safe_print(
f"distinct_fields={actual_fields} "
f"UDE={group_dist['UDE']} external={group_dist['external']}"
)
for item in payload["authors"]:
_safe_print(
f" {item['openalex_id']} | {item['display_name']} | {item['group']} | "
f"{item['primary_field_display_name']} / {item['primary_subfield_display_name']} | "
f"name_matched={item['name_matched_candidate_count']} "
f"production={item['production_patent_count']}"
)
return 0 if status == STATUS_READY_TO_FREEZE else 1
# ---------------------------------------------------------------------------
# Freeze / evaluate
# ---------------------------------------------------------------------------
def _gold_label_from_existing(
existing: dict[str, Any],
patent: model.PatentEntry,
production_row: dict[str, Any],
) -> dict[str, Any]:
return {
"relevant": existing.get("relevant"),
"reviewed": existing.get("reviewed", False),
"notes": existing.get("notes", ""),
"title": patent.title or existing.get("title"),
"source": patent.source or existing.get("source"),
"application_number": patent.application_number
or existing.get("application_number"),
"production_kept": bool(production_row.get("production_kept")),
"production_keep_reason": production_row.get("keep_reason"),
}
def _select_gold_review_sample(
pool: NameMatchedPool,
production: VariantDecisions,
*,
max_candidates: int = MAX_GOLD_REVIEW_CANDIDATES,
) -> list[model.PatentEntry]:
"""All production keeps, then deterministic removes, capped at max_candidates.
Full pools stay in frozen_candidate_pool.json / filter_decisions.json.
No automatic label values are set.
"""
by_id = {
normalize_patent_id(p.patent_id): p
for p in pool.candidates
if p.patent_id
}
kept_ids = sorted(production.kept_ids)
removed_ids = sorted(production.removed_ids)
sample_ids: list[str] = []
for pid in kept_ids:
if pid in by_id:
sample_ids.append(pid)
if len(sample_ids) >= max_candidates:
break
if len(sample_ids) < max_candidates:
for pid in removed_ids:
if pid in by_id and pid not in sample_ids:
sample_ids.append(pid)
if len(sample_ids) >= max_candidates:
break
return [by_id[pid] for pid in sample_ids]
async def cmd_freeze(args: argparse.Namespace) -> int:
if not args.authors.exists():
print(f"Authors file missing: {args.authors}. Run select first.", file=sys.stderr)
return 1
authors_payload = _load_json(args.authors)
if authors_payload.get("evaluation_track") not in {None, args.track}:
print("Authors track mismatch.", file=sys.stderr)
return 1
authors = authors_payload.get("authors") or []
if len(authors) != SELECT_COUNT and not args.author:
print(f"Expected {SELECT_COUNT} authors, found {len(authors)}.", file=sys.stderr)
return 1
gold = (
_load_json(args.gold)
if args.gold.exists()
else {
"version": 3,
"evaluation_track": args.track,
"description": (
"Manual gold labels only. relevant: 1=belongs, 0=does not, null=uncertain."
),
"authors": {},
"label_schema": {
"relevant": "true/1 = belongs; false/0 = does not; null = uncertain",
"reviewed": "set true after manual review",
},
}
)
if gold.get("evaluation_track") not in {None, args.track}:
print("Refusing to mix gold labels across tracks.", file=sys.stderr)
return 1
stamp = _utc_stamp()
frozen_payload: dict[str, Any] = {
"version": 3,
"evaluation_track": args.track,
"frozen_at": stamp,
"description": "Name-matched candidate pool frozen before variant filters.",
"authors": {},
}
decisions_payload: dict[str, Any] = {
"version": 3,
"evaluation_track": args.track,
"frozen_at": stamp,
"variants": list(VARIANTS),
"topic_only_definition": TOPIC_ONLY_NAME,
"production_filter": FILTER_NAME,
"authors": {},
}
for item in authors:
author_id = _short_author_id(item["author_id"])
if args.author and author_id != _short_author_id(args.author):
continue
logger.info("Freezing %s (%s)", author_id, item.get("display_name"))
run = await run_all_variants(author_id)
pool: NameMatchedPool = run["pool"]
if pool.error:
print(f" ERROR {author_id}: {pool.error}", file=sys.stderr)
continue
variants: dict[str, VariantDecisions] = run["variants"]
frozen_payload["authors"][author_id] = {
"author_id": author_id,
"author_name": pool.author_name,
"display_name": item.get("display_name") or pool.author_name,
"primary_field_id": item.get("primary_field_id"),
"primary_field_display_name": item.get("primary_field_display_name"),
"primary_subfield_id": item.get("primary_subfield_id"),
"primary_subfield_display_name": item.get("primary_subfield_display_name"),
"group": item.get("group"),
"search_hit_count": pool.search_hit_count,
"search_completeness": pool.search_completeness,
"is_ambiguous": pool.is_ambiguous,
"name_matched_count": len(pool.candidates),
"candidates": [p.model_dump() for p in pool.candidates],
}
decisions_payload["authors"][author_id] = {
"author_name": pool.author_name,
"variants": {
name: {
"kept_count": len(vd.kept_ids),
"removed_count": len(vd.removed_ids),
"kept_ids": sorted(vd.kept_ids),
"removed_ids": sorted(vd.removed_ids),
"decisions": vd.decisions,
}
for name, vd in variants.items()
},
}
gold_authors = gold.setdefault("authors", {})
entry = gold_authors.setdefault(author_id, {"labels": {}})
labels = entry.setdefault("labels", {})
production_decisions = variants["production"].decisions
review_sample = _select_gold_review_sample(
pool, variants["production"]
)
entry["review_sample_ids"] = [
normalize_patent_id(p.patent_id) for p in review_sample
]
entry["review_sample_cap"] = MAX_GOLD_REVIEW_CANDIDATES
entry["name_matched_count"] = len(pool.candidates)
entry["production_kept_count"] = len(variants["production"].kept_ids)
# Drop stale gold rows that are no longer in the review sample.
keep_sample = set(entry["review_sample_ids"])
for stale in list(labels.keys()):
if normalize_patent_id(stale) not in keep_sample:
del labels[stale]
for patent in review_sample:
pid = normalize_patent_id(patent.patent_id)
labels[pid] = _gold_label_from_existing(
labels.get(pid, {}),
patent,
production_decisions.get(pid, {}),
)
gold.update(
{
"evaluation_track": args.track,
"updated_at": stamp,
"frozen_at": stamp,
"variants": list(VARIANTS),
"production_filter": FILTER_NAME,
"topic_only_definition": TOPIC_ONLY_NAME,
"frozen_candidate_pool": _display_path(args.frozen),
"filter_decisions": _display_path(args.decisions),
"gold_review_sample_cap": MAX_GOLD_REVIEW_CANDIDATES,
"gold_review_policy": (
"All production keeps, then deterministic production removes, "
f"capped at {MAX_GOLD_REVIEW_CANDIDATES} patents per author. "
"No automatic relevant labels."
),
}
)
_write_json(args.frozen, frozen_payload)
_write_json(args.decisions, decisions_payload)
_write_json(args.gold, gold)
result_payload = {
"created_at": stamp,
"frozen_at": stamp,
"mode": "freeze",
"evaluation_track": args.track,
"variants": list(VARIANTS),
"authors_file": _display_path(args.authors),
"gold_labels_file": _display_path(args.gold),
"note": "Gold labels awaiting manual review. No metrics yet.",
}
_write_json(args.result, result_payload)
args.report.write_text(
f"# Freeze report — {args.track}\n\n"
f"- Frozen at: `{stamp}`\n"
f"- Variants: {', '.join(VARIANTS)}\n"
f"- Topic-only: `{TOPIC_ONLY_NAME}`\n"
f"- Production: `{FILTER_NAME}`\n"
f"- Review `{_display_path(args.gold)}` then run evaluate.\n",
encoding="utf-8",
)
print(f"Frozen pool: {args.frozen}")
print(f"Decisions: {args.decisions}")
print(f"Gold labels: {args.gold}")
return 0
def canonical_candidate_key(value: Any) -> tuple[str, str, str, str, str]:
"""Stable 5-tuple identity used to join pool, labels, and decisions."""
if isinstance(value, list):
parts = value
elif isinstance(value, tuple):
parts = list(value)
elif isinstance(value, dict):
try:
parts = [
value["author_id"],
value["patent_family_key"],
value["patent_id"],
value["publication_date"],
value["application_number"],
]
except KeyError as exc:
raise ValueError(f"candidate_key dict missing field: {exc}") from exc
else:
raise ValueError(f"Unsupported candidate_key type: {type(value)!r}")
if len(parts) != 5:
raise ValueError(f"candidate_key must have 5 parts, got {len(parts)}: {parts!r}")
return tuple("" if part is None else str(part).strip() for part in parts)
def _strict_kept_bool(value: Any, *, field_name: str) -> bool:
"""Parse kept flags without bool('false') pitfalls."""
if isinstance(value, bool):
return value
if isinstance(value, str):
if value == "true":
return True
if value == "false":
return False
raise ValueError(
f"Invalid boolean for {field_name}: {value!r} "
"(only true/false or 'true'/'false' allowed)"
)
def _strict_gold_label(value: Any) -> int:
if value is True or value == 1:
return 1
if value is False or value == 0:
return 0
if isinstance(value, str) and value.strip() in {"0", "1"}:
return int(value.strip())
raise ValueError(f"Invalid gold label: {value!r}")
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
if precision is not None and recall is not None and (precision + recall) > 0:
f1 = 2 * precision * recall / (precision + recall)
else:
f1 = None
return {
"tp": tp,
"fp": fp,
"fn": fn,
"tn": tn,
"precision": precision,
"recall": recall,
"f1": f1,
}
def _format_metric(value: Any) -> str:
if value is None:
return "—"
if isinstance(value, float):
return f"{value:.6f}"
return str(value)
def _is_fixed_evaluate_payload(
frozen: dict[str, Any],
decisions: dict[str, Any],
gold: dict[str, Any],
) -> bool:
if frozen.get("imported_fixed_sample") or frozen.get("fixed_candidate_pool"):
return True
if decisions.get("fixed_candidate_replay"):
return True
if gold.get("imported_fixed_sample"):
return True
return False
def _collect_fixed_pool_rows(frozen: dict[str, Any]) -> dict[tuple[str, ...], dict[str, Any]]:
rows: dict[tuple[str, ...], dict[str, Any]] = {}
for author_id, block in (frozen.get("authors") or {}).items():
for cand in (block or {}).get("candidates") or []:
key = canonical_candidate_key(cand.get("candidate_key") or cand)
if key in rows:
raise ValueError(f"duplicate candidate_key in frozen pool: {key}")
row = dict(cand)
row.setdefault("author_id", author_id)
rows[key] = row
return rows
def _collect_fixed_label_rows(gold: dict[str, Any]) -> dict[tuple[str, ...], dict[str, Any]]:
rows: dict[tuple[str, ...], dict[str, Any]] = {}
# Prefer flat labels array when present (complete dump); else authors.*.labels.
flat = gold.get("labels")
if isinstance(flat, list) and flat:
sources = flat
else:
sources = []
for author_id, block in (gold.get("authors") or {}).items():
for _token, row in ((block or {}).get("labels") or {}).items():
if isinstance(row, dict):
item = dict(row)
item.setdefault("author_id", author_id)
sources.append(item)
for row in sources:
if not isinstance(row, dict):
raise ValueError("gold label row must be an object")
key = canonical_candidate_key(row.get("candidate_key") or row)
if key in rows:
raise ValueError(f"duplicate candidate_key in gold labels: {key}")
label = row.get("human_gold_label")
if label is None and "relevant" in row:
label = row.get("relevant")
rows[key] = {
**row,
"human_gold_label": _strict_gold_label(label),
"author_id": _short_author_id(str(row.get("author_id") or key[0])),
"patent_family_key": str(row.get("patent_family_key") or key[1]),
}
return rows
def _collect_fixed_decision_rows(
decisions: dict[str, Any],
) -> dict[tuple[str, ...], dict[str, Any]]:
rows: dict[tuple[str, ...], dict[str, Any]] = {}
candidates = decisions.get("candidates")
if not isinstance(candidates, list):
raise ValueError(
"filter_decisions.json must contain a top-level candidates list "
"for fixed evaluation"
)
for row in candidates:
if not isinstance(row, dict):
raise ValueError("decision row must be an object")
key = canonical_candidate_key(row.get("candidate_key") or row)
if key in rows:
raise ValueError(f"duplicate candidate_key in filter_decisions: {key}")
rows[key] = {
**row,
"name_matching_kept": _strict_kept_bool(
row.get("name_matching_kept"), field_name="name_matching_kept"
),
"topic_only_kept": _strict_kept_bool(
row.get("topic_only_kept"), field_name="topic_only_kept"
),
"production_kept": _strict_kept_bool(
row.get("production_kept"), field_name="production_kept"
),
"author_id": _short_author_id(str(row.get("author_id") or key[0])),
"patent_family_key": str(row.get("patent_family_key") or key[1]),
}
return rows
def _variant_kept_field(variant: str) -> str:
return {
"name_matching": "name_matching_kept",
"topic_only": "topic_only_kept",
"production": "production_kept",
}[variant]
def _confusion_from_pairs(pairs: list[tuple[int, bool]]) -> dict[str, Any]:
tp = fp = fn = tn = 0
for gold, kept in pairs:
if gold == 1 and kept:
tp += 1
elif gold == 0 and kept:
fp += 1
elif gold == 1 and not kept:
fn += 1
else:
tn += 1
return _prf_from_counts(tp, fp, fn, tn)
def normalize_field_name(name: str) -> str:
"""Normalize field display names for grouping (trim + casefold)."""
return str(name).strip().casefold()
def _resolve_aggregation_field(
author_row: dict[str, Any] | None,
pool_rows_for_author: list[dict[str, Any]],
) -> dict[str, Any]:
"""Resolve aggregation field with the same fallback order as evaluate.
Order:
1. primary_field_display_name
2. evaluation_field_original
3. consistent evaluation_field from frozen candidates
primary_field_id is optional and never required.
"""
author_row = author_row or {}
author_id = _short_author_id(str(author_row.get("author_id") or ""))
primary_id = author_row.get("primary_field_id")
if isinstance(primary_id, str) and not primary_id.strip():
primary_id = None
primary_name = author_row.get("primary_field_display_name")
if primary_name is not None and str(primary_name).strip():
display = str(primary_name).strip()
return {
"author_id": author_id,
"aggregation_field_id": primary_id,
"aggregation_field_display_name": display,
"field_metadata_source": (
"openalex_current_profile"
if primary_id
else "historical_evaluation_field"
),
"field_id_missing": primary_id is None,
"field_fallback": "primary_field_display_name",
"field_group_key": normalize_field_name(display),
}
original = author_row.get("evaluation_field_original")
if original is not None and str(original).strip():
display = str(original).strip()
return {
"author_id": author_id,
"aggregation_field_id": primary_id,
"aggregation_field_display_name": display,
"field_metadata_source": "historical_evaluation_field",
"field_id_missing": True,
"field_fallback": "evaluation_field_original",
"field_group_key": normalize_field_name(display),
}
fields = sorted(
{
str(r.get("evaluation_field")).strip()
for r in pool_rows_for_author
if r.get("evaluation_field") is not None
and str(r.get("evaluation_field")).strip()
}
)
if len(fields) > 1:
raise ValueError(
f"Author {author_id or '?'} has conflicting candidate evaluation_field "
f"values: {fields}"
)
if len(fields) == 1:
display = fields[0]
return {
"author_id": author_id,
"aggregation_field_id": None,
"aggregation_field_display_name": display,
"field_metadata_source": "historical_evaluation_field",
"field_id_missing": True,
"field_fallback": "candidate_evaluation_field",
"field_group_key": normalize_field_name(display),
}
raise ValueError(
f"Author {author_id or '?'} missing usable field metadata."
)
def _resolve_author_field(
author_row: dict[str, Any] | None,
pool_rows_for_author: list[dict[str, Any]],
) -> str:
"""Display-name only resolver shared by evaluate and aggregate."""
return _resolve_aggregation_field(author_row, pool_rows_for_author)[
"aggregation_field_display_name"
]
def _archive_invalid_evaluate_outputs(result_path: Path, report_path: Path) -> None:
mapping = [
(result_path, result_path.with_name("evaluation_result.invalid_join.json")),
(report_path, report_path.with_name("evaluation_report.invalid_join.md")),
]
for src, dest in mapping:
if not src.exists():
continue
if dest.exists():
dest.unlink()
src.rename(dest)
def _evaluate_fixed_track(
args: argparse.Namespace,
*,
authors_payload: dict[str, Any],
gold: dict[str, Any],
decisions: dict[str, Any],
frozen: dict[str, Any],
) -> int:
track = args.track
stamp = _utc_stamp()
expected_n = FIXED_EXPERIMENT_SPECS[track]["expected_candidates"]
expected_pos = FIXED_EXPERIMENT_SPECS[track]["expected_positive"]
expected_neg = FIXED_EXPERIMENT_SPECS[track]["expected_negative"]
gold_hash_before = _sha256_file(args.gold)
decisions_hash_before = _sha256_file(args.decisions)
frozen_hash_before = _sha256_file(args.frozen)
try:
pool_rows = _collect_fixed_pool_rows(frozen)
label_rows = _collect_fixed_label_rows(gold)
decision_rows = _collect_fixed_decision_rows(decisions)
except ValueError as exc:
print(f"evaluate aborted: {exc}", file=sys.stderr)
return 1
pool_keys = set(pool_rows)
label_keys = set(label_rows)
decision_keys = set(decision_rows)
missing_in_decisions = sorted(pool_keys - decision_keys)
missing_in_labels = sorted(pool_keys - label_keys)
extra_in_decisions = sorted(decision_keys - pool_keys)
extra_in_labels = sorted(label_keys - pool_keys)
set_ok = pool_keys == label_keys == decision_keys and len(pool_keys) == expected_n
if not set_ok:
print(f"evaluate aborted for {track}: key-set mismatch", file=sys.stderr)
print(f" pool_keys={len(pool_keys)} label_keys={len(label_keys)} "
f"decision_keys={len(decision_keys)} expected={expected_n}", file=sys.stderr)
print(f" missing_in_decisions={missing_in_decisions[:10]}", file=sys.stderr)
print(f" missing_in_labels={missing_in_labels[:10]}", file=sys.stderr)
print(f" extra_in_decisions={extra_in_decisions[:10]}", file=sys.stderr)
print(f" extra_in_labels={extra_in_labels[:10]}", file=sys.stderr)
return 1
authors_by_id = {
_short_author_id(str(a["author_id"])): a
for a in (authors_payload.get("authors") or [])
if a.get("author_id")
}
# Author field resolution + conflict checks.
field_by_author: dict[str, str] = {}
authors_without_field = 0
try:
by_author_pool: dict[str, list[dict[str, Any]]] = defaultdict(list)
for key, row in pool_rows.items():
by_author_pool[_short_author_id(str(row.get("author_id") or key[0]))].append(row)
for author_id, rows in by_author_pool.items():
field_by_author[author_id] = _resolve_author_field(
authors_by_id.get(author_id), rows
)
except ValueError as exc:
print(f"evaluate aborted: {exc}", file=sys.stderr)
return 1
if not field_by_author:
print("evaluate aborted: empty field distribution", file=sys.stderr)
return 1
# Family-level gold consistency.
family_groups: dict[tuple[str, str], list[tuple[str, ...]]] = defaultdict(list)
for key in pool_keys:
author_id = _short_author_id(str(label_rows[key]["author_id"]))
family_key = str(label_rows[key]["patent_family_key"])
family_groups[(author_id, family_key)].append(key)
conflicting_families: list[dict[str, Any]] = []
for (author_id, family_key), keys in family_groups.items():
labels = {label_rows[k]["human_gold_label"] for k in keys}
if len(labels) > 1:
conflicting_families.append(
{
"author_id": author_id,
"patent_family_key": family_key,
"labels": sorted(labels),
"candidate_count": len(keys),
}
)
if conflicting_families:
print(
f"evaluate aborted for {track}: conflicting gold labels within families",
file=sys.stderr,
)
for item in conflicting_families[:20]:
print(f" {item}", file=sys.stderr)
return 1
variant_metrics_candidate: dict[str, dict[str, Any]] = {}
variant_metrics_family: dict[str, dict[str, Any]] = {}
KEPT_FIELDS = {
"name_matching": "name_matching_kept",
"topic_only": "topic_only_kept",
"production": "production_kept",
}
for variant, kept_field in KEPT_FIELDS.items():
cand_pairs: list[tuple[int, bool]] = []
for key in sorted(pool_keys):
gold_label = label_rows[key]["human_gold_label"]
# Missing decision already impossible due to set equality, but never default.
if key not in decision_rows:
print(f"evaluate aborted: missing decision for {key}", file=sys.stderr)
return 1
if kept_field not in decision_rows[key]:
print(
f"evaluate aborted: missing {kept_field} for {key}",
file=sys.stderr,
)
return 1
kept = decision_rows[key][kept_field]
if not isinstance(kept, bool):
# Already normalized in collector; re-check.
kept = _strict_kept_bool(kept, field_name=kept_field)
cand_pairs.append((gold_label, kept))
variant_metrics_candidate[variant] = _confusion_from_pairs(cand_pairs)
fam_pairs: list[tuple[int, bool]] = []
for (author_id, family_key), keys in sorted(family_groups.items()):
gold_label = label_rows[keys[0]]["human_gold_label"]
kept_any = False
for key in keys:
kept_any = kept_any or bool(decision_rows[key][kept_field])
fam_pairs.append((gold_label, kept_any))
variant_metrics_family[variant] = _confusion_from_pairs(fam_pairs)
nm = variant_metrics_candidate["name_matching"]
all_nm_true = all(
decision_rows[key]["name_matching_kept"] is True for key in pool_keys
)
sanity_ok = (
all_nm_true
and nm["tp"] == expected_pos
and nm["fp"] == expected_neg
and nm["fn"] == 0
and nm["tn"] == 0
and nm["recall"] == 1.0
)
if not sanity_ok:
print(
f"evaluate aborted for {track}: failed_sanity_check "
f"name_matching={nm} all_name_matching_kept={all_nm_true}",
file=sys.stderr,
)
failed_path = _track_dir(track) / "evaluation_failed_sanity_check.json"
_write_json(
failed_path,
{
"evaluation_status": "failed_sanity_check",
"evaluation_track": track,
"created_at": stamp,
"name_matching": nm,
"all_name_matching_kept": all_nm_true,
"expected_positive": expected_pos,
"expected_negative": expected_neg,
},
)
return 1
# Field distribution table.
field_table: dict[str, dict[str, Any]] = {}
for key in pool_keys:
author_id = _short_author_id(str(label_rows[key]["author_id"]))
field = field_by_author[author_id]
entry = field_table.setdefault(
field,
{
"field": field,
"authors": set(),
"candidates": 0,
"positive": 0,
"negative": 0,
},
)
entry["authors"].add(author_id)
entry["candidates"] += 1
if label_rows[key]["human_gold_label"] == 1:
entry["positive"] += 1
else:
entry["negative"] += 1
if not field_table:
print("evaluate aborted: empty field distribution despite labels", file=sys.stderr)
return 1
field_rows = [
{
"field": name,
"authors": len(entry["authors"]),
"candidates": entry["candidates"],
"positive": entry["positive"],
"negative": entry["negative"],
}
for name, entry in sorted(field_table.items())
]
# Confirm inputs unchanged.
if _sha256_file(args.gold) != gold_hash_before:
print("evaluate aborted: gold_labels.json changed during evaluate", file=sys.stderr)
return 1
if _sha256_file(args.decisions) != decisions_hash_before:
print("evaluate aborted: filter_decisions.json changed during evaluate", file=sys.stderr)
return 1
if _sha256_file(args.frozen) != frozen_hash_before:
print("evaluate aborted: frozen_candidate_pool.json changed during evaluate", file=sys.stderr)
return 1
_archive_invalid_evaluate_outputs(args.result, args.report)
result_payload = {
"created_at": stamp,
"mode": "evaluate",
"evaluation_status": "completed",
"evaluation_track": track,
"variants": list(VARIANTS),
"topic_only_definition": TOPIC_ONLY_NAME,
"production_filter": FILTER_NAME,
"join_key": "canonical_candidate_key",
"levels": ["candidate_level", "family_level"],
"key_counts": {
"pool_keys": len(pool_keys),
"label_keys": len(label_keys),
"decision_keys": len(decision_keys),
"expected_candidates": expected_n,
},
"missing_in_decisions": [],
"missing_in_labels": [],
"extra_in_decisions": [],
"extra_in_labels": [],
"field_distribution": {
row["field"]: {
"authors": row["authors"],
"candidates": row["candidates"],
"positive": row["positive"],
"negative": row["negative"],
}
for row in field_rows
},
"field_table": field_rows,
"authors_without_field": authors_without_field,
"name_matching_sanity_check": {
"passed": True,
"tp": nm["tp"],
"fp": nm["fp"],
"fn": nm["fn"],
"tn": nm["tn"],
"precision": nm["precision"],
"recall": nm["recall"],
"f1": nm["f1"],
},
"candidate_level": variant_metrics_candidate,
"family_level": variant_metrics_family,
"name_matching_note": (
"Recall for name_matching is 1.0 on the complete frozen name pool "
"because every candidate is kept. Precision shows how many name "
"candidates truly belong."
),
"gold_labels_modified": False,
"filter_decisions_modified": False,
"live_search_performed": False,
"schema_paths": {
"pool_candidates": "frozen_candidate_pool.authors.*.candidates[]",
"gold_labels": "gold_labels.labels[] or gold_labels.authors.*.labels.*",
"gold_value": "human_gold_label",
"candidate_key": "candidate_key[5]",
"name_matching_kept": "filter_decisions.candidates[].name_matching_kept",
"topic_only_kept": "filter_decisions.candidates[].topic_only_kept",
"production_kept": "filter_decisions.candidates[].production_kept",
"author_field": (
"authors[].primary_field_display_name|"
"evaluation_field_original|evaluation_field|"
"frozen.candidates[].evaluation_field"
),
},
}
_write_json(args.result, result_payload)
lines = [
f"# Evaluation report — {track}",
"",
f"- Created: `{stamp}`",
f"- Status: `completed`",
f"- Join key: `canonical_candidate_key`",
f"- Candidates: `{len(pool_keys)}`",
"",
"## Field distribution",
"",
"| Field | Authors | Candidates | Positive | Negative |",
"| --- | ---: | ---: | ---: | ---: |",
]
for row in field_rows:
lines.append(
f"| {row['field']} | {row['authors']} | {row['candidates']} | "
f"{row['positive']} | {row['negative']} |"
)
lines.extend(
[
"",
"## Candidate-level metrics",
"",
"| Variant | P | R | F1 | TP | FP | FN | TN |",
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
)
for variant in VARIANTS:
m = variant_metrics_candidate[variant]
lines.append(
f"| {variant} | {_format_metric(m['precision'])} | "
f"{_format_metric(m['recall'])} | {_format_metric(m['f1'])} | "
f"{m['tp']} | {m['fp']} | {m['fn']} | {m['tn']} |"
)
lines.extend(
[
"",
"## Family-level metrics",
"",
"| Variant | P | R | F1 | TP | FP | FN | TN |",
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
)
for variant in VARIANTS:
m = variant_metrics_family[variant]
lines.append(
f"| {variant} | {_format_metric(m['precision'])} | "
f"{_format_metric(m['recall'])} | {_format_metric(m['f1'])} | "
f"{m['tp']} | {m['fp']} | {m['fn']} | {m['tn']} |"
)
lines.extend(
[
"",
"## Name-matching interpretation",
"",
result_payload["name_matching_note"],
"",
"## Sanity check",
"",
"- name_matching_kept all true: yes",
f"- name_matching TP/FP/FN/TN: {nm['tp']}/{nm['fp']}/{nm['fn']}/{nm['tn']}",
f"- recall: {_format_metric(nm['recall'])}",
"",
]
)
args.report.write_text("\n".join(lines) + "\n", encoding="utf-8")
_safe_print(f"track={track}")
_safe_print(f"evaluation_status=completed")
_safe_print(
f"pool_keys={len(pool_keys)} label_keys={len(label_keys)} "
f"decision_keys={len(decision_keys)}"
)
_safe_print(
f"name_matching candidate-level "
f"TP={nm['tp']} FP={nm['fp']} FN={nm['fn']} TN={nm['tn']} "
f"P={_format_metric(nm['precision'])} R={_format_metric(nm['recall'])} "
f"F1={_format_metric(nm['f1'])}"
)
for variant in ("topic_only", "production"):
m = variant_metrics_candidate[variant]
_safe_print(
f"{variant} candidate-level "
f"TP={m['tp']} FP={m['fp']} FN={m['fn']} TN={m['tn']} "
f"P={_format_metric(m['precision'])} R={_format_metric(m['recall'])} "
f"F1={_format_metric(m['f1'])}"
)
_safe_print(f"fields={json.dumps({r['field']: r['authors'] for r in field_rows}, ensure_ascii=False)}")
_safe_print(f"Evaluation result: {args.result}")
_safe_print(f"Report: {args.report}")
return 0
def _normalize_gold_relevant(value: Any) -> bool | None:
if value is None:
return None
if isinstance(value, bool):
return value
if value in (1, "1", "true", "True"):
return True
if value in (0, "0", "false", "False"):
return False
return None
async def cmd_evaluate(args: argparse.Namespace) -> int:
if not args.authors.exists() or not args.gold.exists():
print("Run select and freeze first.", file=sys.stderr)
return 1
authors_payload = _load_json(args.authors)
gold = _load_json(args.gold)
decisions = _load_json(args.decisions) if args.decisions.exists() else None
frozen = _load_json(args.frozen) if args.frozen.exists() else None
if not decisions or not frozen:
print("Missing frozen artifacts. Run freeze/replay-fixed first.", file=sys.stderr)
return 1
if authors_payload.get("evaluation_track") not in {None, args.track}:
print("Authors track mismatch.", file=sys.stderr)
return 1
if gold.get("evaluation_track") not in {None, args.track}:
print("Gold track mismatch.", file=sys.stderr)
return 1
if _is_fixed_evaluate_payload(frozen, decisions, gold):
status_path = _track_dir(args.track) / "replay_fixed_status.json"
if not status_path.exists():
print(
f"Fixed track {args.track} requires completed replay-fixed first.",
file=sys.stderr,
)
return 1
replay_status = (_load_json(status_path) or {}).get("replay_status")
if replay_status != "completed":
print(
f"evaluate blocked for {args.track}: replay_status={replay_status}",
file=sys.stderr,
)
return 1
if decisions.get("replay_status") != "completed":
print(
f"evaluate blocked for {args.track}: filter_decisions replay_status "
f"!= completed",
file=sys.stderr,
)
return 1
return _evaluate_fixed_track(
args,
authors_payload=authors_payload,
gold=gold,
decisions=decisions,
frozen=frozen,
)
# Legacy evaluate path (non-fixed freeze artifacts with authors/variants schema).
stamp = _utc_stamp()
gold_authors = gold.get("authors") or {}
per_variant_author_blocks: dict[str, list[dict[str, Any]]] = {
v: [] for v in VARIANTS
}
per_variant_metrics: dict[str, list[dict[str, Any]]] = {v: [] for v in VARIANTS}
field_dist: dict[str, int] = defaultdict(int)
for item in authors_payload.get("authors") or []:
author_id = _short_author_id(item["author_id"])
if args.author and author_id != _short_author_id(args.author):
continue
field_name = (
item.get("primary_field_display_name")
or item.get("evaluation_field_original")
or item.get("primary_field_id")
)
if field_name:
field_dist[str(field_name)] += 1
raw_labels = (gold_authors.get(author_id) or {}).get("labels") or {}
labels: dict[str, dict[str, Any]] = {}
for pid, row in raw_labels.items():
labels[normalize_patent_id(pid)] = {
**row,
"relevant": _normalize_gold_relevant(row.get("relevant")),
}
author_decisions = (decisions.get("authors") or {}).get(author_id) or {}
frozen_author = (frozen.get("authors") or {}).get(author_id) or {}
gold_entry = gold_authors.get(author_id) or {}
review_sample_ids = {
normalize_patent_id(pid)
for pid in (gold_entry.get("review_sample_ids") or [])
}
gold_label_ids = {
normalize_patent_id(pid) for pid in (gold_entry.get("labels") or {})
}
candidate_ids = review_sample_ids or gold_label_ids
if not candidate_ids:
candidate_ids = {
normalize_patent_id(c.get("patent_id"))
for c in frozen_author.get("candidates") or []
if c.get("patent_id")
}
if not candidate_ids:
for vname in VARIANTS:
candidate_ids |= set(
((author_decisions.get("variants") or {}).get(vname) or {}).get(
"decisions"
)
or {}
)
for variant in VARIANTS:
vblock = (author_decisions.get("variants") or {}).get(variant) or {}
if "kept_ids" not in vblock:
print(
f"evaluate aborted: missing kept_ids for {author_id}/{variant}",
file=sys.stderr,
)
return 1
kept_ids = {
normalize_patent_id(pid) for pid in (vblock.get("kept_ids") or [])
}
metrics = _classification_metrics(
kept_ids, labels, candidate_ids=candidate_ids
)
block = {
"author_id": author_id,
"display_name": item.get("display_name"),
"group": item.get("group"),
"primary_field_id": item.get("primary_field_id"),
"primary_field_display_name": item.get("primary_field_display_name"),
"primary_subfield_display_name": item.get(
"primary_subfield_display_name"
),
"candidate_count": len(candidate_ids),
"kept_count": len(kept_ids),
"removed_count": len(candidate_ids) - len(kept_ids),
"label_metrics": metrics,
}
per_variant_author_blocks[variant].append(block)
per_variant_metrics[variant].append(metrics)
variant_summaries = {
variant: {
"aggregate": _aggregate_variant_metrics(per_variant_metrics[variant]),
"authors": per_variant_author_blocks[variant],
}
for variant in VARIANTS
}
result_payload = {
"created_at": stamp,
"mode": "evaluate",
"evaluation_status": "completed",
"evaluation_track": args.track,
"variants": list(VARIANTS),
"topic_only_definition": TOPIC_ONLY_NAME,
"production_filter": FILTER_NAME,
"field_distribution": dict(field_dist),
"name_matching_note": (
"Recall for name_matching is normally 1.0 on a complete candidate pool "
"because no candidate is removed. High recall is not evidence of reliable "
"attribution; precision shows how many name candidates truly belong."
),
"variant_results": variant_summaries,
}
_write_json(args.result, result_payload)
lines = [
f"# Evaluation report — {args.track}",
"",
f"- Created: `{stamp}`",
f"- Variants: {', '.join(VARIANTS)}",
"",
"## Field distribution",
"",
"| Field | Authors |",
"| --- | ---: |",
]
if not field_dist:
lines.append("| _(empty)_ | 0 |")
else:
for name, count in sorted(field_dist.items()):
lines.append(f"| {name} | {count} |")
lines.extend(
[
"",
"## Variant summary (micro)",
"",
"| Variant | P | R | F1 | TP | FP | FN | TN |",
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
)
for variant in VARIANTS:
micro = variant_summaries[variant]["aggregate"].get("micro") or {}
lines.append(
f"| {variant} | {_format_metric(micro.get('precision'))} | "
f"{_format_metric(micro.get('recall'))} | "
f"{_format_metric(micro.get('f1'))} | "
f"{micro.get('tp')} | {micro.get('fp')} | "
f"{micro.get('fn')} | {micro.get('tn')} |"
)
lines.extend(
[
"",
"## Name-matching interpretation",
"",
result_payload["name_matching_note"],
"",
]
)
args.report.write_text("\n".join(lines), encoding="utf-8")
print(f"Evaluation result: {args.result}")
print(f"Report: {args.report}")
return 0
# ---------------------------------------------------------------------------
# Aggregate
# ---------------------------------------------------------------------------
def _mean_defined(values: list[float | None]) -> tuple[float | None, int]:
defined = [v for v in values if v is not None]
if not defined:
return None, 0
return round(sum(defined) / len(defined), 4), len(defined)
def _metrics_from_level_block(block: dict[str, Any] | None) -> dict[str, Any]:
block = block or {}
return {
"tp": int(block.get("tp") or 0),
"fp": int(block.get("fp") or 0),
"fn": int(block.get("fn") or 0),
"tn": int(block.get("tn") or 0),
"precision": block.get("precision"),
"recall": block.get("recall"),
"f1": block.get("f1"),
}
def cmd_aggregate(_args: argparse.Namespace) -> int:
experiments: dict[str, dict[str, Any]] = {}
input_hashes: dict[str, dict[str, str]] = {}
for track in EXPERIMENT_TRACKS:
paths = _track_paths(track)
result_path = paths["result"]
authors_path = paths["authors"]
gold_path = paths["gold"]
decisions_path = paths["decisions"]
frozen_path = paths["frozen"]
required = {
"authors.json": authors_path,
"gold_labels.json": gold_path,
"evaluation_result.json": result_path,
"filter_decisions.json": decisions_path,
"frozen_candidate_pool.json": frozen_path,
}
missing = [name for name, path in required.items() if not path.exists()]
if missing:
print(
f"Experiment {track} incomplete (missing {', '.join(missing)}).",
file=sys.stderr,
)
return 1
result = _load_json(result_path)
if result.get("mode") != "evaluate":
print(f"{track}: run evaluate before aggregate.", file=sys.stderr)
return 1
if result.get("evaluation_status") != "completed":
print(
f"{track}: evaluate status is {result.get('evaluation_status')!r}, "
"expected 'completed'.",
file=sys.stderr,
)
return 1
experiments[track] = {
"result": result,
"authors": _load_json(authors_path),
"gold": _load_json(gold_path),
"decisions": _load_json(decisions_path),
"frozen": _load_json(frozen_path),
}
input_hashes[track] = {
"gold": _sha256_file(gold_path),
"decisions": _sha256_file(decisions_path),
"frozen": _sha256_file(frozen_path),
}
# Integrity: unique author IDs + usable field names (primary_field_id optional).
seen_ids: dict[str, str] = {}
author_field_meta: dict[str, dict[str, Any]] = {}
authors_with_primary_field_id = 0
authors_without_primary_field_id = 0
authors_fallback_original = 0
authors_fallback_candidate = 0
authors_fallback_primary_name = 0
authors_without_usable_field = 0
for track, bundle in experiments.items():
authors_by_id = {
_short_author_id(a["author_id"]): a
for a in bundle["authors"].get("authors") or []
if a.get("author_id")
}
pool_by_author: dict[str, list[dict[str, Any]]] = defaultdict(list)
for author_id, block in (bundle["frozen"].get("authors") or {}).items():
aid = _short_author_id(str(author_id))
for cand in (block or {}).get("candidates") or []:
pool_by_author[aid].append(cand)
for author_id, author in authors_by_id.items():
if author_id in seen_ids:
print(
f"Duplicate author {author_id} in {seen_ids[author_id]} and {track}.",
file=sys.stderr,
)
return 1
seen_ids[author_id] = track
try:
meta = _resolve_aggregation_field(
{**author, "author_id": author_id},
pool_by_author.get(author_id) or [],
)
except ValueError as exc:
authors_without_usable_field += 1
print(str(exc), file=sys.stderr)
return 1
author_field_meta[author_id] = {**meta, "track": track}
if meta.get("aggregation_field_id"):
authors_with_primary_field_id += 1
else:
authors_without_primary_field_id += 1
fb = meta.get("field_fallback")
if fb == "primary_field_display_name":
authors_fallback_primary_name += 1
elif fb == "evaluation_field_original":
authors_fallback_original += 1
elif fb == "candidate_evaluation_field":
authors_fallback_candidate += 1
if len(seen_ids) != 18:
print(
f"Expected exactly 18 distinct authors, found {len(seen_ids)}.",
file=sys.stderr,
)
return 1
if authors_without_usable_field:
print("Authors without usable field metadata present.", file=sys.stderr)
return 1
# Pooled micro from completed evaluate results (candidate + family levels).
pooled_candidate: dict[str, dict[str, int]] = {
v: {"tp": 0, "fp": 0, "fn": 0, "tn": 0} for v in VARIANTS
}
pooled_family: dict[str, dict[str, int]] = {
v: {"tp": 0, "fp": 0, "fn": 0, "tn": 0} for v in VARIANTS
}
per_exp_candidate: dict[str, list[dict[str, Any]]] = {v: [] for v in VARIANTS}
per_exp_family: dict[str, list[dict[str, Any]]] = {v: [] for v in VARIANTS}
for track, bundle in experiments.items():
result = bundle["result"]
cand_level = result.get("candidate_level") or {}
fam_level = result.get("family_level") or {}
# Legacy fallback (should not be needed for fixed tracks).
if not cand_level and result.get("variant_results"):
cand_level = {
variant: ((result["variant_results"].get(variant) or {})
.get("aggregate") or {}).get("micro")
or {}
for variant in VARIANTS
}
for variant in VARIANTS:
cm = _metrics_from_level_block(cand_level.get(variant))
fm = _metrics_from_level_block(fam_level.get(variant))
for key in ("tp", "fp", "fn", "tn"):
pooled_candidate[variant][key] += cm[key]
pooled_family[variant][key] += fm[key]
per_exp_candidate[variant].append({**cm, "track": track})
per_exp_family[variant].append({**fm, "track": track})
def _finalize_pooled(pooled: dict[str, dict[str, int]]) -> dict[str, dict[str, Any]]:
out: dict[str, dict[str, Any]] = {}
for variant in VARIANTS:
metrics = _prf_from_counts(
pooled[variant]["tp"],
pooled[variant]["fp"],
pooled[variant]["fn"],
pooled[variant]["tn"],
)
out[variant] = metrics
return out
pooled_candidate_metrics = _finalize_pooled(pooled_candidate)
pooled_family_metrics = _finalize_pooled(pooled_family)
mean_candidate: dict[str, Any] = {}
mean_family: dict[str, Any] = {}
for variant in VARIANTS:
mp, np_ = _mean_defined(
[x.get("precision") for x in per_exp_candidate[variant]]
)
mr, nr = _mean_defined([x.get("recall") for x in per_exp_candidate[variant]])
mf, nf = _mean_defined([x.get("f1") for x in per_exp_candidate[variant]])
mean_candidate[variant] = {
"mean_precision": mp,
"mean_precision_n": np_,
"mean_recall": mr,
"mean_recall_n": nr,
"mean_f1": mf,
"mean_f1_n": nf,
}
mp, np_ = _mean_defined([x.get("precision") for x in per_exp_family[variant]])
mr, nr = _mean_defined([x.get("recall") for x in per_exp_family[variant]])
mf, nf = _mean_defined([x.get("f1") for x in per_exp_family[variant]])
mean_family[variant] = {
"mean_precision": mp,
"mean_precision_n": np_,
"mean_recall": mr,
"mean_recall_n": nr,
"mean_f1": mf,
"mean_f1_n": nf,
}
# Sanity: pooled candidate counts must match evaluate sums.
expected_candidate = {
"name_matching": {"tp": 89, "fp": 42, "fn": 0, "tn": 0},
"topic_only": {"tp": 15, "fp": 2, "fn": 74, "tn": 40},
"production": {"tp": 32, "fp": 2, "fn": 57, "tn": 40},
}
for variant, expected in expected_candidate.items():
actual = {
k: pooled_candidate_metrics[variant][k] for k in ("tp", "fp", "fn", "tn")
}
if actual != expected:
print(
f"Aggregate aborted: candidate-level micro mismatch for {variant}: "
f"expected={expected} actual={actual}",
file=sys.stderr,
)
return 1
# Per-field metrics recomputed by joining fixed gold + decisions (no live search).
# Group key = normalized display name; report uses first-seen display spelling.
field_stats: dict[str, dict[str, Any]] = {}
display_by_group: dict[str, str] = {}
for track, bundle in experiments.items():
try:
label_rows = _collect_fixed_label_rows(bundle["gold"])
decision_rows = _collect_fixed_decision_rows(bundle["decisions"])
pool_rows = _collect_fixed_pool_rows(bundle["frozen"])
except ValueError as exc:
print(f"{track}: {exc}", file=sys.stderr)
return 1
if set(label_rows) != set(decision_rows) or set(label_rows) != set(pool_rows):
print(f"{track}: pool/label/decision key mismatch during aggregate.", file=sys.stderr)
return 1
for key, label in label_rows.items():
author_id = _short_author_id(str(label.get("author_id") or key[0]))
meta = author_field_meta.get(author_id)
if not meta:
print(
f"Author {author_id} missing usable field metadata.",
file=sys.stderr,
)
return 1
group = meta["field_group_key"]
display = meta["aggregation_field_display_name"]
display_by_group.setdefault(group, display)
fs = field_stats.setdefault(
group,
{
"author_ids": set(),
"candidate_keys": set(),
"positive": 0,
"negative": 0,
"field_metadata_source": meta["field_metadata_source"],
"field_id_missing": meta["field_id_missing"],
"aggregation_field_id": meta.get("aggregation_field_id"),
"variants": {
v: {"tp": 0, "fp": 0, "fn": 0, "tn": 0} for v in VARIANTS
},
},
)
fs["author_ids"].add(author_id)
fs["candidate_keys"].add(key)
gold_label = int(label["human_gold_label"])
if gold_label == 1:
fs["positive"] += 1
else:
fs["negative"] += 1
decision = decision_rows[key]
for variant in VARIANTS:
kept_field = _variant_kept_field(variant)
kept = decision[kept_field]
bucket = fs["variants"][variant]
if gold_label == 1 and kept:
bucket["tp"] += 1
elif gold_label == 0 and kept:
bucket["fp"] += 1
elif gold_label == 1 and not kept:
bucket["fn"] += 1
else:
bucket["tn"] += 1
field_rows: list[dict[str, Any]] = []
field_comparison: dict[str, Any] = {}
field_distribution: dict[str, Any] = {}
for group, fs in sorted(field_stats.items(), key=lambda kv: display_by_group[kv[0]]):
field_name = display_by_group[group]
authors_n = len(fs["author_ids"])
candidates_n = len(fs["candidate_keys"])
field_distribution[field_name] = {
"authors": authors_n,
"candidates": candidates_n,
"positive": fs["positive"],
"negative": fs["negative"],
"field_metadata_source": fs["field_metadata_source"],
"field_id_missing": fs["field_id_missing"],
"aggregation_field_id": fs.get("aggregation_field_id"),
}
best = {"precision": None, "recall": None, "f1": None}
best_scores = {"precision": -1.0, "recall": -1.0, "f1": -1.0}
caveats: list[str] = []
if authors_n < 2:
caveats.append("only_one_author")
labeled = fs["positive"] + fs["negative"]
if labeled < 10:
caveats.append("fewer_than_10_labeled_candidates")
if fs["positive"] == 0 or fs["negative"] == 0:
caveats.append("single_class_labels")
if fs["field_id_missing"]:
caveats.append("missing_primary_field_id")
for variant in VARIANTS:
b = fs["variants"][variant]
metrics = _prf_from_counts(b["tp"], b["fp"], b["fn"], b["tn"])
row = {
"field": field_name,
"authors": authors_n,
"candidates": candidates_n,
"positive_labels": fs["positive"],
"negative_labels": fs["negative"],
"variant": variant,
"level": "candidate_level",
"tp": metrics["tp"],
"fp": metrics["fp"],
"tn": metrics["tn"],
"fn": metrics["fn"],
"precision": metrics["precision"],
"recall": metrics["recall"],
"f1": metrics["f1"],
"field_metadata_source": fs["field_metadata_source"],
"field_id_missing": fs["field_id_missing"],
"caveats": caveats,
}
field_rows.append(row)
for metric in ("precision", "recall", "f1"):
val = row[metric]
if val is not None and val > best_scores[metric]:
best_scores[metric] = val
best[metric] = variant
field_comparison[field_name] = {
"best_precision_variant": best["precision"],
"best_recall_variant": best["recall"],
"best_f1_variant": best["f1"],
"caveats": caveats,
"stable_generalization": len(
[c for c in caveats if c != "missing_primary_field_id"]
)
== 0,
"field_metadata_source": fs["field_metadata_source"],
"field_id_missing": fs["field_id_missing"],
}
# Confirm gold/decisions/frozen unchanged.
for track in EXPERIMENT_TRACKS:
paths = _track_paths(track)
if _sha256_file(paths["gold"]) != input_hashes[track]["gold"]:
print(f"{track}: gold_labels.json changed during aggregate", file=sys.stderr)
return 1
if _sha256_file(paths["decisions"]) != input_hashes[track]["decisions"]:
print(
f"{track}: filter_decisions.json changed during aggregate",
file=sys.stderr,
)
return 1
if _sha256_file(paths["frozen"]) != input_hashes[track]["frozen"]:
print(
f"{track}: frozen_candidate_pool.json changed during aggregate",
file=sys.stderr,
)
return 1
stamp = _utc_stamp()
authors_missing_id = [
{
"author_id": aid,
"track": meta["track"],
"aggregation_field_display_name": meta["aggregation_field_display_name"],
"field_fallback": meta["field_fallback"],
"field_metadata_source": meta["field_metadata_source"],
}
for aid, meta in sorted(author_field_meta.items())
if meta.get("field_id_missing")
]
aggregate_payload = {
"created_at": stamp,
"mode": "aggregate",
"evaluation_status": "completed",
"experiments": list(EXPERIMENT_TRACKS),
"variants": list(VARIANTS),
"topic_only_definition": TOPIC_ONLY_NAME,
"production_filter": FILTER_NAME,
"author_count": len(seen_ids),
"field_resolution": {
"order": [
"primary_field_display_name",
"evaluation_field_original",
"candidate_evaluation_field",
],
"primary_field_id_optional": True,
"authors_with_primary_field_id": authors_with_primary_field_id,
"authors_without_primary_field_id": authors_without_primary_field_id,
"authors_fallback_primary_field_display_name": authors_fallback_primary_name,
"authors_fallback_evaluation_field_original": authors_fallback_original,
"authors_fallback_candidate_evaluation_field": authors_fallback_candidate,
"authors_without_usable_field": authors_without_usable_field,
"authors_missing_primary_field_id": authors_missing_id,
},
"field_distribution": field_distribution,
"candidate_level": {
"pooled_micro_metrics": pooled_candidate_metrics,
"mean_across_experiments": mean_candidate,
"per_experiment": {
variant: per_exp_candidate[variant] for variant in VARIANTS
},
},
"family_level": {
"pooled_micro_metrics": pooled_family_metrics,
"mean_across_experiments": mean_family,
"per_experiment": {
variant: per_exp_family[variant] for variant in VARIANTS
},
},
"per_field_metrics": field_rows,
"field_variant_comparison": field_comparison,
"author_field_metadata": author_field_meta,
"live_search_performed": False,
"gold_labels_modified": False,
"filter_decisions_modified": False,
"filter_decisions_recomputed": False,
"name_matching_note": (
"Recall for name_matching is 1.0 on the complete frozen name pool "
"because every candidate is kept. This is not evidence of reliable "
"attribution; use precision instead."
),
"interpretation_prompts": [
"In which fields does name matching produce especially many false positives?",
"In which fields does topic-only lose especially many true positives?",
"In which fields does production achieve the best balance?",
"Are there fields where topic mapping differentiates poorly?",
"Might results relate to broad/overlapping IPC/OpenAlex topics?",
"How strongly do the three experiments differ?",
],
}
AGGREGATE_DIR.mkdir(parents=True, exist_ok=True)
(AGGREGATE_DIR / "field_error_analysis").mkdir(parents=True, exist_ok=True)
result_path = AGGREGATE_DIR / "field_error_analysis" / "aggregate_result.json"
report_path = AGGREGATE_DIR / "field_error_analysis" / "aggregate_report.md"
csv_path = AGGREGATE_DIR / "field_error_analysis" / "field_metrics.csv"
_write_json(result_path, aggregate_payload)
with csv_path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(
handle,
fieldnames=[
"field",
"authors",
"candidates",
"positive_labels",
"negative_labels",
"variant",
"level",
"tp",
"fp",
"tn",
"fn",
"precision",
"recall",
"f1",
"field_metadata_source",
"field_id_missing",
"caveats",
],
)
writer.writeheader()
for row in field_rows:
writer.writerow(
{
**row,
"precision": row["precision"],
"recall": row["recall"],
"f1": row["f1"],
"caveats": ";".join(row["caveats"]),
}
)
lines = [
"# Aggregate field analysis",
"",
f"- Created: `{stamp}`",
f"- Status: `completed`",
f"- Experiments: {', '.join(EXPERIMENT_TRACKS)}",
f"- Authors: {len(seen_ids)}",
f"- Authors with primary_field_id: {authors_with_primary_field_id}",
f"- Authors without primary_field_id: {authors_without_primary_field_id}",
f"- Fallback evaluation_field_original: {authors_fallback_original}",
f"- Fallback candidate evaluation_field: {authors_fallback_candidate}",
f"- Authors without usable field: {authors_without_usable_field}",
"",
"## Candidate-level pooled micro metrics",
"",
"| Variant | P | R | F1 | TP | FP | FN | TN |",
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
for variant in VARIANTS:
m = pooled_candidate_metrics[variant]
lines.append(
f"| {variant} | {_format_metric(m['precision'])} | "
f"{_format_metric(m['recall'])} | {_format_metric(m['f1'])} | "
f"{m['tp']} | {m['fp']} | {m['fn']} | {m['tn']} |"
)
lines.extend(
[
"",
"## Family-level pooled micro metrics",
"",
"| Variant | P | R | F1 | TP | FP | FN | TN |",
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
)
for variant in VARIANTS:
m = pooled_family_metrics[variant]
lines.append(
f"| {variant} | {_format_metric(m['precision'])} | "
f"{_format_metric(m['recall'])} | {_format_metric(m['f1'])} | "
f"{m['tp']} | {m['fp']} | {m['fn']} | {m['tn']} |"
)
lines.extend(["", "## Mean across experiments (candidate-level)", ""])
for variant in VARIANTS:
m = mean_candidate[variant]
lines.append(
f"- **{variant}**: mean P={_format_metric(m['mean_precision'])} "
f"(n={m['mean_precision_n']}), "
f"mean R={_format_metric(m['mean_recall'])} (n={m['mean_recall_n']}), "
f"mean F1={_format_metric(m['mean_f1'])} (n={m['mean_f1_n']})"
)
lines.extend(
[
"",
"## Field distribution",
"",
"| Field | Authors | Candidates | Positive | Negative | Source | ID missing |",
"| --- | ---: | ---: | ---: | ---: | --- | --- |",
]
)
for field_name, entry in field_distribution.items():
lines.append(
f"| {field_name} | {entry['authors']} | {entry['candidates']} | "
f"{entry['positive']} | {entry['negative']} | "
f"{entry['field_metadata_source']} | {entry['field_id_missing']} |"
)
lines.extend(
[
"",
"## Per-field metrics (candidate-level)",
"",
"| Field | Authors | Candidates | Variant | TP | FP | TN | FN | P | R | F1 |",
"| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
)
for row in field_rows:
lines.append(
f"| {row['field']} | {row['authors']} | {row['candidates']} | {row['variant']} | "
f"{row['tp']} | {row['fp']} | {row['tn']} | {row['fn']} | "
f"{_format_metric(row['precision'])} | {_format_metric(row['recall'])} | "
f"{_format_metric(row['f1'])} |"
)
lines.extend(
[
"",
"## Authors without primary_field_id",
"",
]
)
if not authors_missing_id:
lines.append("_None._")
else:
lines.append("| Author | Track | Field | Fallback |")
lines.append("| --- | --- | --- | --- |")
for row in authors_missing_id:
lines.append(
f"| {row['author_id']} | {row['track']} | "
f"{row['aggregation_field_display_name']} | {row['field_fallback']} |"
)
lines.extend(
[
"",
"## Name-matching interpretation",
"",
aggregate_payload["name_matching_note"],
"",
"## Caveat",
"",
"Field results with one author, <10 labeled candidates, or single-class "
"labels are descriptive only and not stably generalizable. "
"Missing OpenAlex `primary_field_id` does not invalidate historical "
"field names (`field_metadata_source=historical_evaluation_field`).",
"",
"- Live search performed: no",
"- Gold labels modified: no",
"- Filter decisions recomputed: no",
"",
]
)
report_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
_safe_print(f"author_count={len(seen_ids)}")
_safe_print(f"authors_without_primary_field_id={authors_without_primary_field_id}")
_safe_print(
f"fallback_original={authors_fallback_original} "
f"fallback_candidate={authors_fallback_candidate}"
)
for variant in VARIANTS:
m = pooled_candidate_metrics[variant]
_safe_print(
f"candidate_level {variant}: "
f"TP={m['tp']} FP={m['fp']} FN={m['fn']} TN={m['tn']} "
f"P={_format_metric(m['precision'])} R={_format_metric(m['recall'])} "
f"F1={_format_metric(m['f1'])}"
)
_safe_print(f"Aggregate result: {result_path}")
_safe_print(f"Aggregate report: {report_path}")
_safe_print(f"Field metrics CSV: {csv_path}")
return 0
# ---------------------------------------------------------------------------
# Historical import (no live search)
# ---------------------------------------------------------------------------
def _methodical_roots(methodical_dir: Path) -> list[Path]:
roots = [methodical_dir, methodical_dir / "_archive_legacy"]
return [r for r in roots if r.exists()]
def _resolve_historical_file(
methodical_dir: Path,
filenames: tuple[str, ...],
source_roots: tuple[str, ...],
) -> dict[str, Any]:
checked: list[str] = []
for root_name in source_roots:
root = methodical_dir if root_name == "." else methodical_dir / root_name
for name in filenames:
path = root / name
checked.append(str(path))
if path.exists():
return {
"found": True,
"path": str(path),
"display": _display_path(path),
"checked": checked,
}
return {"found": False, "path": None, "display": None, "checked": checked}
def _inspect_json_counts(path: Path | None, kind: str) -> dict[str, Any]:
if path is None or not path.exists():
return {"available": False}
try:
payload = _load_json(path)
except Exception as exc:
return {"available": False, "error": str(exc)}
info: dict[str, Any] = {"available": True, "top_keys": list(payload.keys())[:20]}
if kind == "authors":
authors = payload.get("authors") or payload.get("selected_authors") or []
if isinstance(authors, dict):
authors = list(authors.values())
info["author_count"] = len(authors) if isinstance(authors, list) else None
fields = []
for author in authors if isinstance(authors, list) else []:
if isinstance(author, dict):
fields.append(
author.get("primary_field_display_name")
or author.get("primary_field")
or author.get("field")
)
info["field_names_sample"] = [f for f in fields if f][:12]
info["has_field_metadata"] = any(fields)
elif kind == "candidates":
authors = payload.get("authors") or {}
total = 0
if isinstance(authors, dict):
for entry in authors.values():
cands = (
(entry or {}).get("candidates")
or (entry or {}).get("patents")
or []
)
total += len(cands) if isinstance(cands, list) else 0
elif isinstance(payload.get("candidates"), list):
total = len(payload["candidates"])
info["candidate_count"] = total
elif kind == "gold":
authors = payload.get("authors") or {}
pos = neg = unresolved = reviewed = total = 0
if isinstance(authors, dict):
for entry in authors.values():
labels = (entry or {}).get("labels") or {}
if isinstance(labels, dict):
for row in labels.values():
total += 1
if not isinstance(row, dict):
continue
if row.get("reviewed"):
reviewed += 1
rel = row.get("relevant")
if rel is True or rel == 1 or rel == "1":
pos += 1
elif rel is False or rel == 0 or rel == "0":
neg += 1
else:
unresolved += 1
elif isinstance(entry, list):
total += len(entry)
info.update(
{
"label_rows": total,
"reviewed": reviewed,
"positive": pos,
"negative": neg,
"unresolved_or_null": unresolved,
}
)
elif kind == "metrics":
micro = payload.get("micro") or {}
info["micro_variants"] = list(micro.keys()) if isinstance(micro, dict) else []
text = json.dumps(payload)
info["mentions_combined_e"] = "combined_e" in text
info["mentions_production"] = "production" in text
info["mentions_topic_only"] = "topic_only" in text or "strict" in text
return info
def _candidate_key_token(candidate_key: Any) -> str:
if isinstance(candidate_key, (list, tuple)):
return json.dumps(list(candidate_key), ensure_ascii=False, separators=(",", ":"))
return str(candidate_key)
def _required_nonempty(value: Any) -> bool:
if value is None:
return False
if isinstance(value, str) and not value.strip():
return False
if isinstance(value, (list, tuple)) and len(value) == 0:
return False
return True
def _normalize_fixed_gold_label(value: Any) -> int | None:
if value is True or value == 1 or value == "1":
return 1
if value is False or value == 0 or value == "0":
return 0
return None
def _list_fixed_source_json_files(source_dir: Path) -> list[Path]:
if not source_dir.exists() or not source_dir.is_dir():
raise FileNotFoundError(f"source-dir not found or not a directory: {source_dir}")
files = sorted(p for p in source_dir.glob("*.json") if p.is_file())
if not files:
raise FileNotFoundError(f"No *.json files in source-dir: {source_dir}")
return files
def _match_identity(payload: dict[str, Any], spec: dict[str, Any]) -> list[str]:
mismatches: list[str] = []
for key in ("created_at", "validation_type", "source_run"):
expected = spec.get(key)
actual = payload.get(key)
if expected is not None and actual != expected:
mismatches.append(f"{key}: expected={expected!r} actual={actual!r}")
expected_batch = spec.get("batch_number")
if expected_batch is not None:
actual_batch = payload.get("batch_number")
if actual_batch != expected_batch:
mismatches.append(
f"batch_number: expected={expected_batch!r} actual={actual_batch!r}"
)
return mismatches
def _analyze_fixed_candidates(
candidates: list[dict[str, Any]],
*,
source_run: str,
) -> dict[str, Any]:
errors: list[str] = []
key_tokens: list[str] = []
key_set: set[str] = set()
duplicate_keys: list[str] = []
authors: dict[str, dict[str, Any]] = {}
family_counts: dict[tuple[str, str], int] = defaultdict(int)
field_dist: dict[str, int] = defaultdict(int)
positive = 0
negative = 0
unconfirmed = 0
null_labels = 0
required_fields = (
"author_id",
"patent_id",
"patent_family_key",
"application_number",
"publication_date",
"candidate_key",
)
for idx, row in enumerate(candidates):
if not isinstance(row, dict):
errors.append(f"row[{idx}]: not an object")
continue
for field in required_fields:
if not _required_nonempty(row.get(field)):
errors.append(f"row[{idx}]: missing/empty {field}")
review_status = row.get("review_status")
if review_status != "confirmed":
unconfirmed += 1
errors.append(
f"row[{idx}]: review_status={review_status!r} (expected 'confirmed')"
)
label = _normalize_fixed_gold_label(row.get("human_gold_label"))
if label is None:
null_labels += 1
errors.append(f"row[{idx}]: human_gold_label is null/invalid")
elif label == 1:
positive += 1
else:
negative += 1
token = _candidate_key_token(row.get("candidate_key"))
key_tokens.append(token)
if token in key_set:
duplicate_keys.append(token)
else:
key_set.add(token)
author_id = _short_author_id(str(row.get("author_id") or ""))
author_name = row.get("author_name") or row.get("display_name") or ""
evaluation_field = row.get("evaluation_field") or "Other"
family_key = str(row.get("patent_family_key") or "")
if author_id and family_key:
family_counts[(author_id, family_key)] += 1
entry = authors.setdefault(
author_id,
{
"author_id": author_id,
"display_name": author_name,
"evaluation_field_original": evaluation_field,
"candidate_count": 0,
"positive_label_count": 0,
"negative_label_count": 0,
"imported_fixed_sample": True,
"source_run": source_run,
"source_is_ude_value": row.get("is_ude"),
"primary_field_id": None,
"primary_field_display_name": None,
"primary_subfield_id": None,
"primary_subfield_display_name": None,
"field_metadata_source": "historical_evaluation_field",
"field_metadata_needs_review": True,
},
)
if author_name and not entry.get("display_name"):
entry["display_name"] = author_name
# Keep first seen evaluation_field; flag conflict.
if entry.get("evaluation_field_original") != evaluation_field:
entry.setdefault("evaluation_field_conflicts", [])
if evaluation_field not in entry["evaluation_field_conflicts"]:
entry["evaluation_field_conflicts"].append(evaluation_field)
entry["candidate_count"] += 1
if label == 1:
entry["positive_label_count"] += 1
elif label == 0:
entry["negative_label_count"] += 1
if "is_ude" in row and entry.get("source_is_ude_value") is None:
entry["source_is_ude_value"] = row.get("is_ude")
for author in authors.values():
field_dist[str(author.get("evaluation_field_original") or "Other")] += 1
unique_families = len(family_counts)
multi_families = sum(1 for count in family_counts.values() if count > 1)
other_authors = sum(
1
for author in authors.values()
if str(author.get("evaluation_field_original") or "").strip().lower() == "other"
)
return {
"errors": errors,
"author_count": len(authors),
"authors": authors,
"candidate_count": len(candidates),
"positive_labels": positive,
"negative_labels": negative,
"null_labels": null_labels,
"unconfirmed_reviews": unconfirmed,
"candidate_keys_unique": len(duplicate_keys) == 0 and len(key_tokens) == len(candidates),
"duplicate_candidate_keys": duplicate_keys[:20],
"unique_patent_families": unique_families,
"multi_occurrence_families": multi_families,
"field_distribution_historical": dict(sorted(field_dist.items())),
"other_author_count": other_authors,
"family_counts": {
f"{aid}|{fam}": count for (aid, fam), count in family_counts.items()
},
}
def _validate_fixed_track_payload(
track: str,
payload: dict[str, Any],
spec: dict[str, Any],
) -> dict[str, Any]:
identity_errors = _match_identity(payload, spec)
candidates = payload.get("candidates")
if not isinstance(candidates, list):
analysis = {
"errors": ["candidates must be a list"],
"author_count": 0,
"authors": {},
"candidate_count": 0,
"positive_labels": 0,
"negative_labels": 0,
"null_labels": 0,
"unconfirmed_reviews": 0,
"candidate_keys_unique": False,
"duplicate_candidate_keys": [],
"unique_patent_families": 0,
"multi_occurrence_families": 0,
"field_distribution_historical": {},
"other_author_count": 0,
}
else:
analysis = _analyze_fixed_candidates(
candidates,
source_run=str(spec.get("source_run") or payload.get("source_run") or ""),
)
count_errors: list[str] = []
checks = (
("expected_authors", analysis["author_count"], "authors"),
("expected_candidates", analysis["candidate_count"], "candidates"),
("expected_positive", analysis["positive_labels"], "positive labels"),
("expected_negative", analysis["negative_labels"], "negative labels"),
)
for key, actual, label in checks:
expected = spec.get(key)
if expected is not None and actual != expected:
count_errors.append(f"{label}: expected={expected} actual={actual}")
# Header candidate_count if present must match list length.
header_count = payload.get("candidate_count")
if header_count is not None and header_count != analysis["candidate_count"]:
count_errors.append(
f"payload.candidate_count={header_count} != len(candidates)="
f"{analysis['candidate_count']}"
)
all_errors = identity_errors + count_errors + list(analysis.get("errors") or [])
ok = len(all_errors) == 0 and bool(analysis.get("candidate_keys_unique"))
return {
"track": track,
"ok": ok,
"identity_errors": identity_errors,
"count_errors": count_errors,
"integrity_errors": analysis.get("errors") or [],
"created_at": payload.get("created_at"),
"validation_type": payload.get("validation_type"),
"source_run": payload.get("source_run"),
"batch_number": payload.get("batch_number"),
"author_count": analysis["author_count"],
"candidate_count": analysis["candidate_count"],
"positive_labels": analysis["positive_labels"],
"negative_labels": analysis["negative_labels"],
"candidate_keys_unique": analysis["candidate_keys_unique"],
"all_reviews_confirmed": analysis["unconfirmed_reviews"] == 0,
"null_labels": analysis["null_labels"],
"unique_patent_families": analysis["unique_patent_families"],
"multi_occurrence_families": analysis["multi_occurrence_families"],
"field_distribution_historical": analysis["field_distribution_historical"],
"other_author_count": analysis["other_author_count"],
"authors": analysis["authors"],
"variant_decisions_present": False,
"variant_decisions_note": (
"Source dumps have no topic_only/production decisions; "
"replay-fixed is required after import."
),
"fixed_candidate_replay_feasible": ok,
"errors": all_errors,
}
def _assign_fixed_source_files(
source_files: list[Path],
) -> tuple[dict[str, dict[str, Any]], dict[str, Any] | None, list[str]]:
"""Map JSON files by content identity. Abort on missing/ambiguous matches."""
loaded: list[tuple[Path, dict[str, Any]]] = []
errors: list[str] = []
for path in source_files:
try:
payload = _load_json(path)
except Exception as exc: # noqa: BLE001 — surface parse errors in plan
errors.append(f"{path.name}: failed to parse JSON ({exc})")
continue
if not isinstance(payload, dict):
errors.append(f"{path.name}: root must be an object")
continue
loaded.append((path, payload))
assignment: dict[str, dict[str, Any]] = {}
holdout: dict[str, Any] | None = None
for track, spec in FIXED_EXPERIMENT_SPECS.items():
matches = [
(path, payload)
for path, payload in loaded
if not _match_identity(payload, spec)
]
if len(matches) == 0:
errors.append(
f"{track}: no source file matched created_at={spec['created_at']} "
f"validation_type={spec['validation_type']}"
)
continue
if len(matches) > 1:
names = ", ".join(p.name for p, _ in matches)
errors.append(f"{track}: multiple source files matched ({names})")
continue
path, payload = matches[0]
assignment[track] = {"path": path, "payload": payload, "spec": spec}
holdout_matches = [
(path, payload)
for path, payload in loaded
if not _match_identity(payload, FIXED_HOLDOUT_SPEC)
]
if len(holdout_matches) == 0:
errors.append(
"holdout: no source file matched "
f"created_at={FIXED_HOLDOUT_SPEC['created_at']} "
f"validation_type={FIXED_HOLDOUT_SPEC['validation_type']}"
)
elif len(holdout_matches) > 1:
names = ", ".join(p.name for p, _ in holdout_matches)
errors.append(f"holdout: multiple source files matched ({names})")
else:
path, payload = holdout_matches[0]
holdout = {"path": path, "payload": payload, "spec": FIXED_HOLDOUT_SPEC}
assigned_paths = {item["path"] for item in assignment.values()}
if holdout:
assigned_paths.add(holdout["path"])
extras = [p.name for p, _ in loaded if p not in assigned_paths]
if extras:
errors.append(
"unassigned source files (not mapped to experiments/holdout): "
+ ", ".join(extras)
)
return assignment, holdout, errors
def build_fixed_import_plan(source_dir: Path) -> dict[str, Any]:
stamp = _utc_stamp()
try:
source_files = _list_fixed_source_json_files(source_dir)
except FileNotFoundError as exc:
return {
"created_at": stamp,
"mode": "import-fixed-experiments",
"source_dir": str(source_dir),
"confirm_import": False,
"import_performed": False,
"ok": False,
"blocking_issues": [str(exc)],
"experiments": {},
"holdout": None,
"author_selection_performed": False,
"candidate_discovery_performed": False,
"labels_modified": False,
}
assignment, holdout, assign_errors = _assign_fixed_source_files(source_files)
experiments: dict[str, Any] = {}
blocking = list(assign_errors)
for track, spec in FIXED_EXPERIMENT_SPECS.items():
item = assignment.get(track)
if not item:
experiments[track] = {
"track": track,
"ok": False,
"source_file": None,
"errors": [f"unmatched: {spec['validation_type']}"],
}
continue
report = _validate_fixed_track_payload(track, item["payload"], spec)
report["source_file"] = str(item["path"])
report["source_file_name"] = item["path"].name
report["target_dir"] = str(_track_dir(track))
report["planned_outputs"] = [
"source_snapshot.json",
"import_manifest.json",
"authors.json",
"frozen_candidate_pool.json",
"gold_labels.json",
]
experiments[track] = report
if not report["ok"]:
blocking.extend(f"{track}: {err}" for err in report["errors"][:30])
holdout_report: dict[str, Any] | None = None
if holdout:
payload = holdout["payload"]
candidates = payload.get("candidates") if isinstance(payload, dict) else None
analysis = _analyze_fixed_candidates(
candidates if isinstance(candidates, list) else [],
source_run=str(payload.get("source_run") or FIXED_HOLDOUT_SPEC["source_run"]),
)
identity_errors = _match_identity(payload, FIXED_HOLDOUT_SPEC)
holdout_errors = identity_errors + list(analysis.get("errors") or [])
holdout_report = {
"ok": len(holdout_errors) == 0 and analysis["candidate_keys_unique"],
"source_file": str(holdout["path"]),
"source_file_name": holdout["path"].name,
"target_dir": str(DATA_DIR / FIXED_HOLDOUT_SPEC["track_dir"]),
"created_at": payload.get("created_at"),
"validation_type": payload.get("validation_type"),
"source_run": payload.get("source_run"),
"author_count": analysis["author_count"],
"candidate_count": analysis["candidate_count"],
"positive_labels": analysis["positive_labels"],
"negative_labels": analysis["negative_labels"],
"candidate_keys_unique": analysis["candidate_keys_unique"],
"all_reviews_confirmed": analysis["unconfirmed_reviews"] == 0,
"unique_patent_families": analysis["unique_patent_families"],
"multi_occurrence_families": analysis["multi_occurrence_families"],
"field_distribution_historical": analysis["field_distribution_historical"],
"other_author_count": analysis["other_author_count"],
"mixed_into_experiments": False,
"errors": holdout_errors,
"authors": analysis["authors"],
"payload": payload,
"path": holdout["path"],
}
if not holdout_report["ok"]:
blocking.extend(f"holdout: {err}" for err in holdout_errors[:30])
ok = len(blocking) == 0 and all(
(experiments.get(track) or {}).get("ok") for track in EXPERIMENT_TRACKS
) and bool(holdout_report and holdout_report.get("ok"))
return {
"created_at": stamp,
"mode": "import-fixed-experiments",
"source_dir": str(source_dir),
"source_files": [str(p) for p in source_files],
"confirm_import": False,
"import_performed": False,
"ok": ok,
"blocking_issues": blocking,
"experiments": experiments,
"holdout": {
k: v
for k, v in (holdout_report or {}).items()
if k not in {"payload", "path", "authors"}
}
if holdout_report
else None,
"_holdout_internal": holdout_report,
"_assignment_internal": {
track: {"path": item["path"], "payload": item["payload"]}
for track, item in assignment.items()
},
"author_selection_performed": False,
"candidate_discovery_performed": False,
"labels_modified": False,
"production_code_modified": False,
"variant_decisions_missing": True,
"fixed_candidate_replay_appears_possible": ok,
"notes": [
"Without --confirm-import only validation + plan are produced.",
"OpenAlex field enrichment runs only on --confirm-import (fixed author IDs).",
"topic_only/production decisions are absent until replay-fixed.",
"Holdout is archived separately and not mixed into experiment_1/2/3.",
],
}
def _build_fixed_authors_payload(
track: str,
*,
source_run: str,
authors: dict[str, dict[str, Any]],
stamp: str,
) -> dict[str, Any]:
author_list = sorted(authors.values(), key=lambda a: a["author_id"])
return {
"version": 4,
"evaluation_track": track,
"created_at": stamp,
"selection_method": "imported_fixed_historical_sample",
"imported_fixed_sample": True,
"author_selection_performed": False,
"candidate_discovery_performed": False,
"source_run": source_run,
"authors": author_list,
"field_note": (
"evaluation_field_original is the historical evaluation category and may "
"be inaccurate. Prefer primary_field_* from OpenAlex when "
"field_metadata_source=openalex_current_profile."
),
}
def _build_fixed_gold_payload(
track: str,
*,
source_run: str,
candidates: list[dict[str, Any]],
stamp: str,
) -> dict[str, Any]:
authors: dict[str, Any] = {}
flat_labels: list[dict[str, Any]] = []
for row in candidates:
author_id = _short_author_id(str(row["author_id"]))
label = _normalize_fixed_gold_label(row.get("human_gold_label"))
assert label in (0, 1)
key = row["candidate_key"]
token = _candidate_key_token(key)
entry = authors.setdefault(
author_id,
{
"author_id": author_id,
"display_name": row.get("author_name"),
"labels": {},
},
)
label_row = {
"candidate_key": key,
"human_gold_label": label,
"relevant": label,
"review_status": "confirmed",
"reviewed": True,
"label_source": LABEL_SOURCE_FIXED,
"label_reason": row.get("label_reason"),
"evidence": row.get("evidence") if row.get("evidence") is not None else [],
"author_id": author_id,
"patent_id": row.get("patent_id"),
"patent_family_key": row.get("patent_family_key"),
"application_number": row.get("application_number"),
"publication_date": row.get("publication_date"),
"source_is_ude_value": row.get("is_ude"),
}
entry["labels"][token] = label_row
flat_labels.append(label_row)
return {
"version": 4,
"evaluation_track": track,
"created_at": stamp,
"source_run": source_run,
"imported_fixed_sample": True,
"label_source": LABEL_SOURCE_FIXED,
"label_note": (
"Labels were created/checked with AI assistance in an independent review; "
"not an exclusively human gold set."
),
"authors": authors,
"labels": flat_labels,
}
def _build_fixed_frozen_payload(
track: str,
*,
source_run: str,
candidates: list[dict[str, Any]],
authors: dict[str, dict[str, Any]],
stamp: str,
) -> dict[str, Any]:
by_author: dict[str, Any] = {}
for row in candidates:
author_id = _short_author_id(str(row["author_id"]))
entry = by_author.setdefault(
author_id,
{
"author_id": author_id,
"author_name": (authors.get(author_id) or {}).get("display_name")
or row.get("author_name"),
"display_name": (authors.get(author_id) or {}).get("display_name")
or row.get("author_name"),
"evaluation_field_original": (authors.get(author_id) or {}).get(
"evaluation_field_original"
),
"imported_fixed_sample": True,
"candidates": [],
},
)
cand = dict(row)
# Preserve historical is_ude only as source metadata; do not treat as truth.
if "is_ude" in cand:
cand["source_is_ude_value"] = cand.pop("is_ude")
# Strip gold fields from frozen pool objects (labels live in gold_labels.json).
for drop in ("human_gold_label", "review_status", "label_reason", "evidence"):
cand.pop(drop, None)
entry["candidates"].append(cand)
entry["name_matched_count"] = len(entry["candidates"])
return {
"version": 4,
"evaluation_track": track,
"frozen_at": stamp,
"source_run": source_run,
"imported_fixed_sample": True,
"fixed_candidate_pool": True,
"candidate_discovery_performed": False,
"description": (
"Historical name-matched candidate pool imported as-is. "
"Do not add/remove/replace candidates."
),
"authors": by_author,
}
def _write_fixed_track_import(
track: str,
*,
source_path: Path,
payload: dict[str, Any],
validation: dict[str, Any],
stamp: str,
enrich_openalex: bool,
) -> dict[str, Any]:
if not validation.get("ok"):
raise RuntimeError(f"Refusing to write {track}: validation failed")
authors_map = dict(validation["authors"])
source_run = str(validation.get("source_run") or payload.get("source_run") or "")
if enrich_openalex:
# Best-effort profile enrichment for fixed author IDs only (no new search).
for author_id, entry in authors_map.items():
try:
# Lazy import path already available via person_logic / ES helpers.
profile = None
try:
from inse.persons import logic as _person_logic # local alias
profile = _person_logic.get_author_by_id(author_id)
except Exception: # noqa: BLE001
profile = None
if profile is None:
entry["field_metadata_source"] = "historical_evaluation_field"
entry["field_metadata_needs_review"] = True
continue
topics = getattr(profile, "topics", None) or []
# Prefer explicit primary topic fields when present on Author model.
primary_field_id = None
primary_field_name = None
primary_subfield_id = None
primary_subfield_name = None
if topics:
top = topics[0]
field = getattr(top, "field", None) or (
top.get("field") if isinstance(top, dict) else None
)
subfield = getattr(top, "subfield", None) or (
top.get("subfield") if isinstance(top, dict) else None
)
if isinstance(field, dict):
primary_field_id = field.get("id")
primary_field_name = field.get("display_name")
elif field is not None:
primary_field_id = getattr(field, "id", None)
primary_field_name = getattr(field, "display_name", None)
if isinstance(subfield, dict):
primary_subfield_id = subfield.get("id")
primary_subfield_name = subfield.get("display_name")
elif subfield is not None:
primary_subfield_id = getattr(subfield, "id", None)
primary_subfield_name = getattr(subfield, "display_name", None)
entry["primary_field_id"] = primary_field_id
entry["primary_field_display_name"] = primary_field_name
entry["primary_subfield_id"] = primary_subfield_id
entry["primary_subfield_display_name"] = primary_subfield_name
if primary_field_id or primary_field_name:
entry["field_metadata_source"] = "openalex_current_profile"
entry["field_metadata_needs_review"] = (
str(entry.get("evaluation_field_original") or "").lower()
== "other"
and not primary_field_name
)
else:
entry["field_metadata_source"] = "historical_evaluation_field"
entry["field_metadata_needs_review"] = True
except Exception: # noqa: BLE001
entry["field_metadata_source"] = "historical_evaluation_field"
entry["field_metadata_needs_review"] = True
root = _track_dir(track)
root.mkdir(parents=True, exist_ok=True)
# Exact byte-preserving snapshot via copy of original file text.
snapshot_path = root / "source_snapshot.json"
snapshot_path.write_bytes(source_path.read_bytes())
authors_payload = _build_fixed_authors_payload(
track, source_run=source_run, authors=authors_map, stamp=stamp
)
gold_payload = _build_fixed_gold_payload(
track,
source_run=source_run,
candidates=list(payload.get("candidates") or []),
stamp=stamp,
)
frozen_payload = _build_fixed_frozen_payload(
track,
source_run=source_run,
candidates=list(payload.get("candidates") or []),
authors=authors_map,
stamp=stamp,
)
manifest = {
"created_at": stamp,
"mode": "import-fixed-experiments",
"evaluation_track": track,
"source_file": str(source_path),
"source_created_at": payload.get("created_at"),
"validation_type": payload.get("validation_type"),
"source_run": source_run,
"batch_number": payload.get("batch_number"),
"author_count": validation["author_count"],
"candidate_count": validation["candidate_count"],
"positive_labels": validation["positive_labels"],
"negative_labels": validation["negative_labels"],
"unique_patent_families": validation["unique_patent_families"],
"multi_occurrence_families": validation["multi_occurrence_families"],
"author_selection_performed": False,
"candidate_discovery_performed": False,
"labels_modified": False,
"openalex_enrichment_attempted": enrich_openalex,
"outputs": {
"source_snapshot": "source_snapshot.json",
"authors": "authors.json",
"frozen_candidate_pool": "frozen_candidate_pool.json",
"gold_labels": "gold_labels.json",
},
}
_write_json(root / "import_manifest.json", manifest)
_write_json(root / "authors.json", authors_payload)
_write_json(root / "gold_labels.json", gold_payload)
_write_json(root / "frozen_candidate_pool.json", frozen_payload)
return manifest
def cmd_import_fixed_experiments(args: argparse.Namespace) -> int:
source_dir = Path(getattr(args, "source_dir", None) or "")
if not source_dir:
print("--source-dir is required for import-fixed-experiments", file=sys.stderr)
return 2
confirm = bool(getattr(args, "confirm_import", False))
plan = build_fixed_import_plan(source_dir)
plan["confirm_import"] = confirm
# Persist a shareable plan without huge internal blobs.
plan_public = {
k: v
for k, v in plan.items()
if not k.startswith("_")
}
# Strip nested author maps from public experiment plan (keep counts).
experiments_public: dict[str, Any] = {}
for track, report in (plan.get("experiments") or {}).items():
experiments_public[track] = {
k: v for k, v in report.items() if k != "authors"
}
plan_public["experiments"] = experiments_public
plan_path = DATA_DIR / "fixed_import_plan.json"
_write_json(plan_path, plan_public)
_safe_print(f"source_dir={source_dir}")
_safe_print(f"import_ok={plan['ok']}")
_safe_print(f"confirm_import={confirm}")
for track in EXPERIMENT_TRACKS:
report = (plan.get("experiments") or {}).get(track) or {}
_safe_print(
f"{track}: file={report.get('source_file_name')} "
f"authors={report.get('author_count')} "
f"candidates={report.get('candidate_count')} "
f"pos={report.get('positive_labels')} neg={report.get('negative_labels')} "
f"families={report.get('unique_patent_families')} "
f"multi_fam={report.get('multi_occurrence_families')} "
f"other_authors={report.get('other_author_count')} "
f"keys_unique={report.get('candidate_keys_unique')} "
f"confirmed={report.get('all_reviews_confirmed')} ok={report.get('ok')}"
)
fields = report.get("field_distribution_historical") or {}
_safe_print(f" fields={json.dumps(fields, ensure_ascii=False)}")
holdout = plan.get("holdout") or {}
if holdout:
_safe_print(
f"holdout: file={holdout.get('source_file_name')} "
f"authors={holdout.get('author_count')} "
f"candidates={holdout.get('candidate_count')} "
f"ok={holdout.get('ok')} mixed_into_experiments=False"
)
for issue in plan.get("blocking_issues") or []:
_safe_print(f"BLOCK: {issue}")
_safe_print(f"Import plan: {plan_path}")
_safe_print("author_selection_performed=False")
_safe_print("candidate_discovery_performed=False")
_safe_print("labels_modified=False")
_safe_print("variant_decisions_missing=True (need replay-fixed after import)")
_safe_print(
f"fixed_candidate_replay_appears_possible={plan.get('fixed_candidate_replay_appears_possible')}"
)
if not confirm:
_safe_print("Dry-run only (pass --confirm-import to write track files).")
return 0 if plan["ok"] else 1
if not plan["ok"]:
print(
"Refusing --confirm-import because validation failed. No target files written.",
file=sys.stderr,
)
return 1
stamp = _utc_stamp()
written: list[str] = []
assignment = plan.get("_assignment_internal") or {}
for track in EXPERIMENT_TRACKS:
item = assignment[track]
validation = plan["experiments"][track]
# Re-attach authors map from validation (present in full plan before strip).
# Rebuild authors from payload to be safe.
rebuilt = _validate_fixed_track_payload(
track, item["payload"], FIXED_EXPERIMENT_SPECS[track]
)
manifest = _write_fixed_track_import(
track,
source_path=item["path"],
payload=item["payload"],
validation=rebuilt,
stamp=stamp,
enrich_openalex=True,
)
written.append(str(_track_dir(track)))
_safe_print(f"Wrote {track}: {manifest['candidate_count']} candidates")
holdout_internal = plan.get("_holdout_internal")
if holdout_internal:
hroot = DATA_DIR / FIXED_HOLDOUT_SPEC["track_dir"]
hroot.mkdir(parents=True, exist_ok=True)
source_path = holdout_internal["path"]
payload = holdout_internal["payload"]
(hroot / "source_snapshot.json").write_bytes(source_path.read_bytes())
authors_map = holdout_internal["authors"]
authors_payload = _build_fixed_authors_payload(
FIXED_HOLDOUT_SPEC["track_dir"],
source_run=str(payload.get("source_run") or ""),
authors=authors_map,
stamp=stamp,
)
gold_payload = _build_fixed_gold_payload(
FIXED_HOLDOUT_SPEC["track_dir"],
source_run=str(payload.get("source_run") or ""),
candidates=list(payload.get("candidates") or []),
stamp=stamp,
)
frozen_payload = _build_fixed_frozen_payload(
FIXED_HOLDOUT_SPEC["track_dir"],
source_run=str(payload.get("source_run") or ""),
candidates=list(payload.get("candidates") or []),
authors=authors_map,
stamp=stamp,
)
_write_json(
hroot / "import_manifest.json",
{
"created_at": stamp,
"mode": "import-fixed-experiments",
"role": "holdout_archive_only",
"mixed_into_experiments": False,
"source_file": str(source_path),
"source_created_at": payload.get("created_at"),
"validation_type": payload.get("validation_type"),
"source_run": payload.get("source_run"),
"author_count": holdout_internal["author_count"],
"candidate_count": holdout_internal["candidate_count"],
"positive_labels": holdout_internal["positive_labels"],
"negative_labels": holdout_internal["negative_labels"],
},
)
_write_json(hroot / "authors.json", authors_payload)
_write_json(hroot / "gold_labels.json", gold_payload)
_write_json(hroot / "frozen_candidate_pool.json", frozen_payload)
written.append(str(hroot))
_safe_print(f"Archived holdout -> {hroot}")
plan_public["import_performed"] = True
plan_public["written_dirs"] = written
_write_json(plan_path, plan_public)
_safe_print("Import complete.")
return 0
def _sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _sha256_file(path: Path) -> str:
return _sha256_bytes(path.read_bytes())
def _pipeline_fingerprint() -> str:
payload = {
"mode": "replay-fixed",
"production_filter": FILTER_NAME,
"topic_only_definition": TOPIC_ONLY_NAME,
"script": Path(__file__).name,
"script_sha256": _sha256_file(Path(__file__)),
}
return _sha256_bytes(
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
)
def _normalize_date_token(value: Any) -> str:
if value is None:
return ""
text = str(value).strip()
if not text:
return ""
digits = "".join(ch for ch in text if ch.isdigit())
return digits[:8] if digits else text
def _iter_frozen_candidates(frozen: dict[str, Any]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for author_id, block in (frozen.get("authors") or {}).items():
for cand in (block or {}).get("candidates") or []:
if not isinstance(cand, dict):
continue
row = dict(cand)
row.setdefault("author_id", author_id)
rows.append(row)
return rows
def _candidate_identity_tuple(row: dict[str, Any]) -> tuple[str, str, str, str, str]:
return (
_short_author_id(str(row.get("author_id") or "")),
str(row.get("patent_family_key") or ""),
str(row.get("patent_id") or ""),
_normalize_date_token(row.get("publication_date")),
str(row.get("application_number") or ""),
)
def _topic_only_keep_and_reason(
mapped_topics: list[Any] | None,
author: Author,
) -> tuple[bool, str]:
mapped = list(mapped_topics or [])
author_refs = author_openalex_topic_refs(author)
keep = mapped_topics_match_author_strict(mapped, author)
if not mapped:
return keep, "missing_topic_mapping"
for item in mapped:
refs = mapped_topic_refs(item)
if refs.topic_ids & author_refs.topic_ids:
return True, "exact_topic_id_overlap"
if refs.subfield_ids & author_refs.subfield_ids:
return True, "exact_subfield_id_overlap"
if keep:
# mapped_topics_match_author_strict keeps when author has no topic/subfield refs
return True, "exact_topic_id_overlap"
return False, "no_strict_topic_overlap"
def _pick_patent_hit(
hits: list[model.PatentEntry],
*,
patent_id: str,
publication_date: str,
application_number: str,
) -> model.PatentEntry | None:
if not hits:
return None
want_pid = normalize_patent_id(patent_id)
want_date = _normalize_date_token(publication_date)
want_app = str(application_number or "").strip()
def score(hit: model.PatentEntry) -> tuple[int, int, int]:
pid_ok = int(normalize_patent_id(hit.patent_id) == want_pid)
date_ok = int(_normalize_date_token(hit.publication_date) == want_date) if want_date else 0
app_ok = int(
bool(want_app)
and str(hit.application_number or "").strip() == want_app
)
return (pid_ok, date_ok, app_ok)
ranked = sorted(hits, key=score, reverse=True)
best = ranked[0]
best_score = score(best)
if best_score[0] != 1:
# Require patent_id match; otherwise reject.
return None
if want_date and best_score[1] != 1:
# Prefer exact publication stage; if unavailable, still allow same patent_id.
same_id = [h for h in hits if normalize_patent_id(h.patent_id) == want_pid]
if not same_id:
return None
# Keep closest: prefer matching application number among same patent_id.
same_id_ranked = sorted(same_id, key=score, reverse=True)
return same_id_ranked[0]
return best
async def _lookup_patent_hits(
search_client: PatentSearchClient,
*,
source: str,
patent_id: str,
application_number: str | None,
) -> list[model.PatentEntry]:
source_u = (source or "").upper()
pid = str(patent_id or "").strip()
app = str(application_number or "").strip()
hits: list[model.PatentEntry] = []
try:
if source_u == "EPO" or pid.upper().startswith("EP"):
if app:
data = await search_client.search_epo(
search_client.epo_query_by_application_number(app, size=50)
)
hits.extend(parse_epo_hits(data))
doc_number = pid.upper().removeprefix("EP")
if doc_number:
payload = {
"size": 50,
"query": {
"bool": {
"should": [
{"term": {"doc_number": doc_number}},
{"term": {"doc_number": doc_number.lstrip("0")}},
],
"minimum_should_match": 1,
}
},
"_source": [
"doc_number",
"country",
"kind",
"date_publication",
"date_publication_year",
"application_number",
"application_filing_date",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
"cpc",
],
}
data = await search_client.search_epo(payload)
hits.extend(parse_epo_hits(data))
else:
pub_number = pid.upper().removeprefix("US")
should: list[dict[str, Any]] = []
if pub_number:
should.extend(
[
{"term": {"publication_number": pub_number}},
{"term": {"publication_number": pub_number.lstrip("0")}},
]
)
if app:
should.append({"term": {"application_number": app}})
if should:
payload = {
"size": 50,
"query": {
"bool": {
"should": should,
"minimum_should_match": 1,
}
},
"_source": [
"publication_number",
"country",
"publication_date",
"publication_year",
"application_number",
"application_date",
"application_type",
"title",
"abstract",
"inventors_names",
"assignees_orgs",
"ipcr",
"cpc",
"number_of_claims",
"status",
],
}
data = await search_client.search_uspto(payload)
hits.extend(parse_uspto_hits(data))
except MissingApiKeyError:
raise
except Exception:
logger.exception(
"Patent lookup failed for patent_id=%s application_number=%s",
patent_id,
application_number,
)
return []
# Deduplicate by map key while preserving order.
seen: set[str] = set()
unique: list[model.PatentEntry] = []
for hit in hits:
key = patent_map_key(hit)
if key in seen:
continue
seen.add(key)
unique.append(hit)
return unique
async def _load_author_for_replay(author_id: str) -> tuple[Author | None, bool | None, str | None]:
"""Load fixed OpenAlex author profile only (no author search / discovery)."""
short_id = _short_author_id(author_id)
author = await _get_author(short_id)
if not author:
return None, None, "incomplete_missing_author_profile"
author_name = author.display_name or ""
try:
full_name_count = await person_logic.count_authors_by_display_name(author_name)
except Exception:
full_name_count = None
parsed = parse_person_name(author_name)
last_name_count: int | None = None
if parsed and not parsed.is_single_token:
try:
last_name_count = await person_logic.count_authors_by_last_name(
parsed.last_name
)
except Exception:
last_name_count = None
# patent_hit_count=0: we intentionally do not run inventor name search.
ambiguous = is_ambiguous_name(
author_name,
patent_hit_count=0,
openalex_full_name_count=full_name_count,
openalex_last_name_count=last_name_count,
)
return author, ambiguous, None
async def cmd_replay_fixed(args: argparse.Namespace) -> int:
"""Replay topic_only + production on an imported frozen candidate pool only."""
track = args.track
root = _track_dir(track)
paths = _track_paths(track)
frozen_path = args.frozen or paths["frozen"]
authors_path = args.authors or paths["authors"]
decisions_path = args.decisions or paths["decisions"]
gold_path = args.gold or paths["gold"]
manifest_path = root / "import_manifest.json"
snapshot_path = root / "source_snapshot.json"
status_path = root / "replay_fixed_status.json"
required = {
"authors.json": authors_path,
"frozen_candidate_pool.json": frozen_path,
"gold_labels.json": gold_path,
"import_manifest.json": manifest_path,
"source_snapshot.json": snapshot_path,
}
missing = [name for name, path in required.items() if not path.exists()]
if missing:
print(f"Missing required files for {track}: {', '.join(missing)}", file=sys.stderr)
return 1
# Integrity baselines — do not read gold label values for decisions.
gold_hash_before = _sha256_file(gold_path)
frozen_bytes = frozen_path.read_bytes()
frozen_hash_before = _sha256_bytes(frozen_bytes)
frozen = json.loads(frozen_bytes.decode("utf-8-sig"))
authors_payload = _load_json(authors_path)
_ = _load_json(manifest_path)
_ = _load_json(snapshot_path)
if not frozen.get("imported_fixed_sample") and not frozen.get("fixed_candidate_pool"):
print(
"frozen_candidate_pool.json is not marked as an imported fixed sample.",
file=sys.stderr,
)
return 1
stamp = _utc_stamp()
fingerprint = _pipeline_fingerprint()
frozen_rows = _iter_frozen_candidates(frozen)
expected_keys = [_candidate_key_token(r.get("candidate_key")) for r in frozen_rows]
if len(expected_keys) != len(set(expected_keys)):
status = {
"created_at": stamp,
"evaluation_track": track,
"fixed_candidate_replay": True,
"candidate_discovery_performed": False,
"author_selection_performed": False,
"replay_status": "candidate_key_mismatch",
"candidate_count": len(frozen_rows),
"completed_decision_count": 0,
"incomplete_candidate_count": len(frozen_rows),
"pipeline_fingerprint": fingerprint,
"candidate_pool_hash": frozen_hash_before,
"error": "duplicate candidate_key in frozen pool",
}
_write_json(status_path, status)
print("Replay aborted: duplicate candidate_key in frozen pool.", file=sys.stderr)
return 1
search_client = PatentSearchClient()
ipc_client = IpcSearchClient()
# Author profiles (fixed IDs only).
author_ids = sorted(
{
_short_author_id(str(a.get("author_id") or ""))
for a in (authors_payload.get("authors") or [])
if a.get("author_id")
}
| {
_short_author_id(str(r.get("author_id") or ""))
for r in frozen_rows
if r.get("author_id")
}
)
authors_by_id: dict[str, Author] = {}
ambiguous_by_id: dict[str, bool] = {}
author_errors: dict[str, str] = {}
for author_id in author_ids:
author, ambiguous, err = await _load_author_for_replay(author_id)
if err or author is None:
author_errors[author_id] = err or "incomplete_missing_author_profile"
continue
authors_by_id[author_id] = author
ambiguous_by_id[author_id] = bool(ambiguous)
decision_rows: list[dict[str, Any]] = []
incomplete: list[dict[str, Any]] = []
loaded_patents: dict[str, model.PatentEntry] = {}
# Load patent records for frozen candidates only (by patent_id / application_number).
for row in frozen_rows:
token = _candidate_key_token(row.get("candidate_key"))
author_id = _short_author_id(str(row.get("author_id") or ""))
base = {
"candidate_key": row.get("candidate_key"),
"author_id": author_id,
"patent_id": row.get("patent_id"),
"patent_family_key": row.get("patent_family_key"),
"publication_date": row.get("publication_date"),
"application_number": row.get("application_number"),
"name_matching_kept": True,
}
if author_id in author_errors:
incomplete.append(
{
**base,
"enrichment_status": "incomplete",
"replay_error": author_errors[author_id],
"topic_only_kept": None,
"topic_only_reason": None,
"production_kept": None,
"production_keep_reason": None,
}
)
continue
try:
hits = await _lookup_patent_hits(
search_client,
source=str(row.get("source") or ""),
patent_id=str(row.get("patent_id") or ""),
application_number=row.get("application_number"),
)
except MissingApiKeyError as exc:
print(f"Patent Elasticsearch not configured: {exc}", file=sys.stderr)
status = {
"created_at": stamp,
"evaluation_track": track,
"fixed_candidate_replay": True,
"candidate_discovery_performed": False,
"author_selection_performed": False,
"replay_status": "incomplete_missing_patent_record",
"candidate_count": len(frozen_rows),
"completed_decision_count": 0,
"incomplete_candidate_count": len(frozen_rows),
"pipeline_fingerprint": fingerprint,
"candidate_pool_hash": frozen_hash_before,
"error": str(exc),
}
_write_json(status_path, status)
return 1
patent = _pick_patent_hit(
hits,
patent_id=str(row.get("patent_id") or ""),
publication_date=str(row.get("publication_date") or ""),
application_number=str(row.get("application_number") or ""),
)
if patent is None:
incomplete.append(
{
**base,
"enrichment_status": "incomplete",
"replay_error": "incomplete_missing_patent_record",
"topic_only_kept": None,
"topic_only_reason": None,
"production_kept": None,
"production_keep_reason": None,
}
)
continue
# Preserve frozen publication_date on the working patent object when possible
# so topic map keys stay stable across stages.
if row.get("publication_date") and not patent.publication_date:
patent.publication_date = str(row.get("publication_date"))
loaded_patents[token] = patent
# Classification enrichment for successfully loaded patents only.
# Empty IPC/CPC after a successful record load is a valid outcome (e.g. design
# patents) and yields topic_only_reason=missing_topic_mapping — not incomplete.
unique_patents = list({id(p): p for p in loaded_patents.values()}.values())
if unique_patents:
try:
await enrich_patents_classifications(unique_patents, ipc_client)
except Exception:
logger.exception("Classification enrichment failed during replay-fixed")
for token in list(loaded_patents):
row = next(
r
for r in frozen_rows
if _candidate_key_token(r.get("candidate_key")) == token
)
incomplete.append(
{
"candidate_key": row.get("candidate_key"),
"author_id": _short_author_id(str(row.get("author_id") or "")),
"patent_id": row.get("patent_id"),
"patent_family_key": row.get("patent_family_key"),
"publication_date": row.get("publication_date"),
"application_number": row.get("application_number"),
"name_matching_kept": True,
"enrichment_status": "incomplete",
"replay_error": "incomplete_missing_classification",
"topic_only_kept": None,
"topic_only_reason": None,
"production_kept": None,
"production_keep_reason": None,
}
)
del loaded_patents[token]
incomplete_tokens = {
_candidate_key_token(item.get("candidate_key")) for item in incomplete
}
complete_tokens = [t for t in loaded_patents if t not in incomplete_tokens]
patent_topic_map: dict[str, list] | None = None
topic_map_error: str | None = None
if complete_tokens:
try:
patents_for_topics = [loaded_patents[t] for t in complete_tokens]
patent_topic_map = await _resolve_topic_map(patents_for_topics)
if patent_topic_map is None:
topic_map_error = "incomplete_missing_topic_mapping"
except Exception:
logger.exception("Topic mapping failed during replay-fixed")
topic_map_error = "incomplete_missing_topic_mapping"
patent_topic_map = None
if topic_map_error:
for token in list(complete_tokens):
row = next(
r
for r in frozen_rows
if _candidate_key_token(r.get("candidate_key")) == token
)
incomplete.append(
{
"candidate_key": row.get("candidate_key"),
"author_id": _short_author_id(str(row.get("author_id") or "")),
"patent_id": row.get("patent_id"),
"patent_family_key": row.get("patent_family_key"),
"publication_date": row.get("publication_date"),
"application_number": row.get("application_number"),
"name_matching_kept": True,
"enrichment_status": "incomplete",
"replay_error": topic_map_error,
"topic_only_kept": None,
"topic_only_reason": None,
"production_kept": None,
"production_keep_reason": None,
}
)
loaded_patents.pop(token, None)
complete_tokens = []
# Compute filter decisions per author on complete patents only (no gold labels).
by_author_tokens: dict[str, list[str]] = defaultdict(list)
for token in complete_tokens:
row = next(
r
for r in frozen_rows
if _candidate_key_token(r.get("candidate_key")) == token
)
by_author_tokens[_short_author_id(str(row["author_id"]))].append(token)
for author_id, tokens in by_author_tokens.items():
author = authors_by_id[author_id]
patents = [loaded_patents[t] for t in tokens]
topic_only_by_token: dict[str, tuple[bool, str]] = {}
for token, patent in zip(tokens, patents):
mapped = []
if patent_topic_map is not None:
mapped = patent_topic_map.get(patent_map_key(patent), [])
topic_only_by_token[token] = _topic_only_keep_and_reason(mapped, author)
production_results = filter_patents_by_ipc_topic_mapping(
patents,
author,
is_ambiguous=bool(ambiguous_by_id.get(author_id, False)),
patent_topic_map=patent_topic_map,
)
# Match production results back by patent_map_key (not patent_id alone),
# because frozen pools may contain multiple publication stages.
kept_by_map_key = {
patent_map_key(result.patent): result for result in production_results
}
for token, patent in zip(tokens, patents):
row = next(
r
for r in frozen_rows
if _candidate_key_token(r.get("candidate_key")) == token
)
topic_kept, topic_reason = topic_only_by_token[token]
prod = kept_by_map_key.get(patent_map_key(patent))
decision_rows.append(
{
"candidate_key": row.get("candidate_key"),
"author_id": author_id,
"patent_id": row.get("patent_id"),
"patent_family_key": row.get("patent_family_key"),
"publication_date": row.get("publication_date"),
"application_number": row.get("application_number"),
"name_matching_kept": True,
"topic_only_kept": bool(topic_kept),
"topic_only_reason": topic_reason,
"production_kept": bool(prod is not None),
"production_keep_reason": (
getattr(prod, "keep_reason", None) if prod is not None else None
),
"enrichment_status": "complete",
}
)
# Merge incomplete rows into output candidates for documentation.
all_out = decision_rows + incomplete
out_by_token = {
_candidate_key_token(item.get("candidate_key")): item for item in all_out
}
# Ensure every frozen candidate appears exactly once in output order.
ordered_out: list[dict[str, Any]] = []
for row in frozen_rows:
token = _candidate_key_token(row.get("candidate_key"))
item = out_by_token.get(token)
if item is None:
incomplete.append(
{
"candidate_key": row.get("candidate_key"),
"author_id": _short_author_id(str(row.get("author_id") or "")),
"patent_id": row.get("patent_id"),
"name_matching_kept": True,
"enrichment_status": "incomplete",
"replay_error": "candidate_key_mismatch",
"topic_only_kept": None,
"production_kept": None,
}
)
ordered_out.append(incomplete[-1])
else:
ordered_out.append(item)
completed_decision_count = sum(
1 for item in ordered_out if item.get("enrichment_status") == "complete"
)
incomplete_candidate_count = len(ordered_out) - completed_decision_count
topic_only_kept_count = sum(
1 for item in ordered_out if item.get("topic_only_kept") is True
)
production_kept_count = sum(
1 for item in ordered_out if item.get("production_kept") is True
)
# Determine replay_status.
replay_status = "completed"
if incomplete_candidate_count:
error_counts: dict[str, int] = defaultdict(int)
for item in ordered_out:
if item.get("enrichment_status") != "complete":
error_counts[str(item.get("replay_error") or "incomplete")] += 1
# Prefer the most frequent concrete incomplete_* code.
replay_status = max(error_counts.items(), key=lambda kv: kv[1])[0]
if not str(replay_status).startswith("incomplete_"):
if replay_status == "candidate_key_mismatch":
pass
else:
replay_status = "incomplete_missing_enrichment"
if len(ordered_out) != len(frozen_rows):
replay_status = "candidate_count_mismatch"
out_keys = [_candidate_key_token(item.get("candidate_key")) for item in ordered_out]
if set(out_keys) != set(expected_keys):
replay_status = "candidate_key_mismatch"
if any(item.get("name_matching_kept") is not True for item in ordered_out):
replay_status = "candidate_key_mismatch"
decisions_payload = {
"evaluation_track": track,
"created_at": stamp,
"fixed_candidate_replay": True,
"candidate_discovery_performed": False,
"author_selection_performed": False,
"production_filter": FILTER_NAME,
"topic_only_definition": TOPIC_ONLY_NAME,
"pipeline_fingerprint": fingerprint,
"replay_status": replay_status,
"author_profile_source": "openalex_by_fixed_author_id",
"replay_timestamp": stamp,
"candidate_count": len(frozen_rows),
"completed_decision_count": completed_decision_count,
"incomplete_candidate_count": incomplete_candidate_count,
"candidates": ordered_out if replay_status == "completed" else ordered_out,
"incomplete_candidates": [
item
for item in ordered_out
if item.get("enrichment_status") != "complete"
],
"gold_labels_used_for_decisions": False,
"notes": [
"Decisions computed on frozen candidates only; no inventor name search.",
"Gold labels were not loaded for filter decisions.",
],
}
if replay_status != "completed":
# Do not pretend successful final decisions.
for item in decisions_payload["candidates"]:
if item.get("enrichment_status") != "complete":
item["topic_only_kept"] = None
item["production_kept"] = None
_write_json(decisions_path, decisions_payload)
decisions_hash = _sha256_file(decisions_path)
# Confirm frozen pool + gold labels untouched.
frozen_hash_after = _sha256_file(frozen_path)
gold_hash_after = _sha256_file(gold_path)
pool_unchanged = frozen_hash_after == frozen_hash_before
gold_unchanged = gold_hash_after == gold_hash_before
if not pool_unchanged:
replay_status = "candidate_key_mismatch"
if not gold_unchanged:
print("ERROR: gold_labels.json changed during replay-fixed", file=sys.stderr)
replay_status = "candidate_key_mismatch"
status = {
"created_at": stamp,
"evaluation_track": track,
"fixed_candidate_replay": True,
"candidate_discovery_performed": False,
"author_selection_performed": False,
"production_filter": FILTER_NAME,
"topic_only_definition": TOPIC_ONLY_NAME,
"replay_status": replay_status,
"candidate_count": len(frozen_rows),
"completed_decision_count": completed_decision_count,
"incomplete_candidate_count": incomplete_candidate_count,
"topic_only_kept_count": topic_only_kept_count,
"production_kept_count": production_kept_count,
"name_matching_kept_count": sum(
1 for item in ordered_out if item.get("name_matching_kept") is True
),
"pipeline_fingerprint": fingerprint,
"candidate_pool_hash": frozen_hash_before,
"filter_decisions_hash": decisions_hash,
"gold_labels_hash": gold_hash_before,
"candidate_pool_unchanged": pool_unchanged,
"gold_labels_unchanged": gold_unchanged,
"gold_labels_used_for_decisions": False,
"filter_decisions_file": _display_path(decisions_path),
"author_profile_source": "openalex_by_fixed_author_id",
"replay_timestamp": stamp,
}
# Re-write decisions with final status if integrity failed after write.
if decisions_payload["replay_status"] != replay_status:
decisions_payload["replay_status"] = replay_status
_write_json(decisions_path, decisions_payload)
status["filter_decisions_hash"] = _sha256_file(decisions_path)
_write_json(status_path, status)
_safe_print(f"track={track}")
_safe_print(f"replay_status={replay_status}")
_safe_print(f"candidate_count={len(frozen_rows)}")
_safe_print(f"completed_decision_count={completed_decision_count}")
_safe_print(f"incomplete_candidate_count={incomplete_candidate_count}")
_safe_print(
f"name_matching_kept={status['name_matching_kept_count']}"
)
_safe_print(f"topic_only_kept={topic_only_kept_count}")
_safe_print(f"production_kept={production_kept_count}")
_safe_print(f"filter_decisions={decisions_path}")
_safe_print(f"pipeline_fingerprint={fingerprint}")
_safe_print("candidate_discovery_performed=False")
_safe_print("author_selection_performed=False")
_safe_print(f"candidate_pool_unchanged={pool_unchanged}")
_safe_print(f"gold_labels_unchanged={gold_unchanged}")
_safe_print("gold_labels_used_for_decisions=False")
if incomplete_candidate_count:
for item in ordered_out:
if item.get("enrichment_status") != "complete":
_safe_print(
f"INCOMPLETE {_candidate_key_token(item.get('candidate_key'))}: "
f"{item.get('replay_error')}"
)
return 0 if replay_status == "completed" else 1
def inventory_historical_sources(
*,
methodical_dir: Path | None = None,
) -> dict[str, Any]:
base = methodical_dir or METHODICAL_EVAL_DIR
stamp = _utc_stamp()
runs_out: dict[str, Any] = {}
blocking: list[str] = []
for track, spec in HISTORICAL_RUNS.items():
authors = _resolve_historical_file(
base, spec["authors_files"], spec["source_roots"]
)
candidates = _resolve_historical_file(
base, spec["candidates_files"], spec["source_roots"]
)
gold = _resolve_historical_file(
base, spec["gold_files"], spec["source_roots"]
)
metrics = _resolve_historical_file(
base, spec["metrics_files"], spec["source_roots"]
)
decisions = _resolve_historical_file(
base, spec["decisions_files"], spec["source_roots"]
)
authors_info = _inspect_json_counts(
Path(authors["path"]) if authors["found"] else None, "authors"
)
candidates_info = _inspect_json_counts(
Path(candidates["path"]) if candidates["found"] else None, "candidates"
)
gold_info = _inspect_json_counts(
Path(gold["path"]) if gold["found"] else None, "gold"
)
metrics_info = _inspect_json_counts(
Path(metrics["path"]) if metrics["found"] else None, "metrics"
)
ready = bool(authors["found"] and candidates["found"] and gold["found"])
missing = []
if not authors["found"]:
missing.append("authors")
if not candidates["found"]:
missing.append("candidates")
if not gold["found"]:
missing.append("gold_labels")
if missing:
blocking.append(f"{track} ({spec['run_id']}): missing {', '.join(missing)}")
# Replay feasibility: need frozen candidates with patent payloads.
if candidates["found"] and candidates_info.get("candidate_count", 0):
replay_status = "fully_frozen_current_production_replay"
replay_note = (
"Frozen candidates present; current "
f"{FILTER_NAME} can be applied without live search."
)
elif gold["found"] and not candidates["found"]:
replay_status = "replay_unavailable_missing_candidate_data"
replay_note = (
"Gold labels found or expected, but frozen candidate pool is missing. "
"Do not reload patents via live EPO/USPTO search."
)
else:
replay_status = "replay_unavailable_missing_candidate_data"
replay_note = "Insufficient frozen artifacts for current-filter replay."
runs_out[track] = {
"track": track,
"label": spec["label"],
"run_id": spec["run_id"],
"selection_method": spec["selection_method"],
"selection_frozen": True,
"imported_historical_run": True,
"import_ready": ready,
"missing_required": missing,
"expected_from_protocol": spec.get("expected_from_protocol"),
"sources": {
"authors": authors,
"candidates": candidates,
"gold_labels": gold,
"metrics": metrics,
"filter_decisions": decisions,
},
"counts": {
"authors": authors_info,
"candidates": candidates_info,
"gold_labels": gold_info,
"metrics": metrics_info,
},
"topic_only_definition_expected": spec["topic_only_expected"],
"historical_production_expected": spec["historical_production_expected"],
"current_production_replay": {
"status": replay_status,
"note": replay_note,
"target_filter": FILTER_NAME,
},
"field_metadata": {
"historical_snapshot_available": bool(
authors_info.get("has_field_metadata")
),
"fallback_allowed": "current_openalex_profile",
"note": (
"Prefer historical author snapshot fields; only if missing may "
"current OpenAlex profile fill field/subfield/domain."
),
},
}
plan = {
"created_at": stamp,
"mode": "inventory-historical",
"methodical_dir": str(base),
"methodical_dir_exists": base.exists(),
"copy_performed": False,
"live_search_performed": False,
"import_blocked": bool(blocking) or not base.exists(),
"blocking_issues": blocking
+ (
[
f"methodical_eval directory missing: {base}. "
"Restore backup before import-historical."
]
if not base.exists()
else []
),
"experiments": runs_out,
"next_steps": [
"Restore service/scripts/patents/data/methodical_eval/ from backup "
"(including _archive_legacy candidate + gold files).",
"Re-run: python scripts/patents/evaluate_author_patent_search.py "
"inventory-historical",
"After confirmation: python scripts/patents/evaluate_author_patent_search.py "
"import-historical",
"Then: evaluate per track (offline) and aggregate.",
],
"name_matching_note": (
"Recall for name_matching is normally 1.0 on a complete frozen name pool "
"because no candidate is removed. This is not evidence of reliable "
"attribution; use precision instead."
),
}
return plan
def cmd_inventory_historical(args: argparse.Namespace) -> int:
methodical_dir = getattr(args, "methodical_dir", None) or METHODICAL_EVAL_DIR
plan = inventory_historical_sources(methodical_dir=Path(methodical_dir))
out_dir = AGGREGATE_DIR
out_dir.mkdir(parents=True, exist_ok=True)
plan_path = out_dir / "historical_import_plan.json"
_write_json(plan_path, plan)
# Also write per-run manifests under historical/<run_id>/ without copying data.
for track, run in (plan.get("experiments") or {}).items():
run_id = run["run_id"]
manifest_dir = HISTORICAL_DIR / run_id
manifest_dir.mkdir(parents=True, exist_ok=True)
_write_json(
manifest_dir / "restore_manifest.json",
{
"created_at": plan["created_at"],
"track": track,
"run": run,
"copy_performed": False,
},
)
_safe_print(f"methodical_dir_exists={plan['methodical_dir_exists']}")
_safe_print(f"import_blocked={plan['import_blocked']}")
for track, run in (plan.get("experiments") or {}).items():
src = run["sources"]
_safe_print(
f"{track} {run['run_id']}: ready={run['import_ready']} "
f"authors={src['authors']['found']} "
f"candidates={src['candidates']['found']} "
f"gold={src['gold_labels']['found']} "
f"replay={run['current_production_replay']['status']}"
)
for issue in plan.get("blocking_issues") or []:
_safe_print(f"BLOCK: {issue}")
_safe_print(f"Import plan: {plan_path}")
return 1 if plan["import_blocked"] else 0
def cmd_import_historical(args: argparse.Namespace) -> int:
"""Import historical runs into experiment_* directories.
Refuses to copy when inventory is blocked, unless --allow-partial is set.
Never performs live patent/author search.
"""
methodical_dir = Path(getattr(args, "methodical_dir", None) or METHODICAL_EVAL_DIR)
plan = inventory_historical_sources(methodical_dir=methodical_dir)
allow_partial = bool(getattr(args, "allow_partial", False))
if plan["import_blocked"] and not allow_partial:
print(
"Import blocked — restore methodical_eval sources first. "
"Run inventory-historical for details. No files copied.",
file=sys.stderr,
)
cmd_inventory_historical(args)
return 1
print(
"Import copying is intentionally gated: sources must be confirmed. "
"Re-run after restoring methodical_eval, or pass --allow-partial only "
"for incomplete diagnostics (still no live search).",
file=sys.stderr,
)
# Hard stop: user asked not to copy before sources are confirmed.
if not getattr(args, "confirm_copy", False):
print(
"Refusing to copy: pass --confirm-copy after reviewing inventory-historical.",
file=sys.stderr,
)
return 2
print("Confirmed copy path is not implemented until sources are present.", file=sys.stderr)
return 1
def cmd_experiment_semantic_topic_fallback(args: argparse.Namespace) -> int:
"""Restored historical offline experiment semantic_topic_fallback_v1.
Evaluation-path only. Does not modify production filtering, ES, or gold labels.
"""
runner_path = current_dir / "experiment_semantic_topic_fallback_v1.py"
spec = importlib.util.spec_from_file_location(
"experiment_semantic_topic_fallback_v1", runner_path
)
assert spec and spec.loader
runner = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = runner
spec.loader.exec_module(runner)
return int(runner.run_experiment(args))
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Field-based evaluation of author-to-patent search.",
)
parser.add_argument(
"mode",
choices=[
"select",
"freeze",
"bootstrap",
"evaluate",
"eval",
"aggregate",
"inventory-historical",
"import-historical",
"import-fixed-experiments",
"replay-fixed",
"experiment-semantic-topic-fallback",
],
help=(
"select|freeze|evaluate|aggregate|"
"import-fixed-experiments|replay-fixed|"
"experiment-semantic-topic-fallback|"
"inventory-historical|import-historical "
"(bootstrap=freeze, eval=evaluate)"
),
)
parser.add_argument(
"--track",
choices=list(EXPERIMENT_TRACKS),
default=None,
help="experiment_1|experiment_2|experiment_3",
)
parser.add_argument("--authors", type=Path, default=None)
parser.add_argument("--gold", type=Path, default=None)
parser.add_argument("--frozen", type=Path, default=None)
parser.add_argument("--decisions", type=Path, default=None)
parser.add_argument("--result", type=Path, default=None)
parser.add_argument("--report", type=Path, default=None)
parser.add_argument("--author", type=str, default=None)
parser.add_argument(
"--source-dir",
type=Path,
default=None,
help="Directory with the four restored labelled candidate JSON files",
)
parser.add_argument(
"--confirm-import",
action="store_true",
help="Required for import-fixed-experiments to write experiment_* files",
)
parser.add_argument(
"--methodical-dir",
type=Path,
default=None,
help="Override path to methodical_eval backup directory",
)
parser.add_argument(
"--confirm-copy",
action="store_true",
help="Required for import-historical to write experiment_* files",
)
parser.add_argument(
"--allow-partial",
action="store_true",
help="Allow import-historical diagnostics with incomplete sources",
)
parser.add_argument("-v", "--verbose", action="store_true")
return parser
def main() -> int:
parser = build_parser()
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(levelname)s %(message)s",
)
if args.mode == "bootstrap":
args.mode = "freeze"
if args.mode == "eval":
args.mode = "evaluate"
_apply_track_paths(args)
if args.mode == "select":
return asyncio.run(cmd_select(args))
if args.mode == "freeze":
return asyncio.run(cmd_freeze(args))
if args.mode == "evaluate":
return asyncio.run(cmd_evaluate(args))
if args.mode == "aggregate":
return cmd_aggregate(args)
if args.mode == "inventory-historical":
return cmd_inventory_historical(args)
if args.mode == "import-historical":
return cmd_import_historical(args)
if args.mode == "import-fixed-experiments":
return cmd_import_fixed_experiments(args)
if args.mode == "replay-fixed":
return asyncio.run(cmd_replay_fixed(args))
if args.mode == "experiment-semantic-topic-fallback":
return cmd_experiment_semantic_topic_fallback(args)
parser.error(f"Unknown mode: {args.mode}")
return 2
if __name__ == "__main__":
raise SystemExit(main())