Coverage for src/courtpy/references/courts.py: 99%
59 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"""The courts of each jurisdiction, and the circuit of each federal case.
3The table of a jurisdiction's courts is "courts.csv" in its folder of
4"instructions" (such as "instructions/federal/courts.csv"), which can be
5opened in a spreadsheet, with one row for each court:
7| Column | Meaning |
8| --- | --- |
9| `court_num` | courtpy's number for the court: 1 to 13 for the courts of appeals (12 for the D.C. Circuit and 13 for the Federal Circuit), as the rules that make "court_num" for cases number them, 99 for the Supreme Court, 101 and up for specialized and historical courts (such as the bankruptcy appellate panels), and 1001 and up for the district courts. |
10| `court` | A name for the court that can be a folder's name (such as "southern_district_of_new_york", or "scotus" for the Supreme Court). |
11| `feature_name` | The court's name as a label for tables and plots (such as "Southern District of New York"). |
12| `level` | "high", "appellate", "trial", or "specialty", which state courts will share. |
13| `circuit_num` | The number of the court of appeals that hears its appeals (for a district court, that of its state, as fjc-biographies numbers them). |
14| `courtlistener_name` | CourtListener's id for the court (such as "nysd"), if it has one. |
15| `fjc_name` | A regular expression for the Federal Judicial Center's names for the court, matched ignoring case. Several names are separated by a vertical bar. |
16| `opinion_name` | A regular expression for how an opinion names the court (its name, or its abbreviation in a citation, such as "S.D.N.Y.", "S. D. N.Y.", or "S.D. New York"), matched ignoring case. The header rules of a source whose cases name their court in text (such as Lexis-Nexis) find "court_num" and "court_name" with it, and then with `fjc_name`, and every source's header rules find the trial or specialized court whose decision is reviewed in the history the same way ("lower_court_num" and "lower_court_name"; see `courtpy.rules.make_court_rules`). |
18The header rules have no names of courts of their own, so a court added to
19the table is found in cases without changing any rules. CourtListener cases
20find "court_num" and "court_name" by CourtListener's id for the court
21instead (see `court_numbers_by_courtlistener_name` and
22`court_names_by_courtlistener_name`), and "lower_court_num" and
23"lower_court_name" by the id of the court appealed from, if the docket has
24it.
26`circuits` finds the circuit of each case in a table of cases, which
27`add_circuit` uses.
29Contents:
30 circuits: returns the number of the circuit of each case.
31 court_labels: returns the label of each case's court for tables and
32 plots, in the order of the table of courts.
33 court_names_by_courtlistener_name: returns courtpy's name for each
34 court, by CourtListener's id for it.
35 court_numbers_by_courtlistener_name: returns courtpy's number for each
36 court, by CourtListener's id for it.
37 court_table: returns the table of a jurisdiction's courts.
38 federal_courts: returns the table of the federal courts.
39 _COURTS_FILE_NAME: the name of the file of each jurisdiction's courts.
41"""
43from __future__ import annotations
45import functools
46import types
47from collections.abc import Mapping
48from typing import Any
50import pandas as pd
52from ..core import utilities
54_COURTS_FILE_NAME = 'courts.csv'
57""" Public Functions """
60def circuits(
61 data: pd.DataFrame,
62 *,
63 court_num: str = 'court_num',
64 court: str = 'court') -> pd.Series:
65 """Returns the number of the circuit of each case.
67 A case of a court of appeals is in its own circuit ("court_num" from 1 to
68 13). Any other case is in the circuit that `federal_courts` gives its
69 court, which is found by CourtListener's id for the court (the "court"
70 column of CourtListener cases, such as "nysd") or else by courtpy's
71 number for it.
73 Args:
74 data: the cases.
75 court_num: the column with courtpy's number for each case's court.
76 Defaults to "court_num".
77 court: the column with CourtListener's id for each case's court.
78 Defaults to "court".
80 Returns:
81 The number of each case's circuit, as whole numbers, missing for a
82 case whose court is not known or (like the Supreme Court) is in
83 no circuit.
85 """
86 table = federal_courts()
87 found = pd.Series(pd.NA, index = data.index, dtype = 'Int64')
88 if court in data.columns:
89 by_id = table.dropna(subset = ['courtlistener_name']).set_index(
90 'courtlistener_name')['circuit_num']
91 found = found.fillna(
92 data[court].astype('string').str.lower().map(by_id)
93 .astype('Int64'))
94 if court_num in data.columns: 94 ↛ 99line 94 didn't jump to line 99 because the condition on line 94 was always true
95 numbers = pd.to_numeric(data[court_num], errors = 'coerce')
96 by_number = table.drop_duplicates('court_num').set_index(
97 'court_num')['circuit_num']
98 found = found.fillna(numbers.map(by_number).astype('Int64'))
99 return found
102def court_labels(
103 data: pd.DataFrame,
104 *,
105 court_name: str = 'court_name',
106 court_num: str = 'court_num',
107 jurisdiction: str = 'federal') -> pd.Series:
108 """Returns the label of each case's court for tables and plots.
110 A court's label is its "feature_name" in the table of courts (such as
111 "Southern District of New York"), found by courtpy's name for the court
112 (such as "southern_district_of_new_york") or else by its number. A
113 number that several courts share (as 9 is the Ninth Circuit's and the
114 old Circuit Court for the Districts of California's) labels the court
115 that CourtListener has.
117 Args:
118 data: the cases.
119 court_name: the column with courtpy's name for each case's court.
120 Defaults to "court_name".
121 court_num: the column with courtpy's number for each case's court.
122 Defaults to "court_num".
123 jurisdiction: the folder of the jurisdiction's instructions, such as
124 "federal". Defaults to "federal".
126 Raises:
127 KeyError: if `data` has neither column.
128 FileNotFoundError: if the jurisdiction has no table of courts.
130 Returns:
131 The labels, as an ordered category whose categories are the courts
132 that the cases have, in the order of the table of courts (so the
133 courts of appeals come first, by number). A case whose court is
134 not known has a missing label.
136 """
137 if court_name not in data.columns and court_num not in data.columns:
138 message = (
139 f'the cases have neither {court_name!r} nor {court_num!r}, so '
140 f'their courts cannot be labeled')
141 raise KeyError(message)
142 table = court_table(jurisdiction)
143 labels = pd.Series(pd.NA, index = data.index, dtype = object)
144 if court_name in data.columns:
145 by_name = dict(zip(table['court'], table['feature_name'], strict = True))
146 labels = data[court_name].map(by_name)
147 if court_num in data.columns:
148 # The courts that CourtListener has come first, so that a shared
149 # number labels the court that cases come from.
150 modern = table.sort_values(
151 'courtlistener_name', key = lambda found: found.isna(),
152 kind = 'stable').drop_duplicates('court_num')
153 by_number = dict(zip(
154 modern['court_num'], modern['feature_name'], strict = True))
155 numbers = pd.to_numeric(data[court_num], errors = 'coerce')
156 labels = labels.fillna(numbers.map(by_number))
157 present = set(labels.dropna())
158 order = [c for c in dict.fromkeys(table['feature_name']) if c in present]
159 return pd.Series(
160 pd.Categorical(labels, categories = order, ordered = True),
161 index = data.index, name = 'court')
164def court_names_by_courtlistener_name(
165 jurisdiction: str = 'federal') -> Mapping[str, str]:
166 """Returns courtpy's name for each court, by CourtListener's id for it.
168 Args:
169 jurisdiction: the folder of the jurisdiction's instructions, such as
170 "federal". Defaults to "federal".
172 Raises:
173 FileNotFoundError: if the jurisdiction has no table of courts.
175 Returns:
176 The "court" of each court that has a "courtlistener_name" (such as
177 "first_circuit" for "ca1"), by that id in lower case. It is read
178 only, and made once for each jurisdiction, since it is used for
179 every case.
181 """
182 return _index_courtlistener_courts(jurisdiction, 'court')
185def court_numbers_by_courtlistener_name(
186 jurisdiction: str = 'federal') -> Mapping[str, int]:
187 """Returns courtpy's number for each court, by CourtListener's id for it.
189 Args:
190 jurisdiction: the folder of the jurisdiction's instructions, such as
191 "federal". Defaults to "federal".
193 Raises:
194 FileNotFoundError: if the jurisdiction has no table of courts.
196 Returns:
197 The "court_num" of each court that has a "courtlistener_name" (such
198 as 1 for "ca1"), by that id in lower case. It is read only, and
199 made once for each jurisdiction, since it is used for every
200 case.
202 """
203 return _index_courtlistener_courts(jurisdiction, 'court_num')
206def court_table(jurisdiction: str = 'federal') -> pd.DataFrame:
207 """Returns the table of a jurisdiction's courts.
209 Args:
210 jurisdiction: the folder of the jurisdiction's instructions, such as
211 "federal". Defaults to "federal".
213 Raises:
214 FileNotFoundError: if the jurisdiction has no table of courts.
216 Returns:
217 A copy of the jurisdiction's "courts.csv" (see the module's
218 documentation), with "court_num" and "circuit_num" as whole
219 numbers (missing for a court in no circuit).
221 """
222 return _read_courts(jurisdiction).copy()
225def federal_courts() -> pd.DataFrame:
226 """Returns the table of the federal courts.
228 Returns:
229 A copy of the table of the federal courts (see `court_table`).
231 """
232 return court_table('federal')
235""" Private Functions """
238@functools.cache
239def _index_courtlistener_courts(
240 jurisdiction: str,
241 column: str) -> Mapping[str, Any]:
242 """Maps CourtListener's id for each court to a column of its row, once.
244 Args:
245 jurisdiction: the folder of the jurisdiction's instructions.
246 column: the column of the table of courts, such as "court_num".
248 Raises:
249 FileNotFoundError: if the jurisdiction has no table of courts.
251 Returns:
252 The value of `column` for each court that has an id (as a Python
253 `int` or `str`), by the id in lower case, as a read-only
254 mapping.
256 """
257 table = _read_courts(jurisdiction).dropna(subset = ['courtlistener_name'])
258 values = table[column].tolist()
259 return types.MappingProxyType(dict(zip(
260 table['courtlistener_name'].str.lower(), values, strict = True)))
263@functools.cache
264def _read_courts(jurisdiction: str) -> pd.DataFrame:
265 """Reads the table of a jurisdiction's courts once.
267 Args:
268 jurisdiction: the folder of the jurisdiction's instructions.
270 Raises:
271 FileNotFoundError: if the jurisdiction has no table of courts.
273 Returns:
274 The table in the jurisdiction's `_COURTS_FILE_NAME`.
276 """
277 path = utilities.instructions_folder() / jurisdiction / _COURTS_FILE_NAME
278 if not path.is_file():
279 message = f'there is no table of courts for {jurisdiction!r}: {path}'
280 raise FileNotFoundError(message)
281 table = utilities.read_csv(
282 path, dtype = {'courtlistener_name': 'string'},
283 keep_default_na = False, na_values = [''])
284 return table.astype({'court_num': 'int64', 'circuit_num': 'Int64'})