pylsl 1.17.4__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pylsl/__init__.py +43 -0
- pylsl/__version__.py +16 -0
- pylsl/examples/GetTimeCorrection.py +25 -0
- pylsl/examples/HandleMetadata.py +61 -0
- pylsl/examples/PerformanceTest.py +423 -0
- pylsl/examples/README.md +10 -0
- pylsl/examples/ReceiveAndPlot.py +195 -0
- pylsl/examples/ReceiveData.py +22 -0
- pylsl/examples/ReceiveDataInChunks.py +24 -0
- pylsl/examples/ReceiveStringMarkers.py +22 -0
- pylsl/examples/SendData.py +66 -0
- pylsl/examples/SendDataAdvanced.py +113 -0
- pylsl/examples/SendStringMarkers.py +32 -0
- pylsl/examples/__init__.py +1 -0
- pylsl/info.py +577 -0
- pylsl/inlet.py +309 -0
- pylsl/lib/__init__.py +373 -0
- pylsl/outlet.py +228 -0
- pylsl/resolve.py +183 -0
- pylsl/util.py +110 -0
- pylsl-1.17.4.dist-info/METADATA +133 -0
- pylsl-1.17.4.dist-info/RECORD +24 -0
- pylsl-1.17.4.dist-info/WHEEL +5 -0
- pylsl-1.17.4.dist-info/licenses/LICENSE +19 -0
pylsl/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Python API for the lab streaming layer.
|
|
2
|
+
|
|
3
|
+
The lab streaming layer provides a set of functions to make instrument data
|
|
4
|
+
accessible in real time within a lab network. From there, streams can be
|
|
5
|
+
picked up by recording programs, viewing programs or custom experiment
|
|
6
|
+
applications that access data streams in real time.
|
|
7
|
+
|
|
8
|
+
The API covers two areas:
|
|
9
|
+
- The "push API" allows to create stream outlets and to push data (regular
|
|
10
|
+
or irregular measurement time series, event data, coded audio/video frames,
|
|
11
|
+
etc.) into them.
|
|
12
|
+
- The "pull API" allows to create stream inlets and read time-synched
|
|
13
|
+
experiment data from them (for recording, viewing or experiment control).
|
|
14
|
+
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from .__version__ import __version__ as __version__
|
|
18
|
+
from .resolve import ContinuousResolver as ContinuousResolver
|
|
19
|
+
from .resolve import resolve_streams as resolve_streams
|
|
20
|
+
from .resolve import resolve_bypred as resolve_bypred
|
|
21
|
+
from .resolve import resolve_byprop as resolve_byprop
|
|
22
|
+
from .info import StreamInfo as StreamInfo
|
|
23
|
+
from .inlet import StreamInlet as StreamInlet
|
|
24
|
+
from .outlet import StreamOutlet as StreamOutlet
|
|
25
|
+
from .util import IRREGULAR_RATE as IRREGULAR_RATE
|
|
26
|
+
from .util import FOREVER as FOREVER
|
|
27
|
+
from .util import proc_none as proc_none
|
|
28
|
+
from .util import proc_clocksync as proc_clocksync
|
|
29
|
+
from .util import proc_dejitter as proc_dejitter
|
|
30
|
+
from .util import proc_monotonize as proc_monotonize
|
|
31
|
+
from .util import proc_threadsafe as proc_threadsafe
|
|
32
|
+
from .util import proc_ALL as proc_ALL
|
|
33
|
+
from .util import protocol_version as protocol_version
|
|
34
|
+
from .util import library_version as library_version
|
|
35
|
+
from .util import library_info as library_info
|
|
36
|
+
from .util import local_clock as local_clock
|
|
37
|
+
from .lib import cf_int8 as cf_int8
|
|
38
|
+
from .lib import cf_int16 as cf_int16
|
|
39
|
+
from .lib import cf_int32 as cf_int32
|
|
40
|
+
from .lib import cf_int64 as cf_int64
|
|
41
|
+
from .lib import cf_float32 as cf_float32
|
|
42
|
+
from .lib import cf_double64 as cf_double64
|
|
43
|
+
from .lib import cf_string as cf_string
|
pylsl/__version__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# file generated by setuptools_scm
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
TYPE_CHECKING = False
|
|
4
|
+
if TYPE_CHECKING:
|
|
5
|
+
from typing import Tuple, Union
|
|
6
|
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
|
7
|
+
else:
|
|
8
|
+
VERSION_TUPLE = object
|
|
9
|
+
|
|
10
|
+
version: str
|
|
11
|
+
__version__: str
|
|
12
|
+
__version_tuple__: VERSION_TUPLE
|
|
13
|
+
version_tuple: VERSION_TUPLE
|
|
14
|
+
|
|
15
|
+
__version__ = version = '1.17.4'
|
|
16
|
+
__version_tuple__ = version_tuple = (1, 17, 4)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Example program to show how to read a multi-channel time series from LSL."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from pylsl import StreamInlet, resolve_byprop
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main():
|
|
9
|
+
# first resolve an EEG stream on the lab network
|
|
10
|
+
print("looking for an EEG stream...")
|
|
11
|
+
streams = resolve_byprop("type", "EEG")
|
|
12
|
+
info = streams[0]
|
|
13
|
+
|
|
14
|
+
# create a new inlet to read from the stream
|
|
15
|
+
inlet = StreamInlet(info)
|
|
16
|
+
|
|
17
|
+
print("Connected to outlet " + info.name() + "@" + info.hostname())
|
|
18
|
+
while True:
|
|
19
|
+
offset = inlet.time_correction()
|
|
20
|
+
print("Offset: " + str(offset))
|
|
21
|
+
time.sleep(1)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
main()
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Example program that shows how to attach meta-data to a stream, and how to
|
|
2
|
+
later on retrieve the meta-data again at the receiver side."""
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from pylsl import StreamInfo, StreamInlet, StreamOutlet, resolve_byprop
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main():
|
|
11
|
+
# create a new StreamInfo object which shall describe our stream
|
|
12
|
+
info = StreamInfo("MetaTester", "EEG", 8, 100, "float32", "myuid56872")
|
|
13
|
+
|
|
14
|
+
# now attach some meta-data (in accordance with XDF format,
|
|
15
|
+
# see also https://github.com/sccn/xdf/wiki/Meta-Data)
|
|
16
|
+
chns = info.desc().append_child("channels")
|
|
17
|
+
ch_labels = ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]
|
|
18
|
+
for label in ch_labels:
|
|
19
|
+
ch = chns.append_child("channel")
|
|
20
|
+
ch.append_child_value("label", label)
|
|
21
|
+
ch.append_child_value("unit", "microvolts")
|
|
22
|
+
ch.append_child_value("type", "EEG")
|
|
23
|
+
info.desc().append_child_value("manufacturer", "SCCN")
|
|
24
|
+
cap = info.desc().append_child("cap")
|
|
25
|
+
cap.append_child_value("name", "EasyCap")
|
|
26
|
+
cap.append_child_value("size", "54")
|
|
27
|
+
cap.append_child_value("labelscheme", "10-20")
|
|
28
|
+
|
|
29
|
+
# create outlet for the stream
|
|
30
|
+
outlet = StreamOutlet(info)
|
|
31
|
+
|
|
32
|
+
# Send a sample into the outlet...
|
|
33
|
+
dummy_sample = np.arange(len(ch_labels), dtype=np.float32)
|
|
34
|
+
outlet.push_sample(dummy_sample)
|
|
35
|
+
|
|
36
|
+
# === the following could run on another computer ===
|
|
37
|
+
|
|
38
|
+
# first we resolve a stream whose name is MetaTester (note that there are
|
|
39
|
+
# other ways to query a stream, too - for instance by content-type)
|
|
40
|
+
results = resolve_byprop("name", "MetaTester")
|
|
41
|
+
|
|
42
|
+
# open an inlet so we can read the stream's data (and meta-data)
|
|
43
|
+
inlet = StreamInlet(results[0])
|
|
44
|
+
|
|
45
|
+
# get the full stream info (including custom meta-data) and dissect it
|
|
46
|
+
info = inlet.info()
|
|
47
|
+
print("The stream's XML meta-data is: ")
|
|
48
|
+
print(info.as_xml())
|
|
49
|
+
print("The manufacturer is: %s" % info.desc().child_value("manufacturer"))
|
|
50
|
+
print("Cap circumference is: %s" % info.desc().child("cap").child_value("size"))
|
|
51
|
+
print("The channel labels are as follows:")
|
|
52
|
+
ch = info.desc().child("channels").child("channel")
|
|
53
|
+
for k in range(info.channel_count()):
|
|
54
|
+
print(" " + ch.child_value("label"))
|
|
55
|
+
ch = ch.next_sibling()
|
|
56
|
+
|
|
57
|
+
time.sleep(3)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
main()
|
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import random
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from pylsl import (
|
|
7
|
+
StreamInfo,
|
|
8
|
+
StreamInlet,
|
|
9
|
+
StreamOutlet,
|
|
10
|
+
local_clock,
|
|
11
|
+
proc_clocksync,
|
|
12
|
+
proc_dejitter,
|
|
13
|
+
proc_monotonize,
|
|
14
|
+
resolve_bypred,
|
|
15
|
+
resolve_byprop,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
from pyfftw.interfaces.numpy_fft import irfft
|
|
20
|
+
# Performs much better than numpy's fftpack
|
|
21
|
+
except ImportError:
|
|
22
|
+
from numpy.fft import irfft
|
|
23
|
+
try:
|
|
24
|
+
import sys
|
|
25
|
+
|
|
26
|
+
import pyqtgraph as pg
|
|
27
|
+
|
|
28
|
+
haspyqtgraph = True
|
|
29
|
+
except ImportError:
|
|
30
|
+
haspyqtgraph = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# The code for pink noise generation is taken from
|
|
34
|
+
# https://github.com/python-acoustics/python-acoustics/blob/master/acoustics/generator.py
|
|
35
|
+
# which is distributed under the BSD license.
|
|
36
|
+
def ms(x):
|
|
37
|
+
"""Mean value of signal `x` squared.
|
|
38
|
+
:param x: Dynamic quantity.
|
|
39
|
+
:returns: Mean squared of `x`.
|
|
40
|
+
"""
|
|
41
|
+
return (np.abs(x) ** 2.0).mean()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def normalize(y, x=None):
|
|
45
|
+
"""normalize power in y to a (standard normal) white noise signal.
|
|
46
|
+
Optionally normalize to power in signal `x`.
|
|
47
|
+
#The mean power of a Gaussian with :math:`\\mu=0` and :math:`\\sigma=1` is 1.
|
|
48
|
+
"""
|
|
49
|
+
# return y * np.sqrt( (np.abs(x)**2.0).mean() / (np.abs(y)**2.0).mean() )
|
|
50
|
+
if x is not None:
|
|
51
|
+
x = ms(x)
|
|
52
|
+
else:
|
|
53
|
+
x = 1.0
|
|
54
|
+
return y * np.sqrt(x / ms(y))
|
|
55
|
+
# return y * np.sqrt( 1.0 / (np.abs(y)**2.0).mean() )
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def pink(N):
|
|
59
|
+
"""
|
|
60
|
+
Pink noise.
|
|
61
|
+
|
|
62
|
+
:param N: Amount of samples.
|
|
63
|
+
|
|
64
|
+
Pink noise has equal power in bands that are proportionally wide.
|
|
65
|
+
Power density decreases with 3 dB per octave.
|
|
66
|
+
|
|
67
|
+
"""
|
|
68
|
+
# This method uses the filter with the following coefficients.
|
|
69
|
+
# b = np.array([0.049922035, -0.095993537, 0.050612699, -0.004408786])
|
|
70
|
+
# a = np.array([1, -2.494956002, 2.017265875, -0.522189400])
|
|
71
|
+
# return lfilter(B, A, np.random.randn(N))
|
|
72
|
+
# Another way would be using the FFT
|
|
73
|
+
# x = np.random.randn(N)
|
|
74
|
+
# X = rfft(x) / N
|
|
75
|
+
uneven = N % 2
|
|
76
|
+
X = np.random.randn(N // 2 + 1 + uneven) + 1j * np.random.randn(N // 2 + 1 + uneven)
|
|
77
|
+
S = np.sqrt(np.arange(len(X)) + 1.0) # +1 to avoid divide by zero
|
|
78
|
+
y = (irfft(X / S)).real
|
|
79
|
+
if uneven:
|
|
80
|
+
y = y[:-1]
|
|
81
|
+
return normalize(y)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class PinkNoiseGenerator(object):
|
|
85
|
+
def __init__(self, nSampsPerBlock=1024):
|
|
86
|
+
self.N = nSampsPerBlock
|
|
87
|
+
self.uneven = self.N % 2
|
|
88
|
+
lenX = self.N // 2 + 1 + self.uneven
|
|
89
|
+
self.S = np.sqrt(np.arange(lenX) + 1.0)
|
|
90
|
+
|
|
91
|
+
def generate(self):
|
|
92
|
+
X = np.random.randn(self.N // 2 + 1 + self.uneven) + 1j * np.random.randn(
|
|
93
|
+
self.N // 2 + 1 + self.uneven
|
|
94
|
+
)
|
|
95
|
+
y = (irfft(X / self.S)).real
|
|
96
|
+
if self.uneven:
|
|
97
|
+
y = y[:-1]
|
|
98
|
+
return normalize(y)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class BetaGeneratorOutlet(object):
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
Fs=2**14,
|
|
105
|
+
FreqBeta=20.0,
|
|
106
|
+
AmpBeta=100.0,
|
|
107
|
+
AmpNoise=20.0,
|
|
108
|
+
NCyclesPerChunk=4,
|
|
109
|
+
channels=["RAW1", "SPK1", "RAW2", "SPK2", "RAW3", "SPK3"],
|
|
110
|
+
):
|
|
111
|
+
"""
|
|
112
|
+
:param Fs: Sampling rate
|
|
113
|
+
:param FreqBeta: Central frequency of beta band
|
|
114
|
+
:param AmpBeta: Amplitude of beta (uV)
|
|
115
|
+
:param AmpNoise: Amplitude of pink noise (uV)
|
|
116
|
+
:param NCyclesPerChunk: Minimum number of cycles of beta in a chunk.
|
|
117
|
+
:param channels: List of channel names
|
|
118
|
+
"""
|
|
119
|
+
# Saved arguments
|
|
120
|
+
self.FreqBeta = FreqBeta
|
|
121
|
+
self.AmpBeta = AmpBeta # Amplitude of Beta (uV)
|
|
122
|
+
self.AmpNoise = AmpNoise # Amplitude of pink noise
|
|
123
|
+
self.channels = channels
|
|
124
|
+
# Derived variables
|
|
125
|
+
chunk_dur = NCyclesPerChunk / self.FreqBeta # Duration, in sec, of one chunk
|
|
126
|
+
chunk_len = int(Fs * chunk_dur) # Number of samples in a chunk
|
|
127
|
+
self.tvec = 1.0 * (np.arange(chunk_len) + 1) / Fs # time vector for chunk (sec)
|
|
128
|
+
# Pink noise generator
|
|
129
|
+
self.pinkNoiseGen = PinkNoiseGenerator(nSampsPerBlock=chunk_len)
|
|
130
|
+
|
|
131
|
+
# Create a stream of fake 'raw' data
|
|
132
|
+
raw_info = StreamInfo(
|
|
133
|
+
name="BetaGen",
|
|
134
|
+
type="EEG",
|
|
135
|
+
channel_count=len(self.channels),
|
|
136
|
+
nominal_srate=Fs,
|
|
137
|
+
channel_format="float32",
|
|
138
|
+
source_id="betagen1234",
|
|
139
|
+
)
|
|
140
|
+
raw_xml = raw_info.desc()
|
|
141
|
+
chans = raw_xml.append_child("channels")
|
|
142
|
+
for channame in self.channels:
|
|
143
|
+
chn = chans.append_child("channel")
|
|
144
|
+
chn.append_child_value("label", channame)
|
|
145
|
+
chn.append_child_value("unit", "microvolts")
|
|
146
|
+
chn.append_child_value("type", "generated")
|
|
147
|
+
self.eeg_outlet = StreamOutlet(raw_info)
|
|
148
|
+
print("Created outlet with name BetaGen and type EEG")
|
|
149
|
+
|
|
150
|
+
self.last_time = local_clock()
|
|
151
|
+
|
|
152
|
+
def update(self, task={"phase": "precue", "class": 1}):
|
|
153
|
+
# Convert phase and class_id into beta_amp
|
|
154
|
+
if task["phase"] in ["cue", "go"]:
|
|
155
|
+
beta_amp = 0 if task["class"] == 3 else self.AmpBeta
|
|
156
|
+
else:
|
|
157
|
+
beta_amp = self.AmpBeta / 5.0
|
|
158
|
+
|
|
159
|
+
this_tvec = self.tvec + self.last_time # Sample times
|
|
160
|
+
# Put the signal together
|
|
161
|
+
this_sig = self.AmpNoise * np.asarray(
|
|
162
|
+
self.pinkNoiseGen.generate(), dtype=np.float32
|
|
163
|
+
) # Start with some pink noise
|
|
164
|
+
this_sig += beta_amp * np.sin(
|
|
165
|
+
this_tvec * 2 * np.pi * self.FreqBeta
|
|
166
|
+
) # Add our beta signal
|
|
167
|
+
this_sig = np.atleast_2d(this_sig).T * np.ones(
|
|
168
|
+
(1, len(self.channels)), dtype=np.float32
|
|
169
|
+
) # Tile across channels
|
|
170
|
+
|
|
171
|
+
time_to_sleep = max(0, this_tvec[-1] - local_clock())
|
|
172
|
+
time.sleep(time_to_sleep)
|
|
173
|
+
|
|
174
|
+
print(
|
|
175
|
+
"Beta outlet pushing signal with shape {},{} and Beta amp {}".format(
|
|
176
|
+
this_sig.shape[0], this_sig.shape[1], beta_amp
|
|
177
|
+
)
|
|
178
|
+
)
|
|
179
|
+
self.eeg_outlet.push_chunk(this_sig, timestamp=this_tvec[-1])
|
|
180
|
+
|
|
181
|
+
self.last_time = local_clock()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class BetaInlet(object):
|
|
185
|
+
def __init__(self):
|
|
186
|
+
print("looking for an EEG stream...")
|
|
187
|
+
streams = resolve_byprop("type", "EEG")
|
|
188
|
+
|
|
189
|
+
# create a new inlet to read from the stream
|
|
190
|
+
proc_flags = proc_clocksync | proc_dejitter | proc_monotonize
|
|
191
|
+
self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)
|
|
192
|
+
|
|
193
|
+
# The following is an example of how to read stream info
|
|
194
|
+
stream_info = self.inlet.info()
|
|
195
|
+
stream_Fs = stream_info.nominal_srate()
|
|
196
|
+
stream_xml = stream_info.desc()
|
|
197
|
+
chans_xml = stream_xml.child("channels")
|
|
198
|
+
chan_xml_list = []
|
|
199
|
+
ch = chans_xml.child("channel")
|
|
200
|
+
while ch.name() == "channel":
|
|
201
|
+
chan_xml_list.append(ch)
|
|
202
|
+
ch = ch.next_sibling("channel")
|
|
203
|
+
self.channel_names = [ch_xml.child_value("label") for ch_xml in chan_xml_list]
|
|
204
|
+
print(
|
|
205
|
+
"Reading from inlet named {} with channels {} sending data at {} Hz".format(
|
|
206
|
+
stream_info.name(), self.channel_names, stream_Fs
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
def update(self):
|
|
211
|
+
max_samps = 3276 * 2
|
|
212
|
+
data = np.nan * np.ones((max_samps, len(self.channel_names)), dtype=np.float32)
|
|
213
|
+
_, timestamps = self.inlet.pull_chunk(max_samples=max_samps, dest_obj=data)
|
|
214
|
+
data = data[: len(timestamps), :]
|
|
215
|
+
print("Beta inlet retrieved {} samples.".format(len(timestamps)))
|
|
216
|
+
return data, np.asarray(timestamps)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class MarkersGeneratorOutlet(object):
|
|
220
|
+
phases = {
|
|
221
|
+
"precue": {"next": "cue", "duration": 1.0},
|
|
222
|
+
"cue": {"next": "go", "duration": 0.5},
|
|
223
|
+
"go": {"next": "evaluate", "duration": 5.0},
|
|
224
|
+
"evaluate": {"next": "precue", "duration": 0.1},
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
def __init__(
|
|
228
|
+
self,
|
|
229
|
+
class_list=[1, 3],
|
|
230
|
+
classes_rand=True,
|
|
231
|
+
target_list=[1, 2],
|
|
232
|
+
targets_rand=True,
|
|
233
|
+
):
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
:param class_list: A list of integers comprising different class ids. Default: [1, 3]
|
|
237
|
+
:param classes_rand: If True, classes are chosen randomly from list. If False, the list is cycled. Default: True
|
|
238
|
+
:param target_list: A list of integers comprising different target ids. Default: [1, 2]
|
|
239
|
+
:param targets_rand: If True, targets are chosen randomly from list. If False, the list is cycled. Default: True
|
|
240
|
+
"""
|
|
241
|
+
stream_name = "GeneratedCentreOutMarkers"
|
|
242
|
+
stream_type = "Markers"
|
|
243
|
+
outlet_info = StreamInfo(
|
|
244
|
+
name=stream_name,
|
|
245
|
+
type=stream_type,
|
|
246
|
+
channel_count=1,
|
|
247
|
+
nominal_srate=0,
|
|
248
|
+
channel_format="string",
|
|
249
|
+
source_id="centreoutmarkergen1234",
|
|
250
|
+
)
|
|
251
|
+
outlet_xml = outlet_info.desc()
|
|
252
|
+
channels_xml = outlet_xml.append_child("channels")
|
|
253
|
+
chan_xml = channels_xml.append_child("channel")
|
|
254
|
+
chan_xml.append_child_value("label", "EventMarkers")
|
|
255
|
+
chan_xml.append_child_value("type", "generated")
|
|
256
|
+
self.outlet = StreamOutlet(outlet_info)
|
|
257
|
+
print(
|
|
258
|
+
"Created outlet with name {} and type {}".format(stream_name, stream_type)
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
self.class_list = class_list
|
|
262
|
+
self.classes_rand = classes_rand
|
|
263
|
+
self.target_list = target_list
|
|
264
|
+
self.targets_rand = targets_rand
|
|
265
|
+
self.next_transition = -1
|
|
266
|
+
self.in_phase = "evaluate"
|
|
267
|
+
self.trial_ix = 0
|
|
268
|
+
self.class_id = self.class_list[0]
|
|
269
|
+
self.target_id = self.target_list[0]
|
|
270
|
+
|
|
271
|
+
def update(self):
|
|
272
|
+
now = local_clock()
|
|
273
|
+
if now > self.next_transition:
|
|
274
|
+
# Transition phase
|
|
275
|
+
self.in_phase = self.phases[self.in_phase]["next"]
|
|
276
|
+
self.next_transition = now + self.phases[self.in_phase]["duration"]
|
|
277
|
+
|
|
278
|
+
# Send markers
|
|
279
|
+
out_string = "undefined"
|
|
280
|
+
if self.in_phase == "precue":
|
|
281
|
+
# transition from evaluate to precue
|
|
282
|
+
# print("Previous class_id: {}, target_id: {}".format(self.class_id, self.target_id))
|
|
283
|
+
self.trial_ix += 1
|
|
284
|
+
self.target_id = (
|
|
285
|
+
random.choice(self.target_list)
|
|
286
|
+
if self.targets_rand
|
|
287
|
+
else self.target_list[
|
|
288
|
+
(self.target_list.index(self.target_id) + 1)
|
|
289
|
+
% len(self.target_list)
|
|
290
|
+
]
|
|
291
|
+
)
|
|
292
|
+
self.class_id = (
|
|
293
|
+
random.choice(self.class_list)
|
|
294
|
+
if self.classes_rand
|
|
295
|
+
else self.class_list[
|
|
296
|
+
(self.class_list.index(self.class_id) + 1)
|
|
297
|
+
% len(self.class_list)
|
|
298
|
+
]
|
|
299
|
+
)
|
|
300
|
+
# print("New class_id: {}, target_id: {}".format(self.class_id, self.target_id))
|
|
301
|
+
out_string = "NewTrial {}, Class {}, Target {}".format(
|
|
302
|
+
self.trial_ix, self.class_id, self.target_id
|
|
303
|
+
)
|
|
304
|
+
elif self.in_phase == "cue":
|
|
305
|
+
# transition from precue to cue
|
|
306
|
+
out_string = "TargetCue, Class {}, Target {}".format(
|
|
307
|
+
self.class_id, self.target_id
|
|
308
|
+
)
|
|
309
|
+
elif self.in_phase == "go":
|
|
310
|
+
# transition from cue to go
|
|
311
|
+
out_string = "GoCue, Class {}, Target {}".format(
|
|
312
|
+
self.class_id, self.target_id
|
|
313
|
+
)
|
|
314
|
+
elif self.in_phase == "evaluate":
|
|
315
|
+
# transition from go to evaluate
|
|
316
|
+
hit_string = "Hit" if random.randint(0, 1) == 1 else "Miss"
|
|
317
|
+
out_string = "{}, Class {}, Target {}".format(
|
|
318
|
+
hit_string, self.class_id, self.target_id
|
|
319
|
+
)
|
|
320
|
+
print("Marker outlet pushing string: {}".format(out_string))
|
|
321
|
+
self.outlet.push_sample(
|
|
322
|
+
[
|
|
323
|
+
out_string,
|
|
324
|
+
]
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
return True
|
|
328
|
+
return False
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class MarkerInlet(object):
|
|
332
|
+
def __init__(self):
|
|
333
|
+
self.task = {"phase": "precue", "class": 1, "target": 1}
|
|
334
|
+
print("Looking for stream with type Markers")
|
|
335
|
+
streams = resolve_bypred("type='Markers'", minimum=1)
|
|
336
|
+
proc_flags = 0 # Marker events are relatively rare. No need to post-process.
|
|
337
|
+
self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)
|
|
338
|
+
# The following is an example of how to read stream info
|
|
339
|
+
stream_info = self.inlet.info()
|
|
340
|
+
# stream_Fs = stream_info.nominal_srate()
|
|
341
|
+
stream_xml = stream_info.desc()
|
|
342
|
+
chans_xml = stream_xml.child("channels")
|
|
343
|
+
chan_xml_list = []
|
|
344
|
+
ch = chans_xml.child("channel")
|
|
345
|
+
while ch.name() == "channel":
|
|
346
|
+
chan_xml_list.append(ch)
|
|
347
|
+
ch = ch.next_sibling("channel")
|
|
348
|
+
stream_ch_names = [ch_xml.child_value("label") for ch_xml in chan_xml_list]
|
|
349
|
+
print(
|
|
350
|
+
"Reading from inlet named {} with channels {}".format(
|
|
351
|
+
stream_info.name(), stream_ch_names
|
|
352
|
+
)
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
def update(self):
|
|
356
|
+
marker_samples, marker_timestamps = self.inlet.pull_chunk(timeout=0.0)
|
|
357
|
+
if marker_timestamps:
|
|
358
|
+
[phase_str, class_str, targ_str] = marker_samples[-1][0].split(", ")
|
|
359
|
+
if phase_str in ["TargetCue"]:
|
|
360
|
+
self.task["phase"] = "cue"
|
|
361
|
+
elif phase_str in ["GoCue"]:
|
|
362
|
+
self.task["phase"] = "go"
|
|
363
|
+
elif phase_str in ["Miss", "Hit"]:
|
|
364
|
+
self.task["phase"] = "evaluate"
|
|
365
|
+
elif phase_str[:8] == "NewTrial":
|
|
366
|
+
self.task["phase"] = "precue"
|
|
367
|
+
else:
|
|
368
|
+
print(phase_str)
|
|
369
|
+
self.task["class"] = int(class_str.split(" ")[1])
|
|
370
|
+
self.task["target"] = int(targ_str.split(" ")[1])
|
|
371
|
+
print("Marker inlet updated with task {}".format(self.task))
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
betaGen = BetaGeneratorOutlet()
|
|
375
|
+
markerGen = MarkersGeneratorOutlet()
|
|
376
|
+
betaIn = BetaInlet()
|
|
377
|
+
markerIn = MarkerInlet()
|
|
378
|
+
|
|
379
|
+
if haspyqtgraph:
|
|
380
|
+
qapp = pg.QtGui.QApplication(sys.argv)
|
|
381
|
+
qwindow = pg.plot()
|
|
382
|
+
qwindow.clear()
|
|
383
|
+
qwindow.parent().setWindowTitle("pylsl PerformanceTest")
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def update():
|
|
387
|
+
markerGen.update()
|
|
388
|
+
markerIn.update()
|
|
389
|
+
betaGen.update(task=markerIn.task) # Rate-limiting step. Will time.sleep as needed.
|
|
390
|
+
signal, tvec = betaIn.update()
|
|
391
|
+
|
|
392
|
+
if haspyqtgraph:
|
|
393
|
+
plot = qwindow.getPlotItem()
|
|
394
|
+
graphs = plot.listDataItems()
|
|
395
|
+
if not graphs:
|
|
396
|
+
# create graphs
|
|
397
|
+
for i in range(signal.shape[1]):
|
|
398
|
+
plot.plot(tvec, signal[:, i])
|
|
399
|
+
else:
|
|
400
|
+
# update graphs
|
|
401
|
+
for i in range(signal.shape[1]):
|
|
402
|
+
graphs[i].setData(signal[:, i], x=tvec)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
if __name__ == "__main__":
|
|
406
|
+
"""
|
|
407
|
+
python3 -m cProfile -o pylsl.cprof PerformanceTest.py
|
|
408
|
+
gprof2dot -f pstats pylsl.cprof | dot -Tpng -o pylsl_prof.png
|
|
409
|
+
"""
|
|
410
|
+
try:
|
|
411
|
+
if haspyqtgraph:
|
|
412
|
+
timer = pg.QtCore.QTimer()
|
|
413
|
+
timer.timeout.connect(update)
|
|
414
|
+
timer.start(1) # Delay not needed because update has time.sleep
|
|
415
|
+
if (sys.flags.interactive != 1) or not hasattr(pg.QtCore, "PYQT_VERSION"):
|
|
416
|
+
sys.exit(pg.QtGui.QApplication.instance().exec_())
|
|
417
|
+
else:
|
|
418
|
+
while True:
|
|
419
|
+
update()
|
|
420
|
+
|
|
421
|
+
except KeyboardInterrupt:
|
|
422
|
+
# No cleanup necessary?
|
|
423
|
+
pass
|
pylsl/examples/README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
If pylsl was installed with `pip install pylsl` (recommended), then you can run each of these examples with `python -m pylsl.examples.name_of_example`.
|
|
2
|
+
|
|
3
|
+
There are few other noteworthy uses of pylsl in the wild. These might give you some inspiration or direct examples of how to use pylsl in your project.
|
|
4
|
+
|
|
5
|
+
* [mne-realtime examples](https://github.com/mne-tools/mne-realtime/tree/master/examples)
|
|
6
|
+
* [NeuroPype](https://www.neuropype.io/)
|
|
7
|
+
* [Sig-Visualizer](https://github.com/labstreaminglayer/App-SigVisualizer)
|
|
8
|
+
* [Pupil-Labs has 2 different pylsl uses](https://github.com/labstreaminglayer/App-PupilLabs)
|
|
9
|
+
* [@agricolab's pyliesl](https://github.com/pyreiz/pyliesl) makes use of some less-common features of LSL and XDF.
|
|
10
|
+
* [muse-lsl](https://github.com/alexandrebarachant/muse-lsl)
|