Coverage for src/courtpy/references/fjc_idb.py: 91%
469 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 Federal Judicial Center's Integrated Database to cases.
3The Federal Judicial Center's Integrated Database (IDB) has a record of each
4appeal that the federal courts of appeals have docketed, terminated, or had
5pending since the 2008 fiscal year, taken from the courts' own dockets: the
6type of appeal, the parties, the court and judge appealed from, the dates of
7each step, the judges of the panel and the opinions each wrote, how the
8appeal ended, and whether the decision was published, among much else. It
9covers the twelve regional circuits (not the Federal Circuit). Its codebooks
10(https://www.fjc.gov/research/idb) explain each variable.
12courtpy uses the fjc-idb package (https://github.com/WithPrecedent/fjc_idb)
13to download, read, and decode the database's files. `download` gets the
14yearly files that are missing and keeps them outside of projects (in
15"fjc_idb" in `courtpy.utilities.data_folder()`, in the layout that fjc-idb
16uses). `appeals` returns the database's table of appeals for a range of
17years, with fjc-idb's descriptive names for its columns (such as
18"appeal_type", "docket_date", and "judgment_date") and labels in place of
19many of its codes. With `district = True`, each appeal from a district court
20also has the district court's record of the case that was appealed (in
21columns that begin with "district_"), which fjc-idb's `merge_district`
22finds.
24`add_idb` (an `amos.Merger`, which is added to the `amos` library as soon
25as courtpy is imported) adds the database's columns, with "idb_" before
26their names, by circuit and docket number. The database has a record for
27each docket, so it is best added to `Dockets` (which `cases_to_dockets`
28makes), each of whose rows has one docket number ("docket"). A case that
29consolidated several appeals then has each appeal's record on its own row:
31```python
32import courtpy
34cases = courtpy.parse("data/courtlistener")
35dockets = courtpy.code(cases, ["cases_to_dockets", "add_idb"], parameters = {
36 "add_idb": {"columns": "appeal_type, judgment_date, published"}})
37```
39Added to `Cases`, a case with several docket numbers gets the record of the
40first of them that the database has.
42`load_idb` and `download_idb` (reference loaders, see
43`courtpy.loaders.ReferenceLoader`) start a study of the appeals themselves,
44whether or not they have opinions.
46Contents:
47 AddIdb: adds the Integrated Database's record of each appeal to its
48 case.
49 DownloadIdb: downloads the Integrated Database's files and loads its
50 appeals.
51 CompareWithIdb: compares a dataset with the Integrated Database's
52 records of appeals, and its appeals that the dataset lacks.
53 LoadIdb: loads the Integrated Database's table of appeals for a range of
54 years.
55 appeals: returns the database's table of appeals for a range of years.
56 download: downloads the database's yearly files that are missing.
57 logger: the module's logger, which reports the files that are
58 downloaded.
59 _BY: the columns of the database that the groups of `compare_with_idb`
60 name.
61 _DOCKET_COLUMN: the column of `Dockets` with each row's one docket
62 number.
63 _FALSE_TEXT: text that is false in a column of flags.
64 _TRUE_TEXT: text that is true in a column of flags.
65 _VARIABLES: the variables that `compare_with_idb` compares, by name.
67"""
69from __future__ import annotations
71import dataclasses
72import datetime as dt
73import logging
74import math
75import pathlib
76import re
77from collections.abc import Callable, Mapping, MutableMapping, Sequence
78from typing import Any, ClassVar
80import amos
81import chrisjen
82import fjc_idb
83import fjc_idb.main
84import fjc_idb.options
85import fjc_idb.rules
86import numpy as np
87import pandas as pd
89from ..core import cases, options, utilities
90from ..wrangler import loaders, shapers
92logger = logging.getLogger(__name__)
93_COURTS: tuple[str, ...] = ('court_num', 'court')
94# The federal rules number the D.C. Circuit 12 (and the Federal Circuit 13,
95# which the database does not cover).
96_COURT_NUMBERS: dict[int, str] = {
97 **{number: str(number) for number in range(1, 12)}, 12: '0'}
98_DATES: tuple[str, ...] = ('date_filed', 'year')
99_DOCKET: re.Pattern[str] = re.compile(r'(?<!\d)(\d{2})-(\d{1,6})(?!\d)')
100_DOCKET_COLUMN: str = 'docket'
101_DOCKETS: tuple[str, ...] = ('docket_numbers', 'docket_number')
102_KINDS: tuple[str, ...] = ('appellate', 'civil', 'criminal')
103_TEXT_COLUMNS: tuple[str, ...] = (
104 'circuit', 'docket_num_idb', 'docket_number', 'district_of_origin',
105 'district_courthouse', 'district_docket', 'criminal_defendant_number',
106 'joined_docket')
109@dataclasses.dataclass
110class AddIdb(amos.Merger):
111 """Adds the Integrated Database's record of each appeal by its docket.
113 Each row of `Dockets` (see `cases_to_dockets`) is matched to the
114 database's record of the appeal with the same circuit and docket number
115 ("docket"), so each docket of a case that consolidated several appeals
116 gets its own record. Each row of `Cases` is matched by the first of its
117 docket numbers that the database has. An appeal that was reopened or remanded has
118 a record for each time it ended, under the same docket number, so the
119 record whose judgment is nearest the date of the decision is used (or
120 the latest one, if there are no dates), and never a record of an appeal
121 docketed after the decision. A case that is not matched, such as a case
122 of another court or of a year that the database does not cover, gets
123 missing values.
125 The database's records come from fjc-idb (see `appeals`). By default,
126 they are those of the years of the cases (from the year of the earliest
127 decision to the year after the latest, since the database's years end on
128 September 30), and the yearly files that are missing are downloaded.
130 Like every merger of `amos`, it takes these parameters, never adds,
131 removes, or reorders rows, and records how many cases it matched in the
132 dataset's history:
134 | Parameter | Meaning |
135 | --- | --- |
136 | `source` | The database's table of appeals: a table, or the path of a file (looked for in the current folder and then in the clerk's input folder), such as the CSV file that the `fjc-idb` command makes. Without it, the table is made from the database's yearly files (see `appeals`). |
137 | `columns` | The columns of the database to add, by fjc-idb's names for them (such as "appeal_type"). By default, they are all of them. |
138 | `prefix` | Text to put before the names of the added columns. It is "idb_" unless another is set. |
139 | `indicator` | The name of a column to make that says whether each case was found in the database. |
140 | `start_year`, `stop_year` | The first and last years of the database to use, without a `source`. They cover the cases unless they are set. |
141 | `district` | Whether to add the district court's record of the case that was appealed, without a `source` (in columns that begin with "idb_district_"). It is false unless set, since the district courts' files are large. |
142 | `folder` | The folder of the database's yearly files, without a `source` (looked for in the current folder and then in the clerk's input folder). It is "fjc_idb" in courtpy's data folder unless another is set. |
143 | `download` | Whether to download the yearly files that are missing, without a `source`. It is true unless set. |
144 | `courts`, `dockets`, `dates` | The columns of the cases with their courts, docket numbers, and dates of decision. They are "court_num" (or else "court"), "docket" (in `Dockets`, and otherwise "docket_numbers" or else "docket_number"), and "date_filed" (or else "year") unless others are set. |
146 Needs a court (a CourtListener court id, such as "ca1", or the number
147 that the federal rules give a court of appeals) and docket numbers (such
148 as "17-1234").
150 """
152 """ Public Methods """
154 def apply(
155 self,
156 item: amos.Dataset,
157 *,
158 source: Any = None,
159 columns: Sequence[str] | str | None = None,
160 prefix: str | None = 'idb_',
161 start_year: int | None = None,
162 stop_year: int | None = None,
163 district: bool = False,
164 folder: pathlib.Path | str | None = None,
165 download: bool = True,
166 **kwargs: Any) -> amos.Dataset:
167 """Adds the database's record of the appeal of each case of `item`.
169 Args:
170 item: the dataset of parsed cases.
171 source: the database's table of appeals, or the path of a file of
172 it. Defaults to `None`, in which case it is made from the
173 database's yearly files (see `appeals`).
174 columns: the columns of the database to add, as a list or as
175 text with commas between their names. Defaults to `None`,
176 for all of them.
177 prefix: text to put before the names of the added columns.
178 Defaults to "idb_".
179 start_year: the first year of the database to use, without a
180 `source`. Defaults to `None`, in which case it is the year of
181 the earliest decision in `item`.
182 stop_year: the last year of the database to use, without a
183 `source`. Defaults to `None`, in which case it is the year
184 after the latest decision in `item` (but not after this
185 year).
186 district: whether to add the district court's record of the case
187 that was appealed, without a `source`. Defaults to `False`.
188 folder: the folder of the database's yearly files, without a
189 `source`, which is found as the clerk finds files (see
190 `utilities.locate`). Defaults to `None`, in which case
191 "fjc_idb" in `utilities.data_folder()` is used.
192 download: whether to download the yearly files that are missing,
193 without a `source`. Defaults to `True`.
194 **kwargs: other parameters of the mergers of `amos` (such as
195 "indicator" and "reader"), and those of `match`.
197 Raises:
198 KeyError: if the cases lack a court or docket numbers, or one of
199 "columns" is not in the database.
200 ValueError: if the years of the cases are all before the
201 database's first year, or an added column would have the
202 name of a column of the cases.
204 Returns:
205 The dataset, with the new columns.
207 """
208 table, described = _load_appeals(
209 self,
210 item.data,
211 source,
212 start_year = start_year,
213 stop_year = stop_year,
214 district = district,
215 folder = folder,
216 download = download,
217 dates = kwargs.get('dates', _DATES),
218 reader = kwargs.pop('reader', None))
219 # A merger leaves out the columns whose names the cases have, but
220 # the prefix keeps the database's columns apart from the cases'.
221 chosen = (
222 list(table.columns) if columns is None
223 else utilities.listify(columns))
224 dataset = super().apply(
225 item, source = table, columns = chosen, prefix = prefix, **kwargs)
226 dataset.history[-1]['source'] = described
227 return dataset
229 def match(
230 self,
231 data: pd.DataFrame,
232 other: pd.DataFrame,
233 *,
234 courts: Sequence[str] | str = _COURTS,
235 dockets: Sequence[str] | str | None = None,
236 dates: Sequence[str] | str = _DATES,
237 **kwargs: Any) -> Any:
238 """Returns the database's record of the appeal of each case.
240 Args:
241 data: the parsed cases.
242 other: the database's table of appeals.
243 courts: the columns of `data` with the court of each case, tried
244 in order: CourtListener court ids or the numbers that the
245 federal rules give the courts of appeals. Defaults to
246 `_COURTS`.
247 dockets: the columns of `data` with the docket numbers of each
248 case, as lists or as text, tried in order. Defaults to
249 `None`, in which case it is "docket" (the one docket number
250 of each row of `Dockets`) if `data` has it, so that a row is
251 matched only by its own docket, and otherwise `_DOCKETS`.
252 dates: the columns of `data` with the date (or year) of each
253 decision, tried in order. Defaults to `_DATES`.
254 **kwargs: not used.
256 Raises:
257 KeyError: if `data` has none of `courts` or `dockets`.
259 Returns:
260 The position of the matching row of `other` for each row of
261 `data`, or -1 if there is none.
263 """
264 courts = utilities.listify(courts)
265 if dockets is None: 265 ↛ 268line 265 didn't jump to line 268 because the condition on line 265 was always true
266 dockets = [_DOCKET_COLUMN] if _DOCKET_COLUMN in data.columns else (
267 list(_DOCKETS))
268 dockets = utilities.listify(dockets)
269 for wanted, kind in ((courts, 'courts'), (dockets, 'docket numbers')):
270 if not any(column in data.columns for column in wanted):
271 message = (
272 f'{self.name!r} needs the {kind} of the cases (one of '
273 f'the columns {wanted}), and the cases have none'
274 )
275 raise KeyError(message)
276 records, docketed, judged = _records(other)
277 circuits = _circuits(data, courts)
278 decided = _decided(data, utilities.listify(dates))
279 cells = [data[c].tolist() for c in dockets if c in data.columns]
280 positions = np.full(len(data), -1, dtype = 'int64')
281 for place, circuit in enumerate(circuits):
282 if circuit is None:
283 continue
284 when = decided[place]
285 numbers = [column[place] for column in cells]
286 for key in _keys(circuit, numbers):
287 # An appeal docketed after the decision is not its appeal.
288 found = [
289 row for row in records.get(key, [])
290 if pd.isna(when) or pd.isna(docketed[row])
291 or docketed[row] <= when]
292 if found:
293 positions[place] = min(found, key = lambda row: (
294 np.inf if pd.isna(when) or pd.isna(judged[row])
295 else abs((judged[row] - when).days), -row))
296 break
297 return positions
299 def read(self, source: Any, **kwargs: Any) -> pd.DataFrame:
300 """Returns the database's table of appeals.
302 A CSV file (such as the one that the `fjc-idb` command makes) keeps
303 its codes and docket numbers as text, and its dates are read as
304 dates.
306 Args:
307 source: the path of a file of the table, or a table.
308 **kwargs: parameters for loading the file (see
309 `amos.Merger.read`, or `pandas.read_csv` for a CSV file).
311 Returns:
312 The table.
314 """
315 if isinstance(source, str | pathlib.Path) and (
316 '.csv' in pathlib.Path(str(source)).suffixes):
317 path = utilities.locate(source, self.clerk)
318 header = utilities.read_csv(path, nrows = 0).columns
319 table = utilities.read_csv(
320 path,
321 dtype = {c: 'string' for c in _TEXT_COLUMNS if c in header},
322 low_memory = False,
323 **kwargs)
324 for column in table.columns:
325 if column.endswith('_date'):
326 table[column] = pd.to_datetime(
327 table[column], errors = 'coerce', format = 'ISO8601')
328 return table
329 return super().read(source, **kwargs)
332@dataclasses.dataclass
333class LoadIdb(loaders.ReferenceLoader):
334 """Loads the Integrated Database's table of appeals for a range of years.
336 The table starts a study of the appeals themselves, which need not have
337 opinions. Its "source" is the folder of the database's yearly files, in
338 fjc-idb's layout, which is "fjc_idb" in
339 `courtpy.utilities.data_folder()` unless another is set. The files that
340 are missing are downloaded first unless "download" is false (see
341 `appeals`). To add the database's records to parsed cases, use
342 `add_idb` instead.
344 """
346 """ Public Methods """
348 def load(
349 self,
350 source: Any,
351 *,
352 start_year: int | str | None = None,
353 stop_year: int | str | None = None,
354 district: bool | str = False,
355 download: bool | str = True,
356 fix_city_spellings: bool | str = True,
357 **kwargs: Any) -> pd.DataFrame:
358 """Returns the database's table of appeals.
360 Args:
361 source: the folder of the yearly files, or "current" for
362 "fjc_idb" in `utilities.data_folder()`.
363 start_year: the first fiscal year to include. Defaults to `None`,
364 in which case it is the database's first year.
365 stop_year: the last fiscal year to include. Defaults to `None`,
366 in which case it is this year.
367 district: whether to add the district court's record of the case
368 that each appeal is from. Defaults to `False`.
369 download: whether to download the yearly files that are missing.
370 Defaults to `True`.
371 fix_city_spellings: whether to correct the names of cities that
372 the database's codebook misspells. Defaults to `True`.
373 **kwargs: not used.
375 Returns:
376 The table (see `appeals`).
378 """
379 return appeals(
380 _year(start_year),
381 _year(stop_year),
382 self._locate(source),
383 district = utilities.to_bool(district),
384 download = utilities.to_bool(download),
385 fix_city_spellings = utilities.to_bool(fix_city_spellings))
388@dataclasses.dataclass
389class DownloadIdb(loaders.ReferenceLoader):
390 """Downloads the Integrated Database's files and loads its appeals.
392 The yearly files that are missing are downloaded (see `download`), and
393 every file of the years is downloaded again if "refresh" is true, which
394 gets the latest records of the current year. Its "source" is the folder
395 to keep the files in, which is "fjc_idb" in
396 `courtpy.utilities.data_folder()` unless another is set.
398 """
400 """ Public Methods """
402 def load(
403 self,
404 source: Any,
405 *,
406 start_year: int | str | None = None,
407 stop_year: int | str | None = None,
408 district: bool | str = False,
409 refresh: bool | str = False,
410 fix_city_spellings: bool | str = True,
411 **kwargs: Any) -> pd.DataFrame:
412 """Downloads the database's yearly files and returns its appeals.
414 Args:
415 source: the folder to keep the yearly files in, or "current" for
416 "fjc_idb" in `utilities.data_folder()`.
417 start_year: the first fiscal year to download and include.
418 Defaults to `None`, in which case it is the database's first
419 year.
420 stop_year: the last fiscal year to download and include. Defaults
421 to `None`, in which case it is this year.
422 district: whether to also download the district courts' files and
423 add the district court's record of the case that each appeal
424 is from. Defaults to `False`.
425 refresh: whether to download the files of years that are in the
426 folder again. Defaults to `False`.
427 fix_city_spellings: whether to correct the names of cities that
428 the database's codebook misspells. Defaults to `True`.
429 **kwargs: not used.
431 Returns:
432 The table (see `appeals`).
434 """
435 folder = self._locate(source)
436 start, stop = _year(start_year), _year(stop_year)
437 with_district = utilities.to_bool(district)
438 download(
439 start, stop, folder, district = with_district,
440 overwrite = utilities.to_bool(refresh))
441 return appeals(
442 start, stop, folder, district = with_district, download = False,
443 fix_city_spellings = utilities.to_bool(fix_city_spellings))
446@dataclasses.dataclass
447class CompareWithIdb(amos.describers.Describer):
448 """Compares a dataset with the Integrated Database's records of appeals.
450 The cases are made `Dockets` first (see `cases_to_dockets`), unless they
451 are already, since the database has a record for each docket rather than
452 for each decision. Each docket is matched to its record as `add_idb`
453 matches it, and two tables are made.
455 The first, stored under the technique's name, says how well the
456 variables that both have agree, one row for each variable, for the
457 dockets that were matched: how many dockets have both values ("compared"),
458 how many of those agree ("matches", "match_share", and Cohen's "kappa"),
459 and the disagreements in each direction ("data_only" is true in the data
460 and false in the database, and "idb_only" the reverse). The variables
461 are true-or-false. By default, they are each of these whose column the
462 data has:
464 | Variable | The data's column | The database's column |
465 | --- | --- | --- |
466 | criminal | "type_criminal" | "appeal_type" is a criminal appeal |
467 | civil | "type_civil" | "appeal_type" is not a criminal appeal |
468 | reversal | "outcome_reversal" | "disposition" is reversed (in whole or part) or remanded |
469 | published | "published" | "published" |
470 | dissent | "dissents" (more than 0) | "dissents" (more than 0) |
471 | us_appellant | the United States is a party ("party1_united_states") and the appellant ("party1_appellant"), for either party | "us_appellant" |
472 | pro_se_appellant | "pro_se_appellant" | "pro_se_appellant" |
473 | prisoner_appeal | "prisoner_appeal" | "prisoner_appeal" |
475 The second, stored under the technique's name and "_missing", compares
476 the appeals in the database that the data has with those that it lacks,
477 in each circuit (or district, or any column of the database) and in all
478 of them ("All"). The database has every appeal, so the data always lacks
479 some. What matters is whether the appeals it lacks differ from those it
480 has, such as whether reversals are more common among them. The appeals
481 are those of the data's circuits whose judgments are between the data's
482 first and last decisions and, unless "merits_only" is false, that were
483 decided on the merits (those with a "disposition"), since the others
484 rarely have opinions. Each row is one variable in one group: how many
485 appeals there are ("appeals"), how many the data has ("in_data") and
486 their share ("coverage"), the share of the appeals with a known value
487 that are true among those the data has ("share_in_data") and those it
488 lacks ("share_missing"), their "difference", and the p value of a
489 two-proportion z test of it ("p_value"). Its variables are the
490 database's side of the variables above, by default.
492 With "visualize", `idb_confusion_matrices` draws the first table and
493 `idb_missing_differences` the second (stored in `figures` under the
494 tables' names).
496 | Parameter | Meaning |
497 | --- | --- |
498 | `variables` | The variables to compare: names of those above, or a mapping of new names to a column of the data and a column of the database (as a list or as text with a comma between them). By default, each of those above whose column the data has. |
499 | `report` | The variables of the second table: names of those above, or columns of the database. By default, all of those above. |
500 | `by` | "circuit", "district" (the district court appealed from), or another column of the database, for the groups of the second table. It is "circuit" unless set. |
501 | `merits_only` | Whether the second table counts only the appeals decided on the merits. It is true unless set. |
502 | `alpha` | Not used by the tables; `idb_missing_differences` stars differences whose p value is below it. |
503 | `source`, `start_year`, `stop_year`, `district`, `folder`, `download`, `reader`, `courts`, `dockets`, `dates` | As for `add_idb`. |
505 """
507 visual: ClassVar[str] = 'idb_confusion_matrices'
508 clerk: Any = dataclasses.field(default = None, repr = False)
510 """ Class Methods """
512 @classmethod
513 def build(
514 cls,
515 name: str,
516 project: Any,
517 parameters: MutableMapping[str, Any] | None = None,
518 **kwargs: Any) -> CompareWithIdb:
519 """Builds the technique with the clerk of `project`.
521 Args:
522 name: name of the technique.
523 project: the project the technique belongs to.
524 parameters: more parameters, which take precedence over those in
525 the settings. Defaults to `None`.
526 **kwargs: other arguments for the constructor.
528 Returns:
529 The built technique.
531 """
532 kwargs.setdefault('clerk', project.clerk)
533 return super().build(name, project, parameters, **kwargs)
535 """ Required Methods """
537 def describe(self, item: amos.Dataset, **kwargs: Any) -> pd.DataFrame:
538 """Returns the table of how well the variables agree.
540 Args:
541 item: the dataset of cases or dockets.
542 **kwargs: the parameters of `compare`.
544 Returns:
545 The first table of `compare`.
547 """
548 return self.compare(item, **kwargs)[0]
550 """ Public Methods """
552 def apply(
553 self,
554 item: amos.Dataset,
555 *,
556 visualize: bool = False,
557 **kwargs: Any) -> amos.Dataset:
558 """Adds both tables of `compare` to the tables of `item`.
560 Args:
561 item: the dataset of cases or dockets. It is not changed, and
562 stays cases if it is cases.
563 visualize: whether to draw both tables as figures. The dataset's
564 `visualize_explorers` replaces it, if it is set. Defaults to
565 `False`.
566 **kwargs: the parameters of `compare`.
568 Returns:
569 The dataset, with the new tables (and figures).
571 """
572 alpha = kwargs.pop('alpha', None)
573 agreement, missing, details = self.compare(item, **kwargs)
574 item.tables[self.name] = agreement
575 item.tables[self.missing_name] = missing
576 item.record(
577 self.name, table = self.name, missing_table = self.missing_name,
578 **details)
579 if alpha is not None: 579 ↛ 580line 579 didn't jump to line 580 because the condition on line 579 was never true
580 kwargs['alpha'] = alpha
581 self._visualize(item, visualize, kwargs)
582 return item
584 def compare(
585 self,
586 item: amos.Dataset,
587 *,
588 variables: Mapping[str, Any] | Sequence[str] | str | None = None,
589 report: Sequence[str] | str | None = None,
590 by: str = 'circuit',
591 merits_only: bool | str = True,
592 source: Any = None,
593 start_year: int | None = None,
594 stop_year: int | None = None,
595 district: bool = False,
596 folder: pathlib.Path | str | None = None,
597 download: bool = True,
598 reader: Mapping[str, Any] | None = None,
599 **kwargs: Any,
600 ) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
601 """Returns how the dataset agrees with the database, and what it lacks.
603 Args:
604 item: the dataset of cases or dockets.
605 variables: the variables to compare: names of `_VARIABLES`, or a
606 mapping of new names to a column of the data and a column of
607 the database. Defaults to `None`, for each of `_VARIABLES`
608 whose column the data has.
609 report: the variables of the second table: names of
610 `_VARIABLES` or columns of the database. Defaults to `None`,
611 for all of `_VARIABLES`.
612 by: "circuit", "district", or a column of the database, for the
613 groups of the second table. Defaults to "circuit".
614 merits_only: whether the second table counts only the appeals
615 decided on the merits. Defaults to `True`.
616 source: the database's table of appeals, or the path of a file of
617 it (see `AddIdb.apply`). Defaults to `None`.
618 start_year: the first year of the database to use, without a
619 `source`. Defaults to `None`.
620 stop_year: the last year of the database to use, without a
621 `source`. Defaults to `None`.
622 district: whether to read the district court's records too,
623 without a `source` (needed for district columns other than
624 "district_of_origin"). Defaults to `False`.
625 folder: the folder of the database's yearly files, without a
626 `source`. Defaults to `None`.
627 download: whether to download the yearly files that are missing,
628 without a `source`. Defaults to `True`.
629 reader: parameters for reading `source`. Defaults to `None`.
630 **kwargs: "courts", "dockets", and "dates" (see `AddIdb.match`).
632 Raises:
633 KeyError: if a variable or a column is unknown, or the database
634 lacks "disposition" and `merits_only` is true.
636 Returns:
637 The table of agreement, the table of what the data lacks, and
638 details for the dataset's history.
640 """
641 data = _as_dockets(item.data)
642 merger = AddIdb(clerk = self.clerk)
643 table, described = _load_appeals(
644 merger, data, source, start_year = start_year,
645 stop_year = stop_year, district = district, folder = folder,
646 download = download, dates = kwargs.get('dates', _DATES),
647 reader = reader)
648 found = np.asarray(merger.match(data, table, **kwargs), dtype = 'int64')
649 matched = found >= 0
650 agreement = _agreement(
651 data[matched], table.iloc[found[matched]], variables)
652 universe = _universe(
653 data, table, utilities.to_bool(merits_only),
654 utilities.listify(kwargs.get('courts', _COURTS)),
655 utilities.listify(kwargs.get('dates', _DATES)))
656 in_data = np.isin(np.flatnonzero(universe), found[matched])
657 missing = _missing(
658 table[universe].assign(_in_data = in_data), report, by)
659 details = {
660 'source': described,
661 'dockets': len(data),
662 'matched': int(matched.sum()),
663 'idb_appeals': int(universe.sum()),
664 'in_data': int(in_data.sum()),
665 'by': by}
666 return agreement, missing, details
668 """ Properties """
670 @property
671 def missing_name(self) -> str:
672 """Returns the name of the table (and figure) of what the data lacks.
674 Returns:
675 The technique's name with "_missing" after it.
677 """
678 return f'{self.name}_missing'
680 """ Private Methods """
682 def _visualize(
683 self,
684 item: amos.Dataset,
685 visualize: Any,
686 parameters: Mapping[str, Any] | None = None) -> None:
687 """Draws both tables, if it is asked for.
689 Args:
690 item: the dataset, with both tables.
691 visualize: the technique's `visualize` argument.
692 parameters: the parameters that the technique was applied with.
693 Defaults to `None`.
695 """
696 super()._visualize(item, visualize, parameters)
697 entry = next(
698 e for e in reversed(item.history)
699 if e.get('technique') == self.name)
700 if entry.get('figure') != self.name:
701 return
702 settings = {'source': self.missing_name}
703 if parameters and 'alpha' in parameters: 703 ↛ 704line 703 didn't jump to line 704 because the condition on line 703 was never true
704 settings['alpha'] = parameters['alpha']
705 try:
706 plot: Any = chrisjen.library.borrow('idb_missing_differences')()
707 figure = plot.make_figure(item, **settings)
708 except Exception as error: # noqa: BLE001
709 logger.warning(
710 f'the figure of {self.missing_name!r} was not drawn: {error}')
711 entry['figure_error'] = str(error)
712 return
713 item.figures[self.missing_name] = figure
714 entry['missing_figure'] = self.missing_name
716 def _visual_parameters(
717 self,
718 item: amos.Dataset, # noqa: ARG002
719 parameters: Mapping[str, Any]) -> dict[str, Any]: # noqa: ARG002
720 """Returns the parameters of `idb_confusion_matrices`.
722 Args:
723 item: the dataset, with the technique's table.
724 parameters: the parameters that the technique was applied with.
726 Returns:
727 The name of the table of agreement as "source".
729 """
730 return {'source': self.name}
733def appeals(
734 start_year: int | None = None,
735 stop_year: int | None = None,
736 folder: pathlib.Path | str | None = None,
737 *,
738 district: bool = False,
739 download: bool = True,
740 fix_city_spellings: bool = True) -> pd.DataFrame:
741 """Returns the Integrated Database's table of appeals for a range of years.
743 fjc-idb reads the yearly files, keeps the records of appeals that were
744 still pending only from the latest year (since each year's file repeats
745 them), decodes the database's codes, and gives the columns descriptive
746 names. Its codebooks of the columns are in its documentation
747 (https://WithPrecedent.github.io/fjc_idb).
749 Args:
750 start_year: the first year to include. The database's years are the
751 federal government's fiscal years, which end on September 30.
752 Defaults to `None`, in which case it is the database's first year
753 (`options._IDB_FIRST_YEAR`).
754 stop_year: the last year to include. Defaults to `None`, in which
755 case it is this year.
756 folder: the folder of the database's yearly files, in fjc-idb's
757 layout. Defaults to `None`, in which case "fjc_idb" in
758 `utilities.data_folder()` is used.
759 district: whether to add the district court's record of the case
760 that each appeal is from (see `fjc_idb.merge_district`), from the
761 district courts' files of the same years. Defaults to `False`.
762 download: whether to download the yearly files that are missing (see
763 `download`). Defaults to `True`.
764 fix_city_spellings: whether to correct the names of cities that the
765 database's codebook misspells. Defaults to `True`.
767 Raises:
768 FileNotFoundError: if the folder has no yearly files of appeals for
769 the years.
770 ValueError: if `start_year` is after `stop_year`.
772 Returns:
773 The table, with a row for each appeal (or each time an appeal ended,
774 if it was reopened or remanded) and columns such as "circuit",
775 "docket_number" (such as "No. 17-1234"), "appeal_type",
776 "docket_date", "judgment_date", "disposition", "published", and
777 "judge_1" (and, with `district`, "district_match" and the
778 district court's columns).
780 """
781 start, stop = _span(start_year, stop_year)
782 root = _folder(folder)
783 if download:
784 _download(start, stop, root, district = district)
785 if district:
786 return fjc_idb.merge_district(
787 start, stop, root, fix_city_spellings = fix_city_spellings,
788 export = False)
789 data = fjc_idb.main.import_data(
790 'appellate', start, stop,
791 fjc_idb.main._get_data_path('appellate', root))
792 return fjc_idb.main.parse_data(
793 data, 'appellate', fix_city_spellings = fix_city_spellings)
796def download(
797 start_year: int | None = None,
798 stop_year: int | None = None,
799 folder: pathlib.Path | str | None = None,
800 *,
801 district: bool = False,
802 overwrite: bool = False) -> list[pathlib.Path]:
803 """Downloads the Integrated Database's yearly files that are missing.
805 fjc-idb downloads each year's file from the Federal Judicial Center's
806 website, with the codebook, and needs no account. A year whose file is
807 in the folder is skipped unless `overwrite` is true. The Federal
808 Judicial Center updates the file of the current year during the year, so
809 overwrite it to get the latest records. Years that it has not published
810 are skipped (fjc-idb logs a warning).
812 Args:
813 start_year: the first year to download. Defaults to `None`, in which
814 case it is the database's first year (`options._IDB_FIRST_YEAR`).
815 stop_year: the last year to download. Defaults to `None`, in which
816 case it is this year.
817 folder: the folder to keep the files in, in fjc-idb's layout
818 ("appellate", "district/civil", "district/criminal", and "docs").
819 Defaults to `None`, in which case "fjc_idb" in
820 `utilities.data_folder()` is used.
821 district: whether to also download the district courts' files of
822 civil cases and criminal defendants, which `appeals` uses with
823 `district = True`. They are much larger than the files of
824 appeals. Defaults to `False`.
825 overwrite: whether to download the files of years that are in the
826 folder again. Defaults to `False`.
828 Raises:
829 ValueError: if `start_year` is after `stop_year`.
831 Returns:
832 The paths of the files that were downloaded.
834 """
835 start, stop = _span(start_year, stop_year)
836 return _download(
837 start, stop, _folder(folder), district = district,
838 overwrite = overwrite)
841""" Private Functions """
844def _circuit(court: Any) -> str | None:
845 """Returns the database's code for the circuit of a court.
847 Args:
848 court: a CourtListener court id (such as "ca1" or "cadc") or the
849 number that the federal rules give a court of appeals (such as 1,
850 or 12 for the D.C. Circuit).
852 Returns:
853 The database's code for the court's circuit (such as "1", or "0" for
854 the D.C. Circuit), or `None` if `court` is not one of the
855 database's courts.
857 """
858 if court is None or (not isinstance(court, str) and pd.isna(court)):
859 return None
860 if isinstance(court, str):
861 text = court.strip().lower()
862 if text in options._IDB_CIRCUITS:
863 return options._IDB_CIRCUITS[text]
864 if not text.isdigit(): 864 ↛ 866line 864 didn't jump to line 866 because the condition on line 864 was always true
865 return None
866 court = int(text)
867 try:
868 return _COURT_NUMBERS.get(int(court))
869 except (TypeError, ValueError):
870 return None
873def _circuits(data: pd.DataFrame, courts: Sequence[str]) -> list[str | None]:
874 """Returns the database's code for the circuit of each case.
876 Args:
877 data: the parsed cases.
878 courts: the columns of `data` with the court of each case, tried in
879 order.
881 Returns:
882 The code of each row of `data` (see `_circuit`), or `None` for a row
883 whose court is not one of the database's.
885 """
886 found: list[str | None] = [None] * len(data)
887 for column in courts:
888 if column not in data.columns:
889 continue
890 for place, court in enumerate(data[column].tolist()):
891 if found[place] is None:
892 found[place] = _circuit(court)
893 return found
896def _decided(data: pd.DataFrame, dates: Sequence[str]) -> list[Any]:
897 """Returns the date of each decision.
899 Args:
900 data: the parsed cases.
901 dates: the columns of `data` with the date of each decision, or its
902 year, tried in order. A year is taken to be its last day.
904 Returns:
905 The date of each row of `data` as a `pandas.Timestamp`, or `pd.NaT`
906 if no column has it.
908 """
909 decided = pd.Series(pd.NaT, index = data.index, dtype = 'datetime64[ns]')
910 for column in dates:
911 if column not in data.columns:
912 continue
913 values = data[column]
914 if pd.api.types.is_numeric_dtype(values.dtype):
915 years = pd.to_numeric(values, errors = 'coerce')
916 known = years.between(1, 9999)
917 when = pd.to_datetime(
918 years[known].astype('int64').astype(str) + '-12-31',
919 errors = 'coerce')
920 when = when.reindex(data.index)
921 else:
922 when = pd.to_datetime(
923 values, errors = 'coerce', format = 'ISO8601')
924 decided = decided.fillna(when.astype('datetime64[ns]'))
925 return decided.tolist()
928def _download(
929 start: int,
930 stop: int,
931 root: pathlib.Path,
932 *,
933 district: bool = False,
934 overwrite: bool = False) -> list[pathlib.Path]:
935 """Downloads the database's yearly files that are missing.
937 fjc-idb is only asked for the files of a kind if some year of that kind
938 is missing (or `overwrite` is true), since it reads the Federal Judicial
939 Center's page of the files each time it is asked.
941 Args:
942 start: the first year to download.
943 stop: the last year to download.
944 root: the folder to keep the files in, in fjc-idb's layout.
945 district: whether to also download the district courts' files of
946 civil cases and criminal defendants. Defaults to `False`.
947 overwrite: whether to download the files of years that are in the
948 folder again. Defaults to `False`.
950 Returns:
951 The paths of the files that were downloaded.
953 """
954 saved: list[pathlib.Path] = []
955 for kind in _KINDS if district else _KINDS[:1]:
956 folder = fjc_idb.main._get_data_path(kind, root)
957 prefix = fjc_idb.options._SOURCE_PREFIXES[kind]
958 missing = [
959 year for year in range(start, stop + 1)
960 if overwrite or not any(
961 folder.glob(f'{prefix}{year % 100:02d}*.sas7bdat'))]
962 if missing:
963 logger.info(
964 'downloading the FJC IDB %s files of %s-%s to %s',
965 kind, min(missing), max(missing), root)
966 saved.extend(fjc_idb.download(
967 kind, min(missing), max(missing), root,
968 overwrite = overwrite))
969 return saved
972def _year(value: int | str | None) -> int | None:
973 """Returns a year from a setting.
975 Args:
976 value: a year, as a number or as text, or `None`.
978 Raises:
979 ValueError: if `value` is text that is not a whole number.
981 Returns:
982 The year, or `None` if `value` is `None` or blank.
984 """
985 if value is None or str(value).strip() == '':
986 return None
987 return int(value)
990def _folder(folder: pathlib.Path | str | None = None) -> pathlib.Path:
991 """Returns the folder where the database's files are kept.
993 Args:
994 folder: the folder. Defaults to `None`.
996 Returns:
997 `folder` (with "~" expanded), or "fjc_idb" in
998 `utilities.data_folder()` if it is `None`. It is not created.
1000 """
1001 if folder:
1002 return pathlib.Path(folder).expanduser()
1003 return utilities.data_folder() / 'fjc_idb'
1006def _keys(circuit: str, cells: Sequence[Any]) -> list[tuple[str, str, int]]:
1007 """Returns the circuit, year, and number of each docket number of a case.
1009 Args:
1010 circuit: the database's code for the case's circuit.
1011 cells: the case's cells of the columns with its docket numbers, in
1012 the order in which they are tried: lists of docket numbers, text
1013 with one or more of them, or missing values.
1015 Returns:
1016 A key for each docket number, in order and without repeats: the
1017 circuit, the last two digits of the year the appeal was
1018 docketed, and its number that year (so that "17-01234" and
1019 "17-1234" are the same).
1021 """
1022 keys: list[tuple[str, str, int]] = []
1023 for cell in cells:
1024 if isinstance(cell, str):
1025 texts = [cell]
1026 elif isinstance(cell, list | tuple | np.ndarray):
1027 texts = [str(text) for text in cell]
1028 else:
1029 continue
1030 for text in texts:
1031 for year, number in _DOCKET.findall(text):
1032 key = (circuit, year, int(number))
1033 if key not in keys:
1034 keys.append(key)
1035 return keys
1038def _records(
1039 table: pd.DataFrame,
1040) -> tuple[dict[tuple[str, str, int], list[int]], list[Any], list[Any]]:
1041 """Returns the database's records of each docket.
1043 Args:
1044 table: the database's table of appeals. It needs "circuit" (fjc-idb's
1045 label or the database's code) and "docket_number" (such as "No.
1046 17-1234") or "docket_num_idb" (the database's form, such as
1047 "1701234"). "docket_date" and "judgment_date" are used if they are
1048 there.
1050 Raises:
1051 KeyError: if `table` lacks "circuit" or both columns of docket
1052 numbers.
1054 Returns:
1055 The positions of the rows of `table` for each key (as `_keys` makes
1056 them), and the date that each row's appeal was docketed and its
1057 date of judgment (`pd.NaT` if it is unknown).
1059 """
1060 if 'circuit' not in table.columns or not (
1061 {'docket_number', 'docket_num_idb'} & set(table.columns)):
1062 message = (
1063 'the table of appeals needs the columns "circuit" and '
1064 '"docket_number" (or "docket_num_idb"), as fjc-idb names them'
1065 )
1066 raise KeyError(message)
1067 # fjc-idb's labels (such as "First Circuit") become the database's codes,
1068 # and codes stay as they are.
1069 circuits = _circuit_codes(table)
1070 if 'docket_number' in table.columns:
1071 parts = table['docket_number'].astype('string').str.extract(
1072 r'(\d{2})-(\d+)')
1073 else:
1074 idb = table['docket_num_idb'].astype('string').str.strip().str.zfill(7)
1075 parts = pd.DataFrame({0: idb.str[:2], 1: idb.str[2:]})
1076 numbers = pd.to_numeric(parts[1], errors = 'coerce')
1077 records: dict[tuple[str, str, int], list[int]] = {}
1078 for row, (circuit, year, number) in enumerate(zip(
1079 circuits.tolist(), parts[0].tolist(), numbers.tolist(),
1080 strict = True)):
1081 if pd.isna(circuit) or pd.isna(year) or pd.isna(number): 1081 ↛ 1082line 1081 didn't jump to line 1082 because the condition on line 1081 was never true
1082 continue
1083 records.setdefault((circuit, year, int(number)), []).append(row)
1085 def dates(column: str) -> list[Any]:
1086 """Returns a column of dates of `table`.
1088 Args:
1089 column: name of the column.
1091 Returns:
1092 Its dates, or `pd.NaT` for each row if `table` lacks it.
1094 """
1095 if column not in table.columns: 1095 ↛ 1096line 1095 didn't jump to line 1096 because the condition on line 1095 was never true
1096 return [pd.NaT] * len(table)
1097 return pd.to_datetime(
1098 table[column], errors = 'coerce', format = 'ISO8601').tolist()
1100 return records, dates('docket_date'), dates('judgment_date')
1103def _span(start_year: int | None, stop_year: int | None) -> tuple[int, int]:
1104 """Returns the first and last years of the database to use.
1106 Args:
1107 start_year: the first year, or `None` for the database's first year.
1108 A year before the database's first is taken to be its first.
1109 stop_year: the last year, or `None` for this year.
1111 Raises:
1112 ValueError: if the first year is after the last.
1114 Returns:
1115 The first and last years.
1117 """
1118 start = max(
1119 int(start_year or options._IDB_FIRST_YEAR), options._IDB_FIRST_YEAR)
1120 stop = int(stop_year or dt.datetime.now(tz = dt.UTC).year)
1121 if start > stop:
1122 message = (
1123 f"the Integrated Database's records of appeals begin in "
1124 f"{options._IDB_FIRST_YEAR}, so there are none for the years "
1125 f"{start_year}-{stop_year}"
1126 )
1127 raise ValueError(message)
1128 return start, stop
1131def _years(
1132 data: pd.DataFrame,
1133 start_year: int | None,
1134 stop_year: int | None,
1135 dates: Sequence[str] | str) -> tuple[int, int]:
1136 """Returns the years of the database that cover a table of cases.
1138 Args:
1139 data: the parsed cases.
1140 start_year: the first year, or `None` for the year of the earliest
1141 decision.
1142 stop_year: the last year, or `None` for the year after the latest
1143 decision (since the database's years end on September 30), but
1144 not after this year.
1145 dates: the columns of `data` with the date (or year) of each
1146 decision, tried in order.
1148 Raises:
1149 ValueError: if the first year is after the last (as it is if every
1150 decision was before the database's first year).
1152 Returns:
1153 The first and last years (see `_span`).
1155 """
1156 years = pd.Series(
1157 [when.year for when in _decided(data, utilities.listify(dates))
1158 if not pd.isna(when)],
1159 dtype = 'int64')
1160 this_year = dt.datetime.now(tz = dt.UTC).year
1161 if start_year is None and not years.empty: 1161 ↛ 1163line 1161 didn't jump to line 1163 because the condition on line 1161 was always true
1162 start_year = max(int(years.min()), options._IDB_FIRST_YEAR)
1163 if stop_year is None and not years.empty: 1163 ↛ 1165line 1163 didn't jump to line 1165 because the condition on line 1163 was always true
1164 stop_year = min(int(years.max()) + 1, this_year)
1165 return _span(start_year, stop_year)
1168def _agreement(
1169 data: pd.DataFrame,
1170 records: pd.DataFrame,
1171 variables: Mapping[str, Any] | Sequence[str] | str | None) -> pd.DataFrame:
1172 """Returns how well the variables of the data and the database agree.
1174 Args:
1175 data: the dockets that were matched.
1176 records: the database's record of each of `data`, in the same order.
1177 variables: the variables to compare (see `CompareWithIdb.compare`).
1179 Raises:
1180 KeyError: if a variable that was named is unknown, or a column of it
1181 is missing.
1183 Returns:
1184 One row for each variable (see `CompareWithIdb`).
1186 """
1187 chosen, named = _chosen_variables(variables)
1188 rows = []
1189 for name, variable in chosen.items():
1190 mine = _values(data, variable.data)
1191 theirs = _values(records, variable.idb)
1192 if mine is None or theirs is None:
1193 if named:
1194 side = 'data' if mine is None else 'database'
1195 needed = (
1196 variable.data_text if mine is None else variable.idb_text)
1197 message = (
1198 f'the {side} lacks the column of the variable {name!r} '
1199 f'({needed})'
1200 )
1201 raise KeyError(message)
1202 continue
1203 ours = mine.to_numpy(dtype = 'float64')
1204 idb = theirs.to_numpy(dtype = 'float64')
1205 known = ~np.isnan(ours) & ~np.isnan(idb)
1206 counts = {
1207 (a, b): int(((ours == a) & (idb == b) & known).sum())
1208 for a in (0, 1) for b in (0, 1)}
1209 compared = int(known.sum())
1210 matches = counts[1, 1] + counts[0, 0]
1211 rows.append({
1212 'variable': name,
1213 'data_column': variable.data_text,
1214 'idb_column': variable.idb_text,
1215 'dockets': len(ours),
1216 'compared': compared,
1217 'matches': matches,
1218 'match_share': matches / compared if compared else np.nan,
1219 'both_true': counts[1, 1],
1220 'both_false': counts[0, 0],
1221 'data_only': counts[1, 0],
1222 'idb_only': counts[0, 1],
1223 'data_missing': int(np.isnan(ours).sum()),
1224 'idb_missing': int(np.isnan(idb).sum()),
1225 'kappa': _kappa(counts, compared)})
1226 columns = [
1227 'variable', 'data_column', 'idb_column', 'dockets', 'compared',
1228 'matches', 'match_share', 'both_true', 'both_false', 'data_only',
1229 'idb_only', 'data_missing', 'idb_missing', 'kappa']
1230 return pd.DataFrame(rows, columns = columns).set_index('variable')
1233def _as_dockets(data: pd.DataFrame) -> pd.DataFrame:
1234 """Returns a table of cases as a table of dockets.
1236 Args:
1237 data: cases (labeled by "case_id", or by their positions) or dockets
1238 (which have "docket").
1240 Raises:
1241 KeyError: if `data` has no docket numbers.
1243 Returns:
1244 `data` itself if it has "docket", and otherwise a row for each
1245 docket number of each case (see `cases_to_dockets`).
1247 """
1248 if _DOCKET_COLUMN in data.columns: 1248 ↛ 1249line 1248 didn't jump to line 1249 because the condition on line 1248 was never true
1249 return data
1250 if 'case_id' in data.columns: 1250 ↛ 1251line 1250 didn't jump to line 1251 because the condition on line 1250 was never true
1251 data = data.set_index('case_id')
1252 elif data.index.name != 'case_id': 1252 ↛ 1253line 1252 didn't jump to line 1253 because the condition on line 1252 was never true
1253 data = data.rename_axis('case_id')
1254 return shapers.CasesToDockets().shape(data)
1257def _chosen_variables(
1258 variables: Mapping[str, Any] | Sequence[str] | str | None,
1259) -> tuple[dict[str, _Variable], bool]:
1260 """Returns the variables to compare.
1262 Args:
1263 variables: names of `_VARIABLES`, a mapping of new names to a column
1264 of the data and a column of the database, or `None`.
1266 Raises:
1267 KeyError: if a name is not one of `_VARIABLES`.
1268 ValueError: if a new variable does not have two columns.
1270 Returns:
1271 The variables by name, and whether they were named (so that a
1272 missing column is an error, rather than a reason to leave the
1273 variable out).
1275 """
1276 if variables is None:
1277 return dict(_VARIABLES), False
1278 if isinstance(variables, Mapping):
1279 chosen = {}
1280 for name, columns in variables.items():
1281 pair = utilities.listify(columns)
1282 if len(pair) != 2: 1282 ↛ 1283line 1282 didn't jump to line 1283 because the condition on line 1282 was never true
1283 message = (
1284 f'the variable {name!r} needs a column of the data and a '
1285 f'column of the database, not {columns!r}'
1286 )
1287 raise ValueError(message)
1288 chosen[str(name)] = _Variable(*pair, *pair)
1289 return chosen, True
1290 names = utilities.listify(variables)
1291 unknown = [name for name in names if name not in _VARIABLES]
1292 if unknown:
1293 message = (
1294 f'the variables {unknown} are unknown (the known ones are '
1295 f'{list(_VARIABLES)})'
1296 )
1297 raise KeyError(message)
1298 return {name: _VARIABLES[name] for name in names}, True
1301def _circuit_codes(table: pd.DataFrame) -> pd.Series:
1302 """Returns the database's code for the circuit of each appeal.
1304 Args:
1305 table: the database's table of appeals, with "circuit" (fjc-idb's
1306 label, such as "First Circuit", or the database's code).
1308 Returns:
1309 The code of each appeal (such as "1", or "0" for the D.C. Circuit).
1311 """
1312 codes = {label: code for code, label in fjc_idb.rules.circuits.items()}
1313 circuits = table['circuit'].astype('string').str.strip()
1314 return circuits.map(codes).fillna(circuits)
1317def _codes(values: pd.Series) -> pd.Series:
1318 """Returns a column of the database's codes as text.
1320 Args:
1321 values: codes, as numbers or text.
1323 Returns:
1324 The codes as text without spaces (and without ".0" after whole
1325 numbers), with missing values (and the database's "-8", for
1326 missing) kept missing.
1328 """
1329 texts = values.astype('string').str.strip().str.replace(
1330 r'\.0$', '', regex = True)
1331 return texts.mask(texts == '-8')
1334def _data_us_appellant(data: pd.DataFrame) -> pd.Series | None:
1335 """Returns whether the United States brought each appeal of the data.
1337 Args:
1338 data: the dockets.
1340 Returns:
1341 1 if a party is the United States and the appellant, and otherwise
1342 0, or `None` if `data` lacks the columns of the parties.
1344 """
1345 sides = ('party1', 'party2')
1346 needed = [
1347 f'{side}_{role}' for side in sides
1348 for role in ('united_states', 'appellant')]
1349 if any(column not in data.columns for column in needed): 1349 ↛ 1351line 1349 didn't jump to line 1351 because the condition on line 1349 was always true
1350 return None
1351 brought = pd.Series(False, index = data.index)
1352 for side in sides:
1353 brought |= (
1354 cases.column_as_flags(data, f'{side}_united_states')
1355 & cases.column_as_flags(data, f'{side}_appellant'))
1356 return brought.astype('float64')
1359def _flags(values: pd.Series) -> pd.Series:
1360 """Returns a column as 1s and 0s, with missing values kept missing.
1362 Args:
1363 values: true-or-false values, counts (which are true if more than 0),
1364 or text such as "true", "false", "1", or "0".
1366 Returns:
1367 The values as decimals: 1.0, 0.0, or NaN.
1369 """
1370 def flag(value: Any) -> float:
1371 """Returns one value as 1.0, 0.0, or NaN.
1373 Args:
1374 value: the value.
1376 Returns:
1377 1.0 if it is true (or more than 0), 0.0 if it is false (or 0),
1378 and NaN if it is missing or neither.
1380 """
1381 if value is None or (not isinstance(value, str) and pd.isna(value)):
1382 return np.nan
1383 if isinstance(value, str):
1384 text = value.strip().lower()
1385 if text in _TRUE_TEXT:
1386 return 1.0
1387 if text in _FALSE_TEXT:
1388 return 0.0
1389 try:
1390 return float(float(text) > 0)
1391 except ValueError:
1392 return np.nan
1393 try:
1394 return float(float(value) > 0)
1395 except (TypeError, ValueError):
1396 return np.nan
1398 return pd.Series(
1399 [flag(value) for value in values.tolist()], index = values.index,
1400 dtype = 'float64')
1403def _idb_criminal(table: pd.DataFrame) -> pd.Series | None:
1404 """Returns whether each appeal of the database is a criminal appeal.
1406 Args:
1407 table: the database's table of appeals.
1409 Returns:
1410 1 if its "appeal_type" is one of fjc-idb's criminal appeal types, 0
1411 if it is another type, and missing if it is unknown, or `None`
1412 if `table` lacks "appeal_type".
1414 """
1415 if 'appeal_type' not in table.columns: 1415 ↛ 1416line 1415 didn't jump to line 1416 because the condition on line 1415 was never true
1416 return None
1417 codes = _codes(table['appeal_type'])
1418 criminal = codes.isin(fjc_idb.rules.criminal_apptypes).astype('float64')
1419 return criminal.mask(codes.isna())
1422def _idb_civil(table: pd.DataFrame) -> pd.Series | None:
1423 """Returns whether each appeal of the database is not a criminal appeal.
1425 Args:
1426 table: the database's table of appeals.
1428 Returns:
1429 The reverse of `_idb_criminal`, or `None` if `table` lacks
1430 "appeal_type".
1432 """
1433 criminal = _idb_criminal(table)
1434 return None if criminal is None else 1 - criminal
1437def _idb_reversal(table: pd.DataFrame) -> pd.Series | None:
1438 """Returns whether each appeal of the database was reversed or remanded.
1440 It is what courtpy's "outcome_reversal" means: the court of appeals
1441 reversed, vacated, or remanded (in whole or in part).
1443 Args:
1444 table: the database's table of appeals.
1446 Returns:
1447 1 if its "disposition" is reversed, affirmed and reversed in part, or
1448 remanded, 0 if it is another disposition on the merits, and
1449 missing if it was not decided on the merits, or `None` if
1450 `table` lacks "disposition".
1452 """
1453 if 'disposition' not in table.columns:
1454 return None
1455 codes = _codes(table['disposition'])
1456 rules = fjc_idb.rules.disposition_columns
1457 reversed_codes = [
1458 *rules['reversed_in_whole_or_part'], *rules['remanded_only']]
1459 reversal = codes.isin(reversed_codes).astype('float64')
1460 return reversal.mask(codes.isna())
1463def _kappa(counts: Mapping[tuple[int, int], int], compared: int) -> float:
1464 """Returns Cohen's kappa for two true-or-false columns.
1466 Args:
1467 counts: the number of rows with each pair of values (the data's and
1468 the database's).
1469 compared: the number of rows with both values.
1471 Returns:
1472 The agreement beyond what chance would give, from -1 to 1, or NaN if
1473 there are no rows or both columns have one value throughout.
1475 """
1476 if not compared: 1476 ↛ 1477line 1476 didn't jump to line 1477 because the condition on line 1476 was never true
1477 return np.nan
1478 observed = (counts[1, 1] + counts[0, 0]) / compared
1479 ours = (counts[1, 1] + counts[1, 0]) / compared
1480 theirs = (counts[1, 1] + counts[0, 1]) / compared
1481 expected = ours * theirs + (1 - ours) * (1 - theirs)
1482 if expected >= 1: 1482 ↛ 1483line 1482 didn't jump to line 1483 because the condition on line 1482 was never true
1483 return np.nan
1484 return (observed - expected) / (1 - expected)
1487def _load_appeals(
1488 merger: AddIdb,
1489 data: pd.DataFrame,
1490 source: Any,
1491 *,
1492 start_year: int | None,
1493 stop_year: int | None,
1494 district: bool | str,
1495 folder: pathlib.Path | str | None,
1496 download: bool | str,
1497 dates: Sequence[str] | str,
1498 reader: Mapping[str, Any] | None) -> tuple[pd.DataFrame, str]:
1499 """Returns the database's table of appeals for a table of cases.
1501 Args:
1502 merger: the merger whose clerk finds files and that reads `source`.
1503 data: the cases, whose dates set the years without a `source`.
1504 source: the database's table of appeals, the path of a file of it,
1505 or `None` to make it from the yearly files (see `appeals`).
1506 start_year: the first year to use, without a `source`, or `None` for
1507 the year of the earliest decision.
1508 stop_year: the last year to use, without a `source`, or `None` for
1509 the year after the latest decision.
1510 district: whether to add the district courts' records, without a
1511 `source`.
1512 folder: the folder of the yearly files, or `None` for the default.
1513 download: whether to download the yearly files that are missing.
1514 dates: the columns of `data` with the date of each decision.
1515 reader: parameters for reading `source`, or `None`.
1517 Returns:
1518 The table, and a description of where it came from.
1520 """
1521 if source is None:
1522 start, stop = _years(data, start_year, stop_year, dates)
1523 with_district = utilities.to_bool(district)
1524 table = appeals(
1525 start,
1526 stop,
1527 utilities.locate(folder, merger.clerk) if folder else None,
1528 district = with_district,
1529 download = utilities.to_bool(download))
1530 described = f'FJC IDB appeals, {start}-{stop}' + (
1531 ', with district records' if with_district else '')
1532 return table, described
1533 table = merger.read(source, **dict(reader or {}))
1534 described = (
1535 str(source) if isinstance(source, str | pathlib.Path)
1536 else type(source).__name__)
1537 return table, described
1540def _missing(
1541 table: pd.DataFrame,
1542 report: Sequence[str] | str | None,
1543 by: str) -> pd.DataFrame:
1544 """Returns how the appeals that the data has differ from those it lacks.
1546 Args:
1547 table: the database's appeals that the data could have, with
1548 "_in_data" (whether the data has each).
1549 report: names of `_VARIABLES` or columns of `table`, or `None` for
1550 all of `_VARIABLES`.
1551 by: "circuit", "district" (for "district_of_origin"), or another
1552 column of `table`, for the groups.
1554 Raises:
1555 KeyError: if `by` or a variable of `report` is not a column of
1556 `table`.
1558 Returns:
1559 One row for each variable in each group, "All" first (see
1560 `CompareWithIdb`).
1562 """
1563 column = _BY.get(by, by)
1564 if column not in table.columns: 1564 ↛ 1565line 1564 didn't jump to line 1565 because the condition on line 1564 was never true
1565 message = f'the database lacks the column {column!r} to group by'
1566 raise KeyError(message)
1567 named = report is not None
1568 names = list(_VARIABLES) if report is None else utilities.listify(report)
1569 flags: dict[str, pd.Series] = {}
1570 for name in names:
1571 variable = _VARIABLES.get(name)
1572 values = _values(table, variable.idb if variable else name)
1573 if values is None:
1574 if named: 1574 ↛ 1575line 1574 didn't jump to line 1575 because the condition on line 1574 was never true
1575 message = f'the database lacks the variable {name!r}'
1576 raise KeyError(message)
1577 continue
1578 flags[name] = values
1579 groups = table[column].astype('string').fillna(f'No {by}')
1580 order = _group_order(groups, by)
1581 frame = pd.DataFrame({
1582 'group': pd.concat([pd.Series('All', index = table.index), groups]),
1583 'in_data': pd.concat([table['_in_data']] * 2).astype(bool)})
1584 totals = frame.groupby('group', sort = False)['in_data'].agg(
1585 ['size', 'sum']).astype('int64')
1586 sizes = totals['size'].to_dict()
1587 helds = totals['sum'].to_dict()
1588 rows = []
1589 for name, values in flags.items():
1590 frame['value'] = pd.concat([values, values]).to_numpy()
1591 known = frame.dropna(subset = ['value'])
1592 sums = known.pivot_table(
1593 index = 'group', columns = 'in_data', values = 'value',
1594 aggfunc = ['size', 'sum'], fill_value = 0)
1595 for group in order:
1596 size, held = int(sizes.get(group, 0)), int(helds.get(group, 0))
1597 n_in, x_in, n_out, x_out = (
1598 _cell(sums, group, kind, side)
1599 for side in (True, False) for kind in ('size', 'sum'))
1600 share_in = x_in / n_in if n_in else np.nan
1601 share_out = x_out / n_out if n_out else np.nan
1602 rows.append({
1603 'group': group,
1604 'variable': name,
1605 'appeals': int(size),
1606 'in_data': int(held),
1607 'coverage': held / size if size else np.nan,
1608 'known_in_data': n_in,
1609 'known_missing': n_out,
1610 'share_in_data': share_in,
1611 'share_missing': share_out,
1612 'difference': share_in - share_out,
1613 'p_value': _p_value(x_in, n_in, x_out, n_out)})
1614 columns = [
1615 'group', 'variable', 'appeals', 'in_data', 'coverage',
1616 'known_in_data', 'known_missing', 'share_in_data', 'share_missing',
1617 'difference', 'p_value']
1618 return pd.DataFrame(rows, columns = columns)
1621def _cell(sums: pd.DataFrame, group: str, kind: str, side: bool) -> int:
1622 """Returns one count of a table of counts by group and side.
1624 Args:
1625 sums: the number ("size") and number true ("sum") of the known values
1626 of each group (rows) and side (whether the data has the appeal).
1627 group: the group.
1628 kind: "size" or "sum".
1629 side: whether the data has the appeals.
1631 Returns:
1632 The count, or 0 if the table lacks it.
1634 """
1635 if (kind, side) not in sums.columns: 1635 ↛ 1636line 1635 didn't jump to line 1636 because the condition on line 1635 was never true
1636 return 0
1637 return int(sums[(kind, side)].to_dict().get(group, 0))
1640def _group_order(groups: pd.Series, by: str) -> list[str]:
1641 """Returns the groups of the second table in the order to report them.
1643 Args:
1644 groups: the group of each appeal.
1645 by: what the groups are.
1647 Returns:
1648 "All", and then the circuits in their order (for "circuit") or the
1649 other groups in alphabetical order.
1651 """
1652 found = set(groups.dropna().unique())
1653 if by == 'circuit':
1654 labels = [
1655 label for code, label in fjc_idb.rules.circuits.items()
1656 if code != '-8']
1657 ordered = [label for label in labels if label in found]
1658 ordered += sorted(found - set(ordered))
1659 else:
1660 ordered = sorted(found)
1661 return ['All', *ordered]
1664def _p_value(x_in: int, n_in: int, x_out: int, n_out: int) -> float:
1665 """Returns the p value of a two-proportion z test.
1667 Args:
1668 x_in: the number true among the appeals that the data has.
1669 n_in: the number of those appeals with a known value.
1670 x_out: the number true among the appeals that the data lacks.
1671 n_out: the number of those appeals with a known value.
1673 Returns:
1674 The two-sided p value that the shares are the same, or NaN if a
1675 side has no appeals or every value is the same.
1677 """
1678 if not n_in or not n_out: 1678 ↛ 1679line 1678 didn't jump to line 1679 because the condition on line 1678 was never true
1679 return np.nan
1680 pooled = (x_in + x_out) / (n_in + n_out)
1681 error = math.sqrt(pooled * (1 - pooled) * (1 / n_in + 1 / n_out))
1682 if error == 0:
1683 return np.nan
1684 z = (x_in / n_in - x_out / n_out) / error
1685 return math.erfc(abs(z) / math.sqrt(2))
1688def _universe(
1689 data: pd.DataFrame,
1690 table: pd.DataFrame,
1691 merits_only: bool,
1692 courts: Sequence[str],
1693 dates: Sequence[str]) -> np.ndarray:
1694 """Returns which appeals of the database the data could have.
1696 Args:
1697 data: the dockets.
1698 table: the database's table of appeals.
1699 merits_only: whether to keep only the appeals decided on the merits
1700 (those with a "disposition").
1701 courts: the columns of `data` with the court of each case.
1702 dates: the columns of `data` with the date of each decision.
1704 Raises:
1705 KeyError: if `merits_only` is true and `table` lacks "disposition".
1707 Returns:
1708 Whether each appeal is in one of the data's circuits, was judged
1709 between the data's first and last decisions, and (with
1710 `merits_only`) was decided on the merits.
1712 """
1713 circuits = {code for code in _circuits(data, courts) if code is not None}
1714 keep = _circuit_codes(table).isin(circuits).fillna(False).to_numpy(
1715 bool, copy = True)
1716 decided = pd.Series(_decided(data, dates), dtype = 'datetime64[ns]')
1717 if decided.notna().any() and 'judgment_date' in table.columns: 1717 ↛ 1722line 1717 didn't jump to line 1722 because the condition on line 1717 was always true
1718 judged = pd.to_datetime(
1719 table['judgment_date'], errors = 'coerce', format = 'ISO8601')
1720 keep = keep & judged.between(
1721 decided.min(), decided.max()).to_numpy(bool)
1722 if merits_only:
1723 if 'disposition' not in table.columns:
1724 message = (
1725 'the table of appeals needs "disposition" to keep the '
1726 'appeals decided on the merits (or set "merits_only" to '
1727 'false)'
1728 )
1729 raise KeyError(message)
1730 keep = keep & _codes(table['disposition']).notna().to_numpy(bool)
1731 return keep
1734def _values(
1735 frame: pd.DataFrame,
1736 spec: str | Callable[[pd.DataFrame], pd.Series | None],
1737) -> pd.Series | None:
1738 """Returns one side of a variable as 1s and 0s.
1740 Args:
1741 frame: the data or the database's records.
1742 spec: a column of `frame`, or a function that makes the values.
1744 Returns:
1745 The values (see `_flags`), or `None` if `frame` lacks what they need.
1747 """
1748 if callable(spec):
1749 values = spec(frame)
1750 return None if values is None else _flags(values)
1751 if spec not in frame.columns:
1752 return None
1753 return _flags(frame[spec])
1756@dataclasses.dataclass(frozen = True)
1757class _Variable:
1758 """A true-or-false variable that the data and the database both have.
1760 Attributes:
1761 data: the column of the data, or a function that makes its values.
1762 idb: the column of the database, or a function that makes its values.
1763 data_text: what the data's values are, for the table.
1764 idb_text: what the database's values are, for the table.
1766 """
1768 data: str | Callable[[pd.DataFrame], pd.Series | None]
1769 idb: str | Callable[[pd.DataFrame], pd.Series | None]
1770 data_text: str
1771 idb_text: str
1774_BY: dict[str, str] = {'district': 'district_of_origin'}
1775_FALSE_TEXT: frozenset[str] = frozenset({'false', 'f', 'no', 'n'})
1776_TRUE_TEXT: frozenset[str] = frozenset({'true', 't', 'yes', 'y'})
1777_VARIABLES: dict[str, _Variable] = {
1778 'criminal': _Variable(
1779 'type_criminal', _idb_criminal, 'type_criminal',
1780 'appeal_type (criminal)'),
1781 'civil': _Variable(
1782 'type_civil', _idb_civil, 'type_civil', 'appeal_type (not criminal)'),
1783 'reversal': _Variable(
1784 'outcome_reversal', _idb_reversal, 'outcome_reversal',
1785 'disposition (reversed or remanded)'),
1786 'published': _Variable('published', 'published', 'published', 'published'),
1787 'dissent': _Variable('dissents', 'dissents', 'dissents', 'dissents'),
1788 'us_appellant': _Variable(
1789 _data_us_appellant, 'us_appellant',
1790 'party{1,2}_united_states & party{1,2}_appellant', 'us_appellant'),
1791 'pro_se_appellant': _Variable(
1792 'pro_se_appellant', 'pro_se_appellant', 'pro_se_appellant',
1793 'pro_se_appellant'),
1794 'prisoner_appeal': _Variable(
1795 'prisoner_appeal', 'prisoner_appeal', 'prisoner_appeal',
1796 'prisoner_appeal')}