Episode 9: Into MNE-Python
Hand a recording to MNE-Python through a Result, in volts, with its channel types and its markers, and let the bridge refuse a file that cannot say what its numbers mean.
MNE-Python is where much EEG analysis happens. It wants data in volts, a type per channel and events as annotations or as a stim channel; this script gives both. A Result carries all of that, if the recording did; this episode builds an mne.io.RawArray from one, and shows what happens when it did not. MNE is not a g.Pype dependency: pip install mne first.
A Generator measures nothing, so the script says what its channels stand for: microvolts for the four signals, and no unit for the marker channel, which carries codes rather than a physical quantity. A ChannelLabeler writes both the names and the units into the stream, and the recording goes to HDF5 and to CSV at once.
23#: A Generator measures nothing, so say what it stands for. A marker
24#: channel carries codes, not a physical quantity, so it has no unit.
25UNITS = ["uV", "uV", "uV", "uV", None]
26#: What each role becomes in MNE. Any other role is refused.
27MNE_TYPES = {"signal": "eeg", "trigger": "stim"}
36def record() -> None:
37 """Record under three seconds and three markers, as Episode 7 does."""
38 p = gp.Pipeline()
39 source = gp.Generator(sampling_rate=RATE, channel_count=4,
40 signal_frequency=10, signal_amplitude=20.0,
41 noise_amplitude=2.0)
42 marker = gp.Marker()
43 both = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
44 described = gp.ChannelLabeler(labels=LABELS, units=UNITS)
45 p.connect(source, both["in1"])
46 p.connect(marker, both["in2"])
47 p.connect(both, described)
48 stem = os.path.join(OUT, "s4e9")
49 p.connect(described, gp.HDF5Writer(file_name=stem + ".h5"))
50 p.connect(described, gp.CsvWriter(file_name=stem + ".csv"))
51 p.start()
52 time.sleep(0.8)
53 for code in (1, 2, 1):
54 marker.emit(code)
55 time.sleep(0.6)
56 p.stop()
57 p.close()
result.si_scale is the factor that takes each channel to its SI unit, 1e-6 for microvolts, and None where the unit is unknown. The bridge refuses a result that records no units at all rather than guess microvolts. Then, per channel, the role picks the MNE type: a signal becomes eeg and is scaled to volts by its own factor; a trigger becomes stim and passes through unscaled, as MNE expects; any other role is refused.
78 if result.si_scale is None:
79 raise ValueError(
80 "this recording records no units, so its scale is unknown. "
81 "A missing unit is not taken to be microvolts: record with "
82 "ChannelLabeler(units=...) or an amplifier source, to a "
83 "format that keeps them."
84 )
85 types, factors = [], []
86 for channel in result.channels:
87 if channel.role not in MNE_TYPES:
88 raise ValueError(
89 f"channel {channel.name!r} has role {channel.role!r}; "
90 f"select the signal and trigger channels first."
91 )
92 types.append(MNE_TYPES[channel.role])
93 if channel.role == "trigger":
94 factors.append(1.0)
95 elif channel.si_scale is None:
96 raise ValueError(
97 f"channel {channel.name!r} has unit {channel.unit!r}, "
98 f"which g.Pype cannot put in volts."
99 )
100 else:
101 factors.append(channel.si_scale)
MNE wants channels as rows, so the data is transposed and scaled; create_info takes the labels, the rate and the types; and the result’s events, each a sample, a duration and a label, become annotations with onsets in seconds.
103 data = result.data.T * np.asarray(factors)[:, None]
104 info = mne.create_info(result.labels, result.rate, types)
105 raw = mne.io.RawArray(data, info, verbose=False)
106 raw.set_annotations(mne.Annotations(
107 onset=[event.sample / result.rate for event in result.events],
108 duration=[event.duration / result.rate for event in result.events],
109 description=[event.label for event in result.events],
110 ))
111 return raw
The HDF5 copy, read in a batch run, carries labels, roles, units and events, and goes through the bridge.
118 # 1. A recording that kept its units
119 result = read(gp.HDF5Reader(file_name=newest(".h5"), mode="batch",
120 variable_name="data", has_time_row=True))
121 print("units :", result.units)
122 print("si_scale :", result.si_scale)
123
124 raw = to_mne(result)
125 print()
126 print(raw)
127 print("types :", raw.get_channel_types())
128 notes = raw.annotations
129 print("markers :", dict(zip(notes.onset.round(3).tolist(),
130 notes.description.tolist())))
131 print("Cz, first samples in volts:", raw.get_data(picks="Cz")[0, :3])
The CSV copy of the same recording stores no units and no roles, so its Result says so, and the bridge refuses it.
133 # 2. One that did not: a CSV stores no units and no roles, so its
134 # Result says so, and the bridge refuses it instead of guessing
135 print()
136 try:
137 to_mne(read(gp.CsvReader(file_name=newest(".csv"), mode="batch")))
138 except ValueError as error:
139 print("ValueError:", error)
Run the script. The first half prints the units and scale factors, the Raw, its channel types, the markers as annotations and the first samples of Cz in volts; the second half prints the refusal:
units : ['uV', 'uV', 'uV', 'uV', None]
si_scale : [1e-06, 1e-06, 1e-06, 1e-06, None]
<RawArray | 5 x ... (... s), ~... kB, data loaded>
types : ['eeg', 'eeg', 'eeg', 'eeg', 'stim']
markers : {<time>: '1', <time>: '2', <time>: '1'}
Cz, first samples in volts: [...]
ValueError: this recording records no units, so its scale is unknown. ...
A missing unit is not taken to be microvolts. Record with ChannelLabeler(units=...) or an amplifier source, to a format that keeps them.
In this episode, you learned how to:
record units with a ChannelLabeler, and read them back as
si_scalebuild an MNE Raw from a Result: volts by unit, type by role, events as annotations
refuse a recording that cannot say what its numbers mean
Proceed to Episode 10, where a scikit-learn classifier is fitted on a recording and deployed the way a running pipeline calls it.
Nodes in this episode: Generator, Marker, Router, ChannelLabeler, HDF5Writer, CsvWriter, HDF5Reader, CsvReader, Collector
File s4e9_into_mne.py – View file on GitHub
1"""Season 4, Episode 9: a recording handed to MNE-Python, in volts.
2
3Records four named channels and a marker channel, with their units, to
4HDF5 and to CSV. The HDF5 copy becomes an mne.io.RawArray: signal
5channels as EEG in volts, the trigger as a stim channel, its markers as
6annotations. The CSV copy stores no units, and the bridge refuses it
7rather than guess microvolts. Requires mne: pip install mne
8"""
9
10import glob
11import os
12import tempfile
13import time
14
15import mne
16import numpy as np
17
18import gpype as gp
19
20RATE = 250
21OUT = tempfile.gettempdir()
22LABELS = ["Fz", "C3", "Cz", "C4", "marker"]
23#: A Generator measures nothing, so say what it stands for. A marker
24#: channel carries codes, not a physical quantity, so it has no unit.
25UNITS = ["uV", "uV", "uV", "uV", None]
26#: What each role becomes in MNE. Any other role is refused.
27MNE_TYPES = {"signal": "eeg", "trigger": "stim"}
28
29
30def newest(extension: str) -> str:
31 """The file a writer produced last; writers timestamp their names."""
32 pattern = os.path.join(OUT, f"s4e9_*{extension}")
33 return sorted(glob.glob(pattern))[-1]
34
35
36def record() -> None:
37 """Record under three seconds and three markers, as Episode 7 does."""
38 p = gp.Pipeline()
39 source = gp.Generator(sampling_rate=RATE, channel_count=4,
40 signal_frequency=10, signal_amplitude=20.0,
41 noise_amplitude=2.0)
42 marker = gp.Marker()
43 both = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
44 described = gp.ChannelLabeler(labels=LABELS, units=UNITS)
45 p.connect(source, both["in1"])
46 p.connect(marker, both["in2"])
47 p.connect(both, described)
48 stem = os.path.join(OUT, "s4e9")
49 p.connect(described, gp.HDF5Writer(file_name=stem + ".h5"))
50 p.connect(described, gp.CsvWriter(file_name=stem + ".csv"))
51 p.start()
52 time.sleep(0.8)
53 for code in (1, 2, 1):
54 marker.emit(code)
55 time.sleep(0.6)
56 p.stop()
57 p.close()
58
59
60def read(reader) -> gp.Result:
61 """Read a whole recording in one batch run."""
62 with gp.Pipeline() as p:
63 p.connect(reader, gp.Collector())
64 return p.run()
65
66
67def to_mne(result: gp.Result) -> mne.io.RawArray:
68 """Build an MNE Raw from a Result, or refuse.
69
70 Signal channels are scaled to volts by their own unit; trigger codes
71 pass through unscaled, as MNE expects of a stim channel.
72
73 Raises:
74 ValueError: If the result records no units, if a signal channel's
75 unit is not one g.Pype can scale, or if a channel has a role
76 MNE_TYPES does not map.
77 """
78 if result.si_scale is None:
79 raise ValueError(
80 "this recording records no units, so its scale is unknown. "
81 "A missing unit is not taken to be microvolts: record with "
82 "ChannelLabeler(units=...) or an amplifier source, to a "
83 "format that keeps them."
84 )
85 types, factors = [], []
86 for channel in result.channels:
87 if channel.role not in MNE_TYPES:
88 raise ValueError(
89 f"channel {channel.name!r} has role {channel.role!r}; "
90 f"select the signal and trigger channels first."
91 )
92 types.append(MNE_TYPES[channel.role])
93 if channel.role == "trigger":
94 factors.append(1.0)
95 elif channel.si_scale is None:
96 raise ValueError(
97 f"channel {channel.name!r} has unit {channel.unit!r}, "
98 f"which g.Pype cannot put in volts."
99 )
100 else:
101 factors.append(channel.si_scale)
102
103 data = result.data.T * np.asarray(factors)[:, None]
104 info = mne.create_info(result.labels, result.rate, types)
105 raw = mne.io.RawArray(data, info, verbose=False)
106 raw.set_annotations(mne.Annotations(
107 onset=[event.sample / result.rate for event in result.events],
108 duration=[event.duration / result.rate for event in result.events],
109 description=[event.label for event in result.events],
110 ))
111 return raw
112
113
114if __name__ == "__main__":
115
116 record()
117
118 # 1. A recording that kept its units
119 result = read(gp.HDF5Reader(file_name=newest(".h5"), mode="batch",
120 variable_name="data", has_time_row=True))
121 print("units :", result.units)
122 print("si_scale :", result.si_scale)
123
124 raw = to_mne(result)
125 print()
126 print(raw)
127 print("types :", raw.get_channel_types())
128 notes = raw.annotations
129 print("markers :", dict(zip(notes.onset.round(3).tolist(),
130 notes.description.tolist())))
131 print("Cz, first samples in volts:", raw.get_data(picks="Cz")[0, :3])
132
133 # 2. One that did not: a CSV stores no units and no roles, so its
134 # Result says so, and the bridge refuses it instead of guessing
135 print()
136 try:
137 to_mne(read(gp.CsvReader(file_name=newest(".csv"), mode="batch")))
138 except ValueError as error:
139 print("ValueError:", error)