Episode 4: A Control Surface
Give a node a control surface, values to read and set while the pipeline runs and actions it performs on request, and drive it by the node’s id.
Some settings are found by moving them while you watch: a gain, a neurofeedback level. A node offers them as a control surface, one dict to read and set while the pipeline runs and named actions it performs on request, and whatever drives the pipeline reaches them by the node’s id. Gain multiplies its input by a gain that can be set mid-run; its action take_peak reports the largest output since it was last asked.
A gain in the configuration, and a peak kept under a lock: the control surface runs on the caller’s thread, beside step() on the source’s. A single value replaced whole is safe to read on the next frame; anything read and reset together, like the peak, needs the lock.
14class Gain(gp.IONode):
15 """Multiplies the signal by a gain an operator can move."""
16
17 class Configuration(gp.IONode.Configuration):
18 class Keys(gp.IONode.Configuration.Keys):
19 GAIN = "gain"
20
21 def __init__(self, gain: float = 1.0, **kwargs):
22 super().__init__(gain=gain, **kwargs)
23 self._gain = float(gain)
24 self._peak = 0.0
25 # The control surface is called from the caller's thread, step()
26 # from the source's.
27 self._lock = threading.Lock()
28
29 def step(self, data):
30 out = data[PORT_IN] * self._gain
31 with self._lock:
32 self._peak = max(self._peak, float(np.abs(out).max()))
33 return {PORT_OUT: out}
Mark get_control and set_control with @gp.controllable, and each action with @gp.action. Only marked methods are reachable: an ordinary method is not an action, whatever its name. The control needs both halves, because get_control is also the list of keys set_control accepts.
35 @gp.controllable
36 def get_control(self) -> dict:
37 """The values a caller may read and set."""
38 return {"gain": self._gain}
39
40 @gp.controllable
41 def set_control(self, arg: dict) -> dict:
42 """Handed every key of get_control(), changed or not."""
43 gain = float(arg["gain"])
44 if gain < 0:
45 raise ValueError(f"gain must not be negative, got {gain}")
46 self._gain = gain
47 return self.get_control()
48
49 @gp.action
50 def take_peak(self, arg: dict) -> dict:
51 """Report the largest output since the last call, and reset."""
52 with self._lock:
53 peak, self._peak = self._peak, 0.0
54 return {"peak": round(peak, 1)}
55
Pipeline.get_nodes() lists every node with its id, whether it is controllable, and its actions. The id is how a controlling process names the node.
59 p = gp.Pipeline()
60 source = gp.Generator(sampling_rate=250, channel_count=2,
61 signal_frequency=10, signal_amplitude=10.0)
62 gain = Gain(gain=1.0, name="gain")
63 p.connect(source, gain)
64 p.connect(gain, gp.Collector())
65
66 # What a controlling process sees: every node, its id and surface.
67 entry = next(n for n in p.get_nodes() if n["class"] == "Gain")
68 node = entry["id"]
69 print(f"controllable: {entry['controllable']}, "
70 f"actions: {entry['actions']}")
get_control reads the dict. set_control takes only what changes, merges it into what the node reported, hands the node the whole result and returns what the node now holds. invoke_action runs an action with a dict and returns its dict.
72 p.start()
73 time.sleep(1.0)
74 print(f"before: {p.get_control(node)}, "
75 f"{p.invoke_action(node, 'take_peak', {})}")
76
77 # A set names only what changes, and returns the whole state.
78 print(f"set: {p.set_control(node, {'gain': 2.0})}")
79 time.sleep(1.0)
80 print(f"after: {p.get_control(node)}, "
81 f"{p.invoke_action(node, 'take_peak', {})}")
A key the node does not report is refused by the pipeline, which is what the misspelt gian meets; a value the node cannot use is the node’s to refuse, by raising. And a control is not configuration: it changes the running node and nothing else, so the saved pipeline keeps the gain the node was built with. A setting found this way belongs in the constructor once it is found.
83 # A key get_control() does not report is refused before the node
84 # sees it.
85 try:
86 p.set_control(node, {"gian": 3.0})
87 except KeyError as error:
88 print(f"refused: {error.args[0]}")
89
90 # A control is not configuration: the saved pipeline keeps the gain
91 # it was built with.
92 saved = next(n for n in p.serialize()["nodes"] if n["class"] == "Gain")
93 print(f"saved: gain={saved['config']['gain']}")
94 p.stop()
95 p.close()
Run the script:
controllable: True, actions: ['take_peak']
before: {'gain': 1.0}, {'peak': 10.0}
set: {'gain': 2.0}
after: {'gain': 2.0}, {'peak': 20.0}
refused: unknown control key(s) ['gian']; accepted keys are ['gain']
saved: gain=1.0
Threshold is the shipped node with a control surface. Its level, release and dwell can be moved while it runs, which is how a neurofeedback threshold is tuned against the person in the chair.
In this episode, you learned how to:
declare a control surface with
@gp.controllableand@gp.actiondrive it through the pipeline by the node’s id
keep a control apart from configuration, and share state between two threads
Proceed to Episode 5, where a widget of your own draws what arrives.
Nodes in this episode: Generator, Collector, and the file’s own Gain
File s7e4_a_control_surface.py – View file on GitHub
1"""Season 7, Episode 4: a control surface, read and set while it runs."""
2
3import threading
4import time
5
6import numpy as np
7
8import gpype as gp
9
10PORT_IN = gp.Constants.Defaults.PORT_IN
11PORT_OUT = gp.Constants.Defaults.PORT_OUT
12
13
14class Gain(gp.IONode):
15 """Multiplies the signal by a gain an operator can move."""
16
17 class Configuration(gp.IONode.Configuration):
18 class Keys(gp.IONode.Configuration.Keys):
19 GAIN = "gain"
20
21 def __init__(self, gain: float = 1.0, **kwargs):
22 super().__init__(gain=gain, **kwargs)
23 self._gain = float(gain)
24 self._peak = 0.0
25 # The control surface is called from the caller's thread, step()
26 # from the source's.
27 self._lock = threading.Lock()
28
29 def step(self, data):
30 out = data[PORT_IN] * self._gain
31 with self._lock:
32 self._peak = max(self._peak, float(np.abs(out).max()))
33 return {PORT_OUT: out}
34
35 @gp.controllable
36 def get_control(self) -> dict:
37 """The values a caller may read and set."""
38 return {"gain": self._gain}
39
40 @gp.controllable
41 def set_control(self, arg: dict) -> dict:
42 """Handed every key of get_control(), changed or not."""
43 gain = float(arg["gain"])
44 if gain < 0:
45 raise ValueError(f"gain must not be negative, got {gain}")
46 self._gain = gain
47 return self.get_control()
48
49 @gp.action
50 def take_peak(self, arg: dict) -> dict:
51 """Report the largest output since the last call, and reset."""
52 with self._lock:
53 peak, self._peak = self._peak, 0.0
54 return {"peak": round(peak, 1)}
55
56
57if __name__ == "__main__":
58
59 p = gp.Pipeline()
60 source = gp.Generator(sampling_rate=250, channel_count=2,
61 signal_frequency=10, signal_amplitude=10.0)
62 gain = Gain(gain=1.0, name="gain")
63 p.connect(source, gain)
64 p.connect(gain, gp.Collector())
65
66 # What a controlling process sees: every node, its id and surface.
67 entry = next(n for n in p.get_nodes() if n["class"] == "Gain")
68 node = entry["id"]
69 print(f"controllable: {entry['controllable']}, "
70 f"actions: {entry['actions']}")
71
72 p.start()
73 time.sleep(1.0)
74 print(f"before: {p.get_control(node)}, "
75 f"{p.invoke_action(node, 'take_peak', {})}")
76
77 # A set names only what changes, and returns the whole state.
78 print(f"set: {p.set_control(node, {'gain': 2.0})}")
79 time.sleep(1.0)
80 print(f"after: {p.get_control(node)}, "
81 f"{p.invoke_action(node, 'take_peak', {})}")
82
83 # A key get_control() does not report is refused before the node
84 # sees it.
85 try:
86 p.set_control(node, {"gian": 3.0})
87 except KeyError as error:
88 print(f"refused: {error.args[0]}")
89
90 # A control is not configuration: the saved pipeline keeps the gain
91 # it was built with.
92 saved = next(n for n in p.serialize()["nodes"] if n["class"] == "Gain")
93 print(f"saved: gain={saved['config']['gain']}")
94 p.stop()
95 p.close()