Exemple #1
0
def axb(screen,
        background,
        input_file,
        result_file,
        instructions,
        isi=1000,
        fixation_duration=500,
        train=False):
    try:
        # Import stimuli files =========================================
        # stimuli are organised in a python dictionary type, to view the content use print()
        trial, header_index = psypsyio.read_stimuli(input_file, "\t")
        # print(trial["trial_number"])

        # Create result file ===========================================
        result = open(result_file, "w")

        # Add header to result output file
        psypsyio.write_result_header(result, trial, result_columns)

        # Initialize counts for feedback
        nb_trials = nb_correct = nb_wrong = nb_missed = 0
        correct_rt = wrong_rt = 0

        for i in range(trial["trial_number"]):
            # for i in range(2):  # modify number in the range() to make test
            screen.fill(background)
            pygame.display.flip()

            # Pauses: 192 trials, 1 break
            if not train:
                if i == 95:
                    psypsyaxb.axb_pause(screen, screen_width, screen_height,
                                        background, instructions.get("pause"))

            # Processing sound stimuli =*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*
            if train:
                path = "training/"
            else:
                path = "stim/"

            # Get stimuli path
            stimulus_a = path + trial["A"][i] + ".wav"
            stimulus_x = path + trial["X"][i] + ".wav"
            stimulus_b = path + trial["B"][i] + ".wav"
            sound_path = [stimulus_a, stimulus_x, stimulus_b]

            # Load stimuli & Compute sound stimuli duration
            mixed_sounds, duration_sounds = psypsyinterface.mix_sound_stimuli(
                sound_path)

            # Compute target result
            if trial["X"][i][:-2] == trial["A"][i][:-2]:
                # compare two strings of A and X if identical then A else B
                target_response = "A"
            else:
                target_response = "B"

            # Prepare output line
            trial_result = []
            for key in header_index:
                trial_result.append(trial[header_index[key]][i])

            # =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
            # Play sounds and record response                          *
            # =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
            # Display fixation point
            psypsyinterface.point_fixation(screen, fixation_duration)
            # 500ms of display
            psypsyinterface.clear_screen(screen, background)

            # Play A ==============
            start_sound_a = pygame.time.get_ticks()
            mixed_sounds[0].play()  # PLAY SOUND A
            while pygame.mixer.get_busy():  # sound playing
                continue
            end_sound_a = pygame.time.get_ticks()

            while pygame.time.get_ticks() - end_sound_a < 1000:
                continue
            pygame.event.pump()
            pygame.event.clear()  # clear event and wait for response

            # Play X and B and record response (Type, Time) =============
            xb_sequence = [mixed_sounds[1], mixed_sounds[2]]
            xb_measures = []
            response = False
            response_type = []
            response_time = []

            # indication for X and B
            # index_b == 0: ISI after X
            # index_b == 1: ISI after B
            index_b = 0

            for s in xb_sequence:
                # get start point of the sound
                duration = int(
                    round(pygame.mixer.Sound.get_length(s), 3) * 1000)
                start_sound = pygame.time.get_ticks()
                xb_measures.append(start_sound)
                s.play()  # play sound

                # index_b == 1: 2000ms after sound B
                if index_b == 1:
                    isi_post = 2000
                else:
                    # index_b == 0: 1000ms after sound X
                    isi_post = 1000

                while pygame.mixer.get_busy() and not response or (
                        pygame.time.get_ticks() - start_sound <=
                        duration + isi_post):
                    for e in pygame.event.get():
                        if e.type == QUIT or (e.type == KEYDOWN
                                              and e.key == K_ESCAPE):
                            raise Exception
                        elif e.type == KEYDOWN:
                            if e.key == K_LSHIFT:
                                response_time = [pygame.time.get_ticks()]
                                response_type = ["A"]
                                response = True
                            elif e.key == K_RSHIFT:
                                response_time = [pygame.time.get_ticks()]
                                response_type = ["B"]
                                response = True
                        else:
                            response = False

                # Get end point of the sound
                if index_b == 1:
                    xb_measures.append(pygame.time.get_ticks() - 2 * isi)
                elif index_b == 0:
                    xb_measures.append(pygame.time.get_ticks() - isi)

                index_b += 1

            # Get measures
            start_sound_x = xb_measures[0]
            end_sound_x = xb_measures[1]
            start_sound_b = xb_measures[2]
            end_sound_b = xb_measures[3]

            # Handle empty response
            # response time =*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*
            if response_time != []:
                response_time_s = response_time[0]
                real_rt = response_time_s - start_sound_b
            else:
                response_time_s = 0
                real_rt = 0
            # response type =*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*
            if response_type != []:
                response_type_s = response_type[0]
            else:
                response_type_s = "NA"

            # Compute the correctness of response
            # And display feedback for training
            nb_trials += 1

            if response_type_s == target_response:
                correct = "T"
                nb_correct += 1
                correct_rt += real_rt
                if train:
                    psypsyinterface.display_text_colour(screen,
                                                        str(real_rt) + " ms",
                                                        colour=(0, 255, 0))
                    pygame.time.wait(500)
                    psypsyinterface.clear_screen(screen, background)
            elif response_type_s == "NA":
                correct = "F"
                nb_missed += 1
                if train:
                    psypsyinterface.display_text_colour(screen, "???")
                    pygame.time.wait(500)
                    psypsyinterface.clear_screen(screen, background)
            else:
                correct = "F"
                # Calculate wrong response number and mean(rt)
                nb_wrong += 1
                wrong_rt += real_rt
                if train:
                    for click in range(3):
                        psypsyinterface.display_text_colour(
                            screen,
                            str(real_rt) + "ms")
                        pygame.time.wait(100)
                        psypsyinterface.clear_screen(screen, background)
                        pygame.time.wait(50)

            # Append trial measures
            trial_result.extend([
                start_sound_a, duration_sounds[0], end_sound_a, start_sound_x,
                duration_sounds[1], end_sound_x, start_sound_b,
                duration_sounds[2], end_sound_b, response_time_s,
                target_response, response_type_s, real_rt, correct
            ])

            # Output results
            psypsyio.write_result_line(result, trial_result)

            # inter-trial time
            pygame.time.wait(interTrial)

        # Avoid division by zero
        if nb_correct == 0:
            nb_correct = 1

        resume = {
            "nb_trials": nb_trials,
            "nb_correct": nb_correct,
            "nb_wrong": nb_wrong,
            "nb_missed": nb_missed,
            "correct_rt": correct_rt,
            "wrong_rt": wrong_rt
        }

        result.close()
    finally:

        if not train:
            print("End experiment\n")
            pygame.time.wait(1000)
        else:
            print("End training\n")

    return resume
Exemple #2
0
def habituation_3(subj, condition_p3, skip_to_3, path, screen, tk,
                  screen_width, screen_height):
    start_time = datetime.datetime.now().strftime(
        '%Y-%m-%d-%H:%M:%S')  # get current date time
    background_black = (0, 0, 0)  # black
    background_white = (255, 255, 255)  # white
    psypsyinterface.clear_screen(screen, background_black)
    # Path to files ==========================================================
    # path to experiment materials
    phase3_path = "_experimental_suite\Exp_1_looking_time\\2018tsi_nn"
    hab_video_path = phase3_path + "\hab_test\\"

    # Stimuli Path
    stimuli_file = "_experimental_suite\exp1_p3_test_trial_.csv"

    # output
    output = "_experimental_suite\\results\exp1_p3_results_{}.csv".format(
        participant_id)

    # Check experiment condition ==============================================
    u = "u"
    y = "y"

    if skip_to_3:
        u = "a"
        y = "i"

    if condition_p3 == "u-c":
        habituation = u
    elif condition_p3 == "u-s":
        habituation = u
    elif condition_p3 == "y-c":
        habituation = y
    elif condition_p3 == "y-s":
        habituation = y
    else:
        raise ValueError('something is wrong in condition')

    # Start Experiment =======================================================

    # Attention-getter ==================================
    # loop video until there's a key press
    trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    trial_start = pygame.time.get_ticks()
    duration = 0
    trial_off = False
    write_result_phase3(output,
                        subj,
                        start_time,
                        condition_p3,
                        "1",
                        trial_on,
                        trial_off,
                        "gaze on",
                        duration,
                        "attention-getter",
                        "spiral.mov",
                        "NA",
                        startend="attentionSTART")
    attention_getter = "_experimental_suite\Exp_1_looking_time\\2018tsi_nn\\attention-getter\spiral.mov"
    loop = psypsyvideo.play_video_loop(attention_getter, screen, tk, -1)
    print("Looping video...")
    check_exit(loop)
    trial_end = pygame.time.get_ticks()
    duration = trial_end - trial_start
    trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    write_result_phase3(output,
                        subj,
                        start_time,
                        condition_p3,
                        "1",
                        trial_on,
                        trial_off,
                        "gaze on",
                        duration,
                        "attention-getter",
                        "spiral.mov",
                        "NA",
                        startend="attentionEND")

    psypsyinterface.clear_screen(screen, background_black)

    # Habituation section ====================================================

    trial_duration_list = []
    hab_i = 1
    while hab_i < 24:  # reach 24 habituation trial

        # Attention-getter ==================================
        # loop video until there's a key press
        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()
        write_result_phase3(output,
                            subj,
                            start_time,
                            condition_p3,
                            str(hab_i + 2),
                            trial_on,
                            trial_off,
                            "gaze on",
                            duration,
                            "attention-getter",
                            "spiral.mov",
                            "NA",
                            startend="attentionSTART")
        loop = psypsyvideo.play_video_loop(attention_getter, screen, tk, -1)
        check_exit(loop)

        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        write_result_phase3(output,
                            subj,
                            start_time,
                            condition_p3,
                            str(hab_i + 2),
                            trial_on,
                            trial_off,
                            "gaze on",
                            duration,
                            "attention-getter",
                            "spiral.mov",
                            "NA",
                            startend="attentionEND")

        psypsyinterface.clear_screen(screen, background_black)

        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()
        habituation_file = "habituation.mov"
        habituation_trial_video = hab_video_path + "habituation.mov"
        clip_habituation = VideoFileClip(habituation_trial_video)
        log = "NA"
        # Habituation trial
        # Trial ends when the movie finishes, or when there's no key press for the last 2 seconds
        tagEvent("TRIALSTART", hab_i, trial_on, trial_off, "end",
                 "habituation", habituation_file)
        key = psypsyvideo.play_video_2s(clip_habituation, screen, tk)
        check_exit(key)
        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        trial_duration_list.append(duration)

        # Calculate average duration
        if len(trial_duration_list) > 3:
            order = trial_duration_list[:]
            ordered = sorted(order)
            average_duration_long = int(
                (ordered[-1] + ordered[-2] + ordered[-3]) / 3)
            last_three_duration = int(
                (trial_duration_list[-1] + trial_duration_list[-2] +
                 trial_duration_list[-3]) / 3)
            log = str(average_duration_long) + " / " + str(last_three_duration)
            if last_three_duration < (average_duration_long * 0.5):
                log = str(average_duration_long) + " / " + str(
                    last_three_duration) + "_criterion_met"
                write_result_phase3(output,
                                    subj,
                                    start_time,
                                    condition_p3,
                                    str(hab_i + 2),
                                    trial_on,
                                    trial_off,
                                    key,
                                    duration,
                                    "habituation",
                                    habituation_file,
                                    log,
                                    startend="criterionmet")
                break

        if hab_i == 24:
            write_result_phase3(output,
                                subj,
                                start_time,
                                condition_p3,
                                str(hab_i + 2),
                                trial_on,
                                trial_off,
                                key,
                                duration,
                                "habituation",
                                habituation_file,
                                log + "_24_trial",
                                startend="24TRIAL")
        else:
            write_result_phase3(output,
                                subj,
                                start_time,
                                condition_p3,
                                str(hab_i + 2),
                                trial_on,
                                trial_off,
                                key,
                                duration,
                                "habituation",
                                habituation_file,
                                log,
                                startend="TRIALEND")

        hab_i += 1

        psypsyinterface.clear_screen(screen, background_black)

    # Test trial =======================================================================
    trial, header_index = psypsyio.read_stimuli(stimuli_file, "\t")
    print(trial, header_index)

    index = 0
    for i in range(trial["trial_number"]):
        screen.fill(background_gray)
        pygame.display.flip()
        # Attention-getter ==================================
        # loop video until there's a key press
        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()

        write_result_phase3(output,
                            subj,
                            start_time,
                            condition_p3,
                            str(i + hab_i + 3),
                            trial_on,
                            trial_off,
                            "gaze on",
                            duration,
                            "attention-getter",
                            "attention.mov",
                            "NA",
                            startend="attentionSTART")
        loop = psypsyvideo.play_video_loop(attention_getter, screen, tk, -1)
        check_exit(loop)
        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        write_result_phase3(output,
                            subj,
                            start_time,
                            condition_p3,
                            str(i + hab_i + 3),
                            trial_on,
                            trial_off,
                            "gaze on",
                            duration,
                            "attention-getter",
                            "attention.mov",
                            "NA",
                            startend="attentionEND")

        psypsyinterface.clear_screen(screen, background_black)

        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()
        # replace file name to correspond to conditions
        trial_video_file = trial[condition_p3][i]
        print("file: ", trial_video_file)
        if skip_to_3:
            trial_video_file = trial_video_file
            #trial_video_file = re.sub(r"u", "a", trial_video_file) kk
            #trial_video_file = re.sub(r"y", "i", trial_video_file) kk

        #video_file = hab_video_path + "test-" + trial_video_file + "_trial" + ".mp4" kk
        video_file = hab_video_path + trial_video_file + ".mov"
        print(video_file)
        video_file = VideoFileClip(video_file)
        tagEvent("TRIALSTART", i, trial_on, trial_off, "end", "test",
                 str(video_file))
        # Each trial ends when the sound file finishes, or when there's a key press
        # test_video = VideoFileClip(video_file)
        key = psypsyvideo.play_video_2s(video_file, screen, tk)
        check_exit(key)
        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        write_result_phase3(output,
                            subj,
                            start_time,
                            condition_p3,
                            str(i + hab_i + 3),
                            trial_on,
                            trial_off,
                            key,
                            duration,
                            "test",
                            trial_video_file,
                            "NA",
                            startend="TRIALEND")

        index = i + hab_i + 4

    psypsyinterface.clear_screen(screen, background_black)
    pygame.quit()
Exemple #3
0
def av_matching_1(subj, condition_p1, path, screen):
    start_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')  # get current date time
    # Path to files =================================================================================
    # path to experiment materials
    phase1_path = path["path"] + path["phase1"] + "infants/"

    # path to video files
    video_path = phase1_path
    # path to sound files
    sound_path = phase1_path

    # path to attention-getter
    video_attention_getter = phase1_path + "attention.mov"

    # Visual exposure
    trial3_visual = phase1_path + "bullseye.png"

    # fa file
    video_fa_list = ["FAH_34.mov", "FAH_40.mov", "FAH_60.mov", "FAH_98.mov"]
    video_fa = random.choice(video_fa_list)
    sound_fa = "fa_trial.wav"
    # tha file
    video_tha_list = ["THA_202.mov", "THA_206.mov", "THA_208.mov", "THA_214.mov"]
    video_tha = random.choice(video_tha_list)
    sound_tha = "tha_trial.wav"

    # output
    output = "./results/exp1_p1_results.csv"

    # Check condition ===============================================================================
    if condition_p1 == "fL-fE":
        left_video = video_path + video_fa
        right_video = video_path + video_tha
        sound_file = sound_path + sound_fa
        left = "fa"
        right = "tha"
        soundplay = "fa"
    elif condition_p1 == "fR-fE":
        left_video = video_path + video_tha
        right_video = video_path + video_fa
        sound_file = sound_path + sound_fa
        left = "tha"
        right = "fa"
        soundplay = "fa"
    elif condition_p1 == "fL-tE":
        left_video = video_path + video_fa
        right_video = video_path + video_tha
        sound_file = sound_path + sound_tha
        left = "fa"
        right = "tha"
        soundplay = "tha"
    elif condition_p1 == "fR-tE":
        left_video = video_path + video_tha
        right_video = video_path + video_fa
        sound_file = sound_path + sound_tha
        left = "tha"
        right = "fa"
        soundplay = "tha"
    else:
        raise ValueError('something is wrong in condition')

    # Background ====================================================================================
    background_black = (0, 0, 0)
    background_white = (255, 255, 255)
    # background_gray = (211, 211, 211)  # light gray
    psypsyinterface.clear_screen(screen, background_black)

    # Start experiment =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    write_result_phase1(output, subj, start_time, condition_p1, "1", trial_time, "attention-getter",
                        "NA", "NA", "NA")
    psypsyinterface.clear_screen(screen, background_black)

    # Trial 1: Baseline Trial =======================================================================
    # No sound ======================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyvideo.play_two_videos_loop(left_video, right_video, screen, duration=21000, audio=False)

    write_result_phase1(output, subj, start_time, condition_p1, "1", trial_time, "baseline",
                        left, right, "NA")
    psypsyinterface.clear_screen(screen, background_black)

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    write_result_phase1(output, subj, start_time, condition_p1, "2", trial_time, "attention-getter",
                        "NA", "NA", "NA")
    psypsyinterface.clear_screen(screen, background_black)

    # Trial 2: Baseline Trial  ======================================================================
    # swap videos ===================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyvideo.play_two_videos_loop(right_video, left_video, screen, duration=21000, audio=False)

    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "2", trial_time, "baseline",
                        right, left, "NA")

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    psypsyinterface.clear_screen(screen, background_white)
    write_result_phase1(output, subj, start_time, condition_p1, "3", trial_time, "attention-getter",
                        "NA", "NA", "NA")

    # Trial 3: auditory exposure trial ==============================================================
    # ===============================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyinterface.display_original_image(trial3_visual, screen, screen_width, screen_height)
    # presentation of sound file
    sound = pygame.mixer.Sound(sound_file)
    sound.play()
    while pygame.mixer.get_busy():  # sound playing
        continue

    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "3", trial_time, "exposure",
                        left, right, "NA")

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    psypsyinterface.clear_screen(screen, background_white)
    write_result_phase1(output, subj, start_time, condition_p1, "4", trial_time, "attention-getter",
                        "NA", "NA", "NA")

    # Trial 4: repeat trial 3 =======================================================================
    # ===============================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyinterface.display_original_image(trial3_visual, screen, screen_width, screen_height)
    # presentation of sound file
    sound = pygame.mixer.Sound(sound_file)
    sound.play()
    while pygame.mixer.get_busy():  # sound playing
        continue

    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "4", trial_time, "exposure",
                        "NA", "NA", soundplay)

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "5", trial_time, "attention-getter",
                        "NA", "NA", "NA")

    # Trial 5 intersensory matching test trial ======================================================
    # ===============================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyvideo.play_two_videos_loop(left_video, right_video, screen, duration=45000, audio=False)

    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "5", trial_time, "matching",
                        left, right, "NA")

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    psypsyinterface.clear_screen(screen, background_white)
    write_result_phase1(output, subj, start_time, condition_p1, "6", trial_time, "attention-getter",
                        "NA", "NA", "NA")

    # Trial 6 auditory exposure trial ===============================================================
    # ===============================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyinterface.display_original_image(trial3_visual, screen, screen_width, screen_height)
    sound = pygame.mixer.Sound(sound_file)
    sound.play()
    while pygame.mixer.get_busy():  # sound playing
        continue

    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "6", trial_time, "exposure",
                        "NA", "NA", soundplay)

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    psypsyinterface.clear_screen(screen, background_white)
    write_result_phase1(output, subj, start_time, condition_p1, "7", trial_time, "attention-getter",
                        "NA", "NA", "NA")

    # Trial 7 repeat trial 6 ========================================================================
    # ===============================================================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyinterface.display_original_image(trial3_visual, screen, screen_width, screen_height)
    sound = pygame.mixer.Sound(sound_file)
    sound.play()
    while pygame.mixer.get_busy():  # sound playing
        continue

    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "7", trial_time, "exposure",
                        "NA", "NA", soundplay)

    # attention-getter ========================================
    # Loop attention.mov until there's a key press [SPACE]
    clip = VideoFileClip(video_attention_getter)
    psypsyvideo.play_video(clip, screen)
    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "8", trial_time, "attention-getter",
                        "NA", "NA", "NA")

    # Trial 8 Intersensory matching =================================================================
    # Same as trial 5 but video swapped =============================================================
    trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    psypsyvideo.play_two_videos_loop(right_video, left_video, screen, duration=45000, audio=False)
    psypsyinterface.clear_screen(screen, background_black)
    write_result_phase1(output, subj, start_time, condition_p1, "8", trial_time, "matching",
                        right, left, "NA")
Exemple #4
0
def exp3_av_matching(participant_id):
    exp_start = datetime.datetime.now().strftime(
        '%Y-%m-%d-%H:%M:%S')  # get current date time

    background_white = (255, 255, 255)  # white
    background_black = (0, 0, 0)  # black
    # Initialisation Pygame
    screen, screen_width, screen_height = psypsyinterface.initialisation_pygame_mouse(
        background_white)
    psypsyinterface.clear_screen(screen, background_white)

    path = {
        "path": "Exp_3_av_matching/",
        "instructions": "instructions/",
        "visual": "visual/",
        "adults": "adults/"
    }

    # Instructions =*=*=*=*=*=*=*=*=*=*=*=*=*=*
    instructions = [
        "instructions1.wav", "instructions2.wav", "instructions3.wav",
        "instructions4.wav", "instructions5.wav"
    ]
    instruction_path = path["path"] + path["instructions"]

    # visual =*=*=*=*=*=*=*=*=*=*=*=*=*=*
    visual_path = path["path"] + path["visual"]
    ear_file = visual_path + "ear.png"
    eye_file = visual_path + "eye.png"
    finger_file = visual_path + "finger.png"
    box_file = visual_path + "box.png"

    # Video  =*=*=*=*=*=*=*=*=*=*=*=*=*=*
    video_path = path["path"] + path["adults"]
    left_video = video_path + "BAH_44.mov"
    right_video = video_path + "VAH_24.mov"

    # Audio
    ba_sound = video_path + "BAH_44.wav"

    # Repetition constraints for trials
    constraints = {3: 2}

    # Stimuli input file
    stimuli_file = "exp3_trial.csv"

    # Result file ==============================================================================
    result_file = "results/exp3_results.csv"

    # Load Images & calculate size
    ear = pygame.image.load(ear_file)
    eye = pygame.image.load(eye_file)
    finger = pygame.image.load(finger_file)
    box = pygame.image.load(box_file)

    ear_size = ear.get_rect().size
    eye_size = eye.get_rect().size
    finger_size = finger.get_rect().size
    box_size = box.get_rect().size

    # Play instructions1.wav (says there are 3 phases) ================================================
    instruction1 = instruction_path + instructions[0]
    instruction1_sound = pygame.mixer.Sound(instruction1)
    instruction1_sound.play()  # play instruction
    while pygame.mixer.get_busy():  # Instruction playing
        continue
    psypsyinterface.wait_for_click()
    psypsyinterface.clear_screen(screen, background_white)

    # Make ear appear and play instructions2.wav (it will explain the procedure for the listening phase)
    psypsyinterface.display_original_image(ear_file, screen, screen_width,
                                           screen_height)
    instruction2 = instruction_path + instructions[1]
    instruction2_sound = pygame.mixer.Sound(instruction2)
    instruction2_sound.play()  # play instruction
    while pygame.mixer.get_busy():  # Instruction playing
        continue
    psypsyinterface.wait_for_click()
    psypsyinterface.clear_screen(screen, background_white)

    # Make eye appear and play instructions3.wav (same for viewing phase) ==============================
    psypsyinterface.display_original_image(eye_file, screen, screen_width,
                                           screen_height)
    instruction3 = instruction_path + instructions[2]
    instruction3_sound = pygame.mixer.Sound(instruction3)
    instruction3_sound.play()  # play instruction
    while pygame.mixer.get_busy():  # Instruction playing
        continue
    psypsyinterface.wait_for_click()
    psypsyinterface.clear_screen(screen, background_white)

    # Show the arrow and play instructions4.wav (same for choice) ======================================
    psypsyinterface.display_original_image(finger_file, screen, screen_width,
                                           screen_height)
    instruction4 = instruction_path + instructions[3]
    instruction4_sound = pygame.mixer.Sound(instruction4)
    instruction4_sound.play()  # play instruction
    while pygame.mixer.get_busy():  # Instruction playing
        continue
    psypsyinterface.wait_for_click()
    psypsyinterface.clear_screen(screen, background_white)

    # One trial for practice with ba-by ================================================================
    trial_start = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    # Audio-only
    ear_resize = pygame.transform.scale(
        ear, (int(screen_width * 0.3),
              int(screen_width * 0.3 / ear_size[0] * ear_size[1])))
    ear_position = (int((screen_width - (screen_width * 0.3)) / 2), 0)
    screen.blit(ear_resize, ear_position)
    pygame.display.flip()
    pygame.event.pump()
    pygame.event.clear()
    bah = pygame.mixer.Sound(ba_sound)
    for j in range(2):  # play twice ba sound
        bah.play()  # play sound
        while pygame.mixer.get_busy():  # sound playing
            continue
        pygame.time.wait(500)

    psypsyinterface.clear_screen(screen, background_white)
    # Video-only
    eye_resize = pygame.transform.scale(
        eye, (int(screen_width * 0.3),
              int(screen_width * 0.3 / eye_size[0] * eye_size[1])))
    eye_position = (int((screen_width - (screen_width * 0.3)) / 2), 0)
    screen.blit(eye_resize, eye_position)
    left_video_clip = VideoFileClip(left_video)
    right_video_clip = VideoFileClip(right_video)
    time_video_on = pygame.time.get_ticks()
    psypsyvideo.play_two_videos_audio(left_video_clip, right_video_clip,
                                      "left", screen)

    # Show black screen with two boxes where the videos were & the finger
    psypsyinterface.clear_screen(screen, background_white)

    # Response: visual
    box_resize = pygame.transform.scale(
        box, (int(screen_width * 0.3),
              int(screen_width * 0.3 / box_size[0] * box_size[1])))
    box_size_2 = box_resize.get_rect().size
    box_left_position = (0, int((screen_height - box_size_2[1]) / 2))
    box_right_position = (int(screen_width - box_size_2[0]),
                          int((screen_height - box_size_2[1]) / 2))
    position_box_left = screen.blit(box_resize, box_left_position)
    position_box_right = screen.blit(box_resize, box_right_position)

    finger_resize = pygame.transform.scale(
        finger, (int(screen_width * 0.1),
                 int(screen_width * 0.1 / finger_size[0] * finger_size[1])))
    finger_position = (int((screen_width - (screen_width * 0.1)) / 2), 0)
    screen.blit(finger_resize, finger_position)
    pygame.display.flip()
    pygame.event.pump()
    pygame.event.clear()

    response = False
    while not response:
        for e in pygame.event.get():
            if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
                raise Exception
            elif e.type == MOUSEBUTTONDOWN:
                # set x, y positions of the mouse click
                x, y = e.pos
                if position_box_left.collidepoint(x, y):
                    # print("click on a")
                    response_time = [pygame.time.get_ticks()]
                    response_type = ["left"]
                    response = True
                elif position_box_right.collidepoint(x, y):
                    # print("click on b")
                    response_time = [pygame.time.get_ticks()]
                    # absolute_response_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
                    response_type = ["right"]
                    response = True

    off = response_time[0]
    rt = off - time_video_on
    response_side = response_type[0]

    if response_side == "left":
        correct = "1"
    else:
        correct = "0"

    write_result_exp3(result_file, str(participant_id), exp_start, "0", "N",
                      "left", "BAH_44.mov", trial_start, str(time_video_on),
                      str(off), str(rt), response_side, correct)
    # Wait for click to advance, log response
    psypsyinterface.wait_for_click()
    psypsyinterface.clear_screen(screen, background_white)

    # Play instructions5.wav ===========================================================================
    # (it will ask the participant to tell the experimenter if they have any questions)
    instruction5 = instruction_path + instructions[4]
    instruction5_sound = pygame.mixer.Sound(instruction5)
    instruction5_sound.play()  # play instruction
    while pygame.mixer.get_busy():  # Instruction playing
        continue
    # Continue with a click anywhere on the scree
    psypsyinterface.wait_for_click()

    # Test trials
    # randomisation
    psypsyaxb.randomisation_one_part(stimuli_file, "results/exp3/",
                                     "test_trial", participant_id, constraints)
    trial_file = "results/exp3/test_trial_" + str(participant_id) + ".csv"
    trial, header_index = psypsyio.read_stimuli(trial_file, "\t")
    for i in range(trial["trial_number"]):
        psypsyinterface.clear_screen(screen, background_black)
        trial_start = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        psypsyinterface.clear_screen(screen, background_white)
        # Audio-only trial ===================================
        screen.blit(ear_resize, ear_position)
        pygame.display.flip()
        pygame.event.pump()
        pygame.event.clear()
        target_sound = pygame.mixer.Sound(video_path +
                                          trial["target_audio"][i])
        for j in range(2):  # play twice ba sound
            target_sound.play()  # play sound
            while pygame.mixer.get_busy():  # sound playing
                continue
            pygame.time.wait(500)

        # Video-only trial ====================================
        psypsyinterface.clear_screen(screen, background_white)
        screen.blit(eye_resize, eye_position)

        left_video = video_path + trial["left"][i]
        right_video = video_path + trial["right"][i]
        left_video_clip = VideoFileClip(left_video)
        right_video_clip = VideoFileClip(right_video)
        audioside = trial["target_side"][i]
        time_video_on = pygame.time.get_ticks()
        psypsyvideo.play_two_videos_audio(left_video_clip, right_video_clip,
                                          audioside, screen)
        psypsyinterface.clear_screen(screen, background_white)

        position_box_left = screen.blit(box_resize, box_left_position)
        position_box_right = screen.blit(box_resize, box_right_position)
        screen.blit(finger_resize, finger_position)
        pygame.display.flip()
        pygame.event.pump()
        pygame.event.clear()

        time_video_off = pygame.time.get_ticks()

        response = False
        while not response:
            for e in pygame.event.get():
                if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
                    raise Exception
                elif e.type == MOUSEBUTTONDOWN:
                    # set x, y positions of the mouse click
                    x, y = e.pos
                    if position_box_left.collidepoint(x, y):
                        # print("click on a")
                        response_time = [pygame.time.get_ticks()]
                        response_type = ["left"]
                        response = True
                    elif position_box_right.collidepoint(x, y):
                        # print("click on b")
                        response_time = [pygame.time.get_ticks()]
                        response_type = ["right"]
                        response = True
        off = response_time[0]
        rt = off - time_video_on
        response_side = response_type[0]

        if response_side == trial["target_side"][i]:
            correct = "1"
        else:
            correct = "0"

        write_result_exp3(result_file, str(participant_id), exp_start,
                          str(i + 1), trial["contrasts"][i],
                          trial["target_side"][i],
                          trial["target_video"][i], trial_start,
                          str(time_video_on), str(off), str(rt), response_side,
                          correct)

        psypsyinterface.clear_screen(screen, background_black)
Exemple #5
0
def mispronunciation_2(subj, condition_p2, path, screen, screen_width, screen_height):
    start_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')  # get current date time

    # Path to files =================================================================================
    # path to experiment materials
    phase2_path = path["path"] + path["phase2"]

    # path to attention-getter
    attention_path = phase2_path + "attention-getters/"
    attention_videos = ["attention1.mov", "attention2.mov", "attention3.mov"]

    # Image Path
    image_path = phase2_path + "visual/"

    # Stimuli Path
    original_stimuli_file = "exp1_p2_stimuli.csv"

    # output
    output = "./results/exp1_p2_results.csv"

    # randomize stimuli list
    # repetition constraint
    constraints = {0: 0}

    # stimuli file destination
    result_file_path = "results/phase2/input/"
    psypsyaxb.randomisation_one_part(original_stimuli_file, result_file_path, "mispronunciation", subj, constraints)
    randomized_stimuli_file = result_file_path + "mispronunciation" + "_" + subj + ".csv"

    # Background ====================================================================================
    background_black = (0, 0, 0)
    background_white = (255, 255, 255)
    background_gray = (211, 211, 211)  # light gray
    psypsyinterface.clear_screen(screen, background_black)

    # Trial stimuli (shuffled)
    trial, header_index = psypsyio.read_stimuli(randomized_stimuli_file, "\t")

    # for i in range(2):
    for i in range(trial["trial_number"]):
        # Show an attention-getter movies chosen at random
        psypsyinterface.clear_screen(screen, background_black)
        attention_getter = random.choice(attention_videos)
        video_file = attention_path + attention_getter
        # play attention-getter video ===================================================================
        clip = VideoFileClip(video_file)
        psypsyvideo.play_video(clip, screen)
        psypsyinterface.clear_screen(screen, background_gray)

        # load image files
        image_target_obj = pygame.image.load(image_path + trial["target"][i] + ".png")
        image_competitor_obj = pygame.image.load(image_path + trial["competitor"][i] + ".png")

        if condition_p2 == "A":
            left_image = image_target_obj
            right_image = image_competitor_obj
            left = trial["target"][i]
            right = trial["competitor"][i]
        elif condition_p2 == "B":
            left_image = image_competitor_obj
            right_image = image_target_obj
            left = trial["competitor"][i]
            right = trial["target"][i]
        else:
            raise ValueError('something is wrong in condition')

        # resize image files
        left_size = left_image.get_rect().size
        right_size = right_image.get_rect().size

        # Calculate and rescale image to fit the screen
        # 40% empty space at the center, images occupy 30% left and right
        screen_30_percent = int(screen_width / 10 * 3)
        resize_left_height = int(screen_30_percent / left_size[0] * left_size[1])
        resize_right_height = int(screen_30_percent / right_size[0] * right_size[1])

        # rescale images
        image_left = pygame.transform.scale(left_image, (screen_30_percent, resize_left_height))
        image_right = pygame.transform.scale(right_image, (screen_30_percent, resize_right_height))

        # Display images
        trial_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        screen.blit(image_left, (0, int((screen_height - resize_left_height) / 2)))
        screen.blit(image_right, (int(screen_width / 10 * 7), int((screen_height - resize_right_height) / 2)))
        pygame.display.flip()
        pygame.event.pump()
        pygame.event.clear()

        # 2s of silence
        pygame.time.wait(2000)

        # Play sound
        # Replace this line
        sound_file = trial["target"][i] + "_" + trial["extension"][i]
        sound_path = phase2_path + "wavs/" + sound_file + ".wav"
        # sound_file = trial["target"][i]
        # sound_path = phase2_path + "wavs/" + sound_file + ".wav"
        sound = pygame.mixer.Sound(sound_path)
        sound_time = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        sound.play()
        while pygame.mixer.get_busy():  # sound playing
            continue

        # Wait for 2.5s
        pygame.time.wait(2500)

        psypsyinterface.clear_screen(screen, background_gray)
        write_result_phase2(output, subj, start_time, condition_p2, str(i+1), trial_time, sound_time,
                            trial["trial_id"][i], attention_getter, left, right, sound_file)

    # End of Trial ==============================================================

    # Show red screen with message
    screen.fill((255, 0, 0))
    psypsyinterface.display_text(screen, "Move computer", font_size=90)

    # Wait for key press
    psypsyinterface.wait_for_space()
Exemple #6
0
def abx(screen, background, expedir, input_file, result_file, instructions, isi=1000, fixation_duration=500, interTrial=1000, train=False):
	try:
	# Get trials from input_file
	# stimuli are organised in a python dictionary: trial[field][i]  
		trial, header_index = psypsyio.read_stimuli(input_file, "\t")
		nb_trials = int(trial["trial_number"])
		pause_1 = int(nb_trials / 4 -1) 
		pause_2 = int(nb_trials / 4 * 2 -1) 
		pause_3 = int(nb_trials / 4 * 3 -1) 
		# print(trial["trial_number"])

		# Create result file
		result = open(result_file, "w")

		# Add header to result output file
		psypsyio.write_result_header(result, trial, abx_result_columns)

		# Initialize counts for feedback
		nb_trials = nb_correct = nb_wrong = nb_missed = 0
		correct_rt = wrong_rt = 0

		for i in range(trial["trial_number"]):
			screen.fill(background)
			pygame.display.flip()

			# Pauses (test phase): halfway, 1 break
			if not train:
				if i == pause_1 or i == pause_2 or i == pause_3:
					psypsyaxb.axb_pause(screen, screen_width, screen_height, background, instructions.get("pause"))

			# Processing sound stimuli =*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*
			if train:
				path = "stimuli/training/"
			else:
				path = "stimuli/test/"

			# Get stimuli path
			stimulus_a = path + trial["A"][i] 
			stimulus_x = path + trial["X"][i] 
			stimulus_b = path + trial["B"][i] 
			sound_path = [stimulus_a, stimulus_b, stimulus_x]

			# Load stimuli & Compute sound stimuli duration, get offset
			mixed_sounds, duration_sounds = psypsyinterface.mix_sound_stimuli(sound_path)
			# offset = int(trial["offset"][i])
#			print(stimulus_a, stimulus_x, stimulus_b, offset)

			# Compute target result
			if trial["X"][i][:-2] == trial["A"][i][:-2]:
				# compare two strings of A and X if identical then A else B
				target_response = "A"
			else:
				target_response = "B"

			# Prepare output line
			trial_result = []
			for key in header_index:
				trial_result.append(trial[header_index[key]][i])

			# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
			# Play sounds and record response						   *
			# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
			# Display fixation point
			psypsyinterface.point_fixation(screen, fixation_duration)
			# 500ms of display
			psypsyinterface.clear_screen(screen, background)

			# Play A ==============
			start_sound_a = pygame.time.get_ticks()
			mixed_sounds[0].play()	# PLAY SOUND A
			while pygame.mixer.get_busy():	# sound playing
				continue
			end_sound_a = pygame.time.get_ticks()

			while pygame.time.get_ticks() - end_sound_a < isi:
				continue
			pygame.event.pump()
			pygame.event.clear()  # clear event and wait for response

			# Play X and B and record response (Type, Time) =============
			xb_sequence = [mixed_sounds[1], mixed_sounds[2]]
			xb_measures = []
			response = False
			response_type = []
			response_time = []

			# indication for X and B
			# index_b == 0: ISI after X
			# index_b == 1: ISI after B
			index_b = 0

			for s in xb_sequence:
				# get start point of the sound
				duration = int(round(pygame.mixer.Sound.get_length(s), 3) * 1000)
				start_sound = pygame.time.get_ticks()
				xb_measures.append(start_sound)
				s.play()  # play sound

				# index_b == 1: 2000ms after sound X
				if index_b == 1:
					isi_post = 2000
				else:
					# index_b == 0: 1000ms after sound B
					isi_post = 1000

				# while pygame.mixer.get_busy() and not response or (
				# 		pygame.time.get_ticks() - start_sound <= duration + isi_post):
				while pygame.mixer.get_busy() and not response or (index_b == 0 and
						pygame.time.get_ticks() - start_sound <= duration + isi_post) or (index_b == 1 and not response):
					for e in pygame.event.get():
						if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
							raise Exception("aborted")
						elif e.type == KEYDOWN:
							if e.key == K_LEFT:
								response_time = [pygame.time.get_ticks()]
								response_type = ["A"]
								response = True
							elif e.key == K_RIGHT:
								response_time = [pygame.time.get_ticks()]
								response_type = ["B"]
								response = True
						else:
							response = False

				# Get end point of the sound
				if index_b == 1:
					xb_measures.append(pygame.time.get_ticks() - 2*isi)
				elif index_b == 0:
					xb_measures.append(pygame.time.get_ticks() - isi)

				index_b += 1

			# Get measures
			start_sound_x = xb_measures[0]
			end_sound_x = xb_measures[1]
			start_sound_b = xb_measures[2]
			end_sound_b = xb_measures[3]

			# Handle empty response
			# response time =*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*
			if response_time != []:
				response_time_s = response_time[0]
				real_rt = response_time_s - start_sound_b 
			else:
				response_time_s = 0
				real_rt = 0
			# response type =*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*
			if response_type != []:
				response_type_s = response_type[0]
			else:
				response_type_s = "NA"

			# Compute the correctness of response
			# And display feedback for training
			nb_trials += 1

			if response_type_s == target_response:
				correct = "T"
				nb_correct += 1
				correct_rt += real_rt
				if train:
					psypsyinterface.display_text_colour(screen, "O", font_size=600, colour=(0, 255, 0))
					pygame.time.wait(500)
					psypsyinterface.clear_screen(screen, background)
			elif response_type_s == "NA":
				correct = "F"
				nb_missed += 1
				if train:
					psypsyinterface.display_text_colour(screen, "???", font_size=400)
					pygame.time.wait(500)
					psypsyinterface.clear_screen(screen, background)
			else:
				correct = "F"
				# Calculate wrong response number and mean(rt)
				nb_wrong += 1
				wrong_rt += real_rt
				if train:
					for click in range(3):
						psypsyinterface.display_text_colour(screen, "X", font_size=600)
						pygame.time.wait(100)
						psypsyinterface.clear_screen(screen, background)
						pygame.time.wait(50)

			# Append trial measures
			trial_result.extend([start_sound_a, duration_sounds[0], end_sound_a,
								 start_sound_b, duration_sounds[1], end_sound_b,
								 start_sound_x, duration_sounds[2], end_sound_x,
								 response_time_s, target_response, response_type_s, real_rt, correct])

			# Output results
			psypsyio.write_result_line(result, trial_result)

			# inter-trial time
			pygame.time.wait(interTrial)

		# Avoid division by zero for averaged RTs
		if nb_correct == 0:
			ave_crt = 0
		else:
			ave_crt = int(correct_rt / nb_correct)
		if nb_wrong == 0:
			ave_wrt = 0
		else:
			ave_wrt = int(wrong_rt / nb_wrong)

		resume = {"nb_trials": nb_trials,
				  "nb_correct": nb_correct,
				  "nb_wrong": nb_wrong,
				  "nb_missed": nb_missed,
				  "ave_crt": ave_crt,
				  "ave_wrt": ave_wrt}

		result.close()

	finally:
		resume = None

		if not train:
#			print("End experiment\n")
			pygame.time.wait(1000)
		else:
	# 		summary = "nb ok: " + str(resume["nb_correct"]) + "/" \
 # + str(resume["nb_trials"]) + ", ok RT: " + str(int(resume["ave_crt"])) \
 # + " ==> Space to continue"
			# psypsyinterface.display_text(screen, summary)
			psypsyinterface.wait_for_space()
			psypsyinterface.clear_screen(screen, background)
#			print("End training\n")

	return resume
Exemple #7
0
def habituation_3(subj, condition_p3, skip_to_3, path, screen, screen_width,
                  screen_height):
    start_time = datetime.datetime.now().strftime(
        '%Y-%m-%d-%H:%M:%S')  # get current date time
    background_black = (0, 0, 0)  # black
    background_white = (255, 255, 255)  # white
    psypsyinterface.clear_screen(screen, background_black)
    # Path to files ==========================================================
    # path to experiment materials
    phase3_path = path["path"] + path["phase3"]

    # Video Path
    video_path = phase3_path + "final_media/"

    attention_video = "attention.mov"
    pretest_video = "pretest.mov"

    attention_getter = video_path + attention_video
    pretest = video_path + pretest_video
    posttest_video = video_path + "pretest.mov"

    hab_video_path = phase3_path + "hab_test/"

    # Stimuli Path
    stimuli_file = "exp1_p3_test_trial.csv"

    # output
    output = "./results/exp1_p3_results.csv"

    # Check experiment condition ==============================================
    u = "u"
    y = "y"

    if skip_to_3:
        u = "a"
        y = "i"

    if condition_p3 == "u-c":
        habituation = u
    elif condition_p3 == "u-s":
        habituation = u
    elif condition_p3 == "y-c":
        habituation = y
    elif condition_p3 == "y-s":
        habituation = y
    else:
        raise ValueError('something is wrong in condition')

    # Start Experiment =======================================================
    # Attention-getter ==================================
    # loop video until there's a key press
    trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    trial_start = pygame.time.get_ticks()

    psypsyvideo.play_video_loop(attention_getter, screen, -1)

    trial_end = pygame.time.get_ticks()
    duration = trial_end - trial_start
    trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    write_result_phase3(output, subj, start_time, condition_p3, "1", trial_on,
                        trial_off, "keypress", duration, "attention-getter",
                        "attention.mov", "NA")

    psypsyinterface.clear_screen(screen, background_black)

    # pretest ===========================================
    # loop video until there's a key press
    trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    trial_start = pygame.time.get_ticks()

    # psypsyvideo.play_video_loop(pretest, screen, -1)
    prestest_video = VideoFileClip(pretest)
    key = psypsyvideo.play_video_2s(prestest_video, screen)

    trial_end = pygame.time.get_ticks()
    duration = trial_end - trial_start
    trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    write_result_phase3(output, subj, start_time, condition_p3, "2", trial_on,
                        trial_off, key, duration, "pretest", "prestest.mov",
                        "NA")

    psypsyinterface.clear_screen(screen, background_black)

    # Habituation section ====================================================
    # ========================================================================
    # # Attention-getter ==================================
    # # loop video until there's a key press
    # trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    # trial_start = pygame.time.get_ticks()
    #
    # attention = VideoFileClip(attention_getter)
    # stop = False
    # while not stop:
    #     stop = psypsyvideo.play_video(attention, screen)
    #
    # trial_end = pygame.time.get_ticks()
    # duration = trial_end - trial_start
    # trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    # write_result_phase3(output, subj, start_time, condition_p3, "3", trial_on, trial_off,
    #                     "keypress", duration, "attention-getter", "attention.mov", "NA")

    trial_duration_list = []
    hab_i = 1
    while hab_i < 25:  # reach 24 habituation trial

        # Attention-getter ==================================
        # loop video until there's a key press
        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()

        psypsyvideo.play_video_loop(attention_getter, screen, -1)

        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        write_result_phase3(output, subj, start_time, condition_p3,
                            str(hab_i + 2), trial_on, trial_off, "keypress",
                            duration, "attention-getter", "attention.mov",
                            "NA")

        psypsyinterface.clear_screen(screen, background_black)

        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()
        # Load habituation video depends on the condition
        habituation_file = "hab-" + habituation + "_trial.mp4"
        habituation_trial_video = hab_video_path + "hab-" + habituation + "_trial.mp4"
        clip_habituation = VideoFileClip(habituation_trial_video)

        # Habituation trial
        # Trial ends when the movie finishes, or when there's no key press for the last 2 seconds
        key = psypsyvideo.play_video_2s(clip_habituation, screen)

        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        log = "NA"

        trial_duration_list.append(duration)

        # Calculate average duration
        if len(trial_duration_list) > 3:
            order = trial_duration_list[:]
            ordered = sorted(order)
            average_duration_long = int(
                (ordered[-1] + ordered[-2] + ordered[-3]) / 3)
            last_three_duration = int(
                (trial_duration_list[-1] + trial_duration_list[-2] +
                 trial_duration_list[-3]) / 3)
            log = str(average_duration_long) + " / " + str(last_three_duration)
            if last_three_duration < (average_duration_long * 0.6):
                log = str(average_duration_long) + " / " + str(
                    last_three_duration) + "_criterion_met"
                write_result_phase3(output, subj, start_time, condition_p3,
                                    str(hab_i + 2), trial_on, trial_off, key,
                                    duration, "habituation", habituation_file,
                                    log)
                break

        if hab_i == 24:
            write_result_phase3(output, subj, start_time, condition_p3,
                                str(hab_i + 2), trial_on, trial_off, key,
                                duration, "habituation", habituation_file,
                                log + "_24_trial")
        else:
            write_result_phase3(output, subj, start_time, condition_p3,
                                str(hab_i + 2), trial_on, trial_off, key,
                                duration, "habituation", habituation_file, log)

        hab_i += 1

        psypsyinterface.clear_screen(screen, background_black)

    # Test section ===========================================================
    # ========================================================================
    # # attention getter
    # # loop video until there's a key press
    # trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    # trial_start = pygame.time.get_ticks()
    #
    # psypsyvideo.play_video_loop(attention_getter, screen, -1)
    #
    # trial_end = pygame.time.get_ticks()
    # duration = trial_end - trial_start
    # trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    #
    # write_result_phase3(output, subj, start_time, condition_p3, str(hab_i + 3), trial_on, trial_off,
    #                     "keypress", duration, "attention-getter", "attention.mov", "NA")
    #
    # psypsyinterface.clear_screen(screen, background_black)

    # Test trial =======================================================================
    trial, header_index = psypsyio.read_stimuli(stimuli_file, "\t")

    index = 0
    for i in range(trial["trial_number"]):
        screen.fill(background_black)
        pygame.display.flip()
        # Attention-getter ==================================
        # loop video until there's a key press
        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()

        psypsyvideo.play_video_loop(attention_getter, screen, -1)

        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

        write_result_phase3(output, subj, start_time, condition_p3,
                            str(i + hab_i + 3), trial_on, trial_off,
                            "keypress", duration, "attention-getter",
                            "attention.mov", "NA")

        psypsyinterface.clear_screen(screen, background_black)

        trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        trial_start = pygame.time.get_ticks()

        # replace file name to correspond to conditions
        trial_video_file = trial[condition_p3][i]
        if skip_to_3:
            trial_video_file = re.sub(r"u", "a", trial_video_file)
            trial_video_file = re.sub(r"y", "i", trial_video_file)

        video_file = hab_video_path + "test-" + trial_video_file + "_trial" + ".mp4"

        # Each trial ends when the sound file finishes, or when there's a key press
        test_video = VideoFileClip(video_file)
        key = psypsyvideo.play_video_2s(test_video, screen)

        trial_end = pygame.time.get_ticks()
        duration = trial_end - trial_start
        trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        write_result_phase3(output, subj, start_time, condition_p3,
                            str(i + hab_i + 3), trial_on, trial_off, key,
                            duration, "test", trial_video_file, "NA")

        index = i + hab_i + 4

        psypsyinterface.clear_screen(screen, background_black)

    # Loop attention-getter
    trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    trial_start = pygame.time.get_ticks()

    psypsyvideo.play_video_loop(attention_getter, screen, -1)

    trial_end = pygame.time.get_ticks()
    duration = trial_end - trial_start
    trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')

    write_result_phase3(output, subj, start_time, condition_p3, str(index),
                        trial_on, trial_off, "keypress", duration,
                        "attention-getter", "attention.mov", "NA")

    psypsyinterface.clear_screen(screen, background_black)

    # Loop video posttest.mov
    trial_on = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    trial_start = pygame.time.get_ticks()

    # psypsyvideo.play_video_loop(posttest_video, screen, -1)
    prestest_video = VideoFileClip(pretest)
    key = psypsyvideo.play_video_2s(prestest_video, screen)

    trial_end = pygame.time.get_ticks()
    duration = trial_end - trial_start
    trial_off = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    write_result_phase3(output, subj, start_time, condition_p3, str(index + 1),
                        trial_on, trial_off, key, duration, "posttest",
                        "pretest.mov", "NA")

    psypsyinterface.clear_screen(screen, background_black)
    pygame.quit()