Coverage for src/chrisjen/nodes.py: 100%

84 statements  

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

1"""Nodes of a workflow: the subclasses of `base.Vertex`. 

2 

3Contents: 

4 Technique: a single action that wraps a tool. 

5 NullVertex: a `Vertex` that does nothing. 

6 Step: a stage of a workflow that wraps a technique or a worker. 

7 Worker: base class for the designs in the `workers` module, which are 

8 vertexes that are graphs of other vertexes. 

9 

10""" 

11 

12from __future__ import annotations 

13 

14import abc 

15import copy 

16import dataclasses 

17from collections.abc import Callable, Hashable, MutableMapping, Sequence 

18from typing import Any 

19 

20import holden 

21 

22from . import base, utilities 

23 

24 

25@dataclasses.dataclass 

26class Technique(base.Vertex): 

27 """A single action in a workflow, which usually wraps another tool. 

28 

29 A `Technique` is an ordinary object. Its `contents` is the tool that it 

30 wraps: any callable, or the import path of one, such as 

31 `statistics.fmean`. A path is only imported when the technique is first 

32 used, so techniques can wrap optional packages. A subclass can set a 

33 default `contents` or override `apply` instead. Subclasses are stored 

34 in the library under their snake case names, which is how settings refer 

35 to them. 

36 

37 Args: 

38 name: name used to refer to the technique in a workflow. 

39 contents: the tool to wrap: a callable or the import path of one. 

40 Defaults to `None`, which is only useful for subclasses that 

41 override `apply`. 

42 parameters: keyword arguments passed to the tool. Defaults to an empty 

43 `dict`. 

44 

45 """ 

46 

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

48 contents: str | Callable[..., Any] | None = dataclasses.field( 

49 default = None) 

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

51 

52 """ Public Methods """ 

53 

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

55 """Calls the wrapped tool with `item`. 

56 

57 Override this method to call a tool differently (for example, to build 

58 an object from the parameters and then call one of its methods). 

59 

60 Args: 

61 item: data or object to change. 

62 **kwargs: keyword arguments for the tool. Any that the tool does 

63 not accept are dropped. 

64 

65 Raises: 

66 ImportError: if `contents` is an import path that cannot be 

67 imported. 

68 NotImplementedError: if there is no tool in `contents` and a 

69 subclass does not override this method. 

70 TypeError: if the tool is not callable. 

71 

72 Returns: 

73 The changed `item`. 

74 

75 """ 

76 tool = self.contents 

77 if isinstance(tool, str): 

78 tool = utilities.import_object(tool) 

79 if tool is None: 

80 message = ( 

81 f'technique {self.name!r} has no tool: pass a callable or ' 

82 f'import path as contents or override apply in a subclass' 

83 ) 

84 raise NotImplementedError(message) 

85 if not callable(tool): 

86 message = ( 

87 f'technique {self.name!r} wraps {tool!r}, which is not ' 

88 f'callable: override apply to use it' 

89 ) 

90 raise TypeError(message) 

91 return tool(item, **utilities.accepted_arguments(tool, kwargs)) 

92 

93 """ Dunder Methods """ 

94 

95 def __deepcopy__(self, memo: dict[int, Any]) -> Technique: 

96 """Copies the technique, sharing a tool that cannot be copied. 

97 

98 Everything is copied, including a tool in `contents` (so that a tool 

99 with its own state, such as a model, is not shared). If the tool cannot 

100 be copied (because it holds a lock or a connection, for example), the 

101 copy uses the same tool. 

102 

103 Args: 

104 memo: `dict` of objects already copied. 

105 

106 Returns: 

107 A copy of the technique. 

108 

109 """ 

110 clone = copy.copy(self) 

111 for field in dataclasses.fields(self): 

112 value = getattr(self, field.name) 

113 try: 

114 value = copy.deepcopy(value, memo) 

115 except Exception: 

116 if field.name != 'contents': 

117 raise 

118 setattr(clone, field.name, value) 

119 return clone 

120 

121 

122@dataclasses.dataclass 

123class NullVertex(base.Vertex): 

124 """A Vertex that does nothing. 

125 

126 This node is stored in the library as "none" (and as "null_vertex"). 

127 

128 This is a useful node when you want to compare using one technique with 

129 making no changes. 

130 

131 Args: 

132 name: name used to refer to the node in a workflow. Defaults to 

133 "none". 

134 

135 """ 

136 

137 name: str = dataclasses.field(default = 'none') 

138 

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

140 """Returns `item` unchanged. 

141 

142 Args: 

143 item: data or object. 

144 **kwargs: ignored. 

145 

146 Returns: 

147 `item`. 

148 

149 """ 

150 return item 

151 

152 

153# Lets settings refer to a `NullVertex` as "none". 

154base.library.add(NullVertex, name = 'none') 

155 

156 

157@dataclasses.dataclass 

158class Step(base.Vertex, abc.ABC): 

159 """A stage of a workflow that wraps a technique or a worker. 

160 

161 Unlike a simple Technique, a Step includes preparatory and finishing code 

162 (in the `begin` and `end` methods). Subclasses of Step can store methods 

163 and attributes shared by all of the techniques that a step might use, 

164 which is useful when a worker compares several techniques for the same 

165 step. When a workflow is built from settings, each technique of a step is 

166 wrapped in its own step node, named "{technique}_{step}", and a subclass 

167 named after the step (such as `Scale` for "scale") is used if there is 

168 one. 

169 

170 A Step returns the attributes of `contents` that it does not have itself. 

171 

172 Args: 

173 name: name used to refer to the step in a workflow. 

174 contents: the technique or worker to wrap. Defaults to `None`, which 

175 is only useful for subclasses that override `apply`. 

176 parameters: keyword arguments for the step to use. Defaults to an empty 

177 `dict`. 

178 

179 """ 

180 

181 name: str | None = None 

182 contents: Technique | Worker | None = None 

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

184 

185 """ Public Methods """ 

186 

187 def begin(self, item: Any) -> Any: 

188 """Runs any preparation needed for the step. 

189 

190 Args: 

191 item: data or object to change. 

192 

193 Returns: 

194 The item in a prepared state. 

195 

196 """ 

197 return item 

198 

199 def end(self, item: Any) -> Any: 

200 """Finalizes the step's execution. 

201 

202 Args: 

203 item: data or object to change. 

204 

205 Returns: 

206 The final result of the step. 

207 

208 """ 

209 return item 

210 

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

212 """Applies the technique or worker in `contents` to `item`. 

213 

214 Parameter priority, from lowest to highest, is the `parameters` of 

215 `contents`, the step's `parameters`, and `kwargs`. 

216 

217 Args: 

218 item: data or object to change. 

219 **kwargs: keyword arguments for the `apply` method of `contents`. 

220 

221 Raises: 

222 ValueError: if there is nothing in `contents`. 

223 

224 Returns: 

225 The result of `begin`, the `apply` method of `contents`, and 

226 `end`. 

227 

228 """ 

229 if self.contents is None: 

230 message = ( 

231 f'step {self.name!r} has no technique or workflow in contents' 

232 ) 

233 raise ValueError(message) 

234 item = self.begin(item) 

235 item = self.contents.apply(item, **kwargs) 

236 return self.end(item) 

237 

238 """ Dunder Methods """ 

239 

240 def __getattr__(self, attribute: str) -> Any: 

241 """Returns an attribute of `contents` that the step does not have. 

242 

243 Args: 

244 attribute: name of the attribute. 

245 

246 Raises: 

247 AttributeError: if neither the step nor `contents` has `attribute`. 

248 

249 Returns: 

250 The attribute of `contents`. 

251 

252 """ 

253 # Dunder and private attributes are not passed on, so that copying 

254 # and comparing a step use the step's own methods. 'contents' is also 

255 # not passed on, which avoids endless recursion before it is set. 

256 if attribute.startswith('_') or attribute == 'contents': 

257 raise AttributeError(attribute) 

258 return getattr(self.contents, attribute) 

259 

260 

261@dataclasses.dataclass 

262class Worker(holden.System, base.Vertex, abc.ABC): 

263 """Base class for nodes that are workflows of other nodes. 

264 

265 A worker is a directed graph (a `holden.System`) whose nodes are vertexes. 

266 Each subclass is a design with its own rules for how the nodes are 

267 connected (`populate`) and applied to an item (`apply`). Workers are 

268 hashed and compared by name, like other vertexes, so a worker can be a 

269 node in another worker. 

270 

271 Args: 

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

273 contents: the graph: a `dict` mapping each node to the `set` of nodes 

274 that come after it. Defaults to an empty `dict`. 

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

276 empty `dict`. 

277 

278 """ 

279 

280 name: str | None = None 

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

282 default_factory = dict) 

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

284 

285 # Workers are hashed and compared by name, like other vertexes, so that 

286 # they can be nodes in other workers. 

287 __eq__ = base.Vertex.__eq__ 

288 __hash__ = base.Vertex.__hash__ 

289 

290 """ Public Methods """ 

291 

292 def populate( 

293 self, 

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

295 """Adds `nodes` to the graph, each one after the one before it. 

296 

297 Args: 

298 nodes: vertexes to add, in order. An item may also be a list of 

299 vertexes (such as the techniques of a step), which are added 

300 one after another as well. 

301 

302 """ 

303 previous = None 

304 for item in nodes: 

305 layer = item if isinstance(item, list) else [item] 

306 for node in layer: 

307 self.add(node) 

308 if previous is not None: 

309 self.connect((previous, node)) 

310 previous = node 

311 

312 @abc.abstractmethod 

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

314 """Applies the nodes to `item`, so that the worker can be a node. 

315 

316 Args: 

317 item: data or object to change. 

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

319 

320 Returns: 

321 The result of the workflow. 

322 

323 """