Esempio n. 1
0
from pyOpenBCI import OpenBCICyton
import matplotlib.pyplot as plt


# ax1 = fig1.add_subplot(111)
.show()

i = 0
x1,x2,y1,y2 = [], [], [], []

def plot1(x,y):
	global i
	x1.append(x)
	y1.append(y)
 	plt.plot(x1, y1, color='b')
	fig1.canvas.draw()
	fig1.set_xlim(left=max(0, i-50), right=i+50)
	#time.sleep(0.1)



def print_raw(sample):
	global i
	# print(sample.channels_data[0]) * (4.5)/24/(2**23-1)
	plot1(i,(sample.channels_data[0] * ((4.5)/24/(2**23-1)*1000000)))
	#plot2(i,(sample.channels_data[1] * ((4.5)/24/(2**23-1))))
	i += 1

board = OpenBCICyton(port='/dev/ttyUSB0', daisy=False)

board.start_stream(print_raw)
def start_board():
    board = OpenBCICyton(port='COM8', daisy=False)

    board.start_stream(save_data)
Esempio n. 3
0
Testing sampling frequency when streaming directly with lsl and python

"""
from pyOpenBCI import OpenBCICyton
from pylsl import StreamInfo, StreamOutlet
import numpy as np

SCALE_FACTOR_EEG = (4500000) / 24 / (2**23 - 1)  #uV/count
SCALE_FACTOR_AUX = 0.002 / (2**4)

print("Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n")

info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 8, 250, 'float32', 'OpenBCItestEEG')

print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

outlet_eeg = StreamOutlet(info_eeg)
outlet_aux = StreamOutlet(info_aux)


def lsl_streamers(sample):
    outlet_eeg.push_sample(np.array(sample.channels_data) * SCALE_FACTOR_EEG)
    outlet_aux.push_sample(np.array(sample.aux_data) * SCALE_FACTOR_AUX)


board = OpenBCICyton(port='COM11', daisy=False)

board.start_stream(lsl_streamers)
Esempio n. 4
0
def start_board():  # Hilo configuracion cyton y lectura de datos
    board = OpenBCICyton("COM8",
                         daisy=False)  # LLamado de la clase OpenBCYCyton.
    board.start_stream(
        ui.save_data)  # Se llama el metodo de solicitud de datos.
Esempio n. 5
0
# First you need to install pyOpenBCI using: pip install pyOpenBCI
from pyOpenBCI import OpenBCICyton
from pylsl import StreamInfo, StreamOutlet
import numpy as np

SCALE_FACTOR_EEG = (4500000) / 24 / (2**23 - 1)  #uV/count
SCALE_FACTOR_AUX = 0.002 / (2**4)

info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 16, 125, 'float32',
                      'OpenBCItestEEG')

print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 125, 'float32', 'OpenBCItestAUX')

outlet_eeg = StreamOutlet(info_eeg)
outlet_aux = StreamOutlet(info_aux)


def lsl_streamers(sample):
    outlet_eeg.push_sample(np.array(sample.channels_data) * SCALE_FACTOR_EEG)
    outlet_aux.push_sample(np.array(sample.aux_data) * SCALE_FACTOR_AUX)


board = OpenBCICyton(port='COM3', daisy=True)

board.start_stream(lsl_streamers)
Esempio n. 6
0
from pyOpenBCI import OpenBCICyton
from pylsl import StreamInfo, StreamOutlet
import numpy as np

SCALE_FACTOR_EEG = (4500000)/24/(2**23-1) #uV/count
SCALE_FACTOR_AUX = 0.002 / (2**4)


print("Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n")

info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 8, 250, 'float32', 'OpenBCItestEEG')

print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

outlet_eeg = StreamOutlet(info_eeg)
outlet_aux = StreamOutlet(info_aux)

def lsl_streamers(sample):
    outlet_eeg.push_sample(np.array(sample.channels_data)*SCALE_FACTOR_EEG)
    outlet_aux.push_sample(np.array(sample.aux_data)*SCALE_FACTOR_AUX)

board = OpenBCICyton()

board.start_stream(lsl_streamers)
Esempio n. 7
0
SCALE_FACTOR_AUX = 0.002 / (2**4)

print("Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n")

info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 8, 250, 'float32', 'OpenBCItestEEG')

print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

outlet_eeg = StreamOutlet(info_eeg)
outlet_aux = StreamOutlet(info_aux)


def lsl_streamers(sample):

    outlet_eeg.push_sample(np.array(sample.channels_data) * scale_factor)
    outlet_aux.push_sample(np.array(sample.aux_data) * SCALE_FACTOR_AUX)


board = OpenBCICyton(port='COM3', daisy=False)

while (True):
    try:
        board.start_stream(lsl_streamers)
    except:
        board.stop_stream()
        time.sleep(0.5)
        board.disconnect()
        break
Esempio n. 8
0
    global rawBuffer, filterBuffer
    #print(rawBuffer)
    filterBuffer[:-window_size] = filterBuffer[window_size:]
    filterBuffer[-window_size:] = rawBuffer

    last64 = remove_dc_offset()
    notch_filter()
    bandpass()
    #plot(rawBuffer, last64)
    #plot2()
    #get_spectrum_data()
    #makePlot()
    plt.pause(0.0001)
    ax1.clear()
    #time.sleep(1)


plt.ion()
plt.show()
print("AFTER PYQT")

board = OpenBCICyton(port='/dev/ttyUSB0', daisy=False)
while (True):
    data = board.start_stream(1)
    print(data)
    acquire_raw(data[0])

#t1 = threading.Thread(target=board.start_stream, args=(acquire_raw,))
#board.start_stream(acquire_raw)
#t1.start()
Esempio n. 9
0
        np.squeeze(raw_data),
        NFFT,
        window=mlab.window_hanning,
        Fs=fs_Hz,
        noverlap=overlap)  # returns PSD power per Hz
    # convert the units of the spectral data
    spec_PSDperBin = spec_PSDperHz * fs_Hz / float(NFFT)


def plot_spectrum_avg_fft():

    # print("Generating power spectrum plot")

    spectrum_PSDperHz = np.mean(spec_PSDperHz, 1)
    plt.figure(figsize=(10, 5))
    plt.plot(spec_freqs, 10 * np.log10(spectrum_PSDperHz))  # dB re: 1 uV
    plt.xlim((0, 60))
    plt.ylim((-30, 50))
    # plotname = 'Channel '+str(self.channel)+' Spectrum Average FFT Plot'
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('PSD per Hz (dB re: 1uV^2/Hz)')

    # plt.title(self.plot_title("Power Spectrum"))
    # self.plotit(plt, self.plot_filename("Power Spectrum"))


board = OpenBCICyton(port='/dev/ttyUSB2', daisy=False)

board.start_stream(process_raw)

plt.close()
Esempio n. 10
0
	global i
	x1.append(x)
	y1.append(y)
    
 	ax1.plot(x1, y1, color='b')
	fig1.canvas.draw()
	ax1.set_xlim(left=max(0, i-50), right=i+50)
	#time.sleep(0.1)

def plot2(x,y):
	global i
	x2.append(x)
	y2.append(y)

	ax2.plot(x2, y2, color='b')
	fig2.canvas.draw()
	ax2.set_xlim(left=max(0, i-50), right=i+50)
	#time.sleep(0.1)

def print_raw(sample):
	global i
	print(sample.channels_data) #* (4.5)/24/(2**23-1))
	plot1(i,(sample.channels_data[0] * ((4.5)/24/(2**23-1))))
	plot2(i,(sample.channels_data[1] * ((4.5)/24/(2**23-1))))
	i += 1

board = OpenBCICyton(port='/dev/ttyUSB1', daisy=False)

def save_raw

board.start_stream(save_raw)
Esempio n. 11
0
        keep_block = arr2D.shape[1] * (SAMPLES_PER_FRAME - 1)
        im_data = np.delete(im_data, np.s_[:-keep_block], 1)
        im_data = np.hstack((im_data, arr2D))
        im.set_array(im_data)
    return im,


#main program
arr2D, freqs, bins = get_specgram(streamedData.channels_data[0] * ((4.5)/24/(2**23-1)))
"""
   Setup the plot paramters
   """
extent = (bins[0], bins[-1] * SAMPLES_PER_FRAME, freqs[-1], freqs[0])
im = plt.imshow(arr2D, aspect='auto', extent=extent, interpolation="none",
                cmap='jet', norm=LogNorm(vmin=.01, vmax=1))
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')


plt.title('Real Time Spectogram')
plt.gca().invert_yaxis()
##plt.colorbar() #enable if you want to display a color bar

anim = animation.FuncAnimation(fig, update_fig, blit=False,interval=10)
                               # interval=mic_read.CHUNK_SIZE / 1000)
plt.show(block=False)

board = OpenBCICyton(port='/dev/ttyUSB0', daisy=False)
#call back fn
board.start_stream(get_data)
Esempio n. 12
0
Author: zachandfox
Source Materials: https://docs.openbci.com/OpenBCI%20Software/05-OpenBCI_Python#pyopenbci-installation
    - Keyboard Interrupt: https://stackoverflow.com/questions/4205317/capture-keyboardinterrupt-in-python-without-try-except

Pull in raw data from Cyton Board using bluetooth arduino
"""

from pyOpenBCI import OpenBCICyton
import time
import numpy as np

output = np.zeros(8)
timer = 1000
SCALE_FACTOR_EEG = (4500000) / 24 / (2**23 - 1)  #uV/count

board = OpenBCICyton()

MaxVal = 100000
StepInterval = 1

### start_stream method ###
#def print_raw(sample):
#    try:
#        #output.append(sample.channels_data)
#        print(sample.channels_data)
#        for i in range(1, MaxVal, StepInterval):
#            print(i)
#    except KeyboardInterrupt:
#        for i in range(1, MaxVal, StepInterval):
#            print('INTERRUPTED! Closing in: ', str(MaxVal-i))
#        board.stop_stream()
Esempio n. 13
0
  SCALE_FACTOR_EEG = (4500000)/24/(2**23-1) #uV/count

  # Defining stream info:
  name = 'OpenBCIEEG'
  ID = 'OpenBCItestEEG'
  port = argv[1]
  channels = 8
  sample_rate = 250
  datatype = 'float32'
  streamType = 'EEG'

  print(f"Creating LSL stream for EEG. \nName: {name}\nID: {ID}\n")

  info_eeg = StreamInfo(name, streamType, channels, sample_rate, datatype, ID)
  outlet_eeg = StreamOutlet(info_eeg)

  def lsl_streamer(sample):
      """
      Convert the sample data from it's raw format (counts) to uV and push it
      to the LSL-stream.
      * Input: Raw EEG data from the Cyton board, unit is counts
      * Output: EEG-data formatted as a LSL-sample with unit micro-volts (uV). 

      """
    outlet_eeg.push_sample(np.array(sample.channels_data)*SCALE_FACTOR_EEG)


  # Start the stream:
  board = OpenBCICyton(port=port, daisy=False)
  board.start_stream(lsl_streamer)
Esempio n. 14
0
from pyOpenBCI import OpenBCICyton


def print_raw(sample):
    print(sample.channels_data)


#Set (daisy = True) to stream 16 ch
board = OpenBCICyton(daisy=False)

board.start_stream(print_raw)
Esempio n. 15
0
class OpenBCI(object):
    def __init__(self,
                 port=None,
                 daisy=None,
                 chunk_size=250,
                 method=1,
                 path=None,
                 createSession=True):
        '''
			Initialize all the variables
		'''
        self.port = port
        self.daisy = daisy
        self.chunk_size = chunk_size
        self.method = method  # Read data continously or in chunks of chunk_size
        print("Starting creating streamer....")
        self.streamer = BCI(self.port, self.daisy)
        self.uVolts_per_count = (4.5) / 24 / (
            2**23 - 1
        ) * 1000000  # scalar factor to convert raw data into real world signal data

        #Saving data and naming conventions
        self.homeFolder = os.getcwd()
        self.sessionFolder = self.homeFolder + "/SessionData"
        self.sessionId = time.strftime("SESSION_%Y%m%d_%H%M%S")
        if (path == None):
            self.currentSession = self.sessionFolder + "/" + self.sessionId
        else:
            self.currentSession = self.sessionFolder + "/" + path
        print("Building Session Folders....")
        if (createSession == True):
            self.makeSessionFolder()

    def makeSessionFolder(self):
        if (os.path.isdir(self.sessionFolder) == False):
            os.mkdir(self.sessionFolder)
        if (os.path.isdir(self.currentSession) == False):
            os.mkdir(self.currentSession)

    def read_chunk(self,
                   n_chunks=1,
                   verbose=False,
                   data_only=True,
                   exit_after=False,
                   save_data=False):
        '''
			- Each chunk is defined by "chunk_size".
			- "n_chunks" defines how many chunks of data you want.
			- "data_only" is to say whether you want only the numeric
			  signal data or you want the entire sample points.
			- "exit_after" is for if you want to close the stream after 
			  reading the data.
			- "save_data" if you want to save the raw data some where

			Create a numpy array if the user is requesting for data only
			Use lists if you entire object of the sample.

			The output of this function is an array of shape:
				(n_chunks,chunk_size,n_channels)
		'''
        if (data_only == True):
            t = 0
            data = np.zeros(shape=(1, self.chunk_size, 8))
            for i in range(n_chunks):
                if verbose:
                    print("Reading Chunk: %d " % (i + 1))
                sample = self.streamer.start_stream_ext(
                    method=self.method,
                    chunk_size=self.chunk_size,
                    data_only=data_only)
                sample = np.expand_dims(np.asarray(sample), 0)
                data = np.append(data, sample, 0)
            data = data[1:]
            data = data * self.uVolts_per_count
            if (exit_after == True):
                self.streamer.stop_stream()
            if (save_data == True):
                t = time.strftime("%Y%m%d_%H%M%S")
                np.save(self.currentSession + "/RawData_" + t, data)

            #return (data.transpose(0,2,1),self.currentSession,t)
            return data.transpose(0, 2, 1)
        else:
            data = []
            for i in range(n_chunks):
                print("Reading Chunk: %d " % (i + 1))
                sample = self.streamer.start_stream_ext(
                    method=self.method,
                    chunk_size=self.chunk_size,
                    data_only=data_only)
                data.append(sample)
            if (exit_after == True):
                self.streamer.stop_stream()
            if (save_data == True):
                t = time.strftime("%Y%m%d_%H%M%D")
                with open(self.currentSession + "/RawData_" + t + ".pickle",
                          'w') as f:
                    pickle.dump(data, f)
            return data
Esempio n. 16
0
File: app.py Progetto: node2319/axon
        rawBuffer = []


def process_raw():
    global rawBuffer, filterBuffer
    #print(rawBuffer)
    filterBuffer[:-window_size] = filterBuffer[window_size:]
    filterBuffer[-window_size:] = rawBuffer

    last64 = remove_dc_offset()
    notch_filter()
    lastBandpass = bandpass()
    #plot(rawBuffer, lastBandpass)
    #plot2()
    #get_spectrum_data()
    #makePlot()
    plt.pause(0.0001)
    ax1.clear()
    #time.sleep(1)


plt.ion()
plt.show()
print("AFTER PYQT")

board = OpenBCICyton(port='/dev/ttyUSB1', daisy=False)
board.start_stream(acquire_raw)
#t1 = threading.Thread(target=board.start_stream, args=(acquire_raw,))
#board.start_stream(acquire_raw)
#t1.start()
Esempio n. 17
0
from pyOpenBCI import OpenBCICyton
from pylsl import StreamInfo, StreamOutlet, local_clock
import numpy as np
import time

SCALE_FACTOR_EEG = (4500000) / 24 / (2**23 - 1)  #uV/count
SCALE_FACTOR_AUX = 0.002 / (2**4)

print("Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n")

info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 8, 250, 'float32', 'OpenBCItestEEG')

print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

outlet_eeg = StreamOutlet(info_eeg)
outlet_aux = StreamOutlet(info_aux)


def lsl_streamers(sample):
    outlet_eeg.push_sample(np.array(sample.channels_data) * SCALE_FACTOR_EEG)
    outlet_aux.push_sample(np.array(sample.aux_data) * SCALE_FACTOR_AUX)


board = OpenBCICyton(port='/dev/ttyUSB0')

board.start_stream(lsl_streamers)
Esempio n. 18
0
from pyOpenBCI import OpenBCICyton

board = OpenBCICyton(port='/dev/tty.usbserial-DM01N5XP')
uVolts_per_count = (4500000)/24/(2**23-1) #uV/count
accel_G_per_count = 0.002 / (2**4) #G/count

def print_raw(sample):
    print(sample.channels_data)

board.start_stream(print_raw)
Esempio n. 19
0
        help='Chosse a callback function: print_raw, lsl_stream, or osc_stream.'
    )

    args = parser.parse_args()

    def print_raw(sample):
        print(sample.channels_data)

    callback = eval(args.fun)

    if args.board not in ['Cyton', 'CytonDaisy', 'Ganglion', 'Wifi']:
        sys.exit(
            'No Board Selected. You should use Cyton, CytonDaisy, Ganglion, or Wifi. Try: python openbci_interface.py --board Cyton'
        )
    elif args.board == 'Cyton':
        board = OpenBCICyton(port=args.port)
    elif args.boad == 'CytonDaisy':
        board = OpenBCICyton(port=args.port, daisy=True)
    elif args.board == 'Ganglion':
        if sys.platform.startswith("linux"):
            board = OpenBCIGanglion(mac=args.port)
        else:
            sys.exit(
                'Currently the Ganglion Python repo only works with Linux OS.')
    else:
        board = OpenBCIWiFi()

    valid_commands = '012345678!@#$%^&*qwertyuiQWERTYUI[]pdbsvnN;-=xXDzZASFGHJKLajbs?c<>'

    while True:
        command = input('--> ')
Esempio n. 20
0
from pyOpenBCI import OpenBCICyton
from pylsl import StreamInfo, StreamOutlet
import numpy as np

SCALE_FACTOR_EEG = (4500000) / 24 / (2**23 - 1)  #uV/count
SCALE_FACTOR_AUX = 0.002 / (2**4)

print("Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n")
info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 8, 250, 'float32', 'OpenBCItestEEG')
print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")
info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')
outlet_eeg = StreamOutlet(info_eeg)
outlet_aux = StreamOutlet(info_aux)


def lsl_streamers(sample):
    outlet_eeg.push_sample(np.array(sample.channels_data) * SCALE_FACTOR_EEG)
    outlet_aux.push_sample(np.array(sample.aux_data) * SCALE_FACTOR_AUX)
    #print(np.array(sample.aux_data)*SCALE_FACTOR_AUX)


board = OpenBCICyton(port='/dev/cu.usbserial-DM00D7TW')
board.write_command('/2')  # change the cyton AUX board mode to Analog mode.
board.start_stream(lsl_streamers)