Coverage for src/courtpy/references/judges/_biographies.py: 98%

107 statements  

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

1"""Adds what is known about the judges that the rows name. 

2 

3Contents: 

4 AddBiography: adds what a roster says about each judge that each row 

5 names. 

6 AddJcs: adds the Judicial Common Space score of each judge that each row 

7 names. 

8 by_seat: returns columns of each judge of each case, numbered by the 

9 judge's seat. 

10 find_roster: returns the roster that a technique's "source" names. 

11 _IDENTITY: the columns that name the judge in each seat. 

12 _ROW: column that holds the position of each row's case while a table 

13 is made. 

14 _SEAT: column that holds each judge's seat on a panel while a table is 

15 made. 

16 _WRITTEN: column that holds each judge's name, as the opinion writes it, 

17 while a table is made. 

18 

19""" 

20 

21from __future__ import annotations 

22 

23import dataclasses 

24import pathlib 

25from collections.abc import Callable, Mapping, Sequence 

26from typing import Any, ClassVar 

27 

28import amos 

29import numpy as np 

30import pandas as pd 

31 

32from ...core import cases, datasets, utilities 

33from ._roster import _ROSTER_FILE, Roster, _folder, _whole 

34 

35# A function that finds what is known about a judge, from the judge's name 

36# as an opinion writes it, the number of the case's court, and its year. 

37Lookup = Callable[[str, int | None, int | None], Mapping[str, Any] | None] 

38 

39_IDENTITY: tuple[str, ...] = ('name', 'nid') 

40_ROW: str = '__row__' 

41_SEAT: str = '__seat__' 

42_WRITTEN: str = '__written__' 

43 

44 

45@dataclasses.dataclass 

46class AddBiography(amos.Merger): 

47 """Adds what a roster says about each judge that each row names. 

48 

49 A name, as an opinion writes it (such as "LYNCH"), is matched to a judge 

50 in a roster (see `Roster`) with the court and year of the row's case, and 

51 the columns of the judge's row of the roster are added, with a prefix 

52 before their names. A name that is not matched gets missing values. 

53 

54 In `Votes` (or any table with a row for each judge), each row names one 

55 judge ("judge"), so it gets "judge_party", "judge_woman", and so on. With 

56 "name" set to "author" and "prefix" to "author_", a table of cases gets 

57 what is known about the author of each opinion. 

58 

59 In `Cases`, each case names several judges ("panel_judges", with "; " 

60 between the names), so the columns are numbered by each judge's seat 

61 (the place of the judge's name in the list): "judge_name1" (the judge's 

62 name, as the roster reports it), "judge_nid1" (the Federal Judicial 

63 Center's number for the judge), "judge_party1", "judge_woman1", and so on 

64 for the first judge, "judge_name2" and the rest for the second, for as 

65 many seats as the longest panel has. A name that is not matched leaves 

66 its seat missing, so the judges after it keep theirs. "judge_name" and 

67 "judge_nid" columns that the cases already have (from `code_panels`) are 

68 left as they are. 

69 

70 Instead of a roster, "lookup" can be a function that takes a judge's name 

71 (as the opinion writes it), the number of the case's court, and its year, 

72 and returns what is known about the judge, by the names of its columns 

73 (or `None` if nothing is). Then "judge_name1" is the name as the opinion 

74 writes it. 

75 

76 Like every merger of `amos`, it takes these parameters, never adds, 

77 removes, or reorders rows, and records how many rows it matched in the 

78 dataset's history: 

79 

80 | Parameter | Meaning | 

81 | --- | --- | 

82 | `source` | The roster: the path of a saved one (looked for in the current folder and then in the clerk's input folder), a roster, or the table of one. Without it, the roster saved in "judges" in `utilities.data_folder()` is used. | 

83 | `columns` | The columns to add. By default, they are the roster's attributes (see `Roster.attributes`) and those that depend on the case: "age", "senior", "designated", and "district_judge" (see `Roster.describe`). All of them are added as numbers (1 and 0 for true and false). Any other column of the roster can be named too, such as "judge" (the judge's name, as the roster reports it), "nid", or "president". | 

84 | `prefix` | Text to put before the names of the added columns. It is "judge_" unless another is set. | 

85 | `indicator` | The name of a column to make that says whether each row's judge was found (or, numbered, how many of its judges were). | 

86 | `name`, `court`, `year` | The columns of the data with the judges' names and the number of the court and the year of the row's case. They are "panel_judges" (for `Cases`) or "judge", "court_num", and "year" unless others are set. | 

87 | `numbered` | Whether each row names several judges, whose columns are numbered by their seats. Unless it is set, it is true for `Cases` without a "name", and false otherwise. | 

88 | `lookup` | A function that finds what is known about a judge, used instead of a roster. | 

89 

90 Attributes: 

91 default_columns: the columns to add when "columns" is not set, or 

92 `None` for every attribute of the judges. 

93 

94 """ 

95 

96 default_columns: ClassVar[tuple[str, ...] | None] = None 

97 

98 """ Public Methods """ 

99 

100 def apply( 

101 self, 

102 item: amos.Dataset, 

103 *, 

104 source: Any = None, 

105 columns: Sequence[str] | str | None = None, 

106 prefix: str | None = 'judge_', 

107 indicator: str | None = None, 

108 name: str | None = None, 

109 court: str = 'court_num', 

110 year: str = 'year', 

111 numbered: bool | None = None, 

112 lookup: Lookup | None = None, 

113 **kwargs: Any) -> amos.Dataset: 

114 """Adds the columns of each judge that each row of `item` names. 

115 

116 Args: 

117 item: the dataset to add columns to. 

118 source: the roster: a roster, the table of one, or the path of a 

119 saved one. Defaults to `None`, in which case the roster saved 

120 in "judges" in `utilities.data_folder()` is used. It is not 

121 used with `lookup`. 

122 columns: the columns to add: attributes of the judge (see 

123 `Roster.described`) or other columns of the roster (or, with 

124 `lookup`, names that it returns). Defaults to `None`, in 

125 which case they are every attribute (or, with `lookup`, every 

126 name that it returns). 

127 prefix: text to put before the names of the added columns. 

128 Defaults to "judge_". 

129 indicator: name of a column to make that says whether each row's 

130 judge was found, or (numbered) how many of its judges were. 

131 Defaults to `None`, which makes no such column. 

132 name: the column of `item` with the judges' names, as an opinion 

133 writes them. Defaults to `None`, in which case it is 

134 "panel_judges" if `numbered`, and otherwise "judge". 

135 court: the column of `item` with the number of the court of the 

136 row's case. Defaults to "court_num". 

137 year: the column of `item` with the year of the row's case. 

138 Defaults to "year". 

139 numbered: whether each row names several judges, separated by 

140 "; " (or in a list), whose columns are numbered by their 

141 seats. Defaults to `None`, in which case it is true if `item` 

142 is `Cases` and `name` is `None`. 

143 lookup: a function that takes a judge's name, the number of the 

144 case's court, and its year, and returns what is known about 

145 the judge (or `None`). Defaults to `None`, in which case the 

146 roster is used. 

147 **kwargs: not used. 

148 

149 Raises: 

150 KeyError: if `item` lacks one of the columns `name`, `court`, and 

151 `year`, or one of `columns` is not in the roster. 

152 ValueError: if an added column would have the name of a column 

153 of the data. 

154 

155 Returns: 

156 The dataset with the added columns. Its rows and index are not 

157 changed. 

158 

159 """ 

160 if numbered is None: 160 ↛ 162line 160 didn't jump to line 162 because the condition on line 160 was always true

161 numbered = isinstance(item, datasets.Cases) and name is None 

162 if name is None: 

163 name = 'panel_judges' if numbered else 'judge' 

164 if columns is None and self.default_columns is not None: 

165 columns = list(self.default_columns) 

166 data = item.data 

167 cases.require_columns(data, [name, court, year], repr(self.name)) 

168 named = _listed(data, name, court, year) if numbered else pd.DataFrame({ 

169 _ROW: np.arange(len(data)), 

170 _SEAT: 1, 

171 _WRITTEN: data[name].to_numpy(), 

172 court: data[court].to_numpy(), 

173 year: data[year].to_numpy()}) 

174 if lookup is None: 

175 roster = self._roster(source) 

176 found, rows = self._from_roster( 

177 named, roster, columns, court = court, year = year) 

178 matched = rows >= 0 

179 identity = pd.DataFrame({ 

180 'name': roster.data['judge'].reindex(rows).to_numpy(), 

181 'nid': roster.data['nid'].reindex(rows).astype( 

182 'Int64').array}) 

183 else: 

184 found = _from_lookup(named, lookup, columns, court, year) 

185 matched = found.notna().any(axis = 1).to_numpy() 

186 identity = pd.DataFrame({ 

187 'name': named[_WRITTEN].where(matched).to_numpy()}) 

188 start = prefix or '' 

189 if numbered: 

190 identity = identity[[ 

191 key for key in identity.columns 

192 if f'{start}{key}1' not in data.columns]] 

193 seated = pd.concat([ 

194 named[[_ROW, _SEAT]].reset_index(drop = True), 

195 identity.add_prefix(start), 

196 found.add_prefix(start)], axis = 1) 

197 added = by_seat(seated, len(data)) 

198 if indicator is not None: 

199 added[indicator] = pd.Series(matched).groupby( 

200 named[_ROW].to_numpy()).sum().reindex( 

201 range(len(data)), fill_value = 0).to_numpy() 

202 else: 

203 added = found.add_prefix(start) 

204 if indicator is not None: 

205 added[indicator] = matched 

206 added.index = data.index 

207 clashes = [c for c in added.columns if c in data.columns] 

208 if clashes: 

209 message = ( 

210 f'{self.name!r} would add columns named {clashes}, which the ' 

211 f'data already has: set "prefix" to tell them apart, or name ' 

212 f'the columns to add in "columns"' 

213 ) 

214 raise ValueError(message) 

215 item.replace(pd.concat([data, added], axis = 1)) 

216 item.record( 

217 self.name, 

218 source = ( 

219 'lookup' if lookup is not None 

220 else str(source) if isinstance(source, str | pathlib.Path) 

221 else type(source).__name__), 

222 rows = len(data), 

223 judges = int(named[_WRITTEN].notna().sum()), 

224 matched = int(matched.sum()), 

225 created = list(added.columns)) 

226 return item 

227 

228 def match( 

229 self, 

230 data: pd.DataFrame, 

231 other: pd.DataFrame | Roster, 

232 *, 

233 name: str = 'judge', 

234 court: str = 'court_num', 

235 year: str = 'year', 

236 **kwargs: Any) -> Any: 

237 """Returns the row of a roster for the judge that each row names. 

238 

239 Args: 

240 data: the data, with a row for each judge to find. 

241 other: a roster, or the table of one. 

242 name: the column of `data` with the judge's name, as an opinion 

243 writes it. Defaults to "judge". 

244 court: the column of `data` with the number of the court of the 

245 row's case. Defaults to "court_num". 

246 year: the column of `data` with the year of the row's case. 

247 Defaults to "year". 

248 **kwargs: not used. 

249 

250 Raises: 

251 KeyError: if `data` lacks one of the columns. 

252 

253 Returns: 

254 The position of the judge's row in the roster for each row of 

255 `data` (see `Roster.match`), or -1 if the name is missing or 

256 is not matched. 

257 

258 """ 

259 cases.require_columns(data, [name, court, year], repr(self.name)) 

260 roster = Roster.create(other) 

261 named = zip( 

262 data[name].tolist(), data[court].tolist(), data[year].tolist(), 

263 strict = True) 

264 found = ( 

265 roster.match(written, _whole(number), _whole(when)) 

266 if isinstance(written, str) and written.strip() else None 

267 for written, number, when in named) 

268 return np.array( 

269 [-1 if row is None else row for row in found], dtype = 'int64') 

270 

271 """ Private Methods """ 

272 

273 def _from_roster( 

274 self, 

275 named: pd.DataFrame, 

276 roster: Roster, 

277 columns: Sequence[str] | str | None, 

278 *, 

279 court: str, 

280 year: str) -> tuple[pd.DataFrame, np.ndarray]: 

281 """Returns what the roster says about each named judge. 

282 

283 Args: 

284 named: a table with a row for each name, with `_WRITTEN`, `court`, 

285 and `year`. 

286 roster: the roster. 

287 columns: the columns to add, or `None` for every attribute. 

288 court: the column of `named` with the number of the case's court. 

289 year: the column of `named` with the year of the case. 

290 

291 Raises: 

292 KeyError: if one of `columns` is not in the roster. 

293 

294 Returns: 

295 A table with a row for each row of `named` and a column for each 

296 of the chosen columns, and the judge's row of the roster for 

297 each row of `named` (or -1 if the name is not matched). 

298 

299 """ 

300 rows = np.asarray( 

301 self.match( 

302 named, roster, name = _WRITTEN, court = court, year = year), 

303 dtype = 'int64') 

304 chosen = ( 

305 roster.described if columns is None 

306 else utilities.listify(columns)) 

307 missing = [ 

308 c for c in chosen 

309 if c not in roster.described and c not in roster.data.columns] 

310 if missing: 

311 message = ( 

312 f'the columns {missing} are not in the roster of judges' 

313 + (': make the roster with Roster.from_fjc(jcs = True)' 

314 if 'jcs' in missing else '')) 

315 raise KeyError(message) 

316 described = pd.DataFrame(columns = roster.described, dtype = 'float64') 

317 if any(column in roster.described for column in chosen): 

318 blank: dict[str, float | None] = dict.fromkeys(roster.described) 

319 cases_of = zip( 

320 rows.tolist(), named[court].tolist(), named[year].tolist(), 

321 strict = True) 

322 described = pd.DataFrame.from_records( 

323 [roster.describe(row, _whole(number), _whole(when)) 

324 if row >= 0 else blank for row, number, when in cases_of], 

325 columns = roster.described).astype('float64') 

326 # A row of -1 is no row of the roster, so its values are missing. 

327 listed = roster.data.reindex(rows) 

328 found = pd.DataFrame({ 

329 column: ( 

330 described[column] if column in roster.described 

331 else listed[column]).to_numpy() 

332 for column in chosen}) 

333 return found, rows 

334 

335 def _roster(self, source: Any) -> Roster: 

336 """Returns the roster that `source` names. 

337 

338 Args: 

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

340 `None` for the roster saved in "judges" in 

341 `utilities.data_folder()`. 

342 

343 Returns: 

344 The roster. 

345 

346 """ 

347 return find_roster(source, self.clerk) 

348 

349 

350@dataclasses.dataclass 

351class AddJcs(AddBiography): 

352 """Adds the Judicial Common Space score of each judge that each row names. 

353 

354 It is `add_biography` with "jcs" as its only column: the score of each 

355 judge's appointment on the scale of the Judicial Common Space (higher is 

356 more conservative), which a roster has if it was made with 

357 `Roster.from_fjc(jcs = True)` (see `courtpy.jcs`). So `Votes` gets 

358 "judge_jcs", and `Cases` gets "judge_name1", "judge_nid1", and 

359 "judge_jcs1" for the first judge, and so on for each seat. It takes the 

360 parameters of `add_biography`, so "lookup" can be a function that finds 

361 each judge's score instead (returning {"jcs": score}). 

362 

363 """ 

364 

365 default_columns: ClassVar[tuple[str, ...] | None] = ('jcs',) 

366 

367 

368""" Public Functions """ 

369 

370 

371def find_roster(source: Any, clerk: Any = None) -> Roster: 

372 """Returns the roster that a technique's "source" names. 

373 

374 Args: 

375 source: a roster, the table of one, the path of a saved one (looked 

376 for in the current folder and then in the clerk's input folder), 

377 or `None` for the roster saved in "judges" in 

378 `utilities.data_folder()`. 

379 clerk: the file manager of the technique. Defaults to `None`. 

380 

381 Returns: 

382 The roster. 

383 

384 """ 

385 if source is None: 

386 source = _folder() / _ROSTER_FILE 

387 return ( 

388 Roster.create(utilities.locate(source, clerk)) 

389 if isinstance(source, str | pathlib.Path) 

390 else Roster.create(source)) 

391 

392 

393def by_seat(seated: pd.DataFrame, size: int) -> pd.DataFrame: 

394 """Returns columns of each judge of each case, numbered by the judge's seat. 

395 

396 The `long_to_wide` technique of `amos` makes a column for each seat of 

397 each column. 

398 

399 Args: 

400 seated: a table with a row for each judge on each case, with the 

401 position of the judge's case (`_ROW`), the judge's seat 

402 (`_SEAT`, 1 for the first), and columns to number. 

403 size: the number of cases. 

404 

405 Returns: 

406 A table with a row for each case, in order, and, for each column of 

407 `seated` and each seat, the column named for it and the seat 

408 ("judge_party1", "judge_party2", and so on), for as many seats 

409 as any case has. A case with fewer judges has missing values in 

410 the rest. It has no columns if `seated` has no rows. 

411 

412 """ 

413 values = [c for c in seated.columns if c not in (_ROW, _SEAT)] 

414 if seated.empty or not values: 414 ↛ 415line 414 didn't jump to line 415 because the condition on line 414 was never true

415 return pd.DataFrame(index = pd.RangeIndex(size)) 

416 seats = int(seated[_SEAT].max()) 

417 renamed = {column: f'{column}__' for column in values} 

418 wide = amos.shapers.LongToWide().shape( 

419 seated.rename(columns = renamed), names = _SEAT, 

420 stubs = list(renamed.values()), ids = _ROW, separator = '') 

421 wide = wide.set_index(_ROW).reindex(range(size)) 

422 # Each column keeps its type (such as "Int64" for the judges' numbers). 

423 columns = { 

424 f'{column}{seat}': wide[f'{column}__{seat}'].astype( 

425 seated[column].dtype) 

426 for seat in range(1, seats + 1) for column in values 

427 if f'{column}__{seat}' in wide.columns} 

428 return pd.DataFrame(columns).reset_index(drop = True) 

429 

430 

431""" Private Functions """ 

432 

433 

434def _from_lookup( 

435 named: pd.DataFrame, 

436 lookup: Lookup, 

437 columns: Sequence[str] | str | None, 

438 court: str, 

439 year: str) -> pd.DataFrame: 

440 """Returns what a function says about each named judge. 

441 

442 Args: 

443 named: a table with a row for each name, with `_WRITTEN`, `court`, 

444 and `year`. 

445 lookup: the function. 

446 columns: the columns to add, or `None` for every name that the 

447 function returns. 

448 court: the column of `named` with the number of the case's court. 

449 year: the column of `named` with the year of the case. 

450 

451 Returns: 

452 A table with a row for each row of `named` and a column for each of 

453 the chosen columns, missing where the function says nothing. 

454 

455 """ 

456 found = [ 

457 dict(lookup(written, _whole(number), _whole(when)) or {}) 

458 if isinstance(written, str) and written.strip() else {} 

459 for written, number, when in zip( 

460 named[_WRITTEN].tolist(), named[court].tolist(), 

461 named[year].tolist(), strict = True)] 

462 chosen = ( 

463 list(dict.fromkeys(key for record in found for key in record)) 

464 if columns is None else utilities.listify(columns)) 

465 return pd.DataFrame.from_records(found, columns = chosen) 

466 

467 

468def _listed( 

469 data: pd.DataFrame, 

470 name: str, 

471 court: str, 

472 year: str) -> pd.DataFrame: 

473 """Returns a table with a row for each name that each row lists. 

474 

475 The `lists_to_rows` technique of `amos` makes the rows. 

476 

477 Args: 

478 data: the data. 

479 name: the column with the names, separated by "; " (or in lists). 

480 court: the column with the number of each row's court. 

481 year: the column with each row's year. 

482 

483 Returns: 

484 A table with the position of each name's row in `data` (`_ROW`), the 

485 place of the name in its row's list (`_SEAT`), the name 

486 (`_WRITTEN`), and `court` and `year`. A row with no names has 

487 one row, whose name is missing. 

488 

489 """ 

490 names = pd.DataFrame({ 

491 _ROW: np.arange(len(data)), 

492 _WRITTEN: pd.Series(data[name].tolist(), dtype = object), 

493 court: pd.Series(data[court].tolist(), dtype = object), 

494 year: pd.Series(data[year].tolist(), dtype = object)}) 

495 listed = amos.shapers.ListsToRows().shape( 

496 names, column = _WRITTEN, separator = cases._SEPARATOR.strip()) 

497 listed[_SEAT] = listed.groupby(_ROW).cumcount() + 1 

498 return listed.reset_index(drop = True)