Coverage for tests/critic/test_audits.py: 100%
81 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"""Tests the audits module: courtpy's checks of court data."""
3from __future__ import annotations
5import amos
6import numpy as np
7import pandas as pd
8import pytest
10import courtpy
11from courtpy.critic import _strata
14def make_panels(size: int = 600, seed: int = 0) -> pd.DataFrame:
15 """Returns cases with panels drawn at random within each court and year."""
16 generator = np.random.default_rng(seed)
17 parties = generator.choice([-1, 1], (size, 3))
18 data = pd.DataFrame({
19 'court_num': generator.choice([1, 5, 9], size),
20 'year': generator.integers(2005, 2010, size),
21 'judge_party1': parties[:, 0], 'judge_party2': parties[:, 1], 'judge_party3': parties[:, 2],
22 'type_criminal': generator.random(size) < 0.5},
23 index = pd.Index([f'c{n}' for n in range(size)], name = 'case_id'))
24 # A trait that Republican panels get more often, as if panels were not
25 # assigned at random.
26 data['chosen'] = (parties == 1).sum(axis = 1) + generator.normal(0, 0.5, size) > 2
27 return data
30def test_audits_are_in_the_library() -> None:
31 for name in ('audit_random_assignment', 'audit_parsing', 'audit_coverage', 'validate_coding'):
32 assert amos.library.classify(name) == 'evaluator'
35def test_permute_within_keeps_each_stratum() -> None:
36 codes = np.array([0, 0, 0, 1, 1, 2])
37 values = np.array([1.0, 2.0, 3.0, 10.0, 20.0, 7.0])
38 shuffled = _strata.permute_within(values, codes, np.random.default_rng(1))
39 for code in range(3):
40 assert sorted(shuffled[codes == code]) == sorted(values[codes == code])
41 centered = _strata.demean(values, codes)
42 assert np.allclose(np.bincount(codes, weights = centered), 0)
43 data = pd.DataFrame({'court_num': [1, 1, 2, None], 'year': [2008, 2008, 2008, 2008]})
44 assert _strata.stratum_codes(data, ['court_num', 'year']).tolist() == [0, 0, 1, -1]
47def test_audit_random_assignment() -> None:
48 item = courtpy.Cases.create(make_panels())
49 courtpy.audits.AuditRandomAssignment().apply(
50 item, traits = 'type_criminal, chosen', n_permutations = 200)
51 table = item.tables['audit_random_assignment']
52 assert list(table.index) == ['type_criminal', 'chosen']
53 assert list(table.columns) == [
54 'DDD', 'DDR', 'DRR', 'RRR', 'correlation', 'p_value', 'balanced', 'cases']
55 assert table.loc['type_criminal', 'balanced']
56 assert not table.loc['chosen', 'balanced'] and table.loc['chosen', 'p_value'] < 0.01
57 assert table.loc['chosen', 'RRR'] > table.loc['chosen', 'DDD']
58 assert table.loc['chosen', 'cases'] == 600
59 # The same seed gives the same test.
60 again = courtpy.Cases.create(make_panels())
61 courtpy.audits.AuditRandomAssignment().apply(
62 again, traits = 'type_criminal, chosen', n_permutations = 200)
63 pd.testing.assert_frame_equal(again.tables['audit_random_assignment'], table)
66def test_audit_random_assignment_needs_panels() -> None:
67 data = make_panels().drop(columns = ['judge_party3']).assign(panel_party = np.nan, panel_found = 2)
68 with pytest.raises(ValueError, match = 'no case has a panel of 3'):
69 courtpy.audits.AuditRandomAssignment().apply(
70 courtpy.Cases.create(data), traits = 'type_criminal')
73def test_audit_parsing() -> None:
74 data = pd.DataFrame({
75 'court_num': [1, None, 9, 9],
76 'lower_court_num': [1026, None, None, 1084],
77 'review_agency': [False, False, True, False],
78 'panel_judges': ['A; B; C', '', 'A; B', 'A; B; C'],
79 'panel_size': [3, 0, 2, 3],
80 'year': [2008, 2008, None, 2009],
81 'outcome_reversal': pd.array([True, pd.NA, False, False], dtype = 'boolean'),
82 'disposition_affirm': [False, False, True, True],
83 'decision_affirm': [False, False, False, True],
84 'disposition_reverse': [True, False, False, False],
85 'decision_reverse': [True, False, True, False]},
86 index = pd.Index(['a', 'b', 'c', 'd'], name = 'case_id'))
87 item = courtpy.Cases.create(data)
88 courtpy.audits.AuditParsing().apply(item)
89 table = item.tables['audit_parsing']
90 assert table['cases'].to_dict() == {
91 'no court': 1, 'no court below': 1, 'no judges': 1, 'panel not of 3': 2,
92 'no year': 1, 'no outcome': 1, 'disposition and decision disagree': 1}
93 assert table.loc['panel not of 3', 'examples'] == 'b; c'
94 assert table.loc['disposition and decision disagree', 'examples'] == 'c'
95 assert table.loc['no court', 'share'] == 0.25
98def test_audit_coverage() -> None:
99 data = pd.DataFrame({
100 'court_num': [1, 1, 1, 10],
101 'year': [2008, 2008, 2009, 2008],
102 'published': [True, False, True, True]},
103 index = pd.Index(['a', 'b', 'c', 'd'], name = 'case_id'))
104 appeals = pd.DataFrame({
105 'circuit': ['First Circuit'] * 4 + ['Tenth Circuit'] * 2 + ['Ninth Circuit'],
106 'judgment_date': pd.to_datetime([
107 '2008-03-01', '2008-05-01', '2008-07-01', '2009-01-01', '2008-02-01',
108 '2008-03-01', '2008-01-01']),
109 'published': [1, 0, 1, 0, 1, 1, 1]})
110 item = courtpy.Cases.create(data)
111 courtpy.audits.AuditCoverage().apply(item, source = appeals)
112 table = item.tables['audit_coverage']
113 assert list(table.index) == [('First Circuit', 2008), ('First Circuit', 2009), ('Tenth Circuit', 2008)]
114 assert table['cases'].tolist() == [2, 1, 1]
115 assert table['idb_appeals'].tolist() == [3, 1, 2]
116 assert table['coverage'].round(3).tolist() == [0.667, 1.0, 0.5]
117 assert table['published'].tolist() == [1, 1, 1]
118 assert table['idb_published'].tolist() == [2, 0, 2]
119 assert pd.isna(table.loc[('First Circuit', 2009), 'published_coverage'])
122def test_validate_coding() -> None:
123 data = pd.DataFrame({
124 'published': [True, True, False, False, None],
125 'idb_published': [1, 0, 0, 0, 1],
126 'type_criminal': [True, False, True, False, True],
127 'idb_appeal_type': ['15', '3', '19', '4', None]},
128 index = pd.Index(list('abcde'), name = 'case_id'))
129 item = courtpy.Cases.create(data)
130 courtpy.audits.ValidateCoding().apply(item)
131 table = item.tables['validate_coding']
132 assert list(table.index) == ['published', 'type_criminal']
133 assert table.loc['published', 'cases'] == 4
134 assert table.loc['published', 'agreement'] == 0.75
135 assert table.loc['published', 'courtpy_only'] == 1
136 assert table.loc['published', 'kappa'] == pytest.approx(0.5)
137 assert table.loc['type_criminal', 'reference'] == 'idb_appeal_type'
138 assert table.loc['type_criminal', 'kappa'] == 1
139 # Codes of one's own, and pairs named as text.
140 courtpy.audits.ValidateCoding().apply(
141 item, pairs = 'type_criminal = idb_appeal_type', true_values = {'idb_appeal_type': '3|4'})
142 assert item.tables['validate_coding'].loc['type_criminal', 'agreement'] == 0
143 with pytest.raises(ValueError, match = 'pairs'):
144 courtpy.audits.ValidateCoding().apply(courtpy.Cases.create(data[['published']]))