Coverage for src/courtpy/references/jcs.py: 100%

47 statements  

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

1"""Adds Judicial Common Space scores of judges, justices, and courts. 

2 

3The Judicial Common Space (Epstein, Martin, Segal, and Westerland, "The 

4Judicial Common Space," 23 J.L. Econ. & Org. 303 (2007)) places judges, 

5justices of the Supreme Court, members of Congress, and presidents on one 

6scale of ideology, on which higher scores are more conservative. The 

7judicial-common-space package 

8(https://github.com/WithPrecedent/judicial_common_space) computes the scores 

9and downloads the files that they are computed from and checked against, 

10which courtpy uses in three ways: 

11 

12* Each appointment of a judge or justice has a score, which fjc-biographies 

13 adds to a roster with judicial-common-space 

14 (`courtpy.judges.Roster.from_fjc(jcs = True)`) as "jcs", an attribute of 

15 each judge like "party": `code_panels` adds "panel_jcs" (the mean score of 

16 each case's panel), and `add_biography` adds "judge_jcs". Unlike the 

17 published scores, which are of the judges of the courts of appeals and the 

18 justices, the computed scores are of district judges too. 

19* Each justice has a score in each term, which `courtpy.politics.justices` 

20 returns with the justice's Martin-Quinn score, so the scores can be added 

21 to the Supreme Court Database's votes (see `courtpy.scdb.votes`). 

22* Each year has the scores of the president and of the medians of the House, 

23 the Senate, the Supreme Court, and each court of appeals, which its authors 

24 publish at https://epstein.wustl.edu/jcs. `medians` reads them, so they can 

25 be added to cases by "year" with the `merge_keys` technique of `amos` (or 

26 be a part of `courtpy.politics.build_table`). 

27 

28The published files are downloaded by judicial-common-space (see `download`) 

29into "jcs" in `courtpy.utilities.data_folder()`, where it looks for them too: 

30 

31| Kind | File | Rows | 

32| --- | --- | --- | 

33| `judges` | "judges.csv" | Each judge of a court of appeals, with the judge's name, circuit, and score. | 

34| `justices` | "justices.csv" | Each justice in each term of the Supreme Court. | 

35| `medians` | "medians.csv" | Each year, with the scores of the president and of the medians of the House, the Senate, the Supreme Court, and each court of appeals. | 

36 

37```python 

38import courtpy 

39 

40roster = courtpy.judges.Roster.from_fjc(jcs = True) 

41roster.save() 

42table = courtpy.politics.build_table(common_space = True) 

43``` 

44 

45`download_jcs` (a reference loader, see `courtpy.loaders.ReferenceLoader`) 

46downloads the files and loads one of them, so a study can start from the 

47scores themselves. 

48 

49Contents: 

50 DownloadJcs: downloads the published files of Judicial Common Space 

51 scores and loads one of them. 

52 download: downloads the published files of Judicial Common Space scores. 

53 medians: returns the scores of the president and of the medians of 

54 Congress and the courts in each year. 

55 

56""" 

57 

58from __future__ import annotations 

59 

60import dataclasses 

61import pathlib 

62from collections.abc import Sequence 

63from typing import Any 

64 

65import judicial_common_space 

66import pandas as pd 

67 

68from ..core import cases, utilities 

69from ..wrangler import loaders 

70 

71# The published files, by what judicial-common-space calls each. 

72_KINDS: dict[str, str] = { 

73 'judges': 'jcs_judges', 

74 'justices': 'jcs_justices', 

75 'medians': 'jcs_medians'} 

76_MEDIANS: dict[str, str] = { 

77 'president': 'jcs_president', 

78 'house_median': 'jcs_house_median', 

79 'senate_median': 'jcs_senate_median', 

80 'sc_median': 'jcs_supreme_court_median', 

81 **{f'circuit_median{number}': f'jcs_circuit{number}_median' 

82 for number in range(1, 14)}, 

83 **{f'circuit_sd{number}': f'jcs_circuit{number}_sd' 

84 for number in range(1, 14)}} 

85 

86 

87@dataclasses.dataclass 

88class DownloadJcs(loaders.ReferenceLoader): 

89 """Downloads the published files of Judicial Common Space scores. 

90 

91 The archive of the scores is downloaded unless its files are there 

92 already, or "refresh" is true (see `download`), and the file named by 

93 "kind" is loaded: "medians" (the default, a row for each year, as 

94 `medians` returns it), "judges" (a row for each judge of a court of 

95 appeals), or "justices" (a row for each justice in each term). Its 

96 "source" is the data folder whose "jcs" folder keeps the files, which is 

97 `courtpy.utilities.data_folder()` unless another is set. 

98 

99 """ 

100 

101 """ Public Methods """ 

102 

103 def load( 

104 self, 

105 source: Any, 

106 *, 

107 kind: str = 'medians', 

108 refresh: bool | str = False, 

109 session: Any = None, 

110 **kwargs: Any) -> pd.DataFrame: 

111 """Downloads the files and returns the table of one of them. 

112 

113 Args: 

114 source: the data folder, or "current" for 

115 `utilities.data_folder()`. 

116 kind: the file to load: "medians", "judges", or "justices". 

117 Defaults to "medians". 

118 refresh: whether to download the archive even if the files are 

119 there. Defaults to `False`. 

120 session: an object with a `get` method like a 

121 `requests.Session`. Defaults to `None`, in which case one is 

122 made. 

123 **kwargs: not used. 

124 

125 Raises: 

126 ValueError: if `kind` is not one of the files. 

127 

128 Returns: 

129 The table. 

130 

131 """ 

132 kind = str(kind).strip() 

133 path = download( 

134 self._locate(source), kinds = kind, 

135 overwrite = utilities.to_bool(refresh), session = session)[kind] 

136 if kind == 'medians': 

137 return medians(path) 

138 return _read(path, kind) 

139 

140 

141def download( 

142 folder: pathlib.Path | str | None = None, 

143 *, 

144 kinds: Sequence[str] | str | None = None, 

145 overwrite: bool = False, 

146 session: Any = None) -> dict[str, pathlib.Path]: 

147 """Downloads the published files of Judicial Common Space scores. 

148 

149 The scores are posted as one archive (about 100 kilobytes), which 

150 `judicial_common_space.sources.download` finds by its link on 

151 https://epstein.wustl.edu/jcs and unpacks. Its CSV files are saved as 

152 "judges.csv", "justices.csv", and "medians.csv" (see the module's 

153 documentation), and the archive is kept beside them. 

154 

155 Args: 

156 folder: the data folder, whose "jcs" folder they are saved in. 

157 Defaults to `None`, in which case `utilities.data_folder()` is 

158 used. 

159 kinds: the files to return: any of "judges", "justices", and 

160 "medians". Defaults to `None`, for all of them. The archive is 

161 downloaded if any of them is missing. 

162 overwrite: whether to download the archive even if the files are 

163 there. The scores are updated every few years. Defaults to 

164 `False`. 

165 session: an object with a `get` method like a `requests.Session`. 

166 Defaults to `None`, in which case a `requests.Session` that 

167 identifies courtpy is made. 

168 

169 Raises: 

170 requests.HTTPError: if the page or the archive cannot be downloaded. 

171 ValueError: if one of `kinds` is not a file that courtpy knows, the 

172 page has no link to an archive, or the archive lacks a file. 

173 

174 Returns: 

175 The path of each file, by its kind. 

176 

177 """ 

178 wanted = list(_KINDS) if kinds is None else utilities.listify(kinds) 

179 unknown = [kind for kind in wanted if kind not in _KINDS] 

180 if unknown: 

181 message = f'kinds must be among {list(_KINDS)}, not {unknown}' 

182 raise ValueError(message) 

183 paths = judicial_common_space.sources.download( 

184 [_KINDS[kind] for kind in wanted], 

185 folder or utilities.data_folder(), 

186 overwrite = overwrite, 

187 session = utilities.open_session(session)) 

188 return {kind: paths[_KINDS[kind]] for kind in wanted} 

189 

190 

191def medians( 

192 source: pd.DataFrame | pathlib.Path | str | None = None) -> pd.DataFrame: 

193 """Returns the scores of the president and of medians in each year. 

194 

195 Args: 

196 source: the file of medians (see `download`), as a path or a table, 

197 with a "year" column and columns of scores. Defaults to `None`, 

198 in which case the current file is used, which is downloaded 

199 unless it was before. 

200 

201 Raises: 

202 KeyError: if `source` lacks a "year" column. 

203 

204 Returns: 

205 A table with "year" and, for each of these that the file has, 

206 "jcs_president" (the president's score), 

207 "jcs_house_median", "jcs_senate_median", 

208 "jcs_supreme_court_median", and "jcs_circuit{n}_median" and 

209 "jcs_circuit{n}_sd" (the median and standard deviation of the 

210 scores of each court of appeals, numbered as the federal rules 

211 number them, with 12 for the District of Columbia and 13 for the 

212 Federal Circuit). A year with more than one row in the file (as 

213 when a new president or Congress took office) has their means. 

214 

215 """ 

216 scores = _read(source, 'medians') 

217 cases.require_columns( 

218 scores, ['year'], 'the file of Judicial Common Space medians') 

219 columns = [column for column in _MEDIANS if column in scores.columns] 

220 numbers = scores[columns].apply(pd.to_numeric, errors = 'coerce') 

221 numbers['year'] = pd.to_numeric(scores['year'], errors = 'coerce') 

222 numbers = numbers.dropna(subset = ['year']).astype({'year': int}) 

223 means = numbers.groupby('year')[columns].mean().reset_index() 

224 renamed: pd.DataFrame = means.rename(columns = _MEDIANS) 

225 return renamed 

226 

227 

228""" Private Functions """ 

229 

230 

231def _read( 

232 source: pd.DataFrame | pathlib.Path | str | None, 

233 kind: str) -> pd.DataFrame: 

234 """Returns a table from a table or a CSV file, or one of the files. 

235 

236 Args: 

237 source: a table (which is copied), the path of a CSV file, or `None`. 

238 kind: the file to use if `source` is `None`: "judges", "justices", or 

239 "medians". It is downloaded unless it was before (see 

240 `download`). 

241 

242 Returns: 

243 The table, without the column of row numbers that the files have. 

244 

245 """ 

246 if isinstance(source, pd.DataFrame): 

247 table = source.copy() 

248 else: 

249 if source is None: 

250 source = download(kinds = kind)[kind] 

251 table = utilities.read_csv(source) 

252 numbered = [ 

253 column for column in table.columns 

254 if str(column) == '' or str(column).startswith('Unnamed:')] 

255 return table.drop(columns = numbered)