예제 #1
0
def _clickable_numeric_input(title, start_at):
    # copied from the 0.7.0 release of expyriment
    # https://github.com/expyriment/expyriment/blob/81acb8be1a2abcecdbbfe501e9c4f662c9ba6620/expyriment/control/_experiment_control.py#L96
    background_stimulus = stimuli.BlankScreen(colour=(0, 0, 0))
    fields = [
        stimuli.Circle(diameter=200, colour=(70, 70, 70), position=(0, 70)),
        stimuli.Circle(diameter=200, colour=(70, 70, 70), position=(0, -70)),
        stimuli.Rectangle(size=(50, 50),
                          colour=(70, 70, 70),
                          position=(120, 0))
    ]
    fields[0].scale((0.25, 0.25))
    fields[1].scale((0.25, 0.25))

    # stimuli.TextLine(text="-", text_size=36, position=(0, -70),
    #                  text_font="FreeMono",
    #                  text_colour=(0, 0, 0)),
    plusminus = [
        stimuli.TextLine(title,
                         text_size=24,
                         text_colour=misc.constants.C_EXPYRIMENT_PURPLE,
                         position=(-182, 0)),
        stimuli.FixCross(size=(15, 15),
                         position=(0, 70),
                         colour=(0, 0, 0),
                         line_width=2),
        stimuli.FixCross(size=(15, 2),
                         position=(0, -70),
                         colour=(0, 0, 0),
                         line_width=2),
        stimuli.TextLine(text="Go",
                         text_size=18,
                         position=(120, 0),
                         text_colour=(0, 0, 0))
    ]
    number = int(start_at)

    while True:
        text = stimuli.TextLine(text="{0}".format(number),
                                text_size=28,
                                text_colour=misc.constants.C_EXPYRIMENT_ORANGE)
        btn = io.TouchScreenButtonBox(button_fields=fields,
                                      stimuli=plusminus + [text],
                                      background_stimulus=background_stimulus)
        btn.show()
        key, rt = btn.wait()
        if key == fields[0]:
            number += 1
        elif key == fields[1]:
            number -= 1
            if number <= 0:
                number = 0
        elif key == fields[2]:
            break
    return (number)
예제 #2
0
 def paint_cross(self):
     time_delay = 0
     canvas = stimuli.BlankScreen()
     cross = stimuli.FixCross((50, 50), (0, 0), 5)
     time_delay += cross.plot(canvas)
     time_delay += canvas.present()
     return time_delay;
예제 #3
0
def execute_experiment(exp, text, key_mapping, pairings):
    """Executes a predesigned Simon Task."""

    fixcross = stimuli.FixCross()
    fixcross.preload()

    for block in exp.blocks:

        pairing = pairings[block.get_factor("pairing")]
        instructions = text.format(*pairing)

        stimuli.TextScreen("Instructions", instructions).present()
        exp.keyboard.wait()

        for trial in block.trials:

            fixcross.present()

            exp.clock.wait(1000 - trial.stimuli[0].preload())
            trial.stimuli[0].present()

            key, rt = exp.keyboard.wait(keys=key_mapping.keys())

            exp.data.add([
                block.get_factor("pairing"),
                trial.get_factor("position"),
                trial.get_factor("color"), key_mapping[key], rt
            ])
예제 #4
0
def _clickable_numeric_input(title, start_at, scale=1.0):
    positions = [(100*scale, 0),
                 (-100*scale, 0),
                 (300*scale, -200*scale)]
    btn_colour = misc.constants.C_DARKGREY
    btn_size = (int(70*scale), int(70*scale))
    btn_text_colour = (0, 0, 0)
    pos_title = (0, 100*scale)
    title_text_colour = misc.constants.C_GREY
    number_text_colour = misc.constants.C_GREY

    buttons = [stimuli.Rectangle(size=btn_size, colour=btn_colour, position=pos)
               for pos in positions]

    plus_width = 2*scale if expyriment_version[0] == 7 else 3*scale
    minus_width = 3*scale

    labels = [
        stimuli.TextLine(text='OK', text_size=int(30*scale),
                         position=positions[2], text_colour=btn_text_colour),
        stimuli.FixCross(size=(40*scale, 40*scale),
                         position=positions[0], colour=btn_text_colour,
                         line_width=plus_width),
        stimuli.FixCross(size=(40*scale, 3*scale),
                         position=positions[1], colour=btn_text_colour,
                         line_width=minus_width),
        stimuli.TextLine(title, text_size=int(30*scale),
                         text_colour=title_text_colour, position=pos_title)
    ]

    number = int(start_at)

    while True:
        current_num = stimuli.TextLine(text=str(number),
                                       text_size=int(40*scale),
                                       text_colour=number_text_colour)
        button_box = io.TouchScreenButtonBox(buttons, labels+[current_num])
        button_box.show()
        key = button_box.wait()[0]
        if key == buttons[0]:
            number = number + 1
        elif key == buttons[1]:
            number = max(number - 1, 1)
        elif key == buttons[2]:
            return(number)
    return(number)
def startTrial(NUMBER, OPERATOR):

    #fixcross.preload()
    exp = design.Experiment("MATH")
    control.initialize(exp)
    control.start()
    fixcross = stimuli.FixCross()
    txt_input = io.TextInput("= ")

    stimuli.TextScreen("MATH GAME",
                       "STARTING in 10 secs",
                       heading_size=40,
                       text_size=60).present()
    exp.clock.wait(2000)  #stim -1
    fixcross.preload()
    fixcross.present()
    exp.clock.wait(10000)
    b = design.Block()

    for i in range(0, 10):  #FOR 10 TRIALS
        b.clear_trials()
        b = design.Block()
        print(i)
        tr = atl.arithmetictriall1(NUMBER, OPERATOR)
        print(tr)

        for trel in tr[0]:
            t = design.Trial()
            s = stimuli.TextLine(text=str(trel),
                                 text_size=120,
                                 text_colour=misc.constants.C_GREEN)
            t.add_stimulus(s)
            b.add_trial(t)
        #print(b.trials)
        exp.add_block(b)

        #START TEST: ONSCREEN
        for b in exp.blocks:
            fixcross.present()
            exp.clock.wait(100)

            for t in b.trials:
                t.stimuli[0].present()
                exp.clock.wait(1000)

        print(b)
        exp.clock.reset_stopwatch()
        answer = txt_input.get()

        try:
            answer = int(answer)
            if answer == tr[1]:
                print("Correct")
            else:
                print("incorrect")
        except:
            print("incorrect")
예제 #6
0
 def paint_cross(self, exp):
     self.canvas = stimuli.BlankScreen()
     cross = stimuli.FixCross((50, 50), (0, 0), 5)
     cross.plot(self.canvas)
     self.canvas.present()
     key, rt = exp.keyboard.wait([self.exit_key], self.show_cross_for_seconds * 1000)
     if key is self.exit_key:
         return False
     return True
예제 #7
0
    def __init__(self, should_paint_grid):
        self.should_paint_grid = should_paint_grid
        self.line_horsizontal1 = stimuli.Line((-300, 80), (300, 80), 5)
        self.line_horsizontal2 = stimuli.Line((-300, -80), (300, -80), 5)
        self.line_vertical1 = stimuli.Line((-100, 200), (-100, -200), 5)
        self.line_vertical2 = stimuli.Line((100, 200), (100, -200), 5)
        self.cross = stimuli.FixCross((50, 50), (0, 0), 5)

        self.line_horsizontal1.preload()
        self.line_horsizontal2.preload()
        self.line_vertical1.preload()
        self.line_vertical2.preload()
예제 #8
0
    def prepare_grid_stimulus(self):
        side = self.num_boxes**(0.5)
        block_size = self.canvas_size / side
        center = self.canvas_size / 2
        grid = stimuli.BlankScreen()

        colour_grid = self.exp._colours(
            self.exp.config.get('APPEARANCE', 'colour_grid'))
        colour_fixation_cross = self.exp._colours(
            self.exp.config.get('APPEARANCE', 'colour_fixation_cross'))
        antialiasing = 10 if self.exp.config.getboolean(
            'APPEARANCE', 'antialiasing') else None

        if colour_grid:
            for a, b in [(i % side, i // side) for i in range(self.num_boxes)]:
                stimuli.Line(
                    (a * block_size - center, b * block_size - center),
                    ((a + 1) * block_size - center, b * block_size - center),
                    line_width=self.line_width,
                    colour=colour_grid,
                    anti_aliasing=antialiasing).plot(grid)
                stimuli.Line(
                    (a * block_size - center, b * block_size - center),
                    (a * block_size - center, (b + 1) * block_size - center),
                    line_width=self.line_width,
                    colour=(colour_grid),
                    anti_aliasing=antialiasing).plot(grid)

            stimuli.Line(
                (0 - center, side * block_size - center),
                (side * block_size - center, side * block_size - center),
                line_width=self.line_width,
                colour=colour_grid,
                anti_aliasing=antialiasing).plot(grid)
            stimuli.Line(
                (side * block_size - center, 0 - center),
                (side * block_size - center, side * block_size - center),
                line_width=self.line_width,
                colour=colour_grid,
                anti_aliasing=antialiasing).plot(grid)

        if colour_fixation_cross:
            stimuli.FixCross(colour=colour_fixation_cross).plot(grid)
        grid.preload()
        return (grid)
def execute_trial(motion_coherence,
                  direction,
                  number_dots,
                  time_duration=MAX_RESPONSE_DELAY):
    dot_list = generate_n_dots(N_DOTS)
    stimuli.BlankScreen().present()
    arena = stimuli.Circle(radius=RADIUS_OF_ARENA + 2 * RADIUS_OF_DOTS,
                           colour=COLOR_OF_ARENA)
    cue = stimuli.FixCross(size=(SIZE_FIXATION_CROSS, SIZE_FIXATION_CROSS),
                           line_width=LINE_WIDTH_FIXATION_CROSS)

    cue.present()
    exp.clock.wait(1000)

    key = exp.keyboard.check()
    exp.clock.reset_stopwatch()

    while (exp.clock.stopwatch_time < time_duration) and (key is None):

        update_stimulus(dot_list, arena)
        key, time = check_keyboard_response_and_time()
        exp.clock.wait(1)

    return (key, time)
예제 #10
0
exp = design.Experiment(name="Le_Petit_Prince")

control.set_develop_mode(False)
control.defaults.open_gl = 2
control.defaults.window_mode = True
control.defaults.window_size = (1920, 1080)

##
control.initialize(exp)

stim = stimuli.Audio(AUDIO)
stim.preload()

fixcrossGreen = stimuli.FixCross(size=(45, 45),
                                 line_width=5,
                                 colour=(0, 255, 0))
fixcrossGreen.preload()
fixcrossGrey = stimuli.FixCross(size=(45, 45),
                                line_width=3,
                                colour=(192, 192, 192))
fixcrossGrey.preload()


def clear_screen():
    exp.screen.clear()
    exp.screen.update()


def wait_for_MRI_synchro():
    fixcrossGreen.present(clear=True, update=True)
예제 #11
0
#START TEST: ONSCREEN
for i in range(0, 1):  #commission 1>3
    trialname = "trial no. _0" + str(i + 1)
    print("*** [%s start]-----------" % trialname)

    COLORS1 = n4b.n4back(rCOLORS)
    while type(
            COLORS1
    ) != list:  #BUG removal : since sometimes n2back returns Nonetype
        COLORS1 = n4b.n4back(rCOLORS)
        print(type(COLORS1))

    exp = design.Experiment(trialname)
    b1 = cB.createBlock(COLORS1, trialname, exp)
    fixcross = stimuli.FixCross(size=(40, 40), colour=misc.constants.C_WHITE)

    control.initialize(exp)

    control.start()

    inputNAME = io.TextInput("ENTER NAME: ")
    VolunteerNAME = inputNAME.get()  # First input by volunteer

    stimuli.TextScreen(
        "4-BACK GAME",
        ". . . RELAX . . .\n\n\n\n\n\n+\n\nlook at fixcross\n\n\nSTARTS IN 10 SECONDS",
        heading_size=40,
        text_size=20,
        heading_colour=misc.constants.C_WHITE,
        text_colour=misc.constants.C_WHITE).present()
예제 #12
0
from expyriment import stimuli, control, design, io, misc

from config import windowMode, windowSize, restBGColor, restCrossColor, restCrossSize, restCrossThickness

control.defaults.window_mode = windowMode
control.defaults.window_size = windowSize

exp = design.Experiment('Rest')  # Save experiment name
control.initialize(exp)
control.start(exp, auto_create_subject_id=True, skip_ready_screen=True)
bs = stimuli.BlankScreen(restBGColor)  # Create blank screen
cross = stimuli.FixCross(size=restCrossSize,
                         colour=restCrossColor,
                         line_width=restCrossThickness)  # Create cross
cross.plot(bs)
kb = io.Keyboard()
bs.present()

kb.wait(keys=misc.constants.K_q)
예제 #13
0
import random
from expyriment import design, control, stimuli

NTRIALS = 20
ITI = 1000  # inter trial interval
MAX_RESPONSE_TIME = 2000
AUDIO_STIMULUS = 'click.wav'

exp = design.Experiment(name="AudioVisual Detection")
control.initialize(exp)

blankscreen = stimuli.BlankScreen()

visual_trial = design.Trial()
visual_trial.add_stimulus(stimuli.FixCross(size=(50, 50), line_width=4))

audio_trial = design.Trial()
audio_trial.add_stimulus(stimuli.Audio(AUDIO_STIMULUS))

visual_block = design.Block("visual")
for i in range(NTRIALS):
    visual_block.add_trial(visual_trial)
exp.add_block(visual_block)

audio_block = design.Block("audio")
for i in range(NTRIALS):
    audio_block.add_trial(audio_trial)
exp.add_block(audio_block)

audiovisual_block = design.Block("audiovisual")
예제 #14
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A very short example experiment in 16 lines of pure code.
Participants have to indicate the parity of digits by pressing 
the left arrow key for odd and the right arrow key for even numbers.
"""

from expyriment import control, stimuli, design, misc

digit_list = [1, 2, 3, 4, 6, 7, 8, 9] * 12
design.randomize.shuffle_list(digit_list)

exp = control.initialize()
exp.data_variable_names = ["digit", "btn", "rt", "error"]

control.start(exp)

for digit in digit_list:
    target = stimuli.TextLine(text=str(digit), text_size=80)
    exp.clock.wait(500 - stimuli.FixCross().present() - target.preload())
    target.present()
    button, rt = exp.keyboard.wait(
        [misc.constants.K_LEFT, misc.constants.K_RIGHT])
    error = (button == misc.constants.K_LEFT) == digit % 2
    if error: stimuli.Tone(duration=200, frequency=2000).play()
    exp.data.add([digit, button, rt, int(error)])
    exp.clock.wait(1000 - stimuli.BlankScreen().present() - target.unload())

control.end(goodbye_text="Thank you very much...", goodbye_delay=2000)
예제 #15
0
def startTrial(b, exp):
    numelTrial = len(b.trials)
    print(numelTrial)
    mem = [0, 0, 0, 0, 0, 0]
    response_key = [misc.constants.K_SPACE]

    for b in exp.blocks:
        #------------monitoring variables
        Ncount = 0  # counting nbacks in  the block && reset Ncount for next block
        totcount, memcount = 0, 0
        n_mem = numelTrial - 6 + 1  # since 121
        #keyprflag=1 #flag intially set
        #----------monitoring variables...[end]
        #leftovertime=0

        for t in b.trials:
            keyprflag = 1  # flag initially set
            memcount += 1
            #t.stimuli[0].preload()
            fixcross = stimuli.FixCross()
            fixcross.present()
            exp.clock.wait(500)  #-t.stimuli[0].preload) #remove #
            t.stimuli[0].present()  # Presenting the stimulus onscreen

            if memcount == 1 or memcount == 2 or memcount == 3 or memcount == 4 or memcount == 5:  #no need of key_response
                """rt=exp.keyboard.wait(keys=response_key,duration=3000) #remove #
                try:
                    leftovertime=3000-rt[1]   #LEFT OVER TIME AFTER KEYPRESS ::ADJUST TIME FOR NEXT STIMULI
                    print(leftovertime)
                    exp.clock.wait(leftovertime)
                except:
                    print(None)"""
                exp.clock.wait(3000)

            if memcount == 1:
                mem[0] = t.factor_dict['COLOR']
                keyprflag = 0
                #print(mem[0])
                #mem[0]=t.stimuli[0]
            if memcount == 2:
                mem[1] = t.factor_dict['COLOR']  #t.stimuli[0]
                keyprflag = 0
            if memcount == 3:
                mem[2] = t.factor_dict['COLOR']  #t.stimuli[0]
                keyprflag = 0
            if memcount == 4:
                mem[3] = t.factor_dict['COLOR']  #t.stimuli[0]
                keyprflag = 0
            if memcount == 5:
                mem[4] = t.factor_dict['COLOR']  #t.stimuli[0]
                keyprflag = 0

            if memcount == 6:
                mem[5] = t.factor_dict['COLOR']

                memcount = 5
                n_mem -= 1
                # 3 memories here
                #print(mem)

                #...CHECKING nback or not...[start]
                if mem[0] == mem[5]:  #Counting nback in stimuli
                    Ncount += 1
                    nbackoccured = True
                else:
                    nbackoccured = False  #.....CHECK COMPLETE

                #if keyprflag==1:
                #    keyprflag=0
                #print("keyprflag reset") #remove#
                rt = exp.keyboard.wait(keys=response_key,
                                       duration=3000)  #remove #

                if rt[0] != None:
                    #print("keyprflag set") #remove#
                    keyprflag = 1
                    leftovertime = 3000 - rt[
                        1]  #LEFT OVER TIME AFTER KEYPRESS <ADJUST TIME FOR NEXT STIMULI>
                    exp.clock.wait(leftovertime)
                    #print(rt)
                    #print(leftovertime)
                else:
                    keyprflag = 0

                if nbackoccured == True and keyprflag == 1:
                    print('HIT')
                    keyprflag = 0
                elif nbackoccured == True and keyprflag == 0:
                    print('MISS')
                elif nbackoccured == False:
                    print(-1)
                #   keyprflag=0 #reset flag
                #...compare...[end]
                print(mem)  # put#
                if n_mem != 0:
                    #mem[0]=mem[1]
                    #mem[1]=mem[2] #b is a list
                    mem[0], mem[1], mem[2], mem[3], mem[4] = mem[1], mem[
                        2], mem[3], mem[4], mem[5]
    print("*** fN startTrial: ncount = %d " % Ncount)
예제 #16
0
from expyriment import design, control, stimuli, misc, io
import random
control.set_develop_mode(True)

exp = design.Experiment(name="My Experiment")
control.initialize(exp)

fixcross = stimuli.FixCross()
fixcross.preload()
blankscreen = stimuli.BlankScreen()
blankscreen.preload()

b = design.Block(name="Only Block")
for i in range(10):
    waiting_time = random.randint(200, 2000)
    t = design.Trial()
    t.set_factor("waiting_time", waiting_time)
    s = stimuli.Circle(50)
    t.add_stimulus(s)
    b.add_trial(t)
exp.add_block(b)

exp.data_variable_names = ["Waiting Time", "Response Time"]

control.start()

for block in exp.blocks:
    for trial in block.trials:
        fixcross.present()
        exp.clock.wait(
            trial.get_factor("waiting_time") - trial.stimuli[0].preload())
def start(experiment=None,
          auto_create_subject_id=None,
          subject_id=None,
          skip_ready_screen=False):
    """Start an experiment.

    This starts an experiment defined by 'experiment' and asks for the subject
    number. When the subject number is entered and confirmed by ENTER, a data
    file is created.
    Eventually, "Ready" will be shown on the screen and the method waits for
    ENTER to be pressed.

    After experiment start the following additional properties are available:

    * experiment.subject -- the current subject id
    * experiment.data    -- the main data file

    Parameters
    ----------
    experiment : design.Experiment, optional (DEPRECATED)
        don't use this parameter, it only exists to keep backward compatibility
    auto_create_subject_id : bool, optional
        if True new subject id will be created automatically
    subject_id : integer, optional
        start with a specific subject_id;
        no subject id input mask will be presented; subject_id must be an
        integer; setting this paramter overrules auto_create_subject_id
    skip_ready_screen : bool, optional
        if True ready screen will be skipped (default=False)

    Returns
    -------
    exp : design.Experiment
        The started experiment will be returned.

    """

    if experiment is None:
        experiment = expyriment._active_exp
    if experiment != expyriment._active_exp:
        raise Exception("Experiment is not the currently initialized " +
                        "experiment!")
    if experiment.is_started:
        raise Exception("Experiment is already started!")
    if subject_id is not None:
        if not isinstance(subject_id, int):
            raise Exception("Subject id must be an integer. " +
                            "{0} is not allowed.".format(type(subject_id)))
        auto_create_subject_id = True
    elif auto_create_subject_id is None:
        auto_create_subject_id = defaults.auto_create_subject_id

    experiment._is_started = True
    # temporarily switch off log_level
    old_logging = experiment.log_level
    experiment.set_log_level(0)
    screen_colour = experiment.screen.colour
    experiment._screen.colour = [0, 0, 0]
    if subject_id is None:
        default_number = DataFile.get_next_subject_number()
    else:
        default_number = subject_id

    if not auto_create_subject_id:
        if android is not None:
            background_stimulus = stimuli.BlankScreen(colour=(0, 0, 0))
            fields = [
                stimuli.Circle(radius=100,
                               colour=(70, 70, 70),
                               position=(0, 70),
                               anti_aliasing=10),
                stimuli.Circle(radius=100,
                               colour=(70, 70, 70),
                               position=(0, -70),
                               anti_aliasing=10),
                stimuli.Rectangle(size=(50, 50),
                                  colour=(70, 70, 70),
                                  position=(120, 0))
            ]
            fields[0].scale((0.25, 0.25))
            fields[1].scale((0.25, 0.25))
            plusminus = [
                stimuli.TextLine("Subject Number:",
                                 text_size=24,
                                 text_colour=constants.C_EXPYRIMENT_PURPLE,
                                 position=(-182, 0)),
                stimuli.FixCross(size=(15, 15),
                                 position=(0, 70),
                                 colour=(0, 0, 0),
                                 line_width=2),
                stimuli.FixCross(size=(15, 2),
                                 position=(0, -70),
                                 colour=(0, 0, 0),
                                 line_width=2),
                stimuli.TextLine(text="Go",
                                 text_size=18,
                                 position=(120, 0),
                                 text_colour=(0, 0, 0))
            ]
            subject_id = default_number
            while True:
                text = stimuli.TextLine(
                    text="{0}".format(subject_id),
                    text_size=28,
                    text_colour=constants.C_EXPYRIMENT_ORANGE)
                btn = TouchScreenButtonBox(
                    button_fields=fields,
                    stimuli=plusminus + [text],
                    background_stimulus=background_stimulus)
                btn.show()
                key, rt = btn.wait()
                if key == fields[0]:
                    subject_id += 1
                elif key == fields[1]:
                    subject_id -= 1
                    if subject_id <= 0:
                        subject_id = 0
                elif key == fields[2]:
                    break
            experiment._subject = int(subject_id)

        else:
            position = (0, 0)
            while True:
                ask_for_subject = TextInput(
                    message="Subject Number:",
                    position=position,
                    message_colour=misc.constants.C_EXPYRIMENT_PURPLE,
                    message_text_size=24,
                    user_text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
                    user_text_size=20,
                    background_colour=(0, 0, 0),
                    frame_colour=(70, 70, 70),
                    ascii_filter=misc.constants.K_ALL_DIGITS)
                subject_id = ask_for_subject.get(repr(default_number))
                try:
                    experiment._subject = int(subject_id)
                    break
                except:
                    pass

    else:
        experiment._subject = default_number

    experiment.screen.clear()
    experiment.screen.update()
    experiment._data = DataFile(additional_suffix=experiment.filename_suffix)
    experiment.data.add_variable_names(experiment.data_variable_names)
    for txt in experiment.experiment_info:
        experiment.data.add_experiment_info(txt)
    for line in experiment.__str__().splitlines():
        experiment.data.add_experiment_info(line)

    for f in experiment.bws_factor_names:
        _permuted_bws_factor_condition = \
            experiment.get_permuted_bws_factor_condition(f)
        if isinstance(_permuted_bws_factor_condition, unicode):
            _permuted_bws_factor_condition = \
                unicode2str(_permuted_bws_factor_condition)
        experiment.data.add_subject_info("{0} = {1}".format(
            unicode2str(f), _permuted_bws_factor_condition))

    if experiment.events is not None:
        experiment.events._time_stamp = experiment.data._time_stamp
        experiment.events.rename(experiment.events.standard_file_name)

    number = defaults.initialize_delay - int(experiment.clock.time / 1000)
    if number > 0:
        text = stimuli.TextLine("Initializing, please wait...",
                                text_size=24,
                                text_colour=(160, 70, 250),
                                position=(0, 0))
        stimuli._stimulus.Stimulus._id_counter -= 1
        text.present()
        text.present()  # for flipping with double buffer
        text.present()  # for flipping with tripple buffer
    while number > 0:
        counter = stimuli.TextLine(
            "{num:02d}".format(num=number),
            text_font='FreeMono',
            text_size=18,
            text_bold=True,
            text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
            position=(0, -50),
            background_colour=(0, 0, 0))

        stimuli._stimulus.Stimulus._id_counter -= 1
        counter.present(clear=False)
        number -= 1
        key = experiment.keyboard.wait(pygame.K_ESCAPE,
                                       duration=1000,
                                       check_for_control_keys=False)
        if key[0] is not None:
            break

    position = (0, 0)
    if not skip_ready_screen:
        stimuli.TextLine(
            "Ready",
            position=position,
            text_size=24,
            text_colour=misc.constants.C_EXPYRIMENT_ORANGE).present()
        stimuli._stimulus.Stimulus._id_counter -= 1
        if android is None:
            experiment.keyboard.wait()
        else:
            experiment.mouse.wait_press()
    experiment.set_log_level(old_logging)
    experiment._screen.colour = screen_colour
    experiment.log_design_to_event_file()
    experiment._event_file_log("Experiment,started")
    return experiment
예제 #18
0
파일: posner_task.py 프로젝트: chrplr/PCBS
BLACK = (0, 0, 0)

MAX_RESPONSE_DURATION = 2000

trials = [('congruent', 'left'), ('congruent', 'right')] * 40
trials += [('incongruent', 'left'), ('incongruent', 'right')] * 10
random.shuffle(trials)

exp = design.Experiment(name="Posner-task",
                        text_size=30,
                        background_colour=GREY,
                        foreground_colour=BLACK)
# control.set_develop_mode()
control.initialize(exp)

cross = stimuli.FixCross(size=(40, 40), colour=BLACK, line_width=6)
cross.preload()

blankscreen = stimuli.BlankScreen(colour=GREY)

target_left = stimuli.Picture("star.png", position=(-150, 0))
target_left.preload()

target_right = stimuli.Picture("star.png", position=(+150, 0))
target_right.preload()

cue_left = stimuli.Picture('left_arrow.png')
cue_left.preload()

cue_right = stimuli.Picture('right_arrow.png')
cue_right.preload()

## Stimulus
n = 10
expected_block_one = np.zeros(n)
expected_block_two = np.zeros(n)
circle_dist = 200
circle_radius = 20
left_circle = stimuli.Circle(circle_radius, position=[-circle_dist, 0])
left_circle.preload()
right_circle = stimuli.Circle(circle_radius, position=[circle_dist, 0])
right_circle.preload()
circle_displaytime = 100

## Fixcross
fixcross = stimuli.FixCross(size=(15, 15), line_width=3)
fixcross.preload()

## Instruction
instruction1 = """ Block 1 \n\
Fixez  la croix de fixation. \n\
Positionnez  votre index droit sur la flèche droite du clavier et votre index gauche sur la flèche gauche du clavier. \n\
Appuyez  avec la flèche droite quand le rond blanc apparait à droite et appuyez avec la flèche gauche quand il apparait à gauche. \n\
Appuyez sur une des flèches pour commencer."""

instruction2 = """Block 2 \n\
Fixez la croix de fixation. \n\
Positionnez votre index droit sur la flèche gauche du clavier et votre index gauche sur la flèche droite du clavier. \n\
Appuyez avec la flèche droite quand le rond blanc apparait à droite et appuyez avec la flèche gauche quand il apparait à gauche.
Appuyer sur une des flèches pour commencer."""
import random
import listes
from expyriment import design, control, stimuli

STANDARD = listes.MEAN_2DIGITS_NUMBER
TRAINING_LIST_LENGHT = 10
MAX_RESPONSE_DELAY = 2000
TARGETS = listes.create_valid_experimental_list(STANDARD, TRAINING_LIST_LENGHT)
SMALLER_RESPONSE = 'f'
LARGER_RESPONSE = 'j'

exp = design.Experiment(name="Numerical Comparison", text_size=40)
control.initialize(exp)

cue = stimuli.FixCross(size=(80, 80), line_width=4)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen(
    "Instructions",
    f"""You will see two-digit numbers, distributed around {STANDARD}, appear on the screen one by one.
    You task is to decide as fast as possible but by minimising errors, whether it is smaller or larger than {STANDARD}.
    
    If it is smaller than {STANDARD}, press '{SMALLER_RESPONSE}'
    If it is larger than {STANDARD}, press '{LARGER_RESPONSE}'
    
    There will be {len(TARGETS)} trials in total.
    Press the space bar to start.""")

# Prepare the stimuli
trials = []
for number in TARGETS:
exp = expyriment.design.Experiment(name="Localizer",
                                   background_colour=BACKGROUND_COLOR,
                                   foreground_colour=TEXT_COLOR,
                                   text_size=TEXT_SIZE,
                                   text_font=TEXT_FONT)
#expyriment.control.defaults.open_gl=1
expyriment.misc.add_fonts('fonts')
expyriment.control.initialize(exp)
#expyriment.control.defaults.quit_key = expyriment.misc.constants.K_q
#expyriment.control.defaults.fast_quit = True
#exp.background_colour = BACKGROUND_COLOR
exp._screen_colour = BACKGROUND_COLOR

kb = expyriment.io.Keyboard()
bs = stimuli.BlankScreen(colour=BACKGROUND_COLOR)
fs = stimuli.FixCross(size=(25, 25), line_width=3, colour=TEXT_COLOR)

##############################
# START PROTOCOL

#time to display the message of Preparing expyriment, otherwise it can be very short
#and we don't see what it is exactly
exp.clock.wait(800)

#CALIBRATION
if not (calibration is None):
    calibrage = "Nous allons faire un calibrage"
    calibration = stimuli.TextLine(calibrage,
                                   text_font=TEXT_FONT,
                                   text_size=TEXT_SIZE,
                                   text_colour=TEXT_COLOR,
예제 #22
0
from expyriment import design, control, stimuli

control.defaults.window_mode = True
control.defaults.window_size = [800, 600]
design.defaults.experiment_background_colour = (230, 230, 70)

exp = design.Experiment(name="Cool Experiment")

control.initialize(exp)

block_one = design.Block("Our only block")
tmp_trial = design.Trial()

cross = stimuli.FixCross(colour=(0, 0, 0))
cross.preload()

tmp_trial.add_stimulus(cross)
block_one.add_trial(tmp_trial)
exp.add_block(block_one)

control.start()

for b in exp.blocks:
    for t in b.trials:
        t.stimuli[0].present()

        exp.keyboard.wait()

control.end()
예제 #23
0
    def run_experiment(self):
        # define headers for expyriment log file output table (we currently don't use it,
        # but if we want - we can improve it and use it if we want
        self.exp.data_variable_names = ["time", "location", "direction", "trialType", "response", "rt"\
                                        ,"is success", "is practice", "blockType", "order"]

        currentTrailsNumber = self.test_trials_number;
        if self.is_practice:
            currentTrailsNumber = self.practice_trials_number;
        for trial_index in range(0, currentTrailsNumber):
            canvas = stimuli.BlankScreen()

            time_delay = 0

            # plot cross on canvas
            cross = stimuli.FixCross((50, 50), (0, 0), 5)
            time_delay += cross.plot(canvas)

            # plot arrow on canvas
            picture_arrow = stimuli.Picture(self.direction_file_converter[self.directions[trial_index]] \
                                            , position=self.locations_converter[self.locations[trial_index]])
            time_delay += picture_arrow.preload()
            time_delay += picture_arrow.plot(canvas)

            # show canvas
            time_delay += canvas.present();

            # send trigger to LSL with arrow details
            utils.push_sample_current_time(self.outlet, ["stimulus_task_stroop_type_arrow_location_" + ("u" if "up" in self.directions[trial_index] else "d") \
                                    + "_direction_"  + ("u" if "up" in self.locations[trial_index] else "d")])

            # wait for subject's response. Wait only for "duration" time
            key, rt = self.game_controller.wait_press(self.possible_joystick_buttons, self.duration,\
                                                      process_control_events=False)

            # we get here is subjects responded or of duration of stimulus ended
            if key != None: # subject responded and stimulus duration hasn't ended
                utils.push_sample_current_time(self.outlet, ["keyPressed_task_stroop_key_" + str(key)])
                self.exp.clock.wait(self.duration - rt) # wait the rest of the stimulus duration before going on

                # we get here when stimulus duration has ended (and subject responded)
                time_delay += self.paint_cross();
                self.exp.clock.wait(
                    self.isi - time_delay)  # wait for the ISI before going on

            else:
                # we get here if subject hasn't responded but stimulus duration ended - so we clean the screen
                time_delay += self.paint_cross();

                key = None;
                # we wait for subject to respond (but only for the ISI duration)
                key, rt = self.game_controller.wait_press(self.possible_joystick_buttons, self.isi - time_delay,
                                                          process_control_events=False)
                if key != None: # we get here if subject has responded - so we need to wait for the rest of
                                # the ISI
                    self.exp.clock.wait(
                        self.isi - rt - time_delay)  # wait the rest of the ISI before going on

                utils.push_sample_current_time(self.outlet, ["keyPressed_task_stroop_key_" + str(key)])
            self.save_trial_data(key, rt, trial_index)

        self.show_feedback_if_needed()
예제 #24
0
 def paint_cross(self, exp):
     cross = stimuli.FixCross((50, 50), (0, 0), 5)
     canvas = stimuli.BlankScreen()
     cross.plot(canvas)
     canvas.present()
     exp.clock.wait(self.show_cross_for_seconds * 1000)
예제 #25
0
exp = design.Experiment(name="Lexical Decision", text_size=40)
control.initialize(exp)

# prepare the stimuli
words = ['bonjour.wav', 'chien.wav', 'président.wav']
pseudos = ['lopadol.wav', 'mirance.wav', 'clapour.wav' ]

trials = []
for item in words:
    trials.append(("W", item, stimuli.Audio(item)))
for item in pseudos:
    trials.append(("P", item, stimuli.Audio(item)))

random.shuffle(trials)

cue = stimuli.FixCross(size=(50, 50), line_width=4)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen("Instructions",
    f"""When you hear a stimulus, your task to decide, as quickly as possible, whether it is a word or not.

    if it is a word, press '{WORD_RESPONSE_KEY.upper()}'

    if it is a non-word, press '{NONW_RESPONSE_KEY.upper()}'

    Press the space bar to start.""")

exp.add_data_variable_names(['cat', 'word', 'respkey', 'RT'])

control.start(skip_ready_screen=True)
instructions.present()
exp.keyboard.wait_char(" ")
예제 #26
0
from expyriment import design, control, stimuli, io

#%%

exp = design.Experiment(name="Visual Language Localizer")

# comment out the following line to get in real mode
# control.set_develop_mode(True)

control.initialize(exp)

#%%

control.start(exp)

fixcross = stimuli.FixCross(size=(30, 30), line_width=3, colour=(0, 255, 0))
fixcross.preload()

fixcross2 = stimuli.FixCross(size=(30, 30),
                             line_width=2,
                             colour=(128, 128, 128))
fixcross2.preload()

liste = "list%d.csv" % (2 - exp.subject % 2)
listname = os.path.join("lists", liste)

sequences = [i for i in csv.reader(open(listname))]

block = design.Block(name="block1")

for line in sequences:
예제 #27
0
def startTrial(b, exp):
    numelTrial = len(b.trials)
    print(numelTrial)
    mem = [0, 0, 0]
    response_key = [misc.constants.K_SPACE]

    hit, miss, incorrect_ = 0, 0, 0  #for final correct and incorrect responsed
    for b in exp.blocks:
        #------------monitoring variables
        Ncount = 0  # counting nbacks in  the block && reset Ncount for next block
        totcount, memcount = 0, 0
        n_mem = numelTrial - 3 + 1  # since 121
        #keyprflag=1 #flag intially set
        #----------monitoring variables...[end]
        #leftovertime=0

        for t in b.trials:
            keyprflag = 1  # flag initially set
            memcount += 1
            #t.stimuli[0].preload()
            fixcross = stimuli.FixCross(size=(40, 40),
                                        colour=misc.constants.C_WHITE)
            fixcross.present()
            exp.clock.wait(500)  #-t.stimuli[0].preload) #remove #
            t.stimuli[0].present()  # Presenting the stimulus onscreen

            if memcount == 1 or memcount == 2:  #no need of key_response
                """rt=exp.keyboard.wait(keys=response_key,duration=3000) #remove #
                try:
                    leftovertime=3000-rt[1]   #LEFT OVER TIME AFTER KEYPRESS ::ADJUST TIME FOR NEXT STIMULI
                    print(leftovertime)
                    exp.clock.wait(leftovertime)
                except:
                    print(None)"""
                exp.clock.wait(3000)

            if memcount == 1:
                mem[0] = t.factor_dict['COLOR']
                keyprflag = 0
                #print(mem[0])
                #mem[0]=t.stimuli[0]
            if memcount == 2:
                mem[1] = t.factor_dict['COLOR']  #t.stimuli[0]
                keyprflag = 0

            if memcount == 3:
                mem[2] = t.factor_dict['COLOR']

                memcount = 2
                n_mem -= 1
                # 3 memories here
                #print(mem)

                #...CHECKING nback or not...[start]
                if mem[0] == mem[2]:  #Counting nback in stimuli
                    Ncount += 1
                    nbackoccured = True
                else:
                    nbackoccured = False  #.....CHECK COMPLETE

                #if keyprflag==1:
                #    keyprflag=0
                #print("keyprflag reset") #remove#
                rt = exp.keyboard.wait(keys=response_key,
                                       duration=3000)  #remove #

                if rt[0] != None:
                    #print("keyprflag set") #remove#
                    keyprflag = 1
                    leftovertime = 3000 - rt[
                        1]  #LEFT OVER TIME AFTER KEYPRESS <ADJUST TIME FOR NEXT STIMULI>
                    exp.clock.wait(leftovertime)
                    #print(rt)
                    #print(leftovertime)
                else:
                    keyprflag = 0

                if nbackoccured == True and keyprflag == 1:
                    print('HIT')
                    keyprflag = 0
                    hit += 1
                elif nbackoccured == True and keyprflag == 0:
                    print('MISS')
                    miss += 1
                elif nbackoccured == False:
                    print(-1)
                    if keyprflag == 1:
                        print('incorrect')
                        incorrect_ += 1
                #   keyprflag=0 #reset flag
                #...compare...[end]
                print(mem)  # put#
                if n_mem != 0:
                    mem[0] = mem[1]
                    mem[1] = mem[2]  #b is a list

    #Evaluating % correct
    print("***RESULT: -------------\n*** -H:" + str(hit) + "->M:" + str(miss) +
          "-> I:" + str(incorrect_))
    correctpercent = hit / (hit + incorrect_ + miss) * 100
    #incorrectpercent=incorrect
    print("*** fN startTrial: nbacks = %d nos." % Ncount)
    #print("*** %d % Correct"%correctpercent)
    print("*** Correct " + str(correctpercent) +
          "% \n----------------------[trial end]")
block = design.Block()
with open("word_fragment_completion_stimuluslist.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        trial = design.Trial()
        trial.set_factor("word", row[0].strip())
        trial.set_factor("fragment", row[1].strip())
        block.add_trial(trial)
block.shuffle_trials()
exp.add_block(block)
exp.add_data_variable_names(["word", "fragment", "RT", "RT2", "answer"])

control.initialize(exp)

#prepare some stimuli
fixcross = stimuli.FixCross(line_width=1)
fixcross.preload()
blank = stimuli.BlankScreen()
blank.preload()
txt_input = io.TextInput("")
control.start(exp)

#run experiment
for trial in exp.blocks[0].trials:
    #present blank inter-trial-screen and prepare stimulus
    blank.present()
    fragment = ""
    for c in trial.get_factor("fragment").upper():
        fragment += c + " "
    target = stimuli.TextLine(fragment.strip())
    target.preload()
예제 #29
0
TEXT_DURATION = 3000
#TOTAL_EXPE_DURATION = 20000 # 10 sec

exp = expyriment.design.Experiment(name="HiRes Experiment")
#expyriment.control.defaults.open_gl=1
expyriment.control.defaults.window_size = (1280, 1028)
expyriment.control.set_develop_mode(True)

#%

expyriment.control.initialize(exp)

kb = expyriment.io.Keyboard()
bs = stimuli.BlankScreen()
wm = stimuli.TextLine('Waiting for scanner sync (or press \'t\')')
fs = stimuli.FixCross()

events = PriorityQueue()  # all stimuli will be queued here

# load stimuli

mapsounds = dict()
mapspeech = dict()
maptext = dict()
mappictures = dict()
mapvideos = dict()

for listfile in sys.argv[1:]:
    stimlist = csv.reader(io.open(listfile, 'r', encoding='utf-8'))
    bp = op.dirname(listfile)
    for row in stimlist:
예제 #30
0
############### INITIALISATION DE L'EXPERIENCE #################

exp = design.Experiment(
    "Projet PCBS: information crossing hemispheres - bimanual")
control.initialize(exp)
screen_size = exp.screen.surface.get_size()
user_device = exp.keyboard

##################### INITIALISATION DES PARAMETRES #####################

key_m = 59
key_q = 97
response_keys = [key_m, key_q]

nb_trial = 100
fixcross = stimuli.FixCross(size=(20, 20), line_width=3)
fixcross.preload()
Blankscreen = stimuli.BlankScreen()

# Paramètres d'affichage du stimulus:
square_dist = 200
square_size = [20, 20]
left_square = stimuli.Rectangle(square_size, position=[-square_dist, 0])
left_square.preload()
right_square = stimuli.Rectangle(square_size, position=[square_dist, 0])
right_square.preload()
square_displaytime = 100

# Définition des stimuli et paramètres de réponse utilisateur
trial_left = ["left", key_q, left_square, 0]
trial_right = ["right", key_m, right_square, 0]