Ejemplo n.º 1
0
def stimuli(canvas):
    cue = reiz.Cue(
        canvas=canvas,
        audiostim=reiz.audio.library.beep,
        visualstim=reiz.visual.library.go,
    )
    N = reiz.Cue(canvas=canvas, audiostim=None, visualstim=None)
    return cue, N
Ejemplo n.º 2
0
def test_sanitization(rmarker, capsys):
    assert rmarker
    out, err = capsys.readouterr()
    reiz.marker.push("ä ö ü")
    out, err = capsys.readouterr()
    assert "Sending ae_oe_ue " in out
    out, err = capsys.readouterr()
    reiz.marker.push("ping")
    out, err = capsys.readouterr()
    assert 'Sending {"msg": "ping"}' in out
    out, err = capsys.readouterr()
    reiz.marker.push("poison-pill")
    out, err = capsys.readouterr()
    assert 'Sending {"msg": "poison-pill"}' in out

    c = reiz.Canvas((10, 10))
    reiz.audio.library.beep.volume = 0
    cue = reiz.Cue(
        canvas=c,
        audiostim=reiz.audio.library.beep,
        visualstim=reiz.visual.library.go,
        markerstr="test",
    )

    out, err = capsys.readouterr()
    cue.show()
    out, err = capsys.readouterr()
    assert "Sending test at" in out
Ejemplo n.º 3
0
 def countdown(canvas, sek):
     for i in range(0, sek):
         cue = reiz.Cue(canvas,
                        visualstim=[
                            bg,
                            Mural(text=str(sek - i),
                                  color=(0.18, 0.18, 0.18))
                        ])
         cue.show(duration=1)
Ejemplo n.º 4
0
def start(trials=5):
    canvas = reiz.Canvas()
    canvas.open()

    bg = Background(color='red')

    def countdown(canvas, sek):
        for i in range(0, sek):
            cue = reiz.Cue(canvas,
                           visualstim=[
                               bg,
                               Mural(text=str(sek - i),
                                     color=(0.18, 0.18, 0.18))
                           ])
            cue.show(duration=1)

    pre = reiz.Cue(canvas, visualstim=[bg, reiz.visual.library.pre])
    post = reiz.Cue(canvas, visualstim=[bg, reiz.visual.library.post])
    f5 = reiz.Cue(canvas,
                  visualstim=[bg, reiz.visual.Mural('Press F5 to start')])
    open_eyes = Message('Open eyes')
    close_eyes = Message('Close eyes')
    augen_auf = reiz.Cue(canvas,
                         audiostim=reiz.audio.library.beep,
                         visualstim=[bg, reiz.visual.library.fixation],
                         markerstr='augen_auf')

    augen_zu = reiz.Cue(canvas,
                        audiostim=reiz.audio.library.beep,
                        visualstim=[bg, reiz.visual.library.fixation],
                        markerstr='augen_zu')

    while not canvas.start_run:
        f5.show(duration=1)

    pre.show(duration=3)

    for trl_num in range(trials):
        augen_auf.show(duration=30)
        augen_zu.show(duration=30)
    post.show(duration=3)

    canvas.close()
Ejemplo n.º 5
0
def bmi_main():
    import numpy as np
    import matplotlib.pyplot as plt
    import time, reiz, liesl
    from reiz.visual import Mural, Background
    canvas = reiz.Canvas()
    canvas.open()

    def countdown(canvas, sek):
        for i in range(0, sek):
            cue = reiz.Cue(canvas,
                           visualstim=[
                               bg,
                               Mural(text=str(sek - i),
                                     color=(0.18, 0.18, 0.18))
                           ])
            cue.show(duration=1)

    def part2(cuetype, image_lib):
        if "Nothing" in cuetype:
            DispImage = image_lib.Nothing
        elif "Imagine" in cuetype:
            DispImage = image_lib.Imagine
        elif "Open" in cuetype:
            DispImage = image_lib.Open
        elif "Close" in cuetype:
            DispImage = image_lib.Close
        return DispImage

    bg = Background(color='gray')
    states = ("Nothing", "Imagine", "Open", "Close")
    image_lib = reiz.visual.read_folder(
        r'C:\Users\Messung\Desktop\study-phase-triggered-TMS\phase_triggered_tms\pre_post'
    )
    nBlocks = 3
    tiles = np.tile(states, (4))
    block_tiles = np.tile(states, (nBlocks, 4))
    for i in range(nBlocks):
        block_tiles[i, :] = np.random.permutation(tiles)

    canvas.start_run = False
    start_protocol = reiz.Cue(canvas,
                              visualstim=[
                                  bg,
                                  Mural(text='Press F5 to start BMI',
                                        color=(0.18, 0.18, 0.18))
                              ])
    while not canvas.start_run:
        start_protocol.show(duration=0.1)
    countdown(canvas, 3)

    reiz.Cue(canvas,
             visualstim=[
                 bg,
                 reiz.visual.Mural("BMI Task:",
                                   position=[0, 0.5],
                                   fontsize=1.5,
                                   color=(0.18, 0.18, 0.18)),
                 reiz.visual.Mural("Bitte folgen Sie den Anweisungen",
                                   position=[0, -0.25],
                                   fontsize=1,
                                   color=(0.18, 0.18, 0.18))
             ]).show(duration=5)

    reiz.Cue(canvas,
             visualstim=[
                 bg,
                 reiz.visual.Mural("Bilder werden angezeigt.",
                                   position=[0, 0.4],
                                   fontsize=1,
                                   color=(0.18, 0.18, 0.18)),
                 reiz.visual.Mural("Bitte 3 Sekunden lang durchführen",
                                   position=[0, -0.4],
                                   fontsize=1,
                                   color=(0.18, 0.18, 0.18))
             ]).show(5)

    reiz.Cue(canvas,
             visualstim=[
                 bg, image_lib.Open,
                 reiz.visual.Mural("Öffnen Ihre rechte Hand",
                                   position=[0, 0.7],
                                   fontsize=1,
                                   color=(0.18, 0.18, 0.18))
             ]).show(5)
    reiz.Cue(canvas,
             visualstim=[
                 bg, image_lib.Close,
                 reiz.visual.Mural("Schließe Ihre rechte Hand",
                                   position=[0, 0.7],
                                   fontsize=1,
                                   color=(0.18, 0.18, 0.18))
             ]).show(5)
    reiz.Cue(canvas,
             visualstim=[
                 bg, image_lib.Imagine,
                 reiz.visual.Mural(
                     "Stellen sich vor Ihre rechte Hand zu öffnen",
                     position=[0, 0.7],
                     fontsize=0.7,
                     color=(0.18, 0.18, 0.18))
             ]).show(5)
    reiz.Cue(canvas,
             visualstim=[
                 bg, image_lib.Nothing,
                 reiz.visual.Mural("Mach nichts",
                                   position=[0, 0.7],
                                   fontsize=1,
                                   color=(0.18, 0.18, 0.18))
             ]).show(10)

    reiz.marker.push('bmi_start')
    for k in range(nBlocks):

        canvas.start_run = False
        start_protocol = reiz.Cue(canvas,
                                  visualstim=[
                                      bg,
                                      Mural(text="Press F5 to start block " +
                                            str(k + 1),
                                            color=(0.18, 0.18, 0.18))
                                  ])

        while not canvas.start_run:
            start_protocol.show(duration=0.1)
        countdown(canvas, 3)

        for cue in range(np.size(block_tiles, 1)):
            reiz.marker.push("prepare_" + str(k) + '_' + str(cue))
            reiz.Cue(canvas,
                     visualstim=[
                         bg,
                         reiz.visual.Mural("Bereitmachen",
                                           position=[0, 0.4],
                                           fontsize=1,
                                           color=(0.18, 0.18, 0.18))
                     ]).show(3)

            reiz.marker.push(
                str(block_tiles[k, cue]) + '_' + str(k) + '_' + str(cue))
            reiz.Cue(canvas,
                     visualstim=[bg, part2(block_tiles[k, cue],
                                           image_lib)]).show(3)

            reiz.marker.push("relax_" + str(k) + '_' + str(cue))
            reiz.Cue(canvas,
                     visualstim=[
                         bg,
                         reiz.visual.Mural("Entspannen",
                                           position=[0, -0.4],
                                           fontsize=1,
                                           color=(0.18, 0.18, 0.18))
                     ]).show(5)

    reiz.marker.push('bmi_end')
    canvas.close()
Ejemplo n.º 6
0
def countdown(canvas, sek):
    for i in range(0, sek):
        cue = reiz.Cue(canvas, visualstim=Mural(text=str(sek - i)))
        cue.show(duration=1)
Ejemplo n.º 7
0
def start_intervention(cfg, condition, stim_number, verbose: bool = False):
    RMT = get_RMT(max_percent_RMT=120)
    run_length = int(cfg['main']['run_length'])
    condition_idx = condition['index']
    """Save the condition"""
    condition_order_directory = cfg['main']['recordings_path'] + "\\" + cfg[
        'general']['subject_token'] + '\\condition_%s\\config\\' % condition_idx
    condition_order_file_path = condition_order_directory + 'config.json'
    try:
        with open(condition_order_file_path) as json_file:
            stimuli = json.load(json_file)
        print('Loaded condition file')
        break_idx, timeleft = create_break_idx_timeleft(
            stimuli, condition, run_length)
        stimuli = stimuli[stim_number:]
    except:
        stimuli = create_stim_list(condition, cfg)
        print('create new condition file')
        break_idx, timeleft = create_break_idx_timeleft(
            stimuli, condition, run_length)
        os.makedirs(condition_order_directory)
        with open(condition_order_file_path, 'w') as file:
            file.write(json.dumps(stimuli))  #überschreibt immer
        print('Created new condition file')
    """Check if all streams are available"""
    #    streamargs = [{'name':"localite_marker"},   # comments: make a real list
    #                  {'name':"reiz-marker"},
    #                  {'name':"eego"},
    #                  {'name':"LuckyLoop"},
    #                  {'name':"pupil_capture"},
    #                  {'name':"GDX-RB_0K2002A1"}]

    streamargs = [{'name': "eego"}]

    session = Session(prefix=cfg['general']['subject_token'],
                      streamargs=streamargs)
    """Define stimulation intensity"""
    stimulation_intensity = round(condition['percent_RMT'] * RMT / 100)
    print(f"Stimulation intensity {stimulation_intensity}")
    """"Calculate the time duration for the intervention"""
    #    TMS_stimulus = {'stim_type': 'TMS', 'frequency':condition['frequency'], 'phase':condition['phase_in_deg']}
    #    N = stimuli.count(TMS_stimulus)
    #    expected_duration = (N * 10) / 60
    #    print(f'Expected duration is around {expected_duration:.2f} min')

    #%%
    """Intit Lucky Client"""
    print("Init lucky")
    #lucky = LuckyClient('134.2.117.144')
    """Init Coil"""
    print("Init coil")
    coil = Coil(0)
    time.sleep(.8)
    coil.amplitude = stimulation_intensity
    time.sleep(.8)
    """Init Sandy"""
    print("Init sandy")
    #    sandy_cli = sandy.Arduino(timeout=1.5, version =  'v0.3.1 - StalwartSandy')
    #    sandy_cli.reset()
    #    sandy_cli.set_threshold(150)
    #    sandy_cli.blink(5)
    #sandy_cli.set_threshold(0)
    print("Sandy in standby")
    time.sleep(1)
    """Create the GUI"""
    canvas = Canvas()
    canvas.open()
    labcue = reiz.Cue(canvas, visualstim=reiz.visual.library.logo)
    labcue.show(duration=2)

    #%%
    with session("TMS_intervention"):
        print("Started recording")
        canvas.window.start_run = False
        start_protocol = reiz.Cue(
            canvas, visualstim=Mural(text='Start protocol with F5'))
        print("Waiting for user to start in GUI")

        while not canvas.window.start_run:
            start_protocol.show(duration=1)
        countdown(canvas, 5)
        labcue.show()

        t0 = time.time()
        break_counter = 0
        reaction_times = []
        """ set up phase and frequency parameter """
        phase = condition['phase_in_deg']
        frequency = condition['frequency']
        lucky.phase = phase
        lucky.frequency = frequency

        for single_stimulus in stimuli:
            """get some parameter informations"""
            stimulus_idx = single_stimulus['stimulus_idx']
            stim_type = single_stimulus['stim_type']

            print(f"Stimulation index {single_stimulus['stimulus_idx']}")
            time.sleep(0.5)
            time_setup_trial = time.time()

            # sends current setup as marker
            push(json.dumps({
                'stimulus_idx': str(stimulus_idx),
                'stim_type': stim_type,
                'freq': str(frequency),
                'phase': str(phase)
            }),
                 sanitize=False)
            if verbose:
                print("Start " + stim_type + " for frequency " +
                      str(frequency) + ' and phase ' + str(phase))

            # conditional of stimtype, setup TMS and Arduino this trial
            if stim_type == 'TMS':
                coil.amplitude = stimulation_intensity
                time.sleep(.8)
                t1 = time.time()
                trial_time = t1 - t0
                if verbose:
                    print("\n Trial time: " + str(trial_time))
                # TG: wait and trigger phase and frequency dependent, if next stimuli is TMS, then wait 10s, else wait 5s
                if stimulus_idx < (stimuli[-1]['stimulus_idx']) and stimuli[
                        stimulus_idx - stim_number + 1]['stim_type'] == 'TMS':
                    sleep_time = random_time(min=9.5 - trial_time,
                                             max=10.5 - trial_time)
                else:
                    sleep_time = random_time(min=4.5 - trial_time,
                                             max=5.5 - trial_time)

            if stim_type == 'PVT':
                coil.amplitude = 0
                time.sleep(.8)
                # wait and trigger phase and frequency dependent
                t1 = time.time()
                trial_time = t1 - t0
                if verbose:
                    print("\n Trial time: " + str(trial_time))
                sleep_time = random_time(min=4.5 - trial_time,
                                         max=5.5 - trial_time)
                try:
                    sandy_cli.await_blink()
                    if verbose:
                        print('Sandy is waiting for blink')
                except:
                    raise ConnectionError('Sandy in unclear state')
            print(f"\n Setup: {(time.time()-time_setup_trial):.2f}s")

            if sleep_time < 0.75:
                sleep_time = 0.75
            if True or verbose:
                print(f"\n Sleep_time = {sleep_time:.2f}s")
                print(f"\n ISI = {sleep_time+trial_time:.2f}s\n")
            labcue.show(duration=sleep_time)
            t0 = time.time()

            # conditional on stimtype, wait for keypress
            if stim_type == 'PVT':
                event_list = []
                sandy_cli.receive()
                blink_wait_start = time.time()
                while not (event_list) or len(event_list) == 0:
                    if time.time() - blink_wait_start > 30:
                        raise ConnectionError(
                            f"Sandy could not be triggered for 30 seconds. Stimulus idx: {stimulus_idx}"
                        )
                        break
                    print(f"Wait for blink trigger. Stim: {stimulus_idx}")
                    lucky.trigger()
                    event_list = sandy_cli.receive()
                    print(f"Event list: {event_list}")
                for event in event_list:
                    if event['state-change'] == 'blink-started':
                        time_trigger = int(event['timestamp'])
                time_wait_for_press = time.time()
                print("Waiting for button pressed")
                atleast_one_button_pressed = False
                time_reaction = False
                while time.time() - time_wait_for_press < 1.25:
                    response = sandy_cli.receive()
                    if response:
                        event_list.extend(response)
                    if event_list:
                        for event in event_list:
                            if event:
                                print(event)
                                button_1_pressed = event[
                                    'state-change'] == 'button-1-pressed'
                                button_2_pressed = event[
                                    'state-change'] == 'button-2-pressed'
                                both_buttons_pressed = event[
                                    'state-change'] == 'both-buttons-pressed'
                                atleast_one_button_pressed = button_1_pressed or button_2_pressed or both_buttons_pressed
                                if atleast_one_button_pressed:
                                    time_reaction = int(event['timestamp'])
                                    break
                    if atleast_one_button_pressed:
                        break
                if verbose:
                    print(f"Trigger timestamp= {time_trigger}")

                if time_trigger is not None:  # led was turned on
                    if verbose:
                        print("Reaction timestamp= " + str(time_reaction))
                    if not (
                            time_reaction
                    ) or time_reaction - time_trigger < 0 or time_reaction - time_trigger > 1000:
                        reaction_time = "No reaction"
                        rt = reiz.Cue(canvas,
                                      visualstim=Mural(text=reaction_time))
                    else:
                        reaction_time = time_reaction - time_trigger
                        reaction_times.append(reaction_time)
                        rt = reiz.Cue(
                            canvas,
                            visualstim=Mural(
                                text='{0:3.1f} ms'.format(reaction_time)))
                    if verbose:
                        print('Reaction time: ' + str(reaction_time))

                    push(json.dumps({'reaction_time': str(reaction_time)}),
                         sanitize=False)
                    rt.show(duration=1)
            else:
                # when TMS stimulus
                lucky.trigger()

            try:
                if stimuli[stimulus_idx - stim_number]['stim_type'] == "PVT":
                    coil.amplitude = 0
                    time.sleep(.8)
            except IndexError:
                print("Index error")

            if stimulus_idx in break_idx:  #make a break after cfg.run_length stimuli if experiment is not over
                break_counter += 1
                if break_counter == 1:
                    mean_run_reaction_time = np.mean(
                        reaction_times[:break_idx.index(stimulus_idx)])
                else:
                    mean_run_reaction_time = np.mean(reaction_times[(
                        break_idx[break_idx.index(stimulus_idx) - 1] -
                        stim_number +
                        1):break_idx[break_idx.index(stimulus_idx)]])
                mean_overall_reaction_time = np.mean(reaction_times)
                #displays run reaction time
                v_run_reaction_time = reiz.Cue(
                    canvas,
                    visualstim=Mural(
                        text='Run reaction time = ' +
                        '{0:3.1f} ms'.format(mean_run_reaction_time)))
                v_run_reaction_time.show(duration=2)

                #displays overall reaction time
                v_overall_reaction_time = reiz.Cue(
                    canvas,
                    visualstim=Mural(
                        text='Overall reaction time = ' +
                        '{0:3.1f} ms'.format(mean_overall_reaction_time)))
                v_overall_reaction_time.show(duration=2)

                #calculates and shows the expected duration of the intervention that is  left
                expected_duration_left = timeleft[break_idx.index(
                    stimulus_idx)]
                print(
                    f'Expected duration is around {expected_duration_left} min'
                )
                v_expected_duration_left = reiz.Cue(
                    canvas,
                    visualstim=Mural(
                        text='Expected duration left = ' +
                        '{0:3.1f} min'.format(expected_duration_left)))
                v_expected_duration_left.show(duration=4)

                canvas.window.start_run = False
                nextrun = reiz.Cue(canvas,
                                   visualstim=Mural(text='Continue with F5'))
                while not canvas.window.start_run:
                    nextrun.show(duration=1)
                countdown(canvas, 5)
            labcue.show()

    v_intervention_finished = reiz.Cue(
        canvas,
        visualstim=Mural(
            text='Intervention is finished. Please stop the recording'))
    v_intervention_finished.show(duration=1)
Ejemplo n.º 8
0
# start the MarkerServer which distributes markerstrings over LSL
reiz.marker.start()

# create a window
canvas = reiz.Canvas()

# initialize a clock for timing control
clock = reiz.Clock()
# initialize Cues
# each Cue reveices information about
# the Window where it will be shown -> canvas
# auditory and visual stimuli, e.g. a tone (Hertz) or text (Mural)
# and a markerstring to be send via LSL when .show() is called
hello = reiz.Cue(canvas,
                 audiostim=reiz.audio.Hertz(frequency=400,
                                            duration_in_ms=1000),
                 visualstim=reiz.visual.Mural('Hello World!'),
                 markerstr='hello')

# there is also a library of typical auditory and visual stimuli and
# we can for example, take the visual "los" and the auditory "beep" stimuli
# for convenience, we use the text of the go stimulus as marker message
los = reiz.Cue(canvas,
               audiostim=reiz.audio.library.beep,
               visualstim=reiz.visual.library.go,
               markerstr=reiz.visual.library.go.text)

# here we show a fixation cross but don't want to play an auditory stimulus.
# we can therefore either set it to None or just leave it out (defaults to None)
fix = reiz.Cue(canvas,
               visualstim=reiz.visual.library.fixation,