diff --git a/tests/v2/test_config_diff.py b/tests/v2/test_config_diff.py index b1858adcf..772f2ea33 100644 --- a/tests/v2/test_config_diff.py +++ b/tests/v2/test_config_diff.py @@ -249,7 +249,7 @@ def test_a_source_holding_none_of_a_group_says_so( def test_a_group_needs_a_grouped_corpus() -> None: with pytest.raises(SystemExit, match="needs a grouped corpus"): - cd.local_names("ctgov-officials", ["US"]) + cd.local_names("fec-individuals", ["US"]) def test_local_all_with_a_group_reads_the_grouped_corpora_only( @@ -277,6 +277,21 @@ def test_a_group_keeps_a_grouped_corpus_s_records_by_its_source_s_key( assert [t for t, _o, _i in got] == ["Ana Souza"] +@pytest.mark.parametrize("source", ["ctgov-officials", "ctgov-contacts"]) +def test_a_group_keeps_a_ctgov_corpus_s_records_by_country( + monkeypatch: pytest.MonkeyPatch, source: str) -> None: + # A record with no country (a study's sites in several) is in no group. + records = [{"name": name, "study": "NCT1", "role": "", "country": country} + for name, country in (("Ana Souza", "BR"), ("Bo Lima", "KR"), + ("Cy Dias", ""))] + plant_corpus(monkeypatch, cd.local_corpora, source, records, "2026-11-18", "officials", + {"read_version": importlib.import_module("local_ctgov").CTGOV_READ_VERSION}) + assert cd.group_keys()[source] == "country" + assert cd.local_names(source, ["KR"]) == (["Bo Lima"], {"KR"}) + got = cd.gather(_args(local=[source], group=["BR"])) + assert [t for t, _o, _i in got] == ["Ana Souza"] + + @needs_checkout def test_main_runs_a_diff_end_to_end(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: diff --git a/tests/v2/test_local_corpora.py b/tests/v2/test_local_corpora.py index 5273d33c3..4005eb71d 100644 --- a/tests/v2/test_local_corpora.py +++ b/tests/v2/test_local_corpora.py @@ -69,10 +69,12 @@ def _own_cache(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.TempPat def _study(nct: str, *officials: str) -> dict[str, Any]: + """A study with one site, in the United States.""" return {"protocolSection": { "identificationModule": {"nctId": nct}, "contactsLocationsModule": {"overallOfficials": [ - {"name": name, "role": "PRINCIPAL_INVESTIGATOR"} for name in officials]}}} + {"name": name, "role": "PRINCIPAL_INVESTIGATOR"} for name in officials], + "locations": [{"country": "United States"}]}}} #: Two pages holding three studies, one study without officials. @@ -148,14 +150,16 @@ def test_a_fetch_pages_through_and_writes_the_three_files( assert [r["name"] for r in corpus.records] == [ "Ann Lee, MD, PhD", "BOB ROE MD", "Ann Lee, MD, PhD", "Cy Doe,M.D."] assert corpus.records[0] == {"name": "Ann Lee, MD, PhD", "study": "NCT1", - "role": "PRINCIPAL_INVESTIGATOR"} + "role": "PRINCIPAL_INVESTIGATOR", "country": "US"} assert [json.loads(line) for line in (_folder(tmp_path) / "corpus.jsonl").read_text().splitlines()] == [ "Ann Lee, MD, PhD", "BOB ROE MD", "Cy Doe,M.D."] meta = json.loads((_folder(tmp_path) / "meta.json").read_text()) assert (meta["data_date"], meta["records"], meta["names"]) == (_DATE, 4, 3) assert meta["detail"] == {"api_version": "2.0.5", "studies": 3, - "officials_without_a_name": 0} + "read_version": ctgov.CTGOV_READ_VERSION, + "officials_without_a_name": 0, + "officials_by_sites": {"one_country": 4}} assert local.load(_SOURCE) == corpus assert corpus.header().startswith( f"ClinicalTrials.gov (NLM) study officials, data as of {_DATE}; 4 officials") @@ -225,11 +229,247 @@ def test_an_official_without_a_name_is_counted_not_dropped_in_silence( page = {"totalCount": 1, "studies": [{"protocolSection": { "identificationModule": {"nctId": "NCT1"}, "contactsLocationsModule": {"overallOfficials": [ - {"role": "STUDY_CHAIR"}, {"name": "Ann Lee, MD"}]}}}]} + {"role": "STUDY_CHAIR"}, {"name": "Ann Lee, MD"}], + "locations": [{"country": "United States"}]}}}]} _serve(monkeypatch, tmp_path, pages=[page]) corpus = local.fetch(_SOURCE) assert [r["name"] for r in corpus.records] == ["Ann Lee, MD"] assert corpus.meta["detail"]["officials_without_a_name"] == 1 + # The officials kept, by sites: the nameless one is in no bucket. + assert corpus.meta["detail"]["officials_by_sites"] == {"one_country": 1} + + +def _sited(nct: str, countries: list[str | None], *officials: str, + contacts: list[list[dict[str, str]]] | None = None) -> dict[str, Any]: + """A study whose sites are in `countries` (None: a site stating no + country), each site holding the contacts given for it.""" + study = _study(nct, *officials) + sites: list[dict[str, Any]] = [] + for n, country in enumerate(countries): + site: dict[str, Any] = {} if country is None else {"country": country} + if contacts and contacts[n]: + site["contacts"] = contacts[n] + sites.append(site) + study["protocolSection"]["contactsLocationsModule"]["locations"] = sites + return study + + +@pytest.mark.parametrize(("countries", "country", "where"), [ + (["United States"], "US", "one_country"), + (["Turkey (Türkiye)", "Turkey (Türkiye)"], "TR", "one_country"), + (["Bonaire, Saint Eustatius and Saba "], "BQ", "one_country"), + (["United States", "France"], "", "several_countries"), + ([], "", "no_site"), + (["United States", None], "", "a_site_without_a_country"), + (["United States", " "], "", "a_site_without_a_country"), +], ids=["one site", "two sites in one country", "a name with a trailing space", + "two countries", "no site", "a site stating none", "a blank country"]) +def test_an_official_takes_the_country_only_where_every_site_is_in_it( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, countries: list[str | None], + country: str, where: str) -> None: + # The gates off: a study of two officials is the whole registry here, + # and the gates are tested on their own below. + monkeypatch.setattr(ctgov, "_gated", lambda records, counted: None) + page = {"totalCount": 1, "studies": [_sited("NCT1", countries, "Ann Lee", "Bo Wu")]} + _serve(monkeypatch, tmp_path, pages=[page]) + corpus = local.fetch(_SOURCE) + assert [(r["name"], r["country"]) for r in corpus.records] == [ + ("Ann Lee", country), ("Bo Wu", country)] + assert corpus.meta["detail"]["officials_by_sites"] == {where: 2} + + +def test_the_fetch_asks_for_the_sites_countries( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + fetched = _serve(monkeypatch, tmp_path) + local.fetch(_SOURCE) + fields = {urllib.parse.parse_qs(urllib.parse.urlsplit(u).query)["fields"][0] + for u in fetched if "/studies" in u} + assert fields == {ctgov.OFFICIAL_FIELDS} + assert "LocationCountry" in ctgov.OFFICIAL_FIELDS.split(",") + + +@pytest.mark.parametrize("source", [ctgov.CTGOV_OFFICIALS, ctgov.CTGOV_CONTACTS]) +def test_a_country_the_map_does_not_hold_fails_the_fetch_naming_it( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source: str) -> None: + # Even at a site with no official or contact: an unmapped name read as + # no country would hide its study's officials from every group. + page = {"totalCount": 1, "studies": [ + _sited("NCT1", ["United States", "Freedonia"], "Ann Lee", + contacts=[[{"name": "Bo Wu", "role": "CONTACT"}], []])]} + _serve(monkeypatch, tmp_path, pages=[page]) + with pytest.raises(ValueError, match=r"NCT1 lists a site in 'Freedonia'.*CTGOV_COUNTRIES"): + local.fetch(source) + assert local.load(source) is None + + +def test_a_contact_is_kept_once_per_name_role_study_and_country_only( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + # Each repeat dropped is one of the same name, role, study and country; + # any of the four differing keeps a record. The countryless count is + # of records kept, after the repeats are dropped. + monkeypatch.setattr(ctgov, "CTGOV_MAX_COUNTRYLESS", 1.0) + ann = {"name": "Ann Lee", "role": "PRINCIPAL_INVESTIGATOR"} + ann_contact = {"name": "Ann Lee", "role": "CONTACT"} + page = {"totalCount": 2, "studies": [ + _sited("NCT1", ["United States", "United States", None, None], + contacts=[[ann], [ann_contact], [ann], [ann]]), + _sited("NCT2", ["United States"], contacts=[[ann]])]} + _serve(monkeypatch, tmp_path, pages=[page]) + corpus = local.fetch(ctgov.CTGOV_CONTACTS) + assert [(r["study"], r["role"], r["country"]) for r in corpus.records] == [ + ("NCT1", "PRINCIPAL_INVESTIGATOR", "US"), ("NCT1", "CONTACT", "US"), + ("NCT1", "PRINCIPAL_INVESTIGATOR", ""), ("NCT2", "PRINCIPAL_INVESTIGATOR", "US")] + detail = corpus.meta["detail"] + assert (detail["repeated_in_study_and_country"], + detail["at_a_site_without_a_country"]) == (1, 1) + + +def _studies(n: int, countries: list[str | None], + contacts: list[list[dict[str, Any]]] | None = None) -> dict[str, Any]: + """One page of `n` studies, each with one official ("Ann Lee") and + sites in `countries` holding `contacts`.""" + return {"totalCount": n, "studies": [ + _sited(f"NCT{i}", countries, "Ann Lee", contacts=contacts) for i in range(n)]} + + +@pytest.mark.parametrize("source", [ctgov.CTGOV_OFFICIALS, ctgov.CTGOV_CONTACTS]) +def test_a_fetch_whose_records_hold_no_country_is_refused( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source: str) -> None: + # The "country" key renamed: every site reads as stating none. + page = _studies(3, ["United States"], + contacts=[[{"name": "Bo Wu", "role": "CONTACT"}]]) + for study in page["studies"]: + for site in study["protocolSection"]["contactsLocationsModule"]["locations"]: + site["countryName"] = site.pop("country") + monkeypatch.setattr(ctgov, "CTGOV_MAX_COUNTRYLESS", 1.0) + _serve(monkeypatch, tmp_path, pages=[page]) + with pytest.raises(ValueError, match="none of 3 records holds a country"): + local.fetch(source) + assert local.load(source) is None + + +@pytest.mark.parametrize(("source", "countries", "limit", "what"), [ + (ctgov.CTGOV_OFFICIALS, [], "CTGOV_MAX_NO_SITE", "officials of a study listing no site"), + (ctgov.CTGOV_OFFICIALS, ["United States", None], "CTGOV_MAX_COUNTRYLESS", + "officials of a study with a site stating no country"), + (ctgov.CTGOV_CONTACTS, [None], "CTGOV_MAX_COUNTRYLESS", + "contacts at a site stating no country"), +], ids=["officials with no site", "officials at a countryless site", + "contacts at a countryless site"]) +def test_a_fetch_past_a_share_of_records_without_a_country_is_refused( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source: str, + countries: list[str | None], limit: str, what: str) -> None: + # Two studies of four read right, one of each other share: 2 of 4 + # (one share past) against 1 of 4 (at it). A partial rename of the + # key shows as a rising share before it empties every record. + contacts: list[list[dict[str, Any]]] = [[{"name": "Bo Wu", "role": "CONTACT"}]] * len(countries) + right = _studies(1, ["United States"], + contacts=[[{"name": "Bo Wu", "role": "CONTACT"}]])["studies"][0] + monkeypatch.setattr(ctgov, limit, 0.25) + for bad, refused in ((2, True), (1, False)): + studies = [_sited(f"NCTB{i}", countries, "Ann Lee", contacts=contacts) + for i in range(bad)] + studies += [{**right, "protocolSection": { + **right["protocolSection"], + "identificationModule": {"nctId": f"NCTR{i}"}}} for i in range(4 - bad)] + _serve(monkeypatch, tmp_path, pages=[{"totalCount": 4, "studies": studies}]) + if refused: + with pytest.raises(ValueError, match=f"{bad} of 4 {what}"): + local.fetch(source) + else: + local.fetch(source) + + +@pytest.mark.parametrize("source", [ctgov.CTGOV_OFFICIALS, ctgov.CTGOV_CONTACTS]) +@pytest.mark.parametrize(("key", "value"), [ + ("country", {"name": "France"}), ("country", 0), ("role", None), ("role", 3)], + ids=["a country object", "a country number", "a null role", "a role number"]) +def test_a_country_or_role_that_is_not_text_fails_the_fetch_naming_the_study( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source: str, key: str, + value: object) -> None: + # Written as it came, a role of null would make a corpus every reader + # refuses, and a fetch again would write it again. + contact: dict[str, Any] = {"name": "Bo Wu", "role": "CONTACT"} + page = _studies(1, ["United States"], contacts=[[contact]]) + module = page["studies"][0]["protocolSection"]["contactsLocationsModule"] + if key == "country": + module["locations"][0]["country"] = value + else: + contact["role"] = value + module["overallOfficials"][0]["role"] = value + _serve(monkeypatch, tmp_path, pages=[page]) + with pytest.raises(ValueError, match=rf"NCT0 lists a .*{key}.* not text"): + local.fetch(source) + + +def test_every_mapped_code_is_two_capitals_and_names_one_country() -> None: + codes = list(ctgov.CTGOV_COUNTRIES.values()) + assert all(len(c) == 2 and c.isascii() and c.isupper() for c in codes) + assert len(set(codes)) == len(codes) + assert all(name == name.strip() for name in ctgov.CTGOV_COUNTRIES) + + +@pytest.mark.parametrize("source", [ctgov.CTGOV_OFFICIALS, ctgov.CTGOV_CONTACTS]) +@pytest.mark.parametrize("detail", [{}, {"read_version": 0}], + ids=["fetched before the country", "read another way"]) +def test_a_ctgov_corpus_read_by_another_version_is_refused_on_load( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source: str, + detail: dict[str, int]) -> None: + # A corpus fetched before #1451 holds no "country": read, it would + # pass for a registry with no country anywhere. + monkeypatch.setenv("NAMEPARSER_TOOLS_CACHE", str(tmp_path)) + real = local.SOURCES[source] + plant_corpus(monkeypatch, local, source, [{"name": "Ann Lee"}], _DATE, + real.unit, detail) + monkeypatch.setitem(local.SOURCES, source, real) + with pytest.raises(local.CorpusDamaged, match=( + rf"read by read version {detail.get('read_version')}, and this tool reads " + rf"version {ctgov.CTGOV_READ_VERSION}; fetch it again: " + rf"tools/differential/local_corpora.py fetch {source} --refresh")): + local.load(source) + + +def test_the_contacts_corpus_keeps_each_site_contact_with_its_site_s_country( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + ann = {"name": "Ann Lee, MD", "role": "PRINCIPAL_INVESTIGATOR"} + bo = {"name": "Bo Wu", "role": "CONTACT"} + # Ann at two sites in the US (kept once) and one in France (kept); a + # nameless contact counted; a site stating no country; a central + # contact, which belongs to no site, left out. + first = _sited("NCT1", ["United States", "United States", "France", None], "Cy Doe", + contacts=[[ann, bo], [ann, {"role": "CONTACT"}], [ann], [bo]]) + first["protocolSection"]["contactsLocationsModule"]["centralContacts"] = [ + {"name": "Di Central", "role": "CONTACT"}] + pages: list[dict[str, Any]] = [ + {"totalCount": 2, "nextPageToken": "t2", "studies": [first]}, + {"studies": [_sited("NCT2", ["South Korea"], contacts=[[ann]])]}] + monkeypatch.setattr(ctgov, "CTGOV_MAX_COUNTRYLESS", 1.0) + fetched = _serve(monkeypatch, tmp_path, pages=pages) + corpus = local.fetch(ctgov.CTGOV_CONTACTS) + assert corpus.records == [ + {"name": "Ann Lee, MD", "study": "NCT1", "role": "PRINCIPAL_INVESTIGATOR", + "country": "US"}, + {"name": "Bo Wu", "study": "NCT1", "role": "CONTACT", "country": "US"}, + {"name": "Ann Lee, MD", "study": "NCT1", "role": "PRINCIPAL_INVESTIGATOR", + "country": "FR"}, + {"name": "Bo Wu", "study": "NCT1", "role": "CONTACT", "country": ""}, + {"name": "Ann Lee, MD", "study": "NCT2", "role": "PRINCIPAL_INVESTIGATOR", + "country": "KR"}] + assert corpus.meta["detail"] == { + "api_version": "2.0.5", "studies": 2, "read_version": ctgov.CTGOV_READ_VERSION, + "contacts_without_a_name": 1, "repeated_in_study_and_country": 1, + "at_a_site_without_a_country": 1} + assert corpus.header().startswith( + f"ClinicalTrials.gov (NLM) study site contacts, data as of {_DATE}; 5 contacts") + fields = {urllib.parse.parse_qs(urllib.parse.urlsplit(u).query)["fields"][0] + for u in fetched if "/studies" in u} + assert fields == {ctgov.CONTACT_FIELDS} + # The fake server ignores the fields, so hold the list itself. + assert {"NCTId", "LocationCountry", "LocationContactName", + "LocationContactRole"} <= set(ctgov.CONTACT_FIELDS.split(",")) + # The officials' corpus is untouched by the sibling's fetch. + assert local.load(_SOURCE) is None + assert local.load(ctgov.CTGOV_CONTACTS) == corpus @pytest.mark.parametrize("answer", [ @@ -3112,7 +3352,8 @@ def _fetched(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, behind it; its folder.""" monkeypatch.setenv("NAMEPARSER_TOOLS_CACHE", str(tmp_path)) records = [{"name": n} for n in names or ("Ann Lee, MD", "Bo Wu, PhD")] - plant_corpus(monkeypatch, local, _SOURCE, records, date, "officials") + plant_corpus(monkeypatch, local, _SOURCE, records, date, "officials", + {"read_version": ctgov.CTGOV_READ_VERSION}) return _folder(tmp_path) @@ -3353,7 +3594,8 @@ 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 and PARLIAMENTS are sources' names, keys of + # JRC, ORCID, PV, VOLBY, DOF, UIT, VN, PARLIAMENTS, 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()} @@ -3372,7 +3614,9 @@ def test_no_module_imports_a_sibling_constant() -> None: ("local_corpora", "ORCID"), ("local_corpora", "PV"), ("local_corpora", "VOLBY"), ("local_corpora", "DOF"), ("local_corpora", "UIT"), ("local_corpora", "VN"), - ("local_corpora", "PARLIAMENTS")} + ("local_corpora", "PARLIAMENTS"), + ("local_corpora", "CTGOV_OFFICIALS"), + ("local_corpora", "CTGOV_CONTACTS")} def test_the_fold_lists_everything_its_functions_call_and_read() -> None: diff --git a/tests/v2/test_measure.py b/tests/v2/test_measure.py index ac6263e86..eac5c2318 100644 --- a/tests/v2/test_measure.py +++ b/tests/v2/test_measure.py @@ -101,7 +101,7 @@ def run(step: object) -> object: assert "Zyx" not in summary assert "none failed" in summary assert "== committed snapshot (against this branch's committed record): moves" in summary - assert "not measured, not fetched: ctgov-officials," in summary + assert "not measured, not fetched: ctgov-contacts, ctgov-officials," in summary assert (out / "01-committed-snapshot.txt").read_text().endswith("Ann Zyx\n") codes["CLDR and GND agreement"] = 2 assert measure.main(["--base", str(base), "--out", str(out)]) == 1 diff --git a/tests/v2/test_word_report.py b/tests/v2/test_word_report.py index 9120a4156..ef2cad114 100644 --- a/tests/v2/test_word_report.py +++ b/tests/v2/test_word_report.py @@ -8,6 +8,7 @@ the output. The corpus names are invented, and each carries a word no grid shape holds, so that one in the output is a quoted name. """ +import importlib import importlib.util import sys from collections import Counter @@ -60,7 +61,8 @@ def _no_usage(monkeypatch: pytest.MonkeyPatch) -> None: def _plant(monkeypatch: pytest.MonkeyPatch, names: list[str] = _NAMES) -> None: plant_corpus(monkeypatch, corpora, "ctgov-officials", [{"name": n, "nct": str(i)} for i, n in enumerate(names)], - "2026-10-21T09:00:05", "officials") + "2026-10-21T09:00:05", "officials", + {"read_version": importlib.import_module("local_ctgov").CTGOV_READ_VERSION}) def test_the_grid_spells_every_shape_three_ways_under_every_order() -> None: diff --git a/tools/differential/README.md b/tools/differential/README.md index c19653c1b..e57f78ede 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`) 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; `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`) 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). ``` uv run python tools/differential/local_corpora.py fetch ctgov-officials @@ -320,7 +320,8 @@ Any snapshot reading of 5,000 entries or more, committed or local, parses in a w | Source | What it is | Blind to | |---|---|---| -| `ctgov-officials` | every overall official of every study on ClinicalTrials.gov, whatever the role (principal investigators, study directors and chairs, and a few sub-investigators and officials with no role), the name as the sponsor's staff typed it into a free-text field: credentials run together (`MBBS,FCPS`), job titles in the name, all-caps and all-lowercase names, typos. Fetched from API v2 (NLM) | names outside clinical research, which is mostly medicine and heavily credentialed; names nobody typed by hand | +| `ctgov-officials` | every overall official of every study on ClinicalTrials.gov, whatever the role (principal investigators, study directors and chairs, and a few sub-investigators and officials with no role), the name as the sponsor's staff typed it into a free-text field: credentials run together (`MBBS,FCPS`), job titles in the name, all-caps and all-lowercase names, typos. Fetched from API v2 (NLM). Each record carries its study, its role and a `country` (#1451): the ISO 3166-1 alpha-2 code of the one country every site of its study is in, and empty where the sites are in several, one states none or the study lists none -- where the study ran, not where the official is from, the affiliation text left unread. The country is the group `config_diff.py --group` keeps (`--group KR`); `snapshot.py --local` reads the whole corpus | names outside clinical research, which is mostly medicine and heavily credentialed; names nobody typed by hand; the country of an official whose study ran in several countries or lists no site | +| `ctgov-contacts` | the sibling of `ctgov-officials` (#1451): the named contacts under each study's sites (mostly `CONTACT`, `PRINCIPAL_INVESTIGATOR` and `SUB_INVESTIGATOR`, the role as the registry writes it), typed into the same registry's free-text fields, each with its study, role and its site's `country` code, the group `--group` keeps, empty where the site states none. One record per name, role, study and country: a name listed again with the same role at another site of one study in one country is kept once and counted in `meta.json`'s detail (`repeated_in_study_and_country`). A corpus of its own so that every count quoted from `ctgov-officials` stays true. Central contacts are left out, belonging to no site. Both corpora map the registry's country names (`Turkey (Türkiye)`, `South Korea`) to codes by `local_ctgov.CTGOV_COUNTRIES`, so the groups line up with ORCID's and PatentsView's, and a name it does not hold fails the fetch, naming it. A fetch holding no country at all, or past a share of records without one (`CTGOV_MAX_NO_SITE`, `CTGOV_MAX_COUNTRYLESS`), is refused, as a renamed key would leave it; a corpus fetched before the country, or read by another `CTGOV_READ_VERSION`, is refused on load with the fetch that replaces it | as `ctgov-officials`; studies with no named site contact | | `fec-individuals` | the distinct names of every individual contributor in the FEC's bulk file for the 2026 cycle (`indiv26.zip`, downloaded once into the cache and read without unpacking; `fetch --refresh` downloads it again). Mostly a filer's software writing a form's fields in a fixed order: of its 1,893,964 names on 2026-10-18 every one was in capitals and 1,893,961 held a comma, with hand-typed text inside the fields -- 3,306 held a second comma, for a credential run or a suffix in a part of its own (`DOE, JR., JOHN`). The population for the one-case family-comma shape. The FEC's terms (52 U.S.C. 30111(a)(4)) bar using the names to solicit contributions or for any commercial purpose | case, since every name is in capitals; names written in their spoken order, or without a comma; small donors, since a committee need itemize only a donor whose gifts to it pass $200; names outside the US; names in any script but Latin | | `tse-donors` | every individual donor to a candidate in Brazil's 2022 general and 2024 municipal elections (the TSE's candidates' accounts, rows from `Recursos de pessoas físicas`), a record per distinct pair of the name as the campaign filed it (`name`) and the federal tax registry's name for the same donor (`registry`): a typed form with its reference form beside it. Of 854,531 records fetched 2026-10-22 (848,351 distinct filed names), 205,925 differ from their registry name -- an agnomen dropped or abbreviated (`JR` filed for the registry's `JUNIOR` in 1,615, `JÚNIOR` for `JUNIOR` in 975), a word left out. Nearly all in capitals (845,498 filed names), in spoken order with no comma (184 records hold one), and full of particles and agnomens (`DE`, `DA`, `DOS`; `FILHO` ends 10,955 distinct filed names, `JUNIOR` 13,784, `NETO` 8,410). Published by the TSE under CC BY | case, mostly; the family-comma shape; credentials and titles, which a donation form has no place for; donors to parties rather than candidates; names outside Brazil; names in any script but Latin | | `tw-donors` | the distinct names of every individual donor in every campaign finance report Taiwan's Control Yuan publishes on its political donation platform (ardata.cy.gov.tw, whose zips data.gov.tw also lists): 454 reports of 64 elections on 2026-10-22, presidential, legislative and local: every report from 2018's elections on, and the residual reports of 2014's and 2016's. Each report's zip is cached under the name the platform lists it by, which carries the date it was built, so a refresh downloads only the reports published or rebuilt since. Names as a candidate's staff typed them into a filing, published in full where the ID, address and phone beside them are masked. Of the 308,667 names dated 2026-10-05, 296,820 were three Han characters, 5,449 four and 5,260 two; the population for unspaced Han names written family first, and for the married double surname (冠夫姓) a four-character name often is. Under the Open Government Data License, version 1.0, with the platform's own bar on using the data for profit, credit investigation or another improper purpose | names in spoken order; Latin script (80 of the names dated 2026-10-05 held a Latin letter); the comma (3 of them held a fullwidth one, none an ASCII one); case; names outside Taiwan; donors whose names the report does not publish, such as anonymous gifts; Japanese kanji names, which the Han script cannot tell from Chinese | @@ -395,7 +396,7 @@ 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. -**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, or `opensanctions-parliaments`' datasets (`--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. +**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, or the ctgov corpora's ISO country codes (`--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. ``` uv run python tools/differential/config_diff.py diff default strict:PT_BR --local orcid-researchers --group BR diff --git a/tools/differential/config_diff.py b/tools/differential/config_diff.py index 87e111874..75dbe35ac 100644 --- a/tools/differential/config_diff.py +++ b/tools/differential/config_diff.py @@ -31,9 +31,10 @@ `--local SOURCE` (repeatable, or `all`) a fetched local corpus's distinct names. With neither, the committed corpora. `--group` keeps a grouped local corpus's records of that country or nationality, or for -opensanctions-parliaments that dataset (local_agreement.FIELDED names -the key, and Source.group for a corpus with no fields; matched exactly -as the corpus writes it), and needs `--local`: with `--committed` beside it, which +opensanctions-parliaments that dataset, or for ctgov-officials and +ctgov-contacts that ISO country code (local_agreement.FIELDED names the +key, and Source.group for a corpus with no fields; matched exactly as +the corpus writes it), and needs `--local`: with `--committed` beside it, which has no groups, it is refused, as is a group no record read holds; with `--local all` it reads the grouped corpora alone, saying so. `--match` keeps the names a regular expression finds anywhere in them, `--sample @@ -419,7 +420,8 @@ def format_tally(spec: str, base: str, t: Tally, top: int) -> list[str]: def group_keys() -> dict[str, str]: """The record key naming each grouped local corpus's group: a fielded corpus's (local_agreement.FIELDED), then a source's own - (Source.group, opensanctions-parliaments' dataset).""" + (Source.group: opensanctions-parliaments' dataset, the ctgov corpora's + country).""" keys = {source: fielded.group for source, fielded in local_agreement.FIELDED.items()} return keys | {source: s.group for source, s in local_corpora.SOURCES.items() if s.group and source not in keys} @@ -482,7 +484,8 @@ def gather(args: argparse.Namespace) -> list[tuple[str, str | None, frozenset[st if missing := sorted(set(args.group) - held): keys = "; ".join(f"{s} by {k}" for s, k in group_keys().items()) raise SystemExit(f"--group {', '.join(missing)}: no record read holds it; a group is " - f"matched as the corpus writes it, ORCID and PatentsView an ISO code " + f"matched as the corpus writes it, ORCID, PatentsView and the ctgov " + f"corpora an ISO code " f"such as BR, PSC a nationality such as Brazilian, " f"opensanctions-parliaments a dataset such as kz_mazhilis ({keys})") if args.spelling: diff --git a/tools/differential/local_core.py b/tools/differential/local_core.py index 157124010..ed97ade0d 100644 --- a/tools/differential/local_core.py +++ b/tools/differential/local_core.py @@ -71,7 +71,8 @@ class Source: boxes: Callable[[Path], Iterator[tuple[str, str, str, int]]] | None = None #: For a source with no fields to score (no local_agreement.FIELDED #: entry) whose records name a group all the same: the record key - #: holding it (opensanctions-parliaments' "dataset"), which + #: holding it (opensanctions-parliaments' "dataset", the ctgov + #: corpora's "country"), which #: config_diff.py --group keeps, as it keeps a fielded source's. group: str = "" @@ -111,7 +112,7 @@ def _zip_stamp(info: zipfile.ZipInfo) -> str: return "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}".format(*info.date_time) -def _pinned(key: str, wanted: Callable[[], str], says: str +def _pinned(key: str, wanted: Callable[[], object], says: str ) -> Callable[[dict[str, Any]], str]: """A Source.check refusing a corpus whose meta.json detail `key` is not `wanted()` now, read at check time so that a change to the diff --git a/tools/differential/local_corpora.py b/tools/differential/local_corpora.py index f377ff26d..e723fb067 100644 --- a/tools/differential/local_corpora.py +++ b/tools/differential/local_corpora.py @@ -36,7 +36,10 @@ - raw.jsonl -- one record per name as the source gave it, with where it came from where the source says: a ClinicalTrials.gov official, with - the study and role; one distinct FEC, Taiwan or UK donor name, alone; + the study, role and the country every site of the study is in, or + none where they differ, one states none or there are none; a + ClinicalTrials.gov site contact, with the study, role and site's + country; one distinct FEC, Taiwan or UK donor name, alone; one distinct pair of a TSE donor's filed name and the tax registry's name for the same donor; one distinct PSC filed name, with its four boxes and nationality; one distinct spelling of a JRC-Names person, @@ -89,7 +92,7 @@ read from another version of it (tw-donors needs neither: each zip it caches is named by the version the listing gives). What each source is, what it is the population for and what its terms allow is its module's docstring: local_ctgov.py -(ctgov-officials), local_fec.py (fec-individuals), local_tse.py +(ctgov-officials, ctgov-contacts), local_fec.py (fec-individuals), local_tse.py (tse-donors), local_tw.py (tw-donors), local_ukec.py (ukec-individuals), local_govuk.py (govuk-people), local_psc.py (psc-individuals), local_jrc.py (jrc-names), @@ -133,7 +136,8 @@ import corpus_build # noqa: E402 import local_core # noqa: E402 from local_core import Fetched as Fetched, Source, _again, fetch_command # noqa: E402 -from local_ctgov import fetch_ctgov # noqa: E402 +from local_ctgov import (CTGOV_CONTACTS, CTGOV_OFFICIALS, check_ctgov, # noqa: E402 + fetch_ctgov, fetch_ctgov_contacts) import local_dof # noqa: E402 from local_dof import DOF, check_dof, fetch_dof, renew_dof # noqa: E402 import local_fec # noqa: E402 @@ -223,9 +227,12 @@ def index(self) -> WordIndex: SOURCES: dict[str, Source] = { - "ctgov-officials": Source( + CTGOV_OFFICIALS: Source( credit="ClinicalTrials.gov (NLM) study officials", unit="officials", - fetch=fetch_ctgov), + fetch=fetch_ctgov, check=check_ctgov, group="country"), + CTGOV_CONTACTS: Source( + credit="ClinicalTrials.gov (NLM) study site contacts", unit="contacts", + fetch=fetch_ctgov_contacts, check=check_ctgov, group="country"), "fec-individuals": Source( credit=f"FEC individual contributions, {local_fec.FEC_CYCLE} cycle " f"(52 U.S.C. 30111(a)(4): not for soliciting or commercial use)", diff --git a/tools/differential/local_ctgov.py b/tools/differential/local_ctgov.py index c0cc07bd0..5a3114613 100644 --- a/tools/differential/local_ctgov.py +++ b/tools/differential/local_ctgov.py @@ -1,28 +1,163 @@ -"""The ctgov-officials local corpus: ClinicalTrials.gov's study officials. +"""The ctgov-officials and ctgov-contacts local corpora: ClinicalTrials.gov's +study officials and site contacts. ctgov-officials -- every overall official of every study on ClinicalTrials.gov, whatever the role (principal investigators, study directors and chairs, and a few sub-investigators and officials with no role), the name as the sponsor's staff typed it into a free-text field, -with credentials, job titles and typos left in. Fetched from API v2 -(NLM). ClinicalTrials.gov's terms ask anyone redistributing the data to -credit it, show NLM's processing date and say what was changed: every -report local_corpora.py prints and the tools/name_usage.py row carry the credit and the -date, and the names are kept unchanged. +with credentials, job titles and typos left in, each with its study, its +role and a country: the ISO 3166-1 alpha-2 code of the one country every +site of the study is in, and "" where the sites are in several countries, +a site states none, or the study lists no site. The country says where +the study ran, not where the official is from; the affiliation text is +not read (#1451). + +ctgov-contacts -- the named contacts under each study's sites, the +officials' sibling (#1451): one record per contact name, role, study and +site country, a name listed again with the same role at another site of +one study in one country kept once and counted, each with its role +(mostly CONTACT, PRINCIPAL_INVESTIGATOR or SUB_INVESTIGATOR, as the +registry writes it) and its site's country code, +"" where the site states no country. Central contacts are left out: they +belong to no site, so they have no country of their own. A corpus of its +own rather than more records in ctgov-officials, so the counts already +quoted from that one stay true. + +Both are fetched from API v2 (NLM), each paging the whole registry, and +the registry's country names (`Turkey (Türkiye)`, `South Korea`) are +mapped to codes by CTGOV_COUNTRIES, so the groups line up with +orcid-researchers' and patentsview-inventors'; a name the map does not +hold fails the fetch, naming it. ClinicalTrials.gov's terms ask anyone +redistributing the data to credit it, show NLM's processing date and say +what was changed: every report local_corpora.py prints and the +tools/name_usage.py row carry the credit and the date, the names are +kept unchanged; the changes are the country, a code for the registry's +name, and ctgov-contacts' repeats, kept once. """ from __future__ import annotations import sys import urllib.parse -from collections.abc import Iterator +from collections import Counter +from collections.abc import Callable, Iterator from typing import Any -from local_core import Fetched, _get_json +from local_core import Fetched, _get_json, _pinned, _refuse_past CTGOV_API = "https://clinicaltrials.gov/api/v2" CTGOV_PAGE = 1000 # the API's largest page -CTGOV_FIELDS = "NCTId,OverallOfficialName,OverallOfficialRole" +CTGOV_OFFICIALS = "ctgov-officials" +CTGOV_CONTACTS = "ctgov-contacts" +#: LocationCountry alone still returns a site stating no country, as +#: {} (NCT00320424, 2026-11-18), so the rule sees it. +OFFICIAL_FIELDS = "NCTId,OverallOfficialName,OverallOfficialRole,LocationCountry" +CONTACT_FIELDS = "NCTId,LocationCountry,LocationContactName,LocationContactRole" +#: The version of how a record is built from what the API gives (the +#: country rule, ctgov-contacts' repeat key and CTGOV_COUNTRIES's +#: codes), stored in meta.json and +#: required on load: bump it with any change to either, so a corpus read +#: the old way is refused rather than read. 1: the country (#1451); a +#: corpus fetched before it holds no "country" and is refused too. +CTGOV_READ_VERSION = 1 +#: The most of the officials kept whose study lists no site, and of the +#: officials or contacts kept at a site stating no country, before a +#: fetch is refused: a renamed "locations" or "country" key would +#: otherwise empty every record's country in silence. Measured +#: 2026-11-18 by the API's own filters: of the 430,126 studies naming an +#: official, 31,924 list no site country, all but 15 of them no site at +#: all (about 7.4%), and no site of 3,000 studies paged stated no +#: country. +CTGOV_MAX_NO_SITE = 0.25 +CTGOV_MAX_COUNTRYLESS = 0.01 + +#: Every country name the registry writes, as listed by +#: /api/v2/stats/field/values?fields=LocationCountry (226 names on +#: 2026-11-18), with its ISO 3166-1 alpha-2 code. A territory the +#: registry names apart (Puerto Rico, Guam, Réunion) keeps its own code, +#: as ISO gives it one (Reunion: RE). Four names have no current code: Kosovo takes the +#: user-assigned XK, the code in common use for it, and Serbia and Montenegro, the +#: Federal Republic of Yugoslavia and the Netherlands Antilles their +#: former codes (CS, YU, AN, ISO 3166-3). Names are looked up with their +#: edges stripped: the registry writes one with a trailing space. +CTGOV_COUNTRIES: dict[str, str] = { + "Afghanistan": "AF", "Aland Islands": "AX", "Albania": "AL", "Algeria": "DZ", + "American Samoa": "AS", "Andorra": "AD", "Angola": "AO", "Anguilla": "AI", + "Antarctica": "AQ", "Antigua and Barbuda": "AG", "Argentina": "AR", + "Armenia": "AM", "Aruba": "AW", "Australia": "AU", "Austria": "AT", + "Azerbaijan": "AZ", "Bahrain": "BH", "Bangladesh": "BD", "Barbados": "BB", + "Belarus": "BY", "Belgium": "BE", "Belize": "BZ", "Benin": "BJ", + "Bermuda": "BM", "Bhutan": "BT", "Bolivia": "BO", + "Bonaire, Saint Eustatius and Saba": "BQ", "Bosnia and Herzegovina": "BA", + "Botswana": "BW", "Brazil": "BR", "Brunei": "BN", "Bulgaria": "BG", + "Burkina Faso": "BF", "Burma": "MM", "Burundi": "BI", "Cabo Verde": "CV", + "Cambodia": "KH", "Cameroon": "CM", "Canada": "CA", "Cayman Islands": "KY", + "Central African Republic": "CF", "Chad": "TD", "Chile": "CL", "China": "CN", + "Christmas Island": "CX", "Colombia": "CO", "Comoros": "KM", + "Costa Rica": "CR", "Côte d’Ivoire": "CI", "Croatia": "HR", "Cuba": "CU", + "Curacao": "CW", "Cyprus": "CY", "Czechia": "CZ", + "Democratic Republic of the Congo": "CD", "Denmark": "DK", "Djibouti": "DJ", + "Dominica": "DM", "Dominican Republic": "DO", "Ecuador": "EC", "Egypt": "EG", + "El Salvador": "SV", "Equatorial Guinea": "GQ", "Eritrea": "ER", + "Estonia": "EE", "Eswatini": "SZ", "Ethiopia": "ET", "Faroe Islands": "FO", + "Federal Republic of Yugoslavia": "YU", "Fiji": "FJ", "Finland": "FI", + "France": "FR", "French Guiana": "GF", "French Polynesia": "PF", + "French Southern and Antarctic Lands": "TF", "Gabon": "GA", "Georgia": "GE", + "Germany": "DE", "Ghana": "GH", "Gibraltar": "GI", "Greece": "GR", + "Greenland": "GL", "Grenada": "GD", "Guadeloupe": "GP", "Guam": "GU", + "Guatemala": "GT", "Guinea": "GN", "Guinea-Bissau": "GW", "Guyana": "GY", + "Haiti": "HT", "Holy See": "VA", "Honduras": "HN", "Hong Kong": "HK", + "Hungary": "HU", "Iceland": "IS", "India": "IN", "Indonesia": "ID", + "Iran": "IR", "Iraq": "IQ", "Ireland": "IE", "Israel": "IL", "Italy": "IT", + "Jamaica": "JM", "Japan": "JP", "Jersey": "JE", "Jordan": "JO", + "Kazakhstan": "KZ", "Kenya": "KE", "Kiribati": "KI", "Kosovo": "XK", + "Kuwait": "KW", "Kyrgyzstan": "KG", "Laos": "LA", "Latvia": "LV", + "Lebanon": "LB", "Lesotho": "LS", "Liberia": "LR", "Libya": "LY", + "Liechtenstein": "LI", "Lithuania": "LT", "Luxembourg": "LU", "Macau": "MO", + "Madagascar": "MG", "Malawi": "MW", "Malaysia": "MY", "Maldives": "MV", + "Mali": "ML", "Malta": "MT", "Martinique": "MQ", "Mauritania": "MR", + "Mauritius": "MU", "Mayotte": "YT", "Mexico": "MX", "Micronesia": "FM", + "Moldova": "MD", "Monaco": "MC", "Mongolia": "MN", "Montenegro": "ME", + "Montserrat": "MS", "Morocco": "MA", "Mozambique": "MZ", "Namibia": "NA", + "Nepal": "NP", "Netherlands": "NL", "Netherlands Antilles": "AN", + "New Caledonia": "NC", "New Zealand": "NZ", "Nicaragua": "NI", "Niger": "NE", + "Nigeria": "NG", "Niue": "NU", "North Korea": "KP", "North Macedonia": "MK", + "Northern Mariana Islands": "MP", "Norway": "NO", "Oman": "OM", + "Pakistan": "PK", "Palestinian Territories": "PS", "Panama": "PA", + "Papua New Guinea": "PG", "Paraguay": "PY", "Peru": "PE", + "Philippines": "PH", "Poland": "PL", "Portugal": "PT", "Puerto Rico": "PR", + "Qatar": "QA", "Republic of the Congo": "CG", "Reunion": "RE", + "Romania": "RO", "Russia": "RU", "Rwanda": "RW", "Saint Kitts and Nevis": "KN", + "Saint Lucia": "LC", "Saint Martin": "MF", + "Saint Vincent and the Grenadines": "VC", "Samoa": "WS", "San Marino": "SM", + "Saudi Arabia": "SA", "Senegal": "SN", "Serbia": "RS", + "Serbia and Montenegro": "CS", "Seychelles": "SC", "Sierra Leone": "SL", + "Singapore": "SG", "Slovakia": "SK", "Slovenia": "SI", + "Solomon Islands": "SB", "Somalia": "SO", "South Africa": "ZA", + "South Korea": "KR", "South Sudan": "SS", "Spain": "ES", "Sri Lanka": "LK", + "Sudan": "SD", "Suriname": "SR", "Sweden": "SE", "Switzerland": "CH", + "Syria": "SY", "Taiwan": "TW", "Tajikistan": "TJ", "Tanzania": "TZ", + "Thailand": "TH", "The Bahamas": "BS", "The Gambia": "GM", + "Timor-Leste": "TL", "Togo": "TG", "Trinidad and Tobago": "TT", + "Tunisia": "TN", "Turkey (Türkiye)": "TR", "Turkmenistan": "TM", + "Uganda": "UG", "Ukraine": "UA", "United Arab Emirates": "AE", + "United Kingdom": "GB", "United States": "US", + "United States Minor Outlying Islands": "UM", "Uruguay": "UY", + "Uzbekistan": "UZ", "Vanuatu": "VU", "Venezuela": "VE", "Vietnam": "VN", + "Virgin Islands": "VI", "Yemen": "YE", "Zambia": "ZM", "Zimbabwe": "ZW", +} + + +def country_code(name: str, nct: str) -> str: + """The ISO code of the registry's country `name` (CTGOV_COUNTRIES), + or ValueError naming it and the study `nct` that wrote it: an + unmapped name would otherwise read as no country.""" + code = CTGOV_COUNTRIES.get(name.strip()) + if code is None: + raise ValueError(f"{nct} lists a site in {name!r}, which " + f"local_ctgov.CTGOV_COUNTRIES does not map to an ISO " + f"code; add it and fetch again") + return code def _ctgov_version() -> tuple[str, str]: @@ -30,10 +165,10 @@ def _ctgov_version() -> tuple[str, str]: return str(data["dataTimestamp"]), str(data["apiVersion"]) -def _ctgov_pages() -> Iterator[dict[str, Any]]: +def _ctgov_pages(fields: str) -> Iterator[dict[str, Any]]: token = "" while True: - query = {"pageSize": CTGOV_PAGE, "fields": CTGOV_FIELDS} + query = {"pageSize": CTGOV_PAGE, "fields": fields} if token: query["pageToken"] = token else: @@ -45,23 +180,21 @@ def _ctgov_pages() -> Iterator[dict[str, Any]]: return -def fetch_ctgov() -> Fetched: - """Every study's overall officials, in the API's order. +def _ctgov_read(fields: str, take: Callable[[str, dict[str, Any]], None] + ) -> tuple[str, str, int]: + """Page the registry for `fields`, handing each study's NCT id and + contactsLocationsModule to `take`, and return the data date, the API + version and the studies paged. The registry is refreshed daily, so the data date is read before and after: a fetch that straddles a refresh mixes two days and is - refused. A study paged twice is refused, since its officials would - count twice, and the studies paged must number the totalCount the - first page states, so a fetch cut short cannot pass for the - registry. An official - with no name is counted rather than dropped in silence, so a renamed - field shows as a count in the header instead of a smaller registry.""" + refused. A study paged twice is refused, since its names would count + twice, and the studies paged must number the totalCount the first + page states, so a fetch cut short cannot pass for the registry.""" before, api = _ctgov_version() - records: list[dict[str, str]] = [] total: int | None = None studies: set[str] = set() - nameless = 0 - for number, page in enumerate(_ctgov_pages(), 1): + for number, page in enumerate(_ctgov_pages(fields), 1): if total is None: total = int(page["totalCount"]) if number % 50 == 0: @@ -73,13 +206,7 @@ def fetch_ctgov() -> Fetched: raise ValueError(f"{nct} was paged twice: the pages shifted " f"under the fetch; fetch again") studies.add(nct) - for official in section.get("contactsLocationsModule", {}).get( - "overallOfficials", []): - if official.get("name"): - records.append({"name": official["name"], "study": nct, - "role": official.get("role", "")}) - else: - nameless += 1 + take(nct, section.get("contactsLocationsModule", {})) after, _ = _ctgov_version() if after != before: raise ValueError(f"ClinicalTrials.gov refreshed during the fetch " @@ -87,5 +214,132 @@ def fetch_ctgov() -> Fetched: if len(studies) != total: raise ValueError(f"paged {len(studies):,} studies of the " f"{total:,} the API counted; fetch again") - return Fetched(records, before, {"api_version": api, "studies": total, - "officials_without_a_name": nameless}) + return before, api, total + + +def _site_country(site: dict[str, Any], nct: str) -> str: + """A site's country code, or "" where it states no country; a + country that is not text, or that CTGOV_COUNTRIES does not map, + raises ValueError naming the study.""" + name = site.get("country") + if name is None: + return "" + if not isinstance(name, str): + raise ValueError(f"{nct} lists a site whose country is {name!r}, not " + f"text: the API's shape has changed") + return country_code(name, nct) if name.strip() else "" + + +def _role(entry: dict[str, Any], nct: str) -> str: + """An official's or contact's role, "" where it states none; a role + that is not text raises, naming the study, rather than writing a + corpus every reader refuses.""" + role = entry.get("role", "") + if not isinstance(role, str): + raise ValueError(f"{nct} lists a role {role!r}, not text: the API's " + f"shape has changed") + return role + + +def _gated(records: list[dict[str, str]], counted: list[tuple[int, float, str]]) -> None: + """Refuse a fetch whose records hold no country at all, or where any + of `counted`'s (count, share, what) is past its share of the records + (CTGOV_MAX_NO_SITE, CTGOV_MAX_COUNTRYLESS).""" + if records and not any(r["country"] for r in records): + raise ValueError(f"none of {len(records):,} records holds a country: " + f"a location's \"country\" key may have moved") + _refuse_past([(count, len(records), share, what) for count, share, what in counted], + "a location's key may have moved") + + +def fetch_ctgov() -> Fetched: + """Every study's overall officials, in the API's order, each with + the country its study's sites share (the module docstring). + + An official with no name is counted rather than dropped in silence, + so a renamed field shows as a count in meta.json's detail, which + `fetch` prints, instead of a smaller registry; the officials kept are + counted there by where their study's sites are: none listed, then + a site stating none (whatever the other sites say), then several + countries, else one. A fetch past CTGOV_MAX_NO_SITE or + CTGOV_MAX_COUNTRYLESS, or holding no country at all, is refused.""" + records: list[dict[str, str]] = [] + nameless = 0 + sites: Counter[str] = Counter() + + def take(nct: str, module: dict[str, Any]) -> None: + nonlocal nameless + codes = [_site_country(site, nct) for site in module.get("locations", [])] + named = set(codes) - {""} + if not codes: + where, country = "no_site", "" + elif "" in codes: + where, country = "a_site_without_a_country", "" + elif len(named) > 1: + where, country = "several_countries", "" + else: + where, country = "one_country", named.pop() + for official in module.get("overallOfficials", []): + if official.get("name"): + records.append({"name": official["name"], "study": nct, + "role": _role(official, nct), "country": country}) + sites[where] += 1 + else: + nameless += 1 + + date, api, total = _ctgov_read(OFFICIAL_FIELDS, take) + _gated(records, [ + (sites["no_site"], CTGOV_MAX_NO_SITE, "officials of a study listing no site"), + (sites["a_site_without_a_country"], CTGOV_MAX_COUNTRYLESS, + "officials of a study with a site stating no country")]) + return Fetched(records, date, { + "api_version": api, "studies": total, "read_version": CTGOV_READ_VERSION, + "officials_without_a_name": nameless, + "officials_by_sites": dict(sorted(sites.items()))}) + + +def fetch_ctgov_contacts() -> Fetched: + """Every named contact under every study's sites, in the API's + order, once per name, role, study and country (the module + docstring), counting in meta.json's detail the contacts without a + name, the repeats dropped and the records kept at a site stating no + country. A fetch past CTGOV_MAX_COUNTRYLESS, or holding no country + at all, is refused.""" + records: list[dict[str, str]] = [] + nameless = repeated = countryless = 0 + + def take(nct: str, module: dict[str, Any]) -> None: + nonlocal nameless, repeated, countryless + seen: set[tuple[str, str, str]] = set() + for site in module.get("locations", []): + country = _site_country(site, nct) + for contact in site.get("contacts", []): + name = contact.get("name") + if not name: + nameless += 1 + continue + role = _role(contact, nct) + if (name, role, country) in seen: + repeated += 1 + continue + seen.add((name, role, country)) + countryless += not country + records.append({"name": name, "study": nct, "role": role, + "country": country}) + + date, api, total = _ctgov_read(CONTACT_FIELDS, take) + _gated(records, [(countryless, CTGOV_MAX_COUNTRYLESS, + "contacts at a site stating no country")]) + return Fetched(records, date, { + "api_version": api, "studies": total, "read_version": CTGOV_READ_VERSION, + "contacts_without_a_name": nameless, + "repeated_in_study_and_country": repeated, + "at_a_site_without_a_country": countryless}) + + +#: Source.check for both corpora: a corpus read by another +#: CTGOV_READ_VERSION, or fetched before there was one (and so without a +#: "country"), is refused, naming the fetch that replaces it. +check_ctgov = _pinned("read_version", lambda: CTGOV_READ_VERSION, + "was read by read version {held}, and this tool reads " + "version {wanted}") diff --git a/tools/name_usage.py b/tools/name_usage.py index 39c183fe1..cd8da4bc8 100644 --- a/tools/name_usage.py +++ b/tools/name_usage.py @@ -124,10 +124,10 @@ name and how many after a comma, and the spellings as written. Words are matched ignoring case, periods and edge punctuation (local_corpora.word_key); a spaced word ('Ph. D.') is matched as its - words in a row, with the joined spelling's count beside it. The first is - ClinicalTrials.gov's study officials, where `MD` after a comma is the - usual case and a credential before it is the noise worth seeing; the - second the FEC's individual contributors, nearly every name written + words in a row, with the joined spelling's count beside it. Among them + are ClinicalTrials.gov's study officials and site contacts, where `MD` + after a comma is the usual case and a credential before it is the noise + worth seeing, and the FEC's individual contributors, nearly every name written family, comma, given in capitals by a filer's form, so a count there is a word typed into a field rather than into a whole name. Not a census of anyone: it counts what each source holds.