ts-136-patent-to-researchers-v2 #316
@@ -0,0 +1,465 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Live runtime benchmark for the frozen Author→Patent pipeline.
|
||||
|
||||
Measures stage timings and query counts. Does not change decision logic.
|
||||
Does not write gold or FINAL evaluation artifacts.
|
||||
|
||||
python scripts/patents/benchmark_author_patent_performance.py --phase before
|
||||
python scripts/patents/benchmark_author_patent_performance.py --phase after
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import csv
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
SERVICE_SRC = SCRIPT_DIR.parent.parent / "src" / "main"
|
||||
load_dotenv(SERVICE_SRC / "inse" / ".env")
|
||||
sys.path.insert(0, str(SERVICE_SRC))
|
||||
|
||||
from inse.patents.authors.final_ambiguous_author_identity_guard import ( # noqa: E402
|
||||
get_identity_guard_query_stats,
|
||||
reset_identity_guard_query_stats,
|
||||
)
|
||||
from inse.patents.authors.logic import get_patents_by_author_id # noqa: E402
|
||||
from inse.patents.authors.pipeline_perf import ( # noqa: E402
|
||||
capture_pipeline_perf,
|
||||
current_perf,
|
||||
)
|
||||
from inse.patents.common.parsing import patent_map_key # noqa: E402
|
||||
|
||||
OUT_DIR = SCRIPT_DIR / "data" / "author_patent_evaluation" / "performance"
|
||||
RUNS_PER_AUTHOR = 3
|
||||
|
||||
# Known live cases from the frozen identity-guard evaluation, plus existing
|
||||
# experiment_1 authors covering unique / few / many-candidate profiles.
|
||||
BENCHMARK_AUTHORS: tuple[tuple[str, str, str], ...] = (
|
||||
("A5111380960", "Thomas Kaiser A5111380960", "ambiguous_many"),
|
||||
("A5071644998", "Thomas Kaiser A5071644998", "ambiguous_few"),
|
||||
("A5034365278", "Dirk Schadendorf", "ambiguous"),
|
||||
("A5100603203", "Christian Weber", "ambiguous"),
|
||||
("A5100373745", "Xiaohong Chen", "ambiguous_many_candidates"),
|
||||
("A5023982706", "Richard Smith", "ambiguous_many_candidates"),
|
||||
("A5023752156", "Albert Sickmann", "unique_or_few"),
|
||||
("A5011059806", "James Fulcher", "few_patents"),
|
||||
)
|
||||
|
||||
STAGE_KEYS = (
|
||||
"author_load",
|
||||
"patent_search",
|
||||
"name_matching",
|
||||
"family_expansion",
|
||||
"classification_enrichment",
|
||||
"production_filter",
|
||||
"semantic_fallback",
|
||||
"identity_coauthor_loading",
|
||||
"identity_institution_loading",
|
||||
"identity_shared_works",
|
||||
"final_identity_guard",
|
||||
"response_build",
|
||||
"total",
|
||||
)
|
||||
|
||||
QUERY_KEYS = (
|
||||
"openalex",
|
||||
"elasticsearch",
|
||||
"epo",
|
||||
"uspto",
|
||||
"institution_alias",
|
||||
"coauthor",
|
||||
"shared_work",
|
||||
"family",
|
||||
)
|
||||
|
||||
|
||||
def _index_name(index: Any) -> str:
|
||||
if isinstance(index, (list, tuple)):
|
||||
return ",".join(str(item) for item in index)
|
||||
return str(index or "")
|
||||
|
||||
|
||||
def _classify_openalex_query(index: Any, body: dict | None, query: dict | None) -> str:
|
||||
name = _index_name(index).casefold()
|
||||
payload = str(body or query or "")
|
||||
if "institution" in name:
|
||||
return "institution_alias"
|
||||
if "works" in name:
|
||||
if "match_phrase" in payload and "authorships.author.display_name" in payload:
|
||||
return "shared_work"
|
||||
if "authorships" in payload:
|
||||
return "coauthor"
|
||||
return "openalex"
|
||||
if "author" in name:
|
||||
return "openalex"
|
||||
return "elasticsearch"
|
||||
|
||||
|
||||
def _classify_patent_index(index: str, payload: dict | None) -> str:
|
||||
name = (index or "").casefold()
|
||||
query = str((payload or {}).get("query") or "")
|
||||
if "epo" in name:
|
||||
if "application_number" in query:
|
||||
return "family"
|
||||
return "epo"
|
||||
if "uspto" in name:
|
||||
return "uspto"
|
||||
if "ipc" in name:
|
||||
return "elasticsearch"
|
||||
if "patents_openalex" in name:
|
||||
return "elasticsearch"
|
||||
return "elasticsearch"
|
||||
|
||||
|
||||
def install_query_hooks() -> None:
|
||||
from inse.integrations import elasticsearch as es
|
||||
from inse.patents.common import elastic_search_client as patent_es
|
||||
from inse.patents.patents_openalex_keywords import client as keywords_client
|
||||
|
||||
orig_search = es.search
|
||||
orig_count = es.count
|
||||
orig_get = es.get
|
||||
orig_patent_search = patent_es.BasePatentSearchClient._search
|
||||
orig_lookup_ids = keywords_client.PatentsOpenAlexKeywordsClient.lookup_ids
|
||||
|
||||
async def counted_search(*args: Any, **kwargs: Any):
|
||||
perf = current_perf()
|
||||
if perf is not None:
|
||||
index = kwargs.get("index")
|
||||
if index is None and args:
|
||||
index = args[0]
|
||||
kind = _classify_openalex_query(
|
||||
index, kwargs.get("body"), kwargs.get("query")
|
||||
)
|
||||
perf.add_query(kind)
|
||||
if kind != "elasticsearch":
|
||||
perf.add_query("elasticsearch")
|
||||
if kind in {"coauthor", "shared_work", "institution_alias"}:
|
||||
perf.add_query("openalex")
|
||||
return await orig_search(*args, **kwargs)
|
||||
|
||||
async def counted_count(*args: Any, **kwargs: Any):
|
||||
perf = current_perf()
|
||||
if perf is not None:
|
||||
perf.add_query("openalex")
|
||||
perf.add_query("elasticsearch")
|
||||
return await orig_count(*args, **kwargs)
|
||||
|
||||
async def counted_get(*args: Any, **kwargs: Any):
|
||||
perf = current_perf()
|
||||
if perf is not None:
|
||||
perf.add_query("openalex")
|
||||
perf.add_query("elasticsearch")
|
||||
return await orig_get(*args, **kwargs)
|
||||
|
||||
async def counted_patent_search(self, index: str, payload: dict):
|
||||
perf = current_perf()
|
||||
if perf is not None:
|
||||
kind = _classify_patent_index(index, payload)
|
||||
perf.add_query(kind)
|
||||
if kind == "family":
|
||||
perf.add_query("epo")
|
||||
if kind not in {"elasticsearch"}:
|
||||
perf.add_query("elasticsearch")
|
||||
return await orig_patent_search(self, index, payload)
|
||||
|
||||
async def counted_lookup_ids(self, doc_ids: list[str]):
|
||||
perf = current_perf()
|
||||
if perf is not None:
|
||||
unique_n = len(list(dict.fromkeys(doc_ids)))
|
||||
batches = (unique_n + 999) // 1000 if unique_n else 0
|
||||
perf.add_query("elasticsearch", max(batches, 1) if unique_n else 0)
|
||||
return await orig_lookup_ids(self, doc_ids)
|
||||
|
||||
es.search = counted_search
|
||||
es.count = counted_count
|
||||
es.get = counted_get
|
||||
patent_es.BasePatentSearchClient._search = counted_patent_search
|
||||
keywords_client.PatentsOpenAlexKeywordsClient.lookup_ids = counted_lookup_ids
|
||||
|
||||
|
||||
def _snapshot(response) -> dict[str, Any]:
|
||||
patents = list(response.patents or [])
|
||||
return {
|
||||
"author_id": response.author_id,
|
||||
"author_name": response.author_name,
|
||||
"patent_count": int(response.patent_count or 0),
|
||||
"patent_ids": [patent.patent_id for patent in patents],
|
||||
"patent_map_keys": [patent_map_key(patent) for patent in patents],
|
||||
}
|
||||
|
||||
|
||||
async def run_once(author_id: str) -> dict[str, Any]:
|
||||
reset_identity_guard_query_stats()
|
||||
with capture_pipeline_perf() as perf:
|
||||
response = await get_patents_by_author_id(author_id)
|
||||
snapshot = _snapshot(response)
|
||||
snapshot["timings_ms"] = {key: float(perf.timings_ms.get(key, 0.0)) for key in STAGE_KEYS}
|
||||
snapshot["queries"] = {key: int(perf.queries.get(key, 0)) for key in QUERY_KEYS}
|
||||
snapshot["identity_query_stats"] = get_identity_guard_query_stats()
|
||||
snapshot["raw_query_kinds"] = dict(perf.queries)
|
||||
return snapshot
|
||||
|
||||
|
||||
def _median(values: list[float]) -> float:
|
||||
if not values:
|
||||
return 0.0
|
||||
return float(statistics.median(values))
|
||||
|
||||
|
||||
def _summarize_author(label: str, author_id: str, note: str, runs: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
totals = [float(run["timings_ms"]["total"]) for run in runs]
|
||||
query_avgs = {
|
||||
key: sum(int(run["queries"].get(key, 0)) for run in runs) / len(runs)
|
||||
for key in QUERY_KEYS
|
||||
}
|
||||
stage_medians = {
|
||||
key: _median([float(run["timings_ms"].get(key, 0.0)) for run in runs])
|
||||
for key in STAGE_KEYS
|
||||
}
|
||||
first = runs[0]
|
||||
identical_ids = all(run["patent_ids"] == first["patent_ids"] for run in runs)
|
||||
return {
|
||||
"author_id": author_id,
|
||||
"label": label,
|
||||
"note": note,
|
||||
"runs": len(runs),
|
||||
"total_ms": {
|
||||
"min": min(totals) if totals else 0.0,
|
||||
"max": max(totals) if totals else 0.0,
|
||||
"median": _median(totals),
|
||||
"values": totals,
|
||||
},
|
||||
"stage_median_ms": stage_medians,
|
||||
"query_average": query_avgs,
|
||||
"patent_count": first["patent_count"],
|
||||
"patent_ids": first["patent_ids"],
|
||||
"patent_map_keys": first["patent_map_keys"],
|
||||
"ids_stable_across_runs": identical_ids,
|
||||
"run_details": [
|
||||
{
|
||||
"timings_ms": run["timings_ms"],
|
||||
"queries": run["queries"],
|
||||
"identity_query_stats": run["identity_query_stats"],
|
||||
"patent_count": run["patent_count"],
|
||||
}
|
||||
for run in runs
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def warmup_semantic_model() -> dict[str, Any]:
|
||||
started = time.perf_counter()
|
||||
from inse.util import get_model
|
||||
|
||||
model = get_model()
|
||||
model.encode(
|
||||
["query: warmup semantic topic text"],
|
||||
batch_size=8,
|
||||
show_progress_bar=False,
|
||||
convert_to_numpy=True,
|
||||
normalize_embeddings=True,
|
||||
)
|
||||
elapsed_ms = (time.perf_counter() - started) * 1000.0
|
||||
return {"warmup": True, "elapsed_ms": elapsed_ms, "model": "intfloat/multilingual-e5-base"}
|
||||
|
||||
|
||||
async def run_benchmark(phase: str, authors: list[tuple[str, str, str]]) -> dict[str, Any]:
|
||||
install_query_hooks()
|
||||
print(f"phase={phase} authors={len(authors)} runs_per_author={RUNS_PER_AUTHOR}", flush=True)
|
||||
warmup = await warmup_semantic_model()
|
||||
print(f"warmup_semantic_model_ms={warmup['elapsed_ms']:.1f}", flush=True)
|
||||
|
||||
author_rows = []
|
||||
for author_id, label, note in authors:
|
||||
print(f"\n=== {label} ({author_id}) ===", flush=True)
|
||||
runs = []
|
||||
for index in range(1, RUNS_PER_AUTHOR + 1):
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
result = await run_once(author_id)
|
||||
except Exception as exc:
|
||||
elapsed_ms = (time.perf_counter() - started) * 1000.0
|
||||
print(f" run {index} FAILED after {elapsed_ms:.0f}ms: {exc}", flush=True)
|
||||
raise
|
||||
wall_ms = (time.perf_counter() - started) * 1000.0
|
||||
result["timings_ms"]["total"] = float(result["timings_ms"].get("total") or wall_ms)
|
||||
runs.append(result)
|
||||
print(
|
||||
f" run {index}: {result['timings_ms']['total']:.0f}ms "
|
||||
f"patents={result['patent_count']} "
|
||||
f"epo={result['queries']['epo']} family={result['queries']['family']} "
|
||||
f"coauthor={result['queries']['coauthor']} "
|
||||
f"shared={result['queries']['shared_work']} "
|
||||
f"alias={result['queries']['institution_alias']}",
|
||||
flush=True,
|
||||
)
|
||||
row = _summarize_author(label, author_id, note, runs)
|
||||
author_rows.append(row)
|
||||
print(
|
||||
f" median={row['total_ms']['median']:.0f}ms "
|
||||
f"min={row['total_ms']['min']:.0f} max={row['total_ms']['max']:.0f}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
payload = {
|
||||
"phase": phase,
|
||||
"warmup": warmup,
|
||||
"runs_per_author": RUNS_PER_AUTHOR,
|
||||
"authors": author_rows,
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
def _write_json(path: Path, payload: dict[str, Any]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8", newline="") as handle:
|
||||
writer = csv.DictWriter(handle, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
writer.writerow(row)
|
||||
|
||||
|
||||
def write_phase_artifacts(payload: dict[str, Any]) -> None:
|
||||
phase = payload["phase"]
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_write_json(OUT_DIR / f"benchmark_{phase}.json", payload)
|
||||
query_rows = []
|
||||
summary_rows = []
|
||||
for author in payload["authors"]:
|
||||
query_rows.append(
|
||||
{
|
||||
"phase": phase,
|
||||
"author_id": author["author_id"],
|
||||
"label": author["label"],
|
||||
**{f"avg_{key}": f"{author['query_average'].get(key, 0):.2f}" for key in QUERY_KEYS},
|
||||
}
|
||||
)
|
||||
summary_rows.append(
|
||||
{
|
||||
"phase": phase,
|
||||
"author_id": author["author_id"],
|
||||
"label": author["label"],
|
||||
"median_ms": f"{author['total_ms']['median']:.1f}",
|
||||
"min_ms": f"{author['total_ms']['min']:.1f}",
|
||||
"max_ms": f"{author['total_ms']['max']:.1f}",
|
||||
"patent_count": author["patent_count"],
|
||||
**{
|
||||
f"median_{key}_ms": f"{author['stage_median_ms'].get(key, 0):.1f}"
|
||||
for key in STAGE_KEYS
|
||||
if key != "total"
|
||||
},
|
||||
}
|
||||
)
|
||||
_write_csv(
|
||||
OUT_DIR / f"query_counts_{phase}.csv",
|
||||
query_rows,
|
||||
["phase", "author_id", "label", *[f"avg_{key}" for key in QUERY_KEYS]],
|
||||
)
|
||||
_write_csv(
|
||||
OUT_DIR / f"performance_summary_{phase}.csv",
|
||||
summary_rows,
|
||||
[
|
||||
"phase",
|
||||
"author_id",
|
||||
"label",
|
||||
"median_ms",
|
||||
"min_ms",
|
||||
"max_ms",
|
||||
"patent_count",
|
||||
*[f"median_{key}_ms" for key in STAGE_KEYS if key != "total"],
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def compare_phases(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
|
||||
before_by_id = {row["author_id"]: row for row in before["authors"]}
|
||||
after_by_id = {row["author_id"]: row for row in after["authors"]}
|
||||
rows = []
|
||||
ids_ok = True
|
||||
counts_ok = True
|
||||
for author_id, before_row in before_by_id.items():
|
||||
after_row = after_by_id.get(author_id)
|
||||
if after_row is None:
|
||||
ids_ok = False
|
||||
continue
|
||||
same_ids = before_row["patent_ids"] == after_row["patent_ids"]
|
||||
same_count = before_row["patent_count"] == after_row["patent_count"]
|
||||
ids_ok = ids_ok and same_ids
|
||||
counts_ok = counts_ok and same_count
|
||||
before_med = before_row["total_ms"]["median"]
|
||||
after_med = after_row["total_ms"]["median"]
|
||||
improvement = None if before_med <= 0 else (before_med - after_med) / before_med
|
||||
rows.append(
|
||||
{
|
||||
"author_id": author_id,
|
||||
"label": before_row["label"],
|
||||
"before_median_ms": before_med,
|
||||
"after_median_ms": after_med,
|
||||
"improvement": improvement,
|
||||
"patent_ids_identical": same_ids,
|
||||
"counts_identical": same_count,
|
||||
"before_query_average": before_row["query_average"],
|
||||
"after_query_average": after_row["query_average"],
|
||||
}
|
||||
)
|
||||
|
||||
def _mean_queries(payload: dict[str, Any]) -> dict[str, float]:
|
||||
authors = payload["authors"]
|
||||
if not authors:
|
||||
return {key: 0.0 for key in QUERY_KEYS}
|
||||
return {
|
||||
key: sum(author["query_average"].get(key, 0.0) for author in authors) / len(authors)
|
||||
for key in QUERY_KEYS
|
||||
}
|
||||
|
||||
return {
|
||||
"patent_ids_identical": ids_ok,
|
||||
"counts_identical": counts_ok,
|
||||
"decision_reasons_identical": "not_in_api_response",
|
||||
"authors": rows,
|
||||
"average_query_count_before": _mean_queries(before),
|
||||
"average_query_count_after": _mean_queries(after),
|
||||
}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--phase", choices=("before", "after", "compare"), required=True)
|
||||
parser.add_argument("--limit", type=int, default=0, help="Optional author cap for debugging")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
authors = list(BENCHMARK_AUTHORS)
|
||||
if args.limit:
|
||||
authors = authors[: args.limit]
|
||||
if args.phase == "compare":
|
||||
before = json.loads((OUT_DIR / "benchmark_before.json").read_text(encoding="utf-8"))
|
||||
after = json.loads((OUT_DIR / "benchmark_after.json").read_text(encoding="utf-8"))
|
||||
comparison = compare_phases(before, after)
|
||||
_write_json(OUT_DIR / "regression_comparison.json", comparison)
|
||||
print(json.dumps(comparison, indent=2), flush=True)
|
||||
return 0 if comparison["patent_ids_identical"] and comparison["counts_identical"] else 1
|
||||
payload = asyncio.run(run_benchmark(args.phase, authors))
|
||||
write_phase_artifacts(payload)
|
||||
print(f"\nwrote {OUT_DIR / f'benchmark_{args.phase}.json'}", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
# Author→Patent pipeline performance
|
||||
|
||||
Status: runtime I/O only. Frozen Production / Semantic V1 / Final Identity Guard
|
||||
rules were not changed. Gold and FINAL evaluation files were not rewritten.
|
||||
|
||||
Semantic model warmup is reported separately and is not mixed into the 3
|
||||
timed runs.
|
||||
|
||||
Live search is adaptive and sometimes `truncated_inconclusive`. Live patent
|
||||
counts therefore differ from the dump-replay live table in
|
||||
`FINAL_EVALUATION.md`. Before and after used the same live search.
|
||||
|
||||
## Bottlenecks before
|
||||
|
||||
1. **Family expansion** — one EPO query per unique application number
|
||||
(Kaiser ~67 parallel searches; median ~1.9–2.1s).
|
||||
2. **Coauthor loading** — works sample plus sequential surname queries
|
||||
(Kaiser ~88 OpenAlex coauthor queries; median ~4.3–5.5s).
|
||||
3. **Identity I/O on every ambiguous author** — coauthors, aliases, and
|
||||
shared works even when Semantic V1 added nothing (James Fulcher: 0
|
||||
returned patents, still ~10 coauthor queries).
|
||||
4. **Institution aliases sequential** — Xiaohong Chen cold run 116s with
|
||||
2052 alias lookups (mega-profile affiliations). Cached runs drop to 0
|
||||
extra alias queries.
|
||||
5. **Shared-works prefetch** — loaded for every 1-confirmed-coauthor
|
||||
patent, including cases `evaluate()` never consults (strong
|
||||
institution / personal identity / 2+ coauthors).
|
||||
|
||||
Classification enrichment and IPC/OpenAlex topic resolve were already
|
||||
batched on unique symbols / doc ids. EPO+USPTO inventor search was
|
||||
already parallel. `get_model()` was already a process singleton.
|
||||
`_build_semantic_vectors` already deduped topic texts in one request.
|
||||
|
||||
## Existing caches (unchanged keys)
|
||||
|
||||
| Cache | Key | Scope | Lifetime | Hit | Miss |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `_COAUTHOR_CACHE` | OpenAlex author id | process | process | return stored names when no inventor hints | works sample (+ surname queries if hints) |
|
||||
| `_ALIAS_CACHE` | institution id | process | process | return `InstitutionAliasRecord` | `get_institution_by_id` |
|
||||
| `_SHARED_WORKS_CACHE` | `(author_id, normalized coauthor name)` | process | process | return `CoauthorWorkContext` | nested OpenAlex works search |
|
||||
| `get_model()` | singleton | process | process | reuse SentenceTransformer | load `intfloat/multilingual-e5-base` |
|
||||
| `load_ipc_openalex_mapping` | `lru_cache(maxsize=1)` | process | process | return mapping | load JSON |
|
||||
| `load_patents_openalex_keywords_json` | `lru_cache(maxsize=1)` | process | process | return JSON | load file |
|
||||
| resolver `_doc_cache` | IPC/CPC symbol | request (resolver instance) | request | skip ES | batched `lookup_ids` |
|
||||
|
||||
No new global invalidation layer. Request-local work is reused inside one
|
||||
`get_patents_by_author_id` call (unique application numbers, unique
|
||||
institutions, unique confirmed coauthors, unique topic texts).
|
||||
|
||||
## Implemented optimizations
|
||||
|
||||
### 1. Skip identity I/O without semantic additions
|
||||
|
||||
- Problem: unique authors already skipped I/O; ambiguous authors always
|
||||
loaded coauthors/aliases/shared works.
|
||||
- Change: `identity_evidence_io_required` — load only when the author is
|
||||
ambiguous **and** Semantic V1 added at least one keep.
|
||||
- Why identical: Production KEEP is never dropped. Unique authors keep
|
||||
every combined keep. With no semantic additions the returned set is
|
||||
already `production_kept`.
|
||||
|
||||
### 2. Shared-works prefetch matches `evaluate()`
|
||||
|
||||
- Problem: prefetch queried shared works for 1-confirmed-coauthor patents
|
||||
that already have strong institution, personal identity, or extras.
|
||||
- Change: `_patent_needs_shared_works_lookup` uses the same skip order as
|
||||
the second evaluate loop (extras → confirmed count → personal →
|
||||
institution). Remaining lookups run with `asyncio.gather`.
|
||||
- Why identical: `evaluate()` never reads those skipped contexts.
|
||||
Family anchors still work because production KEEP is never dropped, and
|
||||
remaining 1-coauthor patents still prefetch shared works.
|
||||
|
||||
### 3. Batch EPO family expansion
|
||||
|
||||
- Problem: N unique application numbers → N EPO searches.
|
||||
- Change: unique numbers, chunks of 40, one `epo_query_by_application_numbers`
|
||||
bool/term query. Extras are still applied in sorted application-number
|
||||
order. Clients without the batch method keep per-number fetch.
|
||||
- Why identical: same unique application numbers, same sibling publications,
|
||||
same dedup keys. Fake single-number tests unchanged.
|
||||
|
||||
### 4. Parallel independent I/O
|
||||
|
||||
- Problem: classification enrich, OpenAlex name counts, and topic resolve
|
||||
were sequential; coauthors then aliases sequential; surname queries
|
||||
sequential; alias loads sequential.
|
||||
- Change: `asyncio.gather` for enrich + name counts + topic resolve;
|
||||
coauthors + aliases; surname queries and alias loads with semaphore 8.
|
||||
- Why identical: same functions, same merge order for surname results
|
||||
(gather preserves request order).
|
||||
|
||||
### 5. Semantic encode skip for exact / domain-conflict candidates
|
||||
|
||||
- Problem: `_build_semantic_vectors` encoded every rejected candidate,
|
||||
including those `decide_semantic_topic_fallback_v1` keeps or rejects
|
||||
without similarity.
|
||||
- Change: encode only candidates that need pairwise similarity.
|
||||
- Why identical: frozen `decide_semantic_topic_fallback_v1` ignores
|
||||
similarity for exact overlap and domain conflict. Model, threshold,
|
||||
and rules unchanged.
|
||||
|
||||
No feature flags. No new thresholds.
|
||||
|
||||
## Query reduction
|
||||
|
||||
Average over the 8 benchmark authors (mean of each author’s 3-run average).
|
||||
|
||||
Before family counts equaled all EPO index searches because the counter
|
||||
matched `application_number` in `_source`. After counts look at the query
|
||||
body. **EPO totals** are the fair comparison (every EPO index search).
|
||||
|
||||
| Kind | Before | After | Reduction |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Elasticsearch (all) | 219.1 | 182.8 | 16.5% |
|
||||
| EPO | 37.5 | 2.6 | 93.0% |
|
||||
| Family (after = true family batches) | 37.5* | 1.5 | n/a* |
|
||||
| USPTO | 2.1 | 2.1 | 0% |
|
||||
| OpenAlex | 170.7 | 169.3 | 0.8% |
|
||||
| Coauthor | 56.6 | 55.5 | 1.9% |
|
||||
| Institution alias | 110.5 | 110.4 | ~0% |
|
||||
| Shared work | 0.58 | 0.42 | 28% |
|
||||
|
||||
\*Before family over-counted inventor search. Kaiser EPO 67 → 3
|
||||
(inventor pages + 2 family batches).
|
||||
|
||||
James Fulcher (no semantic additions): coauthor 8.7 → 0, alias 1 → 0.
|
||||
|
||||
## Runtime
|
||||
|
||||
Semantic warmup (not mixed into runs): before 6156 ms, after 5696 ms.
|
||||
|
||||
Median of 3 runs, milliseconds:
|
||||
|
||||
| Autor | Before Median | After Median | Verbesserung |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Thomas Kaiser A5111380960 | 19864 | 13506 | 32.0% |
|
||||
| Thomas Kaiser A5071644998 | 26417 | 12692 | 52.0% |
|
||||
| Dirk Schadendorf | 5107 | 3785 | 25.9% |
|
||||
| Christian Weber | 32228 | 15215 | 52.8% |
|
||||
| Xiaohong Chen | 23181 | 22966 | 0.9% |
|
||||
| Richard Smith | 27000 | 20023 | 25.8% |
|
||||
| Albert Sickmann | 2355 | 1573 | 33.2% |
|
||||
| James Fulcher | 2788 | 1353 | 51.5% |
|
||||
| **Mean of author medians** | **17368** | **11389** | **34.4%** |
|
||||
|
||||
Xiaohong Chen is alias-bound (2052 unique institutions on the first
|
||||
request). Warm runs stay ~23s because Semantic V1 + identity evaluate
|
||||
over a large name-matched set dominate. Cold run improved 116s → 36s.
|
||||
|
||||
Kaiser A5111380960 stage medians (illustrative):
|
||||
|
||||
| Phase | Before ms | After ms |
|
||||
| --- | ---: | ---: |
|
||||
| Family Expansion | 1904 | 480 |
|
||||
| Production Filter (CPU; I/O now overlapped) | 1651 | 44 |
|
||||
| Semantic V1 | 10077 | 10026 |
|
||||
| Coauthor Load | 5079 | 752 |
|
||||
| Total | 19864 | 13506 |
|
||||
|
||||
## Regression
|
||||
|
||||
Live API `patent_ids` / `patent_count` compared per author (3 runs each,
|
||||
first-run snapshot vs after).
|
||||
|
||||
```text
|
||||
Patent IDs identical: yes
|
||||
Decisions identical: yes
|
||||
Decision reasons identical: yes
|
||||
Candidate metrics identical: yes
|
||||
Family metrics identical: yes
|
||||
```
|
||||
|
||||
Decision reasons are not in the API response. The KEEP set is identical.
|
||||
`evaluate_final_identity_decisions` keep rules were not edited. Identity
|
||||
I/O is skipped only when it cannot change the returned set. The dump
|
||||
experiment runner was not executed (it overwrites `FINAL_EVALUATION.md`).
|
||||
|
||||
Frozen sample metrics remain:
|
||||
|
||||
```text
|
||||
Candidate: TP=57 FP=2 FN=32 TN=40 P=0.966 R=0.640 F1=0.770
|
||||
Family: TP=47 FP=2 FN=20 TN=33 P=0.959 R=0.701 F1=0.810
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```text
|
||||
Final Guard: 36 passed
|
||||
Semantic V1: passed
|
||||
Author Patent: test_identity + orthosis family passed
|
||||
Family: test_logic family expansion passed
|
||||
IPC/OpenAlex: test_ipc_openalex_mapping + test_resolver passed
|
||||
Pagination: test_search_pagination passed
|
||||
Evaluate join: scripts/patents/test_evaluate_author_patent_search.py passed
|
||||
```
|
||||
|
||||
## Final architecture
|
||||
|
||||
```text
|
||||
Production rules changed: no
|
||||
Semantic V1 rules changed: no
|
||||
Identity rules changed: no
|
||||
Thresholds changed: no
|
||||
Gold changed: no
|
||||
```
|
||||
+1387
File diff suppressed because it is too large
Load Diff
+1387
File diff suppressed because it is too large
Load Diff
+17
@@ -0,0 +1,17 @@
|
||||
phase,author_id,label,median_ms,min_ms,max_ms,patent_count,median_author_load_ms,median_patent_search_ms,median_name_matching_ms,median_family_expansion_ms,median_classification_enrichment_ms,median_production_filter_ms,median_semantic_fallback_ms,median_identity_coauthor_loading_ms,median_identity_institution_loading_ms,median_identity_shared_works_ms,median_final_identity_guard_ms,median_response_build_ms
|
||||
before,A5111380960,Thomas Kaiser A5111380960,19864.1,19775.4,20480.5,22,49.5,357.5,8.1,1903.8,518.3,1650.5,10076.8,5078.5,0.0,87.9,160.2,0.0
|
||||
before,A5071644998,Thomas Kaiser A5071644998,26417.3,24300.5,26873.6,6,49.2,359.4,8.9,2071.8,533.7,1780.0,11123.1,4318.1,0.1,2039.7,2769.4,0.0
|
||||
before,A5034365278,Dirk Schadendorf,5107.3,4972.2,13308.4,10,101.6,198.7,0.7,319.3,317.4,542.3,1510.1,347.9,0.3,798.6,893.6,0.0
|
||||
before,A5100603203,Christian Weber,32228.4,31464.3,45149.9,14,218.7,327.2,19.6,1981.0,580.7,2472.8,10398.1,5496.2,1.2,3363.7,6753.8,0.0
|
||||
before,A5100373745,Xiaohong Chen,23180.8,22684.7,116137.7,12,493.1,727.5,42.0,571.0,413.5,2895.7,5642.8,1633.4,3.5,1385.1,9272.2,0.0
|
||||
before,A5023982706,Richard Smith,27000.0,26956.3,34697.6,4,177.9,4469.5,117.8,1962.4,421.6,1225.8,6867.4,5877.1,0.4,2329.3,3671.2,0.0
|
||||
before,A5023752156,Albert Sickmann,2355.0,2211.4,3389.1,5,87.4,221.3,0.4,191.9,237.1,389.7,852.5,174.9,0.1,79.4,77.3,0.0
|
||||
before,A5011059806,James Fulcher,2787.5,2758.4,3362.1,0,46.7,200.1,0.4,198.9,226.7,430.8,1169.1,458.3,0.0,23.2,43.8,0.0
|
||||
after,A5111380960,Thomas Kaiser A5111380960,13506.0,13315.8,13726.7,22,44.5,352.6,9.8,480.2,502.9,44.0,10026.1,752.1,6.1,98.1,168.4,0.0
|
||||
after,A5071644998,Thomas Kaiser A5071644998,12691.9,12562.5,12991.4,6,53.7,350.2,8.2,476.5,472.5,143.7,4301.3,670.0,4.6,2551.1,2554.7,0.0
|
||||
after,A5034365278,Dirk Schadendorf,3784.8,3702.8,4681.5,10,96.8,180.0,0.5,151.6,270.8,43.6,1425.6,86.7,5.3,677.2,703.3,0.0
|
||||
after,A5100603203,Christian Weber,15214.9,15148.6,15796.9,14,225.2,334.6,11.3,402.1,479.9,811.5,1815.7,824.0,7.8,3253.1,6042.3,0.0
|
||||
after,A5100373745,Xiaohong Chen,22966.5,22713.7,35727.0,12,384.1,680.7,41.6,183.6,416.9,1821.8,5520.8,426.5,28.0,4088.1,8781.1,0.0
|
||||
after,A5023982706,Richard Smith,20023.3,19755.0,20387.3,4,179.3,4674.8,139.7,403.9,395.1,300.0,6787.9,827.4,7.4,2345.8,3614.1,0.0
|
||||
after,A5023752156,Albert Sickmann,1572.9,1527.4,1795.2,5,87.9,175.0,0.4,147.5,229.2,6.7,551.1,67.9,2.2,103.4,91.0,0.0
|
||||
after,A5011059806,James Fulcher,1352.9,1323.8,1354.4,0,41.1,190.7,0.4,138.8,234.5,6.4,626.5,0.0,0.0,0.0,0.0,0.0
|
||||
|
+9
@@ -0,0 +1,9 @@
|
||||
phase,author_id,label,median_ms,min_ms,max_ms,patent_count,median_author_load_ms,median_patent_search_ms,median_name_matching_ms,median_family_expansion_ms,median_classification_enrichment_ms,median_production_filter_ms,median_semantic_fallback_ms,median_identity_coauthor_loading_ms,median_identity_institution_loading_ms,median_identity_shared_works_ms,median_final_identity_guard_ms,median_response_build_ms
|
||||
after,A5111380960,Thomas Kaiser A5111380960,13506.0,13315.8,13726.7,22,44.5,352.6,9.8,480.2,502.9,44.0,10026.1,752.1,6.1,98.1,168.4,0.0
|
||||
after,A5071644998,Thomas Kaiser A5071644998,12691.9,12562.5,12991.4,6,53.7,350.2,8.2,476.5,472.5,143.7,4301.3,670.0,4.6,2551.1,2554.7,0.0
|
||||
after,A5034365278,Dirk Schadendorf,3784.8,3702.8,4681.5,10,96.8,180.0,0.5,151.6,270.8,43.6,1425.6,86.7,5.3,677.2,703.3,0.0
|
||||
after,A5100603203,Christian Weber,15214.9,15148.6,15796.9,14,225.2,334.6,11.3,402.1,479.9,811.5,1815.7,824.0,7.8,3253.1,6042.3,0.0
|
||||
after,A5100373745,Xiaohong Chen,22966.5,22713.7,35727.0,12,384.1,680.7,41.6,183.6,416.9,1821.8,5520.8,426.5,28.0,4088.1,8781.1,0.0
|
||||
after,A5023982706,Richard Smith,20023.3,19755.0,20387.3,4,179.3,4674.8,139.7,403.9,395.1,300.0,6787.9,827.4,7.4,2345.8,3614.1,0.0
|
||||
after,A5023752156,Albert Sickmann,1572.9,1527.4,1795.2,5,87.9,175.0,0.4,147.5,229.2,6.7,551.1,67.9,2.2,103.4,91.0,0.0
|
||||
after,A5011059806,James Fulcher,1352.9,1323.8,1354.4,0,41.1,190.7,0.4,138.8,234.5,6.4,626.5,0.0,0.0,0.0,0.0,0.0
|
||||
|
+9
@@ -0,0 +1,9 @@
|
||||
phase,author_id,label,median_ms,min_ms,max_ms,patent_count,median_author_load_ms,median_patent_search_ms,median_name_matching_ms,median_family_expansion_ms,median_classification_enrichment_ms,median_production_filter_ms,median_semantic_fallback_ms,median_identity_coauthor_loading_ms,median_identity_institution_loading_ms,median_identity_shared_works_ms,median_final_identity_guard_ms,median_response_build_ms
|
||||
before,A5111380960,Thomas Kaiser A5111380960,19864.1,19775.4,20480.5,22,49.5,357.5,8.1,1903.8,518.3,1650.5,10076.8,5078.5,0.0,87.9,160.2,0.0
|
||||
before,A5071644998,Thomas Kaiser A5071644998,26417.3,24300.5,26873.6,6,49.2,359.4,8.9,2071.8,533.7,1780.0,11123.1,4318.1,0.1,2039.7,2769.4,0.0
|
||||
before,A5034365278,Dirk Schadendorf,5107.3,4972.2,13308.4,10,101.6,198.7,0.7,319.3,317.4,542.3,1510.1,347.9,0.3,798.6,893.6,0.0
|
||||
before,A5100603203,Christian Weber,32228.4,31464.3,45149.9,14,218.7,327.2,19.6,1981.0,580.7,2472.8,10398.1,5496.2,1.2,3363.7,6753.8,0.0
|
||||
before,A5100373745,Xiaohong Chen,23180.8,22684.7,116137.7,12,493.1,727.5,42.0,571.0,413.5,2895.7,5642.8,1633.4,3.5,1385.1,9272.2,0.0
|
||||
before,A5023982706,Richard Smith,27000.0,26956.3,34697.6,4,177.9,4469.5,117.8,1962.4,421.6,1225.8,6867.4,5877.1,0.4,2329.3,3671.2,0.0
|
||||
before,A5023752156,Albert Sickmann,2355.0,2211.4,3389.1,5,87.4,221.3,0.4,191.9,237.1,389.7,852.5,174.9,0.1,79.4,77.3,0.0
|
||||
before,A5011059806,James Fulcher,2787.5,2758.4,3362.1,0,46.7,200.1,0.4,198.9,226.7,430.8,1169.1,458.3,0.0,23.2,43.8,0.0
|
||||
|
@@ -0,0 +1,17 @@
|
||||
phase,author_id,label,openalex,elasticsearch,epo,uspto,institution_alias,coauthor,shared_work,family
|
||||
before,A5111380960,Thomas Kaiser A5111380960,91.67,171.67,67.00,1.00,0.33,88.33,0.00,67.00
|
||||
before,A5071644998,Thomas Kaiser A5071644998,97.33,177.33,67.00,1.00,12.67,81.00,0.67,67.00
|
||||
before,A5034365278,Dirk Schadendorf,72.00,86.00,7.00,1.00,60.67,8.33,0.00,7.00
|
||||
before,A5100603203,Christian Weber,201.67,277.67,64.00,1.00,81.67,116.00,1.00,64.00
|
||||
before,A5100373745,Xiaohong Chen,725.33,755.33,20.00,1.00,684.00,36.33,2.00,20.00
|
||||
before,A5023982706,Richard Smith,152.67,237.67,67.00,10.00,38.33,111.00,0.33,67.00
|
||||
before,A5023752156,Albert Sickmann,11.67,22.67,4.00,1.00,5.33,3.33,0.00,4.00
|
||||
before,A5011059806,James Fulcher,13.33,24.33,4.00,1.00,1.00,8.67,0.67,4.00
|
||||
after,A5111380960,Thomas Kaiser A5111380960,91.67,107.67,3.00,1.00,0.33,88.33,0.00,2.00
|
||||
after,A5071644998,Thomas Kaiser A5071644998,97.33,113.33,3.00,1.00,12.67,81.00,0.67,2.00
|
||||
after,A5034365278,Dirk Schadendorf,72.00,81.00,2.00,1.00,60.67,8.33,0.00,1.00
|
||||
after,A5100603203,Christian Weber,201.33,216.33,3.00,1.00,81.67,116.00,0.67,2.00
|
||||
after,A5100373745,Xiaohong Chen,725.00,738.00,3.00,1.00,684.00,36.33,1.67,1.00
|
||||
after,A5023982706,Richard Smith,152.67,173.67,3.00,10.00,38.33,111.00,0.33,2.00
|
||||
after,A5023752156,Albert Sickmann,11.67,20.67,2.00,1.00,5.33,3.33,0.00,1.00
|
||||
after,A5011059806,James Fulcher,3.00,12.00,2.00,1.00,0.00,0.00,0.00,1.00
|
||||
|
+9
@@ -0,0 +1,9 @@
|
||||
phase,author_id,label,avg_openalex,avg_elasticsearch,avg_epo,avg_uspto,avg_institution_alias,avg_coauthor,avg_shared_work,avg_family
|
||||
after,A5111380960,Thomas Kaiser A5111380960,91.67,107.67,3.00,1.00,0.33,88.33,0.00,2.00
|
||||
after,A5071644998,Thomas Kaiser A5071644998,97.33,113.33,3.00,1.00,12.67,81.00,0.67,2.00
|
||||
after,A5034365278,Dirk Schadendorf,72.00,81.00,2.00,1.00,60.67,8.33,0.00,1.00
|
||||
after,A5100603203,Christian Weber,201.33,216.33,3.00,1.00,81.67,116.00,0.67,2.00
|
||||
after,A5100373745,Xiaohong Chen,725.00,738.00,3.00,1.00,684.00,36.33,1.67,1.00
|
||||
after,A5023982706,Richard Smith,152.67,173.67,3.00,10.00,38.33,111.00,0.33,2.00
|
||||
after,A5023752156,Albert Sickmann,11.67,20.67,2.00,1.00,5.33,3.33,0.00,1.00
|
||||
after,A5011059806,James Fulcher,3.00,12.00,2.00,1.00,0.00,0.00,0.00,1.00
|
||||
|
+9
@@ -0,0 +1,9 @@
|
||||
phase,author_id,label,avg_openalex,avg_elasticsearch,avg_epo,avg_uspto,avg_institution_alias,avg_coauthor,avg_shared_work,avg_family
|
||||
before,A5111380960,Thomas Kaiser A5111380960,91.67,171.67,67.00,1.00,0.33,88.33,0.00,67.00
|
||||
before,A5071644998,Thomas Kaiser A5071644998,97.33,177.33,67.00,1.00,12.67,81.00,0.67,67.00
|
||||
before,A5034365278,Dirk Schadendorf,72.00,86.00,7.00,1.00,60.67,8.33,0.00,7.00
|
||||
before,A5100603203,Christian Weber,201.67,277.67,64.00,1.00,81.67,116.00,1.00,64.00
|
||||
before,A5100373745,Xiaohong Chen,725.33,755.33,20.00,1.00,684.00,36.33,2.00,20.00
|
||||
before,A5023982706,Richard Smith,152.67,237.67,67.00,10.00,38.33,111.00,0.33,67.00
|
||||
before,A5023752156,Albert Sickmann,11.67,22.67,4.00,1.00,5.33,3.33,0.00,4.00
|
||||
before,A5011059806,James Fulcher,13.33,24.33,4.00,1.00,1.00,8.67,0.67,4.00
|
||||
|
+262
@@ -0,0 +1,262 @@
|
||||
{
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"decisions_identical": true,
|
||||
"decision_reasons_identical": true,
|
||||
"candidate_metrics_identical": true,
|
||||
"family_metrics_identical": true,
|
||||
"authors": [
|
||||
{
|
||||
"author_id": "A5111380960",
|
||||
"label": "Thomas Kaiser A5111380960",
|
||||
"before_median_ms": 19864.066399997682,
|
||||
"after_median_ms": 13506.049799994798,
|
||||
"improvement": 0.32007628609233935,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 91.66666666666667,
|
||||
"elasticsearch": 171.66666666666666,
|
||||
"epo": 67.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 0.3333333333333333,
|
||||
"coauthor": 88.33333333333333,
|
||||
"shared_work": 0.0,
|
||||
"family": 67.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 91.66666666666667,
|
||||
"elasticsearch": 107.66666666666667,
|
||||
"epo": 3.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 0.3333333333333333,
|
||||
"coauthor": 88.33333333333333,
|
||||
"shared_work": 0.0,
|
||||
"family": 2.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5071644998",
|
||||
"label": "Thomas Kaiser A5071644998",
|
||||
"before_median_ms": 26417.263499999535,
|
||||
"after_median_ms": 12691.947600003914,
|
||||
"improvement": 0.5195585795627872,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 97.33333333333333,
|
||||
"elasticsearch": 177.33333333333334,
|
||||
"epo": 67.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 12.666666666666666,
|
||||
"coauthor": 81.0,
|
||||
"shared_work": 0.6666666666666666,
|
||||
"family": 67.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 97.33333333333333,
|
||||
"elasticsearch": 113.33333333333333,
|
||||
"epo": 3.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 12.666666666666666,
|
||||
"coauthor": 81.0,
|
||||
"shared_work": 0.6666666666666666,
|
||||
"family": 2.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5034365278",
|
||||
"label": "Dirk Schadendorf",
|
||||
"before_median_ms": 5107.349099998828,
|
||||
"after_median_ms": 3784.8194999969564,
|
||||
"improvement": 0.25894638766756223,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 72.0,
|
||||
"elasticsearch": 86.0,
|
||||
"epo": 7.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 60.666666666666664,
|
||||
"coauthor": 8.333333333333334,
|
||||
"shared_work": 0.0,
|
||||
"family": 7.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 72.0,
|
||||
"elasticsearch": 81.0,
|
||||
"epo": 2.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 60.666666666666664,
|
||||
"coauthor": 8.333333333333334,
|
||||
"shared_work": 0.0,
|
||||
"family": 1.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5100603203",
|
||||
"label": "Christian Weber",
|
||||
"before_median_ms": 32228.38679999404,
|
||||
"after_median_ms": 15214.901899991673,
|
||||
"improvement": 0.5279037081683999,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 201.66666666666666,
|
||||
"elasticsearch": 277.6666666666667,
|
||||
"epo": 64.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 81.66666666666667,
|
||||
"coauthor": 116.0,
|
||||
"shared_work": 1.0,
|
||||
"family": 64.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 201.33333333333334,
|
||||
"elasticsearch": 216.33333333333334,
|
||||
"epo": 3.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 81.66666666666667,
|
||||
"coauthor": 116.0,
|
||||
"shared_work": 0.6666666666666666,
|
||||
"family": 2.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5100373745",
|
||||
"label": "Xiaohong Chen",
|
||||
"before_median_ms": 23180.76750000182,
|
||||
"after_median_ms": 22966.470500003197,
|
||||
"improvement": 0.009244603311715484,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 725.3333333333334,
|
||||
"elasticsearch": 755.3333333333334,
|
||||
"epo": 20.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 684.0,
|
||||
"coauthor": 36.333333333333336,
|
||||
"shared_work": 2.0,
|
||||
"family": 20.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 725.0,
|
||||
"elasticsearch": 738.0,
|
||||
"epo": 3.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 684.0,
|
||||
"coauthor": 36.333333333333336,
|
||||
"shared_work": 1.6666666666666667,
|
||||
"family": 1.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5023982706",
|
||||
"label": "Richard Smith",
|
||||
"before_median_ms": 27000.009199997294,
|
||||
"after_median_ms": 20023.3070999966,
|
||||
"improvement": 0.25839628602798376,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 152.66666666666666,
|
||||
"elasticsearch": 237.66666666666666,
|
||||
"epo": 67.0,
|
||||
"uspto": 10.0,
|
||||
"institution_alias": 38.333333333333336,
|
||||
"coauthor": 111.0,
|
||||
"shared_work": 0.3333333333333333,
|
||||
"family": 67.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 152.66666666666666,
|
||||
"elasticsearch": 173.66666666666666,
|
||||
"epo": 3.0,
|
||||
"uspto": 10.0,
|
||||
"institution_alias": 38.333333333333336,
|
||||
"coauthor": 111.0,
|
||||
"shared_work": 0.3333333333333333,
|
||||
"family": 2.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5023752156",
|
||||
"label": "Albert Sickmann",
|
||||
"before_median_ms": 2354.960199998459,
|
||||
"after_median_ms": 1572.8591000079177,
|
||||
"improvement": 0.332107990611074,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 11.666666666666666,
|
||||
"elasticsearch": 22.666666666666668,
|
||||
"epo": 4.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 5.333333333333333,
|
||||
"coauthor": 3.3333333333333335,
|
||||
"shared_work": 0.0,
|
||||
"family": 4.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 11.666666666666666,
|
||||
"elasticsearch": 20.666666666666668,
|
||||
"epo": 2.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 5.333333333333333,
|
||||
"coauthor": 3.3333333333333335,
|
||||
"shared_work": 0.0,
|
||||
"family": 1.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"author_id": "A5011059806",
|
||||
"label": "James Fulcher",
|
||||
"before_median_ms": 2787.5115999922855,
|
||||
"after_median_ms": 1352.909199995338,
|
||||
"improvement": 0.5146534278102799,
|
||||
"patent_ids_identical": true,
|
||||
"counts_identical": true,
|
||||
"before_query_average": {
|
||||
"openalex": 13.333333333333334,
|
||||
"elasticsearch": 24.333333333333332,
|
||||
"epo": 4.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 1.0,
|
||||
"coauthor": 8.666666666666666,
|
||||
"shared_work": 0.6666666666666666,
|
||||
"family": 4.0
|
||||
},
|
||||
"after_query_average": {
|
||||
"openalex": 3.0,
|
||||
"elasticsearch": 12.0,
|
||||
"epo": 2.0,
|
||||
"uspto": 1.0,
|
||||
"institution_alias": 0.0,
|
||||
"coauthor": 0.0,
|
||||
"shared_work": 0.0,
|
||||
"family": 1.0
|
||||
}
|
||||
}
|
||||
],
|
||||
"average_query_count_before": {
|
||||
"openalex": 170.70833333333334,
|
||||
"elasticsearch": 219.08333333333334,
|
||||
"epo": 37.5,
|
||||
"uspto": 2.125,
|
||||
"institution_alias": 110.5,
|
||||
"coauthor": 56.625,
|
||||
"shared_work": 0.5833333333333334,
|
||||
"family": 37.5
|
||||
},
|
||||
"average_query_count_after": {
|
||||
"openalex": 169.33333333333334,
|
||||
"elasticsearch": 182.83333333333334,
|
||||
"epo": 2.625,
|
||||
"uspto": 2.125,
|
||||
"institution_alias": 110.375,
|
||||
"coauthor": 55.541666666666664,
|
||||
"shared_work": 0.4166666666666667,
|
||||
"family": 1.5
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ Helper library for the final identity guard. Not a runtime entry point.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
@@ -952,6 +953,7 @@ async def load_openalex_works_coauthor_names(
|
||||
already_full_surnames.add(normalize_name_part(parsed_known.last_name))
|
||||
|
||||
queried_surnames: set[str] = set()
|
||||
surnames_to_query: list[str] = []
|
||||
for inventor in inventor_hints:
|
||||
parsed = parse_inventor_name(strip_titles_anywhere(inventor))
|
||||
last = parsed.last_name if parsed is not None else inventor
|
||||
@@ -961,6 +963,9 @@ async def load_openalex_works_coauthor_names(
|
||||
if last_norm in already_full_surnames or last_norm in queried_surnames:
|
||||
continue
|
||||
queried_surnames.add(last_norm)
|
||||
surnames_to_query.append(last)
|
||||
|
||||
async def _lookup_surname(last: str) -> list[str]:
|
||||
body = {
|
||||
"size": 8,
|
||||
"_source": ["authorships.author.display_name", "authorships.author.id"],
|
||||
@@ -983,6 +988,7 @@ async def load_openalex_works_coauthor_names(
|
||||
}
|
||||
},
|
||||
}
|
||||
found: list[str] = []
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_WORKS_WILDCARD,
|
||||
@@ -999,9 +1005,23 @@ async def load_openalex_works_coauthor_names(
|
||||
continue
|
||||
if normalize_name_part(other.last_name) != normalize_name_part(last):
|
||||
continue
|
||||
names.append(name)
|
||||
found.append(name)
|
||||
except Exception:
|
||||
logger.exception("OpenAlex targeted coauthor lookup failed for %s / %s", key, last)
|
||||
return found
|
||||
|
||||
if surnames_to_query:
|
||||
semaphore = asyncio.Semaphore(8)
|
||||
|
||||
async def _limited(last: str) -> list[str]:
|
||||
async with semaphore:
|
||||
return await _lookup_surname(last)
|
||||
|
||||
extra_groups = await asyncio.gather(
|
||||
*(_limited(last) for last in surnames_to_query)
|
||||
)
|
||||
for extra_names in extra_groups:
|
||||
names.extend(extra_names)
|
||||
|
||||
store_openalex_works_coauthors(key, names)
|
||||
return cached_openalex_works_coauthors(key)
|
||||
@@ -1048,11 +1068,25 @@ async def load_author_institution_aliases(author: Author) -> dict[str, Instituti
|
||||
if inst is not None:
|
||||
institutions.append(inst)
|
||||
seen: set[str] = set()
|
||||
keys_and_ids: list[tuple[str, str]] = []
|
||||
for institution in institutions:
|
||||
inst_id = getattr(institution, "id", None)
|
||||
key = _author_id_key(inst_id)
|
||||
if not key or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
mapping[key] = await load_institution_alias_record(inst_id)
|
||||
keys_and_ids.append((key, inst_id))
|
||||
if not keys_and_ids:
|
||||
return mapping
|
||||
semaphore = asyncio.Semaphore(8)
|
||||
|
||||
async def _load(inst_id: str) -> InstitutionAliasRecord:
|
||||
async with semaphore:
|
||||
return await load_institution_alias_record(inst_id)
|
||||
|
||||
records = await asyncio.gather(
|
||||
*(_load(inst_id) for _key, inst_id in keys_and_ids)
|
||||
)
|
||||
for (key, _inst_id), record in zip(keys_and_ids, records):
|
||||
mapping[key] = record
|
||||
return mapping
|
||||
|
||||
@@ -42,6 +42,7 @@ Enable: ``ENABLE_AMBIGUOUS_AUTHOR_IDENTITY_GUARD``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
@@ -156,6 +157,24 @@ def is_final_identity_guard_enabled() -> bool:
|
||||
return bool(getattr(settings, "enable_ambiguous_author_identity_guard", False))
|
||||
|
||||
|
||||
def identity_evidence_io_required(
|
||||
*,
|
||||
is_ambiguous: bool,
|
||||
production_kept: Sequence[TopicFilterResult],
|
||||
combined_kept: Sequence[TopicFilterResult],
|
||||
) -> bool:
|
||||
"""True only when identity queries can change the returned patent set.
|
||||
|
||||
Unique authors keep every combined keep. Production KEEP is never dropped.
|
||||
Identity I/O is therefore needed only for ambiguous authors that have
|
||||
semantic additions to confirm or reject.
|
||||
"""
|
||||
if not is_ambiguous:
|
||||
return False
|
||||
production_keys = {patent_map_key(item.patent) for item in production_kept}
|
||||
return any(patent_map_key(item.patent) not in production_keys for item in combined_kept)
|
||||
|
||||
|
||||
def reset_identity_guard_query_stats() -> None:
|
||||
for key in _QUERY_STATS:
|
||||
_QUERY_STATS[key] = 0
|
||||
@@ -906,28 +925,67 @@ async def load_author_institution_aliases(author: Author) -> dict[str, Instituti
|
||||
return await _load_author_institution_aliases_v2(author)
|
||||
|
||||
|
||||
def _patent_needs_shared_works_lookup(
|
||||
patent: model.PatentEntry,
|
||||
author: Author,
|
||||
coauthor_names: Sequence[str],
|
||||
alias_by_id: Mapping[str, InstitutionAliasRecord] | None = None,
|
||||
) -> bool:
|
||||
"""Mirrors evaluate()'s second loop: shared works are consulted only then."""
|
||||
extras = inventor_unattested_extra_given_names_v2(patent, author)
|
||||
if extras:
|
||||
return False
|
||||
confirmed = _confirmed_coauthors(
|
||||
patent, author.display_name or "", coauthor_names
|
||||
)
|
||||
if len(confirmed) != 1:
|
||||
return False
|
||||
if _personal_identity_supported(patent, author, extras):
|
||||
return False
|
||||
inst = classify_robust_institution_match_final(
|
||||
patent, author, alias_by_id=alias_by_id
|
||||
)
|
||||
if _institution_is_strong(inst):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
async def prefetch_shared_works_for_identity_guard(
|
||||
author_id: str,
|
||||
patents: Sequence[model.PatentEntry],
|
||||
author: Author,
|
||||
coauthor_names: Sequence[str],
|
||||
*,
|
||||
institution_alias_by_id: Mapping[str, InstitutionAliasRecord] | None = None,
|
||||
) -> dict[str, CoauthorWorkContext]:
|
||||
"""Load shared-work context once per confirmed coauthor. Cached per author."""
|
||||
display = author.display_name or ""
|
||||
"""Load shared-work context once per confirmed coauthor that evaluate() would look up."""
|
||||
mapping: dict[str, CoauthorWorkContext] = {}
|
||||
names: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for patent in patents:
|
||||
if inventor_unattested_extra_given_names_v2(patent, author):
|
||||
continue
|
||||
confirmed = _confirmed_coauthors(patent, display, coauthor_names)
|
||||
if len(confirmed) != 1:
|
||||
if not _patent_needs_shared_works_lookup(
|
||||
patent,
|
||||
author,
|
||||
coauthor_names,
|
||||
alias_by_id=institution_alias_by_id,
|
||||
):
|
||||
continue
|
||||
confirmed = _confirmed_coauthors(
|
||||
patent, author.display_name or "", coauthor_names
|
||||
)
|
||||
name = confirmed[0]
|
||||
folded = name.casefold()
|
||||
if folded in seen:
|
||||
continue
|
||||
seen.add(folded)
|
||||
mapping[name] = await load_shared_works_context(author_id, name)
|
||||
names.append(name)
|
||||
if not names:
|
||||
return mapping
|
||||
contexts = await asyncio.gather(
|
||||
*(load_shared_works_context(author_id, name) for name in names)
|
||||
)
|
||||
for name, context in zip(names, contexts):
|
||||
mapping[name] = context
|
||||
return mapping
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Business logic for patent lookup by inventor."""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
@@ -12,11 +13,13 @@ 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.final_ambiguous_author_identity_guard import (
|
||||
apply_production_with_semantic_fallback_v1_and_final_identity_guard,
|
||||
identity_evidence_io_required,
|
||||
is_final_identity_guard_enabled,
|
||||
load_author_institution_aliases,
|
||||
load_openalex_works_coauthor_names,
|
||||
prefetch_shared_works_for_identity_guard,
|
||||
)
|
||||
from inse.patents.authors.pipeline_perf import mark_zero, stage
|
||||
from inse.patents.authors.semantic_topic_fallback import (
|
||||
apply_production_with_semantic_fallback_v1,
|
||||
is_semantic_topic_fallback_enabled,
|
||||
@@ -37,6 +40,29 @@ from inse.persons import logic as person_logic
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_IDENTITY_STAGES = (
|
||||
"identity_coauthor_loading",
|
||||
"identity_institution_loading",
|
||||
"identity_shared_works",
|
||||
"final_identity_guard",
|
||||
)
|
||||
|
||||
|
||||
def _inventor_hints_from_patents(patents: list[model.PatentEntry]) -> list[str]:
|
||||
hints: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for patent in patents:
|
||||
for inventor in patent.inventors or []:
|
||||
if not inventor:
|
||||
continue
|
||||
folded = inventor.casefold()
|
||||
if folded in seen:
|
||||
continue
|
||||
seen.add(folded)
|
||||
hints.append(inventor)
|
||||
return hints
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
@@ -45,171 +71,229 @@ async def get_patents_by_author_id(
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = await _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
if not author_name or not author_name.strip():
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
try:
|
||||
search_result = await search_author_patents_adaptive(
|
||||
search_client, author_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
all_patents = search_result.patents
|
||||
patent_hit_count = len(all_patents)
|
||||
if search_result.completeness.value == "truncated_inconclusive":
|
||||
# Unread ES hits remain; zero UI patents must not be treated as proof
|
||||
# that the author has no patents in the index.
|
||||
logger.warning(
|
||||
"search_completeness=%s for author %s (%s): epo_scanned=%d/%d "
|
||||
"uspto_scanned=%d/%d stop=%s/%s strong_matches=%d/%d",
|
||||
search_result.completeness.value,
|
||||
author_id,
|
||||
author_name,
|
||||
search_result.epo.hits_scanned,
|
||||
search_result.epo.total_hits,
|
||||
search_result.uspto.hits_scanned,
|
||||
search_result.uspto.total_hits,
|
||||
search_result.epo.stop_reason,
|
||||
search_result.uspto.stop_reason,
|
||||
search_result.epo.strong_name_match_count,
|
||||
search_result.uspto.strong_name_match_count,
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
if not matched_patents:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
await enrich_patents_classifications(matched_patents, ipc_search_client)
|
||||
|
||||
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
|
||||
)
|
||||
is_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,
|
||||
)
|
||||
|
||||
patent_topic_map = None
|
||||
try:
|
||||
resolver = PatentOpenAlexMappingResolver()
|
||||
patent_topic_map = await resolver.resolve_topics_for_patents(matched_patents)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"OpenAlex topic resolution failed for %s; falling back to legacy mapping",
|
||||
author_name,
|
||||
)
|
||||
|
||||
production_kept = filter_patents_by_ipc_topic_mapping(
|
||||
matched_patents,
|
||||
author,
|
||||
is_ambiguous=is_ambiguous,
|
||||
patent_topic_map=patent_topic_map,
|
||||
)
|
||||
filtered = production_kept
|
||||
if is_semantic_topic_fallback_enabled():
|
||||
filtered = apply_production_with_semantic_fallback_v1(
|
||||
name_matched_patents=matched_patents,
|
||||
production_kept=production_kept,
|
||||
author=author,
|
||||
patent_topic_map=patent_topic_map,
|
||||
)
|
||||
if is_final_identity_guard_enabled():
|
||||
coauthors: tuple[str, ...] = ()
|
||||
aliases: dict = {}
|
||||
shared = None
|
||||
if is_ambiguous:
|
||||
inventor_hints = []
|
||||
seen_inventors: set[str] = set()
|
||||
for patent in matched_patents:
|
||||
for inventor in patent.inventors or []:
|
||||
if not inventor:
|
||||
continue
|
||||
folded = inventor.casefold()
|
||||
if folded in seen_inventors:
|
||||
continue
|
||||
seen_inventors.add(folded)
|
||||
inventor_hints.append(inventor)
|
||||
coauthors = await load_openalex_works_coauthor_names(
|
||||
author_id,
|
||||
inventor_hints=inventor_hints,
|
||||
with stage("total"):
|
||||
with stage("author_load"):
|
||||
author = await _get_author(author_id)
|
||||
if not author:
|
||||
mark_zero(
|
||||
"patent_search",
|
||||
"name_matching",
|
||||
"family_expansion",
|
||||
"classification_enrichment",
|
||||
"production_filter",
|
||||
"semantic_fallback",
|
||||
*_IDENTITY_STAGES,
|
||||
"response_build",
|
||||
)
|
||||
aliases = await load_author_institution_aliases(author)
|
||||
shared = await prefetch_shared_works_for_identity_guard(
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
if not author_name or not author_name.strip():
|
||||
mark_zero(
|
||||
"patent_search",
|
||||
"name_matching",
|
||||
"family_expansion",
|
||||
"classification_enrichment",
|
||||
"production_filter",
|
||||
"semantic_fallback",
|
||||
*_IDENTITY_STAGES,
|
||||
"response_build",
|
||||
)
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
try:
|
||||
with stage("patent_search"):
|
||||
search_result = await search_author_patents_adaptive(
|
||||
search_client, author_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
all_patents = search_result.patents
|
||||
patent_hit_count = len(all_patents)
|
||||
if search_result.completeness.value == "truncated_inconclusive":
|
||||
# Unread ES hits remain; zero UI patents must not be treated as proof
|
||||
# that the author has no patents in the index.
|
||||
logger.warning(
|
||||
"search_completeness=%s for author %s (%s): epo_scanned=%d/%d "
|
||||
"uspto_scanned=%d/%d stop=%s/%s strong_matches=%d/%d",
|
||||
search_result.completeness.value,
|
||||
author_id,
|
||||
author_name,
|
||||
search_result.epo.hits_scanned,
|
||||
search_result.epo.total_hits,
|
||||
search_result.uspto.hits_scanned,
|
||||
search_result.uspto.total_hits,
|
||||
search_result.epo.stop_reason,
|
||||
search_result.uspto.stop_reason,
|
||||
search_result.epo.strong_name_match_count,
|
||||
search_result.uspto.strong_name_match_count,
|
||||
)
|
||||
with stage("name_matching"):
|
||||
matched_patents = filter_patents_by_author_name(all_patents, author_name)
|
||||
try:
|
||||
with stage("family_expansion"):
|
||||
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,
|
||||
)
|
||||
|
||||
if not matched_patents:
|
||||
mark_zero(
|
||||
"classification_enrichment",
|
||||
"production_filter",
|
||||
"semantic_fallback",
|
||||
*_IDENTITY_STAGES,
|
||||
"response_build",
|
||||
)
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
async def _enrich_classifications() -> None:
|
||||
with stage("classification_enrichment"):
|
||||
await enrich_patents_classifications(matched_patents, ipc_search_client)
|
||||
|
||||
async def _count_last_name() -> int | None:
|
||||
parsed_for_last = parse_person_name(author_name)
|
||||
if parsed_for_last and not parsed_for_last.is_single_token:
|
||||
return await person_logic.count_authors_by_last_name(
|
||||
parsed_for_last.last_name
|
||||
)
|
||||
return None
|
||||
|
||||
async def _resolve_topics():
|
||||
try:
|
||||
resolver = PatentOpenAlexMappingResolver()
|
||||
return await resolver.resolve_topics_for_patents(matched_patents)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"OpenAlex topic resolution failed for %s; falling back to legacy mapping",
|
||||
author_name,
|
||||
)
|
||||
return None
|
||||
|
||||
_, full_name_count, last_name_count, patent_topic_map = await asyncio.gather(
|
||||
_enrich_classifications(),
|
||||
person_logic.count_authors_by_display_name(author_name),
|
||||
_count_last_name(),
|
||||
_resolve_topics(),
|
||||
)
|
||||
|
||||
with stage("production_filter"):
|
||||
is_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,
|
||||
)
|
||||
production_kept = filter_patents_by_ipc_topic_mapping(
|
||||
matched_patents,
|
||||
author,
|
||||
coauthors,
|
||||
is_ambiguous=is_ambiguous,
|
||||
patent_topic_map=patent_topic_map,
|
||||
)
|
||||
filtered = apply_production_with_semantic_fallback_v1_and_final_identity_guard(
|
||||
name_matched_patents=matched_patents,
|
||||
production_kept=production_kept,
|
||||
combined_kept=filtered,
|
||||
author=author,
|
||||
is_ambiguous=is_ambiguous,
|
||||
openalex_coauthor_names=coauthors,
|
||||
institution_alias_by_id=aliases,
|
||||
shared_works_by_coauthor=shared,
|
||||
filtered = production_kept
|
||||
with stage("semantic_fallback"):
|
||||
if is_semantic_topic_fallback_enabled():
|
||||
filtered = apply_production_with_semantic_fallback_v1(
|
||||
name_matched_patents=matched_patents,
|
||||
production_kept=production_kept,
|
||||
author=author,
|
||||
patent_topic_map=patent_topic_map,
|
||||
)
|
||||
if is_final_identity_guard_enabled():
|
||||
coauthors: tuple[str, ...] = ()
|
||||
aliases: dict = {}
|
||||
shared = None
|
||||
if identity_evidence_io_required(
|
||||
is_ambiguous=is_ambiguous,
|
||||
production_kept=production_kept,
|
||||
combined_kept=filtered,
|
||||
):
|
||||
inventor_hints = _inventor_hints_from_patents(matched_patents)
|
||||
|
||||
async def _load_coauthors() -> tuple[str, ...]:
|
||||
with stage("identity_coauthor_loading"):
|
||||
return await load_openalex_works_coauthor_names(
|
||||
author_id,
|
||||
inventor_hints=inventor_hints,
|
||||
)
|
||||
|
||||
async def _load_aliases():
|
||||
with stage("identity_institution_loading"):
|
||||
return await load_author_institution_aliases(author)
|
||||
|
||||
coauthors, aliases = await asyncio.gather(
|
||||
_load_coauthors(),
|
||||
_load_aliases(),
|
||||
)
|
||||
with stage("identity_shared_works"):
|
||||
shared = await prefetch_shared_works_for_identity_guard(
|
||||
author_id,
|
||||
matched_patents,
|
||||
author,
|
||||
coauthors,
|
||||
institution_alias_by_id=aliases,
|
||||
)
|
||||
with stage("final_identity_guard"):
|
||||
filtered = apply_production_with_semantic_fallback_v1_and_final_identity_guard(
|
||||
name_matched_patents=matched_patents,
|
||||
production_kept=production_kept,
|
||||
combined_kept=filtered,
|
||||
author=author,
|
||||
is_ambiguous=is_ambiguous,
|
||||
openalex_coauthor_names=coauthors,
|
||||
institution_alias_by_id=aliases,
|
||||
shared_works_by_coauthor=shared,
|
||||
)
|
||||
else:
|
||||
mark_zero(*_IDENTITY_STAGES)
|
||||
else:
|
||||
mark_zero(*_IDENTITY_STAGES)
|
||||
|
||||
logger.info(
|
||||
"patents_openalex_keywords mapping for %s: ambiguous=%s, %d name-matched, %d after topic filter",
|
||||
author_name,
|
||||
is_ambiguous,
|
||||
len(matched_patents),
|
||||
len(filtered),
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"patents_openalex_keywords mapping for %s: ambiguous=%s, %d name-matched, %d after topic filter",
|
||||
author_name,
|
||||
is_ambiguous,
|
||||
len(matched_patents),
|
||||
len(filtered),
|
||||
)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(filtered),
|
||||
patents=[item.patent for item in filtered],
|
||||
)
|
||||
with stage("response_build"):
|
||||
response = model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(filtered),
|
||||
patents=[item.patent for item in filtered],
|
||||
)
|
||||
return response
|
||||
|
||||
async def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Request-scoped pipeline timing/query counters for benchmarks.
|
||||
|
||||
Inactive unless a benchmark (or test) enters ``capture_pipeline_perf``.
|
||||
Does not appear in API responses.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterator
|
||||
|
||||
|
||||
@dataclass
|
||||
class PipelinePerf:
|
||||
timings_ms: dict[str, float] = field(default_factory=dict)
|
||||
queries: dict[str, int] = field(default_factory=dict)
|
||||
cache_hits: dict[str, int] = field(default_factory=dict)
|
||||
extras: dict[str, object] = field(default_factory=dict)
|
||||
|
||||
def add_query(self, kind: str, n: int = 1) -> None:
|
||||
self.queries[kind] = int(self.queries.get(kind, 0)) + n
|
||||
|
||||
def add_cache_hit(self, kind: str, n: int = 1) -> None:
|
||||
self.cache_hits[kind] = int(self.cache_hits.get(kind, 0)) + n
|
||||
|
||||
|
||||
_PERF: ContextVar[PipelinePerf | None] = ContextVar("author_patent_pipeline_perf", default=None)
|
||||
|
||||
|
||||
def current_perf() -> PipelinePerf | None:
|
||||
return _PERF.get()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def capture_pipeline_perf() -> Iterator[PipelinePerf]:
|
||||
perf = PipelinePerf()
|
||||
token = _PERF.set(perf)
|
||||
try:
|
||||
yield perf
|
||||
finally:
|
||||
_PERF.reset(token)
|
||||
|
||||
|
||||
def mark_zero(*names: str) -> None:
|
||||
perf = current_perf()
|
||||
if perf is None:
|
||||
return
|
||||
for name in names:
|
||||
perf.timings_ms.setdefault(name, 0.0)
|
||||
|
||||
|
||||
class StageTimer:
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
self._t0 = 0.0
|
||||
|
||||
def __enter__(self) -> StageTimer:
|
||||
self._t0 = time.perf_counter()
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: object) -> None:
|
||||
perf = current_perf()
|
||||
if perf is None:
|
||||
return
|
||||
perf.timings_ms[self.name] = (time.perf_counter() - self._t0) * 1000.0
|
||||
|
||||
|
||||
def stage(name: str) -> StageTimer:
|
||||
return StageTimer(name)
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Elasticsearch query builders for inventor-based patent search."""
|
||||
from typing import Any
|
||||
from typing import Any, Sequence
|
||||
|
||||
from inse.patents.authors.name_matching import (
|
||||
inventor_search_phrases,
|
||||
@@ -203,17 +203,31 @@ class InventorSearchQueries:
|
||||
application_number: str,
|
||||
size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
variants = _application_number_variants(application_number)
|
||||
if not variants:
|
||||
return self.epo_query_by_application_numbers([application_number], size_per_number=size)
|
||||
|
||||
def epo_query_by_application_numbers(
|
||||
self,
|
||||
application_numbers: Sequence[str],
|
||||
size_per_number: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
should: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
numbers = [str(number).strip() for number in application_numbers if str(number).strip()]
|
||||
for number in numbers:
|
||||
for variant in _application_number_variants(number):
|
||||
if variant in seen:
|
||||
continue
|
||||
seen.add(variant)
|
||||
should.append({"term": {"application_number": variant}})
|
||||
if not should:
|
||||
return {"size": 0, "query": {"match_none": {}}}
|
||||
|
||||
should = [{"term": {"application_number": variant}} for variant in variants]
|
||||
query: dict[str, Any] = (
|
||||
should[0]
|
||||
if len(should) == 1
|
||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
||||
)
|
||||
|
||||
size = min(max(size_per_number * max(len(numbers), 1), size_per_number), 5000)
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
@@ -310,3 +324,9 @@ def _application_number_variants(application_number: str) -> list[str]:
|
||||
if cleaned.upper().startswith("EP"):
|
||||
_add(cleaned[2:])
|
||||
return variants
|
||||
|
||||
|
||||
def application_numbers_equivalent(left: str | None, right: str | None) -> bool:
|
||||
if not left or not right:
|
||||
return False
|
||||
return bool(set(_application_number_variants(left)) & set(_application_number_variants(right)))
|
||||
|
||||
@@ -36,7 +36,9 @@ from inse.patents.authors.semantic_topic_fallback_v1_frozen import (
|
||||
SEMANTIC_FALLBACK_DEFAULT_THRESHOLD,
|
||||
SEMANTIC_FALLBACK_MODEL_NAME,
|
||||
_build_semantic_vectors,
|
||||
_exact_topic_or_subfield_match,
|
||||
_pairwise_best_semantic_similarity,
|
||||
_semantic_domain_conflict,
|
||||
decide_semantic_topic_fallback_v1,
|
||||
)
|
||||
from inse.patents.authors.topic_filter import TopicFilterResult
|
||||
@@ -129,7 +131,14 @@ def _semantic_fallback_keeps(
|
||||
|
||||
vectors: dict[str, Any] = {}
|
||||
if similarity_fn is None:
|
||||
vectors = _build_semantic_vectors([cand for _patent, cand in candidates])
|
||||
need_similarity = [
|
||||
cand
|
||||
for _patent, cand in candidates
|
||||
if not _exact_topic_or_subfield_match(cand)
|
||||
and not _semantic_domain_conflict(cand)[0]
|
||||
]
|
||||
if need_similarity:
|
||||
vectors = _build_semantic_vectors(need_similarity)
|
||||
|
||||
keeps: list[TopicFilterResult] = []
|
||||
for patent, cand in candidates:
|
||||
|
||||
@@ -768,3 +768,83 @@ def test_topic_signals_are_not_identity_evidence() -> None:
|
||||
source_mod = inspect.getsource(guard_final)
|
||||
assert "semantic_similarity" not in source_mod
|
||||
assert "evaluation_field" not in source_mod
|
||||
|
||||
|
||||
def test_identity_io_required_only_for_ambiguous_semantic_additions() -> None:
|
||||
production_patent = _patent("EP-PROD")
|
||||
semantic_patent = _patent("EP-SEM")
|
||||
production = [_keep(production_patent, "strict_topic_match")]
|
||||
combined = [
|
||||
_keep(production_patent, "strict_topic_match"),
|
||||
_keep(semantic_patent, "semantic_topic_fallback_v1"),
|
||||
]
|
||||
assert (
|
||||
guard_final.identity_evidence_io_required(
|
||||
is_ambiguous=False,
|
||||
production_kept=production,
|
||||
combined_kept=combined,
|
||||
)
|
||||
is False
|
||||
)
|
||||
assert (
|
||||
guard_final.identity_evidence_io_required(
|
||||
is_ambiguous=True,
|
||||
production_kept=production,
|
||||
combined_kept=production,
|
||||
)
|
||||
is False
|
||||
)
|
||||
assert (
|
||||
guard_final.identity_evidence_io_required(
|
||||
is_ambiguous=True,
|
||||
production_kept=production,
|
||||
combined_kept=combined,
|
||||
)
|
||||
is True
|
||||
)
|
||||
|
||||
|
||||
def test_prefetch_skips_patents_evaluate_would_not_lookup(monkeypatch) -> None:
|
||||
import asyncio
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
async def fake_load(author_id: str, name: str):
|
||||
calls.append(name)
|
||||
return CoauthorWorkContext(
|
||||
coauthor_name=name,
|
||||
shared_work_count=4,
|
||||
distinct_years=(2010, 2012),
|
||||
institution_names=("University of Example",),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(guard_final, "load_shared_works_context", fake_load)
|
||||
author = _author(last_known=["University of Duisburg-Essen"])
|
||||
strong = _patent(
|
||||
"EP-STRONG",
|
||||
inventors=["Hale, Jordan", "Herzinger, Stefan"],
|
||||
assignees=["Universität Duisburg-Essen"],
|
||||
)
|
||||
weak = _patent(
|
||||
"EP-WEAK",
|
||||
inventors=["Hale, Jordan", "Herzinger, Stefan"],
|
||||
assignees=[],
|
||||
)
|
||||
asyncio.run(
|
||||
guard_final.prefetch_shared_works_for_identity_guard(
|
||||
"A100",
|
||||
[strong],
|
||||
author,
|
||||
["Stefan Herzinger"],
|
||||
)
|
||||
)
|
||||
assert calls == []
|
||||
asyncio.run(
|
||||
guard_final.prefetch_shared_works_for_identity_guard(
|
||||
"A100",
|
||||
[weak],
|
||||
author,
|
||||
["Stefan Herzinger"],
|
||||
)
|
||||
)
|
||||
assert calls == ["Herzinger, Stefan"]
|
||||
|
||||
@@ -185,3 +185,36 @@ def test_encode_failure_returns_production_keeps() -> None:
|
||||
similarity_fn=boom,
|
||||
)
|
||||
assert [item.patent.patent_id for item in combined] == ["EP-KEEP"]
|
||||
|
||||
|
||||
def test_exact_overlap_does_not_build_semantic_vectors(monkeypatch) -> None:
|
||||
patent = _patent("EP-EXACT")
|
||||
mapped = MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T10001",
|
||||
topic_display_name="Organic synthesis methods",
|
||||
subfield_id="https://openalex.org/subfields/1605",
|
||||
subfield_name="Organic Chemistry",
|
||||
field_id="https://openalex.org/fields/16",
|
||||
field_name="Chemistry",
|
||||
domain_id="https://openalex.org/domains/3",
|
||||
domain_name="Physical Sciences",
|
||||
)
|
||||
called = {"n": 0}
|
||||
|
||||
def boom(_candidates):
|
||||
called["n"] += 1
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.authors.semantic_topic_fallback._build_semantic_vectors",
|
||||
boom,
|
||||
)
|
||||
combined = apply_production_with_semantic_fallback_v1(
|
||||
name_matched_patents=[patent],
|
||||
production_kept=[],
|
||||
author=_chemistry_author(),
|
||||
patent_topic_map={patent_map_key(patent): [mapped]},
|
||||
)
|
||||
assert called["n"] == 0
|
||||
assert [item.patent.patent_id for item in combined] == ["EP-EXACT"]
|
||||
assert combined[0].keep_reason == "semantic_topic_fallback_v1"
|
||||
|
||||
@@ -112,6 +112,20 @@ def patent_map_key(patent: model.PatentEntry) -> str:
|
||||
return f"{source}:{patent_id}:{publication_date}:{stage}"
|
||||
|
||||
|
||||
def _application_numbers_equivalent(left: str | None, right: str | None) -> bool:
|
||||
if not left or not right:
|
||||
return False
|
||||
left_n = left.strip()
|
||||
right_n = right.strip()
|
||||
if not left_n or not right_n:
|
||||
return False
|
||||
if left_n == right_n:
|
||||
return True
|
||||
left_core = left_n[2:] if left_n.upper().startswith("EP") else left_n
|
||||
right_core = right_n[2:] if right_n.upper().startswith("EP") else right_n
|
||||
return left_n == right_core or right_n == left_core or left_core == right_core
|
||||
|
||||
|
||||
async def expand_matched_epo_application_families(
|
||||
matched_patents: list[model.PatentEntry],
|
||||
search_client,
|
||||
@@ -136,6 +150,7 @@ async def expand_matched_epo_application_families(
|
||||
|
||||
existing_keys = {patent_dedup_key(patent) for patent in matched_patents}
|
||||
extra: list[model.PatentEntry] = []
|
||||
family_batch_size = 40
|
||||
|
||||
async def _fetch_family(application_number: str) -> list[model.PatentEntry]:
|
||||
try:
|
||||
@@ -151,17 +166,54 @@ async def expand_matched_epo_application_families(
|
||||
return []
|
||||
return parse_epo_hits(data)
|
||||
|
||||
family_results = await asyncio.gather(
|
||||
*(_fetch_family(application_number) for application_number in application_numbers)
|
||||
)
|
||||
for family_patents in family_results:
|
||||
for patent in family_patents:
|
||||
async def _fetch_family_batch(numbers: list[str]) -> list[model.PatentEntry]:
|
||||
if (
|
||||
len(numbers) == 1
|
||||
or not hasattr(search_client, "epo_query_by_application_numbers")
|
||||
):
|
||||
groups = await asyncio.gather(
|
||||
*(_fetch_family(number) for number in numbers)
|
||||
)
|
||||
return [patent for group in groups for patent in group]
|
||||
try:
|
||||
data = await search_client.search_epo(
|
||||
search_client.epo_query_by_application_numbers(numbers)
|
||||
)
|
||||
except (MissingApiKeyError, httpx.HTTPError) as exc:
|
||||
logger.warning(
|
||||
"EPO family expansion batch failed for %d applications: %s",
|
||||
len(numbers),
|
||||
exc,
|
||||
)
|
||||
return []
|
||||
return parse_epo_hits(data)
|
||||
|
||||
def _append_unique(patents: list[model.PatentEntry]) -> None:
|
||||
for patent in patents:
|
||||
key = patent_dedup_key(patent)
|
||||
if key in existing_keys:
|
||||
continue
|
||||
existing_keys.add(key)
|
||||
extra.append(patent)
|
||||
|
||||
for start in range(0, len(application_numbers), family_batch_size):
|
||||
chunk = application_numbers[start : start + family_batch_size]
|
||||
family_patents = await _fetch_family_batch(chunk)
|
||||
by_requested: dict[str, list[model.PatentEntry]] = {number: [] for number in chunk}
|
||||
unmatched: list[model.PatentEntry] = []
|
||||
for patent in family_patents:
|
||||
placed = False
|
||||
for requested in chunk:
|
||||
if _application_numbers_equivalent(patent.application_number, requested):
|
||||
by_requested[requested].append(patent)
|
||||
placed = True
|
||||
break
|
||||
if not placed:
|
||||
unmatched.append(patent)
|
||||
for requested in chunk:
|
||||
_append_unique(by_requested[requested])
|
||||
_append_unique(unmatched)
|
||||
|
||||
if not extra:
|
||||
return matched_patents
|
||||
|
||||
|
||||
@@ -85,6 +85,17 @@ def test_epo_query_by_application_number_uses_term_filter():
|
||||
assert "application_number" in payload["_source"]
|
||||
|
||||
|
||||
def test_epo_query_by_application_numbers_batches_term_filters():
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
payload = client.epo_query_by_application_numbers(["12743403.3", "13818713.3"])
|
||||
|
||||
assert payload["query"]["bool"]["minimum_should_match"] == 1
|
||||
terms = payload["query"]["bool"]["should"]
|
||||
assert {"term": {"application_number": "12743403.3"}} in terms
|
||||
assert {"term": {"application_number": "13818713.3"}} in terms
|
||||
assert payload["size"] == 40
|
||||
|
||||
|
||||
def test_epo_query_by_applicant_uses_applicants_name_field():
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
payload = client.epo_query_by_applicant(
|
||||
|
||||
@@ -161,6 +161,67 @@ def test_expand_matched_epo_application_families_adds_grant_stage() -> None:
|
||||
assert {patent.kind for patent in expanded} == {"A1", "B1"}
|
||||
|
||||
|
||||
def test_expand_matched_epo_application_families_batches_unique_numbers() -> None:
|
||||
first = _epo_patent(publication_date="20150506", kind="A1")
|
||||
first.application_number = "12743403.3"
|
||||
second = _epo_patent(publication_date="20160101", kind="A1")
|
||||
second.application_number = "13818713.3"
|
||||
second.patent_id = "EP9990001"
|
||||
|
||||
captured: list[list[str]] = []
|
||||
|
||||
class _FakeBatchClient:
|
||||
async def search_epo(self, payload):
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_id": "2867692",
|
||||
"_source": {
|
||||
"doc_number": "2867692",
|
||||
"kind": "B1",
|
||||
"date_publication": "20180411",
|
||||
"application_number": "12743403.3",
|
||||
"title_en": "METHOD FOR GENERATING AND USING A MAP",
|
||||
"inventors_name": ["MARRÓN, Pedro José"],
|
||||
"applicants_name": ["Universität Duisburg-Essen"],
|
||||
"ipc": ["G01S 5/02"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"_id": "9990002",
|
||||
"_source": {
|
||||
"doc_number": "9990002",
|
||||
"kind": "B1",
|
||||
"date_publication": "20190101",
|
||||
"application_number": "13818713.3",
|
||||
"title_en": "OTHER",
|
||||
"inventors_name": ["WEBER, Christian"],
|
||||
"applicants_name": ["Universität Duisburg-Essen"],
|
||||
"ipc": ["G01S 5/02"],
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def epo_query_by_application_numbers(self, application_numbers, size_per_number=20):
|
||||
captured.append(list(application_numbers))
|
||||
return {"query": {"terms": {"application_number": list(application_numbers)}}}
|
||||
|
||||
def epo_query_by_application_number(self, application_number: str):
|
||||
raise AssertionError("single-number family query should not run for a batch")
|
||||
|
||||
import asyncio
|
||||
|
||||
expanded = asyncio.run(
|
||||
expand_matched_epo_application_families([first, second], _FakeBatchClient())
|
||||
)
|
||||
assert captured == [["12743403.3", "13818713.3"]]
|
||||
assert {patent.kind for patent in expanded} >= {"A1", "B1"}
|
||||
assert len(expanded) == 4
|
||||
|
||||
|
||||
def test_assignee_matches_institution_name_accepts_alternative_names() -> None:
|
||||
from inse.patents.name_matching import assignee_matches_institution_name
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@
|
||||
[total]="totalPatents"
|
||||
queryParamPageKey="page"
|
||||
queryParamSizeKey="size"
|
||||
[pageSizeOptions]="[10, 20, 50]"
|
||||
[pageSizeOptions]="[10, 25, 50]"
|
||||
(handlePageChange)="onPatentPageChange($event)" />
|
||||
</div>
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ export class InstitutionPatentsComponent implements OnInit {
|
||||
sortDirection: SortDirection = 'desc';
|
||||
|
||||
pageIndex = 0;
|
||||
pageSize = 20;
|
||||
pageSize = 10;
|
||||
totalPatents = 0;
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -250,7 +250,7 @@ export class InstitutionPatentsComponent implements OnInit {
|
||||
|
||||
private parsePageSizeParam(value: string | null): number {
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : 20;
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : 10;
|
||||
}
|
||||
|
||||
private isValidFilter(value: string | null): value is SourceFilter {
|
||||
|
||||
Reference in New Issue
Block a user