From cfc2c29994b7069cf3ca89346e857c64277a6ea9 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sun, 19 Jul 2026 13:29:02 +0200 Subject: [PATCH 1/6] Include CPC subclass-field main groups in IPC fetch and lookup. Reads cpc_subclass_* as group-level symbols (e.g. H01M8/00) so descriptions and OpenAlex topic mappings cover the previously missing */00 codes. --- .../main/inse/patents/ipc_search_client.py | 37 +++- .../patents_openalex_keywords/ipc_entries.py | 58 ++++-- .../patents_openalex_keywords/matching.py | 20 +- .../test_ipc_entries.py | 175 ++++++++++++++++++ .../test_matching.py | 12 ++ .../src/main/inse/patents/test_ipc_lookup.py | 20 ++ .../inse/patents/test_ipc_search_client.py | 147 +++++++++++++++ 7 files changed, 447 insertions(+), 22 deletions(-) create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py index 846a6a69..4eb2ec07 100644 --- a/service/src/main/inse/patents/ipc_search_client.py +++ b/service/src/main/inse/patents/ipc_search_client.py @@ -12,6 +12,7 @@ from . import model from inse.exceptions import MissingApiKeyError from .ipc_lookup import IpcHierarchyKeys from .ipc_lookup import build_ipc_classification +from .ipc_lookup import normalize_ipc_symbol from .ipc_lookup import parse_ipc_symbol from inse.integrations import elasticsearch @@ -26,6 +27,10 @@ _LEVELS: tuple[tuple[str, str, str], ...] = ( ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), ) +# Main-group symbols (typically */00, e.g. H01M8/00) live under these fields. +_GROUP_FALLBACK_FIELDS = ("cpc_subclass_number", "cpc_subclass_name") + + class IpcSearchClient: def __init__( @@ -91,6 +96,16 @@ class IpcSearchClient: if level_symbols: results[level] = await self._lookup_level(number_field, name_field, level_symbols) + group_symbols = {s for s in symbols_by_level["group"] if s} + if group_symbols: + fallback_number, fallback_name = _GROUP_FALLBACK_FIELDS + fallback_hits = await self._lookup_level( + fallback_number, fallback_name, group_symbols + ) + for key, name in fallback_hits.items(): + if name and not results["group"].get(key): + results["group"][key] = name + return results async def _lookup_level( @@ -102,13 +117,22 @@ class IpcSearchClient: if not symbols: return {} + # Query both raw and fully normalized forms so spaced/unspaced inputs match. + query_symbols: set[str] = set() + for symbol in symbols: + cleaned = symbol.strip() + if not cleaned: + continue + query_symbols.add(cleaned) + query_symbols.add(normalize_ipc_symbol(cleaned)) + payload: dict[str, Any] = { - "size": min(len(symbols), 100), + "size": min(len(query_symbols), 100), "query": { "bool": { "should": [ {"bool": {"filter": [{"match_phrase": {number_field: symbol}}]}} - for symbol in sorted(symbols) + for symbol in sorted(query_symbols) ], "minimum_should_match": 1, } @@ -124,9 +148,12 @@ class IpcSearchClient: number = source.get(number_field) if not number: continue - normalized_number = number.strip().upper() - found[normalized_number] = source.get(name_field) - found[number.strip()] = source.get(name_field) + name = source.get(name_field) + stripped = str(number).strip() + normalized_number = normalize_ipc_symbol(stripped) + found[normalized_number] = name + found[stripped] = name + found[stripped.upper()] = name return found diff --git a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py index b89ad79e..8756d8da 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py @@ -73,11 +73,35 @@ async def fetch_unique_ipc_entries( ) -> dict[str, dict[str, str]]: entries: dict[str, dict[str, str]] = defaultdict(dict) + def _store_entry( + level: str, + symbol: str, + name: str, + *, + overwrite: bool, + ) -> None: + normalized = normalize_symbol(symbol) + if not normalized: + return + if level == "subclass": + if len(normalized) <= 3: + return + normalized = infer_subclass(symbol) or normalized + if level == "class" and len(normalized) != 3: + return + label = str(name).strip() + if not label: + return + if overwrite or normalized not in entries[level]: + entries[level][normalized] = label + async def _composite_with_label( level: str, number_field: str, name_field: str, page_size: int, + *, + overwrite: bool = True, ) -> bool: for field_name in (number_field, f"{number_field}.keyword"): after_key: dict[str, str] | None = None @@ -126,12 +150,7 @@ async def fetch_unique_ipc_entries( name = hits[0].get("_source", {}).get(name_field) if not name: continue - normalized = normalize_symbol(str(symbol)) - if level == "subclass": - if len(normalized) <= 3: - continue - normalized = infer_subclass(str(symbol)) or normalized - entries[level][normalized] = str(name).strip() + _store_entry(level, str(symbol), str(name), overwrite=overwrite) after_key = items.get("after_key") if not after_key: break @@ -144,6 +163,8 @@ async def fetch_unique_ipc_entries( number_field: str, name_field: str, size: int, + *, + overwrite: bool = True, ) -> None: for field_name in (number_field, f"{number_field}.keyword"): payload = { @@ -180,14 +201,7 @@ async def fetch_unique_ipc_entries( name = hits[0].get("_source", {}).get(name_field) if not name: continue - normalized = normalize_symbol(str(symbol)) - if level == "class" and len(normalized) != 3: - continue - if level == "subclass": - if len(normalized) <= 3: - continue - normalized = infer_subclass(str(symbol)) or normalized - entries[level][normalized] = str(name).strip() + _store_entry(level, str(symbol), str(name), overwrite=overwrite) if "section" in levels: await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30) @@ -196,6 +210,22 @@ async def fetch_unique_ipc_entries( if "group" in levels: if not await _composite_with_label("group", "cpc_group_number", "cpc_group_name", 1000): await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000) + # Main groups (e.g. H01M8/00) are stored under the historically misnamed + # cpc_subclass_* fields. Merge without overwriting existing group entries. + if not await _composite_with_label( + "group", + "cpc_subclass_number", + "cpc_subclass_name", + 1000, + overwrite=False, + ): + await _terms_with_label( + "group", + "cpc_subclass_number", + "cpc_subclass_name", + 20000, + overwrite=False, + ) if "subgroup" in levels: if not await _composite_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 1000): await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000) diff --git a/service/src/main/inse/patents/patents_openalex_keywords/matching.py b/service/src/main/inse/patents/patents_openalex_keywords/matching.py index 2467d4d6..872d2837 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/matching.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/matching.py @@ -271,6 +271,20 @@ def documents_to_json_mapping(documents: list[tuple[str, dict]]) -> dict[str, di return mapping +def _hierarchy_label(value: Any) -> str | None: + """Normalize OpenAlex hierarchy fields to plain strings for keyword mapping.""" + if value is None: + return None + if isinstance(value, dict): + display = value.get("display_name") or value.get("name") + if display is None: + return None + text = str(display).strip() + return text or None + text = str(value).strip() + return text or None + + class TopicVectorsMatcher: def __init__( @@ -337,9 +351,9 @@ class TopicVectorsMatcher: "rank": len(topic_matches) + 1, "topic_id": topic_id, "topic_display_name": topic_name, - "subfield": source.get("subfield"), - "field": source.get("field"), - "domain": source.get("domain"), + "subfield": _hierarchy_label(source.get("subfield")), + "field": _hierarchy_label(source.get("field")), + "domain": _hierarchy_label(source.get("domain")), "match_score": round(score, 4), } ) diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py new file mode 100644 index 00000000..be6e3a5a --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py @@ -0,0 +1,175 @@ +"""Tests for IPC entry fetching, including cpc_subclass_* main groups.""" +from __future__ import annotations + +from unittest.mock import AsyncMock, patch + +import pytest + +from inse.patents.patents_openalex_keywords.ipc_entries import ( + fetch_unique_ipc_entries, + normalize_symbol, +) + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def _composite_response(buckets: list[dict]) -> dict: + return {"aggregations": {"items": {"buckets": buckets, "after_key": None}}} + + +def _bucket(symbol: str, name_field: str, name: str) -> dict: + return { + "key": {"symbol": symbol}, + "sample": {"hits": {"hits": [{"_source": {name_field: name}}]}}, + } + + +@pytest.mark.anyio +async def test_fetch_unique_ipc_entries_includes_main_groups_from_cpc_subclass(): + """H01M8/00 from cpc_subclass_* is stored as group with a non-empty label.""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + sources = body.get("aggs", {}).get("items", {}).get("composite", {}).get( + "sources", [] + ) + field = sources[0]["symbol"]["terms"]["field"] if sources else "" + # terms agg path + terms = body.get("aggs", {}).get("items", {}).get("terms", {}) + if terms: + field = terms.get("field", "") + + if field.startswith("cpc_section"): + return {"aggregations": {"items": {"buckets": []}}} + if field.startswith("cpc_class"): + return { + "aggregations": { + "items": { + "buckets": [ + { + "key": "H01M", + "sample": { + "hits": { + "hits": [ + { + "_source": { + "cpc_class_name": "BATTERIES" + } + } + ] + } + }, + } + ] + } + } + } + if "cpc_group_number" in field: + return _composite_response( + [ + _bucket( + "H01M8/08", + "cpc_group_name", + "Fuel cells with aqueous electrolytes", + ) + ] + ) + if "cpc_subclass_number" in field: + return _composite_response( + [ + _bucket("H01M8/00", "cpc_subclass_name", "Fuel cells Manufacture thereof"), + _bucket("H01M 8/00", "cpc_subclass_name", "Fuel cells Manufacture thereof"), + _bucket("A01B1/00", "cpc_subclass_name", "Hand tools"), + ] + ) + if "cpc_subgroup" in field: + return _composite_response( + [ + _bucket("H01M8/083", "cpc_subgroup_name", "Alkaline fuel cells"), + ] + ) + return {"aggregations": {"items": {"buckets": []}}} + + with patch( + "inse.patents.patents_openalex_keywords.ipc_entries.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + entries = await fetch_unique_ipc_entries() + + assert "H01M8/00" in entries["group"] + assert entries["group"]["H01M8/00"] + assert "H01M 8/00" not in entries["group"] # spaced form normalized away + assert normalize_symbol("H01M 8/00") == "H01M8/00" + assert entries["group"]["H01M8/00"] == "Fuel cells Manufacture thereof" + assert "A01B1/00" in entries["group"] + + # Existing levels unchanged in role + assert "H01M" in entries["subclass"] + assert "H01M8/083" in entries["subgroup"] + assert "H01M8/08" in entries["group"] + + +@pytest.mark.anyio +async def test_fetch_unique_ipc_entries_dedupes_normalized_group_symbols(): + """Spaced and unspaced main-group variants collapse to one entry.""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + sources = body.get("aggs", {}).get("items", {}).get("composite", {}).get( + "sources", [] + ) + field = sources[0]["symbol"]["terms"]["field"] if sources else "" + terms = body.get("aggs", {}).get("items", {}).get("terms", {}) + if terms: + field = terms.get("field", "") + + if "cpc_group_number" in field: + return _composite_response([]) + if "cpc_subclass_number" in field: + return _composite_response( + [ + _bucket("H01M8/00", "cpc_subclass_name", "from-unspaced"), + _bucket("H01M 8/00", "cpc_subclass_name", "from-spaced"), + ] + ) + return {"aggregations": {"items": {"buckets": []}}} + + with patch( + "inse.patents.patents_openalex_keywords.ipc_entries.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + entries = await fetch_unique_ipc_entries(levels=("group",)) + + assert list(entries["group"]) == ["H01M8/00"] + # First write wins when overwrite=False for the subclass-field merge; + # both normalize to the same key so only one label is kept. + assert entries["group"]["H01M8/00"] in {"from-unspaced", "from-spaced"} + + +@pytest.mark.anyio +async def test_fetch_unique_ipc_entries_prefers_existing_group_over_subclass_field(): + """cpc_group_* labels are not overwritten by cpc_subclass_*.""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + sources = body.get("aggs", {}).get("items", {}).get("composite", {}).get( + "sources", [] + ) + field = sources[0]["symbol"]["terms"]["field"] if sources else "" + if "cpc_group_number" in field: + return _composite_response( + [_bucket("X01A1/00", "cpc_group_name", "from-group-field")] + ) + if "cpc_subclass_number" in field: + return _composite_response( + [_bucket("X01A1/00", "cpc_subclass_name", "from-subclass-field")] + ) + return {"aggregations": {"items": {"buckets": []}}} + + with patch( + "inse.patents.patents_openalex_keywords.ipc_entries.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + entries = await fetch_unique_ipc_entries(levels=("group",)) + + assert entries["group"]["X01A1/00"] == "from-group-field" diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py index 66417433..4b7c5051 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py @@ -7,11 +7,23 @@ import pytest from inse.patents.patents_openalex_keywords.matching import ( EmbeddingMatcher, TopicCandidate, + _hierarchy_label, top_k_indices, topic_embedding_text, ) +def test_hierarchy_label_extracts_display_name_from_object() -> None: + assert ( + _hierarchy_label( + {"id": "https://openalex.org/subfields/2211", "display_name": "Mechanics of Materials"} + ) + == "Mechanics of Materials" + ) + assert _hierarchy_label("Oncology") == "Oncology" + assert _hierarchy_label(None) is None + + def test_topic_embedding_text_joins_hierarchy() -> None: topic = TopicCandidate( topic_id="T1", diff --git a/service/src/main/inse/patents/test_ipc_lookup.py b/service/src/main/inse/patents/test_ipc_lookup.py index 941ff03b..7d26dbad 100644 --- a/service/src/main/inse/patents/test_ipc_lookup.py +++ b/service/src/main/inse/patents/test_ipc_lookup.py @@ -127,3 +127,23 @@ def test_build_ipc_classification_falls_back_to_symbol_only() -> None: result = build_ipc_classification(keys, {}) assert result == IpcClassification(symbol="INVALID") + + +def test_build_ipc_classification_main_group_from_normalized_key() -> None: + """Group labels keyed by normalized */00 symbols resolve for spaced inputs.""" + keys = parse_ipc_symbol("H01M 8/00") + names = { + "section": {"H": "ELECTRICITY"}, + "class": { + "H01": None, + "H01M": "BATTERIES / FUEL CELLS", + }, + "group": {"H01M8/00": "Fuel cells Manufacture thereof"}, + "subgroup": {}, + } + + result = build_ipc_classification(keys, names) + + assert keys.main_group == "H01M8/00" + assert result.main_group == "H01M 8/00 - Fuel cells Manufacture thereof" + assert result.subclass == "H01M - BATTERIES / FUEL CELLS" diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py index 78df758e..4abc4a67 100644 --- a/service/src/main/inse/patents/test_ipc_search_client.py +++ b/service/src/main/inse/patents/test_ipc_search_client.py @@ -1,6 +1,7 @@ from unittest.mock import AsyncMock, patch import pytest +from inse.patents.ipc_lookup import parse_ipc_symbol from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient @@ -59,3 +60,149 @@ async def test_resolve_symbols_does_not_crash_for_subclass_codes(): assert "A61J 1/14" in result assert "C07D 319/06" in result + + +@pytest.mark.anyio +async def test_resolve_symbols_main_group_from_cpc_subclass_field(): + """H01M8/00 description comes from cpc_subclass_name (main-group storage).""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + source_fields = body.get("_source") or [] + if "cpc_subclass_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_subclass_number": "H01M8/00", + "cpc_subclass_name": "Fuel cells Manufacture thereof", + } + } + ] + } + } + if "cpc_class_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_class_number": "H01M", + "cpc_class_name": ( + "PROCESSES OR MEANS, e.g. BATTERIES, FOR THE " + "DIRECT CONVERSION OF CHEMICAL ENERGY INTO " + "ELECTRICAL ENERGY" + ), + } + } + ] + } + } + if "cpc_section_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + } + ] + } + } + return {"hits": {"hits": []}} + + with patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + client = IpcSearchClient() + result = await client.resolve_symbols(["H01M8/00", "H01M 8/00"]) + + for symbol in ("H01M8/00", "H01M 8/00"): + clas = result[symbol] + assert clas.main_group is not None + assert "Fuel cells Manufacture thereof" in clas.main_group + assert clas.subclass is not None + assert clas.subclass.startswith("H01M") + + +@pytest.mark.anyio +async def test_resolve_symbols_keeps_subgroup_and_subclass_roles(): + async def fake_search(*, index, body, cluster): # noqa: ANN001 + source_fields = body.get("_source") or [] + if "cpc_subgroup_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_subgroup_number": "H01M8/083", + "cpc_subgroup_name": "Alkaline fuel cells", + } + } + ] + } + } + if "cpc_group_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_group_number": "H01M8/08", + "cpc_group_name": "Fuel cells with aqueous electrolytes", + } + } + ] + } + } + if "cpc_class_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_class_number": "H01M", + "cpc_class_name": "BATTERIES / FUEL CELLS", + } + } + ] + } + } + if "cpc_section_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + } + ] + } + } + return {"hits": {"hits": []}} + + with patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + client = IpcSearchClient() + subgroup = (await client.resolve_symbols(["H01M8/083"]))["H01M8/083"] + subclass = (await client.resolve_symbols(["H01M"]))["H01M"] + + assert subgroup.subgroup is not None + assert "Alkaline fuel cells" in subgroup.subgroup + assert subclass.subclass is not None + assert subclass.subclass.startswith("H01M") + assert subclass.main_group is None + assert subclass.subgroup is None + + keys_subgroup = parse_ipc_symbol("H01M8/083") + assert keys_subgroup.subgroup == "H01M8/083" + keys_subclass = parse_ipc_symbol("H01M") + assert keys_subclass.subclass == "H01M" + assert keys_subclass.main_group is None -- 2.56.1 From f9b63977ff46419f49a4f05ee5bc5a469eefcdd7 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sun, 19 Jul 2026 15:58:46 +0200 Subject: [PATCH 2/6] Reduce false patent matches for ambiguous authors. --- .../src/main/inse/patents/authors/identity.py | 221 +++++++++++++- .../inse/patents/authors/name_matching.py | 241 ++++++++++++--- .../inse/patents/authors/search_queries.py | 186 +++++++++--- .../authors/test_ipc_openalex_mapping.py | 204 +++++++++++++ .../authors/test_orthosis_family_identity.py | 229 ++++++++++++++ .../main/inse/patents/authors/topic_filter.py | 286 ++++++++++++++---- .../patents/institutions/name_matching.py | 33 +- .../patents/test_elastic_search_client.py | 13 + .../inse/patents/test_institution_matching.py | 47 +++ .../main/inse/patents/test_name_matching.py | 78 +++++ service/src/main/inse/persons/logic.py | 14 +- 11 files changed, 1380 insertions(+), 172 deletions(-) create mode 100644 service/src/main/inse/patents/authors/test_orthosis_family_identity.py diff --git a/service/src/main/inse/patents/authors/identity.py b/service/src/main/inse/patents/authors/identity.py index e3496202..79ab6115 100644 --- a/service/src/main/inse/patents/authors/identity.py +++ b/service/src/main/inse/patents/authors/identity.py @@ -5,14 +5,23 @@ that distinguish one same-named person from another. """ from __future__ import annotations +from dataclasses import dataclass + from inse.models.openalex.author import Author from inse.patents.authors.name_matching import ( first_name_match_kind_for_person, name_matches_person, + tokens_equal, + _family_name_matches, + _given_name_matches, ) -from inse.patents.authors.name_variants import parse_person_name +from inse.patents.authors.name_variants import parse_inventor_name, parse_person_name from inse.patents.common import model -from inse.patents.institutions.name_matching import assignee_matches_institution_name +from inse.patents.common.text_normalization import normalize_name_part, strip_person_titles +from inse.patents.institutions.name_matching import ( + assignee_matches_institution_name, + is_generic_institution_name, +) # Ambiguity is derived purely from data that already exists in the project (the # number of patent hits for the name and the number of same-named authors in the @@ -24,6 +33,33 @@ PATENT_HIT_COUNT_THRESHOLD = 300 OPENALEX_FULL_NAME_COUNT_THRESHOLD = 2 OPENALEX_LAST_NAME_COUNT_THRESHOLD = 100 +_ORG_MARKERS = ( + "llc", + "ltd", + "inc", + "gmbh", + "corp", + "corporation", + "company", + " co.", + "university", + "universit", + "institute", + "institut", + "foundation", + "hospital", + "college", + "limited", + " ag", + "bv", + "plc", + "kg", + "oy", + "sas", + "spa", + "srl", +) + def is_ambiguous_name( display_name: str | None, @@ -95,6 +131,39 @@ def author_institution_names(author: Author) -> list[str]: return names +def author_last_known_institution_names(author: Author) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + for institution in author.last_known_institutions or []: + name = getattr(institution, "display_name", None) + if not name or not name.strip(): + continue + key = name.casefold() + if key in seen: + continue + seen.add(key) + names.append(name.strip()) + return names + + +def author_historical_institution_names(author: Author) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + for affiliation in author.affiliations or []: + institution = getattr(affiliation, "institution", None) + if institution is None: + continue + name = getattr(institution, "display_name", None) + if not name or not name.strip(): + continue + key = name.casefold() + if key in seen: + continue + seen.add(key) + names.append(name.strip()) + return names + + def patent_institution_match( patent: model.PatentEntry, institution_names: list[str], @@ -110,6 +179,108 @@ def patent_institution_match( return False +@dataclass(frozen=True) +class InstitutionMatchDetail: + last_known_institution_match: bool + historical_institution_match: bool + generic_institution_match: bool + last_known_institution_name: str | None = None + historical_institution_name: str | None = None + + @property + def any_institution_match(self) -> bool: + return self.last_known_institution_match or self.historical_institution_match + + +def classify_patent_institution_match( + patent: model.PatentEntry, + author: Author, +) -> InstitutionMatchDetail: + """Separate last-known vs historical institution signals for a patent.""" + last_known_names = author_last_known_institution_names(author) + historical_names = author_historical_institution_names(author) + + last_known_hit: str | None = None + historical_hit: str | None = None + generic_hit = False + + for assignee in patent.assignees or []: + if not assignee: + continue + for name in last_known_names: + if assignee_matches_institution_name(assignee, name): + last_known_hit = last_known_hit or name + if is_generic_institution_name(name): + generic_hit = True + for name in historical_names: + if assignee_matches_institution_name(assignee, name): + historical_hit = historical_hit or name + if is_generic_institution_name(name): + generic_hit = True + + return InstitutionMatchDetail( + last_known_institution_match=last_known_hit is not None, + historical_institution_match=historical_hit is not None, + generic_institution_match=generic_hit, + last_known_institution_name=last_known_hit, + historical_institution_name=historical_hit, + ) + + +def assignee_looks_like_organization(name: str | None) -> bool: + """Heuristic: corporate / institutional assignee strings.""" + if not name or not name.strip(): + return False + lowered = f" {name.casefold()} " + if any(marker in lowered for marker in _ORG_MARKERS): + return True + stripped = name.strip() + if "," not in stripped and stripped.isupper() and " " in stripped and len(stripped) > 8: + return True + return False + + +def _person_names_equivalent(left: str, right: str) -> bool: + """True when two person-name strings refer to the same individual.""" + left_parsed = parse_inventor_name(strip_person_titles(left)) + right_parsed = parse_inventor_name(strip_person_titles(right)) + if left_parsed is None or right_parsed is None: + return normalize_name_part(left) == normalize_name_part(right) + if not _family_name_matches(left_parsed, right_parsed): + return False + if left_parsed.given_names and right_parsed.given_names: + return _given_name_matches(left_parsed, right_parsed) and _given_name_matches( + right_parsed, left_parsed + ) + if left_parsed.given_names or right_parsed.given_names: + return normalize_name_part(left) == normalize_name_part(right) + return tokens_equal(left_parsed.last_name, right_parsed.last_name, allow_initial=False) + + +def assignee_is_inventor_echo(assignee: str, inventors: list[str] | None) -> bool: + """True when a person-like assignee merely repeats an inventor name. + + Typical EPO A1 pattern: ``applicants_name`` copies ``inventors_name``. + """ + if not assignee or not assignee.strip(): + return False + if assignee_looks_like_organization(assignee): + return False + for inventor in inventors or []: + if inventor and _person_names_equivalent(assignee, inventor): + return True + return False + + +def patent_has_inventor_echo_assignee(patent: model.PatentEntry) -> bool: + """True when any person-like assignee is an inventor echo.""" + return any( + assignee_is_inventor_echo(assignee, patent.inventors) + for assignee in (patent.assignees or []) + if assignee + ) + + def patent_personal_assignee_full_match( patent: model.PatentEntry, display_name: str, @@ -123,13 +294,46 @@ def patent_personal_assignee_full_match( return False -def patent_full_personal_identity_match( +def patent_independent_personal_assignee_match( patent: model.PatentEntry, display_name: str, ) -> bool: - """Strong personal identity: full inventor name and full personal assignee.""" + """Full personal assignee that is not a company and not an inventor echo. + + An EPO applicant that only repeats an inventor name does not count as an + independent identity signal. + """ + if not display_name or not display_name.strip(): + return False + for assignee in patent.assignees or []: + if not assignee: + continue + if assignee_looks_like_organization(assignee): + continue + if first_name_match_kind_for_person(assignee, display_name) != "full": + continue + if assignee_is_inventor_echo(assignee, patent.inventors): + continue + return True + return False + + +def patent_full_personal_identity_match( + patent: model.PatentEntry, + display_name: str, + *, + is_ambiguous: bool = False, +) -> bool: + """Strong personal identity: full inventor name plus personal assignee. + + For ambiguous author names the assignee must be an *independent* personal + applicant (not merely an inventor name echoed into EPO ``applicants_name``). + For unique names, a sole inventor who is also the applicant may still count. + """ if best_name_match_kind(patent, display_name) != "full": return False + if is_ambiguous: + return patent_independent_personal_assignee_match(patent, display_name) return patent_personal_assignee_full_match(patent, display_name) @@ -152,14 +356,15 @@ def patent_personal_assignee_match( def best_name_match_kind(patent: model.PatentEntry, display_name: str) -> str: - """Best given-name match across all inventors: 'full' > 'initial' > 'none'.""" + """Best given-name match across inventors: full > initial > partial > none.""" + rank = {"none": 0, "partial": 1, "initial": 2, "full": 3} best = "none" for inventor in patent.inventors: if not inventor: continue kind = first_name_match_kind_for_person(inventor, display_name) - if kind == "full": + if rank.get(kind, 0) > rank.get(best, 0): + best = kind + if best == "full": return "full" - if kind == "initial": - best = "initial" return best diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index 3934e465..e6132d47 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -67,20 +67,50 @@ def inventor_first_token(inventor_name: str) -> str: return parts[0] if parts else "" +def _is_standalone_single_letter(phrase: str) -> bool: + """True when the whole phrase collapses to a single alphabetic character.""" + cleaned = normalize_name_part(phrase) + return len(cleaned) == 1 and cleaned.isalpha() + + +def _given_starts_compound(given: str, compound_last: str | None) -> bool: + if not compound_last: + return False + given_norm = normalize_name_part(given) + compound_first = normalize_name_part(compound_last.split()[0]) + return bool(given_norm) and given_norm == compound_first + + def inventor_search_phrases(display_name: str) -> list[str]: + """Build inventor search phrases for EPO/USPTO queries. + + Phrases always include a family-name token. Standalone single-letter + phrases (``D``, ``S``, …) are never emitted. Multi-word phrases are not + run through whole-phrase vowel transliteration (which produced forms like + ``Daen`` / ``Geoerge``). Compound-last combinations use leading givens + only so ``Dan J.`` + ``J. Stein`` does not become ``Dan J. J. Stein``. + """ parsed = parse_person_name(display_name) if parsed is None: return [] if parsed.is_single_token: - return search_name_variants(parsed.last_name) + return [ + variant + for variant in search_name_variants( + parsed.last_name, + include_initial=False, + allow_vowel_expansion=False, + ) + if not _is_standalone_single_letter(variant) + ] seen: set[str] = set() phrases: list[str] = [] def _add(phrase: str) -> None: phrase = phrase.strip() - if not phrase: + if not phrase or _is_standalone_single_letter(phrase): return key = phrase.casefold() if key in seen: @@ -92,43 +122,91 @@ def inventor_search_phrases(display_name: str) -> list[str]: last_name = parsed.last_name compound_last = parsed.compound_last_name full_given = " ".join(given_names) + # Tokens that are not part of the compound surname (avoids doubled middles). + leading_givens = ( + given_names[:-1] + if compound_last and len(given_names) >= 2 + else given_names + ) + leading_full = " ".join(leading_givens) - _add(f"{full_given} {last_name}") - if compound_last and compound_last != last_name: - _add(f"{full_given} {compound_last}") + last_name_variants = search_name_variants( + last_name, + include_initial=False, + allow_vowel_expansion=False, + ) + compound_variants = ( + search_name_variants( + compound_last, + include_initial=False, + allow_vowel_expansion=False, + ) + if compound_last and compound_last != last_name + else [] + ) + + def _add_with_last_variants(prefix: str, *, use_compound: bool = False) -> None: + if not prefix.strip(): + return + variants = compound_variants if use_compound else last_name_variants + for last_variant in variants: + _add(f"{prefix} {last_variant}") + + _add_with_last_variants(full_given) + if compound_last and compound_last != last_name and leading_full: + _add_with_last_variants(leading_full, use_compound=True) for given_name in given_names: - _add(f"{given_name} {last_name}") - if compound_last and compound_last != last_name: - _add(f"{given_name} {compound_last}") + for given_variant in search_name_variants( + given_name, + include_initial=False, + allow_vowel_expansion=False, + ): + _add_with_last_variants(given_variant) + if ( + compound_last + and compound_last != last_name + and not _given_starts_compound(given_name, compound_last) + ): + _add_with_last_variants(given_variant, use_compound=True) + + # Initial + last name (e.g. "D Stein", "D. Stein") — never bare "D". + initial = _initial_letter(given_name) + if initial is None: + initial_norm = normalize_name_part(given_name) + if initial_norm: + initial = initial_norm[0] + if initial: + _add_with_last_variants(initial.upper()) + _add_with_last_variants(f"{initial.upper()}.") initials = _initials_from_tokens(given_names) + leading_initials = _initials_from_tokens(leading_givens) if initials: - _add(f"{initials} {last_name}") - if compound_last and compound_last != last_name: - _add(f"{initials} {compound_last}") + # Combined initials only with the simple last name (DJ Stein). + # With compound last they double the middle token (DJ J. Stein). + _add_with_last_variants(initials) dotted = ".".join(char for char in initials) + "." - _add(f"{dotted} {last_name}") - if compound_last and compound_last != last_name: - _add(f"{dotted} {compound_last}") + _add_with_last_variants(dotted) + if compound_last and compound_last != last_name and leading_initials: + _add_with_last_variants(leading_initials, use_compound=True) + leading_dotted = ".".join(char for char in leading_initials) + "." + _add_with_last_variants(leading_dotted, use_compound=True) - _add(f"{last_name}, {full_given}") - for given_name in given_names: - _add(f"{last_name}, {given_name}") - if compound_last and compound_last != last_name: - _add(f"{compound_last}, {full_given}") + for last_variant in last_name_variants: + _add(f"{last_variant}, {full_given}") + for given_name in given_names: + for given_variant in search_name_variants( + given_name, + include_initial=False, + allow_vowel_expansion=False, + ): + _add(f"{last_variant}, {given_variant}") + if compound_last and compound_last != last_name and leading_full: + for compound_variant in compound_variants: + _add(f"{compound_variant}, {leading_full}") - expanded: list[str] = [] - expanded_seen: set[str] = set() - for phrase in phrases: - for variant in search_name_variants(phrase): - key = variant.casefold() - if key in expanded_seen: - continue - expanded_seen.add(key) - expanded.append(variant) - - return expanded + return phrases def name_matches_person(inventor_name: str, person_display_name: str) -> bool: @@ -153,14 +231,48 @@ def first_name_match_kind_for_person( ) -> str: if not name_matches_person(inventor_name, person_display_name): return "none" - if _given_names_full_match( - parse_person_name(person_display_name), - parse_inventor_name(inventor_name), - ): + author = parse_person_name(person_display_name) + inventor = parse_inventor_name(strip_person_titles(inventor_name)) + if author is None or inventor is None: + return "none" + if _is_partial_given_name_match(author, inventor): + return "partial" + if _given_names_full_match(author, inventor): return "full" return "initial" +def _is_partial_given_name_match( + author: ParsedPersonName, + inventor: ParsedPersonName, +) -> bool: + """True when the author has extra full given names absent from the inventor. + + Example: OpenAlex ``George Davey Smith`` vs inventor ``SMITH, George``. + Initial-only inventor forms (``G. D. Smith``) are *not* partial — they stay + ``initial``. + """ + author_full = [g for g in author.given_names if _initial_letter(g) is None] + if len(author_full) <= 1: + return False + + inventor_has_any_full = any( + _initial_letter(g) is None for g in inventor.given_names + ) + if not inventor_has_any_full: + # Initials-only inventor → handled as initial, not partial. + return False + + for author_given in author_full[1:]: + covered = any( + tokens_equal(author_given, inventor_given, allow_initial=True) + for inventor_given in inventor.given_names + ) + if not covered: + return True + return False + + def first_name_match_kind( inventor_name: str, first_name: str, @@ -174,20 +286,66 @@ def first_name_match_kind( return first_name_match_kind_for_person(inventor_name, last_name) -def search_name_variants(value: str | None) -> list[str]: +def search_name_variants( + value: str | None, + *, + include_initial: bool = True, + allow_vowel_expansion: bool = True, +) -> list[str]: + """Return spelling/transliteration variants of a name token or short phrase. + + Whole-phrase vowel transliteration and leading-initial extraction are only + applied to single-token values. Multi-word values keep the original form + plus a diacritic-stripped token join — never ``Daen J Stein``-style forms + or a bare first letter of the entire phrase. + + ``allow_vowel_expansion`` controls patent-style ``u→ue`` / ``a→ae`` rewrites. + Inventor search phrases disable it to avoid implausible forms such as + ``Daen`` / ``Thoempsoen``. + """ if not value or not value.strip(): return [] + stripped = value.strip() + tokens = [part for part in stripped.replace(",", " ").split() if part] + is_multi_token = len(tokens) > 1 + seen: set[str] = set() ordered: list[str] = [] def _add(candidate: str) -> None: + candidate = candidate.strip() + if not candidate: + return key = candidate.casefold() - if candidate.strip() and key not in seen: + if key not in seen: seen.add(key) - ordered.append(candidate.strip()) + ordered.append(candidate) - _add(value.strip()) + _add(stripped) + + if is_multi_token: + # Diacritic strip per token only — no patent vowel expansion on phrases. + stripped_tokens: list[str] = [] + for token in tokens: + normalized_token = normalize_name_part(token) + stripped_tokens.append( + normalized_token.title() if normalized_token else token + ) + joined = " ".join(stripped_tokens) + if "," in stripped: + # Preserve a simple "Last, Given" shape when present. + parts = [part.strip() for part in stripped.split(",", 1)] + if len(parts) == 2 and parts[0] and parts[1]: + left = " ".join( + normalize_name_part(t).title() or t for t in parts[0].split() + ) + right = " ".join( + normalize_name_part(t).title() or t for t in parts[1].split() + ) + _add(f"{left}, {right}") + _add(joined) + return ordered normalized = normalize_name_part(value) if normalized: @@ -196,10 +354,11 @@ def search_name_variants(value: str | None) -> list[str]: for variant in name_token_variants(value): _add(variant.title()) - for variant in patent_transliteration_expansions(normalized): - _add(variant.title()) + if allow_vowel_expansion: + for variant in patent_transliteration_expansions(normalized): + _add(variant.title()) - if normalized and len(normalized) > 1: + if include_initial and normalized and len(normalized) > 1: _add(normalized[0].upper()) return ordered diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py index af67bf1d..e87c6583 100644 --- a/service/src/main/inse/patents/authors/search_queries.py +++ b/service/src/main/inse/patents/authors/search_queries.py @@ -1,13 +1,43 @@ """Elasticsearch query builders for inventor-based patent search.""" from typing import Any -from inse.patents.authors.name_matching import inventor_search_phrases, search_name_variants -from inse.patents.authors.name_variants import parse_person_name +from inse.patents.authors.name_matching import ( + inventor_search_phrases, + search_name_variants, +) +from inse.patents.authors.name_variants import _initials_from_tokens, parse_person_name from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE +from inse.patents.common.text_normalization import normalize_name_part -def _match_name_field(field: str, name: str) -> dict[str, Any]: - variants = search_name_variants(name) +def _token_initial(token: str) -> str | None: + normalized = normalize_name_part(token) + if len(normalized) == 1 and normalized.isalpha(): + return normalized + if normalized: + return normalized[0] + return None + + +def _dedupe_preserve(values: list[str]) -> list[str]: + seen: set[str] = set() + ordered: list[str] = [] + for value in values: + key = value.casefold() + if not value or key in seen: + continue + seen.add(key) + ordered.append(value) + return ordered + + +def _match_name_field( + field: str, + name: str, + *, + include_initial: bool = False, +) -> dict[str, Any]: + variants = search_name_variants(name, include_initial=include_initial) if len(variants) <= 1: return {"match": {field: variants[0] if variants else name}} return { @@ -18,15 +48,98 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]: } -def _match_any_phrase_field(field: str, phrases: list[str]) -> dict[str, Any]: - if not phrases: +def _family_name_variants(parsed) -> list[str]: + variants: list[str] = [] + variants.extend( + search_name_variants( + parsed.last_name, + include_initial=False, + allow_vowel_expansion=False, + ) + ) + if parsed.compound_last_name and parsed.compound_last_name != parsed.last_name: + variants.extend( + search_name_variants( + parsed.compound_last_name, + include_initial=False, + allow_vowel_expansion=False, + ) + ) + return _dedupe_preserve(variants) + + +def _given_name_query_variants(parsed) -> list[str]: + """Given-name / initial tokens that may appear on the inventor record. + + Single-letter initials are allowed here because the ES query always + requires a family-name match in the same nested inventor document. + """ + variants: list[str] = [] + for given in parsed.given_names: + variants.extend( + search_name_variants( + given, + include_initial=True, + allow_vowel_expansion=False, + ) + ) + initial = _token_initial(given) + if initial: + variants.append(initial.upper()) + variants.append(f"{initial.upper()}.") + + initials = _initials_from_tokens(list(parsed.given_names)) + if initials: + variants.append(initials) + variants.append(".".join(char for char in initials) + ".") + + return _dedupe_preserve(variants) + + +def _inventor_identity_query(field: str, display_name: str) -> dict[str, Any]: + """Require family name + at least one given/initial token on the same inventor. + + Phrase matches are added as optional ``should`` clauses for scoring only. + A bare given name or initial never searches without the family name. + """ + parsed = parse_person_name(display_name) + if parsed is None: return {"match_none": {}} - if len(phrases) == 1: - return {"match": {field: phrases[0]}} + + if parsed.is_single_token: + return _match_name_field(field, parsed.last_name, include_initial=False) + + family_variants = _family_name_variants(parsed) + given_variants = _given_name_query_variants(parsed) + if not family_variants or not given_variants: + return {"match_none": {}} + + phrases = inventor_search_phrases(display_name) + should_boost: list[dict[str, Any]] = [ + {"match_phrase": {field: phrase}} for phrase in phrases + ] + return { "bool": { - "should": [{"match": {field: phrase}} for phrase in phrases], - "minimum_should_match": 1, + "must": [ + { + "bool": { + "should": [ + {"match": {field: variant}} for variant in family_variants + ], + "minimum_should_match": 1, + } + }, + { + "bool": { + "should": [ + {"match": {field: variant}} for variant in given_variants + ], + "minimum_should_match": 1, + } + }, + ], + "should": should_boost, } } @@ -41,30 +154,15 @@ class InventorSearchQueries: if first_name and display_name and " " not in display_name.strip(): display_name = f"{first_name} {display_name}".strip() - parsed = parse_person_name(display_name) - if parsed is None: - query = {"match_none": {}} - elif parsed.is_single_token: - query = { - "nested": { - "path": "inventors_name_nested", - "query": _match_name_field( - "inventors_name_nested.inventor", - parsed.last_name, - ), - } - } - else: - phrases = inventor_search_phrases(display_name) - query = { - "nested": { - "path": "inventors_name_nested", - "query": _match_any_phrase_field( - "inventors_name_nested.inventor", - phrases, - ), - } + query = { + "nested": { + "path": "inventors_name_nested", + "query": _inventor_identity_query( + "inventors_name_nested.inventor", + display_name, + ), } + } return { "size": size, @@ -144,24 +242,12 @@ class InventorSearchQueries: if first_name and display_name and " " not in display_name.strip(): display_name = f"{first_name} {display_name}".strip() - parsed = parse_person_name(display_name) - if parsed is None: - query = {"match_none": {}} - elif parsed.is_single_token: - query = { - "nested": { - "path": "inventors", - "query": _match_name_field("inventors.name", parsed.last_name), - } - } - else: - phrases = inventor_search_phrases(display_name) - query = { - "nested": { - "path": "inventors", - "query": _match_any_phrase_field("inventors.name", phrases), - } + query = { + "nested": { + "path": "inventors", + "query": _inventor_identity_query("inventors.name", display_name), } + } return { "size": size, diff --git a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py index c4b82d1a..3972cb2a 100644 --- a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py +++ b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py @@ -315,6 +315,210 @@ def test_filter_rejects_initial_only_personal_assignee_without_topic_match() -> assert filtered == [] +def test_filter_keeps_ambiguous_on_last_known_institution_without_topic() -> None: + from inse.models.openalex.dehydrated_institution import DehydratedInstitution + from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner + + author = _author_with_topic( + "https://openalex.org/T10158", + "Cancer Immunotherapy and Biomarkers", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + author.display_name = "Dirk Schadendorf" + author.last_known_institutions = [ + DehydratedInstitution(display_name="University of Duisburg-Essen"), + ] + patent = model.PatentEntry( + patent_id="EP2932264", + source="EPO", + title="NOVEL MHC-INDEPENDENT TUMOR-ASSOCIATED ANTIGENS", + inventors=["SCHADENDORF, Dirk"], + assignees=["Universität Duisburg-Essen"], + ipc=["G01N 33/50"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Unrelated Topic", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/11", + field_name="Other", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + patent_topic_map={patent_map_key(patent): [unrelated]}, + ) + assert len(filtered) == 1 + assert filtered[0].last_known_institution_match is True + assert filtered[0].keep_reason == "last_known_institution" + + +def test_filter_rejects_ambiguous_historical_institution_alone() -> None: + from inse.models.openalex.dehydrated_institution import DehydratedInstitution + from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner + + author = _author_with_topic( + "https://openalex.org/T11111", + "Advanced Neuroimaging Techniques and Applications", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + author.display_name = "Paul M. Thompson" + author.last_known_institutions = [ + DehydratedInstitution(display_name="University of California, Riverside"), + ] + author.affiliations = [ + AuthorAffiliationsInner( + institution=DehydratedInstitution(display_name="Southwest Research Institute"), + years=[2008, 2014], + ) + ] + patent = model.PatentEntry( + patent_id="US08987496", + source="USPTO", + title="Point of use generation of amyl nitrite", + inventors=["Paul M. Thompson"], + assignees=["Southwest Research Institute"], + ipc=["C07C 203/04"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Organic Chemistry Methods", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/16", + field_name="Chemistry", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + patent_topic_map={patent_map_key(patent): [unrelated]}, + ) + assert filtered == [] + + +def test_filter_rejects_ambiguous_generic_historical_institution() -> None: + from inse.models.openalex.dehydrated_institution import DehydratedInstitution + from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner + + author = _author_with_topic( + "https://openalex.org/T11111", + "Advanced Neuroimaging Techniques and Applications", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + author.display_name = "Paul M. Thompson" + author.affiliations = [ + AuthorAffiliationsInner( + institution=DehydratedInstitution(display_name="University Medical Center"), + years=[2015, 2019], + ) + ] + patent = model.PatentEntry( + patent_id="US10667940", + source="USPTO", + title="Orthosis for deformity correction", + inventors=["Paul M. Thompson"], + assignees=["Green Sun Medical, LLC"], + ipc=["A61F 5/00"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Orthopaedic implants and arthroplasty", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/27", + field_name="Medicine", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + patent_topic_map={patent_map_key(patent): [unrelated]}, + ) + assert filtered == [] + + +def test_filter_keeps_historical_with_confirmed_co_inventors() -> None: + from inse.models.openalex.dehydrated_institution import DehydratedInstitution + from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner + + author = _author_with_topic( + "https://openalex.org/T10158", + "Cancer Immunotherapy and Biomarkers", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + author.display_name = "Dirk Schadendorf" + author.affiliations = [ + AuthorAffiliationsInner( + institution=DehydratedInstitution( + display_name="Johannes Gutenberg University Mainz" + ), + years=[2015], + ) + ] + topic_match = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T10158", + topic_display_name="Cancer Immunotherapy and Biomarkers", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + field_name="Medicine", + ) + secure = model.PatentEntry( + patent_id="US10987413", + source="USPTO", + title="MHC-independent tumor-associated antigens", + inventors=[ + "Dirk Schadendorf", + "Annette Paschen", + "Silke Lubcke", + "Martina Fatho", + ], + assignees=["BioNTech RNA Pharmaceuticals GmbH"], + ipc=["A61K 39/00"], + ) + historical_only = model.PatentEntry( + patent_id="EP2932264", + source="EPO", + title="NOVEL MHC-INDEPENDENT TUMOR-ASSOCIATED ANTIGENS", + inventors=[ + "SCHADENDORF, Dirk", + "PASCHEN, Anette", + "LUBCKE, Silke", + "FATHO, Martina", + ], + assignees=["Universitätsmedizin der Johannes Gutenberg-Universität Mainz"], + ipc=["G01N 33/50"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Unrelated", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/11", + field_name="Other", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [secure, historical_only], + author, + is_ambiguous=True, + patent_topic_map={ + patent_map_key(secure): [topic_match], + patent_map_key(historical_only): [unrelated], + }, + ) + kept_ids = {item.patent.patent_id for item in filtered} + assert "US10987413" in kept_ids + assert "EP2932264" in kept_ids + hist = next(item for item in filtered if item.patent.patent_id == "EP2932264") + assert hist.keep_reason == "historical_institution+confirmed_co_inventors" + + def test_custom_mapping_table() -> None: custom = _custom_mapping() author = Author( diff --git a/service/src/main/inse/patents/authors/test_orthosis_family_identity.py b/service/src/main/inse/patents/authors/test_orthosis_family_identity.py new file mode 100644 index 00000000..c3b0f3ec --- /dev/null +++ b/service/src/main/inse/patents/authors/test_orthosis_family_identity.py @@ -0,0 +1,229 @@ +"""Tests for inventor-applicant echo and independent personal assignee signals.""" +from __future__ import annotations + +from inse.models.openalex.author import Author +from inse.models.openalex.dehydrated_institution import DehydratedInstitution +from inse.models.openalex.work_topic import WorkTopic +from inse.models.openalex.work_topic_domain import WorkTopicDomain +from inse.models.openalex.work_topic_field import WorkTopicField +from inse.models.openalex.work_topic_subfield import WorkTopicSubfield +from inse.patents.authors import ipc_openalex_mapping as mapping_module +from inse.patents.authors.identity import ( + assignee_is_inventor_echo, + patent_full_personal_identity_match, + patent_independent_personal_assignee_match, + patent_personal_assignee_full_match, + patent_personal_assignee_match, +) +from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.common import model +from inse.patents.common.parsing import patent_map_key + + +def _author(topic_id: str, display_name: str, *, topic_name: str = "Topic") -> Author: + return Author( + display_name=display_name, + topics=[ + WorkTopic( + id=topic_id, + display_name=topic_name, + score=1.0, + subfield=WorkTopicSubfield( + id="https://openalex.org/subfields/2705", + display_name="Subfield", + ), + var_field=WorkTopicField( + id="https://openalex.org/fields/27", + display_name="Medicine", + ), + domain=WorkTopicDomain( + id="https://openalex.org/domains/4", + display_name="Health Sciences", + ), + ) + ], + ) + + +def test_assignee_is_inventor_echo_for_epo_applicants() -> None: + inventors = ["Thompson, Matthew", "Thompson, Paul M."] + assert assignee_is_inventor_echo("Thompson, Paul M.", inventors) is True + assert assignee_is_inventor_echo("Thompson, Matthew", inventors) is True + assert assignee_is_inventor_echo("Paul M. Thompson", inventors) is True + + +def test_echo_does_not_create_independent_personal_assignee() -> None: + display = "Paul M. Thompson" + patent = model.PatentEntry( + patent_id="EP3094287", + source="EPO", + inventors=["Thompson, Matthew", "Thompson, Paul M."], + assignees=["Thompson, Matthew", "Thompson, Paul M."], + ) + assert patent_personal_assignee_full_match(patent, display) is True + assert patent_independent_personal_assignee_match(patent, display) is False + assert ( + patent_full_personal_identity_match(patent, display, is_ambiguous=True) is False + ) + + +def test_company_assignee_is_not_personal_or_independent() -> None: + display = "Paul M. Thompson" + patent = model.PatentEntry( + patent_id="US10667940", + source="USPTO", + inventors=["Matthew Thompson", "Paul M. Thompson"], + assignees=["Green Sun Medical, LLC"], + ) + assert patent_personal_assignee_match(patent, display) is False + assert patent_personal_assignee_full_match(patent, display) is False + assert patent_independent_personal_assignee_match(patent, display) is False + assert patent_full_personal_identity_match(patent, display, is_ambiguous=True) is False + + +def test_independent_personal_assignee_not_in_inventor_list() -> None: + display = "Paul M. Thompson" + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + inventors=["Other, Inventor"], + assignees=["Thompson, Paul M."], + ) + assert assignee_is_inventor_echo("Thompson, Paul M.", patent.inventors) is False + assert patent_independent_personal_assignee_match(patent, display) is True + + +def test_unique_name_still_allows_inventor_as_applicant() -> None: + """Non-ambiguous authors may keep inventor==applicant as personal identity.""" + display = "Pedro José Marrón" + patent = model.PatentEntry( + patent_id="EP1542159", + source="EPO", + inventors=["Marron, Pedro José"], + assignees=["Marron, Pedro José, Dr."], + ) + assert patent_full_personal_identity_match(patent, display, is_ambiguous=False) is True + + +def test_filter_drops_ep3094287_for_ambiguous_thompson() -> None: + author = _author("https://openalex.org/T11111", "Paul M. Thompson") + author.last_known_institutions = [ + DehydratedInstitution(display_name="University of California, Riverside"), + ] + ep = model.PatentEntry( + patent_id="EP3094287", + source="EPO", + title="ORTHOSIS FOR DEFORMITY CORRECTION", + inventors=["Thompson, Matthew", "Thompson, Paul M."], + assignees=["Thompson, Matthew", "Thompson, Paul M."], + ipc=["A61F 5/00"], + ) + us = model.PatentEntry( + patent_id="US10667940", + source="USPTO", + title="Orthosis for deformity correction", + inventors=["Matthew Thompson", "Paul M. Thompson"], + assignees=["Green Sun Medical, LLC"], + ipc=["A61F 5/00"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Orthopaedic implants and arthroplasty", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/27", + field_name="Medicine", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [ep, us], + author, + is_ambiguous=True, + patent_topic_map={ + patent_map_key(ep): [unrelated], + patent_map_key(us): [unrelated], + }, + ) + assert filtered == [] + + +def test_filter_schadendorf_still_three() -> None: + author = _author( + "https://openalex.org/T10158", + "Dirk Schadendorf", + topic_name="Cancer Immunotherapy and Biomarkers", + ) + author.last_known_institutions = [ + DehydratedInstitution(display_name="University of Duisburg-Essen"), + ] + topic = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T10158", + topic_display_name="Cancer Immunotherapy and Biomarkers", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + field_name="Medicine", + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Unrelated", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/11", + field_name="Other", + ) + patents = [ + model.PatentEntry( + patent_id="US10987413", + source="USPTO", + inventors=["Dirk Schadendorf"], + assignees=["BioNTech RNA Pharmaceuticals GmbH"], + ipc=["A61K 39/00"], + ), + model.PatentEntry( + patent_id="US09861688", + source="USPTO", + inventors=["Dirk Schadendorf"], + assignees=["Universitaet Duisburg-Essen"], + ipc=["A61K 35/17"], + ), + model.PatentEntry( + patent_id="EP2932264", + source="EPO", + inventors=["SCHADENDORF, Dirk"], + assignees=["Universität Duisburg-Essen"], + ipc=["G01N 33/50"], + ), + ] + filtered = filter_patents_by_ipc_topic_mapping( + patents, + author, + is_ambiguous=True, + patent_topic_map={ + patent_map_key(patents[0]): [topic], + patent_map_key(patents[1]): [topic], + patent_map_key(patents[2]): [unrelated], + }, + ) + assert len(filtered) == 3 + + +def test_filter_shoji_stays_zero() -> None: + author = _author("https://openalex.org/T10346", "M. Shoji") + patent = model.PatentEntry( + patent_id="EP0023413", + source="EPO", + inventors=["Shoji, M."], + assignees=["Western Electric Company, Incorporated"], + ipc=["G06F 11/26"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Unrelated", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/17", + field_name="Computer Science", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + patent_topic_map={patent_map_key(patent): [unrelated]}, + ) + assert filtered == [] diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py index 79ab8e20..3eb31701 100644 --- a/service/src/main/inse/patents/authors/topic_filter.py +++ b/service/src/main/inse/patents/authors/topic_filter.py @@ -5,8 +5,9 @@ from dataclasses import dataclass from inse.models.openalex.author import Author from inse.patents.authors.identity import ( + best_name_match_kind, + classify_patent_institution_match, patent_full_personal_identity_match, - patent_institution_match, patent_personal_assignee_match, ) from inse.patents.authors.ipc_openalex_mapping import ( @@ -21,6 +22,7 @@ from inse.patents.authors.ipc_openalex_mapping import ( ) from inse.patents.common import model from inse.patents.common.parsing import patent_map_key +from inse.patents.common.text_normalization import normalize_name_part @dataclass(frozen=True) @@ -30,6 +32,11 @@ class TopicFilterResult: matched_via_mapping: bool institution_match: bool personal_assignee_match: bool + last_known_institution_match: bool = False + historical_institution_match: bool = False + generic_institution_match: bool = False + name_match_kind: str = "none" + keep_reason: str = "" def _author_has_topic_profile(author: Author) -> bool: @@ -64,6 +71,77 @@ def _resolve_patent_topics( return resolve_mapped_topics_for_patent(patent, mapping) +def _inventor_token_set(patent: model.PatentEntry) -> set[str]: + tokens: set[str] = set() + for inventor in patent.inventors or []: + if not inventor: + continue + normalized = normalize_name_part(inventor).replace("-", " ") + for token in normalized.split(): + if len(token) >= 3: + tokens.add(token) + return tokens + + +def _shares_confirmed_co_inventors( + patent: model.PatentEntry, + secure_co_inventor_tokens: set[str], + *, + author_display_name: str, + min_shared: int = 2, +) -> bool: + """True when patent shares enough co-inventor tokens with securely kept patents.""" + if not secure_co_inventor_tokens: + return False + author_tokens = { + t + for t in normalize_name_part(author_display_name).replace("-", " ").split() + if len(t) >= 3 + } + patent_tokens = _inventor_token_set(patent) - author_tokens + shared = patent_tokens & secure_co_inventor_tokens + return len(shared) >= min_shared + + +def _shares_application_family( + patent: model.PatentEntry, + secure_patents: list[model.PatentEntry], +) -> bool: + app = (patent.application_number or "").strip() + if not app: + return False + for other in secure_patents: + other_app = (other.application_number or "").strip() + if other_app and other_app == app and other.patent_id != patent.patent_id: + return True + return False + + +def _result( + patent: model.PatentEntry, + *, + matched_via_mapping: bool, + personal_assignee_match: bool, + inst, + name_match_kind: str, + keep_reason: str, +) -> TopicFilterResult: + return TopicFilterResult( + patent=patent, + decision="keep", + matched_via_mapping=matched_via_mapping, + institution_match=( + inst.last_known_institution_match or inst.historical_institution_match + ), + personal_assignee_match=personal_assignee_match, + last_known_institution_match=inst.last_known_institution_match, + historical_institution_match=inst.historical_institution_match, + generic_institution_match=inst.generic_institution_match, + name_match_kind=name_match_kind, + keep_reason=keep_reason, + ) + + def filter_patents_by_ipc_topic_mapping( patents: list[model.PatentEntry], author: Author, @@ -76,38 +154,23 @@ def filter_patents_by_ipc_topic_mapping( When ``patent_topic_map`` is provided (from the ``patents_openalex_keywords`` index via :class:`PatentOpenAlexMappingResolver`), that mapping is the primary - signal: patents must share a topic or subfield with the author, unless the - assignee matches one of the author's institutions. + signal. For ambiguous author names, last-known institutions are strong but + historical affiliations alone are not (variant D). """ table = mapping if mapping is not None else load_ipc_openalex_mapping() using_keywords_index = patent_topic_map is not None - institution_names = [ - name - for institution in author.last_known_institutions or [] - if (name := getattr(institution, "display_name", None)) - ] - for affiliation in author.affiliations or []: - institution = getattr(affiliation, "institution", None) - if institution is not None and (name := getattr(institution, "display_name", None)): - institution_names.append(name) - display_name = author.display_name or "" - filtered: list[TopicFilterResult] = [] + evaluated: list[tuple[model.PatentEntry, dict]] = [] for patent in patents: - institution_match = patent_institution_match(patent, institution_names) - personal_assignee_match = patent_personal_assignee_match(patent, display_name) - if using_keywords_index: - if is_ambiguous: - strong_identity = institution_match - else: - strong_identity = institution_match or patent_full_personal_identity_match( - patent, - display_name, - ) - else: - strong_identity = institution_match or personal_assignee_match - + inst = classify_patent_institution_match(patent, author) + personal_assignee = patent_personal_assignee_match(patent, display_name) + full_identity = patent_full_personal_identity_match( + patent, + display_name, + is_ambiguous=is_ambiguous, + ) + name_kind = best_name_match_kind(patent, display_name) mapped_topics = _resolve_patent_topics(patent, table, patent_topic_map) if using_keywords_index: @@ -125,49 +188,128 @@ def filter_patents_by_ipc_topic_mapping( else: matched_via_mapping = patent_topics_match_author(patent, author, table) - if strong_identity: - filtered.append( - TopicFilterResult( - patent=patent, - decision="keep", - matched_via_mapping=matched_via_mapping, - institution_match=institution_match, - personal_assignee_match=personal_assignee_match, - ) - ) - continue - - if matched_via_mapping: - filtered.append( - TopicFilterResult( - patent=patent, - decision="keep", - matched_via_mapping=True, - institution_match=False, - personal_assignee_match=False, - ) - ) - continue - - if using_keywords_index: - continue - - if is_ambiguous: - continue - - if _topic_conflict(mapped_topics, author): - continue - - filtered.append( - TopicFilterResult( - patent=patent, - decision="keep", - matched_via_mapping=matched_via_mapping, - institution_match=False, - personal_assignee_match=False, + evaluated.append( + ( + patent, + { + "inst": inst, + "personal_assignee": personal_assignee, + "full_identity": full_identity, + "name_kind": name_kind, + "matched_via_mapping": matched_via_mapping, + "mapped_topics": mapped_topics, + }, ) ) + filtered: list[TopicFilterResult] = [] + secure_patents: list[model.PatentEntry] = [] + + def _keep(patent: model.PatentEntry, meta: dict, reason: str) -> None: + filtered.append( + _result( + patent, + matched_via_mapping=meta["matched_via_mapping"], + personal_assignee_match=meta["personal_assignee"], + inst=meta["inst"], + name_match_kind=meta["name_kind"], + keep_reason=reason, + ) + ) + secure_patents.append(patent) + + # Pass 1: strong signals (topic, last-known non-generic, full personal identity) + remaining: list[tuple[model.PatentEntry, dict]] = [] + for patent, meta in evaluated: + inst = meta["inst"] + if meta["matched_via_mapping"]: + _keep(patent, meta, "strict_topic_match") + continue + + if using_keywords_index and is_ambiguous: + if ( + inst.last_known_institution_match + and not is_generic_only_last_known(inst) + ): + _keep(patent, meta, "last_known_institution") + continue + if meta["full_identity"] and meta["name_kind"] == "full": + _keep(patent, meta, "full_personal_identity") + continue + remaining.append((patent, meta)) + continue + + # Non-ambiguous or legacy mapping path + if using_keywords_index: + if inst.last_known_institution_match and not is_generic_only_last_known(inst): + _keep(patent, meta, "last_known_institution") + continue + if inst.historical_institution_match and not inst.generic_institution_match: + _keep(patent, meta, "historical_institution") + continue + if meta["full_identity"]: + _keep(patent, meta, "full_personal_identity") + continue + # No strong identity and no topic → drop when keywords index is used + continue + + # Legacy non-keywords path + if inst.any_institution_match or meta["personal_assignee"]: + _keep( + patent, + meta, + "institution_or_personal_assignee", + ) + continue + if is_ambiguous: + continue + if _topic_conflict(meta["mapped_topics"], author): + continue + _keep(patent, meta, "legacy_no_conflict") + + if not (using_keywords_index and is_ambiguous): + filtered.sort( + key=lambda item: ( + not item.matched_via_mapping, + not (item.institution_match or item.personal_assignee_match), + item.patent.publication_date or "", + ), + reverse=False, + ) + return filtered + + # Pass 2 (ambiguous + keywords): historical only with corroboration + author_tokens = { + t + for t in normalize_name_part(display_name).replace("-", " ").split() + if len(t) >= 3 + } + secure_co_inventor_tokens: set[str] = set() + for secure in secure_patents: + secure_co_inventor_tokens |= _inventor_token_set(secure) - author_tokens + + for patent, meta in remaining: + inst = meta["inst"] + if not inst.historical_institution_match: + continue + if inst.generic_institution_match and not inst.last_known_institution_match: + # Generic historical affiliation alone is never enough. + continue + # partial_name + historical alone is not enough (requires corroboration below) + if meta["matched_via_mapping"]: + _keep(patent, meta, "historical_institution+strict_topic_match") + continue + if _shares_application_family(patent, secure_patents): + _keep(patent, meta, "historical_institution+confirmed_family") + continue + if _shares_confirmed_co_inventors( + patent, + secure_co_inventor_tokens, + author_display_name=display_name, + ): + _keep(patent, meta, "historical_institution+confirmed_co_inventors") + continue + filtered.sort( key=lambda item: ( not item.matched_via_mapping, @@ -179,6 +321,16 @@ def filter_patents_by_ipc_topic_mapping( return filtered +def is_generic_only_last_known(inst) -> bool: + """True when the only last-known hit is a generic institution label.""" + from inse.patents.institutions.name_matching import is_generic_institution_name + + if not inst.last_known_institution_match: + return False + name = inst.last_known_institution_name + return bool(name) and is_generic_institution_name(name) + + def finest_mapped_topic_label( patent: model.PatentEntry, mapping=None, diff --git a/service/src/main/inse/patents/institutions/name_matching.py b/service/src/main/inse/patents/institutions/name_matching.py index 132b85cb..ba0fbf95 100644 --- a/service/src/main/inse/patents/institutions/name_matching.py +++ b/service/src/main/inse/patents/institutions/name_matching.py @@ -5,12 +5,15 @@ from inse.patents.common.text_normalization import ( patent_transliteration_expansions, ) +# Structural / stop words — never used as the sole basis for a match. _INSTITUTION_GENERIC_TOKENS = frozenset({ "university", "universitat", "universitaet", "universiteit", "college", "institute", "institut", "institution", "national", "sciences", "science", "school", "center", "centre", "laboratory", "department", "academy", + "medical", "research", "foundation", "hospital", "hospitals", "the", "of", "for", "and", "de", "la", "des", "der", "die", "das", "und", - "fur", "von", + "fur", "von", "inc", "ltd", "llc", "gmbh", "corp", "corporation", + "company", "co", "org", "organization", "organisation", }) MIN_INSTITUTION_SUBSTRING_LEN = 6 @@ -57,6 +60,7 @@ def institution_search_variants(value: str | None) -> list[str]: def _significant_institution_tokens(text: str) -> set[str]: + """Specific (non-generic) tokens that can support an institution match.""" # Normalize hyphens to spaces so "Duisburg-Essen" splits into "duisburg" + "essen", # matching both hyphenated and space-separated forms in patent databases. normalized = normalize_name_part(text).replace("-", " ") @@ -68,7 +72,21 @@ def _significant_institution_tokens(text: str) -> set[str]: } +def is_generic_institution_name(name: str | None) -> bool: + """True when the name has no specific organisation tokens (diagnostic + gating).""" + if not name or not name.strip(): + return True + return not _significant_institution_tokens(name) + + def assignee_matches_institution_name(assignee: str, institution_name: str) -> bool: + """Match patent assignee to an OpenAlex institution name. + + Generic organisation tokens (``medical``, ``research``, ``foundation``, + ``university``, ``center``, …) may appear in both sides but cannot alone + produce a positive match. A match requires near-full name containment, + a short acronym hit, or overlapping *specific* tokens. + """ norm_assignee = normalize_name_part(assignee) norm_name = normalize_name_part(institution_name) if not norm_assignee or not norm_name: @@ -80,18 +98,23 @@ def assignee_matches_institution_name(assignee: str, institution_name: str) -> b norm_name_flat = norm_name.replace("-", " ") assignee_tokens = set(norm_assignee_flat.split()) + # Short acronyms / compact codes (e.g. "MIT", "KAIST"). if len(original) <= 6 and " " not in original: return norm_name_flat in assignee_tokens + significant = _significant_institution_tokens(institution_name) + if not significant: + # Entirely generic labels such as "University Medical Center" never match. + return False + + # Near-full normalised containment only when the institution string itself + # carries specific tokens (avoids "medical"/"research" substrings). if len(norm_name_flat) >= MIN_INSTITUTION_SUBSTRING_LEN: if norm_name_flat in norm_assignee_flat or norm_assignee_flat in norm_name_flat: return True - significant = _significant_institution_tokens(institution_name) - if not significant: - return False - matched = significant & assignee_tokens if len(significant) >= 2: return len(matched) >= 2 + # Single specific token (e.g. "Harvard", "Louisville") is enough. return bool(matched) diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py index d9225534..9bbfaa47 100644 --- a/service/src/main/inse/patents/test_elastic_search_client.py +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -30,9 +30,22 @@ def test_epo_query_uses_nested_search_and_name_variants(): nested = payload["query"]["nested"] assert nested["path"] == "inventors_name_nested" inventor_query = nested["query"] + # Family name + given/initial must both match; phrases only boost score. + assert "must" in inventor_query["bool"] + assert len(inventor_query["bool"]["must"]) == 2 assert "should" in inventor_query["bool"] +def test_epo_query_never_searches_standalone_initial_without_last_name(): + client = PatentSearchClient(api_key="test-key") + payload = client.epo_query_by_inventor("Dan J. Stein") + query_text = json.dumps(payload["query"]) + # Single-letter tokens may appear inside must+given clauses, but the query + # structure always requires a family-name must clause as well. + assert '"must"' in query_text + assert "Stein" in query_text + + def test_uspto_index_is_3_0(): assert ESIndex.USPTO_INDEX == "uspto_patents_3.0" assert ESIndex.EPO_INDEX == "epo_index_1.0" diff --git a/service/src/main/inse/patents/test_institution_matching.py b/service/src/main/inse/patents/test_institution_matching.py index 3dc109cd..3625e2f1 100644 --- a/service/src/main/inse/patents/test_institution_matching.py +++ b/service/src/main/inse/patents/test_institution_matching.py @@ -41,6 +41,53 @@ def test_assignee_matches_institution_name_rejects_false_positives() -> None: ) +def test_assignee_rejects_generic_token_only_matches() -> None: + assert not assignee_matches_institution_name( + "Green Sun Medical, LLC", + "University Medical Center", + ) + assert not assignee_matches_institution_name( + "University Of Louisville Research Foundation, Inc.", + "Research Triangle Park Foundation", + ) + assert not assignee_matches_institution_name( + "University Of Louisville Research Foundation, Inc.", + "Orthopaedic Research Foundation", + ) + assert not assignee_matches_institution_name( + "Some Research Institute", + "Research Institute", + ) + + +def test_assignee_accepts_specific_last_known_style_matches() -> None: + assert assignee_matches_institution_name( + "Universitaet Duisburg-Essen", + "University of Duisburg-Essen", + ) + assert assignee_matches_institution_name( + "Universitaetsmedizin der Johannes Gutenberg-Universitaet Mainz", + "Johannes Gutenberg University Mainz", + ) + assert assignee_matches_institution_name( + "University Of Louisville Research Foundation, Inc.", + "University of Louisville", + ) + assert assignee_matches_institution_name( + "Southwest Research Institute", + "Southwest Research Institute", + ) + + +def test_is_generic_institution_name() -> None: + from inse.patents.institutions.name_matching import is_generic_institution_name + + assert is_generic_institution_name("University Medical Center") + assert is_generic_institution_name("Research Institute") + assert not is_generic_institution_name("University of Duisburg-Essen") + assert not is_generic_institution_name("Southwest Research Institute") + + def test_filter_patents_by_institution_removes_unrelated_assignees() -> None: institution = _institution( display_name="Harvard University", diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py index 675b93fd..1fbe7b7c 100644 --- a/service/src/main/inse/patents/test_name_matching.py +++ b/service/src/main/inse/patents/test_name_matching.py @@ -155,6 +155,64 @@ def test_inventor_search_phrases_include_comma_and_initials() -> None: assert any("," in phrase for phrase in phrases) +def test_inventor_search_phrases_exclude_standalone_single_letters() -> None: + for display_name in ( + "Dan J. Stein", + "M. Shoji", + "Paul M. Thompson", + "Gregory Y. H. Lip", + ): + phrases = inventor_search_phrases(display_name) + standalone = [ + phrase + for phrase in phrases + if len(normalize_name_part(phrase)) == 1 + ] + assert standalone == [], f"{display_name}: {standalone}" + + +def test_inventor_search_phrases_exclude_doubled_middle_tokens() -> None: + for display_name, forbidden_substrings in ( + ("Dan J. Stein", ("j. j.", "dj j.", "d.j. j.")), + ("Paul M. Thompson", ("m. m.", "pm m.", "p.m. m.")), + ("Gregory Y.H. Lip", ("y.h. y.h.", "yh yh")), + ("Walter C. Willett", ("c. c.", "wc c.", "w.c. c.")), + ): + folded = {phrase.casefold() for phrase in inventor_search_phrases(display_name)} + for forbidden in forbidden_substrings: + assert not any(forbidden in phrase for phrase in folded), ( + f"{display_name} still has {forbidden!r} in {sorted(folded)[:12]}" + ) + + +def test_inventor_search_phrases_exclude_whole_phrase_vowel_expansion() -> None: + phrases = inventor_search_phrases("Dan J. Stein") + folded = {phrase.casefold() for phrase in phrases} + assert not any("daen" in phrase for phrase in folded) + + phrases = inventor_search_phrases("George Davey Smith") + folded = {phrase.casefold() for phrase in phrases} + assert not any("geoerge" in phrase for phrase in folded) + + phrases = inventor_search_phrases("Paul M. Thompson") + folded = {phrase.casefold() for phrase in phrases} + assert not any("thoempsoen" in phrase for phrase in folded) + + +def test_inventor_search_phrases_allow_initial_with_last_name() -> None: + phrases = inventor_search_phrases("Dan J. Stein") + folded = {phrase.casefold() for phrase in phrases} + assert any(phrase in folded for phrase in ("d stein", "d. stein", "dj stein")) + + +def test_search_name_variants_multiword_skips_vowel_expansion_and_initial() -> None: + variants = search_name_variants("Dan J. Stein") + folded = {variant.casefold() for variant in variants} + assert "dan j. stein" in folded or "dan j stein" in folded + assert "d" not in folded + assert not any("daen" in variant for variant in folded) + + def test_first_name_match_kind_multi_part() -> None: assert ( first_name_match_kind_for_person("Marrón, Pedro José", "Pedro José Marrón") @@ -166,6 +224,26 @@ def test_first_name_match_kind_multi_part() -> None: ) +def test_partial_name_match_when_full_middle_given_missing() -> None: + assert name_matches_person("SMITH, George", "George Davey Smith") + assert ( + first_name_match_kind_for_person("SMITH, George", "George Davey Smith") + == "partial" + ) + assert ( + first_name_match_kind_for_person( + "SMITH, George Davey", + "George Davey Smith", + ) + == "full" + ) + # Initial forms stay initial, not partial. + assert ( + first_name_match_kind_for_person("G. D. Smith", "George Davey Smith") + == "initial" + ) + + def test_middle_initial_requires_corroboration() -> None: assert not name_matches_person("Schmitz, Oliver", "Oliver J. Schmitz") assert name_matches_person("Schmitz, Oliver J.", "Oliver J. Schmitz") diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 7bf9c9a7..a07d551d 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -173,10 +173,22 @@ async def count_authors_by_display_name(display_name: str) -> int: Used purely as an internal ambiguity signal: a value >= 2 means at least one other author shares the exact name. + + Uses a ``term`` query on ``display_name.keyword`` so individual name tokens + cannot inflate the count the way an analyzed ``match`` / loose phrase query + would. """ if not display_name or not display_name.strip(): return 0 - query = {"match_phrase": {"display_name": display_name.strip()}} + exact_name = display_name.strip() + query = { + "term": { + "display_name.keyword": { + "value": exact_name, + "case_insensitive": True, + } + } + } return await _count_authors(query) -- 2.56.1 From 2e0883edae24f6ae5b5ce550e94f9ef5ce263d88 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 20 Jul 2026 17:06:12 +0200 Subject: [PATCH 3/6] feat(patents): add adaptive pagination for author patent search --- .../src/main/inse/patents/authors/logic.py | 37 +- .../inse/patents/authors/search_pagination.py | 315 ++++++++++++++++++ .../inse/patents/authors/search_queries.py | 18 +- .../patents/authors/test_search_pagination.py | 232 +++++++++++++ .../patents/test_elastic_search_client.py | 25 ++ 5 files changed, 611 insertions(+), 16 deletions(-) create mode 100644 service/src/main/inse/patents/authors/search_pagination.py create mode 100644 service/src/main/inse/patents/authors/test_search_pagination.py diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 8b2df53a..32a6f8bc 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -1,5 +1,4 @@ """Business logic for patent lookup by inventor.""" -import asyncio import logging import httpx @@ -10,16 +9,14 @@ from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.patents.authors.identity import is_ambiguous_name from inse.patents.authors.name_matching import filter_patents_by_author_name from inse.patents.authors.name_variants import parse_person_name +from inse.patents.authors.search_pagination import search_author_patents_adaptive from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver from inse.patents.common import model from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.parsing import ( - deduplicate_patents, enrich_patents_classifications, expand_matched_epo_application_families, - parse_epo_hits, - parse_uspto_hits, ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.search_client import PatentSearchClient @@ -55,7 +52,9 @@ async def get_patents_by_author_id( ) try: - epo_data, uspto_data = await _search_both_indices(search_client, author_name) + search_result = await search_author_patents_adaptive( + search_client, author_name + ) except MissingApiKeyError as exc: raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, @@ -67,9 +66,26 @@ async def get_patents_by_author_id( detail="Patent search request failed.", ) from exc - all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) - all_patents = deduplicate_patents(all_patents) + all_patents = search_result.patents patent_hit_count = len(all_patents) + if search_result.completeness.value == "truncated_inconclusive": + # Unread ES hits remain; zero UI patents must not be treated as proof + # that the author has no patents in the index. + logger.warning( + "search_completeness=%s for author %s (%s): epo_scanned=%d/%d " + "uspto_scanned=%d/%d stop=%s/%s strong_matches=%d/%d", + search_result.completeness.value, + author_id, + author_name, + search_result.epo.hits_scanned, + search_result.epo.total_hits, + search_result.uspto.hits_scanned, + search_result.uspto.total_hits, + search_result.epo.stop_reason, + search_result.uspto.stop_reason, + search_result.epo.strong_name_match_count, + search_result.uspto.strong_name_match_count, + ) matched_patents = filter_patents_by_author_name(all_patents, author_name) try: matched_patents = await expand_matched_epo_application_families( @@ -138,13 +154,6 @@ async def get_patents_by_author_id( patents=[item.patent for item in filtered], ) -async def _search_both_indices(client, display_name: str): - return await asyncio.gather( - client.search_epo(client.epo_query_by_inventor(display_name)), - client.search_uspto(client.uspto_query_by_inventor(display_name)), - ) - - async def _get_author(author_id: str) -> Author | None: short_id = author_id.replace("https://openalex.org/", "") result = await person_logic.search_persons(author_id=short_id) diff --git a/service/src/main/inse/patents/authors/search_pagination.py b/service/src/main/inse/patents/authors/search_pagination.py new file mode 100644 index 00000000..b4af7bed --- /dev/null +++ b/service/src/main/inse/patents/authors/search_pagination.py @@ -0,0 +1,315 @@ +"""Adaptive inventor-search pagination for author → patent lookup. + +Fetches ES hits in pages and stops early once enough *strong, unique* local +name matches are found, or when scan / page / time budgets are exhausted. +Does not change the inventor query itself — only how many scored hits are +examined and how completeness is interpreted. +""" +from __future__ import annotations + +import asyncio +import logging +import time +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Awaitable, Callable + +from inse.patents.authors.identity import best_name_match_kind +from inse.patents.authors.name_matching import filter_patents_by_author_name +from inse.patents.common import model +from inse.patents.common.parsing import ( + deduplicate_patents, + parse_epo_hits, + parse_search_total, + parse_uspto_hits, +) + +logger = logging.getLogger(__name__) + +AUTHOR_PATENT_PAGE_SIZE = 100 +AUTHOR_PATENT_MAX_SCANNED_PER_SOURCE = 1000 +AUTHOR_PATENT_TARGET_NAME_MATCHES = 30 +AUTHOR_PATENT_MAX_PAGES_PER_SOURCE = 10 +AUTHOR_PATENT_MAX_SECONDS_PER_SOURCE = 20.0 + +# Partial matches (e.g. "George Smith" for "George Davey Smith") may pass the +# name filter but must not drive the early-stop budget. +_STRONG_NAME_MATCH_KINDS = frozenset({"full", "initial"}) + + +class SearchCompleteness(str, Enum): + """How complete the inventor hit scan is for UI interpretation. + + COMPLETE + The ES result set for the source (or both sources) was fully read. + TRUNCATED_INCONCLUSIVE + Scanning stopped while unread hits remain. A zero UI result does **not** + prove the author has no patents in the index. + EXTRA_FINAL_RESULTS_FOUND + Diagnostic only: finals appear only when scanning beyond the first page. + """ + + COMPLETE = "complete" + TRUNCATED_INCONCLUSIVE = "truncated_inconclusive" + EXTRA_FINAL_RESULTS_FOUND = "extra_final_results_found" + + +def is_strong_name_match(patent: model.PatentEntry, display_name: str) -> bool: + """True when the patent is a unique-worthy strong personal name hit. + + Requires the existing name filter to accept the patent, and the best + inventor given-name kind to be ``full`` or ``initial`` (not ``partial``). + """ + if not filter_patents_by_author_name([patent], display_name): + return False + return best_name_match_kind(patent, display_name) in _STRONG_NAME_MATCH_KINDS + + +def count_unique_name_matches( + patents: list[model.PatentEntry], + display_name: str, + *, + strong_only: bool = False, +) -> int: + """Count distinct patent IDs that pass the name filter (optionally strong).""" + seen: set[str] = set() + for patent in patents: + pid = patent.patent_id + if not pid or pid in seen: + continue + if strong_only: + if is_strong_name_match(patent, display_name): + seen.add(pid) + elif filter_patents_by_author_name([patent], display_name): + seen.add(pid) + return len(seen) + + +@dataclass +class SourcePaginationResult: + source: str + patents: list[model.PatentEntry] = field(default_factory=list) + total_hits: int = 0 + hits_scanned: int = 0 + pages_fetched: int = 0 + name_match_count: int = 0 + strong_name_match_count: int = 0 + truncated: bool = False + completeness: SearchCompleteness = SearchCompleteness.COMPLETE + stop_reason: str = "" + elapsed_seconds: float = 0.0 + page_timings_ms: list[float] = field(default_factory=list) + error: str | None = None + + +@dataclass +class AuthorPatentSearchResult: + patents: list[model.PatentEntry] + epo: SourcePaginationResult + uspto: SourcePaginationResult + + @property + def truncated(self) -> bool: + return self.epo.truncated or self.uspto.truncated + + @property + def completeness(self) -> SearchCompleteness: + if ( + self.epo.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + or self.uspto.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ): + return SearchCompleteness.TRUNCATED_INCONCLUSIVE + return SearchCompleteness.COMPLETE + + +def classify_search_completeness( + *, + hits_scanned: int, + total_hits: int, + stop_reason: str, +) -> SearchCompleteness: + """Map pagination stop state to a completeness verdict.""" + if stop_reason == "error": + return SearchCompleteness.TRUNCATED_INCONCLUSIVE + if hits_scanned >= total_hits: + return SearchCompleteness.COMPLETE + # Unread hits remain — including early stop on strong-name target. + return SearchCompleteness.TRUNCATED_INCONCLUSIVE + + +async def search_author_patents_adaptive( + client: Any, + display_name: str, + *, + page_size: int = AUTHOR_PATENT_PAGE_SIZE, + max_scanned_per_source: int = AUTHOR_PATENT_MAX_SCANNED_PER_SOURCE, + target_name_matches: int = AUTHOR_PATENT_TARGET_NAME_MATCHES, + max_pages_per_source: int = AUTHOR_PATENT_MAX_PAGES_PER_SOURCE, + max_seconds_per_source: float = AUTHOR_PATENT_MAX_SECONDS_PER_SOURCE, +) -> AuthorPatentSearchResult: + """Search EPO and USPTO with independent adaptive pagination.""" + epo, uspto = await asyncio.gather( + paginate_inventor_source( + source="EPO", + display_name=display_name, + build_payload=lambda size, search_after: client.epo_query_by_inventor( + display_name, size=size, search_after=search_after + ), + search=client.search_epo, + parse_hits=parse_epo_hits, + page_size=page_size, + max_scanned=max_scanned_per_source, + target_name_matches=target_name_matches, + max_pages=max_pages_per_source, + max_seconds=max_seconds_per_source, + ), + paginate_inventor_source( + source="USPTO", + display_name=display_name, + build_payload=lambda size, search_after: client.uspto_query_by_inventor( + display_name, size=size, search_after=search_after + ), + search=client.search_uspto, + parse_hits=parse_uspto_hits, + page_size=page_size, + max_scanned=max_scanned_per_source, + target_name_matches=target_name_matches, + max_pages=max_pages_per_source, + max_seconds=max_seconds_per_source, + ), + ) + combined = deduplicate_patents(epo.patents + uspto.patents) + result = AuthorPatentSearchResult(patents=combined, epo=epo, uspto=uspto) + if result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE: + logger.info( + "Author patent search completeness=%s for %r: epo=%s uspto=%s " + "(scanned epo=%d/%d uspto=%d/%d, strong_matches epo=%d uspto=%d)", + result.completeness.value, + display_name, + epo.stop_reason, + uspto.stop_reason, + epo.hits_scanned, + epo.total_hits, + uspto.hits_scanned, + uspto.total_hits, + epo.strong_name_match_count, + uspto.strong_name_match_count, + ) + return result + + +async def paginate_inventor_source( + *, + source: str, + display_name: str, + build_payload: Callable[[int, list[Any] | None], dict[str, Any]], + search: Callable[[dict[str, Any]], Awaitable[dict[str, Any]]], + parse_hits: Callable[[dict[str, Any]], list[model.PatentEntry]], + page_size: int, + max_scanned: int, + target_name_matches: int, + max_pages: int, + max_seconds: float, +) -> SourcePaginationResult: + """Fetch inventor hits page-by-page until strong name-match or safety limits. + + Pagination uses ``search_after`` (stable cursor) after the first page. + The early-stop target counts **unique** patents with a strong name match + (``full`` / ``initial``), not raw or partial filter hits. + """ + started = time.perf_counter() + result = SourcePaginationResult(source=source) + accumulated: list[model.PatentEntry] = [] + search_after: list[Any] | None = None + + try: + while True: + elapsed = time.perf_counter() - started + if elapsed >= max_seconds: + result.stop_reason = "time_budget" + break + if result.pages_fetched >= max_pages: + result.stop_reason = "max_pages" + break + if result.hits_scanned >= max_scanned: + result.stop_reason = "max_scanned" + break + if ( + result.pages_fetched > 0 + and result.strong_name_match_count >= target_name_matches + ): + result.stop_reason = "target_strong_name_matches" + break + if result.pages_fetched > 0 and result.hits_scanned >= result.total_hits: + result.stop_reason = "exhausted" + break + + remaining_budget = max_scanned - result.hits_scanned + size = min(page_size, remaining_budget) + if size <= 0: + result.stop_reason = "max_scanned" + break + + payload = build_payload(size, search_after) + page_started = time.perf_counter() + data = await search(payload) + page_ms = (time.perf_counter() - page_started) * 1000.0 + result.page_timings_ms.append(round(page_ms, 1)) + + if result.pages_fetched == 0: + result.total_hits = parse_search_total(data) + + raw_hits = data.get("hits", {}).get("hits", []) or [] + page_patents = parse_hits(data) + if not page_patents: + result.stop_reason = "exhausted" + break + + accumulated.extend(page_patents) + result.hits_scanned += len(page_patents) + result.pages_fetched += 1 + result.name_match_count = count_unique_name_matches( + accumulated, display_name, strong_only=False + ) + result.strong_name_match_count = count_unique_name_matches( + accumulated, display_name, strong_only=True + ) + + last_sort = raw_hits[-1].get("sort") if raw_hits else None + search_after = last_sort if last_sort is not None else search_after + + if result.hits_scanned >= result.total_hits: + result.stop_reason = "exhausted" + break + if result.strong_name_match_count >= target_name_matches: + result.stop_reason = "target_strong_name_matches" + break + if result.hits_scanned >= max_scanned: + result.stop_reason = "max_scanned" + break + if result.pages_fetched >= max_pages: + result.stop_reason = "max_pages" + break + if time.perf_counter() - started >= max_seconds: + result.stop_reason = "time_budget" + break + + except Exception as exc: + result.error = f"{type(exc).__name__}: {exc}" + result.stop_reason = "error" + logger.exception("%s inventor pagination failed for %r", source, display_name) + + result.patents = accumulated + result.elapsed_seconds = round(time.perf_counter() - started, 3) + if not result.stop_reason: + result.stop_reason = "exhausted" + + result.completeness = classify_search_completeness( + hits_scanned=result.hits_scanned, + total_hits=result.total_hits, + stop_reason=result.stop_reason, + ) + result.truncated = ( + result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ) + return result diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py index e87c6583..436169b2 100644 --- a/service/src/main/inse/patents/authors/search_queries.py +++ b/service/src/main/inse/patents/authors/search_queries.py @@ -150,6 +150,8 @@ class InventorSearchQueries: display_name: str, first_name: str | None = None, size: int = DEFAULT_SEARCH_SIZE, + from_: int = 0, + search_after: list | None = None, ) -> dict[str, Any]: if first_name and display_name and " " not in display_name.strip(): display_name = f"{first_name} {display_name}".strip() @@ -164,7 +166,7 @@ class InventorSearchQueries: } } - return { + payload: dict[str, Any] = { "size": size, "track_total_hits": True, "sort": [ @@ -190,6 +192,11 @@ class InventorSearchQueries: ], "query": query, } + if search_after: + payload["search_after"] = search_after + else: + payload["from"] = max(0, int(from_)) + return payload def epo_query_by_application_number( self, @@ -238,6 +245,8 @@ class InventorSearchQueries: display_name: str, first_name: str | None = None, size: int = DEFAULT_SEARCH_SIZE, + from_: int = 0, + search_after: list | None = None, ) -> dict[str, Any]: if first_name and display_name and " " not in display_name.strip(): display_name = f"{first_name} {display_name}".strip() @@ -249,7 +258,7 @@ class InventorSearchQueries: } } - return { + payload: dict[str, Any] = { "size": size, "track_total_hits": True, "sort": [ @@ -276,6 +285,11 @@ class InventorSearchQueries: ], "query": query, } + if search_after: + payload["search_after"] = search_after + else: + payload["from"] = max(0, int(from_)) + return payload def _application_number_variants(application_number: str) -> list[str]: diff --git a/service/src/main/inse/patents/authors/test_search_pagination.py b/service/src/main/inse/patents/authors/test_search_pagination.py new file mode 100644 index 00000000..4c902b16 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_search_pagination.py @@ -0,0 +1,232 @@ +"""Unit tests for adaptive inventor-search pagination.""" +from __future__ import annotations + +import pytest + +from inse.patents.authors.search_pagination import ( + SearchCompleteness, + classify_search_completeness, + count_unique_name_matches, + is_strong_name_match, + paginate_inventor_source, +) +from inse.patents.common import model +from inse.patents.common.parsing import parse_epo_hits + + +def _hit(patent_id: str, inventors: list[str], *, sort: list | None = None) -> dict: + doc = { + "_id": patent_id[2:], + "_source": { + "doc_number": patent_id[2:], + "inventors_name": inventors, + "applicants_name": [], + "title_en": f"Title {patent_id}", + }, + } + if sort is not None: + doc["sort"] = sort + return doc + + +def _response(total: int, hits: list[dict]) -> dict: + return {"hits": {"total": {"value": total, "relation": "eq"}, "hits": hits}} + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_pagination_stops_on_unique_strong_name_matches() -> None: + pages: list[dict] = [] + + async def search(payload: dict) -> dict: + pages.append(payload) + if "search_after" not in payload: + hits = [ + _hit(f"EP{i:07d}", ["Other, Person"], sort=[1.0, "2020", i]) + for i in range(100) + ] + else: + hits = [ + _hit( + f"EP{100 + i:07d}", + ["Stein, Dan J."], + sort=[2.0, "2019", 100 + i], + ) + for i in range(30) + ] + return _response(5000, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="Dan J. Stein", + build_payload=lambda size, search_after: ( + {"size": size, "search_after": search_after} + if search_after + else {"size": size, "from": 0} + ), + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=1000, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.pages_fetched == 2 + assert result.strong_name_match_count >= 30 + assert result.stop_reason == "target_strong_name_matches" + assert result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + assert result.truncated is True + assert "search_after" in pages[1] + + +@pytest.mark.anyio +async def test_partial_matches_do_not_count_toward_stop_target() -> None: + """George Smith is partial for George Davey Smith — keep scanning.""" + + async def search(payload: dict) -> dict: + # Always return partial-style matches; never reach strong target. + offset = 0 if "search_after" not in payload else 100 + hits = [ + _hit( + f"EP{offset + i:07d}", + ["Smith, George"], + sort=[1.0, "2020", offset + i], + ) + for i in range(100) + ] + return _response(5000, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="George Davey Smith", + build_payload=lambda size, search_after: ( + {"size": size, "search_after": search_after} + if search_after + else {"size": size} + ), + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=300, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.strong_name_match_count == 0 + assert result.name_match_count > 0 + assert result.stop_reason == "max_scanned" + assert result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + + +@pytest.mark.anyio +async def test_duplicate_patent_ids_count_once() -> None: + patents = [ + model.PatentEntry( + patent_id="EP1", + source="EPO", + inventors=["Stein, Dan J."], + assignees=[], + ), + model.PatentEntry( + patent_id="EP1", + source="EPO", + inventors=["Stein, Dan J."], + assignees=[], + ), + model.PatentEntry( + patent_id="EP2", + source="EPO", + inventors=["Stein, Dan J."], + assignees=[], + ), + ] + assert count_unique_name_matches(patents, "Dan J. Stein", strong_only=True) == 2 + + +@pytest.mark.anyio +async def test_pagination_marks_truncated_inconclusive_at_max_scanned() -> None: + async def search(payload: dict) -> dict: + cursor = payload.get("search_after") + base = int(cursor[-1]) + 1 if cursor else 0 + hits = [ + _hit(f"EP{base + i:07d}", ["Other, Person"], sort=[1.0, "2020", base + i]) + for i in range(payload["size"]) + ] + return _response(200_000, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="Dan J. Stein", + build_payload=lambda size, search_after: ( + {"size": size, "search_after": search_after} + if search_after + else {"size": size} + ), + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=300, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.hits_scanned == 300 + assert result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + assert result.truncated is True + assert result.strong_name_match_count == 0 + + +@pytest.mark.anyio +async def test_pagination_complete_when_exhausted() -> None: + async def search(payload: dict) -> dict: + hits = [_hit("EP0000001", ["Stein, Dan J."], sort=[1.0, "2020", 1])] + return _response(1, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="Dan J. Stein", + build_payload=lambda size, search_after: {"size": size}, + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=1000, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.completeness == SearchCompleteness.COMPLETE + assert result.truncated is False + assert result.stop_reason == "exhausted" + assert is_strong_name_match(result.patents[0], "Dan J. Stein") + + +def test_classify_search_completeness() -> None: + assert ( + classify_search_completeness( + hits_scanned=8, total_hits=8, stop_reason="exhausted" + ) + == SearchCompleteness.COMPLETE + ) + assert ( + classify_search_completeness( + hits_scanned=1000, total_hits=200000, stop_reason="max_scanned" + ) + == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ) + assert ( + classify_search_completeness( + hits_scanned=200, + total_hits=5000, + stop_reason="target_strong_name_matches", + ) + == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ) diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py index 9bbfaa47..6403362c 100644 --- a/service/src/main/inse/patents/test_elastic_search_client.py +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -26,6 +26,7 @@ def test_epo_query_uses_nested_search_and_name_variants(): payload = client.epo_query_by_inventor("Pedro José Marrón") assert payload["size"] == DEFAULT_SEARCH_SIZE + assert payload["from"] == 0 assert payload["sort"][0] == {"_score": {"order": "desc"}} nested = payload["query"]["nested"] assert nested["path"] == "inventors_name_nested" @@ -36,6 +37,30 @@ def test_epo_query_uses_nested_search_and_name_variants(): assert "should" in inventor_query["bool"] +def test_epo_and_uspto_inventor_queries_support_from_offset(): + client = PatentSearchClient(api_key="test-key") + epo = client.epo_query_by_inventor("Dan J. Stein", size=100, from_=200) + uspto = client.uspto_query_by_inventor("Dan J. Stein", size=50, from_=100) + assert epo["from"] == 200 + assert epo["size"] == 100 + assert "search_after" not in epo + assert uspto["from"] == 100 + assert uspto["size"] == 50 + + +def test_inventor_queries_use_search_after_instead_of_from(): + client = PatentSearchClient(api_key="test-key") + cursor = [12.5, "20200101", 42] + epo = client.epo_query_by_inventor("Dan J. Stein", size=100, search_after=cursor) + uspto = client.uspto_query_by_inventor( + "Dan J. Stein", size=100, search_after=cursor + ) + assert epo["search_after"] == cursor + assert "from" not in epo + assert uspto["search_after"] == cursor + assert "from" not in uspto + + def test_epo_query_never_searches_standalone_initial_without_last_name(): client = PatentSearchClient(api_key="test-key") payload = client.epo_query_by_inventor("Dan J. Stein") -- 2.56.1 From f342406402d2038b241e3d120ebbe98505f16b23 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Mon, 20 Jul 2026 22:52:43 +0200 Subject: [PATCH 4/6] fix(person-funding): color author-position stat boxes and filter chip by position. --- .../person-funding.component.html | 5 +- .../person-funding.component.scss | 75 +++++++++++++------ 2 files changed, 56 insertions(+), 24 deletions(-) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 2051dd59..c25bc55a 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -445,7 +445,9 @@
@if (activeFilter !== 'all') { - + Filter: {{ getPositionLabel(activeFilter) }} } @@ -474,7 +476,6 @@
-

Wähle links einen Förderer aus, um die zugehörigen Publikationen anzuzeigen. diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index e8de6dea..3d0ba121 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -147,51 +147,64 @@ font-weight: bold; color: #333; } + + &.stat-first { + background: #effaf3; + border-color: #bdebcf; + + .stat-label, + .stat-value { + color: #24834f; + } + } + + &.stat-middle { + background: #f6f0ff; + border-color: #d8cafe; + + .stat-label, + .stat-value { + color: #7255d9; + } + } + + &.stat-last { + background: #fff1f2; + border-color: #fda4af; + + .stat-label, + .stat-value { + color: #be123c; + } + } } } -.stat-first, .position-badge--first, .hero-highlight--open, .publication-detail-grid .access-badge--open { background: #effaf3; -} - -.stat-first { - border-color: #bdebcf; -} - -.position-badge--first { - color: #24834f; - border: 1px solid #bdebcf; -} - -.hero-highlight--open, -.publication-detail-grid .access-badge--open { border-color: #bdebcf; color: #24834f; } -.stat-middle, .position-badge--middle { background: #f6f0ff; border-color: #d8cafe; -} - -.position-badge--middle { color: #7255d9; - border: 1px solid #d8cafe; } -.stat-last, .position-badge--last { background: #fff1f2; border-color: #fda4af; + color: #be123c; } +.position-badge--first, +.position-badge--middle, .position-badge--last { - color: #be123c; - border: 1px solid #fda4af; + border-width: 1px; + border-style: solid; } .publication-list { @@ -250,6 +263,24 @@ font-size: 0.75rem; font-weight: 600; text-transform: uppercase; + + &.position-badge--first { + background: #effaf3; + border-color: #bdebcf; + color: #24834f; + } + + &.position-badge--middle { + background: #f6f0ff; + border-color: #d8cafe; + color: #7255d9; + } + + &.position-badge--last { + background: #fff1f2; + border-color: #fda4af; + color: #be123c; + } } &__title { -- 2.56.1 From 7d695f8439b66c5471fb0dc5c965759864b6bdb6 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Fri, 24 Jul 2026 13:05:41 +0200 Subject: [PATCH 5/6] =?UTF-8?q?style(patents):=20unify=20filter=20chips,?= =?UTF-8?q?=20F=C3=B6rder=C3=BCbersicht=20design,=20and=20dropdown=20styli?= =?UTF-8?q?ng=20across=20patents/funding=20views,=20and=20fix=20adaptive?= =?UTF-8?q?=20EPO/USPTO=20pagination=20when=20one=20source=20has=20no=20hi?= =?UTF-8?q?ts=20for=20the=20selected=20date=20range?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/src/main/inse/patents/all/logic.py | 69 +++++++++-- .../src/main/inse/patents/all/test_logic.py | 54 +++++++++ .../modules/patents/patents.component.html | 6 +- .../modules/patents/patents.component.scss | 4 + .../app/modules/patents/patents.component.ts | 35 ++++-- .../person-funding.component.html | 46 ++++---- .../person-funding.component.scss | 111 ++++++------------ .../person-funding.component.ts | 10 +- .../person-patents.component.html | 46 ++++---- .../person-patents.component.scss | 45 +++---- .../person-patents.component.ts | 11 +- 11 files changed, 277 insertions(+), 160 deletions(-) create mode 100644 service/src/main/inse/patents/all/test_logic.py diff --git a/service/src/main/inse/patents/all/logic.py b/service/src/main/inse/patents/all/logic.py index 76defc74..7521b3cd 100644 --- a/service/src/main/inse/patents/all/logic.py +++ b/service/src/main/inse/patents/all/logic.py @@ -55,21 +55,38 @@ async def get_all_patents( total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) else: - half = size // 2 - epo_data, uspto_data = await asyncio.gather( + # Determine each source's total hit count for the current filters + # first: a fixed 50/50 split per page wastes half the page when one + # source has no matches at all for the requested range (e.g. USPTO + # has no data before 2014), so the split must adapt to how many + # hits each source actually has. + epo_count_data, uspto_count_data = await asyncio.gather( all_patents_client.search_epo( - all_patents_client.epo_query(page, half, search, sort_direction, year_from, year_to) + all_patents_client.epo_query(0, 0, search, sort_direction, year_from, year_to) ), all_patents_client.search_uspto( - all_patents_client.uspto_query(page, half, search, sort_direction, year_from, year_to) + all_patents_client.uspto_query(0, 0, search, sort_direction, year_from, year_to) ), ) - patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) - total = ( - epo_data.get("hits", {}).get("total", {}).get("value", 0) - + uspto_data.get("hits", {}).get("total", {}).get("value", 0) + epo_total = epo_count_data.get("hits", {}).get("total", {}).get("value", 0) + uspto_total = uspto_count_data.get("hits", {}).get("total", {}).get("value", 0) + + epo_from, uspto_from, epo_take, uspto_take = _split_two_source_page( + page, size, epo_total, uspto_total ) + epo_query = all_patents_client.epo_query(0, epo_take, search, sort_direction, year_from, year_to) + epo_query["from"] = epo_from + uspto_query = all_patents_client.uspto_query(0, uspto_take, search, sort_direction, year_from, year_to) + uspto_query["from"] = uspto_from + + epo_data, uspto_data = await asyncio.gather( + all_patents_client.search_epo(epo_query), + all_patents_client.search_uspto(uspto_query), + ) + patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + total = epo_total + uspto_total + except MissingApiKeyError as exc: raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, @@ -99,6 +116,42 @@ async def get_all_patents( ) +def _split_two_source_page( + page: int, + size: int, + epo_total: int, + uspto_total: int, +) -> tuple[int, int, int, int]: + """Compute (epo_from, uspto_from, epo_take, uspto_take) for a combined page. + + Targets an even split per page, but once a source is exhausted for the + current filters (e.g. USPTO has no hits before 2014), the remaining slots + shift to the other source instead of leaving the page short. + """ + half = size // 2 + epo_from = 0 + uspto_from = 0 + epo_take = 0 + uspto_take = 0 + + for _ in range(page + 1): + epo_remaining = max(epo_total - epo_from, 0) + uspto_remaining = max(uspto_total - uspto_from, 0) + + epo_take = min(half, epo_remaining) + uspto_take = min(size - epo_take, uspto_remaining) + + leftover = size - epo_take - uspto_take + if leftover > 0: + epo_take += min(leftover, epo_remaining - epo_take) + + this_epo_from, this_uspto_from = epo_from, uspto_from + epo_from += epo_take + uspto_from += uspto_take + + return this_epo_from, this_uspto_from, epo_take, uspto_take + + def _normalize_patent_date(date_str: str) -> str: return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d") diff --git a/service/src/main/inse/patents/all/test_logic.py b/service/src/main/inse/patents/all/test_logic.py new file mode 100644 index 00000000..5e3e4dc5 --- /dev/null +++ b/service/src/main/inse/patents/all/test_logic.py @@ -0,0 +1,54 @@ +from inse.patents.all.logic import _split_two_source_page + + +def test_even_split_when_both_sources_have_enough_hits(): + epo_from, uspto_from, epo_take, uspto_take = _split_two_source_page( + page=0, size=10, epo_total=100, uspto_total=100 + ) + assert (epo_from, uspto_from, epo_take, uspto_take) == (0, 0, 5, 5) + + +def test_odd_size_no_longer_drops_an_item(): + _, _, epo_take, uspto_take = _split_two_source_page( + page=0, size=11, epo_total=100, uspto_total=100 + ) + assert epo_take + uspto_take == 11 + + +def test_shifts_remaining_slots_to_epo_when_uspto_has_no_hits(): + # e.g. year range entirely before USPTO's earliest indexed publication. + epo_from, uspto_from, epo_take, uspto_take = _split_two_source_page( + page=0, size=10, epo_total=100, uspto_total=0 + ) + assert (epo_from, uspto_from, epo_take, uspto_take) == (0, 0, 10, 0) + + +def test_shifts_remaining_slots_to_uspto_when_epo_has_no_hits(): + epo_from, uspto_from, epo_take, uspto_take = _split_two_source_page( + page=0, size=10, epo_total=0, uspto_total=100 + ) + assert (epo_from, uspto_from, epo_take, uspto_take) == (0, 0, 0, 10) + + +def test_later_pages_advance_offsets_without_overlap_or_gaps(): + epo_total, uspto_total = 3, 100 + seen_epo: list[int] = [] + seen_uspto: list[int] = [] + for page in range(3): + epo_from, uspto_from, epo_take, uspto_take = _split_two_source_page( + page, size=10, epo_total=epo_total, uspto_total=uspto_total + ) + seen_epo.append((epo_from, epo_take)) + seen_uspto.append((uspto_from, uspto_take)) + + # EPO only has 3 hits total: page 0 exhausts it, later pages take none. + assert seen_epo == [(0, 3), (3, 0), (3, 0)] + # USPTO absorbs whatever EPO could not fill, contiguously across pages. + assert seen_uspto == [(0, 7), (7, 10), (17, 10)] + + +def test_last_page_can_be_shorter_than_requested_size(): + epo_from, uspto_from, epo_take, uspto_take = _split_two_source_page( + page=0, size=10, epo_total=2, uspto_total=3 + ) + assert (epo_from, uspto_from, epo_take, uspto_take) == (0, 0, 2, 3) diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index a3177536..999a7e6b 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -19,9 +19,9 @@

- Alle + [value]="selectedSources" + multiple + (change)="handleSourceChipChange($event)"> EPO USPTO diff --git a/webapp/src/app/modules/patents/patents.component.scss b/webapp/src/app/modules/patents/patents.component.scss index feba9411..e3c8edf0 100644 --- a/webapp/src/app/modules/patents/patents.component.scss +++ b/webapp/src/app/modules/patents/patents.component.scss @@ -27,6 +27,10 @@ h1 { gap: 1rem; } +.mat-mdc-standard-chip { + border-radius: var(--sg-radius-sm); +} + .year-filter { width: min(285px, 100%); padding: 8px 10px; diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index bbf90d41..3eb7e479 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -7,7 +7,7 @@ import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; -import { MatChipsModule } from '@angular/material/chips'; +import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; import { MatDividerModule } from '@angular/material/divider'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; @@ -22,7 +22,7 @@ import { topicHierarchyColor, } from '../../resolvers/utils/topic-colors'; -type SourceFilter = 'all' | 'EPO' | 'USPTO'; +type PatentSource = 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; @@ -72,7 +72,7 @@ export class PatentsComponent implements OnInit { error = false; searchTerm = ''; - activeFilter: SourceFilter = 'all'; + selectedSources: PatentSource[] = ['EPO', 'USPTO']; sortDirection: string = 'asc'; // Jahr-Slider @@ -103,8 +103,10 @@ export class PatentsComponent implements OnInit { this.searchTerm = qp.get('search') ?? ''; this.page = parseInt(qp.get('page') ?? '0', 10); this.pageSize = parseInt(qp.get('size') ?? '10', 10); - const f = qp.get('source'); - if (f === 'EPO' || f === 'USPTO') this.activeFilter = f; + const sourcesParam = qp.get('sources'); + this.selectedSources = (sourcesParam ?? 'EPO,USPTO') + .split(',') + .filter((s): s is PatentSource => s === 'EPO' || s === 'USPTO'); const d = qp.get('sort_direction'); if (d === 'asc' || d === 'desc') this.sortDirection = d; const sy = parseInt(qp.get('year_from') ?? '', 10); @@ -184,9 +186,18 @@ export class PatentsComponent implements OnInit { } private loadPatents(): void { + if (this.selectedSources.length === 0) { + this.patents = []; + this.total = 0; + this.loading = false; + this.error = false; + return; + } + this.loading = true; this.error = false; - const source = this.activeFilter === 'all' ? undefined : this.activeFilter; + const source = + this.selectedSources.length === 1 ? this.selectedSources[0] : undefined; this.patentsApi .getAllPatents( @@ -223,9 +234,11 @@ export class PatentsComponent implements OnInit { this.updateQueryParams(); } - setFilterFromChip(event: any): void { - const val = event.value; - this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all'; + handleSourceChipChange(change: MatChipListboxChange): void { + const selected = change.value as PatentSource[]; + // Deselecting every chip resets back to "all sources", mirroring the + // project-type filter's behavior instead of showing an empty state. + this.selectedSources = selected.length ? selected : ['EPO', 'USPTO']; this.page = 0; this.loadPatents(); this.updateQueryParams(); @@ -267,7 +280,9 @@ export class PatentsComponent implements OnInit { search: this.searchTerm || null, page: this.page, size: this.pageSize, - source: this.activeFilter === 'all' ? null : this.activeFilter, + sources: this.selectedSources.length + ? this.selectedSources.join(',') + : null, sort_direction: this.sortDirection, year_from: this.selectedStartYear !== this.minYear diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index c25bc55a..00805abc 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -307,26 +307,32 @@
- - + (selectionChange)="setSortMode($event.value)"> + Sortieren nach + Name + Top Förderer + +
@@ -460,7 +466,7 @@ }

-
+
{{ getUniquePublicationCount() }} @@ -468,7 +474,7 @@ >Einzigartige Publikationen
-
+
{{ filteredFunders.length }} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index 3d0ba121..2cc57090 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -10,29 +10,9 @@ gap: 16px; } -.sort-control { - display: inline-flex; - align-items: center; - gap: 6px; +.funding-toolbar-field { width: fit-content; - padding: 10px 14px; - border-radius: 20px; - background: #f2f2f2; - color: #333; - font-size: 14px; - - span { - color: #555; - } - - select { - border: 0; - background: transparent; - color: #111827; - font: inherit; - cursor: pointer; - outline: none; - } + min-width: 180px; } .funding-content { @@ -91,22 +71,6 @@ padding: 20px; background: #fafafa; - &.empty { - display: flex; - align-items: center; - justify-content: center; - min-height: 280px; - padding: 24px; - background: - radial-gradient( - circle at 100% 0%, - rgba(200, 217, 255, 0.35), - transparent 45% - ), - linear-gradient(160deg, #fff 0%, #f8faff 100%); - border-color: #dbe3f2; - } - h3 { margin: 0 0 16px; font-size: 16px; @@ -250,7 +214,6 @@ .empty-overview { width: 100%; - text-align: center; &__filter { display: inline-block; @@ -285,67 +248,65 @@ &__title { margin: 0 0 8px; - font-size: 1.125rem; - color: #1e3a5f; + font-size: 15px; + font-weight: 600; + color: #333; } &__subtitle { margin: 0 0 20px; - color: #64748b; - font-size: 0.875rem; - line-height: 1.5; + color: #888; + font-size: 13px; } &__stats { display: grid; grid-template-columns: 1fr 1fr; - gap: 12px; + gap: 10px; margin-bottom: 20px; } &__stat { - display: flex; - flex-direction: column; - gap: 6px; - padding: 16px 12px; - border: 1px solid #e0e6f0; - border-radius: 10px; - background: rgba(255, 255, 255, 0.85); + text-align: center; + padding: 12px 8px; + border: 1px solid #e0e0e0; + border-radius: 8px; + background: #fff; } &__stat-value { - font-size: 1.75rem; + display: block; + font-size: 22px; font-weight: 700; - line-height: 1.1; - color: #1e3a5f; + color: #333; } &__stat-label { - font-size: 0.8rem; - line-height: 1.35; - color: #64748b; + display: block; + font-size: 12px; + color: #888; + margin-top: 4px; + } + + &__stat--publications { + .empty-overview__stat-value, + .empty-overview__stat-label { + color: #0b63ce; + } + } + + &__stat--funders { + .empty-overview__stat-value, + .empty-overview__stat-label { + color: #b45309; + } } &__hint { - display: flex; - align-items: flex-start; - gap: 10px; - padding: 12px 14px; - border: 1px dashed #c7d5ea; - border-radius: 10px; - background: rgba(255, 255, 255, 0.7); - text-align: left; - - .material-icons { - font-size: 20px; - color: #3b82c4; - } - p { margin: 0; - color: #475569; - font-size: 0.875rem; - line-height: 1.45; + color: #aaa; + font-size: 12px; } } } diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts index 49a9cce9..250711b4 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -3,6 +3,9 @@ import { CommonModule } from '@angular/common'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; import { Router } from '@angular/router'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; +import { MatIconModule } from '@angular/material/icon'; import { FundingService } from '../../api'; type SortMode = 'name' | 'top'; @@ -52,7 +55,12 @@ type FundingPublicationDetail = { @Component({ selector: 'app-person-funding', - imports: [CommonModule], + imports: [ + CommonModule, + MatFormFieldModule, + MatSelectModule, + MatIconModule, + ], templateUrl: './person-funding.component.html', styleUrl: './person-funding.component.scss', }) diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 1c7114aa..4f659cdd 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -13,25 +13,31 @@
- - + (selectionChange)="setSortMode($event.value)"> + Sortieren nach + Datum + Titel + +
@@ -142,15 +148,15 @@

Patentübersicht

Patente mit passendem Erfindername.

-
+
{{ patents.length }} Patente
-
+
{{ getEpoCount() }} EPO
-
+
{{ getUsptoCount() }} USPTO
diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 6c1d17ee..b5fe67d8 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -10,29 +10,9 @@ gap: 16px; } -.sort-control { - display: inline-flex; - align-items: center; - gap: 6px; +.patents-toolbar-field { width: fit-content; - padding: 10px 14px; - border-radius: 20px; - background: #f2f2f2; - color: #333; - font-size: 14px; - - span { - color: #555; - } - - select { - border: 0; - background: transparent; - color: #111827; - font: inherit; - cursor: pointer; - outline: none; - } + min-width: 180px; } .patents-content { @@ -210,6 +190,27 @@ color: #888; margin-top: 4px; } + + &--total { + .overview-value, + .overview-label { + color: #7255d9; + } + } + + &--epo { + .overview-value, + .overview-label { + color: #24834f; + } + } + + &--uspto { + .overview-value, + .overview-label { + color: #0b63ce; + } + } } .overview-hint { diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index 739aac5d..9e837060 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -3,6 +3,9 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; import { finalize, of, switchMap } from 'rxjs'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; +import { MatIconModule } from '@angular/material/icon'; import { PatentEntry } from '../../api/model/patentEntry'; import { PersonPatentsResolved } from '../../resolvers/person-patents.resolver'; import { @@ -16,7 +19,13 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO'; @Component({ selector: 'app-person-patents', - imports: [CommonModule, LoadingComponent], + imports: [ + CommonModule, + LoadingComponent, + MatFormFieldModule, + MatSelectModule, + MatIconModule, + ], templateUrl: './person-patents.component.html', styleUrl: './person-patents.component.scss', }) -- 2.56.1 From ae8d01b5ce7121c47aef21a534aa3e805ecc4520 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Fri, 24 Jul 2026 16:39:54 +0200 Subject: [PATCH 6/6] style(institution-patents): align filter dropdowns, overview stat colors, and match-type badge with the design used across other patent/funding views --- .../institution-patents.component.html | 82 +++++++++++-------- .../institution-patents.component.scss | 52 +++++++----- .../institution-patents.component.ts | 12 ++- .../modules/patents/patents.component.html | 11 ++- .../modules/patents/patents.component.scss | 12 +-- 5 files changed, 98 insertions(+), 71 deletions(-) diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index 70702f6a..a80d0f90 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -22,36 +22,45 @@
- - - + (selectionChange)="setSortMode($event.value)"> + Sortieren nach + Datum + Titel + +
@@ -164,9 +173,14 @@
Match-Typ - {{ - getMatchTypeLabel(selectedPatent) - }} + + + {{ getMatchTypeLabel(selectedPatent) }} + +
@if (getPublicationStageLabel(selectedPatent); as stageLabel) {
@@ -227,21 +241,21 @@ }

-
+
{{ totalPatents }} Patente
-
+
{{ getInstitutionMatchCount() }} Institution
-
+
{{ getNameMatchCount() }} Name
-
+
{{ getBothMatchCount() }} Beides
diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.scss b/webapp/src/app/modules/institution-patents/institution-patents.component.scss index b5f3fa12..ec7cf852 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.scss +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.scss @@ -26,29 +26,9 @@ gap: 16px; } -.sort-control { - display: inline-flex; - align-items: center; - gap: 6px; +.patents-toolbar-field { width: fit-content; - padding: 10px 14px; - border-radius: 20px; - background: #f2f2f2; - color: #333; - font-size: 14px; - - span { - color: #555; - } - - select { - border: 0; - background: transparent; - color: #111827; - font: inherit; - cursor: pointer; - outline: none; - } + min-width: 180px; } .patents-content { @@ -247,6 +227,34 @@ color: #888; margin-top: 4px; } + + &--total { + .overview-value, + .overview-label { + color: #0b63ce; + } + } + + &--institution { + .overview-value, + .overview-label { + color: #6d28d9; + } + } + + &--name { + .overview-value, + .overview-label { + color: #c2410c; + } + } + + &--both { + .overview-value, + .overview-label { + color: #047857; + } + } } .overview-hint { diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 94c6abca..532fc1d2 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -1,6 +1,9 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; +import { MatIconModule } from '@angular/material/icon'; import { PatentsService } from '../../api/api/patents.service'; import { OrgPatentEntry } from '../../api/model/orgPatentEntry'; import { @@ -15,7 +18,14 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; @Component({ selector: 'app-institution-patents', - imports: [CommonModule, RouterLink, LoadingComponent], + imports: [ + CommonModule, + RouterLink, + LoadingComponent, + MatFormFieldModule, + MatSelectModule, + MatIconModule, + ], templateUrl: './institution-patents.component.html', styleUrl: './institution-patents.component.scss', }) diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 999a7e6b..a030c35c 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -29,6 +29,11 @@
Zeitraum + + + {{ selectedStartYear }} bis {{ selectedEndYear }} + +
-
- {{ selectedStartYear }} - bis - {{ selectedEndYear }} -
-