Episode 1: Saving Data
In this episode, you learn how to save EEG data to a file using g.Pype.
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_file_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 * Columns 0-7: Signal data from 8 channels
20 * Column 8: Event markers (38=Up, 39=Right, 40=Down, 37=Left)
21 * Automatic timestamp in filename prevents overwrites
22
23Interactive controls:
24- Arrow keys trigger colored markers in the display:
25 * ↑ (Up): Red marker (value 38)
26 * → (Right): Green marker (value 39)
27 * ↓ (Down): Blue marker (value 40)
28 * ← (Left): Black marker (value 37)
29
30Real-world applications:
31- BCI training data collection
32- Event-related potential (ERP) experiments
33- Motor imagery paradigm recording
34- Behavioral experiment data logging
35- Synchronizing neural and behavioral data
36
37Technical details:
38- Router combines 8 signal channels + 1 event channel = 9 total channels
39- FileWriter automatically adds timestamps to prevent file overwrites
40- Keyboard node converts key presses to numerical event codes
41- Markers appear on channel 8 in both display and saved file
42
43Usage:
44 python example_basic_file_writer_record.py
45 Press arrow keys to create event markers
46 Close window to stop recording
47"""
48import gpype as gp
49
50fs = 250 # Sampling frequency in Hz
51
52if __name__ == "__main__":
53 # Create the main application window
54 app = gp.MainApp()
55
56 # Create processing pipeline
57 p = gp.Pipeline()
58
59 # Generate synthetic 8-channel EEG-like signals
60 source = gp.Generator(
61 sampling_rate=fs,
62 channel_count=8, # 8 EEG channels
63 signal_frequency=10, # 10 Hz alpha-like rhythm
64 signal_amplitude=10, # Signal strength
65 signal_shape="sine", # Clean sine waves
66 noise_amplitude=10,
67 ) # Realistic noise level
68
69 # Capture keyboard input as event markers
70 keyboard = gp.Keyboard() # Arrow keys -> event codes
71
72 # Combine signal data (8 channels) + event data (1 channel) = 9 channels
73 router = gp.Router(input_selector=[gp.Router.ALL, gp.Router.ALL])
74
75 # Define colored markers for visualization (values korrespond to arrows)
76 mk = gp.TimeSeriesScope.Markers
77 markers = [
78 mk(color="r", label="up", channel=8, value=38),
79 mk(color="g", label="right", channel=8, value=39),
80 mk(color="b", label="down", channel=8, value=40),
81 mk(color="k", label="left", channel=8, value=37),
82 ]
83
84 # Real-time display with event markers
85 scope = gp.TimeSeriesScope(
86 amplitude_limit=30, # Y-axis range
87 time_window=10, # 10 seconds history
88 markers=markers,
89 ) # Show event markers
90
91 # CSV file writer (auto-timestamped filename)
92 writer = gp.FileWriter(file_name="example_writer.csv")
93
94 # Connect processing chain
95 p.connect(source, router["in1"]) # Signal data -> Router input 1
96 p.connect(keyboard, router["in2"]) # Event data -> Router input 2
97 p.connect(router, scope) # Combined data -> Display
98 p.connect(router, writer) # Combined data -> File
99
100 # Add scope to application window
101 app.add_widget(scope)
102
103 # Start recording and visualization
104 p.start()
105 app.run()
106 p.stop()
File example_basic_file_writer_plot.py (plot recorded data) – View file on GitHub
1"""
2Basic File Plot Example - Offline Data Analysis and Visualization
3
4This example demonstrates how to load and visualize data recorded from g.Pype
5FileWriter nodes. It complements example_basic_file_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 FileWriter
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_file_writer_record.py containing:
17- Column 0: Sample index (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- Professional EEG-style visualization format
27
28Workflow:
291. Run example_basic_file_writer_record.py to create data
302. Press arrow keys to generate event markers during recording
313. Close recording window to save CSV file
324. Run this script to visualize the recorded data
33
34Real-world applications:
35- Offline BCI data analysis
36- Event-related potential (ERP) visualization
37- Quality assessment of recorded data
38- Validating experimental paradigms
39
40Usage:
41 python example_basic_file_writer_plot.py
42
43Dependencies:
44 - pandas (data loading and manipulation)
45 - matplotlib (plotting and visualization)
46"""
47import pandas as pd
48import matplotlib.pyplot as plt
49import glob
50import os
51
52# Find the most recent CSV file from g.Pype recordings
53csv_files = glob.glob("example_writer*.csv")
54if not csv_files:
55 raise FileNotFoundError("No CSV files starting with 'example_' found.")
56file_path = max(csv_files, key=os.path.getmtime) # Most recent file
57
58# Load recorded data into pandas DataFrame
59data = pd.read_csv(file_path)
60
61# Extract time index and channel data
62index = data["Index"] # Sample timestamps
63channels = data.columns[1:] # All data columns (signals + events)
64
65# Create multi-channel EEG-style plot
66plt.figure(figsize=(10, 6))
67
68# Channel stacking parameters for clear visualization
69offset = -100 # Vertical spacing between channels
70yticks = [] # Y-axis tick positions
71yticklabels = [] # Y-axis tick labels
72
73# Plot each channel with vertical offset
74for i, ch in enumerate(channels):
75 channel_offset = i * offset
76 plt.plot(index, data[ch] + channel_offset, label=ch)
77 yticks.append(channel_offset)
78 yticklabels.append(f"Ch{i + 1}")
79
80# Configure plot appearance
81plt.yticks(yticks, yticklabels)
82plt.xlabel("Sample Index")
83plt.title("EEG Recordings")
84plt.grid(True, axis="y", linestyle="--", alpha=0.6)
85plt.ylim((len(channels)) * offset, -offset)
86
87# Display the plot
88plt.tight_layout()
89plt.show()