Coverage for src/courtpy/critic/inferers.py: 95%
79 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 that infer the effects of panels on judges' votes.
3`panel_effects` (`PanelEffects`) is an `amos` inferer
4(`amos.inferers.Inferer`), so it is added to the `amos` library when
5courtpy is imported, can be named in the settings of a "critic" worker,
6adds its table of effects to the dataset's `tables` under its name, and
7draws it as a `coefficient_plot` with "visualize".
9Contents:
10 PanelEffects: estimates the effect of a judge's colleagues on the
11 judge's vote, with a test that reassigns panels at random.
12 _Z_95: the number of standard errors on each side of an estimate in its
13 95% confidence interval.
15"""
17from __future__ import annotations
19import dataclasses
20import math
21from collections.abc import Sequence
22from typing import Any
24import amos
25import numpy as np
26import pandas as pd
28from ..core import cases, utilities
29from . import _strata
31# The number of standard errors on each side of an estimate in its 95%
32# confidence interval, from the normal distribution.
33_Z_95: float = 1.959963984540054
36@dataclasses.dataclass
37class PanelEffects(amos.inferers.Inferer):
38 """Estimates the effect of a judge's colleagues on the judge's vote.
40 The data is `Votes` (see `cases_to_votes`): a row for each judge on
41 each case, with the judge's vote (such as "vote_reversal"), the party of
42 the president who appointed the judge ("judge_party", -1 or 1), and the
43 mean party of the judge's colleagues on the panel ("colleagues_party").
44 The vote is regressed on the colleagues' party, the judge's own party,
45 and (with "interact") their product, which says whether a judge of one
46 party is moved more by the other party's colleagues, with a fixed effect
47 for each court in each year, so that each vote is compared only with
48 the votes of its own court and year (a linear probability model for a
49 vote of yes or no).
51 Panels are assigned at random within a court (or so the design
52 assumes; see `audit_random_assignment`), so the effects are causal if
53 that holds. Two tests say how sure the estimates are:
55 * The standard errors are clustered by case, since the judges of a case
56 vote together, with Stata's correction for few clusters, and give the
57 p-values and 95% confidence intervals.
58 * A randomization test reassigns each vote's colleagues' party at random
59 among the votes of the same court and year `n_permutations` times, and
60 its p-value is the share of reassignments whose estimate is at least
61 as far from 0 as the one found. It assumes nothing about the
62 distribution of the votes.
64 The table has a row for each term, with "coefficient", "std_error",
65 "t_statistic", "p_value", "ri_p_value" (for the colleagues' party and
66 its product with the judge's party), "ci_lower", and "ci_upper".
68 """
70 """ Required Methods """
72 def infer(
73 self,
74 item: amos.Dataset,
75 *,
76 outcome: str | None = None,
77 treatment: str = 'colleagues_party',
78 controls: Sequence[str] | str = ('judge_party',),
79 interact: bool = True,
80 strata: Sequence[str] | str = ('court_num', 'year'),
81 cluster: str = 'case_id',
82 n_permutations: int = 1000,
83 seed: int = 0,
84 **kwargs: Any) -> amos.inferers.Inference:
85 """Returns the effects of the colleagues on the votes of `item`.
87 Args:
88 item: the votes, a row for each judge on each case.
89 outcome: the column with each judge's vote. Defaults to `None`,
90 which uses the dataset's label, or else "vote_reversal".
91 treatment: the column with the judge's colleagues' party.
92 Defaults to "colleagues_party".
93 controls: other columns of the regression, as a list or a
94 comma-separated `str`. Defaults to "judge_party".
95 interact: whether to add the product of the treatment and the
96 first control. Defaults to `True`.
97 strata: the columns within whose values votes are compared (a
98 fixed effect for each combination). Defaults to "court_num"
99 and "year".
100 cluster: the column whose values group the votes for the
101 standard errors. Defaults to "case_id".
102 n_permutations: the number of random reassignments of the
103 treatment. 0 skips the randomization test. Defaults to 1000.
104 seed: the seed of the random reassignments. Defaults to 0.
105 **kwargs: not used.
107 Raises:
108 KeyError: if the votes lack a column that is needed.
109 ValueError: if no vote has every column.
111 Returns:
112 The table of effects, the arrays of the fitted regression, and
113 the details to record.
115 """
116 data = item.data
117 outcome = outcome or item.label or 'vote_reversal'
118 named = utilities.listify(controls)
119 grouped = utilities.listify(strata)
120 cases.require_columns(
121 data, [outcome, treatment, *named, *grouped, cluster],
122 'panel_effects')
123 numbers = pd.DataFrame({
124 c: _numbers(data[c]) for c in [outcome, treatment, *named]})
125 codes = _strata.stratum_codes(data, grouped)
126 kept = (
127 numbers.notna().all(axis = 1) & (codes >= 0)
128 & data[cluster].notna()).to_numpy()
129 if not kept.any(): 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 message = 'no vote has every column that panel_effects needs'
131 raise ValueError(message)
132 y = numbers.loc[kept, outcome].to_numpy(dtype = float)
133 dose = numbers.loc[kept, treatment].to_numpy(dtype = float)
134 others = numbers.loc[kept, named].to_numpy(dtype = float)
135 stratum = pd.factorize(codes[kept])[0]
136 groups = pd.factorize(data.loc[kept, cluster])[0]
137 terms = [treatment]
138 if interact and named:
139 terms.append(f'{treatment} x {named[0]}')
140 terms.extend(named)
142 def design(treated: np.ndarray) -> np.ndarray:
143 """Returns the regression's columns with strata's means removed.
145 Args:
146 treated: the treatment of each vote.
148 Returns:
149 The treatment, its product with the first control (if
150 interacted), and the controls, each less the mean of
151 its stratum.
153 """
154 columns = [treated]
155 if interact and named:
156 columns.append(treated * others[:, 0])
157 raw = np.column_stack([*columns, others])
158 return _strata.demean(raw, stratum)
160 x = design(dose)
161 centered = _strata.demean(y, stratum)
162 coefficients, *_ = np.linalg.lstsq(x, centered, rcond = None)
163 errors = _clustered_errors(
164 x, centered - x @ coefficients, groups,
165 absorbed = int(stratum.max()) + 1)
166 tested = 2 if interact and named else 1
167 reassigned = _randomization_p_values(
168 coefficients[:tested], dose = dose, stratum = stratum,
169 centered = centered, design = design,
170 n_permutations = n_permutations, seed = seed)
171 t_statistics = np.divide(
172 coefficients, errors, out = np.full_like(coefficients, np.nan),
173 where = errors > 0)
174 table = pd.DataFrame({
175 'coefficient': coefficients,
176 'std_error': errors,
177 't_statistic': t_statistics,
178 'p_value': [
179 math.erfc(abs(t) / math.sqrt(2)) if np.isfinite(t)
180 else np.nan for t in t_statistics],
181 'ri_p_value': [
182 *reassigned, *[np.nan] * (len(terms) - tested)],
183 'ci_lower': coefficients - _Z_95 * errors,
184 'ci_upper': coefficients + _Z_95 * errors},
185 index = pd.Index(terms, name = 'term'))
186 fitted = {
187 'terms': terms, 'coefficients': coefficients, 'errors': errors}
188 details = {
189 'tool': 'courtpy (least squares with fixed effects)',
190 'outcome': outcome,
191 'treatment': treatment,
192 'controls': named,
193 'strata': grouped,
194 'votes': int(kept.sum()),
195 'clusters': int(groups.max()) + 1,
196 'n_permutations': n_permutations}
197 return amos.inferers.Inference(
198 table = table, fitted = fitted, details = details)
201""" Private Functions """
204def _clustered_errors(
205 x: np.ndarray,
206 residuals: np.ndarray,
207 groups: np.ndarray,
208 absorbed: int) -> np.ndarray:
209 """Returns standard errors clustered by group.
211 Args:
212 x: the regression's columns, with the strata's means removed.
213 residuals: the regression's errors.
214 groups: the cluster of each row, from 0.
215 absorbed: the number of fixed effects that removing the strata's
216 means absorbed, which count against the degrees of freedom.
218 Returns:
219 The standard error of each coefficient, with Stata's correction for
220 few clusters: G / (G - 1) times (N - 1) / (N - K), where G is
221 the number of clusters, N of rows, and K of coefficients and
222 fixed effects.
224 """
225 rows, width = x.shape
226 clusters = int(groups.max()) + 1
227 scores = np.column_stack([
228 np.bincount(groups, weights = x[:, c] * residuals,
229 minlength = clusters)
230 for c in range(width)])
231 bread = np.linalg.pinv(x.T @ x)
232 covariance = bread @ (scores.T @ scores) @ bread
233 freedom = max(rows - width - absorbed, 1)
234 correction = (
235 clusters / max(clusters - 1, 1) * (rows - 1) / freedom)
236 errors: np.ndarray = np.sqrt(
237 np.clip(np.diag(covariance) * correction, 0, None))
238 return errors
241def _numbers(values: pd.Series) -> pd.Series:
242 """Returns a column as numbers (1 for true and 0 for false).
244 Args:
245 values: a column of flags or numbers, which may be missing.
247 Returns:
248 The values as decimals, with missing values kept missing.
250 """
251 if values.dtype == object: 251 ↛ 252line 251 didn't jump to line 252 because the condition on line 251 was never true
252 values = values.map(
253 lambda v: float(v) if isinstance(v, bool | int | float) else v)
254 if pd.api.types.is_bool_dtype(values.dtype):
255 return values.astype('Float64').astype(float)
256 return pd.to_numeric(values, errors = 'coerce').astype(float)
259def _randomization_p_values(
260 found: np.ndarray,
261 *,
262 dose: np.ndarray,
263 stratum: np.ndarray,
264 centered: np.ndarray,
265 design: Any,
266 n_permutations: int,
267 seed: int) -> list[float]:
268 """Returns the p-values of a test that reassigns the treatment at random.
270 Args:
271 found: the coefficients to test (the treatment's, and its product's
272 with the first control), as estimated.
273 dose: the treatment of each row.
274 stratum: the stratum of each row, within which the treatment is
275 reassigned.
276 centered: the outcome, less the mean of its stratum.
277 design: a function that makes the regression's columns from a
278 treatment.
279 n_permutations: the number of reassignments, or 0 for none.
280 seed: the seed of the reassignments.
282 Returns:
283 For each coefficient of `found`, the share of reassignments (counting
284 the one found) whose estimate is at least as far from 0, or
285 missing values if there are no reassignments.
287 """
288 if n_permutations <= 0:
289 return [np.nan] * len(found)
290 generator = np.random.default_rng(seed)
291 extreme = np.zeros(len(found))
292 for _ in range(n_permutations):
293 shuffled = design(_strata.permute_within(dose, stratum, generator))
294 estimate, *_ = np.linalg.lstsq(shuffled, centered, rcond = None)
295 extreme += np.abs(estimate[:len(found)]) >= np.abs(found) - 1e-12
296 return [float((e + 1) / (n_permutations + 1)) for e in extreme]