Coverage for src/courtpy/references/judges/_roster.py: 99%

251 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""The roster of judges, which finds the judge that a name refers to. 

2 

3Contents: 

4 DownloadBiographies: downloads the Federal Judicial Center's files about 

5 judges and loads the roster that they make. 

6 LoadRoster: loads the table of a roster of judges. 

7 Roster: a table of judges that finds the judge a name refers to. 

8 build_roster: makes the table of a roster from the Federal Judicial 

9 Center's files with fjc-biographies. 

10 download: downloads the Federal Judicial Center's files about judges 

11 with fjc-biographies. 

12 _ALIASES: names that some judges signed opinions with, by their numbers. 

13 _APPELLATE: the kinds of courts whose judges are on panels of appeals. 

14 _CATEGORIES: the categories of the Federal Judicial Center's files that 

15 a roster is made from. 

16 _DISTRICT_COURT: the Federal Judicial Center's name for a district 

17 court. 

18 _FEWEST_TO_REPAIR: the fewest letters of a name that is matched with 

19 one edit. 

20 _IDENTIFIERS: columns of numbers that identify or date a judge's 

21 service, which are not attributes of the judge. 

22 _NEEDED: the columns that every roster needs. 

23 _OTHER_TEXT: pattern for the other columns of text in a roster. 

24 _PERMUTATIONS: the start of the names of the columns with each judge's 

25 full name written in different ways. 

26 _RELATIVE: attributes of a judge that depend on the year of a case. 

27 _ROSTER_FILE: the name of a saved roster's file. 

28 _TEXT: the columns of text in a roster. 

29 

30""" 

31 

32from __future__ import annotations 

33 

34import dataclasses 

35import pathlib 

36import re 

37from collections.abc import Iterable 

38from typing import Any 

39 

40import amos 

41import fjc_biographies 

42import pandas as pd 

43 

44from ...core import cases, options, utilities 

45from ...wrangler import loaders, rules 

46from ._names import ( 

47 _LEVELS, 

48 clean_name, 

49 edit_distance, 

50 name_forms, 

51 repaired_names, 

52 shorter_names, 

53) 

54 

55# Judge Johnson of the Fifth Circuit signed opinions as "Sam D. Johnson", 

56# Judge King of the Fifth Circuit sat as Carolyn Dineen Randall until 1988, 

57# Judge Richman of the Fifth Circuit sat as Priscilla Owen until 2019, and 

58# Judge Forrest of the Ninth Circuit sat as Danielle J. Hunsaker (the 

59# Federal Judicial Center's files give only the names that judges have now). 

60_ALIASES: dict[int, str] = { 

61 1382851: 'Sam D. Johnson', 

62 1386716: 'Carolyn Dineen Randall', 

63 1392271: 'Priscilla Owen', 

64 7328941: 'Danielle J. Hunsaker'} 

65_APPELLATE: frozenset[str] = frozenset({ 

66 'U.S. Court of Appeals', 'Supreme Court'}) 

67# The categories of the Federal Judicial Center's files that a roster is made 

68# from, which are the names of the parameters of `build_roster` that take 

69# them. 

70_CATEGORIES: tuple[str, ...] = ('service', 'demographics', 'career') 

71_DISTRICT_COURT: str = 'U.S. District Court' 

72# The fewest letters of a name that `Roster` matches with one edit, since a 

73# shorter name is too near too many others. 

74_FEWEST_TO_REPAIR: int = 5 

75_IDENTIFIERS: frozenset[str] = frozenset({ 

76 'nid', 'sequence', 'court_num', 'circuit_num', 'start_year', 'end_year', 

77 'senior_year', 'birth_year'}) 

78_NEEDED: tuple[str, ...] = ( 

79 'nid', 'judge', 'last_name', 'first_name', 'court_num', 'circuit_num', 

80 'start_year', 'end_year') 

81# The other columns of text that fjc-biographies puts in a roster: the career 

82# that the rules searched, the ways of writing each judge's name, and the 

83# dates of each appointment. A saved roster would read such a column that is 

84# blank in every row as numbers, which would make it an attribute. 

85_OTHER_TEXT: re.Pattern[str] = re.compile(r'career|name_.+|.+_date') 

86# The start of the names of the columns in which fjc-biographies writes each 

87# judge's full name in different ways. 

88_PERMUTATIONS: str = 'name_' 

89_RELATIVE: tuple[str, ...] = ('age', 'senior', 'designated', 'district_judge') 

90_ROSTER_FILE: str = 'roster.csv' 

91_TEXT: tuple[str, ...] = ( 

92 'judge', 'last_name', 'first_name', 'middle_name', 'suffix', 'aliases', 

93 'court', 'court_type', 'president') 

94 

95 

96@dataclasses.dataclass 

97class Roster: 

98 """A table of judges that finds the judge a name in an opinion refers to. 

99 

100 Each row of the table is a judge's service on one court, so a judge who 

101 was promoted from a district court to a court of appeals has two rows, 

102 with the president who made each appointment. Only judges who were 

103 serving in the year of the case (or had left their court no more than 

104 `grace` years before it) are considered. A name is matched by how much of 

105 a judge's name it gives, from the most to the least (see `name_forms`): 

106 

107 1. a full name: one of the ways that fjc-biographies writes the judge's 

108 name (the "name_..." columns, such as "Sandra Lea Lynch", "Sandra L. 

109 Lynch", "Sandra Lynch", and each with any suffix), or one of the 

110 judge's "aliases", 

111 2. or else initials and the last name ("S. Lynch", "S. L. Lynch", "S.L. 

112 Lynch", or "S. Lea Lynch"), or the middle and last names ("Lea Lynch", 

113 for a judge who goes by a middle name), 

114 3. or else the last name alone, which is how opinions usually name 

115 judges. 

116 

117 The first of them that fits any judge who was serving is used. A name 

118 that fits no judge at all is then tried in shorter forms, as a full name 

119 or initials (see `shorter_names`): an opinion's "Susan P. Graber" is 

120 "Susan Graber", and its "Ed Carnes" is "E. Carnes", but never the last 

121 name alone. Many 

122 judges share a name, especially a last name, so the judges whose names 

123 fit are then narrowed by the court of the case: 

124 

125 1. to a judge of the case's court, 

126 2. or else to a judge of a district court in the case's circuit, who may 

127 sit on its court of appeals by designation, 

128 3. or else to a judge of any other court, such as a court of appeals or 

129 district court of another circuit, who may sit by designation. 

130 

131 If more than one judge fits at the first step that any judge fits, the 

132 name is not matched, since there is no telling which judge was meant 

133 (`candidates` returns them all, so that other names on the case can 

134 tell them apart). A name that fits no judge at all is repaired, if it 

135 then fits exactly one judge: written without the damage that some 

136 opinions' text does to names ("P OSNER" for "POSNER"), or compared with 

137 the judges of the case's court for a scanning error ("KRAVTTCH" for 

138 "Kravitch"; see `_repaired`). 

139 Nor is a name on a case of a court that has no judges in the table (such 

140 as a bankruptcy appellate panel, whose judges are not in the Federal 

141 Judicial Center's files), since a judge of another court who shares the 

142 name would be a guess. 

143 

144 Args: 

145 data: the table. It needs the columns "nid" (a number that identifies 

146 each judge), "judge" (the judge's name, as it is reported), 

147 "last_name", "first_name", "court_num" and "circuit_num" (the 

148 numbers that the federal rules give the judge's court and its 

149 circuit), and "start_year" and "end_year" (of the judge's service 

150 on the court). "middle_name", "suffix", the "name_..." columns 

151 that fjc-biographies makes, "aliases" (other names that opinions 

152 use for the judge, as "First Middle Last", separated by 

153 semicolons), "senior_year", "birth_year", and "court_type" are 

154 used if they are there. 

155 grace: years after a judge's service on a court ended in which an 

156 opinion may still name the judge. Defaults to 

157 `options._JUDGE_GRACE` (as it is when the roster is made). 

158 

159 """ 

160 

161 data: pd.DataFrame 

162 grace: int = dataclasses.field( 

163 default_factory = lambda: options._JUDGE_GRACE) 

164 _described: dict[ 

165 tuple[int, int | None, int | None], dict[str, float | None]] = ( 

166 dataclasses.field( 

167 default_factory = dict, init = False, repr = False)) 

168 _forms: dict[str, dict[str, list[int]]] = dataclasses.field( 

169 default_factory = dict, init = False, repr = False) 

170 _found: dict[tuple[str, int | None, int | None], tuple[int, ...]] = ( 

171 dataclasses.field(default_factory = dict, init = False, repr = False)) 

172 _numbers: dict[str, list[int | None]] = dataclasses.field( 

173 default_factory = dict, init = False, repr = False) 

174 _seated: dict[tuple[int, int], list[int]] = dataclasses.field( 

175 default_factory = dict, init = False, repr = False) 

176 _text: dict[str, list[str]] = dataclasses.field( 

177 default_factory = dict, init = False, repr = False) 

178 _values: dict[str, list[float | None]] = dataclasses.field( 

179 default_factory = dict, init = False, repr = False) 

180 

181 """ Initialization Methods """ 

182 

183 def __post_init__(self) -> None: 

184 """Checks the table and indexes the names and numbers of its judges. 

185 

186 Raises: 

187 KeyError: if the table lacks a column that every roster needs. 

188 

189 """ 

190 cases.require_columns(self.data, _NEEDED, 'a roster of judges') 

191 self.data = cases.tidy(self.data.reset_index(drop = True)) 

192 for column in _TEXT: 

193 self._text[column] = ( 

194 self.data[column].fillna('').astype(str).tolist() 

195 if column in self.data.columns else [''] * len(self.data)) 

196 permutations = [ 

197 self.data[column].tolist() for column in self.data.columns 

198 if str(column).startswith(_PERMUTATIONS)] 

199 self._forms = {level: {} for level in _LEVELS} 

200 people = zip( 

201 self._text['first_name'], self._text['middle_name'], 

202 self._text['last_name'], self._text['suffix'], 

203 self._text['aliases'], strict = True) 

204 for row, (first, middle, last, suffix, aliases) in enumerate(people): 

205 levels = name_forms(first, middle, last, suffix) 

206 # The ways that fjc-biographies writes a name are full names. 

207 levels['full'].extend( 

208 clean_name(values[row]) for values in permutations 

209 if isinstance(values[row], str)) 

210 for alias in aliases.split(';'): 

211 parts = alias.split() 

212 if len(parts) > 1: 

213 found = name_forms( 

214 parts[0], ' '.join(parts[1:-1]), parts[-1]) 

215 for level, forms in found.items(): 

216 levels[level].extend(forms) 

217 # A form is indexed only at the first level that has it, so a 

218 # judge whose first name is an initial ("J. Smith") is matched by 

219 # it as a full name. 

220 seen: set[str] = set() 

221 for level in _LEVELS: 

222 for form in levels[level]: 

223 if form and form not in seen: 

224 seen.add(form) 

225 self._forms[level].setdefault(form, []).append(row) 

226 for column in sorted(_IDENTIFIERS): 

227 self._numbers[column] = ( 

228 [_whole(value) for value in self.data[column]] 

229 if column in self.data.columns else [None] * len(self.data)) 

230 for column in self.attributes: 

231 self._values[column] = [ 

232 None if pd.isna(value) else float(value) 

233 for value in self.data[column]] 

234 

235 """ Class Methods """ 

236 

237 @classmethod 

238 def create( 

239 cls, 

240 source: Roster | pd.DataFrame | pathlib.Path | str | None = None) -> ( 

241 Roster): 

242 """Returns a roster made from `source`. 

243 

244 Args: 

245 source: a roster, the table of one, or the path of a saved one. 

246 Defaults to `None`, in which case the roster saved in 

247 "judges" in `utilities.data_folder()` is loaded. 

248 

249 Returns: 

250 The roster. 

251 

252 """ 

253 if isinstance(source, Roster): 

254 return source 

255 if isinstance(source, pd.DataFrame): 

256 return cls(source) 

257 return cls.load(source) 

258 

259 @classmethod 

260 def from_fjc( 

261 cls, 

262 folder: pathlib.Path | str | None = None, 

263 *, 

264 update: bool = False, 

265 scores: pd.DataFrame | pathlib.Path | str | None = None, 

266 jcs: bool = False, 

267 martin_quinn: bool | pathlib.Path | str = False, 

268 rulebook: fjc_biographies.Rulebook | pathlib.Path | str = 'judges') -> ( 

269 Roster): 

270 """Returns a roster made from the Federal Judicial Center's files. 

271 

272 Any of the files that `folder` lacks is downloaded to it first (see 

273 `download`). The files that the scores of `jcs` and `martin_quinn` 

274 are computed from (Voteview's NOMINATE scores, the dates of 

275 senators' service, and the justices' Martin-Quinn scores) are 

276 downloaded by fjc-biographies and judicial-common-space into 

277 `utilities.data_folder()`, where `courtpy.politics` keeps the same 

278 files. 

279 

280 Args: 

281 folder: the folder with the files, whose "raw" folder they are 

282 kept in. Defaults to `None`, in which case "judges" in 

283 `utilities.data_folder()` is used. 

284 update: whether to download the files again even if they are 

285 there, to get the judges and changes since they were 

286 downloaded. Defaults to `False`. 

287 scores: scores of the judges to add (see `build_roster`). Defaults 

288 to `None`. 

289 jcs: whether to add each appointment's Judicial Common Space 

290 score as "jcs" (see `fjc_biographies.add_jcs`): the NOMINATE 

291 score of the judge's home-state senators of the president's 

292 party, or else of the president, and for a justice, the 

293 Martin-Quinn score of the appointment's first term on the 

294 same scale. Defaults to `False`. 

295 martin_quinn: whether to add the Martin-Quinn scores of each 

296 appointment to the Supreme Court as "mq_first", "mq_last", 

297 "mq_mean", and "mq_terms" (see 

298 `fjc_biographies.add_martin_quinn`), or the path of the file 

299 of the justices' scores ("justices.csv" from 

300 https://mqscores.wustl.edu/measures.php), which is used for 

301 `jcs` too. The Martin-Quinn website sometimes refuses 

302 automated requests, so the file may have to be saved in a 

303 browser. Defaults to `False`. 

304 rulebook: the rules that code the judges' careers (see 

305 `build_roster`). Defaults to "judges". 

306 

307 Returns: 

308 The roster. 

309 

310 """ 

311 folder = pathlib.Path(folder).expanduser() if folder else _folder() 

312 files = download(folder, overwrite = update) 

313 table = build_roster( 

314 files['service'], files['demographics'], files['career'], 

315 scores = scores, rulebook = rulebook) 

316 named = None if isinstance(martin_quinn, bool) else martin_quinn 

317 if jcs: 

318 table = fjc_biographies.add_jcs( 

319 table, folder, scores_folder = utilities.data_folder(), 

320 martin_quinn = named, update = update) 

321 if martin_quinn is not False: 

322 table = fjc_biographies.add_martin_quinn( 

323 table, folder, scores_folder = utilities.data_folder(), 

324 martin_quinn = named, update = update) 

325 return cls(table) 

326 

327 @classmethod 

328 def load(cls, path: pathlib.Path | str | None = None) -> Roster: 

329 """Loads a roster saved by `save` (or made in a spreadsheet). 

330 

331 Args: 

332 path: path of the CSV file. Defaults to `None`, in which case it 

333 is "roster.csv" in "judges" in `utilities.data_folder()`. 

334 

335 Raises: 

336 FileNotFoundError: if there is no file at `path`. 

337 

338 Returns: 

339 The roster. 

340 

341 """ 

342 found = ( 

343 pathlib.Path(path).expanduser() if path 

344 else _folder() / _ROSTER_FILE) 

345 if not found.is_file(): 

346 message = ( 

347 f'there is no roster of judges at {found}: make one with ' 

348 f'`courtpy.judges.Roster.from_fjc()` and save it with its ' 

349 f'`save` method' 

350 ) 

351 raise FileNotFoundError(message) 

352 columns = pd.read_csv(found, encoding = 'utf-8', nrows = 0).columns 

353 return cls(pd.read_csv( 

354 found, encoding = 'utf-8', 

355 dtype = {column: str for column in columns if _is_text(column)})) 

356 

357 """ Properties """ 

358 

359 @property 

360 def attributes(self) -> list[str]: 

361 """Returns the names of the columns that describe the judges. 

362 

363 Returns: 

364 The columns of numbers or booleans that do not identify or date a 

365 judge's service (such as "party" and "woman"), in order. 

366 

367 """ 

368 return [ 

369 column for column in self.data.columns 

370 if column not in _IDENTIFIERS and not _is_text(column) and ( 

371 pd.api.types.is_bool_dtype(self.data[column].dtype) 

372 or pd.api.types.is_numeric_dtype(self.data[column].dtype))] 

373 

374 @property 

375 def described(self) -> list[str]: 

376 """Returns the names of everything that `describe` reports. 

377 

378 Returns: 

379 `attributes`, followed by the attributes that depend on the case 

380 ("age", "senior", "designated", and "district_judge"). 

381 

382 """ 

383 return [*self.attributes, *_RELATIVE] 

384 

385 """ Public Methods """ 

386 

387 def describe( 

388 self, 

389 row: int, 

390 court_num: int | None = None, 

391 year: int | None = None) -> dict[str, float | None]: 

392 """Returns what is known about a judge on a case. 

393 

394 Args: 

395 row: the judge's row of the table (as `match` returns it). 

396 court_num: the number of the case's court. Defaults to `None`. 

397 year: the year of the case. Defaults to `None`. 

398 

399 Returns: 

400 Each of `described`, as a number (1 and 0 for true and false) or 

401 `None` if it is not known. "age" is the judge's age at the 

402 end of `year`, "senior" is whether the judge had taken senior 

403 status by `year`, "designated" is whether the judge's court 

404 is not the case's court (so the judge sat by designation), 

405 and "district_judge" is whether it is a district court. The 

406 same `dict` is returned each time for a judge, court, and 

407 year, so copy it before changing it. 

408 

409 """ 

410 key = (row, court_num, year) 

411 if key in self._described: 

412 return self._described[key] 

413 known = {name: values[row] for name, values in self._values.items()} 

414 birth = self._numbers['birth_year'][row] 

415 senior = self._numbers['senior_year'][row] 

416 known['age'] = ( 

417 None if year is None or birth is None else float(year - birth)) 

418 known['senior'] = ( 

419 None if year is None or 'senior_year' not in self.data.columns 

420 else float(senior is not None and senior <= year)) 

421 known['designated'] = ( 

422 None if court_num is None 

423 else float(self._numbers['court_num'][row] != court_num)) 

424 known['district_judge'] = ( 

425 float(self._text['court_type'][row] == _DISTRICT_COURT) 

426 if 'court_type' in self.data.columns else None) 

427 self._described[key] = known 

428 return known 

429 

430 def identify( 

431 self, 

432 names: Iterable[str], 

433 court_num: int | None = None, 

434 year: int | None = None) -> list[int]: 

435 """Returns the judges that the names on a case refer to. 

436 

437 Args: 

438 names: the names, as the opinion writes them. 

439 court_num: the number of the case's court. Defaults to `None`. 

440 year: the year of the case. Defaults to `None`. 

441 

442 Returns: 

443 The rows of the judges who were found, in the order of `names`, 

444 with each judge once. 

445 

446 """ 

447 rows: list[int] = [] 

448 judges: set[int | None] = set() 

449 for name in names: 

450 row = self.match(name, court_num, year) 

451 if row is not None and self._numbers['nid'][row] not in judges: 

452 rows.append(row) 

453 judges.add(self._numbers['nid'][row]) 

454 return rows 

455 

456 def match( 

457 self, 

458 name: str, 

459 court_num: int | None = None, 

460 year: int | None = None) -> int | None: 

461 """Returns the judge that a name on a case refers to. 

462 

463 Args: 

464 name: the name, as the opinion writes it (such as "LYNCH", 

465 "R. Thompson", or "Sandra L. Lynch"). 

466 court_num: the number of the case's court, which is needed to 

467 prefer its own judges and those of its circuit. Defaults to 

468 `None`, in which case judges of every court are considered. 

469 year: the year of the case. Defaults to `None`, in which case 

470 judges of every year are considered. 

471 

472 Returns: 

473 The row of the judge's service in the table (the most recent, if 

474 more than one fits), or `None` if the name is not matched 

475 (see the class's documentation). 

476 

477 """ 

478 rows = self.candidates(name, court_num, year) 

479 return rows[0] if len(rows) == 1 else None 

480 

481 def candidates( 

482 self, 

483 name: str, 

484 court_num: int | None = None, 

485 year: int | None = None) -> list[int]: 

486 """Returns every judge that a name on a case may refer to. 

487 

488 They are the judges that `match` chooses among: those whose names 

489 fit at the first of the steps that any judge's name fits (see the 

490 class's documentation). More than one means that the name is 

491 ambiguous, such as "SMITH" on a panel of the Ninth Circuit, which had 

492 two Judges Smith. 

493 

494 Args: 

495 name: the name, as the opinion writes it. 

496 court_num: the number of the case's court. Defaults to `None`. 

497 year: the year of the case. Defaults to `None`. 

498 

499 Returns: 

500 The row of each judge's service (the most recent of each judge's 

501 rows that fit), or none. 

502 

503 """ 

504 key = (clean_name(name), court_num, year) 

505 if key not in self._found: 

506 self._found[key] = self._candidates(*key) 

507 return list(self._found[key]) 

508 

509 def full_name(self, row: int) -> str: 

510 """Returns a judge's first, middle, and last names, as one name. 

511 

512 It is a full name of the judge (see `name_forms`), which `match` 

513 finds before any shorter name that other judges share. 

514 

515 Args: 

516 row: a row of the table. 

517 

518 Returns: 

519 The name, such as "SANDRA LEA LYNCH". 

520 

521 """ 

522 parts = ( 

523 self._text[column][row] 

524 for column in ('first_name', 'middle_name', 'last_name', 'suffix')) 

525 return clean_name(' '.join(part for part in parts if part)) 

526 

527 def name_words(self, row: int) -> set[str]: 

528 """Returns the words of a judge's name that a source may list alone. 

529 

530 A source that lists the words of a panel's names separately (as 

531 CourtListener's list of judges can: "Jill, Marcus, Martin, Pryor", or 

532 "Brennan, Eve, Rovner, St") gives a judge's first name, the first name 

533 and middle initial run together ("ROBERTA" for "Robert A."), or a 

534 word of a last name of several words as a word of its own. 

535 

536 Args: 

537 row: a row of the table. 

538 

539 Returns: 

540 The first name, the middle name, the first name and middle 

541 initial run together, and each word of a last name of several 

542 words, as `clean_name` writes them, if they are longer than 

543 an initial. 

544 

545 """ 

546 first = clean_name(self._text['first_name'][row]) 

547 middle = clean_name(self._text['middle_name'][row]) 

548 last = clean_name(self._text['last_name'][row]).split() 

549 words = { 

550 first, middle, f'{first}{middle[:1]}' if middle else '', 

551 *(last if len(last) > 1 else [])} 

552 return {word for word in words if len(word) > 1} 

553 

554 def names(self, rows: Iterable[int]) -> list[str]: 

555 """Returns the names of judges as the roster reports them. 

556 

557 Args: 

558 rows: rows of the table (as `identify` returns them). 

559 

560 Returns: 

561 The "judge" of each row, such as "Lynch, Sandra Lea". 

562 

563 """ 

564 return [self._text['judge'][row] for row in rows] 

565 

566 def nids(self, rows: Iterable[int]) -> list[int]: 

567 """Returns the numbers that identify judges. 

568 

569 Args: 

570 rows: rows of the table (as `identify` returns them). 

571 

572 Returns: 

573 The "nid" of each row. 

574 

575 """ 

576 return [int(self._numbers['nid'][row] or 0) for row in rows] 

577 

578 def save(self, path: pathlib.Path | str | None = None) -> pathlib.Path: 

579 """Saves the table as a CSV file, which a spreadsheet can change. 

580 

581 Args: 

582 path: path to save it to. Its folder is created if needed. 

583 Defaults to `None`, in which case it is "roster.csv" in 

584 "judges" in `utilities.data_folder()`, where `load` and the 

585 techniques look for it. 

586 

587 Returns: 

588 The path the table was saved to. 

589 

590 """ 

591 saved = ( 

592 pathlib.Path(path).expanduser() if path 

593 else _folder() / _ROSTER_FILE) 

594 saved.parent.mkdir(parents = True, exist_ok = True) 

595 self.data.to_csv(saved, index = False, encoding = 'utf-8') 

596 return saved 

597 

598 """ Private Methods """ 

599 

600 def _candidates( 

601 self, 

602 name: str, 

603 court_num: int | None, 

604 year: int | None) -> tuple[int, ...]: 

605 """Returns the judges that a cleaned name on a case may refer to. 

606 

607 The name as it is, at every level, and then its shorter forms as 

608 full names or initials (never the last name alone) are tried first. 

609 Only a name that none of them fits is repaired (see `_repaired`). 

610 

611 Args: 

612 name: the name, as `clean_name` returns it. 

613 court_num: the number of the case's court, or `None`. 

614 year: the year of the case, or `None`. 

615 

616 Returns: 

617 The row of each judge's service, or none. 

618 

619 """ 

620 courts = self._numbers['court_num'] 

621 if court_num is not None and court_num not in courts: 

622 return () 

623 attempts = [(name, _LEVELS)] + [ 

624 (form, _LEVELS[:-1]) for form in shorter_names(name)] 

625 for form, levels in attempts: 

626 rows = self._fitting(form, levels, year) 

627 if rows: 

628 return self._narrow(rows, court_num) 

629 return self._repaired(name, court_num, year) 

630 

631 def _court_judges(self, court_num: int, year: int) -> list[int]: 

632 """Returns the judges of a court who were serving in a year. 

633 

634 Args: 

635 court_num: the number of the court. 

636 year: the year. 

637 

638 Returns: 

639 The row of each judge's service on the court (the most recent of 

640 each judge's), in the order of the table. 

641 

642 """ 

643 key = (court_num, year) 

644 if key not in self._seated: 

645 rows = [ 

646 row for row, court in enumerate(self._numbers['court_num']) 

647 if court == court_num and self._serving(row, year)] 

648 self._seated[key] = list(self._narrow(rows, court_num)) 

649 return self._seated[key] 

650 

651 def _fitting( 

652 self, 

653 form: str, 

654 levels: Iterable[str], 

655 year: int | None) -> list[int]: 

656 """Returns the serving judges with a form of a name, at its first level. 

657 

658 Args: 

659 form: a form of a name, as `clean_name` writes it. 

660 levels: the levels of the forms of names to look in, in order. 

661 year: the year of the case, or `None`. 

662 

663 Returns: 

664 The rows of the judges who have the form at the first level that 

665 any serving judge has it, or none. 

666 

667 """ 

668 for level in levels: 

669 rows = [ 

670 row for row in self._forms[level].get(form, ()) 

671 if year is None or self._serving(row, year)] 

672 if rows: 

673 return rows 

674 return [] 

675 

676 def _narrow( 

677 self, 

678 rows: list[int], 

679 court_num: int | None) -> tuple[int, ...]: 

680 """Returns the judges that a name refers to among judges it fits. 

681 

682 Args: 

683 rows: the rows of the judges whose names fit, who were serving. 

684 court_num: the number of the case's court, or `None`. 

685 

686 Returns: 

687 The rows of the judges at the first of the steps (the case's 

688 court, a district court of its circuit, and any court) at 

689 which any judge fits, the most recent of each judge's rows. 

690 

691 """ 

692 courts = self._numbers['court_num'] 

693 circuits = self._numbers['circuit_num'] 

694 nids = self._numbers['nid'] 

695 starts = self._numbers['start_year'] 

696 tiers = ( 

697 [r for r in rows if court_num is not None 

698 and courts[r] == court_num], 

699 [r for r in rows if court_num is not None 

700 and circuits[r] == court_num], 

701 rows) 

702 for tier in tiers: 

703 latest: dict[int | None, int] = {} 

704 for row in tier: 

705 kept = latest.get(nids[row]) 

706 if kept is None or (starts[row] or 0) > (starts[kept] or 0): 706 ↛ 704line 706 didn't jump to line 704 because the condition on line 706 was always true

707 latest[nids[row]] = row 

708 if latest: 

709 return tuple(latest.values()) 

710 return () 

711 

712 def _repaired( 

713 self, 

714 name: str, 

715 court_num: int | None, 

716 year: int | None) -> tuple[int, ...]: 

717 """Returns the judge that a name that fits no judge was meant to be. 

718 

719 The name is first written in the forms that undo the damage of some 

720 opinions' text (see `repaired_names`), each tried as a name is. Then 

721 it is compared with the judges of the case's court who were serving 

722 in its year: it is a judge's if it is the last word of the judge's 

723 last name of several words ("EVE" for "St. Eve", or "ANTWERPEN" for 

724 "Van Antwerpen"), the judge's first and last names run together 

725 ("REENARAGGI"), or, for a name of five letters or more, one edit from 

726 the judge's last name (`edit_distance`), as scanning errors make it 

727 ("KRAVTTCH" for "Kravitch", or "SCANNLAIN" for "O'Scannlain"). Only 

728 a name that fits exactly one judge there is repaired. 

729 

730 Args: 

731 name: the name, as `clean_name` returns it. 

732 court_num: the number of the case's court, or `None`. 

733 year: the year of the case, or `None`. 

734 

735 Returns: 

736 The row of the judge's service, or none. 

737 

738 """ 

739 for form in repaired_names(name): 

740 rows = self._fitting(form, _LEVELS, year) 

741 if rows: 

742 found = self._narrow(rows, court_num) 

743 if len(found) == 1: 743 ↛ 739line 743 didn't jump to line 739 because the condition on line 743 was always true

744 return found 

745 if court_num is None or year is None or ' ' in name: 

746 return () 

747 fits = [] 

748 for row in self._court_judges(court_num, year): 

749 last = clean_name(self._text['last_name'][row]) 

750 first = clean_name(self._text['first_name'][row]) 

751 words = last.split() 

752 if ( 

753 (len(words) > 1 and name == words[-1]) 

754 or name == f'{first}{last}'.replace(' ', '') 

755 or (len(name) >= _FEWEST_TO_REPAIR 

756 and edit_distance(name, last.replace(' ', '')) <= 1)): 

757 fits.append(row) 

758 return tuple(fits) if len(fits) == 1 else () 

759 

760 def _serving(self, row: int, year: int) -> bool: 

761 """Returns whether an opinion of a year may name a judge. 

762 

763 Args: 

764 row: a row of the table. 

765 year: the year of a case. 

766 

767 Returns: 

768 Whether the service of `row` had begun by `year` and had not 

769 ended more than `grace` years before it. 

770 

771 """ 

772 start = self._numbers['start_year'][row] 

773 end = self._numbers['end_year'][row] 

774 return ( 

775 start is not None and start <= year 

776 and (end is None or year <= end + self.grace)) 

777 

778 

779@dataclasses.dataclass 

780class LoadRoster(loaders.ReferenceLoader): 

781 """Loads the table of a roster of judges. 

782 

783 The table (see `Roster`), with a row for each court that each judge has 

784 served on, starts a study of the judges themselves. Its "source" is the 

785 path of a saved roster. Without one, the roster saved in "judges" in 

786 `courtpy.utilities.data_folder()` is used (see `Roster.load`). To add 

787 what a roster says about judges to cases, use `add_biography` or 

788 `code_panels` instead. 

789 

790 """ 

791 

792 """ Public Methods """ 

793 

794 def load(self, source: Any, **kwargs: Any) -> pd.DataFrame: 

795 """Returns the table of a saved roster. 

796 

797 Args: 

798 source: the path of a saved roster, or "current" for the roster 

799 saved in "judges" in `utilities.data_folder()`. 

800 **kwargs: not used. 

801 

802 Raises: 

803 FileNotFoundError: if there is no roster at the path. 

804 

805 Returns: 

806 The roster's table. 

807 

808 """ 

809 return Roster.load(self._locate(source)).data 

810 

811 

812@dataclasses.dataclass 

813class DownloadBiographies(loaders.ReferenceLoader): 

814 """Downloads the Federal Judicial Center's files and loads their roster. 

815 

816 The center's files about judges are downloaded unless they are there 

817 already, or "refresh" is true (see `download`), and a roster is made from 

818 them (see `Roster.from_fjc`), which is saved too if "save" is set. Its 

819 "source" is the folder to keep the files in, which is "judges" in 

820 `courtpy.utilities.data_folder()` unless another is set. 

821 

822 """ 

823 

824 """ Public Methods """ 

825 

826 def load( 

827 self, 

828 source: Any, 

829 *, 

830 refresh: bool | str = False, 

831 scores: pathlib.Path | str | None = None, 

832 jcs: bool | str = False, 

833 martin_quinn: bool | pathlib.Path | str = False, 

834 rulebook: str = 'judges', 

835 save: bool | pathlib.Path | str = False, 

836 **kwargs: Any) -> pd.DataFrame: 

837 """Downloads the files and returns the table of the roster they make. 

838 

839 Args: 

840 source: the folder to keep the files in, or "current" for 

841 "judges" in `utilities.data_folder()`. 

842 refresh: whether to download the files even if they are there, 

843 to get the judges and changes since. Defaults to `False`. 

844 scores: the path of a file of scores of the judges to add (see 

845 `build_roster`). Defaults to `None`. 

846 jcs: whether to add each appointment's Judicial Common Space 

847 score as "jcs". Defaults to `False`. 

848 martin_quinn: whether to add the justices' Martin-Quinn scores, 

849 or the path of the file of them. Defaults to `False`. 

850 rulebook: the rules that code the judges' careers. Defaults to 

851 "judges". 

852 save: whether to save the roster where the techniques look for 

853 it (see `Roster.save`), or the path to save it to. Defaults 

854 to `False`. 

855 **kwargs: not used. 

856 

857 Returns: 

858 The roster's table. 

859 

860 """ 

861 chosen = self._choose(martin_quinn) 

862 roster = Roster.from_fjc( 

863 self._locate(source), 

864 update = utilities.to_bool(refresh), 

865 scores = None if scores is None else utilities.locate( 

866 scores, self._get_clerk()), 

867 jcs = utilities.to_bool(jcs), 

868 martin_quinn = False if chosen is None else chosen, 

869 rulebook = rulebook) 

870 target = self._choose(save) 

871 if target is True: 

872 roster.save() 

873 elif isinstance(target, pathlib.Path): 

874 roster.save(target) 

875 return roster.data 

876 

877 

878""" Public Functions """ 

879 

880 

881def build_roster( 

882 service: pd.DataFrame | pathlib.Path | str, 

883 demographics: pd.DataFrame | pathlib.Path | str, 

884 career: pd.DataFrame | pathlib.Path | str | None = None, 

885 *, 

886 scores: pd.DataFrame | pathlib.Path | str | None = None, 

887 rulebook: fjc_biographies.Rulebook | pathlib.Path | str = 'judges') -> ( 

888 pd.DataFrame): 

889 """Makes the table of a roster from the Federal Judicial Center's files. 

890 

891 The files are those of the Biographical Directory of Article III Federal 

892 Judges that are organized by category (see `download`). The table is the 

893 roster that `fjc_biographies.build_roster` makes, with one row for each 

894 court that each judge has served on, and the two columns that courtpy 

895 adds to find the judges of cases. Among its columns are: 

896 

897 | Column | Meaning | 

898 | --- | --- | 

899 | `nid` | The center's number for the judge. | 

900 | `judge` | The judge's name, as the center reports it. | 

901 | `last_name`, `first_name`, `middle_name`, `suffix` | Its parts. | 

902 | `aliases` | Other names that opinions use for the judge. Added by courtpy. | 

903 | `name_first_middle_last`, ... | The name written in the ways that fjc-biographies writes it, for matching it against other sources. | 

904 | `sequence` | The center's number for the order of the judge's service on the court among the judge's. | 

905 | `court`, `court_type` | The court's name and its type. | 

906 | `court_num` | The number that the federal rules give a court of appeals or the Supreme Court. Missing for other courts. Added by courtpy. | 

907 | `circuit_num` | The number of the court's circuit: its own `court_num`, or for a district court, that of its state. | 

908 | `start_date`, `end_date`, `senior_date` | The dates the judge's service on the court began (with a commission or a recess appointment) and ended, and the judge took senior status. | 

909 | `start_year`, `end_year`, `senior_year` | Their years. `end_year` is missing for a judge who is still serving. | 

910 | `birth_year` | The year the judge was born. | 

911 | `president` | The president who appointed the judge. | 

912 | `party` | That president's party: -1 for Democratic and 1 for Republican. Missing for other parties. | 

913 | `aba_rating` | The American Bar Association's rating, from 1 (not qualified) to 4 (exceptionally well qualified). Missing if there was none. | 

914 | `recess` | Whether the judge first took the seat by a recess appointment. | 

915 | `senate_vote` | The share of senators who voted to confirm the judge (1 for a voice vote). Missing if the vote is not recorded. | 

916 | `woman`, `minority` | Whether the judge is a woman, and whether the judge's race or ethnicity is anything other than white. | 

917 

918 A judge who was reassigned to another court without a new appointment 

919 (as when the Eleventh Circuit was divided from the Fifth) keeps the 

920 president, party, rating, recess appointment, and vote of the judge's 

921 last appointment. 

922 

923 If `career` is passed, the judge's career is the column "career" (each 

924 position on its own line), and each variable that `rulebook` makes from 

925 it is a column too. The "judges" rulebook of fjc-biographies makes 

926 "prosecutor", "public_defender", "law_clerk", "supreme_court_clerk", 

927 "solicitor_general", and "law_professor". 

928 

929 Args: 

930 service: the file of federal judicial service 

931 ("federal-judicial-service.csv"), as a path or a table. 

932 demographics: the file of demographics ("demographics.csv"). 

933 career: the file of professional careers 

934 ("professional-career.csv"). Defaults to `None`, in which case no 

935 careers are coded. 

936 scores: a table (or the path of a CSV file) with an "nid" column and 

937 columns of scores for the judges, which are added to the roster 

938 with the `merge_keys` technique of `amos`. If it has more than 

939 one row for a judge, the first is used, and a column whose name 

940 the roster already has is left out. Defaults to `None`. 

941 rulebook: the rules that code careers: a rulebook of fjc-biographies, 

942 or the name of one of its built-in rulebooks or the path of a CSV 

943 file. Its rules search the section "career", which has each 

944 position that a judge held on its own line. Defaults to "judges". 

945 

946 Raises: 

947 KeyError: if a file lacks a column that is needed. 

948 ValueError: if the file of demographics has more than one row for a 

949 judge. 

950 

951 Returns: 

952 The table, sorted by judge and then by the order of the judge's 

953 service. 

954 

955 """ 

956 roster = fjc_biographies.build_roster( 

957 service, demographics, career, rulebook = rulebook) 

958 numbers = _number_courts( 

959 roster.loc[roster['court_type'].isin(_APPELLATE), 'court']) 

960 court_num = roster['court'].map(numbers).astype('Int64') 

961 # A court of appeals or the Supreme Court is the circuit of its own cases, 

962 # as `Roster.match` compares them, so its circuit is its number. 

963 roster['circuit_num'] = court_num.where( 

964 roster['court_type'] != _DISTRICT_COURT, roster['circuit_num']) 

965 columns = list(roster.columns) 

966 roster.insert(columns.index('circuit_num'), 'court_num', court_num) 

967 roster.insert( 

968 columns.index('suffix') + 1, 'aliases', 

969 roster['nid'].map(_ALIASES).fillna('').astype(str)) 

970 if scores is not None: 

971 scored = ( 

972 scores.copy() if isinstance(scores, pd.DataFrame) 

973 else utilities.read_csv(scores)) 

974 cases.require_columns(scored, ['nid'], 'the table of scores') 

975 roster = amos.mergers.MergeKeys().apply( 

976 amos.Dataset(roster), 

977 source = scored.assign( 

978 nid = pd.to_numeric(scored['nid'], errors = 'coerce')), 

979 on = 'nid', 

980 duplicates = 'first').data 

981 return roster 

982 

983 

984def download( 

985 folder: pathlib.Path | str | None = None, 

986 *, 

987 overwrite: bool = False) -> dict[str, pathlib.Path]: 

988 """Downloads the Federal Judicial Center's files about judges. 

989 

990 The files are three of those of the Biographical Directory of Article III 

991 Federal Judges that are organized by category (see 

992 https://www.fjc.gov/history/judges/biographical-directory-article-iii-federal-judges-export): 

993 federal judicial service, demographics, and professional careers. They 

994 need no account and are a few megabytes together. fjc-biographies 

995 downloads them (see `fjc_biographies.download`), into the "raw" folder of 

996 `folder`, which is where its scores look for them too. 

997 

998 Args: 

999 folder: the folder whose "raw" folder they are saved in. Defaults to 

1000 `None`, in which case "judges" in `utilities.data_folder()` is 

1001 used. 

1002 overwrite: whether to download a file that is already there. The 

1003 center adds new judges and changes as they happen. Defaults to 

1004 `False`. 

1005 

1006 Raises: 

1007 urllib.error.URLError: if a file cannot be downloaded. 

1008 

1009 Returns: 

1010 The path of each file, by the name of the parameter of `build_roster` 

1011 that takes it ("service", "demographics", and "career"). 

1012 

1013 """ 

1014 folder = pathlib.Path(folder).expanduser() if folder else _folder() 

1015 return fjc_biographies.download( 

1016 _CATEGORIES, folder, overwrite = overwrite) 

1017 

1018 

1019""" Private Functions """ 

1020 

1021 

1022def _folder() -> pathlib.Path: 

1023 """Returns the folder where a roster and its sources are kept. 

1024 

1025 Returns: 

1026 "judges" in `utilities.data_folder()`. It is not created. 

1027 

1028 """ 

1029 return utilities.data_folder() / 'judges' 

1030 

1031 

1032def _is_text(column: Any) -> bool: 

1033 """Returns whether a column of a roster is text. 

1034 

1035 Args: 

1036 column: the name of the column. 

1037 

1038 Returns: 

1039 Whether it is one of `_TEXT` or matches `_OTHER_TEXT`. 

1040 

1041 """ 

1042 return column in _TEXT or bool(_OTHER_TEXT.fullmatch(str(column))) 

1043 

1044 

1045def _number_courts(courts: Iterable[str]) -> dict[str, int]: 

1046 """Returns the numbers that the federal rules give courts. 

1047 

1048 The numbers come from the rules that make "court_num" for cases from the 

1049 names in the table of federal courts (see `rules.make_court_rules`), so 

1050 a judge's court and a case's court always have the same number. 

1051 

1052 Args: 

1053 courts: the Federal Judicial Center's names of courts of appeals and 

1054 the Supreme Court. 

1055 

1056 Returns: 

1057 The number of each court that the rules number, by its name. 

1058 

1059 """ 

1060 numbering = amos.parsers.Rulebook.create(rules.make_court_rules()) 

1061 names = list(dict.fromkeys(courts)) 

1062 found = numbering.apply( 

1063 pd.DataFrame({'court': pd.Series(names, dtype = 'str')})) 

1064 return { 

1065 court: int(number) 

1066 for court, number in zip(names, found['court_num'], strict = True) 

1067 if not pd.isna(number)} 

1068 

1069 

1070def _whole(value: Any) -> int | None: 

1071 """Returns a value as a whole number, or `None` if it is missing. 

1072 

1073 Args: 

1074 value: a number (or text of one) or a missing value. 

1075 

1076 Returns: 

1077 The number, or `None`. 

1078 

1079 """ 

1080 return None if value is None or pd.isna(value) else int(value)