Coverage for src/courtpy/wrangler/coders.py: 98%
233 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"""Techniques that code variables from parsed cases.
3`code_parties`, `code_case_type`, `code_outcome`, `split_values`, and
4`tidy_cases` are `amos.Munger` techniques, which change and add columns
5without adding or removing rows, and `drop_text_columns` is an
6`amos.Cleaner`, which removes columns.
7Each is added to the `amos` (and `chrisjen`) library as soon as courtpy is
8imported, and it can be named in the settings of any `amos` worker.
9courtpy's loaders (see `courtpy.loaders`) also run the coders named in
10their "coders" parameter (by default, `code_parties`, `code_case_type`, and
11`code_outcome`, in that order) right after parsing, so that a label such as
12"outcome_reversal" exists when the data is loaded.
14The coders use the columns made by the federal rules (such as
15"party1_appellant" and "disposition_reverse"). With other rules, make columns
16with the same names or write your own coder.
18Contents:
19 CodeCaseType: decides whether each case is criminal or civil, and its
20 other types.
21 CodeOutcome: decides whether each decision reversed the court below, and
22 which side won.
23 CodeParties: completes the roles of the parties.
24 DropTextColumns: removes columns that models cannot use, such as text and lists.
25 SplitValues: turns text with several values in each cell into lists or
26 columns.
27 TidyCases: gives columns of booleans or whole numbers with missing values
28 types that allow them.
29 code: applies coders (or other `amos` techniques) to parsed cases.
30 _UNITED_STATES_FIRST: the pattern of a party's text that begins with the
31 United States.
33"""
35from __future__ import annotations
37import dataclasses
38import functools
39import re
40from collections.abc import Mapping, Sequence
41from typing import Any, cast
43import amos
44import chrisjen
45import pandas as pd
47from ..core import cases, datasets, options, utilities
48from . import rules
50_OPPOSITES: tuple[tuple[str, str], ...] = (
51 ('appellant', 'appellee'),
52 ('petitioner', 'respondent'),
53 ('plaintiff', 'defendant'))
54_SIDES: tuple[tuple[str, str], ...] = (
55 ('party1', 'party2'), ('party2', 'party1'))
56_UNITED_STATES_FIRST: re.Pattern[str] = re.compile(
57 r'\W*(?:THE\s+)?(?:UNITED\s+STATES|U\.\s?S\.|USA\b)', re.IGNORECASE)
58# The kinds of rules that write several values in one cell.
59_SEVERAL_KINDS: tuple[str, ...] = ('names', 'matches', 'categories')
60_SPLIT_INTO: tuple[str, ...] = ('lists', 'columns')
63@dataclasses.dataclass
64class CodeParties(amos.Munger):
65 """Completes the roles of the parties and finds who brought the appeal.
67 A caption often gives one party's role but not the other's ("United
68 States v. Smith, Defendant-Appellant"). Because the roles in each pair are
69 opposites, a party is coded as an appellee if the other party is an
70 appellant (and so on for petitioners and respondents, and for plaintiffs
71 and defendants).
73 It also adds "party1_appealing" and "party2_appealing" (the party brought
74 the appeal) and "party1_defending" and "party2_defending" (the other
75 party did). Each party's own caption decides first: a party is appealing
76 if it is an appellant and not an appellee, and defending if the reverse.
77 Only a party named neither appellant nor appellee is judged by whether it
78 is a petitioner or respondent, since a habeas petitioner who won below is
79 the appellee ("Petitioner, Appellee"). A party whose own caption decides
80 nothing, or names it both (as a caption that joins several appeals can:
81 "Joseph Prochilo, Defendant, Appellee; United States of America,
82 Appellant, v. Elvis Guerrero, Defendant, Appellee"), takes the opposite
83 of the other party's, if the other party's caption decides it. If both
84 captions decide and agree, both are kept, and if they disagree (both
85 appellants, as in a cross-appeal), both are unknown. Both are false for a
86 party whose role is unknown.
88 Many captions name no roles at all ("United States v. Bullock"), since
89 CourtListener's name of a case has none and some opinions print their
90 caption in a way that the caption rules cannot read (such as the Seventh
91 Circuit's orders, whose captions are in two columns). When neither
92 party's caption decides anything and exactly one party is the United
93 States, the opening of the opinion decides, through the columns that the
94 general header rules make from it, in this order:
96 * "opening_united_states_role": the role that the opening gives the
97 United States ("Plaintiff-Appellee" means the other party appealed,
98 and "Appellant" that the United States did). A role with both, as in
99 a cross-appeal, decides nothing.
100 * "opening_defendant_appellant" and "opening_defendant_appellee": the
101 opening names a defendant (or petitioner or movant) as the appellant,
102 or as the appellee, so the other party (or the United States) did.
103 * "opening_party_appeals" and "opening_government_appeals": the opening
104 says that a party other than the government appealed ("Eduardo Ayon
105 appeals", or counsel filed an Anders brief), or that the government
106 did.
108 Evidence on both sides decides nothing, and the roles stay unknown.
110 Needs the columns "party1_{role}" and "party2_{role}" for each role:
111 appellant, appellee, petitioner, respondent, plaintiff, and defendant.
112 Uses the columns of the opening, if they exist.
114 """
116 def munge(self, data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame:
117 """Completes the roles of the parties.
119 Args:
120 data: the parsed cases.
121 **kwargs: not used.
123 Returns:
124 The cases, with completed roles.
126 """
127 roles = [r for pair in _OPPOSITES for r in pair]
128 needed = [f'{s}_{r}' for s in ('party1', 'party2') for r in roles]
129 _require_federal_columns(data, needed, self.name)
130 original = {c: cases.column_as_flags(data, c) for c in needed}
131 for first, second in _OPPOSITES:
132 for side, other in _SIDES:
133 data[f'{side}_{first}'] = (
134 original[f'{side}_{first}'] | original[f'{other}_{second}'])
135 data[f'{side}_{second}'] = (
136 original[f'{side}_{second}'] | original[f'{other}_{first}'])
137 own = {side: _own_direction(original, side) for side, _ in _SIDES}
138 for side, other in _SIDES:
139 mine_appealing, mine_defending = own[side]
140 other_appealing, other_defending = own[other]
141 mine_known = mine_appealing | mine_defending
142 other_known = other_appealing | other_defending
143 agree = (
144 (mine_appealing & other_defending)
145 | (mine_defending & other_appealing))
146 data[f'{side}_appealing'] = (
147 (mine_appealing & (agree | ~other_known))
148 | (~mine_known & other_defending))
149 data[f'{side}_defending'] = (
150 (mine_defending & (agree | ~other_known))
151 | (~mine_known & other_appealing))
152 found = _opening_direction(data)
153 if found is not None:
154 silent = ~(
155 own['party1'][0] | own['party1'][1]
156 | own['party2'][0] | own['party2'][1])
157 government = _prosecuting_sides(data)
158 one = government['party1'] ^ government['party2']
159 us_appealing, other_appealing = found
160 decided = silent & one & (us_appealing ^ other_appealing)
161 for side, _ in _SIDES:
162 appealing = us_appealing.where(
163 government[side], other_appealing)
164 data[f'{side}_appealing'] = data[f'{side}_appealing'].where(
165 ~decided, appealing)
166 data[f'{side}_defending'] = data[f'{side}_defending'].where(
167 ~decided, ~appealing)
168 return data
171@dataclasses.dataclass
172class CodeCaseType(amos.Munger):
173 """Decides whether each case is criminal or civil, and its other types.
175 A case is criminal ("type_criminal") if the United States is a party and
176 there is a sign of a criminal case: a criminal docket number or history,
177 a United States Attorney as counsel, or a criminal issue in the opinion
178 (any "criminal_..." column). The United States is then the prosecution,
179 and the other party is the criminal defendant. When both parties' text
180 names the United States (as a caption that joins several appeals can:
181 "Joseph Prochilo, Defendant, Appellee; United States of America,
182 Appellant, v. Elvis Guerrero, Defendant, Appellee"), the party whose text
183 ("party1" or "party2") begins with the United States is the prosecution,
184 if only one does, and otherwise the party that is a defendant and not a
185 plaintiff, if only one is, is the criminal defendant.
186 Every other case is civil
187 ("type_civil"), and its plaintiffs and defendants are coded as civil
188 plaintiffs and defendants.
190 Each other prefix of the rules of the topics of cases (see
191 `rules.case_type_prefixes`: "tort", "contract", "ip", "writ", and
192 "constitutional" in courtpy's rules) is a case type too: "type_tort" is
193 true if any "tort_..." column is. So a case can be of several types (a
194 civil case that is a tort case and a contract case), and a prefix added
195 to the rules (such as "immigration_") is a type once the cases are
196 parsed with it. `cases_to_case_types` makes a table of the types.
198 Adds "type_criminal", "type_civil", "type_{prefix}" for each other prefix
199 that a column of the cases has, and for each party, "party1_prosecution",
200 "party1_criminal_defendant", "party1_civil_plaintiff", and
201 "party1_civil_defendant" (and the same for "party2").
203 Needs "party1_united_states", "party2_united_states", "party1_plaintiff",
204 "party2_plaintiff", "party1_defendant", and "party2_defendant". Uses
205 "docket_criminal", "counsel_us_attorney", and the "criminal_..." columns
206 if they exist.
208 """
210 def munge(
211 self,
212 data: pd.DataFrame,
213 prefixes: Sequence[str] | str | None = None,
214 **kwargs: Any) -> pd.DataFrame:
215 """Codes the types of each case.
217 Args:
218 data: the parsed cases.
219 prefixes: the prefixes of the columns of flags that are case
220 types, other than "criminal" and "civil". Defaults to `None`,
221 in which case they are those of courtpy's rules (see
222 `rules.case_type_prefixes`).
223 **kwargs: not used.
225 Returns:
226 The cases, with the new columns.
228 """
229 needed = [
230 f'{side}_{role}' for side in ('party1', 'party2')
231 for role in ('united_states', 'plaintiff', 'defendant')]
232 _require_federal_columns(data, needed, self.name)
233 signals = [
234 c for c in data.columns
235 if c in ('docket_criminal', 'counsel_us_attorney')
236 or c.startswith('criminal_')]
237 criminal_signal = pd.Series(False, index = data.index)
238 for column in signals:
239 criminal_signal |= cases.column_as_flags(data, column)
240 government = (
241 cases.column_as_flags(data, 'party1_united_states')
242 | cases.column_as_flags(data, 'party2_united_states'))
243 criminal = government & criminal_signal
244 data['type_criminal'] = criminal
245 data['type_civil'] = ~criminal
246 chosen = (
247 rules.case_type_prefixes() if prefixes is None
248 else utilities.listify(prefixes))
249 for prefix in chosen:
250 flags = [c for c in data.columns if str(c).startswith(f'{prefix}_')]
251 if prefix in ('criminal', 'civil') or not flags:
252 continue
253 found = pd.Series(False, index = data.index)
254 for column in flags:
255 found |= cases.column_as_flags(data, column)
256 data[f'type_{prefix}'] = found
257 united_states = _prosecuting_sides(data)
258 for side, other in _SIDES:
259 prosecution = criminal & united_states[side]
260 data[f'{side}_prosecution'] = prosecution
261 data[f'{side}_criminal_defendant'] = (
262 criminal & united_states[other] & ~prosecution)
263 data[f'{side}_civil_plaintiff'] = ~criminal & (
264 cases.column_as_flags(data, f'{side}_plaintiff')
265 | cases.column_as_flags(data, f'{other}_defendant'))
266 data[f'{side}_civil_defendant'] = ~criminal & (
267 cases.column_as_flags(data, f'{side}_defendant')
268 | cases.column_as_flags(data, f'{other}_plaintiff'))
269 return data
272@dataclasses.dataclass
273class CodeOutcome(amos.Munger):
274 """Decides whether each decision reversed the court below, and who won.
276 A decision is a reversal ("outcome_reversal") if it reversed, vacated, or
277 remanded. The disposition in the header (or in CourtListener's data) is
278 used when there is one, because the opinion may mention reversals that are
279 not its own. Otherwise, the decision that the opinion states ("AFFIRMED."
280 or "we reverse", which the federal rules find as "decision") is used.
281 Only when there is neither are the opinion's words anywhere ("reverse",
282 "vacate", or "remand") used, which may be about an earlier decision or a
283 standard of review ("we will reverse only if").
285 Then, for each party whose role is known (see `CodeParties`), the party
286 won ("outcome_party1_won") if it brought the appeal and the decision was
287 reversed, or it defended the appeal and the decision was not reversed.
288 With `CodeCaseType`, the winner is also coded by side:
289 "outcome_criminal_defendant_won", "outcome_prosecution_won",
290 "outcome_civil_plaintiff_won", and "outcome_civil_defendant_won", and
291 "appeal_by_defendant" says whether the (criminal or civil) defendant
292 brought the appeal.
294 Values that cannot be known (such as who won when neither party's role is
295 known, or whether the criminal defendant won a civil case) are missing
296 (`pd.NA`). Filter the cases before using such a column as a label (for
297 example, with the `filter_rows` technique and the query "type_criminal").
299 Needs "disposition_reverse", "disposition_vacate", "disposition_remand",
300 "opinion_reverse", "opinion_vacate", and "opinion_remand". Uses
301 "disposition", "decision", "decision_reverse", "decision_vacate", and
302 "decision_remand", and the columns made by `CodeParties` and
303 `CodeCaseType`, if they exist.
305 """
307 def munge(self, data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame:
308 """Codes the outcome of each decision.
310 Args:
311 data: the parsed cases.
312 **kwargs: not used.
314 Returns:
315 The cases, with the new columns.
317 """
318 rulings = ('reverse', 'vacate', 'remand')
319 _require_federal_columns(
320 data,
321 [f'{p}_{r}' for p in ('disposition', 'opinion') for r in rulings],
322 self.name)
323 header = pd.Series(False, index = data.index)
324 decision = pd.Series(False, index = data.index)
325 opinion = pd.Series(False, index = data.index)
326 for ruling in rulings:
327 header |= cases.column_as_flags(data, f'disposition_{ruling}')
328 decision |= cases.column_as_flags(data, f'decision_{ruling}')
329 opinion |= cases.column_as_flags(data, f'opinion_{ruling}')
330 reversal = header.where(
331 _has_text(data, 'disposition'),
332 decision.where(_has_text(data, 'decision'), opinion))
333 data['outcome_reversal'] = reversal
334 if not {'party1_appealing', 'party2_appealing'} <= set(data.columns):
335 return data
336 won = {}
337 for side, _ in _SIDES:
338 outcome = pd.Series(pd.NA, index = data.index, dtype = 'boolean')
339 appealing = cases.column_as_flags(data, f'{side}_appealing')
340 defending = cases.column_as_flags(data, f'{side}_defending')
341 outcome[appealing] = reversal[appealing]
342 outcome[defending] = ~reversal[defending]
343 won[side] = outcome
344 data[f'outcome_{side}_won'] = outcome
345 categories = {
346 'criminal_defendant': 'criminal_defendant',
347 'prosecution': 'prosecution',
348 'civil_plaintiff': 'civil_plaintiff',
349 'civil_defendant': 'civil_defendant'}
350 if all(f'party1_{c}' in data.columns for c in categories.values()): 350 ↛ 370line 350 didn't jump to line 370 because the condition on line 350 was always true
351 for name, column in categories.items():
352 outcome = pd.Series(
353 pd.NA, index = data.index, dtype = 'boolean')
354 for side, _ in _SIDES:
355 present = cases.column_as_flags(data, f'{side}_{column}')
356 outcome[present] = won[side][present]
357 data[f'outcome_{name}_won'] = outcome
358 by_defendant = pd.Series(
359 pd.NA, index = data.index, dtype = 'boolean')
360 for side, _ in _SIDES:
361 defendant = (
362 cases.column_as_flags(data, f'{side}_criminal_defendant')
363 | cases.column_as_flags(data, f'{side}_civil_defendant'))
364 known = defendant & (
365 cases.column_as_flags(data, f'{side}_appealing')
366 | cases.column_as_flags(data, f'{side}_defending'))
367 appealing = cases.column_as_flags(data, f'{side}_appealing')
368 by_defendant[known] = appealing[known]
369 data['appeal_by_defendant'] = by_defendant
370 return data
373@dataclasses.dataclass
374class DropTextColumns(amos.Cleaner):
375 """Removes columns that models cannot use, such as text and lists.
377 Removes every column of text, lists, or dates stored as text (such as
378 "case_name", "panel_judges", and "date_filed"), so that the cases can be
379 analyzed. Categories, numbers, and booleans are kept. The label and groups
380 are always kept.
382 """
384 def clean(
385 self,
386 data: pd.DataFrame,
387 keep: Sequence[str] | str | None = None,
388 label: str | None = None,
389 groups: Sequence[str] = (),
390 **kwargs: Any) -> pd.DataFrame:
391 """Removes columns of text and lists.
393 Args:
394 data: the cases.
395 keep: names of columns to keep even if they hold text. Defaults to
396 `None`.
397 label: name of the label, which is always kept. Defaults to
398 `None`.
399 groups: names of the group columns, which are always kept.
400 Defaults to an empty tuple.
401 **kwargs: not used.
403 Returns:
404 The cases, without text and lists.
406 """
407 names = [keep] if isinstance(keep, str) else list(keep or [])
408 missing = [c for c in names if c not in data.columns]
409 if missing: 409 ↛ 410line 409 didn't jump to line 410 because the condition on line 409 was never true
410 message = f'the columns {missing} are not in the data'
411 raise KeyError(message)
412 kept = {*names, *(c for c in [label, *groups] if c)}
413 dropped = [
414 c for c in data.columns
415 if c not in kept and _is_text(data[c])]
416 return data.drop(columns = dropped)
418 def apply(self, item: amos.Dataset, **kwargs: Any) -> amos.Dataset:
419 """Removes the columns of text and lists of `item`.
421 Args:
422 item: the dataset to clean.
423 **kwargs: parameters for `clean`.
425 Returns:
426 The cleaned dataset.
428 """
429 return super().apply(
430 item, **{'label': item.label, 'groups': item.groups, **kwargs})
433@dataclasses.dataclass
434class SplitValues(amos.Munger):
435 """Turns text with several values in each cell into lists or columns.
437 Rules that find several values in a case (`names`, `matches`, and
438 `categories` rules, such as "panel_judges", "citations_case", and
439 "agencies") write them as text, with "; " between them. With "into" set
440 to "lists" (the default), each cell becomes a list of its values, and a
441 cell without values an empty list.
442 With "columns", each value gets a column of its own, named for the column
443 and the value's place ("panel_judges_1", "panel_judges_2", and so on, for
444 as many values as the row with the most has), and the text is kept.
446 To make a row for each value instead, use the `lists_to_rows` technique
447 of `amos` (with "separator" set to ";").
449 """
451 """ Public Methods """
453 def munge(
454 self,
455 data: pd.DataFrame,
456 columns: str | Sequence[str] | None = None,
457 separator: str = cases._SEPARATOR,
458 into: str = 'lists',
459 **kwargs: Any) -> pd.DataFrame:
460 """Splits the values of each cell of `columns`.
462 Args:
463 data: the cases.
464 columns: names of the columns to split. Defaults to `None`, in
465 which case they are the columns of the `names`, `matches`,
466 and `categories` rules of the federal rulebook that are in
467 the data.
468 separator: the text between the values. Defaults to "; ", as the
469 federal rules write them.
470 into: "lists" or "columns". Defaults to "lists".
471 **kwargs: not used.
473 Raises:
474 KeyError: if a column is not in the data.
475 ValueError: if `into` is not "lists" or "columns".
477 Returns:
478 The cases, with lists in place of the text or with new columns.
480 """
481 if into not in _SPLIT_INTO:
482 message = f'into must be one of {list(_SPLIT_INTO)}, not {into!r}'
483 raise ValueError(message)
484 if columns is None:
485 names = [c for c in _several_values() if c in data.columns]
486 else:
487 names = utilities.listify(columns)
488 _require_federal_columns(data, names, self.name)
489 added: list[pd.DataFrame] = []
490 for column in names:
491 values = [
492 cases.split_cell(v, separator) for v in data[column].tolist()]
493 if into == 'lists':
494 data[column] = pd.Series(
495 values, index = data.index, dtype = object)
496 continue
497 wide = pd.DataFrame(values, index = data.index, dtype = object)
498 wide.columns = [f'{column}_{n + 1}' for n in range(wide.shape[1])]
499 added.append(wide)
500 if added:
501 data = pd.concat([data, *added], axis = 1)
502 return data
505@dataclasses.dataclass
506class TidyCases(amos.Munger):
507 """Gives columns of booleans or whole numbers with missing values a type.
509 `pandas` stores a column of booleans with missing values (such as
510 "published", which is unknown for some cases) as plain objects, and a
511 column of whole numbers with missing values (such as "year") as decimals.
512 Such columns become the "boolean" and "Int64" types, which allow missing
513 values (see `courtpy.cases.tidy`). Tables that courtpy parses or loads
514 are tidied already, so it is for tables made or changed in other ways.
516 """
518 """ Public Methods """
520 def munge(self, data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame:
521 """Gives the columns of booleans and whole numbers their types.
523 Args:
524 data: the cases.
525 **kwargs: not used.
527 Returns:
528 The cases, with those columns changed.
530 """
531 return cases.tidy(data)
534def code(
535 data: pd.DataFrame | amos.Dataset,
536 coders: str | Sequence[str] | None = options._DEFAULT_CODERS,
537 *,
538 parameters: Mapping[str, Mapping[str, Any]] | None = None) -> amos.Dataset:
539 """Applies coders (or other `amos` techniques) to parsed cases.
541 Args:
542 data: the parsed cases, or a dataset of them (which is changed in
543 place).
544 coders: names of the techniques to apply, in order. Defaults to
545 `options._DEFAULT_CODERS`. "none" (or `None`) applies none.
546 parameters: parameters for the techniques, by their names. Defaults
547 to `None`.
549 Returns:
550 A dataset of the coded cases, whose history records each technique:
551 `Cases` made from a table, or the kind that the last shaper made
552 (such as `Votes`, after "cases_to_votes").
554 """
555 dataset = (
556 data if isinstance(data, amos.Dataset)
557 else datasets.Cases.create(data))
558 for name in utilities.listify(coders):
559 if utilities.is_none_setting(name):
560 continue
561 kind = cast(
562 'type[amos.Operation]',
563 chrisjen.library.borrow(name, genre = 'operation'))
564 settings = dict((parameters or {}).get(name, {}))
565 technique = kind(parameters = settings)
566 dataset = technique.apply(dataset)
567 return dataset
570""" Private Functions """
573@functools.cache
574def _several_values() -> tuple[str, ...]:
575 """Returns the columns of the federal rules with several values in a cell.
577 The rulebooks' files are read the first time only.
579 Returns:
580 The names of the columns that the `names`, `matches`, and
581 `categories` rules of the header rulebooks of every source and of
582 the federal rulebook make, in order.
584 """
585 book = amos.parsers.Rulebook.create(*(
586 rulebook for name, rulebook in rules.RULEBOOKS.items()
587 if name == 'federal' or name.endswith('header')))
588 return tuple(dict.fromkeys(
589 n for r in book if r.kind in _SEVERAL_KINDS for n in r.names))
592def _opening_direction(
593 data: pd.DataFrame) -> tuple[pd.Series, pd.Series] | None:
594 """Returns whether the opening says the United States or the other appealed.
596 The role that the opening gives the United States decides first. Where
597 it gives none, the defendant's role in the opening decides, and where
598 there is neither, whether the opening says that a party other than the
599 government appealed, or that the government did. Evidence on both sides,
600 or a role that the opening's sentences contradict, is true for both,
601 which decides nothing (see `CodeParties`).
603 Args:
604 data: the cases, with the columns of the opening that the general
605 header rules make.
607 Returns:
608 Whether the United States appealed and whether the other party did,
609 or `None` if `data` has none of the columns of the opening.
611 """
612 columns = [
613 'opening_united_states_role', 'opening_defendant_appellant',
614 'opening_defendant_appellee', 'opening_party_appeals',
615 'opening_government_appeals']
616 if not any(c in data.columns for c in columns):
617 return None
618 false = pd.Series(False, index = data.index)
619 role = (
620 data['opening_united_states_role'].astype('string').fillna('')
621 if 'opening_united_states_role' in data.columns
622 else pd.Series('', index = data.index, dtype = 'string'))
623 role = role.str.upper()
624 role_appellant = role.str.contains('APPELLANT', regex = False)
625 role_appellee = role.str.contains('APPELLEE', regex = False)
626 role_known = role_appellant | role_appellee
627 flags = {
628 c: cases.column_as_flags(data, c) if c in data.columns else false
629 for c in columns[1:]}
630 by_defendant = (
631 flags['opening_defendant_appellant']
632 | flags['opening_defendant_appellee'])
633 caption_known = role_known | by_defendant
634 caption_us = role_appellant.where(
635 role_known, flags['opening_defendant_appellee'])
636 caption_other = role_appellee.where(
637 role_known, flags['opening_defendant_appellant'])
638 said_us = flags['opening_government_appeals']
639 said_other = flags['opening_party_appeals']
640 said = said_us ^ said_other
641 # A caption that the opening's sentences contradict decides nothing.
642 conflict = caption_known & said & (
643 (caption_us & said_other) | (caption_other & said_us))
644 us_appealing = caption_us.where(caption_known, said_us) | conflict
645 other_appealing = caption_other.where(caption_known, said_other) | conflict
646 return us_appealing.astype(bool), other_appealing.astype(bool)
649def _own_direction(
650 roles: Mapping[str, pd.Series],
651 side: str) -> tuple[pd.Series, pd.Series]:
652 """Returns whether a party's own caption says it appealed or defended.
654 The party's appellant and appellee flags decide, unless it has neither,
655 in which case its petitioner and respondent flags do. A party with both
656 flags of the pair that decides is neither appealing nor defending.
658 Args:
659 roles: the parties' flags as parsed, by column name (such as
660 "party1_appellant").
661 side: "party1" or "party2".
663 Returns:
664 Whether the party is appealing, and whether it is defending, by its
665 own caption alone.
667 """
668 appellant = roles[f'{side}_appellant']
669 appellee = roles[f'{side}_appellee']
670 appellate = appellant | appellee
671 appealing = appellant.where(appellate, roles[f'{side}_petitioner'])
672 defending = appellee.where(appellate, roles[f'{side}_respondent'])
673 return appealing & ~defending, defending & ~appealing
676def _prosecuting_sides(data: pd.DataFrame) -> dict[str, pd.Series]:
677 """Returns which party is the United States, for finding the prosecution.
679 A party is the United States if its text names it. If both parties' text
680 does, as a caption that joins several appeals can, the party whose text
681 begins with the United States is, if only one does ("party1" and
682 "party2" are the parties' text). Otherwise, if only one of them is a
683 defendant and not a plaintiff, that one is not.
685 Args:
686 data: the cases, with "party1_united_states", "party2_united_states",
687 and the parties' plaintiff and defendant flags.
689 Returns:
690 Whether each party is the United States, by "party1" and "party2".
692 """
693 named = {
694 side: cases.column_as_flags(data, f'{side}_united_states')
695 for side, _ in _SIDES}
696 both = named['party1'] & named['party2']
697 defendant = {
698 side: cases.column_as_flags(data, f'{side}_defendant')
699 & ~cases.column_as_flags(data, f'{side}_plaintiff')
700 for side, _ in _SIDES}
701 first = {side: _begins_with_united_states(data, side) for side, _ in _SIDES}
702 by_text = first['party1'] ^ first['party2']
703 by_role = ~by_text & (defendant['party1'] ^ defendant['party2'])
704 return {
705 side: named[side] & ~(
706 both & ((by_text & ~first[side]) | (by_role & defendant[side])))
707 for side, _ in _SIDES}
710def _begins_with_united_states(data: pd.DataFrame, side: str) -> pd.Series:
711 """Returns whether a party's text begins with the United States.
713 Args:
714 data: the cases.
715 side: "party1" or "party2", the column of the party's text.
717 Returns:
718 Whether the text begins with "United States" (or "U.S." or "USA"),
719 or false values if `data` has no such column.
721 """
722 if side not in data.columns:
723 return pd.Series(False, index = data.index)
724 text = data[side].astype('string').fillna('')
725 return text.str.match(_UNITED_STATES_FIRST).astype(bool)
728def _has_text(data: pd.DataFrame, column: str) -> pd.Series:
729 """Returns whether each case has text in a column.
731 Args:
732 data: the cases.
733 column: name of the column.
735 Returns:
736 Whether each case's value is text that is not blank, or a column of
737 false values if `data` has no such column.
739 """
740 if column not in data.columns:
741 return pd.Series(False, index = data.index)
742 return data[column].fillna('').astype(str).str.strip() != ''
745def _is_text(column: pd.Series) -> bool:
746 """Returns whether a column holds text, lists, or other objects.
748 Categories, booleans, numbers, and dates are not text. Neither is a
749 column of `object` type that holds only booleans (and missing values),
750 which `pandas` makes when booleans are mixed with missing values.
752 Args:
753 column: a column of the cases.
755 Returns:
756 Whether models cannot use the column (so `DropTextColumns` removes it).
758 """
759 if isinstance(column.dtype, pd.CategoricalDtype):
760 return False
761 if (pd.api.types.is_bool_dtype(column.dtype)
762 or pd.api.types.is_numeric_dtype(column.dtype)):
763 return False
764 if pd.api.types.is_datetime64_any_dtype(column.dtype): 764 ↛ 765line 764 didn't jump to line 765 because the condition on line 764 was never true
765 return False
766 values = column.dropna()
767 only_booleans = values.map(lambda v: isinstance(v, bool)).all()
768 return not (len(values) > 0 and only_booleans)
771def _require_federal_columns(
772 data: pd.DataFrame,
773 columns: Sequence[str],
774 name: str) -> None:
775 """Raises an error if the cases lack columns that the federal rules make.
777 Args:
778 data: the cases.
779 columns: names of the columns that are needed.
780 name: name of the technique that needs them.
782 Raises:
783 KeyError: if a column is missing.
785 """
786 cases.require_columns(
787 data, columns, repr(name),
788 hint = (
789 'The federal rules make them: parse the cases with them (or '
790 'with rules that make the same columns) first.'))