How can I write data to an EDF file in Python?

371 Views Asked by At

If I have a 5 minutes long signal stored in an EDF file that I'm reading from using the function readSignal(), imagine that I'm interested only in the first second of that 5 minutes, and I want to store that portion of the signal in a separate edf file. How can I do this? The following code reads the first 1 second, where the sampling rate is 1kHz, and I'm simply visualizing it.

import pyedflib
import numpy as np
import matplotlib.pyplot as plt

file_name = "17335.0001_0001.edf"
f = pyedflib.EdfReader(file_name)
signal_labels = f.getSignalLabels()
fig=plt.figure()
ax=plt.axes()
ax.plot(f.readSignal(0,0,1000))
1

There are 1 best solutions below

0
Michael Shevelin On

With EDF format, you have to adjust the metadata to the modifications you applied to the signal, in your case - number of channels and duration. I'd recommend using pyedflib's high level functions for IO. pyedflib.highlevel.read_edf provides the metadata, along with the signal data for you to modify easily. The downside of it, it reads the whole channel, instead of only the first second, what may harm the performance. If your signal is not very large - I'd go with high level convenience functions.

def trim_edf():
    file_name = r"17335.0001_0001.edf"
    sample_rate = 1000
    seconds = 1
    ch_nrs = [0]  # Read the first channel
    signals, signal_headers, header = pyedflib.highlevel.read_edf(file_name, ch_nrs=ch_nrs)
    # Trim the signal:
    signals = signals[:, :seconds * sample_rate]  # 2D numpy array of shape (1, 1000)
    # Modify metadata to fit new signal data

    # Signal headers is the list of dict, each dict corresponds to some channel.
    # We only want the first channel.
    new_signal_headers = [signal_headers[0]]

    # Update signal duration(seconds) in the main header.
    # Main header is a dict of global EDF properties, like start date, duration, patient details etc...
    new_header = header.copy()
    new_header['Duration'] = seconds

    # Save modified signal with adjusted metadata as EDF file.
    pyedflib.highlevel.write_edf('modified_signal.edf', signals=signals, header=new_header,
                                 signal_headers=new_signal_headers)