Esempio n. 1
0
def run_trial(n):
    trial = Trial(n=n, x=config["MATRIX_X_SIZE"], y=config["MATRIX_Y_SIZE"], n_answers=config["N_ANSWERS"])
    trial.prepare_draw(window, matrix_offset=config['MATRIX_OFFSET'], line_len=config['LINE_LEN'],
                       main_move_y=config['MOVE_MAIN_Y'], answers_move_y=config['MOVE_ANSWERS_Y'],
                       line_width=config["LINE_WIDTH"], grid_width=config["GRID_WIDTH"],
                       line_color=config["LINE_COLOR"], grid_color=config["GRID_COLOR"])
    stim_time = config['CONST_TIME'] + n * config['LEVEL_TIME']
    acc = None
    rt = -1
    window.callOnFlip(response_clock.reset)
    event.clearEvents()
    help_line.setAutoDraw(True)
    trial.set_auto_draw(True)
    window.flip()
    while response_clock.getTime() < stim_time:
        if stim_time - response_clock.getTime() < config['SHOW_CLOCK']:
            clock_image.draw()
        check_exit()
        window.flip()
        keys = event.getKeys(keyList=KEYS)
        if keys:
            rt = response_clock.getTime()
            resp = KEYS.index(keys[0])
            acc = 1 if trial.answers[resp].name == "correct" else 0
            break

    help_line.setAutoDraw(False)
    trial.set_auto_draw(False)
    window.flip()
    time.sleep(config['JITTER_TIME'])

    return acc, rt, stim_time, n
Esempio n. 2
0
File: main.py Progetto: ociepkam/PER
def run_trial(win, n):
    trial = Trial(win, config, n)
    stim_time = config['CONST_TIME'] + n * config['LEVEL_TIME']
    acc = 0
    rt = -1
    answer_type = None
    window.callOnFlip(response_clock.reset)
    event.clearEvents()
    trial.set_auto_draw(True)
    window.flip()

    while response_clock.getTime() < stim_time:
        if stim_time - response_clock.getTime() < config['SHOW_CLOCK']:
            clock_image.draw()
            window.flip()
        keys = event.getKeys(keyList=config["KEYS"])
        if keys:
            rt = response_clock.getTime()
            idx = config["KEYS"].index(keys[0])
            answer_type = trial.answers[idx].check_permutation(trial.task)
            acc = 1 if answer_type == 'answer' else -1
            break
        check_exit()
    trial.set_auto_draw(False)
    window.flip()
    time.sleep(config['JITTER_TIME'])

    return acc, rt, stim_time, n, answer_type
Esempio n. 3
0
File: main.py Progetto: ociepkam/DIF
def run_trial(n):
    m = Matrix(n=n, possible_answers=ALL_LINES)
    m.fill_matrix(distractors=config['DISTRACTORS'])
    matrix = TrialMatrix(matrix=m,
                         position=0,
                         window=window,
                         viz_offset=config['VIZ_OFFSET'],
                         text_size=config['TEXT_SIZE'])
    stim_time = config['CONST_TIME'] + m.n * config['LEVEL_TIME']
    acc = None
    rt = -1
    window.callOnFlip(response_clock.reset)
    event.clearEvents()
    help_line.setAutoDraw(True)
    matrix.set_auto_draw(True)
    window.flip()
    while response_clock.getTime() < stim_time:
        if stim_time - response_clock.getTime() < config['SHOW_CLOCK']:
            clock_image.draw()
        check_exit()
        window.flip()
        keys = event.getKeys(keyList=KEYS)
        if keys:
            rt = response_clock.getTime()
            resp = KEYS_TO_TRIAL_TYPE[keys[0]]
            acc = 1 if resp == m.answer_line_type else 0
            break

    help_line.setAutoDraw(False)
    matrix.set_auto_draw(False)
    window.flip()
    time.sleep(config['JITTER_TIME'])

    return acc, rt, stim_time, m.n, m.answer_line_type
Esempio n. 4
0
def run_trial(n):
    trial = Trial(n_relations=n)
    trial.prepare_to_draw(win=window,
                          main_fig_size=config['MAIN_FIG_SIZE'],
                          main_move_y=config['MAIN_MOVE_Y'],
                          answers_fig_size=config['ANSWERS_FIG_SIZE'],
                          fig_offset=config['FIG_OFFSET'],
                          answers_pos=[
                              config["ANSWERS_1_POS"], config["ANSWERS_2_POS"],
                              config["ANSWERS_3_POS"]
                          ],
                          arrow_long=config['ARROW_LONG'],
                          arrow_width=config['ARROW_WIDTH'],
                          arrow_color=config['ARROW_COLOR'])
    stim_time = config['CONST_TIME'] + trial.n_relations * config['LEVEL_TIME']
    acc = 0
    rt = -1
    answer_type = None
    window.callOnFlip(response_clock.reset)
    event.clearEvents()
    trial.set_auto_draw(True)
    window.flip()
    while response_clock.getTime() < stim_time:
        if stim_time - response_clock.getTime() < config['SHOW_CLOCK']:
            clock_image.draw()
        check_exit()
        window.flip()
        keys = event.getKeys(keyList=KEYS)
        if keys:
            rt = response_clock.getTime()
            idx = KEYS.index(keys[0])
            answer_type = trial.answers[idx].name
            acc = 1 if answer_type == 'answer' else -1
            break

    trial.set_auto_draw(False)
    window.flip()
    time.sleep(config['JITTER_TIME'])

    return acc, rt, stim_time, trial.n_relations, answer_type
Esempio n. 5
0
for elem in config['TRAINING_TRIALS']:
    print(elem)
    for trail in range(elem['n_trails']):
        acc, rt, stim_time, n = run_trial(n=elem['level'])
        RESULTS.append([i, 0, acc, rt, stim_time, n, 0, 0])
        i += 1
    ### FEEDBACK
        if acc == 1:
            feedb_msg = pos_feedb
        elif acc == 0:
            feedb_msg = neg_feedb
        else:
            feedb_msg = no_feedb
        for _ in range(100):
            feedb_msg.draw()
            check_exit()
            window.flip()
# EXPERIMENT
# show_info(window, join('.', 'messages', "instruction2.txt"), text_size=config['TEXT_SIZE'], screen_width=SCREEN_RES[0])
show_image(window, 'instruction2.png', SCREEN_RES)

experiment = NUpNDown(start_val=config['START_LEVEL'], max_revs=config['MAX_REVS'],
                      min_level=config["MIN_LEVEL"], max_level=config['MAX_LEVEL'])


old_rev_count_val = -1
for i, soa in enumerate(experiment, i):
    if i > config['MAX_TRIALS']:
        break
    acc, rt, stim_time, n = run_trial(soa)
    level, reversal, revs_count = map(int, experiment.get_jump_status())
Esempio n. 6
0
def run(words):
    global RESULTS, TRIGGER_NO, TRIGGERS_LIST, PORT_EEG
    for idx, word in enumerate(words):
        print(word['WORD'], type(word['WORD']), type(config["QUESTION"]))
        word_stim = visual.TextStim(win=win,
                                    text=word['WORD'].decode('utf-8'),
                                    antialias=True,
                                    font=u'Arial',
                                    height=config['WORD_SIZE'],
                                    wrapWidth=win.size[0],
                                    color=u'black',
                                    alignHoriz='center',
                                    alignVert='center',
                                    pos=config["WORD_POS"])

        trigger_name = "_{}_{}_{}_{}_".format(
            "new" if word['WORD_LIST'] != experiment_version else "exp",
            word['WORD_LIST'], word['WORD_EMO'], word['WORD'])
        TRIGGER_NO, TRIGGERS_LIST = prepare_trigger(
            trigger_type=TriggerTypes.WORD,
            trigger_no=TRIGGER_NO,
            triggers_list=TRIGGERS_LIST,
            trigger_name=trigger_name)

        answer = None
        rt = -1
        acc = None

        ans_show = False
        question_show = False

        fixation.setAutoDraw(True)
        win.flip()
        time.sleep(config["FIX_TIME"])
        fixation.setAutoDraw(False)
        win.flip()
        time.sleep(config["WAIT_AFTER_FIX"])

        win.callOnFlip(response_clock.reset)
        event.clearEvents()

        word_stim.setAutoDraw(True)
        win.flip()

        send_trigger(port_eeg=PORT_EEG,
                     trigger_no=TRIGGER_NO,
                     send_eeg_triggers=config['EEG_TRIGGERS'])

        while response_clock.getTime() < config["STIM_TIME"]:
            key = event.getKeys(config["KEYS"])
            if key:
                rt = response_clock.getTime()
                send_trigger(port_eeg=PORT_EEG,
                             trigger_no=TRIGGER_NO,
                             send_eeg_triggers=config['EEG_TRIGGERS'])
                answer = key[0]
                acc = word["WORD_TYPE"] == answers_order[config["KEYS"].index(
                    answer)]
                TRIGGER_NO, TRIGGERS_LIST = prepare_trigger(
                    trigger_type=TriggerTypes.REACTION,
                    trigger_no=TRIGGER_NO,
                    triggers_list=TRIGGERS_LIST,
                    trigger_name=trigger_name + str(acc))
                break
            if response_clock.getTime(
            ) > config["ANS_TIME_START"] and not ans_show:
                ans_1.setAutoDraw(True)
                ans_2.setAutoDraw(True)
                ans_show = True
                win.flip()
            if response_clock.getTime(
            ) > config["QUESTION_TIME_START"] and not question_show:
                question.setAutoDraw(True)
                question_show = True
                win.flip()
            check_exit(config["EXIT_KEY"])
            if response_clock.getTime() > config["SHOW_CLOCK"]:
                clock_image.setAutoDraw(True)
                win.flip()

        word_stim.setAutoDraw(False)
        ans_1.setAutoDraw(False)
        ans_2.setAutoDraw(False)
        clock_image.setAutoDraw(False)
        question.setAutoDraw(False)
        win.flip()

        # ['TRIAL_NR', 'NAWL_NR', 'WORD', 'WORD_EMO', 'WORD_LIST', 'WORD_TYPE', 'ANSWER', 'ACC', 'RT']
        result = [
            idx + 1, word['NAWL_NR'], word['WORD'], word['WORD_EMO'],
            word['WORD_LIST'], word['WORD_TYPE'], answer, acc, rt
        ]
        RESULTS.append(result)
        time.sleep(config["WAIT_TIME"])
def ophthalmic_procedure(win,
                         screen_res,
                         frames_per_sec,
                         trigger_no,
                         triggers_list,
                         text_size,
                         send_eeg_triggers=False,
                         send_nirs_triggers=False,
                         port_eeg=None,
                         port_nirs=None,
                         vis_offset=60,
                         secs_of_msg=5,
                         secs_of_blinks=9,
                         secs_of_saccades=9,
                         exit_key='f7'):
    """
    :param port_nirs:
    :param port_eeg:
    :param send_nirs_triggers:
    :param text_size:
    :param triggers_list:
    :param trigger_no:
    :param frames_per_sec:
    :param screen_res:
    :param win:
    :param send_eeg_triggers:
    :param vis_offset: No of pixels of margin between fixation crosses and screen border
    :param secs_of_msg:
    :param secs_of_blinks:
    :param secs_of_saccades:
    :return:
    """
    logging.info('Starting ophthalmic procedure... ')
    # prepare stim's
    ophthalmic_info = read_text_from_file(
        os.path.join('.', 'messages', 'ophthalmic_instruction.txt'))
    corners_info = read_text_from_file(
        os.path.join('.', 'messages', 'ophthalmic_corners.txt'))

    ophthalmic_info = visual.TextStim(win=win,
                                      font=u'Arial',
                                      text=ophthalmic_info,
                                      height=text_size,
                                      wrapWidth=screen_res['width'],
                                      color=u'black')
    corners_info = visual.TextStim(win=win,
                                   font=u'Arial',
                                   text=corners_info,
                                   height=text_size,
                                   wrapWidth=screen_res['width'],
                                   color=u'black')
    # crosses are located in corners
    crosses = [[x, y] for x in [
        -screen_res['width'] / 2 + vis_offset, screen_res['width'] / 2 -
        vis_offset
    ] for y in [
        -screen_res['height'] / 2 + vis_offset, screen_res['height'] / 2 -
        vis_offset
    ]]
    crosses = [
        visual.TextStim(win=win,
                        text=u'+',
                        height=3 * text_size,
                        color=u'black',
                        pos=pos) for pos in crosses
    ]

    ophthalmic_info.setAutoDraw(True)
    for _ in range(frames_per_sec * secs_of_msg):
        win.flip()
        check_exit(exit_key)
    ophthalmic_info.setAutoDraw(False)
    win.flip()

    for frame_counter in range(frames_per_sec * secs_of_blinks):
        if frame_counter % frames_per_sec == 0:
            trigger_no, triggers_list = prepare_trigger(
                trigger_type=TriggerTypes.BLINK,
                trigger_no=trigger_no,
                triggers_list=triggers_list)
            send_trigger(port_eeg=port_eeg,
                         port_nirs=port_nirs,
                         trigger_no=trigger_no,
                         send_eeg_triggers=send_eeg_triggers,
                         send_nirs_triggers=send_nirs_triggers)
        win.flip()
        check_exit(exit_key)

    corners_info.setAutoDraw(True)
    for _ in range(frames_per_sec * secs_of_msg):
        win.flip()
        check_exit(exit_key)
    corners_info.setAutoDraw(False)

    [item.setAutoDraw(True) for item in crosses]
    for frame_counter in range(frames_per_sec * secs_of_saccades):
        if frame_counter % frames_per_sec == 0:
            trigger_no, triggers_list = prepare_trigger(
                trigger_type=TriggerTypes.BLINK,
                trigger_no=trigger_no,
                triggers_list=triggers_list)
            send_trigger(port_eeg=port_eeg,
                         port_nirs=port_nirs,
                         trigger_no=trigger_no,
                         send_eeg_triggers=send_eeg_triggers,
                         send_nirs_triggers=send_nirs_triggers)
        win.flip()
        check_exit(exit_key)
    [item.setAutoDraw(False) for item in crosses]
    win.flip()

    logging.info('Ophthalmic procedure finished correctly!')

    return trigger_no, triggers_list
Esempio n. 8
0
    def run(self, config, win, response_clock, clock_image, mouse, accept_box,
            feedback, feedback_positive, feedback_negative):
        accept_box.set_start_colors()
        win.callOnFlip(response_clock.reset)
        event.clearEvents()

        accept_box.setAutoDraw(True)
        self.setAutoDraw(True, win)
        clock_is_shown = False

        while response_clock.getTime() < config["STIM_TIME"]:
            for answer in self.answers:
                if mouse.isPressedIn(answer["frame"]):
                    for ans in self.answers:
                        ans["frame"].setAutoDraw(False)
                    answer["frame"].setAutoDraw(True)
                    self.chosen_answer = answer["name"]
                    self.acc = self.chosen_answer == "target_living"
                    accept_box.set_end_colors()
                    win.flip()
                    event.clearEvents()
                    break
            if mouse.isPressedIn(accept_box.accept_box) and self.chosen_answer is not None:
                self.rt = response_clock.getTime()
                break

            if not clock_is_shown and config["STIM_TIME"] - response_clock.getTime() < config["SHOW_CLOCK"]:
                clock_image.setAutoDraw(True)
                clock_is_shown = True
                win.flip()

            check_exit()
            win.flip()

        if feedback:
            time.sleep(0.1)
            true_answer = str(self.answers.index([a for a in self.answers if a["name"] == "target_living"][0]) + 1)
            if self.acc:
                feedback_positive.text += " " + true_answer
                feedback_positive.setAutoDraw(True)
                win.callOnFlip(response_clock.reset)
                accept_box.accept_label.text = config["ACCEPT_BOX_TEXT"]
                win.flip()

                while response_clock.getTime() < config["FEEDBACK_SHOW_TIME"]:
                    event.clearEvents()
                    if mouse.isPressedIn(accept_box.accept_box):
                        break
                feedback_positive.text = feedback_positive.text[:-len(true_answer)-1]
            else:
                feedback_negative.text += " " + true_answer
                feedback_negative.setAutoDraw(True)
                win.callOnFlip(response_clock.reset)
                accept_box.accept_label.text = config["ACCEPT_BOX_TEXT"]
                win.flip()

                while response_clock.getTime() < config["FEEDBACK_SHOW_TIME"]:
                    event.clearEvents()
                    if mouse.isPressedIn(accept_box.accept_box):
                        break
                feedback_negative.text = feedback_negative.text[:-len(true_answer)-1]
            feedback_positive.setAutoDraw(False)
            feedback_negative.setAutoDraw(False)

        for ans in self.answers:
            ans["frame"].setAutoDraw(False)
        clock_image.setAutoDraw(False)
        accept_box.setAutoDraw(False)
        self.setAutoDraw(False, win)
Esempio n. 9
0
def run_trial(win, k, n, ans_type, config, feedback, feedb):
    response_clock = core.Clock()
    trial = Trial(k, n, ans_type)
    trial.prepare_to_draw(win, config)

    idx_info = visual.TextStim(win,
                               color='black',
                               pos=(500, 400),
                               height=50,
                               text=i)
    acc = None
    corr = [None, None]
    rt = []
    trial.draw(True)
    idx_info.setAutoDraw(True)
    win.callOnFlip(response_clock.reset)
    event.clearEvents()
    win.flip()

    clicked = []
    while response_clock.getTime() < config["trial_time"] and len(clicked) < 2:
        for idx, ans in enumerate(trial.answers):
            if mouse.isPressedIn(ans["frame"]) and ans["frame"].opacity == 0:
                rt.append(response_clock.getTime())
                ans["frame"].opacity = 1
                clicked.append(idx)
                win.flip()
                time.sleep(config["click_show_time"])
                ans["frame"].opacity = 0
                win.flip()
        if config["trial_time"] - response_clock.getTime(
        ) < config['SHOW_CLOCK']:
            clock_image.setAutoDraw(True)
        check_exit(config["exit_key"])
        win.flip()
    if len(clicked):
        corr[0] = trial.answers[clicked[0]]["corr"]
    if len(set(clicked)) == 2:
        corr[1] = trial.answers[clicked[1]]["corr"]
        acc = 1 if corr[0] and corr[1] else 0

    if feedback:
        for ans in trial.answers:
            if ans["corr"]:
                ans["frame"].lineColor = config["frame_answer_color"]
                ans["frame"].opacity = 1
        if acc and len(set(clicked)) == 2:
            feedb["pos"].setAutoDraw(True)
        elif len(clicked) == 2:
            feedb["neg"].setAutoDraw(True)
        else:
            feedb["no"].setAutoDraw(True)
        win.flip()
        if config["feedback_time"] > 0:
            time.sleep(config["feedback_time"])
        elif config["feedback_time"] == -1:
            press_space_msg.setAutoDraw(True)
            win.flip()
            key = event.waitKeys(keyList=['f7', 'space'])
            if key == ['f7']:
                logging.critical(
                    'Experiment finished by user! {} pressed.'.format(key[0]))
                exit(0)
        # else:
        #     key = event.waitKeys(["space", config["exit_key"]])
        #     if key == config["exit_key"]:
        #         logging.critical('Experiment finished by user! {} pressed.'.format(key))
        #         exit(1)
    for _, v in feedb.items():
        v.setAutoDraw(False)
    trial.draw(False)
    idx_info.setAutoDraw(False)
    clock_image.setAutoDraw(False)
    press_space_msg.setAutoDraw(False)
    win.flip()
    time.sleep(config["wait_time"])
    rt += [None, None]
    return corr[0], corr[1], acc, rt[0], rt[1]
Esempio n. 10
0
def run_trial(trial, config, response_clock, clock_image, mouse, win, fixation, stim_time,
              instruction=None, training=False, training_trial_idx=None):
    win.callOnFlip(response_clock.reset)
    win.flip()
    while response_clock.getTime() < config["FIXATION_TIME"]:
        fixation.draw(win)
        win.flip()

    acc = -1
    chosen_answer = {"word": None, "length": None, "category": None}
    rt = None
    trial.set_auto_draw(True)
    if instruction is not None:
        instruction.setAutoDraw(True)
    clock_is_shown = False
    win.callOnFlip(response_clock.reset)
    win.flip()
    event.clearEvents()

    while response_clock.getTime() < stim_time and acc == -1:
        for idx, frame in enumerate(trial.frames):
            if frame.contains(mouse.getPos()) and config["SHOW_FRAMES"]:
                frame.draw()
            if mouse.isPressedIn(frame):
                chosen_answer = trial.info["answers"][idx]
                acc = chosen_answer == trial.info["task"]
                rt = response_clock.getTime()
                break

        if clock_image is not None and \
                not clock_is_shown and \
                config["STIM_TIME"] - response_clock.getTime() < config["SHOW_CLOCK"]:
            clock_image.setAutoDraw(True)
            clock_is_shown = True
            win.flip()

        check_exit()
        win.flip()
    if clock_image is not None:
        clock_image.setAutoDraw(False)
    if training:
        if acc == 1:
            feedback_file_name = "feedback_positive.txt"
        elif acc == -1:
            feedback_file_name = "feedback_no_answer.txt"
        else:
            feedback_file_name = "feedback_negative.txt"
        text = read_text_from_file(join('.', 'messages', feedback_file_name)) + \
               read_text_from_file(join('.', 'messages', "feedback_info_{}.txt".format(training_trial_idx + 1)))

        feedback = visual.TextStim(win=win, height=config['FEEDBACK_SIZE'], alignHoriz='center', alignVert='center',
                                   font=u'Arial', pos=config["FEEDBACK_POS"], text=text, wrapWidth=win.size[0],
                                   color=config["FEEDBACK_COLOR"])
        feedback.setAutoDraw(True)

        answer_idx = trial.info["answers"].index(trial.info["task"])
        trial.frames[answer_idx].lineColor = config["FRAME_COLOR_CORR"]
        trial.frames[answer_idx].setAutoDraw(True)
        if not acc:
            chosen_idx = trial.info["answers"].index(chosen_answer)
            trial.frames[chosen_idx].lineColor = config["FRAME_COLOR_WRONG"]
            trial.frames[chosen_idx].setAutoDraw(True)

        win.flip()
        event.waitKeys(keyList=['space'])
        feedback.setAutoDraw(False)

    trial.set_auto_draw(False)
    if instruction is not None:
        instruction.setAutoDraw(False)
    win.flip()
    time.sleep(config["WAIT_TIME"] + random.uniform(config["WAIT_JITTER"][0], config["WAIT_JITTER"][1]))

    return chosen_answer, acc, rt
Esempio n. 11
0
def run_trial(n, feedback=False):
    # Prepare trial
    m = Matrix(n=n, possible_answers=ALL_LINES)
    m.fill_matrix(distractors=config['DISTRACTORS'])
    matrix = TrialMatrix(matrix=m, position=0, window=window, viz_offset=config['VIZ_OFFSET'],
                         text_size=config['TEXT_SIZE'])
    idx_info = visual.TextStim(window, color='black', pos=(500, 400), height=50,
                               text=i)
    stim_time = config['CONST_TIME'] + m.n * config['LEVEL_TIME']
    acc = None
    rt = -1
    window.callOnFlip(response_clock.reset)
    event.clearEvents()

    # draw trial
    matrix.set_auto_draw(True)
    idx_info.setAutoDraw(True)
    frames = create_items_frames(matrix.stimulus_matrix)

    for frame in frames:
        frame.setAutoDraw(True)

    window.flip()

    # run trial
    clicked = []
    while response_clock.getTime() < stim_time and len(clicked) < 2:

        for idx, frame in enumerate(frames):
            if mouse.isPressedIn(frame) and frame.opacity == 0:
                frame.opacity = 1
                clicked.append(idx)
        if stim_time - response_clock.getTime() < config['SHOW_CLOCK']:
            clock_image.draw()
        check_exit()
        window.flip()
    rt = response_clock.getTime()
    time.sleep(config["wait_after_answer"])

    # check answer
    if m.answer_line_type == "column":
        # good_answer = [m.answer_line_number, m.answer_line_number + n*n - n]  # have to click first and last
        good_answer = list(range(m.answer_line_number, m.answer_line_number + n * n, n))  # any two elements in line

    elif m.answer_line_type == "row":
        # good_answer = [m.answer_line_number * n, m.answer_line_number * n + n - 1]  # have to click first and last
        good_answer = list(range(m.answer_line_number * n, m.answer_line_number * n + n))  # any two elements in line
    else:
        raise Exception("Wrong answer type")

    if len(clicked) == 2:
        acc = 1 if clicked[0] in good_answer and clicked[1] in good_answer else 0

    # draw feedback
    if feedback:
        answer_frame = create_answer_frame(m.answer_line_type, m.answer_line_number, n)
        answer_frame.setAutoDraw(True)
        if acc == 1:
            feedb_msg = pos_feedb
        elif acc == 0:
            feedb_msg = neg_feedb
        else:
            feedb_msg = no_feedb
        feedb_msg.setAutoDraw(True)
        window.flip()

        if config["feedback_time"] > 0:
            time.sleep(config["feedback_time"])
        elif config["feedback_time"] == -1:
            press_space_msg.setAutoDraw(True)
            window.flip()
            key = event.waitKeys(keyList=['f7', 'space'])
            if key == ['f7']:
                logging.critical('Experiment finished by user! {} pressed.'.format(key[0]))
                exit(0)

        feedb_msg.setAutoDraw(False)
        answer_frame.setAutoDraw(False)
        press_space_msg.setAutoDraw(False)

    # cleaning
    for frame in frames:
        frame.setAutoDraw(False)
    matrix.set_auto_draw(False)
    idx_info.setAutoDraw(False)
    window.flip()

    time.sleep(config['JITTER_TIME'])

    return acc, rt, stim_time, m.n, m.answer_line_type
Esempio n. 12
0
def trial(window, config, answers_colors, info, mouse, clock_image, feedb,
          mouse_info, idx_info):
    response_clock = core.Clock()
    a_to_b_relation = None
    press_space_msg = None
    transformation_a = None
    transformation_b = None
    if config["randomize_graphs"] or config[
            "session_type"] == "Randomized experiment" and info['TRAIN'] == 0:
        while True:
            for matrix in ["A", "B"]:
                if random.choice([True, False]):
                    rotate_matrices_in_trial(info, matrix)
                    if matrix == "A":
                        transformation_a = "ROTATION"
                    else:
                        transformation_b = "ROTATION"
                else:
                    mirror_matrices_in_trial(info, matrix)
                    if matrix == "A":
                        transformation_a = "MIRROR"
                    else:
                        transformation_b = "MIRROR"
            if info["Nodes_A"] != info["Nodes_B"] or info["Edges_A"] != info[
                    "Edges_B"]:
                if transformation_a == transformation_b:
                    a_to_b_relation = "ROTATION"
                else:
                    a_to_b_relation = "MIRROR"
                break
    if not config["randomize_graphs"] or not config["session_type"] == "Randomized experiment" \
            or info['TRAIN'] == 1 or random.choice([True, False]):
        a = Matrix(win=window,
                   pos=config["left_graph_position"],
                   config=config,
                   v=info["Nodes_A"],
                   e=info["Edges_A"])
        b = Matrix(win=window,
                   pos=config["right_graph_position"],
                   config=config,
                   v=info["Nodes_B"],
                   e=info["Edges_B"])
    else:
        a = Matrix(win=window,
                   pos=config["left_graph_position"],
                   config=config,
                   v=info["Nodes_B"],
                   e=info["Edges_B"])
        b = Matrix(win=window,
                   pos=config["right_graph_position"],
                   config=config,
                   v=info["Nodes_A"],
                   e=info["Edges_A"])
        info["Left_button_targets"] = info["Left_button_targets"][::-1]
        info["Right_button_targets"] = info["Right_button_targets"][::-1]

    switch_targets = False
    if not config["one_target"] and (config["session_type"] == "Randomized experiment" or config["randomize_graphs"])\
            and info['TRAIN'] == 0 and random.choice([True, False]):
        a.mark_answer(v_nr=info["Left_button_targets"][0],
                      color=answers_colors[1])
        a.mark_answer(v_nr=info["Right_button_targets"][0],
                      color=answers_colors[0])
        switch_targets = True
    elif not config["one_target"]:
        a.mark_answer(v_nr=info["Left_button_targets"][0],
                      color=answers_colors[0])
        a.mark_answer(v_nr=info["Right_button_targets"][0],
                      color=answers_colors[1])
    elif (config["session_type"] == "Randomized experiment" or config["randomize_graphs"]) \
            and info['TRAIN'] == 0 and random.choice([True, False]):
        a.mark_answer(v_nr=info["Right_button_targets"][0],
                      color=answers_colors[0])
        switch_targets = True
    else:
        a.mark_answer(v_nr=info["Left_button_targets"][0],
                      color=answers_colors[0])

    if config["feedback"]:
        press_space_msg = visual.TextStim(
            window,
            text=replace_polish(config["press_space_message"]),
            color=config["press_space_button_color"],
            height=config["feedback_text_size"],
            pos=[
                config["feedback_position"][0],
                config["feedback_position"][1] - 60
            ])
    a.set_auto_draw(True)
    b.set_auto_draw(True)
    window.callOnFlip(response_clock.reset)
    event.clearEvents()
    if config["show_mouse_buttons"]:
        mouse_info.setAutoDraw(True)
    if config["show_trial_number"]:
        idx_info.setAutoDraw(True)
    window.flip()

    click = {"left": False, "right": False}
    answers = {"left": None, "right": None}
    rt = {"left": None, "right": None}
    if not config["one_target"]:
        while response_clock.getTime() < config["trial_time"] and not (
                click["left"] and click["right"]):
            for idx, point in b.v:
                if not click["left"] and mouse.isPressedIn(point, buttons=[0]):
                    rt["left"] = response_clock.getTime()
                    b.mark_answer(idx, color=answers_colors[0])
                    window.flip()
                    if not config["click_show_time"]:
                        time.sleep(0.2)
                        b.mark_answer(idx, color=config["vertices_color"])
                        window.flip()
                    click["left"] = True
                    answers["left"] = idx
                elif not click["right"] and mouse.isPressedIn(point,
                                                              buttons=[2]):
                    rt["right"] = response_clock.getTime()
                    b.mark_answer(idx, color=answers_colors[1])
                    window.flip()
                    if not config["click_show_time"]:
                        time.sleep(0.2)
                        b.mark_answer(idx, color=config["vertices_color"])
                        window.flip()
                    click["right"] = True
                    answers["right"] = idx
            if config["show_clock_icon"] and config[
                    "trial_time"] - response_clock.getTime(
                    ) < config['clock_time']:
                clock_image.setAutoDraw(True)
            check_exit()
            window.flip()
        if config["show_clock_icon"]:
            clock_image.setAutoDraw(False)
        if not switch_targets:
            acc = {
                "left": answers["left"] == info["Left_button_targets"][1],
                "right": answers["right"] == info["Right_button_targets"][1]
            }
        else:
            acc = {
                "left": answers["left"] == info["Right_button_targets"][1],
                "right": answers["right"] == info["Left_button_targets"][1]
            }
    else:
        while response_clock.getTime(
        ) < config["trial_time"] and not click["left"]:
            for idx, point in b.v:
                if not click["left"] and mouse.isPressedIn(point, buttons=[0]):
                    rt["left"] = response_clock.getTime()
                    b.mark_answer(idx, color=answers_colors[0])
                    window.flip()
                    if not config["click_show_time"]:
                        time.sleep(0.2)
                        b.mark_answer(idx, color=config["vertices_color"])
                        window.flip()
                    click["left"] = True
                    answers["left"] = idx
            if config["show_clock_icon"] and \
               config["trial_time"] - response_clock.getTime() < config['click_show_time']:
                clock_image.setAutoDraw(True)
            check_exit()
            window.flip()
        if config["show_clock_icon"]:
            clock_image.setAutoDraw(False)
        if not switch_targets:
            acc = {
                "left": answers["left"] == info["Left_button_targets"][1],
                "right": answers["right"]
            }
        else:
            acc = {
                "left": answers["left"] == info["Right_button_targets"][1],
                "right": answers["right"]
            }

    b.mark_answer(answers["left"], color=config["vertices_color"])
    b.mark_answer(answers["right"], color=config["vertices_color"])

    if config["feedback"] and info["FEED"] == 1:
        b.mark_answer(info["Left_button_targets"][1], color=answers_colors[0])
        if not config["one_target"]:
            b.mark_answer(info["Right_button_targets"][1],
                          color=answers_colors[1])

        if not config["one_target"]:
            if not click["left"] or not click["right"]:
                feedb["no"].setAutoDraw(True)
            elif acc["left"] and acc["right"]:
                feedb["pos"].setAutoDraw(True)
            else:
                feedb["neg"].setAutoDraw(True)
            window.flip()
        else:
            if not click["left"]:
                feedb["no"].setAutoDraw(True)
            elif acc["left"]:
                feedb["pos"].setAutoDraw(True)
            else:
                feedb["neg"].setAutoDraw(True)
            window.flip()

        press_space_msg.setAutoDraw(True)
        window.flip()
        event.waitKeys(keyList=['f7', 'space'])

    a.set_auto_draw(False)
    b.set_auto_draw(False)
    if config["show_mouse_buttons"]:
        mouse_info.setAutoDraw(False)
    if config["show_trial_number"]:
        idx_info.setAutoDraw(False)
    if config["feedback"]:
        press_space_msg.setAutoDraw(False)
        for k, v in feedb.items():
            v.setAutoDraw(False)

    window.flip()
    time.sleep(config["break_time"])
    return answers, rt, acc, a_to_b_relation