diff --git a/AGENTS.md b/AGENTS.md index ac7ba38bd..22160d2cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -334,7 +334,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 or rules/O6, whose readings the `capitals_as_family` and `two_family_names` votes ask 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 `pv-listed-given`'s two same-order rows, a list of nothing but given names that are surnames the ORCID surname table lists (`Cooper`, `Burke`, `Clarke`), which that table reads the wrong way round, a cost left open (decisions/group-suggestion, 2026-11-19 #1364), 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 --set _MIN_TWO_FAMILY_VOTES=1000000` decides nothing and is the harness proof (the order count alone leaves the patronymic rule free to decide its own given-first order, the two vote counts leave the letters setting free to decide, and the last holds `two_family_names`; `_MIN_VOTES` also holds `capitals_as_family`, whose table `--set _MIN_CAPITALS_LETTERS=1000000` empties alone). A change to the `two_family_names` vote reads the `orcid-span-CC` populations (ORCID holders of a country, the boxes saying which words are the family) by country: the groups deciding the switch, which the countries the switch costs (Bangladesh, Ghana, Kenya, Pakistan, Vietnam, Angola, Mozambique, Turkey) must not reach, and whole names right under the suggestion against the base (decisions/group-suggestion, 2026-11-19 #1452). 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 entries carrying re-taken sizes, 2026-11-19 #1364's, #1447's and #1452's, hold the figures 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 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 title vocabulary reads `local_agreement.py --base`'s `titled in` and `titled out` lines beside its regressions: a listed title the filer typed into the given-names box and the parse reads as the title is counted apart from the agreement figure since #1501, 9,145 `orcid-researchers` records on 2026-11-20, so a word newly read as a title moves records that agreed into `titled in` (a given name wrongly peeled, as `Hon` is in Hong Kong), not into the regressions; read the titles listed there. 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 to how a surname followed by initials is read (`Fox DE`, a citation's byline), to a family-first order, or to a credential that two or three initials can spell reads `local_agreement.py pmc-citations --base `: the names tagged inside the text of PubMed Central's reference lists, each kept as written beside its tagged surname and given names, so the one population `local_agreement.py` scores whose name is the writer's own text beside parts the source tagged, grouped by the order written (a prototype over a sample of articles, #1540: 68,215 records from 4,915 articles in the 2026-12-01 fetch, 43,500 a surname then given names with no comma, 43,381 of them initials alone, which the default read 0.0% right and `name_order=FAMILY_FIRST` 91.0%, 3,175 of the 3,929 it missed being initials read as a credential, `MA`, `AM`, `CM`); `local_agreement.py pmc-authors` scores the contributors of a sample of the same specification, composed given first with the prefix, suffix and degrees each article tags apart from the name. 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 title vocabulary reads `local_agreement.py --base`'s `titled in` and `titled out` lines beside its regressions: a listed title the filer typed into the given-names box and the parse reads as the title is counted apart from the agreement figure since #1501, 9,145 `orcid-researchers` records on 2026-11-20, so a word newly read as a title moves records that agreed into `titled in` (a given name wrongly peeled, as `Hon` is in Hong Kong), not into the regressions; read the titles listed there. 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_corpora.py b/tests/v2/test_local_corpora.py index a156a086f..ef1d4624a 100644 --- a/tests/v2/test_local_corpora.py +++ b/tests/v2/test_local_corpora.py @@ -3595,15 +3595,15 @@ def test_no_module_imports_a_sibling_constant() -> None: # module. A `from local_x import CONSTANT` would bind a second name a # patch on local_x cannot reach, and a test could pass with its guard # off. The modules are SOURCES' own, so a new source is covered. PSC, - # JRC, ORCID, PV, VOLBY, DOF, UIT, VN, PARLIAMENTS, MY, CTGOV_OFFICIALS and - # CTGOV_CONTACTS are sources' names, keys of + # JRC, ORCID, PV, VOLBY, DOF, UIT, VN, PARLIAMENTS, MY, PMC_AUTHORS, + # PMC_CITATIONS, CTGOV_OFFICIALS and CTGOV_CONTACTS are sources' names, keys of # SOURCES, and no fetch's setting; split is a function, not a setting. import ast sources = {source.fetch.__module__ for source in local.SOURCES.values()} assert sources == {m.__name__ for m in (ctgov, fec, tse, tw, ukec, psc, jrc, nepal, orcid, patentsview, volby, dof, uit, vnassembly, parliaments, mycandidates) - } | {"local_govuk"} + } | {"local_govuk", "local_pmc"} siblings = {"local_corpora", "local_core", *sources} imported = {(path.stem, alias.name) for path in (Path(str(local.__file__)).parent / f"{s}.py" @@ -3616,6 +3616,8 @@ def test_no_module_imports_a_sibling_constant() -> None: ("local_corpora", "VOLBY"), ("local_corpora", "DOF"), ("local_corpora", "UIT"), ("local_corpora", "VN"), ("local_corpora", "PARLIAMENTS"), ("local_corpora", "MY"), + ("local_corpora", "PMC_AUTHORS"), + ("local_corpora", "PMC_CITATIONS"), ("local_corpora", "CTGOV_OFFICIALS"), ("local_corpora", "CTGOV_CONTACTS")} diff --git a/tests/v2/test_local_pmc.py b/tests/v2/test_local_pmc.py new file mode 100644 index 000000000..989ca0654 --- /dev/null +++ b/tests/v2/test_local_pmc.py @@ -0,0 +1,493 @@ +"""Offline checks on tools/differential/local_pmc.py, the pmc-authors +and pmc-citations local corpora. + +Every name here is invented: the articles' names are personal data and +each article keeps its own licence, so not one of them may reach the +repository. What these pin is how a name is read off JATS markup (the +composed contributor, the cited name as written, its order), what the +fetch keeps, skips and counts, and its refusals. The network is a stub +answering by URL. +""" +import importlib +import json +import time +import urllib.error +import urllib.request +import xml.etree.ElementTree as ET +from collections.abc import Callable +from pathlib import Path + +import pytest + +from ._differential_fixtures import _Response, load_tool, own_cache + +local = load_tool("local_corpora") +agreement = load_tool("local_agreement") +# The module the fetch reads its constants from, by name: a patch set on +# a second load by path would reach nothing (test_local_corpora.py). +core = importlib.import_module("local_core") +pmc = importlib.import_module("local_pmc") + + +@pytest.fixture(autouse=True) +def _own_cache(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.TempPathFactory) -> Path: + # A walk waits for the corpus that has not taken it, so each test starts with none. + monkeypatch.setattr(pmc, "_walk", {}) + return own_cache(monkeypatch, tmp_path_factory) + + +def _article(contribs: str = "", refs: str = "", journal: str = "J Invented") -> bytes: + return (f'
{journal}' + f"{contribs}" + f"{refs}" + f"
").encode() + + +_ROE = ('Roe' + 'Jane Q.Dr' + "JrMD, PhD") +_WU = "WuBo" +_REFS = ('Fox, D. E.' + ", CY" + "Lee, Van Poe " + "AB 3rd. A title." + "") + + +@pytest.mark.parametrize(("markup", "name", "order"), [ + ("Fox, D. E.", "Fox, D. E.", "family, given"), + ("Fox DE", "Fox DE", "family given"), + # Tags stored glued, as PMC stores a separator that was whitespace alone. + ("FoxDE", "Fox DE", "family given"), + ("DEFox", "DE Fox", "given family"), + ("\nD. E.\nFox\nIII\n", + "D. E. Fox III", "given family"), + ("Fox DE, Jr", + "Fox DE, Jr", "family given"), + # The comma may stand after a suffix written between the two parts. + ("Fox Jr, DE", + "Fox Jr, DE", "family, given"), + # Text before the first tag and after the last, the edge punctuation dropped. + ("and Fox, D. E.;", "and Fox, D. E.", + "family, given"), + # A line break before the comma leaves no space before it. + ("Fox\n , DE", "Fox, DE", "family, given"), + # A prefix ahead of the given names does not make the name family-first. + ("Dr DE Fox", "Dr DE Fox", + "given family"), + # Markup nested inside a part. + ("Fox DE", "Fox DE", + "family given"), + # A tail holding text takes no space. + ("DE-Fox", "DE-Fox", "given family"), +]) +def test_a_cited_name_is_its_text_as_written_with_its_order( + markup: str, name: str, order: str) -> None: + record = pmc.citation(ET.fromstring(f"{markup}")) + assert record is not None + assert (record["name"], record["order"]) == (name, order) + assert (record["family"], record["given"].replace(".", "").replace(" ", "")) == ("Fox", "DE") + + +@pytest.mark.parametrize("markup", [ + "The Invented Consortium", + "Cy", + "Fox DE", +]) +def test_a_cited_name_without_both_parts_tagged_is_skipped(markup: str) -> None: + assert pmc.citation(ET.fromstring(f"{markup}")) is None + + +def test_a_contributor_is_composed_given_first_with_the_degrees_in_the_suffix_box() -> None: + assert pmc.author(ET.fromstring(_ROE)) == { + "name": "Dr Jane Q. Roe Jr, MD, PhD", "prefix": "Dr", "given": "Jane Q.", + "family": "Roe", "suffix": "Jr MD, PhD"} + assert pmc.author(ET.fromstring(_WU)) == {"name": "Bo Wu", "given": "Bo", "family": "Wu"} + several = ("WuBo\n Li" + "MD,PhD;") + assert pmc.author(ET.fromstring(several)) == { + "name": "Bo Li Wu, MD, PhD", "given": "Bo Li", "family": "Wu", "suffix": "MD, PhD"} + + +@pytest.mark.parametrize("names", [ + '吴波{latin}', + '{latin}吴波', +], ids=["Han first", "Latin first"]) +def test_of_a_contributor_s_alternatives_the_latin_name_is_read(names: str) -> None: + # Composed given names first, the Han name would score as a miss of + # the parser, which reads a wholly-Han name family first. + latin = "WúBo" + contrib = f"{names.format(latin=latin)}" + assert pmc.author(ET.fromstring(contrib)) == {"name": "Bo Wú", "given": "Bo", "family": "Wú"} + han = contrib.replace(latin, "") + assert pmc.author(ET.fromstring(han)) == {"name": "波 吴", "given": "波", "family": "吴"} + # An alternative with no surname is no candidate, though it holds no + # letter that is not Latin. + empty = contrib.replace("", "") + assert pmc.author(ET.fromstring(empty)) == {"name": "Bo Wú", "given": "Bo", "family": "Wú"} + + +@pytest.mark.parametrize(("text", "latin"), [ + ("Bo Wú", True), ("Bo Wu\u0301", True), ("Gʻulomov Bo", True), ("Oʼroe", True), + ("Mª Roe", True), ("Wu", True), ("O'Roe-Fox 3", True), + ("吴 波", False), ("Иван Roe", False), ("Wu 波", False), +]) +def test_a_name_is_latin_by_its_letters(text: str, latin: bool) -> None: + assert pmc._latin(text) is latin + + +@pytest.mark.parametrize("contrib", [ + "The Invented Group", + "Cy", + "Wu Bo" + "", + # A group's members are contributors of their own, never the group's name. + "Group" + _WU + "", +]) +def test_a_contributor_with_no_name_of_its_own_holding_a_surname_is_skipped( + contrib: str) -> None: + assert pmc.author(ET.fromstring(contrib)) is None + + +def test_the_journal_falls_back_to_its_title_and_only_a_mixed_citation_s_names_are_read() -> None: + body = (b"
jinv" + b"Journal of Invention" + b"" + b"FoxDE" + b"" + b"RoeA" + b"Poe" + b" A" + b"
") + assert pmc.read_article(body) == ("Journal of Invention", [], []) + both = body.replace(b"", b"J Invent", 1) + assert pmc.read_article(both)[0] == "J Invent" + + +def _listing(keys: list[str], *, count: int | None = None, between: str = "") -> bytes: + """A bucket listing of `keys`' metadata, dated a day apart in order.""" + entries = "".join( + f"{key if '/' in key else f'metadata/{key}.json'}{between}" + f"2026-11-{i + 1:02d}T00:00:00.000Z" + for i, key in enumerate(keys)) + return (f'' + f"{len(keys) if count is None else count}{entries}" + f"").encode() + + +def _serve(monkeypatch: pytest.MonkeyPatch, articles: dict[str, bytes], *, + retracted: frozenset[str] = frozenset(), + answers: dict[str, list[bytes]] | None = None, floor: bool = False) -> list[str]: + """Answer the bucket from `articles` (key -> XML), numbered from + PMC100 up to PMC1099: the sample's first start lists every key and + its second none. `answers` gives a URL's bodies in turn, ahead of + the stub's own, _LIST standing for the first start's listing; a 404 + answers anything else. The floor on the articles listed is off + unless `floor`, the sample asking for twice the keys served. Returns + the URLs asked.""" + for name, value in (("PMC_FIRST", 100), ("PMC_LAST", 2100), ("PMC_STARTS", 2), + ("PMC_RUN", len(articles)), ("PMC_THREADS", 1)): + monkeypatch.setattr(pmc, name, value) + if not floor: + monkeypatch.setattr(pmc, "PMC_MIN_LISTED", 0) + monkeypatch.setattr(time, "sleep", lambda seconds: None) + queued = {pmc.list_url(100) if url == _LIST else url: list(bodies) + for url, bodies in (answers or {}).items()} + asked: list[str] = [] + + def urlopen(request: urllib.request.Request, timeout: int) -> _Response: + url = request.full_url + asked.append(url) + if queued.get(url): + return _Response(queued[url].pop(0)) + if url == pmc.list_url(100): + return _Response(_listing(sorted(articles))) + if url == pmc.list_url(1100): + return _Response(_listing([])) + key = url.rsplit("/", 1)[1].rsplit(".", 1)[0] + if url == _meta_url(key) and key in articles: + return _Response(json.dumps({ + "pmcid": key.split(".")[0], "license_code": "CC BY", + "is_retracted": key in retracted}).encode()) + if url == _xml_url(key) and key in articles: + return _Response(articles[key]) + raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) # type: ignore[arg-type] + monkeypatch.setattr(urllib.request, "urlopen", urlopen) + return asked + + +_LIST = "the first start's listing" + + +def _meta_url(key: str) -> str: + return f"{pmc.PMC_BUCKET}metadata/{key}.json" + + +def _xml_url(key: str) -> str: + return f"{pmc.PMC_BUCKET}{key}/{key}.xml" + + +def test_one_walk_of_the_sample_fills_both_corpora(monkeypatch: pytest.MonkeyPatch) -> None: + asked = _serve(monkeypatch, { + "PMC100.1": _article(_ROE + _WU, _REFS), + # The same contributor again, an older version of one article and + # a retracted article: none adds a record. + "PMC101.1": _article(_WU, journal="J Other"), "PMC101.2": _article(_WU + _ROE), + "PMC102.1": _article(_ROE.replace("Roe", "Gone"))}, + retracted=frozenset({"PMC102.1"})) + authors = local.fetch(pmc.PMC_AUTHORS) + cited = local.fetch(pmc.PMC_CITATIONS) + tags = {"journal": "J Invented", "licence": "CC BY"} + assert authors.records == [ + {"name": "Bo Wu", "given": "Bo", "family": "Wu", **tags, "article": "PMC100.1"}, + {"name": "Dr Jane Q. Roe Jr, MD, PhD", "prefix": "Dr", "given": "Jane Q.", + "family": "Roe", "suffix": "Jr MD, PhD", **tags, "article": "PMC100.1"}] + assert cited.records == [ + {"name": "CY Lee", "given": "CY", "family": "Lee", "order": "given family", + **tags, "article": "PMC100.1"}, + {"name": "Fox, D. E.", "given": "D. E.", "family": "Fox", "order": "family, given", + **tags, "article": "PMC100.1"}, + {"name": "Van Poe AB 3rd", "given": "AB", "family": "Van Poe", "suffix": "3rd", + "order": "family given", **tags, "article": "PMC100.1"}] + # The newest date sampled is the retracted article's. + assert authors.meta["data_date"] == cited.meta["data_date"] == "2026-11-04T00:00:00.000Z" + assert authors.meta["detail"] == cited.meta["detail"] == { + "sample": pmc.sample(), "articles": 3, "retracted": 1, "read": 2, "licence CC BY": 2, + "no_journal": 0, "with_authors": 2, "with_cited_names": 1, "author_names": 4, + "cited_names": 3} + # The second fetch read nothing more; the older version was never + # read, nor the retracted article's XML. + assert len(asked) == 2 + 3 + 2 + assert not any("PMC101.1" in url for url in asked) + assert _xml_url("PMC102.1") not in asked + + +def test_a_second_fetch_of_one_corpus_walks_the_sample_again( + monkeypatch: pytest.MonkeyPatch) -> None: + asked = _serve(monkeypatch, {"PMC100.1": _article(_WU, _REFS)}) + local.fetch(pmc.PMC_AUTHORS) + local.fetch(pmc.PMC_AUTHORS) + local.fetch(pmc.PMC_CITATIONS) + assert asked.count(pmc.list_url(100)) == 2 + + +def test_of_an_article_s_versions_the_highest_number_is_read( + monkeypatch: pytest.MonkeyPatch) -> None: + # .10 sorts before .2 and .9 as text, the order the stub lists in. + asked = _serve(monkeypatch, { + "PMC100.2": _article(_WU), "PMC100.10": _article(_ROE), "PMC100.9": _article(_WU)}) + assert [r["article"] for r in local.fetch(pmc.PMC_AUTHORS).records] == ["PMC100.10"] + assert _meta_url("PMC100.2") not in asked and _meta_url("PMC100.9") not in asked + + +def test_one_spelling_tagged_two_ways_is_two_records(monkeypatch: pytest.MonkeyPatch) -> None: + refs = ("Van Poe AB" + " Van " + "Poe AB") + _serve(monkeypatch, {"PMC100.1": _article(_WU, refs)}) + cited = local.fetch(pmc.PMC_CITATIONS).records + assert sorted((r["name"], r["family"]) for r in cited) == [ + ("Van Poe AB", "Poe AB"), ("Van Poe AB", "Van Poe")] + + +def test_the_sample_is_spread_over_the_range_and_pinned_whole( + monkeypatch: pytest.MonkeyPatch) -> None: + assert set(pmc.sample()) == {"first", "last", "starts", "run", "read_version"} + for name, value in (("PMC_FIRST", 100), ("PMC_LAST", 210), ("PMC_STARTS", 4), + ("PMC_RUN", 7)): + monkeypatch.setattr(pmc, name, value) + assert pmc.sample() == {"first": 100, "last": 210, "starts": 4, "run": 7, + "read_version": pmc.PMC_READ_VERSION} + assert pmc.starts() == [100, 127, 154, 181] + assert pmc.list_url(123).endswith("&start-after=metadata/PMC123&max-keys=7") + + +def test_a_run_keeps_the_versions_numbered_before_the_next_start() -> None: + # The bucket lists in byte order, so after PMC12995600 a run that + # finds too few versions goes on to PMC1299561. + body = _listing(["PMC12995600.1", "PMC1299561.1", "PMC12995999.2", "PMC12996000.1"]) + assert pmc._listing(body, 12995600, 12996000, "URL") == [ + ("PMC12995600.1", "2026-11-01T00:00:00.000Z"), + ("PMC12995999.2", "2026-11-03T00:00:00.000Z")] + + +@pytest.mark.parametrize(("body", "why"), [ + (b"a notice naming metadata/PMC100.1.json", "is not a bucket listing"), + (b" None: + _serve(monkeypatch, {"PMC100.1": _article(_WU)}, + answers={_LIST: [body] * core.RETRIES}) + with pytest.raises(ValueError, match=why): + local.fetch(pmc.PMC_AUTHORS) + + +def test_a_listing_with_an_element_between_the_key_and_its_date_still_reads() -> None: + body = _listing(["PMC100.1"], between="x") + assert [key for key, _ in pmc._listing(body, 100, 200, "URL")] == ["PMC100.1"] + + +def test_listings_yielding_few_of_the_articles_asked_for_are_refused( + monkeypatch: pytest.MonkeyPatch) -> None: + articles = {f"PMC{100 + i}.1": _article(_WU) for i in range(4)} + _serve(monkeypatch, articles, floor=True, + answers={_LIST: [_listing(sorted(articles)[:3])]}) + with pytest.raises(ValueError, match="hold 3 articles of the 8 asked for"): + local.fetch(pmc.PMC_AUTHORS) + # At the share itself the sample is kept: 4 of 8. + _serve(monkeypatch, articles, floor=True) + assert local.fetch(pmc.PMC_AUTHORS).meta["detail"]["articles"] == 4 + + +@pytest.mark.parametrize("meta", [ + b'["not", "an object"]', b'{"pmcid": "PMC999", "is_retracted": false, "license_code": null}', + b'{"pmcid": "PMC101", "license_code": "CC BY"}', + b'{"pmcid": "PMC101", "is_retracted": "no", "license_code": "CC BY"}', + b'{"pmcid": "PMC101", "is_retracted": false}', b'{"pmcid": "PMC1', +], ids=["no object", "another article's", "no is_retracted", "is_retracted no bool", + "no license_code", "cut"]) +def test_metadata_that_is_not_the_article_s_counts_toward_the_refusal( + monkeypatch: pytest.MonkeyPatch, meta: bytes) -> None: + asked = _serve(monkeypatch, {"PMC100.1": _article(_WU), "PMC101.1": _article(_WU)}, + answers={_meta_url("PMC101.1"): [meta] * core.RETRIES}) + with pytest.raises(ValueError, match="1 of 2 articles did not read"): + local.fetch(pmc.PMC_AUTHORS) + # Asked for again each time, as a body cut in transit, and its XML never. + assert asked.count(_meta_url("PMC101.1")) == core.RETRIES + assert _xml_url("PMC101.1") not in asked + + +def test_a_body_cut_in_transit_is_asked_for_again(monkeypatch: pytest.MonkeyPatch) -> None: + asked = _serve(monkeypatch, {"PMC100.1": _article(_WU)}, answers={ + _meta_url("PMC100.1"): [b'{"pmcid": "PMC1'], _xml_url("PMC100.1"): [b"
None: + _serve(monkeypatch, {"PMC100.1": _article(_WU)}, answers={_meta_url("PMC100.1"): [ + b'{"pmcid": "PMC100", "is_retracted": false, "license_code": null}']}) + corpus = local.fetch(pmc.PMC_AUTHORS) + assert "licence" not in corpus.records[0] + assert corpus.meta["detail"]["licence (none)"] == 1 + + +def test_the_refusals_stand_at_their_shipped_shares(monkeypatch: pytest.MonkeyPatch) -> None: + # Of 200 articles, 2 unparsed (1/100), 100 naming a contributor (1/2) + # and 4 tagging a cited name (1/50) are each kept, and one more + # unparsed or one fewer of the others is refused. + def serve(**replaced: bytes) -> None: + articles = {f"PMC{100 + i}.1": _article(_WU if i < 100 else "", _REFS if i < 4 else "") + for i in range(198)} + articles |= {"PMC298.1": b"
", "PMC299.1": b"
"} + monkeypatch.setattr(pmc, "_walk", {}) + _serve(monkeypatch, {**articles, **replaced}) + serve() + detail = local.fetch(pmc.PMC_AUTHORS).meta["detail"] + assert (detail["articles"], detail["unparsed"], detail["with_authors"], + detail["with_cited_names"]) == (200, 2, 100, 4) + assert local.fetch(pmc.PMC_CITATIONS).records + serve(**{"PMC297.1": b"
"}) + with pytest.raises(ValueError, match="3 of 200 articles did not read"): + local.fetch(pmc.PMC_AUTHORS) + serve(**{"PMC199.1": _article("")}) + with pytest.raises(ValueError, match="99 of 200 articles name a contributor"): + local.fetch(pmc.PMC_AUTHORS) + # Each corpus has its own floor: the citations' does not refuse the authors. + serve(**{"PMC100.1": _article(_WU)}) + assert local.fetch(pmc.PMC_AUTHORS).records + with pytest.raises(ValueError, match="3 of 200 articles tag a name in a citation"): + local.fetch(pmc.PMC_CITATIONS) + + +def _failing(monkeypatch: pytest.MonkeyPatch, asked: list[str], url: str, code: int) -> None: + """Answer `url` with an HTTP error of `code`, and the rest as before.""" + inner = urllib.request.urlopen + + def urlopen(request: urllib.request.Request, timeout: int) -> _Response: + if request.full_url == url: + asked.append(url) + raise urllib.error.HTTPError(url, code, "Refused", {}, None) # type: ignore[arg-type] + return inner(request, timeout=timeout) + monkeypatch.setattr(urllib.request, "urlopen", urlopen) + + +@pytest.mark.parametrize("url_of", [_meta_url, _xml_url], ids=["metadata", "XML"]) +def test_an_article_gone_since_the_listing_counts_toward_the_refusal( + monkeypatch: pytest.MonkeyPatch, url_of: Callable[[str], str]) -> None: + asked = _serve(monkeypatch, {"PMC100.1": _article(_WU), "PMC101.1": _article(_WU)}) + _failing(monkeypatch, asked, url_of("PMC101.1"), 404) + with pytest.raises(ValueError, match="1 of 2 articles did not read"): + local.fetch(pmc.PMC_AUTHORS) + assert asked.count(url_of("PMC101.1")) == 1 + + +@pytest.mark.parametrize("url_of", [_meta_url, _xml_url], ids=["metadata", "XML"]) +@pytest.mark.parametrize("code", [403, 500]) +def test_an_article_the_bucket_refuses_fails_the_fetch( + monkeypatch: pytest.MonkeyPatch, url_of: Callable[[str], str], code: int) -> None: + # Only a 404 is an article gone: any other error, once retried, is + # the fetch's, never one more article under the share read past. + asked = _serve(monkeypatch, {f"PMC{100 + i}.1": _article(_WU) for i in range(200)}) + _failing(monkeypatch, asked, url_of("PMC101.1"), code) + with pytest.raises(urllib.error.HTTPError) as raised: + local.fetch(pmc.PMC_AUTHORS) + assert raised.value.code == code + raised.value.close() # an HTTPError holds the response open + + +def test_a_run_reaching_the_next_start_s_stretch_leaves_it_to_that_start( + monkeypatch: pytest.MonkeyPatch) -> None: + # The stub's first start lists every key; PMC1100.1 belongs to the + # second start, whose listing here is empty, so it is never read. + asked = _serve(monkeypatch, {"PMC100.1": _article(_WU), "PMC1100.1": _article(_ROE)}) + corpus = local.fetch(pmc.PMC_AUTHORS) + assert [r["article"] for r in corpus.records] == ["PMC100.1"] + assert corpus.meta["detail"]["articles"] == 1 + assert _meta_url("PMC1100.1") not in asked + + +def test_the_data_date_is_the_newest_among_the_versions_sampled( + monkeypatch: pytest.MonkeyPatch) -> None: + # Listed in text order, the older version PMC100.9 is dated last. + _serve(monkeypatch, {"PMC100.10": _article(_WU), "PMC100.9": _article(_WU)}) + assert local.fetch(pmc.PMC_AUTHORS).meta["data_date"] == "2026-11-01T00:00:00.000Z" + + +def test_articles_naming_no_journal_are_refused_past_their_share( + monkeypatch: pytest.MonkeyPatch) -> None: + _serve(monkeypatch, {"PMC100.1": _article(_WU), "PMC101.1": _article(_WU, journal="")}) + with pytest.raises(ValueError, match="1 of 2 articles name no journal"): + local.fetch(pmc.PMC_AUTHORS) + + +@pytest.mark.parametrize("constant", ["PMC_FIRST", "PMC_LAST", "PMC_STARTS", "PMC_RUN", + "PMC_READ_VERSION"]) +def test_a_corpus_of_another_sample_is_refused_on_load( + monkeypatch: pytest.MonkeyPatch, constant: str) -> None: + _serve(monkeypatch, {"PMC100.1": _article(_WU, _REFS)}) + local.fetch(pmc.PMC_CITATIONS) + assert local.load(pmc.PMC_CITATIONS).records + monkeypatch.setattr(pmc, constant, getattr(pmc, constant) + 1) + with pytest.raises(ValueError, match="sampled and read as"): + local.load(pmc.PMC_CITATIONS) + + +def test_both_corpora_are_scored_by_their_boxes() -> None: + assert agreement.FIELDED[pmc.PMC_AUTHORS].group == "journal" + assert agreement.FIELDED[pmc.PMC_CITATIONS].group == "order" + parser = agreement.parser_of("") + listed = agreement._title_words(parser.lexicon) + for source, record in ((pmc.PMC_AUTHORS, pmc.author(ET.fromstring(_ROE))), + (pmc.PMC_CITATIONS, pmc.citation(ET.fromstring( + "Fox, D. E." + "")))): + assert record is not None + assert agreement.read(record, agreement.FIELDED[source], parser, listed).got == {} diff --git a/tools/differential/README.md b/tools/differential/README.md index 93f0451cd..746b08624 100644 --- a/tools/differential/README.md +++ b/tools/differential/README.md @@ -291,7 +291,7 @@ uv run python tools/differential/build_shapes_corpus.py --coverage A local corpus holds real names that are not committed: fetched into the cache by `local_corpora.py`, read by `snapshot.py --local` and by a row of `tools/name_usage.py`, scored by `local_agreement.py` where its records carry their fields, and seen by no reviewer and no CI run (the SURVEY job in mechanisms.md#NAME-DATA-JOBS, and WATCH and SCORE outside CI). What reaches the repository is what a contributor cites from it, counts and shapes written with made-up names. -`local_corpora.py` holds the `SOURCES` registry, the cache's files, the views and the command line; each source's fetch is a module of its own (`local_ctgov.py`, `local_fec.py`, `local_tse.py`, `local_tw.py`, `local_ukec.py`, `local_govuk.py`, `local_psc.py`, `local_jrc.py`, `local_nepal.py`, `local_orcid.py`, `local_patentsview.py`, `local_volby.py`, `local_dof.py`, `local_uit.py`, `local_vnassembly.py`, `local_parliaments.py`, `local_mycandidates.py`) whose docstring says what the source is and what its terms allow, built on the retry policy, share gate and downloads in `local_core.py`. A new source is a module and a `SOURCES` row. A source whose records hold a value its own code derives, rather than one the source gave (`jrc-names`' script label), stores a read version in `meta.json`'s detail and refuses on load a corpus read by another (`JRC_READ_VERSION`, bumped by hand with any change to how a record is built, and `CTGOV_READ_VERSION` likewise for the ctgov corpora's country; `psc-individuals` does the same for its cached extracts, with `PSC_EXTRACT_VERSION` in each extract's file name): the sha256 checks prove the files are the ones fetched, not that today's code would write them. A constant such as `TSE_MAX_BAD` or `RETRIES` lives in one module, which every reader reads it through, so a test patches it there; no other module `from`-imports it, so a patch set elsewhere raises rather than missing the code (`test_no_module_imports_a_sibling_constant` holds this). +`local_corpora.py` holds the `SOURCES` registry, the cache's files, the views and the command line; each source's fetch is a module of its own (`local_ctgov.py`, `local_fec.py`, `local_tse.py`, `local_tw.py`, `local_ukec.py`, `local_govuk.py`, `local_psc.py`, `local_jrc.py`, `local_nepal.py`, `local_orcid.py`, `local_patentsview.py`, `local_volby.py`, `local_dof.py`, `local_uit.py`, `local_vnassembly.py`, `local_parliaments.py`, `local_mycandidates.py`, `local_pmc.py`) whose docstring says what the source is and what its terms allow, built on the retry policy, share gate and downloads in `local_core.py`. A new source is a module and a `SOURCES` row. A source whose records hold a value its own code derives, rather than one the source gave (`jrc-names`' script label), stores a read version in `meta.json`'s detail and refuses on load a corpus read by another (`JRC_READ_VERSION`, bumped by hand with any change to how a record is built, and `CTGOV_READ_VERSION` likewise for the ctgov corpora's country, and `PMC_READ_VERSION` for the PMC corpora, pinned with the sample's specification; `psc-individuals` does the same for its cached extracts, with `PSC_EXTRACT_VERSION` in each extract's file name): the sha256 checks prove the files are the ones fetched, not that today's code would write them. A constant such as `TSE_MAX_BAD` or `RETRIES` lives in one module, which every reader reads it through, so a test patches it there; no other module `from`-imports it, so a patch set elsewhere raises rather than missing the code (`test_no_module_imports_a_sibling_constant` holds this). ``` uv run python tools/differential/local_corpora.py fetch ctgov-officials @@ -338,6 +338,8 @@ Any snapshot reading of 5,000 entries or more, committed or local, parses in a w | `vn-assembly` | the 499 deputies of Vietnam's 15th National Assembly (2021-2026) as the Assembly's deputy database (dbqh.quochoi.vn) lists them, read through OpenSanctions' `vn_national_assembly` dataset (one FollowTheMoney file, crawled weekly; the 2026-11-04 export). Each name in the Vietnamese order with diacritics, beside the deputy's gender, ethnicity (410 Kinh), education and any alias (a religious name with its title, `Hòa thượng Thích ...`, or a former name). A record's name is COMPOSED: the academic rank and degree the education states in words, abbreviated as the press writes them before a name (`local_vnassembly.title_of`: the higher rank, `GS.` or `PGS.`, then the higher degree, `TS.` or `ThS.`, glued, `PGS.TS.`), then the official name, which the record keeps too (`official`, a second corpus key); of the 499, 7 `GS.TS.`, 9 `PGS.TS.`, 142 `TS.`, 241 `ThS.` and 100 untitled. Its parts are derived by `uit-vinames`' convention. The population for Vietnamese titles stated apart from the name. OpenSanctions licenses it under CC BY-NC 4.0, crediting OpenSanctions, and the composed names are derived, which the credit line says | the convention's misses outside Kinh names (an Ê-đê name gives the given name first), which the score cannot see, since it derives its truth by position; the doctor of science (`TSKH`), the medical titles (`BS.`, `BSCKII`), military ranks and religious titles, none composed; private persons; case, spacing and punctuation of a writer's own | | `opensanctions-parliaments` | the members of twenty-eight national chambers as each parliament's own website writes them, read through OpenSanctions' parliament datasets (`local_parliaments.DATASETS`: Azerbaijan, Kyrgyzstan, Uzbekistan's two chambers, Kazakhstan's two, Turkmenistan, Turkey, Croatia, Slovenia, Slovakia, Portugal, India's Sansad, Ukraine's Rada, Belarus's Council of the Republic, Russia's Duma and Federation Council, Indonesia's DPR and DPD, Ethiopia's House of Peoples' Representatives, South Korea's National Assembly, Israel's Knesset, Mongolia's State Great Khural, Malaysia's Dewan Rakyat, Pakistan's National Assembly and Senate, Egypt's House of Representatives, Somalia's House of the People), and the governors, regents and mayors Indonesia elected in 2018 (`id_regional_2018`, read beside its chambers because it writes names as they do and holds 128 of the corpus's 138 Indonesian names opening with `H.`, Haji), one `targets.simple.csv` per dataset, crawled from the parliaments' and the election commission's sites: a record is one distinct spelling of one member, the `name` column or one of the `;`-joined `aliases`, with the member (`entity`, the dataset and OpenSanctions' id), the spelling's script (`local_jrc.script`), the dataset (`dataset`, the group `config_diff.py --group` keeps) and the `form` it stood in (`name` or `alias`). On 2026-11-08 (exports dated 2026-10-08 to 2026-11-08), 19,216 members, 3,479 of them spelled two ways or more, and 24,084 spellings, distinct within each member (23,970 distinct names in the corpus): 19,738 Latin, 2,362 Cyrillic (Ukraine's Rada, Russia's Duma, Kyrgyzstan's, Kazakhstan's Mazhilis in its Kazakh and Russian forms, Uzbekistan's Senate's Cyrillic beside its Latin), 915 Devanagari (India's), 432 Hebrew (the Knesset's, one beside each member's Latin), 299 Hangul and 295 Han (Korea's, beside its Latin), 8 Ethiopic and 35 `mixed` (26 of them Ethiopia's, 4 Korea's). The first seventeen datasets held 13,354 members and 17,041 spellings that day; the four added after them (Indonesia's three and Ethiopia's) 5,131 members and 5,284 spellings, and Korea's and Israel's 731 members and 1,759 spellings. Mongolia's Khural, added 2026-11-12 (export of 2026-11-06), holds 126 members, each written once in Cyrillic with the father's name first; the fetch of that day held 19,283 members and 24,302 spellings (24,192 distinct names), the other datasets' exports unchanged from the same day's earlier fetch. The five chambers added 2026-11-19 (#1465) hold 1,572 members and 2,211 spellings: Malaysia's 276 (16 with an alias writing the `bin` or `a/l` the name leaves out), Pakistan's 332 and 95, each written once, Egypt's 594 in Arabic script, 588 of them written twice, a short name and the full chain of names, and Somalia's 275 (35 with an alias holding a nickname in brackets); the fetch of that day held 20,856 members and 26,515 spellings (26,400 distinct names), some of the other datasets' exports having moved since 2026-11-12. The aliases are other scripts, a parliamentary short name (Portugal's `Jorge Costa` for the full name), the name with its title (India's `Shri`, `Smt.`, `श्री`) and, in Ukraine's 12, another surname (a maiden or married name, or another spelling). Issues #1186 to #1192 were read from it in the 2026-11-07/08 check of the shipped packs, and it holds the shapes they ask about; the Indonesian datasets, 90% in capitals with no family name (`H.` for Haji, `R.` for Raden, `Imam` as a given name), measure #1205 and #1206 but not #1204, holding no degrees, Ethiopia's, a given, a father's and a grandfather's name, measures #1203, Korea's, every member in Latin, Hangul and Hanja, measures #1213, #1215 and #1216, Israel's, every member in Latin and Hebrew, #1209, #1210 and #1211, Mongolia's #1237, and Malaysia's and Egypt's #1468, #1072 and #1464: Turkic patronymics (`qızı`, `oğlu`, `-uly`, `-yevich`, `o‘g‘li`) and East Slavic ones, in Cyrillic and Latin, family first and last, the family often in capitals (`AĞAZADƏ Əminə`, `Mehmet DEMİR`); Indic titles and initials; Slavic and Portuguese double surnames. OpenSanctions licenses it under CC BY-NC 4.0, crediting OpenSanctions | private persons, and how anyone but a parliament's web team writes a name: most chambers write every member one way (India's Sansad is the exception, a title before some names and not others, and freeform entries such as two people in one name); the parliaments not listed (OpenSanctions crawls more) | | `my-candidates` | the candidates of Malaysia's general elections GE12 (2008) to GE15 (2022) and of the six state elections of 2023 (PRN15), from Thevesh Theva's analysis-election-msia repository on GitHub (`data/candidates_ge12.csv` to `candidates_ge15.csv` and `candidates_prn15.csv`), pinned by commit and each file's sha256 (`local_mycandidates.FILES`): a record is one distinct spelling within an election and ethnicity, with the `election`, the `form` (`ballot`, or `full` for PRN15's full names) and the candidate's `ethnicity` as the file writes it (the group `config_diff.py --group` keeps: `bumiputera` in the general elections, `malay` in PRN15, `chinese`, `indian`, `other`). The names are in capitals, as gazetted. Each file's ballot name is read (GE12 to GE14's `name`, GE15's `name_display`, PRN15's `name_ballot`), and PRN15's full `name` beside it; GE15's `name` is the full name recased into title case by the repository's author, and is read past. On 2026-11-19, 3,261 rows gave 3,683 spellings (3,260 ballot, 423 full) and 3,077 distinct names: 2,759 records `bumiputera` or `malay` (the general elections' `bumiputera` is the wider, taking in Sabah's and Sarawak's peoples, the Iban among them; PRN15's six states are all in the peninsula, where it writes `malay`), 665 `chinese`, 247 `indian`, 12 `other`. The population for `BIN`, `BINTI` and their short forms `B.` and `BT` (#1467), `A/L`, `A/P` and `ANAK` (#1468), the `@` alias (#1164), `MD` and `MOHD` before a name, honorifics opening a ballot name (`USTAZ`, `CIKGU`, `DR`, `HJ`, #1179) and Chinese names written family first (#1183). The repository is licensed under the GPL-3.0; the names are cached, never committed or shipped | how a candidate writes their own name, mixed case (one candidate's name, recorded in three elections, is not in capitals), commas; the full names behind the general elections' ballot names; candidates of other years | +| `pmc-authors` | a prototype (#1540): the contributors of a sample of PubMed Central's article datasets, read from the PMC Cloud Service's public bucket as JATS XML, which tags a name by part. The sample is fixed by its specification (`local_pmc.sample()`: `PMC_STARTS` accession numbers spread over the archive and `PMC_RUN` article versions listed after each, 2,500 and 2 on 2026-12-01). Each name is composed given names first from the tagged ``, ``, `` and ``, with the contributor's `` after a comma, and the record keeps the boxes, the suffix box holding the suffix and the degrees: 4,915 articles and 31,741 records (a distinct name and boxes) in the 2026-12-01 fetch, 56 with a prefix and 3,088 with a suffix or degrees, 98.5% agreeing in every field by default | the order and punctuation a byline wrote, the name being composed; any country (few articles tag an affiliation's); `name-style`, which was `western` on every name of 116 articles read on 2026-11-30; fields other than biomedicine | +| `pmc-citations` | from a sample of the same specification, the names tagged inside the text of a reference (`` in a ``), each as written with its tags dropped (`Fox, D. E.`, `Fox DE`, `D. E. Fox`), beside its tagged surname, given names and suffix and the order it was written in, which the score groups by: 68,215 records (a distinct spelling and boxes) from the 451 articles of 4,915 that tag them in the 2026-12-01 fetch, 43,500 a surname then given names with no comma (43,381 of them initials alone), of which the default read 0.0% and `name_order=FAMILY_FIRST` 91.0%. Each `fetch` command walks the sample anew, so the two corpora hold the same articles only where one process fetched both, as these were | full given names (nearly all are initials); references tagged apart from their text (``), which are most; a `` in a reference; the publishers that tag no reference | A live source has no fixed snapshot to pin, so the cached copy is the pin: `meta.json` holds the source's data date and the sha256 of `raw.jsonl` and `corpus.jsonl`, checked on every load, and every report, the `name_usage.py` row included, carries the source and that date. Quote a count with the date, and expect a later fetch to differ. A local snapshot records which fetch it was read from, and `snapshot.py --local` refuses to compare it with a corpus fetched since, which would report the names the source gained and lost as moves: after a `fetch --refresh`, record again from the base checkout. ClinicalTrials.gov's terms ask anyone redistributing its data to credit it, show NLM's processing date and say what was changed; keeping the names in the cache and citing counts with that header meets them. The FEC's bar on soliciting and commercial use is in the credit line of every `fec-individuals` report, so a count quoted from it carries the bar with it. A record there is a distinct name, not a contribution or a contributor: one donor gives many times (34,264,742 rows held 1,893,964 names in the file dated 2026-10-18), and counting contributions would weight a shape by how often its bearers give. `tools/name_usage.py` looks a word up in each corpus's word index, cached as `wordindex.json` beside it on first use and keyed to the records' sha256, to the code that cuts and folds a word and to the record keys it reads (`Source.corpus_keys`; a record whose two names write one word counts once), so a refetch, a change to the fold or a change to which of a record's names are read rebuilds it; a single-word lookup it answers parses neither the records nor the names. Measured 2026-10-22 with both corpora fetched, a single-word `name_usage.py --no-wikidata` run took 2.5s with their indexes cached (12.5s before the cache, 14.8s on the run that builds it). A spaced word (`Ph. D.`) still scans every name, which took 8.6s, nearly all of it the FEC corpus's. For `orcid-researchers` and `patentsview-inventors`, whose extracts keep every record's boxes and country uncapped, `name_usage.py --boxes` adds a row by box and country, read from a second index, `boxindex.json.gz` beside the corpus (`cached_box_index`): per word and country the people whose given box or family box writes it, each country shown as a share of its people, so a word can be weighed in the country a language pack is for (`--country CC`). It is keyed to the extract's sha256, taken from the bytes as they are read, and to a fingerprint of the reader and the fold, so a refetch rebuilds it. Building it took 2 min 19 s for ORCID's 24,990,909 records (3,780,309 words in 6,660,756 word-and-country cells, 41 MB cached) on 2026-10-28. With both indexes cached a lookup took 10.4 s with `--boxes` against 5.3 s without, the difference nearly all reading the two indexes (the 369 MB extract hashes in a fraction of a second once the system has it cached), which is why the rows are asked for rather than always built; an extract that cannot be read fails its own row, naming the refresh. `fetch --refresh` re-downloads the FEC's zip rather than re-reading the cached one, replacing it only once the new one is whole, and a corpus fetched for another cycle than `FEC_CYCLE` is refused on load. The `fec-individuals` fetch refuses a file whose lines stop matching the 21 columns it reads, or whose names stop holding a comma, rather than read it as a smaller or a different corpus. A `ukec-individuals` record is a distinct name too, not a donation or a `DonorId`: one name often holds several IDs, which seem to come with reports rather than with people (15,214 names held 24,473 on 2026-10-22, the IDs counted in `meta.json`'s detail; 2,663 names held several at one `RegulatedEntityId` alone, counted from the export and not kept, though some of those may be two people of one name), so a count of IDs would weight a name by how often it was reported. Its fetch reads the register's total from the JSON search under the same filter before and after the export, and refuses an export holding another number of rows, or a register that changed in between: the export ignores `rows=`, so the total is what tells a cut or capped export from the whole register. It refuses an export whose last row is cut short (Python's `csv` returns a body cut inside a row as a short last row, which the row count would otherwise take for a whole one), and a header other than the 29 columns `UKEC_COLUMNS` names, and counts into `meta.json`'s detail the rows it skips: rows not 29 fields, rows from a donor that is not an individual (the filter asks the server to leave those out), and individuals with no name. Past `UKEC_MAX_BAD` of either of the first two, or `UKEC_MAX_NAMELESS` of the third (4 of 42,355 rows were nameless on 2026-10-22), it refuses the export. The data date is when the first search answered, in UTC: the register states no date of its own, so the counts above, dated by the day they were fetched (2026-10-22), carry the data date 2026-10-23T03:13:19Z in their header. `tw-donors` keeps one zip per report under `reports/`, whole, its masked ID, address and phone columns included, as the FEC's zip is kept: the platform's download answers a report that does not exist and a fault alike, with a 500 and an incident number, so the fetch reads which reports exist from the platform's listing and refuses a listed report it cannot download. It reads each file's columns by name, since a 2020 report lacks a column the newest ones write, and refuses a column it does not know, a category it does not know, a row whose serial column names another report (the zip is not the one asked for), a listing that changes during the fetch, and a report past `TW_MAX_REPORT_BAD` of whose rows it reads past. It reads back the rows a stray quote took into one field (169 rows in 12 records of three reports on 2026-10-22, 8 of them two rows joined by two stray quotes), counts donor cells that hold no name (匿名, a dash) or a masked one, and caches a downloaded zip only once its rows are read, so a refused zip is asked for again. A zip the platform rebuilt under the name it had is not seen: delete `reports/` to download every report again. A layout check written from one surveyed file meets every other file only at fetch time: `tw-donors`' first three fetches were each refused partway, by a report with no income writing one row of dashes, by a 2020 report with 24 columns where the surveyed one had 25, and by a row with no category. Each refusal cost every download again until the source cached its zips, so a new source that downloads many files caches each one before its checks run. `tse-donors` caches nothing but the corpus: each election's national member (`receitas_candidatos__BRASIL.csv`) is read from the TSE's CDN in HTTP Range requests, 209 MB for the two elections where their zips are 1.82 GB (2026-10-22), because the TSE regenerates the zips every few days and a cached one would be stale within the week. Every range request carries `If-Range` with the ETag the HEAD gave if it is strong, else its `Last-Modified`, and every part must state the `Content-Range` asked for, so a zip replaced during the read is refused rather than read across two versions; a HEAD that states no length, neither a strong ETag nor a `Last-Modified`, or `Accept-Ranges` other than `bytes` is refused before the read. A fetch took 69s on 2026-10-22. It refuses a zip without the national member, a header that is not 60 columns or lacks its three columns, a `DS_ORIGEM_RECEITA` value it does not know (a renamed category, or the file no longer in Latin-1), malformed rows or lines folded into a field past `TSE_MAX_BAD`, an election with too few rows from individuals (`TSE_MIN_INDIVIDUALS`: a member cut to its header, or the donations moved under another category) too many without a name or registry name (`TSE_MAX_MISSING`, counting a placeholder such as `#NULO` or `***` as none: a masked column) or with a number in one (`TSE_MAX_NUMBERED`: a numeric column moved under a name), too few distinct filed or registry names (`TSE_MIN_DISTINCT`: a column masked with one word), and a corpus fetched for other elections than `TSE_ELECTIONS`. The CPF in each row is unmasked in the file, and like every other column it is read past, never stored or printed; a pair either of whose names holds more than `TSE_MAX_DIGITS` digits is dropped and counted, since campaigns sometimes typed a number, a CPF among them, into the name field. A record is a pair, so the counts in its reports (`tally`, the `name_usage.py` row) are of pairs, and a filed name standing beside two registry names counts twice. @@ -361,7 +363,9 @@ 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. 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, and #1477 after any full stop the filer typed, whatever stands before it (`Md.Karim` read `Md.`, `Karim`: 168 `orcid-researchers` records and 1 `patentsview-inventors` record moved on 2026-11-19, 146 of them Bangladesh's). `agrees` holds the rule, guarded by `test_a_reading_cut_only_after_a_full_stop_is_never_scored_a_miss` with a recorded negative control; a run with no full stop, a full stop the reading lost, a word left over, other letters, and a cut across two boxes a source states apart (`psc-individuals`' forename and middle name) still score a miss. A parser change that cuts one written word across two fields, or joins two written words, reads `agrees` before trusting the score it moves. A listed title the filer typed into the given-names box and the parse reads as the title, the rest of the box read as the box's names (`Dr. Anna`, `Dr/ Anna`, `د. منى`, and `Dr.Ahmed`, which #1477 left a miss), every other field agreeing and no title box filed, is a class of its own (`titled`, #1501): the parse is right and the box is what differs, so it counts as neither agreeing nor missing, the agreement figure is taken over the records outside it, and the report gives its size, its records per group and the titles read there, so a reader checks the words, a given name wrongly peeled among them (`Hon`, a Cantonese given name the default reads as the style, #999), rather than the records. On 2026-11-20 it held 9,145 `orcid-researchers` records (the most in India, 1,190, Pakistan, 835, and Bangladesh, 595; `Dr.` 5,311, `Dr` 1,807), 90 `patentsview-inventors` records (`Hon` 39) and 6 `psc-individuals` records, every one a miss before, raising ORCID's figure from 81.1% to 81.5%. A title the vocabulary does not list (`Xyz. Anna`, read by its shape), a box holding only a title, a title typed into the family box and a title box filed stay out of it. `--base` reports a record entering or leaving the class as `titled in` or `titled out`, with the titles read, apart from the regressions and progress: a record that agreed and is now read with a title (a given name newly peeled) is `titled in`, never a regression, so a change to the title vocabulary reads those lines beside its regressions; `config_diff.py`'s `gaps` and `score` drop a record any configuration reads into the class from every column. 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, the commonest disagreement shapes and the titled class, as counts, word counts, the commonest set-aside titles and the titles read in the given-names box; `--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. +`pmc-authors` and `pmc-citations` list the sample's runs first, and refuse a listing that is not the bucket's, that lists an entry other than an article version's metadata with its date, or that counts other than the entries it holds (retried first, as a body cut short). A version numbered at or past the next start is left out: the bucket lists in byte order, where `PMC1299561` follows `PMC12995600`, so a run that finds too few versions after its start goes on into another part of the archive. The walk is refused where the listings yield under `PMC_MIN_LISTED` of the articles asked for, every other share being of the articles listed. Of an article's versions listed the newest is read, and a retracted article is skipped. Metadata that is not that article's (its `pmcid`, a boolean `is_retracted`, a `license_code`), XML that does not parse (each asked for again first) and an article gone since the listing are counted, and past `PMC_MAX_BAD` of them together, or `PMC_MAX_NO_JOURNAL` of the read articles naming no journal, the walk is refused. Each corpus has its own floor on the articles holding its names (`PMC_MIN_WITH_AUTHORS`, `PMC_MIN_WITH_CITED`), so a change to how references are tagged does not refuse the contributors. + +`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`; title, family, middle and given for `vn-assembly`; prefix as the title, given and middle joined, family, and the suffix with the degrees for `pmc-authors`; and given and middle joined, family and suffix for `pmc-citations`, whose display name is the citation's text as written and not the boxes joined), 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, and #1477 after any full stop the filer typed, whatever stands before it (`Md.Karim` read `Md.`, `Karim`: 168 `orcid-researchers` records and 1 `patentsview-inventors` record moved on 2026-11-19, 146 of them Bangladesh's). `agrees` holds the rule, guarded by `test_a_reading_cut_only_after_a_full_stop_is_never_scored_a_miss` with a recorded negative control; a run with no full stop, a full stop the reading lost, a word left over, other letters, and a cut across two boxes a source states apart (`psc-individuals`' forename and middle name) still score a miss. A parser change that cuts one written word across two fields, or joins two written words, reads `agrees` before trusting the score it moves. A listed title the filer typed into the given-names box and the parse reads as the title, the rest of the box read as the box's names (`Dr. Anna`, `Dr/ Anna`, `د. منى`, and `Dr.Ahmed`, which #1477 left a miss), every other field agreeing and no title box filed, is a class of its own (`titled`, #1501): the parse is right and the box is what differs, so it counts as neither agreeing nor missing, the agreement figure is taken over the records outside it, and the report gives its size, its records per group and the titles read there, so a reader checks the words, a given name wrongly peeled among them (`Hon`, a Cantonese given name the default reads as the style, #999), rather than the records. On 2026-11-20 it held 9,145 `orcid-researchers` records (the most in India, 1,190, Pakistan, 835, and Bangladesh, 595; `Dr.` 5,311, `Dr` 1,807), 90 `patentsview-inventors` records (`Hon` 39) and 6 `psc-individuals` records, every one a miss before, raising ORCID's figure from 81.1% to 81.5%. A title the vocabulary does not list (`Xyz. Anna`, read by its shape), a box holding only a title, a title typed into the family box and a title box filed stay out of it. `--base` reports a record entering or leaving the class as `titled in` or `titled out`, with the titles read, apart from the regressions and progress: a record that agreed and is now read with a title (a given name newly peeled) is `titled in`, never a regression, so a change to the title vocabulary reads those lines beside its regressions; `config_diff.py`'s `gaps` and `score` drop a record any configuration reads into the class from every column. 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, the commonest disagreement shapes and the titled class, as counts, word counts, the commonest set-aside titles and the titles read in the given-names box; `--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. @@ -397,7 +401,7 @@ Measured 2026-10-27 on a 12-CPU machine (load average 3 to 15 from other session uv run python tools/differential/measure.py --base ../master-checkout ``` -The steps: the committed snapshot (`snapshot.py`, the check `tests/v2/test_snapshot.py` makes), `cldr_agreement.py`, `snapshot.py --local --base` for every fetched local corpus, `local_agreement.py SOURCE --base` for every fetched source whose records carry their fields (`psc-individuals`, `orcid-researchers`, `patentsview-inventors`, `cz-candidates`, `uit-vinames`, `vn-assembly`), and `local_corpora.py alike --base` for every fetched source that pairs spellings. Only the local steps read `--base`: the first two compare the tree with the records committed on its branch, so on a branch that has re-recorded `snapshot.jsonl` the committed snapshot says no moves and the moves are in the PR's diff of that file, and the summary labels each step with what it compared against. A local corpus that is not fetched gets no step, the summary names it, and a run in which no step read `--base` exits 1. Each step's whole output goes to a file of its own under `--out`, by default a folder named for the time under the cache's `measure/`, outside the repository, since a local snapshot lists its moves by name. The summary, `summary.txt` beside them and printed, gives each step's status (no moves, moves, or failed with its exit code), its time, and its unindented lines (the first few and the last, where the verdicts are, up to `SUMMARY_LINES`, and any line saying part of a check was not measured), never the indented ones where the tools list names; a crash's traceback is indented below a line naming only its type, since its message may hold a name. A step that fails makes the run exit 1; one that finds moves does not. Each tool refuses with `SystemExit("message")`, which exits 1 as a move does, so measure runs every step through its own `--step` wrapper, which turns a message exit or an uncaught exception into exit 2: a refused base or a damaged corpus is reported as a failure, never as moves. +The steps: the committed snapshot (`snapshot.py`, the check `tests/v2/test_snapshot.py` makes), `cldr_agreement.py`, `snapshot.py --local --base` for every fetched local corpus, `local_agreement.py SOURCE --base` for every fetched source whose records carry their fields (`psc-individuals`, `orcid-researchers`, `patentsview-inventors`, `cz-candidates`, `uit-vinames`, `vn-assembly`, `pmc-authors`, `pmc-citations`), and `local_corpora.py alike --base` for every fetched source that pairs spellings. Only the local steps read `--base`: the first two compare the tree with the records committed on its branch, so on a branch that has re-recorded `snapshot.jsonl` the committed snapshot says no moves and the moves are in the PR's diff of that file, and the summary labels each step with what it compared against. A local corpus that is not fetched gets no step, the summary names it, and a run in which no step read `--base` exits 1. Each step's whole output goes to a file of its own under `--out`, by default a folder named for the time under the cache's `measure/`, outside the repository, since a local snapshot lists its moves by name. The summary, `summary.txt` beside them and printed, gives each step's status (no moves, moves, or failed with its exit code), its time, and its unindented lines (the first few and the last, where the verdicts are, up to `SUMMARY_LINES`, and any line saying part of a check was not measured), never the indented ones where the tools list names; a crash's traceback is indented below a line naming only its type, since its message may hold a name. A step that fails makes the run exit 1; one that finds moves does not. Each tool refuses with `SystemExit("message")`, which exits 1 as a move does, so measure runs every step through its own `--step` wrapper, which turns a message exit or an uncaught exception into exit 2: a refused base or a damaged corpus is reported as a failure, never as moves. **Comparing configurations in one tree.** `snapshot.py --local` compares two trees under one configuration and `local_agreement.py` scores one configuration against the filed boxes; `config_diff.py diff` compares two or more CONFIGURATIONS in the tree it runs in, over the committed corpora, any fetched local corpus (`--local SOURCE`, or `all`), a fielded corpus's countries or nationalities as it writes them, `opensanctions-parliaments`' datasets, the ctgov corpora's ISO country codes, or `my-candidates`' ethnicities (`--group`, which needs `--local` and refuses a group no record holds; a corpus with no fields names its group key in its `Source`'s `group`), the names a regular expression finds (`--match`) and a hash sample (`--sample N`), each name rewritten first where `--spelling` asks (`stripped`, `upper`, `lower`, comma-separated: `--spelling stripped,upper` reads a Vietnamese population as plain-ASCII data in capitals writes it, #1108). A configuration is `default`, `plain:` or `strict:` (`parser_for` over the items joined by `+`: a shipped pack in capitals, `ES`, `PT_BR`, a bare language tag in lower case, `pt-BR`), or `expr:` for any other lexicon or policy; the first is the baseline. It compares the seven roles, the ambiguity kinds and 3.0's views (`generation`, `credentials`, `honorifics`, `patronymic`, `surname2`), and prints, per configuration, the names that moved by input and grouped by the fields that changed, and the words whose token changed role, ranked, each with an example; `--json` keeps the counts and the moved names, `--readings` every name's readings one line a name, so a run in each of two trees compares line by line. Every parse runs in `--jobs` worker processes (`snapshot.parallel`). Reach for it before writing a script that parses the corpora under two configurations: #1000, #1005, #1017 and #1019 each wrote one. diff --git a/tools/differential/local_agreement.py b/tools/differential/local_agreement.py index 1a3f1c09d..7f3aeb1a0 100644 --- a/tools/differential/local_agreement.py +++ b/tools/differential/local_agreement.py @@ -13,7 +13,12 @@ and `vn-assembly` state a name whole, in the Vietnamese order, and their parts are derived by the convention a reader of the name assumes, first word the family name and last the given (local_uit.split), with -`vn-assembly`'s title composed from the education its deputies state). What +`vn-assembly`'s title composed from the education its deputies state; +and the two PubMed Central corpora, whose parts the articles' JATS +markup tags: `pmc-authors`' prefix, given names, surname and suffix with +the degrees, the name composed from them, and `pmc-citations`' given +names, surname and suffix, whose display name is not the boxes joined +but the citation's text as written). What cldr_agreement.py does for the committed fields files, over names that are never committed -- so no CI run and no reviewer sees this score, and its record lives in the cache beside the corpus, where a re-run @@ -39,7 +44,8 @@ default's record and a pack's never stand for each other. The report prints counts and shapes, never a record: agreement overall -and by the group a source states (a nationality, a country), the misses per field, +and by the group a source states (a nationality, a country, a journal, +the order a cited name was written in), the misses per field, the commonest disagreement shapes, a shape being each disagreeing field's word count as filed and as parsed (`middle 0->1, family 2->1` is a two-word surname whose first word was read as a middle name), and the @@ -54,7 +60,8 @@ - Each field is compared case-folded, with periods dropped, commas read as spaces and runs of spaces read as one. The display name is the - boxes joined, so the parser sees the filer's own spelling, and the + boxes joined (`pmc-citations`' is the citation's own text, which the + boxes were tagged in), 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. A word @@ -68,7 +75,8 @@ `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 with its suffix appended, and the report counts the agreements that - needed it. Where it has one (`cz-candidates`' title after the name), + needed it. Where it has one (`cz-candidates`' title after the name, + the PMC corpora's suffix, `pmc-authors`' holding the degrees too), the suffix is compared with that box alone. - Where a source has a title box, a filed title the parser does not read as the title, holding a word the vocabulary lists in neither its titles nor its connectives, is @@ -187,7 +195,13 @@ def __post_init__(self) -> None: {"family": "family", "middle": "middle", "given": "given"}, group="gender"), local_corpora.VN: Fielded( {"title": "title", "family": "family", "middle": "middle", "given": "given"}, - group="ethnicity", group_cased=True, sets_aside=False, group_floor=10)} + group="ethnicity", group_cased=True, sets_aside=False, group_floor=10), + local_corpora.PMC_AUTHORS: Fielded( + {"prefix": "title", "given": "given+middle", "family": "family", + "suffix": "suffix"}, group="journal", group_cased=True, group_floor=100), + local_corpora.PMC_CITATIONS: Fielded( + {"given": "given+middle", "family": "family", "suffix": "suffix"}, + group="order", group_cased=True, group_floor=100)} #: The fewest records sharing a set-aside title for the report to print #: it: a word typed into the title box by this many filers is no one #: person's name. diff --git a/tools/differential/local_corpora.py b/tools/differential/local_corpora.py index a22f749d8..6d7f0aa1f 100644 --- a/tools/differential/local_corpora.py +++ b/tools/differential/local_corpora.py @@ -59,8 +59,12 @@ national parliament, with the member, its script, the dataset and whether it is the name or an alias; one distinct spelling of a Malaysian election candidate within an election, with the election, - the form (ballot or full name) and the ethnicity. The counts are - counted from here. + the form (ballot or full name) and the ethnicity; one distinct + composed name and boxes of a PMC article's contributor, with the + first article holding it, its journal and licence; one distinct + spelling and boxes of a name tagged in the text of a PMC article's + reference, with the order written and the same three. The counts + are counted from here. - corpus.jsonl -- the distinct names, in the corpus line format snapshot.py and compare.py --corpus read: each record's "name", and for nepal-candidates its Devanagari name too, and for @@ -103,8 +107,9 @@ (orcid-researchers), local_patentsview.py (patentsview-inventors), local_volby.py (cz-candidates), local_dof.py (dof-signatures), local_uit.py (uit-vinames), local_vnassembly.py (vn-assembly), -local_parliaments.py (opensanctions-parliaments) and -local_mycandidates.py (my-candidates). +local_parliaments.py (opensanctions-parliaments), +local_mycandidates.py (my-candidates) and local_pmc.py (pmc-authors, +pmc-citations). """ from __future__ import annotations @@ -156,6 +161,8 @@ from local_parliaments import PARLIAMENTS, check_parliaments, fetch_parliaments # noqa: E402 from local_patentsview import (PV, check_pv, extract_path as pv_extract, # noqa: E402 fetch_pv, pv_boxes, renew_pv) +from local_pmc import (PMC_AUTHORS, PMC_CITATIONS, check_pmc, # noqa: E402 + fetch_authors, fetch_citations) from local_psc import PSC, check_psc, fetch_psc, renew_psc # noqa: E402 from local_tse import check_tse, fetch_tse # noqa: E402 from local_tw import fetch_tw # noqa: E402 @@ -322,6 +329,16 @@ def index(self) -> WordIndex: "elections, from Thevesh Theva's analysis-election-msia " "(github.com/Thevesh/analysis-election-msia, GPL-3.0)", unit="spellings", fetch=fetch_my, check=check_my, group="ethnicity"), + PMC_AUTHORS: Source( + credit="PubMed Central (NIH/NLM) Article Datasets, a sample of articles' " + "contributors (each article under its own licence; each name " + "composed from the tagged parts, so derived data)", + unit="names", fetch=fetch_authors, check=check_pmc), + PMC_CITATIONS: Source( + credit="PubMed Central (NIH/NLM) Article Datasets, a sample of articles' " + "cited names as their reference lists write them (each article " + "under its own licence)", + unit="spellings", fetch=fetch_citations, check=check_pmc), } diff --git a/tools/differential/local_pmc.py b/tools/differential/local_pmc.py new file mode 100644 index 000000000..505c989ae --- /dev/null +++ b/tools/differential/local_pmc.py @@ -0,0 +1,424 @@ +"""The PubMed Central local corpora: names as open-access articles tag them. + +A prototype (#1540): a SAMPLE of the PMC Article Datasets, not the whole +of them. PubMed Central (NIH/NLM) keeps each article as JATS XML +(ANSI/NISO Z39.96), which tags a person's name by part: ``, +``, `` and `` inside a `` or a +``, and a contributor's `` beside the name. Two +corpora are read from a sample of articles: + +pmc-authors -- each article's contributors (``), one record per +distinct name and boxes. The name is COMPOSED from the tagged parts, +given names first, as ORCID's is (`Dr Ann Q. Roe Jr, MD, PhD`: prefix, +given names, surname, suffix, then the degrees after a comma, as the +element writes them), so it says nothing about the order or the +punctuation a byline wrote. What it adds to orcid-researchers is the +prefix, the suffix and the degrees, each tagged apart from the name, +and a split made by a typesetter or a submission system rather than by +the person. The suffix box holds the suffix and the degrees together, +as the parser's suffix does. A record carries the article's journal, +which the score groups by. Where a contributor's name is given in +several scripts (``), the first written wholly in +Latin letters is read, since a name composed given names first in a +script that writes the family name first would score as the parser's +miss. `name-style` is no signal here: PMC wrote `western` on every name +of the 116 articles an earlier probe read on 2026-11-30, names of +family-first cultures included. + +pmc-citations -- the names in the articles' reference lists that are +tagged INSIDE the text of the citation (`` in a +``), one record per distinct spelling and boxes. The +name is the text AS WRITTEN, tags dropped: `Fox, D. E.`, `Fox DE`, +`D. E. Fox 3rd`, with whatever punctuation stands between the parts, so +it is the one population local_agreement.py scores whose name is the +writer's own text beside parts the source tagged. A record's `order` +states the order written (`family, given`, `family given`, +`given family`), which the score groups by. Where the tags stand glued +(`DEFox`, the form PMC +stores for citations whose separator was whitespace alone) a space is +put between them. Most are a surname and initials: the population for +the family-name-then-initials shape (#1137, rules/O8), not for full +given names. A name tagged without both a surname and given names is +skipped (a collective author tagged as a surname), and so is every +name outside a ``'s ``: a `` +anywhere in a reference, and all of an ``, whose +parts are stored apart with no text between them. + +The sample is fixed by its specification (sample()): PMC_STARTS +accession numbers spread evenly from PMC_FIRST up to PMC_LAST, and from +each the next PMC_RUN article versions the bucket lists after it that +fall before the next start. Accession numbers are given out in batches +by journal, so many short runs sample more journals than a few long +ones. The bucket's content moves daily, so two fetches differ, and each +`fetch` command walks the sample anew: the two corpora hold the same +articles only where one process fetched both. The data date is the +newest modification date among the article versions sampled, a +retracted or unreadable one included. + +The articles are read from the PMC Cloud Service's bucket +(https://pmc-oa-opendata.s3.amazonaws.com/, its README.txt read +2026-11-30), one of the services PMC names for automated retrieval +(pmc.ncbi.nlm.nih.gov/tools/openftlist/ forbids any other). Its terms +ask that NLM be acknowledged as the source, which the credit line does. +Each article keeps its own licence (CC0, CC BY and its variants, or +text mining only for an author manuscript), which each record carries +where the metadata states one, and the names are personal data: cached, +never committed. +""" +from __future__ import annotations + +import json +import re +import sys +import unicodedata +import urllib.error +import xml.etree.ElementTree as ET +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from typing import Any, NamedTuple + +from local_core import Fetched, _pinned, _refuse_past, _retried + + +PMC_AUTHORS = "pmc-authors" +PMC_CITATIONS = "pmc-citations" +PMC_BUCKET = "https://pmc-oa-opendata.s3.amazonaws.com/" +#: The sample: PMC_STARTS accession numbers from PMC_FIRST up to +#: PMC_LAST, evenly spaced, and PMC_RUN article versions listed after +#: each. Below PMC_FIRST the articles are mostly scanned back issues +#: with no tagged references; the bucket held accession numbers up to +#: PMC_LAST's last hundred thousand on 2026-12-01. +PMC_FIRST, PMC_LAST = 2_000_000, 13_000_000 +PMC_STARTS = 2_500 +PMC_RUN = 2 +#: Requests in flight at once: the bucket is public S3, built for more. +PMC_THREADS = 16 +#: How the articles are read (read_article): a change bumps it, and a +#: corpus read by another version, or sampled otherwise, is refused. +PMC_READ_VERSION = 3 +#: The share of sampled articles a fetch reads past before refusing: +#: XML that does not parse, metadata that is not the object the bucket's +#: README describes for that article, and an article gone between the +#: listing and the read. +PMC_MAX_BAD = 1 / 100 +#: The share of read articles with no journal a fetch reads past: the +#: score groups pmc-authors by it. +PMC_MAX_NO_JOURNAL = 1 / 10 +#: The least share of the PMC_STARTS * PMC_RUN articles asked for that +#: the listings must yield (4,927 of 5,000 on 2026-11-30): every other +#: gate is a share of the articles listed, so a listing that mostly +#: broke would otherwise read as a small sample. +PMC_MIN_LISTED = 1 / 2 +#: The least share of sampled articles holding a contributor's name +#: (4,766 of 4,927 on 2026-11-30), and holding a name tagged in a +#: citation's text (449 of 4,927): a renamed element would otherwise +#: read as a corpus of little. Each is its own corpus's gate. +PMC_MIN_WITH_AUTHORS = 1 / 2 +PMC_MIN_WITH_CITED = 1 / 50 + +_KEY = re.compile(r"metadata/(PMC(\d+)\.\d+)\.json") +_S3 = "{http://s3.amazonaws.com/doc/2006-03-01/}" +_PARTS = ("prefix", "given-names", "surname", "suffix") + + +class Walk(NamedTuple): + """One walk of the sample: both corpora's records, the data date and + the counts.""" + authors: list[dict[str, str]] + cited: list[dict[str, str]] + when: str + counts: dict[str, int] + + +def sample() -> dict[str, int]: + """The sample's specification, as meta.json records it.""" + return {"first": PMC_FIRST, "last": PMC_LAST, "starts": PMC_STARTS, + "run": PMC_RUN, "read_version": PMC_READ_VERSION} + + +def starts() -> list[int]: + """The accession numbers the sample lists from.""" + step = (PMC_LAST - PMC_FIRST) // PMC_STARTS + return [PMC_FIRST + i * step for i in range(PMC_STARTS)] + + +def list_url(number: int) -> str: + """The bucket's listing of the PMC_RUN article versions after `number`.""" + return (f"{PMC_BUCKET}?list-type=2&prefix=metadata/" + f"&start-after=metadata/PMC{number}&max-keys={PMC_RUN}") + + +def _text(element: ET.Element | None) -> str: + return " ".join("".join(element.itertext()).split()) if element is not None else "" + + +def _parts(name: ET.Element) -> dict[str, str]: + """The text of each tagged part of a name, an absent part "".""" + return {tag: _text(name.find(tag)) for tag in _PARTS} + + +def as_written(name: ET.Element) -> str: + """A ``'s text with its tags dropped, a space put where + one tagged part ends against the next with nothing between, and the + space a line break left before a comma removed.""" + pieces = [name.text or ""] + for child in name: + pieces.append("".join(child.itertext())) + pieces.append(child.tail or " ") + return re.sub(r"\s+,", ",", " ".join("".join(pieces).split())).strip(" ,;") + + +def order_of(name: ET.Element) -> str: + """The order a `` writes its surname and given names in: + `given family`, or, by whether a comma stands in the text between + the surname and the given names, `family, given` or `family given`.""" + between: list[str] | None = None + for child in name: + if child.tag == "given-names": + if between is None: + return "given family" + break + if child.tag == "surname" and between is None: + between = [] + if between is not None: + between.append(child.tail or "") + return "family, given" if "," in "".join(between or []) else "family given" + + +def _latin(text: str) -> bool: + """Whether every letter of `text` is a Latin one, a fullwidth one + included; a modifier letter (the okina of `Gʻulomov`) and the + ordinals of `Mª` are read past, as marks a Latin name is written with.""" + return all("LATIN" in unicodedata.name(c, "") for c in text + if c.isalpha() and unicodedata.category(c) != "Lm" and c not in "ªº") + + +def _named(contrib: ET.Element) -> ET.Element | None: + """A contributor's ``: its own, or of its alternatives the + first holding a surname and written wholly in Latin letters, else + the first holding a surname.""" + name = contrib.find("name") + if name is not None: + return name + names = [n for n in contrib.findall("name-alternatives/name") if _text(n.find("surname"))] + return next((n for n in names if _latin(_text(n))), names[0] if names else None) + + +def author(contrib: ET.Element) -> dict[str, str] | None: + """A contributor's record, or None for one with no `` holding a + surname (a group, a name tagged as given names alone, a name tagged + only as a ``): the composed name and the boxes, the + suffix box holding the suffix and the degrees.""" + name = _named(contrib) + if name is None: + return None + parts = _parts(name) + if not parts["surname"]: + return None + degrees = " ".join(_text(d) for d in contrib.findall("degrees")).strip(" ,;") + spoken = " ".join(parts[tag] for tag in _PARTS if parts[tag]) + record = {"name": f"{spoken}, {degrees}" if degrees else spoken, + "prefix": parts["prefix"], "given": parts["given-names"], + "family": parts["surname"], + "suffix": " ".join(filter(None, (parts["suffix"], degrees)))} + return {k: v for k, v in record.items() if v} + + +def citation(name: ET.Element) -> dict[str, str] | None: + """A ``'s record, or None where it does not tag both a + surname and given names.""" + parts = _parts(name) + if not parts["surname"] or not parts["given-names"]: + return None + record = {"name": as_written(name), "given": parts["given-names"], + "family": parts["surname"], "suffix": parts["suffix"], + "order": order_of(name)} + return {k: v for k, v in record.items() if v} + + +def read_article(body: bytes) -> tuple[str, list[dict[str, str]], list[dict[str, str]]]: + """An article's journal, its contributors' records and its cited + names' records. Raises ValueError where the XML does not parse.""" + try: + root = ET.fromstring(body) + except ET.ParseError as exc: + raise ValueError(f"not XML: {exc}") from None + journal = (_text(root.find(".//journal-meta//journal-id[@journal-id-type='nlm-ta']")) + or _text(root.find(".//journal-meta//journal-title"))) + authors = [r for c in root.iter("contrib") if (r := author(c))] + cited = [r for ref in root.iter("mixed-citation") + for n in ref.iter("string-name") if (r := citation(n))] + return journal, authors, cited + + +def _listing(body: bytes, number: int, until: int, url: str) -> list[tuple[str, str]]: + """The article versions a listing after `number` holds, as (key, last + modified), those numbered past `until` left out: the bucket lists in + byte order, where `PMC1299561` follows `PMC12995600`, so a run that + finds too few versions after its start goes on into another part of + the archive. Raises ValueError for a body that is not a listing of + metadata keys, each with its date, as many as it counts.""" + try: + root = ET.fromstring(body) + except ET.ParseError as exc: + raise ValueError(f"not XML: {exc}") from None + if root.tag != f"{_S3}ListBucketResult": + raise ValueError(f"{url} is not a bucket listing") + found: list[tuple[str, str]] = [] + contents = root.findall(f"{_S3}Contents") + for entry in contents: + key = _KEY.fullmatch(entry.findtext(f"{_S3}Key") or "") + modified = entry.findtext(f"{_S3}LastModified") or "" + if not key or not modified: + raise ValueError(f"{url} lists an entry that is no article version's " + f"metadata with its date: the bucket's layout has changed") + if number <= int(key[2]) < until: + found.append((key[1], modified)) + if root.findtext(f"{_S3}KeyCount") != str(len(contents)): + raise ValueError(f"{url} does not count the {len(contents)} entries it lists") + return found + + +def _listed(number: int, until: int) -> list[tuple[str, str]]: + url = list_url(number) + return _retried(url, lambda body: _listing(body, number, until, url), 0) + + +def _metadata(body: bytes, key: str) -> dict[str, Any]: + """`key`'s metadata, or ValueError where it is not the object the + bucket's README describes: this article's, saying whether it is + retracted and stating a licence code, null where it has none.""" + meta = json.loads(body) + if not (isinstance(meta, dict) and meta.get("pmcid") == key.split(".")[0] + and isinstance(meta.get("is_retracted"), bool) and "license_code" in meta): + raise ValueError(f"not {key}'s metadata") + return meta + + +def _article(key: str) -> tuple[dict[str, Any], tuple[str, list[dict[str, str]], + list[dict[str, str]]] | None] | str: + """An article version's metadata and, unless it is retracted, what + read_article reads of its XML; or why it did not read + (`bad_metadata`, `unparsed`, `gone`), each body having been asked + for again first, as one cut short in transit would be.""" + try: + meta = _retried(f"{PMC_BUCKET}metadata/{key}.json", lambda b: _metadata(b, key), 0) + except urllib.error.HTTPError as exc: + if exc.code != 404: + raise + exc.close() # an HTTPError holds the response open + return "gone" + except ValueError: + return "bad_metadata" + if meta["is_retracted"]: + return meta, None + try: + return meta, _retried(f"{PMC_BUCKET}{key}/{key}.xml", read_article, 0) + except urllib.error.HTTPError as exc: + if exc.code != 404: + raise + exc.close() # an HTTPError holds the response open + return "gone" + except ValueError: + return "unparsed" + + +def _sampled() -> Walk: + """Both corpora's records from one walk of the sample. A retracted + article is skipped, and of an article's versions listed the newest + is read.""" + numbers = starts() + print(f"listing {len(numbers):,} runs of {PMC_RUN} articles from {PMC_BUCKET} ...", + file=sys.stderr) + with ThreadPoolExecutor(PMC_THREADS) as pool: + listed = dict(pair for run in pool.map( + _listed, numbers, [*numbers[1:], PMC_LAST]) for pair in run) + newest = sorted(listed, key=lambda k: (k.split(".")[0], int(k.split(".")[1]))) + keys = sorted({key.split(".")[0]: key for key in newest}.values()) + asked = len(numbers) * PMC_RUN + if len(keys) < asked * PMC_MIN_LISTED: + raise ValueError(f"the listings hold {len(keys):,} articles of the {asked:,} " + f"asked for: the bucket is not laid out as this reads it") + print(f"reading {len(keys):,} articles ...", file=sys.stderr) + fetched = list(pool.map(_article, keys)) + counts: Counter[str] = Counter(articles=len(keys)) + authors: dict[str, dict[str, str]] = {} + cited: dict[str, dict[str, str]] = {} + for key, got in zip(keys, fetched): + if isinstance(got, str): + counts[got] += 1 + continue + meta, read = got + if read is None: + counts["retracted"] += 1 + continue + journal, people, names = read + licence = str(meta["license_code"] or "") + counts[f"licence {licence or '(none)'}"] += 1 + counts["read"] += 1 + counts["no_journal"] += not journal + counts["with_authors"] += bool(people) + counts["with_cited_names"] += bool(names) + counts["author_names"] += len(people) + counts["cited_names"] += len(names) + tags = {k: v for k, v in (("journal", journal), ("licence", licence), + ("article", key)) if v} + for held, records in ((authors, people), (cited, names)): + for record in records: + held.setdefault(json.dumps(record, sort_keys=True), {**record, **tags}) + bad = counts["bad_metadata"] + counts["unparsed"] + counts["gone"] + _refuse_past([(bad, len(keys), PMC_MAX_BAD, "articles did not read"), + (counts["no_journal"], counts["read"], PMC_MAX_NO_JOURNAL, + "articles name no journal")], + "the bucket is not laid out as this reads it") + by_name = lambda r: (r["name"], r["article"]) # noqa: E731 + return Walk(sorted(authors.values(), key=by_name), sorted(cited.values(), key=by_name), + max(listed[k] for k in keys), dict(counts)) + + +#: A walk waiting for the corpus that has not taken it yet: a process +#: that fetches both corpora (the command line fetches one) reads the +#: bucket once and gives both the same articles, and a second fetch of +#: either walks again. +_walk: dict[str, Walk] = {} + + +def _walked(source: str) -> Walk: + if source not in _walk: + walk = _sampled() + _walk.update({PMC_AUTHORS: walk, PMC_CITATIONS: walk}) + return _walk.pop(source) + + +def _fetched(source: str, holding: str, floor: float, what: str) -> Fetched: + walk = _walked(source) + articles = walk.counts["articles"] + if walk.counts.get(holding, 0) < articles * floor: + raise ValueError(f"{walk.counts.get(holding, 0):,} of {articles:,} articles " + f"{what}: the markup is not what this reads") + records = walk.authors if source == PMC_AUTHORS else walk.cited + return Fetched(records, walk.when, {"sample": sample(), **walk.counts}) + + +def fetch_authors() -> Fetched: + """The sample's contributors, one record per distinct name and boxes: + the composed name, the prefix, given, family and suffix boxes that + are filled, and the first article holding it with its journal and + licence. Refused where fewer than PMC_MIN_WITH_AUTHORS of the + articles name one.""" + return _fetched(PMC_AUTHORS, "with_authors", PMC_MIN_WITH_AUTHORS, "name a contributor") + + +def fetch_citations() -> Fetched: + """The sample's cited names tagged in the citation's text, one record + per distinct spelling and boxes: the name as written, the given, + family and suffix boxes that are filled, the order written, and the + first article holding it with its journal and licence. Refused + where fewer than PMC_MIN_WITH_CITED of the articles tag one.""" + return _fetched(PMC_CITATIONS, "with_cited_names", PMC_MIN_WITH_CITED, + "tag a name in a citation's text") + + +check_pmc = _pinned( + "sample", sample, + "the corpus was sampled and read as {held}, and this tool reads {wanted}")