Coverage for src/courtpy/references/judges/_names.py: 100%
57 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
1"""How the names of judges are compared.
3Contents:
4 clean_name: returns a name the way that names are compared.
5 edit_distance: returns how many edits turn one name into another.
6 name_forms: returns the ways that an opinion may write a judge's name,
7 grouped by how much of the name they give.
8 repaired_names: returns a name with the damage that some opinions' text
9 does undone.
10 shorter_names: returns shorter ways of writing a name that an opinion
11 gives, to try when the name itself fits no judge.
12 _LEVELS: the groups of the forms of a judge's name, from the most of
13 the name to the least.
14 _NAME_PUNCTUATION: pattern for the punctuation that is removed from
15 names before they are compared.
16 _SUFFIXES: the suffixes of names, as `clean_name` writes them.
18"""
20from __future__ import annotations
22import re
23import unicodedata
25# The groups of the forms of a judge's name (see `name_forms`), in the order
26# that `Roster.match` tries them: from the most of the name to the least.
27_LEVELS: tuple[str, ...] = ('full', 'initials', 'last')
28# The curly apostrophe (U+2019) is added with `chr` so that the source file
29# has only plain characters.
30_NAME_PUNCTUATION: re.Pattern[str] = re.compile(
31 r"[.,\[\]'" + chr(0x2019) + ']')
32_SUFFIXES: frozenset[str] = frozenset({'JR', 'SR', 'II', 'III', 'IV', 'V'})
35""" Public Functions """
38def clean_name(name: str) -> str:
39 """Returns a name the way that names are compared.
41 Args:
42 name: a name or a part of one, such as "R[obert] Lanier" or
43 "O'Scannlain".
45 Returns:
46 The name in capital letters, without accents, periods, commas,
47 brackets, or apostrophes, and with single spaces (as the `names`
48 rules of a rulebook write the names they find). Accents are left
49 out because sources differ in whether they write them (so a name
50 with an accented letter matches the same name without it).
52 """
53 letters = ''.join(
54 character for character in unicodedata.normalize('NFKD', name)
55 if not unicodedata.combining(character))
56 return ' '.join(_NAME_PUNCTUATION.sub('', letters.upper()).split())
59def name_forms(
60 first: str,
61 middle: str,
62 last: str,
63 suffix: str = '') -> dict[str, list[str]]:
64 """Returns the ways that an opinion may write a judge's name.
66 Opinions name judges by their last names, with initials or first names
67 only when two judges of a court share one. The forms are grouped by how
68 much of the name they give, which is the order in which `Roster.match`
69 tries them. For Sandra Lea Lynch, they are:
71 | Level | Forms |
72 | --- | --- |
73 | `full` | "SANDRA LEA LYNCH", "SANDRA L LYNCH", and "SANDRA LYNCH". |
74 | `initials` | "S LEA LYNCH", "S L LYNCH", "SL LYNCH" (as "S.L." is written once its periods are removed), "S LYNCH", and "LEA LYNCH" (for a judge who goes by a middle name). |
75 | `last` | "LYNCH". |
77 With a suffix, each form is also written with it after the last name
78 (such as "M D SMITH JR" and "SMITH JR"). A form is in only the first
79 level that has it.
81 Args:
82 first: the judge's first name.
83 middle: the judge's middle name or names, which may be blank.
84 last: the judge's last name.
85 suffix: the suffix of the judge's name, such as "Jr." or "III".
86 Defaults to an empty `str`.
88 Returns:
89 The forms of each level ("full", "initials", and "last"), as
90 `clean_name` writes them, without repeats. There are none if
91 `last` is blank.
93 """
94 first, middle, last, suffix = (
95 clean_name(part) for part in (first, middle, last, suffix))
96 levels: dict[str, list[str]] = {level: [] for level in _LEVELS}
97 if not last:
98 return levels
99 written = {
100 'full': [
101 f'{first} {middle} {last}',
102 f'{first} {middle[:1]} {last}',
103 f'{first} {last}'],
104 'initials': [
105 f'{first[:1]} {middle} {last}',
106 f'{first[:1]} {middle[:1]} {last}',
107 f'{first[:1]}{middle[:1]} {last}',
108 f'{first[:1]} {last}',
109 # An initial alone is not a name that a judge goes by.
110 f'{middle} {last}' if len(middle) > 1 else ''],
111 'last': [last]}
112 # Without a first name, a full name or initials would be the last name
113 # alone, which belongs to the last level.
114 alone = {last, f'{last} {suffix}'.strip()}
115 seen: set[str] = set()
116 for level, forms in written.items():
117 for form in forms:
118 for written_form in (form, f'{form} {suffix}' if suffix else ''):
119 named = ' '.join(written_form.split())
120 if not named or named in seen or (
121 level != 'last' and named in alone):
122 continue
123 seen.add(named)
124 levels[level].append(named)
125 return levels
128def edit_distance(first: str, second: str) -> int:
129 """Returns how many edits turn one name into another.
131 An edit adds, removes, or changes a letter, or swaps two letters next to
132 each other (the optimal string alignment distance), which are the errors
133 that scanning and typing make in names ("KRAVTTCH" for "KRAVITCH", or
134 "TJOFALT" for "TJOFLAT").
136 Args:
137 first: a name.
138 second: another name.
140 Returns:
141 The number of edits.
143 """
144 rows = len(first) + 1
145 columns = len(second) + 1
146 table = [[0] * columns for _ in range(rows)]
147 for row in range(rows):
148 table[row][0] = row
149 for column in range(columns):
150 table[0][column] = column
151 for row in range(1, rows):
152 for column in range(1, columns):
153 changed = int(first[row - 1] != second[column - 1])
154 table[row][column] = min(
155 table[row - 1][column] + 1,
156 table[row][column - 1] + 1,
157 table[row - 1][column - 1] + changed)
158 if (
159 row > 1 and column > 1
160 and first[row - 1] == second[column - 2]
161 and first[row - 2] == second[column - 1]):
162 table[row][column] = min(
163 table[row][column], table[row - 2][column - 2] + 1)
164 return table[-1][-1]
167def repaired_names(name: str) -> list[str]:
168 """Returns a name with the damage that some opinions' text does undone.
170 Some opinions are printed in small capitals, which their text writes
171 with a space after each large first letter ("P OSNER" for "POSNER", or
172 "V AN B OKKELEN"), break a hyphenated name at its hyphen
173 ("JACKSON- AKIWUMI"), or run a word of the panel into a name
174 ("BEFORENIEMEYER"). `Roster.match` tries these forms of a name that fits
175 no judge as it is written.
177 Args:
178 name: the name, as `clean_name` returns it.
180 Returns:
181 The repaired forms, without repeats or `name` itself.
183 """
184 forms = [
185 re.sub(r'\b([A-Z]) (?=[A-Z]{2,})', r'\1', name),
186 re.sub(r'\s*-\s*', '-', name).strip('-'),
187 name.replace(' ', '-'),
188 re.sub(r'^(?:BEFORE|PRESENT)(?=[A-Z]{3,})', '', name)]
189 return [form for form in dict.fromkeys(forms) if form and form != name]
192def shorter_names(name: str) -> list[str]:
193 """Returns shorter ways of writing a name that an opinion gives.
195 An opinion may give more of a judge's name than the Federal Judicial
196 Center's files do (as "Susan P. Graber" for a judge whom the files name
197 "Susan Graber"), give middle initials that are not those of the files'
198 middle names (as "Sarah A. L. Merriam" for "Sarah Ann Leilani Merriam"),
199 or give a short first name (as "Ed Carnes" for "Edward Carnes"). Such a
200 name is none of the forms of the judge's name (see `name_forms`), but a
201 shorter way of writing it is: the first and last names, and then the
202 first initial and the last name. A suffix stays with the last name. The
203 last name alone is never one of them, since a name that gives more
204 should not be matched by less than its first name or initial.
206 Args:
207 name: the name, as `clean_name` returns it.
209 Returns:
210 The first and last names (if the name has a middle name or initial)
211 and the first initial and last name (if the first name is longer
212 than an initial), as `clean_name` writes them, without repeats
213 or `name` itself. There are none for a name of one word.
215 """
216 parts = name.split()
217 tail = 2 if len(parts) > 1 and parts[-1] in _SUFFIXES else 1
218 given, last = parts[:-tail], ' '.join(parts[-tail:])
219 if not given:
220 return []
221 shorter = []
222 if len(given) > 1:
223 shorter.append(f'{given[0]} {last}')
224 if len(given[0]) > 1:
225 shorter.append(f'{given[0][:1]} {last}')
226 return [form for form in dict.fromkeys(shorter) if form != name]