Coverage for src/courtpy/critic/audits.py: 87%
181 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 check court data and how well it was coded.
3Each is an `amos` evaluator (`amos.evaluators.Evaluator`), so it is added to
4the `amos` library when courtpy is imported, can be named in the settings
5of a "critic" worker, and adds a table to the dataset's `tables` under its
6name. Unlike `amos`'s audits, they check the data, not a fitted model, so
7they need no model.
9| Technique | Checks | Needs |
10| --- | --- | --- |
11| `audit_random_assignment` | Whether the traits of cases (such as their types, and whether they review an agency) are balanced across the compositions of their panels within each court in each year, as random assignment of panels would make them. | `Cases`, with the judges' parties (from `add_biography` or `code_panels`). |
12| `audit_parsing` | How many cases lack what the rules should find (the court, the court below, the judges, the year, or the outcome), have panels of another size, or have a header's disposition that disagrees with the decision that the opinion states, with examples to read. | `Cases`. |
13| `audit_coverage` | How many cases of each court in each year the data has, against the appeals that the Federal Judicial Center's Integrated Database records, and so how much of each court's work it covers. | `Cases` of the courts of appeals, with "year". |
14| `validate_coding` | How often courtpy's coding agrees with another source's (such as the Integrated Database after `add_idb`, or the Supreme Court Database after `add_scdb`): the share of cases on which they agree and Cohen's kappa. | `Cases`, with both columns of each pair. |
16Contents:
17 AuditCoverage: compares the cases of each court in each year with the
18 appeals of the Integrated Database.
19 AuditParsing: counts the cases that lack what the rules should find, or
20 whose parts disagree.
21 AuditRandomAssignment: checks that the traits of cases are balanced
22 across the compositions of their panels.
23 ValidateCoding: measures how often courtpy's coding agrees with another
24 source's.
25 _BALANCE_TRAITS: the traits of cases checked for balance when none are
26 named.
27 _RULINGS: the rulings that a header's disposition and an opinion's
28 decision are compared on.
29 _VALIDATION_CODES: the codes that mean true in the other source's
30 columns that have codes, unless others are named.
31 _VALIDATIONS: the pairs of columns compared when none are named, if the
32 data has them.
34"""
36from __future__ import annotations
38import dataclasses
39import pathlib
40from collections.abc import Mapping, Sequence
41from typing import Any
43import amos
44import numpy as np
45import pandas as pd
47from ..core import cases, utilities
48from ..references import courts, fjc_idb, judges
49from . import _strata
51# The traits of cases checked for balance across panels when none are named:
52# what kind of case it is and where it comes from, which a panel cannot
53# change.
54_BALANCE_TRAITS: tuple[str, ...] = (
55 'type_criminal', 'type_civil', 'review_agency', 'review_immigration',
56 'procedure_pro_se', 'party1_united_states', 'party2_united_states')
57# The rulings on which a header's disposition ("disposition_...") and the
58# decision the opinion states ("decision_...") are compared.
59_RULINGS: tuple[str, ...] = (
60 'affirm', 'reverse', 'vacate', 'remand', 'dismiss')
61# The pairs of columns that `validate_coding` compares when none are named,
62# if the data has both: courtpy's column and the other source's.
63_VALIDATIONS: dict[str, str] = {
64 'published': 'idb_published',
65 'procedure_pro_se': 'idb_pro_se_party',
66 'type_criminal': 'idb_appeal_type'}
67# The codes that mean true in the other source's columns that have codes,
68# unless "true_values" names others: the Integrated Database's types of
69# criminal appeals (see fjc-idb's `rules.appellate.appeal_types_to_columns`).
70_VALIDATION_CODES: dict[str, tuple[str, ...]] = {
71 'idb_appeal_type': tuple(str(code) for code in range(13, 23))}
74@dataclasses.dataclass
75class AuditRandomAssignment(amos.evaluators.Evaluator):
76 """Checks that the traits of cases are balanced across their panels.
78 Studies of panels (such as of whether a judge votes differently beside
79 judges appointed by the other party) rely on panels being assigned to
80 cases at random within a court. If they are, a trait of a case that the
81 panel cannot change (such as whether it is criminal) has nothing to do
82 with the panel's composition within each court in each year.
84 For each trait, the table has its mean for each composition of the panel
85 ("DDD" to "RRR"; see `courtpy.judges.panel_compositions`), the
86 correlation between the trait and the number of Republican appointees
87 within each court and year (each stratum's mean removed), and the share
88 of `n_permutations` random reassignments of the compositions within each
89 court and year whose correlation is at least as far from 0 (a
90 permutation test, with no assumption about how the trait is
91 distributed). A trait is balanced if that share is at least `alpha`.
93 """
95 """ Required Methods """
97 def evaluate(
98 self,
99 item: amos.Dataset,
100 *,
101 traits: Sequence[str] | str | None = None,
102 size: int = 3,
103 strata: Sequence[str] | str = ('court_num', 'year'),
104 n_permutations: int = 1000,
105 alpha: float = 0.05,
106 seed: int = 0,
107 **kwargs: Any) -> pd.DataFrame:
108 """Returns the balance of each trait across panel compositions.
110 Args:
111 item: the cases, with the parties of their judges.
112 traits: the columns of the traits to check. Defaults to `None`,
113 which checks those of `_BALANCE_TRAITS` that the cases have.
114 size: the number of judges on the panels to check. Defaults to 3.
115 strata: the columns within whose values panels are assigned.
116 Defaults to "court_num" and "year".
117 n_permutations: the number of random reassignments. Defaults to
118 1000.
119 alpha: the smallest share of reassignments at which a trait is
120 balanced. Defaults to 0.05.
121 seed: the seed of the random reassignments. Defaults to 0.
122 **kwargs: not used.
124 Raises:
125 ValueError: if no trait is named or found, or no case has a panel
126 of `size` judges whose parties are known.
128 Returns:
129 A row for each trait, labeled by it, with the trait's mean for
130 each composition, "correlation", "p_value", "balanced", and
131 "cases" (the number of cases compared).
133 """
134 data = item.data
135 named = utilities.listify(traits) or [
136 t for t in _BALANCE_TRAITS if t in data.columns]
137 if not named: 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true
138 message = 'audit_random_assignment needs "traits" to check'
139 raise ValueError(message)
140 cases.require_columns(data, named, 'audit_random_assignment')
141 compositions = judges.panel_compositions(data, size)
142 republicans = judges.republican_appointees(data, size)
143 codes = _strata.stratum_codes(data, utilities.listify(strata))
144 usable = republicans.notna() & (codes >= 0)
145 if not usable.any():
146 message = (
147 f'no case has a panel of {size} judges whose parties are '
148 f'known')
149 raise ValueError(message)
150 generator = np.random.default_rng(seed)
151 rows = []
152 for trait in named:
153 values = _flags_or_numbers(data[trait])
154 kept = (usable & values.notna()).to_numpy()
155 found = values[kept].to_numpy(dtype = float)
156 count = republicans[kept].to_numpy(dtype = float)
157 stratum = pd.factorize(codes[kept])[0]
158 centered = _strata.demean(found, stratum)
159 counted = _strata.demean(count, stratum)
160 observed = _correlation(centered, counted)
161 # Shuffling within strata keeps each stratum's mean, so the
162 # shuffled counts are already centered.
163 extreme = sum(
164 abs(_correlation(centered, _strata.permute_within(
165 counted, stratum, generator))) >= abs(observed) - 1e-12
166 for _ in range(n_permutations))
167 p_value = (extreme + 1) / (n_permutations + 1)
168 means = values[kept].groupby(
169 compositions[kept], observed = False).mean()
170 rows.append({
171 **means.to_dict(),
172 'correlation': observed,
173 'p_value': p_value,
174 'balanced': p_value >= alpha,
175 'cases': int(kept.sum())})
176 return pd.DataFrame(rows, index = pd.Index(named, name = 'trait'))
179@dataclasses.dataclass
180class AuditParsing(amos.evaluators.Evaluator):
181 """Counts the cases that lack what the rules should find.
183 Each row is a check that the cases have: their court ("court_num"), the
184 court below ("lower_court_num", except for a review of an agency or of
185 the Board of Immigration Appeals), their judges ("panel_judges"), a
186 panel of `size` judges ("panel_size"), their year, and their outcome
187 ("outcome_reversal"), and that the disposition in the header
188 ("disposition_...") agrees with the decision that the opinion states
189 ("decision_...") where both are found. A check of a column that the cases
190 do not have is left out. After a change to the rules, the examples are
191 the cases to read first.
193 """
195 """ Required Methods """
197 def evaluate(
198 self,
199 item: amos.Dataset,
200 *,
201 size: int = 3,
202 examples: int = 10,
203 **kwargs: Any) -> pd.DataFrame:
204 """Returns how many cases fail each check.
206 Args:
207 item: the cases.
208 size: the number of judges that a panel should have. Defaults to
209 3.
210 examples: the most cases to list for each check. Defaults to 10.
211 **kwargs: not used.
213 Returns:
214 A row for each check, labeled by it, with "cases" (how many fail
215 it), "share" (of all the cases), and "examples" (the labels
216 of the first that fail it, separated by "; ").
218 """
219 data = item.data
220 checks: dict[str, pd.Series] = {}
221 if 'court_num' in data.columns: 221 ↛ 223line 221 didn't jump to line 223 because the condition on line 221 was always true
222 checks['no court'] = data['court_num'].isna()
223 if 'lower_court_num' in data.columns: 223 ↛ 229line 223 didn't jump to line 229 because the condition on line 223 was always true
224 agency = pd.Series(False, index = data.index)
225 for column in ('review_agency', 'review_immigration'):
226 if column in data.columns:
227 agency |= cases.column_as_flags(data, column)
228 checks['no court below'] = data['lower_court_num'].isna() & ~agency
229 if 'panel_judges' in data.columns: 229 ↛ 231line 229 didn't jump to line 231 because the condition on line 229 was always true
230 checks['no judges'] = ~_has_text(data['panel_judges'])
231 if 'panel_size' in data.columns: 231 ↛ 234line 231 didn't jump to line 234 because the condition on line 231 was always true
232 checks[f'panel not of {size}'] = pd.to_numeric(
233 data['panel_size'], errors = 'coerce') != size
234 if 'year' in data.columns: 234 ↛ 236line 234 didn't jump to line 236 because the condition on line 234 was always true
235 checks['no year'] = data['year'].isna()
236 if 'outcome_reversal' in data.columns: 236 ↛ 238line 236 didn't jump to line 238 because the condition on line 236 was always true
237 checks['no outcome'] = data['outcome_reversal'].isna()
238 disagreement = _disagreement(data)
239 if disagreement is not None: 239 ↛ 241line 239 didn't jump to line 241 because the condition on line 239 was always true
240 checks['disposition and decision disagree'] = disagreement
241 total = max(len(data), 1)
242 rows = []
243 for check in checks.values():
244 failing = check.fillna(False).astype(bool)
245 rows.append({
246 'cases': int(failing.sum()),
247 'share': failing.sum() / total,
248 'examples': cases._SEPARATOR.join(
249 str(label) for label in data.index[failing][:examples])})
250 return pd.DataFrame(
251 rows, index = pd.Index(list(checks), name = 'check'))
254@dataclasses.dataclass
255class AuditCoverage(amos.evaluators.Evaluator):
256 """Compares the cases of each court in each year with the database's.
258 The Federal Judicial Center's Integrated Database records every appeal
259 that the courts of appeals decide. For each court and year of the cases,
260 the table has how many cases the data has, how many appeals the
261 database records as decided (by the year of their judgment), and the
262 share of them that the data has, which shows which courts and years a
263 study's cases (such as CourtListener's) leave out. If both have
264 publication, it has the same for published opinions.
266 The database's records come from fjc-idb (see `courtpy.fjc_idb.appeals`),
267 or from "source".
269 """
271 """ Required Methods """
273 def evaluate(
274 self,
275 item: amos.Dataset,
276 *,
277 source: Any = None,
278 folder: pathlib.Path | str | None = None,
279 download: bool = True,
280 year: str = 'year',
281 court_name: str = 'court_name',
282 court_num: str = 'court_num',
283 **kwargs: Any) -> pd.DataFrame:
284 """Returns the coverage of each court in each year.
286 Args:
287 item: the cases of the courts of appeals.
288 source: the database's table of appeals, or the path of a file
289 of it (see `courtpy.fjc_idb.AddIdb`). Defaults to `None`, in
290 which case the database's records of the years of the cases
291 are read (and downloaded, if `download`).
292 folder: the folder of the database's yearly files, without a
293 `source`. Defaults to `None`, for fjc-idb's folder in
294 courtpy's data folder.
295 download: whether to download the yearly files that are missing,
296 without a `source`. Defaults to `True`.
297 year: the column with each case's year. Defaults to "year".
298 court_name: the column with courtpy's name for each case's court.
299 Defaults to "court_name".
300 court_num: the column with courtpy's number for each case's
301 court. Defaults to "court_num".
302 **kwargs: not used.
304 Raises:
305 KeyError: if the cases have no `year`, or the database's table
306 has no "circuit" or "judgment_date".
308 Returns:
309 A row for each court (by its label) and year, with "cases",
310 "idb_appeals", and "coverage" (and "published",
311 "idb_published", and "published_coverage" if both have
312 publication).
314 """
315 data = item.data
316 cases.require_columns(data, [year], 'audit_coverage')
317 years = pd.to_numeric(data[year], errors = 'coerce')
318 found = pd.DataFrame({
319 'court': courts.court_labels(
320 data, court_name = court_name, court_num = court_num),
321 'year': years}).dropna()
322 if found.empty: 322 ↛ 323line 322 didn't jump to line 323 because the condition on line 322 was never true
323 message = 'no case has a known court and year'
324 raise ValueError(message)
325 appeals = self._appeals(
326 source, int(found['year'].min()), int(found['year'].max()) + 1,
327 folder, download)
328 cases.require_columns(
329 appeals, ['circuit', 'judgment_date'], 'the database of appeals')
330 recorded = pd.DataFrame({
331 'court': appeals['circuit'].astype('string'),
332 'year': pd.to_datetime(
333 appeals['judgment_date'], errors = 'coerce').dt.year})
334 group = ['court', 'year']
335 counts = found.assign(court = found['court'].astype('string')).groupby(
336 group).size().rename('cases')
337 expected = recorded.dropna().groupby(group).size().rename(
338 'idb_appeals')
339 table = pd.concat([counts, expected], axis = 1).loc[counts.index]
340 table['idb_appeals'] = table['idb_appeals'].fillna(0).astype('int64')
341 table['coverage'] = table['cases'] / table['idb_appeals'].where(
342 table['idb_appeals'] > 0)
343 if 'published' in data.columns and 'published' in appeals.columns: 343 ↛ 356line 343 didn't jump to line 356 because the condition on line 343 was always true
344 mine = found.assign(
345 court = found['court'].astype('string'),
346 published = cases.column_as_flags(data, 'published')[
347 found.index])
348 theirs = recorded.assign(published = pd.to_numeric(
349 appeals['published'], errors = 'coerce').fillna(0) > 0)
350 table['published'] = mine.groupby(group)['published'].sum()
351 table['idb_published'] = theirs.dropna().groupby(group)[
352 'published'].sum().reindex(table.index).fillna(0).astype(
353 'int64')
354 table['published_coverage'] = table['published'] / table[
355 'idb_published'].where(table['idb_published'] > 0)
356 order = {c: n for n, c in enumerate(
357 courts.court_labels(data).cat.categories)}
358 return table.sort_index(
359 key = lambda level: level.map(order) if level.name == 'court'
360 else level)
362 """ Private Methods """
364 def _appeals(
365 self,
366 source: Any,
367 start_year: int,
368 stop_year: int,
369 folder: pathlib.Path | str | None,
370 download: bool) -> pd.DataFrame:
371 """Returns the database's table of appeals.
373 Args:
374 source: a table or the path of a file of one, or `None`.
375 start_year: the first year of the cases.
376 stop_year: the year after the last year of the cases (the
377 database's years end on September 30).
378 folder: the folder of the database's yearly files, or `None`.
379 download: whether to download the yearly files that are missing.
381 Returns:
382 The table of appeals.
384 """
385 if isinstance(source, pd.DataFrame): 385 ↛ 387line 385 didn't jump to line 387 because the condition on line 385 was always true
386 return source
387 if source is not None:
388 reader = fjc_idb.AddIdb()
389 reader.clerk = getattr(self, 'clerk', None)
390 return reader.read(source)
391 return fjc_idb.appeals(
392 start_year, stop_year, folder, download = download)
395@dataclasses.dataclass
396class ValidateCoding(amos.evaluators.Evaluator):
397 """Measures how often courtpy's coding agrees with another source's.
399 Each pair names a column of courtpy's (such as "published") and the
400 other source's column for the same thing (such as "idb_published",
401 after `add_idb`). Both are read as flags: true, nonzero, or (for the
402 other source's column) one of its `true_values`. Only the cases with
403 both are compared. Cohen's kappa is the agreement beyond what the shares
404 of true values in each would give by chance (1 is perfect agreement,
405 and 0 is no better than chance).
407 """
409 """ Required Methods """
411 def evaluate(
412 self,
413 item: amos.Dataset,
414 *,
415 pairs: Mapping[str, str] | str | None = None,
416 true_values: Mapping[str, Sequence[Any] | str] | None = None,
417 **kwargs: Any) -> pd.DataFrame:
418 """Returns the agreement of each pair of columns.
420 Args:
421 item: the cases.
422 pairs: courtpy's columns and the other source's, as a `dict` or
423 text such as "published = idb_published, type_criminal =
424 idb_appeal_type". Defaults to `None`, which compares the
425 pairs of `_VALIDATIONS` that the cases have.
426 true_values: for a column of the other source with codes, the
427 codes that mean true (as a list, or text separated by "|"),
428 by the column's name. Defaults to `None`, which uses
429 `_VALIDATION_CODES` for the columns it names.
430 **kwargs: not used.
432 Raises:
433 ValueError: if no pair is named or found.
434 KeyError: if a column of a pair is not in the cases.
436 Returns:
437 A row for each pair, labeled by courtpy's column, with
438 "reference" (the other column), "cases" (how many have both),
439 "agreement", "kappa", "both_true", "both_false",
440 "courtpy_only" (true only in courtpy's), and "reference_only".
442 """
443 data = item.data
444 chosen = _parse_pairs(pairs) or {
445 mine: theirs for mine, theirs in _VALIDATIONS.items()
446 if mine in data.columns and theirs in data.columns}
447 if not chosen:
448 message = (
449 'validate_coding needs "pairs" of columns to compare, such as '
450 '"published = idb_published"')
451 raise ValueError(message)
452 cases.require_columns(
453 data, [*chosen, *chosen.values()], 'validate_coding')
454 codes = {
455 column: [str(v) for v in utilities.listify(
456 values.split('|') if isinstance(values, str) else values)]
457 for column, values in {
458 **_VALIDATION_CODES, **(true_values or {})}.items()}
459 rows = []
460 for mine, theirs in chosen.items():
461 ours = _flags_or_numbers(data[mine]).ne(0).where(
462 data[mine].notna())
463 reference = data[theirs]
464 if theirs in codes:
465 truth = reference.astype('string').isin(codes[theirs])
466 else:
467 truth = _flags_or_numbers(reference).ne(0)
468 truth = truth.where(reference.notna())
469 both = ours.notna() & truth.notna()
470 a = ours[both].astype(bool).to_numpy()
471 b = truth[both].astype(bool).to_numpy()
472 rows.append({
473 'reference': theirs,
474 'cases': int(both.sum()),
475 **_agreement(a, b)})
476 return pd.DataFrame(
477 rows, index = pd.Index(list(chosen), name = 'column'))
480""" Private Functions """
483def _agreement(first: np.ndarray, second: np.ndarray) -> dict[str, Any]:
484 """Returns how often two columns of flags agree.
486 Args:
487 first: courtpy's flags.
488 second: the other source's flags, for the same cases.
490 Returns:
491 "agreement" (the share of cases on which they agree), "kappa"
492 (Cohen's kappa, missing if either is constant), "both_true",
493 "both_false", "courtpy_only", and "reference_only".
495 """
496 total = len(first)
497 if not total: 497 ↛ 498line 497 didn't jump to line 498 because the condition on line 497 was never true
498 return {
499 'agreement': np.nan, 'kappa': np.nan, 'both_true': 0,
500 'both_false': 0, 'courtpy_only': 0, 'reference_only': 0}
501 agreement = float((first == second).mean())
502 chance = float(
503 first.mean() * second.mean()
504 + (1 - first.mean()) * (1 - second.mean()))
505 kappa = (agreement - chance) / (1 - chance) if chance < 1 else np.nan
506 return {
507 'agreement': agreement,
508 'kappa': kappa,
509 'both_true': int((first & second).sum()),
510 'both_false': int((~first & ~second).sum()),
511 'courtpy_only': int((first & ~second).sum()),
512 'reference_only': int((~first & second).sum())}
515def _correlation(first: np.ndarray, second: np.ndarray) -> float:
516 """Returns the correlation of two columns whose means are 0.
518 Args:
519 first: values with each stratum's mean removed.
520 second: values with each stratum's mean removed.
522 Returns:
523 Their correlation, or 0 if either does not vary.
525 """
526 scale = float(np.sqrt((first ** 2).sum() * (second ** 2).sum()))
527 return float((first * second).sum() / scale) if scale else 0.0
530def _disagreement(data: pd.DataFrame) -> pd.Series | None:
531 """Returns which cases' header disposition and stated decision disagree.
533 Args:
534 data: the cases.
536 Returns:
537 Whether each case's disposition and decision differ on any ruling of
538 `_RULINGS`, among the cases that have at least one ruling in
539 each, or `None` if the cases have neither kind of column.
541 """
542 rulings = [
543 r for r in _RULINGS
544 if f'disposition_{r}' in data.columns
545 and f'decision_{r}' in data.columns]
546 if not rulings: 546 ↛ 547line 546 didn't jump to line 547 because the condition on line 546 was never true
547 return None
548 header = pd.DataFrame({
549 r: cases.column_as_flags(data, f'disposition_{r}') for r in rulings})
550 stated = pd.DataFrame({
551 r: cases.column_as_flags(data, f'decision_{r}') for r in rulings})
552 both = header.any(axis = 1) & stated.any(axis = 1)
553 return both & (header != stated).any(axis = 1)
556def _flags_or_numbers(values: pd.Series) -> pd.Series:
557 """Returns a column as numbers (1 for true and 0 for false).
559 Args:
560 values: a column of flags or numbers, which may be missing.
562 Returns:
563 The values as decimals, with missing values kept missing.
565 """
566 if values.dtype == object:
567 values = values.map(
568 lambda v: float(v) if isinstance(v, bool | int | float) else v)
569 if pd.api.types.is_bool_dtype(values.dtype):
570 return values.astype('Float64').astype(float)
571 return pd.to_numeric(values, errors = 'coerce').astype(float)
574def _has_text(values: pd.Series) -> pd.Series:
575 """Returns which values are text that is not blank.
577 Args:
578 values: a column.
580 Returns:
581 Whether each value is text with something in it (a list counts if
582 it is not empty).
584 """
585 return values.map(
586 lambda v: bool(v) if isinstance(v, list | tuple)
587 else isinstance(v, str) and bool(v.strip()))
590def _parse_pairs(pairs: Mapping[str, str] | str | None) -> dict[str, str]:
591 """Returns the pairs of columns that `validate_coding` compares.
593 Args:
594 pairs: a `dict`, or text such as "a = b, c = d", or `None`.
596 Raises:
597 ValueError: if a pair in text has no "=".
599 Returns:
600 courtpy's columns and the other source's, in order.
602 """
603 if pairs is None:
604 return {}
605 if isinstance(pairs, Mapping): 605 ↛ 606line 605 didn't jump to line 606 because the condition on line 605 was never true
606 return {str(k): str(v) for k, v in pairs.items()}
607 found: dict[str, str] = {}
608 for pair in utilities.listify(pairs):
609 mine, equals, theirs = str(pair).partition('=')
610 if not equals: 610 ↛ 611line 610 didn't jump to line 611 because the condition on line 610 was never true
611 message = (
612 f'{pair!r} is not a pair such as '
613 f'"published = idb_published"')
614 raise ValueError(message)
615 found[mine.strip()] = theirs.strip()
616 return found