Coverage for src/courtpy/core/datasets.py: 100%

96 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""The kinds of datasets that courtpy makes, one for each kind of row. 

2 

3Each is an `amos.Dataset`, so every technique of `amos` works on it, and 

4everything that `amos` says about datasets is true of it. What a class adds 

5is what its rows are, the column that labels them, and how to save and load 

6it. courtpy's loaders make `Cases`, and its shapers turn one kind into 

7another: 

8 

9| Dataset | One row for each | Labeled by | Made by | 

10| --- | --- | --- | --- | 

11| `Cases` | Case, with its information and the text of its sections. | `case_id` | courtpy's loaders, `votes_to_cases`, `dockets_to_cases` | 

12| `Dockets` | Docket number of each case, with the case's columns. A case that consolidated several appeals has a row for each. | `case_docket` | `cases_to_dockets` | 

13| `Votes` | Judge on each case (or each docket), with the case's columns and the judge's vote. | `vote_id` | `cases_to_votes`, `dockets_to_votes` | 

14| `Judges` | Judge, with what is known about the judge and summaries of the judge's votes. | `judge_nid` | `cases_to_judges` | 

15| `Courts` | Court, with summaries of its cases and their judges. | `court_num` | `cases_to_courts` | 

16| `CaseTypes` | Case type (such as "criminal" or "tort"), with summaries of its cases. | `case_type` | `cases_to_case_types` | 

17| `PartyTypes` | Party type, with summaries of the cases of parties of that type. | `party_type` | `cases_to_party_types` | 

18 

19`Cases`, `Dockets`, and `Votes` can be made from each other. `Judges`, `Courts`, 

20`CaseTypes`, and `PartyTypes` summarize many cases, and they keep nothing 

21about any one case (such as its docket number or date), so there is no 

22going back from them. 

23 

24`save` saves a dataset whole (with its label, split, history, and anything 

25that techniques have added) in a joblib file, and its data as a table that a 

26spreadsheet or another program can read, as the `save_data` technique of 

27`amos` does. `load` loads either one: 

28 

29```python 

30import courtpy 

31 

32cases = courtpy.Cases.load('cases.csv') 

33cases.save('cases.parquet') 

34``` 

35 

36Contents: 

37 CaseTypes: a table with one row for each case type. 

38 Cases: a table with one row for each case. 

39 CourtData: base class for courtpy's datasets. 

40 Courts: a table with one row for each court. 

41 Dockets: a table with one row for each docket number of each case. 

42 Judges: a table with one row for each judge. 

43 PartyTypes: a table with one row for each party type. 

44 Votes: a table with one row for each judge on each case. 

45 _TABLE_FORMATS: the format of the table that `CourtData.save` saves, by 

46 the extension of the file. 

47 

48""" 

49 

50from __future__ import annotations 

51 

52import copy 

53import dataclasses 

54import pathlib 

55from typing import Any, ClassVar, Self 

56 

57import amos 

58import nagata 

59import pandas as pd 

60 

61from . import cases 

62 

63_TABLE_FORMATS: dict[str, str | None] = { 

64 '.csv': 'csv', 

65 '.parquet': 'parquet', 

66 '.xlsx': 'excel', 

67 '.joblib': None, 

68 '': None} 

69 

70 

71@dataclasses.dataclass(eq = False) 

72class CourtData(amos.Dataset): 

73 """Base class for courtpy's datasets. 

74 

75 A subclass names the column that labels its rows (`key`). It has no 

76 fields of its own, so a dataset of one kind can become another (see 

77 `adopt`) without losing anything. 

78 

79 Args: 

80 data: the data. Defaults to an empty `DataFrame`. 

81 (the other arguments of `amos.Dataset`) 

82 

83 Attributes: 

84 key: the name of the index of the rows (such as "case_id"). 

85 

86 """ 

87 

88 key: ClassVar[str] = '' 

89 

90 """ Class Methods """ 

91 

92 @classmethod 

93 def adopt(cls, dataset: amos.Dataset) -> Self: 

94 """Returns `dataset` as a dataset of this kind. 

95 

96 The new dataset shares everything with `dataset` (its data, label, 

97 split, history, and so on), so a shaper can hand on a dataset of 

98 another kind. If the data has a column named `key`, it labels the 

99 rows. 

100 

101 Args: 

102 dataset: a dataset of any kind. 

103 

104 Returns: 

105 `dataset` itself if it is already of this kind, and otherwise a 

106 new dataset of this kind with the same attributes. 

107 

108 """ 

109 if type(dataset) is cls: 

110 adopted = dataset 

111 else: 

112 adopted = cls.__new__(cls) 

113 adopted.__dict__.update(dataset.__dict__) 

114 adopted._label_rows() 

115 return adopted 

116 

117 @classmethod 

118 def create(cls, item: Any, **kwargs: Any) -> Self: 

119 """Returns a dataset of this kind made from `item`. 

120 

121 Args: 

122 item: anything that `amos.Dataset.create` takes: a dataset, a 

123 table, or the path of a data file (including a joblib file 

124 that `save` saved). 

125 **kwargs: arguments of `amos.Dataset.create`, such as "label" 

126 and "groups". 

127 

128 Returns: 

129 The dataset. 

130 

131 """ 

132 return cls.adopt(amos.Dataset.create(item, **kwargs)) 

133 

134 @classmethod 

135 def load(cls, path: pathlib.Path | str, **kwargs: Any) -> Self: 

136 """Loads a dataset that `save` saved, or a table of one. 

137 

138 A joblib file holds the whole dataset, which goes on from where it 

139 was saved. A table (such as a CSV or parquet file) holds only its 

140 data: the column named `key` labels the rows again, and columns of 

141 booleans and whole numbers with missing values get the types that 

142 allow them (see `cases.tidy`). 

143 

144 Args: 

145 path: the path of the file. 

146 **kwargs: arguments of `amos.Dataset.create`, such as "label" 

147 and "groups". 

148 

149 Raises: 

150 FileNotFoundError: if there is no file at `path`. 

151 TypeError: if the file holds a courtpy dataset of another kind. 

152 

153 Returns: 

154 The dataset. 

155 

156 """ 

157 path = pathlib.Path(path).expanduser() 

158 if not path.is_file(): 

159 message = f'there is no file of {cls.__name__} at {path}' 

160 raise FileNotFoundError(message) 

161 loaded = amos.Dataset.create(path, **kwargs) 

162 if isinstance(loaded, CourtData) and not isinstance(loaded, cls): 

163 message = ( 

164 f'{path} holds {type(loaded).__name__}, not {cls.__name__}: ' 

165 f'load it with courtpy.{type(loaded).__name__}.load' 

166 ) 

167 raise TypeError(message) 

168 dataset = loaded if isinstance(loaded, cls) else cls.adopt(loaded) 

169 if not isinstance(loaded, CourtData): 

170 dataset.data = cases.tidy(dataset.data) 

171 dataset._label_rows() 

172 return dataset 

173 

174 """ Public Methods """ 

175 

176 def save( 

177 self, 

178 path: pathlib.Path | str, 

179 *, 

180 clerk: nagata.FileManager | None = None, 

181 compress: int | bool = 0) -> list[pathlib.Path]: 

182 """Saves the whole dataset, and its data as a table. 

183 

184 The `save_data` technique of `amos` saves the dataset in a joblib file 

185 named for `path` (such as "cases.joblib" beside "cases.csv"), which 

186 `load` loads as it was, and the data in `path`, in the format of its 

187 extension: ".csv", ".parquet", or ".xlsx". A path ending in ".joblib" 

188 (or with no extension) saves only the dataset. Several values in one 

189 cell (such as the lists that `split_values` makes) are saved as text, 

190 with "; " between them, as courtpy's rules write them. The dataset's 

191 history records where the files are. 

192 

193 Args: 

194 path: the path of the table. Its folder is made if needed. 

195 clerk: the file manager that saves the files. Defaults to `None`, 

196 in which case one for the folder of `path` is used, so 

197 nothing else is made. 

198 compress: how much joblib compresses the file of the dataset, 

199 from 0 (not at all) to 9. Defaults to 0. 

200 

201 Raises: 

202 ValueError: if the extension of `path` is not one listed above. 

203 

204 Returns: 

205 The paths of the files that were saved. 

206 

207 """ 

208 path = pathlib.Path(path).expanduser().resolve() 

209 suffix = path.suffix.lower() 

210 if suffix not in _TABLE_FORMATS: 

211 message = ( 

212 f'{path.name} must end in one of ' 

213 f'{[s for s in _TABLE_FORMATS if s]}') 

214 raise ValueError(message) 

215 folder = path.parent 

216 folder.mkdir(parents = True, exist_ok = True) 

217 if clerk is None: 

218 clerk = nagata.FileManager( 

219 root_folder = folder, 

220 input_folder = folder, 

221 interim_folder = folder, 

222 output_folder = folder) 

223 joined = copy.copy(self) 

224 joined.data = _join_lists(self.data) 

225 joined.history = list(self.history) 

226 amos.savers.SaveData(clerk = clerk).apply( 

227 joined, 

228 folder = folder, 

229 file_name = path.stem, 

230 table_format = _TABLE_FORMATS[suffix] or False, 

231 compress = compress) 

232 self.history.append(joined.history[-1]) 

233 return [pathlib.Path(file) for file in joined.history[-1]['files']] 

234 

235 """ Private Methods """ 

236 

237 def _label_rows(self) -> None: 

238 """Makes the column named `key`, if the data has one, label the rows. 

239 

240 A table read from a CSV file has its labels as a column, since a CSV 

241 file has no index. 

242 

243 """ 

244 if self.key and self.key in self.data.columns: 

245 labeled = self.data.set_index(self.key) 

246 if self.key in {'case_id', 'case_docket', 'vote_id'}: 

247 labeled.index = labeled.index.astype(str) 

248 self.data = labeled 

249 

250 

251@dataclasses.dataclass(eq = False) 

252class Cases(CourtData): 

253 """A table with one row for each case. 

254 

255 The rows are labeled by "case_id", and the columns are what courtpy's 

256 rules and coders find in each case: its information (court, date, 

257 parties, judges, and so on), the issues that it discusses, its outcome, 

258 and (with a loader's "keep_text") the text of its sections. courtpy's 

259 loaders make it, and `votes_to_cases` makes it from `Votes`. 

260 

261 """ 

262 

263 key: ClassVar[str] = 'case_id' 

264 

265 

266@dataclasses.dataclass(eq = False) 

267class Dockets(CourtData): 

268 """A table with one row for each docket number of each case. 

269 

270 A case that decided several consolidated appeals has several docket 

271 numbers, and records kept by docket (such as the Federal Judicial 

272 Center's Integrated Database, which `add_idb` adds) have one for each. 

273 The rows are labeled by "case_docket" (the case's id and the docket's 

274 place among its docket numbers, such as "4567890-2"), "case_id" says 

275 which case each row belongs to, and "docket" is the row's one docket 

276 number. Each row has the case's columns. `cases_to_dockets` makes it from 

277 `Cases`, and `dockets_to_cases` and `dockets_to_votes` make `Cases` and 

278 `Votes` from it. 

279 

280 """ 

281 

282 key: ClassVar[str] = 'case_docket' 

283 

284 

285@dataclasses.dataclass(eq = False) 

286class Votes(CourtData): 

287 """A table with one row for each judge on each case. 

288 

289 The rows are labeled by "vote_id" (the case's id and the judge's place on 

290 the panel, such as "4567890-2"), and "case_id" says which case each row 

291 belongs to. Each row has the case's columns, the judge's (such as 

292 "judge_party"), the other judges' (such as "colleagues_party"), and the 

293 judge's vote (such as "vote_reversal"). `cases_to_votes` makes it from 

294 `Cases`. 

295 

296 """ 

297 

298 key: ClassVar[str] = 'vote_id' 

299 

300 

301@dataclasses.dataclass(eq = False) 

302class Judges(CourtData): 

303 """A table with one row for each judge. 

304 

305 The rows are labeled by "judge_nid" (the Federal Judicial Center's number 

306 for the judge). Each row has the judge's name, the number of the judge's 

307 cases, what is known about the judge, and the means of the judge's votes: 

308 the share of the judge's votes to reverse, the share of the judge's cases 

309 of each case type, and so on. `cases_to_judges` makes it from `Cases` or 

310 `Votes`. 

311 

312 """ 

313 

314 key: ClassVar[str] = 'judge_nid' 

315 

316 

317@dataclasses.dataclass(eq = False) 

318class Courts(CourtData): 

319 """A table with one row for each court. 

320 

321 The rows are labeled by the court's number ("court_num", unless another 

322 column was named). Each row has the number of the court's cases and of 

323 its judges, and the means of its cases' columns: the share of its cases 

324 of each case type, the share that it reversed, the mean composition of 

325 its panels, and so on. `cases_to_courts` makes it from `Cases`. 

326 

327 """ 

328 

329 key: ClassVar[str] = 'court_num' 

330 

331 

332@dataclasses.dataclass(eq = False) 

333class CaseTypes(CourtData): 

334 """A table with one row for each case type. 

335 

336 The rows are labeled by "case_type" (such as "criminal", "civil", "tort", 

337 or "contract"; see `code_case_type`). Each row has the number of cases of 

338 the type and the means of their columns. A case of several types (such 

339 as a tort case and a contract case) counts for each of them. 

340 `cases_to_case_types` makes it from `Cases`. 

341 

342 """ 

343 

344 key: ClassVar[str] = 'case_type' 

345 

346 

347@dataclasses.dataclass(eq = False) 

348class PartyTypes(CourtData): 

349 """A table with one row for each party type. 

350 

351 The rows are labeled by "party_type" (such as "individual" or 

352 "corporation"). Each row has the number of parties of the type, the 

353 share of them that won, and the means of the columns of their cases. 

354 `cases_to_party_types` makes it from `Cases` whose parties have types. 

355 

356 """ 

357 

358 key: ClassVar[str] = 'party_type' 

359 

360 

361""" Private Functions """ 

362 

363 

364def _join_lists(data: pd.DataFrame) -> pd.DataFrame: 

365 """Returns a table with each list in a cell joined into text. 

366 

367 Args: 

368 data: the table. 

369 

370 Returns: 

371 A copy of `data` in which each list or tuple in a column of objects 

372 is its items, joined with "; ". `data` itself if it has none. 

373 

374 """ 

375 listed = [ 

376 column for column in data.columns 

377 if data[column].dtype == object 

378 and data[column].map(_is_list).any()] 

379 if not listed: 

380 return data 

381 joined = data.copy() 

382 for column in listed: 

383 joined[column] = joined[column].map( 

384 lambda v: cases._SEPARATOR.join(map(str, v)) if _is_list(v) 

385 else v) 

386 return joined 

387 

388 

389def _is_list(value: Any) -> bool: 

390 """Returns whether a value is a `list` or `tuple`. 

391 

392 Args: 

393 value: a cell of a table. 

394 

395 Returns: 

396 Whether it is a `list` or `tuple`. 

397 

398 """ 

399 return isinstance(value, list | tuple)