Esempio n. 1
0
    def __init__(self, params):
        # 0. set up internal and external clocks
        self.internal_counter = core.MonotonicClock()

        for i in range(params['num_counter']):
            self.counter.append(core.MonotonicClock())
            self.resettime.append(self.counter[i].getTime())
            self.nCounter += 1

        # 1. reset both internal and external clocks
        self.reset_internal_counter()
        self.reset_all()
Esempio n. 2
0
def setup(session):
    """TODO: Docstring for runTask.

    :num_pieces: TODO
    :puzzle_start: TODO
    :puzzle_solution: TODO
    :auto_run: TODO
    :returns: TODO

    """
    session.clock = core.MonotonicClock()
    session.display = display.Display(session)
Esempio n. 3
0
    def __init__(self, win, radius=0.04, pos=(0.84, 0.44), **kwargs):
        self.win = win
        self.bitpattern = None
        self.counter = None
        self.timer = core.MonotonicClock()

        kwargs['radius'] = radius
        kwargs['pos'] = pos

        # we want to override these
        kwargs['fillColorSpace'] = 'rgb255'
        kwargs['lineColorSpace'] = 'rgb255'
        kwargs['lineColor'] = None
        kwargs['units'] = 'height'
        kwargs['autoDraw'] = True

        super(Flicker, self).__init__(win, **kwargs)
Esempio n. 4
0
    def show(self, is_odd):
        self.text.draw()
        self.window.flip()

        #  Create timer for individual stimulus
        stim_timer = core.MonotonicClock()

        if self.duration:
            core.wait(self.duration)
        elif self.keys:
            wait = WaitForKey(self.window, self.keys, self.word_key,
                              self.stim_type, self.probe_details)

            return wait.show(self, is_odd, stim_timer)

        self.window.flip()
        return self
Esempio n. 5
0
    def playAll(self, is_odd, verbose=False):
        """Plays all the stimuli in the sequence.

        Args:
            verbose: bool if show stimuli details

        """
        stim_index = 0

        #  Initialize clock for total experiment runtime
        global experiment_timer
        experiment_timer = core.MonotonicClock()
        while self.escape_key not in event.getKeys():
            stim_index += 1

            if verbose:
                "Playing stimulus {stim_index}".format(stim_index=stim_index)

            self.playNext(is_odd)

        core.quit()
Esempio n. 6
0
    def run(self, exp_win, ctl_win):
        # needs to be the 1rst callbacks
        exp_win.timeOnFlip(self, '_exp_win_first_flip_time')
        self._flip_all_windows(exp_win, ctl_win, True)
        #sync to first screen flip
        self.task_timer = core.MonotonicClock(self._exp_win_first_flip_time)

        if self.progress_bar:
            self.progress_bar.reset()
        flip_idx = 0

        for clearBuffer in self._run(exp_win, ctl_win):
            # yield first to allow external draw before flip
            yield
            self._flip_all_windows(exp_win, ctl_win, clearBuffer)
            # increment the progress bar depending on task flip rate
            if self.progress_bar:
                if self._progress_bar_refresh_rate and flip_idx % self._progress_bar_refresh_rate == 0:
                    self.progress_bar.update(1)
            flip_idx += 1
        self._task_completed = True
Esempio n. 7
0
    def run_trial(self):
        #start time counter for the trial
        self.time = core.MonotonicClock()

        #------------------------------------
        #for every first trial of a block make an announcement
        if self.anounce:
            self.present_anouncement()
#------------------------------------
#slide for baseline time
#get time of baseline slide
        self.t_baseline = self.time.getTime()
        #present baseline slide
        self.present_baseline()
        #get time of end of trial
        self.t_end = self.time.getTime()
        #------------------------------------
        #get time of presentation of task slide from time counter
        self.t_stimuli = self.time.getTime()
        #present stimulus slide for time self.time_stimulus
        self.present_stimuli()
        #------------------------------------
        #get time for presentation of delay slide
        self.t_delay_1 = self.time.getTime()
        #first delay slide
        self.present_delay_1()
        #------------------------------------
        #show choice options and rewards
        self.t_options = self.time.getTime()
        self.present_options()
        #------------------------------------
        #second delay slide
        self.t_delay_2 = self.time.getTime()
        self.present_delay_2()
        #------------------------------------
        #response slide shows motor markers and records user input.
        #get start time
        self.t_response = self.time.getTime()
        #present slide
        self.present_response()
def run_experiment():
    #  Get participant ID
    exp_info = {"participant": "", "session:": "001"}
    dlg = gui.DlgFromDict(exp_info, sortKeys=False,
                          title=st.settings["exp_name"])

    #  Save participant ID
    st.settings["participant"] = exp_info["participant"]

    if dlg.OK == False:
        core.quit()

    #  Check if participant ID is odd
    is_odd = True if int(exp_info["participant"]) % 2 != 0 else False

    #  Initialize experiment paradigm
    st.construct_par(is_odd)
    if st.par:
        #  Start clock for total experiment runtime
        experiment_timer = core.MonotonicClock()
        st.par.playAll(is_odd)
        elapsed = experiment_timer.getTime()
Esempio n. 9
0
    def start_experiment(self):
        """ Display a reward location and start timer"""
        while self._currenttrial < self.numtrials:
            print('Trial %d beginning...' % self._currenttrial)
            currentreward = np.random.choice(len(self.rewardlocation), 1)
            currentrewardlocation = self.rewardlocation.iloc[currentreward]

            # Start trial - show reward
            print('Go to reward location (%d, %d)' %
                  (currentrewardlocation['x'], currentrewardlocation['y']))
            self.plotrewardlocation(currentrewardlocation)

            # Set up plot for realtime plotting
            cv2.namedWindow('Trial %d Reward' % self._currenttrial,
                            cv2.WINDOW_NORMAL)
            cv2.resizeWindow('Trial %d Reward' % self._currenttrial, 600, 600)

            # Get initial location of robot
            loc_x, loc_y = self.get_random_xy_loc(currentrewardlocation)

            # Start timer for reward timeout
            timer = core.CountdownTimer(self.rewardtimeout)
            abstime = core.MonotonicClock()

            while timer.getTime() > 0:
                # Print elapsed time on map and console
                # Change location for testing purposes
                loc_x += 1
                loc_y += 1
                elapsedtime = abstime.getTime()
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime,
                                          robotloc=(loc_x, loc_y))
                print "\033[K Elapsed Time : ", elapsedtime, "\r",
                sys.stdout.flush()

            print('\n Trial Ended')
            cv2.destroyAllWindows()
            self.updatetrial()  # Trial ended - start of next trial
Esempio n. 10
0
def main():
    # Store info about the experiment session
    participant_no = raw_input('Participant Number:')
    session_no = raw_input('Session Number:')
    raw_input('Press enter when you are ready to start the task.')
    participant = IST_objects.Participant(participant_no, session_no)

    # set up logging information
    globalClock = core.MonotonicClock(
    )  # if this isn't provided the log times will reflect secs since python started
    trial_clock = core.Clock()
    sample_clock = core.Clock()
    logging.setDefaultClock(globalClock)

    # set up file creation
    filename = config.config.get(
        'log_location') + os.sep + '{}_{}_{}_IST_sampling'.format(
            participant.id, participant.session, data.getDateStr()) + '.csv'
    file_writer = open(filename, 'a')
    file_writer.write(
        'participant_id, session, trial_no, global_time_onset_trial, category_of_pics, probability, reward_type, '
        'majority_cat, final_choice, final_choice_time, num_of_samples, global_final_choice_time, '
        'total_trial_time, sample_no, picture_path, pic_name, dec_to_sample_time, global_picture_onset, '
        'image_judgement, time_of_judge, global_time_of_judge, \n')

    # set up display
    win = visual.Window(size=(1440, 900),
                        fullscr=True,
                        screen=0,
                        allowGUI=False,
                        allowStencil=False,
                        monitor='testMonitor',
                        color='black',
                        colorSpace='rgb',
                        blendMode='avg',
                        useFBO=True)

    # set up directions
    # judge_button = visual.ImageStim(win, image=judgement_button_img, pos=(0, 0), opacity=0.65)

    feedback_positive = visual.TextStim(win,
                                        text=u"Correct!",
                                        pos=(0, 0),
                                        bold=True,
                                        height=0.15)
    feedback_negative = visual.TextStim(win,
                                        text=u"Incorrect!",
                                        pos=(0, 0),
                                        bold=True,
                                        height=0.15)

    # create fixation cross
    blank_fixation = visual.TextStim(win, text='+', color=u'white')

    # number of trials (must divide by 16 evenly)
    total_num_trials = 16  # --------TRIAL NUMBER ADJUSTMENTS HERE------------
    pic_per_trial = 20

    trial_types_idx = [(x % 16) + 1 for x in range(total_num_trials)]

    random.shuffle(trial_types_idx)

    ready_screen = visual.TextStim(win, text=u"Ready?", pos=(0, 0), bold=True)
    sample_screen(win, [ready_screen])
    event.waitKeys(maxWait=10, keyList=['space'], modifiers=False)

    # start looping through trials
    for no, trial in enumerate(trial_types_idx):
        trial_data = trial_types.get(trial)
        trial_object = IST_objects.OverallTrial(
            no + 1, globalClock.getTime(), trial_data.get('category_of_pic'),
            trial_data.get('probability_dist'), trial_data.get('reward_type'),
            trial_data.get('majority_cat'))
        trial_pics = identify_trial_pictures(trial_object.prob_dist,
                                             trial_object.majority_cat,
                                             pic_per_trial)
        random.shuffle(trial_pics)

        # beginning trial from user's perspective
        trial_clock.reset()
        start_screen(win,
                     trial_data.get('category_of_pic'),
                     trial_data.get('reward_type'),
                     wait=3)
        sample_button, maj_button, min_button, trial_object.majority_side = create_trial_buttons(
            win, trial_object.majority_cat)
        next_unseen_pic = 0

        for idx, sample_pic in enumerate(trial_pics):
            sample_screen(win, [sample_button, maj_button, min_button])
            sample_clock.reset(0)
            choice_to_sample = event.waitKeys(
                maxWait=10,
                keyList=['left', 'down', 'right'],
                modifiers=False,
                timeStamped=sample_clock)

            if choice_to_sample is None:
                feedback = [feedback_negative]
                sample_screen(win, feedback, 2)
                trial_object.set_final_choice('No Choice')
                trial_object.final_choice_time = 'No Time'
                trial_object.global_final_choice_time = globalClock.getTime()
                trial_object.total_trial_time = trial_clock.getTime()
                next_unseen_pic = idx
                break
            elif 'down' in choice_to_sample[0]:
                # allocate all sample data
                sample = IST_objects.SamplesInTrial(idx + 1, sample_pic,
                                                    sample_clock.getTime(),
                                                    globalClock.getTime())
                visual_select = visual.ImageStim(win, image=sample_pic)
                sample_clock.reset(0)
                globalClock.getTime()
                sample_screen(win, [visual_select, maj_button, min_button],
                              2.5)
                #sample_screen(win, [visual_select, maj_button, min_button, judge_button])
                #image_judgement = event.waitKeys(maxWait=5, keyList=['left', 'right'], modifiers=False,
                #                                 timeStamped=sample_clock)
                #if image_judgement:
                #    sample.image_judgement = image_judgement[0][0]
                #    sample.time_of_judge = image_judgement[0][1]
                #else:
                #    sample.image_judgement = 'No Judgement'
                #    sample.time_of_judge = 'No Time'
                sample.global_time_of_judgment = globalClock.getTime()
                trial_object.add_sample(sample)
                core.wait(0.25)
            else:
                if 'left' in choice_to_sample[0]:
                    if trial_object.majority_side == 'left':
                        feedback = [feedback_positive]
                    else:
                        feedback = [feedback_negative]
                else:
                    if trial_object.majority_side == 'right':
                        feedback = [feedback_positive]
                    else:
                        feedback = [feedback_negative]
                sample_screen(win, feedback, 2)
                trial_object.set_final_choice(choice_to_sample[0][0])
                trial_object.final_choice_time = choice_to_sample[0][1]
                trial_object.global_final_choice_time = globalClock.getTime()
                trial_object.total_trial_time = trial_clock.getTime()
                next_unseen_pic = idx
                break
        for unused_pic in trial_pics[next_unseen_pic:]:
            return_unused_pic(unused_pic)
        sample_screen(win, [blank_fixation], 2)
        if trial_object.num_of_pics_sampled == 0 or choice_to_sample is None:
            file_writer.write(participant.csv_format() +
                              trial_object.csv_format() + '\n')
        else:
            for samp in trial_object.samples:
                file_writer.write(participant.csv_format() +
                                  trial_object.csv_format() +
                                  samp.csv_format() + '\n')
    file_writer.flush()
    file_writer.close()
Esempio n. 11
0
Directions.draw()
win.flip()
event.waitKeys()


##### TTL Pulse trigger
if MRIflag:
    Wait_for_Scanner.draw()
    win.flip()
    event.waitKeys(keyList=['lshift','z'])

##### Triggers for serial port ***

#### Setting up a global clock to track initiation of experiment to end
Time_Since_Run = core.MonotonicClock()  # to track the time since experiment started, this way it is very flexible compared to psychopy.clock
RT_clock=core.Clock()
##### 2 seconds Intial fixation
Fix_Cue.draw()
win.flip()
core.wait(Initial_wait_time)

##### Start trials

for trial_num in range(len(Trial_dict)): #range(len(Trial_dict))
    #print('\n')
    print(trial_num)
    # draw the cue
    Trial_dict[trial_num]['cue_stim'].draw()
    Cue_Prez_T=Time_Since_Run.getTime()
    win.flip()
Esempio n. 12
0
    def start_experiment(self):
        global currentrewardlocation
        global angle_desired
        initialparam()
        GetGUI()

        currentreward = np.arange(len(self.rewardlocation))
        random.shuffle(currentreward)
        i = 0
        print 'Reward location order:', currentreward

        while self._currenttrial < self.numtrials:

            print('Trial %d beginning...' % self._currenttrial)
            print 'Looking at reward location number:', currentreward[i]
            #currentreward = np.random.choice(len(self.rewardlocation), 1)

            _sendHttpMsg(currentreward[i])

            currentrewardlocation = self.rewardlocation.iloc[currentreward[i]]

            small_rotation = atan(
                abs(currentrewardlocation['y1'] - currentrewardlocation['y2'])
                /
                abs(currentrewardlocation['x1'] - currentrewardlocation['x2']))
            #print (currentrewardlocation['y1'],currentrewardlocation['y2'],currentrewardlocation['x1'],currentrewardlocation['x2'])
            #print (small_rotation)
            if (int(currentrewardlocation['y1'] - currentrewardlocation['y2'])
                    <= 0) & (int(currentrewardlocation['x1'] -
                                 currentrewardlocation['x2']) <= 0):

                angle_desired = 2 * pi - small_rotation

            elif (int(currentrewardlocation['y1'] -
                      currentrewardlocation['y2']) >=
                  0) & (int(currentrewardlocation['x1'] -
                            currentrewardlocation['x2']) >= 0):
                angle_desired = pi - small_rotation

            elif (int(currentrewardlocation['y1'] -
                      currentrewardlocation['y2']) <=
                  0) & (int(currentrewardlocation['x1'] -
                            currentrewardlocation['x2']) >= 0):

                angle_desired = pi + small_rotation

            else:
                angle_desired = small_rotation

            # Start trial - show reward
            print('Go to reward location (%d, %d)' %
                  (currentrewardlocation['x1'], currentrewardlocation['y1']))

            self.plotrewardlocation(currentrewardlocation)

            # Set up plot for realtime plotting
            cv2.namedWindow('Trial %d Reward' % self._currenttrial,
                            cv2.WINDOW_NORMAL)
            #resize image window depending on the screen
            #cv2.resizeWindow('Trial %d Reward' % self._currenttrial, 1088, 1088) #ori 800800

            # Start timer for reward timeout

            timer = core.CountdownTimer(self.rewardtimeout)
            #timer = core.CountdownTimer(GUIsettings.get("maze_trialDuration"))
            abstime = core.MonotonicClock()

            found = 0
            check_duration = 0

            elapsedtime = abstime.getTime()
            os.system('play -n synth %s sin %s' % (0.5, frequency))
            self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                      elapsedtime=elapsedtime,
                                      robotloc=(int(loc_x_rotate),
                                                int(loc_y_rotate)),
                                      foundOrNot=found)

            while (timer.getTime() > 0) & (found == 0):

                #subcribe to robot location
                rospy.Subscriber("/amcl_pose", PoseWithCovarianceStamped,
                                 get_xy_loc)

                # Print elapsed time on map and console
                elapsedtime = abstime.getTime()
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime,
                                          robotloc=(int(loc_x_rotate),
                                                    int(loc_y_rotate)),
                                          foundOrNot=found)

                #print "\033[K Elapsed Time : ", elapsedtime, "\r",
                sys.stdout.flush()
                #if(abs(int(loc_x_rotate) - int(currentrewardlocation['x1']))<30) & (abs(int(loc_y_rotate) - int(currentrewardlocation['y1']))<30):
                #if ((abs(int(loc_x) - int(currentrewardlocation['x']))<40) & (abs(int(loc_y) - int(currentrewardlocation['y']))<40) & (abs(orien_z-self.orientation)<0.333)):
                #print (abs(int(loc_x) - int(currentrewardlocation['x'])))
                if (abs(int(loc_x_rotate) - int(currentrewardlocation['x1'])) <
                        self.position_tolerance
                    ) & (abs(
                        int(loc_y_rotate) - int(currentrewardlocation['y1'])) <
                         self.position_tolerance) & (
                             abs(angle_desired - angle_current) <
                             self.angle_tolerance):
                    check_duration = check_duration + 1
                    #print ('duration %d' %check_duration)
                    if (check_duration == GUIsettings.get(
                            "maze_destinationDuration")):
                        #if (check_duration==self.stay_duration):
                        found = 1
                        self.realtime_elapsedtime(
                            rewardloc=currentrewardlocation,
                            elapsedtime=elapsedtime,
                            robotloc=(int(loc_x_rotate), int(loc_y_rotate)),
                            foundOrNot=found)

                        for x in range(0, 6):

                            os.system('play -n synth %s sin %s' %
                                      (0.2, frequency))

                            time.sleep(.2)
                        print('\n Trial Ended; Target %s Found' %
                              self._currenttrial)
                        #save to excel
                        appendInfo = 'target number %d found in %f' % (
                            self._currenttrial, elapsedtime)
                        print(appendInfo)
                        SaveTrialParameters(appendInfo)

                        break

                else:
                    check_duration = 0

            if (found == 0):
                print('\n Trial Ended; Time Out')
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime,
                                          robotloc=(int(loc_x_rotate),
                                                    int(loc_y_rotate)),
                                          foundOrNot=2)
                for x in range(0, 12):
                    os.system('play -n synth %s sin %s' %
                              (0.15, (frequency - x * 100)))

            cv2.destroyAllWindows()
            i += 1
            self.updatetrial()  # Trial ended - start of next trial
Esempio n. 13
0
def show_study(params, study_list, study_cond, set_bins):
    """ Shows the study phase """
    global log
    global win

    instructions1 = visual.TextStim(win,
                                    text="Indoor or Outdoor?",
                                    pos=(0, 0.9),
                                    color=(-1, -1, -1),
                                    wrapWidth=1.75,
                                    alignHoriz='center',
                                    alignVert='center')
    instructions2 = visual.TextStim(win,
                                    text="Press the spacebar to begin",
                                    pos=(0, -0.25),
                                    color=(-0.5, -0.5, -0.5),
                                    wrapWidth=1.75,
                                    alignHoriz='center',
                                    alignVert='center')

    instructions1.draw()
    instructions2.draw()
    win.flip()
    key = event.waitKeys(keyList=['space', '5', 'esc', 'escape'])
    if key and key[0] in ['escape', 'esc']:
        print('Escape hit - bailing')
        return -1

    log.write('Study phase started at {0}\n'.format(str(datetime.now())))
    log.write('Trial,Stim,Cond,StartT,Resp,RT\n')

    local_timer = core.MonotonicClock()
    duration = params['Duration']
    isi = params['ISI']
    log.flush()
    valid_keys = list(params['Resp1Keys'].lower()) + list(
        params['Resp2Keys'].lower()) + list(
            params['Resp3Keys'].lower()) + ['esc', 'escape']
    for trial in range(len(study_list)):
        if params['SelfPaced']:
            t1 = local_timer.getTime()
        else:
            t1 = trial * (duration + isi
                          )  # Time when this trial should have started
        log.write('{0},{1},{2},{3:.3f},'.format(trial + 1, study_list[trial],
                                                study_cond[trial],
                                                local_timer.getTime()))
        log.flush()
        image = visual.ImageStim(win, image=study_list[trial])
        image.draw()
        instructions1.draw()
        win.flip()
        RT = 0
        key = event.waitKeys(duration,
                             keyList=valid_keys)  # Wait our normal duration
        if key and key[0] in ['escape', 'esc']:
            log.write('\nEscape key aborted experiment\n')
            print('Escape hit - bailing')
            return -1
        elif key:
            RT = local_timer.getTime() - t1
            core.wait(t1 + duration -
                      local_timer.getTime())  # Wait the remainder of the trial
        win.flip()  # Clear the screen for the ISI
        if params['SelfPaced'] and (
                RT < 0.05):  # Continue waiting until we get something
            key = event.waitKeys(keyList=valid_keys)
            RT = local_timer.getTime() - t1
        if params['SelfPaced']:
            core.wait(isi)
        else:  # Do the ISI locking to the clock cleaning and allow a response in it if we don't have one
            while local_timer.getTime() < (t1 + duration + isi):
                if (RT < 0.05):
                    key = event.getKeys(keyList=valid_keys)
                    if key:
                        RT = local_timer.getTime() - t1
        if RT > 0.05:  # We have a response
            log.write('{0},{1:.3f}\n'.format(decode_response(params, key[0]),
                                             RT))
        else:
            log.write('NA\n')
    return 0
Esempio n. 14
0
	stdscr.refresh()
	#stdscr.addstr(0, 0, "Poster sequence generated ... ")
	master_log = []
	master_log.append(["Marker", "Master Time"])
	with open(date_folder + "/sessionTriggers.csv", 'w') as storage:
		wr = csv.writer(storage, dialect='excel')
		wr.writerows(master_log)
		storage.close()
	master_log = []
	attempts = 0  # inclusive of failed attempts
	curr_trial = 0  # only tracks successful attempts
	curr_target = 0  # follows curr_trial, actually kind of redundant
	inter_trial_duration = np.random.randint(
	    inter_trial_interval[0], inter_trial_interval[1]+1)
	# reference clock, csv file will report with this time
	master_timer = core.MonotonicClock()
	mini_timer = core.MonotonicClock()  # to be used every event
	status = "Normal"
	phase = "Pre Trial Interval"
	encoding_dict = {"Cue Up": 10, "Movement": 20, "Reward": 30, "Penalty": 40}
	pt = PointStamped()
	pt.header.stamp = rospy.Time.now()
	pt.header.frame_id = '/map'
	pt.point.x = float(poster_locations[targets[curr_target]][0])
	pt.point.y = float(poster_locations[targets[curr_target]][1])
	pt.point.z = 0
	marker.publish(pt)
	target_location = [pt.point.x, pt.point.y, float(
	    poster_locations[targets[curr_target]][2])]
	pos_saver = []
	zone_entered = -1
Esempio n. 15
0
def run_vs(win,
           sequence_level,
           sequence_target,
           sequence_load,
           sequence_retentionDur,
           sequence_ITI,
           fi=None,
           setSize=3,
           dummymode=True):
    num_trial = len(sequence_level)
    win.flip()
    stim = Stimuli(win, timing_vs, dummymode=dummymode)
    stim.mouse = event.Mouse(visible=False)
    #Experiment instructions
    if dummymode:
        stim.text_and_stim_keypress(
            'Welcome to the attentional control task\n\nPress Enter to continue',
            pos=(0, 0.7))
        stim.text_and_stim_keypress('You will be asked to search for an inverted T (target) among an array of distractors\n\nThe target looks like this:'\
                                    ,pos=(0,0.7), stim=stim.target)
        stim.text_and_stim_keypress('The trials look like the picture below\n\nYou job is to determine whether there is the target or not as accurately as possible within 4 seconds while ignoring the color of the border'\
                                    ,pos=(0,0.7), image='wm-instruction1.png'    )
        stim.text_and_stim_keypress(
            'Press left button if a target is present\n\nPress right button if it is not present',
            pos=(0, 0.7),
            image='wm-instruction1.png')
        stim.text_and_stim_keypress('The array will remain on the screen for 6 s even after you press a button\n\nBut the fixation cross will turn red after the first 4s\n\nYour response will not be recorded after this'\
                                    ,pos=(0,0.7), image='wm-instruction2.png'    )
        stim.text_and_stim_keypress('After a short delay of blank screen, one of the objects is presented again with a random orientation\n\nYou need to rotate it to the upright position'\
                                    ,pos=(0,0.7), image='wm-instruction3.png'    )
        stim.text_and_stim_keypress(
            'Use left button to rotate the item anti-clockwise\n\nand the right button to rotate clockwise\n\nThe trial will begin after you press Enter',
            pos=(0, 0.7),
            stim=stim.ready)

    #Generate stimulus parameters
    c, p, parameters = trialGen_ori(
        0.4, 0.5, 0.05, 0.39
    )  #c is mean TD disimilarity(only y), p is DD(only y), parameters has x1,y1,x2,y2
    param_list = []
    c_list = []
    #select those trial parameters that match the specified level in levelSpace
    for i in range(num_trial):
        index = np.random.choice(range(len(np.unique(sequence_level))))
        param_list.append(
            parameters[np.where(p == sequence_level[i])[0]][index])
        c_list.append(c[np.where(p == sequence_level[i])[0]][index])
    triallist = []
    for i in range(num_trial):
        trial = {}
        trial['x1'] = param_list[i][0]
        trial['y1'] = param_list[i][1]
        trial['x2'] = param_list[i][2]
        trial['y2'] = param_list[i][3]
        trial['p'] = sequence_level[i]
        trial['c'] = c_list[i]
        trial['load'] = sequence_load[i]
        trial['target'] = sequence_target[i]
        trial['retention'] = sequence_retentionDur[i]
        triallist.append(trial)

    print(len(triallist))
    #Create a clock to log time stamps to match imaging datafile
    runTimer = core.MonotonicClock()
    if not dummymode:
        # Present a screen that tells the participant and experimenter to wait
        # while the scanner starts.
        text_stim = visual.TextStim(
            stim.win,
            text=
            "Please wait for the scanner to start...\n\nThis is the attentional control task",
            font='Helvetica',
            alignHoriz='center',
            alignVert='center',
            units='norm',
            pos=(0, 0.7),
            height=0.08,
            color=[255, 255, 255],
            colorSpace='rgb255',
            wrapWidth=3)
        text_stim.draw()
        stim.win.flip()
        # Wait for the scanner to start its sequence.
        stim.mri.wait_for_sync()
        # Remove the text from screen.
        stim.win.flip()
        #Create a clock to log time stamps to match imaging datafile
        runTimer = core.MonotonicClock()
        #present a 10s countdown timer (10s=5 TRs, discarded in analysis)
        countdownTimer(stim.win, 10)

    # run trials
    for i, trial in enumerate(triallist):
        try:
            resp, answer, rt, target, targetborder,fixation_onset,stimuli_onset,retention_onset = \
                stim.search_array(trial,condition='vs',target= trial['target'], load=trial['load'], timer=runTimer)
            corr = (resp == answer)

            #only outside scanner feedback will be provided
            if dummymode:
                if not corr:
                    if resp == 'timeout':
                        stim.text('Timeout', max_wait=0.6)
                    else:
                        stim.text('Incorrect', max_wait=0.6)
            #A dummy retrival phase will be presented
            #Pps are asked to rotate the stimulus to upright position
            resp_ori, correct_ori, probe_ori, rt_ori, no_click, recall_onset = stim.recall(
                target, targetborder, timer=runTimer)

            ITI_onset = runTimer.getTime()
            if fi is not None:
                fi.writerow([
                    '%s, %s, %s, %d, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %d, %.2f, %.2f,%.2f, %.2f, %.2f, %.2f,%d,%.2f, %.2f,%.2f, %.2f, %.2f'
                    % ('vs', answer, resp, int(corr), rt * 1000, trial['c'],
                       trial['p'], trial['x1'], trial['y1'], trial['x2'],
                       trial['y2'], trial['load'], trial['retention'] * 1000,
                       sequence_ITI[i] * 1000, resp_ori, correct_ori,
                       probe_ori, rt_ori * 1000, no_click, fixation_onset,
                       stimuli_onset, retention_onset, recall_onset, ITI_onset)
                ])
            #ITI
            core.wait(sequence_ITI[i])
        except Exception as err:
            traceback.print_exc()
            raise Exception(err)
    def search_array(self,
                     trial,
                     condition,
                     target=None,
                     ori=0,
                     setSize=3,
                     load=3,
                     timer=None):
        #timer to log run time, not reset on each trial
        if timer == None:
            timer = core.MonotonicClock()
        self.fixation.setAutoDraw(True)
        self.win.flip()
        fixation_onset = timer.getTime()
        core.wait(self.timing['fixation'])
        draw_objs = []
        radius = 0.30
        borders = []
        stimpos = self.calculatePosition(radius, 40)
        #randomly rotate the whole array
        stimori = np.random.choice(orilist)
        #print (stimpos)
        #Draw memory array
        if condition == 'memory':
            for i in range(setSize**2):
                x = np.random.choice(
                    [trial['x1'],
                     trial['x2']])  #can be either of 2 type of distractors
                draw_objs.append(self.make_stim(x, y=trial['orilist'][i]))

        #Draw search array
        if condition == 'vs':  #half of trials have no target
            for n in range(int((setSize**2 - 1) / 2)):
                draw_objs.append(self.make_stim(x=trial['x1'],
                                                y=trial['y1']))  #distractor1
                draw_objs.append(self.make_stim(x=trial['x2'],
                                                y=trial['y2']))  #distractor2
            if target == 1:
                draw_objs.append(self.make_stim(x=0, y=0, name='t'))  #target
                answer = 'yes'
            else:
                answer = 'no'
            while len(draw_objs) < setSize**2:
                draw_objs.append(self.make_stim(x=trial['x2'], y=trial['y2']))
            #randomly rotate the entire array
            [x.setOri(stimori + x.ori) for x in draw_objs]
            #randomise order of the object array
            shuffle(draw_objs)

        #Determine which N (load) borders are of target color
        border_seq = np.concatenate(
            (np.ones(load,
                     dtype=int), np.zeros(len(draw_objs) - load, dtype=int)))
        shuffle(border_seq)
        #Ensure that in low load condition encoding items are not adjacent
        if load <= 4:
            duplicate = True
            while duplicate == True:
                shuffle(border_seq)
                duplicate = self.check_duplicate(border_seq)
        #draw borders for each object
        for i in range(len(draw_objs)):
            borders.append(self.make_border(color=border_color[border_seq[i]]))
        #pass on the memory probe item and its border
        rand = np.random.choice(np.where(border_seq == 1)[0])
        targetobj = draw_objs[rand]
        targetborder = borders[rand]
        #Arrange items into an array along an invisible circle
        [x.setPos(y) for x, y in zip(draw_objs, stimpos)]
        [x.setPos(y) for x, y in zip(borders, stimpos)]
        #Draw stimuli
        [x.setAutoDraw(True) for x in draw_objs]
        [x.setAutoDraw(True) for x in borders]
        if condition == 'vs' and self.dummymode:
            self.probe_vs.draw()  #Reminder of response contingency
        start_time = self.win.flip()
        stimuli_onset = timer.getTime()
        #memory array stay for a fixed duration
        #but the color of fixation turn red to signify remaining encoding time, matched with AC task also.
        if condition == 'memory':
            # Get the starting time.
            t0 = self.win.flip()
            t1 = t0
            # Loop until the duration runs out.
            while t1 - t0 < timing_memory['search']:
                core.wait(timing_vs['search'])
                self.fixation.setColor('red')
                # Get a timestamp.
                t1 = self.win.flip()
            [x.setAutoDraw(False) for x in draw_objs]
            [x.setAutoDraw(False) for x in borders]
            self.fixation.setColor('white')
            self.fixation.setAutoDraw(False)
            self.win.flip()
            retention_onset = timer.getTime()
            #delay blank screen
            core.wait(trial['retention'])
            return targetobj, targetborder, fixation_onset, stimuli_onset, retention_onset

        #search array stays after button press for the same duration as in STM task
        #However, Pps only have 4s to respond; after 4s, the fixation cross become red and they can no longer respond
        if condition == 'vs':
            # Get the starting time.
            t0 = self.win.flip()
            t1 = t0
            key = None
            resp_time = 0
            # Loop until the duration runs out.
            while t1 - t0 < timing_memory['search']:
                while t1 - t0 < self.timing['search']:
                    tempKey, tempResp_time = self.get_input(
                        max_wait=self.timing['search'],
                        keylist=list(self.vs_keymap_mri.keys()))
                    if tempKey is not None:
                        key = tempKey
                        #Not using tempResp_time as scanner time is different from psychopy core timer
                        resp_time = self.win.flip()
                        #prevent the recorded response being overridden
                        core.wait(self.timing['search'] - (resp_time - t0))
                        break
                    # Get a timestamp.
                    t1 = self.win.flip()
                self.fixation.setColor('red')
                # Get a timestamp.
                t1 = self.win.flip()
            [x.setAutoDraw(False) for x in draw_objs]
            [x.setAutoDraw(False) for x in borders]
            self.fixation.setColor('white')
            self.fixation.setAutoDraw(False)
            self.win.flip()
            retention_onset = timer.getTime()
            #delay blank screen
            core.wait(trial['retention'])
            if key is None:
                return ('timeout', answer, resp_time - start_time, targetobj,
                        targetborder, fixation_onset, stimuli_onset,
                        retention_onset)

            else:
                return (self.vs_keymap[key], answer, resp_time - start_time,
                        targetobj, targetborder, fixation_onset, stimuli_onset,
                        retention_onset)  #return response, correct answer &RT
Esempio n. 17
0
def main():
    # Store info about the experiment session
    participant_no = raw_input('Participant Number:')
    session_no = raw_input('Session Number:')
    raw_input('Press enter when you are ready to start the task.')
    participant = IST_objects.Participant(participant_no, session_no)

    # set up logging information
    globalClock = core.MonotonicClock()  # if this isn't provided the log times will reflect secs since python started
    trial_clock = core.Clock()
    logging.setDefaultClock(globalClock)
    # set up file creation
    filename = config.get('log_location') + os.sep + '{}_{}_{}_IST_memory'.format(participant.id, participant.session,
                                                                                  data.getDateStr()) + '.csv'
    file_writer = open(filename, 'a')
    file_writer.write(
        'participant_id, session, trial_number, global_time, picture, old/new, time_of_choice, confidence, '
        'time_con_rating,\n')

    endExpNow = False

    # set up display
    win = visual.Window(size=(1440, 900), fullscr=True, screen=0,
                        allowGUI=False, allowStencil=False, monitor='testMonitor',
                        color='black', colorSpace='rgb', blendMode='avg', useFBO=True)

    # set up directions
    old_new = visual.TextStim(win, text=u"Old/New", pos=(0, -0.77), bold=True)
    confidence_rating = visual.TextStim(win, text=u"1   2   3", pos=(0, 0), height=0.3, bold=True)
    confidence_text = visual.TextStim(win, text=u"low                     high", pos=(0, -0.3), height=0.1, bold=True)

    ready_screen = visual.TextStim(win, text=u"Ready?", pos=(0, 0), bold=True)
    ready_screen.draw()
    win.flip()
    event.waitKeys(maxWait=10, keyList=['space'], modifiers=False)

    for x in range(num_of_images):
        pic = total_images[x]
        visual_select = visual.ImageStim(win, image=pic)
        visual_select.draw()
        old_new.draw()
        win.flip()
        trial_clock.reset(0)
        status_in = event.waitKeys(maxWait=5, keyList=['left','right'], modifiers=False, timeStamped=trial_clock)
        confidence_rating.draw()
        confidence_text.draw()
        win.flip()
        trial_clock.reset(0)
        conf_in = event.waitKeys(maxWait=5, keyList=['left','down','right'], modifiers=False, timeStamped=trial_clock)
        blank_fixation = visual.TextStim(win, text='+', color=u'white')
        blank_fixation.draw()
        win.flip()
        core.wait(1.0)
        trial = IST_objects.ConfidenceTrial(x+1, globalClock.getTime(), pic, status_in, conf_in)
        if pic in old_images:
            trial.old_new = 'old'
        else:
            trial.old_new = 'new'
        file_writer.write(participant.csv_format() + trial.csv_format()+'\n')

    print'!!!!!!!!!!!!!!!!!!!!!!!!!'
    file_writer.close()
Esempio n. 18
0
def show_task(params, fnames, type_code, lag, set_bins):
    """
    params: structure with all the expeirmental parameters
    fnames: list of filenames to show in order (from load_and_decode_order)
    type_code: Trial type numeric code (see load_and_decode_order)
    lag: # of intervening items b/n 1st and second (from load_and_decode_order)
    set_bins: lure-bin number (only relevant if it's a lure)

    """

    global log, win

    if params['TwoChoice'] == True:
        instructions1 = visual.TextStim(win,
                                        text="Old or New?",
                                        pos=(0, 0.9),
                                        color=(-1, -1, -1),
                                        wrapWidth=1.75,
                                        alignHoriz='center',
                                        alignVert='center')
    else:
        instructions1 = visual.TextStim(win,
                                        text="Old, Similar, or New?",
                                        pos=(0, 0.9),
                                        color=(-1, -1, -1),
                                        wrapWidth=1.75,
                                        alignHoriz='center',
                                        alignVert='center')

    instructions2 = visual.TextStim(win,
                                    text="Press the spacebar to begin",
                                    pos=(0, -0.25),
                                    color=(-0.5, -0.5, -0.5),
                                    wrapWidth=1.75,
                                    alignHoriz='center',
                                    alignVert='center')

    instructions1.draw()
    instructions2.draw()
    win.flip()
    key = event.waitKeys(keyList=['space', '5', 'esc', 'escape'])
    if key and key[0] in ['escape', 'esc']:
        print('Escape  hit - bailing')
        return -1
    TLF_trials = np.zeros(
        3)  # Number of trials of each type we have a response to
    TLF_response_matrix = np.zeros((3, 3))  # Rows = O,(S),N  Cols = T,L,R
    lure_bin_matrix = np.zeros((4, 5))  # Rows: O,S,N,NR  Cols=Lure bins

    log.write('Task started at {0}\n'.format(str(datetime.now())))
    log.write('Trial,Stim,Cond,Lag,LBin,StartT,Resp,RT,Corr\n')
    local_timer = core.MonotonicClock()
    duration = params['Duration']
    isi = params['ISI']
    ncorrect = 0
    log.flush()
    valid_keys = list(params['Resp1Keys'].lower()) + list(
        params['Resp2Keys'].lower()) + list(
            params['Resp3Keys'].lower()) + ['esc', 'escape']
    for trial in range(len(fnames)):
        if params['SelfPaced']:
            t1 = local_timer.getTime()
        else:
            t1 = trial * (duration + isi
                          )  # Time when this trial should have started
        stim_path = fnames[trial]
        stim_number = int(stim_path[-8:-5])
        log.write('{0},{1},{2},{3},{4:.3f},'.format(trial + 1, fnames[trial],
                                                    type_code[trial],
                                                    lag[trial],
                                                    set_bins[stim_number - 1],
                                                    local_timer.getTime()))
        log.flush()
        image = visual.ImageStim(win, image=fnames[trial])
        image.draw()
        instructions1.draw()
        win.flip()
        response = 0
        correct = 0
        RT = 0
        key = event.waitKeys(duration,
                             keyList=valid_keys)  # Wait our normal duration
        if key and key[0] in ['escape', 'esc']:
            print('Escape hit - bailing')
            log.write('\nEscape key aborted experiment\n')
            return -1
        elif key:
            RT = local_timer.getTime() - t1
            core.wait(t1 + duration -
                      local_timer.getTime())  # Wait the remainder of the trial
        win.flip()  # Clear the screen for the ISI
        if params['SelfPaced'] and (
                RT < 0.05):  # Continue waiting until we get something
            key = event.waitKeys(keyList=valid_keys)
            RT = local_timer.getTime() - t1
        if params['SelfPaced']:
            core.wait(isi)
        else:  # Do the ISI locking to the clock cleaning and allow a response in it if we don't have one
            while local_timer.getTime() < (t1 + duration + isi):
                if (RT < 0.05):
                    key = event.getKeys(keyList=valid_keys)
                    if key:
                        RT = local_timer.getTime() - t1
        if RT > 0.05:  # We have a response
            response = decode_response(params, key[0])
            # Increment the appropriate trial type counter (for count of # they responded to)
            if type_code[trial] == 1:  # Repeatitions -- 2nd of real repeat
                TLF_trials[0] += 1
                trial_type = 1
            elif type_code[trial] == 3:  # Lure 2nd presentations
                TLF_trials[1] += 1
                trial_type = 2
            else:  # All others -- 1st of 2 and extra foils are firsts
                TLF_trials[2] += 1
                trial_type = 3
            TLF_response_matrix[
                response - 1, trial_type -
                1] += 1  # Increment the response x type  matrix as needed
            if params['TwoChoice'] == True:  # Old/new variant
                if trial_type == 1 and response == 1:  # Hit
                    correct = 1
                elif trial_type == 2 and response == 2:  #Lure-CR
                    correct = 1
                elif trial_type == 3 and response == 2:  #CR
                    correct = 1
            else:  #Old/similar/new variant
                if trial_type == 1 and response == 1:  # Hit
                    correct = 1
                elif trial_type == 2 and response == 2:  #Lure-Similar
                    correct = 1
                elif trial_type == 3 and response == 3:  #CR
                    correct = 1
            log.write('{0},{1},{2:.3f}\n'.format(response, correct, RT))
        else:
            log.write('NA\n')
        if type_code[
                trial] == 3:  # A 2nd of lure pair - Take care of the lure-bin details
            bin_index = set_bins[stim_number - 1] - 1  # Make it 0-indexed
            resp_index = response - 1  # Make this 0-indexed
            if resp_index == -1:
                resp_index = 3  # Loop the no-responses into the 4th entry here
            lure_bin_matrix[resp_index, bin_index] += 1
        win.flip()  # Clear the screen for the ISI
        while local_timer.getTime() < (t1 + duration + isi):
            key = event.getKeys()
            #print(key)
            if key and key[0] in ['escape', 'esc']:
                print('Escape hit - bailing')
                log.write('\nEscape key aborted experiment\n')
                return -1
        ncorrect += correct
    # Print some summary stats to the log file
    log.write('\nValid responses:\nTargets, {0:d}\nlures, {1:d}\nfoils, {2:d}'.
              format(TLF_trials[0], TLF_trials[1], TLF_trials[2]))
    log.write('\nCorrected rates\n')
    log.write('\nRateMatrix,Targ,Lure,Foil\n')
    # Fix up any no-response cell here so we don't divide by zero
    TLF_trials[TLF_trials == 0.0] = 0.00001
    log.write('Old,{0:.2f},{1:.2f},{2:.2f}\n'.format(
        TLF_response_matrix[0, 0] / TLF_trials[0],
        TLF_response_matrix[0, 1] / TLF_trials[1],
        TLF_response_matrix[0, 2] / TLF_trials[2]))
    log.write('Similar,{0:.2f},{1:.2f},{2:.2f}\n'.format(
        TLF_response_matrix[1, 0] / TLF_trials[0],
        TLF_response_matrix[1, 1] / TLF_trials[1],
        TLF_response_matrix[1, 2] / TLF_trials[2]))
    log.write('New,{0:.2f},{1:.2f},{2:.2f}\n'.format(
        TLF_response_matrix[2, 0] / TLF_trials[0],
        TLF_response_matrix[2, 1] / TLF_trials[1],
        TLF_response_matrix[2, 2] / TLF_trials[2]))

    log.write('\nRaw counts')
    log.write('\nRawRespMatrix,Targ,Lure,Foil\n')
    log.write('Old,{0:d},{1:d},{2:d}\n'.format(TLF_response_matrix[0, 0],
                                               TLF_response_matrix[0, 1],
                                               TLF_response_matrix[0, 2]))
    log.write('Similar,{0:d},{1:d},{2:d}\n'.format(TLF_response_matrix[1, 0],
                                                   TLF_response_matrix[1, 1],
                                                   TLF_response_matrix[1, 2]))
    log.write('New,{0:d},{1:d},{2:d}\n'.format(TLF_response_matrix[2, 0],
                                               TLF_response_matrix[2, 1],
                                               TLF_response_matrix[2, 2]))

    log.write('\n\nLureRawRespMatrix,Bin1,Bin2,Bin3,Bin4,Bin5\n')
    log.write('Old,{0:d},{1:d},{2:d},{3:d},{4:d}\n'.format(
        lure_bin_matrix[0, 0], lure_bin_matrix[0, 1], lure_bin_matrix[0, 2],
        lure_bin_matrix[0, 3], lure_bin_matrix[0, 4]))
    log.write('Similar,{0:d},{1:d},{2:d},{3:d},{4:d}\n'.format(
        lure_bin_matrix[1, 0], lure_bin_matrix[1, 1], lure_bin_matrix[1, 2],
        lure_bin_matrix[1, 3], lure_bin_matrix[1, 4]))
    log.write('New,{0:d},{1:d},{2:d},{3:d},{4:d}\n'.format(
        lure_bin_matrix[2, 0], lure_bin_matrix[2, 1], lure_bin_matrix[2, 2],
        lure_bin_matrix[2, 3], lure_bin_matrix[2, 4]))
    log.write('NR,{0:d},{1:d},{2:d},{3:d},{4:d}\n'.format(
        lure_bin_matrix[3, 0], lure_bin_matrix[3, 1], lure_bin_matrix[3, 2],
        lure_bin_matrix[3, 3], lure_bin_matrix[3, 4]))

    log.write('\nPercent-correct (corrected),{0:.2}\n'.format(
        ncorrect / TLF_trials.sum()))
    log.write('Percent-correct (raw),{0:.2}\n'.format(ncorrect / len(fnames)))

    hit_rate = TLF_response_matrix[0, 0] / TLF_trials[0]
    false_rate = TLF_response_matrix[0, 2] / TLF_trials[2]
    log.write(
        '\nCorrected recognition (p(Old|Target)-p(Old|Foil)), {0:.2f}'.format(
            hit_rate - false_rate))

    if params['TwoChoice'] == True:
        log.write('\nTwo-choice test metrics\n')
        lure_rate = TLF_response_matrix[0, 1] / TLF_trials[1]
        if hit_rate == 0.0:
            hit_rate = 0.5 / TLF_trials[0]
        if false_rate == 0.0:
            false_rate = 0.5 / TLF_trials[2]
        if lure_rate == 0.0:
            lure_rate = 0.5 / TLF_trials[1]

        log.write('Endorsement rates')
        log.write('Targets: {0:.2f}'.format(hit_rate))
        log.write('Lures: {0:.2f}'.format(lure_rate))
        log.write('Foils and Firsts: {0:.2f}'.format(false_rate))

        dpTF = norm.ppf(hit_rate) - norm.ppf(false_rate)
        dpTL = norm.ppf(hit_rate) - norm.ppf(lure_rate)
        dpLF = norm.ppf(lure_rate) - norm.ppf(false_rate)

        log.write("d' Target:Foil, {0:.2f}".format(dpTF))
        log.write("d' Target:Lure, {0:.2f}".format(dpTL))
        log.write("d' Lure:Foil, {0:.2f}".format(dpLF))
    else:
        log.write('\nThree-choice test metrics\n')
        sim_lure_rate = TLF_response_matrix[1, 1] / TLF_trials[1]
        sim_foil_rate = TLF_response_matrix[1, 2] / TLF_trials[2]
        log.write('LDI,{0:.2f}'.format(sim_lure_rate - sim_foil_rate))
    log.flush()
    return 0
Esempio n. 19
0
    Block_start.text = "Block " + str(b + 1) + " will start now"
    Block_start.draw()
    win.flip()
    time.sleep(1)

    # in 16 trials
    for i in range(b * ntrials, (b + 1) * ntrials):

        # set the color word and the font color for this trial
        Stroop_stim.text = trials[i, 0]
        Stroop_stim.color = trials[i, 1]

        # display the stimulus on the screen
        Stroop_stim.draw()
        win.flip()
        trial_timer = core.MonotonicClock()
        k = event.waitKeys(keyList=["d", "f", "j", "k"], maxWait=1.0)
        if k == None:
            k = [""]
        key = event.getKeys(timeStamped=trial_timer)
        lijst.append(k[0])
        tijd.append("{0:.2f}".format(trial_timer.getTime()))

        # determine accuracy
        trials[i, 4] = int(trials[i, 3] == k[0])

        # determine the feedback message
        if int(trials[i, 4]) == 1:
            Feedback.text = "Correct!"
        else:
            Feedback.text = "Wrong answer!"
Esempio n. 20
0
    def start_experiment(self):
        global currentrewardlocation
        global angle_desired
        """ Display a reward location and start timer"""
        while self._currenttrial < self.numtrials:
            print('Trial %d beginning...' % self._currenttrial)

            currentreward = np.random.choice(len(self.rewardlocation), 1)
            currentrewardlocation = self.rewardlocation.iloc[currentreward]

            small_rotation = atan(
                abs(currentrewardlocation['y1'] - currentrewardlocation['y2'])
                /
                abs(currentrewardlocation['x1'] - currentrewardlocation['x2']))
            #print (currentrewardlocation['y1'],currentrewardlocation['y2'],currentrewardlocation['x1'],currentrewardlocation['x2'])
            #print (small_rotation)
            if (int(currentrewardlocation['y1'] - currentrewardlocation['y2'])
                    <= 0) & (int(currentrewardlocation['x1'] -
                                 currentrewardlocation['x2']) <= 0):

                angle_desired = 2 * pi - small_rotation

            elif (int(currentrewardlocation['y1'] -
                      currentrewardlocation['y2']) >=
                  0) & (int(currentrewardlocation['x1'] -
                            currentrewardlocation['x2']) >= 0):
                angle_desired = pi - small_rotation

            elif (int(currentrewardlocation['y1'] -
                      currentrewardlocation['y2']) <=
                  0) & (int(currentrewardlocation['x1'] -
                            currentrewardlocation['x2']) >= 0):

                angle_desired = pi + small_rotation

            else:
                angle_desired = small_rotation

            # Start trial - show reward
            print('Go to reward location (%d, %d)' %
                  (currentrewardlocation['x1'], currentrewardlocation['y1']))

            self.plotrewardlocation(currentrewardlocation)

            # Set up plot for realtime plotting
            cv2.namedWindow('Trial %d Reward' % self._currenttrial,
                            cv2.WINDOW_NORMAL)
            cv2.resizeWindow('Trial %d Reward' % self._currenttrial, 800, 800)

            # Start timer for reward timeout

            timer = core.CountdownTimer(self.rewardtimeout)
            abstime = core.MonotonicClock()

            found = 0
            check_duration = 0

            elapsedtime = abstime.getTime()
            os.system('play -n synth %s sin %s' % (0.5, frequency))
            self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                      elapsedtime=elapsedtime,
                                      robotloc=(int(loc_x_rotate),
                                                int(loc_y_rotate)),
                                      foundOrNot=found)
            while (timer.getTime() > 0) & (found == 0):

                #subcribe to robot location,joy and laser scan data
                rospy.Subscriber("/amcl_pose", PoseWithCovarianceStamped,
                                 get_xy_loc)
                #rospy.Subscriber("joy", Joy, processjoy)
                #rospy.Subscriber("/base_scan", LaserScan, LaserData)

                # Print elapsed time on map and console
                elapsedtime = abstime.getTime()
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime,
                                          robotloc=(int(loc_x_rotate),
                                                    int(loc_y_rotate)),
                                          foundOrNot=found)

                #print "\033[K Elapsed Time : ", elapsedtime, "\r",
                sys.stdout.flush()

                #if(abs(int(loc_x_rotate) - int(currentrewardlocation['x1']))<30) & (abs(int(loc_y_rotate) - int(currentrewardlocation['y1']))<30):
                #if ((abs(int(loc_x) - int(currentrewardlocation['x']))<40) & (abs(int(loc_y) - int(currentrewardlocation['y']))<40) & (abs(orien_z-self.orientation)<0.333)):
                #print (abs(int(loc_x) - int(currentrewardlocation['x'])))
                if (abs(int(loc_x_rotate) - int(currentrewardlocation['x1'])) <
                        self.position_tolerance
                    ) & (abs(
                        int(loc_y_rotate) - int(currentrewardlocation['y1'])) <
                         self.position_tolerance) & (
                             abs(angle_desired - angle_current) <
                             self.angle_tolerance):
                    check_duration = check_duration + 1
                    #print ('duration %d' %check_duration)

                    if (check_duration == self.stay_duration):
                        found = 1
                        self.realtime_elapsedtime(
                            rewardloc=currentrewardlocation,
                            elapsedtime=elapsedtime,
                            robotloc=(int(loc_x_rotate), int(loc_y_rotate)),
                            foundOrNot=found)

                        for x in range(0, 6):

                            os.system('play -n synth %s sin %s' %
                                      (0.2, frequency))
                            time.sleep(.2)
                        print('\n Trial Ended; Target %s Found' %
                              self._currenttrial)
                        break

                else:
                    check_duration = 0

            if (found == 0):
                print('\n Trial Ended; Time Out')
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime,
                                          robotloc=(int(loc_x_rotate),
                                                    int(loc_y_rotate)),
                                          foundOrNot=2)
                for x in range(0, 12):
                    os.system('play -n synth %s sin %s' %
                              (0.15, (frequency - x * 100)))

            cv2.destroyAllWindows()
            self.updatetrial()  # Trial ended - start of next trial
Esempio n. 21
0
from psychopy import visual, core, event, logging
import numpy as np
import time
import subprocess, sys

# change the logger path as required
logging.console.setLevel(logging.CRITICAL)
# log = logging.LogFile("/media/zfishlab/Data/FlyCapture/stimuli_timing.log", level=logging.CRITICAL,filemode='w')

globalClock = core.MonotonicClock(start_time=0)
logging.setDefaultClock(globalClock)


def write_file(output_name, list_name):
    csvfile = str(output_name)
    with open(csvfile, "w") as output:
        writer = csv.writer(output, lineterminator='\n')
        for n in list_name:
            if isinstance(n, list):
                writer.writerow(n)
            elif isinstance(n, dict):
                writer.writerow([n["x"], n["y"], n["t"]])
            else:
                writer.writerow([n])


# These are the dimensions of the plate.
# DO NOT CHANGE!
width_plate = 620 * 1.56
height_plate = 400 * 1.61
Esempio n. 22
0
]  # create a placeholder for the movie stims created below to be itterated through

###CONSTANTS###

mode = ''  # dummy variable to track program state condition
counting = 0  # set to zero when not counting how long the child has been looking away, and set to one if counting how long child has been looking away
look_away_time = 0  # when child looks away during test phase, get the time, and use it to keep checking if two seconds have passed

stim_start_stim = 0

get_done = 0  # flags the getter as being done or not

data = []  # to hold collected data points
key = pyglet.window.key  # contains constants for key values, e.g. key.SPACE returns 32
win = visual.Window([1366, 768])  # create psychopy window object
clock = core.MonotonicClock(
)  # create sub-ms accurate clock that starts counting up from zero upon creation

info = []  # to hold initial metadata results
stimuli = ''  # to hold current stimuli filename
look_onset = 0.0
click_stim = ''  # to hold stimuli that was playing during click
space_down = 0.0  # create global place holder for clock time that space is pressed
space_time = 0.0  # crea                                  te global place holder for time space was pressed (space_down minus clock time when space is released)

data_root = './data/'  # path to folder to write data
subject = str(
    len([
        filename
        for filename in os.listdir(data_root) if not filename.startswith('.')
    ]) + 1
)  # determine which subject this is by taking the number of data files in the directory (ignoring hidden files with list comprehension), adding one, and converting to string
Esempio n. 23
0
# CLI: command line interface options and main loop

import os, datetime, traceback, glob, time
from psychopy import core, visual, logging, event

visual.window.reportNDroppedFrames = 10e10

TIMEOUT = 5
DELAY_BETWEEN_TASK = 5

globalClock = core.MonotonicClock(0)
logging.setDefaultClock(globalClock)

from . import config  # import first separately
from . import fmri, eyetracking, utils, meg, config
from ..tasks import task_base, video


def listen_shortcuts():
    if any([k[1] & event.MOD_CTRL for k in event._keyBuffer]):
        allKeys = event.getKeys(["n", "c", "q"], modifiers=True)
        ctrl_pressed = any([k[1]["ctrl"] for k in allKeys])
        all_keys_only = [k[0] for k in allKeys]
        if len(allKeys) and ctrl_pressed:
            return all_keys_only[0]
    return False


def run_task_loop(loop, eyetracker=None, gaze_drawer=None, record_movie=False):
    for frameN, _ in enumerate(loop):
        if gaze_drawer:
Esempio n. 24
0
def run_memory(win,
               fi,
               sequence_ori,
               sequence_load,
               sequence_retentionDur,
               sequence_ITI,
               setSize=3,
               dummymode=True):
    num_trial = len(sequence_load)
    win.flip()
    stim = Stimuli(win, timing_memory, dummymode=dummymode)
    stim.mouse = event.Mouse(visible=False)
    #Experiment instructions
    if dummymode:
        stim.text_and_stim_keypress(
            'Welcome to the short-term memory task\n\nPress Enter to continue',
            pos=(0, 0.7))
        stim.text_and_stim_keypress('You will see an array of objects like in the picture below\n\nYou job is to remember the orientation of those in the blue border within 6 seconds'\
                                    ,pos=(0,0.7), image='wm-instruction1.png'    )
        stim.text_and_stim_keypress('The number of items in blue border will change across trials'\
                                    ,pos=(0,0.7), image='wm-instruction1.png'    )
        stim.text_and_stim_keypress('The fixation cross will turn red after 4 second\n\nBut you should not let it distract you'\
                                    ,pos=(0,0.7), image='wm-instruction2.png'    )
        stim.text_and_stim_keypress('After a short delay of blank screen, one of the remembered objects is presented again at the same location but with a new orientation\n\nYou need to rotate it to match the orientation as you remembered'\
                                    ,pos=(0,0.7), image='wm-instruction3.png'    )
        stim.text_and_stim_keypress(
            'Use left button to rotate the item anti-clockwise\n\nand the right button to rotate clockwise\n\nThe trial will begin after you press Enter',
            pos=(0, 0.7),
            stim=stim.ready)

    # construct trials
    triallist = []
    for i in range(num_trial):
        trial = {}
        trial['x1'] = np.random.choice([.4, .5, .6, .7])
        trial['x2'] = np.random.choice([-.4, -.5, -.6, -.7])
        trial['orilist'] = sequence_ori[i]
        trial['load'] = sequence_load[i]
        trial['retention'] = sequence_retentionDur[i]
        triallist.append(trial)
    #shuffle(triallist)
    print(len(triallist))
    runTimer = core.MonotonicClock()
    # Wait for the scanner to start syncing.
    if not dummymode:
        # Present a screen that tells the participant and experimenter to wait
        # while the scanner starts.
        text_stim = visual.TextStim(
            stim.win,
            text=
            "Please wait for the scanner to start...\n\nThis is the short-term memory task",
            font='Helvetica',
            alignHoriz='center',
            alignVert='center',
            units='norm',
            pos=(0, 0.7),
            height=0.08,
            color=[255, 255, 255],
            colorSpace='rgb255',
            wrapWidth=3)
        text_stim.draw()
        stim.win.flip()
        # Wait for the scanner to start its sequence.
        stim.mri.wait_for_sync()
        # Remove the text from the screen.
        stim.win.flip()
        #Create a clock to log time stamps to match imaging datafile
        runTimer = core.MonotonicClock()
        #present a 10s countdown timer (10s=5 TRs, discarded in analysis)
        countdownTimer(stim.win, 10)

    # run trials
    for i, trial in enumerate(triallist):
        try:
            target, targetborder,fixation_onset,stimuli_onset,retention_onset = \
                stim.search_array(trial,condition='memory', load = trial['load'], timer=runTimer)
            # return response, correct ori, probe ori (randomised) and RT, whether mouse click.
            resp_ori, correct_ori, probe_ori, rt, no_click, recall_onset = stim.recall(
                target, targetborder, timer=runTimer)
            if dummymode:
                if no_click == True:
                    stim.text('Timeout', max_wait=0.6)
                else:
                    stim.text('Next trial', max_wait=0.6)
            ITI_onset = runTimer.getTime()
            #make list into a string to write out
            orientations = ','.join(str(e) for e in trial['orilist'])
            if fi is not None:
                fi.writerow([
                    '%s, %.2f, %.2f, %.2f, %.2f, %d, %.2f, %.2f, %s, %d, %.2f, %.2f,%.2f, %.2f,%.2f, %.2f, %.2f'
                    % ('memory', resp_ori, correct_ori, probe_ori, rt * 1000,
                       no_click, trial['x1'], trial['x2'], orientations,
                       trial['load'], trial['retention'] * 1000,
                       sequence_ITI[i] * 1000, fixation_onset, stimuli_onset,
                       retention_onset, recall_onset, ITI_onset)
                ])

            #ITI
            core.wait(sequence_ITI[i])
        except Exception as err:
            traceback.print_exc()
            raise Exception(err)
Esempio n. 25
0
from psychopy import visual, core, event, gui

import pyglet
import os
import random

from preloader import preload

# PSYCHOPY SETUP
# for variables used in all experiments, regardless of design, i.e. can
# likely copy into new experiment
# contains constants for key values, e.g. key.SPACE returns 32
key = pyglet.window.key
win = visual.Window([1366, 768])  # window setup
mode = ''  # dummy variable for state machine like behavior
clock = core.MonotonicClock()
stimuli = {}  # dictionary to populate with stimuli
info = []


def get_metadata():
    global info
    myDlg = gui.Dlg(title="JWP's experiment")
    myDlg.addText('Participant Information')
    myDlg.addField('Name:')
    myDlg.addField('Age:')
    myDlg.addText('Experiment Information')
    myDlg.addField('RA:')
    myDlg.show()
    if myDlg.OK:
        info = myDlg.data
Esempio n. 26
0
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file


# Setup the Window
win = visual.Window(
    size=(960, 400), fullscr=False, allowGUI=False,
    monitor='testMonitor', color=[1,1,1], useFBO=True)

##########Timer##########
globalClock = core.MonotonicClock() # to track the time since experiment started
trialClock = core.Clock() #unlike globalclock, gets reset each trial


##########Instruction##########
Instr_1 = visual.TextStim(win=win, name='Instr_1', color='black',
    text='Please read these instructions carefully before you begin the experiment. Press the spacebar to continue.')

Instr_2 = visual.TextStim(win=win, name='Instr_2', color='black',
    text='In this experiment, you will see a series of face images...Press w if the image shows a female face and o if it shows a male face...Press the spacebar to continue.')

Ending = visual.TextStim(win=win, name='Instr_1', color='black',
    text='Thank you for participating in this study. Press the spacebar to quit.')

##########Stimuli##########
os.chdir(current_working_directory + '/Stimuli_faces')
Esempio n. 27
0
                       port=CONF["pupillometry"]["port"],
                       shouldRecord=CONF["recordEyetracking"])

trigger = Trigger(CONF["trigger"]["serial_device"], CONF["sendTriggers"],
                  CONF["trigger"]["labels"])

screen = Screen(CONF)

datalog = Datalog(OUTPUT_FOLDER=os.path.join(
    'output', CONF["participant"] + "_" + CONF["session"],
    datetime.datetime.now().strftime("%Y-%m-%d")),
                  CONF=CONF)  # This is for saving data

kb = keyboard.Keyboard()

mainClock = core.MonotonicClock()  # starts clock for timestamping events

alarm = sound.Sound(os.path.join('sounds', CONF["instructions"]["alarm"]),
                    stereo=True)

questionnaireReminder = sound.Sound(os.path.join(
    'sounds', CONF["instructions"]["questionnaireReminder"]),
                                    stereo=True)

scorer = Scorer()

logging.info('Initialization completed')

#########################################################################

text_16.text = u'积分可以兑换真实的金钱奖赏。'
text_17.text = u'您将扮演一位公司职员,现在您有一个会议要开,'
text_18.text = u'为了赶时间,你需要乘坐地铁'

text_11.draw()
text_12.draw()
text_13.draw()
text_14.draw()
text_15.draw()
text_16.draw()
text_17.draw()
text_18.draw()
win.flip()
core.wait(0)
k_syn = event.waitKeys()
globaltime = core.MonotonicClock()  # 记录从该语句开始的,绝对不会被重设的时间,用于计算每个界面的开始时间


# 赏金信息
def info_reward():
    global reward
    text_success_reward = visual.TextStim(win,
                                          text=u'',
                                          height=0.1,
                                          pos=(0.7, 0.9),
                                          color='white',
                                          bold=True,
                                          italic=0)
    text_success_reward.text = u'当前赏金:' + str(reward)
    text_success_reward.draw()
Esempio n. 29
0
                    allowGUI=False,
                    allowStencil=False,
                    monitor='testMonitor',
                    color='black',
                    colorSpace='rgb',
                    blendMode='avg',
                    waitBlanking=True,
                    winType='pyglet')
win.recordFrameIntervals = True
frameRate = win.getActualFrameRate()

print(frameRate)

# Initialize Clock
clock = core.StaticPeriod(screenHz=frameRate)
experiment_clock = core.MonotonicClock(start_time=None)

rsvp = CopyPhraseDisplay(win,
                         clock,
                         experiment_clock,
                         marker_writer=NullMarkerWriter(),
                         static_task_text=text_task,
                         static_task_color=color_task,
                         info_text=text_text,
                         info_color=color_text,
                         info_pos=pos_text,
                         info_height=txt_height,
                         info_font=font_text,
                         task_color=['white'],
                         task_font=font_task,
                         task_text='COPY_PH',
Esempio n. 30
0
#-----------------------------------------------------------------------------

#wait for machine start signal
#-----------------------------------------------------------------------------
event.clearEvents()
start_machine = False
print 'waiting for machine start signal'
while start_machine == False:
    for key in event.getKeys():
        if key == globvar.fMRI_start_signal:
            start_machine = True
#-----------------------------------------------------------------------------

#Experiment starts if both start signals are given
#initialize run timer
globvar.experiment_timer.append(core.MonotonicClock())
globvar.sequential_timer.append(0)

#iterate over requested number of blocks and set parameters
#-----------------------------------------------------------------------------
for block, kind in enumerate(blocks):
    j = 0
    i1 = block * globvar.blocks[1]
    i2 = (block + 1) * globvar.blocks[1]
    print>>globvar.output_run_timing, globvar.sequential_timer[-1], \
            'start_block', block, 'of ', globvar.blocks[1], kind, 'trials'

    #-----------------------------------------------------------------------------

    #run the actual trials and record user input
    #-----------------------------------------------------------------------------