Episode 3: The Two Ends
Write a source and a sink of your own by subclassing gp.Source and gp.Sink, and let the pipeline build the chain it needs around each.
A pipeline begins at a source and ends at a sink, and both reach outside it: a device, a file, a database. Subclass gp.Source or gp.Sink and the node is one class like any other; the pipeline builds the chain it needs around it, as it does around a Generator or a CsvWriter. Counter stands in for a device g.Pype has no driver for and sends a numbered ramp for two seconds; SqliteWriter writes each sample it receives as a row of an SQLite table.
gp.Source describes the port’s width and frame size in setup(). The rate is yours to add; without one the Sync behind the source refuses the pipeline at start(), since nothing could place the samples.
22class Counter(gp.Source):
23 """A device that sends a numbered ramp, in whole frames, then stops."""
24
25 class Configuration(gp.Source.Configuration):
26 class Keys(gp.Source.Configuration.Keys):
27 SAMPLING_RATE = KEYS.SAMPLING_RATE
28 SECONDS = "seconds"
29
30 def __init__(self, sampling_rate: float = 250.0, channel_count: int = 2,
31 seconds: float = 2.0, **kwargs):
32 output_ports = kwargs.pop(KEYS.OUTPUT_PORTS,
33 [gp.OPort.Configuration()])
34 super().__init__(output_ports=output_ports,
35 channel_count=channel_count,
36 sampling_rate=sampling_rate, seconds=seconds,
37 **kwargs)
38 self._thread = None
39 self._running = False
40 self._frame = None
41
42 def setup(self, data, port_context_in):
43 # gp.Source describes the width and the frame size. The rate is
44 # this source's to publish, and nothing downstream runs without.
45 port_context_out = super().setup(data, port_context_in)
46 port_context_out[PORT_OUT][KEYS.SAMPLING_RATE] = (
47 self.config[KEYS.SAMPLING_RATE])
48 return port_context_out
It runs its own cycles: a thread started in start(), self.cycle() whenever a frame is ready, the frame handed over in step(), and the thread ended in stop(). A driver would wait for the device where this one waits for the clock.
50 def start(self):
51 super().start()
52 self._running = True
53 self._thread = threading.Thread(target=self._acquire, daemon=True)
54 self._thread.start()
55
56 def stop(self):
57 self._running = False
58 if self._thread is not None:
59 self._thread.join()
60 super().stop()
61
62 def _acquire(self):
63 # A driver would wait for the device here; this one waits for
64 # the clock. A source drives its own cycles: one per frame.
65 rate = self.config[KEYS.SAMPLING_RATE]
66 size = self.config[KEYS.FRAME_SIZE][0]
67 width = self.config[KEYS.CHANNEL_COUNT][0]
68 seconds = self.config[self.Configuration.Keys.SECONDS]
69 frames = int(rate * seconds) // size
70 due = time.perf_counter()
71 for first in range(0, frames * size, size):
72 if not self._running:
73 break
74 due += size / rate
75 time.sleep(max(0.0, due - time.perf_counter()))
76 count = np.arange(first, first + size, dtype=np.float32)
77 self._frame = np.repeat(count[:, None], width, axis=1)
78 self.cycle()
79
80 def step(self, data):
81 frame, self._frame = self._frame, None
82 return None if frame is None else {PORT_OUT: frame}
setup() is where a sink learns what it will receive, so it is where it refuses what it cannot write: SqliteWriter needs a rate for its time column and a channel count for its table. It opens the database there, on the first frame.
85class SqliteWriter(gp.Sink):
86 """One row per sample: its time, then one column per channel."""
87
88 class Configuration(gp.Sink.Configuration):
89 class Keys(gp.Sink.Configuration.Keys):
90 FILE_NAME = "file_name"
91
92 def __init__(self, file_name: str, **kwargs):
93 input_ports = kwargs.pop(KEYS.INPUT_PORTS,
94 [gp.IPort.Configuration()])
95 super().__init__(file_name=file_name, input_ports=input_ports,
96 **kwargs)
97 self._db = None
98 self.written = 0
99
100 def setup(self, data, port_context_in):
101 # A row needs its time, and the table needs its columns.
102 context = port_context_in[PORT_IN]
103 missing = [key for key in (KEYS.SAMPLING_RATE, KEYS.CHANNEL_COUNT)
104 if context.get(key) is None]
105 if missing:
106 raise ValueError(
107 f"SqliteWriter needs {' and '.join(missing)} in its input "
108 f"context; got {sorted(context) or 'none'}.")
109 self._rate = context[KEYS.SAMPLING_RATE]
110 self.written = 0
111 columns = ", ".join(f"ch{i + 1} REAL"
112 for i in range(context[KEYS.CHANNEL_COUNT]))
113 # setup() and step() run on the source's thread, stop() on the
114 # caller's.
115 self._db = sqlite3.connect(self.config["file_name"],
116 check_same_thread=False)
117 self._db.execute("DROP TABLE IF EXISTS samples")
118 self._db.execute(f"CREATE TABLE samples (t REAL, {columns})")
119 return super().setup(data, port_context_in)
One row per sample, its time first; commit and close in stop(). setup() and step() run on the source’s thread and stop() on the caller’s, which is why the connection allows that.
121 def step(self, data):
122 frame = data[PORT_IN]
123 t = (self.written + np.arange(len(frame))) / self._rate
124 marks = ", ".join("?" * (frame.shape[1] + 1))
125 self._db.executemany(f"INSERT INTO samples VALUES ({marks})",
126 np.column_stack((t, frame)).tolist())
127 self.written += len(frame)
128 return {}
129
130 def stop(self):
131 super().stop()
132 if self._db is not None:
133 self._db.commit()
134 self._db.close()
135 self._db = None
The type decides it: a subclass of gp.Source, gp.Sink or gp.Widget is wrapped when it is connected, and any other node is not. p.chain_of(node) returns the chain. The Sync behind a source puts its samples on the pipeline’s timeline, and the Link in front of a sink is where a distributed pipeline crosses from one process to another; in one process it passes frames through. You write neither. A Collector subclasses gp.INode and gets no chain, because it keeps its data in this process.
140 p = gp.Pipeline()
141 device = Counter(sampling_rate=RATE, channel_count=2, seconds=SECONDS,
142 name="device")
143 database = SqliteWriter(file_name=DATABASE, name="database")
144 p.connect(device, database)
145
146 # 1. Each end is one class, and the pipeline built its chain.
147 for node in (device, database):
148 chain = p.chain_of(node)
149 inside = ", ".join(type(n).__name__ for n in chain.internal_nodes)
150 print(f"{node.name}: {type(chain).__name__} [{inside}]")
The script waits for the last row before stopping, because stop() ends the run where it is, and a frame still on its way then may not be written.
152 # 2. Run until the device has sent everything and the last row is in.
153 p.start()
154 while database.written < RATE * SECONDS:
155 time.sleep(0.05)
156 p.stop()
157 p.close()
158
159 db = sqlite3.connect(DATABASE)
160 rows, first, last = db.execute(
161 "SELECT COUNT(*), MIN(ch1), MAX(ch1) FROM samples").fetchone()
162 db.close()
163 print(f"{rows} rows for {RATE * SECONDS} samples sent, "
164 f"counting {first:g} to {last:g}")
A live source g.Pype ships, a Generator or any amplifier, adds one channel to its port: the instant each frame reached the host. The Sync in its chain finds it by its timestamp role and removes it, so a source’s port is one channel wider than it was asked for and nothing downstream sees the difference. The clock the stamp is written from is not public, so Counter adds none, as LslReceiver adds none; in one process its Sync reads that clock itself when the frame arrives. Last, the sink refuses an input context with nothing in it.
166 # 3. A live source g.Pype ships has a port one channel wider than it
167 # was asked for: the instant each frame reached the host, found
168 # by its role. The Sync in its chain removes it.
169 port = gp.Generator(channel_count=2).setup({}, {})[PORT_OUT]
170 print(f"Generator port: {port[KEYS.CHANNEL_COUNT]} channels, "
171 f"{port[KEYS.CHANNEL_ROLES]}")
172
173 # 4. The sink says what it needs, and refuses without it.
174 try:
175 SqliteWriter(file_name=DATABASE).setup({}, {PORT_IN: {}})
176 except ValueError as error:
177 print(f"refused: {error}")
Run the script:
device: SourceChain [Counter, Sync]
database: SinkChain [Link, SqliteWriter]
500 rows for 500 samples sent, counting 0 to 499
Generator port: 3 channels, ['signal', 'signal', 'timestamp']
refused: SqliteWriter needs sampling_rate and channel_count in its input context; got none.
In this episode, you learned how to:
write a source that drives its own cycles and declares its rate
write a sink that refuses in
setup()what it cannot writeread the chain the pipeline builds around each, and the arrival stamp a live source carries
Proceed to Episode 4, where a node offers values to read and set while the pipeline runs.
Nodes in this episode: Source, Sink, Generator, and the file’s own Counter and SqliteWriter
File s7e3_two_ends.py – View file on GitHub
1"""Season 7, Episode 3: a source and a sink of your own, chains included."""
2
3import os
4import sqlite3
5import tempfile
6import threading
7import time
8
9import numpy as np
10
11import gpype as gp
12
13KEYS = gp.Constants.Keys
14PORT_IN = gp.Constants.Defaults.PORT_IN
15PORT_OUT = gp.Constants.Defaults.PORT_OUT
16
17RATE = 250
18SECONDS = 2
19DATABASE = os.path.join(tempfile.gettempdir(), "s7e3_two_ends.sqlite")
20
21
22class Counter(gp.Source):
23 """A device that sends a numbered ramp, in whole frames, then stops."""
24
25 class Configuration(gp.Source.Configuration):
26 class Keys(gp.Source.Configuration.Keys):
27 SAMPLING_RATE = KEYS.SAMPLING_RATE
28 SECONDS = "seconds"
29
30 def __init__(self, sampling_rate: float = 250.0, channel_count: int = 2,
31 seconds: float = 2.0, **kwargs):
32 output_ports = kwargs.pop(KEYS.OUTPUT_PORTS,
33 [gp.OPort.Configuration()])
34 super().__init__(output_ports=output_ports,
35 channel_count=channel_count,
36 sampling_rate=sampling_rate, seconds=seconds,
37 **kwargs)
38 self._thread = None
39 self._running = False
40 self._frame = None
41
42 def setup(self, data, port_context_in):
43 # gp.Source describes the width and the frame size. The rate is
44 # this source's to publish, and nothing downstream runs without.
45 port_context_out = super().setup(data, port_context_in)
46 port_context_out[PORT_OUT][KEYS.SAMPLING_RATE] = (
47 self.config[KEYS.SAMPLING_RATE])
48 return port_context_out
49
50 def start(self):
51 super().start()
52 self._running = True
53 self._thread = threading.Thread(target=self._acquire, daemon=True)
54 self._thread.start()
55
56 def stop(self):
57 self._running = False
58 if self._thread is not None:
59 self._thread.join()
60 super().stop()
61
62 def _acquire(self):
63 # A driver would wait for the device here; this one waits for
64 # the clock. A source drives its own cycles: one per frame.
65 rate = self.config[KEYS.SAMPLING_RATE]
66 size = self.config[KEYS.FRAME_SIZE][0]
67 width = self.config[KEYS.CHANNEL_COUNT][0]
68 seconds = self.config[self.Configuration.Keys.SECONDS]
69 frames = int(rate * seconds) // size
70 due = time.perf_counter()
71 for first in range(0, frames * size, size):
72 if not self._running:
73 break
74 due += size / rate
75 time.sleep(max(0.0, due - time.perf_counter()))
76 count = np.arange(first, first + size, dtype=np.float32)
77 self._frame = np.repeat(count[:, None], width, axis=1)
78 self.cycle()
79
80 def step(self, data):
81 frame, self._frame = self._frame, None
82 return None if frame is None else {PORT_OUT: frame}
83
84
85class SqliteWriter(gp.Sink):
86 """One row per sample: its time, then one column per channel."""
87
88 class Configuration(gp.Sink.Configuration):
89 class Keys(gp.Sink.Configuration.Keys):
90 FILE_NAME = "file_name"
91
92 def __init__(self, file_name: str, **kwargs):
93 input_ports = kwargs.pop(KEYS.INPUT_PORTS,
94 [gp.IPort.Configuration()])
95 super().__init__(file_name=file_name, input_ports=input_ports,
96 **kwargs)
97 self._db = None
98 self.written = 0
99
100 def setup(self, data, port_context_in):
101 # A row needs its time, and the table needs its columns.
102 context = port_context_in[PORT_IN]
103 missing = [key for key in (KEYS.SAMPLING_RATE, KEYS.CHANNEL_COUNT)
104 if context.get(key) is None]
105 if missing:
106 raise ValueError(
107 f"SqliteWriter needs {' and '.join(missing)} in its input "
108 f"context; got {sorted(context) or 'none'}.")
109 self._rate = context[KEYS.SAMPLING_RATE]
110 self.written = 0
111 columns = ", ".join(f"ch{i + 1} REAL"
112 for i in range(context[KEYS.CHANNEL_COUNT]))
113 # setup() and step() run on the source's thread, stop() on the
114 # caller's.
115 self._db = sqlite3.connect(self.config["file_name"],
116 check_same_thread=False)
117 self._db.execute("DROP TABLE IF EXISTS samples")
118 self._db.execute(f"CREATE TABLE samples (t REAL, {columns})")
119 return super().setup(data, port_context_in)
120
121 def step(self, data):
122 frame = data[PORT_IN]
123 t = (self.written + np.arange(len(frame))) / self._rate
124 marks = ", ".join("?" * (frame.shape[1] + 1))
125 self._db.executemany(f"INSERT INTO samples VALUES ({marks})",
126 np.column_stack((t, frame)).tolist())
127 self.written += len(frame)
128 return {}
129
130 def stop(self):
131 super().stop()
132 if self._db is not None:
133 self._db.commit()
134 self._db.close()
135 self._db = None
136
137
138if __name__ == "__main__":
139
140 p = gp.Pipeline()
141 device = Counter(sampling_rate=RATE, channel_count=2, seconds=SECONDS,
142 name="device")
143 database = SqliteWriter(file_name=DATABASE, name="database")
144 p.connect(device, database)
145
146 # 1. Each end is one class, and the pipeline built its chain.
147 for node in (device, database):
148 chain = p.chain_of(node)
149 inside = ", ".join(type(n).__name__ for n in chain.internal_nodes)
150 print(f"{node.name}: {type(chain).__name__} [{inside}]")
151
152 # 2. Run until the device has sent everything and the last row is in.
153 p.start()
154 while database.written < RATE * SECONDS:
155 time.sleep(0.05)
156 p.stop()
157 p.close()
158
159 db = sqlite3.connect(DATABASE)
160 rows, first, last = db.execute(
161 "SELECT COUNT(*), MIN(ch1), MAX(ch1) FROM samples").fetchone()
162 db.close()
163 print(f"{rows} rows for {RATE * SECONDS} samples sent, "
164 f"counting {first:g} to {last:g}")
165
166 # 3. A live source g.Pype ships has a port one channel wider than it
167 # was asked for: the instant each frame reached the host, found
168 # by its role. The Sync in its chain removes it.
169 port = gp.Generator(channel_count=2).setup({}, {})[PORT_OUT]
170 print(f"Generator port: {port[KEYS.CHANNEL_COUNT]} channels, "
171 f"{port[KEYS.CHANNEL_ROLES]}")
172
173 # 4. The sink says what it needs, and refuses without it.
174 try:
175 SqliteWriter(file_name=DATABASE).setup({}, {PORT_IN: {}})
176 except ValueError as error:
177 print(f"refused: {error}")