From 55741208c011147f20667c0f1d583a14c88a132d Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Thu, 19 Nov 2026 10:21:11 -0800 Subject: [PATCH] Score joined initials the parse cuts at a full stop as agreeing (#1470) Since 3.1 (#1296, rules/T7) the parser reads a given-names box holding `B.A.S.D.` as given `B.`, middle `A.S.D.`. local_agreement.read joins the two with a space to compare them with the one box, and the fold could not tell that space from one the filer typed, so the record scored a miss with the box's letters in the box's field. agrees() calls a box and a reading agreeing where they fold alike, or where one writes as one word what the other cuts after one or more of its initials (`B.A.S.D.` and `B.` `A.S.D.`, `V.G.Ravi` and `V.` `G.Ravi`). A cut after a word that is not initials (`Md.Karim`), a run without full stops, a word left over and other letters stay misses. read() uses it for every box and for the suffix comparison, and config_diff.py score reads through read(). Measured with the same parser, old scorer against new: 1,140 orcid-researchers and 35 patentsview-inventors records move from disagreeing to agreeing, all in the given+middle field; no record moves the other way and no other corpus moves. A guard test holds the invariant over a grid both ways, with a recorded negative control. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- tests/v2/test_local_agreement.py | 108 ++++++++++++++++++++++++++ tools/differential/README.md | 2 +- tools/differential/local_agreement.py | 60 +++++++++++++- 4 files changed, 166 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6951f6c53..ff01275af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -328,7 +328,7 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 **Measuring a change to the group suggester: use `tools/differential/suggest_measure.py`.** Run it after any change to `nameparser/_suggest.py`, to `nameparser/config/_order_names.py` (or `tools/vocab/order_names.py`, which writes it) or to a predicate a signal reads (the capitals, particle and patronymic tests, and the title, suffix and numeral tests a name is read past), or to rules/O9, whose reading the `capitals_as_family` vote asks of the parse itself: `suggest` moves no parse, so the snapshot and every corpus check report nothing. It draws groups of known order, 2, 3, 4, 5, 10, 20, 50 and 200 names by default (a change to a threshold adds `--sizes 2,3,4,5,10,20,50,100,200,500,1000,2000`: a share counted among the names that vote holds at 200 names and fails past it, which no default size shows, and #1442's two stray votes decided lists of 500 and more for that reason), from the local corpora and reports the share of groups read right by size, the same-order rows being the anti-goal (at least 95% at every size, save `orcid-givcaps`' two same-order rows, a list writing its given names in capitals (`ANNA Smith`), which the capitals signal reads the wrong way round by design (decisions/group-suggestion, 2026-11-12 CAPITALS), and `orcid-byline-joined`'s given-first row at 50 and 100 names, and at 200 until #1357, a list of nothing but `AM Hoy` bylines that the few names the name tables vote on decide (decisions/group-suggestion, 2026-11-14 #1355, which took `orcid-byline`'s own row off this list, as #1397 took `orcid-famcaps-short`'s); groups of 2 to 4 are where #1308's final review found a patronymic rule forcing given-first on a family-first base); `--set NAME=VALUE` overrides a threshold, and `--set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000` decides nothing and is the harness proof (the order count alone leaves the patronymic rule free to decide its own given-first order, and the two vote counts leave the letters setting free to decide; `_MIN_VOTES` also holds `capitals_as_family`, whose table `--set _MIN_CAPITALS_LETTERS=1000000` empties alone). A table change also moves the `print(suggestion)` evidence docs/getting-started.rst and docs/suggest.rst show as doctests, which `uv run pytest` does not run: run `uv run sphinx-build -b doctest docs ` too (#1374's ORCID table made `Wang Xiaoming` a given-name vote and failed every build job). Its figures are quoted in `Parser.suggest`'s docstring, docs/suggest.rst and docs/design/decisions/group-suggestion.md; re-take all three when they move (decisions/group-suggestion's THRESHOLDS entry names the command, and its latest dated entry carrying a re-taken table, 2026-11-15 #1357's, holds the table the other two round; the 2026-11-12 CAPITALS entry holds the `capitals_as_family` table, which the docstring's and docs/suggest.rst's capitals sentences round). A signal that reads one of the pipeline's predicates must read it exactly where the pipeline's rule does, no wider and no narrower, and its tests need a row at each edge: #1310's patronymic signal first voted an `-ovich` ending on any word (wider: two-word `Abramovich Roman` decided East Slavic and forced given-first), then its fix refused one on the first word, which rules/O1 never asks about (narrower: `Abramovich Roman Arkadyevich`, which the rule reads right, cast nothing). Only the second review caught the narrowing. A signal that votes where exactly ONE end of a name is listed votes by the other end alone once one end is no longer read: #1355's first sketch stopped looking up a short capitals word opening a name, and `WU Zhi` then cast a given-first surname vote by `Zhi`, so the shipped rule silences the signal on the whole name; when a rule stops reading a word, put a name whose other word is listed too in its grid. And a rule keyed to a word's shape needs a population of nothing but that shape: the default populations mix short capitals surnames with long ones, so the ending word's twin of that defect (`Zhi LI`) went unseen from #1308 until #1355 cut `orcid-famcaps-short`, and #1397 fixed it (decisions/group-suggestion, 2026-11-14 #1355 and #1397). A setting has more than one effect, and a suggestion that leaves something out leaves it out on every base: #1356 was first decided on "the East Slavic rule stands down under a family-first order", true of its reordering and false of its `patronymic` view, and PR #1399 as first pushed then kept every family-first base's order. Five names written `Zzyvan Petrovich Qqsidorov` under `FAMILY_FIRST` were read family `Zzyvan` where master moved the base and read them right; and `SIDOROV Ivan Petrovich` five times under `FAMILY_FIRST_GIVEN_LAST` lost the rule, though `capitals_as_family`, suggested in the same patch, makes the rule name the patronymic there. Review found both; the tool's table was identical with and without them, its populations then holding neither shape and no `FAMILY_FIRST_GIVEN_LAST` base anywhere in it (it has read the parliament lists under one since, which catches the second kind on a real list; its draws still run under two bases). Before deciding what a suggestion leaves out, sweep every base order × every switch the same patch can turn on × both written positions of the word the rule reads, and compare whole names read right (given and family), not the family alone: `FAMILY_FIRST_GIVEN_LAST` reads the family of `Sidorov Ivan Petrovich` right and its given name wrong, which a family count scored as nothing to fix. One signal is wider on purpose, and says so where it is decided: the letters signal (#1254) counts a run joined with full stops (`B.K.`), which rules/O8 never moves, beside the spaced runs it does, since three quarters of Nepal's runs are written joined (decisions/group-suggestion, 2026-11-11 LETTER RUNS); a test holds every other run to the rule exactly. -**Validating a new parsing rule** — before implementing, simulate it in a throwaway script against `TEST_NAMES` (plus a few target-language examples) to catch regressions/false-positives early. E.g. this surfaced the `last_base` `do`/`st`/`mc` empties and the patronymic `"David Michael Abramovich"` false-reorder. After the change, `tests/v2/test_snapshot.py` lists every corpus name it moved, grouped by changed field -- read them, and re-record with `uv run python tools/differential/snapshot.py --record` once every move is intended, so the PR diff of `snapshot.jsonl` shows the reviewer the same list. `uv run python tools/differential/cldr_agreement.py` reports how the tree's agreement with CLDR's stated name fields moved; `tests/v2/test_cldr_agreement.py` fails on any move, and `tools/differential/cldr_agreement.json` doubles as a measured list of names the parser and CLDR read differently. The same command and test score the GND corpus's real names (`gnd_fields.jsonl`, record `gnd_agreement.json`) by the same rules, and `--record` rewrites every record, printing per source what it accepts. A locale-pack change reads the second view the same command prints, per pack (`cldr_agreement_locales.json`, #672, and `wikidata_native_agreement_locales.json` for real Han and kana names); its `JA` rows run only with the `ja` extra installed. A change to Han, Hangul or kana order or to Korean segmentation reads `wikidata_native_agreement.json` too: the only real names in those scripts the corpora hold. It holds no honorific, so a change to the honorific peel moves nothing there. A change to comma or credential handling also reads the local corpus of hand-typed names (`snapshot.py --local ctgov-officials --base `, which reads the base from a baseline kept for its package's files and never the shared snapshot beside the corpus (a base read once from the same fetch is copied rather than parsed again; `--sample N` reads a fixed sample while iterating; the shared snapshot beside the corpus is one file per source for every worktree, and #752's phase 2f found ctgov reporting a sibling branch's 1,334 joined-credential readings as its own moves against it); tools/differential/README.md's "Local corpora"): the one population of names nobody chose for a test or a catalog, so it shows how often each shape is typed, and the one no CI run sees. A change to title handling reads `ukec-individuals` the same way: UK donors' names in spoken order and mixed case, in 8,219 of whose 15,214 `parse()` read a title on 2026-10-22. A change to English titles, honorifics or post-nominals also reads `snapshot.py --local govuk-people` the same way: GOV.UK's display names of ministers, officials and officers, the title run and the post-nominals as an office writes them (`The Rt Hon`, `Sir`, `Baroness`, ranks; `KC`, `CBE`, `KCB`), in 2,093 of whose 6,021 `parse()` read one or both on 2026-10-30. A change to Spanish titles, to the `es` pack, or to how a title marks where a name starts after an office reads `snapshot.py --local dof-signatures` the same way: the names in the signature blocks of Mexico's Diario Oficial for 2025, cut from the clause that names the signatory's office, 65.4% of its 33,565 signatures opening with a title (`Lic.`, `Dr.`, `Mtro.`, `C.`, `Licenciada`, `C.P.`), whose first word `parse()` read as a title in 82.1% and `parser_for(locales.ES)` in 86.8% on 2026-10-31. A change to particles or generational words reads `snapshot.py --local tse-donors` the same way, Brazilian names in spoken order dense with both. A change to initials, to a title word outside English, or to how a script's combining marks are read reads `snapshot.py --local nepal-candidates` the same way: Nepal's local election candidates, each a romanized name (surnames written as initials, `B.K.`, `K.C.`; honorific titles such as `Guru` in front, `Shekh`, a title there until #752's phase 2j made it one only inside a title phrase, and `Md.`, a title by its period's shape until #1383 made it Muhammad written short, the given name) beside the same name in Devanagari, written with vowel signs and the virama, combining marks the letter-shape tests do not count as letters (decisions/nfd-shapes), and with the joiners ZWJ and ZWNJ. It is the only large population of South Asian names the corpora hold, and its corpus reads both scripts. A change to non-Latin scripts or to Arabic-script names reads `snapshot.py --local jrc-names` the same way, and `local_corpora.py groups jrc-names`: the spellings of one person across scripts and transliterations, harvested from news text, with 17,074 Arabic-script spellings where the committed corpora hold 315 distinct names with an Arabic letter, 96 of them CLDR's fictional renderings (2026-10-24), and under a licence that keeps even a reading of one of its names in the cache. A change to patronymics, to Turkic or East Slavic names, to Indic titles and initials, or to Slavic or Portuguese double surnames reads `snapshot.py --local opensanctions-parliaments --base ` the same way, and `local_corpora.py groups opensanctions-parliaments`: the members of twenty-eight national chambers as each parliament writes them (Azerbaijan, the Central Asian chambers, Turkey, Croatia, Slovenia, Slovakia, Portugal, India, Ukraine, Belarus, Russia, Indonesia, Ethiopia, South Korea, Israel, Mongolia, and since 2026-11-19 Malaysia, Pakistan's two chambers, Egypt and Somalia, #1465) and Indonesia's 2018 regional heads, read through OpenSanctions, 26,515 spellings of 20,856 members on 2026-11-19 (24,302 of 19,283 on 2026-11-12, before the five chambers and some other lists' newer exports; 24,084 of 19,216 on 2026-11-08, before the Khural and other lists' newer exports), some members' aliases in another script (Kazakh beside Russian Cyrillic, Uzbek Cyrillic beside Latin, Devanagari beside Latin, Hangul and Hanja or Hebrew beside Latin) or with a title (`Shri`, `Smt.`), the population issues #1186 to #1192 were read from, and the one that measures Indonesia's `H.` and `Imam` (#1205, #1206) Ethiopia's father's name (#1203), Korea's Hangul and Hanja (#1213, #1215, #1216) Israel's Hebrew (#1209 to #1211) and Mongolia's Cyrillic, the father's name first (#1237, `mn_parliament`, 126 members, added 2026-11-12), and Egypt's Arabic-script names, each written short and with the full chain of names (#1072, #1464); `config_diff.py --group ` keeps one parliament. A change to Malay, Indian-Malaysian or Chinese-Malaysian names (`bin`, `binti`, `B.`, `bt`, `a/l`, `a/p`, `anak`, the `@` alias, `MD`, honorifics such as `Ustaz` and `Cikgu` opening a name, a Chinese name written family first) or to names written wholly in capitals reads `snapshot.py --local my-candidates --base ` the same way: Malaysia's election candidates of 2008 to 2023 as their ballots name them, in capitals, 3,077 distinct names on 2026-11-19, grouped by the ethnicity each file states (`config_diff.py --group chinese`), the population issues #1467, #1468, #1164, #1183 and #1179 were read from. A change to which field a word lands in also reads `local_agreement.py psc-individuals --base ` the same way: real names with the four boxes their filers typed them into (UK companies' people with significant control), scored field by field and by nationality; and `local_agreement.py orcid-researchers --base `, ORCID holders' own two boxes (given names, family name) from every country, scored by the country they work or live in -- a population each person split for themselves, academic but worldwide, the one to read for a change a language pack makes. Its `name` is COMPOSED from those boxes, given first, so it cannot show which word a writer put first: a count of where a word falls in it is fixed by construction, and #1163's 538 records with the trailing letters in the family box against 0 with the word before them (`Lakshmi R S`, never `R S Lakshmi`) reproduced from that field. Order is measured on the free-text `credit` name (125,960 of the 2026-10-27 fetch's 1,831,533 records, which lean towards bibliographic bylines), against the boxes (decisions/O8); and `local_agreement.py patentsview-inventors --base `, US patents' inventors in the two boxes their filings give, split by a professional filer, with how many people filed under each name in each country, the one to read for how common a name's word is among a country's US-patent inventors. A change to titles or post-nominals, or to the `cs` pack, reads `local_agreement.py cz-candidates --base `, and with `--locale cs` too: Czech election candidates' four boxes (the title before the name, given names, surname, the title after it), scored by election, the only population whose titles are stated apart from the name, 36% of its 170,181 records titled (2026-10-30), nearly all academic degrees; its names are composed from the boxes (`Ing. Jan Novák, Ph.D.`), so it says nothing about how a writer spaces or punctuates them. A change to family-first order, to Vietnamese names or to their titles reads `local_agreement.py uit-vinames --base ` and `local_agreement.py vn-assembly --base `, and with `--locale vi`, `locales.VI` being that pack (#1108): 21,090 distinct names and 499 National Assembly deputies written family name first with their diacritics, whose parts no one filed but the convention derives (first word the family, last the given, the words between the middle name), so they score middle names, which ORCID's two boxes cannot, and `vn-assembly` the `GS.`/`PGS.`/`TS.`/`ThS.` titles composed from the education each deputy states. These are the only real fielded populations outside the committed fields files, and no CI run sees them either. +**Validating a new parsing rule** — before implementing, simulate it in a throwaway script against `TEST_NAMES` (plus a few target-language examples) to catch regressions/false-positives early. E.g. this surfaced the `last_base` `do`/`st`/`mc` empties and the patronymic `"David Michael Abramovich"` false-reorder. After the change, `tests/v2/test_snapshot.py` lists every corpus name it moved, grouped by changed field -- read them, and re-record with `uv run python tools/differential/snapshot.py --record` once every move is intended, so the PR diff of `snapshot.jsonl` shows the reviewer the same list. `uv run python tools/differential/cldr_agreement.py` reports how the tree's agreement with CLDR's stated name fields moved; `tests/v2/test_cldr_agreement.py` fails on any move, and `tools/differential/cldr_agreement.json` doubles as a measured list of names the parser and CLDR read differently. The same command and test score the GND corpus's real names (`gnd_fields.jsonl`, record `gnd_agreement.json`) by the same rules, and `--record` rewrites every record, printing per source what it accepts. A locale-pack change reads the second view the same command prints, per pack (`cldr_agreement_locales.json`, #672, and `wikidata_native_agreement_locales.json` for real Han and kana names); its `JA` rows run only with the `ja` extra installed. A change to Han, Hangul or kana order or to Korean segmentation reads `wikidata_native_agreement.json` too: the only real names in those scripts the corpora hold. It holds no honorific, so a change to the honorific peel moves nothing there. A change to comma or credential handling also reads the local corpus of hand-typed names (`snapshot.py --local ctgov-officials --base `, which reads the base from a baseline kept for its package's files and never the shared snapshot beside the corpus (a base read once from the same fetch is copied rather than parsed again; `--sample N` reads a fixed sample while iterating; the shared snapshot beside the corpus is one file per source for every worktree, and #752's phase 2f found ctgov reporting a sibling branch's 1,334 joined-credential readings as its own moves against it); tools/differential/README.md's "Local corpora"): the one population of names nobody chose for a test or a catalog, so it shows how often each shape is typed, and the one no CI run sees. A change to title handling reads `ukec-individuals` the same way: UK donors' names in spoken order and mixed case, in 8,219 of whose 15,214 `parse()` read a title on 2026-10-22. A change to English titles, honorifics or post-nominals also reads `snapshot.py --local govuk-people` the same way: GOV.UK's display names of ministers, officials and officers, the title run and the post-nominals as an office writes them (`The Rt Hon`, `Sir`, `Baroness`, ranks; `KC`, `CBE`, `KCB`), in 2,093 of whose 6,021 `parse()` read one or both on 2026-10-30. A change to Spanish titles, to the `es` pack, or to how a title marks where a name starts after an office reads `snapshot.py --local dof-signatures` the same way: the names in the signature blocks of Mexico's Diario Oficial for 2025, cut from the clause that names the signatory's office, 65.4% of its 33,565 signatures opening with a title (`Lic.`, `Dr.`, `Mtro.`, `C.`, `Licenciada`, `C.P.`), whose first word `parse()` read as a title in 82.1% and `parser_for(locales.ES)` in 86.8% on 2026-10-31. A change to particles or generational words reads `snapshot.py --local tse-donors` the same way, Brazilian names in spoken order dense with both. A change to initials, to a title word outside English, or to how a script's combining marks are read reads `snapshot.py --local nepal-candidates` the same way: Nepal's local election candidates, each a romanized name (surnames written as initials, `B.K.`, `K.C.`; honorific titles such as `Guru` in front, `Shekh`, a title there until #752's phase 2j made it one only inside a title phrase, and `Md.`, a title by its period's shape until #1383 made it Muhammad written short, the given name) beside the same name in Devanagari, written with vowel signs and the virama, combining marks the letter-shape tests do not count as letters (decisions/nfd-shapes), and with the joiners ZWJ and ZWNJ. It is the only large population of South Asian names the corpora hold, and its corpus reads both scripts. A change to non-Latin scripts or to Arabic-script names reads `snapshot.py --local jrc-names` the same way, and `local_corpora.py groups jrc-names`: the spellings of one person across scripts and transliterations, harvested from news text, with 17,074 Arabic-script spellings where the committed corpora hold 315 distinct names with an Arabic letter, 96 of them CLDR's fictional renderings (2026-10-24), and under a licence that keeps even a reading of one of its names in the cache. A change to patronymics, to Turkic or East Slavic names, to Indic titles and initials, or to Slavic or Portuguese double surnames reads `snapshot.py --local opensanctions-parliaments --base ` the same way, and `local_corpora.py groups opensanctions-parliaments`: the members of twenty-eight national chambers as each parliament writes them (Azerbaijan, the Central Asian chambers, Turkey, Croatia, Slovenia, Slovakia, Portugal, India, Ukraine, Belarus, Russia, Indonesia, Ethiopia, South Korea, Israel, Mongolia, and since 2026-11-19 Malaysia, Pakistan's two chambers, Egypt and Somalia, #1465) and Indonesia's 2018 regional heads, read through OpenSanctions, 26,515 spellings of 20,856 members on 2026-11-19 (24,302 of 19,283 on 2026-11-12, before the five chambers and some other lists' newer exports; 24,084 of 19,216 on 2026-11-08, before the Khural and other lists' newer exports), some members' aliases in another script (Kazakh beside Russian Cyrillic, Uzbek Cyrillic beside Latin, Devanagari beside Latin, Hangul and Hanja or Hebrew beside Latin) or with a title (`Shri`, `Smt.`), the population issues #1186 to #1192 were read from, and the one that measures Indonesia's `H.` and `Imam` (#1205, #1206) Ethiopia's father's name (#1203), Korea's Hangul and Hanja (#1213, #1215, #1216) Israel's Hebrew (#1209 to #1211) and Mongolia's Cyrillic, the father's name first (#1237, `mn_parliament`, 126 members, added 2026-11-12), and Egypt's Arabic-script names, each written short and with the full chain of names (#1072, #1464); `config_diff.py --group ` keeps one parliament. A change to Malay, Indian-Malaysian or Chinese-Malaysian names (`bin`, `binti`, `B.`, `bt`, `a/l`, `a/p`, `anak`, the `@` alias, `MD`, honorifics such as `Ustaz` and `Cikgu` opening a name, a Chinese name written family first) or to names written wholly in capitals reads `snapshot.py --local my-candidates --base ` the same way: Malaysia's election candidates of 2008 to 2023 as their ballots name them, in capitals, 3,077 distinct names on 2026-11-19, grouped by the ethnicity each file states (`config_diff.py --group chinese`), the population issues #1467, #1468, #1164, #1183 and #1179 were read from. A change that cuts one written word across two fields, or joins two written words, first reads how `local_agreement.py` compares a box (`agrees`, tools/differential/README.md): 3.1's #1296 cut `B.A.S.D.` into given `B.`, middle `A.S.D.`, and 1,140 `orcid-researchers` records scored a miss though read right until #1470 (measured 2026-11-19). A change to which field a word lands in also reads `local_agreement.py psc-individuals --base ` the same way: real names with the four boxes their filers typed them into (UK companies' people with significant control), scored field by field and by nationality; and `local_agreement.py orcid-researchers --base `, ORCID holders' own two boxes (given names, family name) from every country, scored by the country they work or live in -- a population each person split for themselves, academic but worldwide, the one to read for a change a language pack makes. Its `name` is COMPOSED from those boxes, given first, so it cannot show which word a writer put first: a count of where a word falls in it is fixed by construction, and #1163's 538 records with the trailing letters in the family box against 0 with the word before them (`Lakshmi R S`, never `R S Lakshmi`) reproduced from that field. Order is measured on the free-text `credit` name (125,960 of the 2026-10-27 fetch's 1,831,533 records, which lean towards bibliographic bylines), against the boxes (decisions/O8); and `local_agreement.py patentsview-inventors --base `, US patents' inventors in the two boxes their filings give, split by a professional filer, with how many people filed under each name in each country, the one to read for how common a name's word is among a country's US-patent inventors. A change to titles or post-nominals, or to the `cs` pack, reads `local_agreement.py cz-candidates --base `, and with `--locale cs` too: Czech election candidates' four boxes (the title before the name, given names, surname, the title after it), scored by election, the only population whose titles are stated apart from the name, 36% of its 170,181 records titled (2026-10-30), nearly all academic degrees; its names are composed from the boxes (`Ing. Jan Novák, Ph.D.`), so it says nothing about how a writer spaces or punctuates them. A change to family-first order, to Vietnamese names or to their titles reads `local_agreement.py uit-vinames --base ` and `local_agreement.py vn-assembly --base `, and with `--locale vi`, `locales.VI` being that pack (#1108): 21,090 distinct names and 499 National Assembly deputies written family name first with their diacritics, whose parts no one filed but the convention derives (first word the family, last the given, the words between the middle name), so they score middle names, which ORCID's two boxes cannot, and `vn-assembly` the `GS.`/`PGS.`/`TS.`/`ThS.` titles composed from the education each deputy states. These are the only real fielded populations outside the committed fields files, and no CI run sees them either. ## Gotchas diff --git a/tests/v2/test_local_agreement.py b/tests/v2/test_local_agreement.py index 43024cea7..e62397cce 100644 --- a/tests/v2/test_local_agreement.py +++ b/tests/v2/test_local_agreement.py @@ -9,6 +9,7 @@ """ import hashlib import importlib +import itertools import json import sys import unicodedata @@ -540,6 +541,113 @@ def test_a_peeled_suffix_is_compared_inside_the_family_box_of_a_joined_source() assert (reading.got, reading.by_suffix) == ({}, True) +@pytest.mark.parametrize("given", [ + "B.A.S.D.", # given B., middle A.S.D. + "K.S", # given K., middle S + "B.H. Nuwan", # given B., middle H. Nuwan + "V.G.Ravi", # given V., middle G.Ravi + "A.B.C", # given A., middle B.C +]) +def test_joined_initials_the_parse_spaces_at_their_full_stops_agree(given: str) -> None: + # #1470: the parse holds the box's letters in the box's field, a + # space after a full stop being all that differs. + record = _held(given, "Kumarasiri", "LK") + assert agreement.read(record, _ORCID_FIELDS, Parser(), _LISTED).got == {} + # The control: compared folded alone, as before #1470, it is a miss. + assert agreement.fold(given) != agreement.fold( + " ".join(filter(None, (lambda p: (p.given, p.middle))(Parser().parse(record["name"]))))) + + +@pytest.mark.parametrize(("given", "family", "got"), [ + # A word before the full stop, not initials: Md is Muhammad written + # short, and Jo.Ann the same shape with no vocabulary involved. + ("Md.Karim", "Hossain", {"given+middle": "Md. Karim"}), + ("Jo.Ann", "Lee", {"given+middle": "Jo. Ann"}), + # The box's letters read as a title: no field holds them. + ("AB", "Lee", {"given+middle": ""}), + # A word of the family box read into the given box's field. + ("K.S", "Perera Silva", {"given+middle": "K. S Perera", "family": "Silva"}), + # A title glued before the box's initials, peeled to a field ORCID has no box for. + ("Dr.A.B.", "Perera", {"given+middle": "A. B."}), +]) +def test_a_misreading_beside_joined_initials_stays_a_miss( + given: str, family: str, got: dict[str, str]) -> None: + assert agreement.read(_held(given, family), _ORCID_FIELDS, Parser(), _LISTED).got == got + + +@pytest.mark.parametrize(("box", "got", "same"), [ + ("a.b.", "a. b.", True), # box joined, reading spaced + ("a. b.", "a.b.", True), # box spaced, reading joined + ("A.B. Lee", "a. b. lee", True), + ("A.B.", "A. B. Lee", False), # a word left over + ("A.B. Lee", "A. B. Ann Lee", False), # a word left over in the middle + ("A.Bc.D.", "A. Bc. D.", False), # a word inside the run + ("1.2.", "1. 2.", False), # digits are not initials + ("A.B.", "A. C.", False), # other letters + ("A.B.", "A.", False), # letters missing + ("AB", "A B", False), # no full stops: a word, not initials + ("A B", "AB", False), + ("MD", "M D", False), + ("Al", "A l", False), + ("Jo.Ann", "Jo. Ann", False), # a word before the full stop + ("K.S", "K S", False), # the reading's full stop gone + ("क.ख.", "क. ख.", True), # letters of any script + ("कि.ख.", "कि. ख.", True), # a letter with its vowel sign, a combining mark +]) +def test_agreement_across_a_joint_after_initials_only(box: str, got: str, same: bool) -> None: + assert agreement.agrees(box, got) is same + assert agreement.agrees(got, box) is same + + +#: The joined-initials grid: a run of initials, with a name word glued +#: to it, one or two spaced from it, or none, before a one- and a +#: two-word family. +_INITIAL_RUNS = ("A.", "A.B.", "A.B", "A.B.C.", "A.B.C", "Т.В.", "क.ख.") +#: How many of the grid's records the comparison before #1470 scored a +#: miss, though the reading held the box's letters in the box's field: the +#: guard's negative control, re-taken whenever the grid or the parse moves. +_UNGUARDED_EFFECT = 22 +#: The grid's records whose reading holds the box's letters in the box's +#: field, and the rest, read with a word of the family box in the given +#: box's field (`A.B. Kumarasiri Silva`), which stay misses. +_HELD, _MISREAD = 28, 28 + + +def test_a_reading_cut_only_after_initials_is_never_scored_a_miss( + monkeypatch: pytest.MonkeyPatch) -> None: + # #1470: 3.1's #1296 began reading `B.A.S.D.` as given `B.`, middle + # `A.S.D.`, and the space the scorer's join puts between the two, + # which the fold kept, scored a miss where the box was read right. + # Wherever the box's field holds the box's letters, the cut a parse + # draws after initials must not decide the score. + # "The box's letters" is the fold with its spaces removed, which is + # looser than the rule (`AB` against `A B` would pass it): every run + # in the grid holds a full stop, so the filter never meets that case. + parser = Parser() + rows: list[dict[str, str]] = [] + misread: list[dict[str, str]] = [] + for run, rest, family in itertools.product( + _INITIAL_RUNS, ("", " Nuwan", "Nuwan", " Nuwan Ravi"), ("Perera", "Kumarasiri Silva")): + record = _held(run + rest, family, "LK") + name = parser.parse(record["name"]) + held = " ".join(filter(None, (name.given, name.middle))) + same = agreement.fold(held).replace(" ", "") == agreement.fold(record["given"]).replace(" ", "") + (rows if same else misread).append(record) + assert (len(rows), len(misread)) == (_HELD, _MISREAD) + + def misses(records: list[dict[str, str]]) -> int: + return sum("given+middle" in agreement.read(r, _ORCID_FIELDS, parser, _LISTED).got + for r in records) + + assert misses(rows) == 0 + # The other half: a word of the family box read beside the initials + # stays a miss. + assert misses(misread) == _MISREAD + # The negative control: compared folded alone, as before #1470. + monkeypatch.setattr(agreement, "agrees", lambda box, got: agreement.fold(box) == agreement.fold(got)) + assert misses(rows) == _UNGUARDED_EFFECT + + def test_a_country_code_group_prints_as_written(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(agreement, "GROUP_FLOOR", 1) result = agreement.score([_held("Ann", "Lee"), _held("Bo Yu", "Wu Li", "CN")], diff --git a/tools/differential/README.md b/tools/differential/README.md index e4482695f..39eacd589 100644 --- a/tools/differential/README.md +++ b/tools/differential/README.md @@ -361,7 +361,7 @@ Its score reads the title before the name against `TITULPRED`, the given and mid `my-candidates` downloads the five pinned files and refuses one whose sha256 is not the pinned one (retried first, as a body cut short), then, in this order, one of another header than the file's pinned one, one whose body does not end with a line break or whose last row is short (as `opensanctions-parliaments` does), one holding another number of rows than pinned, and past their shares rows of another width (`MY_MAX_BAD`) and rows with an empty name in a column read (`MY_MAX_NAMELESS`), a row counted once however many of its columns are empty. Its data date is the pinned commit's, and a corpus read at another `MY_COMMIT` or by another `MY_READ_VERSION` is refused on load. It holds no fields, so it is a `snapshot.py --local` population, not a `local_agreement.py` one. The fetch took under a second on 2026-11-19. -`local_agreement.py` does the SCORE job for a local corpus. It parses each filed display name and compares the parser's roles with the boxes the source states (title, given, middle and family for `psc-individuals`; given and middle joined against the given-names box, then family, for `orcid-researchers` and `patentsview-inventors`; title, given and middle joined, family and suffix for `cz-candidates`; family, middle and given, the parts derived, for `uit-vinames`; and title, family, middle and given for `vn-assembly`), folding case, periods, commas and spacing. Where the source has no box after the name, a suffix the parser peels is compared inside the surname box: the display name joins the surname last, so a trailing suffix was typed into it whenever it is filled, with or without a comma (`Smith, Jr.`); the fold read the comma as a miss until 2026-10-28, which moved 83 `psc-individuals` records and 561 `orcid-researchers` records to agreeing and none away. Where a source has a title box, and save `cz-candidates` (above), a title the parser reads otherwise, holding a word the vocabulary lists as neither a title nor a connective (a job typed as a title), is set aside as filer error rather than scored, and the report lists the commonest such titles as leads for the vocabulary. The report gives agreement overall and by the group the source states (nationality, country), misses per field, and the commonest disagreement shapes, as counts, word counts and the commonest set-aside titles; `--list N` prints moved records, names and all, for reading locally. Its record, `agreement.jsonl` beside the corpus, holds every record that did not wholly agree, so a re-run reports what moved. As with the local snapshot, check it from the branch against a base you name (`--base `, whose record is kept under `agreements/` beside the corpus, keyed by the fetch, the base's `nameparser/` files, the interpreter's minor version and the scorer, the ten most recent kept; the scorer's fingerprint reads only its own source's `FIELDED` entry, so adding a source leaves the others' records standing, which the whole table, hashed until `patentsview-inventors` was added on 2026-10-28, did not), or, alone, record the shared one from the base checkout (`--record --tree `) and run it from the branch; it refuses a record from another fetch, or one written by another version of the scorer, whose own change would otherwise read as the parser's moves. `--locale cs` scores the parser of a locale pack, `parser_for(locales.CS)`, against a record of its own (`agreement.cs.jsonl`, and kept records keyed by the locale too), so a pack's score and the default's never stand for each other; `measure.py` runs the default's alone. No CI run sees it. +`local_agreement.py` does the SCORE job for a local corpus. It parses each filed display name and compares the parser's roles with the boxes the source states (title, given, middle and family for `psc-individuals`; given and middle joined against the given-names box, then family, for `orcid-researchers` and `patentsview-inventors`; title, given and middle joined, family and suffix for `cz-candidates`; family, middle and given, the parts derived, for `uit-vinames`; and title, family, middle and given for `vn-assembly`), folding case, periods, commas and spacing. Where the source has no box after the name, a suffix the parser peels is compared inside the surname box: the display name joins the surname last, so a trailing suffix was typed into it whenever it is filled, with or without a comma (`Smith, Jr.`); the fold read the comma as a miss until 2026-10-28, which moved 83 `psc-individuals` records and 561 `orcid-researchers` records to agreeing and none away. Joining two fields to compare them with one box puts a space between them, which the fold cannot tell from one the filer typed, and a reading that cuts one written word across the two makes it false: 3.1's run of initials (#1296, rules/T7) reads the box `B.A.S.D.` as given `B.`, middle `A.S.D.`, and 1,140 `orcid-researchers` records (403 of them Sri Lanka's) and 35 `patentsview-inventors` records scored a miss with the box's letters in the box's field (measured 2026-11-19), until #1470 had a word agree with the reading that cuts it after one or more of its initials (`agrees`, guarded by `test_a_reading_cut_only_after_initials_is_never_scored_a_miss` with a recorded negative control); a cut after anything but initials still scores a miss (`Md.Karim` read `Md.`, `Karim`: 168 `orcid-researchers` records and 1 `patentsview-inventors` record on 2026-11-19). A parser change that cuts one written word across two fields, or joins two written words, reads `agrees` before trusting the score it moves. Where a source has a title box, and save `cz-candidates` (above), a title the parser reads otherwise, holding a word the vocabulary lists as neither a title nor a connective (a job typed as a title), is set aside as filer error rather than scored, and the report lists the commonest such titles as leads for the vocabulary. The report gives agreement overall and by the group the source states (nationality, country), misses per field, and the commonest disagreement shapes, as counts, word counts and the commonest set-aside titles; `--list N` prints moved records, names and all, for reading locally. Its record, `agreement.jsonl` beside the corpus, holds every record that did not wholly agree, so a re-run reports what moved. As with the local snapshot, check it from the branch against a base you name (`--base `, whose record is kept under `agreements/` beside the corpus, keyed by the fetch, the base's `nameparser/` files, the interpreter's minor version and the scorer, the ten most recent kept; the scorer's fingerprint reads only its own source's `FIELDED` entry, so adding a source leaves the others' records standing, which the whole table, hashed until `patentsview-inventors` was added on 2026-10-28, did not), or, alone, record the shared one from the base checkout (`--record --tree `) and run it from the branch; it refuses a record from another fetch, or one written by another version of the scorer, whose own change would otherwise read as the parser's moves. `--locale cs` scores the parser of a locale pack, `parser_for(locales.CS)`, against a record of its own (`agreement.cs.jsonl`, and kept records keyed by the locale too), so a pack's score and the default's never stand for each other; `measure.py` runs the default's alone. No CI run sees it. `pairs` reads a paired source (`tse-donors`, whose records carry the registry's name beside the filed one) as two spellings of one person, and sorts each pair by how the filed name departs from the reference: the first of its shapes that fits, from case, accents (case unchanged) and case and accents together, through words left out, shortened or misspelled, to few words in common. A word left out or added counts once per pair, and is listed only when ten pairs share it. `--agreement` also parses both spellings of every pair with a reference name that differs, and counts the pairs whose two readings end the family name in the same word (two readings with no family name share none). It lists the accents-only pairs read with two surnames by the two spellings' last words, the same ten-pair floor applied. diff --git a/tools/differential/local_agreement.py b/tools/differential/local_agreement.py index 513710837..4eebc41ae 100644 --- a/tools/differential/local_agreement.py +++ b/tools/differential/local_agreement.py @@ -54,7 +54,11 @@ boxes joined, so the parser sees the filer's own spelling, and the fold only keeps a box's case, periods, commas or spacing from reading as a miss: a suffix typed into the surname box after a comma - (`Smith, Jr.`) is the parser's family and suffix rejoined. + (`Smith, Jr.`) is the parser's family and suffix rejoined. Initials + written joined agree with a reading that cuts them after one or more + of them (agrees): since 3.1 (#1296, rules/T7) a box holding `B.A.S.D.` is + read given `B.`, middle `A.S.D.`, and the scorer's join of the two + puts a space where the filer typed none (#1470). - Where a source has no suffix box, a suffix the parser peels (`Jr`, `OBE`) stood last in the display name, so it was typed into the last filled box, normally the surname: the parser's family is compared @@ -83,6 +87,7 @@ import subprocess import sys import types +import unicodedata from collections import Counter from collections.abc import Callable, Iterator from dataclasses import dataclass, field @@ -178,6 +183,53 @@ def fold(text: str) -> str: return " ".join(text.replace(".", "").replace(",", " ").casefold().split()) +def agrees(box: str, got: str) -> bool: + """Whether a box and the parser's value for it agree: the same once + folded (fold), or the same words save that one side writes as one + word what the other cuts after one or more of its initials + (_joined): the parser reads the box `B.A.S.D.` as given + `B.`, middle `A.S.D.`, and `V.G.Ravi` as `V.`, `G.Ravi`, the box's + letters in the box's field (#1470).""" + if fold(box) == fold(got): + return True + box_words, got_words = _words(box), _words(got) + return _joined(box_words, got_words) or _joined(got_words, box_words) + + +def _words(text: str) -> list[str]: + """`text`'s words as written, less any that fold reads as nothing.""" + return [w for w in text.split() if fold(w)] + + +def _initials(word: str) -> bool: + """Whether `word` is one or more initials, each a letter (with any + combining marks) and a full stop: `B.`, `A.S.D.`, never `Md.`.""" + return word.endswith(".") and all( + chunk[:1].isalpha() and all(unicodedata.category(c).startswith("M") for c in chunk[1:]) + for chunk in word[:-1].split(".")) + + +def _joined(joined: list[str], spaced: list[str]) -> bool: + """Whether `spaced` is `joined` with some words cut after initials: + each word of `joined` is the next of `spaced` as fold reads them, or + is spelled, case aside, by the next two or more of `spaced`, each + but the last initials (`B.A.S.D.` by `B.` `A.S.D.`, `K.S` by `K.` + `S`, never `AB` by `A` `B` or `Md.Karim` by `Md.` `Karim`), and no + word of `spaced` is left over.""" + i = 0 + for word in joined: + if i < len(spaced) and fold(word) == fold(spaced[i]): + i += 1 + continue + built, j = spaced[i] if i < len(spaced) else "", i + 1 + while j < len(spaced) and len(built) < len(word) and _initials(spaced[j - 1]): + built, j = built + spaced[j], j + 1 + if j - i < 2 or built.casefold() != word.casefold(): + return False + i = j + return i == len(spaced) + + def _title_words(lexicon: Lexicon) -> frozenset[str]: return frozenset(lexicon._sets.titles) | frozenset(lexicon._sets.conjunctions) @@ -211,10 +263,10 @@ def read(record: dict[str, str], fielded: Fielded, parser: Parser, if name.suffix and not _box(fielded, "suffix"): family = fielded.fields[_box(fielded, "family")] with_suffix = f"{got[family]} {name.suffix}".strip() - by_suffix = fold(with_suffix) == fold(record.get(_box(fielded, "family"), "")) + by_suffix = agrees(record.get(_box(fielded, "family"), ""), with_suffix) got[family] = with_suffix wrong = {role: got[role] for box, role in fielded.fields.items() - if fold(record.get(box, "")) != fold(got[role])} + if not agrees(record.get(box, ""), got[role])} title = record.get(_box(fielded, "title"), "") if fielded.sets_aside and title and "title" in wrong and unlisted(title, listed): return Reading(wrong, set_aside=True) @@ -415,7 +467,7 @@ def read_record(path: Path, local: local_corpora.Local, locale: str = "" #: What decides a record's reading, besides the parser: scorer_fingerprint #: hashes them, as local_corpora.fold_fingerprint hashes the word fold. -_SCORER_CODE = ("fold", "_title_words", "unlisted", "read", "_box", "Reading", +_SCORER_CODE = ("fold", "agrees", "_words", "_initials", "_joined", "_title_words", "unlisted", "read", "_box", "Reading", "key", "score", "_read_chunk", "parser_of")