Пример #1
0
def dataStream():
    global delta_waves
    global alpha_waves
    global beta_waves
    global theta_waves

    try:
        # The following loop acquires data, computes band powers, and calculates neurofeedback metrics based on those band powers
        while True:
            eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                                   max_samples=int(
                                                       SHIFT_LENGTH * fs))

            ch_data = np.array(eeg_data)[:, INDEX_CHANNEL]

            eeg_buffer, filter_state = utils.update_buffer(
                eeg_buffer, ch_data, notch=True, filter_state=filter_state)

            data_epoch = utils.get_last_data(eeg_buffer, EPOCH_LENGTH * fs)

            band_powers = utils.compute_band_powers(data_epoch, fs)
            band_buffer, _ = utils.update_buffer(band_buffer,
                                                 np.asarray([band_powers]))

            smooth_band_powers = np.mean(band_buffer, axis=0)

            delta_waves = band_powers[Band.Delta]
            theta_waves = band_powers[Band.Theta]
            alpha_waves = band_powers[Band.Alpha]
            beta_waves = band_powers[Band.Beta]

    except Exception as e:
        print(e)
Пример #2
0
    def _get_data_epoch(self, eeg_buffer):
        """ Get newest samples from the buffer

        :param eeg_buffer:
        :return:
        """
        data_epoch = utils.get_last_data(eeg_buffer,
                                         utils.EPOCH_LENGTH * self.fs)
        return data_epoch
Пример #3
0
def get_average_blink(eye_index):
    eeg_buffer = np.zeros((int(fs * BUFFER_LENGTH), 1))
    filter_state = None
    eye = "left" if eye_index == INDEX_CHANNEL_LEFT else "right"
    print("Please blink your " + eye + " eye. Press enter when done.")
    maxMatches = []
    stop_flag = []
    _thread.start_new_thread(input_thread, (stop_flag, ))
    i = 10  # number of times to run after user presses enter
    while i > 0:
        if stop_flag:
            i = i - 1
        eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                               max_samples=int(SHIFT_LENGTH *
                                                               fs))

        # Only keep the channel we're interested in
        ch_data = np.array(eeg_data)[:, eye_index]

        # Update EEG buffer with the new data
        eeg_buffer, filter_state = utils.update_buffer(
            eeg_buffer, ch_data, notch=True, filter_state=filter_state)
        """ 3.2 COMPUTE BAND POWERS """
        # Get newest samples from the buffer
        data_epoch = utils.get_last_data(eeg_buffer, int(EPOCH_LENGTH * fs))
        matchFilt = signal.hilbert(filt)
        matches = signal.correlate(matchFilt, data_epoch[:, 0])
        matchesAbs = np.abs(matches[:])
        maxMatches.append((np.max(matchesAbs) / 1e5).astype(int))

    maxMatchesIdx = np.argmax(maxMatches)
    idx = maxMatchesIdx
    peakValues = []
    stop_flag = 1
    check_right_side = False
    while True:
        if idx > 0 and idx < len(maxMatches) - 1:
            idx = idx + (1 if stop_flag == 2 else -1)
            possPeak = maxMatches[idx]
            if maxMatches[maxMatchesIdx] * 0.6 < possPeak:
                peakValues.append(possPeak)
            elif stop_flag == 2:
                break
            else:
                check_right_side = True
        elif stop_flag == 2:
            break
        else:
            check_right_side = True
        if check_right_side:
            idx = maxMatchesIdx
            stop_flag = 2
            check_right_side = False

    return peakValues
Пример #4
0
def readData(eeg_buffer, filter_state, n_win_test, band_buffer):

    """ ACQUIRE DATA """
    eeg_data, timestamp = inlet.pull_chunk(timeout=1, max_samples=int(SHIFT_LENGTH * fs))
    ch_data = np.array(eeg_data)[:, INDEX_CHANNEL]
    eeg_buffer, filter_state = utils.update_buffer(eeg_buffer, ch_data, notch=True, filter_state=filter_state)

    """ COMPUTE BAND POWERS """
    data_epoch = utils.get_last_data(eeg_buffer, EPOCH_LENGTH * fs)
    band_powers = utils.compute_band_powers(data_epoch, fs)

    return band_powers
Пример #5
0
def get_dada():
	""" 3.1 ACQUIRE DATA """
	# Obtain EEG data from the LSL stream
	global eeg_buffer
	global filter_state
	global band_buffer

	global file

	eeg_data, timestamp = inlet.pull_chunk(
		timeout=1, max_samples=int(SHIFT_LENGTH * fs))

	# Only keep the channel we're interested in
	ret = [None]*4
	for i in range(4):
		ch_data = np.array(eeg_data)[:, i]#he tocat aixo

		# Update EEG buffer with the new data
		eeg_buffer, filter_state = utils.update_buffer(
			eeg_buffer, ch_data, notch=True,
			filter_state=filter_state)

		""" 3.2 COMPUTE BAND POWERS """
		# Get newest samples from the buffer
		data_epoch = utils.get_last_data(eeg_buffer,
											EPOCH_LENGTH * fs)

		# Compute band powers
		band_powers = utils.compute_band_powers(data_epoch, fs)
		band_buffer, _ = utils.update_buffer(band_buffer,
												np.asarray([band_powers]))
		# Compute the average band powers for all epochs in buffer
		# This helps to smooth out noise
		smooth_band_powers = np.mean(band_buffer, axis=0)

		# print('Delta: ', band_powers[Band.Delta], ' Theta: ', band_powers[Band.Theta],
		#       ' Alpha: ', band_powers[Band.Alpha], ' Beta: ', band_powers[Band.Beta])
		#file.write("%lf,%lf,%lf,%lf\n" % (band_powers[Band.Alpha],band_powers[Band.Beta],band_powers[Band.Delta],band_powers[Band.Theta]))
		""" 3.3 COMPUTE NEUROFEEDBACK METRICS """
		# These metrics could also be used to drive brain-computer interfaces

		# Alpha Protocol:
		# Simple redout of alpha power, divided by delta waves in order to rule out noise
		#return (10 + (smooth_band_powers[Band.Alpha] / \
		#	smooth_band_powers[Band.Delta]))**5
		ret[i] = (smooth_band_powers[Band.Alpha] / smooth_band_powers[Band.Delta])
		#acum += (smooth_band_powers[Band.Alpha] - smooth_band_powers[Band.Delta])
	return ret
Пример #6
0
def animate(i, eeg_buffer, filter_state, n_win_test, band_buffer):

    global t, start_time
    """ 3.1 ACQUIRE DATA """
    eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                           max_samples=int(SHIFT_LENGTH * fs))
    ch_data = np.array(eeg_data)[:, INDEX_CHANNEL]
    eeg_buffer, filter_state = utils.update_buffer(eeg_buffer,
                                                   ch_data,
                                                   notch=True,
                                                   filter_state=filter_state)
    """ 3.2 COMPUTE BAND POWERS """
    data_epoch = utils.get_last_data(eeg_buffer, EPOCH_LENGTH * fs)
    band_powers = utils.compute_band_powers(data_epoch, fs)

    # Add x and y to lists
    sensor['A'].append(band_powers[0])
    sensor['B'].append(band_powers[1])
    sensor['G'].append(band_powers[2])
    sensor['T'].append(band_powers[3])
    t.append(((time.time()) - start_time))

    # Limit x and y lists to 20 items
    sensor['A'] = sensor['A'][-40:]
    sensor['B'] = sensor['B'][-40:]
    sensor['G'] = sensor['G'][-40:]
    sensor['T'] = sensor['T'][-40:]
    t = t[-40:]

    # Draw x and y lists
    ax.clear()
    ax.plot(t, sensor['A'], color="blue")
    ax.plot(t, sensor['B'], color="red")
    ax.plot(t, sensor['G'], color="green")
    ax.plot(t, sensor['T'], color="black")

    # Format plot
    plt.title('sensor')
    plt.ylabel('data')
    plt.xlabel('time')
    plt.ylim(-2, 4)
Пример #7
0
                              startTime).total_seconds()
            """ 3.1 ACQUIRE DATA """
            # Obtain EEG data from the LSL stream
            eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                                   max_samples=int(
                                                       SHIFT_LENGTH * fs))

            # Only keep the channel we're interested in
            ch_data = np.array(eeg_data)[:, INDEX_CHANNEL]

            # Update EEG buffer with the new data
            eeg_buffer, filter_state = utils.update_buffer(
                eeg_buffer, ch_data, notch=True, filter_state=filter_state)
            """ 3.2 COMPUTE BAND POWERS """
            # Get newest samples from the buffer
            data_epoch = utils.get_last_data(eeg_buffer, EPOCH_LENGTH * fs)

            # Compute band powers
            band_powers = utils.compute_band_powers(data_epoch, fs)
            band_buffer, _ = utils.update_buffer(band_buffer,
                                                 np.asarray([band_powers]))
            # Compute the average band powers for all epochs in buffer
            # This helps to smooth out noise
            smooth_band_powers = np.mean(band_buffer, axis=0)

            print('Delta: ', band_powers[Band.Delta], ' Theta: ',
                  band_powers[Band.Theta], ' Alpha: ', band_powers[Band.Alpha],
                  ' Beta: ', band_powers[Band.Beta])
            """ 3.3 COMPUTE NEUROFEEDBACK METRICS """
            # These metrics could also be used to drive brain-computer interfaces
Пример #8
0
def recordData():
    global timeReadings
    """ 1. CONNECT TO EEG STREAM """

    # Search for active LSL streams
    print('Looking for an EEG stream...')
    streams = resolve_byprop('type', 'EEG', timeout=2)
    if len(streams) == 0:
        raise RuntimeError('Can\'t find EEG stream.')

    # Set active EEG stream to inlet and apply time correction
    print("Start acquiring data")
    inlet = StreamInlet(streams[0], max_chunklen=12)
    eeg_time_correction = inlet.time_correction()

    # Get the stream info and description
    info = inlet.info()
    description = info.desc()

    # Get the sampling frequency
    # This is an important value that represents how many EEG data points are
    # collected in a second. This influences our frequency band calculation.
    # for the Muse 2016, this should always be 256
    fs = int(info.nominal_srate())
    """ 2. INITIALIZE BUFFERS """

    # Initialize raw EEG data buffer
    eeg_buffer = np.zeros((int(fs * BUFFER_LENGTH), 1))
    filter_state = None  # for use with the notch filter

    # Compute the number of epochs in "buffer_length"
    n_win_test = int(
        np.floor((BUFFER_LENGTH - EPOCH_LENGTH) / SHIFT_LENGTH + 1))

    # Initialize the band power buffer (for plotting)
    # bands will be ordered: [delta, theta, alpha, beta]
    band_buffer = np.zeros((n_win_test, 4))
    """ 3. GET DATA """

    # The try/except structure allows to quit the while loop by aborting the
    # script with <Ctrl-C>
    # print('Press Ctrl-C in the console to break the while loop.')
    i = 0

    try:
        #     # The following loop acquires data, computes band powers, and calculates neurofeedback metrics based on those band powers
        while temp:
            """ 3.1 ACQUIRE DATA """
            # Obtain EEG data from the LSL stream
            eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                                   max_samples=int(
                                                       SHIFT_LENGTH * fs))

            # Only keep the channel we're interested in
            ch_data = np.array(eeg_data)[:, INDEX_CHANNEL]

            # Update EEG buffer with the new data
            eeg_buffer, filter_state = utils.update_buffer(
                eeg_buffer, ch_data, notch=True, filter_state=filter_state)
            """ 3.2 COMPUTE BAND POWERS """
            # Get newest samples from the buffer
            data_epoch = utils.get_last_data(eeg_buffer, EPOCH_LENGTH * fs)

            # Compute band powers
            band_powers = utils.compute_band_powers(data_epoch, fs)
            band_buffer, _ = utils.update_buffer(band_buffer,
                                                 np.asarray([band_powers]))
            # Compute the average band powers for all epochs in buffer
            # This helps to smooth out noise
            smooth_band_powers = np.mean(band_buffer, axis=0)

            # print('Delta: ', band_powers[Band.Delta], ' Theta: ', band_powers[Band.Theta],
            #       ' Alpha: ', band_powers[Band.Alpha], ' Beta: ', band_powers[Band.Beta])
            """ 3.3 COMPUTE NEUROFEEDBACK METRICS """
            # These metrics could also be used to drive brain-computer interfaces

            # Alpha Protocol:
            # Simple redout of alpha power, divided by delta waves in order to rule out noise
            alpha_metric = smooth_band_powers[Band.Alpha] / \
                smooth_band_powers[Band.Delta]
            alphaReadings.append(alpha_metric)
            # print('Alpha Relaxation: ', alpha_metric)

            # Beta Protocol:
            # Beta waves have been used as a measure of mental activity and concentration
            # This beta over theta ratio is commonly used as neurofeedback for ADHD
            beta_metric = smooth_band_powers[Band.Beta] / \
                smooth_band_powers[Band.Theta]
            betaReadings.append(beta_metric)
            # print('Beta Concentration: ', beta_metric)

            # Alpha/Theta Protocol:
            # This is another popular neurofeedback metric for stress reduction
            # Higher theta over alpha is supposedly associated with reduced anxiety
            theta_metric = smooth_band_powers[Band.Theta] / \
                smooth_band_powers[Band.Alpha]
            thetaReadings.append(theta_metric)

            dt = datetime.datetime.now().strftime("%x %X")
            if dt in timeReadings.keys():
                tempDt = timeReadings[dt]
                aph = tempDt['alpha']
                bth = tempDt['beta']
                tth = tempDt['theta']
                aph.append(alpha_metric)
                bth.append(beta_metric)
                tth.append(theta_metric)
            else:
                timeReadings = {
                    dt: {
                        "alpha": [alpha_metric],
                        "beta": [beta_metric],
                        "theta": [theta_metric]
                    }
                }
                result.append(timeReadings)
            i = i + 1

    except KeyboardInterrupt:
        print('Closing!')
Пример #9
0
        while True:
            """ 3.1 ACQUIRE DATA """
            # Obtain EEG data from the LSL stream
            eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                                   max_samples=int(
                                                       SHIFT_LENGTH * fs))

            # Only keep the channel we're interested in
            ch_data = np.array(eeg_data)[:, INDEX_CHANNEL]

            # Update EEG buffer with the new data
            eeg_buffer, filter_state = utils.update_buffer(
                eeg_buffer, ch_data, notch=True, filter_state=filter_state)
            """ 3.2 COMPUTE BAND POWERS """
            # Get newest samples from the buffer
            data_epoch = utils.get_last_data(eeg_buffer, EPOCH_LENGTH * fs)

            # Compute band powers
            #band_powers = utils.compute_band_powers(data_epoch, fs)
            #band_buffer, _ = utils.update_buffer(band_buffer,
            #np.asarray([band_powers]))
            # Compute the average band powers for all epochs in buffer
            # This helps to smooth out noise
            #smooth_band_powers = np.mean(band_buffer, axis=0)

            # print('Delta: ', band_powers[Band.Delta], ' Theta: ', band_powers[Band.Theta],
            #       ' Alpha: ', band_powers[Band.Alpha], ' Beta: ', band_powers[Band.Beta])
            """ 3.3 COMPUTE NEUROFEEDBACK METRICS """
            # These metrics could also be used to drive brain-computer interfaces

            # Alpha Protocol:
Пример #10
0
            eeg_data, timestamp = inlet.pull_chunk(timeout=1,
                                                   max_samples=int(
                                                       SHIFT_LENGTH * fs))

            # Only keep the channel we're interested in
            ch_data = np.array(eeg_data)[:, INDEX_CHANNEL_LEFT]

            # Update EEG buffer with the new data
            eeg_buffer_left, filter_state_left = utils.update_buffer(
                eeg_buffer_left,
                ch_data,
                notch=True,
                filter_state=filter_state_left)
            """ 3.2 COMPUTE BAND POWERS """
            # Get newest samples from the buffer
            data_epoch = utils.get_last_data(eeg_buffer_left,
                                             int(EPOCH_LENGTH * fs))
            #print(data_epoch.shape)

            matchFilt = signal.hilbert(filt)

            matches = signal.correlate(matchFilt, data_epoch[:, 0])

            matchesAbs = np.abs(matches[:])

            maxMatch = np.max(matchesAbs) / 1e5
            maxMatchL = maxMatch

            if maxMatch > left_thresh:
                newTime = datetime.datetime.now()
                if (newTime - oldTimeL).total_seconds() * 1000 > left_delay:
                    print('selector')