Esempio n. 1
0
def present(duration=120, eeg=None, save_fn=None):
    n_trials = 2010
    iti = 0.4
    soa = 0.3
    jitter = 0.2
    record_duration = np.float32(duration)
    markernames = [1, 2]

    # Setup trial list
    image_type = np.random.binomial(1, 0.5, n_trials)
    trials = DataFrame(
        dict(image_type=image_type, timestamp=np.zeros(n_trials)))

    def load_image(fn):
        return visual.ImageStim(win=mywin, image=fn)

    # Setup graphics
    mywin = visual.Window([1600, 900],
                          monitor='testMonitor',
                          units="deg",
                          fullscr=True)

    targets = list(map(load_image, glob(os.path.join(CAT_DOG,
                                                     'target-*.jpg'))))
    nontargets = list(
        map(load_image, glob(os.path.join(CAT_DOG, 'nontarget-*.jpg'))))
    stim = [nontargets, targets]

    # start the EEG stream, will delay 5 seconds to let signal settle
    if eeg:
        if save_fn is None:  # If no save_fn passed, generate a new unnamed save file
            save_fn = generate_save_fn(eeg.device_name, 'visual_p300',
                                       'unnamed')
            print(
                f'No path for a save file was passed to the experiment. Saving data to {save_fn}'
            )
        eeg.start(save_fn, duration=record_duration)

    # Iterate through the events
    start = time()
    for ii, trial in trials.iterrows():
        # Inter trial interval
        core.wait(iti + np.random.rand() * jitter)

        # Select and display image
        label = trials['image_type'].iloc[ii]
        image = choice(targets if label == 1 else nontargets)
        image.draw()

        # Push sample
        if eeg:
            timestamp = time()
            if eeg.backend == 'muselsl':
                marker = [markernames[label]]
            else:
                marker = markernames[label]
            eeg.push_sample(marker=marker, timestamp=timestamp)

        mywin.flip()

        # offset
        core.wait(soa)
        mywin.flip()
        if len(event.getKeys()) > 0 or (time() - start) > record_duration:
            break

        event.clearEvents()

    # Cleanup
    if eeg: eeg.stop()
    mywin.close()
Esempio n. 2
0
#
# Imports
import os
from eegnb import generate_save_fn
from eegnb.devices.eeg import EEG
from eegnb.experiments.visual_p300 import p300

# Define some variables
board_name = "muse"
experiment = "visual_p300"
subject_id = 0
session_nb = 0
record_duration = 120

###################################################################################################
# Initiate EEG device
# ---------------------
#
# Start EEG device
eeg_device = EEG(device=board_name)

# Create save file name
save_fn = generate_save_fn(board_name, experiment, subject_id, session_nb)
print(save_fn)

###################################################################################################
# Run experiment
# ---------------------
#
p300.present(duration=record_duration, eeg=eeg_device, save_fn=save_fn)
Esempio n. 3
0
def present(record_duration=120,
            stim_types=None,
            itis=None,
            additional_labels={},
            secs=0.07,
            volume=0.8,
            eeg=None,
            save_fn=None):

    markernames = [1, 2]
    record_duration = np.float32(record_duration)

    ## Initialize stimuli
    #aud1 = sound.Sound('C', octave=5, sampleRate=44100, secs=secs)
    aud1 = sound.Sound(440,
                       secs=secs)  #, octave=5, sampleRate=44100, secs=secs)
    aud1.setVolume(volume)

    #aud2 = sound.Sound('D', octave=6, sampleRate=44100, secs=secs)
    aud2 = sound.Sound(528, secs=secs)
    aud2.setVolume(volume)
    auds = [aud1, aud2]

    # Setup trial list
    trials = DataFrame(dict(sound_ind=stim_types, iti=itis))

    for col_name, col_vec in additional_labels.items():
        trials[col_name] = col_vec

    # Setup graphics
    mywin = visual.Window([1920, 1080],
                          monitor='testMonitor',
                          units='deg',
                          fullscr=True)
    fixation = visual.GratingStim(win=mywin,
                                  size=0.2,
                                  pos=[0, 0],
                                  sf=0,
                                  rgb=[1, 0, 0])
    fixation.setAutoDraw(True)
    mywin.flip()
    iteratorthing = 0

    # start the EEG stream, will delay 5 seconds to let signal settle
    if eeg:
        if save_fn is None:  # If no save_fn passed, generate a new unnamed save file
            save_fn = generate_save_fn(eeg.device_name, 'auditoryaMMN',
                                       'unnamed')
            print(
                f'No path for a save file was passed to the experiment. Saving data to {save_fn}'
            )
        eeg.start(save_fn, duration=record_duration)

    show_instructions(10)

    # Start EEG Stream, wait for signal to settle, and then pull timestamp for start point
    start = time()

    # Iterate through the events
    for ii, trial in trials.iterrows():

        iteratorthing = iteratorthing + 1

        # Inter trial interval
        core.wait(trial['iti'])

        # Select and display image
        ind = int(trial['sound_ind'])
        auds[ind].stop()
        auds[ind].play()

        # Push sample
        if eeg:
            timestamp = time()
            if eeg.backend == 'muselsl':
                marker = [additional_labels['labels'][iteratorthing - 1]]
                marker = list(map(int, marker))
            else:
                marker = additional_labels['labels'][iteratorthing - 1]
            eeg.push_sample(marker=marker, timestamp=timestamp)

        mywin.flip()
        if len(event.getKeys()) > 0:
            break
        if (time() - start) > record_duration:
            break

        event.clearEvents()

        if iteratorthing == 1798:
            sleep(10)

    # Cleanup
    if eeg: eeg.stop()

    mywin.close()
Esempio n. 4
0
def present(duration=120,
            eeg=None,
            save_fn=None,
            iti=0.5,
            soa=3.0,
            jitter=0.2,
            n_trials=2010,
            cf1=900,
            amf1=45,
            cf2=770,
            amf2=40.018):

    # Create markers stream outlet
    info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')
    outlet = StreamOutlet(info)

    markernames = [1, 2]
    start = time()

    # Set up trial parameters
    record_duration = np.float32(duration)

    # Set up trial list
    stim_freq = np.random.binomial(1, 0.5, n_trials)
    trials = DataFrame(dict(stim_freq=stim_freq, timestamp=np.zeros(n_trials)))

    # Setup graphics
    mywin = visual.Window([1920, 1080],
                          monitor='testMonitor',
                          units='deg',
                          fullscr=True)
    fixation = visual.GratingStim(win=mywin,
                                  size=0.2,
                                  pos=[0, 0],
                                  sf=0,
                                  rgb=[1, 0, 0])
    fixation.setAutoDraw(True)

    def generate_am_waveform(carrier_freq,
                             am_freq,
                             secs=1,
                             sample_rate=44100,
                             am_type='gaussian',
                             gaussian_std_ratio=8):
        """Generate an amplitude-modulated waveform.

        Generate a sine wave amplitude-modulated by a second sine wave or a
        Gaussian envelope with standard deviation = period_AM/8.

        Args:
            carrier_freq (float): carrier wave frequency, in Hz
            am_freq (float): amplitude modulation frequency, in Hz

        Keyword Args:
            secs (float): duration of the stimulus, in seconds
            sample_rate (float): sampling rate of the sound, in Hz
            am_type (str): amplitude-modulation type
                'gaussian' -> Gaussian with std defined by `gaussian_std`
                'sine' -> sine wave
            gaussian_std_ratio (float): only used if `am_type` is 'gaussian'.
                Ratio between AM period and std of the Gaussian envelope. E.g.,
                gaussian_std = 8 means the Gaussian window has 8 standard
                deviations around its mean inside one AM period.

        Returns:
            (numpy.ndarray): sound samples
        """
        t = np.arange(0, secs, 1. / sample_rate)

        if am_type == 'gaussian':
            period = int(sample_rate / am_freq)
            std = period / gaussian_std_ratio
            norm_window = stats.norm.pdf(np.arange(period), period / 2, std)
            norm_window /= np.max(norm_window)
            n_windows = int(np.ceil(secs * am_freq))
            am = np.tile(norm_window, n_windows)
            am = am[:len(t)]

        elif am_type == 'sine':
            am = np.sin(2 * np.pi * am_freq * t)

        carrier = 0.5 * np.sin(2 * np.pi * carrier_freq * t) + 0.5
        am_out = carrier * am

        return am_out

    # Generate stimuli
    am1 = generate_am_waveform(cf1, amf1, secs=soa, sample_rate=44100)
    am2 = generate_am_waveform(cf2, amf2, secs=soa, sample_rate=44100)

    aud1 = sound.Sound(am1)
    aud1.setVolume(0.8)
    aud2 = sound.Sound(am2)
    aud2.setVolume(0.8)
    auds = [aud1, aud2]

    mywin.flip()

    # start the EEG stream=
    if eeg:
        if save_fn is None:  # If no save_fn passed, generate a new unnamed save file
            save_fn = generate_save_fn(eeg.device_name, 'ssaep', 'unnamed')
            print(
                f'No path for a save file was passed to the experiment. Saving data to {save_fn}'
            )
        eeg.start(save_fn, duration=record_duration)

    for ii, trial in trials.iterrows():
        # Intertrial interval
        core.wait(iti + np.random.rand() * jitter)

        # Select stimulus frequency
        ind = trials['stim_freq'].iloc[ii]
        auds[ind].stop()
        auds[ind].play()

        # Push sample
        if eeg:
            timestamp = time()
            if eeg.backend == 'muselsl':
                marker = [markernames[ind]]
                marker = list(map(int, marker))
            else:
                marker = markernames[ind]
            eeg.push_sample(marker=marker, timestamp=timestamp)

        # offset
        core.wait(soa)
        mywin.flip()
        if len(event.getKeys()) > 0:
            break
        if (time() - start) > record_duration:
            break

        event.clearEvents()

    # Cleanup
    if eeg: eeg.stop()

    mywin.close()
Esempio n. 5
0
def intro_prompt():
    """ This function handles the user prompts for inputting information about the session they wish to record.

    """
    # define the names of the available boards
    boards = [
        'None', 'Muse2016', 'Muse2', 'MuseS', 'OpenBCI Ganglion',
        'OpenBCI Cyton', 'OpenBCI Cyton + Daisy', 'G.Tec Unicorn', 'BrainBit',
        'Notion 1', 'Notion 2', 'Synthetic'
    ]

    # also define the board codes for passing to functions
    board_codes = [
        'none', 'muse2016', 'muse2', 'museS', 'ganglion', 'cyton',
        'cyton_daisy', 'unicorn', 'brainbit', 'notion1', 'notion2', 'synthetic'
    ]

    experiments = [
        'visual-N170', 'visual-P300', 'visual-SSVEP', 'auditory_oddball',
        'auditory-SSAEP'
    ]

    # have the user input which device they intend to record with
    print(
        "Welcome to NeurotechX EEG Notebooks. \n"
        "Please enter the integer value corresponding to your EEG device: \n"
        f"[0] {boards[0]} \n"
        f"[1] {boards[1]} \n"
        f"[2] {boards[2]} \n"
        f"[3] {boards[3]} \n"
        f"[4] {boards[4]} \n"
        f"[5] {boards[5]} \n"
        f"[6] {boards[6]} \n"
        f"[7] {boards[7]} \n"
        f"[8] {boards[8]} \n"
        f"[9] {boards[9]} \n"
        f"[10] {boards[10]} \n", f"[11] {boards[11]} \n")

    board_idx = int(input('Enter Board Selection:'))
    board_selection = board_codes[
        board_idx]  # Board_codes are the actual names to be passed to the EEG class
    print(f"Selected board {boards[board_idx]} \n")

    # Handles wifi shield connectivity selection if an OpenBCI board is being used
    if board_selection in ['cyton', 'cyton_daisy', 'ganglion']:
        # if the ganglion is being used, will also need the MAC address
        if board_selection == 'ganglion':
            print("Please enter the Ganglions MAC address:\n")
            mac_address = input("MAC address:")

        # determine whether board is connected via Wifi or BLE
        print("Please select your connection method:\n"
              "[0] usb dongle \n"
              "[1] wifi shield \n")
        connect_idx = input("Enter connection method:")

        # add "_wifi" suffix to the end of the board name for brainflow
        if connect_idx == 1:
            board_selection = board_selection + "_wifi"

    # Experiment selection
    print("Please select which experiment you would like to run: \n"
          "[0] visual n170 \n"
          "[1] visual p300 \n"
          "[2] ssvep \n"
          "[3] auditory_oddball \n"
          "[4] auditory_ssaep \n")

    exp_idx = int(input('Enter Experiment Selection:'))
    exp_selection = experiments[exp_idx]
    print(f"Selected experiment {exp_selection} \n")

    # record duration
    print("Now, enter the duration of the recording (in seconds). \n")
    duration = int(input("Enter duration:"))

    # Subject ID specification
    print("Next, enter the ID# of the subject you are recording data from. \n")
    subj_id = int(input("Enter subject ID#:"))

    # Session ID specification
    print("Next, enter the session number you are recording for. \n")
    session_nb = int(input("Enter session #:"))

    # start the EEG device
    if board_selection == 'ganglion':
        # if the ganglion is chosen a MAC address should also be proviced
        eeg_device = EEG(device=board_selection, mac_addr=mac_address)
    else:
        eeg_device = EEG(device=board_selection)

    # ask if they are ready to begin
    input("Press [ENTER] when ready to begin...")

    # generate the save file name
    save_fn = generate_save_fn(board_selection, exp_selection, subj_id,
                               session_nb)

    return eeg_device, exp_selection, duration, save_fn
Esempio n. 6
0
def intro_prompt():
    """This function handles the user prompts for inputting information about the session they wish to record."""
    # define the names of the available boards
    boards = [
        "None",
        "Muse2016",
        "Muse2",
        "MuseS",
        "OpenBCI Ganglion",
        "OpenBCI Cyton",
        "OpenBCI Cyton + Daisy",
        "G.Tec Unicorn",
        "BrainBit",
        "Notion 1",
        "Notion 2",
        "Synthetic",
        "FreeEEG32",
    ]

    # also define the board codes for passing to functions
    board_codes = [
        "none",
        "muse2016",
        "muse2",
        "museS",
        "ganglion",
        "cyton",
        "cyton_daisy",
        "unicorn",
        "brainbit",
        "notion1",
        "notion2",
        "synthetic",
        "freeeeg32",
    ]

    experiments = {
        '0': "visual-N170",
        '1': "visual-P300",
        '2': "visual-SSVEP",
        '3a': "auditory-oddball orig",
        '3b': "auditory-oddball diaconescu",
        '4a': "auditory-SSAEP orig",
        "4b": "auditory-SSAEP onefreq"
    }

    # have the user input which device they intend to record with
    print(
        "Welcome to NeurotechX EEG Notebooks. \n"
        "Please enter the integer value corresponding to your EEG device: \n"
        f"[0] {boards[0]} \n"
        f"[1] {boards[1]} \n"
        f"[2] {boards[2]} \n"
        f"[3] {boards[3]} \n"
        f"[4] {boards[4]} \n"
        f"[5] {boards[5]} \n"
        f"[6] {boards[6]} \n"
        f"[7] {boards[7]} \n"
        f"[8] {boards[8]} \n"
        f"[9] {boards[9]} \n"
        f"[10] {boards[10]} \n",
        f"[11] {boards[11]} \n",
        f"[12] {boards[12]} \n",
    )

    board_idx = int(input("Enter Board Selection: "))
    board_selection = board_codes[
        board_idx]  # Board_codes are the actual names to be passed to the EEG class
    print(f"Selected board {boards[board_idx]} \n")

    # Handles connectivity selection if an OpenBCI board is being used
    if board_selection in ["cyton", "cyton_daisy", "ganglion"]:

        # determine whether board is connected via Wifi or BLE
        print("Please select your connection method:\n"
              "[0] usb dongle \n"
              "[1] wifi shield \n")
        connect_idx = int(input("Enter connection method: "))

        # add "_wifi" suffix to the end of the board name for brainflow
        if connect_idx == 1:
            board_selection = board_selection + "_wifi"

        if board_selection == "ganglion":
            # If the Ganglion is being used, you can enter optional Ganglion mac address
            ganglion_mac_address = input(
                "\nGanglion MAC Address (Press Enter to Autoscan): ")
        elif board_selection == "ganglion_wifi":
            # IP address is required for this board configuration
            ip_address = input("\nEnter Ganglion+WiFi IP Address: ")
        elif board_selection == "cyton_wifi" or board_selection == "cyton_daisy_wifi":
            print(
                f"\n{boards[board_idx]} + WiFi is not supported. Please use the dongle that was shipped with the device.\n"
            )
            exit()

    # Experiment selection
    print("\nPlease select which experiment you would like to run: \n"
          "[0] visual n170 \n"
          "[1] visual p300 \n"
          "[2] ssvep \n"
          "[3a] auditory oddball, orig version\n"
          "[3b] auditory oddball, diaconescu version\n"
          "[4a] auditory ssaep, orig version \n"
          "[4b] auditory ssaep, single freq version\n")

    exp_idx = str(input("Enter Experiment Selection: "))
    exp_selection = experiments[exp_idx]
    print(f"Selected experiment {exp_selection} \n")

    # record duration
    print("Now, enter the duration of the recording (in seconds). \n")
    duration = int(input("Enter duration: "))

    # Subject ID specification
    print(
        "\nNext, enter the ID# of the subject you are recording data from. \n")
    subj_id = int(input("Enter subject ID#: "))

    # Session ID specification
    print("\nNext, enter the session number you are recording for. \n")
    session_nb = int(input("Enter session #: "))

    # start the EEG device
    if board_selection.startswith("ganglion"):
        if board_selection == "ganglion_wifi":
            eeg_device = EEG(device=board_selection, ip_addr=ip_address)
        else:
            eeg_device = EEG(device=board_selection,
                             mac_addr=ganglion_mac_address)
    else:
        eeg_device = EEG(device=board_selection)

    # ask if they are ready to begin
    print("\nEEG device successfully connected!")
    input("Press [ENTER] when ready to begin...")

    # generate the save file name
    save_fn = generate_save_fn(board_selection, exp_selection, subj_id,
                               session_nb)

    return eeg_device, exp_selection, duration, save_fn