Coverage for src/courtpy/references/scdb.py: 100%
137 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"""Adds the Supreme Court Database's coding to cases of the Supreme Court.
3The Supreme Court Database (https://scdb.la.psu.edu) codes every case that
4the Supreme Court has decided since its 1946 term: the issue, the direction
5of the decision, what the court did with the decision below, which party won,
6and how each justice voted, among much else. Its online codebook explains
7each variable.
9`download` gets the latest release from https://scdb.la.psu.edu/data/ and
10keeps it outside of projects (in "scdb" in `courtpy.utilities.data_folder()`).
11`cases` returns its table with a row for each case, and `votes` its table
12with a row for each justice in each case. Both keep the database's names for
13their columns (such as "issueArea" and "decisionDirection"), so the codebook
14applies to them as it is.
16`add_scdb` (an `amos.Merger`, which is added to the `amos` library as soon
17as courtpy is imported) adds the database's columns to parsed cases of the
18Supreme Court, with "scdb_" before their names. A case is matched by the
19database's id for it, which CourtListener records ("scdb_id"), or else by
20one of its citations:
22```python
23import courtpy
25cases = courtpy.parse("data/courtlistener")
26dataset = courtpy.code(cases, "add_scdb", parameters = {
27 "add_scdb": {"columns": "issueArea, decisionDirection, partyWinning"}})
28```
30`load_scdb` and `download_scdb` (reference loaders, see
31`courtpy.loaders.ReferenceLoader`) start a study of the database itself,
32such as of how the justices vote ("kind" set to "votes").
34Contents:
35 AddScdb: adds the Supreme Court Database's columns to each case.
36 DownloadScdb: downloads the Supreme Court Database and loads its cases
37 or votes.
38 LoadScdb: loads the Supreme Court Database's table of cases or of votes.
39 cases: returns the database's table with a row for each case.
40 download: downloads the latest release of the database.
41 votes: returns the database's table with a row for each justice in each
42 case.
43 _CITATIONS: the columns of the database with the citations of a case, in
44 the order in which they are tried.
45 _SEPARATORS: pattern for the text between the citations of a case in a
46 table of parsed cases.
47 _SYMBOLS: pattern for everything in a citation other than letters and
48 digits, which `_cite` removes.
50"""
52from __future__ import annotations
54import dataclasses
55import pathlib
56import re
57from collections.abc import Sequence
58from typing import Any
60import amos
61import numpy as np
62import pandas as pd
64from ..core import options, utilities
65from ..wrangler import loaders
67_CITATIONS: tuple[str, ...] = ('usCite', 'sctCite', 'ledCite', 'lexisCite')
68_SEPARATORS: re.Pattern[str] = re.compile(r'[;\n]')
69_SYMBOLS: re.Pattern[str] = re.compile(r'[^A-Z0-9]')
72@dataclasses.dataclass
73class AddScdb(amos.Merger):
74 """Adds the Supreme Court Database's columns to each case.
76 Each case is matched to the database's row for it: the row with the
77 case's id in the database ("scdb_id", which CourtListener records for
78 cases of the Supreme Court), or else the row with one of the case's
79 citations (such as "347 U.S. 483"). Rather than guess, a case whose
80 citations are those of more than one row of the database (as short
81 orders on one page of a reporter are) is not matched. A case that is not
82 matched, such as a case of another court, gets missing values.
84 Like every merger of `amos`, it takes these parameters, never adds,
85 removes, or reorders rows, and records how many cases it matched in the
86 dataset's history:
88 | Parameter | Meaning |
89 | --- | --- |
90 | `source` | The database's table of cases: the path of its file (looked for in the current folder and then in the clerk's input folder), or a table. Without it, the latest release is used, which is downloaded unless it was before (see `download`). |
91 | `columns` | The columns of the database to add, by its names for them (such as "issueArea"). By default, they are all of them. |
92 | `prefix` | Text to put before the names of the added columns. It is "scdb_" unless another is set. |
93 | `indicator` | The name of a column to make that says whether each case was found in the database. |
94 | `on`, `other_on` | The columns of the cases and of the database with the database's id of each case. They are "scdb_id" and "caseId" unless others are set. |
95 | `citations` | The column of the cases with their citations. It is "citation" unless another is set. |
97 Needs "scdb_id" or "citation" (or the columns named by "on" and
98 "citations").
100 """
102 """ Public Methods """
104 def apply(
105 self,
106 item: amos.Dataset,
107 *,
108 source: Any = None,
109 columns: Sequence[str] | str | None = None,
110 prefix: str | None = 'scdb_',
111 **kwargs: Any) -> amos.Dataset:
112 """Adds the database's columns for each case of `item`.
114 Args:
115 item: the dataset of parsed cases.
116 source: the database's table of cases, or the path of its file.
117 Defaults to `None`, in which case the latest release is
118 used, which is downloaded unless it was before.
119 columns: the columns of the database to add, as a list or as
120 text with commas between their names. Defaults to `None`,
121 for all of them.
122 prefix: text to put before the names of the added columns.
123 Defaults to "scdb_".
124 **kwargs: other parameters of the mergers of `amos` (such as
125 "indicator"), and those of `match`.
127 Raises:
128 KeyError: if the cases have neither the column of ids nor the
129 column of citations, or one of "columns" is not in the
130 database.
131 ValueError: if an added column would have the name of a column
132 of the cases.
134 Returns:
135 The dataset, with the new columns.
137 """
138 if source is None:
139 source = download(kinds = 'cases')['cases']
140 return super().apply(
141 item,
142 source = source,
143 columns = None if columns is None else utilities.listify(columns),
144 prefix = prefix,
145 **kwargs)
147 def match(
148 self,
149 data: pd.DataFrame,
150 other: pd.DataFrame,
151 *,
152 on: str = 'scdb_id',
153 other_on: str = 'caseId',
154 citations: str = 'citation',
155 **kwargs: Any) -> Any:
156 """Returns the row of the database for each case.
158 Args:
159 data: the parsed cases.
160 other: the database's table of cases.
161 on: the column of `data` with the database's id of each case.
162 Defaults to "scdb_id".
163 other_on: the column of `other` with its id of each case.
164 Defaults to "caseId".
165 citations: the column of `data` with the citations of each case:
166 lists of them, or text with semicolons or line breaks
167 between them. Defaults to "citation".
168 **kwargs: not used.
170 Raises:
171 KeyError: if `data` has neither `on` nor `citations`, or `other`
172 lacks `other_on`.
174 Returns:
175 The position of the matching row of `other` for each row of
176 `data`, or -1 if there is none.
178 """
179 if on not in data.columns and citations not in data.columns:
180 message = (
181 f'{self.name!r} needs the column {on!r} (the Supreme Court '
182 f"Database's id of each case, which CourtListener records "
183 f'for cases of the Supreme Court) or {citations!r} (the '
184 f'citations of each case), and the cases have neither'
185 )
186 raise KeyError(message)
187 if other_on not in other.columns:
188 message = f'the columns {[other_on]} are not in the other table'
189 raise KeyError(message)
190 positions = np.full(len(data), -1, dtype = 'int64')
191 if on in data.columns:
192 # The first row with an id is used, since the database's other
193 # files have a row for each docket or issue of a case.
194 ids = other[other_on].astype(str).str.strip()
195 first = pd.Series(np.arange(len(other)), index = ids)
196 first = first[~first.index.duplicated()]
197 wanted = data[on].astype('object').map(
198 lambda value: str(value).strip() if pd.notna(value) else '')
199 positions = wanted.map(first).fillna(-1).to_numpy(dtype = 'int64')
200 if citations in data.columns and (positions < 0).any():
201 rows = _cited(other)
202 listed = data[citations].tolist()
203 for place in np.flatnonzero(positions < 0):
204 cell = listed[place]
205 if isinstance(cell, str):
206 cell = _SEPARATORS.split(cell)
207 elif not isinstance(cell, list | tuple):
208 continue
209 found = {
210 rows[cite] for cite in map(_cite, cell) if cite in rows}
211 # Citations of more than one case, or of rows that several
212 # cases share, do not say which case this is.
213 if len(found) == 1 and -1 not in found:
214 positions[place] = found.pop()
215 return positions
217 def read(self, source: Any, **kwargs: Any) -> pd.DataFrame:
218 """Returns the database's table of cases.
220 Args:
221 source: the path of the database's file (a CSV file, or a zip
222 archive of one, as it is downloaded), or a table.
223 **kwargs: parameters for loading any other kind of source (see
224 `amos.Merger.read`).
226 Returns:
227 The table.
229 """
230 if isinstance(source, str | pathlib.Path):
231 return cases(utilities.locate(source, self.clerk))
232 return super().read(source, **kwargs)
235@dataclasses.dataclass
236class LoadScdb(loaders.ReferenceLoader):
237 """Loads the Supreme Court Database's table of cases or of votes.
239 The table starts a study of the database itself, such as of how the
240 justices vote ("kind" set to "votes"). Its "source" is the path of one
241 of the database's files. Without one, the latest release that was
242 downloaded is used, which is downloaded first if there is none (see
243 `download`). To add the database's columns to parsed cases, use
244 `add_scdb` instead.
246 """
248 """ Public Methods """
250 def load(
251 self,
252 source: Any,
253 *,
254 kind: str = 'cases',
255 **kwargs: Any) -> pd.DataFrame:
256 """Returns the database's table.
258 Args:
259 source: the path of the database's file of the kind (a CSV file
260 or the zip archive of one), or "current" for the latest
261 release that was downloaded.
262 kind: "cases" (a row for each case) or "votes" (a row for each
263 justice in each case). Defaults to "cases".
264 **kwargs: not used.
266 Returns:
267 The table (see `cases` and `votes`).
269 """
270 return _read(self._locate(source), _kind(kind))
273@dataclasses.dataclass
274class DownloadScdb(loaders.ReferenceLoader):
275 """Downloads the Supreme Court Database and loads its cases or votes.
277 The file is downloaded (see `download`) unless the folder has one
278 already, or "refresh" is true, which looks for a newer release. Its
279 "source" is the folder to keep the files in, which is "scdb" in
280 `courtpy.utilities.data_folder()` unless another is set.
282 """
284 """ Public Methods """
286 def load(
287 self,
288 source: Any,
289 *,
290 kind: str = 'cases',
291 refresh: bool | str = False,
292 session: Any = None,
293 **kwargs: Any) -> pd.DataFrame:
294 """Downloads the database's file of a kind and returns its table.
296 Args:
297 source: the folder to keep the files in, or "current" for "scdb"
298 in `utilities.data_folder()`.
299 kind: "cases" (a row for each case) or "votes" (a row for each
300 justice in each case). Defaults to "cases".
301 refresh: whether to look for the latest release even if the
302 folder has a file of the kind. Defaults to `False`.
303 session: an object with a `get` method like a
304 `requests.Session`. Defaults to `None`, in which case a
305 `requests.Session` is made.
306 **kwargs: not used.
308 Returns:
309 The table (see `cases` and `votes`).
311 """
312 kind = _kind(kind)
313 paths = download(
314 self._locate(source),
315 kinds = kind,
316 overwrite = utilities.to_bool(refresh),
317 session = session)
318 return _read(paths[kind], kind)
321def cases(
322 source: pd.DataFrame | pathlib.Path | str | None = None) -> pd.DataFrame:
323 """Returns the Supreme Court Database's table with a row for each case.
325 Args:
326 source: the database's case centered file that is organized by
327 citation (a CSV file, or the zip archive of one that
328 https://scdb.la.psu.edu/data/ offers), as a path or a table.
329 Defaults to `None`, in which case the latest release is used,
330 which is downloaded unless it was before (see `download`).
332 Returns:
333 The table, with the database's names for its columns: "caseId" (such
334 as "1946-001"), "usCite", "term", "caseName", "issueArea",
335 "decisionDirection", "partyWinning", "majVotes", "minVotes", and
336 the rest that its codebook explains.
338 """
339 return _read(source, 'cases')
342def download(
343 folder: pathlib.Path | str | None = None,
344 *,
345 kinds: Sequence[str] | str | None = None,
346 overwrite: bool = False,
347 session: Any = None) -> dict[str, pathlib.Path]:
348 """Downloads the latest release of the Supreme Court Database.
350 The files are those of the modern database (the terms since 1946) that
351 are organized by citation, as zip archives of CSV files. They need no
352 account:
354 | Kind | File |
355 | --- | --- |
356 | `cases` | The case centered data: a row for each case (less than a megabyte). |
357 | `votes` | The justice centered data: a row for each justice in each case (about 2 megabytes). |
359 A file is saved with the name of its release (such as
360 "SCDB_2026_01_caseCentered_Citation.csv.zip"), so the release that a
361 study used is in the dataset's history. The database's page lists its
362 releases, and the page of the latest one links to its files, so they are
363 found by those links.
365 Args:
366 folder: the folder to save them in. Defaults to `None`, in which case
367 "scdb" in `utilities.data_folder()` is used.
368 kinds: the files to download: "cases", "votes", or both. Defaults to
369 `None`, for both.
370 overwrite: whether to look for the latest release even if the folder
371 has a file of an earlier one (or of the same one). A new release
372 comes out each year. Defaults to `False`.
373 session: an object with a `get` method like a `requests.Session`.
374 Defaults to `None`, in which case a `requests.Session` is made.
376 Raises:
377 requests.HTTPError: if a page or a file cannot be downloaded.
378 ValueError: if one of `kinds` is not a file that courtpy knows, or
379 the database's pages do not link to the files as they did.
381 Returns:
382 The path of each file, by its kind. If the folder has the files of
383 more than one release, they are those of the latest.
385 """
386 files = options._SCDB_FILES
387 wanted = list(files) if kinds is None else utilities.listify(kinds)
388 unknown = [kind for kind in wanted if kind not in files]
389 if unknown:
390 message = f'kinds must be among {list(files)}, not {unknown}'
391 raise ValueError(message)
392 folder = pathlib.Path(folder).expanduser() if folder else _folder()
393 session = utilities.open_session(session)
394 release: tuple[str, list[str]] | None = None
395 paths = {}
396 for kind in wanted:
397 saved = sorted(folder.glob(f'*{files[kind]}*')) if not overwrite else []
398 if saved:
399 paths[kind] = saved[-1]
400 continue
401 release = release or _release(session)
402 name, addresses = release
403 path = folder / f'{name}_{files[kind]}.csv.zip'
404 # The links to both files have the same words, so the file is
405 # checked before it is saved.
406 try:
407 paths[kind] = amos.loaders.download_file(
408 addresses[list(files).index(kind)],
409 path,
410 refresh = True,
411 timeout = options._TIMEOUT,
412 session = session,
413 required_member = f'*{files[kind]}*')
414 except ValueError as error:
415 message = (
416 f'the file that {options._SCDB_PAGE} links to for the '
417 f'{kind} of the Supreme Court Database is not its '
418 f'{files[kind]} file: download the file and pass its path '
419 f'instead'
420 )
421 raise ValueError(message) from error
422 return paths
425def votes(
426 source: pd.DataFrame | pathlib.Path | str | None = None) -> pd.DataFrame:
427 """Returns the database's table with a row for each justice in each case.
429 The table is for studying how the justices vote. The Martin-Quinn score
430 of each justice in each term (see `courtpy.politics.justices`) can be
431 added to it with the `merge_keys` technique of `amos`, by "term" and
432 "justice".
434 Args:
435 source: the database's justice centered file that is organized by
436 citation (a CSV file, or the zip archive of one that
437 https://scdb.la.psu.edu/data/ offers), as a path or a table.
438 Defaults to `None`, in which case the latest release is used,
439 which is downloaded unless it was before (see `download`).
441 Returns:
442 The table, with the columns of `cases` (repeated for each justice of
443 a case) and those of the justice: "justice" and "justiceName"
444 (the database's number and name for the justice, such as 117 and
445 "ACBarrett"), "vote", "opinion", "direction", "majority",
446 "firstAgreement", and "secondAgreement".
448 """
449 return _read(source, 'votes')
452""" Private Functions """
455def _cite(citation: Any) -> str:
456 """Returns a citation the way that citations are compared.
458 Args:
459 citation: a citation, such as "347 U.S. 483" or "74 S.Ct. 686".
461 Returns:
462 The citation in capital letters, without spaces or punctuation (such
463 as "347US483"), or an empty `str` if `citation` is not text.
465 """
466 if not isinstance(citation, str):
467 return ''
468 return _SYMBOLS.sub('', citation.upper())
471def _cited(table: pd.DataFrame) -> dict[str, int]:
472 """Returns the row of the database for each citation that one row has.
474 Args:
475 table: the database's table of cases.
477 Returns:
478 The position of the row with each citation (as `_cite` writes it) in
479 any of the columns of `_CITATIONS`. A citation that more than
480 one row has (as short orders on one page of a reporter do) is
481 given -1, since it does not say which case is meant.
483 """
484 rows: dict[str, int] = {}
485 for column in _CITATIONS:
486 if column not in table.columns:
487 continue
488 for position, citation in enumerate(table[column].tolist()):
489 cite = _cite(citation)
490 if cite:
491 shared = rows.get(cite, position) != position
492 rows[cite] = -1 if shared else position
493 return rows
496def _kind(kind: Any) -> str:
497 """Returns a kind of the database's files, checked.
499 Args:
500 kind: "cases" or "votes".
502 Raises:
503 ValueError: if `kind` is not one of the files that courtpy knows.
505 Returns:
506 `kind` as text.
508 """
509 text = str(kind).strip()
510 if text not in options._SCDB_FILES:
511 message = (
512 f'kind must be one of {list(options._SCDB_FILES)}, not {kind!r}')
513 raise ValueError(message)
514 return text
517def _folder() -> pathlib.Path:
518 """Returns the folder where the database is kept.
520 Returns:
521 "scdb" in `utilities.data_folder()`. It is not created.
523 """
524 return utilities.data_folder() / 'scdb'
527def _read(
528 source: pd.DataFrame | pathlib.Path | str | None,
529 kind: str) -> pd.DataFrame:
530 """Returns a table from a table or a file, or one of the database's.
532 Args:
533 source: a table (which is copied), the path of a CSV file (or of a
534 zip archive of one), or `None`.
535 kind: the file to use if `source` is `None`: "cases" or "votes". It
536 is downloaded unless it was before (see `download`).
538 Returns:
539 The table.
541 """
542 if isinstance(source, pd.DataFrame):
543 return source.copy()
544 if source is None:
545 source = download(kinds = kind)[kind]
546 return utilities.read_csv(source, low_memory = False)
549def _release(session: Any) -> tuple[str, list[str]]:
550 """Finds the latest release of the database and its files.
552 Args:
553 session: an object with a `get` method like a `requests.Session`.
555 Raises:
556 requests.HTTPError: if a page cannot be downloaded.
557 ValueError: if the database's page links to no release, or the page
558 of the release does not link to a file for each of
559 `options._SCDB_FILES`.
561 Returns:
562 The name of the release (such as "SCDB_2026_01") and the addresses
563 of its files that are organized by citation, in the order of the
564 page (which is that of `options._SCDB_FILES`).
566 """
567 pattern = re.compile(options._SCDB_RELEASE)
568 # The page lists the latest release first.
569 links = amos.loaders.page_links(
570 options._SCDB_PAGE, session = session, timeout = options._TIMEOUT)
571 for page, _ in links:
572 found = pattern.search(page)
573 if found is None:
574 continue
575 addresses = [
576 address for address, words in amos.loaders.page_links(
577 page, session = session, timeout = options._TIMEOUT)
578 if options._SCDB_LINK.lower() in words.lower()]
579 if len(addresses) < len(options._SCDB_FILES):
580 message = (
581 f'{page} does not link to the files of the Supreme Court '
582 f'Database as it did: download the files and pass their '
583 f'paths instead'
584 )
585 raise ValueError(message)
586 return f'SCDB_{found.group(1)}_{found.group(2)}', addresses
587 message = (
588 f'no release of the Supreme Court Database was found on '
589 f'{options._SCDB_PAGE}: download its files and pass their paths '
590 f'instead'
591 )
592 raise ValueError(message)