Episode 8: Receiving LSL Streams
Read a stream published by a program that is not g.Pype into a pipeline with an LslReceiver, by name, with its channel names intact.
Episode 2 published a stream for others. This is the direction a pipeline usually meets first: somebody else’s program publishes, and g.Pype reads. Another vendor’s amplifier, MATLAB, a stimulus program, a recording tool. An LslReceiver hands the stream’s samples to the pipeline like any other source, so everything downstream is unchanged.
The publisher is a thread in this file, and nothing in it imports gpype: raw pylsl pushing noise in blocks of 5 samples, fifty times a second, paced against a running deadline so the rate does not drift. The block is the receiver’s pace: the scope advances once per block, so a sender pushing 25 at a time, ten times a second, shows up in steps of 100 ms. The channel labels go into the stream description, which is where a receiver finds them. In a real session this is somebody else’s process, usually on somebody else’s machine; delete the thread and keep the rest.
23def foreign_publisher(stop: threading.Event) -> None:
24 """The other vendor's program. No gpype below this line."""
25 info = StreamInfo(name=STREAM_NAME, type="EEG", channel_count=CHANNELS,
26 nominal_srate=FS, channel_format="float32",
27 source_id="s4e8-noise")
28 # Channel labels travel in the stream description
29 channels = info.desc().append_child("channels")
30 for index in range(CHANNELS):
31 channels.append_child("channel").append_child_value(
32 "label", f"NOISE{index + 1}")
33 outlet = StreamOutlet(info, chunk_size=BLOCK)
34 rng = np.random.default_rng(7)
35 # Paced against a running deadline, so the rate does not drift
36 deadline = time.perf_counter()
37 while not stop.is_set():
38 chunk = rng.normal(0.0, 20.0, size=(BLOCK, CHANNELS))
39 outlet.push_chunk(chunk.astype(np.float32).tolist())
40 deadline += BLOCK / FS
41 time.sleep(max(0.0, deadline - time.perf_counter()))
The receiver looks for its stream as soon as it is created, and gives up after five seconds with No LSL stream with name … appeared within 5 s. So the publisher starts before the pipeline is built.
46 # The publisher first: the receiver looks for the stream as soon as
47 # it is created, and gives up after five seconds
48 stop = threading.Event()
49 threading.Thread(target=foreign_publisher, args=(stop,),
50 daemon=True).start()
Resolved by name, because a lab network carries more than one stream of type EEG and stream_type="EEG" takes whichever answers first. The channel count and the sampling rate are read from the stream when you do not give them; pass them to state what you expect instead.
52 app = gp.MainApp()
53 p = gp.Pipeline()
54
55 # By name, since a lab network carries more than one stream of type
56 # EEG; stream_type="EEG" would take whichever answers first. The
57 # channel count and the rate are read from the stream
58 source = gp.LslReceiver(stream_name=STREAM_NAME)
59
60 scope = gp.TimeSeriesScope(amplitude_limit=100, time_window=10)
Run the script. The scope opens within a couple of seconds showing eight channels of noise, labelled NOISE1 to NOISE8: the labels the publisher put in the stream description. LSL prints a run of Could not bind multicast responder warnings first on a machine with several network interfaces; they are normal and nothing has failed.
Figure 34: The foreign stream, with the names it was published under.
Names come with the stream only where the publisher named every channel; types and units are kept even where it did not, and a stream of type Markers arrives as a trigger. The receiver times samples by their arrival on this machine, not by the timestamps LSL sends alongside, so delay on the network becomes latency in the pipeline. And what arrives is somebody else’s data: LSL carries no per-sample authentication, so a stream says what it is and cannot prove it.
In this episode, you learned how to:
read a stream from a program that is not g.Pype with an LslReceiver
resolve by name rather than by type, and start the publisher first
know which metadata crosses over, and how the samples are timed
Proceed to Episode 9, where a recording is handed to MNE-Python, in volts, through a Result.
Nodes in this episode: LslReceiver, TimeSeriesScope
File s4e8_receiving_lsl.py – View file on GitHub
1"""Season 4, Episode 8: a stream from a program that is not g.Pype.
2
3The publisher is the thread below, and nothing in it imports gpype:
4raw pylsl pushing noise, labelled NOISE1 to NOISE8. In a real session
5it is another vendor's amplifier, MATLAB or a stimulus program, usually
6on another machine; delete the thread and keep the rest.
7"""
8
9import threading
10import time
11
12import numpy as np
13from pylsl import StreamInfo, StreamOutlet
14
15import gpype as gp
16
17STREAM_NAME = "NoiseAmp" # what the other program calls itself
18CHANNELS = 8
19FS = 250
20BLOCK = 5 # samples per push, fifty pushes a second
21
22
23def foreign_publisher(stop: threading.Event) -> None:
24 """The other vendor's program. No gpype below this line."""
25 info = StreamInfo(name=STREAM_NAME, type="EEG", channel_count=CHANNELS,
26 nominal_srate=FS, channel_format="float32",
27 source_id="s4e8-noise")
28 # Channel labels travel in the stream description
29 channels = info.desc().append_child("channels")
30 for index in range(CHANNELS):
31 channels.append_child("channel").append_child_value(
32 "label", f"NOISE{index + 1}")
33 outlet = StreamOutlet(info, chunk_size=BLOCK)
34 rng = np.random.default_rng(7)
35 # Paced against a running deadline, so the rate does not drift
36 deadline = time.perf_counter()
37 while not stop.is_set():
38 chunk = rng.normal(0.0, 20.0, size=(BLOCK, CHANNELS))
39 outlet.push_chunk(chunk.astype(np.float32).tolist())
40 deadline += BLOCK / FS
41 time.sleep(max(0.0, deadline - time.perf_counter()))
42
43
44if __name__ == "__main__":
45
46 # The publisher first: the receiver looks for the stream as soon as
47 # it is created, and gives up after five seconds
48 stop = threading.Event()
49 threading.Thread(target=foreign_publisher, args=(stop,),
50 daemon=True).start()
51
52 app = gp.MainApp()
53 p = gp.Pipeline()
54
55 # By name, since a lab network carries more than one stream of type
56 # EEG; stream_type="EEG" would take whichever answers first. The
57 # channel count and the rate are read from the stream
58 source = gp.LslReceiver(stream_name=STREAM_NAME)
59
60 scope = gp.TimeSeriesScope(amplitude_limit=100, time_window=10)
61
62 p.connect(source, scope)
63 app.add_widget(scope)
64
65 p.start()
66 app.run()
67 p.stop()
68 p.close()
69 stop.set()