Episode 1: Saving Data
Record the signal and the key presses to a CSV file with a CsvWriter, and read the file back.
Everything a scope shows is gone when its window closes, unless a writer puts it on disk. This episode adds one writer to a pipeline you already know.
The pipeline of Season 3, Episode 6, unchanged: a Generator, a Keyboard, a Router that puts the key codes on channel 8, and a TimeSeriesScope with a marker per arrow key.
7 app = gp.MainApp()
8 p = gp.Pipeline()
9
10 source = gp.Generator(sampling_rate=250, channel_count=8,
11 signal_frequency=10, signal_amplitude=10,
12 noise_amplitude=10)
13 keyboard = gp.Keyboard()
14 router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
15
16 mk = gp.TimeSeriesScope.Markers
17 markers = [mk(color="r", label="up", channel=8, value=38),
18 mk(color="g", label="right", channel=8, value=39),
19 mk(color="c", label="down", channel=8, value=40),
20 mk(color="y", label="left", channel=8, value=37)]
21 scope = gp.TimeSeriesScope(amplitude_limit=30, time_window=10,
22 markers=markers, hidden_channels=[8])
A CsvWriter is a sink, like a scope: connect it to whatever you want to keep. Here it hangs off the same Router output as the scope, so the file holds exactly what the scope shows, eight signal channels and the key codes on a ninth. The name you give is a pattern: the writer adds the date and time, so s4e1.csv becomes s4e1_<date>_<time>.csv in the folder the script runs from, and two runs never overwrite each other.
24 # The writer adds the date and time to the name, so every run
25 # writes a new file into the folder the script runs from
26 writer = gp.CsvWriter(file_name="s4e1.csv")
27
28 p.connect(source, router["in1"])
29 p.connect(keyboard, router["in2"])
30 p.connect(router, scope)
31 p.connect(router, writer) # the file holds what the scope shows
32 app.add_widget(scope)
Run the script, press a few arrow keys, and close the window. The scope looks as it did in Season 3; what is new is the file beside the script.
Figure 32: The scope while the file is being written.
The file opens with a comment line and a header, then one row per sample:
# NON-COMMERCIAL USE
Time, Ch01, Ch02, Ch03, Ch04, Ch05, Ch06, Ch07, Ch08, Ch09
Timecounts seconds from the first sample, 0.004 s apart at 250 Hz.The channels are called
Ch01onwards unless you name them, as Season 2, Episode 9 does.A key code sits on the row of the sample it was pressed on, and the column reads 0 everywhere else.
The first line is the non-commercial mark, there unless a g.Pype Runtime licence is held on this computer. It is a label on the file, not an error.
The second file plots the newest recording with pandas and matplotlib, which g.Pype does not install. Reading the file takes two arguments: comment="#" skips the mark, which pandas would otherwise take as the header, and skipinitialspace=True drops the space after each comma, without which the second column is called " Ch01" and data["Ch01"] raises a KeyError. For values exact to the last digit, add float_precision="round_trip"; Episode 7 goes through reading a recording into pandas in full.
15 # The newest file the recorder wrote into this folder
16 files = glob.glob("s4e1_*.csv")
17 if not files:
18 raise FileNotFoundError(f"no s4e1_*.csv in {os.getcwd()}")
19 path = max(files, key=os.path.getmtime)
20
21 # The file opens with comment lines, and its header puts a space
22 # after each comma. Without these two arguments pandas takes the
23 # first comment line as the header, and names a column " Ch01"
24 data = pd.read_csv(path, comment="#", skipinitialspace=True)
The rest stacks one lane per channel; the last lane carries the key codes.
26 time = data["Time"]
27 channels = data.columns[1:]
28
29 # One lane per channel, stacked with a fixed offset; the last lane
30 # carries the key codes
31 offset = -100
32 plt.figure(figsize=(10, 6))
33 for i, ch in enumerate(channels):
34 plt.plot(time, data[ch] + i * offset, label=ch)
35 plt.yticks([i * offset for i in range(len(channels))], channels)
36 plt.xlabel("Time (s)")
37 plt.title(os.path.basename(path))
38 plt.grid(True, axis="y", linestyle="--", alpha=0.6)
39 plt.ylim(len(channels) * offset, -offset)
40 plt.tight_layout()
41 plt.show()
Every value is written as text, to 17 significant digits, so the file is the largest of the formats g.Pype writes. And it stores no channel roles: read back into g.Pype, the key-code channel is a plain signal again, and a filter would smear it. Episode 5 compares the formats that keep more.
In this episode, you learned how to:
record what a scope shows with a CsvWriter off the same output
read the file’s name pattern and its first lines
load a recording into pandas with the two arguments it needs
Proceed to Episode 2, where the same pipeline publishes its output as an LSL stream instead of writing a file.
Nodes in this episode: Generator, Keyboard, Router, TimeSeriesScope, CsvWriter
File s4e1_saving_data.py – View file on GitHub
1"""Season 4, Episode 1: signal and key presses recorded to a CSV file."""
2
3import gpype as gp
4
5if __name__ == "__main__":
6
7 app = gp.MainApp()
8 p = gp.Pipeline()
9
10 source = gp.Generator(sampling_rate=250, channel_count=8,
11 signal_frequency=10, signal_amplitude=10,
12 noise_amplitude=10)
13 keyboard = gp.Keyboard()
14 router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
15
16 mk = gp.TimeSeriesScope.Markers
17 markers = [mk(color="r", label="up", channel=8, value=38),
18 mk(color="g", label="right", channel=8, value=39),
19 mk(color="c", label="down", channel=8, value=40),
20 mk(color="y", label="left", channel=8, value=37)]
21 scope = gp.TimeSeriesScope(amplitude_limit=30, time_window=10,
22 markers=markers, hidden_channels=[8])
23
24 # The writer adds the date and time to the name, so every run
25 # writes a new file into the folder the script runs from
26 writer = gp.CsvWriter(file_name="s4e1.csv")
27
28 p.connect(source, router["in1"])
29 p.connect(keyboard, router["in2"])
30 p.connect(router, scope)
31 p.connect(router, writer) # the file holds what the scope shows
32 app.add_widget(scope)
33
34 p.start()
35 app.run()
36 p.stop()
37 p.close()
File s4e1_plot_recording.py – View file on GitHub
1"""Season 4, Episode 1: the newest recording, plotted with pandas.
2
3Neither pandas nor matplotlib is a g.Pype dependency:
4pip install pandas matplotlib
5"""
6
7import glob
8import os
9
10import matplotlib.pyplot as plt
11import pandas as pd
12
13if __name__ == "__main__":
14
15 # The newest file the recorder wrote into this folder
16 files = glob.glob("s4e1_*.csv")
17 if not files:
18 raise FileNotFoundError(f"no s4e1_*.csv in {os.getcwd()}")
19 path = max(files, key=os.path.getmtime)
20
21 # The file opens with comment lines, and its header puts a space
22 # after each comma. Without these two arguments pandas takes the
23 # first comment line as the header, and names a column " Ch01"
24 data = pd.read_csv(path, comment="#", skipinitialspace=True)
25
26 time = data["Time"]
27 channels = data.columns[1:]
28
29 # One lane per channel, stacked with a fixed offset; the last lane
30 # carries the key codes
31 offset = -100
32 plt.figure(figsize=(10, 6))
33 for i, ch in enumerate(channels):
34 plt.plot(time, data[ch] + i * offset, label=ch)
35 plt.yticks([i * offset for i in range(len(channels))], channels)
36 plt.xlabel("Time (s)")
37 plt.title(os.path.basename(path))
38 plt.grid(True, axis="y", linestyle="--", alpha=0.6)
39 plt.ylim(len(channels) * offset, -offset)
40 plt.tight_layout()
41 plt.show()