Coverage for src/courtpy/references/judges/_circuits.py: 89%
105 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"""Adds the makeup of the whole circuit of each case on the day it was decided.
3Contents:
4 AddCircuit: adds the ideology of the active judges of each case's
5 circuit when the case was decided.
6 _COURT_OF_APPEALS: the Federal Judicial Center's name for the type of a
7 court of appeals.
8 _SCORES: the columns of a roster that `AddCircuit` summarizes, by the
9 word that names them in the added columns.
11"""
13from __future__ import annotations
15import dataclasses
16import warnings
17from collections.abc import Sequence
18from typing import Any
20import amos
21import numpy as np
22import pandas as pd
24from ...core import cases, utilities
25from .. import courts
26from ._biographies import find_roster
27from ._roster import Roster
29_COURT_OF_APPEALS: str = 'U.S. Court of Appeals'
30_SCORES: dict[str, str] = {'party': 'party', 'jcs': 'jcs'}
33@dataclasses.dataclass
34class AddCircuit(amos.Merger):
35 """Adds the ideology of the active judges of each case's circuit.
37 For a case of a court of appeals, the circuit is the court's own; for a
38 case of a district court, it is the circuit of the court of appeals that
39 hears its appeals (see `courtpy.courts.circuits`). The judges of the
40 circuit are those of its court of appeals in a roster (see `Roster`) who
41 were active on the day the case was decided: they had been appointed,
42 had not left the court, and had not taken senior status (senior judges
43 do not sit on the court en banc). Their scores are summarized:
45 | Column | Meaning |
46 | --- | --- |
47 | `circuit_median_party` | The median party of the presidents who appointed them (-1 for Democratic and 1 for Republican). |
48 | `circuit_total_party` | The sum of those parties, which is how many more were appointed by Republicans than by Democrats. |
49 | `circuit_median_jcs` | The median of their Judicial Common Space scores (higher is more conservative). |
50 | `circuit_total_jcs` | The sum of their scores. |
51 | `circuit_judges` | How many judges were active. |
53 The scores of the Judicial Common Space are added if the roster has them
54 (make it with `Roster.from_fjc(jcs = True)`). A judge without a score is
55 left out of its summaries. A case whose circuit or date is not known (or
56 whose circuit had no active judge in the roster) gets missing values.
58 Like every merger of `amos`, it never adds, removes, or reorders rows,
59 and records how many rows it matched in the dataset's history. It takes
60 these parameters:
62 | Parameter | Meaning |
63 | --- | --- |
64 | `source` | The roster: the path of a saved one, a roster, or the table of one. Without it, the roster saved in "judges" in `utilities.data_folder()` is used. |
65 | `columns` | The scores to summarize: "party", "jcs", or both (the default, if the roster has "jcs"). |
66 | `date` | The column with the date each case was decided. It is "date_filed" unless another is set. |
67 | `court_num`, `court` | The columns with courtpy's number for each case's court and CourtListener's id for it. They are "court_num" and "court" unless others are set. |
68 | `prefix` | Text to put before the names of the added columns. It is "circuit_" unless another is set. |
70 """
72 """ Public Methods """
74 def apply(
75 self,
76 item: amos.Dataset,
77 *,
78 source: Any = None,
79 columns: Sequence[str] | str | None = None,
80 date: str = 'date_filed',
81 court_num: str = 'court_num',
82 court: str = 'court',
83 prefix: str | None = 'circuit_',
84 **kwargs: Any) -> amos.Dataset:
85 """Adds the ideology of the active judges of each case's circuit.
87 Args:
88 item: the dataset of cases (or of votes).
89 source: the roster: a roster, the table of one, or the path of a
90 saved one. Defaults to `None`, in which case the roster saved
91 in "judges" in `utilities.data_folder()` is used.
92 columns: the scores to summarize: "party", "jcs", or both.
93 Defaults to `None`, for both if the roster has "jcs", and
94 otherwise "party" (with a warning).
95 date: the column of `item` with the date each case was decided.
96 Defaults to "date_filed".
97 court_num: the column of `item` with courtpy's number for each
98 case's court. Defaults to "court_num".
99 court: the column of `item` with CourtListener's id for each
100 case's court. Defaults to "court".
101 prefix: text to put before the names of the added columns.
102 Defaults to "circuit_".
103 **kwargs: not used.
105 Raises:
106 KeyError: if `item` lacks `date`, or one of `columns` is not a
107 score or not in the roster.
108 ValueError: if an added column would have the name of a column of
109 the data.
111 Returns:
112 The dataset with the added columns.
114 """
115 prefix = prefix or ''
116 data = item.data
117 cases.require_columns(data, [date], repr(self.name))
118 roster = find_roster(source, self.clerk)
119 chosen = self._choose(roster, columns)
120 circuit = courts.circuits(data, court_num = court_num, court = court)
121 when = pd.to_datetime(data[date], errors = 'coerce').to_numpy(
122 dtype = 'datetime64[D]')
123 judges = _active_judges(roster)
124 added = {
125 f'{prefix}{kind}_{_SCORES[score]}': np.full(len(data), np.nan)
126 for score in chosen for kind in ('median', 'total')}
127 counts = np.zeros(len(data), dtype = 'int64')
128 known = circuit.notna().to_numpy() & ~np.isnat(when)
129 numbers = circuit.to_numpy(dtype = 'float64', na_value = np.nan)
130 for number in np.unique(numbers[known]):
131 rows = np.flatnonzero(known & (numbers == number))
132 serving = judges[judges['court_num'] == number]
133 if serving.empty: 133 ↛ 134line 133 didn't jump to line 134 because the condition on line 133 was never true
134 continue
135 days, place = np.unique(when[rows], return_inverse = True)
136 active = _is_active(serving, days)
137 counts[rows] = active.sum(axis = 1)[place]
138 for score in chosen:
139 values = serving[score].to_numpy(dtype = 'float64')
140 medians, totals = _summaries(active, values)
141 added[f'{prefix}median_{_SCORES[score]}'][rows] = medians[place]
142 added[f'{prefix}total_{_SCORES[score]}'][rows] = totals[place]
143 table = pd.DataFrame(added, index = data.index)
144 table[f'{prefix}judges'] = pd.array(counts, dtype = 'Int64')
145 table.loc[~known, f'{prefix}judges'] = pd.NA
146 clashes = [c for c in table.columns if c in data.columns]
147 if clashes: 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true
148 message = (
149 f'{self.name!r} would add columns named {clashes}, which the '
150 f'data already has: set "prefix" to tell them apart')
151 raise ValueError(message)
152 item.replace(pd.concat([data, table], axis = 1))
153 item.record(
154 self.name,
155 rows = len(data),
156 matched = int((counts > 0).sum()),
157 created = list(table.columns))
158 return item
160 def match(
161 self,
162 data: pd.DataFrame,
163 other: pd.DataFrame, # noqa: ARG002
164 **kwargs: Any) -> Any:
165 """Returns no row of a roster for any case.
167 The active judges of a circuit are many rows of a roster, which
168 `apply` summarizes, rather than one row that each case matches.
170 Args:
171 data: the cases.
172 other: the table of a roster.
173 **kwargs: not used.
175 Returns:
176 -1 for each case.
178 """
179 return np.full(len(data), -1, dtype = 'int64')
181 """ Private Methods """
183 def _choose(
184 self,
185 roster: Roster,
186 columns: Sequence[str] | str | None) -> list[str]:
187 """Returns the scores to summarize.
189 Args:
190 roster: the roster.
191 columns: the scores that are named, or `None`.
193 Raises:
194 KeyError: if one of `columns` is not a score or not in the
195 roster.
197 Returns:
198 The scores.
200 """
201 if columns is None:
202 if 'jcs' in roster.data.columns:
203 return ['party', 'jcs']
204 warnings.warn(
205 f'{self.name!r} adds no Judicial Common Space scores, because '
206 f'the roster has none: make it with '
207 f'Roster.from_fjc(jcs = True)',
208 category = amos.AmosWarning,
209 stacklevel = 3)
210 return ['party']
211 chosen = utilities.listify(columns)
212 unknown = [c for c in chosen if c not in _SCORES]
213 if unknown: 213 ↛ 216line 213 didn't jump to line 216 because the condition on line 213 was always true
214 message = f'{self.name!r} summarizes {list(_SCORES)}, not {unknown}'
215 raise KeyError(message)
216 cases.require_columns(
217 roster.data, chosen, 'the roster for ' + repr(self.name),
218 hint = 'Make the roster with Roster.from_fjc(jcs = True)')
219 return chosen
222""" Private Functions """
225def _active_judges(roster: Roster) -> pd.DataFrame:
226 """Returns the service of each judge of a court of appeals, as dates.
228 A roster that has no dates (only years) has its service begin on the
229 first day of its first year, and end (or turn senior) on the last day of
230 its last year.
232 Args:
233 roster: the roster.
235 Returns:
236 A table with a row for each judge's service on a court of appeals,
237 with "court_num", "start", "end", and "senior" (as days, missing
238 if the service has not ended or the judge has not taken senior
239 status), and the roster's "party" and "jcs" (if it has them).
241 """
242 table = roster.data
243 if 'court_type' in table.columns: 243 ↛ 245line 243 didn't jump to line 245 because the condition on line 243 was always true
244 table = table[table['court_type'] == _COURT_OF_APPEALS]
245 table = table[table['court_num'].notna()]
246 service = pd.DataFrame({
247 'court_num': table['court_num'].astype('float64').to_numpy()})
248 for name, fallback in (
249 ('start', '-01-01'), ('end', '-12-31'), ('senior', '-12-31')):
250 if f'{name}_date' in table.columns: 250 ↛ 253line 250 didn't jump to line 253 because the condition on line 250 was always true
251 dates = pd.to_datetime(table[f'{name}_date'], errors = 'coerce')
252 else:
253 years = (
254 pd.to_numeric(table[f'{name}_year'], errors = 'coerce')
255 if f'{name}_year' in table.columns
256 else pd.Series(np.nan, index = table.index))
257 dates = pd.to_datetime(
258 years.astype('Int64').astype('string') + fallback,
259 errors = 'coerce')
260 service[name] = dates.to_numpy(dtype = 'datetime64[D]')
261 for score in _SCORES:
262 if score in table.columns:
263 service[score] = pd.to_numeric(
264 table[score], errors = 'coerce').to_numpy()
265 return service
268def _is_active(serving: pd.DataFrame, days: np.ndarray) -> np.ndarray:
269 """Returns which judges were active on each day.
271 Args:
272 serving: the service of the judges of one court (see
273 `_active_judges`).
274 days: the days.
276 Returns:
277 A table of booleans with a row for each day and a column for each
278 judge: whether the judge had begun to serve, had not stopped,
279 and had not taken senior status.
281 """
282 day = days[:, None]
283 start = serving['start'].to_numpy(dtype = 'datetime64[D]')[None, :]
284 end = serving['end'].to_numpy(dtype = 'datetime64[D]')[None, :]
285 senior = serving['senior'].to_numpy(dtype = 'datetime64[D]')[None, :]
286 begun: np.ndarray = ~np.isnat(start) & (start <= day)
287 serving_still = np.isnat(end) | (day < end)
288 not_senior = np.isnat(senior) | (day < senior)
289 active: np.ndarray = begun & serving_still & not_senior
290 return active
293def _summaries(
294 active: np.ndarray,
295 values: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
296 """Returns the median and sum of the values of the active judges.
298 Args:
299 active: which judges were active on each day (see `_is_active`).
300 values: each judge's score, missing if the judge has none.
302 Returns:
303 The median and the sum of the scores of the judges who were active
304 on each day, missing on a day when none of them has a score.
306 """
307 chosen = np.where(active, values[None, :], np.nan)
308 scored = (~np.isnan(chosen)).sum(axis = 1) > 0
309 medians = np.full(len(active), np.nan)
310 totals = np.full(len(active), np.nan)
311 if scored.any(): 311 ↛ 314line 311 didn't jump to line 314 because the condition on line 311 was always true
312 medians[scored] = np.nanmedian(chosen[scored], axis = 1)
313 totals[scored] = np.nansum(chosen[scored], axis = 1)
314 return medians, totals