EEG Data in Python: NumPy and pandas
The samples are always a NumPy array shaped (time, channel) in
float32, with the channel labels, roles, units and rate beside them.
There are three ways to get hold of it, and which one you want depends on
when you want it.
Live, in memory
A Collector at the end of a realtime pipeline keeps every frame it
receives. Read it after stop():
import time
import gpype as gp
p = gp.Pipeline()
source = gp.BCICore() # or gp.Generator(sampling_rate=250, channel_count=8)
collector = gp.Collector()
p.connect(source, collector)
p.start()
time.sleep(10)
p.stop()
result = collector.result # a gp.Result
data = result.to_numpy() # (2500, 8) float32, in µV
print(result.rate, result.labels, result.units)
The collector grows for as long as the pipeline runs, which is right for a measurement of seconds or minutes and wrong for a session of hours; record those to a file instead.
Live, frame by frame
For a decision on every frame, a sink of your own receives each frame as
it arrives, (frame, channel), on the pipeline’s thread:
class Printer(gp.Sink):
def step(self, data):
frame = data["in"] # (4, 8) at 250 Hz in frames of 4
print(frame.mean(axis=0))
setup() tells it the rate, the labels and the frame size before the
first frame. Season 7, Episode 3 writes a
source and a sink this way, and Threads, Frames and Propagation says what runs where.
From a recording
A reader in batch mode and a Collector, driven by run(), hand back
the whole file at once:
with gp.Pipeline() as p:
reader = gp.HDF5Reader(file_name="session.h5", mode="batch")
p.connect(reader, gp.Collector())
result = p.run()
result.data # (time, channel), float32
result.times # seconds from the first sample
result.start_time # absolute, where the file records it
result.events # markers, as sample positions
result.to_si() # volts for EEG, SI for the rest
frame = result.to_dataframe() # pandas, time-indexed, one column per channel
Any processing can sit between the reader and the collector, and
result.plot() draws it. Season 2, Episode 16
and Season 4, Episode 7
are the walk-throughs; Offline Processing
explains what a batch run does and refuses.
What “raw” means here
The samples are what the driver delivered, in microvolts for every amplifier, before any node you add: no filter, no reference, no scaling. The arrival-stamp channel every live source appends is stripped before the first node you connect, so the array is the device’s width. The layout of each field is in Data Structures.