Coverage for src/courtpy/references/judges/_panels.py: 99%
227 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"""Techniques for the panels of cases and the votes of their judges.
3Contents:
4 CasesToJudges: makes a table with one row for each judge.
5 CasesToVotes: makes a table with one row for each judge on each case.
6 CodePanels: adds the judges and the composition of each case's panel.
7 DocketsToVotes: makes a table with one row for each judge on each
8 docket.
9 VotesToCases: makes a table of votes a table of cases again.
10 panel_compositions: returns the composition of each case's panel by the
11 parties of the presidents who appointed its judges, such as "DDR".
12 republican_appointees: returns how many judges of each case's panel a
13 Republican president appointed.
14 vote_table: returns a table with one row for each judge on each case.
15 _CASE: column that holds the label of each row's case while a table is
16 made.
17 _FOUND: column that holds whether a judge was found while a table is
18 made.
19 _JUDGE_PREFIXES: the starts of the names of the columns that
20 `vote_table` makes for each judge, which `VotesToCases` removes.
21 _NAME: column that holds each judge's name while a table is made.
22 _NID: the column of a table of votes with each judge's number, which
23 labels the table that `CasesToJudges` makes.
24 _OTHER: column that holds the place of the other judge of each pair
25 while a table is made.
26 _PLACE: column that holds each judge's place on a panel while a table
27 is made.
28 _ROLES: the columns of the judges' roles in a case (such as "authors"),
29 with the columns of flags that `vote_table` makes from them.
30 _SEAT: column that holds each judge's seat on a panel while a table is
31 made.
33"""
35from __future__ import annotations
37import dataclasses
38import pathlib
39from collections.abc import Mapping, Sequence
40from typing import Any, ClassVar
42import amos
43import numpy as np
44import pandas as pd
46from ...core import cases, datasets, utilities
47from ...wrangler import shapers
48from ._biographies import _ROW, AddBiography, by_seat
49from ._roster import Roster
51# Names of the columns that the techniques add to the tables that they make
52# on the way to their results, which no table of cases or roster has.
53_CASE: str = '__case__'
54_FOUND: str = '__found__'
55_NAME: str = '__name__'
56_OTHER: str = '__other__'
57_PLACE: str = '__place__'
58_SEAT: str = '__seat__'
59_ROLES: dict[str, str] = {
60 'authors': 'judge_author',
61 'concurring': 'judge_concurred',
62 'dissenting': 'judge_dissented'}
63# The column of a table of votes with the Federal Judicial Center's number
64# for each judge, which labels a table of judges.
65_NID: str = 'judge_nid'
66# The starts of the names of the columns that `vote_table` makes for each
67# judge (with "judge" itself), which a table of cases does not have.
68_JUDGE_PREFIXES: tuple[str, ...] = ('judge_', 'colleagues_', 'vote_')
71@dataclasses.dataclass
72class CodePanels(amos.Munger):
73 """Adds the judges and the composition of each case's panel.
75 Each name in "panel_judges" is matched to a judge in a roster (see
76 `Roster`) with the case's court and year. The judges who are found are
77 listed in "panel_names" (as the roster names them, such as "Lynch, Sandra
78 Lea"), and "panel_found" is how many there are, which can be compared
79 with "panel_size". Each of them also has columns of its own, numbered by
80 the place of the judge's name in "panel_judges": "judge_name1" (the
81 judge's name as the Federal Judicial Center reports it) and "judge_nid1"
82 (the center's number for the judge), "judge_name2" and "judge_nid2", and
83 so on (as `add_biography` numbers the judges of cases), for
84 as many names as the longest panel lists. A name that is not matched
85 leaves its place missing, so the judges after it keep theirs, and a case
86 with fewer names has missing values in the rest. For each attribute in
87 the roster, "panel_{attribute}" is its mean among those judges:
88 "panel_woman" is the share of the judges who are women, and "panel_party"
89 is the mean party of the presidents who appointed them (-1 for a Democrat
90 and 1 for a Republican). So are
91 "panel_age", "panel_senior", "panel_designated", and
92 "panel_district_judge" (see `Roster.describe`). A mean is missing if no
93 judge was found (or none has the attribute).
95 If the cases have "authors", "concurring", or "dissenting" columns, the
96 judges they name are added as "author_name" (the first author found),
97 "concurring_names", and "dissenting_names".
99 The judges of each case are found as `add_biography` finds them (see
100 `AddBiography`), in a table with a row for each judge on each case, and
101 the case gets summaries of its rows (as the `merge_summary` technique of
102 `amos` adds them).
104 The names are read as a panel, not one at a time, before they are
105 matched (see `_resolve_panel`): a last name that fits more than one
106 judge of the court (such as "PRYOR" on a panel of the Eleventh Circuit,
107 which has had two) is the judge whose first name is another word of the
108 panel (as CourtListener's list of judges gives it: "Jill, Marcus,
109 Martin, Pryor") or whose full name is among the case's "authors",
110 "concurring", or "dissenting" ("JULIE CARNES, Circuit Judge:"). A word
111 that is only the first name of another judge of the panel is not a name
112 of its own. "panel_judges" is rewritten with the names as they are read,
113 and "panel_size" (if the cases have it) is counted again from them, each
114 judge once (or the number of the source's panel ids, if there are more
115 of them).
117 Needs "panel_judges", "court_num", and "year".
119 """
121 def munge(
122 self,
123 data: pd.DataFrame,
124 roster: Roster | pd.DataFrame | pathlib.Path | str | None = None,
125 **kwargs: Any) -> pd.DataFrame:
126 """Adds the judges and the composition of each panel.
128 Args:
129 data: the parsed cases.
130 roster: a roster, the table of one, or the path of a saved one.
131 Defaults to `None`, in which case the roster saved in
132 "judges" in `utilities.data_folder()` is used.
133 **kwargs: not used.
135 Returns:
136 The cases, with the new columns.
138 """
139 cases.require_columns(
140 data, ['panel_judges', 'court_num', 'year'], self.name)
141 judges = Roster.create(roster)
142 described = judges.described
143 data['panel_judges'] = _resolve_panels(data, judges)
144 seated = _named(
145 data, 'panel_judges', judges, ['judge', *described],
146 unmatched = True)
147 if 'panel_size' in data.columns:
148 named = seated.groupby(_CASE).size().reindex(
149 range(len(data)), fill_value = 0).to_numpy()
150 data['panel_size'] = np.maximum(named, _ids(data))
151 panel = seated[seated['nid'].notna()].astype({'nid': 'int64'})
152 panels = _summarize(
153 panel,
154 len(data),
155 {'judge': 'list', **dict.fromkeys(described, 'mean')},
156 count = _FOUND)
157 names = {
158 column: _summarize(
159 _named(data, column, judges, ['judge']),
160 len(data),
161 {'judge': 'list'})['judge'].tolist()
162 for column in _ROLES if column in data.columns}
163 data['panel_names'] = pd.Series(
164 panels['judge'].tolist(), index = data.index, dtype = object)
165 data['panel_found'] = panels[_FOUND].to_numpy()
166 for column, values in _numbered(seated, len(data)).items():
167 data[column] = pd.Series(values.array, index = data.index)
168 if 'authors' in names:
169 data['author_name'] = pd.Series(
170 [found[0] if found else None for found in names['authors']],
171 index = data.index, dtype = object)
172 for column in ('concurring', 'dissenting'):
173 if column in names:
174 data[f'{column}_names'] = pd.Series(
175 names[column], index = data.index, dtype = object)
176 for name in described:
177 data[f'panel_{name}'] = panels[name].to_numpy(dtype = 'float64')
178 return data
181@dataclasses.dataclass
182class CasesToVotes(shapers.Converter, amos.Shaper):
183 """Makes a table with one row for each judge on each case (`Votes`).
185 The table is for studying how judges vote, rather than what courts
186 decide. See `vote_table` for its columns. It replaces the table of cases,
187 so it should come after the techniques that code the cases (such as
188 `code_outcome`) and, like every shaper of `amos`, before the data is
189 split. Its "case_id" column can be the "groups" of a study, which keeps
190 the judges of a case together.
192 Like every shaper, it takes "label", "task", and "groups", which name the
193 label and groups of the table of votes (such as "vote_reversal" and
194 "case_id"). Without them, the dataset keeps the label and groups that it
195 has.
197 """
199 output: ClassVar[type[datasets.CourtData]] = datasets.Votes
201 def shape(
202 self,
203 data: pd.DataFrame,
204 roster: Roster | pd.DataFrame | pathlib.Path | str | None = None,
205 outcomes: Sequence[str] | str | None = None,
206 **kwargs: Any) -> pd.DataFrame:
207 """Returns a table with one row for each judge on each case.
209 Args:
210 data: the parsed cases.
211 roster: a roster, the table of one, or the path of a saved one.
212 Defaults to `None`, in which case the roster saved in
213 "judges" in `utilities.data_folder()` is used.
214 outcomes: names of the columns with the outcomes of the cases,
215 for which each judge's vote is added. Defaults to `None`, in
216 which case they are the columns whose names start with
217 "outcome_".
218 **kwargs: not used.
220 Returns:
221 The table of judges' votes.
223 """
224 return vote_table(
225 data, roster, outcomes = utilities.listify(outcomes) or None)
228@dataclasses.dataclass
229class DocketsToVotes(shapers.Converter, amos.Shaper):
230 """Makes a table with one row for each judge on each docket (`Votes`).
232 It is `cases_to_votes` for `Dockets` (see `vote_table`): each docket of a
233 case that consolidated several appeals has a row for each of the case's
234 judges, so each vote has the docket's columns (such as the Integrated
235 Database's, from `add_idb`). The rows are labeled by "vote_id" (the
236 docket's id and the judge's place, such as "4567890-2-1"), and have
237 "case_docket", "case_id", and "docket". A judge's vote on a case is counted
238 once for each of its dockets, so group by "case_id" (or keep one docket
239 of each case) to count each case once.
241 Like every shaper, it takes "label", "task", and "groups" (such as
242 "case_id", which keeps the votes of a case together).
244 """
246 output: ClassVar[type[datasets.CourtData]] = datasets.Votes
248 def shape(
249 self,
250 data: pd.DataFrame,
251 roster: Roster | pd.DataFrame | pathlib.Path | str | None = None,
252 outcomes: Sequence[str] | str | None = None,
253 **kwargs: Any) -> pd.DataFrame:
254 """Returns a table with one row for each judge on each docket.
256 Args:
257 data: the table of dockets, labeled by "case_docket".
258 roster: a roster, the table of one, or the path of a saved one.
259 Defaults to `None`, in which case the roster saved in
260 "judges" in `utilities.data_folder()` is used.
261 outcomes: names of the columns with the outcomes of the cases,
262 for which each judge's vote is added. Defaults to `None`, in
263 which case they are the columns whose names start with
264 "outcome_".
265 **kwargs: not used.
267 Raises:
268 KeyError: if `data` lacks "case_id" or a column that is needed.
270 Returns:
271 The table of judges' votes.
273 """
274 cases.require_columns(
275 data, ['case_id'], repr(self.name),
276 hint = 'Make the dockets with "cases_to_dockets"')
277 return vote_table(
278 data, roster, outcomes = utilities.listify(outcomes) or None,
279 label = 'case_docket')
282@dataclasses.dataclass
283class VotesToCases(shapers.Converter, amos.Shaper):
284 """Makes a table of votes a table of cases again (`Cases`).
286 It undoes `cases_to_votes`: the rows of each case become one row,
287 labeled by "case_id" as a table of parsed cases is, with the case's
288 columns in their order. The columns that `cases_to_votes` makes for
289 each judge are removed: "judge", and those whose names begin with
290 "judge_", "colleagues_", or "vote_" (such as "judge_party",
291 "colleagues_party", "judge_dissented", and "vote_reversal"). Every other
292 column is the case's, so each case keeps the value of its first row
293 (for votes made from dockets, "case_docket" and "docket" are removed too,
294 and other columns keep the first docket's values). A
295 case with no judge who was found in the roster has no rows in the table
296 of votes, so it is not in the table of cases either. To summarize the
297 judges of each case instead, use `code_panels` on the cases, or
298 `group_rows` on the votes.
300 Like every shaper, it takes "label", "task", and "groups". Without them,
301 a label of votes (such as "vote_reversal") becomes the outcome that it
302 was made from ("outcome_reversal"), and the groups are those of the
303 votes other than "case_id" and the judges' columns.
305 """
307 output: ClassVar[type[datasets.CourtData]] = datasets.Cases
309 """ Public Methods """
311 def apply(
312 self,
313 item: amos.Dataset,
314 *,
315 label: str | None = None,
316 groups: Sequence[str] | str | None = None,
317 **kwargs: Any) -> amos.Dataset:
318 """Makes the table of votes of `item` a table of cases.
320 Args:
321 item: the dataset of votes.
322 label: name of the label of the cases. Defaults to `None`, in
323 which case it is the outcome that the label of the votes was
324 made from, if it was made from one, and otherwise the label
325 of `item`.
326 groups: names of the groups of the cases. Defaults to `None`, in
327 which case they are the groups of `item` that are columns of
328 the cases.
329 **kwargs: "task", and parameters for `shape`.
331 Returns:
332 The dataset of cases.
334 """
335 if label is None and item.label is not None:
336 outcome = 'outcome_' + str(item.label).removeprefix('vote_')
337 if (str(item.label).startswith('vote_') 337 ↛ 340line 337 didn't jump to line 340 because the condition on line 337 was always true
338 and outcome in item.data.columns):
339 label = outcome
340 if groups is None: 340 ↛ 344line 340 didn't jump to line 344 because the condition on line 340 was always true
341 groups = [
342 group for group in item.groups
343 if group != 'case_id' and not _is_judge_column(group)]
344 return super().apply(item, label = label, groups = groups, **kwargs)
346 def shape(self, data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame:
347 """Returns a table with one row for each case.
349 Args:
350 data: the table of votes (see `vote_table`).
351 **kwargs: not used.
353 Raises:
354 KeyError: if `data` lacks "case_id".
356 Returns:
357 The table of cases, labeled by "case_id".
359 """
360 cases.require_columns(data, ['case_id'], repr(self.name))
361 judged = [
362 c for c in data.columns
363 if _is_judge_column(c) or c in ('case_docket', 'docket')]
364 table = data.drop(columns = judged).drop_duplicates(subset = 'case_id')
365 return table.set_index('case_id')
368@dataclasses.dataclass
369class CasesToJudges(shapers.Converter, amos.Shaper):
370 """Makes a table with one row for each judge (`Judges`).
372 The rows of each judge in a table of votes (see `vote_table`) become one
373 row, labeled by "judge_nid" (the Federal Judicial Center's number for the
374 judge), with "judge" (the judge's name), "cases" (the number of the
375 judge's votes), and the means of the columns of numbers and booleans, as
376 `group_rows` takes them (see `courtpy.shapers.summarize`). The mean of a
377 boolean is a share: "vote_reversal" is the share of the judge's votes to
378 reverse, "judge_dissented" the share of the judge's cases in which the
379 judge dissented, "type_criminal" the share of the judge's cases that
380 were criminal, "party_type_corporation" (if the parties have types) the
381 share with a corporation as a party, and "judge_age" the judge's mean
382 age when deciding them. Nothing about any one case is kept: columns of
383 text (such as the cases' names and dates) and ids (such as "case_id")
384 are left out, unless "keep" or "how" names them.
386 If the data is a table of cases (it has no "judge_nid" column), the
387 table of votes is made first, as `cases_to_votes` makes it, with
388 "roster" and "outcomes".
390 Like every shaper, it takes "label", "task", and "groups". Without
391 "groups", the table has none, since the groups of votes (such as
392 "case_id") are not columns of it. Without "task", the task is inferred
393 from the label, since a label that was a vote is now a share.
395 """
397 output: ClassVar[type[datasets.CourtData]] = datasets.Judges
399 """ Public Methods """
401 def apply(
402 self,
403 item: amos.Dataset,
404 *,
405 task: str | None = None,
406 groups: Sequence[str] | str | None = None,
407 **kwargs: Any) -> amos.Dataset:
408 """Makes the table of `item` a table of judges.
410 Args:
411 item: the dataset of votes or of cases.
412 task: "classify" or "regress". Defaults to `None`, in which case
413 it is inferred from the label (see `amos.Dataset.infer_task`).
414 groups: names of the groups of the judges. Defaults to `None`,
415 for none.
416 **kwargs: "label", and parameters for `shape`.
418 Returns:
419 The dataset of judges.
421 """
422 dataset = super().apply(
423 item, task = task, groups = [] if groups is None else groups,
424 **kwargs)
425 if task is None and dataset.label is not None:
426 dataset.task = dataset.infer_task()
427 return dataset
429 def shape(
430 self,
431 data: pd.DataFrame,
432 roster: Roster | pd.DataFrame | pathlib.Path | str | None = None,
433 outcomes: Sequence[str] | str | None = None,
434 *,
435 how: Mapping[str, Any] | None = None,
436 keep: Sequence[str] | str | None = None,
437 count: str | None = 'cases',
438 **kwargs: Any) -> pd.DataFrame:
439 """Returns a table with one row for each judge.
441 Args:
442 data: a table of votes (see `vote_table`), or the parsed cases.
443 roster: for a table of cases, a roster, the table of one, or the
444 path of a saved one. Defaults to `None`, in which case the
445 roster saved in "judges" in `utilities.data_folder()` is
446 used.
447 outcomes: for a table of cases, names of the columns with the
448 outcomes of the cases, for which each judge's vote is added.
449 Defaults to `None`, in which case they are the columns whose
450 names start with "outcome_".
451 how: the summaries of columns, by their names, which take the
452 place of the means or add columns, such as
453 {"court": "list"}. Defaults to `None`.
454 keep: columns of text to keep, with the first value of each
455 judge's votes. Defaults to `None`, which keeps "judge".
456 count: name of the column with the number of each judge's votes,
457 or `None` for no such column. Defaults to "cases".
458 **kwargs: not used.
460 Raises:
461 KeyError: if `data` lacks a column that is needed or named.
463 Returns:
464 The table of judges, labeled by "judge_nid".
466 """
467 votes = data if _NID in data.columns else vote_table(
468 data, roster, outcomes = utilities.listify(outcomes) or None)
469 votes = shapers.add_party_type_flags(votes)
470 kept = ['judge'] if keep is None else utilities.listify(keep)
471 table = shapers.summarize(
472 votes, [_NID], how = how, keep = kept, count = count)
473 first = [c for c in ('judge', count) if c is not None and c in table]
474 return table[[*first, *[c for c in table.columns if c not in first]]]
477""" Public Functions """
480def panel_compositions(
481 data: pd.DataFrame,
482 size: int = 3) -> pd.Series:
483 """Returns the composition of each case's panel by its judges' parties.
485 The composition names the party of the president who appointed each
486 judge, Democratic ("D") ones first: "DDD", "DDR", "DRR", and "RRR" for a
487 panel of three (see `republican_appointees`).
489 Args:
490 data: the cases, with "judge_party1" and so on (from
491 `add_biography`) or "panel_party" and "panel_found" (from
492 `code_panels`).
493 size: the number of judges on the panels to describe. Defaults to 3.
495 Returns:
496 The composition of each case's panel, as an ordered category from all
497 Democratic appointees to all Republican ones, missing for a case
498 whose panel is not of `size` judges whose parties are known.
500 """
501 found = republican_appointees(data, size)
502 names = ['D' * (size - r) + 'R' * r for r in range(size + 1)]
503 # The number of Republican appointees is the place of the composition
504 # among `names`, and -1 marks a missing one.
505 codes = found.fillna(-1).astype('int64').to_numpy()
506 return pd.Series(
507 pd.Categorical.from_codes(
508 codes, categories = pd.Index(names), ordered = True),
509 index = data.index, name = 'panel_composition')
512def republican_appointees(
513 data: pd.DataFrame,
514 size: int = 3) -> pd.Series:
515 """Returns how many judges of each case's panel a Republican appointed.
517 The judges' parties are those of the presidents who appointed them (-1
518 for a Democrat and 1 for a Republican). They are read from each seat's
519 "judge_party1", "judge_party2", and so on (which `add_biography` adds to
520 cases), or else from "panel_party" (the mean party) and "panel_found"
521 (the number of judges found), which `code_panels` adds.
523 Args:
524 data: the cases.
525 size: the number of judges on the panels to count. Defaults to 3.
527 Raises:
528 KeyError: if `data` has neither the parties of the seats nor
529 "panel_party" and "panel_found".
531 Returns:
532 The number of Republican appointees on each case's panel, as whole
533 numbers, missing for a case whose panel is not of `size` judges
534 whose parties are all known (as for a judge appointed by a
535 president of another party).
537 """
538 seats = [f'judge_party{n}' for n in range(1, size + 1)]
539 if all(c in data.columns for c in seats):
540 parties = data[seats].apply(pd.to_numeric, errors = 'coerce')
541 complete = parties.isin([-1, 1]).all(axis = 1)
542 # A panel with more seats than `size` is a panel of another size.
543 extra = f'judge_party{size + 1}'
544 if extra in data.columns:
545 complete &= pd.to_numeric(data[extra], errors = 'coerce').isna()
546 counted = (parties == 1).sum(axis = 1)
547 seated: pd.Series = counted.where(complete).astype('Int64')
548 return seated.rename('republican_appointees')
549 if 'panel_party' in data.columns and 'panel_found' in data.columns:
550 party = pd.to_numeric(data['panel_party'], errors = 'coerce')
551 found = pd.to_numeric(data['panel_found'], errors = 'coerce')
552 counted = (found * (party + 1) / 2).round()
553 averaged: pd.Series = counted.where(found == size).astype('Int64')
554 return averaged.rename('republican_appointees')
555 message = (
556 f'counting the Republican appointees of panels needs {seats} (from '
557 f'add_biography) or "panel_party" and "panel_found" (from '
558 f'code_panels)')
559 raise KeyError(message)
562def vote_table(
563 data: pd.DataFrame,
564 roster: Roster | pd.DataFrame | pathlib.Path | str | None = None,
565 *,
566 outcomes: Sequence[str] | None = None,
567 label: str = 'case_id') -> pd.DataFrame:
568 """Returns a table with one row for each judge on each case.
570 Each name in "panel_judges" is matched to a judge in a roster (see
571 `Roster`), and each judge who is found gets a row, labeled by the case's
572 id and the judge's place among them (such as "4567890-2"). Cases with no
573 judge who is found are left out. The table is made as `amos` reshapes
574 and merges data: the `lists_to_rows` technique makes a row for each name,
575 and `add_biography` (see `AddBiography`) adds the judge that each
576 name refers to. The columns are:
578 | Column | Meaning |
579 | --- | --- |
580 | `case_id` | The case's id, which the rows of its judges share. |
581 | `judge`, `judge_nid` | The judge's name and number in the roster. |
582 | (the columns of `data`) | The case's columns, repeated for each judge. |
583 | `judge_{attribute}` | Each attribute of the judge (see `Roster.describe`), such as `judge_party`, `judge_woman`, and `judge_age`. |
584 | `colleagues_{attribute}` | The mean of the attribute among the other judges of the panel who were found. Missing if there are none. |
585 | `judge_author`, `judge_concurred`, `judge_dissented` | Whether the judge wrote the opinion of the court, and wrote or joined a concurrence or a dissent. A judge who concurred in part and dissented in part did both. |
586 | `vote_{outcome}` | For each outcome of the case, how the judge voted: the outcome itself, or its opposite if the judge dissented. So with "outcome_reversal", `vote_reversal` is whether the judge voted to reverse. Missing if the outcome is. |
588 Args:
589 data: the parsed cases, which need "panel_judges", "court_num", and
590 "year". "authors", "concurring", and "dissenting" are used if
591 they are there.
592 roster: a roster, the table of one, or the path of a saved one.
593 Defaults to `None`, in which case the roster saved in "judges" in
594 `utilities.data_folder()` is used.
595 outcomes: names of the columns with the outcomes of the cases.
596 Defaults to `None`, in which case they are the columns whose
597 names start with "outcome_".
598 label: the name of the column of the labels of the rows of `data`
599 (which the rows of each case's judges share). Defaults to
600 "case_id". For a table of dockets, it is "case_docket", and
601 their "case_id" column is kept.
603 Raises:
604 KeyError: if `data` lacks a column that is needed or named.
606 Returns:
607 The table, labeled by "vote_id".
609 """
610 cases.require_columns(
611 data, ['panel_judges', 'court_num', 'year'], 'a table of votes')
612 if outcomes is None:
613 outcomes = [c for c in data.columns if str(c).startswith('outcome_')]
614 cases.require_columns(data, outcomes, 'a table of votes')
615 judges = Roster.create(roster)
616 described = judges.described
617 panel = _named(data, 'panel_judges', judges, ['judge', *described])
618 origins = panel[_CASE].to_numpy()
619 labels = data.index[origins]
620 places = (panel.groupby(_CASE).cumcount() + 1).tolist()
621 index = pd.Index(
622 [f'{row}-{place}' for row, place in zip(
623 labels, places, strict = True)],
624 name = 'vote_id', dtype = object)
625 votes = pd.DataFrame({
626 label: labels.to_numpy(),
627 'judge': panel['judge'].to_numpy(),
628 'judge_nid': panel['nid'].to_numpy()}, index = index)
629 numbers = pd.concat([
630 panel[described].add_prefix('judge_'),
631 _colleagues(panel, described).add_prefix('colleagues_')], axis = 1)
632 made = numbers[[
633 f'{kind}_{name}' for name in described
634 for kind in ('judge', 'colleagues')]].astype('float64')
635 made.index = index
636 # Whether each judge is one of the judges that each kind of opinion
637 # names, which are found in the roster as the judges of the panel are.
638 keys = pd.MultiIndex.from_arrays([origins, votes['judge_nid']])
639 for column, role in _ROLES.items():
640 made[role] = False
641 if column in data.columns:
642 acted = _named(data, column, judges)
643 made[role] = keys.isin(
644 pd.MultiIndex.from_arrays([acted[_CASE], acted['nid']]))
645 repeated = data.iloc[origins].drop(columns = [
646 c for c in data.columns if c in votes.columns or c in made.columns])
647 repeated.index = index
648 table = pd.concat([votes, repeated, made], axis = 1)
649 dissented = table['judge_dissented'].astype('boolean')
650 for column in outcomes:
651 name = str(column).removeprefix('outcome_')
652 table[f'vote_{name}'] = table[column].astype('boolean') ^ dissented
653 return table
656""" Private Functions """
659def _colleagues(panel: pd.DataFrame, columns: Sequence[str]) -> pd.DataFrame:
660 """Returns the means of columns among the other judges of each case.
662 Each judge is paired with every other judge of the same case, and the
663 means are taken of the pairs of each judge.
665 Args:
666 panel: a table with a row for each judge on each case (as `_named`
667 returns it), labeled 0, 1, 2, and so on.
668 columns: names of the columns of numbers to take the means of.
670 Returns:
671 A table with a row for each row of `panel`, in order, and a column
672 for each of `columns` with the mean of the values that are known
673 among the other judges of the row's case. It is missing if there
674 are no other judges, or none has a value.
676 """
677 place = panel.groupby(_CASE).cumcount()
678 judges = pd.DataFrame({_CASE: panel[_CASE], _PLACE: place})
679 pairs = judges.merge(
680 panel[[_CASE, *columns]].assign(**{_OTHER: place}), on = _CASE)
681 pairs = pairs[pairs[_PLACE] != pairs[_OTHER]]
682 means = pairs.groupby([_CASE, _PLACE])[list(columns)].mean()
683 others: pd.DataFrame = means.reindex(
684 pd.MultiIndex.from_frame(judges)).reset_index(drop = True)
685 return others
688def _is_judge_column(column: Any) -> bool:
689 """Returns whether a column of a table of votes is about one judge.
691 Args:
692 column: the name of the column.
694 Returns:
695 Whether it is "judge" or begins with one of `_JUDGE_PREFIXES`.
697 """
698 name = str(column)
699 return name == 'judge' or name.startswith(_JUDGE_PREFIXES)
702def _named(
703 data: pd.DataFrame,
704 column: str,
705 roster: Roster,
706 columns: Sequence[str] = (),
707 *,
708 unmatched: bool = False) -> pd.DataFrame:
709 """Finds the judges that a column of the cases names.
711 The `lists_to_rows` technique of `amos` makes a row for each name that a
712 case lists, and `AddBiography` finds the judge that each name refers to.
714 Args:
715 data: the parsed cases, with "court_num" and "year".
716 column: name of the column that lists judges' names: text with
717 "; " between the names, as the federal rules write them, or
718 lists of names (as `split_values` makes them).
719 roster: the roster to find the judges in.
720 columns: the columns to add for each judge, other than "nid" (see
721 `AddBiography`). Defaults to an empty `tuple`.
722 unmatched: whether to keep the names that are not matched, with
723 missing values. Defaults to `False`.
725 Returns:
726 A table with a row for each judge who was found (and, with
727 `unmatched`, each name that was not), in the order of the cases
728 and then of the names, with each judge once for a case. Its
729 columns are the position of the judge's case in `data`, the
730 place of the judge's name in the case's list (1 for the first),
731 the judge's "nid" (missing for a name that was not matched), and
732 `columns`, and its rows are labeled 0, 1, 2, and so on.
734 """
735 names = pd.DataFrame({
736 _CASE: np.arange(len(data)),
737 _NAME: pd.Series(data[column].tolist(), dtype = object),
738 'court_num': pd.Series(data['court_num'].tolist(), dtype = object),
739 'year': pd.Series(data['year'].tolist(), dtype = object)})
740 listed = amos.shapers.ListsToRows().shape(
741 names, column = _NAME, separator = cases._SEPARATOR.strip())
742 # A case with no names has one row, whose name is missing, so each name's
743 # place is its row among its case's.
744 listed[_SEAT] = listed.groupby(_CASE).cumcount() + 1
745 merged = AddBiography().apply(
746 amos.Dataset(listed),
747 source = roster,
748 name = _NAME,
749 columns = ['nid', *columns],
750 prefix = None,
751 indicator = _FOUND).data
752 repeated = merged[_FOUND] & merged.duplicated([_CASE, 'nid'])
753 kept = (merged[_FOUND] | (unmatched & merged[_NAME].notna())) & ~repeated
754 found: pd.DataFrame = merged[kept][[_CASE, _SEAT, 'nid', *columns]]
755 return found.astype(
756 {'nid': 'Int64' if unmatched else 'int64'}).reset_index(drop = True)
759def _ids(data: pd.DataFrame) -> np.ndarray:
760 """Returns the number of the source's panel ids of each case.
762 Args:
763 data: the parsed cases.
765 Returns:
766 The number of "panel_ids" of each case (0 without the column).
768 """
769 if 'panel_ids' not in data.columns:
770 return np.zeros(len(data), dtype = 'int64')
771 return np.array(
772 [len(_name_list(value)) for value in data['panel_ids']],
773 dtype = 'int64')
776def _name_list(value: Any) -> list[str]:
777 """Returns the names in a cell of a column of names.
779 Args:
780 value: names as the federal rules write them (text with "; "
781 between them), a list of them, or a missing value.
783 Returns:
784 The names, without blanks.
786 """
787 if isinstance(value, list | tuple):
788 names = [str(name) for name in value]
789 elif isinstance(value, str):
790 names = value.split(cases._SEPARATOR)
791 else:
792 return []
793 return [name.strip() for name in names if name and name.strip()]
796def _numbered(panel: pd.DataFrame, size: int) -> pd.DataFrame:
797 """Returns the name and number of each judge of each case, in columns.
799 Args:
800 panel: a table with a row for each name on each case, with "judge"
801 and "nid" (as `_named` returns it with `unmatched`).
802 size: the number of cases.
804 Returns:
805 A table with a row for each case, in order, and "judge_name1",
806 "judge_nid1", "judge_name2", "judge_nid2", and so on, numbered by
807 the places of the names in the cases' lists, for as many as the
808 longest list has (see `by_seat`). A name that was not matched
809 leaves its place missing. It has no columns if `panel` has no
810 rows.
812 """
813 seated = pd.DataFrame({
814 _ROW: panel[_CASE].to_numpy(),
815 _SEAT: panel[_SEAT].to_numpy(),
816 'judge_name': panel['judge'].astype(object).array,
817 'judge_nid': panel['nid'].astype('Int64').array})
818 return by_seat(seated, size)
821def _resolve_panel(
822 names: list[str],
823 hints: list[str],
824 roster: Roster,
825 court_num: int | None,
826 year: int | None) -> list[str]:
827 """Returns the names of a panel as they are read together.
829 A word that fits no judge of its own but is a word of the name of a
830 judge whose last name is another of the names (the first name, the first
831 name and middle initial run together, as "ROBERTA" for "Robert A.", or a
832 word of a last name of several words; see `Roster.name_words`) belongs
833 to that name, and is left out. A last name that fits more than one judge is
834 written as the full name of the one whose first name is such a word, or
835 whose full name is one of `hints`, if exactly one is.
837 Args:
838 names: the names of the panel, as the federal rules find them.
839 hints: other names of judges of the case (its authors, and the
840 judges who concurred or dissented).
841 roster: the roster to find the judges in.
842 court_num: the number of the case's court.
843 year: the year of the case.
845 Returns:
846 The names, with the ambiguous names that the others resolve written
847 in full, and without the words that were first names.
849 """
850 fits = [roster.candidates(name, court_num, year) for name in names]
851 loose = [
852 place for place, found in enumerate(fits) if not found
853 and ' ' not in names[place].strip()]
854 words = {place: names[place].strip().upper() for place in loose}
855 hinted = {
856 roster.nids([row])[0] for hint in hints
857 for row in [roster.match(hint, court_num, year)] if row is not None}
858 used: set[int] = set()
859 resolved = list(names)
860 for place, found in enumerate(fits):
861 if not found:
862 continue
863 given = {
864 row: {
865 spot for spot in loose
866 if spot not in used and words[spot] in roster.name_words(row)}
867 for row in found}
868 if len(found) > 1:
869 chosen = [
870 row for row in found
871 if given[row] or roster.nids([row])[0] in hinted]
872 if len(chosen) != 1:
873 continue
874 row = chosen[0]
875 resolved[place] = roster.full_name(row)
876 else:
877 row = found[0]
878 used |= given[row]
879 return [name for place, name in enumerate(resolved) if place not in used]
882def _resolve_panels(data: pd.DataFrame, roster: Roster) -> pd.Series:
883 """Returns the names of each case's panel as they are read together.
885 Args:
886 data: the parsed cases, with "panel_judges", "court_num", and
887 "year", and any of "authors", "concurring", and "dissenting".
888 roster: the roster to find the judges in.
890 Returns:
891 The names of each panel (see `_resolve_panel`), as text with "; "
892 between them, or a missing value for a panel with none.
894 """
895 roles = [column for column in _ROLES if column in data.columns]
896 courts = pd.to_numeric(data['court_num'], errors = 'coerce')
897 years = pd.to_numeric(data['year'], errors = 'coerce')
898 rows = zip(
899 data['panel_judges'].tolist(), courts.tolist(), years.tolist(),
900 *(data[column].tolist() for column in roles), strict = True)
901 resolved = []
902 for panel, court, year, *named in rows:
903 names = _name_list(panel)
904 if names:
905 hints = [name for value in named for name in _name_list(value)]
906 names = _resolve_panel(
907 names, hints, roster,
908 None if pd.isna(court) else int(court),
909 None if pd.isna(year) else int(year))
910 resolved.append(cases._SEPARATOR.join(names) if names else None)
911 return pd.Series(resolved, index = data.index, dtype = object)
914def _summarize(
915 named: pd.DataFrame,
916 size: int,
917 how: Mapping[str, str],
918 count: str | None = None) -> pd.DataFrame:
919 """Returns summaries of the judges of each case.
921 The `merge_summary` technique of `amos` adds summaries of the rows of
922 another table that have the same keys: here, of the judges of each case.
924 Args:
925 named: a table with a row for each judge on each case (as `_named`
926 returns it).
927 size: the number of cases.
928 how: the summary to take of each column of `named` to summarize,
929 such as "mean" or "list", by the name of the column.
930 count: name of a column to make with the number of judges of each
931 case. Defaults to `None`, which makes no such column.
933 Returns:
934 A table with a row for each case, in order, and the summaries of its
935 judges as columns. A case with no judges has an empty `list` for
936 a "list", no judges for `count`, and other summaries that are
937 missing.
939 """
940 table = amos.Dataset(pd.DataFrame({_CASE: np.arange(size)}))
941 if named.empty:
942 # There is nothing to summarize, so every summary is missing.
943 blank = pd.DataFrame(
944 np.nan, index = table.data.index,
945 columns = [*how, *([count] if count else [])])
946 table.replace(pd.concat([table.data, blank], axis = 1))
947 else:
948 amos.mergers.MergeSummary().apply(
949 table, source = named, on = _CASE, how = dict(how), count = count)
950 summaries = table.data.drop(columns = _CASE)
951 for column, summary in how.items():
952 if summary == 'list':
953 summaries[column] = pd.Series(
954 [found if isinstance(found, list) else []
955 for found in summaries[column].tolist()],
956 index = summaries.index, dtype = object)
957 if count is not None:
958 summaries[count] = summaries[count].fillna(0).astype('int64')
959 return summaries