Coverage for src/courtpy/references/scores.py: 93%

66 statements  

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

1"""Adds behavioral scores of judges and courts, computed from training data. 

2 

3A study can score each judge or court from the cases of a training set (such 

4as the share of a judge's votes to reverse, or how often a court sides with 

5the government) and add the scores to the cases of a test set. These 

6mergers add such scores from a table that has them, as the `merge_keys` 

7technique of `amos` adds the columns of another table's row with the same 

8keys: 

9 

10| Technique | Adds | Matched by | 

11| --- | --- | --- | 

12| `add_judge_scores` | Each column of the table of scores, for each judge: "judge_score_{column}" in `Votes`, and "judge_score_{column}1", "judge_score_{column}2", and so on (by each judge's seat) in `Cases`. | The judge's number ("judge_nid", which `code_panels`, `add_biography`, and `cases_to_votes` add) unless "on" names another column, such as the judge's name. | 

13| `add_court_scores` | Each column of the table of scores: "court_score_{column}". | The court's number ("court_num") unless "on" names another column. | 

14 

15The table is a data file (looked for in the current folder and then in the 

16clerk's input folder) or a table, such as a table of `Judges` or `Courts` 

17made from the training cases (see `cases_to_judges` and `cases_to_courts`). 

18 

19Contents: 

20 AddCourtScores: adds scores of each case's court from a table of them. 

21 AddJudgeScores: adds scores of each judge of each row from a table of 

22 them. 

23 

24""" 

25 

26from __future__ import annotations 

27 

28import dataclasses 

29import re 

30from collections.abc import Sequence 

31from typing import Any 

32 

33import amos 

34import numpy as np 

35import pandas as pd 

36 

37from ..core import cases, datasets, utilities 

38 

39 

40@dataclasses.dataclass 

41class AddJudgeScores(amos.mergers.MergeKeys): 

42 """Adds scores of each judge of each row from a table of them. 

43 

44 Each row of the table of scores is a judge, with the judge's number 

45 ("judge_nid" or "nid") or another key (such as the judge's name) and 

46 columns of scores. In `Votes` (or any table with a row for each judge), 

47 each row gets the scores of its judge, as "judge_score_{column}". In 

48 `Cases`, each case gets the scores of each judge on its panel, numbered 

49 by the judge's seat: "judge_score_{column}1" for the judge in 

50 "judge_nid1", and so on (so `code_panels` or `add_biography` must come 

51 first). A judge who is not in the table gets missing values. 

52 

53 It takes the parameters of the `merge_keys` technique of `amos`: 

54 "source" (the table of scores), "columns" (the scores to add, which are 

55 every column but the key by default), "prefix" ("judge_score_" unless 

56 another is set), "on" (the column of the data with each judge's key, 

57 "judge_nid" unless another is set: in `Cases`, the columns are that name 

58 followed by each seat's number), "other_on" (the key of the table of 

59 scores, which is "judge_nid" or else "nid" if the table has one, and 

60 otherwise the same as "on"), and "duplicates". "numbered" says whether 

61 each row has several judges, whose columns are numbered; it is true for 

62 `Cases` unless it is set. 

63 

64 """ 

65 

66 """ Public Methods """ 

67 

68 def apply( 

69 self, 

70 item: amos.Dataset, 

71 *, 

72 source: Any = None, 

73 columns: Sequence[str] | str | None = None, 

74 prefix: str | None = 'judge_score_', 

75 on: str = 'judge_nid', 

76 other_on: str | None = None, 

77 numbered: bool | None = None, 

78 duplicates: str = 'error', 

79 **kwargs: Any) -> amos.Dataset: 

80 """Adds the scores of each judge of each row of `item`. 

81 

82 Args: 

83 item: the dataset of votes or of cases. 

84 source: the table of scores, or the path of a data file of one. 

85 columns: the scores to add. Defaults to `None`, for every column 

86 of the table but its key. 

87 prefix: text to put before the names of the added columns. 

88 Defaults to "judge_score_". 

89 on: the column of `item` with each judge's key, or (numbered) the 

90 start of the names of the columns of each seat's key. 

91 Defaults to "judge_nid". 

92 other_on: the column of the table with each judge's key. 

93 Defaults to `None`, for "judge_nid" or "nid" if the table has 

94 one, and otherwise `on`. 

95 numbered: whether each row has several judges, whose columns are 

96 numbered by their seats. Defaults to `None`, in which case it 

97 is true if `item` is `Cases`. 

98 duplicates: what to do if the table has several rows for a judge 

99 (see `amos.mergers.MergeKeys.match`). Defaults to "error". 

100 **kwargs: other parameters of `merge_keys`, such as "reader" and 

101 "indicator". 

102 

103 Raises: 

104 KeyError: if `item` lacks the judges' keys, or the table lacks 

105 its key or one of `columns`. 

106 ValueError: if there is no `source`, or an added column would 

107 have the name of a column of the data. 

108 

109 Returns: 

110 The dataset with the added columns. 

111 

112 """ 

113 if numbered is None: 113 ↛ 115line 113 didn't jump to line 115 because the condition on line 113 was always true

114 numbered = isinstance(item, datasets.Cases) 

115 if not numbered: 

116 other = _unlabeled(self.read(source)) if source is not None else ( 

117 None) 

118 return super().apply( 

119 item, 

120 source = other if other is not None else source, 

121 columns = None if columns is None else utilities.listify( 

122 columns), 

123 prefix = prefix, 

124 on = on, 

125 other_on = other_on or _key_of(other, on), 

126 duplicates = duplicates, 

127 **kwargs) 

128 if source is None: 

129 message = ( 

130 f'{self.name!r} has nothing to merge: set its "source" in the ' 

131 f'"{self.name}_parameters" section of the settings') 

132 raise ValueError(message) 

133 other = _unlabeled( 

134 self.read(source, **dict(kwargs.pop('reader', None) or {}))) 

135 key = other_on or _key_of(other, on) 

136 data = item.data 

137 pattern = re.compile(rf'{re.escape(on)}(\d+)') 

138 seats = sorted( 

139 int(numbered_column.group(1)) for column in data.columns 

140 if (numbered_column := pattern.fullmatch(str(column)))) 

141 if not seats: 

142 message = ( 

143 f'{self.name!r} needs the columns "{on}1", "{on}2", and so on, ' 

144 f'with the key of the judge in each seat: apply "code_panels" ' 

145 f'or "add_biography" first') 

146 raise KeyError(message) 

147 chosen = ( 

148 [c for c in other.columns if c != key] if columns is None 

149 else utilities.listify(columns)) 

150 cases.require_columns( 

151 other, [key, *chosen], 'the table of ' + repr(self.name)) 

152 added: dict[str, Any] = {} 

153 matched = 0 

154 for seat in seats: 

155 positions = np.asarray(self.match( 

156 data, other, on = f'{on}{seat}', other_on = key, 

157 duplicates = duplicates), dtype = 'int64') 

158 matched += int((positions >= 0).sum()) 

159 found = other[chosen].reset_index(drop = True).reindex(positions) 

160 for column in chosen: 

161 added[f'{prefix or ""}{column}{seat}'] = found[ 

162 column].to_numpy() 

163 table = pd.DataFrame(added, index = data.index) 

164 clashes = [c for c in table.columns if c in data.columns] 

165 if clashes: 165 ↛ 166line 165 didn't jump to line 166 because the condition on line 165 was never true

166 message = ( 

167 f'{self.name!r} would add columns named {clashes}, which the ' 

168 f'data already has: set "prefix" to tell them apart') 

169 raise ValueError(message) 

170 item.replace(pd.concat([data, table], axis = 1)) 

171 item.record( 

172 self.name, 

173 source = ( 

174 type(source).__name__ if isinstance(source, pd.DataFrame) 

175 else str(source)), 

176 rows = len(data), 

177 matched = matched, 

178 created = list(table.columns)) 

179 return item 

180 

181 

182@dataclasses.dataclass 

183class AddCourtScores(amos.mergers.MergeKeys): 

184 """Adds scores of each case's court from a table of them. 

185 

186 Each row of the table of scores is a court, with its number 

187 ("court_num", unless "other_on" names another column) and columns of 

188 scores, and each case gets the scores of its court as 

189 "court_score_{column}". A court that is not in the table gets missing 

190 values. It takes the parameters of the `merge_keys` technique of `amos`: 

191 "source", "columns", "prefix" ("court_score_" unless another is set), 

192 "on" (the column of the cases with each court, "court_num" unless 

193 another is set), "other_on", and "duplicates". 

194 

195 """ 

196 

197 """ Public Methods """ 

198 

199 def apply( 

200 self, 

201 item: amos.Dataset, 

202 *, 

203 source: Any = None, 

204 columns: Sequence[str] | str | None = None, 

205 prefix: str | None = 'court_score_', 

206 on: str = 'court_num', 

207 **kwargs: Any) -> amos.Dataset: 

208 """Adds the scores of each case's court. 

209 

210 Args: 

211 item: the dataset of cases (or of votes). 

212 source: the table of scores, or the path of a data file of one. 

213 columns: the scores to add. Defaults to `None`, for every column 

214 of the table but its key. 

215 prefix: text to put before the names of the added columns. 

216 Defaults to "court_score_". 

217 on: the column of `item` with each case's court. Defaults to 

218 "court_num". 

219 **kwargs: other parameters of `merge_keys`, such as "other_on", 

220 "indicator", and "duplicates". 

221 

222 Raises: 

223 KeyError: if `item` or the table lacks its key, or the table 

224 lacks one of `columns`. 

225 ValueError: if there is no `source`, or an added column would 

226 have the name of a column of the data. 

227 

228 Returns: 

229 The dataset with the added columns. 

230 

231 """ 

232 other = _unlabeled(self.read(source)) if source is not None else None 

233 return super().apply( 

234 item, 

235 source = other if other is not None else source, 

236 columns = None if columns is None else utilities.listify(columns), 

237 prefix = prefix, 

238 on = on, 

239 **kwargs) 

240 

241 

242""" Private Functions """ 

243 

244 

245def _key_of(other: pd.DataFrame | None, on: str) -> str: 

246 """Returns the column of a table of judges' scores with each judge's key. 

247 

248 Args: 

249 other: the table of scores, or `None`. 

250 on: the key of the data. 

251 

252 Returns: 

253 `on` if the table has it (or there is no table), and otherwise 

254 "judge_nid" or "nid", whichever the table has, or `on`. 

255 

256 """ 

257 if other is None or on in other.columns: 

258 return on 

259 for name in ('judge_nid', 'nid'): 259 ↛ 262line 259 didn't jump to line 262 because the loop on line 259 didn't complete

260 if name in other.columns: 

261 return name 

262 return on 

263 

264 

265def _unlabeled(other: pd.DataFrame) -> pd.DataFrame: 

266 """Returns a table with the names of its labels as a column. 

267 

268 A table of `Judges` or `Courts` is labeled by its key ("judge_nid" or 

269 "court_num"), which the merger matches as a column. 

270 

271 Args: 

272 other: the table of scores. 

273 

274 Returns: 

275 `other`, with its labels as a column if they have a name that is not 

276 a column already. 

277 

278 """ 

279 name = other.index.name 

280 if name is not None and name not in other.columns: 

281 return other.reset_index() 

282 return other