Episode 1: Your First Node
Write a node of your own, with its parameters in the configuration, a setup() that describes its output and a step() that does the work, and run it live and offline.
A node of your own is one class with three parts: the parameters it keeps in its configuration, the setup() that tells the next node what it will receive, and the step() that does the work. This episode builds DriftMonitor, which reports how far each channel has moved from its own running mean, the first sign of an electrode losing contact, and appends one channel with the worst of them.
Whatever __init__ passes to the base class is the node’s configuration, and the configuration is what a saved pipeline stores. A value kept only on self is not saved, and a loaded node runs without it. Name a parameter in Configuration.Keys when it must be given: None or an empty value is refused as the node is built. Name it in OptionalKeys when it may be left out.
23class DriftMonitor(gp.IONode):
24 """Each channel's distance from its running mean, and the worst."""
25
26 class Configuration(gp.IONode.Configuration):
27 class Keys(gp.IONode.Configuration.Keys):
28 #: Required: None or an empty value is refused.
29 WINDOW_SECONDS = "window_seconds"
30
31 class OptionalKeys(gp.IONode.Configuration.OptionalKeys):
32 #: May be left out.
33 LABEL = "label"
34
35 def __init__(self, window_seconds: float = 2.0, label: str = None,
36 **kwargs):
37 # What reaches the base class is the node's configuration, and
38 # the configuration is what a saved pipeline stores.
39 super().__init__(window_seconds=window_seconds, label=label,
40 **kwargs)
41 self._mean = None
42 self._weight = None
setup() receives the context of each input port, its sampling rate, channel count, frame size and what each channel is, and returns the context of each output. The base class checks the input and copies its context to every output port; what your node changes is yours to say. DriftMonitor adds a channel, so the count grows by one and so do the descriptions: the roles by auxiliary, which a filter downstream leaves alone, and the labels by the new channel’s name, where the input names its channels. Leave them short and they no longer fit the data, and a Result then reports no labels and no roles at all. setup() is also where the sampling rate is first known, which is why the window in seconds becomes a weight per sample here and not in __init__.
44 def setup(self, data, port_context_in):
45 # The base class checks the input and copies its context to
46 # every output port. What changes is ours to say.
47 port_context_out = super().setup(data, port_context_in)
48 context = port_context_in[PORT_IN]
49 out = port_context_out[PORT_OUT]
50
51 # The window is in seconds and a frame is in samples. The rate
52 # that converts one into the other is first known here.
53 window = self.config[self.Configuration.Keys.WINDOW_SECONDS]
54 self._weight = 1.0 / max(1.0, context[KEYS.SAMPLING_RATE] * window)
55 count = context[KEYS.CHANNEL_COUNT]
56 self._mean = np.zeros(count, dtype=gp.Constants.DATA_TYPE)
57
58 # One channel more than came in, and its description with it.
59 # Auxiliary, so a filter downstream leaves it alone.
60 out[KEYS.CHANNEL_COUNT] = count + 1
61 roles = context.get(KEYS.CHANNEL_ROLES) or [ROLES.SIGNAL] * count
62 out[KEYS.CHANNEL_ROLES] = list(roles) + [ROLES.AUXILIARY]
63 labels = context.get(KEYS.CHANNEL_LABELS)
64 if labels:
65 label = self.config[self.Configuration.OptionalKeys.LABEL]
66 out[KEYS.CHANNEL_LABELS] = list(labels) + [label or "worst"]
67 return port_context_out
step() takes one frame per input and returns one per output: the running mean is updated sample by sample, the drift is the distance from it, and the worst across channels is the extra column.
69 def step(self, data):
70 frame = data[PORT_IN]
71 drift = np.empty_like(frame)
72 for i, row in enumerate(frame):
73 self._mean += self._weight * (row - self._mean)
74 drift[i] = row - self._mean
75 worst = np.max(np.abs(drift), axis=1, keepdims=True)
76 return {PORT_OUT: np.hstack((drift, worst))}
The script writes an eight-second recording of three channels, with Cz drifting up by 40 over them. replay() drives the node frame by frame, as fast as the machine allows, and waits for the Collector rather than the reader, since a reader is exhausted once its last frame has left it, before that frame arrives. offline() reads the same file in one batch run.
108def replay(node) -> tuple:
109 """Frame by frame, as fast as the machine allows.
110
111 Returns:
112 What the Collector kept, and the pipeline, serialized.
113 """
114 with gp.Pipeline() as p:
115 reader = gp.CsvReader(file_name=RECORDING, frame_size=10, speed=0)
116 collector = gp.Collector()
117 p.connect(reader, node)
118 p.connect(node, collector)
119 p.start()
120 # Wait for the Collector, not the reader: a reader is exhausted
121 # once its last frame has left it, before that frame arrives.
122 while (collector.result is None
123 or len(collector.result.data) < RATE * SECONDS):
124 time.sleep(0.01)
125 p.stop()
126 return collector.result, p.serialize()
127
128
129def offline(node) -> gp.Result:
130 """The whole recording in one cycle."""
131 with gp.Pipeline() as p:
132 reader = gp.CsvReader(file_name=RECORDING, mode="batch")
133 collector = gp.Collector()
134 p.connect(reader, node)
135 p.connect(node, collector)
136 return p.run()
The output is one channel wider than the input, and its labels and roles say so.
143 # 1. Frame by frame. The output is one channel wider than the input,
144 # and its labels and roles say so.
145 live, document = replay(DriftMonitor(window_seconds=WINDOW))
146 print(f"out: {live.data.shape[1]} channels")
147 print(f"labels: {live.labels}")
148 print(f"roles: {live.roles}")
serialize() writes the pipeline as a serialized pipeline, a dict, and Pipeline.deserialize() builds it again, handing each node its saved configuration. Loading imports the module every node names, so a module of your own has to be allowed first, with gp.allow_modules; Season 8 covers why, and the other ways. A node defined in the script you run is saved as module __main__, so only this process can load what it saved; Season 8 moves the node into a package. The copy gets fresh ids because the first pipeline’s nodes still hold theirs in this process. And a key in Keys has to be given.
150 # 2. The saved pipeline carries the parameter, and loading it builds
151 # a node that has it. Loading imports the module each node names,
152 # so a module of your own has to be allowed first (Season 8). The
153 # first pipeline's nodes still hold their ids in this process, so
154 # the copy is given new ones.
155 saved = next(n for n in document["nodes"] if n["class"] == "DriftMonitor")
156 print(f"saved: window_seconds={saved['config']['window_seconds']}, "
157 f"label={saved['config']['label']}")
158 gp.allow_modules(DriftMonitor.__module__)
159 loaded = gp.Pipeline.deserialize(with_fresh_ids(document))
160 again = next(n for n in loaded.serialize()["nodes"]
161 if n["class"] == "DriftMonitor")
162 print(f"loaded: window_seconds={again['config']['window_seconds']}, "
163 f"label={again['config']['label']}")
164 loaded.close()
165
166 # A key in Keys has to be given; one in OptionalKeys may be left out.
167 try:
168 DriftMonitor(window_seconds=None)
169 except ValueError as error:
170 print(f"refused: {error}")
A batch run hands a node the whole recording at once. A node with only step() receives it there, and because DriftMonitor is causal, each output depends only on the samples before it, the answer is the one the frames gave, bit for bit. process() is for what only the whole recording can answer: RecordDrift measures against the recording’s own mean, which does not exist until the recording ends. A node that defines both runs step() live and process() offline.
79class RecordDrift(DriftMonitor):
80 """The same measurement against the mean of the whole recording.
81
82 That mean exists only once the recording does. A batch run calls
83 process() once, with every sample; a realtime run would call the
84 step() this class inherits.
85 """
86
87 def process(self, data):
88 record = data[PORT_IN]
89 drift = record - record.mean(axis=0)
90 worst = np.max(np.abs(drift), axis=1, keepdims=True)
91 return {PORT_OUT: np.hstack((drift, worst))}
172 # 3. Offline. step() is causal, so the whole recording in one call
173 # gives exactly what the frames gave. process() is for what only
174 # a whole recording can answer.
175 batch = offline(DriftMonitor(window_seconds=WINDOW))
176 record = offline(RecordDrift(window_seconds=WINDOW))
177 same = np.array_equal(batch.data, live.data)
178 print(f"step() offline equals frame by frame: {same}")
179 print(f"Cz at the end, step(): {batch.data[-RATE:, 1].mean():5.1f}")
180 print(f"Cz at the end, process(): {record.data[-RATE:, 1].mean():5.1f}")
Run the script:
out: 4 channels
labels: ['Fz', 'Cz', 'Pz', 'worst']
roles: ['signal', 'signal', 'signal', 'auxiliary']
saved: window_seconds=1.5, label=None
loaded: window_seconds=1.5, label=None
refused: Field 'window_seconds' must not be None.
step() offline equals frame by frame: True
Cz at the end, step(): ...
Cz at the end, process(): ...
The last two lines are the difference between the two measures. Cz drifts by 5 per second. The running mean follows it and trails by about its window, so the causal measure settles near 5 × 1.5 = 7.5; against the mean of the whole recording, which sits at the four-second mark, the last second is 3.5 × 5 = 17.5 above it.
In this episode, you learned how to:
declare a node’s parameters, required or optional, in its configuration
describe the output in
setup(), channel count, roles and labels includedsave and load a pipeline that holds your node, and run it live and offline
Proceed to Episode 2, where a node declares ports of its own and one of them carries events.
Nodes in this episode: CsvReader, Collector, and the file’s own DriftMonitor and RecordDrift
File s7e1_your_first_node.py – View file on GitHub
1"""Season 7, Episode 1: a node of your own: parameters, setup(), step()."""
2
3import os
4import tempfile
5import time
6
7import numpy as np
8
9import gpype as gp
10from gpype.common.document import with_fresh_ids
11
12KEYS = gp.Constants.Keys
13ROLES = gp.Constants.ChannelRoles
14PORT_IN = gp.Constants.Defaults.PORT_IN
15PORT_OUT = gp.Constants.Defaults.PORT_OUT
16
17RATE = 250
18SECONDS = 8
19WINDOW = 1.5
20RECORDING = os.path.join(tempfile.gettempdir(), "s7e1_your_first_node.csv")
21
22
23class DriftMonitor(gp.IONode):
24 """Each channel's distance from its running mean, and the worst."""
25
26 class Configuration(gp.IONode.Configuration):
27 class Keys(gp.IONode.Configuration.Keys):
28 #: Required: None or an empty value is refused.
29 WINDOW_SECONDS = "window_seconds"
30
31 class OptionalKeys(gp.IONode.Configuration.OptionalKeys):
32 #: May be left out.
33 LABEL = "label"
34
35 def __init__(self, window_seconds: float = 2.0, label: str = None,
36 **kwargs):
37 # What reaches the base class is the node's configuration, and
38 # the configuration is what a saved pipeline stores.
39 super().__init__(window_seconds=window_seconds, label=label,
40 **kwargs)
41 self._mean = None
42 self._weight = None
43
44 def setup(self, data, port_context_in):
45 # The base class checks the input and copies its context to
46 # every output port. What changes is ours to say.
47 port_context_out = super().setup(data, port_context_in)
48 context = port_context_in[PORT_IN]
49 out = port_context_out[PORT_OUT]
50
51 # The window is in seconds and a frame is in samples. The rate
52 # that converts one into the other is first known here.
53 window = self.config[self.Configuration.Keys.WINDOW_SECONDS]
54 self._weight = 1.0 / max(1.0, context[KEYS.SAMPLING_RATE] * window)
55 count = context[KEYS.CHANNEL_COUNT]
56 self._mean = np.zeros(count, dtype=gp.Constants.DATA_TYPE)
57
58 # One channel more than came in, and its description with it.
59 # Auxiliary, so a filter downstream leaves it alone.
60 out[KEYS.CHANNEL_COUNT] = count + 1
61 roles = context.get(KEYS.CHANNEL_ROLES) or [ROLES.SIGNAL] * count
62 out[KEYS.CHANNEL_ROLES] = list(roles) + [ROLES.AUXILIARY]
63 labels = context.get(KEYS.CHANNEL_LABELS)
64 if labels:
65 label = self.config[self.Configuration.OptionalKeys.LABEL]
66 out[KEYS.CHANNEL_LABELS] = list(labels) + [label or "worst"]
67 return port_context_out
68
69 def step(self, data):
70 frame = data[PORT_IN]
71 drift = np.empty_like(frame)
72 for i, row in enumerate(frame):
73 self._mean += self._weight * (row - self._mean)
74 drift[i] = row - self._mean
75 worst = np.max(np.abs(drift), axis=1, keepdims=True)
76 return {PORT_OUT: np.hstack((drift, worst))}
77
78
79class RecordDrift(DriftMonitor):
80 """The same measurement against the mean of the whole recording.
81
82 That mean exists only once the recording does. A batch run calls
83 process() once, with every sample; a realtime run would call the
84 step() this class inherits.
85 """
86
87 def process(self, data):
88 record = data[PORT_IN]
89 drift = record - record.mean(axis=0)
90 worst = np.max(np.abs(drift), axis=1, keepdims=True)
91 return {PORT_OUT: np.hstack((drift, worst))}
92
93
94def write_recording(path: str = RECORDING) -> None:
95 """Eight seconds of three channels; Cz drifts up by 40 over them."""
96 t = np.arange(RATE * SECONDS) / RATE
97 rng = np.random.default_rng(7)
98 data = 5.0 * np.sin(2 * np.pi * 10 * t)[:, None] + rng.normal(
99 0.0, 1.0, (t.size, 3))
100 data[:, 1] += 40.0 * t / SECONDS
101 with open(path, "w", encoding="utf-8", newline="") as handle:
102 handle.write("Time, Fz, Cz, Pz\n")
103 for second, row in zip(t, data):
104 handle.write(f"{second:g}, " + ", ".join(f"{v:.6f}" for v in row)
105 + "\n")
106
107
108def replay(node) -> tuple:
109 """Frame by frame, as fast as the machine allows.
110
111 Returns:
112 What the Collector kept, and the pipeline, serialized.
113 """
114 with gp.Pipeline() as p:
115 reader = gp.CsvReader(file_name=RECORDING, frame_size=10, speed=0)
116 collector = gp.Collector()
117 p.connect(reader, node)
118 p.connect(node, collector)
119 p.start()
120 # Wait for the Collector, not the reader: a reader is exhausted
121 # once its last frame has left it, before that frame arrives.
122 while (collector.result is None
123 or len(collector.result.data) < RATE * SECONDS):
124 time.sleep(0.01)
125 p.stop()
126 return collector.result, p.serialize()
127
128
129def offline(node) -> gp.Result:
130 """The whole recording in one cycle."""
131 with gp.Pipeline() as p:
132 reader = gp.CsvReader(file_name=RECORDING, mode="batch")
133 collector = gp.Collector()
134 p.connect(reader, node)
135 p.connect(node, collector)
136 return p.run()
137
138
139if __name__ == "__main__":
140
141 write_recording()
142
143 # 1. Frame by frame. The output is one channel wider than the input,
144 # and its labels and roles say so.
145 live, document = replay(DriftMonitor(window_seconds=WINDOW))
146 print(f"out: {live.data.shape[1]} channels")
147 print(f"labels: {live.labels}")
148 print(f"roles: {live.roles}")
149
150 # 2. The saved pipeline carries the parameter, and loading it builds
151 # a node that has it. Loading imports the module each node names,
152 # so a module of your own has to be allowed first (Season 8). The
153 # first pipeline's nodes still hold their ids in this process, so
154 # the copy is given new ones.
155 saved = next(n for n in document["nodes"] if n["class"] == "DriftMonitor")
156 print(f"saved: window_seconds={saved['config']['window_seconds']}, "
157 f"label={saved['config']['label']}")
158 gp.allow_modules(DriftMonitor.__module__)
159 loaded = gp.Pipeline.deserialize(with_fresh_ids(document))
160 again = next(n for n in loaded.serialize()["nodes"]
161 if n["class"] == "DriftMonitor")
162 print(f"loaded: window_seconds={again['config']['window_seconds']}, "
163 f"label={again['config']['label']}")
164 loaded.close()
165
166 # A key in Keys has to be given; one in OptionalKeys may be left out.
167 try:
168 DriftMonitor(window_seconds=None)
169 except ValueError as error:
170 print(f"refused: {error}")
171
172 # 3. Offline. step() is causal, so the whole recording in one call
173 # gives exactly what the frames gave. process() is for what only
174 # a whole recording can answer.
175 batch = offline(DriftMonitor(window_seconds=WINDOW))
176 record = offline(RecordDrift(window_seconds=WINDOW))
177 same = np.array_equal(batch.data, live.data)
178 print(f"step() offline equals frame by frame: {same}")
179 print(f"Cz at the end, step(): {batch.data[-RATE:, 1].mean():5.1f}")
180 print(f"Cz at the end, process(): {record.data[-RATE:, 1].mean():5.1f}")