예제 #1
0
def write_file(filename):
    for i in range(0, ntrials):
        data.append((i+1, userResponse[i], corrLocation[i]))
    # create data directory
    if not os.path.exists('data'):
        os.makedirs('data')
    with open('data/%s.csv' %(filename), 'w') as fp:
        writer = csv.writer(fp, delimiter=',' )
        writer.writerows(data)
def write_file(filename):

    for i in range(0, ntrials):
        data.append((i + 1, userResponse[i], corrLocation[i], uTargetNums[i],
                     cTargetNums[i]))

    with open('%s.csv' % (filename), 'w') as fp:
        writer = csv.writer(fp, delimiter=',')
        writer.writerows(data)
예제 #3
0
 def concat_wavs(self, infiles, outfile):
     data=[]
     for infile in infiles:
         w = wave.open(infile, 'rb')
         data.append( [w.getparams(), w.readframes(w.getnframes())] )
         w.close()
     output = wave.open(outfile, 'w')
     output.setparams(data[0][0])
     for i in range(len(infiles)):
         output.writeframes(data[i][1])
     output.close()
 def concat_wavs(self, infiles, outfile):
     data = []
     for infile in infiles:
         w = wave.open(infile, "rb")
         data.append([w.getparams(), w.readframes(w.getnframes())])
         w.close()
     output = wave.open(outfile, "w")
     output.setparams(data[0][0])
     for i in range(len(infiles)):
         output.writeframes(data[i][1])
     output.close()
예제 #5
0
 def concat_wavs(infiles, length_between_files):
     data=[]
     for infile in infiles:
         w = wave.open(infile, 'rb')
         data.append( w.readframes(w.getnframes()) )
         if infile != infiles[-1]: data.append( '\x00\x00' * int(w.getframerate()*float(length_between_files)) ) #insert blank space
         w.close()
     outfile = join(self.temp_dir,'temp_stim.wav')
     output = wave.open(outfile, 'w')
     output.setparams(w.getparams())
     for i in range(len(data)):
         output.writeframes(data[i])
     output.close()
     return outfile
예제 #6
0
def write_newRetdata(task, run, trialn, pair, new_pair, lure_pair, cue,
                     correct, intrude, lure, critpos, pmpos, upos, corresp,
                     resp, resp_time, acc, data):
    data = data.append(
        {
            'Task': task,
            'Run': run,
            'Trial Number': trialn,
            'CritPair': pair,
            'SubPair': new_pair,
            'LurePair': lure_pair,
            'Cue': cue,
            'Correct': correct,
            'pmLure': intrude,
            'uLure': lure,
            'CorrPos': critpos,
            'pmPos': pmpos,
            'uPos': upos,
            'CorrResp': corresp,
            'Resp': resp,
            'RT': resp_time,
            'Acc': acc
        },
        ignore_index=True)
    return data
예제 #7
0
 def concat_wavs(infiles, length_between_files):
     data = []
     for infile in infiles:
         w = wave.open(infile, 'rb')
         data.append(w.readframes(w.getnframes()))
         if infile != infiles[-1]:
             data.append(
                 '\x00\x00' *
                 int(w.getframerate() *
                     float(length_between_files)))  #insert blank space
         w.close()
     outfile = join(self.temp_dir, 'temp_stim.wav')
     output = wave.open(outfile, 'w')
     output.setparams(w.getparams())
     for i in range(len(data)):
         output.writeframes(data[i])
     output.close()
     return outfile
예제 #8
0
#draw the stimuli
trial_routine = Routine(window=mywin, frames_per_second=frames_per_second, escape_key=escape_key)

for t in range(n_trials):
    # put here things that change every trial
    changing_gamble.text = 'a sure gain of  CHF %s' % rewards[t]

    # first event
    trial_routine.wait_for_time_limit(
        components=[fixation_cross], 
        time_seconds=fixation_duration, 
        label='fixation_cross')

    # second event
    key, rt = trial_routine.wait_for_keys_or_time_limit(
        components=[fixed_gamble, changing_gamble], 
        valid_keys=choice_keys, 
        time_seconds=choice_time_limit, 
        label='gamble_choice')
    data = data.append({'rt':rt, 'choice': key, 'trial': t, 'reward': rewards[t]}, ignore_index=True) # record the responses

    #save data to file
    for label in expInfo.keys():
        data[label] = expInfo[label]
    data.to_csv(fileName + '.csv')
    
#cleanup
mywin.close()
core.quit()
예제 #9
0
    # first event
    trial_routine.wait_for_time_limit(components=[],
                                      time_seconds=fixation_duration,
                                      label='fixation_cross')

    # second event
    key, rt = trial_routine.wait_for_keys(
        components=[safe_gamble, risky_gamble],
        valid_keys=choice_keys,
        label='gamble_choice')
    data = data.append(
        {
            'rt': rt,
            'choice': key,
            'trial': t,
            'current': value_current,
            'upper': value_upper,
            'lower': value_lower,
            'difference': value_upper - value_lower
        },
        ignore_index=True)  # record the responses

    #save data to file
    for label in expInfo.keys():
        data[label] = expInfo[label]
    data.to_csv(fileName + '.csv')

    # put here things that change at the end of every trial
    if key == choice_keys[0]:
        value_upper = value_current
    elif key == choice_keys[1]:
예제 #10
0
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='norm')

session, phases = 30, 120
R1, R2, score, phase, zeros, ones = 0, 0, 0, 0, 0, 0
lpressed, rpressed = False, False
mouse = Mouse()
stimuli_timer = CountdownTimer(0)
phase_timer = CountdownTimer(0)
global_time = Clock()
p_list = [0.25, 0.75]

data = []  #array for data
data.append(['time', 'R1', 'R2', 'score', 'number', 'zeros', 'ones',
             'p'])  #column names in csv file

#displayed text
text = TextStim(win=win, pos=(0, 0), text=' ')

#defines click boxes
lbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(-0.3, -0.6))

rbox = Rect(win=win,
            width=0.3,
            height=0.3,
예제 #11
0
            trialTime=trialClock.getTime()
            # update the image list to be shown based on the fetched parameter
            imagePaths=imageLists[parameter] #list(imageLists[parameter])
            # calculated how long each image should last.
            eachTime=ParameterUpdateDuration/len(imagePaths)
            # update the image
#             image.image=imagePaths[0]
            image.setAutoDraw(False)
            imagePaths[0].setAutoDraw(True)
            # currImage*eachTime is used in the calculation of the start time of next image in the list.
            
            # save when the image is presented and which image is presented.
            data = data.append({'Sub': IDnum, 
                                'Run': run, 
                                'TR': TR[0],
                                'time': trialTime, 
                                'imageTime':imagePaths[0].image,
                                'eachTime':eachTime},
                               ignore_index=True)
            oldMorphParameter=re.findall(r"_\w+_",imagePaths[0].image)[1]
            print('curr morph=',oldMorphParameter)
            remainImageNumber.append(0)
            currImage=1
            # # discard the first image since it has been used.
            # imagePaths.pop(0)
    if (states[0] == 'feedback') and (trialTime>currImage*eachTime):
            # image.image=imagePaths[0]
            try: # sometimes the trialTime accidentally surpasses the maximum time, in this case just do nothing, pass
                imagePaths[currImage-1].setAutoDraw(False)
                imagePaths[currImage].setAutoDraw(True)
                # print('currImage=',imagePaths[currImage],end='\n\n')
예제 #12
0
        mywin.close()
        core.quit()

    if '5' in keys:
        # print(globalClock.getTime())
        trigger_counter += 1  # if there's a trigger, increment the trigger counter
        if len(onsets) != 0:
            # write the data!
            data = data.append(
                {
                    'Sub': sub,
                    'Run': run,
                    'TR': trigger_counter - 1,
                    'Onset': time_list[0],
                    'Item': trials[0],
                    'Change': changes[0],
                    'Resp': resp,
                    'RT': resp_time,
                    'image_on': image_on,
                    'button_on': button_on,
                    'button_off': button_off
                },
                ignore_index=True)
            # pop out all first items, and reset responses, because they correspond to the trial that already happened
            trials.pop(0)  # ['', '', '', '', 'A', '', 'D', '', 'C',...]
            onsets.pop(
                0
            )  # ['blank', 'blank', 'blank', 'blank', 'stim', 'blank', 'stim', 'blank', 'stim', 'blank', 'blank', 'stim', 'blank', 'stim', 'blank',...]
            time_list.pop(
                0
            )  # [0.0, 1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5, 15.0, 16.5, 18.0,...]
예제 #13
0
global_time = Clock()
#timers for the schedule of reinforcement
T1, T2 = CountdownTimer(0), CountdownTimer(0)
phase_timer = CountdownTimer(0)
#tracks responses
lpressed, rpressed = False, False
mouse = Mouse()
R1, n1 = 0, 0  #tracks responses from left and prevents changeovers
R2, n2 = 0, 0  #tracks responses from right
#tracks consequences
Rf1, Rf2, score = 0, 0, 0
#tracks experiment
phase = 0  #how many different conditions introduced

data = []  #array for data
data.append(['time', 'R1', 'R2', 'Rf1', 'Rf2', 'phase',
             'schedule'])  #column names in csv file

#displayed text
text = TextStim(win=win, pos=(0, 0), text=' ')

#defines click boxes
lbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(-0.5, -0.6))
rbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
예제 #14
0
  #  trials.saveAsWideText('test.csv', delim=',', appendFile=True)
   # rating = []
   # myItem = visual.SimpleImageStim(win=myWin, image= os.path.join(im_dir,thisTrial), units='pix', pos=[0, y/9])
data=[]
for image in imageList: 
    x,y = myRatingScale.win.size
    myItem = visual.ImageStim(win=myWin, image= os.path.join(im_dir,image), units='pix', pos=[0, y/9], size=(im_size))
    
    # rate each image on two dimensions
    for dimension in ['0=totalement inconnu..........10=tres familier', '0= extremement douloureux.........10=pas du tout douloureux']:
        myRatingScale.reset() # needed between repeated uses of the same rating scale
        myRatingScale.setDescription(dimension) # reset the instructions for this rating
        event.clearEvents()
        while myRatingScale.noResponse:
            myItem.draw()
            myRatingScale.draw()
            myWin.flip()
       
       # trials.addData('Image', thisTrial)
       # trials.addData('Condition', myRatingScale.scaleDescription.text)
       # trials.addData('Rating',myRatingScale.getRating())
       # trials.addData('RT', myRatingScale.getRT())
        data.append([image, myRatingScale.scaleDescription.text, myRatingScale.getRating(), myRatingScale.getRT()]) # save for later
        # clear the screen & pause between ratings
        myWin.flip()
        core.wait(0.35) # brief pause, slightly smoother for the subject
        #trials.next()
for d in data:
    print '  ',d
myWin.close()
예제 #15
0
            message = too_slow_message
        elif key == correct_resp_trial: # if the correct response was given
            accuracy_trial = 1
            message = correct_message
        else: # if the incorrect response was given
            accuracy_trial = 0
            message = incorrect_message
        
        if bl == 0: # only give a message in the learning block
            trial_routine.wait_for_time_limit(
                components=[message], 
                time_seconds=messages_duration, 
                label='choice_feedback')

        data = data.append(
            {'trial':int(t+1), 'rt':rt, 'choice':key, 'accuracy':accuracy_trial, 'image':image_trial, 'block':['learning', 'transfer'][bl],
             'difficulty':block['difficulty'][t], 'correct_response':correct_resp_trial, 'category':block['category'][t]},
            ignore_index=True) # record the responses

        #save data to file
        for label in expInfo.keys():
            data[label] = expInfo[label]
        data.to_csv(fileName + '.csv')

# final message with accuracy feedback
accuracy_learning = int(data.loc[data.block == 'learning', 'accuracy'].mean()*100)
accuracy_transfer = int(data.loc[data.block == 'transfer', 'accuracy'].mean()*100)

end_transfer_message.text = "Congratulations, you finished the experiment. You accuracy was {}% in the learning part and {}% in the test.".format(accuracy_learning, accuracy_transfer)
trial_routine.wait_for_time_limit(
        components=[end_transfer_message], 
        time_seconds=message_beginning_duration, 
phase_timer = CountdownTimer(0)
link_timer = CountdownTimer(0)
#tracks responses
lpressed, rpressed, cpressed = False, False, False
mouse = Mouse()
R1, n1 = 0, 0  #tracks responses from left and prevents changeovers
R2, n2 = 0, 0  #tracks responses from right
R3 = 0  #tracks responses from center
#tracks consequences
Cs1, Cs2, Cs3, score = 0, 0, 0, 500
#tracks experiment
phase = 0  #how many different conditions introduced

data = []  #array for data
data.append([
    'time', 'R1', 'n1', 'Cs1', 'R2', 'n2', 'Cs2', 'R3', 'Cs3', 'score',
    'phase', 'schedule'
])  #column names in csv file

#displayed text
text = TextStim(win=win, pos=(0, 0), text=' ')

#defines click boxes
lbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(-0.5, -0.6))

rbox = Rect(win=win,
            width=0.3,
예제 #17
0
    # first event
    trial_routine.wait_for_time_limit(components=[fixation_cross],
                                      time_seconds=fixation_duration,
                                      label='fixation_cross')

    # second event
    key, rt = trial_routine.wait_for_keys_or_time_limit(
        components=[A_picture, B_picture],
        valid_keys=choice_keys,
        time_seconds=choice_time_limit,
        label='choice')
    data = data.append(
        {
            'rt': rt,
            'choice': key,
            'trial': t,
            'f_A': A_feedback_trials[t],
            'f_B': B_feedback_trials[t]
        },
        ignore_index=True)  # record the responses

    if key == 'q':
        # third event
        trial_routine.wait_for_time_limit(components=[B_feedback],
                                          time_seconds=feedback_duration,
                                          label='feedback')
    else:
        # third event
        trial_routine.wait_for_time_limit(components=[A_feedback],
                                          time_seconds=feedback_duration,
                                          label='feedback')
    response = psychopy.event.waitKeys(
    )  # you probably have event.waitKeys(keyList=['space']) or something like that right now
    print('after response')
    print(response)
    if 'left' in response:
        left = True
        right = False
        break  # break out of the while-loop
    if 'right' in response:
        right = True
        left = False
        break  # break out of the while-loop

for trial in range(10):  # 10 trails now, how many do we want?

    data.append([random.uniform(0, 180), random.choice(["left", "right"])])

pprint.pprint(data)

coded_data = []

for data_row in data:

    if data_row[1] == "left":
        data_row[1] = 1
    elif data_row[1] == "right":
        data_row[1] = 2

    coded_data.append(data_row)

pprint.pprint(coded_data)
예제 #19
0
    trial_routine.wait_for_time_limit(components=[fixation_cross],
                                      time_seconds=fixation_duration,
                                      label='fixation_cross')

    # second event
    key, rt = trial_routine.wait_for_keys_or_time_limit(
        components=[left_picture, right_picture],
        valid_keys=choice_keys,
        time_seconds=choice_time_limit,
        label='gamble_choice')
    data = data.append(
        {
            'rt': rt,
            'choice': key,
            'trial': t,
            'f_right': stimuli.loc[t, 'right_feedback'],
            'f_left': stimuli.loc[t, 'left_feedback'],
            'i_right': stimuli.loc[t, 'right_image'],
            'i_left': stimuli.loc[t, 'left_image'],
            'trial_type': stimuli.loc[t, 'trial_type'],
        },
        ignore_index=True)  # record the responses

    # third event
    trial_routine.wait_for_time_limit(
        components=[left_feedback, right_feedback],
        time_seconds=feedback_duration,
        label='feedback')

    #save data to file
    for label in expInfo.keys():
        data[label] = expInfo[label]
    elif Block == 3:  #joint block
        instruction_E.draw()
        instruction_J.draw()
        win.flip()
        keys_G = p.event.waitKeys(keyList=["return", "escape"])
        print keys_G
        if keys_G[0] == "escape":
            win.close()
            core.quit()
    #beep/flash combinations
    option = [1, 2, 3, 4, 5, 6, 7, 8, 9
              ] * 2  #multiply my 1/9 number of trials desired
    random.shuffle(option)
    for t in range(2):  #number of trials per condition
        data = []
        data.append(SUB)
        data.append(Block)
        print "Trial number =", Trial
        data.append(Trial)

        for i in range(1):
            #choose random combination
            core.wait(1)
            optionNum = option[0]
            print "optionNum = ", optionNum

            #1B 1F
            if optionNum == 1:
                callsound()
                soa()
                flash()
예제 #21
0
count = 0
value = 0
#count consequences
score = []  #local counter
rws = 0
pns = 0
#count phases
phase = 0
condition = []
instruction = []
i = 0
k = 1
#array for data
data = []
data.append([
    'time', 'responses', 'rewards', 'penalties', 'score', 'phase', 'feedback',
    'instruction'
])

#control over experiment flow
#'q' - proceed to next phase
#'escape' - close window (with data saving and record about stopping)

while global_time.getTime() < session * 60 and k <= len(instruction_list):
    resp_key = event.getKeys(keyList=['e', 'q',
                                      'escape'])  #check of keyboard input

    #proceed to next phase if 'q' is pressed or timer expires
    if 'q' in resp_key or phase_timer.getTime() < 0:
        if randomization == True:
            #picks new schedule randomly
            feedback = random.choice(feedback_list)