Coverage for tests/references/test_judges.py: 100%
728 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 judges module."""
3from __future__ import annotations
5import io
6import pathlib
7import random
8from typing import Any
10import amos
11import chrisjen
12import fjc_biographies
13import pandas as pd
14import pytest
15from conftest import make_cluster, make_opinion, write_case
17import courtpy
18from courtpy import judges, loaders
20EXAMPLES = pathlib.Path(__file__).parents[2] / 'examples'
21FIRST = 'U.S. Court of Appeals for the First Circuit'
22NINTH = 'U.S. Court of Appeals for the Ninth Circuit'
23APPEALS = 'U.S. Court of Appeals'
24DISTRICT = 'U.S. District Court'
25# Invented judges, in the layout of the Federal Judicial Center's file of
26# federal judicial service: nid, sequence, name, court type, court,
27# president, party, ABA rating, recess appointment, vote type, ayes/nays,
28# commission, senior status, and termination.
29SERVICE = [
30 (101, 1, 'Lynch, Mary Ann', APPEALS, FIRST, 'William J. Clinton', 'Democratic', 'Well Qualified', '', 'Voice', '', '1995-03-17', '', ''),
31 (102, 1, 'Howard, John Q.', APPEALS, FIRST, 'George W. Bush', 'Republican', 'Qualified', '', 'Roll Call', ' 99/1', '2002-04-23', '', ''),
32 (103, 1, 'Thompson, Rita Mae', APPEALS, FIRST, 'Barack Obama', 'Democratic', 'Exceptionally Well Qualified', '', 'Roll Call', ' 98/0', '2010-03-17', '', ''),
33 (104, 1, 'Smith, Milton Dale, Jr.', APPEALS, NINTH, 'George W. Bush', 'Republican', 'Well Qualified', '', 'Voice', '', '2006-05-18', '', ''),
34 (105, 1, 'Smith, N[orman] Roy', APPEALS, NINTH, 'George W. Bush', 'Republican', '', '', 'Roll Call', ' 94/0', '2007-03-19', '', ''),
35 (106, 1, 'Woods, Dana Paul', DISTRICT, 'U.S. District Court for the District of Massachusetts', 'Ronald Reagan', 'Republican', 'Not Qualified', '', 'Voice', '', '1986-06-16', '2015-06-01', ''),
36 (107, 2, 'Stone, Nora H.', APPEALS, FIRST, 'George H.W. Bush', 'Republican', 'Well Qualified', '', 'Voice', '', '1992-04-30', '2001-04-16', ''),
37 (107, 1, 'Stone, Nora H.', DISTRICT, 'U.S. District Court for the District of New Hampshire', 'George H.W. Bush', 'Republican', 'Qualified', '', 'Voice', '', '1990-04-27', '', '1992-04-30'),
38 (108, 1, 'Fields, R[ay] Lanier III', APPEALS, 'U.S. Court of Appeals for the Fifth Circuit', 'Jimmy Carter', 'Democratic', 'Well Qualified', '', 'Roll Call', ' 60/30', '1979-07-13', '', '1981-10-01'),
39 (108, 2, 'Fields, R[ay] Lanier III', APPEALS, 'U.S. Court of Appeals for the Eleventh Circuit', 'None (reassignment)', 'None (reassignment)', '', '', '', '', '1981-10-01', '', ''),
40 (109, 1, 'Rake, Jed Saul', DISTRICT, 'U.S. District Court for the Southern District of New York', 'William J. Clinton', 'Democratic', 'Well Qualified', '', 'Voice', '', '1996-03-01', '', ''),
41 (110, 1, 'Poser, Richard Allen', APPEALS, 'U.S. Court of Appeals for the Seventh Circuit', 'Ronald Reagan', 'Republican', 'Qualified', '', 'Voice', '', '1981-12-01', '', '2017-09-02'),
42 (111, 1, 'Gray, Roger L.', APPEALS, 'U.S. Court of Appeals for the Fourth Circuit', 'William J. Clinton', 'Democratic', '', '2000-12-27', 'Unknown', '', '', '', '2001-07-20'),
43 (112, 1, 'Marsh, John', 'Supreme Court', 'Supreme Court of the United States', 'John Adams', 'Federalist', '', '', 'Voice', '', '1801-01-31', '', '1835-07-06')]
44SERVICE_COLUMNS = [
45 'nid', 'Sequence', 'Judge Name', 'Court Type', 'Court Name',
46 'Appointing President', 'Party of Appointing President', 'ABA Rating',
47 'Recess Appointment Date', 'Senate Vote Type', 'Ayes/Nays',
48 'Commission Date', 'Senior Status Date', 'Termination Date']
49DEMOGRAPHICS = [
50 (101, 'Lynch', 'Mary', 'Ann', '', '1946', 'Female', 'White'),
51 (102, 'Howard', 'John', 'Q.', '', '1955', 'Male', 'White'),
52 (103, 'Thompson', 'Rita', 'Mae', '', '1951', 'Female', 'African American'),
53 (104, 'Smith', 'Milton', 'Dale', 'Jr.', '1942', 'Male', 'White'),
54 (105, 'Smith', 'N[orman]', 'Roy', '', '1949', 'Male', 'Hispanic/White'),
55 (106, 'Woods', 'Dana', 'Paul', '', '1947', 'Male', 'White'),
56 (107, 'Stone', 'Nora', 'H.', '', '1931', 'Female', 'White'),
57 (108, 'Fields', 'R[ay]', 'Lanier', 'III', '1936', 'Male', 'White'),
58 (109, 'Rake', 'Jed', 'Saul', '', '1943', 'Male', 'White'),
59 (110, 'Poser', 'Richard', 'Allen', '', '1939', 'Male', 'White'),
60 (111, 'Gray', 'Roger', 'L.', '', '1953', 'Male', 'African American'),
61 (112, 'Marsh', 'John', ' ', '', '1755', '', '')]
62DEMOGRAPHICS_COLUMNS = [
63 'nid', 'Last Name', 'First Name', 'Middle Name', 'Suffix', 'Birth Year',
64 'Gender', 'Race or Ethnicity']
65CAREER = [
66 (101, 'Law clerk, Hon. A. Judge, U.S. District Court, District of Rhode Island, 1971-1973'),
67 (101, 'Assistant attorney general, State of Massachusetts, 1973-1974'),
68 (102, 'Assistant U.S. attorney, District of New Hampshire, 1981-1987'),
69 (103, 'Assistant public defender, Rhode Island, 1976-1979'),
70 (104, 'Law clerk, Hon. B. Justice, Supreme Court of the United States, 1970-1971'),
71 (104, 'Professor, University of the West School of Law, 1980-1990'),
72 (105, 'Reporter of decisions, Supreme Court of the United States, 1990-1991'),
73 (105, 'Law clerk, Hon. C. Judge, U.S. District Court, District of Idaho, 1977-1978')]
76def tables() -> dict[str, pd.DataFrame]:
77 """Returns the three files of invented judges."""
78 return {
79 'service': pd.DataFrame(SERVICE, columns = SERVICE_COLUMNS),
80 'demographics': pd.DataFrame(DEMOGRAPHICS, columns = DEMOGRAPHICS_COLUMNS),
81 'career': pd.DataFrame(CAREER, columns = ['nid', 'Professional Career'])}
84@pytest.fixture
85def table() -> pd.DataFrame:
86 """Returns the table of a roster of the invented judges."""
87 return judges.build_roster(**tables()).set_index('court', drop = False)
90@pytest.fixture
91def roster() -> judges.Roster:
92 """Returns a roster of the invented judges."""
93 return judges.Roster(judges.build_roster(**tables()))
96def found(roster: judges.Roster, name: str, court: Any, year: Any) -> tuple[int, str] | None:
97 """Returns the id and court of the judge that a name is matched to."""
98 row = roster.match(name, court, year)
99 if row is None:
100 return None
101 return int(roster.data['nid'].iloc[row]), str(roster.data['court'].iloc[row])
104def test_techniques_are_in_the_library() -> None:
105 # Each is the genre of `amos` that says what it does to the cases.
106 assert amos.library.classify('add_biography') == 'merger'
107 assert amos.library.classify('code_panels') == 'munger'
108 assert amos.library.classify('cases_to_votes') == 'shaper'
109 assert amos.library.classify('votes_to_cases') == 'shaper'
110 assert amos.library.classify('cases_to_judges') == 'shaper'
111 assert amos.library.classify('load_roster') == 'reference_loader'
112 assert amos.library.classify('download_biographies') == 'reference_loader'
115def test_build_roster(table: pd.DataFrame) -> None:
116 assert len(table) == len(SERVICE)
117 # Rows are sorted by judge and then by the order of the judge's service.
118 assert list(table.loc[table['nid'] == 107, 'court_type']) == [DISTRICT, APPEALS]
119 lynch = table.loc[FIRST].iloc[0]
120 assert lynch['judge'] == 'Lynch, Mary Ann'
121 assert (lynch['last_name'], lynch['first_name'], lynch['middle_name']) == ('Lynch', 'Mary', 'Ann')
122 assert (lynch['court_num'], lynch['circuit_num']) == (1, 1)
123 assert (lynch['start_year'], lynch['birth_year']) == (1995, 1946)
124 assert pd.isna(lynch['end_year']) and pd.isna(lynch['senior_year'])
125 assert (lynch['party'], lynch['aba_rating'], lynch['senate_vote']) == (-1, 3, 1.0)
126 assert lynch['woman'] and not lynch['minority'] and not lynch['recess']
127 by_nid = table.drop_duplicates('nid', keep = 'last').set_index('nid')
128 assert list(by_nid.loc[[102, 103, 106], 'aba_rating']) == [2, 4, 1]
129 assert pd.isna(by_nid.loc[105, 'aba_rating'])
130 assert by_nid.loc[102, 'senate_vote'] == pytest.approx(0.99)
131 assert by_nid.loc[103, 'minority'] and by_nid.loc[105, 'minority']
132 assert by_nid.loc[110, 'end_year'] == 2017
133 assert by_nid.loc[106, 'senior_year'] == 2015
136def test_build_roster_courts(table: pd.DataFrame) -> None:
137 numbers = table.drop_duplicates('court').set_index('court')
138 assert numbers.loc[NINTH, 'court_num'] == 9
139 assert numbers.loc['U.S. Court of Appeals for the Eleventh Circuit', 'court_num'] == 11
140 assert numbers.loc['Supreme Court of the United States', 'court_num'] == 99
141 # A district court has no number of its own, but it has a circuit.
142 massachusetts = numbers.loc['U.S. District Court for the District of Massachusetts']
143 assert pd.isna(massachusetts['court_num']) and massachusetts['circuit_num'] == 1
144 assert numbers.loc['U.S. District Court for the Southern District of New York', 'circuit_num'] == 2
145 # A court of appeals or the Supreme Court is its own circuit, numbered as
146 # the federal rules number it.
147 assert numbers.loc['Supreme Court of the United States', 'circuit_num'] == 99
148 # The columns that courtpy adds are beside those of fjc-biographies.
149 columns = list(table.columns)
150 assert columns.index('aliases') == columns.index('suffix') + 1
151 assert columns.index('court_num') == columns.index('circuit_num') - 1
154def test_build_roster_appointments(table: pd.DataFrame) -> None:
155 by_court = table.set_index('court')
156 fifth = by_court.loc['U.S. Court of Appeals for the Fifth Circuit']
157 eleventh = by_court.loc['U.S. Court of Appeals for the Eleventh Circuit']
158 # A reassigned judge keeps the appointment of the judge's earlier service.
159 assert (fifth['start_year'], fifth['end_year'], eleventh['start_year']) == (1979, 1981, 1981)
160 for column in ('president', 'party', 'aba_rating', 'senate_vote'):
161 assert eleventh[column] == fifth[column]
162 assert eleventh['president'] == 'Jimmy Carter'
163 assert eleventh['senate_vote'] == pytest.approx(60 / 90)
164 # A recess appointment starts a judge's service, and a party other than
165 # the two of today, an unrecorded vote, and an unknown gender are missing.
166 fourth = by_court.loc['U.S. Court of Appeals for the Fourth Circuit']
167 assert fourth['recess'] and fourth['start_year'] == 2000
168 assert pd.isna(fourth['senate_vote'])
169 supreme = by_court.loc['Supreme Court of the United States']
170 assert pd.isna(supreme['party']) and pd.isna(supreme['woman']) and pd.isna(supreme['minority'])
173def test_build_roster_careers(table: pd.DataFrame) -> None:
174 careers = table.drop_duplicates('nid').set_index('nid')
175 flags = ['prosecutor', 'public_defender', 'law_clerk', 'supreme_court_clerk', 'solicitor_general', 'law_professor']
176 assert list(careers.loc[101, flags]) == [True, False, True, False, False, False]
177 assert list(careers.loc[102, flags]) == [True, False, False, False, False, False]
178 assert list(careers.loc[103, flags]) == [False, True, False, False, False, False]
179 assert list(careers.loc[104, flags]) == [False, False, True, True, False, True]
180 # A clerkship and the Supreme Court in different positions are not a
181 # clerkship at the Supreme Court, and "District" alone is not a prosecutor.
182 assert list(careers.loc[105, flags]) == [False, False, True, False, False, False]
183 # A judge with no career in the file has no flags.
184 assert not careers.loc[106, flags].any()
185 assert careers['prosecutor'].dtype == bool
188def test_build_roster_options(tmp_path: pathlib.Path) -> None:
189 files = tables()
190 scores = pd.DataFrame({'nid': [101, 104, 999], 'jcs': [-0.3, 0.4, 0.0]})
191 table = judges.build_roster(files['service'], files['demographics'], scores = scores)
192 assert 'prosecutor' not in table.columns
193 assert table.loc[table['nid'] == 101, 'jcs'].iloc[0] == -0.3
194 assert pd.isna(table.loc[table['nid'] == 102, 'jcs'].iloc[0])
195 assert 'jcs' in judges.Roster(table).attributes
196 # Files are read from paths too, and rules can be the user's own.
197 paths = {}
198 for kind, frame in files.items():
199 paths[kind] = tmp_path / f'{kind}.csv'
200 frame.to_csv(paths[kind], index = False)
201 rules = tmp_path / 'careers.csv'
202 rules.write_text(
203 'target,variable,kind,pattern,value,ignorecase,dotall,note\n'
204 'career,positions,count,\\d{4}-\\d{4},,FALSE,FALSE,\n', encoding = 'utf-8')
205 table = judges.build_roster(**paths, rulebook = rules)
206 assert list(table.loc[table['nid'].isin([101, 106]), 'positions']) == [2, 0]
207 # A file that is not in UTF-8 is read as Windows-1252.
208 files['demographics'].loc[0, 'Last Name'] = 'Peña'
209 files['demographics'].to_csv(paths['demographics'], index = False, encoding = 'cp1252')
210 table = judges.build_roster(paths['service'], paths['demographics'])
211 assert table.loc[table['nid'] == 101, 'last_name'].iloc[0] == 'Peña'
214def test_build_roster_missing_columns() -> None:
215 files = tables()
216 with pytest.raises(KeyError, match = 'federal judicial service'):
217 judges.build_roster(files['service'].drop(columns = 'Court Name'), files['demographics'])
218 with pytest.raises(KeyError, match = 'demographics'):
219 judges.build_roster(files['service'], files['demographics'].drop(columns = 'Gender'))
220 with pytest.raises(KeyError, match = 'careers'):
221 judges.build_roster(files['service'], files['demographics'], files['career'].drop(columns = 'nid'))
222 with pytest.raises(KeyError, match = 'scores'):
223 judges.build_roster(files['service'], files['demographics'], scores = pd.DataFrame({'jcs': [1.0]}))
224 with pytest.raises(KeyError, match = 'roster'):
225 judges.Roster(pd.DataFrame({'judge': ['Lynch, Mary Ann']}))
228def test_name_forms() -> None:
229 assert judges.name_forms('Sandra', 'Lea', 'Lynch') == {
230 'full': ['SANDRA LEA LYNCH', 'SANDRA L LYNCH', 'SANDRA LYNCH'],
231 'initials': ['S LEA LYNCH', 'S L LYNCH', 'SL LYNCH', 'S LYNCH', 'LEA LYNCH'],
232 'last': ['LYNCH']}
233 assert judges.name_forms('Ronnie', '', 'Abrams') == {
234 'full': ['RONNIE ABRAMS'], 'initials': ['R ABRAMS'], 'last': ['ABRAMS']}
235 # Each form is also written with the suffix.
236 smith = judges.name_forms('Milton', 'Dale', 'Smith', 'Jr.')
237 assert smith['full'][:2] == ['MILTON DALE SMITH', 'MILTON DALE SMITH JR']
238 assert 'M SMITH JR' in smith['initials'] and smith['last'] == ['SMITH', 'SMITH JR']
239 assert 'R LANIER FIELDS' in judges.name_forms('R[ay]', 'Lanier', 'Fields')['initials']
240 oscannlain = judges.name_forms('Diarmuid', 'F.', "O'Scannlain")
241 assert 'D OSCANNLAIN' in oscannlain['initials'] and 'F OSCANNLAIN' not in oscannlain['initials']
242 # A first name that is an initial makes a full name, and without a first
243 # name, there is only the last name.
244 assert judges.name_forms('J.', '', 'Doe') == {'full': ['J DOE'], 'initials': [], 'last': ['DOE']}
245 assert judges.name_forms('', '', 'Doe') == {'full': [], 'initials': [], 'last': ['DOE']}
246 assert judges.name_forms('John', '', '') == {'full': [], 'initials': [], 'last': []}
247 assert judges.clean_name(" N.R. Smith, Jr. ") == 'NR SMITH JR'
248 assert judges.clean_name('Gelpí') == judges.clean_name('Gelpi') == 'GELPI'
251def test_match_by_how_much_of_the_name(roster: judges.Roster) -> None:
252 # A full name, in any of the ways that fjc-biographies writes it.
253 assert found(roster, 'Mary Ann Lynch', 1, 2020) == (101, FIRST)
254 assert found(roster, 'Milton Dale Smith, Jr.', 9, 2010) == (104, NINTH)
255 assert found(roster, 'Norman Roy Smith', 9, 2010) == (105, NINTH)
256 assert found(roster, 'R. Lanier Fields', 11, 1990) == (108, 'U.S. Court of Appeals for the Eleventh Circuit')
257 # Initials and the last name tell apart judges who share a last name.
258 assert found(roster, 'M. D. Smith', 9, 2010) == (104, NINTH)
259 assert found(roster, 'N.R. Smith', 9, 2010) == (105, NINTH)
260 # A suffix is part of the last name.
261 assert found(roster, 'SMITH, JR.', 9, 2010) == (104, NINTH)
262 # A full name finds a judge of another circuit, who sits by designation.
263 assert found(roster, 'Ray Fields', 1, 1990) == (108, 'U.S. Court of Appeals for the Eleventh Circuit')
264 # Every level uses the years of the judges' service.
265 assert found(roster, 'Norman Roy Smith', 9, 2006) is None
268def test_match_prefers_a_full_name() -> None:
269 files = tables()
270 files['service'] = pd.concat([files['service'], pd.DataFrame([
271 (120, 1, 'Lynch, Ann', DISTRICT, 'U.S. District Court for the District of Maine', 'Barack Obama', 'Democratic', '', '', 'Voice', '', '2012-05-01', '', '')],
272 columns = SERVICE_COLUMNS)])
273 files['demographics'] = pd.concat([files['demographics'], pd.DataFrame([
274 (120, 'Lynch', 'Ann', '', '', '1960', 'Female', 'White')], columns = DEMOGRAPHICS_COLUMNS)])
275 roster = judges.Roster(judges.build_roster(**files))
276 maine = 'U.S. District Court for the District of Maine'
277 # "Ann Lynch" is the full name of the district judge, and only the middle
278 # and last names of the circuit judge, so it is the district judge.
279 assert found(roster, 'ANN LYNCH', 1, 2020) == (120, maine)
280 assert found(roster, 'A. LYNCH', 1, 2020) == (120, maine)
281 assert found(roster, 'M. LYNCH', 1, 2020) == (101, FIRST)
282 # The last name alone is the judge of the case's court, and then a
283 # district judge of its circuit.
284 assert found(roster, 'LYNCH', 1, 2020) == (101, FIRST)
285 assert found(roster, 'LYNCH', 1, 1990) is None
286 assert found(roster, 'LYNCH', 1, 1996) == (101, FIRST)
289def test_match_prefers_the_court(roster: judges.Roster) -> None:
290 assert found(roster, 'LYNCH', 1, 2020) == (101, FIRST)
291 assert found(roster, 'Mary A. Lynch', 1, 2020) == (101, FIRST)
292 # Two judges of a court share a name, so only their initials tell them apart.
293 assert found(roster, 'SMITH', 9, 2010) is None
294 assert found(roster, 'M SMITH', 9, 2010) == (104, NINTH)
295 assert found(roster, 'N.R. Smith', 9, 2010) == (105, NINTH)
296 # One of them was not yet a judge in 2006.
297 assert found(roster, 'SMITH', 9, 2006) == (104, NINTH)
298 # A district judge of the circuit sits by designation.
299 assert found(roster, 'WOODS', 1, 2010) == (106, 'U.S. District Court for the District of Massachusetts')
300 # A judge of another circuit visits.
301 assert found(roster, 'RAKE', 9, 2015) == (109, 'U.S. District Court for the Southern District of New York')
302 assert found(roster, 'NOBODY', 1, 2020) is None
305def test_match_uses_the_year(roster: judges.Roster, monkeypatch: pytest.MonkeyPatch) -> None:
306 district = 'U.S. District Court for the District of New Hampshire'
307 assert found(roster, 'STONE', 1, 1991) == (107, district)
308 assert found(roster, 'STONE', 1, 1993) == (107, FIRST)
309 assert found(roster, 'STONE', 1, 1989) is None
310 # An opinion may name a judge for two years after the judge left.
311 seventh = 'U.S. Court of Appeals for the Seventh Circuit'
312 assert found(roster, 'POSER', 7, 2019) == (110, seventh)
313 assert found(roster, 'POSER', 7, 2020) is None
314 assert judges.Roster(roster.data, grace = 0).match('POSER', 7, 2018) is None
315 monkeypatch.setattr(courtpy.options, '_JUDGE_GRACE', 5)
316 assert judges.Roster(roster.data).match('POSER', 7, 2022) is not None
317 assert found(roster, 'R LANIER FIELDS', 5, 1980) == (108, 'U.S. Court of Appeals for the Fifth Circuit')
318 assert found(roster, 'FIELDS', 11, 1990) == (108, 'U.S. Court of Appeals for the Eleventh Circuit')
319 # Without a year, any year fits, and the latest service is used.
320 assert found(roster, 'STONE', 1, None) == (107, FIRST)
321 assert found(roster, 'POSER', None, None) == (110, seventh)
322 assert found(roster, 'SMITH', None, 2010) is None
325def test_shorter_names() -> None:
326 assert judges.shorter_names('SUSAN P GRABER') == ['SUSAN GRABER', 'S GRABER']
327 assert judges.shorter_names('SARAH A L MERRIAM') == ['SARAH MERRIAM', 'S MERRIAM']
328 assert judges.shorter_names('ED CARNES') == ['E CARNES']
329 assert judges.shorter_names('MILTON D SMITH JR') == ['MILTON SMITH JR', 'M SMITH JR']
330 assert judges.shorter_names('M SMITH') == []
331 assert judges.shorter_names('SMITH') == []
332 assert judges.shorter_names('SMITH JR') == []
335def test_match_shorter_names(roster: judges.Roster) -> None:
336 # More of a name than the files give, or other middle initials: the first
337 # and last names fit.
338 assert found(roster, 'Rita M. Q. Thompson', 1, 2015) == (103, FIRST)
339 assert found(roster, 'John Quincy Howard', 1, 2015) == (102, FIRST)
340 # A short first name: its initial and the last name fit.
341 assert found(roster, 'Ricky Poser', 7, 2010) == (110, 'U.S. Court of Appeals for the Seventh Circuit')
342 # The shorter forms still tell apart judges who share a last name, and
343 # never fall back to the last name alone.
344 assert found(roster, 'Milt X. Smith', 9, 2010) == (104, NINTH)
345 assert found(roster, 'Zed X. Smith', 9, 2010) is None
346 assert found(roster, 'Zed Lynch', 1, 2015) is None
349def test_match_does_not_guess(roster: judges.Roster) -> None:
350 # A bankruptcy appellate panel (999) has no judges in the roster.
351 assert found(roster, 'RAKE', 999, 2015) is None
352 assert found(roster, 'LYNCH', 999, 2020) is None
355def test_edit_distance_and_repaired_names() -> None:
356 assert judges.edit_distance('KRAVTTCH', 'KRAVITCH') == 1
357 assert judges.edit_distance('TJOFALT', 'TJOFLAT') == 1
358 assert judges.edit_distance('SCANNLAIN', 'OSCANNLAIN') == 1
359 assert judges.edit_distance('SMITH', 'SMITH') == 0
360 assert judges.edit_distance('SMITH', 'JONES') == 5
361 assert 'POSNER' in judges.repaired_names('P OSNER')
362 assert 'VAN BOKKELEN' in judges.repaired_names('V AN B OKKELEN')
363 assert 'JACKSON-AKIWUMI' in judges.repaired_names('JACKSON- AKIWUMI')
364 assert 'NIEMEYER' in judges.repaired_names('BEFORENIEMEYER')
365 assert judges.repaired_names('SMITH') == []
368def test_match_repairs_names_that_fit_no_judge(roster: judges.Roster) -> None:
369 seventh = 'U.S. Court of Appeals for the Seventh Circuit'
370 # Small capitals, a scanning error, and a first and last name run
371 # together.
372 assert found(roster, 'P OSER', 7, 2010) == (110, seventh)
373 assert found(roster, 'THOMSPON', 1, 2015) == (103, FIRST)
374 assert found(roster, 'RITATHOMPSON', 1, 2015) == (103, FIRST)
375 # Only one judge of the case's own court may fit, and the name must be
376 # long enough.
377 assert found(roster, 'SMIHT', 9, 2010) is None
378 assert found(roster, 'THOMSPON', 9, 2015) is None
379 assert found(roster, 'LYNH', 1, 2015) is None
382def test_candidates_and_names(roster: judges.Roster) -> None:
383 rows = roster.candidates('SMITH', 9, 2010)
384 assert sorted(roster.nids(rows)) == [104, 105]
385 assert roster.nids(roster.candidates('LYNCH', 1, 2020)) == [101]
386 assert roster.candidates('NOBODY', 1, 2020) == []
387 milton = next(row for row in rows if roster.nids([row]) == [104])
388 assert roster.full_name(milton) == 'MILTON DALE SMITH JR'
389 assert roster.name_words(milton) == {'MILTON', 'DALE', 'MILTOND'}
390 assert found(roster, roster.full_name(milton), 9, 2010) == (104, NINTH)
393def test_code_panels_reads_the_panel_together(roster: judges.Roster) -> None:
394 # 0: a first name tells apart the judges who share a last name, and is
395 # not a judge of its own.
396 # 1: so does the author's full name.
397 # 2: nothing tells them apart.
398 # 3: a scanning error is the same judge, who is counted once.
399 # 4: a first and middle name, as separate words.
400 data = pd.DataFrame({
401 'panel_judges': [
402 'MILTON; SMITH; RAKE', 'SMITH; RAKE', 'SMITH; RAKE',
403 'POSER; P OSER', 'NORMAN; ROY; SMITH'],
404 'authors': [None, 'N.R. Smith', None, None, None],
405 'court_num': [9, 9, 9, 7, 9],
406 'year': [2010] * 5,
407 'panel_size': [3, 2, 2, 2, 3]})
408 result = judges.CodePanels().apply(amos.Dataset(data), roster = roster).data
409 assert list(result['panel_judges']) == [
410 'MILTON DALE SMITH JR; RAKE', 'NORMAN ROY SMITH; RAKE', 'SMITH; RAKE',
411 'POSER; P OSER', 'NORMAN ROY SMITH']
412 assert list(result['panel_found']) == [2, 2, 1, 1, 1]
413 assert list(result['panel_size']) == [2, 2, 2, 1, 1]
414 assert list(result['judge_nid1'].astype(object)) == [104, 105, pd.NA, 110, 105]
417def test_aliases(table: pd.DataFrame) -> None:
418 table.loc[table['nid'] == 101, 'aliases'] = 'Mary Ann Lane; M. A. Lyn'
419 roster = judges.Roster(table)
420 assert found(roster, 'LANE', 1, 2000) == (101, FIRST)
421 assert found(roster, 'MA LYN', 1, 2000) == (101, FIRST)
422 assert found(roster, 'LYNCH', 1, 2000) == (101, FIRST)
423 built = judges.build_roster(
424 pd.DataFrame([(1386716, 1, 'King, Carolyn Dineen', APPEALS, 'U.S. Court of Appeals for the Fifth Circuit', 'Jimmy Carter', 'Democratic', '', '', 'Voice', '', '1979-07-13', '', '')], columns = SERVICE_COLUMNS),
425 pd.DataFrame([(1386716, 'King', 'Carolyn', 'Dineen', '', '1938', 'Female', 'White')], columns = DEMOGRAPHICS_COLUMNS))
426 assert judges.Roster(built).match('RANDALL', 5, 1985) == 0
427 # Judge Richman sat as Priscilla Owen, so "OWEN" in the Fifth Circuit is
428 # her, and not a district judge of another circuit named Owen.
429 fifth = 'U.S. Court of Appeals for the Fifth Circuit'
430 built = judges.build_roster(
431 pd.DataFrame([
432 (1392271, 1, 'Richman, Priscilla', APPEALS, fifth, 'George W. Bush', 'Republican', '', '', 'Roll Call', ' 55/43', '2005-06-03', '', ''),
433 (130, 1, 'Owen, Richard', DISTRICT, 'U.S. District Court for the Southern District of New York', 'Richard M. Nixon', 'Republican', '', '', 'Voice', '', '1973-12-19', '', '')],
434 columns = SERVICE_COLUMNS),
435 pd.DataFrame([
436 (1392271, 'Richman', 'Priscilla', '', '', '1954', 'Female', 'White'),
437 (130, 'Owen', 'Richard', '', '', '1922', 'Male', 'White')],
438 columns = DEMOGRAPHICS_COLUMNS))
439 renamed = judges.Roster(built)
440 for year in (2012, 2020):
441 assert found(renamed, 'OWEN', 5, year) == (1392271, fifth)
442 assert found(renamed, 'RICHMAN', 5, year) == (1392271, fifth)
443 assert found(renamed, 'Richard Owen', 5, 2012) == (130, 'U.S. District Court for the Southern District of New York')
446def test_identify_and_describe(roster: judges.Roster) -> None:
447 rows = roster.identify(['LYNCH', 'HOWARD', 'NOBODY', 'MARY LYNCH', 'WOODS'], 1, 2016)
448 assert roster.nids(rows) == [101, 102, 106]
449 assert roster.names(rows) == ['Lynch, Mary Ann', 'Howard, John Q.', 'Woods, Dana Paul']
450 lynch, _, woods = (roster.describe(row, 1, 2016) for row in rows)
451 assert list(lynch) == roster.described
452 assert roster.described[-4:] == ['age', 'senior', 'designated', 'district_judge']
453 assert (lynch['party'], lynch['woman'], lynch['prosecutor']) == (-1.0, 1.0, 1.0)
454 assert (lynch['age'], lynch['senior'], lynch['designated'], lynch['district_judge']) == (70.0, 0.0, 0.0, 0.0)
455 assert (woods['senior'], woods['designated'], woods['district_judge']) == (1.0, 1.0, 1.0)
456 assert roster.describe(rows[2], 1, 2014)['senior'] == 0.0
457 unknown = roster.describe(rows[0])
458 assert unknown['age'] is None and unknown['senior'] is None and unknown['designated'] is None
459 # A judge with no rating has none, rather than a rating of zero.
460 assert roster.describe(roster.match('N R SMITH', 9, 2010), 9, 2010)['aba_rating'] is None
463def test_save_and_load(roster: judges.Roster, tmp_path: pathlib.Path) -> None:
464 with pytest.raises(FileNotFoundError, match = 'from_fjc'):
465 judges.Roster.load()
466 saved = roster.save()
467 assert saved == courtpy.utilities.data_folder() / 'judges' / 'roster.csv'
468 loaded = judges.Roster.load()
469 assert loaded.attributes == roster.attributes
470 assert found(loaded, 'N.R. SMITH', 9, 2010) == (105, NINTH)
471 assert loaded.describe(loaded.match('LYNCH', 1, 2016), 1, 2016) == roster.describe(roster.match('LYNCH', 1, 2016), 1, 2016)
472 assert loaded.data['woman'].dtype == 'boolean'
473 elsewhere = roster.save(tmp_path / 'mine' / 'judges.csv')
474 assert judges.Roster.create(elsewhere).match('HOWARD', 1, 2020) is not None
475 assert judges.Roster.create(roster) is roster
476 assert judges.Roster.create(roster.data).match('HOWARD', 1, 2020) is not None
477 # The columns of text that fjc-biographies adds are not attributes, even
478 # when they are blank, which a saved roster would read as numbers.
479 blank = judges.Roster(roster.data.assign(name_other = None, recess_date = None, career = None))
480 assert blank.attributes == roster.attributes
481 assert judges.Roster.load(blank.save(tmp_path / 'blank.csv')).attributes == roster.attributes
482 assert 'sequence' not in roster.attributes and 'name_first_last' in roster.data.columns
485class Website:
486 """Serves the invented judges' files in place of the center's website."""
488 def __init__(self) -> None:
489 self.urls: list[str] = []
490 self.files = {
491 fjc_biographies.options._CATEGORIES[kind]: frame.to_csv(index = False).encode()
492 for kind, frame in tables().items()}
494 def open(self, url: str) -> io.BytesIO:
495 """Records the request and returns the file it names."""
496 self.urls.append(url)
497 return io.BytesIO(self.files[url.rsplit('/', 1)[-1]])
500@pytest.fixture
501def website(monkeypatch: pytest.MonkeyPatch) -> Website:
502 """Returns the website that fjc-biographies downloads the files from."""
503 site = Website()
504 monkeypatch.setattr(fjc_biographies.downloader, '_open', site.open)
505 return site
508def test_download(website: Website, tmp_path: pathlib.Path) -> None:
509 paths = judges.download(tmp_path / 'fjc')
510 assert list(paths) == ['service', 'demographics', 'career']
511 assert [p.name for p in paths.values()] == [
512 'federal-judicial-service.csv', 'demographics.csv', 'professional-career.csv']
513 # fjc-biographies keeps the files in the "raw" folder of the folder.
514 assert {p.parent for p in paths.values()} == {tmp_path / 'fjc' / 'raw'}
515 assert website.urls[0] == 'https://www.fjc.gov/sites/default/files/history/federal-judicial-service.csv'
516 assert len(website.urls) == 3
517 # Files that are there are not downloaded again unless asked.
518 judges.download(tmp_path / 'fjc')
519 assert len(website.urls) == 3
520 judges.download(tmp_path / 'fjc', overwrite = True)
521 assert len(website.urls) == 6
522 assert judges.Roster(judges.build_roster(**paths)).match('LYNCH', 1, 2020) is not None
523 # The default folder is outside of any project.
524 assert judges.download()['service'].parent == (
525 courtpy.utilities.data_folder() / 'judges' / 'raw')
528def test_from_fjc(website: Website, tmp_path: pathlib.Path) -> None:
529 roster = judges.Roster.from_fjc(tmp_path)
530 assert len(website.urls) == 3
531 assert found(roster, 'LYNCH', 1, 2020) == (101, FIRST)
532 assert 'prosecutor' in roster.attributes
533 assert 'jcs' not in roster.data.columns
534 judges.Roster.from_fjc(tmp_path, update = True)
535 assert len(website.urls) == 6
538def test_from_fjc_scores(website: Website, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
539 calls: list[tuple[str, Any, dict[str, Any]]] = []
541 def add_jcs(roster: pd.DataFrame, folder: Any = None, **kwargs: Any) -> pd.DataFrame:
542 calls.append(('jcs', folder, kwargs))
543 return roster.assign(jcs = roster['nid'].astype('Float64') / 1000)
545 def add_martin_quinn(roster: pd.DataFrame, folder: Any = None, **kwargs: Any) -> pd.DataFrame:
546 calls.append(('martin_quinn', folder, kwargs))
547 return roster.assign(mq_mean = pd.array([None] * len(roster), dtype = 'Float64'))
549 monkeypatch.setattr(fjc_biographies, 'add_jcs', add_jcs)
550 monkeypatch.setattr(fjc_biographies, 'add_martin_quinn', add_martin_quinn)
551 roster = judges.Roster.from_fjc(tmp_path, jcs = True)
552 # The scores are computed from the files that fjc-biographies downloaded,
553 # and the files of judicial-common-space are kept with courtpy's.
554 assert calls == [('jcs', tmp_path, {
555 'scores_folder': courtpy.utilities.data_folder(), 'martin_quinn': None, 'update': False})]
556 assert 'jcs' in roster.attributes and 'mq_mean' not in roster.data.columns
557 assert roster.describe(roster.match('LYNCH', 1, 2020), 1, 2020)['jcs'] == pytest.approx(0.101)
558 calls.clear()
559 saved = tmp_path / 'justices.csv'
560 roster = judges.Roster.from_fjc(tmp_path, jcs = True, martin_quinn = saved, update = True)
561 assert [call[0] for call in calls] == ['jcs', 'martin_quinn']
562 assert all(call[2]['martin_quinn'] == saved and call[2]['update'] for call in calls)
563 assert 'mq_mean' in roster.attributes
564 calls.clear()
565 judges.Roster.from_fjc(tmp_path, martin_quinn = True)
566 assert [call[0] for call in calls] == ['martin_quinn']
567 assert calls[0][2]['martin_quinn'] is None
570def test_add_biography(roster: judges.Roster, tmp_path: pathlib.Path) -> None:
571 # A row for each judge on each case, as `lists_to_rows` makes them.
572 data = pd.DataFrame({
573 'judge': ['LYNCH', 'WOODS', 'NOBODY', None, 'SMITH', 'M. SMITH'],
574 'court_num': [1, 1, 1, 1, 9, 9],
575 'year': [2016, 2016, 2016, 2016, 2010, 2010],
576 'reversed': [True, True, True, False, False, False]}, index = list('abcdef'))
577 dataset = judges.AddBiography().apply(
578 amos.Dataset(data.copy(), label = 'reversed'), source = roster, indicator = 'found')
579 merged = dataset.data
580 # A merger never adds, removes, or reorders rows.
581 assert list(merged.index) == list(data.index) and dataset.label == 'reversed'
582 assert list(merged['found']) == [True, True, False, False, False, True]
583 assert list(merged.columns[4:-1]) == [f'judge_{name}' for name in roster.described]
584 assert merged.loc['a', ['judge_party', 'judge_woman', 'judge_age', 'judge_designated']].tolist() == [-1.0, 1.0, 70.0, 0.0]
585 assert merged.loc['b', ['judge_senior', 'judge_designated', 'judge_district_judge']].tolist() == [1.0, 1.0, 1.0]
586 assert merged.loc[['c', 'd', 'e'], 'judge_party'].isna().all()
587 assert all(merged[c].dtype == 'float64' for c in merged.columns[4:-1])
588 record = dataset.history[0]
589 assert (record['technique'], record['source'], record['rows'], record['matched']) == ('add_biography', 'Roster', 6, 3)
590 assert record['created'] == list(merged.columns[4:])
591 # Other columns of the roster can be added, under another prefix, and
592 # the judge can be named by another column, such as a case's author.
593 cases = data.rename(columns = {'judge': 'author'})
594 path = roster.save(tmp_path / 'roster.csv')
595 dataset = judges.AddBiography().apply(
596 amos.Dataset(cases), source = str(path), name = 'author', prefix = 'author_',
597 columns = 'judge, nid, president, party, age')
598 merged = dataset.data
599 assert list(merged.columns[4:]) == ['author_judge', 'author_nid', 'author_president', 'author_party', 'author_age']
600 assert merged.loc['f', ['author_judge', 'author_nid', 'author_president']].tolist() == [
601 'Smith, Milton Dale, Jr.', 104, 'George W. Bush']
602 assert pd.isna(merged.loc['c', 'author_judge'])
603 assert dataset.history[0]['source'] == str(path)
604 assert judges.AddBiography().match(data, roster).tolist() == [0, 5, -1, -1, -1, 3]
607def test_add_biography_fails_clearly(roster: judges.Roster) -> None:
608 data = pd.DataFrame({'judge': ['LYNCH'], 'court_num': [1], 'year': [2016], 'judge_party': [0]})
609 with pytest.raises(ValueError, match = 'prefix'):
610 judges.AddBiography().apply(amos.Dataset(data), source = roster)
611 with pytest.raises(KeyError, match = 'no_such'):
612 judges.AddBiography().apply(amos.Dataset(data), source = roster, columns = ['party', 'no_such'])
613 with pytest.raises(KeyError, match = 'add_biography'):
614 judges.AddBiography().apply(amos.Dataset(data.drop(columns = 'year')), source = roster)
615 with pytest.raises(FileNotFoundError, match = 'no roster'):
616 judges.AddBiography().apply(amos.Dataset(data))
619def test_code_panels(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
620 parsed = courtpy.parse(court_listener_folder)
621 dataset = courtpy.code(
622 parsed, ['code_panels'], parameters = {'code_panels': {'roster': roster}})
623 data = dataset.data
624 assert data.loc['1', 'panel_names'] == ['Lynch, Mary Ann', 'Howard, John Q.', 'Thompson, Rita Mae']
625 assert list(data['panel_found']) == [3, 3, 3]
626 # Each judge who is found has the center's name and number.
627 assert [data.loc['1', f'judge_name{n}'] for n in (1, 2, 3)] == data.loc['1', 'panel_names']
628 assert [data.loc['1', f'judge_nid{n}'] for n in (1, 2, 3)] == [101, 102, 103]
629 assert data['judge_nid1'].dtype == 'Int64' and 'judge_name4' not in data.columns
630 assert list(data['panel_found']) == list(data['panel_size'])
631 assert data.loc['1', 'author_name'] == 'Lynch, Mary Ann'
632 assert data.loc['1', 'dissenting_names'] == []
633 assert data.loc['2', 'dissenting_names'] == ['Thompson, Rita Mae']
634 assert data.loc['1', 'panel_party'] == pytest.approx(-1 / 3)
635 assert data.loc['1', 'panel_woman'] == pytest.approx(2 / 3)
636 assert data.loc['1', 'panel_age'] == pytest.approx((74 + 65 + 69) / 3)
637 assert data.loc['1', 'panel_designated'] == 0.0
638 assert data['panel_prosecutor'].dtype == 'float64'
639 created = dataset.history[0]['created']
640 assert created[:2] == ['panel_names', 'panel_found']
641 assert {'author_name', 'concurring_names', 'panel_senior', 'panel_district_judge'} <= set(created)
644def test_code_panels_with_little(roster: judges.Roster, tmp_path: pathlib.Path) -> None:
645 # Names can be the text of a saved table, and judges and years missing.
646 data = pd.DataFrame({
647 'panel_judges': ['LYNCH; WOODS', None, 'NOBODY', 'HOWARD'],
648 'court_num': pd.array([1, 1, 1, pd.NA], dtype = 'Int64'),
649 'year': pd.array([2016, 2016, 2016, pd.NA], dtype = 'Int64')})
650 path = roster.save(tmp_path / 'roster.csv')
651 result = judges.CodePanels().apply(amos.Dataset(data), roster = str(path)).data
652 assert list(result['panel_found']) == [2, 0, 0, 1]
653 assert [c for c in result.columns if c.startswith('judge')] == ['judge_name1', 'judge_nid1', 'judge_name2', 'judge_nid2']
654 assert list(result['judge_nid1'].astype(object).where(result['judge_nid1'].notna(), None)) == [101, None, None, 102]
655 assert result.loc[0, 'judge_name2'] == 'Woods, Dana Paul' and pd.isna(result.loc[3, 'judge_name2'])
656 # A name that is not matched leaves its place empty, so the judges after
657 # it keep their places.
658 gaps = pd.DataFrame({
659 'panel_judges': [['NOBODY', 'LYNCH', 'HOWARD'], ['LYNCH', 'NOBODY', 'NOBODY']],
660 'court_num': [1, 1], 'year': [2016, 2016]})
661 seated = judges.CodePanels().apply(amos.Dataset(gaps), roster = roster).data
662 assert [c for c in seated.columns if c.startswith('judge')] == [
663 'judge_name1', 'judge_nid1', 'judge_name2', 'judge_nid2', 'judge_name3', 'judge_nid3']
664 assert pd.isna(seated.loc[0, 'judge_name1']) and pd.isna(seated.loc[0, 'judge_nid1'])
665 assert (seated.loc[0, 'judge_nid2'], seated.loc[0, 'judge_nid3']) == (101, 102)
666 assert seated.loc[1, 'judge_name1'] == 'Lynch, Mary Ann' and seated.loc[1, ['judge_name2', 'judge_name3']].isna().all()
667 assert list(seated['panel_found']) == [2, 1]
668 assert result.loc[0, 'panel_district_judge'] == 0.5
669 assert pd.isna(result.loc[1, 'panel_party']) and pd.isna(result.loc[3, 'panel_age'])
670 assert 'author_name' not in result.columns
671 with pytest.raises(KeyError, match = 'panel_judges'):
672 judges.CodePanels().apply(amos.Dataset(pd.DataFrame({'year': [2016]})), roster = roster)
673 with pytest.raises(FileNotFoundError, match = 'no roster'):
674 judges.CodePanels().apply(amos.Dataset(data))
677def test_vote_table(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
678 coded = courtpy.code(courtpy.parse(court_listener_folder)).data
679 votes = judges.vote_table(coded, roster)
680 assert votes.index.name == 'vote_id'
681 assert list(votes.index[:4]) == ['1-1', '1-2', '1-3', '2-1']
682 assert list(votes['case_id']) == ['1'] * 3 + ['2'] * 3 + ['3'] * 3
683 assert list(votes.columns[:3]) == ['case_id', 'judge', 'judge_nid']
684 assert list(votes.loc[['1-1', '1-2', '1-3'], 'judge_nid']) == [101, 102, 103]
685 # The case's columns are repeated for each of its judges.
686 assert list(votes.loc[votes['case_id'] == '2', 'case_name']) == ['Smith v. Acme Corp.'] * 3
687 lynch = votes.loc['1-1']
688 assert (lynch['judge_party'], lynch['colleagues_party']) == (-1.0, 0.0)
689 assert (lynch['judge_woman'], lynch['colleagues_woman']) == (1.0, 0.5)
690 assert lynch['judge_author'] and not lynch['judge_concurred'] and not lynch['judge_dissented']
691 assert not votes.loc['1-2', 'judge_author']
692 # Case 1 was reversed with no dissent, and case 2 affirmed over one.
693 assert list(votes.loc[votes['case_id'] == '1', 'vote_reversal']) == [True, True, True]
694 assert list(votes.loc[votes['case_id'] == '2', 'judge_dissented']) == [False, False, True]
695 assert list(votes.loc[votes['case_id'] == '2', 'vote_reversal']) == [False, False, True]
696 assert not votes.loc['2-3', 'outcome_reversal']
697 # The winner of case 3 is not known, so neither is how its judges voted.
698 assert votes.loc[votes['case_id'] == '3', 'vote_party1_won'].isna().all()
699 assert votes['vote_reversal'].dtype == 'boolean'
700 assert votes['judge_dissented'].dtype == bool
701 assert votes['judge_age'].dtype == 'float64'
704def test_vote_table_options(roster: judges.Roster) -> None:
705 data = pd.DataFrame({
706 'panel_judges': [['LYNCH', 'NOBODY'], [], ['SMITH'], ['HOWARD', 'LYNCH']],
707 'dissenting': [[], [], [], ['LYNCH']],
708 'concurring': [[], [], [], ['LYNCH']],
709 'court_num': [1, 1, 9, 1],
710 'year': [2016, 2016, 2010, 2016],
711 'judge': ['kept', 'out', 'out', 'replaced'],
712 'reversed': [True, True, True, False]}, index = pd.Index(['a', 'b', 'c', 'd'], name = 'case_id'))
713 votes = judges.vote_table(data, roster, outcomes = ['reversed'])
714 # Cases with no judge who is found are left out.
715 assert list(votes.index) == ['a-1', 'd-1', 'd-2']
716 assert pd.isna(votes.loc['a-1', 'colleagues_party'])
717 assert votes.loc['d-1', 'colleagues_party'] == -1.0
718 assert list(votes['judge']) == ['Lynch, Mary Ann', 'Howard, John Q.', 'Lynch, Mary Ann']
719 assert list(votes['vote_reversed']) == [True, False, True]
720 assert votes.loc['d-2', 'judge_concurred'] and votes.loc['d-2', 'judge_dissented']
721 assert not votes['judge_author'].any()
722 assert [c for c in votes.columns if c.startswith('vote_')] == ['vote_reversed']
723 with pytest.raises(KeyError, match = 'no_such'):
724 judges.vote_table(data, roster, outcomes = ['no_such'])
725 with pytest.raises(KeyError, match = 'year'):
726 judges.vote_table(data.drop(columns = 'year'), roster)
727 assert judges.vote_table(data.iloc[1:3], roster).empty
730def test_cases_to_votes_in_a_loader(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
731 # With a roster saved where the techniques look for it, a loader can make
732 # the judges' votes, and a vote can be the label of a study.
733 roster.save()
734 dataset = loaders.LoadCourtlistener().apply(
735 None, source = court_listener_folder,
736 coders = 'code_parties, code_case_type, code_outcome, code_panels, cases_to_votes',
737 label = 'vote_reversal', groups = 'case_id')
738 assert dataset.label == 'vote_reversal'
739 assert dataset.groups == ['case_id']
740 assert dataset.data.shape[0] == 9
741 assert [e['technique'] for e in dataset.history][-2:] == ['code_panels', 'cases_to_votes']
742 assert dataset.history[-1]['rows'] == [3, 9]
743 assert {'panel_party', 'judge_party', 'colleagues_party'} <= set(dataset.data.columns)
744 shaped = judges.CasesToVotes().apply(
745 amos.Dataset(courtpy.code(courtpy.parse(court_listener_folder)).data),
746 outcomes = 'outcome_reversal')
747 assert [c for c in shaped.data.columns if c.startswith('vote_')] == ['vote_reversal']
750def test_cases_to_votes_is_a_shaper(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
751 coded = courtpy.code(courtpy.parse(court_listener_folder)).data
752 # Like every shaper, it names the label and groups of the table it makes.
753 dataset = judges.CasesToVotes().apply(
754 amos.Dataset(coded.copy(), label = 'outcome_reversal'), roster = roster,
755 label = 'vote_reversal', groups = 'case_id')
756 assert (dataset.label, dataset.task, dataset.groups) == ('vote_reversal', 'classify', ['case_id'])
757 record = dataset.history[-1]
758 assert record['rows'] == [3, 9] and record['columns'][1] == dataset.data.shape[1]
759 # It changes what a row is, so it must come before the data is split.
760 split = amos.Dataset(coded.copy(), label = 'outcome_reversal', test = coded.index[:1])
761 with pytest.raises(ValueError, match = 'before the data is split'):
762 judges.CasesToVotes().apply(split, roster = roster)
763 with pytest.raises(KeyError, match = 'no_such'):
764 judges.CasesToVotes().apply(amos.Dataset(coded.copy()), roster = roster, label = 'no_such')
767def test_build_roster_merges_by_judge() -> None:
768 files = tables()
769 # A judge who is not in the file of demographics has missing ones.
770 table = judges.build_roster(files['service'], files['demographics'].iloc[1:])
771 lynch = table.loc[table['nid'] == 101].iloc[0]
772 assert pd.isna(lynch['last_name']) and pd.isna(lynch['first_name']) and pd.isna(lynch['woman'])
773 assert judges.Roster(table).match('LYNCH', 1, 2020) is None
774 assert table.loc[table['nid'] == 102, 'last_name'].iloc[0] == 'Howard'
775 # A judge can only be one row of the demographics.
776 twice = pd.concat([files['demographics'], files['demographics'].iloc[:1]])
777 with pytest.raises(ValueError, match = 'not unique'):
778 judges.build_roster(files['service'], twice)
779 # The first of a judge's scores is used, and a judge without a number or
780 # a column that the roster already has is left out.
781 scores = pd.DataFrame({
782 'nid': [101, 101, None, '104'], 'jcs': [0.1, 0.9, 0.5, 0.4], 'party': [9, 9, 9, 9]})
783 table = judges.build_roster(files['service'], files['demographics'], scores = scores)
784 by_nid = table.drop_duplicates('nid').set_index('nid')
785 assert (by_nid.loc[101, 'jcs'], by_nid.loc[104, 'jcs']) == (0.1, 0.4)
786 assert by_nid.loc[101, 'party'] == -1
789def test_cases_to_votes_example(roster: judges.Roster, tmp_path: pathlib.Path) -> None:
790 # The example study of judges' votes, on invented cases.
791 rng = random.Random(7)
792 folder = tmp_path / 'data' / 'courtlistener'
793 bench = ['Lynch', 'Howard', 'Thompson', 'Stone', 'Woods']
794 for number in range(1, 91):
795 panel = rng.sample(bench, 3)
796 reversed_ = rng.random() < 0.4
797 dissenter = rng.choice(panel[1:]) if rng.random() < 0.3 else None
798 opinions = [make_opinion(
799 number * 10, number, author_str = panel[0],
800 html_with_citations = '<p>He appeals his sentence for possession of a firearm.</p>')]
801 if dissenter:
802 opinions.append(make_opinion(
803 number * 10 + 1, number, type = '040dissent', author_str = dissenter,
804 html_with_citations = f'<p>{dissenter.upper()}, Circuit Judge, dissenting.</p>'))
805 write_case(
806 folder,
807 make_cluster(
808 number, judges = f'Before {panel[0]}, {panel[1]}, and {panel[2]}, Circuit Judges.',
809 disposition = 'Reversed and remanded.' if reversed_ else 'Affirmed.',
810 date_filed = f'{rng.randint(2011, 2014)}-06-15'),
811 opinions)
812 roster.save()
813 idea = chrisjen.Idea.create(EXAMPLES / 'cases_to_votes.ini')
814 # The cases are in the folder already, so they are loaded, not downloaded.
815 idea['wrangler']['techniques'][0] = 'load_courtlistener'
816 idea['load_courtlistener_parameters'] = idea.contents.pop('download_courtlistener_parameters')
817 project = courtpy.Project.create(idea, clerk = tmp_path)
818 result = project.result
819 assert result.label == 'vote_reversal' and result.groups == ['case_id']
820 assert [e['technique'] for e in result.history][:7] == [
821 'load_courtlistener', 'code_parties', 'code_case_type', 'code_outcome',
822 'code_panels', 'add_executive', 'cases_to_votes']
823 assert (tmp_path / 'data' / 'votes.csv').is_file()
824 assert len(result.data) == 270
825 assert {'vote_reversal', 'case_id', 'judge_party', 'colleagues_woman',
826 'executive_ideology'} <= set(result.data.columns)
827 assert 'outcome_reversal' not in result.data.columns
828 assert set(result.tables) >= {'summarize', 'label_balance', 'analyst_comparison', 'scorecard'}
829 assert 0 <= result.metrics['roc_auc'] <= 1
830 # The judges of a case are all in the training rows or all in the test rows.
831 training = set(result.data.loc[result.train, 'case_id'])
832 assert not training & set(result.data.loc[result.test, 'case_id'])
833 # A dissenter's vote is the opposite of the case's outcome.
834 votes = judges.vote_table(courtpy.code(courtpy.parse(folder)).data, roster)
835 dissents = votes[votes['judge_dissented']]
836 assert len(dissents) > 5
837 assert (dissents['vote_reversal'] != dissents['outcome_reversal']).all()
838 # A second run loads the saved table of votes instead of making it again.
839 again = courtpy.Project.create(idea, clerk = tmp_path).result
840 assert any('reused' in entry for entry in again.history) and len(again.data) == 270
841 assert list(again.train) == list(result.train)
842 assert again.metrics['roc_auc'] == result.metrics['roc_auc']
845def test_techniques_in_a_wrangler(
846 court_listener_folder: pathlib.Path,
847 roster: judges.Roster,
848 tmp_path: pathlib.Path) -> None:
849 # As techniques of the wrangler (after the loader), they take parameters,
850 # such as a roster and a table of years that are not in the usual places.
851 folder = tmp_path / 'data' / 'courtlistener'
852 folder.parent.mkdir()
853 court_listener_folder.rename(folder)
854 # The mergers find the files that their "source" names as the clerk finds
855 # files: in the current folder, and then in the input folder.
856 named = roster.save(tmp_path / 'data' / 'my_roster.csv')
857 (tmp_path / 'data' / 'executives.csv').write_text(
858 'executive_name,executive_ideology,start_date,end_date\nChief,1,1900-01-01,2100-01-01\n', encoding = 'utf-8')
859 settings = tmp_path / 'study.ini'
860 settings.write_text(
861 '[general]\n'
862 'label = outcome_reversal\n'
863 '[files]\n'
864 'input_folder = data\n'
865 '[panels_project]\n'
866 'panels_workers = wrangler\n'
867 '[wrangler]\n'
868 'techniques = load_courtlistener, add_biography, code_panels, add_executive, cases_to_votes\n'
869 '[add_biography_parameters]\n'
870 'source = my_roster.csv\n'
871 'name = author\n'
872 'prefix = author_\n'
873 'columns = judge, party, age\n'
874 'indicator = author_found\n'
875 '[code_panels_parameters]\n'
876 f'roster = {named.as_posix()}\n'
877 '[add_executive_parameters]\n'
878 'source = executives.csv\n'
879 'prefix = state_\n'
880 '[cases_to_votes_parameters]\n'
881 f'roster = {named.as_posix()}\n'
882 'outcomes = outcome_reversal\n'
883 'label = vote_reversal\n'
884 'groups = case_id\n', encoding = 'utf-8')
885 result = courtpy.Project.create(settings, clerk = tmp_path).result
886 history = {e['technique']: e for e in result.history}
887 assert list(history)[-4:] == ['add_biography', 'code_panels', 'add_executive', 'cases_to_votes']
888 # Each merger records its source and how many rows it matched.
889 assert (history['add_biography']['source'], history['add_biography']['matched']) == ('my_roster.csv', 3)
890 assert (history['add_executive']['source'], history['add_executive']['matched']) == ('executives.csv', 3)
891 assert history['cases_to_votes']['rows'] == [3, 9]
892 # The shaper names the label and groups of the table that it makes.
893 assert (result.label, result.task, result.groups) == ('vote_reversal', 'classify', ['case_id'])
894 assert len(result.data) == 9
895 assert list(result.data['state_executive_name'].unique()) == ['Chief']
896 assert isinstance(result, courtpy.Votes)
897 assert list(result.data['author_judge'].unique()) == ['Lynch, Mary Ann']
898 assert result.data['author_found'].all() and result.data.loc['1-1', 'author_age'] == 74.0
899 assert result.data.loc['1-1', 'panel_found'] == 3
900 assert [c for c in result.data.columns if c.startswith('vote_')] == ['vote_reversal']
903def test_votes_to_cases(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
904 coded = courtpy.code(courtpy.parse(court_listener_folder)).data
905 votes = judges.CasesToVotes().apply(
906 amos.Dataset(coded.copy(), label = 'outcome_reversal'), roster = roster,
907 label = 'vote_reversal', groups = 'case_id')
908 table = votes.data.copy()
909 # It undoes `cases_to_votes`: the cases come back as they were.
910 dataset = judges.VotesToCases().apply(votes)
911 pd.testing.assert_frame_equal(dataset.data, coded)
912 # The label of the votes becomes the outcome it was made from, and the
913 # groups of the votes are dropped.
914 assert (dataset.label, dataset.groups) == ('outcome_reversal', [])
915 assert dataset.history[-1]['rows'] == [9, 3]
916 # Columns added to the votes about each judge are removed, and others
917 # are kept from each case's first row.
918 extra = table.assign(judge_extra = 1.0, colleagues_extra = 2.0, note = 'x')
919 shaped = judges.VotesToCases().shape(extra)
920 assert 'judge_extra' not in shaped and 'colleagues_extra' not in shaped
921 assert list(shaped['note']) == ['x'] * 3
922 # A case with no judge who was found is not in the table of votes.
923 some = pd.DataFrame({
924 'panel_judges': [['LYNCH'], ['NOBODY']], 'court_num': [1, 1],
925 'year': [2016, 2016]}, index = pd.Index(['a', 'b'], name = 'case_id'))
926 assert list(judges.VotesToCases().shape(judges.vote_table(some, roster)).index) == ['a']
927 with pytest.raises(KeyError, match = 'case_id'):
928 judges.VotesToCases().shape(coded.reset_index(drop = True))
931def test_cases_to_judges(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
932 coded = courtpy.code(courtpy.parse(court_listener_folder)).data
933 votes = judges.vote_table(coded, roster)
934 table = judges.CasesToJudges().shape(votes.copy())
935 assert table.index.name == 'judge_nid'
936 assert list(table.index) == [101, 102, 103]
937 assert list(table.columns[:2]) == ['judge', 'cases']
938 assert list(table['judge']) == ['Lynch, Mary Ann', 'Howard, John Q.', 'Thompson, Rita Mae']
939 assert list(table['cases']) == [3, 3, 3]
940 # Shares of votes, and the judge's attributes, which do not change.
941 assert table.loc[103, 'judge_dissented'] == pytest.approx(1 / 3)
942 assert table.loc[101, 'judge_dissented'] == 0
943 assert table.loc[101, 'judge_woman'] == 1
944 # Lynch wrote every opinion, so the column has one value for each judge.
945 assert list(table['judge_author']) == [True, False, False]
946 # Nothing about any one case is kept: text (even text that is the same
947 # in each judge's cases) and ids are left out unless "keep" names them.
948 assert 'court' not in table and 'panel_judges' not in table
949 assert 'case_id' not in table and 'case_name' not in table
950 assert 'panel_ids' not in table
951 # The shares of the judge's cases of each type are kept.
952 assert table.loc[101, 'type_criminal'] == pytest.approx(coded['type_criminal'].mean())
953 kept = judges.CasesToJudges().shape(votes.copy(), keep = ['judge', 'court'])
954 assert list(kept['court']) == ['ca1'] * 3
955 # "how" chooses other summaries, and "count" another name or none.
956 listed = judges.CasesToJudges().shape(
957 votes.copy(), how = {'case_id': 'list'}, count = None)
958 assert listed.loc[101, 'case_id'] == ['1', '2', '3']
959 assert 'cases' not in listed
960 # A table of cases is made a table of votes first.
961 pd.testing.assert_frame_equal(
962 judges.CasesToJudges().shape(coded.copy(), roster = roster), table)
965def test_cases_to_judges_is_a_shaper(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
966 coded = courtpy.code(courtpy.parse(court_listener_folder)).data
967 votes = judges.CasesToVotes().apply(
968 amos.Dataset(coded.copy(), label = 'outcome_reversal'), roster = roster,
969 label = 'vote_reversal', groups = 'case_id')
970 assert votes.task == 'classify'
971 # A vote is a share of votes for a judge, so the task is inferred again,
972 # and the groups of the votes are not columns of the judges.
973 dataset = judges.CasesToJudges().apply(votes)
974 assert (dataset.label, dataset.task, dataset.groups) == ('vote_reversal', 'regress', [])
975 assert dataset.history[-1]['rows'] == [9, 3]
976 roster.save()
977 project = courtpy.code(
978 coded.copy(), ['cases_to_judges'],
979 parameters = {'cases_to_judges': {'outcomes': 'outcome_reversal'}})
980 assert list(project.data.index) == [101, 102, 103]
981 # As in the recipe, a loader's coders can make a table of judges.
982 dataset = loaders.LoadCourtlistener().apply(
983 None, source = court_listener_folder,
984 coders = 'code_parties, code_case_type, code_outcome, cases_to_votes, cases_to_judges',
985 label = 'judge_dissented')
986 assert (dataset.label, dataset.task) == ('judge_dissented', 'regress')
987 assert dataset.data.loc[103, 'judge_dissented'] == pytest.approx(1 / 3)
990def test_load_roster(roster: judges.Roster, tmp_path: pathlib.Path) -> None:
991 # Without a source, the roster saved where the techniques look for it.
992 with pytest.raises(FileNotFoundError, match = 'no roster'):
993 judges.LoadRoster().apply(None)
994 roster.save()
995 dataset = judges.LoadRoster().apply(None)
996 assert len(dataset.data) == len(roster.data)
997 assert dataset.history[-1]['source'] == 'current'
998 path = roster.save(tmp_path / 'mine.csv')
999 dataset = judges.LoadRoster().apply(None, source = str(path))
1000 assert set(dataset.data['nid']) == set(roster.data['nid'])
1003def test_download_biographies(website: Website, tmp_path: pathlib.Path) -> None:
1004 dataset = judges.DownloadBiographies().apply(
1005 None, source = str(tmp_path / 'fjc'), save = 'true')
1006 assert len(website.urls) == 3
1007 assert 101 in set(dataset.data['nid'])
1008 # The roster was saved where the techniques look for it.
1009 assert judges.Roster.load().match('LYNCH', 1, 2020) is not None
1010 judges.DownloadBiographies().apply(None, source = str(tmp_path / 'fjc'))
1011 assert len(website.urls) == 3
1012 judges.DownloadBiographies().apply(
1013 None, source = str(tmp_path / 'fjc'), refresh = 'yes',
1014 save = str(tmp_path / 'saved.csv'))
1015 assert len(website.urls) == 6
1016 assert (tmp_path / 'saved.csv').is_file()
1019def test_add_biography_numbers_the_judges_of_cases(roster: judges.Roster) -> None:
1020 frame = pd.DataFrame({
1021 'case_id': ['a', 'b', 'c'],
1022 'panel_judges': ['LYNCH; NOBODY; HOWARD', 'THOMPSON', None],
1023 'court_num': [1, 1, 1], 'year': [2016, 2016, 2016]})
1024 cases = courtpy.Cases.create(frame.copy())
1025 data = judges.AddBiography().apply(
1026 cases, source = roster, columns = ['party', 'woman'], indicator = 'found').data
1027 assert [c for c in data.columns if c.startswith('judge_')] == [
1028 'judge_name1', 'judge_nid1', 'judge_party1', 'judge_woman1',
1029 'judge_name2', 'judge_nid2', 'judge_party2', 'judge_woman2',
1030 'judge_name3', 'judge_nid3', 'judge_party3', 'judge_woman3']
1031 assert data.loc['a', 'judge_name1'] == 'Lynch, Mary Ann' and data.loc['a', 'judge_party1'] == -1
1032 # A name that is not matched leaves its seat missing.
1033 assert pd.isna(data.loc['a', 'judge_name2']) and pd.isna(data.loc['a', 'judge_party2'])
1034 assert data.loc['a', 'judge_nid3'] == 102 and data.loc['a', 'judge_party3'] == 1
1035 assert data.loc['b', 'judge_woman1'] == 1 and pd.isna(data.loc['b', 'judge_name2'])
1036 assert list(data['found']) == [2, 1, 0]
1037 assert data['judge_nid1'].dtype == 'Int64'
1038 # With the judges' names and numbers from code_panels, only the rest are
1039 # added.
1040 paneled = judges.CodePanels().apply(courtpy.Cases.create(frame.copy()), roster = roster)
1041 data = judges.AddBiography().apply(paneled, source = roster, columns = 'party').data
1042 assert [c for c in data.columns if c.startswith('judge_party')] == ['judge_party1', 'judge_party2', 'judge_party3']
1043 # A named column of one judge in each case is not numbered.
1044 data = judges.AddBiography().apply(
1045 courtpy.Cases.create(frame.assign(author = ['LYNCH', None, None])), source = roster,
1046 name = 'author', prefix = 'author_', columns = 'party').data
1047 assert list(data['author_party'].fillna(0)) == [-1, 0, 0]
1050def test_add_biography_with_a_lookup() -> None:
1051 known = {'LYNCH': {'party': -1, 'school': 'Harvard'}, 'HOWARD': {'party': 1}}
1052 def lookup(name: str, court: int | None, year: int | None) -> dict[str, Any] | None:
1053 return known.get(name)
1054 cases = courtpy.Cases.create(pd.DataFrame({
1055 'case_id': ['a'], 'panel_judges': ['LYNCH; NOBODY; HOWARD'], 'court_num': [1], 'year': [2016]}))
1056 data = judges.AddBiography().apply(cases, lookup = lookup).data
1057 assert data.loc['a', 'judge_name1'] == 'LYNCH' and pd.isna(data.loc['a', 'judge_name2'])
1058 assert (data.loc['a', 'judge_party1'], data.loc['a', 'judge_party3']) == (-1, 1)
1059 assert data.loc['a', 'judge_school1'] == 'Harvard' and pd.isna(data.loc['a', 'judge_school3'])
1060 assert 'judge_nid1' not in data
1061 votes = amos.Dataset(pd.DataFrame({'judge': ['HOWARD'], 'court_num': [1], 'year': [2016]}))
1062 assert judges.AddBiography().apply(votes, lookup = lookup, columns = 'party').data.loc[0, 'judge_party'] == 1
1065def test_add_jcs(roster: judges.Roster) -> None:
1066 assert amos.library.classify('add_jcs') == 'merger'
1067 scored = judges.Roster(roster.data.assign(jcs = [-0.4, 0.3, -0.2, 0.5, 0.4, 0.2, 0.1, 0.1, -0.3, -0.3, -0.5, 0.4, -0.1, None]))
1068 votes = amos.Dataset(pd.DataFrame({'judge': ['LYNCH', 'HOWARD'], 'court_num': [1, 1], 'year': [2016, 2016]}))
1069 data = judges.AddJcs().apply(votes, source = scored).data
1070 assert list(data.columns) == ['judge', 'court_num', 'year', 'judge_jcs']
1071 assert list(data['judge_jcs']) == [-0.4, 0.3]
1072 cases = courtpy.Cases.create(pd.DataFrame({
1073 'case_id': ['a'], 'panel_judges': ['LYNCH; HOWARD'], 'court_num': [1], 'year': [2016]}))
1074 data = judges.AddJcs().apply(cases, source = scored).data
1075 assert (data.loc['a', 'judge_jcs1'], data.loc['a', 'judge_jcs2']) == (-0.4, 0.3)
1076 with pytest.raises(KeyError, match = r'jcs = True'):
1077 judges.AddJcs().apply(votes, source = roster)
1080def test_add_circuit(roster: judges.Roster) -> None:
1081 assert amos.library.classify('add_circuit') == 'merger'
1082 frame = pd.DataFrame({
1083 'case_id': ['a', 'b', 'c', 'd', 'e'],
1084 'date_filed': ['2016-06-15', '2000-01-01', '2016-06-15', None, '2016-06-15'],
1085 'court_num': pd.array([1, 1, pd.NA, 1, 99], dtype = 'Int64'),
1086 # A district court's case is in the circuit of its district.
1087 'court': ['ca1', 'ca1', 'mad', 'ca1', 'scotus']})
1088 cases = courtpy.Cases.create(frame.copy())
1089 with pytest.warns(amos.AmosWarning, match = 'jcs = True'):
1090 data = judges.AddCircuit().apply(cases, source = roster).data
1091 # On June 15, 2016, Lynch, Howard, and Thompson were active, and Stone
1092 # had taken senior status. In 2000, Lynch and Stone were active.
1093 assert list(data.loc[['a', 'c'], 'circuit_median_party']) == [-1, -1]
1094 assert list(data.loc[['a', 'c'], 'circuit_total_party']) == [-1, -1]
1095 assert list(data.loc[['a', 'b', 'c'], 'circuit_judges']) == [3, 2, 3]
1096 assert (data.loc['b', 'circuit_median_party'], data.loc['b', 'circuit_total_party']) == (0, 0)
1097 # A case with no date, or in no circuit, gets missing values.
1098 assert data.loc[['d', 'e'], ['circuit_median_party', 'circuit_judges']].isna().all().all()
1099 assert 'circuit_median_jcs' not in data
1100 scored = judges.Roster(roster.data.assign(jcs = [-0.4, 0.3, -0.2, 0.5, 0.4, 0.2, 0.1, 0.1, -0.3, -0.3, -0.5, 0.4, -0.1, None]))
1101 data = judges.AddCircuit().apply(courtpy.Cases.create(frame.iloc[:2].copy()), source = scored).data
1102 assert data.loc['a', 'circuit_median_jcs'] == pytest.approx(-0.2)
1103 assert data.loc['a', 'circuit_total_jcs'] == pytest.approx(-0.3)
1104 assert data.loc['b', 'circuit_total_jcs'] == pytest.approx(-0.3)
1105 with pytest.raises(KeyError, match = 'summarizes'):
1106 judges.AddCircuit().apply(courtpy.Cases.create(frame.copy()), source = scored, columns = 'woman')
1109def test_conversions_make_their_kinds(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
1110 coded = courtpy.code(courtpy.parse(court_listener_folder))
1111 assert isinstance(coded, courtpy.Cases)
1112 votes = judges.CasesToVotes().apply(coded, roster = roster)
1113 assert isinstance(votes, courtpy.Votes) and votes.data.index.name == 'vote_id'
1114 back = judges.VotesToCases().apply(courtpy.Votes.create(votes.data.copy()))
1115 assert isinstance(back, courtpy.Cases) and back.data.index.name == 'case_id'
1116 judged = judges.CasesToJudges().apply(courtpy.Votes.create(votes.data.copy()))
1117 assert isinstance(judged, courtpy.Judges) and judged.data.index.name == 'judge_nid'
1120def test_dockets_to_votes(court_listener_folder: pathlib.Path, roster: judges.Roster) -> None:
1121 assert amos.library.classify('dockets_to_votes') == 'shaper'
1122 coded = courtpy.code(courtpy.parse(court_listener_folder)).data
1123 coded['docket_numbers'] = ['17-1; 17-2', '18-5', None]
1124 dockets = courtpy.code(courtpy.Cases.create(coded), ['cases_to_dockets'])
1125 votes = judges.DocketsToVotes().apply(dockets, roster = roster, label = 'vote_reversal', groups = 'case_id')
1126 assert isinstance(votes, courtpy.Votes)
1127 data = votes.data
1128 # Each judge votes once on each docket of a case.
1129 assert list(data.index[:4]) == ['1-1-1', '1-1-2', '1-1-3', '1-2-1']
1130 assert len(data) == 3 * 4
1131 assert list(data['case_docket'].unique()) == ['1-1', '1-2', '2-1', '3-1']
1132 assert set(data.loc[data['case_docket'] == '1-2', 'case_id']) == {'1'}
1133 assert {'docket', 'judge_party', 'vote_reversal'} <= set(data.columns)
1134 # Made cases again, the dockets' columns are removed.
1135 back = judges.VotesToCases().apply(votes)
1136 assert list(back.data.index) == ['1', '2', '3']
1137 assert not {'case_docket', 'docket'} & set(back.data.columns)
1138 with pytest.raises(KeyError, match = 'cases_to_dockets'):
1139 judges.DocketsToVotes().shape(pd.DataFrame({'x': [1]}), roster = roster)
1142def test_panel_compositions() -> None:
1143 seats = pd.DataFrame({
1144 'judge_party1': [-1, 1, -1, 1],
1145 'judge_party2': [-1, 1, 1, 1],
1146 'judge_party3': [-1, 1, 1, None]})
1147 assert courtpy.judges.republican_appointees(seats).tolist() == [0, 3, 2, pd.NA]
1148 found = courtpy.judges.panel_compositions(seats)
1149 assert found.tolist()[:3] == ['DDD', 'RRR', 'DRR'] and pd.isna(found.iloc[3])
1150 assert list(found.cat.categories) == ['DDD', 'DDR', 'DRR', 'RRR']
1151 # A fourth judge makes a panel of another size.
1152 four = seats.assign(judge_party4 = [None, 1, None, None])
1153 assert courtpy.judges.republican_appointees(four).tolist()[:2] == [0, pd.NA]
1154 # From code_panels' mean party.
1155 means = pd.DataFrame({'panel_party': [-1 / 3, 1.0, 0.5], 'panel_found': [3, 3, 2]})
1156 assert courtpy.judges.republican_appointees(means).tolist() == [1, 3, pd.NA]
1157 with pytest.raises(KeyError, match = 'add_biography'):
1158 courtpy.judges.republican_appointees(pd.DataFrame({'year': [2008]}))