def __init__(self, emotiv): self.isRunning = False self.isRecording = False self.sensors = np.array(['F3','P7','O1','O2','P8','F4']) self.headset = emotiv self.dataQueue = Queue() self.host = 'localhost' self.port = 8888 self.commandClient = client.connect(self.host, self.port) self.commands = [6.4, 8, 6.9] # processing parameters self.freqs = [6.4, 6.9, 8] self.winSize = 6 self.method = featex.MSI(list(self.freqs), (self.winSize - 1) * config.FS, config.FS)
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()
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 title = "LMS chirp filterlen %d nx %d noise %.2g mu %.2g " % ( modelorder, nx, noise, damp) print title #............................................................................... msi = featex.MSI(freqs, nx - 1, Fs) mflc = MultiFLC(np.zeros(2 * modelorder), mu=damp) flc = featex.FLC(freqs, nx - 1, Fs) ws = [list() for i in range(len(freqs))] flcs = [list() for i in range(len(freqs))] msis = [list() for i in range(len(freqs))] msiws = [list() for i in range(len(freqs))] errs = [] stds = [] for i in range(0, 100): y1 = X[i * Fs:i * Fs + nx, channel].reshape(nx, len(channel)) # protocol first part, 20s x 2 # f,psd = preprocessing.get_psd(y1[:,0], 3, Fs, config.NFFT)
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()
def filter_and_accuracy(dataFile, signalChannel, noiseChannel): # read data data = sio.loadmat(os.path.join(config.DATA_PATH, dataFile)) data = data['data'] # CAR FILTER & PASSBAND FILTER data -= data.mean(axis=0) # X = np.dot(X, preprocessing.CAR(X.shape[1])) b, a = preprocessing._get_fir_filter(config.WCRITIC, Fs, 251) data = signal.lfilter(b, (a,), data, axis=0) s1 = data[0:160*Fs, np.in1d(SANDRA_SENSORS, signalChannel)]# - X[0:160*Fs, channelN:channelN+1] # protocol first part, 20s x 2 n1 = data[0:160*Fs, np.in1d(SANDRA_SENSORS, noiseChannel)] l1 = offline.make_label_matrix(s1.shape[0], period=20, window=WINLENGTH, fs=Fs, classes=4) 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])) # classifier = processing.PSDA(freqs, nx - fOrder, Fs) classifier = featex.MSI(freqs, nx - fOrder, Fs) outBipolar = np.zeros(signalWindows.shape[0]) outFiltered = np.zeros(signalWindows.shape[0]) SNRsignal = np.zeros(signalWindows.shape[0]) SNRnoise = np.zeros(signalWindows.shape[0]) for ii, (signalWin, noiseWin) in enumerate(zip(signalWindows, noiseWindows)): ys = [] epss = [] bipolar = signalWin[0:nx - fOrder] - noiseWin[0:nx - fOrder] Fxx, Pxx = preprocessing.get_psd(signalWin[:,0], WINLENGTH, Fs, config.NFFT) Fyy, Pyy = preprocessing.get_psd(noiseWin[:,0], WINLENGTH, Fs, config.NFFT) if plot == 1: pl.plot(Fyy[Fyy < 50],Pyy[Fyy < 50]) pl.axvline(x = freqs[l1[ii]], linewidth=2, color='r') pl.axvline(x = freqs[l1[ii]] * 2,linewidth=2, color='r') pl.axvspan(freqs[l1[ii]] - 3, freqs[l1[ii]] + 3, facecolor='r', alpha=.3) pl.axvspan(freqs[l1[ii]] * 2 - 3, freqs[l1[ii]] * 2 + 3, facecolor='r', alpha=.3) pl.show() SNRsignal[ii] = featex.PSDA.compute_SNR(Fxx, Pxx, freqs[l1[ii]], Fs) SNRnoise[ii] = featex.PSDA.compute_SNR(Fyy, Pyy, freqs[l1[ii]], Fs) lms = LMS( np.zeros(fOrder), mu=damp ) for t in xrange( nx - fOrder): XX = noiseWin[t:t+fOrder, :] y = signalWin[t+fOrder, 0] # predict eps = lms.est( XX, y) ys += [y] epss += [eps] y = np.array(ys) sCap = np.array(epss) err = (epss - y)**2 averr = "av %.2g += %.2g" % (err.mean(), err.std()) # print "LMS MSE:", averr # print "LMS weights:", lms.W outBipolar[ii] = freqs.index(classifier.perform(bipolar)) outFiltered[ii] = freqs.index(classifier.perform(np.atleast_2d(sCap).T)) # print outMonopolar[ii], outFiltered[ii], l1[ii] if plot == 2: fig, ax = pl.subplots( nrows=5 ) fig.set_size_inches( 12, 8 ) ax[0].plot( y, color="orangered", label="y" ) ax[0].plot( epss, label="yest" ) ax[0].legend() ax[1].plot( err, label=averr ) ax[1].legend() f,psd = preprocessing.get_psd(signalWin[:,0], 3, Fs, config.NFFT, ax[2]) ax[2].legend() f,psd = preprocessing.get_psd(noiseWin[:,0], 3, Fs, config.NFFT, ax[3]) ax[3].legend() ax[3].axvline(x = freqs[l1[ii]], linewidth=2, color='r') ax[3].axvline(x = freqs[l1[ii]] * 2,linewidth=2, color='r') ax[3].axvspan(freqs[l1[ii]] - 3, freqs[l1[ii]] + 3, facecolor='r', alpha=.3) ax[3].axvspan(freqs[l1[ii]] * 2 - 3, freqs[l1[ii]] * 2 + 3, facecolor='r', alpha=.3) f,psd = preprocessing.get_psd(epss, 3, Fs, config.NFFT, ax[4]) ax[4].legend() ax[4].axvline(x = freqs[l1[ii]], linewidth=2, color='r') ax[4].axvline(x = freqs[l1[ii]] * 2,linewidth=2, color='r') ax[4].axvspan(freqs[l1[ii]] - 3, freqs[l1[ii]] + 3, facecolor='r', alpha=.3) ax[4].axvspan(freqs[l1[ii]] * 2 - 3, freqs[l1[ii]] * 2 + 3, facecolor='r', alpha=.3) pl.show() # print "LMS noise cancellation filterlen %d nx %d noise %s mu %.2g " % ( # fOrder, nx, noiseChannel, damp ) # print 'SNR signal: %f, SNR noise: %f, distorsion: %f, output SNR : %f' % ( # SNRsignal.mean(), SNRnoise.mean(), SNRnoise.mean() / SNRsignal.mean(), np.mean(1 / SNRnoise)) # print performance.get_accuracy(l1, outBipolar), performance.get_accuracy(l1, outFiltered) return performance.get_accuracy(l1, outBipolar), performance.get_accuracy(l1, outFiltered), SNRnoise.mean() / SNRsignal.mean()
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()
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()
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
0:150 * Fs, channelS:channelS + 1] # - X[0:160*Fs, channelN:channelN+1] # protocol first part, 20s x 2 n1 = Y[0:150 * Fs, channelS:channelS + 1] # l1 = offline.make_label_matrix(s1.shape[0], period=20, window=WINLENGTH, fs=Fs, classes=4) #............................................................................... # title = "LMS noise cancellation filterlen %d nx %d noise %.2g mu %.2g " % ( # fOrder, nx, channelN, damp ) # print title 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])) classifier = featex.MSI(freqs, nx - fOrder, Fs) outMonopolar = np.zeros(signalWindows.shape[0]) outFiltered = np.zeros(signalWindows.shape[0]) SNRsignal = np.zeros(signalWindows.shape[0]) SNRnoise = np.zeros(signalWindows.shape[0]) l1 = np.zeros(signalWindows.shape[0]) l1.fill(3) for ii, (signalWin, noiseWin) in enumerate(zip(signalWindows, noiseWindows)): ys = [] epss = [] Fxx, Pxx = preprocessing.get_psd(signalWin[:, 0], WINLENGTH, Fs, config.NFFT) Fyy, Pyy = preprocessing.get_psd(noiseWin[:, 0], WINLENGTH, Fs,