ts-136-patent-to-researchers-v2 #224
+3
-9
@@ -23,15 +23,9 @@ Run tests: `./gradlew :service:test`
|
||||
Builds the `org_patents` Elasticsearch index for a given institution: fetches its
|
||||
OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee
|
||||
and/or inventor name, and reindexes. Each patent is tagged with a `match_type`
|
||||
(`institution`, `name`, or `both`, the latter being highest confidence). Every
|
||||
inventor-name match counts outright only if the assignee is the institution itself;
|
||||
everything else matched on name alone — a personal-assignee match or a third-party
|
||||
assignee (e.g. an industry partner on a co-invented patent) — only counts if the
|
||||
patent's primary IPC/CPC classification also maps to OpenAlex research topics that
|
||||
appear on the author's own profile. This applies regardless of how common the name
|
||||
looks in our local OpenAlex data — a name can appear unique there while still being
|
||||
common globally in EPO/USPTO, so a bare name match alone is never a strong enough
|
||||
signal on its own.
|
||||
(`institution`, `name`, or `both`, the latter being highest confidence). An
|
||||
inventor-name match counts only if the assignee is the institution itself or the
|
||||
person themselves — this avoids pulling in unrelated patents via a shared name.
|
||||
|
||||
```bash
|
||||
python scripts/patents/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
*
|
||||
!.gitignore
|
||||
!labeling_presentation.json
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -4,13 +4,9 @@ index_org_patents.py — Build the org_patents Elasticsearch index for one insti
|
||||
|
||||
Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for
|
||||
patents matched via institution assignee and/or author name (match_type: "institution",
|
||||
"name", or "both"), deletes existing documents for the institution, and reindexes.
|
||||
Every inventor-name match counts outright only if the assignee is the institution
|
||||
itself; everything else (a personal-assignee match or a third-party assignee) only
|
||||
counts if the patent's primary IPC/CPC classification also maps to OpenAlex research
|
||||
topics that appear on the author's own profile — applied regardless of how common the
|
||||
name looks in our local OpenAlex data, since a name can appear unique there while
|
||||
still being common globally in EPO/USPTO.
|
||||
"name", or "both"), deletes existing documents for the institution, and reindexes. An
|
||||
inventor-name match counts only if the assignee is the institution itself or the
|
||||
person themselves, to avoid pulling in unrelated patents via a shared name.
|
||||
|
||||
Usage:
|
||||
python scripts/patents/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Ranking metrics for keyword → patent search evaluation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
|
||||
|
||||
def normalize_patent_id(patent_id: str) -> str:
|
||||
return patent_id.strip().upper()
|
||||
|
||||
|
||||
def precision_at_k(
|
||||
ranked_ids: Sequence[str],
|
||||
relevant_ids: Iterable[str],
|
||||
k: int,
|
||||
) -> float:
|
||||
if k <= 0:
|
||||
return 0.0
|
||||
relevant = {normalize_patent_id(pid) for pid in relevant_ids}
|
||||
if not relevant:
|
||||
return 0.0
|
||||
top = [normalize_patent_id(pid) for pid in ranked_ids[:k]]
|
||||
hits = sum(1 for pid in top if pid in relevant)
|
||||
return hits / k
|
||||
|
||||
|
||||
def recall_at_k(
|
||||
ranked_ids: Sequence[str],
|
||||
relevant_ids: Iterable[str],
|
||||
k: int,
|
||||
) -> float:
|
||||
relevant = {normalize_patent_id(pid) for pid in relevant_ids}
|
||||
if not relevant or k <= 0:
|
||||
return 0.0
|
||||
top = {normalize_patent_id(pid) for pid in ranked_ids[:k]}
|
||||
return len(top & relevant) / len(relevant)
|
||||
|
||||
|
||||
def average_precision(
|
||||
ranked_ids: Sequence[str],
|
||||
relevant_ids: Iterable[str],
|
||||
) -> float:
|
||||
relevant = {normalize_patent_id(pid) for pid in relevant_ids}
|
||||
if not relevant:
|
||||
return 0.0
|
||||
|
||||
hits = 0
|
||||
precision_sum = 0.0
|
||||
for idx, patent_id in enumerate(ranked_ids, start=1):
|
||||
if normalize_patent_id(patent_id) not in relevant:
|
||||
continue
|
||||
hits += 1
|
||||
precision_sum += hits / idx
|
||||
|
||||
if hits == 0:
|
||||
return 0.0
|
||||
return precision_sum / len(relevant)
|
||||
|
||||
|
||||
def dcg_at_k(gains: Sequence[float], k: int) -> float:
|
||||
total = 0.0
|
||||
for idx, gain in enumerate(gains[:k], start=1):
|
||||
total += gain / math.log2(idx + 1)
|
||||
return total
|
||||
|
||||
|
||||
def ndcg_at_k(
|
||||
ranked_ids: Sequence[str],
|
||||
relevance_grades: Mapping[str, float],
|
||||
k: int,
|
||||
) -> float:
|
||||
if k <= 0 or not relevance_grades:
|
||||
return 0.0
|
||||
|
||||
grades = {
|
||||
normalize_patent_id(pid): float(grade)
|
||||
for pid, grade in relevance_grades.items()
|
||||
if float(grade) > 0
|
||||
}
|
||||
if not grades:
|
||||
return 0.0
|
||||
|
||||
gains = [
|
||||
grades.get(normalize_patent_id(pid), 0.0) for pid in ranked_ids[:k]
|
||||
]
|
||||
ideal = sorted(grades.values(), reverse=True)
|
||||
ideal_dcg = dcg_at_k(ideal, k)
|
||||
if ideal_dcg <= 0:
|
||||
return 0.0
|
||||
return dcg_at_k(gains, k) / ideal_dcg
|
||||
|
||||
|
||||
def mrr(
|
||||
ranked_ids: Sequence[str],
|
||||
relevant_ids: Iterable[str],
|
||||
) -> float:
|
||||
relevant = {normalize_patent_id(pid) for pid in relevant_ids}
|
||||
if not relevant:
|
||||
return 0.0
|
||||
for idx, patent_id in enumerate(ranked_ids, start=1):
|
||||
if normalize_patent_id(patent_id) in relevant:
|
||||
return 1.0 / idx
|
||||
return 0.0
|
||||
|
||||
|
||||
def ipc_prefix_hit_rate(
|
||||
patent_ipc_lists: Sequence[Sequence[str]],
|
||||
prefixes: Sequence[str],
|
||||
*,
|
||||
k: int | None = None,
|
||||
) -> float:
|
||||
"""Share of patents whose IPC/CPC codes start with any expected prefix."""
|
||||
if not prefixes:
|
||||
return 0.0
|
||||
subset = list(patent_ipc_lists[:k] if k is not None else patent_ipc_lists)
|
||||
if not subset:
|
||||
return 0.0
|
||||
|
||||
normalized_prefixes = [prefix.strip().upper() for prefix in prefixes if prefix.strip()]
|
||||
if not normalized_prefixes:
|
||||
return 0.0
|
||||
|
||||
hits = 0
|
||||
for codes in subset:
|
||||
normalized_codes = [code.strip().upper().replace(" ", "") for code in codes]
|
||||
if any(
|
||||
code.startswith(prefix)
|
||||
for code in normalized_codes
|
||||
for prefix in normalized_prefixes
|
||||
):
|
||||
hits += 1
|
||||
return hits / len(subset)
|
||||
|
||||
|
||||
def mean(values: Sequence[float]) -> float:
|
||||
if not values:
|
||||
return 0.0
|
||||
return sum(values) / len(values)
|
||||
|
||||
|
||||
def normalize_application_number(application_number: str | None) -> str | None:
|
||||
if not application_number or not application_number.strip():
|
||||
return None
|
||||
return application_number.strip().upper().replace(" ", "")
|
||||
|
||||
|
||||
def normalize_title_key(title: str | None) -> str | None:
|
||||
if not title or not title.strip():
|
||||
return None
|
||||
return " ".join(title.lower().split())
|
||||
|
||||
|
||||
def patent_family_key(
|
||||
*,
|
||||
patent_id: str,
|
||||
application_number: str | None = None,
|
||||
title: str | None = None,
|
||||
) -> str:
|
||||
"""Best-effort family key: application number, else normalized title, else patent id."""
|
||||
app = normalize_application_number(application_number)
|
||||
if app:
|
||||
return f"app:{app}"
|
||||
title_key = normalize_title_key(title)
|
||||
if title_key:
|
||||
return f"title:{title_key}"
|
||||
return f"id:{normalize_patent_id(patent_id)}"
|
||||
|
||||
|
||||
def analyze_family_duplicates_in_top_k(
|
||||
family_keys: Sequence[str],
|
||||
k: int,
|
||||
) -> dict[str, int | list[dict[str, str | int]]]:
|
||||
top = list(family_keys[:k])
|
||||
counts: dict[str, int] = {}
|
||||
for key in top:
|
||||
counts[key] = counts.get(key, 0) + 1
|
||||
duplicate_groups = [
|
||||
{"family_key": key, "count": count}
|
||||
for key, count in sorted(counts.items(), key=lambda item: -item[1])
|
||||
if count > 1
|
||||
]
|
||||
return {
|
||||
"total_in_top_k": len(top),
|
||||
"unique_families": len(counts),
|
||||
"duplicate_entries": len(top) - len(counts),
|
||||
"duplicate_groups": duplicate_groups,
|
||||
}
|
||||
|
||||
|
||||
def unique_family_precision_at_k(
|
||||
ranked_ids: Sequence[str],
|
||||
family_keys: Sequence[str],
|
||||
relevant_ids: Iterable[str],
|
||||
k: int,
|
||||
) -> float:
|
||||
"""Precision@k counting at most one relevant hit per patent family in top-k."""
|
||||
if k <= 0:
|
||||
return 0.0
|
||||
relevant = {normalize_patent_id(pid) for pid in relevant_ids}
|
||||
if not relevant:
|
||||
return 0.0
|
||||
|
||||
credited_families: set[str] = set()
|
||||
hits = 0
|
||||
for patent_id, family_key in zip(ranked_ids[:k], family_keys[:k]):
|
||||
if family_key in credited_families:
|
||||
continue
|
||||
credited_families.add(family_key)
|
||||
if normalize_patent_id(patent_id) in relevant:
|
||||
hits += 1
|
||||
return hits / k
|
||||
|
||||
|
||||
def dedupe_ranked_ids_by_family(
|
||||
ranked_ids: Sequence[str],
|
||||
family_keys: Sequence[str],
|
||||
) -> list[str]:
|
||||
seen: set[str] = set()
|
||||
deduped: list[str] = []
|
||||
for patent_id, family_key in zip(ranked_ids, family_keys):
|
||||
if family_key in seen:
|
||||
continue
|
||||
seen.add(family_key)
|
||||
deduped.append(normalize_patent_id(patent_id))
|
||||
return deduped
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,13 @@ from pydantic import BaseModel, Field
|
||||
from inse.patents.common.model import PatentEntry
|
||||
|
||||
KeywordPatentLevel = Literal["broad", "coarse", "fine", "custom"]
|
||||
KeywordPatentMappingStatus = Literal[
|
||||
"mapped",
|
||||
"uncertain",
|
||||
"no_mapping",
|
||||
"no_patents_found",
|
||||
"search_error",
|
||||
]
|
||||
|
||||
|
||||
class KeywordPatentSearchItem(BaseModel):
|
||||
@@ -42,16 +49,86 @@ class PatentsByKeywordsRequest(BaseModel):
|
||||
)
|
||||
|
||||
|
||||
class KeywordEvidence(BaseModel):
|
||||
"""Traceable title/abstract evidence for keyword text retrieval."""
|
||||
|
||||
phrase_in_title: bool = False
|
||||
phrase_in_abstract: bool = False
|
||||
full_token_match: bool = False
|
||||
partial_token_match: bool = False
|
||||
word_match_score: float = 0.0
|
||||
matched_phrases: list[str] = Field(default_factory=list)
|
||||
matched_words: list[str] = Field(default_factory=list)
|
||||
text_match_kind: str = Field(
|
||||
default="none",
|
||||
description=(
|
||||
"phrase_title | phrase_abstract | full_token | partial_token | none"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class KeywordPatentMatch(BaseModel):
|
||||
patent: PatentEntry
|
||||
match_score: float = Field(description="Combined match quality score.")
|
||||
ipc_score: float = Field(description="IPC/CPC classification match score.")
|
||||
topic_score: float = Field(description="OpenAlex topic overlap score (0 or 1).")
|
||||
topic_score: float = Field(
|
||||
description=(
|
||||
"Graded OpenAlex topic overlap: 1.0 topic_id, 0.7 subfield, "
|
||||
"0.3 compatible field, 0.0 none."
|
||||
),
|
||||
)
|
||||
text_score: float = Field(description="Title/abstract keyword overlap score.")
|
||||
matched_keywords: list[str] = Field(default_factory=list)
|
||||
matched_ipc_symbols: list[str] = Field(default_factory=list)
|
||||
text_retrieval: bool = Field(
|
||||
default=False,
|
||||
description=(
|
||||
"True when the patent was retrieved via title/abstract keyword search "
|
||||
"because IPC mapping was uncertain, missing, or yielded no hits."
|
||||
),
|
||||
)
|
||||
keyword_evidence: KeywordEvidence | None = Field(
|
||||
default=None,
|
||||
description="Structured text evidence when text_retrieval is true.",
|
||||
)
|
||||
topic_match_kind: str | None = Field(
|
||||
default=None,
|
||||
description="topic_id | subfield | compatible_field | none",
|
||||
)
|
||||
|
||||
|
||||
class KeywordPatentSearchDiagnostics(BaseModel):
|
||||
"""Pipeline counters for evaluation (no effect on ranking thresholds)."""
|
||||
|
||||
search_path: str = Field(
|
||||
description="ipc | text | none",
|
||||
)
|
||||
es_query_size_per_index: int = 0
|
||||
raw_patents_after_dedupe: int = 0
|
||||
filtered_by_ipc: int = 0
|
||||
filtered_by_relevance_gate: int = 0
|
||||
filtered_by_min_score: int = 0
|
||||
passed_relevance_gate: int = 0
|
||||
scored_before_cap: int = 0
|
||||
returned: int = 0
|
||||
max_patents_cap: int = 0
|
||||
hit_return_cap: bool = False
|
||||
ipc_cluster_selections: list[dict] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PatentsByKeywordsResponse(BaseModel):
|
||||
patent_count: int
|
||||
patents: list[KeywordPatentMatch]
|
||||
mapping_status: KeywordPatentMappingStatus = Field(
|
||||
description=(
|
||||
"IPC mapping outcome: mapped (IPC used), uncertain (fragmented evidence; "
|
||||
"may include text-retrieved patents), no_mapping (no usable IPC evidence; "
|
||||
"may include text-retrieved patents), no_patents_found (neither IPC nor "
|
||||
"keyword text search produced relevant patents), or search_error (technical "
|
||||
"failure talking to the search backend)."
|
||||
),
|
||||
)
|
||||
diagnostics: KeywordPatentSearchDiagnostics | None = Field(
|
||||
default=None,
|
||||
description="Optional search-pipeline counters for evaluation/debugging.",
|
||||
)
|
||||
|
||||
@@ -24,10 +24,11 @@ logger = logging.getLogger(__name__)
|
||||
_LEVEL_WEIGHTS = {
|
||||
"subgroup": 1.0,
|
||||
"group": 0.92,
|
||||
"subclass": 0.85,
|
||||
"class": 0.75,
|
||||
"section": 0.6,
|
||||
# Subclass is allowed but clearly weaker than group/subgroup.
|
||||
"subclass": 0.70,
|
||||
# Section/class are excluded from keyword→patent retrieval.
|
||||
}
|
||||
_EXCLUDED_IPC_LEVELS = frozenset({"section", "class"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -37,6 +38,7 @@ class IpcCodeMatch:
|
||||
match_score: float
|
||||
source_keyword: str
|
||||
match_type: str
|
||||
topic_id: str | None = None
|
||||
|
||||
|
||||
def _keyword_variants(keyword: str) -> list[str]:
|
||||
@@ -83,7 +85,11 @@ def _weighted_score(
|
||||
relevance_score 0.0 while still mapping to valid OpenAlex topics.
|
||||
"""
|
||||
_ = relevance_score
|
||||
level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7)
|
||||
if ipc_level in _EXCLUDED_IPC_LEVELS:
|
||||
return 0.0
|
||||
level_weight = _LEVEL_WEIGHTS.get(ipc_level)
|
||||
if level_weight is None:
|
||||
return 0.0
|
||||
return round(base_score * level_weight, 4)
|
||||
|
||||
|
||||
@@ -138,15 +144,46 @@ def clear_reverse_lookup_caches() -> None:
|
||||
_build_json_inverted_index.cache_clear()
|
||||
|
||||
|
||||
def _item_topic_id(item: KeywordPatentSearchItem) -> str | None:
|
||||
variants = _topic_id_variants_for_item(item)
|
||||
if not variants:
|
||||
return None
|
||||
for variant in variants:
|
||||
short = normalize_openalex_id(variant)
|
||||
if short:
|
||||
return short
|
||||
return variants[0]
|
||||
|
||||
|
||||
def _topic_group_key(topic_id: str | None, source_keyword: str = "") -> str:
|
||||
"""Stable topic bucket for evidence; must stay aligned with cluster grouping."""
|
||||
if topic_id:
|
||||
short = normalize_openalex_id(topic_id)
|
||||
return short or topic_id.strip()
|
||||
keyword = (source_keyword or "").strip()
|
||||
return f"keyword:{keyword.casefold() or 'unknown'}"
|
||||
|
||||
|
||||
def _merge_ipc_match(
|
||||
matches: dict[tuple[str, str], IpcCodeMatch],
|
||||
matches: dict[tuple[str, str, str], IpcCodeMatch],
|
||||
level: str,
|
||||
symbol: str,
|
||||
score: float,
|
||||
source_keyword: str,
|
||||
match_type: str,
|
||||
topic_id: str | None = None,
|
||||
) -> None:
|
||||
key = (level, normalize_symbol(symbol))
|
||||
"""Merge by topic × level × symbol so evidence for distinct topics is preserved.
|
||||
|
||||
Global symbol collapse happens only after per-topic cluster selection.
|
||||
"""
|
||||
if level in _EXCLUDED_IPC_LEVELS or score <= 0:
|
||||
return
|
||||
key = (
|
||||
_topic_group_key(topic_id, source_keyword),
|
||||
level,
|
||||
normalize_symbol(symbol),
|
||||
)
|
||||
existing = matches.get(key)
|
||||
if existing is None or score > existing.match_score:
|
||||
matches[key] = IpcCodeMatch(
|
||||
@@ -155,6 +192,7 @@ def _merge_ipc_match(
|
||||
match_score=score,
|
||||
source_keyword=source_keyword,
|
||||
match_type=match_type,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -166,10 +204,13 @@ def _matches_from_doc(
|
||||
ipc_symbol = normalize_symbol(str(doc.get("ipc_symbol") or ""))
|
||||
if not ipc_level or not ipc_symbol:
|
||||
return []
|
||||
if ipc_level in _EXCLUDED_IPC_LEVELS:
|
||||
return []
|
||||
|
||||
keyword_variants = set(_keyword_variants(item.keyword))
|
||||
topic_variants = set(_topic_id_variants_for_item(item))
|
||||
topic_name = (item.topic_display_name or "").strip().casefold()
|
||||
topic_id = _item_topic_id(item)
|
||||
found: list[IpcCodeMatch] = []
|
||||
|
||||
for match in doc.get("keyword_matches") or []:
|
||||
@@ -183,6 +224,8 @@ def _matches_from_doc(
|
||||
float(match.get("match_score") or 0.0),
|
||||
item.relevance_score,
|
||||
)
|
||||
if score <= 0:
|
||||
break
|
||||
found.append(
|
||||
IpcCodeMatch(
|
||||
ipc_level=ipc_level,
|
||||
@@ -190,6 +233,7 @@ def _matches_from_doc(
|
||||
match_score=score,
|
||||
source_keyword=item.keyword,
|
||||
match_type="keyword",
|
||||
topic_id=topic_id,
|
||||
)
|
||||
)
|
||||
break
|
||||
@@ -206,6 +250,8 @@ def _matches_from_doc(
|
||||
float(match.get("match_score") or 0.0),
|
||||
item.relevance_score,
|
||||
)
|
||||
if score <= 0:
|
||||
break
|
||||
found.append(
|
||||
IpcCodeMatch(
|
||||
ipc_level=ipc_level,
|
||||
@@ -213,6 +259,7 @@ def _matches_from_doc(
|
||||
match_score=score,
|
||||
source_keyword=item.keyword,
|
||||
match_type="topic",
|
||||
topic_id=topic_id,
|
||||
)
|
||||
)
|
||||
break
|
||||
@@ -222,15 +269,22 @@ def _matches_from_doc(
|
||||
|
||||
def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
|
||||
by_keyword, by_topic = _build_json_inverted_index()
|
||||
merged: dict[tuple[str, str], IpcCodeMatch] = {}
|
||||
merged: dict[tuple[str, str, str], IpcCodeMatch] = {}
|
||||
|
||||
for item in items:
|
||||
topic_id = _item_topic_id(item)
|
||||
for level, symbol, base_score, source_keyword, match_type in by_keyword.get(
|
||||
item.keyword.strip().casefold(), []
|
||||
):
|
||||
score = _weighted_score(level, base_score, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged, level, symbol, score, item.keyword, match_type
|
||||
merged,
|
||||
level,
|
||||
symbol,
|
||||
score,
|
||||
item.keyword,
|
||||
match_type,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
for variant in _topic_id_variants_for_item(item):
|
||||
@@ -239,14 +293,20 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
|
||||
):
|
||||
score = _weighted_score(level, base_score, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged, level, symbol, score, item.keyword, match_type
|
||||
merged,
|
||||
level,
|
||||
symbol,
|
||||
score,
|
||||
item.keyword,
|
||||
match_type,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
|
||||
|
||||
|
||||
def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
|
||||
merged: dict[tuple[str, str], IpcCodeMatch] = {}
|
||||
merged: dict[tuple[str, str, str], IpcCodeMatch] = {}
|
||||
for match in matches:
|
||||
_merge_ipc_match(
|
||||
merged,
|
||||
@@ -255,6 +315,7 @@ def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
|
||||
match.match_score,
|
||||
match.source_keyword,
|
||||
match.match_type,
|
||||
topic_id=match.topic_id,
|
||||
)
|
||||
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
|
||||
|
||||
@@ -336,8 +397,13 @@ class KeywordIpcReverseLookup:
|
||||
self,
|
||||
items: list[KeywordPatentSearchItem],
|
||||
*,
|
||||
max_codes: int = 40,
|
||||
max_codes: int | None = 200,
|
||||
) -> list[IpcCodeMatch]:
|
||||
"""Return mapping candidates for downstream cluster selection.
|
||||
|
||||
``max_codes`` caps raw candidates *after* dedupe. Pass a high value (or
|
||||
``None``) so relative cluster mass is not distorted by early truncation.
|
||||
"""
|
||||
if not items:
|
||||
return []
|
||||
|
||||
@@ -360,6 +426,8 @@ class KeywordIpcReverseLookup:
|
||||
)
|
||||
|
||||
matches = _dedupe_ipc_matches(matches)
|
||||
if max_codes is None:
|
||||
return matches
|
||||
return matches[:max_codes]
|
||||
|
||||
async def _lookup_via_elasticsearch(
|
||||
@@ -394,7 +462,7 @@ class KeywordIpcReverseLookup:
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
merged: dict[tuple[str, str], IpcCodeMatch] = {}
|
||||
merged: dict[tuple[str, str, str], IpcCodeMatch] = {}
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
doc = hit.get("_source", {})
|
||||
for item in items:
|
||||
@@ -406,6 +474,7 @@ class KeywordIpcReverseLookup:
|
||||
match.match_score,
|
||||
match.source_keyword,
|
||||
match.match_type,
|
||||
topic_id=match.topic_id,
|
||||
)
|
||||
|
||||
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
|
||||
from inse.patents.ipc_lookup import parse_ipc_symbol
|
||||
from inse.patents.ipc_lookup import display_ipc_symbol, parse_ipc_symbol
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
|
||||
|
||||
_PATENT_SOURCE_FIELDS = [
|
||||
@@ -43,60 +43,201 @@ _USPTO_SOURCE_FIELDS = [
|
||||
]
|
||||
|
||||
_MIN_MATCH_TERM_LEN = 4
|
||||
_MIN_TEXT_PHRASE_LEN = 3
|
||||
|
||||
# Prefer concrete group/subgroup hits over broad subclass prefixes.
|
||||
_BOOST_SUBGROUP = 4.0
|
||||
_BOOST_MAIN_GROUP = 2.5
|
||||
_BOOST_SUBCLASS = 1.0
|
||||
|
||||
# Text search: prefer exact phrases in title over abstract / loose match.
|
||||
_BOOST_TEXT_PHRASE_TITLE = 5.0
|
||||
_BOOST_TEXT_PHRASE_ABSTRACT = 3.0
|
||||
_BOOST_TEXT_MATCH_TITLE = 1.5
|
||||
_BOOST_TEXT_MATCH_ABSTRACT = 1.0
|
||||
|
||||
|
||||
def _search_terms_for_symbol(symbol: str) -> list[str]:
|
||||
"""Derive EPO/USPTO `match` terms from an IPC/CPC symbol.
|
||||
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
|
||||
cleaned = term.strip()
|
||||
if len(cleaned) < _MIN_MATCH_TERM_LEN:
|
||||
return
|
||||
weights[cleaned] = max(weights.get(cleaned, 0.0), boost)
|
||||
|
||||
|
||||
def _weighted_search_terms_for_symbol(symbol: str) -> dict[str, float]:
|
||||
"""Derive EPO/USPTO `match` terms with specificity boosts.
|
||||
|
||||
Patent indices store IPC values like ``B60L 53/14 20060101AFI...``.
|
||||
Wildcard/prefix on normalized symbols (``B60L*``) does not match; ``match``
|
||||
on subclass codes (``B60L``) does.
|
||||
on subclass / group tokens does. Concrete group/subgroup terms are boosted
|
||||
above broad subclass prefixes.
|
||||
"""
|
||||
normalized = normalize_symbol(symbol)
|
||||
if not normalized:
|
||||
return []
|
||||
|
||||
terms: list[str] = []
|
||||
subclass = infer_subclass(normalized)
|
||||
if subclass and len(subclass) >= _MIN_MATCH_TERM_LEN:
|
||||
terms.append(subclass)
|
||||
return {}
|
||||
|
||||
weights: dict[str, float] = {}
|
||||
keys = parse_ipc_symbol(normalized)
|
||||
subclass = infer_subclass(normalized)
|
||||
if not subclass and keys is not None and keys.subclass:
|
||||
subclass = normalize_symbol(keys.subclass)
|
||||
|
||||
def add_symbol_forms(value: str | None, boost: float) -> None:
|
||||
if not value:
|
||||
return
|
||||
norm = normalize_symbol(value)
|
||||
if not norm:
|
||||
return
|
||||
_add_term_boost(weights, norm, boost)
|
||||
display = display_ipc_symbol(norm)
|
||||
if display and display != norm:
|
||||
_add_term_boost(weights, display, boost)
|
||||
|
||||
if keys is not None:
|
||||
if keys.subclass and len(keys.subclass) >= _MIN_MATCH_TERM_LEN:
|
||||
terms.append(normalize_symbol(keys.subclass))
|
||||
if keys.main_group and len(normalize_symbol(keys.main_group)) >= _MIN_MATCH_TERM_LEN:
|
||||
terms.append(normalize_symbol(keys.main_group))
|
||||
if keys.subgroup:
|
||||
add_symbol_forms(keys.subgroup, _BOOST_SUBGROUP)
|
||||
if keys.main_group:
|
||||
main_group = normalize_symbol(keys.main_group)
|
||||
# Short subgroup digits are folded into main_group by the parser
|
||||
# (e.g. C07C243/08) — treat those leaf symbols as subgroup-level.
|
||||
if keys.subgroup is None and "/" in main_group:
|
||||
add_symbol_forms(main_group, _BOOST_SUBGROUP)
|
||||
else:
|
||||
add_symbol_forms(main_group, _BOOST_MAIN_GROUP)
|
||||
|
||||
if len(normalized) >= _MIN_MATCH_TERM_LEN:
|
||||
prefix = normalized[:_MIN_MATCH_TERM_LEN]
|
||||
if prefix not in terms:
|
||||
terms.append(prefix)
|
||||
if subclass:
|
||||
add_symbol_forms(subclass, _BOOST_SUBCLASS)
|
||||
elif len(normalized) >= _MIN_MATCH_TERM_LEN:
|
||||
_add_term_boost(weights, normalized[:_MIN_MATCH_TERM_LEN], _BOOST_SUBCLASS)
|
||||
|
||||
return list(dict.fromkeys(term for term in terms if len(term) >= _MIN_MATCH_TERM_LEN))
|
||||
return weights
|
||||
|
||||
|
||||
def _ipc_match_clauses(field: str, terms: list[str]) -> list[dict[str, Any]]:
|
||||
def _search_terms_for_symbol(symbol: str) -> list[str]:
|
||||
"""Derive EPO/USPTO `match` terms from an IPC/CPC symbol (boost order)."""
|
||||
weights = _weighted_search_terms_for_symbol(symbol)
|
||||
return [
|
||||
term
|
||||
for term, _boost in sorted(
|
||||
weights.items(),
|
||||
key=lambda item: (-item[1], -len(item[0]), item[0]),
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _merge_term_boosts(symbols: list[str]) -> dict[str, float]:
|
||||
merged: dict[str, float] = {}
|
||||
for symbol in symbols:
|
||||
for term, boost in _weighted_search_terms_for_symbol(symbol).items():
|
||||
merged[term] = max(merged.get(term, 0.0), boost)
|
||||
return merged
|
||||
|
||||
|
||||
def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[str, Any]]:
|
||||
clauses: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for term in terms:
|
||||
for term, boost in sorted(
|
||||
term_boosts.items(),
|
||||
key=lambda item: (-item[1], -len(item[0]), item[0]),
|
||||
):
|
||||
if len(term) < _MIN_MATCH_TERM_LEN:
|
||||
continue
|
||||
key = (field, term)
|
||||
clauses.append(
|
||||
{
|
||||
"match": {
|
||||
field: {
|
||||
"query": term,
|
||||
"boost": boost,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
return clauses
|
||||
|
||||
|
||||
def _normalize_text_phrases(phrases: list[str]) -> list[str]:
|
||||
cleaned: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for phrase in phrases:
|
||||
value = " ".join((phrase or "").strip().split())
|
||||
if len(value) < _MIN_TEXT_PHRASE_LEN:
|
||||
continue
|
||||
key = value.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
clauses.append({"match": {field: term}})
|
||||
cleaned.append(value)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _text_match_clauses(
|
||||
phrases: list[str],
|
||||
*,
|
||||
title_fields: tuple[str, ...],
|
||||
abstract_field: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Build title/abstract should-clauses with phrase boosts over loose match."""
|
||||
clauses: list[dict[str, Any]] = []
|
||||
for phrase in _normalize_text_phrases(phrases):
|
||||
for field in title_fields:
|
||||
clauses.append(
|
||||
{
|
||||
"match_phrase": {
|
||||
field: {
|
||||
"query": phrase,
|
||||
"boost": _BOOST_TEXT_PHRASE_TITLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
clauses.append(
|
||||
{
|
||||
"match": {
|
||||
field: {
|
||||
"query": phrase,
|
||||
"operator": "and",
|
||||
"boost": _BOOST_TEXT_MATCH_TITLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
clauses.append(
|
||||
{
|
||||
"match_phrase": {
|
||||
abstract_field: {
|
||||
"query": phrase,
|
||||
"boost": _BOOST_TEXT_PHRASE_ABSTRACT,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
clauses.append(
|
||||
{
|
||||
"match": {
|
||||
abstract_field: {
|
||||
"query": phrase,
|
||||
"operator": "and",
|
||||
"boost": _BOOST_TEXT_MATCH_ABSTRACT,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
return clauses
|
||||
|
||||
|
||||
class IpcPatentSearchQueries:
|
||||
def epo_query_by_ipc_terms(
|
||||
self,
|
||||
terms: list[str],
|
||||
terms: list[str] | dict[str, float],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
should = _ipc_match_clauses("ipc", terms) + _ipc_match_clauses("cpc", terms)
|
||||
term_boosts = (
|
||||
terms
|
||||
if isinstance(terms, dict)
|
||||
else {term: _BOOST_SUBCLASS for term in terms}
|
||||
)
|
||||
should = _ipc_match_clauses("ipc", term_boosts) + _ipc_match_clauses(
|
||||
"cpc", term_boosts
|
||||
)
|
||||
query: dict[str, Any] = (
|
||||
{"match_none": {}}
|
||||
if not should
|
||||
@@ -106,8 +247,8 @@ class IpcPatentSearchQueries:
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": _PATENT_SOURCE_FIELDS,
|
||||
"query": query,
|
||||
@@ -115,10 +256,17 @@ class IpcPatentSearchQueries:
|
||||
|
||||
def uspto_query_by_ipc_terms(
|
||||
self,
|
||||
terms: list[str],
|
||||
terms: list[str] | dict[str, float],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
should = _ipc_match_clauses("ipcr", terms) + _ipc_match_clauses("cpc", terms)
|
||||
term_boosts = (
|
||||
terms
|
||||
if isinstance(terms, dict)
|
||||
else {term: _BOOST_SUBCLASS for term in terms}
|
||||
)
|
||||
should = _ipc_match_clauses("ipcr", term_boosts) + _ipc_match_clauses(
|
||||
"cpc", term_boosts
|
||||
)
|
||||
query: dict[str, Any] = (
|
||||
{"match_none": {}}
|
||||
if not should
|
||||
@@ -128,8 +276,8 @@ class IpcPatentSearchQueries:
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": _USPTO_SOURCE_FIELDS,
|
||||
"query": query,
|
||||
@@ -140,27 +288,63 @@ class IpcPatentSearchQueries:
|
||||
symbols: list[str],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
terms: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for symbol in symbols:
|
||||
for term in _search_terms_for_symbol(symbol):
|
||||
if term in seen:
|
||||
continue
|
||||
seen.add(term)
|
||||
terms.append(term)
|
||||
return self.epo_query_by_ipc_terms(terms, size=size)
|
||||
return self.epo_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
|
||||
|
||||
def uspto_query_by_ipc_symbols(
|
||||
self,
|
||||
symbols: list[str],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
terms: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for symbol in symbols:
|
||||
for term in _search_terms_for_symbol(symbol):
|
||||
if term in seen:
|
||||
continue
|
||||
seen.add(term)
|
||||
terms.append(term)
|
||||
return self.uspto_query_by_ipc_terms(terms, size=size)
|
||||
return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
|
||||
|
||||
def epo_query_by_text_phrases(
|
||||
self,
|
||||
phrases: list[str],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
should = _text_match_clauses(
|
||||
phrases,
|
||||
title_fields=("title_en", "title_de"),
|
||||
abstract_field="abstract",
|
||||
)
|
||||
query: dict[str, Any] = (
|
||||
{"match_none": {}}
|
||||
if not should
|
||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
||||
)
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
"_source": _PATENT_SOURCE_FIELDS,
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_query_by_text_phrases(
|
||||
self,
|
||||
phrases: list[str],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
should = _text_match_clauses(
|
||||
phrases,
|
||||
title_fields=("title",),
|
||||
abstract_field="abstract",
|
||||
)
|
||||
query: dict[str, Any] = (
|
||||
{"match_none": {}}
|
||||
if not should
|
||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
||||
)
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
"_source": _USPTO_SOURCE_FIELDS,
|
||||
"query": query,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Unit tests for keyword → patent evaluation metrics."""
|
||||
from __future__ import annotations
|
||||
|
||||
from inse.patents.keywords.eval_metrics import (
|
||||
analyze_family_duplicates_in_top_k,
|
||||
average_precision,
|
||||
ipc_prefix_hit_rate,
|
||||
mrr,
|
||||
ndcg_at_k,
|
||||
precision_at_k,
|
||||
recall_at_k,
|
||||
unique_family_precision_at_k,
|
||||
)
|
||||
|
||||
|
||||
def test_precision_at_k() -> None:
|
||||
ranked = ["EP1", "EP2", "EP3", "EP4"]
|
||||
relevant = ["EP2", "EP9"]
|
||||
assert precision_at_k(ranked, relevant, 2) == 0.5
|
||||
assert precision_at_k(ranked, relevant, 4) == 0.25
|
||||
|
||||
|
||||
def test_recall_at_k() -> None:
|
||||
ranked = ["EP1", "EP2", "EP3"]
|
||||
relevant = ["EP2", "EP9"]
|
||||
assert recall_at_k(ranked, relevant, 2) == 0.5
|
||||
assert recall_at_k(ranked, relevant, 3) == 0.5
|
||||
|
||||
|
||||
def test_average_precision() -> None:
|
||||
ranked = ["EP1", "EP2", "EP3"]
|
||||
relevant = ["EP2", "EP3"]
|
||||
# hit@2 → 1/2, hit@3 → 2/3 → AP = (0.5 + 0.666...) / 2
|
||||
assert abs(average_precision(ranked, relevant) - ((0.5 + 2 / 3) / 2)) < 1e-9
|
||||
|
||||
|
||||
def test_ndcg_at_k() -> None:
|
||||
ranked = ["EP1", "EP2", "EP3"]
|
||||
grades = {"EP2": 2.0, "EP3": 1.0}
|
||||
score = ndcg_at_k(ranked, grades, 3)
|
||||
assert 0.0 < score < 1.0
|
||||
|
||||
|
||||
def test_mrr() -> None:
|
||||
assert mrr(["EP1", "EP2", "EP3"], ["EP3"]) == 1 / 3
|
||||
assert mrr(["EP1", "EP2"], ["EP9"]) == 0.0
|
||||
|
||||
|
||||
def test_ipc_prefix_hit_rate() -> None:
|
||||
ipc_lists = [
|
||||
["C07C243/08"],
|
||||
["H01L21/02"],
|
||||
["C07D401/00", "A61K31/00"],
|
||||
]
|
||||
assert ipc_prefix_hit_rate(ipc_lists, ["C07"], k=3) == 2 / 3
|
||||
assert ipc_prefix_hit_rate(ipc_lists, ["C07"], k=1) == 1.0
|
||||
|
||||
|
||||
def test_unique_family_precision_at_k() -> None:
|
||||
ranked = ["EP1", "EP2", "EP3", "EP4"]
|
||||
family_keys = ["app:1", "app:1", "app:2", "app:3"]
|
||||
relevant = ["EP1", "EP2", "EP4"]
|
||||
# top-3: EP1 relevant (family app:1), EP2 dup family skip, EP3 miss -> 1/3
|
||||
assert unique_family_precision_at_k(ranked, family_keys, relevant, 3) == 1 / 3
|
||||
# top-4: EP1 hit, EP2 skip, EP3 miss, EP4 hit -> 2/4
|
||||
assert unique_family_precision_at_k(ranked, family_keys, relevant, 4) == 0.5
|
||||
|
||||
|
||||
def test_analyze_family_duplicates_in_top_k() -> None:
|
||||
keys = ["app:1", "app:1", "app:2", "title:foo"]
|
||||
stats = analyze_family_duplicates_in_top_k(keys, 4)
|
||||
assert stats["unique_families"] == 3
|
||||
assert stats["duplicate_entries"] == 1
|
||||
assert stats["duplicate_groups"][0]["count"] == 2
|
||||
@@ -4,32 +4,49 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
|
||||
from inse.patents.common import model
|
||||
from inse.patents.keywords.logic import (
|
||||
TopicEvidence,
|
||||
_compute_final_score,
|
||||
_compute_topic_evidence,
|
||||
_collect_keyword_text_evidence,
|
||||
_exact_topic_or_subfield_match,
|
||||
_keyword_text_passes_relevance_gate,
|
||||
_keyword_text_score,
|
||||
_filter_keywords_for_patent_search,
|
||||
_ipc_hierarchy_quality,
|
||||
_keyword_is_patent_searchable,
|
||||
_limit_matches_per_keyword,
|
||||
_patent_passes_relevance_gate,
|
||||
_patent_search_terms,
|
||||
_score_ipc_match,
|
||||
_score_patent,
|
||||
_select_dominant_clusters,
|
||||
_aggregate_subclass_clusters,
|
||||
_term_from_ipc_match,
|
||||
_text_overlap_score,
|
||||
_text_search_terms,
|
||||
_topic_passes_relevance_gate,
|
||||
_topics_overlap_keywords,
|
||||
_usable_ipc_matches,
|
||||
get_patents_by_keywords,
|
||||
select_ipc_matches_by_cluster_mass,
|
||||
)
|
||||
from inse.patents.keywords.reverse_lookup import (
|
||||
IpcCodeMatch,
|
||||
_dedupe_ipc_matches,
|
||||
_json_lookup,
|
||||
_weighted_score,
|
||||
clear_reverse_lookup_caches,
|
||||
)
|
||||
from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
|
||||
from inse.patents.keywords.search_queries import IpcPatentSearchQueries, _search_terms_for_symbol
|
||||
from inse.patents.keywords.search_queries import (
|
||||
IpcPatentSearchQueries,
|
||||
_search_terms_for_symbol,
|
||||
_weighted_search_terms_for_symbol,
|
||||
)
|
||||
|
||||
|
||||
def test_ipc_hierarchy_quality_exact_match() -> None:
|
||||
@@ -74,7 +91,166 @@ def test_patent_search_terms_deduplicates_chemistry_subclasses() -> None:
|
||||
IpcCodeMatch("subgroup", "B01J2219/00709", 0.8679, "Organische Chemie", "keyword"),
|
||||
]
|
||||
terms = _patent_search_terms(ipc_matches)
|
||||
assert terms == ["C25B", "C07C", "C09B", "D06L", "C02F", "B01J"]
|
||||
assert "C25B3/03" in terms
|
||||
assert "C07C243/08" in terms
|
||||
assert "C09B68/48" in terms
|
||||
assert terms.count("C09B68/48") == 1
|
||||
|
||||
|
||||
def test_usable_ipc_matches_excludes_section_and_class() -> None:
|
||||
matches = [
|
||||
IpcCodeMatch("section", "C", 0.99, "Topic", "topic"),
|
||||
IpcCodeMatch("class", "C07", 0.95, "Topic", "topic"),
|
||||
IpcCodeMatch("subclass", "C07C", 0.80, "Topic", "topic"),
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.88, "Topic", "topic"),
|
||||
]
|
||||
usable = _usable_ipc_matches(matches)
|
||||
levels = {match.ipc_level for match in usable}
|
||||
assert "section" not in levels
|
||||
assert "class" not in levels
|
||||
assert levels <= {"subclass", "group", "subgroup"}
|
||||
|
||||
|
||||
def test_cluster_mass_prefers_dense_subclass_over_single_outlier() -> None:
|
||||
"""Many related subgroups in one subclass beat one high-score foreign outlier."""
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "G01Q60/36", 0.95, "Robotics", "topic"),
|
||||
IpcCodeMatch("subgroup", "B25J9/16", 0.78, "Robotics", "topic"),
|
||||
IpcCodeMatch("subgroup", "B25J13/08", 0.76, "Robotics", "topic"),
|
||||
IpcCodeMatch("subgroup", "B25J19/02", 0.74, "Robotics", "topic"),
|
||||
IpcCodeMatch("group", "B25J9", 0.72, "Robotics", "topic"),
|
||||
]
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(matches)
|
||||
by_subclass = {selection.subclass: selection for selection in selections}
|
||||
assert "B25J" in by_subclass
|
||||
g01q = by_subclass.get("G01Q")
|
||||
assert g01q is None or by_subclass["B25J"].cluster_mass > g01q.cluster_mass
|
||||
assert by_subclass["B25J"].relative_mass == max(s.relative_mass for s in selections)
|
||||
assert selected
|
||||
assert all(match.match_type != "domain_preference" for match in selected)
|
||||
|
||||
|
||||
def test_cluster_selection_works_for_unseen_battery_topic() -> None:
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "H01M10/052", 0.88, "Battery technology", "topic", "TBAT"),
|
||||
IpcCodeMatch("subgroup", "H01M4/58", 0.84, "Battery technology", "topic", "TBAT"),
|
||||
IpcCodeMatch("subgroup", "H01M10/44", 0.80, "Battery technology", "topic", "TBAT"),
|
||||
IpcCodeMatch("subgroup", "G01R31/36", 0.79, "Battery technology", "topic", "TBAT"),
|
||||
]
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(matches)
|
||||
assert selections
|
||||
assert {s.topic_key for s in selections} == {"TBAT"}
|
||||
assert all(s.cluster_mass > 0 for s in selections)
|
||||
assert all(s.reason for s in selections)
|
||||
terms = _patent_search_terms(selected)
|
||||
assert terms
|
||||
assert any(term.startswith("H01M") for term in terms)
|
||||
|
||||
|
||||
def test_cluster_selection_works_for_unseen_quantum_topic() -> None:
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "G06N10/00", 0.86, "Quantum computing", "topic", "TQ"),
|
||||
IpcCodeMatch("subgroup", "G06N10/40", 0.83, "Quantum computing", "topic", "TQ"),
|
||||
IpcCodeMatch("subclass", "G06N", 0.70, "Quantum computing", "topic", "TQ"),
|
||||
IpcCodeMatch("subgroup", "H01L39/22", 0.75, "Quantum computing", "topic", "TQ"),
|
||||
]
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(matches)
|
||||
assert selections
|
||||
g06n = next(s for s in selections if s.subclass == "G06N")
|
||||
assert g06n.relative_mass > 0
|
||||
assert all(m.ipc_level != "class" for m in selected)
|
||||
assert "domain_preference" not in {m.match_type for m in selected}
|
||||
|
||||
|
||||
def test_search_terms_prefer_specific_subgroup_symbol() -> None:
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "G06N3/08", 0.84, "Neural nets", "topic", "TNN"),
|
||||
]
|
||||
terms = _patent_search_terms(matches)
|
||||
assert terms[0] == "G06N3/08"
|
||||
assert "G06N" in terms
|
||||
|
||||
|
||||
def test_no_synthetic_matches_when_mapping_has_single_family() -> None:
|
||||
"""Sole concentrated family is accepted; nothing else is invented."""
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "C12Q1/68", 0.92, "Unknown Topic X", "topic", "TX"),
|
||||
]
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(matches)
|
||||
assert len(selections) == 1
|
||||
assert selections[0].subclass == "C12Q"
|
||||
assert selections[0].reason == "sole_cluster_evidence"
|
||||
assert selected[0].match_type == "topic"
|
||||
terms = _patent_search_terms(selected)
|
||||
assert terms[0] == "C12Q1/68"
|
||||
|
||||
|
||||
def test_fragmented_weak_clusters_yield_no_ipc_selection() -> None:
|
||||
"""Many similarly weak subclasses must not force a fragmented pick."""
|
||||
matches = [
|
||||
IpcCodeMatch(
|
||||
"subgroup",
|
||||
f"A{index:02d}B1/00",
|
||||
0.70,
|
||||
"Flat Topic",
|
||||
"topic",
|
||||
"TFLAT",
|
||||
)
|
||||
for index in range(1, 16)
|
||||
]
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(matches)
|
||||
assert selections == []
|
||||
assert selected == []
|
||||
assert _patent_search_terms(selected) == []
|
||||
|
||||
|
||||
def test_dedupe_preserves_same_symbol_for_distinct_topics() -> None:
|
||||
"""Identical IPC symbols for different topics must not collapse before clustering."""
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "G06N3/08", 0.80, "Neural nets", "topic", "TNN"),
|
||||
IpcCodeMatch("subgroup", "G06N3/08", 0.75, "Robotics", "topic", "TROB"),
|
||||
IpcCodeMatch("subgroup", "G06N3/08", 0.90, "Neural nets", "topic", "TNN"),
|
||||
]
|
||||
deduped = _dedupe_ipc_matches(matches)
|
||||
by_topic = {match.topic_id: match for match in deduped}
|
||||
assert set(by_topic) == {"TNN", "TROB"}
|
||||
assert by_topic["TNN"].match_score == 0.90
|
||||
assert by_topic["TROB"].match_score == 0.75
|
||||
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(deduped)
|
||||
assert {selection.topic_key for selection in selections} == {"TNN", "TROB"}
|
||||
assert len(selected) == 1
|
||||
assert selected[0].ipc_symbol == "G06N3/08"
|
||||
assert selected[0].match_score == 0.90
|
||||
|
||||
|
||||
def test_aggregate_subclass_clusters_sums_scores_without_second_level_weight() -> None:
|
||||
matches = [
|
||||
IpcCodeMatch("subgroup", "B60L50/50", 0.80, "EV", "topic", "TEV"),
|
||||
IpcCodeMatch("subgroup", "B60L53/14", 0.80, "EV", "topic", "TEV"),
|
||||
IpcCodeMatch("subclass", "B60L", 0.80, "EV", "topic", "TEV"),
|
||||
]
|
||||
clusters = _aggregate_subclass_clusters("TEV", matches)
|
||||
assert len(clusters) == 1
|
||||
assert clusters[0].subclass == "B60L"
|
||||
assert abs(clusters[0].mass - 2.4) < 1e-9
|
||||
|
||||
|
||||
def test_dominant_clusters_skip_low_mass_tail() -> None:
|
||||
clusters = _aggregate_subclass_clusters(
|
||||
"Topic",
|
||||
[
|
||||
IpcCodeMatch("subgroup", "A01B1/00", 0.90, "Topic", "topic"),
|
||||
IpcCodeMatch("subgroup", "A01B3/00", 0.88, "Topic", "topic"),
|
||||
IpcCodeMatch("subgroup", "A01B5/00", 0.86, "Topic", "topic"),
|
||||
IpcCodeMatch("subgroup", "Z99Z1/00", 0.66, "Topic", "topic"),
|
||||
],
|
||||
)
|
||||
selected = _select_dominant_clusters(clusters)
|
||||
selected_subclasses = {cluster.subclass for cluster, _reason in selected}
|
||||
assert "A01B" in selected_subclasses
|
||||
# Tiny tail cluster should not be auto-selected.
|
||||
assert "Z99Z" not in selected_subclasses
|
||||
|
||||
|
||||
def test_score_ipc_match_returns_only_best_evidence() -> None:
|
||||
@@ -148,6 +324,48 @@ def test_score_patent_uses_best_ipc_match() -> None:
|
||||
assert "G01S" in symbols
|
||||
|
||||
|
||||
def test_compute_topic_evidence_is_graded() -> None:
|
||||
topics = [
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T999",
|
||||
subfield_name="Organic Chemistry",
|
||||
field_name="Chemistry",
|
||||
)
|
||||
]
|
||||
exact = _compute_topic_evidence(
|
||||
topics,
|
||||
frozenset({"T999"}),
|
||||
frozenset({"organic chemistry"}),
|
||||
frozenset({"chemistry"}),
|
||||
)
|
||||
assert exact.match_kind == "topic_id"
|
||||
assert exact.score == 1.0
|
||||
|
||||
subfield = _compute_topic_evidence(
|
||||
topics,
|
||||
frozenset({"TOTHER"}),
|
||||
frozenset({"organic chemistry"}),
|
||||
frozenset({"chemistry"}),
|
||||
)
|
||||
assert subfield.match_kind == "subfield"
|
||||
assert subfield.score == 0.7
|
||||
|
||||
field_only = _compute_topic_evidence(
|
||||
[
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T1",
|
||||
field_name="Materials Science",
|
||||
)
|
||||
],
|
||||
frozenset({"TOTHER"}),
|
||||
frozenset({"organic chemistry"}),
|
||||
frozenset({"chemistry"}),
|
||||
)
|
||||
assert field_only.match_kind == "compatible_field"
|
||||
assert field_only.score == 0.3
|
||||
assert not _topic_passes_relevance_gate(field_only)
|
||||
|
||||
|
||||
def test_score_patent_requires_topic_overlap() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
@@ -205,7 +423,45 @@ def test_score_patent_accepts_compatible_engineering_and_computer_science() -> N
|
||||
)
|
||||
],
|
||||
)
|
||||
# Compatible field alone is only a ranking signal; text evidence lets it pass.
|
||||
assert result is not None
|
||||
score, _keywords, _symbols = result
|
||||
assert score == _compute_final_score(0.9 * 0.75, 0.3, 2 / 3)
|
||||
|
||||
|
||||
def test_score_patent_rejects_compatible_field_without_text() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP456",
|
||||
source="EPO",
|
||||
ipc=["G06N 3/08"],
|
||||
title="Unrelated apparatus",
|
||||
abstract="No topical keywords here.",
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subclass", "G06N", 0.9, "Deep Learning", "keyword"),
|
||||
]
|
||||
result = _score_patent(
|
||||
patent,
|
||||
ipc_matches,
|
||||
patent_topics=[
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T12072",
|
||||
field_name="Computer Science",
|
||||
)
|
||||
],
|
||||
keyword_topic_ids=frozenset({"T10653"}),
|
||||
keyword_subfield_names=frozenset({"control and systems engineering"}),
|
||||
keyword_soft_field_names=frozenset({"engineering"}),
|
||||
search_keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Deep Learning",
|
||||
topic_id="https://openalex.org/T10653",
|
||||
field_name="Engineering",
|
||||
relevance_score=0.9,
|
||||
)
|
||||
],
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_filter_keywords_for_patent_search_prefers_coarse_and_fine_over_broad() -> None:
|
||||
@@ -346,21 +602,20 @@ def test_topics_overlap_keywords_rejects_patents_without_topics() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_limit_matches_per_keyword() -> None:
|
||||
def test_selection_is_computed_per_topic_then_merged() -> None:
|
||||
matches = [
|
||||
IpcCodeMatch("subclass", "C07C", 0.95, "Organic Chemistry", "keyword"),
|
||||
IpcCodeMatch("group", "C07C31", 0.9, "Organic Chemistry", "keyword"),
|
||||
IpcCodeMatch("subclass", "C01B", 0.88, "Inorganic Chemistry", "keyword"),
|
||||
IpcCodeMatch("subclass", "C01C", 0.87, "Inorganic Chemistry", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.90, "Organic A", "keyword", "TORG"),
|
||||
IpcCodeMatch("subgroup", "C07C31/20", 0.88, "Organic B", "keyword", "TORG"),
|
||||
IpcCodeMatch("subgroup", "C01B3/00", 0.90, "Inorganic A", "keyword", "TINORG"),
|
||||
IpcCodeMatch("subgroup", "C01C1/00", 0.88, "Inorganic B", "keyword", "TINORG"),
|
||||
]
|
||||
limited = _limit_matches_per_keyword(matches, limit=2)
|
||||
assert len(limited) == 4
|
||||
organic = [match for match in limited if match.source_keyword == "Organic Chemistry"]
|
||||
inorganic = [match for match in limited if match.source_keyword == "Inorganic Chemistry"]
|
||||
assert len(organic) == 2
|
||||
assert len(inorganic) == 2
|
||||
assert organic[0].ipc_symbol == "C07C"
|
||||
assert inorganic[0].ipc_symbol == "C01B"
|
||||
selected, selections = select_ipc_matches_by_cluster_mass(matches)
|
||||
topics = {selection.topic_key for selection in selections}
|
||||
assert topics == {"TORG", "TINORG"}
|
||||
subclasses = {selection.subclass for selection in selections}
|
||||
assert "C07C" in subclasses
|
||||
assert "C01B" in subclasses or "C01C" in subclasses
|
||||
assert selected
|
||||
|
||||
|
||||
def test_text_overlap_score_uses_title_and_abstract() -> None:
|
||||
@@ -377,6 +632,143 @@ def test_text_overlap_score_uses_title_and_abstract() -> None:
|
||||
assert score == 1.0
|
||||
|
||||
|
||||
def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
source="EPO",
|
||||
title="Biochemistry overview",
|
||||
abstract="Spectrochemical analysis.",
|
||||
)
|
||||
# "chemistry" must not match inside "biochemistry" / "spectrochemical".
|
||||
assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0
|
||||
|
||||
|
||||
def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None:
|
||||
"""Soft field / loose words must not accept a mechanical separator patent."""
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP-MECH",
|
||||
source="EPO",
|
||||
title=(
|
||||
"Rotating machine for separating materials in different "
|
||||
"states of aggregation"
|
||||
),
|
||||
abstract="Apparatus for mechanical separation of materials.",
|
||||
ipc=["B01D45/12"],
|
||||
)
|
||||
phrases = ["Organic Chemistry", "organische Chemie"]
|
||||
terms = ["organic", "chemistry", "organische", "chemie"]
|
||||
evidence = _collect_keyword_text_evidence(patent, phrases, terms)
|
||||
|
||||
assert evidence.phrase_in_title is False
|
||||
assert evidence.phrase_in_abstract is False
|
||||
assert evidence.full_token_match is False
|
||||
assert evidence.matched_phrases == []
|
||||
assert evidence.matched_words == []
|
||||
|
||||
field_only = TopicEvidence(match_kind="compatible_field", score=0.3)
|
||||
assert not _keyword_text_passes_relevance_gate(
|
||||
evidence,
|
||||
topic_evidence=field_only,
|
||||
).accepted
|
||||
exact = TopicEvidence(match_kind="topic_id", score=1.0)
|
||||
assert not _keyword_text_passes_relevance_gate(
|
||||
evidence,
|
||||
topic_evidence=exact,
|
||||
).accepted
|
||||
|
||||
|
||||
def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None:
|
||||
phrase_patent = model.PatentEntry(
|
||||
patent_id="EP-PHRASE",
|
||||
source="EPO",
|
||||
title="Process for organic chemistry synthesis",
|
||||
abstract="Catalytic reactions.",
|
||||
)
|
||||
phrases = ["organic chemistry"]
|
||||
terms = ["organic", "chemistry"]
|
||||
evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms)
|
||||
assert evidence.phrase_in_title is True
|
||||
assert evidence.text_match_kind == "phrase_title"
|
||||
assert _keyword_text_score(evidence) == 1.0
|
||||
assert _keyword_text_passes_relevance_gate(
|
||||
evidence,
|
||||
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
|
||||
).accepted
|
||||
|
||||
full_token_patent = model.PatentEntry(
|
||||
patent_id="EP-WORDS",
|
||||
source="EPO",
|
||||
title="Catalytic organic synthesis method",
|
||||
abstract="Uses chemistry laboratory techniques.",
|
||||
)
|
||||
full_evidence = _collect_keyword_text_evidence(
|
||||
full_token_patent,
|
||||
phrases,
|
||||
terms,
|
||||
)
|
||||
assert full_evidence.phrase_in_title is False
|
||||
assert full_evidence.phrase_in_abstract is False
|
||||
assert full_evidence.full_token_match is True
|
||||
assert not _keyword_text_passes_relevance_gate(
|
||||
full_evidence,
|
||||
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
|
||||
).accepted
|
||||
assert _keyword_text_passes_relevance_gate(
|
||||
full_evidence,
|
||||
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
|
||||
).accepted
|
||||
|
||||
partial_patent = model.PatentEntry(
|
||||
patent_id="EP-PARTIAL",
|
||||
source="EPO",
|
||||
title="Organic polymer blend",
|
||||
abstract="Industrial materials processing.",
|
||||
)
|
||||
partial_evidence = _collect_keyword_text_evidence(
|
||||
partial_patent,
|
||||
phrases,
|
||||
terms,
|
||||
)
|
||||
assert partial_evidence.partial_token_match is True
|
||||
assert partial_evidence.full_token_match is False
|
||||
decision = _keyword_text_passes_relevance_gate(
|
||||
partial_evidence,
|
||||
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
|
||||
)
|
||||
assert not decision.accepted
|
||||
assert decision.reason == "exact_topic_with_partial_tokens_only"
|
||||
|
||||
assert _exact_topic_or_subfield_match(
|
||||
[
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/TORG",
|
||||
topic_display_name="Organic Chemistry",
|
||||
subfield_name="Organic Chemistry",
|
||||
field_name="Chemistry",
|
||||
)
|
||||
],
|
||||
frozenset({"TORG"}),
|
||||
frozenset({"organic chemistry"}),
|
||||
)
|
||||
|
||||
|
||||
def test_token_match_rejects_machine_inside_micromachined() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP-MICRO",
|
||||
source="EPO",
|
||||
title="Micromachined sensor device",
|
||||
abstract="Fabrication of micromachined structures.",
|
||||
)
|
||||
assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0
|
||||
evidence = _collect_keyword_text_evidence(
|
||||
patent,
|
||||
["Machine Learning"],
|
||||
["machine", "learning"],
|
||||
)
|
||||
assert evidence.matched_words == []
|
||||
assert evidence.full_token_match is False
|
||||
|
||||
|
||||
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
@@ -517,8 +909,10 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None:
|
||||
|
||||
epo_symbols.assert_called_once()
|
||||
uspto_symbols.assert_called_once()
|
||||
assert epo_symbols.call_args.args[0] == ["C07C"]
|
||||
assert captured == ["epo", "uspto"]
|
||||
assert epo_symbols.call_args.args[0][0] == "C07C243/08"
|
||||
assert "C07C" in epo_symbols.call_args.args[0]
|
||||
# IPC search returns empty → text fallback also queries EPO/USPTO.
|
||||
assert captured == ["epo", "uspto", "epo", "uspto"]
|
||||
|
||||
|
||||
def test_text_search_terms_include_topic_metadata() -> None:
|
||||
@@ -541,8 +935,10 @@ def test_text_search_terms_include_topic_metadata() -> None:
|
||||
def test_weighted_score_applies_level_not_llm_relevance() -> None:
|
||||
score_high = _weighted_score("subclass", 0.8, 1.0)
|
||||
score_zero = _weighted_score("subclass", 0.8, 0.0)
|
||||
assert score_high == round(0.8 * 0.85, 4)
|
||||
assert score_high == round(0.8 * 0.70, 4)
|
||||
assert score_zero == score_high
|
||||
assert _weighted_score("section", 0.9, 1.0) == 0.0
|
||||
assert _weighted_score("class", 0.9, 1.0) == 0.0
|
||||
|
||||
|
||||
def test_search_terms_use_subclass_prefix() -> None:
|
||||
@@ -550,6 +946,233 @@ def test_search_terms_use_subclass_prefix() -> None:
|
||||
assert "G06N" in _search_terms_for_symbol("G06N")
|
||||
|
||||
|
||||
def test_search_terms_include_concrete_subgroup_and_main_group() -> None:
|
||||
terms = _search_terms_for_symbol("B60R2300/8086")
|
||||
assert "B60R2300/8086" in terms
|
||||
assert "B60R2300/80" in terms
|
||||
assert "B60R" in terms
|
||||
|
||||
weights = _weighted_search_terms_for_symbol("G06N3/08")
|
||||
assert weights["G06N3/08"] > weights["G06N"]
|
||||
assert weights["G06N3/08"] >= 4.0
|
||||
|
||||
|
||||
def _match_boost(clauses: list[dict], field: str, term: str) -> float | None:
|
||||
for clause in clauses:
|
||||
payload = clause.get("match", {}).get(field)
|
||||
if isinstance(payload, dict) and payload.get("query") == term:
|
||||
return float(payload.get("boost", 1.0))
|
||||
if payload == term:
|
||||
return 1.0
|
||||
return None
|
||||
|
||||
|
||||
def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None:
|
||||
queries = IpcPatentSearchQueries()
|
||||
epo = queries.epo_query_by_ipc_symbols(["G06N3/08", "G06N"])
|
||||
uspto = queries.uspto_query_by_ipc_symbols(["G06N3/08", "G06N"])
|
||||
|
||||
epo_should = epo["query"]["bool"]["should"]
|
||||
uspto_should = uspto["query"]["bool"]["should"]
|
||||
|
||||
epo_specific = _match_boost(epo_should, "ipc", "G06N3/08")
|
||||
epo_subclass = _match_boost(epo_should, "ipc", "G06N")
|
||||
uspto_specific = _match_boost(uspto_should, "ipcr", "G06N3/08")
|
||||
uspto_subclass = _match_boost(uspto_should, "ipcr", "G06N")
|
||||
|
||||
assert epo_specific is not None and epo_subclass is not None
|
||||
assert uspto_specific is not None and uspto_subclass is not None
|
||||
assert epo_specific > epo_subclass
|
||||
assert uspto_specific > uspto_subclass
|
||||
assert _match_boost(epo_should, "cpc", "G06N3/08") == epo_specific
|
||||
assert _match_boost(uspto_should, "cpc", "G06N3/08") == uspto_specific
|
||||
assert epo["sort"][0] == {"_score": {"order": "desc"}}
|
||||
assert uspto["sort"][0] == {"_score": {"order": "desc"}}
|
||||
|
||||
|
||||
def test_text_queries_prefer_phrase_match_in_title() -> None:
|
||||
queries = IpcPatentSearchQueries()
|
||||
epo = queries.epo_query_by_text_phrases(["organic chemistry"])
|
||||
uspto = queries.uspto_query_by_text_phrases(["organic chemistry"])
|
||||
|
||||
epo_should = epo["query"]["bool"]["should"]
|
||||
uspto_should = uspto["query"]["bool"]["should"]
|
||||
|
||||
def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None:
|
||||
for clause in clauses:
|
||||
payload = clause.get(kind, {}).get(field)
|
||||
if isinstance(payload, dict) and payload.get("query") == "organic chemistry":
|
||||
return float(payload.get("boost", 1.0))
|
||||
return None
|
||||
|
||||
assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0
|
||||
assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0
|
||||
assert clause_boost(epo_should, "match", "title_en") == 1.5
|
||||
assert clause_boost(uspto_should, "match_phrase", "title") == 5.0
|
||||
assert epo["sort"][0] == {"_score": {"order": "desc"}}
|
||||
|
||||
|
||||
def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
|
||||
"""Fragmented IPC abstention must fall back to title/abstract search."""
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
title="Process for organic chemistry synthesis",
|
||||
abstract="A catalytic method in organic chemistry.",
|
||||
publication_date="20240101",
|
||||
ipc=["C07C243/08"],
|
||||
cpc=[],
|
||||
)
|
||||
|
||||
async def fake_search_epo(query):
|
||||
assert "match_phrase" in str(query) or "title_en" in str(query)
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"doc_number": "123",
|
||||
"country": "EP",
|
||||
"kind": "A1",
|
||||
"date_publication": "20240101",
|
||||
"title_en": patent.title,
|
||||
"abstract": patent.abstract,
|
||||
"ipc": patent.ipc,
|
||||
"cpc": [],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
async def fake_search_uspto(query):
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
fragmented = [
|
||||
IpcCodeMatch(
|
||||
"subgroup",
|
||||
f"A{index:02d}B1/00",
|
||||
0.70,
|
||||
"organische Chemie",
|
||||
"topic",
|
||||
"TORG",
|
||||
)
|
||||
for index in range(1, 16)
|
||||
]
|
||||
request = PatentsByKeywordsRequest(
|
||||
keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="organische Chemie",
|
||||
keyword_level="coarse",
|
||||
topic_id="https://openalex.org/TORG",
|
||||
topic_display_name="Organic Chemistry",
|
||||
field_name="Chemistry",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||
new=AsyncMock(return_value=fragmented),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||
new=AsyncMock(side_effect=fake_search_epo),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||
new=AsyncMock(side_effect=fake_search_uspto),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
|
||||
new=AsyncMock(return_value={}),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.enrich_patents_classifications",
|
||||
new=AsyncMock(),
|
||||
), patch.object(
|
||||
IpcPatentSearchQueries,
|
||||
"epo_query_by_text_phrases",
|
||||
wraps=IpcPatentSearchQueries().epo_query_by_text_phrases,
|
||||
) as epo_text:
|
||||
response = asyncio.run(get_patents_by_keywords(request))
|
||||
|
||||
epo_text.assert_called_once()
|
||||
assert response.mapping_status == "uncertain"
|
||||
assert response.patent_count == 1
|
||||
assert response.patents[0].text_retrieval is True
|
||||
assert response.patents[0].ipc_score == 0.0
|
||||
assert response.patents[0].text_score > 0.0
|
||||
assert response.patents[0].matched_ipc_symbols == []
|
||||
assert response.patents[0].keyword_evidence is not None
|
||||
assert response.patents[0].keyword_evidence.phrase_in_title is True
|
||||
assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title"
|
||||
|
||||
|
||||
def test_text_fallback_empty_yields_no_patents_found() -> None:
|
||||
request = PatentsByKeywordsRequest(
|
||||
keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="organische Chemie",
|
||||
keyword_level="coarse",
|
||||
topic_id="https://openalex.org/TORG",
|
||||
topic_display_name="Organic Chemistry",
|
||||
field_name="Chemistry",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||
new=AsyncMock(return_value=[]),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
|
||||
new=AsyncMock(return_value={}),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.enrich_patents_classifications",
|
||||
new=AsyncMock(),
|
||||
):
|
||||
response = asyncio.run(get_patents_by_keywords(request))
|
||||
|
||||
assert response.mapping_status == "no_patents_found"
|
||||
assert response.patent_count == 0
|
||||
assert response.patents == []
|
||||
|
||||
|
||||
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
|
||||
request = PatentsByKeywordsRequest(
|
||||
keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="organische Chemie",
|
||||
keyword_level="coarse",
|
||||
topic_id="https://openalex.org/TORG",
|
||||
topic_display_name="Organic Chemistry",
|
||||
field_name="Chemistry",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||
new=AsyncMock(return_value=[]),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
|
||||
), patch(
|
||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||
):
|
||||
response = asyncio.run(get_patents_by_keywords(request))
|
||||
|
||||
assert response.mapping_status == "search_error"
|
||||
assert response.patent_count == 0
|
||||
|
||||
|
||||
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
|
||||
clear_reverse_lookup_caches()
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -14,8 +14,8 @@ from inse.models.openalex.author import Author
|
||||
from inse.patents.authors.identity import (
|
||||
author_institution_names,
|
||||
patent_institution_match,
|
||||
patent_personal_assignee_match,
|
||||
)
|
||||
from inse.patents.authors.ipc_openalex_mapping import normalize_openalex_id
|
||||
from inse.patents.authors.name_matching import filter_patents_by_author_name
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.model import PatentEntry
|
||||
@@ -26,12 +26,10 @@ from inse.patents.common.parsing import (
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
patent_dedup_key,
|
||||
patent_map_key,
|
||||
)
|
||||
from inse.patents.institutions.logic import get_patents_by_institution_id
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver
|
||||
from inse.patents.org.elastic_search_client import (
|
||||
OrgPatentsSearchClient,
|
||||
fetch_authors_by_institution_name,
|
||||
@@ -219,68 +217,6 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
|
||||
}
|
||||
|
||||
|
||||
MIN_CORROBORATING_TOPIC_OVERLAP = 2
|
||||
|
||||
|
||||
def primary_classification_codes(patent: PatentEntry) -> list[str]:
|
||||
"""Returns only the patent's primary IPC/CPC code(s) (marked "AFI" in the
|
||||
raw EPO/USPTO string), falling back to all codes if none are marked.
|
||||
|
||||
Patents can carry dozens of secondary/incidental classification codes
|
||||
(marked "ALI") alongside their real subject. Resolving OpenAlex topics
|
||||
from *all* of them gives some patents a huge, unfocused topic cloud —
|
||||
confirmed against a real org_patents rebuild, where a 20-code patent
|
||||
picked up 70+ unrelated topics, making a coincidental two-topic overlap
|
||||
with an unrelated same-named author far more likely than intended.
|
||||
"""
|
||||
all_codes = [*patent.ipc, *patent.cpc]
|
||||
primary = [code for code in all_codes if "AFI" in code]
|
||||
return primary or all_codes
|
||||
|
||||
|
||||
def topic_corroborated_patents(
|
||||
patents: list[PatentEntry],
|
||||
author: Author,
|
||||
patent_topic_map: dict[str, list],
|
||||
) -> list[PatentEntry]:
|
||||
"""Keeps only patents whose IPC/CPC-derived OpenAlex topics share at
|
||||
least MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the author's
|
||||
own research topics — used to disambiguate common inventor names where
|
||||
institution/self-assignee matching alone isn't enough.
|
||||
|
||||
Requiring a single shared topic ID was still too loose: broad,
|
||||
genuinely common topics (e.g. "Image Processing Techniques") show up on
|
||||
many unrelated patents *and* on many unrelated researchers' profiles, so
|
||||
one coincidental overlap doesn't mean much (confirmed against a real
|
||||
org_patents rebuild: match_type=name patents still ballooned to ~2000).
|
||||
Two independent topic overlaps happening by chance is far less likely,
|
||||
while a patent genuinely invented by the author would typically share
|
||||
more than one topic with their own body of work. If the author has no
|
||||
topic profile at all, there is nothing to corroborate against.
|
||||
"""
|
||||
author_topic_ids = {
|
||||
normalize_openalex_id(topic.id)
|
||||
for topic in (author.topics or [])
|
||||
if topic.id
|
||||
}
|
||||
author_topic_ids.discard(None)
|
||||
if not author_topic_ids:
|
||||
return []
|
||||
|
||||
kept: list[PatentEntry] = []
|
||||
for patent in patents:
|
||||
mapped_topics = patent_topic_map.get(patent_map_key(patent), [])
|
||||
patent_topic_ids = {
|
||||
normalize_openalex_id(topic.topic_id)
|
||||
for topic in mapped_topics
|
||||
if topic.topic_id
|
||||
}
|
||||
patent_topic_ids.discard(None)
|
||||
if len(patent_topic_ids & author_topic_ids) >= MIN_CORROBORATING_TOPIC_OVERLAP:
|
||||
kept.append(patent)
|
||||
return kept
|
||||
|
||||
|
||||
async def _search_patents_by_author(
|
||||
author: Author,
|
||||
institution_name: str | None,
|
||||
@@ -315,48 +251,18 @@ async def _search_patents_by_author(
|
||||
return []
|
||||
|
||||
# Applied to every name-based hit, not gated behind an ambiguity check:
|
||||
# the institution itself being the assignee is the only unambiguous
|
||||
# case — accepted outright. Everything else matched on name alone,
|
||||
# including a personal-assignee match (several different same-named
|
||||
# people could each be listed as their own patent's assignee) or a
|
||||
# third-party assignee (e.g. an industry partner on a co-invented
|
||||
# patent — the normal case for academic patents, not a red flag by
|
||||
# itself), only counts if the patent's IPC/CPC-derived OpenAlex topics
|
||||
# also overlap with the author's own research topics. This
|
||||
# a match only counts if the assignee is the institution itself or the
|
||||
# person themselves — a bare name match on inventors is too weak a
|
||||
# signal on its own once several same-named people are possible. This
|
||||
# intentionally does not rely on is_ambiguous_name: a name can look
|
||||
# unique in our local OpenAlex slice while still being common globally
|
||||
# in EPO/USPTO, so a bare name-on-inventor match alone is never a
|
||||
# strong enough signal on its own.
|
||||
# in EPO/USPTO.
|
||||
inst_names = [institution_name] if institution_name else []
|
||||
strong_identity_matched = [
|
||||
return [
|
||||
p for p in name_matched
|
||||
if patent_institution_match(p, inst_names)
|
||||
or patent_personal_assignee_match(p, author_name)
|
||||
]
|
||||
matched_keys = {patent_dedup_key(p) for p in strong_identity_matched}
|
||||
remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys]
|
||||
if not remaining:
|
||||
return strong_identity_matched
|
||||
|
||||
topic_matched: list[PatentEntry] = []
|
||||
try:
|
||||
resolver = PatentOpenAlexMappingResolver()
|
||||
primary_only = [
|
||||
patent.model_copy(update={
|
||||
"ipc": primary_classification_codes(patent),
|
||||
"cpc": [],
|
||||
})
|
||||
for patent in remaining
|
||||
]
|
||||
patent_topic_map = await resolver.resolve_topics_for_patents(primary_only)
|
||||
topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"OpenAlex topic corroboration failed for author %s",
|
||||
author_name,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
return strong_identity_matched + topic_matched
|
||||
|
||||
|
||||
async def build_org_patents_for_institution(
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
|
||||
from inse.patents.common.model import PatentEntry
|
||||
from inse.patents.common.parsing import patent_map_key
|
||||
from inse.patents.org.logic import (
|
||||
merge_org_patents,
|
||||
org_patent_document_id,
|
||||
primary_classification_codes,
|
||||
resolve_match_type,
|
||||
topic_corroborated_patents,
|
||||
)
|
||||
from inse.patents.org.model import MatchedAuthor
|
||||
|
||||
@@ -107,108 +102,3 @@ def test_org_patent_document_id_is_stable() -> None:
|
||||
doc_id = org_patent_document_id("I62318514", patent)
|
||||
|
||||
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"
|
||||
|
||||
|
||||
def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author:
|
||||
return Author(
|
||||
id=f"https://openalex.org/{author_id}",
|
||||
display_name=name,
|
||||
topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids],
|
||||
)
|
||||
|
||||
|
||||
def _mapped_topics(*topic_ids: str) -> list[MappedOpenAlexTopic]:
|
||||
return [
|
||||
MappedOpenAlexTopic(topic_id=tid, topic_display_name=f"Topic {tid}")
|
||||
for tid in topic_ids
|
||||
]
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_keeps_two_overlapping_topics() -> None:
|
||||
author = _author_with_topics(
|
||||
"A123", "Wei Zhang",
|
||||
["https://openalex.org/T1", "https://openalex.org/T2"],
|
||||
)
|
||||
patent = _patent("EP1")
|
||||
patent_topic_map = {
|
||||
patent_map_key(patent): _mapped_topics(
|
||||
"https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3"
|
||||
),
|
||||
}
|
||||
|
||||
result = topic_corroborated_patents([patent], author, patent_topic_map)
|
||||
|
||||
assert result == [patent]
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_drops_single_coincidental_overlap() -> None:
|
||||
"""A single shared topic isn't enough — broad, common topics show up on
|
||||
many unrelated patents and profiles by coincidence."""
|
||||
author = _author_with_topics(
|
||||
"A123", "Xin Wang",
|
||||
["https://openalex.org/T1", "https://openalex.org/T9"],
|
||||
)
|
||||
patent = _patent("EP2")
|
||||
patent_topic_map = {
|
||||
patent_map_key(patent): _mapped_topics(
|
||||
"https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3"
|
||||
),
|
||||
}
|
||||
|
||||
result = topic_corroborated_patents([patent], author, patent_topic_map)
|
||||
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_drops_patent_without_mapped_topics() -> None:
|
||||
author = _author_with_topics("A123", "Wei Zhang", ["https://openalex.org/T1"])
|
||||
patent = _patent("EP3")
|
||||
|
||||
result = topic_corroborated_patents([patent], author, {})
|
||||
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_rejects_everything_without_author_topic_profile() -> None:
|
||||
author = Author(id="https://openalex.org/A999", display_name="Wei Zhang")
|
||||
patent = _patent("EP4")
|
||||
patent_topic_map = {
|
||||
patent_map_key(patent): _mapped_topics(
|
||||
"https://openalex.org/T1", "https://openalex.org/T2"
|
||||
),
|
||||
}
|
||||
|
||||
result = topic_corroborated_patents([patent], author, patent_topic_map)
|
||||
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_primary_classification_codes_keeps_only_afi_marked_codes() -> None:
|
||||
"""A patent with many secondary ("ALI") codes alongside its one primary
|
||||
("AFI") code must only contribute the primary one — otherwise a large
|
||||
secondary-code topic cloud makes coincidental multi-topic overlaps with
|
||||
an unrelated same-named author far too easy (confirmed against a real
|
||||
org_patents rebuild: a 20-code patent picked up 70+ topics)."""
|
||||
patent = _patent("EP1")
|
||||
patent.ipc = [
|
||||
"G06V 10/776 20220101AFI20250422BHUS",
|
||||
"G01N 33/569 20060101ALI20250422BHUS",
|
||||
"G06T 5/20 20060101ALI20250422BHUS",
|
||||
]
|
||||
patent.cpc = ["G16H 30/40 20180101ALI20250422BHUS"]
|
||||
|
||||
result = primary_classification_codes(patent)
|
||||
|
||||
assert result == ["G06V 10/776 20220101AFI20250422BHUS"]
|
||||
|
||||
|
||||
def test_primary_classification_codes_falls_back_to_all_codes_without_afi_marker() -> None:
|
||||
patent = _patent("EP2")
|
||||
patent.ipc = ["G06V 10/776 20220101ALI20250422BHUS"]
|
||||
patent.cpc = ["G01N 33/569 20060101ALI20250422BHUS"]
|
||||
|
||||
result = primary_classification_codes(patent)
|
||||
|
||||
assert result == patent.ipc + patent.cpc
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
export interface KeywordEvidence {
|
||||
phrase_in_title?: boolean;
|
||||
phrase_in_abstract?: boolean;
|
||||
full_token_match?: boolean;
|
||||
partial_token_match?: boolean;
|
||||
word_match_score?: number;
|
||||
matched_phrases?: Array<string>;
|
||||
matched_words?: Array<string>;
|
||||
text_match_kind?: string;
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { PatentEntry } from './patentEntry';
|
||||
import { KeywordEvidence } from './keywordEvidence';
|
||||
|
||||
export interface KeywordPatentMatch {
|
||||
patent: PatentEntry;
|
||||
@@ -29,4 +30,10 @@ export interface KeywordPatentMatch {
|
||||
text_score: number;
|
||||
matched_keywords?: Array<string>;
|
||||
matched_ipc_symbols?: Array<string>;
|
||||
/**
|
||||
* True when retrieved via title/abstract text search because IPC mapping was uncertain, missing, or yielded no hits.
|
||||
*/
|
||||
text_retrieval?: boolean;
|
||||
keyword_evidence?: KeywordEvidence | null;
|
||||
topic_match_kind?: string | null;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,15 @@
|
||||
*/
|
||||
import { KeywordPatentMatch } from './keywordPatentMatch';
|
||||
|
||||
export type KeywordPatentMappingStatus =
|
||||
| 'mapped'
|
||||
| 'uncertain'
|
||||
| 'no_mapping'
|
||||
| 'no_patents_found'
|
||||
| 'search_error';
|
||||
|
||||
export interface PatentsByKeywordsResponse {
|
||||
patent_count: number;
|
||||
patents: Array<KeywordPatentMatch>;
|
||||
mapping_status: KeywordPatentMappingStatus;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
RouterLink,
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
RouterLinkActive,
|
||||
} from '@angular/router';
|
||||
import { Institution } from '../../api';
|
||||
import { PatentsService } from '../../api/api/patents.service';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
|
||||
const PATENTS_LINK = { label: 'Patente', path: 'patents', disabled: false };
|
||||
|
||||
@Component({
|
||||
selector: 'app-institution',
|
||||
imports: [
|
||||
@@ -22,6 +25,8 @@ import { MatTabsModule } from '@angular/material/tabs';
|
||||
styleUrl: './institution.component.scss',
|
||||
})
|
||||
export class InstitutionComponent implements OnInit {
|
||||
private readonly patentsApi = inject(PatentsService);
|
||||
|
||||
institution!: Institution;
|
||||
|
||||
links = [
|
||||
@@ -40,7 +45,6 @@ export class InstitutionComponent implements OnInit {
|
||||
sort_direction: 'asc',
|
||||
},
|
||||
},
|
||||
{ label: 'Patente', path: 'patents', disabled: false },
|
||||
];
|
||||
|
||||
constructor(private readonly activatedRoute: ActivatedRoute) {}
|
||||
@@ -49,5 +53,19 @@ export class InstitutionComponent implements OnInit {
|
||||
this.activatedRoute.data.subscribe(({ institution }) => {
|
||||
this.institution = institution;
|
||||
});
|
||||
|
||||
const institutionId = this.activatedRoute.snapshot.paramMap.get('institutionId');
|
||||
if (!institutionId) return;
|
||||
|
||||
// The "Patente" tab only makes sense once org_patents has been indexed for
|
||||
// this institution (currently a manual, ~30-40 min-per-institution process),
|
||||
// so only show it once we know there is actually data behind it.
|
||||
this.patentsApi.getOrgPatentsByInstitution(institutionId, undefined, 0, 0).subscribe({
|
||||
next: (result) => {
|
||||
if ((result.patent_count ?? 0) > 0) {
|
||||
this.links = [...this.links, PATENTS_LINK];
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,17 +75,19 @@
|
||||
<mat-icon>work</mat-icon>
|
||||
Projekte
|
||||
</a>
|
||||
<a
|
||||
mat-button
|
||||
[routerLink]="[
|
||||
'/institution',
|
||||
extractInstitutionId(institution),
|
||||
'patents',
|
||||
]"
|
||||
(click)="$event.stopPropagation()">
|
||||
<mat-icon>verified</mat-icon>
|
||||
Patente
|
||||
</a>
|
||||
@if (hasPatents(institution)) {
|
||||
<a
|
||||
mat-button
|
||||
[routerLink]="[
|
||||
'/institution',
|
||||
extractInstitutionId(institution),
|
||||
'patents',
|
||||
]"
|
||||
(click)="$event.stopPropagation()">
|
||||
<mat-icon>verified</mat-icon>
|
||||
Patente
|
||||
</a>
|
||||
}
|
||||
</mat-card-actions>
|
||||
</mat-card-footer>
|
||||
</mat-card>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { Component, computed, effect, inject, input } from '@angular/core';
|
||||
import { Institution, InstitutionPage } from '../../api';
|
||||
import { PatentsService } from '../../api/api/patents.service';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { RouterModule } from '@angular/router';
|
||||
@@ -27,6 +28,8 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
|
||||
styleUrl: './institutions.component.scss',
|
||||
})
|
||||
export class InstitutionsComponent {
|
||||
private readonly patentsApi = inject(PatentsService);
|
||||
|
||||
institutionPage = input.required<InstitutionPage>();
|
||||
|
||||
observers: FilterObserver[] = [
|
||||
@@ -44,6 +47,31 @@ export class InstitutionsComponent {
|
||||
elements: this.institutionPage().elements || [],
|
||||
}));
|
||||
|
||||
// The "Patente" action only makes sense once org_patents has been indexed
|
||||
// for that institution (currently a manual, per-institution process), so
|
||||
// it's hidden by default and only shown once a cheap count check confirms
|
||||
// there is actually data behind it.
|
||||
private readonly patentsAvailable = new Map<string, boolean>();
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
for (const institution of this.page().elements) {
|
||||
const id = this.extractInstitutionId(institution);
|
||||
if (!id || this.patentsAvailable.has(id)) continue;
|
||||
this.patentsAvailable.set(id, false);
|
||||
this.patentsApi.getOrgPatentsByInstitution(id, undefined, 0, 0).subscribe({
|
||||
next: (result) => {
|
||||
this.patentsAvailable.set(id, (result.patent_count ?? 0) > 0);
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
hasPatents(institution: Institution): boolean {
|
||||
return this.patentsAvailable.get(this.extractInstitutionId(institution)) ?? false;
|
||||
}
|
||||
|
||||
sortingOptions: SelectorOption[] = [
|
||||
{ value: 'relevance', display_name: 'Relevanz' },
|
||||
{ value: 'name', display_name: 'Name' },
|
||||
|
||||
+6
-2
@@ -1,7 +1,11 @@
|
||||
@if (loading()) {
|
||||
<div class="patents-container">
|
||||
<ng-container *ngTemplateOutlet="patentsHeader" />
|
||||
<p class="message">Lade passende Patente...</p>
|
||||
<app-loading
|
||||
text="Patentdaten werden geladen..."
|
||||
icon="workspace_premium"
|
||||
[size]="150"
|
||||
[diameter]="150" />
|
||||
</div>
|
||||
} @else if (error()) {
|
||||
<div class="patents-container">
|
||||
@@ -11,7 +15,7 @@
|
||||
} @else if (matches().length === 0) {
|
||||
<div class="patents-container">
|
||||
<ng-container *ngTemplateOutlet="patentsHeader" />
|
||||
<p class="message">Keine passenden Patente gefunden.</p>
|
||||
<p class="message">{{ emptyMessage() }}</p>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="patents-container">
|
||||
|
||||
+9
@@ -3,6 +3,15 @@
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.fallback-notice {
|
||||
margin: 0 0 12px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
background: #f4f7fb;
|
||||
color: #3d4f63;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 0;
|
||||
font-size: 1.25rem;
|
||||
|
||||
+13
-1
@@ -5,6 +5,8 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { Router } from '@angular/router';
|
||||
import { PatentEntry } from '../../../api/model/patentEntry';
|
||||
import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch';
|
||||
import { KeywordPatentMappingStatus } from '../../../api/model/patentsByKeywordsResponse';
|
||||
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
|
||||
import {
|
||||
formatPatentDate,
|
||||
getPublicationStageLabel,
|
||||
@@ -14,12 +16,13 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||
|
||||
@Component({
|
||||
selector: 'app-keywords-patents',
|
||||
imports: [NgTemplateOutlet, MatButtonModule, MatIconModule],
|
||||
imports: [NgTemplateOutlet, MatButtonModule, MatIconModule, LoadingComponent],
|
||||
templateUrl: './keywords-patents.component.html',
|
||||
styleUrl: './keywords-patents.component.scss',
|
||||
})
|
||||
export class KeywordsPatentsComponent {
|
||||
readonly matches = input<KeywordPatentMatch[]>([]);
|
||||
readonly mappingStatus = input<KeywordPatentMappingStatus | null>(null);
|
||||
readonly loading = input(false);
|
||||
readonly error = input(false);
|
||||
readonly showReload = input(false);
|
||||
@@ -33,6 +36,15 @@ export class KeywordsPatentsComponent {
|
||||
|
||||
constructor(private readonly router: Router) {}
|
||||
|
||||
emptyMessage(): string {
|
||||
switch (this.mappingStatus()) {
|
||||
case 'search_error':
|
||||
return 'Die Patentrecherche ist technisch fehlgeschlagen. Bitte später erneut versuchen.';
|
||||
default:
|
||||
return 'Keine passenden Patente gefunden';
|
||||
}
|
||||
}
|
||||
|
||||
filteredMatches(): KeywordPatentMatch[] {
|
||||
const filter = this.activeFilter();
|
||||
const items = this.matches();
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic';
|
||||
import { KeywordPatentMatch } from '../../api/model/keywordPatentMatch';
|
||||
import { KeywordPatentSearchItem } from '../../api/model/keywordPatentSearchItem';
|
||||
import {
|
||||
KeywordPatentMappingStatus,
|
||||
} from '../../api/model/patentsByKeywordsResponse';
|
||||
import {
|
||||
PatentKeywordEntry,
|
||||
SearchResultsPayload,
|
||||
@@ -8,9 +11,17 @@ import {
|
||||
|
||||
export const PATENTS_CACHE_KEY = 'keywords-patents-cache';
|
||||
|
||||
export type { KeywordPatentMappingStatus };
|
||||
|
||||
export interface PatentsCache {
|
||||
keywords: string[];
|
||||
matches: KeywordPatentMatch[];
|
||||
mappingStatus?: KeywordPatentMappingStatus | null;
|
||||
}
|
||||
|
||||
export interface PatentsCacheResult {
|
||||
matches: KeywordPatentMatch[];
|
||||
mappingStatus: KeywordPatentMappingStatus | null;
|
||||
}
|
||||
|
||||
export function buildPatentSearchItems(
|
||||
@@ -58,14 +69,17 @@ export function buildPatentSearchItemsFromPayload(
|
||||
|
||||
export function readPatentsCache(
|
||||
keywords: string[],
|
||||
): KeywordPatentMatch[] | null {
|
||||
): PatentsCacheResult | null {
|
||||
const raw = sessionStorage.getItem(PATENTS_CACHE_KEY);
|
||||
if (!raw) return null;
|
||||
|
||||
try {
|
||||
const cache = JSON.parse(raw) as PatentsCache;
|
||||
if (!sameKeywordSet(cache.keywords, keywords)) return null;
|
||||
return cache.matches ?? [];
|
||||
return {
|
||||
matches: cache.matches ?? [],
|
||||
mappingStatus: cache.mappingStatus ?? null,
|
||||
};
|
||||
} catch {
|
||||
sessionStorage.removeItem(PATENTS_CACHE_KEY);
|
||||
return null;
|
||||
@@ -75,9 +89,10 @@ export function readPatentsCache(
|
||||
export function writePatentsCache(
|
||||
keywords: string[],
|
||||
matches: KeywordPatentMatch[],
|
||||
mappingStatus: KeywordPatentMappingStatus | null = null,
|
||||
): void {
|
||||
try {
|
||||
const cache: PatentsCache = { keywords, matches };
|
||||
const cache: PatentsCache = { keywords, matches, mappingStatus };
|
||||
sessionStorage.setItem(PATENTS_CACHE_KEY, JSON.stringify(cache));
|
||||
} catch (error) {
|
||||
console.error('Failed to cache patent results:', error);
|
||||
|
||||
+1
@@ -22,6 +22,7 @@
|
||||
<div class="results-card">
|
||||
<app-keywords-patents
|
||||
[matches]="patentMatches()"
|
||||
[mappingStatus]="mappingStatus()"
|
||||
[loading]="loadingPatents()"
|
||||
[error]="patentsError()"
|
||||
[showReload]="state.hasValidSearch()"
|
||||
|
||||
+22
-7
@@ -6,7 +6,10 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import { KeywordsService } from '../../../../api/api/keywords.service';
|
||||
import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch';
|
||||
import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse';
|
||||
import {
|
||||
KeywordPatentMappingStatus,
|
||||
PatentsByKeywordsResponse,
|
||||
} from '../../../../api/model/patentsByKeywordsResponse';
|
||||
import {
|
||||
WeightMap,
|
||||
WeightSliderOption,
|
||||
@@ -83,6 +86,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
||||
});
|
||||
|
||||
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
|
||||
readonly mappingStatus = signal<KeywordPatentMappingStatus | null>(null);
|
||||
readonly loadingPatents = signal(false);
|
||||
readonly patentsError = signal(false);
|
||||
|
||||
@@ -91,7 +95,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
||||
ngOnInit(): void {
|
||||
const cached = readPatentsCache(this.state.keywords());
|
||||
if (cached) {
|
||||
this.setPatentMatches(cached);
|
||||
this.setPatentMatches(cached.matches, cached.mappingStatus);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -119,7 +123,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
||||
private loadMatchingPatents(): void {
|
||||
const keywords = buildPatentSearchItemsFromPayload(this.state.payload());
|
||||
if (keywords.length === 0) {
|
||||
this.setPatentMatches([]);
|
||||
this.setPatentMatches([], 'no_mapping');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -128,22 +132,33 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
||||
|
||||
this.keywordsService.getPatentsByKeywords({ keywords }).subscribe({
|
||||
next: (response: PatentsByKeywordsResponse) => {
|
||||
this.setPatentMatches(response.patents ?? []);
|
||||
this.setPatentMatches(
|
||||
response.patents ?? [],
|
||||
response.mapping_status ?? null,
|
||||
);
|
||||
this.loadingPatents.set(false);
|
||||
},
|
||||
error: (error: unknown) => {
|
||||
console.error('Patent search failed:', error);
|
||||
this.setPatentMatches([]);
|
||||
this.setPatentMatches([], null);
|
||||
this.patentsError.set(true);
|
||||
this.loadingPatents.set(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private setPatentMatches(matches: KeywordPatentMatch[]): void {
|
||||
private setPatentMatches(
|
||||
matches: KeywordPatentMatch[],
|
||||
mappingStatus: KeywordPatentMappingStatus | null = null,
|
||||
): void {
|
||||
this.patentMatchesBase.set(matches);
|
||||
this.mappingStatus.set(mappingStatus);
|
||||
this.updateDisplayedMatches();
|
||||
writePatentsCache(this.state.keywords(), this.patentMatchesBase());
|
||||
writePatentsCache(
|
||||
this.state.keywords(),
|
||||
this.patentMatchesBase(),
|
||||
mappingStatus,
|
||||
);
|
||||
}
|
||||
|
||||
private updateDisplayedMatches(): void {
|
||||
|
||||
@@ -11,7 +11,10 @@ import { PatentsService } from '../../api/api/patents.service';
|
||||
import { PatentEntry } from '../../api/model/patentEntry';
|
||||
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
|
||||
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||
import {
|
||||
classificationSectionColor,
|
||||
topicHierarchyColor,
|
||||
} from '../../resolvers/utils/topic-colors';
|
||||
import {
|
||||
ClassificationCard,
|
||||
ClassificationSystem,
|
||||
@@ -107,7 +110,7 @@ export class PatentDetailComponent implements OnInit {
|
||||
}
|
||||
|
||||
sectionColor(card: ClassificationCard): string {
|
||||
return topicHierarchyColor({ field_name: card.sectionName });
|
||||
return classificationSectionColor(card.sectionName ?? card.symbols[0]);
|
||||
}
|
||||
|
||||
toggleClassificationExpanded(key: string): void {
|
||||
|
||||
@@ -17,7 +17,10 @@ import { IpcClassification } from '../../api';
|
||||
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
|
||||
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||
import {
|
||||
classificationSectionColor,
|
||||
topicHierarchyColor,
|
||||
} from '../../resolvers/utils/topic-colors';
|
||||
|
||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||
|
||||
@@ -404,7 +407,7 @@ export class PatentsComponent implements OnInit {
|
||||
}
|
||||
|
||||
sectionColor(card: ClassificationCard): string {
|
||||
return topicHierarchyColor({ field_name: card.sectionName });
|
||||
return classificationSectionColor(card.sectionName ?? card.symbols[0]);
|
||||
}
|
||||
|
||||
private getClassificationLevel(entry: IpcClassification): {
|
||||
|
||||
@@ -53,6 +53,29 @@ const DOMAIN_FALLBACK_HUES: Record<string, number> = {
|
||||
const FIELD_COLOR_SATURATION = 86;
|
||||
const FIELD_COLOR_LIGHTNESS = 36;
|
||||
|
||||
// IPC/CPC section titles (e.g. "F - Mechanical engineering; Lighting; ...")
|
||||
// never match the academic FIELD_HUES keys above, so they need their own
|
||||
// fixed hue per section letter to avoid an effectively random hash color.
|
||||
const IPC_SECTION_HUES: Record<string, number> = {
|
||||
A: 342, // Human Necessities (agriculture, foodstuffs, health)
|
||||
B: 204, // Performing Operations; Transporting
|
||||
C: 184, // Chemistry; Metallurgy
|
||||
D: 262, // Textiles; Paper
|
||||
E: 96, // Fixed Constructions
|
||||
F: 88, // Mechanical Engineering; Lighting; Heating; Weapons; Blasting
|
||||
G: 250, // Physics
|
||||
H: 222, // Electricity
|
||||
};
|
||||
|
||||
export function classificationSectionColor(
|
||||
section: string | null | undefined,
|
||||
): string {
|
||||
const letter = section?.trim().charAt(0).toUpperCase();
|
||||
const hue = (letter ? IPC_SECTION_HUES[letter] : undefined) ?? stableHue(section ?? 'section');
|
||||
|
||||
return `hsl(${normalizeHue(hue)} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`;
|
||||
}
|
||||
|
||||
export function topicHierarchyColor(
|
||||
topic: TopicHierarchyColorInput | undefined | null,
|
||||
): string {
|
||||
|
||||
Reference in New Issue
Block a user