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
« 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`.
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.
10"""
12from __future__ import annotations
14import abc
15import copy
16import dataclasses
17from collections.abc import Callable, Hashable, MutableMapping, Sequence
18from typing import Any
20import holden
22from . import base, utilities
25@dataclasses.dataclass
26class Technique(base.Vertex):
27 """A single action in a workflow, which usually wraps another tool.
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.
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`.
45 """
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)
52 """ Public Methods """
54 def apply(self, item: Any, **kwargs: Any) -> Any:
55 """Calls the wrapped tool with `item`.
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).
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.
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.
72 Returns:
73 The changed `item`.
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))
93 """ Dunder Methods """
95 def __deepcopy__(self, memo: dict[int, Any]) -> Technique:
96 """Copies the technique, sharing a tool that cannot be copied.
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.
103 Args:
104 memo: `dict` of objects already copied.
106 Returns:
107 A copy of the technique.
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
122@dataclasses.dataclass
123class NullVertex(base.Vertex):
124 """A Vertex that does nothing.
126 This node is stored in the library as "none" (and as "null_vertex").
128 This is a useful node when you want to compare using one technique with
129 making no changes.
131 Args:
132 name: name used to refer to the node in a workflow. Defaults to
133 "none".
135 """
137 name: str = dataclasses.field(default = 'none')
139 def apply(self, item: Any, **kwargs: Any) -> Any:
140 """Returns `item` unchanged.
142 Args:
143 item: data or object.
144 **kwargs: ignored.
146 Returns:
147 `item`.
149 """
150 return item
153# Lets settings refer to a `NullVertex` as "none".
154base.library.add(NullVertex, name = 'none')
157@dataclasses.dataclass
158class Step(base.Vertex, abc.ABC):
159 """A stage of a workflow that wraps a technique or a worker.
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.
170 A Step returns the attributes of `contents` that it does not have itself.
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`.
179 """
181 name: str | None = None
182 contents: Technique | Worker | None = None
183 parameters: base.GenericDict = dataclasses.field(default_factory = dict)
185 """ Public Methods """
187 def begin(self, item: Any) -> Any:
188 """Runs any preparation needed for the step.
190 Args:
191 item: data or object to change.
193 Returns:
194 The item in a prepared state.
196 """
197 return item
199 def end(self, item: Any) -> Any:
200 """Finalizes the step's execution.
202 Args:
203 item: data or object to change.
205 Returns:
206 The final result of the step.
208 """
209 return item
211 def apply(self, item: Any, **kwargs: Any) -> Any:
212 """Applies the technique or worker in `contents` to `item`.
214 Parameter priority, from lowest to highest, is the `parameters` of
215 `contents`, the step's `parameters`, and `kwargs`.
217 Args:
218 item: data or object to change.
219 **kwargs: keyword arguments for the `apply` method of `contents`.
221 Raises:
222 ValueError: if there is nothing in `contents`.
224 Returns:
225 The result of `begin`, the `apply` method of `contents`, and
226 `end`.
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)
238 """ Dunder Methods """
240 def __getattr__(self, attribute: str) -> Any:
241 """Returns an attribute of `contents` that the step does not have.
243 Args:
244 attribute: name of the attribute.
246 Raises:
247 AttributeError: if neither the step nor `contents` has `attribute`.
249 Returns:
250 The attribute of `contents`.
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)
261@dataclasses.dataclass
262class Worker(holden.System, base.Vertex, abc.ABC):
263 """Base class for nodes that are workflows of other nodes.
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.
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`.
278 """
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)
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__
290 """ Public Methods """
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.
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.
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
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.
316 Args:
317 item: data or object to change.
318 **kwargs: keyword arguments passed to the nodes.
320 Returns:
321 The result of the workflow.
323 """