示例#1
0
def importBDF(filename, useCpp=False):
    """returns dataMatrix, eventTable, chanLabels"""
    if len(filename) > 0:
        rec1 = pybdf.bdfRecording(filename)

        data1 = rec1.getData(trigChan=True, useCpp=useCpp)

        #retrieve sampling rates (list of sampling rate of each channel)
        sampRate1 = rec1.sampRate
        print("**********************")
        print("The sampling rate of, ", filename, "is", sampRate1[0], "Hz")
        print()

        dur1 = rec1.duration
        #retrieve recording durations (list of recording durations of each channel)
        print("**********************")
        print("The duration of, ", filename, "is", dur1, "seconds")
        print()

        dataMatrix = data1['data']
        #time_array1 = np.arange(dataMatrix1.shape[1]) / rec1.sampRate[0]

        chanLabels = rec1.chanLabels

        eventTable = data1['eventTable']

        return dataMatrix, eventTable, chanLabels
    else:
        print("--Please enter a file--")
示例#2
0
 def readSigfile(self, filename):
     """ Load ECG signal.
         Return a 2-dim signal (t, bmp(t))
     """
     bdfRec = pybdf.bdfRecording(filename)
     rec = bdfRec.getData(channels=[33])
     self.SIG_SampleRate = bdfRec.sampRate[33]
     data = np.array(rec['data'][0])[rec['eventTable']['idx'][2]:]
     return ECGsignal(data, self.SIG_SampleRate)
示例#3
0
def load_data_bdf(data_bdf_filename, decimation_factor, num_cores=1):

    logging.debug('%s data_bdf_filename: %s', TAG, data_bdf_filename)
    recording_obj = pybdf.bdfRecording(data_bdf_filename)

    # Get recording information
    logging.debug('sampling_rate [Hz]: %f', recording_obj.sampRate[0])
    logging.debug('duration [s]: %f', recording_obj.duration)
    logging.debug('#channels: %d', recording_obj.nChannels)
    logging.debug('unit of measure: %s', recording_obj.physDim[0])
    print 'channel labels:', recording_obj.chanLabels
    print 'dataChanLabels:', recording_obj.dataChanLabels

    # Convert the data channel labels to integers, otherwise pybdf runs into a bug
    for i_label in range(len(recording_obj.dataChanLabels)):
        recording_obj.dataChanLabels[i_label] = i_label
    print 'dataChanLabels:', recording_obj.dataChanLabels

    # Get the data object
    data_obj = recording_obj.getData()

    # Get the signal data from the data object
    logging.debug('Getting the signal data from the data object...')
    X_raw = data_obj['data'].T
    logging.debug('Getting the signal data from the data object finished.')
    logging.debug('X_raw shape: %d, %d', X_raw.shape[0], X_raw.shape[1])
    #time_axis = np.arange(X_raw.shape[1]) / recording_obj.sampRate[0]

    # Get the event information from the data object
    # Event codes: 247 is button pressed (1), 255 is button released (0)
    logging.debug('Getting the event data from the data object...')
    event_table = data_obj['eventTable']
    print 'event_table[\'code\']:\n', event_table['code']
    print 'event_table[\'idx\']:\n', event_table['idx']
    print 'event_table[\'dur\']:\n', event_table['dur']
    logging.debug('Getting the event data from the data object finished.')

    # Build the label feed from the event information
    logging.debug('Building the label feed from the event information...')
    labels = np.zeros((X_raw.shape[0], 1), np.float32)
    n_events = len(event_table['code'])
    EVENT_CODE_ACTION = 247
    #EVENT_CODE_IDLE = 255
    for i_event in range(1, n_events):
        if event_table['code'][i_event] == EVENT_CODE_ACTION:
            labels[(event_table['idx'][i_event] -
                    params.EVENT_LENGTH_SAMPLES / 2):(
                        event_table['idx'][i_event] +
                        params.EVENT_LENGTH_SAMPLES / 2), :] = 1.0
        #if event_table['code'][i_event] == EVENT_CODE_ACTION:
        #    labels[event_table['idx'][i_event]:event_table['idx'][i_event+1], :] = 1.0
    logging.debug('np.sum(labels): %f', np.sum(labels))
    logging.debug(
        'Building the label feed from the event information finished.')

    # Low-pass-filter the data before downsampling
    freq_sampling = recording_obj.sampRate[0]
    logging.debug('freq_sampling: %f', freq_sampling)
    freq_cut_downsampling = freq_sampling / (2.0 * decimation_factor)
    logging.debug('freq_cut_downsampling: %f', freq_cut_downsampling)
    M_fir = freq_sampling
    tdfilt_numer, tdfilt_denom = create_lowpass_filter(
        freq_cut=freq_cut_downsampling,
        freq_s=freq_sampling,
        M_fir=M_fir,
        plot=True)
    logging.debug('Low-pass filtering the data before downsampling...')
    logging.debug(
        'Timestamp: %s',
        datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    if num_cores > 1:
        #X_lpfiltered = np.array(joblib.Parallel(n_jobs=params.NUM_PARALLEL_JOBS)
        #                        (joblib.delayed(scipy.signal.lfilter)
        #                                (tdfilt_numer, tdfilt_denom,
        #                                X_raw[:, i_ch]) for i_ch in range(X_raw.shape[1]))).T
        X_lpfiltered = np.array(
            joblib.Parallel(n_jobs=params.NUM_PARALLEL_JOBS)(
                joblib.delayed(scipy.signal.filtfilt)(
                    tdfilt_numer, tdfilt_denom, X_raw[:, i_ch])
                for i_ch in range(X_raw.shape[1]))).T
    else:
        #X_lpfiltered = scipy.signal.lfilter(tdfilt_numer, tdfilt_denom, X_raw.T).T
        X_lpfiltered = scipy.signal.filtfilt(tdfilt_numer, tdfilt_denom,
                                             X_raw.T).T
    logging.debug(
        'Timestamp: %s',
        datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    logging.debug('Low-pass filtering the data before downsampling finished.')
    logging.debug('X_lpfiltered shape: %d, %d', X_lpfiltered.shape[0],
                  X_lpfiltered.shape[1])

    # Plot the data
    if False:
        time_to = 2048 * 5
        time_axis = np.arange(time_to)
        channels_to_plot = (54, 111)
        plt.plot(time_axis, X_raw[0:time_to, channels_to_plot], label='raw')
        plt.plot(time_axis,
                 X_lpfiltered[0:time_to, channels_to_plot],
                 label='filt')
        #plt.plot(time_axis, labels[0:time_to], label='event')
        plt.legend(loc='lower right')
        plt.show()

    # Downsample the data
    downsample_indices = np.arange(
        0, X_lpfiltered.shape[0],
        int(decimation_factor)) + (int(decimation_factor) - 1)
    print 'downsample_indices:\n', downsample_indices
    logging.debug('Downsampling the data...')
    logging.debug(
        'Timestamp: %s',
        datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    X_downsampled = X_lpfiltered[downsample_indices, :]
    #X_downsampled = X_lpfiltered[downsample_indices, 0:params.NUM_CHANNELS_BDF]
    labels = labels[downsample_indices, :]
    #X_raw = X_raw[::decimation_factor]
    #labels = labels[::decimation_factor]
    logging.debug(
        'Timestamp: %s',
        datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    logging.debug('Downsampling the data finished.')
    logging.debug('X_downsampled shape: %d, %d', X_downsampled.shape[0],
                  X_downsampled.shape[1])

    return X_downsampled, labels
示例#4
0
def load_data_bdf(data_bdf_filename, decimation_factor, num_cores=1):

    logging.debug('%s data_bdf_filename: %s', TAG, data_bdf_filename)
    recording_obj = pybdf.bdfRecording(data_bdf_filename)

    # Get recording information
    logging.debug('sampling_rate [Hz]: %f', recording_obj.sampRate[0])
    logging.debug('duration [s]: %f', recording_obj.duration)
    logging.debug('#channels: %d', recording_obj.nChannels)
    logging.debug('unit of measure: %s', recording_obj.physDim[0])
    print 'channel labels:', recording_obj.chanLabels
    print 'dataChanLabels:', recording_obj.dataChanLabels

    # Convert the data channel labels to integers, otherwise pybdf runs into a bug
    for i_label in range(len(recording_obj.dataChanLabels)):
        recording_obj.dataChanLabels[i_label] = i_label
    print 'dataChanLabels:', recording_obj.dataChanLabels

    # Get the data object
    data_obj = recording_obj.getData()

    # Get the signal data from the data object
    logging.debug('Getting the signal data from the data object...')
    X_raw = data_obj['data'].T
    logging.debug('Getting the signal data from the data object finished.')
    logging.debug('X_raw shape: %d, %d', X_raw.shape[0], X_raw.shape[1])
    #time_axis = np.arange(X_raw.shape[1]) / recording_obj.sampRate[0]

    # Get the event information from the data object
    # Event codes: 247 is button pressed (1), 255 is button released (0)
    logging.debug('Getting the event data from the data object...')
    event_table = data_obj['eventTable']
    print 'event_table[\'code\']:\n', event_table['code']
    print 'event_table[\'idx\']:\n', event_table['idx']
    print 'event_table[\'dur\']:\n', event_table['dur']
    logging.debug('Getting the event data from the data object finished.')

    # Build the label feed from the event information
    logging.debug('Building the label feed from the event information...')
    labels = np.zeros((X_raw.shape[0], 1), np.float32)
    n_events = len(event_table['code'])
    EVENT_CODE_ACTION = 247
    #EVENT_CODE_IDLE = 255
    for i_event in range(1, n_events):
        if event_table['code'][i_event] == EVENT_CODE_ACTION:
            labels[(event_table['idx'][i_event] - params.EVENT_LENGTH_SAMPLES/2)
                    :(event_table['idx'][i_event] + params.EVENT_LENGTH_SAMPLES/2), :] = 1.0
        #if event_table['code'][i_event] == EVENT_CODE_ACTION:
        #    labels[event_table['idx'][i_event]:event_table['idx'][i_event+1], :] = 1.0
    logging.debug('np.sum(labels): %f', np.sum(labels))
    logging.debug('Building the label feed from the event information finished.')

    # Low-pass-filter the data before downsampling
    freq_sampling = recording_obj.sampRate[0]
    logging.debug('freq_sampling: %f', freq_sampling)
    freq_cut_downsampling = freq_sampling / (2.0 * decimation_factor)
    logging.debug('freq_cut_downsampling: %f', freq_cut_downsampling)
    M_fir = freq_sampling
    tdfilt_numer, tdfilt_denom = create_lowpass_filter(
            freq_cut=freq_cut_downsampling,
            freq_s=freq_sampling,
            M_fir=M_fir,
            plot=True)
    logging.debug('Low-pass filtering the data before downsampling...')
    logging.debug('Timestamp: %s', datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    if num_cores > 1:
        #X_lpfiltered = np.array(joblib.Parallel(n_jobs=params.NUM_PARALLEL_JOBS)
        #                        (joblib.delayed(scipy.signal.lfilter)
        #                                (tdfilt_numer, tdfilt_denom,
        #                                X_raw[:, i_ch]) for i_ch in range(X_raw.shape[1]))).T
        X_lpfiltered = np.array(joblib.Parallel(n_jobs=params.NUM_PARALLEL_JOBS)
                                (joblib.delayed(scipy.signal.filtfilt)
                                        (tdfilt_numer, tdfilt_denom,
                                        X_raw[:, i_ch]) for i_ch in range(X_raw.shape[1]))).T
    else:
        #X_lpfiltered = scipy.signal.lfilter(tdfilt_numer, tdfilt_denom, X_raw.T).T
        X_lpfiltered = scipy.signal.filtfilt(tdfilt_numer, tdfilt_denom, X_raw.T).T
    logging.debug('Timestamp: %s', datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    logging.debug('Low-pass filtering the data before downsampling finished.')
    logging.debug('X_lpfiltered shape: %d, %d', X_lpfiltered.shape[0], X_lpfiltered.shape[1])

    # Plot the data
    if False:
        time_to = 2048*5
        time_axis = np.arange(time_to)
        channels_to_plot = (54, 111)
        plt.plot(time_axis, X_raw[0:time_to, channels_to_plot], label='raw')
        plt.plot(time_axis, X_lpfiltered[0:time_to, channels_to_plot], label='filt')
        #plt.plot(time_axis, labels[0:time_to], label='event')
        plt.legend(loc='lower right')
        plt.show()

    # Downsample the data
    downsample_indices = np.arange(0, X_lpfiltered.shape[0], int(decimation_factor)) + (int(decimation_factor)-1)
    print 'downsample_indices:\n', downsample_indices
    logging.debug('Downsampling the data...')
    logging.debug('Timestamp: %s', datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    X_downsampled = X_lpfiltered[downsample_indices, :]
    #X_downsampled = X_lpfiltered[downsample_indices, 0:params.NUM_CHANNELS_BDF]
    labels = labels[downsample_indices, :]
    #X_raw = X_raw[::decimation_factor]
    #labels = labels[::decimation_factor]
    logging.debug('Timestamp: %s', datetime.datetime.now().strftime(params.TIMESTAMP_FORMAT_STR))
    logging.debug('Downsampling the data finished.')
    logging.debug('X_downsampled shape: %d, %d', X_downsampled.shape[0], X_downsampled.shape[1])

    return X_downsampled, labels
示例#5
0
    import matplotlib.pyplot as plt
    matplotlib_available = True
except:
    matplotlib_available = False

#on linux the following automatically
#downloads example datasets from BIOSEMI
#if you're on windows or mac, download manually
# http://www.biosemi.com/download/BDFtestfiles.zip
#subprocess.call("wget http://www.biosemi.com/download/BDFtestfiles.zip", shell=True)
#subprocess.call("unzip BDFtestfiles.zip", shell=True)
fName1 = "Newtest17-256.bdf"
fName2 = "Newtest17-2048.bdf"
#let's see how long it takes

rec1 = pybdf.bdfRecording(fName1)
data1 = rec1.getData()

rec2 = pybdf.bdfRecording(fName2)
data2 = rec1.getData()

#retrieve sampling rates (list of sampling rate of each channel)
sampRate1 = rec1.sampRate
sampRate2 = rec2.sampRate
print("**********************")
print("The sampling rate of, ", fName1, "is", sampRate1[0], "Hz")
print("The sampling rate of, ", fName2, "is", sampRate2[0], "Hz")
print("--------------\n")

dur1 = rec1.duration
dur2 = rec2.duration
示例#6
0
    else:
        print("--Please enter a file--")


files = sorted(glob('./*2048*'))

if len(files) > 1:
    os.remove(files.pop(1))

files.append(files[0][0:-4] + '_out.bdf')

print(files)

copyfile(files[0], files[1])

source_file = pybdf.bdfRecording(files[0])

data = source_file.getData()

cpp_event = data['eventTable']

print(cpp_event)

rec_out = pybdf.bdfRecording(files[1])

out_cpp_codes = np.arange(1, cpp_event['code'].shape[0] + 1, 1, dtype=np.uint8)
out_cpp_times = (cpp_event['idx'] + 1)

# print(len(out_cpp_codes), len(out_cpp_times))

# print(out_cpp_codes, '\n', out_cpp_times)
示例#7
0
from pybdf import bdfRecording
import pandas as pd
import numpy as np
from matplotlib import pyplot
from biosppy import ecg

import matplotlib as ml
import matplotlib.pyplot as plt


#bdfRec = bdfRecording("../Dataset/Sessions/789/Part_7_N_Trial5_emotion.bdf")
bdfRec = bdfRecording("789/Part_7_N_Trial5_emotion.bdf")
ECG_idx = bdfRec.dataChanLabels.index('EXG2')
rec = bdfRec.getData(channels=[ECG_idx])
sampling_rate = bdfRec.sampRate[ECG_idx]
signal = np.array(rec['data'][0])
rec_s = pd.Series(rec['data'][0])
rec_s.plot()
pyplot.pause(0.1)

hr = ecg.ecg(signal=signal, sampling_rate=sampling_rate, show=False)[6]

#Must figure out a better way to find the time table.
#Video is 22 seconds and there is 85 samples
#video_duration = 22
#step = video_duration/float(len(hr))

step = 1/(float(sampling_rate)/60)
length = len(hr)
video_duration = step * float(len(hr))
time_array = np.arange(0, video_duration, step)
示例#8
0
import pybdf
import numpy as np
# def readfile():
# 	pass
# def main(person):
# 	for i in range(1,3):
# 		path = 'Part'+person+'_IAPS_SES'+'_EEG_fNIRS'
# 	readfile()

# if __name__ == '__main__':
# #选择实验者序号
# person = '1';
# main(person)
# 读取EEG数据
rec = pybdf.bdfRecording('sample.bdf')
data = rec.getData()
sampRate = rec.sampRate
durtime = rec.duration
chanlabels = rec.chanLabels
labels = rec.getData(channels=[-1])
print('EEG通道个数为:%d' % len(sampRate))
print('EEG信号采样频率是%d' % sampRate[0])
print('经过时间是:%.2f秒,%.2f分钟' % (durtime, durtime / 60.0))
print('EEG信号采样频率是%d' % sampRate[0])
print('EEG采样通道:', chanlabels)
print('其中脑电信号通道为%d个通道,眼电信号为%d个通道' % ((len(chanlabels) - 9), 8))
print('EEG数据结构:')
for key in labels.keys():
    print(key)
print('EEG-Data:', labels['data'].shape)
print('EEG-TrigChan:', labels['trigChan'])
示例#9
0
文件: test.py 项目: sam81/pybdf
    matplotlib_available = True
except:
    matplotlib_available = False

#on linux the following automatically
#downloads example datasets from BIOSEMI
#if you're on windows or mac, download manually
# http://www.biosemi.com/download/BDFtestfiles.zip
#subprocess.call("wget http://www.biosemi.com/download/BDFtestfiles.zip", shell=True)
#subprocess.call("unzip BDFtestfiles.zip", shell=True)
fName1 = "Newtest17-256.bdf"
fName2 = "Newtest17-2048.bdf"
#let's see how long it takes


rec1 = pybdf.bdfRecording(fName1)
data1 = rec1.getData()

rec2 = pybdf.bdfRecording(fName2)
data2 = rec1.getData()

#retrieve sampling rates (list of sampling rate of each channel)
sampRate1 = rec1.sampRate
sampRate2 = rec2.sampRate
print("**********************")
print("The sampling rate of, ", fName1, "is", sampRate1[0], "Hz")
print("The sampling rate of, ", fName2, "is", sampRate2[0], "Hz")
print("--------------\n")

dur1 = rec1.duration
dur2 = rec2.duration