Episode 1: Saving Data
Learn how to store recorded EEG data to disk. This episode shows how to save EEG data and later reload them for analysis or visualization.
Note
This page is still under development. Until we have the step-by-step instructions ready, please refer to the code example below.
File example_basic_csv_writer_record.py (write recorded data) – View file on GitHub
1"""
2Basic File Writer Example - Data Recording with Event Markers
3
4This example demonstrates how to record data to CSV files while capturing
5event markers from keyboard input. This is essential for BCI experiments
6where you need to save both neural signals and behavioral events for
7offline analysis.
8
9What this example shows:
10- Generating synthetic EEG-like signals (8 channels)
11- Capturing keyboard events as experimental markers
12- Combining signal data with event markers using Router
13- Real-time visualization with color-coded event markers
14- Saving all data (signals + events) to CSV file with timestamps
15
16Expected output:
17- Real-time scope showing 8-channel signals with event markers
18- CSV file 'example_YYYYMMDD_HHMMSS.csv' containing:
19 * Column 1: Timestamp
20 * Columns 1-8: Signal data from 8 channels
21 * Column 9: Event markers (38=Up, 39=Right, 40=Down, 37=Left)
22 * Automatic timestamp in filename prevents overwrites
23
24Interactive controls:
25- Arrow keys trigger colored markers in the display:
26 * ↑ (Up): Red marker (value 38)
27 * → (Right): Green marker (value 39)
28 * ↓ (Down): Blue marker (value 40)
29 * ← (Left): Black marker (value 37)
30
31Real-world applications:
32- BCI training data collection
33- Event-related potential (ERP) experiments
34- Motor imagery paradigm recording
35- Behavioral experiment data logging
36- Synchronizing neural and behavioral data
37
38Technical details:
39- Router combines 8 signal channels + 1 event channel = 9 total channels
40- CsvWriter automatically adds timestamps to prevent file overwrites
41- Keyboard node converts key presses to numerical event codes
42- Markers appear on channel 8 in both display and saved file
43
44Usage:
45 python example_basic_file_writer_record.py
46 Press arrow keys to create event markers
47 Close window to stop recording
48"""
49import gpype as gp
50
51fs = 250 # Sampling frequency in Hz
52
53if __name__ == "__main__":
54 # Create the main application window
55 app = gp.MainApp()
56
57 # Create processing pipeline
58 p = gp.Pipeline()
59
60 # Generate synthetic 8-channel EEG-like signals
61 source = gp.Generator(
62 sampling_rate=fs,
63 channel_count=8, # 8 EEG channels
64 signal_frequency=10, # 10 Hz alpha-like rhythm
65 signal_amplitude=10, # Signal strength
66 signal_shape="sine", # Clean sine waves
67 noise_amplitude=10,
68 ) # Realistic noise level
69
70 # Capture keyboard input as event markers
71 keyboard = gp.Keyboard() # Arrow keys -> event codes
72
73 # Combine signal data (8 channels) + event data (1 channel) = 9 channels
74 router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
75
76 # Define colored markers for visualization (values korrespond to arrows)
77 mk = gp.TimeSeriesScope.Markers
78 markers = [
79 mk(color="r", label="up", channel=8, value=38),
80 mk(color="g", label="right", channel=8, value=39),
81 mk(color="b", label="down", channel=8, value=40),
82 mk(color="k", label="left", channel=8, value=37),
83 ]
84
85 # Real-time display with event markers
86 scope = gp.TimeSeriesScope(
87 amplitude_limit=30, # Y-axis range
88 time_window=10, # 10 seconds history
89 markers=markers,
90 ) # Show event markers
91
92 # CSV file writer (auto-timestamped filename)
93 writer = gp.CsvWriter(file_name="example_writer.csv")
94
95 # Connect processing chain
96 p.connect(source, router["in1"]) # Signal data -> Router input 1
97 p.connect(keyboard, router["in2"]) # Event data -> Router input 2
98 p.connect(router, scope) # Combined data -> Display
99 p.connect(router, writer) # Combined data -> File
100
101 # Add scope to application window
102 app.add_widget(scope)
103
104 # Start recording and visualization
105 p.start()
106 app.run()
107 p.stop()
File example_basic_csv_writer_plot.py (plot recorded data) – View file on GitHub
1"""
2Basic CSV Plot Example - Offline Data Analysis and Visualization
3
4This example demonstrates how to load and visualize data recorded from g.Pype
5CsvWriter nodes. It complements example_basic_csv_writer_record.py by showing
6how to analyze the recorded data offline using standard Python tools.
7
8What this example shows:
9- Loading CSV files created by g.Pype CsvWriter
10- Automatically finding the most recent recording file
11- Creating multi-channel EEG-style plots with proper scaling
12- Visualizing both signal data and event markers
13- Using matplotlib for BCI data visualization
14
15Expected input:
16CSV files generated by example_basic_csv_writer_record.py containing:
17- Column 0: Timestamp
18- Columns 1-8: Signal data from 8 channels
19- Column 9: Event markers (keyboard events: 37,38,39,40)
20
21Expected output:
22Multi-channel plot displaying:
23- 8 signal channels stacked vertically with offset
24- Event markers visible as spikes in the bottom channel
25- Proper channel labeling and grid lines
26
27Workflow:
281. Run example_basic_csv_writer_record.py to create data
292. Press arrow keys to generate event markers during recording
303. Close recording window to save CSV file
314. Run this script to visualize the recorded data
32
33Real-world applications:
34- Offline BCI data analysis
35- Event-related potential (ERP) visualization
36- Quality assessment of recorded data
37- Validating experimental paradigms
38
39Usage:
40 python example_basic_csv_writer_plot.py
41
42Dependencies:
43 - pandas (data loading and manipulation)
44 - matplotlib (plotting and visualization)
45"""
46import pandas as pd
47import matplotlib.pyplot as plt
48import glob
49import os
50
51# Find the most recent CSV file from g.Pype recordings
52csv_files = glob.glob("example_writer*.csv")
53if not csv_files:
54 raise FileNotFoundError("No CSV files starting with 'example_' found.")
55file_path = max(csv_files, key=os.path.getmtime) # Most recent file
56
57# Load recorded data into pandas DataFrame
58data = pd.read_csv(file_path)
59
60# Extract time index and channel data
61time = data["Time"] # Sample timestamps
62channels = data.columns[1:] # All data columns (signals + events)
63
64# Create multi-channel EEG-style plot
65plt.figure(figsize=(10, 6))
66
67# Channel stacking parameters for clear visualization
68offset = -100 # Vertical spacing between channels
69yticks = [] # Y-axis tick positions
70yticklabels = [] # Y-axis tick labels
71
72# Plot each channel with vertical offset
73for i, ch in enumerate(channels):
74 channel_offset = i * offset
75 plt.plot(time, data[ch] + channel_offset, label=ch)
76 yticks.append(channel_offset)
77 yticklabels.append(f"Ch{i + 1}")
78
79# Configure plot appearance
80plt.yticks(yticks, yticklabels)
81plt.xlabel("Time (s)")
82plt.title("EEG Recordings")
83plt.grid(True, axis="y", linestyle="--", alpha=0.6)
84plt.ylim((len(channels)) * offset, -offset)
85
86# Display the plot
87plt.tight_layout()
88plt.show()