def perform(name):
    """
    Perform preprocessing and classification using one method and one window length
    Return a matrix: acc = accuracy und = undefinedRate
    [20 acc20 und20
     10 acc10 und10
     5 acc5 und5]
    """
    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, name))
    X = data['data']

    # CAR FILTER & PASSBAND FILTER
    Wcritic = np.array([0., 4., 5., 49., 50., 300.])
    b, a = preprocessing._get_fir_filter(Wcritic, FS, 851)
    X = signal.fftconvolve(X, b[:, np.newaxis], mode='valid')

    X -= X.mean(axis=0)
    X = np.dot(X, preprocessing.CAR(X.shape[1]))

    chans = np.in1d(config.SENSORS_SANDRA, CHANNELS)
    _ = X[0:160 * FS, chans].reshape(160 * FS, len(CHANNELS))  # protocol first part, 20s x 2
    y2 = X[160 * FS: 320 * FS, chans].reshape(160 * FS, len(CHANNELS))  # protocol second part, 10s x 4
    y3 = X[320 * FS: 420 * FS, chans].reshape(X.shape[0] - 320 * FS, len(CHANNELS))  # protocol third part, 5s x 5

    # Plotting spectrum to observe power distribution
    # f,psd = preprocessing.get_psd(y1[:,0], 3, Fs)
    # plt.plot(f,psd)
    # plt.show()

    # Comparison parameters
    # criterion == 'offline' -> classifier just a criterion of maxima. Windows->Output 1:1
    # criterion == 'pseudoon' -> classifier with a confidence criterion. Windows->Output 1:(0|1)
    criterion = 'pseudoon'
    # segment == 'sliding' -> sliding windows with slide = 1 s
    # segment == 'nooverlap' -> windows with no overlap. Only the first and, if present, the second, are considered
    segmenting = 'sliding'
    method = METHOD(list(FREQUENCIES), (WINLENGTH - 1) * FS, FS)

    records = np.zeros((2, 5))

    acc, avg_time = apply_method(y2, WINLENGTH, segmenting, criterion, method, prot_iterations=4, prot_period=10)
    # avg_time = WINLENGTH + und / (1 - und)
    itr = performance.get_ITR(4, acc, avg_time) * 60
    ut = performance.get_utility(6, acc, avg_time) * 60
    records[0, :] = [10, 100 * acc, avg_time, itr, ut]
    print '##'

    acc, avg_time = apply_method(y3, WINLENGTH, segmenting, criterion, method, prot_iterations=5, prot_period=5)
    # avg_time = WINLENGTH + und / (1 - und)
    itr = performance.get_ITR(4, acc, avg_time) * 60
    ut = performance.get_utility(6, acc, avg_time) * 60
    records[1, :] = [5, 100 * acc, avg_time, itr, ut]
    print '##'

    return records
Example #2
0
def perform(name):
    """
    Perform preprocessing and classification using one method and one window length
    Return a vector: [acc avg_time itr utility]
    """
    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, name))
    X = data['X']

    # select channels and best CCAchannels for PSDA
    CARchannels = np.array(['F3', 'P7', 'O1', 'O2', 'P8', 'F4'])
    # X = X[:, np.in1d(np.array(config.SENSORS), CARchannels)]

    # Filtro passaalto
    Wcritic = np.array([0., 4., 5., 64.])
    b, a = preprocessing._get_fir_filter(Wcritic, FS, mask=[0, 1])
    X = signal.filtfilt(b, (a, ), X, axis=0)

    # CAR FILTER
    X -= X.mean(axis=0)
    X = np.dot(X, preprocessing.CAR(X.shape[1]))

    myChannels = np.array(CHANNELS)
    X = X[:, np.in1d(CARchannels, myChannels)].reshape(len(X), len(myChannels))

    # Comparison parameters
    # criterion == 'offline' -> classifier just a criterion of maxima. Windows->Output 1:1
    # criterion == 'pseudoon' -> classifier with a confidence criterion. Windows->Output 1:(0|1)
    criterion = 'pseudoon'
    # segment == 'sliding' -> sliding windows with slide = 1 s
    # segment == 'nooverlap' -> windows with no overlap. Only the first and, if present, the second, are considered
    segmenting = 'sliding'
    method = METHOD(list(FREQUENCIES), (WINLENGTH - 1) * FS, FS)

    acc, avg_time = apply_method(X,
                                 WINLENGTH,
                                 segmenting,
                                 criterion,
                                 method,
                                 prot_iterations=config.RECORDING_ITERATIONS,
                                 prot_period=config.RECORDING_PERIOD)
    # avg_time = WINLENGTH + und / (1 - und)
    itr = performance.get_ITR(4, acc, avg_time) * 60
    ut = performance.get_utility(6, acc, avg_time) * 60
    records = np.array([100 * acc, avg_time, itr, ut])
    print '##'

    return records
def compare_methods(dataFile):
    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, dataFile))
    X = data['X'].astype('float32', copy=False)

    # select channels and best CCAchannels for PSDA
    CARchannels = np.array(['F3', 'P7', 'O1', 'O2', 'P8', 'F4'])
    # X = X[:, np.in1d(np.array(config.SENSORS), CARchannels)]

    # Filtro passaalto
    Wcritic = np.array([0., 4., 5., 64.])
    b, a = preprocessing._get_fir_filter(Wcritic, config.FS, mask=[0, 1])
    X = signal.filtfilt(b, (a, ), X, axis=0)
    # X = signal.fftconvolve(X, b[:, np.newaxis], mode='valid')

    # CAR FILTER
    X -= X.mean(axis=0)
    X = np.dot(X, preprocessing.CAR(X.shape[1]))

    accuracies = []
    [accuracies.append([]) for i in xrange(3)]
    undefineds = []
    [undefineds.append([]) for i in xrange(3)]
    tries = range(3, 9)

    myChannels = np.array(['O1', 'O2'])
    X = X[:, np.in1d(CARchannels, myChannels)].reshape(len(X), len(myChannels))

    # Comparison parameters
    # criterion == 'offline' -> classifier just a criterion of maxima. Windows->Output 1:1
    # criterion == 'pseudoon' -> classifier with a confidence criterion. Windows->Output 1:(0|1)
    criterion = 'pseudoon'
    # segment == 'sliding' -> sliding windows with slide = 1 s
    # segment == 'nooverlap' -> windows with no overlap. Only the first and, if present, the second, are considered
    segmenting = 'sliding'

    for i in tries:
        print 'Window %d' % i
        if criterion == 'offline':
            actualWindow = i
        elif criterion == 'pseudoon':
            actualWindow = i - 1

        method = featex.CCA(list(FREQUENCIES), actualWindow * config.FS,
                            config.FS)
        acc, avg_time = apply_method(X, i, segmenting, criterion, method)
        accuracies[0].append(acc)
        # undefineds[0].append(i + und / (1 - und))

        method = featex.MSI(list(FREQUENCIES), actualWindow * config.FS,
                            config.FS)
        acc, avg_time = apply_method(X, i, segmenting, criterion, method)
        accuracies[1].append(acc)
        # undefineds[1].append(i + und / (1 - und))

        method = featex.PSDA(list(FREQUENCIES), actualWindow * config.FS,
                             config.FS)
        acc, avg_time = apply_method(X, i, segmenting, criterion, method)
        accuracies[2].append(acc)
        # undefineds[2].append(i + und / (1 - und))

    fig = plt.figure(1)
    fig.suptitle(dataFile + ' ' +
                 ":".join(CARchannels[np.in1d(CARchannels, myChannels)]))
    plt.subplot(121)
    # plt.ylim((33., 100.))
    plt.xlabel("Window length")
    plt.ylabel("Accuracy")
    plt.plot(tries, accuracies[0], '-or', label='CCA')
    plt.plot(tries, accuracies[1], '-oy', label='MSI')
    plt.plot(tries, accuracies[2], '-og', label='PSDA')
    plt.legend()
    plt.grid()
    plt.subplot(122)
    plt.xlabel("Window length")
    plt.ylabel("Time for command")
    plt.plot(tries, undefineds[0], 'r', label='CCA')
    plt.plot(tries, undefineds[1], 'y', label='MSI')
    plt.plot(tries, undefineds[2], 'g', label='PSDA')
    plt.legend()
    plt.grid()
    plt.show()
Example #4
0
    modelorder = 2 * 4  # four w0
    damp = .005
    nx = 600 * 2
    noise = .05 * 2  # * swing
    plot = 0
    seed = 0

    DATA_FILE = "protocolo 7/celso_prot7_config1.mat"

    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, DATA_FILE))
    X = data['data']

    # CAR FILTER & PASSBAND FILTER
    X -= X.mean(axis=0)
    X = np.dot(X, preprocessing.CAR(X.shape[1]))

    Fs = 600
    freqs = [5.6, 6.4, 6.9, 8]

    Wcritic = np.array([0., 4., 5., 49., 50., 300.])
    b, a = preprocessing._get_fir_filter(Wcritic, Fs, 251)
    X = signal.lfilter(b, (a, ), X, axis=0)

    channel = [11]  # Oz

    t = np.arange(nx - 1 + 0.) / 600.
    x = np.empty((2 * modelorder, t.shape[0]))
    for i in range(len(freqs)):
        x[i * 4:(i + 1) * 4, :] = featex.generate_references(
            t.shape[0], freqs[i], Fs, 2).T
def filter_classify(dataFile):
    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, dataFile))
    EEG = data['data']

    Fs = 600
    freqs = [5.6, 6.4, 6.9, 8]
    # freqs = [8]

    # CAR FILTER & PASSBAND FILTER
    Wcritic = np.array([0., 4., 5., 49., 50., 300.])
    b, a = preprocessing._get_fir_filter(Wcritic, Fs, 851)
    EEG = signal.fftconvolve(EEG, b[:, np.newaxis], mode='valid')

    EEG -= EEG.mean(axis=0)
    EEG = np.dot(EEG, preprocessing.CAR(EEG.shape[1]))

    # Filter parameters
    damp = .005
    nx = 600 * 2
    modelorder = 2
    harmonics = 2
    singleFilter = 0

    channel = [9, 10, 11]
    EEG = EEG[0:110 * Fs,
              channel].reshape(110 * Fs,
                               len(channel))  # First part of protocol
    protocolPart1 = preprocessing.sliding_window(EEG, (nx, EEG.shape[1]),
                                                 (Fs, EEG.shape[1]))

    msi = featex.MSI(freqs, nx, Fs)
    # psda = processing.PSDA(freqs, nx, Fs)

    anfs = [adapt_filtering.ANF(harmonics * modelorder, damp) for f in freqs]
    anf = adapt_filtering.ANF(harmonics * modelorder, damp)

    befores = np.zeros((len(protocolPart1), len(freqs)))
    afters = np.zeros((len(protocolPart1), len(freqs)))
    for ii, win in enumerate(protocolPart1):
        ys = []

        #### ONE FILTER
        if singleFilter:
            x = np.zeros((nx, harmonics * modelorder))
            for i in range(len(freqs)):
                x[:, i * 4:(i + 1) * 4] = featex.generate_references(
                    nx, freqs[i], Fs, 2)

            y = np.zeros((nx, len(channel)))
            for c in range(len(channel)):
                y[:, c], _ = anf.filter_synch(x, win[:, c])

            # fig, ax = pl.subplots( nrows=2 )
            # fb, PSDb = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT, ax[0])
            # fa, PSDa = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT, ax[1])
            # pl.show()

            for i, freq in enumerate(freqs):
                x = featex.generate_references(nx, freq, Fs, harmonics)
                # Compute MSI / PSDA indicators
                befores[ii, i] = msi._compute_MSI(x, win)
                # f, PSD = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT)
                # befores[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
                afters[ii, i] = msi._compute_MSI(x, y)
                # f, PSD = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT)
                # afters[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
            np.round(befores, 3)
            np.round(afters, 3)
        else:
            #####################
            #### MULTIPLE FILTERS
            for i, freq in enumerate(freqs):
                x = featex.generate_references(nx, freq, Fs, harmonics)

                # Compute MSI / PSDA indicators
                befores[ii, i] = msi._compute_MSI(x, win)
                # f, PSD = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT)
                # befores[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)

                # Filter
                y = np.zeros((nx, len(channel)))
                for c in range(len(channel)):
                    y[:, c], _ = anfs[i].filter_synch(x, win[:, c])
                ys.append(y)

            y = np.sum(ys, axis=0)
            # fig, ax = pl.subplots( nrows=2 )
            # fb, PSDb = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT, ax[0])
            # fa, PSDa = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT, ax[1])
            # pl.show()

            for i, freq in enumerate(freqs):
                x = featex.generate_references(nx, freq, Fs, harmonics)
                # Compute MSI / PSDA indicators
                afters[ii, i] = msi._compute_MSI(x, y)
                # f, PSD = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT)
                # afters[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
            np.round(befores, 3)
            np.round(afters, 3)
            ################

    c = 0
    for i in range(len(befores)):
        if stdtest(befores[i]):  # 70%
            print np.argmax(befores[i])
            c += 1
    print 'count: %d' % c

    fig, ax = pl.subplots(nrows=2)
    fig.set_size_inches(12, 8)
    plots = ax[0].plot(befores)
    ax[0].legend(plots, map(str, freqs), loc=1)
    start, end = ax[0].get_xlim()
    ax[0].xaxis.set_ticks(np.arange(start, end, 5))
    ax[0].grid()
    plots = ax[1].plot(afters)
    ax[1].legend(plots, map(str, freqs), loc=1)
    ax[1].xaxis.set_ticks(np.arange(start, end, 5))
    ax[1].grid()
    pl.show()
Example #6
0
def filter_classify(dataFile):
    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, dataFile))
    EEG = data['X'].astype('float32', copy=False)

    # CARchannels = np.array(['P7','O1','O2','P8'])
    CARchannels = np.array(['F3', 'P7', 'O1', 'O2', 'P8', 'F4'])
    # EEG = EEG[:, np.in1d(np.array(config.SENSORS), CARchannels)]

    Fs = config.FS
    freqs = [6.4, 6.9, 8]

    # HIGHPASS FILTER
    Wcritic = np.array([0., 4., 5., 64.])
    b, a = preprocessing._get_fir_filter(Wcritic, config.FS, mask=[0, 1])
    EEG = signal.filtfilt(b, (a, ), EEG, axis=0)

    # CAR FILTER
    EEG -= EEG.mean(axis=0)
    EEG = np.dot(EEG, preprocessing.CAR(EEG.shape[1]))

    # Filter parameters
    damp = .005
    window = 4
    nx = Fs * window
    modelorder = 2
    harmonics = 2
    singleFilter = 0

    CCAchannels = np.array(['O1', 'O2'])
    EEG = EEG[:, np.in1d(CARchannels, CCAchannels)].reshape(
        len(EEG), len(CCAchannels))
    msi = featex.MSI(list(freqs), nx, Fs)
    psda = featex.PSDA(freqs, nx, Fs)

    anfs = [adapt_filtering.ANF(harmonics * modelorder, damp) for f in freqs]
    anf = adapt_filtering.ANF(harmonics * modelorder, damp)

    # windowsInPeriod = window*2 <= config.RECORDING_PERIOD and 2 or 1
    windowsInPeriod = config.RECORDING_PERIOD - window + 1
    befores = np.empty(
        (config.RECORDING_ITERATIONS * len(freqs) * windowsInPeriod,
         len(freqs)))
    afters = np.empty(
        (config.RECORDING_ITERATIONS * len(freqs) * windowsInPeriod,
         len(freqs)))
    protocolFiltered = np.empty(
        (config.RECORDING_ITERATIONS * len(freqs) * windowsInPeriod, nx,
         len(CCAchannels)))

    # label = offline.make_label_segments(config.RECORDING_ITERATIONS, config.RECORDING_PERIOD, window, len(freqs))
    # W = offline.extract_segment_start(EEG, window, config.RECORDING_ITERATIONS, config.RECORDING_PERIOD, Fs)
    label = offline.make_label_windows(config.RECORDING_ITERATIONS,
                                       config.RECORDING_PERIOD, window,
                                       len(freqs))
    W = offline.extract_windowed_segment(EEG, window, config.RECORDING_PERIOD,
                                         Fs)

    for wi, win in enumerate(W):
        ys = []

        #### ONE FILTER
        if singleFilter:
            x = np.zeros((nx, harmonics * modelorder))
            for i in range(len(freqs)):
                x[:, i * 4:(i + 1) * 4] = featex.generate_references(
                    nx, freqs[i], Fs, 2)

            y = np.zeros((nx, len(CCAchannels)))
            for c in range(len(CCAchannels)):
                y[:, c], _ = anf.filter_synch(x, win[:, c])

            protocolFiltered[wi] = y
            # fig, ax = pl.subplots( nrows=2 )
            # fb, PSDb = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT, ax[0])
            # fa, PSDa = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT, ax[1])

            for i, freq in enumerate(freqs):
                x = featex.generate_references(nx, freq, Fs, harmonics)
                # Compute MSI / PSDA indicators
                befores[wi, i] = msi._compute_MSI(x, win)
                # f, PSD = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT)
                # befores[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
                afters[wi, i] = msi._compute_MSI(x, y)
                # f, PSD = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT)
                # afters[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
            np.round(befores, 3)
            np.round(afters, 3)
            # print afters[ii, :], befores[ii, :]
            # pl.show()
        else:
            #####################
            #### MULTIPLE FILTERS
            temp = []

            for i, freq in enumerate(freqs):
                x = featex.generate_references(nx, freq, Fs, harmonics)

                # Compute MSI / PSDA indicators
                befores[wi, i] = msi._compute_MSI(x, win)
                # befores[ii, i] = msi._compute_max_corr(x, win)
                # f, PSD = preprocessing.get_psd(win[:,1], nx / Fs, Fs, config.NFFT)
                # befores[wi, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)

                # Filter
                y = np.zeros((nx, len(CCAchannels)))
                for c in range(len(CCAchannels)):
                    y[:, c], _ = anfs[i].filter_synch(x, win[:, c])
                ys.append(y)

            #     ics1 = processing.generate_references(nx, freqs[0], Fs, harmonics)
            #     ics2 = processing.generate_references(nx, freqs[1], Fs, harmonics)
            #     m1 = msi._compute_max_corr(ics1, y)
            #     m2 = msi._compute_max_corr(ics2, y)
            #     if freq == freqs[0]:
            #         temp.append(m1)
            #     else:
            #         temp.append(m2)

            # print befores[ii, :]
            # print temp
            y = np.sum(ys, axis=0)
            protocolFiltered[wi] = y
            # fig, ax = pl.subplots( nrows=2 )
            # fb, PSDb = preprocessing.get_psd(win[:,1], nx / Fs, Fs, config.NFFT, ax[0])
            # fa, PSDa = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT, ax[1])
            # pl.show()

            for i, freq in enumerate(freqs):
                x = featex.generate_references(nx, freq, Fs, harmonics)
                # Compute MSI / PSDA indicators
                afters[wi, i] = msi._compute_MSI(x, y)
                # f, PSD = preprocessing.get_psd(y[:,1], nx / Fs, Fs, config.NFFT)
                # afters[wi, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
            np.round(befores, 3)
            np.round(afters, 3)
            ################

    o1 = offline.offline_classify(W, freqs, msi)
    cm = performance.get_confusion_matrix(label, o1, len(freqs))
    print performance.get_accuracy(cm)

    for i in range(len(befores)):
        if stdtest(befores[i]):  # 70%
            print i, qtest(befores[i])

    fig, ax = pl.subplots(nrows=2)
    fig.suptitle(dataFile)
    fig.set_size_inches(12, 8)
    plots = ax[0].plot(befores, '-o')
    ax[0].plot(label * np.max(befores))
    ax[0].legend(plots, [str(f) for f in freqs], loc=1)
    start, end = ax[0].get_xlim()
    ax[0].xaxis.set_ticks(np.arange(start, end, 1))
    ax[0].grid()
    plots = ax[1].plot(afters, '-o')
    # ax[1].plot(label * np.max(afters))
    ax[1].legend(plots, [str(f) for f in freqs], loc=1)
    ax[1].xaxis.set_ticks(np.arange(start, end, 1))
    ax[1].grid()
    pl.show()
Example #7
0
def filter_classify(dataFile):
    # read data
    data = sio.loadmat(os.path.join(config.DATA_PATH, dataFile))
    EEG = data['X'].astype('float32', copy=False)

    channels = np.array(['F3', 'P7', 'O1', 'O2', 'P8', 'F4'])
    EEG = EEG[:, np.in1d(np.array(config.SENSORS), channels)]

    # CAR FILTER
    EEG -= EEG.mean(axis=0)
    EEG = np.dot(EEG, preprocessing.CAR(EEG.shape[1]))

    Fs = config.FS
    freqs = [6.4, 6.9, 8]

    # HIGHPASS FILTER
    # Per Emotiv DEVE ESSERE DI ORDINE BASSO PER DARE UN POCHINO DI RITARDO
    Wcritic = np.array([0., 4., 5., 64.])
    b, a = preprocessing._get_fir_filter(Wcritic, config.FS, mask=[0, 1])
    EEG = signal.filtfilt(b, (a, ), EEG, axis=0)

    # Filter parameters
    damp = .001
    window = 6
    nx = Fs * window
    modelorder = 50
    harmonics = 2

    channelSignal = np.in1d(channels, ['O2'])
    channelNoise = np.in1d(channels, ['P7'])
    s1 = EEG[:, channelSignal].reshape(len(EEG), 1)
    n1 = EEG[:, channelNoise].reshape(len(EEG), 1)

    signalWindows = preprocessing.sliding_window(s1, (nx, s1.shape[1]),
                                                 (Fs, s1.shape[1]))
    noiseWindows = preprocessing.sliding_window(n1, (nx, s1.shape[1]),
                                                (Fs, s1.shape[1]))

    msi = featex.MSI(freqs, nx, Fs)
    psda = featex.PSDA(freqs, nx, Fs)

    anc = adapt_filtering.ANC(modelorder, damp)

    befores = np.empty((len(signalWindows), len(freqs)))
    afters = np.empty((len(signalWindows), len(freqs)))
    signalFiltered = np.empty((len(signalWindows), nx, len(channelSignal)))
    for ii, (signalWin, noiseWin) in enumerate(zip(signalWindows,
                                                   noiseWindows)):
        ys = []

        #### ONE FILTER
        _, y = anc.filter(noiseWin, signalWin)

        signalFiltered[ii] = y
        # fig, ax = pl.subplots( nrows=3 )
        # ax[2].plot(y)
        # fb, PSDb = preprocessing.get_psd(signalWin[:,0], nx / Fs, Fs, config.NFFT, ax[0])
        # fa, PSDa = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT, ax[1])
        # pl.show()

        for i, freq in enumerate(freqs):
            x = featex.generate_references(nx, freq, Fs, harmonics)
            # Compute MSI / PSDA indicators
            befores[ii, i] = msi._compute_MSI(x, signalWin)
            # f, PSD = preprocessing.get_psd(win[:,0], nx / Fs, Fs, config.NFFT)
            # befores[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
            afters[ii, i] = msi._compute_MSI(x, y)
            # f, PSD = preprocessing.get_psd(y[:,0], nx / Fs, Fs, config.NFFT)
            # afters[ii, i] = processing.PSDA.compute_SNR(f, PSD, freq, Fs)
        np.round(befores, 3)
        np.round(afters, 3)
        # print afters[ii, :], befores[ii, :]
        # pl.show()

    label = offline.make_label_matrix(EEG.shape[0], config.RECORDING_PERIOD,
                                      window, config.FS, len(freqs))
    # o1 = offline.offline_classify(signalWindows, freqs, msi)
    # o = offline.offline_classify(signalFiltered, freqs, msi)
    # print 100 * performance.get_accuracy(label, o1), 100 * performance.get_accuracy(label, o)

    fig, ax = pl.subplots(nrows=2)
    fig.set_size_inches(12, 8)
    plots = ax[0].plot(befores)
    ax[0].plot(label * np.max(befores))
    ax[0].legend(plots, map(str, freqs), loc=1)
    start, end = ax[0].get_xlim()
    ax[0].xaxis.set_ticks(np.arange(start, end, 5))
    ax[0].grid()
    plots = ax[1].plot(afters)
    ax[1].plot(label * np.max(afters))
    ax[1].legend(plots, map(str, freqs), loc=1)
    ax[1].xaxis.set_ticks(np.arange(start, end, 5))
    ax[1].grid()
    pl.show()
Example #8
0
def process_file(dataFile, winLengths, verbose=True):
    # read data
    myData = sio.loadmat(os.path.join(config.DATA_PATH, dataFile))
    X = myData['data']
    # CAR FILTER & PASSBAND FILTER
    Wcritic = np.array([0., 4., 5., 49., 50., 300.])
    b, a = preprocessing._get_fir_filter(Wcritic, FS, 851)
    # X = signal.lfilter(b, [a,], X, axis=0)[len(b) - 1:,:]
    X = signal.fftconvolve(X, b[:, np.newaxis], mode='valid')

    X -= X.mean(axis=0)
    X = np.dot(X, preprocessing.CAR(X.shape[1]))

    # y1 = X[0:160 * FS, :]  # protocol first part, 20s x 2
    y2 = X[160 * FS: 320 * FS, :]  # protocol second part, 10s x 4
    y3 = X[320 * FS: 420 * FS, :]  # protocol first part, 5s x 5

    accuracies = np.zeros((5, len(lengths)))
    ITRs = np.zeros((5, len(lengths)))
    avg_times = np.zeros((5, len(lengths)))

    # Comparison parameters
    # criterion == 'offline' -> classifier just a criterion of maxima. Windows->Output 1:1
    # criterion == 'pseudoon' -> classifier with a confidence criterion. Windows->Output 1:(0|1)
    criterion = 'pseudoon'
    # segment == 'sliding' -> sliding windows with slide = 1 s
    # segment == 'nooverlap' -> windows with no overlap. Only the first and, if present, the second, are considered
    segmenting = 'sliding'

    # FREQUENCY REDUCTION
    # global FREQUENCIES
    # FREQUENCIES = [6.4, 6.9, 8]
    # yi = np.zeros((y3.shape[0] - ITERATIONS * PERIOD * FS, y1.shape[1]))
    # NEW_LENGTH_ITERATION = len(FREQUENCIES) * PERIOD * FS
    # for i in range(ITERATIONS):
    #     buf = y3[PERIOD * FS + i * LENGTH_ITERATION : (i+1) * LENGTH_ITERATION,:]
    #     yi[i * NEW_LENGTH_ITERATION:i * NEW_LENGTH_ITERATION + len(buf)] = buf

    yi = y2

    for il, length in enumerate(winLengths):
        if verbose:
            print 'Window %d' % length
        if criterion == 'offline':
            actualWindow = length
        elif criterion == 'pseudoon':
            actualWindow = length - 1
            # actualWindow = length

        y = yi[:, np.in1d(config.SENSORS_SANDRA, ['O2', 'Oz', 'O1'])]

        # 3 channels CCA
        method = featex.CCA(list(FREQUENCIES), actualWindow * FS, FS)
        acc, avg_time = apply_method(y, length, segmenting, criterion, method)

        accuracies[0, il] = acc * 100
        avg_times[0, il] = avg_time
        ITRs[0, il] = performance.get_ITR(4, acc, avg_time) * 60

        # 3 channels MSI
        method = featex.MSI(list(FREQUENCIES), actualWindow * FS, FS)
        acc, avg_time = apply_method(y, length, segmenting, criterion, method)

        accuracies[1, il] = acc * 100
        avg_times[1, il] = avg_time
        ITRs[1, il] = performance.get_ITR(4, acc, avg_time) * 60

        # 2 channels MSI
        y = yi[:, np.in1d(config.SENSORS_SANDRA, ['O2', 'Oz'])]
        method = featex.MSI(list(FREQUENCIES), actualWindow * FS, FS)
        acc, avg_time = apply_method(y, length, segmenting, criterion, method)

        accuracies[2, il] = acc * 100
        avg_times[2, il] = avg_time
        ITRs[2, il] = performance.get_ITR(4, acc, avg_time) * 60
        # 1 channel MSI
        y = yi[:, np.in1d(config.SENSORS_SANDRA, ['Oz'])]
        method = featex.MSI(list(FREQUENCIES), actualWindow * FS, FS)
        acc, avg_time = apply_method(y, length, segmenting, criterion, method)

        accuracies[3, il] = acc * 100
        avg_times[3, il] = avg_time
        ITRs[3, il] = performance.get_ITR(4, acc, avg_time) * 60

        # 1 channel PSDA
        y = yi[:, np.in1d(config.SENSORS_SANDRA, ['Oz'])]
        method = featex.PSDA(list(FREQUENCIES), actualWindow * FS, FS)
        acc, avg_time = apply_method(y, length, segmenting, criterion, method)

        accuracies[4, il] = acc * 100
        avg_times[4, il] = avg_time
        ITRs[4, il] = performance.get_ITR(4, acc, avg_time) * 60

    return accuracies, avg_times, ITRs