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)