Coverage for src/chrisjen/workers.py: 96%

106 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-14 09:29 +0000

1"""Worker designs. 

2 

3A worker is a directed graph (a `holden.System`) of nodes. Each design is a 

4subclass with its own rules for how the nodes are connected (`populate`) and 

5applied to an item (`apply`). Designs are found by their snake case names, 

6which are used for the "design" setting. 

7 

8Contents: 

9 Flow: nodes are applied one after another. 

10 Benchmark: the sequence repeats until a criterion is met. 

11 Comparator: mixin for workers that compare every combination of 

12 alternatives. 

13 Contest: tries every combination of alternatives and keeps the best. 

14 Survey: tries every combination of alternatives and averages the results. 

15 

16""" 

17 

18from __future__ import annotations 

19 

20import abc 

21import copy 

22import dataclasses 

23from collections.abc import Hashable, Iterator, MutableMapping, Sequence 

24from typing import TYPE_CHECKING, Any, cast 

25 

26from . import base, nodes, utilities 

27 

28if TYPE_CHECKING: 

29 # Type checkers treat `Comparator` as a worker, since it is only mixed 

30 # into workers and uses their methods (such as `add` and `walk`). 

31 _ComparatorBase = nodes.Worker 

32else: 

33 _ComparatorBase = abc.ABC 

34 

35 

36@dataclasses.dataclass 

37class Flow(nodes.Worker): 

38 """Applies nodes one after another. 

39 

40 This is the default design: a rigid, pre-planned sequence. If a step has 

41 more than one technique, they are applied one after another as well. 

42 

43 Args: 

44 name: name used to refer to the worker in a workflow. 

45 contents: the graph of nodes. Defaults to an empty `dict`. 

46 parameters: keyword arguments for the worker to use. Defaults to an 

47 empty `dict`. 

48 

49 """ 

50 

51 """ Public Methods """ 

52 

53 def apply(self, item: Any, **kwargs: Any) -> Any: 

54 """Applies each node, in order, to `item`. 

55 

56 Args: 

57 item: data or object to change. 

58 **kwargs: keyword arguments passed to the nodes. 

59 

60 Returns: 

61 The result of the last node. 

62 

63 """ 

64 for path in self.walk(): 

65 item = utilities._apply_path(path, item, **kwargs) 

66 return item 

67 

68 

69@dataclasses.dataclass 

70class Benchmark(Flow): 

71 """Repeats the sequence of nodes until `criteria` is met. 

72 

73 After each pass, `criteria` tests the result. The worker stops when the 

74 test passes or after `max_iterations` passes. In settings, `criteria` is 

75 named by the "criterion" setting, and "max_iterations" can be set as well. 

76 

77 Args: 

78 name: name used to refer to the worker in a workflow. 

79 contents: the graph of nodes. Defaults to an empty `dict`. 

80 parameters: keyword arguments for the worker to use. Defaults to an 

81 empty `dict`. 

82 criteria: the criteria that decide when to stop. Defaults to `None`. 

83 max_iterations: most passes to make. If `None`, passes are made until 

84 `criteria` is met. Defaults to `None`. 

85 

86 Attributes: 

87 iterations: number of passes made by the most recent call. 

88 

89 """ 

90 

91 criteria: base.Criteria | None = None 

92 max_iterations: int | None = None 

93 iterations: int = 0 

94 

95 """ Public Methods """ 

96 

97 def apply(self, item: Any, **kwargs: Any) -> Any: 

98 """Repeats the sequence until `criteria` is met. 

99 

100 Args: 

101 item: data or object to change. 

102 **kwargs: keyword arguments passed to the nodes. 

103 

104 Raises: 

105 ValueError: if there is no `criteria`. 

106 

107 Returns: 

108 The result of the last pass. 

109 

110 """ 

111 if self.criteria is None: 

112 message = f'benchmark {self.name!r} needs criteria' 

113 raise ValueError(message) 

114 self.iterations = 0 

115 while ( 

116 self.max_iterations is None 

117 or self.iterations < self.max_iterations): 

118 item = super().apply(item, **kwargs) 

119 self.iterations += 1 

120 if self.criteria.test(item): 

121 break 

122 return item 

123 

124 

125# `eq` is `False` so that the mixin does not set `__hash__` to `None`, which 

126# would stop workers that use it from being hashed by name. 

127@dataclasses.dataclass(eq = False) 

128class Comparator(_ComparatorBase): 

129 """Mixin for workers that compare every combination of alternatives. 

130 

131 The techniques of each step are alternatives to each other, and the paths 

132 through the graph are every combination of one technique from each step 

133 (see `populate`). A worker without steps has one path for each of its 

134 techniques. List the mixin before `Worker` in the bases of a design. 

135 

136 If `conserve_memory` is true, a design keeps only the results that it 

137 still needs (such as the best one so far) while it tries the paths, so 

138 that a worker with many paths, or large results, does not have every 

139 result in memory at once. It can be set for every worker in the "general" 

140 section of the settings (see `options._GENERAL_SETTINGS`). 

141 

142 Args: 

143 contents: the graph of nodes. Defaults to an empty `dict`. 

144 name: name used to refer to the worker in a workflow. Defaults to 

145 `None`. 

146 parameters: keyword arguments for the worker to use. Defaults to an 

147 empty `dict`. 

148 criteria: the criteria used to score the result of each path. 

149 Defaults to `None`. 

150 conserve_memory: whether to keep only the results that the design 

151 still needs, rather than the result of every path, in `results`. 

152 Defaults to `False`. 

153 

154 Attributes: 

155 results: the result of each path in the most recent call, by the 

156 names of the nodes in the path (joined by " > "). If 

157 `conserve_memory` is true, only the results that the design kept. 

158 

159 """ 

160 contents: MutableMapping[Hashable, set[Hashable]] = dataclasses.field( 

161 default_factory = dict) 

162 name: str | None = dataclasses.field(default = None) 

163 parameters: base.GenericDict = dataclasses.field(default_factory = dict) 

164 criteria: base.Criteria | None = None 

165 conserve_memory: bool = False 

166 results: dict[str, Any] = dataclasses.field(default_factory = dict) 

167 

168 """ Public Methods """ 

169 

170 def compare(self, items: Sequence[Any]) -> list[Any]: 

171 """Returns the score of each item in `items`. 

172 

173 Args: 

174 items: results to score. 

175 

176 Raises: 

177 ValueError: if there is no `criteria`. 

178 

179 Returns: 

180 The scores, in the same order as `items`. 

181 

182 """ 

183 if self.criteria is None: 

184 message = f'{self.name!r} needs criteria to compare results' 

185 raise ValueError(message) 

186 return [self.criteria.score(item) for item in items] 

187 

188 def populate( 

189 self, 

190 nodes: Sequence[base.Vertex | Sequence[base.Vertex]]) -> None: 

191 """Adds `nodes` so that every combination of alternatives is a path. 

192 

193 Each item in `nodes` is a list of alternatives (such as the techniques 

194 of a step) or a single vertex. Every vertex in an item is connected to 

195 every vertex in the next item, so the paths through the graph are every 

196 combination of one vertex from each item. 

197 

198 Args: 

199 nodes: vertexes and lists of alternative vertexes, in order. 

200 

201 """ 

202 previous: list[base.Vertex] = [] 

203 for item in nodes: 

204 layer = cast( 

205 'list[base.Vertex]', 

206 item if isinstance(item, list) else [item]) 

207 for node in layer: 

208 self.add(node) 

209 for before in previous: 

210 self.connect((before, node)) 

211 previous = layer 

212 

213 def each_path( 

214 self, 

215 item: Any, 

216 **kwargs: Any) -> Iterator[tuple[str, Any]]: 

217 """Applies each path to its own copy of `item`, one at a time. 

218 

219 Each path also uses its own copies of its nodes, so that nothing they 

220 store (such as a fitted model) carries over from one path to another. 

221 Nothing is kept: a path is applied only when the next result is asked 

222 for, so a design can drop each result once it is done with it. 

223 

224 Args: 

225 item: data or object to change. It is not changed itself. 

226 **kwargs: keyword arguments passed to the nodes. 

227 

228 Raises: 

229 ValueError: if there are no paths. 

230 

231 Yields: 

232 tuple[str, Any]: the label of each path (the names of its nodes, 

233 joined by " > ") and its result. 

234 

235 """ 

236 paths = self.walk() 

237 if not paths: 

238 message = f'{self.name!r} has no paths to compare' 

239 raise ValueError(message) 

240 for path in paths: 

241 label = utilities.label_path(path) 

242 copies = [copy.deepcopy(node) for node in path] 

243 yield label, utilities._apply_path( 

244 copies, copy.deepcopy(item), **kwargs) 

245 

246 def try_paths(self, item: Any, **kwargs: Any) -> dict[str, Any]: 

247 """Applies every path to its own copy of `item`. 

248 

249 Unlike `each_path`, this keeps the result of every path, whether or 

250 not `conserve_memory` is true. 

251 

252 Args: 

253 item: data or object to change. It is not changed itself. 

254 **kwargs: keyword arguments passed to the nodes. 

255 

256 Raises: 

257 ValueError: if there are no paths. 

258 

259 Returns: 

260 The result of each path, which is also stored in `results`. 

261 

262 """ 

263 self.results = {} 

264 for label, result in self.each_path(item, **kwargs): 

265 self.results[label] = result 

266 return self.results 

267 

268 """ Private Methods """ 

269 

270 def _observe(self, label: str, result: Any) -> None: 

271 """Notes what a design needs from the result of a path. 

272 

273 `Contest` and `Survey` call this with each result as soon as its path 

274 is applied (and, in a contest, scored), before the result may be 

275 dropped if `conserve_memory` is true. It does nothing by default: 

276 subclasses can override it to keep a summary of each result. 

277 

278 Args: 

279 label: the label of the path. 

280 result: the result of the path. 

281 

282 """ 

283 

284 

285@dataclasses.dataclass 

286class Contest(Comparator, nodes.Worker): 

287 """Tries every combination of alternatives and keeps the best result. 

288 

289 Each path (every combination of one technique from each step) is applied 

290 to its own copy of the item, and the result with the highest score from 

291 `criteria` is kept. Each result is scored as soon as its path is applied, 

292 so if `conserve_memory` is true, only the best result so far is kept: 

293 at most two results are in memory at once, however many paths there are. 

294 

295 Args: 

296 name: name used to refer to the worker in a workflow. 

297 contents: the graph of nodes. Defaults to an empty `dict`. 

298 parameters: keyword arguments for the worker to use. Defaults to an 

299 empty `dict`. 

300 criteria: the criteria used to score each result. Higher scores are 

301 better. Defaults to `None`. 

302 conserve_memory: whether to keep only the best result in `results`. 

303 Defaults to `False`. 

304 

305 Attributes: 

306 scores: the score of each path in the most recent call. 

307 winner: label of the path with the best result in the most recent 

308 call. 

309 

310 """ 

311 

312 scores: dict[str, Any] = dataclasses.field(default_factory = dict) 

313 winner: str | None = None 

314 

315 """ Public Methods """ 

316 

317 def apply(self, item: Any, **kwargs: Any) -> Any: 

318 """Returns the result of the path with the best score. 

319 

320 Args: 

321 item: data or object to change. 

322 **kwargs: keyword arguments passed to the nodes. 

323 

324 Raises: 

325 ValueError: if there are no paths or no `criteria`. 

326 

327 Returns: 

328 The best result. Ties go to the first path. 

329 

330 """ 

331 self.results = {} 

332 self.scores = {} 

333 winner, best = None, None 

334 for label, result in self.each_path(item, **kwargs): 

335 self.scores[label] = self.compare([result])[0] 

336 self._observe(label, result) 

337 if winner is None or self.scores[label] > self.scores[winner]: 

338 if self.conserve_memory: 

339 self.results.clear() 

340 winner, best = label, result 

341 self.results[label] = result 

342 elif not self.conserve_memory: 

343 self.results[label] = result 

344 # Lets a result that was not kept go before the next path makes 

345 # its own. 

346 del result 

347 self.winner = winner 

348 return best 

349 

350 

351@dataclasses.dataclass 

352class Survey(Comparator, nodes.Worker): 

353 """Tries every combination of alternatives and averages the results. 

354 

355 Each path (every combination of one technique from each step) is applied 

356 to its own copy of the item. The results must support addition and 

357 division by an `int`, as numbers, `numpy` arrays, and `pandas` objects do. 

358 Each result is added to a running total as soon as its path is applied, 

359 so if `conserve_memory` is true, no result is kept. 

360 

361 Args: 

362 name: name used to refer to the worker in a workflow. 

363 contents: the graph of nodes. Defaults to an empty `dict`. 

364 parameters: keyword arguments for the worker to use. Defaults to an 

365 empty `dict`. 

366 conserve_memory: whether to leave `results` empty. Defaults to 

367 `False`. 

368 

369 Attributes: 

370 average: the average result of the most recent call. 

371 

372 """ 

373 

374 average: Any = None 

375 

376 """ Public Methods """ 

377 

378 def apply(self, item: Any, **kwargs: Any) -> Any: 

379 """Returns the mean of the results of every path. 

380 

381 Args: 

382 item: data or object to change. 

383 **kwargs: keyword arguments passed to the nodes. 

384 

385 Raises: 

386 ValueError: if there are no paths. 

387 

388 Returns: 

389 The average result. 

390 

391 """ 

392 self.results = {} 

393 

394 def kept(label: str, result: Any) -> Any: 

395 self._observe(label, result) 

396 if not self.conserve_memory: 

397 self.results[label] = result 

398 return result 

399 

400 self.average = utilities._average( 

401 kept(label, result) 

402 for label, result in self.each_path(item, **kwargs)) 

403 return self.average