Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_suggest.py: 22%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""The group suggester: given names a caller declares to be one group,
2it suggests ``Policy`` settings, chiefly the name order (``Parser.suggest``).
4Contracts are stated in prose here, with no doctest blocks. This module
5holds the shared spelling fold so the name tables
6(``config/_order_names.py``, written by ``tools/vocab/order_names.py``)
7and the reader that looks words up in them fold alike, and the per-name
8signals: ``name_votes`` reads one name and returns the votes it casts,
9a dict from ``Signal`` to either an order (``GIVEN_FIRST`` or
10``FAMILY_FIRST``) or, for ``Signal.PATRONYMIC``, the ``PatronymicRule``
11its shape matches. A name is read past its titles at the head and its
12post-nominals at the end, by the base lexicon, with quotes and brackets
13around a word read past too; a name with a comma is read before the
14comma where only post-nominals follow it, and casts nothing otherwise.
15A signal that does not apply casts no vote, so the dict is empty for a
16name of fewer than two words once those are read past. The signals read
17cased evidence in any script: a word with no cased letter never counts
18as capitals (Cyrillic capitals vote, as Latin ones do), a one-letter
19word is never looked up in the name tables, a capitals word of two or
20three letters ending a name that holds a lowercase letter (joined
21initials, `Armitage JO`, or a short surname, `Jason NG`) casts no
22capitals vote and no surname vote of its own, being looked up only to
23veto (a name ending in one that is a listed surname, `Zhou NG`, casts
24no surname vote, #1397), one opening such a name with no capitals word
25after it (`AM Hoy`, `NG Emily`) casts no capitals vote either, and the
26name no surname vote (#1355), and a script the tables do not hold
27(Hangul, Han) simply matches nothing. A patronymic
28votes, Latin or Cyrillic, only where the pipeline's rule reads one
29(rules/O1's three name words, rules/O2's four), through the pipeline's
30own predicates, never a copy of them, and an East Slavic one casts a
31second vote, on the order, by where it stands as rules/O1 reads it
32(``Signal.PATRONYMIC_POSITION``: last family-first, in the middle
33given-first). No signal raises on any string.
35``suggest`` tallies the group's votes and decides two settings
36together, ``patronymic_rules`` first and ``name_order`` second: a
37decided East Slavic rule reorders each name itself, and reorders none
38under a family-first order, so it decides the order as given-first,
39unless the names' own votes decide family-first, as a list of
40patronymics written last does, which it never overrides (a ``FAMILY_FIRST_GIVEN_LAST`` base
41then gets ``FAMILY_FIRST``),
42or the base reads ``FAMILY_FIRST`` and the patronymics are
43mostly written last, whose order it keeps (decisions/group-suggestion).
44Before either it decides
45``initials_as_family`` (rules/O8) from the runs of letters ending the
46group's names, a group property with no per-name vote, and a group
47decided so casts no trailing-initial vote on its order. Beside them it
48decides ``capitals_as_family`` (rules/O9) from the names whose family
49the rule, asked of the parse itself with the switch on, reads as a
50word in capitals of four letters or more that the lexicon lists as no
51credential or numeral and the base reads as no title, against the names
52the switch would give a family the base reads as a title and the names
53in mixed case with no word in capitals; it is no vote on the order,
54which the capitals signal casts as before. Last it weighs
55``two_family_names`` (rules/O6), where the rest reads given-first with
56the East Slavic rule off, asking the parse itself under that parser
57with the switch off and on: a name the switch would change votes for it
58where the word it would take into the family is a common surname of
59the ORCID table (`Signal.FIRST_SURNAME`), casts no vote where that word
60is a common given name, and votes against it where it is a father's
61name. A setting is
62decided only on the evidence the thresholds below admit; any other
63setting keeps the base's value, so an empty group, or one with no
64votes, gives back a parser that reads exactly as the base does. The
65result is a ``Suggestion``: the ``PolicyPatch`` holding only the
66settings the group changed, a ``SettingEvidence`` per setting
67considered, and a ``NameEvidence`` per input name, in input order.
68"""
69from __future__ import annotations
71import dataclasses
72import re
73import reprlib
74import unicodedata
75import warnings
76from collections import Counter
77from collections.abc import Callable, Iterable, Iterator, Mapping
78from dataclasses import dataclass
79from enum import StrEnum
80from types import MappingProxyType
81from typing import TYPE_CHECKING, cast
83from ._lexicon import Lexicon, _normalize
84from ._pipeline._state import COMMA_CHARS
85from ._pipeline._post_rules import _listed_suffix
86from ._pipeline._vocab import (
87 ROMAN, east_slavic_rotates, has_patronymic_ending, is_capitals_word,
88 is_initial, is_one_case, is_patronymic_marker, is_suffix_lenient,
89 is_title_shaped, reads_as_generation, suffix_as_written,
90)
91from ._policy import (
92 UNSET, CapsSuffixes, PatronymicRule, Policy, PolicyPatch, _order_repr,
93 apply_patch, initials_as_family_may_move,
94)
95from ._types import (
96 ADDED_IN, FAMILY_FIRST, GIVEN_FIRST, ReadingSource, Role,
97 _guarded_getstate, _guarded_setstate,
98)
99from .config._order_names import COMMON_GIVEN_NAMES, COMMON_SURNAMES, SURNAMES
101if TYPE_CHECKING:
102 from ._parser import Parser
104# the letters NFKD leaves whole, spelled as an ASCII keyboard writes
105# them
106_KEYBOARD = str.maketrans({
107 "ł": "l", "Ł": "L", "ø": "o", "Ø": "O", "ı": "i", "æ": "ae", "Æ": "AE",
108 "œ": "oe", "Œ": "OE", "ß": "ss", "ẞ": "SS", "đ": "d", "Đ": "D"})
109# a letter u with a diaeresis, decomposed: the pinyin vowel written v on
110# a keyboard (lü -> lv)
111_U_DIAERESIS = {"u\u0308": "v", "U\u0308": "V"}
114def fold(word: str) -> str:
115 """The spelling a word is looked up under in the name tables: lower
116 case, every diacritic dropped, the letters NFKD leaves whole written
117 as an ASCII keyboard writes them (``ł`` as ``l``, ``ø`` as ``o``,
118 ``ı`` as ``i``, ``æ`` as ``ae``, ``œ`` as ``oe``, ``ß`` as ``ss``,
119 ``đ`` as ``d``) and ``ü`` as ``v``.
121 ``Nguyễn`` folds to ``nguyen``, ``Đặng`` to ``dang``, ``Łukasz`` to
122 ``lukasz``, ``Barış`` to ``baris`` and ``Lǚ`` to ``lv``. The tables
123 hold only folded spellings, written with this function, so a reader
124 folds the word first.
125 """
126 text = unicodedata.normalize("NFKD", word).translate(_KEYBOARD)
127 for mark, letter in _U_DIAERESIS.items():
128 text = text.replace(mark, letter)
129 return "".join(c for c in text if not unicodedata.combining(c)).lower()
132class Signal(StrEnum):
133 """The evidence a single name offers about how its writer writes
134 names; each signal votes on one ``Policy`` setting: the order, the
135 patronymic rule or ``two_family_names``."""
137 #: A family name written in capitals at one end of a name in mixed
138 #: case (``Mary SMITH``); votes on the order.
139 CAPITALS = "capitals"
140 #: Initials ending the name (``Smith J.``), counted only where enough
141 #: of the group's names end in them, as a bibliography's do; votes on
142 #: the order.
143 TRAILING_INITIAL = "trailing-initial"
144 #: A lowercase particle first or before the last word; votes on the
145 #: order.
146 PARTICLE = "particle"
147 #: A common surname as the first or last word: a romanized Chinese,
148 #: Korean or Vietnamese one, or one researchers rarely write as a
149 #: given name (``García``, ``Quispe``); votes on the order.
150 SURNAME = "surname"
151 #: A common given name that is rarely a surname (``Emily``, not
152 #: ``Taylor``) as the first or last word; votes on the order.
153 GIVEN_NAME = "given-name"
154 #: A patronymic a rule reads (Russian ``Petrovich``, Azerbaijani
155 #: ``Huseyn oglu``); votes on ``patronymic_rules``.
156 PATRONYMIC = "patronymic"
157 #: Where a Russian-style patronymic stands in a name of three words:
158 #: last (``Sidorov Ivan Petrovich``), the family name is written
159 #: first; in the middle (``Ivan Petrovich Sidorov``), last. Cast only
160 #: beside a Russian-style ``PATRONYMIC`` vote; votes on the order.
161 PATRONYMIC_POSITION = "patronymic-position"
162 #: The word ``two_family_names`` would take into a name's family,
163 #: voting the switch's value: True where it is a surname researchers
164 #: rarely write as a given name, the second of the tables ``SURNAME``
165 #: names (``García`` in ``Gabriel García Márquez``, a first surname where
166 #: a second given name would stand), False where it is a father's
167 #: name the switch would read as a first surname (``Ivan Petrovich
168 #: Sidorov``). A listed given name there casts no vote.
169 FIRST_SURNAME = "first-surname"
172_INITIAL_JOINS = re.compile(r"[.-]+")
175def _is_initialed(word: str) -> bool:
176 """An initial: one letter with an optional period, or single letters
177 joined by periods or hyphens (`J.P.`, `J.-P.`, `J-P`)."""
178 if is_initial(word):
179 return True
180 if "." not in word and "-" not in word:
181 return False
182 chunks = _INITIAL_JOINS.split(word.rstrip("."))
183 return all(chunk and is_initial(chunk + ".") for chunk in chunks)
186def _is_caps_word(word: str) -> bool:
187 """Two or more letters, all of them capitals, and no initial."""
188 letters = [c for c in word if c.isalpha()]
189 # single letters joined by stops or hyphens ('J.-P.', 'J-P') are
190 # initials, however many letters they hold
191 chunks = [c for c in word.replace(".", "-").split("-") if c]
192 paired_initials = len(chunks) > 1 and all(len(c) == 1 for c in chunks)
193 return (len(letters) >= 2 and word.isupper()
194 and not paired_initials and not _is_initialed(word))
197def _has_lower(words: list[str]) -> bool:
198 return any(c.islower() for w in words for c in w)
201def _is_short_capitals(word: str) -> bool:
202 """A capitals word of two or three letters: joined initials (`JO`,
203 `AM`) or a short surname (`NG`, `LI`), which the word alone cannot
204 tell apart."""
205 return 2 <= sum(c.isalpha() for c in word) <= 3 and _is_caps_word(word)
208def _ends_in_short_capitals(words: list[str]) -> bool:
209 """Whether a name holding a lowercase letter ends in a capitals word
210 of two or three letters (`Armitage JO`, `Smith JP`, `Jason NG`).
211 Such a word casts no capitals vote, and no surname vote of its
212 own: `_read` looks it up only to veto the word in front's (#1397)."""
213 return _is_short_capitals(words[-1]) and _has_lower(words)
216def _opens_in_short_capitals(words: list[str]) -> bool:
217 """Whether a name holding a lowercase letter opens in one capitals
218 word of two or three letters (`AM Hoy`, a byline written initials
219 first; `NG Emily`). Such a word casts no capitals vote, and the name
220 no surname vote: with the word in front not looked up, the word at
221 the other end would vote alone (`WU Zhi`, `Zhi` a listed surname
222 too). A run of capitals words in front is the family as before,
223 whatever its first word (`DE SOUZA Maria`, `LI WANG Zhi`)
224 (decisions/group-suggestion, 2026-11-14 #1355)."""
225 return (_is_short_capitals(words[0]) and not _is_caps_word(words[1])
226 and _has_lower(words))
229def _capitals(words: list[str]) -> tuple[Role, Role, Role] | None:
230 """A run of capitals words at one end of a name that also holds a
231 lowercase letter reads as the family name, which writers set in
232 capitals; two or three capitals ending the name, or opening it
233 with no capitals word after them, are joined initials as often, and
234 cast no vote."""
235 if (not _has_lower(words) or _ends_in_short_capitals(words)
236 or _opens_in_short_capitals(words)):
237 return None
238 # a name holding a lowercase letter holds a word that is not all
239 # capitals, so the two ends never both vote by being every word
240 caps = [_is_caps_word(w) for w in words]
241 if caps[0] and not caps[-1]:
242 return FAMILY_FIRST
243 if caps[-1] and not caps[0]:
244 return GIVEN_FIRST
245 return None
248def _particle(words: list[str], lexicon: Lexicon) -> tuple[Role, Role, Role] | None:
249 if len(words) < 3:
250 return None
251 particles = lexicon._sets.particles
253 def is_particle(word: str) -> bool:
254 return word == word.lower() and _normalize(word) in particles
256 first = is_particle(words[0])
257 before_last = is_particle(words[-2])
258 if first == before_last:
259 return None
260 return FAMILY_FIRST if first else GIVEN_FIRST
263def _listed(word: str, table: frozenset[str]) -> bool:
264 spelling = fold(word.strip("."))
265 return len(spelling) >= 2 and spelling in table
268def _a_listed_name(word: str) -> bool:
269 """A word the name tables list: name evidence, which is never read
270 past as a title or a post-nominal (`Law`, a Cantonese surname and a
271 listed title). The given-name and ORCID surname tables hold no
272 listed suffix or title (their builder refuses them), and the
273 romanized surname table's suffixes (`ma`, `meng`) are acronyms that
274 may be a name, which are not read past bare with or without this
275 test, so the post-nominal half acts on no shipped word; it holds for
276 a table built otherwise."""
277 return _listed(word, SURNAMES) or _listed(word, COMMON_GIVEN_NAMES)
280def _is_leading_title(word: str, lexicon: Lexicon) -> bool:
281 """A word the lexicon lists as a title, or one rules/H2's shape
282 reads as a title at the head of a name (`Prof.`, `Insp.`)."""
283 return not _a_listed_name(word) and (
284 _normalize(word) in lexicon._sets.titles
285 or is_title_shaped(word, lexicon))
288def _is_post_nominal(word: str, lexicon: Lexicon) -> bool:
289 """A word after a comma that is a suffix the lexicon lists, or a
290 numeral of two letters or more: is_suffix_lenient, the reading
291 after a comma, which takes a listed one-letter numeral too."""
292 stem = word.rstrip(".")
293 return not _a_listed_name(word) and (
294 is_suffix_lenient(word, lexicon)
295 or (len(stem) > 1 and ROMAN.match(stem) is not None))
298def _ends_in_post_nominal(words: list[str], lexicon: Lexicon,
299 one_case: bool) -> bool:
300 """Whether the last of `words` is a suffix the lexicon lists or a
301 numeral the trailing fork reads as the generation. A one-letter
302 numeral, and a listed acronym written as initials (`J.P.`), need two
303 name words in front of them, as the trailing fork's words-to-spare
304 count asks (rules/S10, rules/S3): `Armitage V` and `Smith J.P.` end
305 in initials."""
306 # the length first: the titles read past at the head can leave no
307 # word at all (`Dr.`, `Jr.`, which H2's shape reads as a title there)
308 if len(words) < 2 or _a_listed_name(words[-1]):
309 return False
310 word = words[-1]
311 stem = word.rstrip(".")
312 if len(words) < 3 and (len(stem) == 1 or _is_initialed(word)):
313 return False
314 listed = suffix_as_written(_normalize(word), word, lexicon)
315 if stem and ROMAN.match(stem) is not None:
316 return reads_as_generation(
317 word, frozenset({"vocab:suffix"}) if listed else frozenset(),
318 words[-2], one_case)
319 return listed
322#: The marks a word is written inside (quotes, brackets), stripped from
323#: its ends before any test.
324_EDGES = "\"'\u2018\u2019\u201a\u201b\u201c\u201d\u201e\u00ab\u00bb\u2039\u203a()[]{}"
325_COMMAS = re.compile("[" + re.escape("".join(sorted(COMMA_CHARS))) + r"\s]+")
328def _name_words(text: str, lexicon: Lexicon) -> tuple[list[str], bool]:
329 """The words the signals read, and whether a comma left the name
330 out. A comma followed by post-nominals alone (`Zhang Wei, PhD`)
331 leaves the part before it; any other comma name is left out, its
332 comma stating its order. Quotes and brackets are stripped from each
333 word, which is composed (NFC), then the titles at the head and the
334 post-nominals at the end (a listed suffix, a numeral read as the
335 generation)."""
336 cut = next((i for i, c in enumerate(text) if c in COMMA_CHARS), None)
337 if cut is not None:
338 tail = [w.strip(_EDGES) for w in _COMMAS.split(text[cut + 1:])]
339 if not all(_is_post_nominal(w, lexicon) for w in tail if w):
340 return [], True
341 text = text[:cut]
342 # composed, so a letter written as base and mark (`oğlu` decomposed)
343 # meets the patterns written composed
344 words = [unicodedata.normalize("NFC", w)
345 for w in (w.strip(_EDGES) for w in text.split()) if w]
346 if not words:
347 return words, False
348 one_case = is_one_case(words)
349 while words and _is_leading_title(words[0], lexicon):
350 del words[0]
351 while _ends_in_post_nominal(words, lexicon, one_case):
352 del words[-1]
353 return words, False
356def _patronymic(words: list[str]) -> PatronymicRule | None:
357 """The rule a name's patronymic votes for, where the pipeline's rule
358 can read it there. rules/O2's four name words, the marker last
359 (family-first) or third (given-first, which the Turkic rule reads
360 too), never first or second, and its three, the marker last
361 whatever the words before it (#1187); rules/O1's three name words, the
362 ending on the middle word (given-first) or on the last
363 (`east_slavic_rotates`, the family-first shape the rule restores),
364 whatever the first word ends in (a surname may end like a
365 patronymic: `Abramovich Roman Arkadyevich`), and no initial first or in the middle (O1's
366 precedence). A final full stop is read past.
368 Both Turkic shapes count the words `_name_words` keeps, not the
369 rule's name words, so they vote where the rule reads nothing: a
370 nickname counted as a word (a bracketed marker among them), a given
371 name P5 binds from two words, a name before a suffix comma, and a
372 marker with a final full stop. The rule the vote turns on leaves
373 each such name as it was (decisions/group-suggestion, 2026-11-12
374 #1187)."""
375 bare = [w.rstrip(".") or w for w in words]
376 if (len(bare) == 4 and not any(map(is_patronymic_marker, bare[:2]))
377 and (is_patronymic_marker(bare[2])
378 or is_patronymic_marker(bare[3]))):
379 return PatronymicRule.TURKIC
380 if len(bare) != 3:
381 return None
382 if is_patronymic_marker(bare[2]):
383 return PatronymicRule.TURKIC
384 if (not (_is_initialed(words[0]) or _is_initialed(words[1]))
385 and (has_patronymic_ending(bare[1])
386 or east_slavic_rotates(bare[1], bare[2]))):
387 return PatronymicRule.EAST_SLAVIC
388 return None
391def _patronymic_end(words: list[str]) -> tuple[Role, Role, Role]:
392 """The end a name casting the East Slavic vote writes its family at,
393 read where rules/O1 reads it: the ending on the middle word is the
394 given-first shape (given, patronymic, family), whatever the last
395 word ends in, and otherwise the patronymic stands last, the
396 family-first shape the rule restores (family, given, patronymic).
397 Asked only of a name `_patronymic` votes East Slavic for, three
398 words long, where the ending stands on the middle word or rules/O1's
399 `east_slavic_rotates` holds."""
400 middle, last = (w.rstrip(".") or w for w in words[1:])
401 return FAMILY_FIRST if east_slavic_rotates(middle, last) else GIVEN_FIRST
404def _letter_run(text: str, readers: tuple[Parser, Parser]) -> str | None:
405 """The letters ending `text` that are evidence of the convention
406 rules/O8 reads, folded and run together (`Lakshmi R. S.` gives
407 ``rs``), or None. A spaced run counts where the rule reads it, asked
408 of the parse itself with the switch on and off (the base's lexicon,
409 the given-first order the rule reads under), so it counts exactly
410 where the rule moves a name. A run written joined with full stops
411 (`B.K.`, `K.C.`) ending the name's words after a name word counts
412 too, though the rule never moves it: the parse makes it the family
413 already (rules/T7), so it is the same convention, and the setting it
414 suggests moves only the spaced runs beside it. Two or three bare
415 capitals (`BK`) do not count: they are written as a short surname is
416 (`Zhi LI`)."""
417 # the cheap text test first: a name it refuses holds no run at all
418 if not initials_as_family_may_move(text):
419 return None
420 on, off = readers
421 family = on.parse(text).family
422 base_family = off.parse(text).family
423 if family != base_family:
424 return "".join(_normalize(word).replace(".", "")
425 for word in family.split())
426 # a comma name gives no words (_name_words), so it holds no run
427 words = _name_words(text, on.lexicon)[0]
428 if len(words) < 2 or _is_initialed(words[0]):
429 return None
430 last = words[-1]
431 # joined with full stops alone: a hyphen joins the halves of one
432 # given name (`J.-P.`, `J-H`), which is no family
433 if not ("." in last.rstrip(".") and "-" not in last
434 and _is_initialed(last)):
435 return None
436 letters = [ch for ch in last if ch.isalpha()]
437 # only where the parse makes the word the whole family: an unlisted
438 # dotted credential (`John Smith X.Y.Z.`, rules/S3) is a suffix
439 if len(letters) < 2 or _normalize(base_family) != _normalize(last):
440 return None
441 return "".join(letters).lower()
444def _read(text: str, lexicon: Lexicon
445 ) -> tuple[dict[Signal, Vote], bool, list[str]]:
446 """The votes one name casts, whether a comma left it out, and the
447 words the signals read."""
448 words, comma = _name_words(text, lexicon)
449 if len(words) < 2:
450 return {}, comma, words
451 votes: dict[Signal, Vote] = {}
453 capitals = _capitals(words)
454 if capitals is not None:
455 votes[Signal.CAPITALS] = capitals
457 if _is_initialed(words[-1]) and not _is_initialed(words[0]):
458 votes[Signal.TRAILING_INITIAL] = FAMILY_FIRST
460 particle = _particle(words, lexicon)
461 if particle is not None:
462 votes[Signal.PARTICLE] = particle
464 # a name opening in two or three capitals casts no surname vote
465 # (#1355), nor does one ending in them where they spell a listed
466 # surname: the ending word is looked up only to veto, so it never
467 # votes alone, and the word in front votes where it does not veto
468 # (#1397)
469 silent = _opens_in_short_capitals(words) or (
470 _ends_in_short_capitals(words)
471 and _listed(words[-1], SURNAMES))
472 tables = () if silent else (
473 (Signal.SURNAME, SURNAMES, FAMILY_FIRST, GIVEN_FIRST),)
474 for signal, table, first_order, last_order in (
475 *tables,
476 (Signal.GIVEN_NAME, COMMON_GIVEN_NAMES, GIVEN_FIRST, FAMILY_FIRST)):
477 at_first = _listed(words[0], table)
478 at_last = _listed(words[-1], table)
479 if at_first != at_last:
480 votes[signal] = first_order if at_first else last_order
482 patronymic = _patronymic(words)
483 if patronymic is not None:
484 votes[Signal.PATRONYMIC] = patronymic
485 if patronymic is PatronymicRule.EAST_SLAVIC:
486 votes[Signal.PATRONYMIC_POSITION] = _patronymic_end(words)
487 return votes, False, words
490def name_votes(text: str, lexicon: Lexicon
491 ) -> dict[Signal, tuple[Role, Role, Role] | PatronymicRule]:
492 """The votes one name casts; empty for a name of fewer than two
493 words once its titles and post-nominals are read past, and for a
494 comma name, save one whose comma is followed by post-nominals
495 alone. It holds no ``two_family_names`` vote, which reads the parse
496 the rest of a suggestion gives."""
497 # _read casts orders and rules alone: the switch's votes are cast in
498 # suggest
499 return cast("dict[Signal, tuple[Role, Role, Role] | PatronymicRule]",
500 _read(text, lexicon)[0])
503# -- the group ----------------------------------------------------------
505#: A vote one signal casts: an order, the patronymic rule a shape
506#: matches, or a switch's value (``two_family_names``).
507Vote = tuple[Role, Role, Role] | PatronymicRule | bool
508#: A setting's value as SettingEvidence holds it: an order, a set of
509#: patronymic rules, or a switch (initials_as_family, capitals_as_family,
510#: two_family_names).
511SettingValue = tuple[Role, Role, Role] | frozenset[PatronymicRule] | bool
513# The thresholds, chosen with tools/differential/suggest_measure.py
514# so that a group written in its base's own order stays right in at
515# least 95% of draws at every size; the measurements behind each are in
516# decisions/group-suggestion, 2026-11-10 THRESHOLDS and 2026-11-11
517# TRAILING INITIAL.
519#: The fewest names voting for a value that can decide it.
520_MIN_VOTES = 2
521#: The share of the names casting an order vote that one end must hold
522#: STRICTLY MORE THAN to decide the order: more than two thirds, so a
523#: tie, or two names against one, decides nothing.
524_MIN_SHARE = 2 / 3
525#: The share of ALL the group's names, voting or not, save those a
526#: comma left out (which state their own order, and which the order
527#: decided reads none of), that the names voting for one end must be at
528#: least to decide the order: in a long list where few names vote, two
529#: stray votes are more than two thirds of the voters and would decide
530#: it. At 200 names or fewer it asks no more than _MIN_VOTES does
531#: (decisions/group-suggestion, 2026-11-16 ORDER FLOOR, #1442).
532_MIN_ORDER_GROUP_SHARE = 0.01
533#: The share of the names casting any vote that one patronymic rule
534#: (East Slavic or Turkic) must hold strictly more than to decide it,
535#: higher than _MIN_SHARE because a decided East Slavic rule brought a
536#: given-first order with it on any base when the share was chosen;
537#: since #1356 a FAMILY_FIRST base keeps its order where the
538#: patronymics are mostly written last.
539_MIN_PATRONYMIC_SHARE = 0.8
540#: The fewest names carrying one patronymic rule that can decide it,
541#: besides the share, chosen for the same reason (decisions/
542#: group-suggestion, 2026-11-15 #1356, which measured what it decides
543#: now).
544_MIN_PATRONYMIC_VOTES = 5
545#: The fewest names ending in one run of letters (rules/O8) that can
546#: decide initials_as_family, and the share of the names ending in any
547#: run that one run must hold at least: a list written in that
548#: convention repeats its letters (Nepal's `B K` and `K C`), where a
549#: list of middle and family initials or of bylines rarely does
550#: (decisions/group-suggestion, 2026-11-11 LETTER RUNS).
551_MIN_RUN_NAMES = 2
552_MIN_RUN_SHARE = 0.5
553#: A word rules/O9 reads as the family is evidence that the group writes
554#: its families in capitals only where it holds at least this many
555#: letters: two or three capitals are joined initials as often as a short
556#: surname (`AM Hoy`, `Zhi LI`), and stay out of the evidence (#659,
557#: decisions/group-suggestion, 2026-11-12 CAPITALS). The names for the
558#: switch must be at least _MIN_VOTES and more than _MIN_SHARE of the
559#: names with evidence either way, as for an order.
560_MIN_CAPITALS_LETTERS = 4
561#: The trailing-initial signal casts its votes only where the names it
562#: reads are at least this many and at least _MIN_TRAILING_SHARE of the
563#: group's names: a byline list ends nearly every name in initials,
564#: while a South Asian or Brazilian list ends a minority that way, and
565#: there the letters are the family or a middle and a family initial
566#: (decisions/group-suggestion, 2026-11-11 TRAILING INITIAL, #1254).
567_MIN_TRAILING_NAMES = 3
568_MIN_TRAILING_SHARE = 0.6
569#: two_family_names is decided where at least this many names vote for
570#: it, they are more than _MIN_TWO_FAMILY_SHARE of the names the switch
571#: would change, and more than the names voting against it: a list of
572#: two family names writes many first surnames the table does not hold,
573#: so the share is lower than an order's (decisions/group-suggestion,
574#: 2026-11-19 #1452, which holds the measurement).
575_MIN_TWO_FAMILY_VOTES = 3
576_MIN_TWO_FAMILY_SHARE = 0.3
578_NAME_ORDER = "name_order"
579_PATRONYMIC_RULES = "patronymic_rules"
580_INITIALS_AS_FAMILY = "initials_as_family"
581_CAPITALS_AS_FAMILY = "capitals_as_family"
582_TWO_FAMILY_NAMES = "two_family_names"
583_SIGNAL_RANK = {signal: rank for rank, signal in enumerate(Signal)}
584#: The setting each signal votes on: one setting a signal, one signal a
585#: kind of vote, read by every site that tells the kinds apart
586#: (decisions/group-suggestion, 2026-11-19 #1447 and #1452).
587_SETTING_OF: Mapping[Signal, str] = MappingProxyType({
588 Signal.CAPITALS: _NAME_ORDER, Signal.TRAILING_INITIAL: _NAME_ORDER,
589 Signal.PARTICLE: _NAME_ORDER, Signal.SURNAME: _NAME_ORDER,
590 Signal.GIVEN_NAME: _NAME_ORDER, Signal.PATRONYMIC: _PATRONYMIC_RULES,
591 Signal.PATRONYMIC_POSITION: _NAME_ORDER,
592 Signal.FIRST_SURNAME: _TWO_FAMILY_NAMES,
593})
596def _end(order: tuple[Role, ...]) -> tuple[Role, Role, Role]:
597 """The end an order writes the family name at, spelled as a vote:
598 ``FAMILY_FIRST`` for either family-first order."""
599 return FAMILY_FIRST if order[0] is Role.FAMILY else GIVEN_FIRST
602def _order_ends(pairs: Iterable[tuple[Signal, Vote]]
603 ) -> frozenset[tuple[Role, Role, Role]]:
604 """The ends a name's order signals voted for: none, one (the name's
605 order vote) or both (the name is contested and casts no order
606 vote)."""
607 return frozenset(vote for signal, vote in pairs # type: ignore[misc]
608 if _SETTING_OF[signal] == _NAME_ORDER)
611def _offered(owner: str, signal: Signal, vote_code: str) -> str:
612 """The code a refused vote's message offers, in its owner's shape: a
613 NameEvidence vote is a mapping entry, a SettingEvidence row a
614 triple."""
615 return (f"{{Signal.{signal.name}: {vote_code}}}"
616 if owner == "NameEvidence"
617 else f"(Signal.{signal.name}, {vote_code}, 2)")
620def _checked_vote(signal: object, vote: object,
621 owner: str = "NameEvidence") -> tuple[Signal, Vote]:
622 """One (signal, vote) pair, validated: an order signal votes
623 ``GIVEN_FIRST`` or ``FAMILY_FIRST``, the patronymic signal a
624 ``PatronymicRule``, a ``two_family_names`` signal the switch's
625 value, True or False. ``owner`` names the type in the message."""
626 signal = Signal(signal) # type: ignore[arg-type] # ValueError names it
627 setting = _SETTING_OF[signal]
628 if setting == _TWO_FAMILY_NAMES:
629 if not isinstance(vote, bool):
630 raise TypeError(
631 f"{owner} vote for {signal.value!r} must be True or False, "
632 f"got {vote!r}; pass e.g. {_offered(owner, signal, 'True')}")
633 return signal, vote
634 if setting == _PATRONYMIC_RULES:
635 if not isinstance(vote, PatronymicRule):
636 raise TypeError(
637 f"{owner} vote for {signal.value!r} must be a "
638 f"PatronymicRule, got {vote!r}; pass e.g. "
639 f"{_offered(owner, signal, 'PatronymicRule.EAST_SLAVIC')}")
640 return signal, vote
641 if not isinstance(vote, (tuple, list)):
642 raise TypeError(
643 f"{owner} vote for {signal.value!r} must be an order, "
644 f"got {vote!r}; pass GIVEN_FIRST or FAMILY_FIRST")
645 order = tuple(vote)
646 for end in (GIVEN_FIRST, FAMILY_FIRST):
647 if order == end:
648 # the shared constant, so a vote compares by identity too
649 return signal, end
650 raise ValueError(
651 f"{owner} vote for {signal.value!r} must name an end, "
652 f"GIVEN_FIRST or FAMILY_FIRST, got {vote!r}; a vote never "
653 f"spells FAMILY_FIRST_GIVEN_LAST, which is FAMILY_FIRST's end")
656def _iterable(value: object, owner: str, form: str, example: str
657 ) -> tuple[object, ...]:
658 """``value`` as a tuple, refusing a bare str, bytes, a mapping or a
659 non-iterable, each of which would iterate into the wrong items."""
660 if (isinstance(value, (str, bytes, bytearray, Mapping))
661 or not isinstance(value, Iterable)):
662 raise TypeError(
663 f"{owner} must be {form}, got {type(value).__name__} "
664 f"{reprlib.repr(value)}; pass e.g. {example}")
665 return tuple(value)
668#: A ``by_signal`` row each setting takes, which a refused row's message
669#: offers: one whose signal votes on that setting
670_ROW_EXAMPLE: Mapping[str, str] = MappingProxyType({
671 _NAME_ORDER: "(Signal.SURNAME, FAMILY_FIRST, 2)",
672 _PATRONYMIC_RULES: "(Signal.PATRONYMIC, PatronymicRule.EAST_SLAVIC, 2)",
673 _TWO_FAMILY_NAMES: "(Signal.FIRST_SURNAME, True, 2)",
674})
677def _checked_row(row: object, setting: str) -> tuple[Signal, Vote, int]:
678 """One ``by_signal`` row, validated: ``(signal, vote, count)``, its
679 signal one that votes on ``setting``."""
680 if isinstance(row, (str, bytes)) or not isinstance(row, (tuple, list)) \
681 or len(row) != 3:
682 raise TypeError(
683 f"SettingEvidence by_signal rows must be (signal, vote, count) "
684 f"triples, got {reprlib.repr(row)}; "
685 + (f"pass e.g. {_ROW_EXAMPLE[setting]}" if setting in _ROW_EXAMPLE
686 else f"no signal votes on {setting}, so pass by_signal=()"))
687 signal, vote, count = row
688 pair = _checked_vote(signal, vote, "SettingEvidence by_signal")
689 if _SETTING_OF[pair[0]] != setting:
690 raise ValueError(
691 f"SettingEvidence by_signal row {reprlib.repr(row)} is a "
692 f"{pair[0].value!r} vote, which votes on {_SETTING_OF[pair[0]]}, "
693 f"not on {setting}; put it in that setting's evidence")
694 if isinstance(count, bool) or not isinstance(count, int):
695 raise TypeError(
696 f"SettingEvidence by_signal count must be an int count of "
697 f"votes, got {count!r}; pass e.g. 2")
698 if count < 0:
699 raise ValueError(
700 f"SettingEvidence by_signal count must not be negative, got "
701 f"{count!r}; a count of votes is 0 or more")
702 return (*pair, count)
705#: The settings a SettingEvidence may be about: the PolicyPatch fields,
706#: which the report reads off the patch by name.
707_SETTINGS = frozenset(f.name for f in dataclasses.fields(PolicyPatch))
710def _label(value: object) -> str:
711 """A vote or a setting's value, as the report and reprs write it."""
712 if isinstance(value, PatronymicRule):
713 return value.value
714 if isinstance(value, frozenset):
715 return ", ".join(sorted(_label(v) for v in value)) or "none"
716 if isinstance(value, tuple):
717 return _order_repr(value)
718 return repr(value)
721_NAME_EVIDENCE_EXAMPLE = (
722 "NameEvidence('Kim Minjun', {Signal.SURNAME: FAMILY_FIRST})")
725@dataclass(frozen=True, slots=True, init=False)
726class NameEvidence:
727 """One input name and the votes it cast, read with the base
728 parser's lexicon. A name with a comma, save one whose comma only
729 post-nominals follow (``Kim Minjun, PhD``), and a name of no words
730 or one word cast none, and a name that casts none never disagrees
731 with the group.
732 Order votes are one per NAME: the end the name's order signals
733 agree on. A name whose order signals point at both ends is
734 contested, casts no order vote and never disagrees on order.
735 ``votes`` holds the votes keyed by signal: an order vote is the
736 order it votes for (``GIVEN_FIRST`` or ``FAMILY_FIRST``), a
737 patronymic vote the ``PatronymicRule``, and a first-surname vote
738 ``True`` or ``False``, cast only where ``two_family_names`` is
739 weighed (not where the base has it on or an East Slavic rule is
740 decided). It keeps every signal's vote all the same, save a
741 trailing-initial vote the group did not cast: too few of its names
742 ending in initials (``Parser.suggest``), or its runs of letters
743 decided ``initials_as_family``, whose letters are its family.
744 ``family_in_capitals`` is the name's evidence on
745 ``capitals_as_family`` (rules/O9), which is no per-signal vote:
746 True where it writes its family in capitals, False where it is in
747 mixed case with no word in capitals, None where it carries none.
748 ``dataclasses.replace`` keeps the votes unless it is passed
749 ``votes=`` too."""
751 #: The name exactly as the caller passed it.
752 text: str
753 # the votes as (Signal, vote) pairs in Signal's order: a tuple, so
754 # the type stays frozen, hashable and picklable; read it through
755 # the `votes` property
756 _votes: tuple[tuple[Signal, Vote], ...]
757 #: The name's evidence on ``capitals_as_family``: True, False or None.
758 family_in_capitals: bool | None = dataclasses.field(
759 default=None, metadata={ADDED_IN: "3.1.0"})
761 __getstate__ = _guarded_getstate
762 __setstate__ = _guarded_setstate
764 def __init__(self, text: str,
765 votes: Mapping[Signal, Vote] | None = None, *,
766 family_in_capitals: bool | None = None,
767 _votes: Iterable[tuple[Signal, Vote]] | None = None
768 ) -> None:
769 # `_votes` is the stored field's name, which dataclasses.replace
770 # passes back; `votes`, where given, wins, so
771 # replace(evidence, votes=...) replaces them
772 if votes is None and _votes is not None:
773 votes = dict(_votes)
774 if not isinstance(text, str):
775 raise TypeError(
776 f"NameEvidence text must be a str, got "
777 f"{type(text).__name__} {reprlib.repr(text)}; pass e.g. "
778 f"{_NAME_EVIDENCE_EXAMPLE}")
779 if not isinstance(votes, Mapping):
780 raise TypeError(
781 f"NameEvidence votes must be a mapping of Signal to vote, "
782 f"got {type(votes).__name__} {reprlib.repr(votes)}; pass "
783 f"e.g. {_NAME_EVIDENCE_EXAMPLE}")
784 pairs = tuple(sorted(
785 (_checked_vote(signal, vote) for signal, vote in votes.items()),
786 key=lambda pair: _SIGNAL_RANK[pair[0]]))
787 if family_in_capitals is not None and not isinstance(
788 family_in_capitals, bool):
789 raise TypeError(
790 f"NameEvidence family_in_capitals must be True, False or "
791 f"None, got {family_in_capitals!r}; pass e.g. "
792 f"NameEvidence('Jean DUPONT', {{}}, family_in_capitals=True)")
793 object.__setattr__(self, "text", text)
794 object.__setattr__(self, "_votes", pairs)
795 object.__setattr__(self, "family_in_capitals", family_in_capitals)
797 def __repr__(self) -> str:
798 votes = "".join(f", {signal.value}={_label(vote)}"
799 for signal, vote in self._votes)
800 capitals = ("" if self.family_in_capitals is None else
801 f", family_in_capitals={self.family_in_capitals}")
802 return f"NameEvidence({self.text!r}{votes}{capitals})"
804 @property
805 def votes(self) -> Mapping[Signal, Vote]:
806 """The votes this name cast, keyed by signal; read-only."""
807 return MappingProxyType(dict(self._votes))
810@dataclass(frozen=True, slots=True)
811class SettingEvidence:
812 """What the group said about one ``Policy`` setting.
814 ``value`` is the setting's value under the suggested parser: the
815 decided value where ``decided`` is true, else the base's. A decided
816 value equal to the base's is not in the patch, which holds only
817 changes, but is still ``decided``. The four counts are of NAMES and
818 add up to the group's size: ``votes_for`` the names whose vote is
819 for ``value``, ``votes_against`` the names whose vote is for
820 another value, ``contested`` the names whose signals point both
821 ways on this setting (and so cast no vote), and ``no_evidence`` the
822 names with no signal on it. ``by_signal`` breaks the signals' own
823 votes down as ``(signal, vote, count)`` rows, so a name two signals
824 read appears in two of them. ``note``, where it is not empty, says
825 why the setting was decided or left undecided as it was."""
827 #: The ``Policy`` field this evidence is about.
828 setting: str
829 #: The field's value under the suggested parser.
830 value: SettingValue
831 #: Whether the group's votes decided the value.
832 decided: bool
833 #: The names whose vote is for ``value``.
834 votes_for: int
835 #: The names whose vote is for another value.
836 votes_against: int
837 #: The names whose signals point both ways on this setting, and so
838 #: cast no vote.
839 contested: int
840 #: The names with no signal on this setting.
841 no_evidence: int
842 #: The signals' own votes as ``(signal, vote, count)`` rows; a name
843 #: two signals read is in two of them.
844 by_signal: tuple[tuple[Signal, Vote, int], ...]
845 #: Why the setting was decided or left undecided as it was, where
846 #: not empty.
847 note: str = ""
849 __getstate__ = _guarded_getstate
850 __setstate__ = _guarded_setstate
852 def __post_init__(self) -> None:
853 if not isinstance(self.setting, str):
854 raise TypeError(
855 f"SettingEvidence setting must be a Policy field name "
856 f"(str), got {self.setting!r}; pass e.g. 'name_order'")
857 if self.setting not in _SETTINGS:
858 raise ValueError(
859 f"SettingEvidence setting must name a Policy field, got "
860 f"{self.setting!r}; pass one of "
861 f"{', '.join(sorted(_SETTINGS))}")
862 if not isinstance(self.decided, bool):
863 raise TypeError(
864 f"SettingEvidence decided must be a bool, got "
865 f"{self.decided!r}; pass True or False")
866 for name in ("votes_for", "votes_against", "contested",
867 "no_evidence"):
868 count = getattr(self, name)
869 if isinstance(count, bool) or not isinstance(count, int):
870 raise TypeError(
871 f"SettingEvidence {name} must be an int count of "
872 f"names, got {count!r}; pass e.g. 0")
873 if count < 0:
874 raise ValueError(
875 f"SettingEvidence {name} must not be negative, got "
876 f"{count!r}; a count of names is 0 or more")
877 if not isinstance(self.note, str):
878 raise TypeError(
879 f"SettingEvidence note must be a str, got {self.note!r}; "
880 f"pass '' for no note")
881 rows = _iterable(self.by_signal, "SettingEvidence by_signal",
882 "an iterable of (signal, vote, count) rows",
883 (f"({_ROW_EXAMPLE[self.setting]},) or ()"
884 if self.setting in _ROW_EXAMPLE else "()"))
885 object.__setattr__(
886 self, "by_signal",
887 tuple(_checked_row(row, self.setting) for row in rows))
889 def __repr__(self) -> str:
890 state = "decided" if self.decided else "undecided"
891 return (f"SettingEvidence({self.setting}={_label(self.value)}, "
892 f"{state}, {self.votes_for} for, {self.votes_against} "
893 f"against, {self.contested} contested, {self.no_evidence} "
894 f"no evidence)")
897@dataclass(frozen=True, slots=True)
898class Suggestion:
899 """The settings a group of names suggests: build it with
900 :meth:`Parser.suggest`. ``patch`` holds only the settings the group
901 decided and that differ from the base's; ``parser`` is the base
902 with the patch applied; ``evidence`` holds one
903 :class:`SettingEvidence` per setting considered, and ``names`` one
904 :class:`NameEvidence` per input name, in input order, blanks and
905 duplicates included. ``str()`` is a readable report.
907 A suggestion is one release's reading of the group: the tables and
908 thresholds behind it change between releases, so keep the ``patch``
909 applied (or the ``parser``'s ``Policy``) with the data rather than
910 calling ``suggest`` again and expecting the same one."""
912 #: The parser ``suggest`` was called on.
913 base: Parser
914 #: The settings the group decided that differ from the base's.
915 patch: PolicyPatch
916 #: One :class:`SettingEvidence` per setting considered.
917 evidence: tuple[SettingEvidence, ...]
918 #: One :class:`NameEvidence` per input name, in input order, blanks and
919 #: duplicates included.
920 names: tuple[NameEvidence, ...]
922 __getstate__ = _guarded_getstate
923 __setstate__ = _guarded_setstate
925 def __post_init__(self) -> None:
926 # Parser at call time: _parser imports this module at call time
927 # too, in Parser.suggest
928 from ._parser import Parser
929 if not isinstance(self.base, Parser):
930 raise TypeError(
931 f"Suggestion base must be a Parser, got "
932 f"{type(self.base).__name__} {reprlib.repr(self.base)}; "
933 f"build a Suggestion with parser.suggest(names)")
934 if not isinstance(self.patch, PolicyPatch):
935 raise TypeError(
936 f"Suggestion patch must be a PolicyPatch, got "
937 f"{reprlib.repr(self.patch)}; pass e.g. PolicyPatch() or "
938 f"PolicyPatch(name_order=FAMILY_FIRST)")
939 for name, cls in (("evidence", SettingEvidence),
940 ("names", NameEvidence)):
941 items = _iterable(
942 getattr(self, name), f"Suggestion {name}",
943 f"a tuple of {cls.__name__}", f"() or a tuple of "
944 f"{cls.__name__} items")
945 for item in items:
946 if not isinstance(item, cls):
947 raise TypeError(
948 f"Suggestion {name} must hold {cls.__name__} "
949 f"items, got {type(item).__name__} "
950 f"{reprlib.repr(item)}; pass a tuple of "
951 f"{cls.__name__}, or build a Suggestion with "
952 f"parser.suggest(names)")
953 object.__setattr__(self, name, items)
954 self._check_against_the_patch()
956 def __repr__(self) -> str:
957 # bounded: the patch and counts, never a name
958 return (f"Suggestion({self.patch!r}, names={len(self.names)}, "
959 f"disagreeing={len(self.disagreeing())})")
961 def __str__(self) -> str:
962 noun = "name" if len(self.names) == 1 else "names"
963 lines = [f"Suggested for {len(self.names)} {noun} "
964 f"(base: {self.base!r}):"]
965 for e in self.evidence:
966 if e.decided:
967 changed = getattr(self.patch, e.setting) is not UNSET
968 state = _label(e.value) + ("" if changed else " (as the base)")
969 else:
970 state = f"unchanged ({_label(e.value)})"
971 if e.votes_for or e.votes_against or e.contested:
972 contested = (f"{e.contested} contested, "
973 if e.contested else "")
974 counts = (f"{e.votes_for} for, {e.votes_against} against, "
975 f"{contested}{e.no_evidence} no evidence")
976 else:
977 counts = "no evidence"
978 lines.append(f" {e.setting} {state} {counts}")
979 for signal, vote, count in e.by_signal:
980 lines.append(f" {signal.value} {_label(vote)} {count}")
981 if e.note:
982 lines.append(f" {e.note}")
983 against = self.disagreeing()
984 if against:
985 shown = ", ".join(n.text for n in against[:5])
986 more = f", and {len(against) - 5} more" if len(against) > 5 else ""
987 lines.append(f" disagreeing ({len(against)}): {shown}{more}")
988 return "\n".join(lines)
990 @property
991 def parser(self) -> Parser:
992 """The base parser with :attr:`patch` applied: the same lexicon
993 and segmenter, and the base's policy for every setting the
994 group did not change. It is built afresh on each access, so
995 bind it once (``p = s.parser``) before parsing in a loop."""
996 # A new construction site for Parser (AGENTS.md's validation
997 # bullet): a warning Parser.__post_init__ gives here is passed
998 # on from the caller's frame only where the base, built the
999 # same way, does not give it too -- the base's own warnings
1000 # reached its caller when it was built.
1001 def built(policy: Policy
1002 ) -> tuple[Parser, list[warnings.WarningMessage]]:
1003 with warnings.catch_warnings(record=True) as caught:
1004 warnings.simplefilter("always")
1005 parser = dataclasses.replace(self.base, policy=policy)
1006 return parser, caught
1008 _, before = built(self.base.policy)
1009 parser, after = built(apply_patch(self.base.policy, self.patch))
1010 seen = {(w.category, str(w.message)) for w in before}
1011 for w in after:
1012 if (w.category, str(w.message)) not in seen:
1013 warnings.warn(w.message, w.category, stacklevel=2)
1014 return parser
1016 def disagreeing(self) -> tuple[NameEvidence, ...]:
1017 """The names whose vote is against a decided setting's value,
1018 in input order. A setting left undecided has no answer to
1019 disagree with; a name that cast no vote, or whose order signals
1020 are contested, never disagrees on order; a name in mixed case
1021 with no word in capitals disagrees with a decided
1022 ``capitals_as_family``; a name whose father's name the switch
1023 would take disagrees with a decided ``two_family_names``; and a
1024 name carrying an
1025 East Slavic patronymic never disagrees on order where the East
1026 Slavic rule is decided with a given-first order, since the rule
1027 reorders it there."""
1028 decided = {e.setting: e.value for e in self.evidence if e.decided}
1029 if not decided:
1030 return ()
1031 return tuple(n for n in self.names if _disagrees(n, decided))
1033 def _check_against_the_patch(self) -> None:
1034 """The evidence, the patch and the names agree: one evidence
1035 per setting, a decided value the suggested parser's own, an
1036 undecided setting out of the patch, every patch field a decided
1037 change from the base, and every setting's counts adding up to
1038 the names."""
1039 settings = Counter(e.setting for e in self.evidence)
1040 for setting, count in settings.items():
1041 if count > 1:
1042 raise ValueError(
1043 f"Suggestion evidence holds {setting!r} more than "
1044 f"once ({count} times); pass one SettingEvidence per "
1045 f"setting")
1046 policy = apply_patch(self.base.policy, self.patch)
1047 decided = set()
1048 size = len(self.names)
1049 for e in self.evidence:
1050 total = (e.votes_for + e.votes_against + e.contested
1051 + e.no_evidence)
1052 if total != size:
1053 raise ValueError(
1054 f"Suggestion evidence for {e.setting} counts names "
1055 f"that add up to {total}, not the {size} names in "
1056 f"names; each name is for, against, contested or of "
1057 f"no evidence on every setting")
1058 if e.decided:
1059 decided.add(e.setting)
1060 if e.value != getattr(policy, e.setting):
1061 raise ValueError(
1062 f"Suggestion's decided {e.setting} value "
1063 f"{_label(e.value)} is not the suggested parser's "
1064 f"{_label(getattr(policy, e.setting))}; set the "
1065 f"patch to the decided value, or leave it out "
1066 f"where the value is the base's")
1067 elif getattr(self.patch, e.setting) is not UNSET:
1068 raise ValueError(
1069 f"Suggestion patch sets {e.setting}, which its "
1070 f"evidence leaves undecided; mark the evidence "
1071 f"decided, or leave {e.setting} out of the patch")
1072 for f in dataclasses.fields(PolicyPatch):
1073 if getattr(self.patch, f.name) is UNSET:
1074 continue
1075 if f.name not in decided:
1076 raise ValueError(
1077 f"Suggestion patch sets {f.name}, which no decided "
1078 f"SettingEvidence holds; add that evidence, or leave "
1079 f"{f.name} out of the patch")
1080 if getattr(policy, f.name) == getattr(self.base.policy, f.name):
1081 raise ValueError(
1082 f"Suggestion patch sets {f.name} to the base's own "
1083 f"value {_label(getattr(policy, f.name))}; a patch "
1084 f"holds only changes, so leave it out and keep the "
1085 f"evidence decided")
1088def _disagrees(name: NameEvidence, decided: Mapping[str, object]) -> bool:
1089 """Whether one name's votes contradict a decided setting."""
1090 if (decided.get(_CAPITALS_AS_FAMILY) is True
1091 and name.family_in_capitals is False):
1092 return True
1093 votes = dict(name._votes)
1094 if (decided.get(_TWO_FAMILY_NAMES) is True
1095 and votes.get(Signal.FIRST_SURNAME) is False):
1096 return True
1097 patronymic = votes.get(Signal.PATRONYMIC)
1098 rules = decided.get(_PATRONYMIC_RULES)
1099 if (rules is not None and patronymic is not None
1100 and patronymic not in rules): # type: ignore[operator]
1101 return True
1102 order = decided.get(_NAME_ORDER)
1103 if order is None:
1104 return False
1105 # a decided rule holds the name's patronymic by now
1106 if (rules is not None and patronymic is PatronymicRule.EAST_SLAVIC
1107 and _end(order) == GIVEN_FIRST): # type: ignore[arg-type]
1108 return False
1109 ends = _order_ends(name._votes)
1110 return len(ends) == 1 and next(iter(ends)) != _end(order) # type: ignore[arg-type]
1113class _Tally:
1114 """The group's votes on one setting, one per name, gathered in one
1115 pass. A plain class rather than a dataclass: it is never pickled or
1116 returned."""
1118 __slots__ = ("names", "left_out", "contested", "by_name", "by_signal")
1120 def __init__(self) -> None:
1121 self.names = 0
1122 #: names a comma left out (`_comma_note`), which cast no vote
1123 self.left_out = 0
1124 self.contested = 0
1125 #: names per value voted for
1126 self.by_name: Counter[Vote] = Counter()
1127 #: signal votes per (signal, value)
1128 self.by_signal: Counter[tuple[Signal, Vote]] = Counter()
1130 def add(self, pairs: list[tuple[Signal, Vote]], left_out: bool = False
1131 ) -> None:
1132 """One name's votes on this setting: its signals' votes, and
1133 one name vote where they agree. ``left_out`` is a name a comma
1134 left out."""
1135 self.names += 1
1136 self.left_out += left_out
1137 for pair in pairs:
1138 self.by_signal[pair] += 1
1139 values = {vote for _, vote in pairs}
1140 if len(values) == 1:
1141 self.by_name[values.pop()] += 1
1142 elif values:
1143 self.contested += 1
1145 def winner(self) -> Vote | None:
1146 """The value whose names are at least _MIN_VOTES, strictly
1147 more than _MIN_SHARE of the names that cast a vote and at least
1148 _MIN_ORDER_GROUP_SHARE of the group's names a comma did not
1149 leave out, if one is."""
1150 end = self.top(_MIN_VOTES, _MIN_SHARE, sum(self.by_name.values()))
1151 return None if end is None or self._short_of_group(end) else end
1153 def held_back(self) -> Vote | None:
1154 """The value the votes would decide but for
1155 _MIN_ORDER_GROUP_SHARE, if one is."""
1156 end = self.top(_MIN_VOTES, _MIN_SHARE, sum(self.by_name.values()))
1157 return end if end is not None and self._short_of_group(end) else None
1159 def _short_of_group(self, end: Vote) -> bool:
1160 # a name a comma left out states its own order, and the order
1161 # decided reads none of them, so it is no name of the floor's
1162 return (self.by_name[end]
1163 < _MIN_ORDER_GROUP_SHARE * (self.names - self.left_out))
1165 def top(self, min_votes: int, min_share: float, total: int
1166 ) -> Vote | None:
1167 """The value most names voted for, where they are at least
1168 ``min_votes`` and strictly more than ``min_share`` of
1169 ``total``."""
1170 if not self.by_name:
1171 return None
1172 vote, count = max(self.by_name.items(), key=lambda item: item[1])
1173 if count < min_votes or count <= min_share * total:
1174 return None
1175 return vote
1177 def evidence(self, setting: str, value: SettingValue, decided: bool,
1178 is_for: Callable[[Vote], bool], note: str = ""
1179 ) -> SettingEvidence:
1180 """Evidence for ``value``; ``is_for`` says which name votes are
1181 for it."""
1182 counts = self.by_name
1183 votes_for = sum(c for v, c in counts.items() if is_for(v))
1184 rows = tuple(sorted(
1185 ((signal, vote, count)
1186 for (signal, vote), count in self.by_signal.items()),
1187 key=lambda row: (_SIGNAL_RANK[row[0]], _label(row[1]))))
1188 voters = sum(counts.values())
1189 return SettingEvidence(
1190 setting, value, decided, votes_for, voters - votes_for,
1191 self.contested, self.names - voters - self.contested, rows,
1192 note)
1195def _patronymic_winner(tally: _Tally, any_voters: int
1196 ) -> PatronymicRule | None:
1197 """The rule whose names are strictly more than _MIN_PATRONYMIC_SHARE
1198 of the names that cast any vote, and at least _MIN_PATRONYMIC_VOTES
1199 of them. A
1200 name whose order signals are contested still counts among the names
1201 that cast a vote: it carries evidence, and leaving it out moved no
1202 measured group by more than a point. A name casts at most one
1203 patronymic vote, so its votes count names: a share of the group,
1204 not of the patronymic votes alone, so one patronymic among many
1205 given-first names decides nothing."""
1206 return tally.top( # type: ignore[return-value]
1207 _MIN_PATRONYMIC_VOTES, _MIN_PATRONYMIC_SHARE, any_voters)
1210def _decide_patronymic(tally: _Tally, base_rules: frozenset[PatronymicRule],
1211 any_voters: int,
1212 written_last: tuple[int, int] | None = None
1213 ) -> tuple[SettingEvidence, dict[str, object], bool]:
1214 """Decide ``patronymic_rules``: the evidence, the patch fields, and
1215 whether the decided rule needs a given-first order. ``written_last``
1216 is given where a decided East Slavic rule keeps the base's
1217 ``FAMILY_FIRST`` order (`_keeps_family_first`): how many of its
1218 voters write the patronymic last and how many in the middle."""
1219 rule = _patronymic_winner(tally, any_voters)
1220 if rule is PatronymicRule.EAST_SLAVIC and written_last is not None:
1221 return (*_rule_decided(tally, base_rules, rule,
1222 _kept_order_note(*written_last)), False)
1223 if rule is PatronymicRule.EAST_SLAVIC:
1224 # the rule reorders a family-first East Slavic name itself, and
1225 # its reordering stands down under a declared family-first
1226 # order, so the group gets the rule with a given-first order
1227 # (what locales.RU ships)
1228 return (*_rule_decided(tally, base_rules, rule), True)
1229 if rule is PatronymicRule.TURKIC:
1230 # unlike the East Slavic rule it reads a name written either way
1231 # round (``Mamedov Ali Huseyn oglu`` and ``Ali Huseyn oglu
1232 # Mamedov`` both read family Mamedov), so it forces no order:
1233 # the order is decided from the names' own votes
1234 # (decisions/group-suggestion, 2026-11-10 TURKIC)
1235 return (*_rule_decided(tally, base_rules, rule), False)
1236 return (tally.evidence(_PATRONYMIC_RULES, base_rules, False,
1237 lambda v: v in base_rules), {}, False)
1240def _rule_decided(tally: _Tally, base_rules: frozenset[PatronymicRule],
1241 rule: PatronymicRule, note: str = ""
1242 ) -> tuple[SettingEvidence, dict[str, object]]:
1243 """The evidence and patch fields for a decided ``rule``: the value
1244 the base's rules with it, the patch the rule alone where the base
1245 lacks it (``patronymic_rules`` composes by union)."""
1246 value = base_rules | {rule}
1247 fields: dict[str, object] = (
1248 {} if rule in base_rules else {_PATRONYMIC_RULES: frozenset({rule})})
1249 return (tally.evidence(_PATRONYMIC_RULES, value, True,
1250 lambda v: v in value, note), fields)
1253def _kept_order_note(last: int, middle: int) -> str:
1254 """The note on an East Slavic rule decided under a ``FAMILY_FIRST``
1255 base the names' own votes do not move (`_keeps_family_first`): the
1256 group gets the rule and no order. That order reads a name written
1257 family, given, patronymic already, and under it the rule reorders
1258 no name and fills the ``patronymic`` view (`Sidorov Ivan
1259 Petrovich`); a given-first order would read the list's names
1260 without a patronymic family-last (`Aliyev Farrukh`). The names that
1261 write the patronymic in the middle get no given-first order, and
1262 the note says how many (decisions/group-suggestion, 2026-11-15
1263 #1356)."""
1264 note = (f"the base's family-first order is kept: {last} of the "
1265 f"{last + middle} names carrying the patronymic write it "
1266 f"last, as a list written family first does, and the rule "
1267 f"reorders none of them")
1268 if middle:
1269 # true whatever else the patch turns on: capitals_as_family,
1270 # suggested beside it, may read these names all the same
1271 verb, gets = ("writes", "gets") if middle == 1 else ("write", "get")
1272 note += (f"; the {middle} that {verb} it in the middle {gets} "
1273 f"no given-first order from this suggestion")
1274 return note
1277def _keeps_family_first(
1278 policy: Policy, order_end: Vote | None,
1279 with_words: list[tuple[str, dict[Signal, Vote], bool, list[str]]]
1280 ) -> tuple[int, int] | None:
1281 """Whether a decided East Slavic rule would keep this base's order,
1282 and if so how many of its voters write the patronymic last and how
1283 many in the middle; None where the rule decides the order as
1284 given-first, as it does on every other base.
1286 The order is kept only under ``FAMILY_FIRST``, only where the names'
1287 own votes do not decide a given-first order, and only where MORE of
1288 the names casting the East Slavic vote write the patronymic last
1289 (family, given, patronymic: rules/O1's family-first shape) than in
1290 the middle (given, patronymic, family); a tie is not kept. A name
1291 with the ending on both its middle and its last word counts as
1292 middle, as rules/O1 reads it. ``FAMILY_FIRST_GIVEN_LAST`` is never
1293 kept: that order takes the patronymic of such a list for the given
1294 name; the names' position votes give it ``FAMILY_FIRST``
1295 (`_decide_order`), and where they decide no order the given-first
1296 order with the rule reads it. The names are counted by their
1297 ``PATRONYMIC_POSITION`` votes, cast beside every East Slavic one."""
1298 if policy.name_order != FAMILY_FIRST or order_end == GIVEN_FIRST:
1299 return None
1300 ends = Counter(votes.get(Signal.PATRONYMIC_POSITION)
1301 for _, votes, _, _ in with_words)
1302 last, middle = ends[FAMILY_FIRST], ends[GIVEN_FIRST]
1303 return (last, middle) if last > middle else None
1306def _comma_note(left_out: int) -> str:
1307 if not left_out:
1308 return ""
1309 noun = "name with a comma was" if left_out == 1 else "names with a comma were"
1310 return (f"{left_out} {noun} left out: a comma states its own order, "
1311 f"so only a comma followed by post-nominals alone is read past")
1314def _floor_note(tally: _Tally, rule_decides: bool) -> str:
1315 """The note on votes _MIN_ORDER_GROUP_SHARE held back: where they
1316 alone leave the order undecided, and where a decided East Slavic
1317 rule sets the given-first order they voted against. None where the
1318 rule sets the order they voted for, which they did not decide."""
1319 end = tally.held_back()
1320 if end is None or (rule_decides and end == GIVEN_FIRST):
1321 return ""
1322 counted = tally.names - tally.left_out
1323 whose = (f"of the group's {counted} names" if not tally.left_out else
1324 f"of the {counted} names no comma left out")
1325 floor = (f"an order is decided where the names voting for one end are "
1326 f"at least {_MIN_ORDER_GROUP_SHARE:.0%} of those names")
1327 if rule_decides:
1328 return (f"{tally.by_name[end]} {whose} vote {_label(end)}, too few "
1329 f"to decide that order against the rule: {floor}")
1330 return (f"{tally.by_name[end]} {whose} vote {_label(end)}, too few to "
1331 f"decide the order: {floor}")
1334def _decide_order(tally: _Tally, base_order: tuple[Role, Role, Role],
1335 rule_needs_given_first: bool, comma_left_out: int,
1336 trailing_note: str = ""
1337 ) -> tuple[SettingEvidence, dict[str, object]]:
1338 """Decide ``name_order`` in either direction. A family-first answer
1339 keeps the base's family-first spelling where the base has one,
1340 unless an East Slavic rule is decided (below). A
1341 decided East Slavic rule decides the order as given-first, since
1342 the rule reorders each name and reorders none under a family-first
1343 order, unless the names' own votes decide family-first: a decided
1344 order is never overridden, and the rule then reorders no name. There
1345 a ``FAMILY_FIRST_GIVEN_LAST`` base gets ``FAMILY_FIRST``, whose
1346 reading the rule leaves as written (`Popov Ivan Ivanovich`, given
1347 `Ivan`); its own spelling would read the patronymic as the given name
1348 (decisions/group-suggestion, 2026-11-19 #1364). A
1349 rule that keeps a ``FAMILY_FIRST`` base's order
1350 (`_keeps_family_first`) is not passed here: the order is then the
1351 votes' or the base's."""
1352 end = tally.winner()
1353 notes = [_comma_note(comma_left_out),
1354 _floor_note(tally, rule_needs_given_first and end is None),
1355 trailing_note]
1356 if rule_needs_given_first and end != FAMILY_FIRST:
1357 end = GIVEN_FIRST
1358 notes.insert(0, "the East Slavic rule reorders each name; it needs "
1359 "a given-first order")
1360 elif rule_needs_given_first:
1361 notes.insert(0, "the East Slavic rule is decided too, but the names' "
1362 "order votes decide a family-first order, under "
1363 "which the rule reorders no name")
1364 note = "; ".join(n for n in notes if n)
1365 if end is None:
1366 return (tally.evidence(_NAME_ORDER, base_order, False,
1367 lambda v: v == _end(base_order), note), {})
1368 # the order tally holds orders alone; a decided East Slavic rule
1369 # takes the end's own spelling, the base's spelling of it otherwise
1370 order = (cast("tuple[Role, Role, Role]", end)
1371 if rule_needs_given_first or _end(base_order) != end
1372 else base_order)
1373 fields: dict[str, object] = (
1374 {} if order == base_order else {_NAME_ORDER: order})
1375 return (tally.evidence(_NAME_ORDER, order, True,
1376 lambda v: v == end, note), fields)
1379def _texts(names: Iterable[str]) -> Iterator[str]:
1380 """The names, checked as they are consumed: one pass, so a
1381 generator is read once."""
1382 example = 'parser.suggest(["Smith Mary", "Kim Minjun"])'
1383 if isinstance(names, str):
1384 raise TypeError(
1385 f"suggest() takes an iterable of names, not a bare string: "
1386 f"{names!r}. Wrap one name in a list: "
1387 f"parser.suggest([{names!r}])")
1388 if isinstance(names, (bytes, bytearray, memoryview)):
1389 raise TypeError(
1390 f"suggest() takes an iterable of str, not "
1391 f"{type(names).__name__} -- decode first, e.g. "
1392 f"raw.decode('utf-8')")
1393 if isinstance(names, Mapping):
1394 raise TypeError(
1395 f"suggest() takes an iterable of names, not a mapping "
1396 f"({type(names).__name__}). A mapping yields only its keys; "
1397 f"pass the names themselves, e.g. list(mapping) or "
1398 f"list(mapping.values()): {example}")
1399 try:
1400 iterator = iter(names)
1401 except TypeError:
1402 raise TypeError(
1403 f"suggest() takes an iterable of names, got {names!r}: "
1404 f"{example}") from None
1405 for index, text in enumerate(iterator):
1406 if not isinstance(text, str):
1407 raise TypeError(
1408 f"suggest() takes an iterable of str; item {index} is "
1409 f"{text!r} ({type(text).__name__}). Pass each name as a "
1410 f"string: {example}")
1411 yield text
1414def _quiet(parser: Parser, policy: Policy) -> Parser:
1415 """``parser`` reading under ``policy``, its construction warnings
1416 silenced: they read only ``segment_scripts``, the lexicon and the
1417 segmenter, which these policies never change from the base's, so
1418 they are the base's own, which reached its caller when it was
1419 built."""
1420 with warnings.catch_warnings():
1421 warnings.simplefilter("ignore")
1422 return dataclasses.replace(parser, policy=policy)
1425def _letter_readers(parser: Parser) -> tuple[Parser, Parser]:
1426 """The base with the switch on and off, every other setting the
1427 base's own save the fold of every middle into the family (rules/O3),
1428 which takes the letters there too and so would hide the run the
1429 switch reads. Asked only of a base reading names given first, where
1430 the rule acts."""
1431 policy = dataclasses.replace(parser.policy, middle_as_family=False)
1432 return (_quiet(parser, dataclasses.replace(policy, initials_as_family=True)),
1433 _quiet(parser, dataclasses.replace(policy, initials_as_family=False)))
1436def _decide_letters(runs: list[str | None], base_value: bool,
1437 family_first: bool
1438 ) -> tuple[SettingEvidence, dict[str, object]]:
1439 """Decide ``initials_as_family``: true where at least _MIN_RUN_NAMES
1440 names end in one run of letters and it is at least _MIN_RUN_SHARE of
1441 the names ending in any run. A group never decides it false: no
1442 name is evidence that letters are NOT a family. Nor does it decide
1443 anything under a base reading names family first (`family_first`),
1444 where rules/O8 stands down, so the switch would change no name and
1445 no name was read for a run."""
1446 counts = Counter(run for run in runs if run)
1447 carrying = sum(counts.values())
1448 if family_first:
1449 return (SettingEvidence(
1450 _INITIALS_AS_FAMILY, base_value, False, 0, 0, 0, len(runs), (),
1451 "not read: the base reads names family first, where letters "
1452 "ending a name are never taken as its family"), {})
1453 if not counts:
1454 return (SettingEvidence(_INITIALS_AS_FAMILY, base_value, False,
1455 0, 0, 0, len(runs), ()), {})
1456 run, top = counts.most_common(1)[0]
1457 decided = top >= _MIN_RUN_NAMES and top >= _MIN_RUN_SHARE * carrying
1458 value = True if decided else base_value
1459 # a name ending in a run is evidence FOR the switch, whatever the
1460 # group decided; the others carry none
1461 votes_for, votes_against = (carrying, 0) if value else (0, carrying)
1462 if top >= _MIN_RUN_NAMES:
1463 note = (f"{top} of the {carrying} names ending in a run of "
1464 f"letters end in {' '.join(run.upper())}")
1465 else:
1466 verb = "ends" if carrying == 1 else "end"
1467 note = (f"{carrying} of {len(runs)} names {verb} in a run of "
1468 f"letters, none repeated")
1469 fields: dict[str, object] = (
1470 {_INITIALS_AS_FAMILY: True} if decided and not base_value else {})
1471 return (SettingEvidence(_INITIALS_AS_FAMILY, value, decided, votes_for,
1472 votes_against, 0, len(runs) - carrying, (),
1473 note), fields)
1476def _capitals_reader(parser: Parser) -> Parser:
1477 """The base with rules/O9's switch on, every other setting the
1478 base's own. Never asked of a base reading an unlisted capitals word
1479 as a credential everywhere, beside which the switch cannot be set."""
1480 return _quiet(parser, dataclasses.replace(parser.policy,
1481 capitals_as_family=True))
1484def _capitals_family(text: str, words: list[str], base: Parser,
1485 reader: Callable[[], Parser]) -> bool | None:
1486 """One name's evidence on ``capitals_as_family``.
1488 True where rules/O9, asked of the parse itself with the switch on,
1489 reads as the family a word of at least _MIN_CAPITALS_LETTERS letters
1490 that the lexicon lists as no credential or numeral, and that the
1491 base, parsing the name itself, does not read as a title. False
1492 where the switch would move the family onto any word the base reads
1493 as a title (`MISS Ann Berg`, `DR DUPONT Jean`), and where the words the signals read (`words`) are two or
1494 more, hold an uppercase and a lowercase letter and none is in
1495 capitals: a title or a credential they are read past leaves such a
1496 name (`DR Ann Berg`, `Prof. Ann Berg`, `John Smith FRCS`). None
1497 otherwise: a name in one case, a run of two or three capitals (`Zhi
1498 LI`), a credential the name is not read past (`Mary Jones MBA`, a
1499 name too), a family comma, a name of one word.
1501 A word is a title by the base's own reading of the name, so a
1502 surname the vocabulary also lists as a title counts as the family
1503 the base reads it as (`Mary BISHOP`); the base parse is asked only
1504 where a word of the family the switch reads is a listed title. A
1505 word in capitals ending in a full stop is no capitals word to the
1506 rule, so a name holding one carries none (`Ann Berg DUPONT.`). Only a name
1507 holding a word in capitals is parsed, its words cut at commas and
1508 read past quotes and brackets as `_name_words` reads them. The loops
1509 are plain and their per-character tests C-level, so a name with no
1510 word holding two capitals costs this one call: the group suggester
1511 parses no name of a list with none."""
1512 # a capitals word holds two capitals at least
1513 if any(sum(map(str.isupper, word)) >= 2
1514 and is_capitals_word(word.strip(_EDGES).rstrip("."))
1515 for word in _COMMAS.split(text)):
1516 lexicon = base.lexicon
1517 sets = lexicon._sets
1518 family = []
1519 counted = False
1520 listed = False
1521 for token in reader().parse(text).tokens:
1522 if token.role is not Role.FAMILY:
1523 continue
1524 family.append(token)
1525 # rules/O9's family: a family word read by its shape is a
1526 # word of the run in capitals (a particle the run took reads
1527 # by vocabulary, a family comma's by position)
1528 counted = counted or (
1529 token.reading is not None
1530 and token.reading.source is ReadingSource.SHAPE
1531 and sum(map(str.isalpha, token.text))
1532 >= _MIN_CAPITALS_LETTERS
1533 and not _listed_suffix(token.text, lexicon))
1534 # a title of any kind the vocabulary lists (a modifier and a
1535 # style compile into the titles, a word that is also a given
1536 # name into the ambiguous titles instead): only such a word
1537 # may be the base's title, so only it costs the base parse
1538 word = _normalize(token.text)
1539 listed = listed or (
1540 word in sets.titles or word in sets.titles_ambiguous)
1541 if counted:
1542 if listed:
1543 titles = {token.span for token in base.parse(text).tokens
1544 if token.role is Role.TITLE}
1545 # the switch would move the family onto a word the base
1546 # reads as a title (`DR DUPONT Jean`, `MISS Ann Berg`)
1547 return not any(token.span in titles for token in family)
1548 return True
1549 for word in words:
1550 # a word in capitals the rule reads as no family, a final
1551 # full stop read past (`Ann Berg DUPONT.`)
1552 if is_capitals_word(word.rstrip(".")):
1553 return None
1554 if len(words) < 2:
1555 return None
1556 if not (_has_lower(words) and any(c.isupper() for w in words for c in w)):
1557 return None
1558 return False
1561def _decide_capitals(marks: list[bool | None], base: Policy
1562 ) -> tuple[SettingEvidence, dict[str, object]]:
1563 """Decide ``capitals_as_family`` (rules/O9): true where at least
1564 _MIN_VOTES names write the family in capitals and more than
1565 _MIN_SHARE of the names with evidence either way do. A group never
1566 decides it false: a name with no capitals is no evidence that a
1567 list does not write them, the rule reading only a name that holds
1568 some. Nor does anything decide it under a base reading an unlisted
1569 capitals word as a credential everywhere, beside which the switch
1570 cannot be set."""
1571 base_value = base.capitals_as_family
1572 if base.unlisted_caps_suffixes is CapsSuffixes.EVERYWHERE:
1573 return (SettingEvidence(
1574 _CAPITALS_AS_FAMILY, base_value, False, 0, 0, 0, len(marks), (),
1575 "not read: the base reads an unlisted word in capitals as a "
1576 "credential everywhere (unlisted_caps_suffixes=EVERYWHERE), "
1577 "beside which capitals_as_family cannot be set"), {})
1578 written = marks.count(True)
1579 plain = marks.count(False)
1580 if not written and not plain:
1581 return (SettingEvidence(_CAPITALS_AS_FAMILY, base_value, False,
1582 0, 0, 0, len(marks), ()), {})
1583 decided = (written >= _MIN_VOTES
1584 and written > _MIN_SHARE * (written + plain))
1585 value = True if decided else base_value
1586 votes_for, votes_against = (written, plain) if value else (plain, written)
1587 # said where a name writes it: a list with none is the common case,
1588 # and its counts say what it showed
1589 noun = "name" if written + plain == 1 else "names"
1590 verb = "writes" if written == 1 else "write"
1591 note = (f"{written} of the {written + plain} {noun} with evidence "
1592 f"{verb} the family in capitals of {_MIN_CAPITALS_LETTERS} "
1593 f"letters or more, {plain} in mixed case with no capitals"
1594 if written else "")
1595 fields: dict[str, object] = (
1596 {_CAPITALS_AS_FAMILY: True} if decided and not base_value else {})
1597 return (SettingEvidence(_CAPITALS_AS_FAMILY, value, decided, votes_for,
1598 votes_against, 0,
1599 len(marks) - written - plain, (), note), fields)
1602def _counts_as_initialed(votes: Mapping[Signal, Vote]) -> bool:
1603 """Whether a name counts toward the trailing-initial share: its
1604 trailing initial is its only order evidence or agrees with the rest
1605 of it, so a name whose listed given name contradicts it (`Anna R S`)
1606 does not count."""
1607 return (Signal.TRAILING_INITIAL in votes
1608 and len(_order_ends(votes.items())) == 1)
1611def _trailing_initials_vote(
1612 with_words: list[tuple[str, dict[Signal, Vote], bool, list[str]]]
1613 ) -> tuple[bool, str]:
1614 """Whether the group's trailing-initial votes are cast, and the note
1615 saying so where they are not. One rule at every count: where any
1616 name casts one, they are cast only where at least _MIN_TRAILING_NAMES
1617 names, and _MIN_TRAILING_SHARE of the group's names, count as
1618 initialed (_counts_as_initialed). The group is the names that hold
1619 a word with a letter or a digit once their titles and post-nominals
1620 are read past, as _name_words reads them: a blank, a mark, a
1621 zero-width character alone (`\u200b`), a name of nothing but titles
1622 and a name a comma left out (which _name_words gives no word) are
1623 no names of the group."""
1624 if not any(Signal.TRAILING_INITIAL in votes
1625 for _, votes, _, _ in with_words):
1626 return True, ""
1627 group = initialed = 0
1628 for _, votes, _, words in with_words:
1629 if not any(c.isalnum() for word in words for c in word):
1630 continue
1631 group += 1
1632 initialed += _counts_as_initialed(votes)
1633 if (initialed >= _MIN_TRAILING_NAMES
1634 and initialed >= _MIN_TRAILING_SHARE * group):
1635 return True, ""
1636 verb = "ends" if initialed == 1 else "end"
1637 return False, (
1638 f"{initialed} of the group's {group} names {verb} in initials no "
1639 f"other signal contradicts, too few for the trailing-initial "
1640 f"signal to vote: it votes where at least {_MIN_TRAILING_NAMES} "
1641 f"names and {_MIN_TRAILING_SHARE:.0%} of the group do")
1644def _two_family_note(base: Policy, rest: Policy) -> str:
1645 """Why ``two_family_names`` is not weighed under ``rest``, the policy
1646 the other settings suggest on ``base``, or "" where it is: it is
1647 weighed only where the base's switch is off and the rest reads
1648 given-first with the East Slavic rule off (decisions/group-suggestion,
1649 2026-11-19 #1452)."""
1650 if base.two_family_names:
1651 return "not read: the base reads two family names already"
1652 if PatronymicRule.EAST_SLAVIC in rest.patronymic_rules:
1653 return ("not read: the East Slavic rule is on, and the switch "
1654 "would read a patronymic as a first surname")
1655 if rest.name_order != GIVEN_FIRST:
1656 return ("not read: the order is family-first, and two family "
1657 "names are weighed under a given-first order alone")
1658 return ""
1661def _two_family_votes(
1662 with_words: list[tuple[str, dict[Signal, Vote], bool, list[str]]],
1663 reader: Parser) -> tuple[list[dict[Signal, Vote]], int, int]:
1664 """Each name's votes on ``two_family_names``, read where rules/O6
1665 reads it: the parse itself is asked, under ``reader`` (the parser the
1666 rest of the suggestion gives) with the switch off and on, and a name
1667 the switch moves is one whose family it changes, every name of the
1668 group with a middle name asked. Where such a name has no comma and
1669 three name words or more, the last word the switch takes into its family votes
1670 (`Signal.FIRST_SURNAME`): for the switch where it is a common
1671 surname of the ORCID table, against it where it is a patronymic or
1672 its marker, a father's name the switch would read as a first
1673 surname, and not at all where it is a common given name, the second
1674 given name the switch would take (`COMMON_GIVEN_NAMES`). Returns the
1675 votes, the names the switch moves and the names whose taken word is
1676 a listed given name."""
1677 on = _quiet(reader, dataclasses.replace(reader.policy,
1678 two_family_names=True))
1679 out: list[dict[Signal, Vote]] = []
1680 moved = vetoed = 0
1681 for text, _, comma, words in with_words:
1682 votes: dict[Signal, Vote] = {}
1683 out.append(votes)
1684 # every name the switch changes counts in the share, a comma name
1685 # and one whose words the signals do not split included; only a
1686 # name they read casts a vote
1687 off = reader.parse(text)
1688 if not off.middle:
1689 # the switch takes the word before the family from the
1690 # middle, so a name with none is one it leaves as it is
1691 continue
1692 off_family, on_family = off.family, on.parse(text).family
1693 if on_family == off_family:
1694 continue
1695 moved += 1
1696 if (comma or len(words) < 3
1697 or not on_family.endswith(" " + off_family)):
1698 continue
1699 word = on_family.removesuffix(off_family).split()[-1]
1700 bare = word.rstrip(".") or word
1701 if is_patronymic_marker(bare) or has_patronymic_ending(bare):
1702 # a father's name or its marker, never a first surname
1703 votes[Signal.FIRST_SURNAME] = False
1704 elif _listed(word, COMMON_GIVEN_NAMES):
1705 vetoed += 1
1706 elif _listed(word, COMMON_SURNAMES):
1707 votes[Signal.FIRST_SURNAME] = True
1708 return out, moved, vetoed
1711def _decide_two_family_names(
1712 votes: list[dict[Signal, Vote]], moved: int, vetoed: int,
1713 base_value: bool, note: str
1714 ) -> tuple[SettingEvidence, dict[str, object]]:
1715 """Decide ``two_family_names`` (rules/O6): true where at least
1716 _MIN_TWO_FAMILY_VOTES names vote for it and they are more than
1717 _MIN_TWO_FAMILY_SHARE of the names the switch would move, and more
1718 than the names it would read a father's name in as a first surname.
1719 A group never decides it false. ``note`` says why it was not
1720 weighed, and is empty where it was, a group no name of which the
1721 switch moves included."""
1722 # a name casts one vote at most, so the tally counts names
1723 tally = _Tally()
1724 for v in votes:
1725 tally.add(list(v.items()))
1726 if note or not moved:
1727 return (tally.evidence(_TWO_FAMILY_NAMES, base_value, False,
1728 lambda v: v == base_value, note), {})
1729 voters, fathers = tally.by_name[True], tally.by_name[False]
1730 decided = (voters >= _MIN_TWO_FAMILY_VOTES
1731 and voters > _MIN_TWO_FAMILY_SHARE * moved
1732 and voters > fathers)
1733 value = True if decided else base_value
1734 noun = "name" if moved == 1 else "names"
1735 text = (f"{voters} of the {moved} {noun} two_family_names would "
1736 f"change carry a common surname where it would take a first "
1737 f"surname")
1738 if vetoed:
1739 text += (f"; {vetoed} of them a common given name there, which "
1740 f"casts no vote")
1741 if fathers:
1742 text += (f"; {fathers} a father's name there, which it would read "
1743 f"as a first surname")
1744 fields: dict[str, object] = (
1745 {_TWO_FAMILY_NAMES: True} if decided and not base_value else {})
1746 # counted for and against the value kept, as the other switches are
1747 return (tally.evidence(_TWO_FAMILY_NAMES, value, decided,
1748 lambda v: v == value, text), fields)
1751def suggest(parser: Parser, names: Iterable[str]) -> Suggestion:
1752 """The settings a group of names suggests, with ``parser`` as the
1753 base: see :meth:`Parser.suggest`."""
1754 tallies = {_NAME_ORDER: _Tally(), _PATRONYMIC_RULES: _Tally()}
1755 any_voters = comma_left_out = 0
1756 texts = list(_texts(names))
1757 family_first = parser.policy.name_order != GIVEN_FIRST
1758 if family_first:
1759 runs: list[str | None] = [None] * len(texts)
1760 else:
1761 readers = _letter_readers(parser)
1762 runs = [_letter_run(text, readers) for text in texts]
1763 letters, letter_fields = _decide_letters(
1764 runs, parser.policy.initials_as_family, family_first)
1765 letters_are_family = letters.decided and letters.value is True
1766 with_words = [(text, *_read(text, parser.lexicon)) for text in texts]
1767 capitals_parser: list[Parser] = []
1769 def capitals_reader() -> Parser:
1770 # built once, and only for a group holding a word in capitals
1771 if not capitals_parser:
1772 capitals_parser.append(_capitals_reader(parser))
1773 return capitals_parser[0]
1775 if parser.policy.unlisted_caps_suffixes is CapsSuffixes.EVERYWHERE:
1776 # the switch cannot be set beside it: no name is read for it
1777 marks: list[bool | None] = [None] * len(texts)
1778 else:
1779 marks = [_capitals_family(text, words, parser, capitals_reader)
1780 for text, _, _, words in with_words]
1781 capitals, capitals_fields = _decide_capitals(marks, parser.policy)
1782 if letters_are_family:
1783 # the group's letters are its family (rules/O8), so a name
1784 # ending in letters is no evidence of a family-first order
1785 trailing_votes, trailing_note = False, (
1786 "the trailing-initial signal casts no vote: the group's "
1787 "letters are its family (initials_as_family)")
1788 else:
1789 trailing_votes, trailing_note = _trailing_initials_vote(with_words)
1790 set_aside = 0
1791 for (text, votes, comma, _), mark in zip(with_words, marks):
1792 # counted before a set-aside vote leaves it: a name ending in
1793 # initials carries evidence all the same, and leaving it out of
1794 # the patronymic share's denominator lets one rule win a group
1795 # of family-first names written with a patronymic initial
1796 # (`Popov Ivan I.`, PatentsView's Russian inventors)
1797 any_voters += bool(votes)
1798 if not trailing_votes and Signal.TRAILING_INITIAL in votes:
1799 del votes[Signal.TRAILING_INITIAL]
1800 set_aside += not votes
1801 comma_left_out += comma
1802 per_setting: dict[str, list[tuple[Signal, Vote]]] = {
1803 setting: [] for setting in tallies}
1804 for signal, vote in votes.items():
1805 per_setting[_SETTING_OF[signal]].append((signal, vote))
1806 for setting, tally in tallies.items():
1807 tally.add(per_setting[setting], comma)
1808 policy = parser.policy
1809 # a FAMILY_FIRST base keeps its order where the group's East Slavic
1810 # patronymics are mostly written last (#1356)
1811 patronymic, patronymic_fields, settled = _decide_patronymic(
1812 tallies[_PATRONYMIC_RULES], policy.patronymic_rules, any_voters,
1813 _keeps_family_first(policy, tallies[_NAME_ORDER].winner(),
1814 with_words))
1815 if set_aside and any(Signal.PATRONYMIC in votes
1816 for _, votes, _, _ in with_words):
1817 # the evidence says what its share was taken of: the names a
1818 # set-aside vote left with none still count among those casting
1819 # one, and show as no evidence
1820 counted = ("1 name whose only vote was a set-aside trailing "
1821 "initial counts" if set_aside == 1 else
1822 f"{set_aside} names whose only vote was a set-aside "
1823 f"trailing initial count")
1824 patronymic = dataclasses.replace(patronymic, note="; ".join(
1825 n for n in (patronymic.note,
1826 f"{counted} among the names casting a vote, the "
1827 f"share's denominator") if n))
1828 order, order_fields = _decide_order(
1829 tallies[_NAME_ORDER], policy.name_order, settled, comma_left_out,
1830 trailing_note)
1831 fields = {**order_fields, **patronymic_fields, **letter_fields,
1832 **capitals_fields}
1833 # the policy the other settings suggest, which the switch's votes
1834 # are read under
1835 rest = apply_patch(policy, PolicyPatch(**fields)) # type: ignore[arg-type]
1836 two_note = _two_family_note(policy, rest)
1837 if two_note:
1838 family_votes: list[dict[Signal, Vote]] = [{} for _ in texts]
1839 moved = vetoed = 0
1840 else:
1841 family_votes, moved, vetoed = _two_family_votes(
1842 with_words, _quiet(parser, rest))
1843 two_family, two_fields = _decide_two_family_names(
1844 family_votes, moved, vetoed, policy.two_family_names, two_note)
1845 fields.update(two_fields)
1846 evidence = [NameEvidence(text, {**votes, **extra},
1847 family_in_capitals=mark)
1848 for (text, votes, _, _), mark, extra
1849 in zip(with_words, marks, family_votes)]
1850 patch = PolicyPatch(**fields) # type: ignore[arg-type]
1851 return Suggestion(parser, patch,
1852 (order, patronymic, letters, capitals, two_family),
1853 tuple(evidence))