Coverage for src/courtpy/wrangler/shapers.py: 97%
138 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"""Shapers that make dockets of cases, and summarize cases.
3`cases_to_dockets` makes a row for each docket number of each case
4(`Dockets`), as records kept by docket (such as the Integrated Database that
5`add_idb` adds) need, and `dockets_to_cases` makes the dockets cases again.
7The other shapers summarize cases by court, case type, and party type.
9Like every shaper of `amos`, each makes a new table from the data and must
10come before the data is split. Each returns a courtpy dataset of the kind
11that its rows are (see `courtpy.datasets`), and none of them can be undone:
12the rows summarize many cases and keep nothing about any one case (such as
13its docket number, its date, or its parties' names). Only columns of numbers
14and booleans are summarized (by their means, so the mean of a boolean is a
15share), along with the columns named in "keep" or "how":
17| Technique | One row for each | Labeled by |
18| --- | --- | --- |
19| `cases_to_courts` | Court, with "cases", "judges" (if `code_panels` found them), and the means of its cases' columns. | `court_num` |
20| `cases_to_case_types` | Case type (see `code_case_type`), with "cases" and the means of its cases' columns. A case of several types counts for each. | `case_type` |
21| `cases_to_party_types` | Party type ("party1_type" and "party2_type"), with "parties", the share of them that won ("party_won"), the means of their other columns (such as "party_appealing"), and the means of their cases' columns. | `party_type` |
23Each takes "by", other columns to group by as well, so `by = year` makes a
24row for each court (or type) in each year.
26The shares of each case type and party type are among the means, so a table
27of courts (or of judges, made by `cases_to_judges`) shows the mix of cases
28that each court (or judge) decides: "type_criminal" is the share of its
29cases that are criminal, and "party_type_corporation" the share with a
30corporation as a party.
32Contents:
33 CasesToCaseTypes: makes a table with one row for each case type.
34 CasesToCourts: makes a table with one row for each court.
35 CasesToDockets: makes a table with one row for each docket number of
36 each case.
37 CasesToPartyTypes: makes a table with one row for each party type.
38 Converter: makes a shaper return a courtpy dataset of the kind it makes.
39 DocketsToCases: makes a table of dockets a table of cases again.
40 add_party_type_flags: adds whether a party of each type is in each case.
41 summarize: returns a table with one row for each group of rows.
42 _DOCKET: pattern of a docket number, such as "17-1234".
43 _DOCKET_COLUMNS: the columns that `CasesToDockets` makes, which
44 `DocketsToCases` removes.
45 _ID: pattern of the names of columns that identify something, which
46 are not summarized.
47 _PARTY_TYPE: the start of the names of the columns of each party's
48 type.
49 _SIDE: column that says which side each party is on while a table is
50 made.
51 _SIDES: the starts of the names of the columns of each side's party.
53"""
55from __future__ import annotations
57import dataclasses
58import re
59from collections.abc import Mapping, Sequence
60from typing import Any, ClassVar
62import amos
63import numpy as np
64import pandas as pd
66from ..core import cases, datasets, utilities
68_DOCKET: re.Pattern[str] = re.compile(r'\d+-\d+')
69_DOCKET_COLUMNS: tuple[str, ...] = ('case_docket', 'docket')
70_ID: re.Pattern[str] = re.compile(r'(?:^|_)(?:id|nid|num)\d*$')
71_PARTY_TYPE: str = 'party_type'
72_SIDE: str = '__side__'
73_SIDES: tuple[str, ...] = ('party1', 'party2')
76class Converter:
77 """Makes a shaper return a courtpy dataset of the kind that it makes.
79 A shaper of courtpy subclasses it before `amos.Shaper` (as in
80 `class CasesToVotes(Converter, amos.Shaper)`) and sets `output`. It is a
81 mixin rather than a base class so that the shaper stays a shaper in the
82 `amos` library.
84 Attributes:
85 output: the kind of dataset that the shaper makes.
87 """
89 output: ClassVar[type[datasets.CourtData]]
91 """ Public Methods """
93 def apply(self, item: amos.Dataset, **kwargs: Any) -> amos.Dataset:
94 """Reshapes `item` and returns it as a dataset of `output`.
96 Args:
97 item: the dataset to reshape.
98 **kwargs: parameters of the shaper.
100 Returns:
101 The reshaped dataset, as a dataset of `output`.
103 """
104 shaped = super().apply(item, **kwargs) # type: ignore[misc]
105 return self.output.adopt(shaped)
108@dataclasses.dataclass
109class CasesToDockets(Converter, amos.Shaper):
110 """Makes a table with one row for each docket number of each case.
112 A case that decided several consolidated appeals has several docket
113 numbers ("docket_numbers", with "; " between them, as the rules find
114 them, or else those in the text of "docket_number"). The
115 `lists_to_rows` technique of `amos` makes a row for each, labeled by
116 "case_docket" (the case's id and the docket's place, such as "4567890-2"),
117 with "case_id", "docket" (the row's one docket number), and the case's
118 other columns. "docket_numbers" is left out, so each row has only its
119 own docket number. A case with no docket number keeps one row, whose
120 "docket" is missing, so `dockets_to_cases` can make every case again.
122 Like every shaper, it takes "label", "task", and "groups". Its "case_id"
123 column can be the "groups" of a study, which keeps the dockets of a case
124 together.
126 """
128 output: ClassVar[type[datasets.CourtData]] = datasets.Dockets
130 def shape(
131 self,
132 data: pd.DataFrame,
133 column: str | None = None,
134 **kwargs: Any) -> pd.DataFrame:
135 """Returns a table with one row for each docket number of each case.
137 Args:
138 data: the cases, labeled by their ids.
139 column: the column with each case's docket numbers: lists, or
140 text in which each "{year}-{number}" is one. Defaults to
141 `None`, in which case it is "docket_numbers" (or else
142 "docket_number").
143 **kwargs: not used.
145 Raises:
146 KeyError: if `data` lacks `column` (or both of the defaults).
148 Returns:
149 The table of dockets, labeled by "case_docket".
151 """
152 if column is None: 152 ↛ 156line 152 didn't jump to line 156 because the condition on line 152 was always true
153 column = next(
154 (c for c in ('docket_numbers', 'docket_number')
155 if c in data.columns), 'docket_numbers')
156 cases.require_columns(data, [column], repr(self.name))
157 cases.require_columns(
158 data.reset_index(), ['case_id'], repr(self.name),
159 hint = 'The cases must be labeled by "case_id"')
160 numbers = data[column].map(_docket_numbers)
161 dropped = [
162 c for c in ('docket_numbers', *_DOCKET_COLUMNS) if c in data]
163 table = data.drop(columns = dropped).assign(docket = numbers)
164 table.index = table.index.rename('case_id')
165 dockets = amos.shapers.ListsToRows().shape(
166 table, column = 'docket', position = '__place__')
167 places = dockets['__place__'].fillna(1).astype(int).astype(str)
168 dockets.insert(
169 0, 'case_docket', dockets['case_id'].astype(str) + '-' + places)
170 order = ['case_docket', 'case_id', 'docket']
171 dockets = dockets.drop(columns = '__place__')
172 dockets = dockets[[
173 *order, *[c for c in dockets.columns if c not in order]]]
174 return dockets.set_index('case_docket')
177@dataclasses.dataclass
178class DocketsToCases(Converter, amos.Shaper):
179 """Makes a table of dockets a table of cases again.
181 It undoes `cases_to_dockets`: the rows of each case become one row,
182 labeled by "case_id", and the docket numbers of its rows become its
183 "docket_numbers" again (with "; " between them). Every other column
184 keeps the value of the case's first docket, so a column that was added
185 to the dockets (such as the Integrated Database's, from `add_idb`) has
186 the first docket's value.
188 Like every shaper, it takes "label", "task", and "groups". Without
189 "groups", the groups are those of the dockets other than "case_id".
191 """
193 output: ClassVar[type[datasets.CourtData]] = datasets.Cases
195 def apply(
196 self,
197 item: amos.Dataset,
198 *,
199 groups: Sequence[str] | str | None = None,
200 **kwargs: Any) -> amos.Dataset:
201 """Makes the table of dockets of `item` a table of cases.
203 Args:
204 item: the dataset of dockets.
205 groups: names of the groups of the cases. Defaults to `None`, in
206 which case they are the groups of `item` other than
207 "case_id" and the dockets' columns.
208 **kwargs: "label", "task", and parameters for `shape`.
210 Returns:
211 The dataset of cases.
213 """
214 if groups is None: 214 ↛ 218line 214 didn't jump to line 218 because the condition on line 214 was always true
215 groups = [
216 group for group in item.groups
217 if group not in ('case_id', *_DOCKET_COLUMNS)]
218 return super().apply(item, groups = groups, **kwargs)
220 def shape(self, data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame:
221 """Returns a table with one row for each case.
223 Args:
224 data: the table of dockets (see `CasesToDockets`).
225 **kwargs: not used.
227 Raises:
228 KeyError: if `data` lacks "case_id".
230 Returns:
231 The table of cases, labeled by "case_id".
233 """
234 cases.require_columns(data, ['case_id'], repr(self.name))
235 table = data.drop(
236 columns = [c for c in _DOCKET_COLUMNS if c in data.columns])
237 table = table.drop_duplicates(subset = 'case_id').set_index('case_id')
238 if 'docket' in data.columns: 238 ↛ 243line 238 didn't jump to line 243 because the condition on line 238 was always true
239 joined = data.groupby('case_id', sort = False)['docket'].agg(
240 _join_dockets)
241 table['docket_numbers'] = joined.reindex(table.index).astype(
242 object)
243 return table
246@dataclasses.dataclass
247class CasesToCourts(Converter, amos.Shaper):
248 """Makes a table with one row for each court.
250 Each court's row has "cases" (the number of its cases), "judges" (the
251 number of different judges on its panels, if `code_panels` found them),
252 and the mean of each column of numbers and booleans of its cases: the
253 share of its cases of each case type ("type_criminal", ...), with a party
254 of each party type ("party_type_corporation", ...), and with each
255 outcome ("outcome_reversal", ...), and the mean composition of its
256 panels ("panel_party", ...). See the module's documentation.
258 Like every shaper, it takes "label", "task", and "groups". Without
259 "groups", the table has none.
261 """
263 output: ClassVar[type[datasets.CourtData]] = datasets.Courts
265 def apply(
266 self,
267 item: amos.Dataset,
268 *,
269 groups: Sequence[str] | str | None = None,
270 **kwargs: Any) -> amos.Dataset:
271 """Makes the table of `item` a table of courts.
273 Args:
274 item: the dataset of cases.
275 groups: names of the groups of the courts. Defaults to `None`,
276 for none.
277 **kwargs: "label", "task", and parameters for `shape`.
279 Returns:
280 The dataset of courts.
282 """
283 return super().apply(
284 item, groups = [] if groups is None else groups, **kwargs)
286 def shape(
287 self,
288 data: pd.DataFrame,
289 court: str = 'court_num',
290 by: Sequence[str] | str | None = None,
291 how: Mapping[str, Any] | None = None,
292 keep: Sequence[str] | str | None = None,
293 **kwargs: Any) -> pd.DataFrame:
294 """Returns a table with one row for each court.
296 Args:
297 data: the cases.
298 court: the column that names each case's court. Defaults to
299 "court_num".
300 by: other columns to group the cases by, such as "year".
301 Defaults to `None`.
302 how: summaries of columns that take the place of the means, or
303 that add columns of text, as `group_rows` takes them (such
304 as {"court": "first"}). Defaults to `None`.
305 keep: columns of text to keep, with the first value of each
306 court's cases (such as "court", CourtListener's id).
307 Defaults to `None`.
308 **kwargs: not used.
310 Raises:
311 KeyError: if `data` lacks `court` or a column that is named.
313 Returns:
314 The table of courts, labeled by `court` (and `by`).
316 """
317 keys = [court, *utilities.listify(by)]
318 cases.require_columns(data, keys, repr(self.name))
319 data = add_party_type_flags(data)
320 nids = [c for c in data.columns if re.fullmatch(r'judge_nid\d+', c)]
321 table = summarize(
322 data, keys, how = how, keep = keep, count = 'cases')
323 if nids: 323 ↛ 329line 323 didn't jump to line 329 because the condition on line 323 was always true
324 stacked = data[keys].join(data[nids]).melt(
325 id_vars = keys, value_name = 'nid').dropna(subset = ['nid'])
326 judges = stacked.groupby(keys, dropna = False)['nid'].nunique()
327 table['judges'] = judges.reindex(table.index).fillna(0).astype(
328 'int64')
329 return table
332@dataclasses.dataclass
333class CasesToCaseTypes(Converter, amos.Shaper):
334 """Makes a table with one row for each case type.
336 The case types are the "type_..." columns that `code_case_type` adds
337 (such as "type_criminal", "type_civil", "type_tort", and
338 "type_contract"). The `wide_to_long` technique of `amos` makes a row for
339 each type of each case, and the rows of each type are summarized: each
340 type's row has "cases" (the number of its cases) and the mean of each
341 column of numbers and booleans of its cases (see the module's
342 documentation). A case of several types (such as a tort case that is
343 also a contract case) counts for each of them.
345 Like every shaper, it takes "label", "task", and "groups". Without
346 "groups", the table has none.
348 """
350 output: ClassVar[type[datasets.CourtData]] = datasets.CaseTypes
352 def apply(
353 self,
354 item: amos.Dataset,
355 *,
356 groups: Sequence[str] | str | None = None,
357 **kwargs: Any) -> amos.Dataset:
358 """Makes the table of `item` a table of case types.
360 Args:
361 item: the dataset of cases.
362 groups: names of the groups of the case types. Defaults to
363 `None`, for none.
364 **kwargs: "label", "task", and parameters for `shape`.
366 Returns:
367 The dataset of case types.
369 """
370 return super().apply(
371 item, groups = [] if groups is None else groups, **kwargs)
373 def shape(
374 self,
375 data: pd.DataFrame,
376 by: Sequence[str] | str | None = None,
377 how: Mapping[str, Any] | None = None,
378 keep: Sequence[str] | str | None = None,
379 **kwargs: Any) -> pd.DataFrame:
380 """Returns a table with one row for each case type.
382 Args:
383 data: the cases, with the "type_..." columns of `code_case_type`.
384 by: other columns to group the cases by, such as "court_num".
385 Defaults to `None`.
386 how: summaries of columns that take the place of the means, as
387 `group_rows` takes them. Defaults to `None`.
388 keep: columns of text to keep, with the first value of each
389 type's cases. Defaults to `None`.
390 **kwargs: not used.
392 Raises:
393 KeyError: if `data` has no "type_..." columns, or lacks a column
394 that is named.
396 Returns:
397 The table of case types, labeled by "case_type" (and `by`).
399 """
400 extra = utilities.listify(by)
401 cases.require_columns(data, extra, repr(self.name))
402 types = [c for c in data.columns if str(c).startswith('type_')]
403 if not types:
404 message = (
405 f'{self.name!r} needs the "type_..." columns of each case '
406 f'type: apply "code_case_type" first')
407 raise KeyError(message)
408 flags = pd.DataFrame(
409 {c: cases.column_as_flags(data, c) for c in types})
410 data = add_party_type_flags(data.drop(columns = types)).join(flags)
411 long = amos.shapers.WideToLong().shape(
412 data, stubs = 'type', name = 'case_type')
413 long = long[long['type'].astype(bool)].drop(columns = 'type')
414 return summarize(
415 long, ['case_type', *extra], how = how, keep = keep,
416 count = 'cases')
419@dataclasses.dataclass
420class CasesToPartyTypes(Converter, amos.Shaper):
421 """Makes a table with one row for each party type.
423 Each party's type is in "party1_type" and "party2_type" (such as
424 "individual", "corporation", or "agency"). The `wide_to_long` technique
425 of `amos` makes a row for each party of each case, and the rows of each
426 type are summarized. Each type's row has "parties" (how many parties
427 were of the type), "party_won" (the share of them that won, from
428 "outcome_party1_won" and "outcome_party2_won", if `code_outcome` made
429 them), the mean of each column of numbers and booleans that both sides
430 have (such as "party1_appealing" and "party2_appealing", which become
431 "party_appealing"), and the mean of each other column of numbers and
432 booleans of their cases (see the module's documentation).
434 Like every shaper, it takes "label", "task", and "groups". Without
435 "groups", the table has none.
437 """
439 output: ClassVar[type[datasets.CourtData]] = datasets.PartyTypes
441 def apply(
442 self,
443 item: amos.Dataset,
444 *,
445 groups: Sequence[str] | str | None = None,
446 **kwargs: Any) -> amos.Dataset:
447 """Makes the table of `item` a table of party types.
449 Args:
450 item: the dataset of cases.
451 groups: names of the groups of the party types. Defaults to
452 `None`, for none.
453 **kwargs: "label", "task", and parameters for `shape`.
455 Returns:
456 The dataset of party types.
458 """
459 return super().apply(
460 item, groups = [] if groups is None else groups, **kwargs)
462 def shape(
463 self,
464 data: pd.DataFrame,
465 by: Sequence[str] | str | None = None,
466 how: Mapping[str, Any] | None = None,
467 keep: Sequence[str] | str | None = None,
468 **kwargs: Any) -> pd.DataFrame:
469 """Returns a table with one row for each party type.
471 Args:
472 data: the cases, with "party1_type" and "party2_type".
473 by: other columns to group the parties by, such as "court_num".
474 Defaults to `None`.
475 how: summaries of columns that take the place of the means, as
476 `group_rows` takes them. Defaults to `None`.
477 keep: columns of text to keep, with the first value of each
478 type's parties. Defaults to `None`.
479 **kwargs: not used.
481 Raises:
482 KeyError: if `data` lacks "party1_type", "party2_type", or a
483 column that is named.
485 Returns:
486 The table of party types, labeled by "party_type" (and `by`).
488 """
489 extra = utilities.listify(by)
490 typed = [f'{side}_type' for side in _SIDES]
491 cases.require_columns(
492 data, [*typed, *extra], repr(self.name),
493 hint = 'Each party needs a type, which rules can find')
494 sided = {
495 str(column).removeprefix('party1_') for column in data.columns
496 if str(column).startswith('party1_')
497 and f'party2_{str(column).removeprefix("party1_")}' in data.columns
498 and (column in typed or _is_number(data[column], column))}
499 renamed = {
500 f'{side}_{name}': f'party_{name}__{number}'
501 for number, side in enumerate(_SIDES, start = 1)
502 for name in sided}
503 for number, side in enumerate(_SIDES, start = 1):
504 won = f'outcome_{side}_won'
505 if won in data.columns: 505 ↛ 503line 505 didn't jump to line 503 because the condition on line 505 was always true
506 renamed[won] = f'party_won__{number}'
507 stubs = sorted({name.rpartition('__')[0] for name in renamed.values()})
508 data = data.rename(columns = renamed)
509 long = amos.shapers.WideToLong().shape(
510 data, stubs = stubs, name = _SIDE, separator = '__')
511 long = long[long[_PARTY_TYPE].notna()].drop(columns = _SIDE)
512 return summarize(
513 long, [_PARTY_TYPE, *extra], how = how, keep = keep,
514 count = 'parties')
517""" Public Functions """
520def add_party_type_flags(data: pd.DataFrame) -> pd.DataFrame:
521 """Adds whether a party of each type is in each case.
523 Args:
524 data: the cases. Without "party1_type" and "party2_type", nothing is
525 added.
527 Returns:
528 `data`, with a column "party_type_{type}" for each type that either
529 party has, which is true if either party of the case has it.
531 """
532 typed = [f'{side}_type' for side in _SIDES if f'{side}_type' in data]
533 if not typed:
534 return data
535 kinds = pd.unique(data[typed].melt()['value'].dropna().astype(str))
536 flags = {
537 f'{_PARTY_TYPE}_{"_".join(kind.lower().split())}': (
538 data[typed].astype('string').eq(kind).any(axis = 1))
539 for kind in sorted(kinds)}
540 added = pd.DataFrame(flags, index = data.index)
541 return pd.concat(
542 [data.drop(columns = [c for c in added if c in data]), added],
543 axis = 1)
546def summarize(
547 data: pd.DataFrame,
548 by: Sequence[str],
549 *,
550 how: Mapping[str, Any] | None = None,
551 keep: Sequence[str] | str | None = None,
552 count: str | None = None) -> pd.DataFrame:
553 """Returns a table with one row for each group of rows.
555 The `group_rows` technique of `amos` summarizes the groups. Only the
556 columns of numbers and booleans are summarized (by their means), except
557 columns that identify something (such as "case_id", "judge_nid", or
558 "court_num", unless they are in `by`), so nothing about any one row
559 (such as a case's docket number or date) is kept.
561 Args:
562 data: the table.
563 by: the columns that say which group each row belongs to.
564 how: summaries of columns that take the place of the means, or that
565 add columns, by their names (such as {"court": "first"}).
566 Defaults to `None`.
567 keep: columns of text to keep, with the first value of each group.
568 Defaults to `None`.
569 count: name of a column to make with the number of rows of each
570 group. Defaults to `None`, for none.
572 Raises:
573 KeyError: if a column of `by`, `how`, or `keep` is not in `data`.
575 Returns:
576 The table, labeled by `by`.
578 """
579 keys = list(by)
580 summaries = {
581 column: 'mean' for column in data.columns
582 if column not in keys and _is_number(data[column], column)}
583 summaries.update(dict.fromkeys(utilities.listify(keep), 'first'))
584 summaries.update(how or {})
585 cases.require_columns(data, [*keys, *summaries], 'summarize')
586 table = amos.shapers.GroupRows().shape(
587 data[[*keys, *summaries]].reset_index(drop = True),
588 by = keys, how = summaries, count = count)
589 return table.set_index(keys)
592""" Private Functions """
595def _docket_numbers(value: Any) -> list[str]:
596 """Returns the docket numbers in a cell of a table of cases.
598 Args:
599 value: a list of docket numbers, text with any number of them (such
600 as "17-1234; 17-1235" or "Nos. 17-1234, 17-1235"), or a missing
601 value.
603 Returns:
604 The docket numbers, in order and without repeats.
606 """
607 if isinstance(value, list | tuple | np.ndarray):
608 found = [str(v).strip() for v in value if str(v).strip()]
609 elif isinstance(value, str):
610 found = _DOCKET.findall(value)
611 else:
612 found = []
613 return list(dict.fromkeys(found))
616def _join_dockets(found: pd.Series) -> str | None:
617 """Returns the docket numbers of a case's dockets, as one cell of text.
619 Args:
620 found: the docket number of each of the case's dockets.
622 Returns:
623 The docket numbers that are not missing, with "; " between them, or
624 `None` if there are none.
626 """
627 numbers = [str(number) for number in found if pd.notna(number)]
628 return cases._SEPARATOR.join(numbers) or None
631def _is_number(values: pd.Series, column: Any) -> bool:
632 """Returns whether a column is numbers or booleans that can be averaged.
634 Args:
635 values: the column.
636 column: the name of the column.
638 Returns:
639 Whether it is numbers or booleans and does not identify something
640 (see `_ID`).
642 """
643 return (
644 (pd.api.types.is_numeric_dtype(values.dtype)
645 or pd.api.types.is_bool_dtype(values.dtype))
646 and not _ID.search(str(column)))