Example #1
0
def make_connection(exp, experiment_name="force_daq"):
    """hand shake and filename,
    returns forceDAQ version
    """

    stimuli.TextScreen("Prepare force recording", "press key if ready").present()
    exp.keyboard.wait()
    stimuli.BlankScreen().present()
    while not udp.connect_peer(FORCE_SERVER_IP):
        stimuli.TextScreen("ERROR while connecting to server",
                           "try again or <ESC> to quit").present()
        exp.keyboard.wait()
        stimuli.BlankScreen().present()
        exp.clock.wait(300)

    stimuli.TextScreen("Connected", "").present()
    exp.clock.wait(500)
    udp.send(rc.Command.FILENAME + "{0}_{1}.csv".format(experiment_name, exp.subject))
    rtn = udp.receive(5)  # paused
    if rtn is None:
        runtimeerror(exp, "Force server not responding")
    version = rc.get_data(rc.Command.GET_VERSION)
    stimuli.TextScreen("Connected", "Version " + version).present()
    exp.clock.wait(1000)
    return version
Example #2
0
def _audio_playback(exp):
    """Test the audio playback"""

    info = """This will test the audio playback. A test tone will be played.

[Press RETURN to continue]
"""
    text = stimuli.TextScreen("Audio playback test", info)
    text.present()
    exp.keyboard.wait([constants.K_RETURN])
    exp.screen.clear()
    exp.screen.update()
    a = stimuli.Tone(duration=1000)
    a.present()
    exp.clock.wait(1000)
    text = stimuli.TextScreen("Did you hear the tone?", "[Press Y or N]")
    text.present()
    key, _rt = exp.keyboard.wait([constants.K_y,
                                 constants.K_n])
    if key == constants.K_y:
        response = "Yes"
    elif key == constants.K_n:
        response = "No"

    return response
def political_ideology_questions(Question_A, Question_B, Question_C,
                                 Answer_Question):
    stimuli.TextScreen(heading=Question_A, text=Answer_Question).present()
    Answer4 = exp.keyboard.wait(constants.K_ALL_DIGITS)
    stimuli.TextScreen(heading=Question_B, text=Answer_Question).present()
    Answer5 = exp.keyboard.wait(constants.K_ALL_DIGITS)
    stimuli.TextScreen(heading=Question_C, text=Answer_Question).present()
    Answer6 = exp.keyboard.wait(constants.K_ALL_DIGITS)
    return Answer4, Answer5, Answer6
Example #4
0
 def _show_message(self, caption, text, format={}, response='both',
                   stall=0, block=None, **kwargs):
     if caption == 'SKIP' or text == 'SKIP':
         return()
     if block:
         if block.get_factor('practice'):
             if _(caption + '[practice]') is not None:
                 caption += '[practice]'
             if _(text + '[practice]') is not None:
                 text += '[practice]'
         block_specific = '[block:{}]'.format(block.id)
         if _(caption + block_specific) is not None:
             caption += block_specific
         if _(text + block_specific) is not None:
             text += block_specific
     if _(caption + '[highlight]') and _(caption + '[highlight]').lower() in ['yes', 'true', '1']:
         kwargs.update({'heading_bold':True, 'heading_colour':(255,0,0)})
     stimuli.TextScreen(_(caption).format(**format),
             _(text).format(**format), **kwargs).present()
     self.clock.wait(stall)
     self.keyboard.clear()
     self.mouse.clear()
     while True:
         self.clock.wait(10)
         if (android or response == 'mouse' or response == 'both') and \
             self.mouse.get_last_button_down_event() is not None or \
             (response == 'keyboard' or response == 'both') and \
                 len(self.keyboard.read_out_buffered_keys()) > 0:
             break
Example #5
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
            ])
Example #6
0
def threshold_menu(exp, thresholds, last_item="Ende"):
    while True:
        select = io.TextMenu(heading=u"Schwellen: " + str(thresholds),
                             menu_items=["Schwellen Anpassen ",  # 0
                                         "Halten",  # 1
                                         last_item],
                             background_colour=misc.constants.C_GREY,
                             text_colour=misc.constants.C_BLACK,
                             width=500)
        x = select.get()
        blank = stimuli.BlankScreen()
        blank.present()

        if x == 0:
            new = textinput_thesholds()
            if new is not None:
                thresholds = new
        elif x == 1:
            if not start(exp):
                stimuli.TextScreen("ERROR: Could not start recording",
                                   "Press key to quit").present()
                exp.keyboard.wait()
                exit()
            exp.clock.wait(500)
            rc.set_force_thresholds(lower=thresholds[0], upper=thresholds[1])
            hold_check(exp, holding_time=10000)
            blank.present()
            pause(exp)
        else:
            break

    return thresholds
Example #7
0
def probes():
    """Displays thought probes and return the answers"""

    instructions = stimuli.TextScreen(heading="Hold your thoughts!",
                                      text="From 1 to 9.\
    \n How are your thoughts related to the task?\
    \n [totally unrelated] 1 2 3 4 5 6 7 8 9 [totally related]")
    instructions.present()
    button_r, rt_r = exp.keyboard.wait(misc.constants.K_ALL_DIGITS)

    instructions = stimuli.TextScreen(heading="",
                                      text="From 1 to 9.\
    \n How in control of your train of thought did you feel ? ?\
    \n [Not in control] 1 2 3 4 5 6 7 8 9 [Totally in control]")
    instructions.present()
    button_c, rt_c = exp.keyboard.wait(misc.constants.K_ALL_DIGITS)

    return button_r, rt_r, button_c, rt_c
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")
Example #9
0
 def _show_message(self, caption, text, format={}):
     if caption == 'SKIP' or text == 'SKIP':
         return ()
     stimuli.TextScreen(
         _(caption).format(**format),
         _(text).format(**format)).present()
     if android:
         self.mouse.wait_press()
     else:
         self.keyboard.wait()
Example #10
0
def get_menu(exp):
    return stimuli.TextScreen("Settings:",
                              "1: Measurement rate\n" +
                              "2: Maximum range of transmitter\n" +
                              "3: Report rate of data\n" +
                              "4: Power line frequency\n" +
                              "5: Metric data reporting\n\n" +
                              "q: Quit settings",
                              text_justification=0,
                              size=[exp.screen.size[0] / 4,
                                    exp.screen.size[1] / 2])
Example #11
0
    def __init__(self, device_ID=0, error_screen=True):
        """Create a Cedrus Device Input.

        Notes
        -----
        If no Cedrus device is connected, an error text screen will be
        presented informing that the device could not be found and suggesting
        to check the connection and to switch on the device. After keypress the
        class tries to reconnect with the device. Use <q> to quit this
        procedure.

        Parameters
        ----------
        device_id : int, optional
            device ID (default=0). Only required if more than one
            Cedrus Devices are connected.
        error_screen : bool, optional
            set False to switch off the 'device not found' error screen.
            An exception will be raise instead (default=True)

        """

        Input.__init__(self)
        if not isinstance(_pyxid, ModuleType):
            message = """CedrusDevice can not be initialized, because the Python package
            'pyxid' is not installed. See Expyriment online documentation."""
            raise ImportError(message)

        while True:
            devices = _pyxid.get_xid_devices()
            if len(devices) < 1:
                message = "Could not find a Cedrus Device. Please check the connection and \n"\
                + " ensure that the device is switch on."
            else:
                if not devices[device_ID].is_response_device():
                    message = "Cedrus Device #{0} is not a response device.".format(
                        device_ID)
                else:
                    self._xid = devices[device_ID]
                    break
            if error_screen and _internals.active_exp.is_initialized:
                stimuli.TextScreen(
                    "Error", message +
                    " Press a key to reconnect to the device.").present()
                _internals.active_exp.keyboard.wait()
                stimuli.BlankScreen().present()
                _internals.active_exp.clock.wait(300)
            else:
                raise IOError(message)

        self._xid.reset_base_timer()
        self._xid.reset_rt_timer()
        self._device_ID = device_ID
        self._buffer = misc.Buffer(name="Cedrus Device {0}".format(device_ID))
Example #12
0
def main(exp):
    """Displays the instructions and successively lauches each block """

    #practice block
    instructions = stimuli.TextScreen(
        heading="Practise",
        text="Thank you for participating in this experiment. \
    \nThe task is very simple : you will see numbers appear briefly on the screen, followed by a crossed capital X.\
    \nYou must press spacebar everytime you see a number EXCEPT when it's the number 3. \
    \n\n You also need to know that at random moments, 'thought probes' are going to appear. \
    \nThose probes inquire about what you were thinking about, just before they appeared.\
    \n(WARNING: to answer the probes, you should use the numbers on top of your keyboard, with Caps Lock on !!!)\
    \n\nIf you understood well and are ready to do a practice trial, press space bar"
    )
    instructions.present()
    exp.keyboard.wait(misc.constants.K_SPACE)
    block_name = "practice"
    blocks(nb_el_block_p, nb_probes_p, exp, block_name)

    #real blocks

    instructions = stimuli.TextScreen(
        heading="Experiment",
        text=
        "Instructions:\nYou must press spacebar everytime you see a number EXCEPT when it's the number 3. \
    \nAnswer on the scaleS about your thoughts when they appear. \
    \n\nIf you are ready for the real experiment, press space bar")
    instructions.present()
    exp.keyboard.wait(misc.constants.K_SPACE)

    for i in range(nb_block_r):
        block_name = "real" + str(i + 1)
        blocks(nb_el_block_r, nb_probes_r, exp, block_name)
        instructions = stimuli.TextLine(
            text="Ready for the next trial? Press spacebar")
        instructions.present()
        exp.keyboard.wait(misc.constants.K_SPACE)

    control.end(goodbye_text="Thank you very much...", goodbye_delay=2000)
def client(server_ip):
    # t : test connect
    # q : quit client
    # space : enter

    control.set_develop_mode(True)
    control.defaults.audiosystem_autostart = False
    exp = control.initialize()

    udp_connection = UDPConnection()
    print(udp_connection)

    if not udp_connection.connect_peer(server_ip):
        print("error connecting to peer")
        exit()

    stimuli.TextScreen(
        "connected to " + udp_connection.peer_ip,
        "\nSPACE: send text\nT: trigger test\nQ: quit").present()

    c = Clock()

    while True:
        key = exp.keyboard.check()
        if key == ord("q"):
            break
        elif key == misc.constants.K_SPACE:
            text = io.TextInput().get()
            stimuli.BlankScreen().present()
            print("send: {} {}".format(c.time, text))
            udp_connection.send(text)
        elif key == ord("t"):
            times = []
            for cnt in range(20):
                stimuli.TextLine("ping test " + str(cnt)).present()
                c.reset_stopwatch()
                ok, time = udp_connection.ping(timeout=1)
                print("answer received in {} ms".format(c.stopwatch_time))
                times.append(time)
                c.wait(100)
            stimuli.BlankScreen().present()
            print(times)

        feedback = udp_connection.poll()
        if feedback is not None:
            print("received: {} {}".format(c.time, feedback))

    udp_connection.unconnect_peer()
def stimulus_question_presentation(Answer):
    canvas = stimuli.Canvas(
        size=screen_size
    )  #create canvas w/ size of the screen/screen surface. Must create new canvas every time or canvases will overwrite themselves
    trial.stimuli[0].plot(canvas)
    stimuli.TextScreen(
        heading='Is it a {}?'.format(trial.get_factor('Stimulus')),
        text=Answer).plot(canvas)  # {} replaces by desired factor
    canvas.present(
    )  #canvas with trial and text stimuli above will be presented
    key, rt = exp.keyboard.wait(constants.K_ALL_DIGITS)
    exp.data.add(
        [
            block_name,
            trial.get_factor('Stimulus'),
            trial.get_factor('Type'),
            trial.get_factor('Filenumber'), [chr(key)], key, rt
        ]
    )  #[chr(key)] dont get keyboard key number but number pressed by participant (useful for participants with different keyboards e.g. french/chinese)
Example #15
0
    def info_screen():
        stimuli.TextScreen(heading="Expyriment Font Viewer",
            text="""
arrow keys left/right -- Switch font type
arrow keys up/down    -- Switch font size
                  i   -- Switch italic
                  b   -- Switch bold
                  c   -- Change text
                  h   -- Help
               return -- Quit


                 [Touch screen]
click left/right side --  Switch font type
click up/down side    --  Switch font size
click center          --  Quit
               """,
            text_font="freemono", text_bold=True,
            text_justification=0).present()
        exp.keyboard.wait()
Example #16
0
def _write_protocol(exp, results):
    """Write a protocol with all test results."""

    sorted_keys = results.keys()
    sorted_keys.sort()
    rtn = ""
    for key in sorted_keys:
        tabs = "\t" * (4 - int((len(key) + 1) / 8)) + "\t"
        try:
            rtn += key + ":" + tabs + results[key] + "\n"
        except TypeError:
            rtn += key + ":" + tabs + repr(results[key]) + "\n"

    filename = os.path.join(os.getcwd(), "test_suite_protocol.xpp")
    with open(filename, 'w') as f:
        f.write(rtn)
    text = stimuli.TextScreen(
        "Saved as", '"' + filename + '"' + "\n\n[Press RETURN to continue]")
    text.present()
    exp.keyboard.wait(constants.K_RETURN)
    return []  # required for event loop
Example #17
0
def _font_viewer(exp):
    all_fonts = expyriment.misc.list_fonts().keys()

    def info_screen():
        stimuli.TextScreen(heading="Expyriment Font Viewer",
                           text="""
arrow keys left/right -- Switch font type
arrow keys up/down    -- Switch font size
                  i   -- Switch italic
                  b   -- Switch bold
                  c   -- Change text
                  h   -- Help
               return -- Quit


                 [Touch screen]
click left/right side --  Switch font type
click up/down side    --  Switch font size
click center          --  Quit
               """,
                           text_font="freemono",
                           text_bold=True,
                           text_justification=0).present()
        exp.keyboard.wait()

    default_text = u"""The quick brown fox jumps over the lazy dog.
ABCDEFGHIJKLMNOPQRSTUVWXYZ ÄÖÜ
abcdefghijklmnopqrstuvwxyz äöü
1234567890.:,;ßéèê(*!?')"""
    text = default_text
    size = 14
    font_id = 0
    italic = False
    bold = False
    quest = io.TextInput(
        message="Please enter text: (Keep empty for default text)", length=35)
    mouse = io.Mouse(show_cursor=True)

    bs = (exp.screen.size[0] / 3.5, exp.screen.size[1] / 3.5)

    # rects center, left, right, top, button]
    cl = (20, 20, 20)
    rects = [
        stimuli.Rectangle(size=bs, position=[0, 0], colour=cl),
        stimuli.Rectangle(size=bs,
                          position=[(bs[0] - exp.screen.size[0]) / 2.2, 0],
                          colour=cl),
        stimuli.Rectangle(size=bs,
                          position=[(exp.screen.size[0] - bs[0]) / 2.2, 0],
                          colour=cl),
        stimuli.Rectangle(size=bs,
                          position=[0, (bs[1] - exp.screen.size[1]) / 2.2],
                          colour=cl),
        stimuli.Rectangle(size=bs,
                          position=[0, (exp.screen.size[1] - bs[1]) / 2.2],
                          colour=cl)
    ]
    rect_key_mapping = [
        constants.K_RETURN, constants.K_LEFT, constants.K_RIGHT,
        constants.K_UP, constants.K_DOWN
    ]

    info_screen()
    while True:
        font_str = all_fonts[font_id]
        font_description = "font '{0}', size {1}".format(font_str, size)
        if italic:
            font_description += ", italic"
        if bold:
            font_description += ", bold"

        canvas = stimuli.BlankScreen()
        for r in rects:
            r.plot(canvas)
        try:
            stimuli.TextScreen(heading=font_description,
                               text=text,
                               text_font=font_str,
                               text_size=size,
                               text_justification=0,
                               text_italic=italic,
                               text_bold=bold,
                               text_colour=(255, 255, 255)).plot(canvas)
        except:
            stimuli.TextLine(
                text="Sorry, I can't display the text with " +
                "{0}".format(font_description),
                text_colour=constants.C_EXPYRIMENT_ORANGE).plot(canvas)
        canvas.present()
        mouse.clear()
        exp.keyboard.clear()
        while True:
            key = exp.keyboard.check()
            if mouse.get_last_button_down_event() is not None:
                for cnt, r in enumerate(rects):
                    if r.overlapping_with_position(mouse.position):
                        key = rect_key_mapping[cnt]
                        break
            if key is not None:
                break

        if (key == constants.K_RETURN):
            break
        elif key == constants.K_UP:
            size += 2
        elif key == constants.K_DOWN:
            size -= 2
        elif key == constants.K_LEFT:
            font_id -= 1
            if font_id < 0:
                font_id = len(all_fonts) - 1
        elif key == constants.K_RIGHT:
            font_id += 1
            if font_id >= len(all_fonts):
                font_id = 0
        elif key == constants.K_i:
            italic = not (italic)
        elif key == constants.K_b:
            bold = not (bold)
        elif key == constants.K_c:
            text = quest.get()
            if len(text) <= 0:
                text = default_text
        else:
            info_screen()
    mouse.hide_cursor()
Example #18
0
exp = design.Experiment(name="Parity Decision", text_size=40)
control.initialize(exp)

# prepare the stimuli
trials = [(number, stimuli.TextLine(str(number)))
          for number in TARGETS * N_TRIALS_PER_TARGET]
random.shuffle(trials)

cue = stimuli.FixCross(size=(50, 50), line_width=4)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen(
    "Instructions",
    f"""When you'll see a number, your task to decide, as q:wuickly as possible, whether it is even or odd.

    if it is even, press '{EVEN_RESPONSE}'

    if it is odd, press '{ODD_RESPONSE}'

    There will be {len(TARGETS)} trials in total.

    Press the space bar to start.""")

exp.add_data_variable_names(['number', 'oddity', 'respkey', 'RT'])

control.start(skip_ready_screen=True)
instructions.present()
exp.keyboard.wait()

for number, stim in trials:
    blankscreen.present()
    exp.clock.wait(1000)
Example #19
0
    second_display = get_3_cards_surface(*fronts, three_cards_surfaces)
    t.add_stimulus(second_display)

    block.add_trial(t)

feedback = Feedback()

################################################################################
control.start(skip_ready_screen=True)

trials_info.to_csv(f'trials_subj_{exp.subject:02}.csv')
exp.data.add_variable_names(['condition', 'response', 'rt', 'is_correct'])

######################## Display Instructions ##################################

instructions = stimuli.TextScreen('Instructions', INSTRUCTIONS, text_size=15)
instructions.present(clear=True, update=True)
exp.keyboard.wait_char(' ')

exp.screen.clear()
exp.screen.update()
exp.clock.wait(2000)

#######################  Present trials  #################################

for trial in block.trials:
    # displays back of cards
    t0 = trial.stimuli[0].present(update=True, clear=True)
    resp, rt = exp.keyboard.wait_char('qsdn', BACK_DISPLAY_DURATION)
    # turn one card
    t1 = trial.stimuli[1].present(update=True, clear=True)
Example #20
0
    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()
    exp.clock.wait(10000)  #stim -1
    fixcross.preload()
    fixcross.present()
    exp.clock.wait(10000)  #stim 0

    start_t0 = time.time()
    Matrix = start.startTrial(b1, exp)  #stim 1 to stim n-1
    end_tend = time.time() - start_t0
    Matrix[2][5] = end_tend
    Matrix[2][1] = VolunteerNAME

    fixcross.present()
Example #21
0
nframe = 0
t1 = clock.time
while clock.time - t1 <= 1000:
    bs.present(update=True)
    nframe += 1
FPS = nframe

frame = stimuli.Canvas((800, 800))
msg = stimuli.TextScreen("",
                         f"""This script displays a white rectangle,
plays a tone and clears the screen, in a loop.

This permits to check the timing with some external equipment
(an oscilloscope, the Blackbox toolkit, etc.).

The current parameters are:

Tone duration = {TONE_DURATION} ms
Display duration = {SQUARE_DURATION} ms
Period = {PERIOD} ms
FPS = {FPS} Hz

Press any key for next screen (Later, to exit the program, just press 'Esc').""",
                         position=(0, -200))
msg.plot(frame)
square_top.plot(frame)
frame.present()
exp.keyboard.wait()
stimuli.TextScreen("", "Press a key to start").present(clear=True, update=True)
exp.keyboard.wait()

iperiod = 1
        t.add_stimulus(where[2])

        b.add_trial(t, copies=where[3])
    b.shuffle_trials()

    exp.add_block(b)

exp.data_variable_names = [
    "Bloc", "Position", "Bouton 1", "RT1", "Bouton 2", "RT2"
]  # Variables à enregistrer à chaque essai

##################### PRESENTATION DE L'EXPERIENCE #####################

control.start()

stimuli.TextScreen("Instructions", instructions).present()
user_device.wait()

block_index = 0
for block in exp.blocks:
    stimuli.TextScreen("Instructions",
                       instructions_total[block_index]).present()
    block_index += 1
    user_device.wait()

    for trial in block.trials:
        show_time = random.randint(1000, 1800)
        fixcross.present()
        exp.clock.wait(show_time)

        fixcross.present()
Example #23
0
feedbackCorrect = stimuli.TextLine(text='Točno!',
                                   text_colour=misc.constants.C_GREEN,
                                   text_bold=True)
feedbackCorrect.preload()

feedbackIncorrect = stimuli.TextLine(text='Pogrešno!',
                                     text_colour=misc.constants.C_RED,
                                     text_bold=True)
feedbackIncorrect.preload()

subCode = ''

# set to 1 after 1st mixed test block to initiate a break
testMixedCnt = 0

instructions1 = stimuli.TextScreen(heading='Uputa', text=instructionsIntro)
instructions2 = stimuli.TextScreen(heading='', text=instructionsGeneral1)
instructions3 = stimuli.TextScreen(heading='', text=instructionsGeneral2)
instructions4 = stimuli.TextScreen(heading='',
                                   text=instructionsOddEvenPractice)
instructions5 = stimuli.TextScreen(heading='', text=instructionsOddEvenTest)
instructions6 = stimuli.TextScreen(heading='',
                                   text=instructionsHighLowPractice)
instructions7 = stimuli.TextScreen(heading='', text=instructionsHighLowTest)
instructions8 = stimuli.TextScreen(heading='', text=instructionsMixed)
instructions9 = stimuli.TextScreen(heading='', text=instructionsMixedPractice)
instructions10 = stimuli.TextScreen(heading='', text=instructionsMixedTest)

breakBlockInstructions = stimuli.TextScreen(heading='Pauza', text=breakText)

instrBlocks = {'practicePureFeedOE': instructions4,
            t.set_factor("shape", my_trial[0])
            t.set_factor("filling", my_trial[1])
            s = stimuli.Picture(my_trial[2])
            t.add_stimulus(s)
            b.add_trial(t, copies=N)
    b.shuffle_trials()
    return b


for N in N_trials:
    for task in tasks:
        b = trial_generator(task, N)
        exp.add_block(b)

control.start(skip_ready_screen=True)
stimuli.TextScreen("Instructions", INSTRUCTIONS).present()
exp.keyboard.wait_char(" ")

for block in exp.blocks:
    stimuli.TextScreen("Instructions", block.get_factor("task_type")).present()
    exp.keyboard.wait(duration=ITI)
    for trial in block.trials:
        fixcross.present()
        exp.clock.wait(ITI - trial.stimuli[0].preload())
        trial.stimuli[0].present()
        button, rt = exp.keyboard.wait(
            [SHAPE_TASK_RECTANGLE, SHAPE_TASK_DIAMOND],
            duration=MAX_RESPONSE_DELAY)
        #Error feedback if required
        if trial.stimuli[0].filename == "S_R_2.png":
            is_correct = (button == SHAPE_TASK_RECTANGLE)
Example #25
0
    for trial in block.trials:
        trial.preload_stimuli()

# preparing global stimuli
blank = stimuli.BlankScreen()
blank.preload()
fixCross = stimuli.FixCross()
fixCross.preload()

# preparing instructions and subject code entry screens
subCodeInstr = stimuli.TextBox(text=subCodeText, size=(800, 400))
subCodeInput = io.TextInput(length=6,
                            background_stimulus=subCodeInstr,
                            position=(0, -100))

instructions1 = stimuli.TextScreen(heading='Uputa', text=instructionsText1)
instructions2 = stimuli.TextScreen(heading='', text=instructionsText2)
instructions3 = stimuli.TextScreen(heading='', text=instructionsText3)

feedbackCorrect = stimuli.TextLine(text='Točno!',
                                   text_colour=misc.constants.C_GREEN,
                                   text_bold=True)
feedbackCorrect.preload()

feedbackIncorrect = stimuli.TextLine(text='Pogrešno!',
                                     text_colour=misc.constants.C_RED,
                                     text_bold=True)
feedbackIncorrect.preload()

subCode = ''
Example #26
0
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(" ")

for category, item, stim in trials:
    blankscreen.present()
    exp.clock.wait(1000)
    cue.present()
    exp.clock.wait(500)
Example #27
0
    def _test1():
        info = """This will test the visual stimulus presentation timing specifics of your system.
During the test, you will see two squares on the screen.
After the test, you will be asked to indicate which (if any) of those two squares were flickering.

[Press RETURN to continue]"""
        # TODO test very slow quit
        text = stimuli.TextScreen("Visual stimulus presentation test", info)
        #y = []
        #for x in [16, 32, 48, 64]:
        #    y.extend([x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, ])
        #graph1 = _make_graph(range(60), y, [0, 255, 0])
        #y = range(80)
        #graph2 = _make_graph(range(60), y, [255, 0, 0])
        #graph1.position = (-200, -100)
        #graph2.position = (200, -100)
        text.present()
        #graph1.present(clear=False, update=False)
        #graph2.present(clear=False)
        exp.keyboard.wait([constants.K_RETURN])

        message = stimuli.TextScreen("Running", "Please wait...")
        message.present()
        message.present()
        message.present()
        c1 = stimuli.Canvas((400, 400))
        c2 = stimuli.Canvas((400, 400))
        c3 = stimuli.Canvas((400, 400))
        frame1 = stimuli.Rectangle((100, 100), position=(-100, 0))
        frame2 = stimuli.Rectangle((100, 100), position=(100, 0))
        bg = stimuli.Rectangle((90, 90), colour=exp.background_colour)
        bg.plot(frame1)
        bg.plot(frame2)
        frame1.plot(c1)
        frame2.plot(c2)
        frame1.plot(c3)
        frame2.plot(c3)
        c1.preload()
        c2.preload()
        c3.preload()
        c1.present(clear=False)
        c2.present(clear=False)
        c3.present(clear=False)

        s1 = stimuli.Circle(1, colour=exp.background_colour)
        s2 = stimuli.Circle(1, colour=exp.background_colour)
        s1.preload()
        s2.preload()
        todo_time = range(0, 60) * 3
        randomize.shuffle_list(todo_time)
        actual_time = []
        for x in todo_time:
            s1.present(clear=False)
            start = get_time()
            exp.clock.wait(x)
            s2.present(clear=False)
            actual_time.append((get_time() - start) * 1000)
            exp.clock.wait(expyriment.design.randomize.rand_int(30, 60))

        # determine refresh_rate
        tmp = []
        for _x in range(100):
            start = get_time()
            s1.present(clear=False)
            tmp.append(get_time() - start)
            start = get_time()
            s2.present(clear=False)
            tmp.append(get_time() - start)
        refresh_rate = 1000 / (statistics.mean(tmp) * 1000)

        #text = stimuli.TextScreen("Results", "[Press RETURN to continue]")
        #graph = _make_graph(todo_time, actual_time, [150, 150, 150])
        #graph.position = (0, -100)
        #text.present(update=False)
        #graph.present(clear=False)
        #exp.keyboard.wait([constants.K_RETURN])
        #text = stimuli.TextScreen(
        #    "Which picture looks most similar to the results?",
        #    "[Press LEFT or RIGHT arrow key]")
        #y = []
        #for x in [16, 32, 48, 64]:
        #    y.extend([x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, ])
        #graph1 = _make_graph(range(60), y, [0, 255, 0])
        #y = range(80)
        #graph2 = _make_graph(range(60), y, [255, 0, 0])
        #graph1.position = (-200, -100)
        #graph2.position = (200, -100)
        #text.present(update=False)
        #graph1.present(clear=False, update=False)
        #graph2.present(clear=False)
        #key, _rt = exp.keyboard.wait([constants.K_LEFT,
        #                             constants.K_RIGHT])
        #if key == constants.K_LEFT:
        #    response1 = "Steps"
        #elif key == constants.K_RIGHT:
        #    response1 = "Line"
        #else:
        #    response1 = None

        # show histogram of presentation delays
        def expected_delay(presentation_time, refresh_rate):
            refresh_time = 1000.0 / refresh_rate
            return refresh_time - (presentation_time % refresh_time)

        # delay = map(lambda x: x[1]- x[0], zip(todo_time, actual_time))
        unexplained_delay = map(
            lambda x: x[1] - x[0] - expected_delay(x[0], refresh_rate),
            zip(todo_time, actual_time))
        hist, hist_str = _histogram(unexplained_delay)
        inaccuracies = []
        delayed_presentations = 0
        for key in hist.keys():
            inaccuracies.extend([key % (1000 / refresh_rate)] * hist[key])
            if key != 0:
                delayed_presentations += hist[key]
        inaccuracy = int(round(sum(inaccuracies) / float(len(inaccuracies))))
        delayed = round(100 * delayed_presentations / 180.0, 2)

        text = stimuli.TextScreen(
            "How many of the two squares were flickering?",
            "[Press 0, 1 or 2]")
        text.present()
        key, _rt = exp.keyboard.wait(
            [constants.K_0, constants.K_1, constants.K_2])
        if key == constants.K_0:
            response = 0
        elif key == constants.K_1:
            response = 1
        elif key == constants.K_2:
            response = 2

        info = stimuli.TextScreen("Results", "")
        results1 = stimuli.TextScreen(
            "",
            "Estimated Screen Refresh Rate:     {0} Hz (~ every {1} ms)\n\n".
            format(int(round(refresh_rate)), int(1000.0 / refresh_rate)),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            position=(0, 40))
        results2 = stimuli.TextScreen(
            "",
            "Detected Framebuffer Pages:        {0}\n\n".format(response + 1),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            position=(0, 20))
        if inaccuracy != 0:
            results3_colour = [255, 0, 0]
        else:
            results3_colour = [0, 255, 0]
        results3 = stimuli.TextScreen(
            "",
            "Average Reporting Inaccuracy:      {0} ms\n\n".format(inaccuracy),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            text_colour=results3_colour,
            position=(0, -20))
        if delayed > 10:
            results4_colour = [255, 0, 0]
        elif 10 > delayed > 1:
            results4_colour = [255, 255, 0]
        else:
            results4_colour = [0, 255, 0]
        results4 = stimuli.TextScreen(
            "",
            "Unexplained Presentation Delays:   {0} %\n\n\n".format(delayed),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            text_colour=results4_colour,
            position=(0, -40))
        results5 = stimuli.TextScreen("",
                                      hist_str,
                                      text_font="freemono",
                                      text_size=16,
                                      text_bold=True,
                                      text_justification=0,
                                      position=(0, -100))
        results1.plot(info)
        results2.plot(info)
        results3.plot(info)
        results4.plot(info)
        results5.plot(info)
        info2 = stimuli.TextLine("[Press RETURN to continue]",
                                 position=(0, -160))
        info2.plot(info)
        info.present()
        exp.keyboard.wait([constants.K_RETURN])

        return todo_time, actual_time, refresh_rate, inaccuracy, delayed, response
Example #28
0
                    anti_aliasing=10)

            if ecc == 0:
                fixcross.plot(s)
            s.plot(canvas)

            memo_disque.plot(canvas), memo_carre.plot(canvas)
            t.add_stimulus(canvas)

            b.add_trial(t)
        exp.add_block(b)

# Run experiment
# introduction speech screen
stimuli.TextScreen(
    "Introduction",
    "Veuillez écouter les consignes de l'expérience.").present()
exp.keyboard.wait(keys=pass_key)

for mode_id in range(2):

    X = 0  # compteur d'erreurs totales
    Y = 0  # somme de rt moyens
    Z = 0  # compteur de blocs avec au moins une réponse

    for block_id in range(6 * mode_id, 6 * (mode_id + 1)):
        b = exp.blocks[block_id]

        # display instructions
        canvas_instruct = stimuli.BlankScreen()
        text = stimuli.TextScreen(
Example #29
0
            trial = design.Trial()
            trial.set_factor('block', 'mixed')
            trial.set_factor('task', task)
            trial.set_factor('shape', shape)
            trial.set_factor('number_of_circles', number)
            pngname = os.path.join(
                STIM_DIR, '{}_{}_{}_circles.png'.format(task, shape, number))
            trial.add_stimulus(stimuli.Picture(pngname))
            mixed_block.add_trial(trial)
mixed_block.shuffle_trials()

BLOCKS = [pure_shape_block, pure_filling_block, mixed_block]

blankscreen = stimuli.BlankScreen()
sex_question = stimuli.TextScreen(
    "One last question...",
    heading_size=40,
    text="What is your biological sex? Press M for male and F for female.")
training_instructions = stimuli.TextScreen("Instructions:",
                                           heading_size=40,
                                           text=TRAINING_INSTRUCTIONS)
reminder_if_incorrect_response = stimuli.TextScreen(
    "Your response was incorrect. Instructions reminder:",
    heading_size=40,
    text=REMINDER_INSTRUCTIONS)
experiment_instructions = stimuli.TextScreen(
    "So, you're all set for the experiment! Instructions:",
    heading_size=40,
    text=EXPERIMENT_INSTRUCTIONS)
exp_1.data_variable_names = [
    "Sex", "Trial Number", "Block", "Task Type", "Frame Shape",
    "Number of Circles", "Congruent Trial", "Correct Key", "RT",
Example #30
0
control.initialize(exp)

W, H = exp.screen.size
print(f"Screen size: {W}x{H}")

# Create a white vertical line
rect = stimuli.Rectangle((4, H), colour=(255, 255, 255))
rect.preload()

exp.add_data_variable_names(['skip', 'xpos', 'time', 'delta_time'])

control.start(subject_id=1, skip_ready_screen=True)

stimuli.TextScreen(
    'Tearing test', """A moving vertical bar will be displayed. 

If the synchronization to vertical blank is set, 
and the computer is fast enough, 
the bar should not be brokeni""").present()
exp.keyboard.wait()

t0 = exp.clock.time
timings = []
for skip in [8, 16, 32]:
    xpos = 0
    rect.reposition((-W // 2, 0))
    while xpos < W:
        rect.move((skip, 0))
        rect.present(clear=True, update=True)
        t1 = exp.clock.time
        exp.data.add([skip, xpos, t1, t1 - t0])
        timings.append(t1 - t0)