Episode 7: From a Run into pandas
Read the same recording into pandas by hand and through a Result, and see what a DataFrame cannot carry.
Most analysis ends up in pandas. A recording gets there two ways: read the file yourself and rebuild what it only half says, or let g.Pype read it and hand you a Result, whose to_dataframe() does the bookkeeping. This episode does both on one recording. pandas is not a g.Pype dependency: pip install pandas first.
Four named channels and a Marker, merged by a Router and named by a ChannelLabeler, written to CSV and to HDF5 at once. The script fires three markers itself, standing in for a paradigm, so the recording has events to find.
27def record() -> None:
28 """Record four channels and a marker channel to CSV and HDF5."""
29 p = gp.Pipeline()
30 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=4,
31 signal_frequency=10, signal_amplitude=20.0,
32 noise_amplitude=2.0)
33 # Markers fired by this script, standing in for a paradigm
34 marker = gp.Marker()
35 both = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
36 names = gp.ChannelLabeler(labels=LABELS)
37 p.connect(source, both["in1"])
38 p.connect(marker, both["in2"])
39 p.connect(both, names)
40 p.connect(names, gp.CsvWriter(file_name=os.path.join(OUT, "s4e7.csv")))
41 p.connect(names, gp.HDF5Writer(file_name=os.path.join(OUT, "s4e7.h5")))
42 p.start()
43 time.sleep(0.8)
44 for code in (1, 2, 1):
45 marker.emit(code)
46 time.sleep(0.5)
47 time.sleep(0.2)
48 p.stop()
49 p.close()
pandas has to be told four things the file only half says. It opens with comment lines, so comment="#". Its header separates names with a comma and a space, so skipinitialspace=True. Values are written to 17 significant digits, and pandas’ default float parser can misread the last one, so float_precision="round_trip". And the time is a column, which becomes the index only when you make it one.
64 # 1. By hand. The file opens with comment lines, its header separates
65 # names with ", ", pandas' default float parser can misread the 17th
66 # digit g.Pype writes, and the time only becomes the index if you
67 # make it one
68 by_hand = pd.read_csv(csv, comment="#", skipinitialspace=True,
69 float_precision="round_trip")
70 by_hand = by_hand.set_index("Time")
A CsvReader in batch mode and a Collector hand back a Result that already knows the columns, the rate and the time axis, and to_dataframe() is one call.
72 # 2. Through a Result: the reader already knows the columns, the
73 # rate and the time axis
74 result = read(gp.CsvReader(file_name=csv, mode="batch"))
75 from_result = result.to_dataframe()
Run the script. It prints the first rows of both frames, then three comparisons, all True: same columns, same values, same times. The values are the same; the types are not. pandas makes the marker column an integer and the rest float64, while the Result keeps the pipeline’s own 32-bit floats. A DataFrame then answers questions a flat array does not, such as every row a marker is on, with its time:
markers: {<time>: 1, <time>: 2, <time>: 1}
Which column is the trigger. A DataFrame has no notion of it, and a CSV stores no roles, so the CSV’s Result calls every column a signal. The HDF5 copy of the same recording kept them, and the script reads it to show the difference.
95 # 3. What the frame cannot say: which column is the trigger. A CSV
96 # stores no roles, so its Result calls every column a signal; the
97 # HDF5 copy of the same recording kept them
98 twin = read(gp.HDF5Reader(file_name=newest("s4e7", ".h5"),
99 mode="batch", variable_name="data",
100 has_time_row=True))
101 print()
102 print("result.roles, from the .csv :", result.roles)
103 print("result.roles, from the .h5 :", twin.roles)
104 print("the trigger column :",
105 [c.name for c in twin.channels if c.role == "trigger"])
106 print("result.times[:3] :", twin.times[:3])
107 print("result.channels[-1] :", twin.channels[-1])
Roles are what keeps a filter off the marker channel, and they live in the Result, not in the DataFrame: to_dataframe() keeps the labels and the time axis and leaves the roles behind. result.channels gives name, role and unit per channel; a unit of None means the source recorded none, which is not the same as dimensionless. result.times is seconds from the first sample, and where the file records one, result.start_time is the absolute time of sample zero. The Result reference lists the rest.
Proceed to Episode 8, where the stream comes in from a program that is not g.Pype, over LSL.
Nodes in this episode: Generator, Marker, Router, ChannelLabeler, CsvWriter, HDF5Writer, CsvReader, HDF5Reader, Collector
File s4e7_from_a_run_into_pandas.py – View file on GitHub
1"""Season 4, Episode 7: one recording read by hand and through a Result.
2
3Requires pandas, which is not a g.Pype dependency: pip install pandas
4"""
5
6import glob
7import os
8import tempfile
9import time
10
11import numpy as np
12import pandas as pd
13
14import gpype as gp
15
16SAMPLING_RATE = 250
17OUT = tempfile.gettempdir()
18LABELS = ["Fz", "C3", "Cz", "C4", "marker"]
19
20
21def newest(stem: str, extension: str) -> str:
22 """The file a writer produced last, timestamp and all."""
23 found = sorted(glob.glob(os.path.join(OUT, f"{stem}_*{extension}")))
24 return found[-1] if found else ""
25
26
27def record() -> None:
28 """Record four channels and a marker channel to CSV and HDF5."""
29 p = gp.Pipeline()
30 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=4,
31 signal_frequency=10, signal_amplitude=20.0,
32 noise_amplitude=2.0)
33 # Markers fired by this script, standing in for a paradigm
34 marker = gp.Marker()
35 both = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
36 names = gp.ChannelLabeler(labels=LABELS)
37 p.connect(source, both["in1"])
38 p.connect(marker, both["in2"])
39 p.connect(both, names)
40 p.connect(names, gp.CsvWriter(file_name=os.path.join(OUT, "s4e7.csv")))
41 p.connect(names, gp.HDF5Writer(file_name=os.path.join(OUT, "s4e7.h5")))
42 p.start()
43 time.sleep(0.8)
44 for code in (1, 2, 1):
45 marker.emit(code)
46 time.sleep(0.5)
47 time.sleep(0.2)
48 p.stop()
49 p.close()
50
51
52def read(reader) -> gp.Result:
53 """Read a whole recording in one batch run."""
54 with gp.Pipeline() as p:
55 p.connect(reader, gp.Collector())
56 return p.run()
57
58
59if __name__ == "__main__":
60
61 record()
62 csv = newest("s4e7", ".csv")
63
64 # 1. By hand. The file opens with comment lines, its header separates
65 # names with ", ", pandas' default float parser can misread the 17th
66 # digit g.Pype writes, and the time only becomes the index if you
67 # make it one
68 by_hand = pd.read_csv(csv, comment="#", skipinitialspace=True,
69 float_precision="round_trip")
70 by_hand = by_hand.set_index("Time")
71
72 # 2. Through a Result: the reader already knows the columns, the
73 # rate and the time axis
74 result = read(gp.CsvReader(file_name=csv, mode="batch"))
75 from_result = result.to_dataframe()
76
77 print("pd.read_csv, by hand:")
78 print(by_hand.head(3))
79 print()
80 print("result.to_dataframe():")
81 print(from_result.head(3))
82 print()
83 print(" same columns :", list(by_hand.columns) == list(from_result))
84 print(" same values :", np.array_equal(by_hand.to_numpy(),
85 from_result.to_numpy()))
86 print(" same times :", np.array_equal(by_hand.index.to_numpy(),
87 from_result.index.to_numpy()))
88
89 # A DataFrame answers questions a flat array does not: every row a
90 # marker is on, with its time
91 fired = from_result[from_result["marker"] != 0]
92 print()
93 print("markers:", {t: int(v) for t, v in fired["marker"].items()})
94
95 # 3. What the frame cannot say: which column is the trigger. A CSV
96 # stores no roles, so its Result calls every column a signal; the
97 # HDF5 copy of the same recording kept them
98 twin = read(gp.HDF5Reader(file_name=newest("s4e7", ".h5"),
99 mode="batch", variable_name="data",
100 has_time_row=True))
101 print()
102 print("result.roles, from the .csv :", result.roles)
103 print("result.roles, from the .h5 :", twin.roles)
104 print("the trigger column :",
105 [c.name for c in twin.channels if c.role == "trigger"])
106 print("result.times[:3] :", twin.times[:3])
107 print("result.channels[-1] :", twin.channels[-1])