temporal_combi_list=combi.combination_for_run()
    Trial_times=[4 for i in xrange(len(temporal_combi_list))]

    Instructions = visual.TextStim(win=win, ori=0, name='Next_Scan_Ready', \
        text=u'Bitte machen Sie sich bereit für einen nächsten Scan',    font='Arial', \
        units='deg', pos=[0, 0],alignHoriz='center',height=0.4,  wrapWidth=12,bold=True, \
        color='white', colorSpace='rgb', opacity=1)
    Instructions.draw()
    win.flip()

    #wait for trigger and sychronize
    event.waitKeys(maxWait=6400, keyList=['t'], timeStamped=True)
    logging.flush()

    Run_clock = core.Clock()
    logging.setDefaultClock(Run_clock)


    logFile.write("\nTemporal_Combi:  %s \n" %str(temporal_combi_list))
    logFile.write("\nTrial_times_with_jitter:  %s \n" %str(Trial_times))
    start_run=Run_clock.getTime()
    logging.exp("Start of Experimental Run: "+str(exp_runN))

    intervals_of_landolt=range(len(temporal_combi_list))

    #inside one experimental run -> execute trials
    for trialN in range(len(temporal_combi_list)):
        start_trial=Run_clock.getTime()
        [l, r]=temporal_combi_list[trialN]

Exemplo n.º 2
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()
Exemplo n.º 3
0
                                lineColor='black',
                                lineWidth=3)
Instr_Rest_Crosshair = visual.ShapeStim(win,
                                        lineColor='#000000',
                                        lineWidth=3.0,
                                        vertices=((-30, -90), (30, -90),
                                                  (0, -90), (0, -60), (0,
                                                                       -120)),
                                        units='pix',
                                        closeShape=False)

# SETTING GENERAL CLOCK AND LOGGING
# =========================================
clock = core.Clock()
logging.setDefaultClock(
    clock
)  #use this for timing of log messages, although these shouldn't be used for experimental events
logging.console.setLevel(
    logging.DATA)  #set the console to receive nearly all messges
Logger = logging.LogFile(LogFileName, logging.DATA, 'w')
win.setRecordFrameIntervals(True)
#capture frame intervals
win.saveFrameIntervals(fileName=LogFileName, clear=False)
#write frame intervals to LogFileName

# (0) PRINT FIRST SET OF INSTRUCTIONS AND WAIT FOR TRIGGER
# ==================================================================
win.logOnFlip('INITIAL INSTRUCTIONS', logging.DATA)

Instr_Rest_S.draw()
win.flip()
csid = ''
if len(argv) > 1:
    csid = argv[1]

ID = gui.Dlg(title='subj ID')
ID.addField('ID (change if subject ID is incorrect): ', csid)
subID = ID.show()

#create csv file for log
filename = logdir + '/' + subID[0] + '_learning_bach_iEEG_custom.csv'
logfile = open(filename, 'w')
logfile.write("subj;trial;trigger;response;RT;time \n")

#create log file
block_time = core.Clock()
logging.setDefaultClock(block_time)
filename2 = logdir + '/' + subID[0] + '_learning_bach_iEEG_default.log'
lastLog = logging.LogFile(filename2, level=logging.INFO, filemode='a')

#getting file for learning phase
os.chdir(stimdir + '/learningdef')
Bachminor = sound.Sound('Bachminorprelude.wav')

#getting files for recognition phase
os.chdir(stimdir + '/recogdef')
pathwave = stimdir + '/recogdef'
wavefilesd = []
wavenamesd = []
for file in sorted(os.listdir(pathwave)):
    if file.endswith(".wav"):
        wavenamesd.append(file)
Exemplo n.º 5
0

# BIDS TEMPLATE
logbids("onset\tduration\tstim_type\tstim_fn")
template_bids = '{onset:.3f}\t{duration:.3f}\t{stim_type}\t{stim_fn}'

# Set up all the relevant directories here
HERE = abspath(dirname(__file__))
STIMDIR = join(HERE, "stim")
CSVDIR = join(HERE, "runs")
RESDIR = join(HERE, "res")
if not exists(RESDIR):
    makedirs(RESDIR)

# Set up PsychoPy's logging function
logging.setDefaultClock(run_clock)
log = logging.LogFile(f=join(
    "res", 'log_p{:02d}_r{:02d}.txt'.format(int(participant), int(run))),
                      level=logging.INFO,
                      filemode='w')

# Load in events / trial order
trials_file = join(
    CSVDIR, 'Sub{:02d}_Run{:02d}.csv'.format(int(participant), int(run)))
trials = pd.read_csv(trials_file)
assert trials.shape[0] == 57

# Open window and wait for first scanner trigger

# # for scanner projector
# win = visual.Window([1280,960], screen=0, fullscr=True, color=(128,128,128),
Exemplo n.º 6
0
#trials.data.addDataType('stimOnset')

#---------------------------------------
# Create timers
#---------------------------------------
trialClock = core.Clock() 
expeClock = core.Clock()  # to track the time since experiment started

#---------------------------------------
# Setup files for logfile  saving
#---------------------------------------

if not os.path.isdir('Logdata'):
	os.makedirs('Logdata')  # if this fails (e.g. permissions) we will get error
filename = 'Logdata' + os.path.sep + '%s_%s' %(expInfo['participant'], expInfo['session'])
logging.setDefaultClock(trialClock)
logFileExp = logging.LogFile(filename +'.log', level=logging.EXP)
logging.console.setLevel(logging.DEBUG)  # this outputs to the screen, not a file

#writer = csvWriter(expInfo['participant'] + '_' + expInfo['session'], 'data')
saveFilePrefix = expInfo['participant'] + '_' + expInfo['session']

saveFile = "data/" + str(saveFilePrefix) + ' (' + time.strftime('%Y-%m-%d %H-%M-%S', time.localtime()) +').csv'  # Filename for csv. E.g. "myFolder/subj1_cond2 (2013-12-28 09-53-04).csv"

headerWritten = False
with open(saveFile, 'wb') as trialsFile:

    #---------------------------------------
    # Setup Window
    #---------------------------------------
Exemplo n.º 7
0
that the log file (or console) is set to receive. You can have multiple log files each receiving 
different levels of input.

The importance levels are;
    40:ERROR
    35:DATA
    30:WARNING
    25:DATA
    22: EXP
    20:INFO
    10:DEBUG
So setting to DEBUG level will include all possible messages, setting to ERROR will include only the absolutely essential messages.

"""
globalClock = core.Clock()#if this isn't provided the log times will reflect secs since python started
logging.setDefaultClock(globalClock)#use this for

logging.console.setLevel(logging.DEBUG)#set the console to receive nearly all messages
logDat = logging.LogFile('logLastRun.log',
    filemode='w',#if you set this to 'a' it will append instead of overwriting
    level=logging.WARNING)#errors, data and warnings will be sent to this logfile

#the following will go to any files with the appropriate minimum level set
logging.info('Something fairly unimportant')
logging.data('Something about our data. Data is likely very important!')
logging.warning('Handy while building your experiment - highlights possible flaws in code/design')
logging.error("You might have done something that PsychoPy can't handle! But hopefully this gives you some idea what.")

#some things should be logged timestamped on the next video frame
#For instance the time of a stimulus appearing is related to the flip:
win = visual.Window([400,400])
#myDlg.addField('Choose monitor', choices=["1", "2"])

myDlg.show()  # show dialog and wait for OK or Cancel

if myDlg.OK:  # then the user pressed OK
    confInfo = myDlg.data
    if DEBUG:
        print confInfo
else:
    if DEBUG:
        print 'user cancelled'
    core.quit()

# SETUP LOGGING & CLOCKING
testClock = core.Clock()
logging.setDefaultClock( testClock )

myLogLevel = logging.CRITICAL + 1
logging.addLevel( myLogLevel, '' )
myLog = logging.LogFile( '.'+s+'logs'+s+''+confInfo[0] +'.log', filemode='w', level=myLogLevel, encoding='utf8')

logThis('Subj ID: ' + confInfo[0] )
logThis('Run: ' + str(datetime.utcnow()) )
logThis('Age: ' + str(confInfo[1]) )
logThis('Group: ' + confInfo[2])
logThis('Config: ' + confInfo[3])

logThis('--------------------------------------------------------')
logThis('INFO')
logThis('timestamp1 CUE [block] [trial] CUE')
logThis('timestamp1 STM [block] [trial] STIMULUS[state for each rule G1 G2 L1 L2 : 0,1,2,3]RULE[current rule]')
Exemplo n.º 9
0
                        'Ahora tome una pequeña pausa y presione barra espaciadora para continuar.',
                color=txt_color, wrapWidth=1.8)

end_txt = visual.TextStim(win, 
                text = 'Este es el final del experimento.\n'
                        'Gracias por participar!',
                color=txt_color, wrapWidth=1.8)

trialtxt = visual.TextStim(win, text='',color=txt_color, height=0.1)

#set clocks
RT = core.Clock()
exp_time = core.Clock()

# set default log file
logging.setDefaultClock(exp_time)
log_fn_def = 'logs/' + sub_id[0] +  '_default_spanish.log'
lastLog = logging.LogFile(log_fn_def, level=logging.INFO, filemode='a')

# set custom log file
log_fn_cus = 'logs/' + sub_id[0] +  '_custom_spanish.csv'
logfile = open(log_fn_cus,'w')
logfile.write("subject,trialCode,code,number,name,rhythm,harmony,"
              "condition,block,startTime,response,rt,trigger\n")

# make function to loop over trials and present the stimuli
def block_run(s_dict, s_order, b_sounds, breaks=[]):
    """
    s_dict: dictionary containing the stimulus list and metadata, as loaded 
            from a csv file. Must contain the lists:
Exemplo n.º 10
0
def empathyp(expe):
    #---------------------------------------
    # Set Variables
    #---------------------------------------

    TRIALS_FILE = 'run1.csv'  # run2
    PAUSE = 30  # Time to pause for hypnosis reinforcement
    STIM_SIZE = 0.5, 0.5
    BACKGROUND_COLOR = [1, 1, 1]

    stimDuration = 2.5

    start_expe = 0
    #---------------------------------------
    # Set Keys for responses and expe flow
    #---------------------------------------

    if expe == 'behav':
        is_fmri = 0

        keyInd = ['space']  # for induction picture
        keyGo = ['up', 'none']  # response to go stimuli
        keyPass = ['space']  # for passing screens

    elif expe == 'fmri':
        is_fmri = 1

        keyPause = ['space']  # for induction picture
        keyGo = ['4', 'none']  # response to go stimuli
        keyPass = ['1']  # for passing screens
    else:
        print('Experience type can be behav or fmri only ')

#---------------------------------------
# Set up parallel port for eye tracker
#---------------------------------------

#parallel.setPortAddress(0x0378) #may need to be changed
#pinNumber = 3
#parallel.setData(0)

#---------------------------------------
# Create timers
#---------------------------------------
    globalClock = core.Clock()  # to track the time since experiment started
    respTime = core.Clock()
    trialClock = core.Clock()
    #countDown= core.CountdownTimer()  # to track time remaining of each (non-slip) routine

    #---------------------------------------
    # Store info about the experiment session
    #---------------------------------------

    expName = 'Empathyp'
    expInfo = {'participant': '', 'session': ''}
    dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
    if dlg.OK == False: core.quit()  # user pressed cancel
    expInfo['date'] = data.getDateStr()  # add a simple timestamp
    expInfo['expName'] = expName

    # Experiment handler
    thisExp = data.ExperimentHandler(
        name=expName,
        version='',
        extraInfo=expInfo,
        runtimeInfo=None,
        originPath=None,
        savePickle=False,
        saveWideText=False
    )  #prevent the experiment handler to write expe data upon termination (and overwriting our files)

    #---------------------------------------
    # Load trial files
    #---------------------------------------

    # read from csv file
    trialList = data.importConditions(TRIALS_FILE, returnFieldNames=False)
    trials = data.TrialHandler(trialList,
                               nReps=1,
                               method='sequential',
                               extraInfo=expInfo)
    trials.data.addDataType('respKey')
    trials.data.addDataType('respTime')
    trials.data.addDataType('stimOnset')
    trials.data.addDataType('scanOnset')
    #---------------------------------------
    # Setup files for logfile  saving
    #---------------------------------------

    if not os.path.isdir('Logdata'):
        os.makedirs(
            'Logdata')  # if this fails (e.g. permissions) we will get error
    filename = 'Logdata' + os.path.sep + '%s_%s' % (expInfo['participant'],
                                                    expInfo['date'])
    logging.setDefaultClock(globalClock)
    logFileExp = logging.LogFile(filename + '.log', level=logging.EXP)
    logging.console.setLevel(
        logging.INFO)  # this outputs to the screen, not a file

    #---------------------------------------
    # Setup the Window
    #---------------------------------------
    win = visual.Window([1280, 1024],
                        color=BACKGROUND_COLOR,
                        monitor='testMonitor',
                        units='height',
                        fullscr=False,
                        colorSpace='rgb')

    #---------------------------------------
    # Setup Paths to read files
    #---------------------------------------

    im_dir = 'Stimuli'

    #---------------------------------------
    # Setup instructions
    #---------------------------------------
    #instrPracticeClock = core.Clock()
    instruct1 = visual.TextStim(
        win=win,
        ori=0,
        name='instruct1',
        text=
        "Consignes : \n\n Pressez le bouton 4 uniquement lorsque l'image est celle d'une main gauche. \n\n Ne pressez pas le bouton lorsque l'image est une image de main droite. Appuyer sur le 1 pour continuer.",
        font='Arial',
        pos=[0, 0],
        height=0.04,
        wrapWidth=None,
        color='black',
        colorSpace='rgb',
        opacity=1.0,
        depth=0.0)

    #---------------------------------------
    # Setup end message
    #---------------------------------------
    #instrPracticeClock = core.Clock()
    theEnd = visual.TextStim(
        win=win,
        ori=0,
        name='theEnd',
        text="Fin de l'experience, merci de votre participation !",
        font='Arial',
        pos=[0, 0],
        height=0.04,
        wrapWidth=None,
        color='black',
        colorSpace='rgb',
        opacity=1,
        depth=0.0)

    pause = visual.TextStim(win=win,
                            ori=0,
                            name='pause',
                            text="Vous pouvez faire une pause",
                            font='Arial',
                            pos=[0, 0],
                            height=0.04,
                            wrapWidth=None,
                            color='black',
                            colorSpace='rgb',
                            opacity=1,
                            depth=0.0)

    pause2 = visual.TextStim(win=win,
                             ori=0,
                             name='pause',
                             text="Fin de la premiere partie",
                             font='Arial',
                             pos=[0, 0],
                             height=0.04,
                             wrapWidth=None,
                             color='black',
                             colorSpace='rgb',
                             opacity=1,
                             depth=0.0)

    #---------------------------------------
    # Setup Fixation cross and circle
    #---------------------------------------

    fixation_cross = visual.TextStim(win=win,
                                     ori=0,
                                     name='fixation_cross',
                                     text='+',
                                     font='Arial',
                                     pos=[0, 0],
                                     height=0.06,
                                     color='black')
    fixation_cross.setLineWidth = 0.4

    if is_fmri == 1:

        #---------------------------------------
        # Settings for launch scan
        #---------------------------------------

        MR_settings = {
            'TR': 2.000,  # duration (sec) per volume
            'volumes': 5,  # number of whole-brain 3D volumes/frames
            'sync':
            '5',  # character used as sync timing event; assumed to come at start of a volume
            'skip':
            5,  # number of volumes lacking a sync pulse at start of scan (for T1 stabilization)
            'sound': False  # True: in test mode only
        }

        #infoDlg = gui.DlgFromDict(MR_settings, title='FMRI parameters', order=['TR', 'volumes'])
        #if not infoDlg.OK: core.quit()

        globalClock = core.Clock()
        mode = 'Scan'

        #summary of run timing for each key press:
        output = 'vol onset key\n'

        for i in range(-1 * MR_settings['skip'], 0):
            output += '%d prescan skip (no sync)\n' % i

        key_code = MR_settings['sync']
        counter = visual.TextStim(win,
                                  height=.05,
                                  pos=(0, 0),
                                  color=win.rgb + 0.5)
        output += "00.000 %s start of scanning run, vol 0\n" % key_code
        pause_during_delay = (MR_settings['TR'] > .4)
        sync_now = False

        # can simulate user responses, here 3 key presses in order 'a', 'b', 'c' (they get sorted by time):
        simResponses = [(0.123, 'a'), (4.789, 'c'), (2.456, 'b')]

        #---------------------------------------
        # launch scanner
        # operator selects Scan or Test
        #---------------------------------------
        vol = launchScan(win,
                         MR_settings,
                         globalClock=globalClock,
                         simResponses=simResponses)

        infer_missed_sync = False  # best no to use it but might be useful
        max_slippage = 0.02  # how long to afford before treating a slow sync as missed

        duration = MR_settings['volumes'] * MR_settings['TR']
        # globalClock has been reset to 0 by launchScan()

        while globalClock.getTime() < duration:
            allKeys = event.getKeys()
            for key in allKeys:
                if key != MR_settings['sync']:
                    output += "%3d %7.3f %s\n" % (
                        vol - 1, globalClock.getTime(), str(key))
            if 'escape' in allKeys:
                output += 'user cancel,'
                break
            #detect sync or infer it shoul have happened:
            if MR_settings['sync'] in allKeys:
                sync_now = key_code  #flag
                onset = globalClock.getTime()
            if infer_missed_sync:
                expected_onset = vol * MR_setting['TR']
                now = globalClock.getTime()
                if now > expected_onset + max_slippage:
                    sync_now = '(inferred onset)'  # flag
                    onset = expected_onset
            if sync_now:
                start_expe = 1
        else:
            start_expe = 1

        if start_expe == 1:

            #--------------------------------------
            # Show Instructions
            #--------------------------------------
            instruct1.draw(win)
            win.flip()
            event.waitKeys(keyList=keyPass)

            trialStart = 0

            #--------------------------------------
            # START EXPERIMENT
            #--------------------------------------
            fixation_cross.draw()
            win.flip()
            core.wait(1)

            win.setRecordFrameIntervals(True)  # frame time tracking
            globalClock.reset()

            trialStart = 1
        if trialStart == 1:

            t = 0
            frameN = -1
            nDone = 0

            #--------------------------------------
            # Run Trials
            #--------------------------------------
            for thisTrial in trials:

                # save data for the trial loop using psychopy function
                trials.saveAsWideText(filename + '.csv',
                                      delim=',',
                                      appendFile=False)
                trials.addData('scanOnset', onset)
                thisResp = []  # to store resp key and resp time
                #   parallel.setData(0) # sets all pins to low

                #--------------------------------------
                # Load stimuli image and set trials
                # variables
                #--------------------------------------
                if thisTrial['Stim'] != 'pause' and thisTrial[
                        'Stim'] != 'blank':
                    stim = visual.ImageStim(win,
                                            image=os.path.join(
                                                im_dir, thisTrial['Stim']),
                                            size=(STIM_SIZE))
                    stimOnset = trialClock.getTime()
                    #--------------------------------------
                    # Display trials
                    #--------------------------------------
                    #if thisTrial['Stim'] != 'blank' and thisTrial['Stim'] != 'pause': # case trial is stimuli

                    while trialClock.getTime() < stimOnset + stimDuration:
                        fixation_cross.draw()
                        stim.draw()
                        win.flip()
                        #	parallel.setPin(pinNumber, 1) # sets pinNumber (variable defined at the beginning) to be high
                        thisResp = getResponse(
                            keyGo, stimDuration)  # evaluate response
                elif thisTrial['Stim'] == 'blank':  # case trial is blank trial
                    fixation_cross.draw()
                    win.flip()
                    stimOnset = trialClock.getTime()
                    thisResp = getResponse(keyGo,
                                           stimDuration)  # evaluate response
                    core.wait(5)
                elif thisTrial[
                        'Stim'] == 'pause':  # case pause for hypnosis reinforcement
                    pause.draw()
                    win.flip()
                    #core.wait(PAUSE)
                    event.waitKeys(keyList=keyPause)
                    fixation_cross.draw()
                    win.flip()
                    core.wait(0.5)

                fixation_cross.draw()
                win.flip()
                #parallel.setData(0)
                core.wait(thisTrial['ITI'])
                nDone += 1

                #		if(thisRespKeys == thisTrial['corrAns']) or (thisRespKeys == [] and thisTrial['corrAns'] =='n') :
                #			respCorr = 1 # lookup response for go and no go trials
                #		else: respCorr = 0

                #--------------------------------------
                # store trial data
                #--------------------------------------
                if len(thisResp) > 0:
                    trials.addData('respKey', thisResp[0])
                    trials.addData('respTime', thisResp[1])
#			trials.addData('respCorr', respCorr)
                trials.addData('stimOnset', stimOnset)

                thisExp.nextEntry()
                # get names of stimulus parameters
                if trials.trialList in ([], [None], None): params = []
                else: params = trials.trialList[0].keys()

                if event.getKeys(['q', ' escape']):
                    win.close()
                    core.quit()

#--------------------------------------
# End Experiment
#--------------------------------------
            core.wait(1)
            win.flip()
            if thisTrial['Run'] == 1 or thisTrial['Run'] == 3:
                pause.draw(win)
                win.flip()
                event.waitKeys('space')
            elif thisTrial['Run'] == 2:
                pause2.draw(win)
                win.flip()
                event.waitKeys('space')
            else:
                theEnd.draw(win)
                win.flip()
                event.waitKeys('space')

            if is_fmri == 1:
                sync_now = False
                output += "end of scan (vol 0..%d= %d of %s). duration = %7.3f" % (
                    vol - 1, vol, MR_settings['volumes'],
                    globalClock.getTime())
                logging.info(output)

        event.waitKeys('space')
        win.close()
        core.quit()
Exemplo n.º 11
0
def empathyp(expe):
	#---------------------------------------
	# Set Variables
	#---------------------------------------

    TRIALS_FILE = 'run1.csv' # run2
    PAUSE = 30 # Time to pause for hypnosis reinforcement
    STIM_SIZE = 0.5, 0.5 
    BACKGROUND_COLOR = [1,1,1]
	
    stimDuration = 2.5
	
    start_expe = 0
	#---------------------------------------
	# Set Keys for responses and expe flow
	#---------------------------------------

    if expe == 'behav':
		is_fmri = 0
	
		keyInd = ['space'] # for induction picture
		keyGo = ['up', 'none'] # response to go stimuli
		keyPass = ['space'] # for passing screens
	
    elif expe == 'fmri':
		is_fmri = 1

		keyPause = ['space'] # for induction picture
		keyGo = ['4', 'none'] # response to go stimuli
		keyPass = ['1'] # for passing screens
    else:
		print('Experience type can be behav or fmri only ')

	#---------------------------------------
	# Set up parallel port for eye tracker
	#---------------------------------------
	
	#parallel.setPortAddress(0x0378) #may need to be changed
	#pinNumber = 3
	#parallel.setData(0) 


		
	#---------------------------------------
	# Create timers
	#---------------------------------------
    globalClock = core.Clock()  # to track the time since experiment started
    respTime = core.Clock()
    trialClock = core.Clock()
	#countDown= core.CountdownTimer()  # to track time remaining of each (non-slip) routine 

	#---------------------------------------
	# Store info about the experiment session
	#---------------------------------------

    expName = 'Empathyp'  
    expInfo = {'participant':'', 'session': ''}
    dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
    if dlg.OK == False: core.quit()  # user pressed cancel  
    expInfo['date'] = data.getDateStr()  # add a simple timestamp  
    expInfo['expName'] = expName

	# Experiment handler
    thisExp = data.ExperimentHandler(name=expName, version='',
	    extraInfo=expInfo, runtimeInfo=None,
	    originPath=None,
	    savePickle=False, saveWideText=False) #prevent the experiment handler to write expe data upon termination (and overwriting our files)
	


	#---------------------------------------
	# Load trial files 
	#---------------------------------------

	# read from csv file
    trialList = data.importConditions(TRIALS_FILE, returnFieldNames=False)
    trials = data.TrialHandler(trialList, nReps=1, method='sequential', extraInfo=expInfo)
    trials.data.addDataType('respKey')
    trials.data.addDataType('respTime')
    trials.data.addDataType('stimOnset')
    trials.data.addDataType('scanOnset')
    #---------------------------------------
	# Setup files for logfile  saving
	#---------------------------------------

    if not os.path.isdir('Logdata'):
        os.makedirs('Logdata')  # if this fails (e.g. permissions) we will get error
    filename = 'Logdata' + os.path.sep + '%s_%s' %(expInfo['participant'], expInfo['date'])
    logging.setDefaultClock(globalClock)
    logFileExp = logging.LogFile(filename +'.log', level=logging.EXP)
    logging.console.setLevel(logging.INFO)  # this outputs to the screen, not a file


	#---------------------------------------
	# Setup the Window
	#---------------------------------------
    win = visual.Window([1280,1024],color = BACKGROUND_COLOR,monitor ='testMonitor',  units='height',
    fullscr = False, colorSpace = 'rgb')

	#---------------------------------------
	# Setup Paths to read files
	#---------------------------------------

    im_dir = 'Stimuli'

	
	#---------------------------------------
	# Setup instructions
	#--------------------------------------- 
	#instrPracticeClock = core.Clock()
    instruct1 = visual.TextStim(win=win, ori=0, name='instruct1',
	    text="Consignes : \n\n Pressez le bouton 4 uniquement lorsque l'image est celle d'une main gauche. \n\n Ne pressez pas le bouton lorsque l'image est une image de main droite. Appuyer sur le 1 pour continuer.", font='Arial',
	    pos=[0, 0], height=0.04, wrapWidth=None,
	    color='black', colorSpace='rgb', opacity=1.0,
	    depth=0.0)

	#---------------------------------------
	# Setup end message
	#--------------------------------------- 
	#instrPracticeClock = core.Clock()
    theEnd = visual.TextStim(win=win, ori=0, name='theEnd',
	    text="Fin de l'experience, merci de votre participation !", font='Arial',
	    pos=[0, 0], height=0.04, wrapWidth=None,
	    color='black', colorSpace='rgb', opacity=1,
	    depth=0.0)

    pause = visual.TextStim(win=win, ori=0, name='pause',
	    text="Vous pouvez faire une pause", font='Arial',
	    pos=[0, 0], height=0.04, wrapWidth=None,
	    color='black', colorSpace='rgb', opacity=1,
	    depth=0.0)

    pause2 = visual.TextStim(win=win, ori=0, name='pause',
	    text="Fin de la premiere partie", font='Arial',
	    pos=[0, 0], height=0.04, wrapWidth=None,
	    color='black', colorSpace='rgb', opacity=1,
	    depth=0.0)


	#---------------------------------------
	# Setup Fixation cross and circle
	#---------------------------------------

	
    fixation_cross=visual.TextStim(win=win, ori=0, name='fixation_cross',
		   text='+',
		   font='Arial',
		   pos=[0, 0], height=0.06,		
		   color='black')
    fixation_cross.setLineWidth = 0.4



    if is_fmri == 1 :

		#---------------------------------------
		# Settings for launch scan 
		#---------------------------------------

        MR_settings={
			'TR': 2.000, # duration (sec) per volume
			'volumes':5, # number of whole-brain 3D volumes/frames
			'sync': '5', # character used as sync timing event; assumed to come at start of a volume
			'skip': 5, # number of volumes lacking a sync pulse at start of scan (for T1 stabilization)
			'sound': False # True: in test mode only
			}

		#infoDlg = gui.DlgFromDict(MR_settings, title='FMRI parameters', order=['TR', 'volumes'])
		#if not infoDlg.OK: core.quit() 

        globalClock = core.Clock()
        mode = 'Scan'

		#summary of run timing for each key press:
        output = 'vol onset key\n'

        for i in range (-1*MR_settings['skip'], 0):
			output += '%d prescan skip (no sync)\n' % i

        key_code = MR_settings['sync']
        counter = visual.TextStim(win, height=.05, pos=(0,0), color=win.rgb+0.5)
        output += "00.000 %s start of scanning run, vol 0\n" % key_code 
        pause_during_delay = (MR_settings['TR']>.4)
        sync_now = False


		# can simulate user responses, here 3 key presses in order 'a', 'b', 'c' (they get sorted by time):
        simResponses = [(0.123, 'a'), (4.789, 'c'), (2.456, 'b')]

	

		#---------------------------------------
		# launch scanner
		# operator selects Scan or Test 
		#---------------------------------------
        vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=simResponses)

        infer_missed_sync = False # best no to use it but might be useful
        max_slippage = 0.02 # how long to afford before treating a slow sync as missed

        duration = MR_settings['volumes']*MR_settings['TR']
		# globalClock has been reset to 0 by launchScan()

        while globalClock.getTime() < duration:
			allKeys = event.getKeys()
			for key in allKeys:
				if key != MR_settings['sync']:
					output += "%3d %7.3f %s\n" % (vol-1, globalClock.getTime(), str(key))
			if 'escape' in allKeys:
				output += 'user cancel,'
				break
			#detect sync or infer it shoul have happened:
			if MR_settings['sync'] in allKeys:
				sync_now = key_code #flag
				onset = globalClock.getTime()
			if infer_missed_sync:
				expected_onset = vol*MR_setting['TR']
				now = globalClock.getTime()
				if now > expected_onset + max_slippage:
					 sync_now = '(inferred onset)' # flag
					 onset = expected_onset
			if sync_now:
				start_expe = 1
	else:	
		start_expe = 1
		
	if start_expe == 1:
	 
		#--------------------------------------
		# Show Instructions
		#--------------------------------------
		instruct1.draw(win)
		win.flip()
		event.waitKeys(keyList= keyPass)
		
	
		trialStart = 0
		
		#--------------------------------------
		# START EXPERIMENT
		#--------------------------------------
		fixation_cross.draw()
		win.flip()
		core.wait(1)
	
		win.setRecordFrameIntervals(True) # frame time tracking
		globalClock.reset()		

		trialStart = 1
        if trialStart == 1:
	
            t = 0
            frameN=-1
            nDone=0
			
					

			
		#--------------------------------------
		# Run Trials
		#--------------------------------------
            for thisTrial in trials:

			# save data for the trial loop using psychopy function
                trials.saveAsWideText(filename + '.csv', delim=',', appendFile = False)
                trials.addData('scanOnset', onset)
                thisResp = [] # to store resp key and resp time
			 #   parallel.setData(0) # sets all pins to low
					
				#--------------------------------------
				# Load stimuli image and set trials
				# variables
				#--------------------------------------
                if thisTrial['Stim'] != 'pause' and thisTrial['Stim'] != 'blank':	
					stim = visual.ImageStim(win, image = os.path.join(im_dir, thisTrial['Stim']), size=(STIM_SIZE ))
					stimOnset = trialClock.getTime()
				#--------------------------------------
				# Display trials		
				#--------------------------------------
                #if thisTrial['Stim'] != 'blank' and thisTrial['Stim'] != 'pause': # case trial is stimuli 
					
					while trialClock.getTime() < stimOnset + stimDuration :
						fixation_cross.draw()
						stim.draw()
						win.flip()
					#	parallel.setPin(pinNumber, 1) # sets pinNumber (variable defined at the beginning) to be high
						thisResp= getResponse(keyGo, stimDuration ) # evaluate response
                elif thisTrial['Stim'] == 'blank': # case trial is blank trial
					fixation_cross.draw()
					win.flip()
					stimOnset = trialClock.getTime()
					thisResp= getResponse(keyGo, stimDuration ) # evaluate response
					core.wait(5)
                elif thisTrial['Stim'] == 'pause':	# case pause for hypnosis reinforcement
					pause.draw()
					win.flip()
					#core.wait(PAUSE)
					event.waitKeys(keyList= keyPause)
					fixation_cross.draw()	
					win.flip()
					core.wait(0.5)

                fixation_cross.draw()
                win.flip()
				#parallel.setData(0)
                core.wait(thisTrial['ITI']) 
                nDone +=1
					
									
		#		if(thisRespKeys == thisTrial['corrAns']) or (thisRespKeys == [] and thisTrial['corrAns'] =='n') :
		#			respCorr = 1 # lookup response for go and no go trials
		#		else: respCorr = 0
				
					
				#--------------------------------------
				# store trial data
				#--------------------------------------
                if len(thisResp)>0 :
					trials.addData('respKey',thisResp[0])
					trials.addData('respTime', thisResp[1])
	#			trials.addData('respCorr', respCorr)
                trials.addData('stimOnset', stimOnset)

                thisExp.nextEntry() 
		# get names of stimulus parameters
                if trials.trialList in ([], [None], None): params = []
                else: params = trials.trialList[0].keys()
		
                if event.getKeys(['q',' escape']):			
					win.close()
					core.quit()
	
		#--------------------------------------
		# End Experiment	
		#--------------------------------------
            core.wait(1)
            win.flip()
            if thisTrial['Run'] == 1 or thisTrial['Run']== 3:
                pause.draw(win)
                win.flip()
                event.waitKeys('space')    
            elif thisTrial['Run'] == 2:
                pause2.draw(win)
                win.flip()
                event.waitKeys('space')    
            else:
                theEnd.draw(win)
                win.flip()
                event.waitKeys('space')    
	

	
            if is_fmri == 1:
                sync_now = False
                output+= "end of scan (vol 0..%d= %d of %s). duration = %7.3f" %(vol-1, vol, MR_settings['volumes'], globalClock.getTime())
                logging.info(output)




		
	event.waitKeys('space')
	win.close()
	core.quit()
Exemplo n.º 12
0
#store info about the experiment session
expName = 'None'  #from the Builder filename that created this script
expInfo = {'participant': '', 'session': '01'}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False: core.quit()  #user pressed cancel
expInfo['date'] = data.getDateStr()  #add a simple timestamp
expInfo['expName'] = expName
#setup files for saving
if not os.path.isdir('data'):
    os.makedirs('data')  #if this fails (e.g. permissions) we will get error
filename = 'data' + os.path.sep + '%s_%s' % (expInfo['participant'],
                                             expInfo['date'])
logFile = logging.LogFile(filename + '.log', level=logging.INFO)
logging.console.setLevel(
    logging.WARNING)  #this outputs to the screen, not a file
logging.setDefaultClock(experimentClock)
#setup the Window
win = visual.Window(size=(1920, 1080),
                    fullscr=True,
                    screen=0,
                    allowGUI=False,
                    allowStencil=False,
                    monitor='testMonitor',
                    color='black',
                    colorSpace='rgb',
                    units='norm')

errorCircle = visual.Circle(win, radius=0.5, edges=100)
errorCircle.setAutoDraw(True)
errorCircle.setFillColor("black", colorSpace="rgb")
errorCircle.setLineColor("black", colorSpace="rgb")
Exemplo n.º 13
0
    for match in matches:
        if match is not None:
            newlist.append(match.group(1))
    logcounter = max([int(n) for n in newlist])

# so make just another logfile on top of this one -- it'll be timestamped
logcounter += 1

# this is the new logfile:
newLogFile = os.path.join(LOGDIR, LOGFILEBASE + '%d.log' % logcounter)
print('Logfile for off-line analysis: %s\n' % newLogFile)

# open up a log:
expLogger = logging.LogFile(newLogFile,
                            logging.EXP)  # the correct loglevel should be EXP!
logging.setDefaultClock(G['mainClock'])
# this ensures that all kinds of Exp thingies are written. DATA, WARNING and ERROR are higher
# but INFO and DEBUG won't be used.
# this is actually useful.

# so -- write stuff away with logging.data('blabla'); logging;flush()
# then -- logging.data('message') --> will give timestamped stuff
# logging.flush() --> to ACTUALLY WRITE it to the file!

# many (!!) of the stimuli also create a logging trigger, but you'd need to flush it
# in order to write it as-you-go
# otherwise it'll only happen at the end of the experiment
# and if there is an error of some sort --> bad luck, if you relied on loggin
# for your experimental logfile data crawlers, you just lost EVERYTHING.
G['expLogger'] = expLogger
different levels of input.

The importance levels are;
    40:ERROR
    35:DATA
    30:WARNING
    25:DATA
    22: EXP
    20:INFO
    10:DEBUG
So setting to DEBUG level will include all possible messages, setting to ERROR will include only the absolutely essential messages.

"""
globalClock = core.Clock(
)  #if this isn't provided the log times will reflect secs since python started
logging.setDefaultClock(globalClock)  #use this for

logging.console.setLevel(
    logging.DEBUG)  #set the console to receive nearly all messges
logDat = logging.LogFile(
    'logLastRun.log',
    filemode='w',  #if you set this to 'a' it will append instead of overwriting
    level=logging.WARNING
)  #errors, data and warnings will be sent to this logfile

#the following will go to any files with the appropriate minimum level set
logging.info('Something fairly unimportant')
logging.data('Something about our data. Data is likely very important!')
logging.warning(
    'Handy while building your experiment - highlights possible flaws in code/design'
)
Exemplo n.º 15
0
    def pre_mainloop(self):

        MostBasicPsychopyFeedback.pre_mainloop(self)

        # do the trick -- SAVE all of those things! --> and put it in settings.pkl.
        v = dict()

        v['caption'] = self.caption
        v['color'] = self.color
        v['fontheight'] = self.fontheight

        v['STARTKEYS'] = self.STARTKEYS

        v['EX_THRLINEWIDTH'] = self.EX_THRLINEWIDTH
        v['EX_COLORGAP'] = self.EX_COLORGAP
        v['EX_TVSP'] = self.EX_TVSP
        v['EX_TPAUSE'] = self.EX_TPAUSE
        v['EX_NREGULATE'] = self.EX_NREGULATE
        v['EX_NTRANSFER'] = self.EX_NTRANSFER

        v['EX_SHOWCHECKORCROSS'] = self.EX_SHOWCHECKORCROSS
        v['EX_SHOWCHECKORCROSSTRANSFER'] = self.EX_SHOWCHECKORCROSSTRANSFER
        v['EX_SHOWPOINTS'] = self.EX_SHOWPOINTS

        v['EX_SQUARESIZE'] = self.EX_SQUARESIZE
        v['EX_UPREGTEXT'] = self.EX_UPREGTEXT
        v['EX_TESTSIGNALUPDATEINTERVAL'] = self.EX_TESTSIGNALUPDATEINTERVAL
        v['EX_NREST'] = self.EX_NREST
        v['EX_SCALING'] = self.EX_SCALING
        v['EX_INTERACTIONMODE'] = self.EX_INTERACTIONMODE
        v['EX_NOBSERVE'] = self.EX_NOBSERVE
        v['EX_NOREGTEXT'] = self.EX_NOREGTEXT
        v['EX_TINSTR'] = self.EX_TINSTR
        v['EX_THERMOCLIMS'] = self.EX_THERMOCLIMS
        v['EX_GRAPHICSMODE'] = self.EX_GRAPHICSMODE

        v['EX_STAIRCASEMANIPULATION'] = self.EX_STAIRCASEMANIPULATION
        v['EX_POINTS_PENALTY'] = self.EX_POINTS_PENALTY
        v['EX_TESTSIGNALPERIOD'] = self.EX_TESTSIGNALPERIOD
        v['EX_TMARK'] = self.EX_TMARK
        v['EX_TESTNFNOISE'] = self.EX_TESTNFNOISE
        v['EX_PATCHCOLOR'] = self.EX_PATCHCOLOR
        v['EX_TJITT'] = self.EX_TJITT
        v['EX_TFB'] = self.EX_TFB
        v['EX_POINTS_REWARD'] = self.EX_POINTS_REWARD
        v['EX_PR_SLEEPTIME'] = self.EX_PR_SLEEPTIME
        v['EX_TESTSIGNALTYPE'] = self.EX_TESTSIGNALTYPE
        v['EX_BUTTONS'] = self.EX_BUTTONS
        v['EX_INSTR'] = self.EX_INSTR
        v['EX_RUNS'] = self.EX_RUNS

        v['EX_SND_LOWESTTONE'] = self.EX_SND_LOWESTTONE
        v['EX_SND_HIGHESTTONE'] = self.EX_SND_HIGHESTTONE

        v['EX_EMG_THERMOWIDTH'] = self.EX_EMG_THERMOWIDTH
        v['EX_EMG_THERMOHEIGHT'] = self.EX_EMG_THERMOHEIGHT
        v['EX_EMG_THERMOEDGE'] = self.EX_EMG_THERMOEDGE

        v['EX_TXT_COUNTER'] = self.EX_TXT_COUNTER

        v['MONITOR_PIXWIDTH'] = self.MONITOR_PIXWIDTH
        v['MONITOR_PIXHEIGHT'] = self.MONITOR_PIXHEIGHT
        v['MONITOR_WIDTH'] = self.MONITOR_WIDTH
        v['MONITOR_HEIGHT'] = self.MONITOR_HEIGHT
        v['MONITOR_DISTANCE'] = self.MONITOR_DISTANCE
        v['MONITOR_GAMMA'] = self.MONITOR_GAMMA
        v['MONITOR_FPS'] = self.MONITOR_FPS
        v['MONITOR_USEDEGS'] = self.MONITOR_USEDEGS
        v['MONITOR_DEGS_WIDTHBASE'] = self.MONITOR_DEGS_WIDTHBASE
        v['MONITOR_DEGS_HEIGHTBASE'] = self.MONITOR_DEGS_HEIGHTBASE
        v['MONITOR_FLIPHORIZONTAL'] = self.MONITOR_FLIPHORIZONTAL
        v['MONITOR_FLIPVERTICAL'] = self.MONITOR_FLIPVERTICAL
        v['MONITOR_RECORDFRAMEINTERVALS'] = self.MONITOR_RECORDFRAMEINTERVALS
        v['MONITOR_NSCREENS'] = self.MONITOR_NSCREENS
        v['MONITOR_DISPLAYONSCREEN'] = self.MONITOR_DISPLAYONSCREEN
        v['MONITOR_FULLSCR'] = self.MONITOR_FULLSCR
        v['MONITOR_ALLOWGUI'] = self.MONITOR_ALLOWGUI

        v['LOG_PATHFILE'] = self.LOG_PATHFILE
        v['LOG_PATHFILE_EVENT'] = self.LOG_PATHFILE_EVENT

        v['EVENT_LPT_TRIGGER_WAIT'] = self.EVENT_LPT_TRIGGER_WAIT
        v['EVENT_destip'] = self.EVENT_destip
        v['EVENT_destport'] = self.EVENT_destport
        v['EVENT_LPTAddress'] = self.EVENT_LPTAddress
        v['EVENT_LPTTrigWaitTime'] = self.EVENT_LPTTrigWaitTime
        v['EVENT_TRIGLOG'] = self.EVENT_TRIGLOG
        v['EVENT_sendParallel'] = self.EVENT_sendParallel
        v['EVENT_sendTcpIp'] = self.EVENT_sendTcpIp
        v['EVENT_sendLogFile'] = self.EVENT_sendLogFile
        v['EVENT_printToTerminal'] = self.EVENT_printToTerminal
        v['EVENT_printToTerminalAllowed'] = self.EVENT_printToTerminalAllowed

        # so these are NOW control parameters:
        v['EX_TUNING_TYPE'] = self.EX_TUNING_TYPE  # = 'thr'  # alternatives are 'linear', and maybe 'fancy'
        v['EX_TUNING_PARAMS'] = self.EX_TUNING_PARAMS  # = [1.0, 0.0]  # linear requires a slope and offset. - eill not be used if it's not 'linear'
        v['EX_WIN_CONDITION'] = self.EX_WIN_CONDITION  # = 'time_above_thr'
        v['EX_WIN_PARAMS'] = self.EX_WIN_PARAMS  # = [0.25]  # 25 % of the time, it needs to be above the threshold...
        v['EX_NUMBEROFSETS'] = self.EX_NUMBEROFSETS  # = 6  # how long (sets of 6) do we wish our experiment to have?? Determines also our staircases.
        v['EX_MIXOFSETS'] = self.EX_MIXOFSETS  # = {'train':3, 'transfer':1, 'observe':1, 'rest':1}
        v['EX_STAIRIDENTIFIER'] = self.EX_STAIRIDENTIFIER  # = '0001'  # needed to keep track of the staircases.
        v['EX_XorV_RESET_POINTS'] = self.EX_XorV_RESET_POINTS  # = False  # at the start of the day --> this should be True.

        # use the Cpntrol Parameters:
        CP = self.CP  # control parameters...

        # create G, put it into self too..
        G = dict()
        G['v'] = v
        self.G = G

        # we need this in order to continue working as if we're doing it using the normal (test) script...
        for key in G['v']:
            G[key] = G['v'][
                key]  # this is actually superfluous. But removing it might possibly break things.

        # the main clock
        mainClock = clock.Clock()
        G['mainClock'] = mainClock

        # screen/monitor...
        G = init_screen(G)  # we need to do this

        # logging...
        logging.setDefaultClock(G['mainClock'])
        newLogFile = create_incremental_filename(G['v']['LOG_PATHFILE'])
        expLogger = logging.LogFile(
            newLogFile, logging.EXP)  # the correct loglevel should be EXP!
        print(expLogger)
        logging.LogFile(newLogFile,
                        logging.EXP)  # the correct loglevel should be EXP!
        print('made new logfile: ' + newLogFile)
        for key in G['v'].keys():
            logging.data("{key}: {value}".format(key=key, value=G['v'][key]))
        logging.flush()
        G['logging'] = logging  # put into the G, which is in self

        # event handler...
        G = init_eventcodes(G)  # and this??
        G = start_eh(G)

        init_staircases_quest(G)
        st = make_stimuli(G, CP)
        pr = init_programs(G, st, CP)

        ex = define_experiment(
            G, st, pr,
            CP)  # pr is passed to define_experiment, but then we won't need...

        self.st = st
        self.ex = ex

        # take care of the randomization(s)...
        trialopts = []

        trialopts.append([1, 1, 2, 1, 3, 4])
        trialopts.append([1, 1, 2, 1, 4, 3])
        trialopts.append([1, 1, 2, 3, 1, 4])
        trialopts.append([1, 1, 2, 4, 1, 3])
        trialopts.append([1, 1, 3, 1, 2, 4])
        trialopts.append([1, 1, 3, 1, 4, 2])
        trialopts.append([1, 1, 3, 2, 1, 4])
        trialopts.append([1, 1, 3, 4, 1, 2])
        trialopts.append([1, 1, 4, 1, 3, 2])
        trialopts.append([1, 1, 4, 1, 2, 3])
        trialopts.append([1, 1, 4, 3, 1, 2])
        trialopts.append([1, 1, 4, 2, 1, 3])
        trialopts.append([1, 2, 1, 4, 1, 3])
        trialopts.append([1, 2, 1, 3, 1, 4])
        trialopts.append([1, 3, 1, 4, 1, 2])
        trialopts.append([1, 3, 1, 2, 1, 4])
        trialopts.append([1, 4, 1, 2, 1, 3])
        trialopts.append([1, 4, 1, 3, 1, 2])

        random.shuffle(trialopts)
        random.shuffle(trialopts)
        random.shuffle(trialopts)  # 3 time shuffle, for good luck :-)
        # computational anathema and heretic!

        my_trial_sequence = flatten(
            trialopts[0:G['v']['EX_RUNS']])  # we do 5 of them.
        my_trial_definitions = {
            1: 'train',
            2: 'transfer',
            3: 'observe',
            4: 'rest'
        }

        # so to debug, just run tasks_dbg instead of tasks.
        for t_i in my_trial_sequence:
            self.runlist = iter(
                [my_trial_definitions[i] for i in my_trial_sequence])

        # the ev loop we're going to be using..
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        self.loop = loop

        if G['EX_TESTNFNOISE'] is True:
            self.loop.create_task(pr['GenTestSignal'](G, st, CP))

        logging.flush()
        G['logging'] = logging

        G['cl'] = clock.Clock(
        )  # init the trial-by-trial clock here and put into G...
Exemplo n.º 16
0
import itertools
import ujson as json
import os
from datetime import datetime
from pprint import PrettyPrinter

import numpy as np
from psychopy import core, logging, sound, visual

from practice_decl import StateMachine
from toon.input import MultiprocessInput as MpI
from toon.input.clock import mono_clock
from toon.input.keyboard import Keyboard

logging.setDefaultClock(mono_clock)
logging.console.setLevel(logging.ERROR)
if os.name == 'nt':
    sound.setDevice('ASIO4ALL v2')

pp = PrettyPrinter()


class Practice(StateMachine):
    def __init__(self, settings=None, generator=None, static_settings=None):
        super(Practice, self).__init__()
        self.settings = settings
        self.trial_generator = generator
        self.static_settings = static_settings

        self.global_clock = mono_clock
        self.feedback_timer = core.CountdownTimer()  # feedback duration
Exemplo n.º 17
0
#-----------------------------------------------------------------------#
# dataFrame is used to keep track of all the data from the experiment
# Pandas is a useful package in Python that helps you efficiently manage data
# we specify the data columns as below
data_columns = ['item', 'resp', 'rt', 'globaltime']
data = pd.DataFrame(columns=data_columns)

# setup a variable 'globalClock' to keep track of time
globalClock = core.Clock()

# 2. Creating a log file
#-----------------------------------------------------------------------#
# log file can be saved everytime a script is run
# log file is useful in a sense that it is a safe-keeper for saving whatever is going on
# in case of data loss, you can refer to the log of what happened
logging.setDefaultClock(globalClock)  # logging needs a timer to base on

# there are different levels of log levels
# (ie. DEBUG is the most low-level, details that prints out almost everything that goes on with the script)
# however, we don't want all the small details, like setting next word is set as 'pepper'
# so intead, in the console level of the logging, we specify logging.ERROR
# which will only print stuff that would cause error, or important data
logging.console.setLevel(logging.ERROR)

# then we have a seperate logDat file that will save out all the details. Notice we set the save out directory and the logging level as DEBUG
logDat = logging.LogFile(
    setDir + '/' + str(exp_summary) + '.log',
    filemode='w',  # if you set this to 'a' it will append instead of overwriting
    level=logging.DEBUG)

#-----------------------------------------------------------------------#
Exemplo n.º 18
0
            if match is not None:
                newlist.append(match.group(1))
        logcounter = max([int(n) for n in newlist])
    
    
    
    # so make just another logfile on top of this one -- it'll be timestamped    
    logcounter += 1
    
    # this is the new logfile:
    newLogFile=os.path.join(LOGDIR, LOGFILEBASE+'%d.log' % logcounter)
    
    
    # open up a log:
    expLogger = logging.LogFile(newLogFile, logging.EXP) # the correct loglevel should be EXP!
    logging.setDefaultClock(mainClock)
# this ensures that all kinds of Exp thingies are written. DATA, WARNING and ERROR are higher
# but INFO and DEBUG won't be used.
# this is actually useful.


# so -- write stuff away with logging.data('blabla'); logging;flush()
# then -- logging.data('message') --> will give timestamped stuff
# logging.flush() --> to ACTUALLY WRITE it to the file!

# many (!!) of the stimuli also create a logging trigger, but you'd need to flush it
# in order to write it as-you-go
# otherwise it'll only happen at the end of the experiment
# and if there is an error of some sort --> bad luck, if you relied on loggin
# for your experimental logfile data crawlers, you just lost EVERYTHING.
Exemplo n.º 19
0
global gStartTc; gStartTc = time.clock();

def msTime():
    deltadt = datetime.datetime.utcnow() - gStartDt
    deltatt = time.time() - gStartTt
    deltatc = time.clock()
    return deltadt.total_seconds(), deltatt, deltatc 
    #delta#int(delta.total_seconds() * 1000)

#setup log
myLogLevel = logging.CRITICAL + 1
logging.addLevel( myLogLevel, '' )
myLog = logging.LogFile( '.\\timings.log', filemode='w', level = myLogLevel, encoding='utf8') #= myLogLevel )

coreClock = core.Clock()
logging.setDefaultClock( coreClock )

logging.log('Run: ' + str(datetime.datetime.utcnow()) , myLogLevel)
logging.log('PP timestamp, datetime, timetime, timeclock', myLogLevel)
#setup window
win = visual.Window([400,400])
msg = visual.TextStim(win, text='<esc> to quit')
msg.draw()
win.flip()

while run:
    
    for i in range( gFrameInterval ): #accurate timing trick
        msg.setText('<esc> to quit\n' + str(i))
        msg.draw(win)
        win.flip()
Exemplo n.º 20
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()
Exemplo n.º 21
0
def prf_stim(dicParam):
    """
    Present stimuli for population receptive field mapping.

    If in logging mode, this script creates a stimulus log of the stimuli used
    for the pRF mapping that can be used for the pRF finding analysis of the
    pyprf library. The stimuli are saved as png files, where each png
    represents the status of visual stimulation for one TR (the png files
    contain modified screenshots of the visual stimulus, and can be directly be
    loaded into the py_pRF_mapping pipepline.
    """
    # *****************************************************************************
    # *** Experimental parameters (from dictionary)

    # Path of design matrix (npz):
    strPthNpz = dicParam['Path of design matrix (npz)']

    # Output path & file name of log file:
    strPthLog = dicParam['Output path (log files)']

    # Target duration [s]:
    varTrgtDur = float(dicParam['Target duration [s]'])

    # Logging mode (logging mode is for creating files for analysis, not to be
    # used during an experiment).
    lgcLogMde = dicParam['Logging mode']

    # On windows, the return value may be a string, not a bool. We need to
    # correct for this.
    if not (isinstance(lgcLogMde, bool)):
        if lgcLogMde == 'True':
            lgcLogMde = True
        else:
            lgcLogMde = False

    # Directory where to save stimulus log (frames) for analysis if in logging
    # mode.
    strPthFrm = dicParam['Output path stimulus log (frames)']

    # Frequency of stimulus bar in Hz:
    varGrtFrq = float(dicParam['Temporal frequency [Hz]'])

    # Sptial frequency of stimulus (cycles along width of bar stimulus):
    varBarSf = float(dicParam['Spatial frequency [cyc per bar]'])

    # Distance between observer and monitor [cm]:
    varMonDist = float(dicParam['Distance between observer and monitor [cm]'])

    # Width of monitor [cm]:
    varMonWdth = float(dicParam['Width of monitor [cm]'])

    # Width of monitor [pixels]:
    varPixX = int(dicParam['Width of monitor [pixels]'])

    # Height of monitor [pixels]:
    varPixY = int(dicParam['Height of monitor [pixels]'])

    # Background colour:
    varBckgrd = float(dicParam['Background colour [-1 to 1]'])

    # Show fixation grid?
    lgcGrd = dicParam['Show fixation grid?']

    # On windows, the return value may be a string, not a bool. We need to
    # correct for this.
    if not (isinstance(lgcGrd, bool)):
        if lgcGrd == 'True':
            lgcGrd = True
        else:
            lgcGrd = False

    # *************************************************************************
    # *** Retrieve design matrix

    # Load stimulus parameters from npz file.
    objNpz = np.load(strPthNpz)

    # Get design matrix (for bar positions and orientation):
    aryDsg = objNpz['aryDsg']

    # Number of volumes:
    varNumVol = aryDsg.shape[0]

    # Vector with times of target events:
    vecTrgt = objNpz['vecTrgt']

    # Number of target events:
    varNumTrgt = vecTrgt.shape[0]

    # Full screen mode? If no, bar stimuli are restricted to a central square.
    # If yes, bars appear on the entire screen. This parameter is set when
    # creating the design matrix.
    lgcFull = bool(objNpz['lgcFull'])

    # Number of bar positions on x-axis:
    varNumPosX = int(objNpz['varNumPosX'])

    # Number of bar positions on y-axis:
    varNumPosY = int(objNpz['varNumPosY'])

    # If in full screen mode, we need to make sure that the bar position along
    # the shorted axis (x-axis) is adjusted, so that the bar is always within
    # the screen area (and not half cut off).
    if lgcFull:
        # Ratio of bar positions (from design matrix), e.g. 18/11:
        varRatioPos = float(varNumPosX) / float(varNumPosY)
        # Ratio of screen widht/height in pixels (e.g. 1920/1200):
        varRatioPix = float(varPixX) / float(varPixY)
        # Scaling factor for bar positions along x-axis:
        varSclPosX = varRatioPos / varRatioPix

    # Adjustments for logging mode:
    if lgcLogMde:

        # Conditional imports:
        from PIL import Image
        from scipy.stats import mode

        # If in logging mode, only present stimuli very briefly. Note: If
        # 'varTr' is set too low in logging mode, frames are dropped and the
        # stimuli do not get logged properly.
        varTr = 0.2

        # In log mode, don't show grid.
        lgcGrd = False

    # Otherwise, use actual volume TR:
    else:
        # Volume TR:
        varTr = float(objNpz['varTr'])

    # *************************************************************************
    # *** Logging

    # Set clock:
    objClck = core.Clock()

    # Set clock for logging:
    logging.setDefaultClock(objClck)

    # Create a log file and set logging verbosity:
    fleLog = logging.LogFile(strPthLog, level=logging.DATA)

    # Log stimulus parameters:
    fleLog.write('Log file path: ' + strPthLog + '\n')
    fleLog.write('Design matrix: ' + strPthNpz + '\n')
    fleLog.write('Full screen: ' + str(lgcFull) + '\n')
    fleLog.write('Volume TR [s] (from design matrix): ' + str(varTr) + '\n')
    fleLog.write('Frequency of stimulus bar in Hz: ' + str(varGrtFrq) + '\n')
    fleLog.write('Sptial frequency of stimulus (cycles along width of ' +
                 'bar stimulus): ' + str(varBarSf) + '\n')
    fleLog.write('Distance between observer and monitor [cm]: ' +
                 str(varMonDist) + '\n')
    fleLog.write('Width of monitor [cm]: ' + str(varMonWdth) + '\n')
    fleLog.write('Width of monitor [pixels]: ' + str(varPixX) + '\n')
    fleLog.write('Height of monitor [pixels]: ' + str(varPixY) + '\n')
    fleLog.write('Background colour [-1 to 1]: ' + str(varBckgrd) + '\n')
    fleLog.write('Target duration [s]: ' + str(varTrgtDur) + '\n')
    fleLog.write('Logging mode: ' + str(lgcLogMde) + '\n')

    # Set console logging verbosity:
    logging.console.setLevel(logging.WARNING)

    # *************************************************************************
    # *** Prepare behavioural response logging

    # Switch target (show target or not?):
    varSwtTrgt = 0

    # Control the logging of participant responses:
    varSwtRspLog = 0

    # The key that the participant has to press after a target event:
    strTrgtKey = '1'

    # Counter for correct/incorrect responses:
    varCntHit = 0  # Counter for hits
    varCntMis = 0  # Counter for misses

    # Time (in seconds) that participants have to respond to a target event in
    # order for the event to be logged as a hit:
    varHitTme = 2.0

    # *************************************************************************
    # *** Setup

    # Create monitor object:
    objMon = monitors.Monitor('Screen_7T_NOVA_32_Channel_Coil',
                              width=varMonWdth,
                              distance=varMonDist)

    # Set size of monitor:
    objMon.setSizePix([varPixX, varPixY])

    # Set screen:
    objWin = visual.Window(
        size=(varPixX, varPixY),
        screen=0,
        winType='pyglet',  # winType : None, 'pyglet', 'pygame'
        allowGUI=False,
        allowStencil=True,
        fullscr=True,
        monitor=objMon,
        color=varBckgrd,
        colorSpace='rgb',
        units='deg',
        blendMode='avg')

    # *************************************************************************
    # *** Spatial stimulus properties

    # The area that will be covered by the bar stimulus depends on whether
    # presenting in full screen mode or not. If in full screen mode, the
    # entire width of the screen will be covered. If not, a central square
    # with a side length equal to the screen height will be covered.
    if lgcFull:
        varPixCov = varPixX
    else:
        varPixCov = varPixY

    # Convert size in pixels to size in degrees (given the monitor settings):
    # varDegCover = pix2deg(varPixCov, objMon)

    # Numberic codes used for bar positions:
    vecPosCode = np.unique(aryDsg[:, 1])

    # Number of bar positions:
    varNumPos = vecPosCode.shape[0]

    # The thickness of the bar stimulus depends on the size of the screen to
    # be covered, and on the number of positions at which to present the bar.
    # Bar thickness in pixels:
    varThckPix = float(varPixCov) / float(varNumPos)

    # Bar thickness in degree:
    varThckDgr = np.around(pix2deg(varThckPix, objMon), decimals=5)

    # Write stimulus parameters to log file.
    fleLog.write('* * * Stimulus properties in degrees of visual angle ' +
                 '* * * \n')
    fleLog.write('Width of bar stimulus [deg]: ' + str(varThckDgr) + '\n')

    # Spatial frequency of bar stimulus is defined (in user input) as cycles
    # along width of the bar  stimulus. We need to convert this to cycles per
    # pixel (for the stimulus creation) and to cycles per degree (for
    # reference, written to log file).

    # Spatial frequency in cycles per pixel:
    varBarSfPix = float(varBarSf) / varThckPix
    tplBarSfPix = (varBarSfPix, varBarSfPix)

    # Spatial frequency in cycles per degree of visual angle (for reference
    # only):
    varBarSfDeg = np.around((float(varBarSf) / varThckDgr), decimals=5)

    # Write stimulus parameters to log file.
    fleLog.write('Spatial frequency of bar stimulus [cyc/deg]: ' +
                 str(varBarSfDeg) + '\n')
    fleLog.write('* * * \n')

    # Bar stimulus size (length & thickness), in pixels.
    tplBarSzePix = (varPixX, int(varThckPix))

    # Offset of the bar stimuli. The bar stimuli should cover the screen area,
    # without extending beyond the screen. Because their position refers to
    # the centre of the bar, we need to limit the extend of positions at the
    # edge of the screen by an offset, Offset in pixels:
    varOffsetPix = varThckPix * 0.5

    # Maximum bar position in pixels, with respect to origin at centre of
    # screen:
    varPosMaxPix = (float(varPixCov) * 0.5) - float(varOffsetPix)

    # Array of possible bar positions (displacement relative to origin at
    # centre of the screen) in pixels:
    vecPosPix = np.linspace(-varPosMaxPix,
                            varPosMaxPix,
                            varNumPos,
                            endpoint=True)

    # Replace numeric position codes with pixel position values:
    for idxPos, varPos in enumerate(vecPosCode):

        # Replace current position code, if this is not a rest block:
        vecLgc = np.multiply((aryDsg[:, 1] == varPos), (aryDsg[:, 0] != 0.0))

        # Place pixel position value in design matrix:
        aryDsg[vecLgc, 1] = vecPosPix[idxPos]

    # Psychopy orientation convention: "Orientation convention is like a clock:
    # 0 is vertical, and positive values rotate clockwise." Actually, 0 is the
    # positive x-axis. Orientations are coded as follows: horizontal = 0.0,
    # vertical = 90.0, lower left to upper right = 45.0, upper left to lower
    # right = 135.0. We need to convert psychopy orientation & direction
    # convention into x and y coordinates.
    lstPos = [None] * varNumVol
    for idxVol in range(varNumVol):

        # Get angle and radius of current volume:
        varRad = float(aryDsg[idxVol, 1])
        varAngle = float(aryDsg[idxVol, 2])

        # Horizontal:
        if varAngle == 0.0:
            varTmpX = 0.0

            # If in full screen mode, make sure that the bar is not partially
            # outside of the screen area.
            if lgcFull:
                # Scale y-position.
                varTmpY = varRad * varSclPosX
            else:
                # Not in full screen mode, don't scale.
                varTmpY = varRad

        # Vertical:
        elif varAngle == 90.0:
            varTmpX = varRad
            varTmpY = 0.0

        # Lower left to upper right:
        elif varAngle == 45.0:
            if varRad < 0.0:
                varTmpX = -np.sqrt(np.add(np.square(varRad),
                                          np.square(varRad)))
            elif 0.0 < varRad:
                varTmpX = np.sqrt(np.add(np.square(varRad), np.square(varRad)))
            else:
                varTmpX = 0.0
            varTmpY = 0.0

        # Upper left to lower right:
        elif varAngle == 135.0:
            if varRad < 0.0:
                varTmpX = -np.sqrt(np.add(np.square(varRad),
                                          np.square(varRad)))
            elif 0.0 < varRad:
                varTmpX = np.sqrt(np.add(np.square(varRad), np.square(varRad)))
            else:
                varTmpX = 0.0
            varTmpY = 0.0

        # Position is coded as a tuple:
        lstPos[idxVol] = (varTmpX, varTmpY)

    # *************************************************************************
    # *** Stimuli

    # Bar stimulus:
    objBar = visual.GratingStim(objWin,
                                contrast=1.0,
                                pos=(0.0, 0.0),
                                tex='sqrXsqr',
                                color=[1.0, 1.0, 1.0],
                                colorSpace='rgb',
                                opacity=1.0,
                                size=tplBarSzePix,
                                sf=tplBarSfPix,
                                ori=0.0,
                                autoLog=False,
                                interpolate=False,
                                units='pix')

    # Colour of fixation dot:
    lstClrFix = [-0.69, 0.83, 0.63]
    # lstClrFix = [0.04, 0.95, -1.0]

    # Colour of fixation dot when it becomes a target:
    lstClrTrgt = [0.95, 0.04, -1.0]

    # Fixation dot:
    objFix = visual.Circle(objWin,
                           units='deg',
                           pos=(0.0, 0.0),
                           radius=0.05,
                           edges=24,
                           fillColor=lstClrFix,
                           fillColorSpace='rgb',
                           lineColor=lstClrFix,
                           lineColorSpace='rgb',
                           lineWidth=0.0,
                           interpolate=False,
                           autoLog=False)

    # Fication dot surround:
    objFixSrd = visual.Circle(objWin,
                              units='deg',
                              pos=(0.0, 0.0),
                              radius=0.09,
                              edges=24,
                              fillColor=lstClrTrgt,
                              fillColorSpace='rgb',
                              lineColor=lstClrTrgt,
                              lineColorSpace='rgb',
                              lineWidth=0.0,
                              interpolate=False,
                              autoLog=False)

    if lgcGrd:

        # Number of grid circles:
        varNumCrcl = 3

        # Radi at which to present grid circles:
        vecGrdCrclRad = np.linspace((0.25 * float(varPixY)),
                                    (0.75 * float(varPixY)),
                                    num=varNumCrcl)

        # In practice 'radius' seems to refer to refer to the diameter of the
        # circle.

        # Fixation grid circles:
        lstGrdCrcl = [None] * varNumCrcl
        for idxCrcl, varRad in enumerate(vecGrdCrclRad):
            lstGrdCrcl[idxCrcl] = visual.Circle(win=objWin,
                                                pos=(0.0, 0.0),
                                                radius=varRad,
                                                edges=128,
                                                lineWidth=1.0,
                                                lineColor=[-0.8, -0.8, -0.8],
                                                lineColorSpace='rgb',
                                                fillColor=None,
                                                fillColorSpace='rgb',
                                                opacity=1.0,
                                                autoLog=False,
                                                interpolate=True,
                                                units='pix')

        # Fixation grid line:
        lstGrdLne = [None] * 4
        for idxLne, varOri in enumerate([0.0, 45.0, 90.0, 135.0]):
            lstGrdLne[idxLne] = visual.Line(win=objWin,
                                            ori=varOri,
                                            start=(int(-varPixY), 0),
                                            end=(int(varPixY), 0),
                                            pos=(0.0, 0.0),
                                            lineWidth=1.0,
                                            lineColor=[-0.8, -0.8, -0.8],
                                            lineColorSpace='rgb',
                                            fillColor=None,
                                            fillColorSpace='rgb',
                                            opacity=1.0,
                                            autoLog=False,
                                            interpolate=True,
                                            units='pix')

    # *************************************************************************
    # *** Aperture

    # The area that will be covered by the bar stimulus depends on whether
    # presenting in full screen mode or not. If in full screen mode, the entire
    # width of the screen will be covered. If not, a central square with a side
    # length equal to the screen height will be covered.

    if not (lgcFull):

        # Aperture side length in degree. For some reason, the aperture does
        # not seem to accept pixel units.
        varDegCov = pix2deg(float(varPixCov), objMon)

        # Aperture for covering left and right side of screen if not presenting
        # in full screen mode.
        objAprtr = visual.Aperture(objWin,
                                   size=varDegCov,
                                   pos=(0, 0),
                                   shape='square',
                                   inverted=False,
                                   units='deg')

        objAprtr.enabled = True

    # *************************************************************************
    # *** Logging mode preparations

    if lgcLogMde:

        print('Logging mode')

        # Calculate area to crop in x-dimension, at left and right (zero is
        # full extend of screeen width is used):
        if lgcFull:
            varCrpX = 0
        else:
            varCrpX = int(np.around((float(varPixX) - float(varPixY)) * 0.5))

        print(('Stimulus log will be cropped by ' + str(varCrpX) +
               ' in x-direction (screen width).'))

        # Temporary array for screenshots, at full screen size and containing
        # RGB values (needed to obtain buffer content from psychopy):
        aryBuff = np.zeros((varPixY, varPixX, 3), dtype=np.int8)

        # It is not necessary to sample every pixel; only every second pixel is
        # sampled. Number of pixel to be sampled along x and y direction:
        varHalfPixX = int(np.around(varPixX * 0.5))
        varHalfPixY = int(np.around(varPixY * 0.5))

        # Prepare array for screenshots. One value per pixel per volume; since
        # the stimuli are greyscale we discard 2nd and 3rd RGB dimension. Also,
        # there is no need to represent the entire screen, just the part of the
        # screen that is actually stimulated (if not in full screen mode, this
        # is a square at the centre of the screen, flanked by unstimulated
        # areas on the left and right side).
        if lgcFull:
            aryFrames = np.zeros((varHalfPixY, varHalfPixX, varNumVol),
                                 dtype=np.uint8)
        else:
            aryFrames = np.zeros((varHalfPixY, varHalfPixY, varNumVol),
                                 dtype=np.uint8)

        # Counter for screenshots:
        idxFrame = 0

    # *************************************************************************
    # *** Timing & switches

    # Target counter:
    varCntTrgt = 0

    # Time of the first target event:
    varTmeTrgt = vecTrgt[varCntTrgt]

    # Switch for grating polarity flicker:
    varSwtGrt = 0

    # The input parameter 'varGrtFrq' gives the grating flicker frequency in
    # Hz. We need to convert to second:
    varGrtDur = 1.0 / float(varGrtFrq)

    # *************************************************************************
    # *** Presentation

    # Hide the mouse cursor:
    event.Mouse(visible=False)

    if not (lgcLogMde):

        if lgcGrd:

            # Draw fixation grid circles:
            for objGrdCrcl in lstGrdCrcl:
                objGrdCrcl.draw(win=objWin)

            # Draw fixation grid lines:
            for objGrdLne in lstGrdLne:
                objGrdLne.draw(win=objWin)

        # Draw fixation dot & surround:
        objFixSrd.draw(win=objWin)
        objFix.draw(win=objWin)

        objWin.flip()

        # Wait for scanner trigger pulse & set clock after receiving trigger
        # pulse (scanner trigger pulse is received as button press ('5')):
        strTrgr = ['0']
        while strTrgr[0][0] != '5':
            # Check for keypress:
            lstTmp = event.getKeys(keyList=['5'], timeStamped=False)
            # Whether the list has the correct length (if nothing has happened,
            # lstTmp # will have length zero):
            if len(lstTmp) == 1:
                strTrgr = lstTmp[0][0]

    # Trigger pulse received, reset clock:
    objClck.reset(newT=0.0)

    # Main timer which represents the starting point of the experiment:
    varTme01 = objClck.getTime()

    # Time that is updated continuously to track time:
    varTme02 = objClck.getTime()

    # Timer used to control the logging of stimulus events:
    varTme03 = objClck.getTime()

    # Timer for grating stimulus polarity flicker:
    varTme04 = objClck.getTime()
    varTme05 = objClck.getTime()

    # Start of the experiment:
    for idxVol in range(varNumVol):

        # Show a grating during this volume?
        lgcOn = (aryDsg[idxVol, 0] == 1.0)

        # Set grating properties for current volume:
        if lgcOn:

            # Get stimulus properties from design matrix:
            varTmpPos = lstPos[idxVol]
            varTmpOri = aryDsg[idxVol, 2]
            varTmpCon = aryDsg[idxVol, 3]

            # Set bar properties:
            objBar.setPos(varTmpPos)
            objBar.setOri(varTmpOri)
            objBar.setColor((varTmpCon, varTmpCon, varTmpCon))

        # Still on the same volume?
        while varTme02 < (varTme01 + (float(idxVol + 1) * varTr)):

            # *****************************************************************
            # *** Draw stimuli

            # Draw fixation grid?
            if lgcGrd:

                # Draw fixation grid circles:
                for objGrdCrcl in lstGrdCrcl:
                    objGrdCrcl.draw(win=objWin)

                # Draw fixation grid lines:
                for objGrdLne in lstGrdLne:
                    objGrdLne.draw(win=objWin)

            # If a grating is shown, which orientation, position, and contrast?
            if lgcOn:

                # Draw grating.
                objBar.draw(win=objWin)

            # Don't draw fixation point in logging mode:
            if not (lgcLogMde):

                # Draw fixation dot & surround:
                objFixSrd.draw(win=objWin)
                objFix.draw(win=objWin)

            # Flip drawn objects to screen:
            objWin.flip()

            # Update current time:
            varTme02 = objClck.getTime()

            # Update current time:
            varTme05 = objClck.getTime()

            # *****************************************************************
            # *** Target control

            # Time for target?
            if ((varTmeTrgt <= varTme02) and (varTme02 <=
                                              (varTmeTrgt + varTrgtDur))):

                # Was the target off on the previous frame?
                if varSwtTrgt == 0:

                    # Switch the target on by changing the fixation dot colour.
                    objFix.fillColor = lstClrTrgt

                    # Log target event:
                    strTmp = ('TARGET scheduled for: ' + str(varTmeTrgt))
                    logging.data(strTmp)

                    # Once after target onset we set varSwtRspLog to one so
                    # that the participant's respond can be logged:
                    varSwtRspLog = 1

                    # Likewise, just after target onset we set the timer for
                    # response logging to the current time so that the response
                    # will only be counted as a hit in a specified time
                    # interval after target onset:
                    varTme03 = objClck.getTime()

                    # Switch the target switch.
                    varSwtTrgt = 1

            else:

                # No time for target.

                # Was the target just on?
                if varSwtTrgt == 1:

                    # Switch the target off (by changing fixation dot colour
                    # back to normal).
                    objFix.fillColor = lstClrFix

                    # Switch the target switch.
                    varSwtTrgt = 0

                    # Only increase the target  counter if the last target has
                    # not been reached yet:
                    if (varCntTrgt + 1) < varNumTrgt:

                        # Increase the target counter:
                        varCntTrgt = varCntTrgt + 1

                        # Time of next target event:
                        varTmeTrgt = vecTrgt[varCntTrgt]

            # Has the participant's response not been reported yet, and is it
            # still within the time window?
            if (varSwtRspLog == 1) and (varTme02 <= (varTme03 + varHitTme)):

                # Check for and log participant's response:
                lstRsps = event.getKeys(keyList=[strTrgtKey],
                                        timeStamped=False)

                # Check whether the list has the correct length:
                if len(lstRsps) == 1:

                    # Does the list contain the response key?
                    if lstRsps[0] == strTrgtKey:

                        # Log hit:
                        logging.data('Hit')

                        # Count hit:
                        varCntHit += 1

                        # After logging the hit, we have to switch off the
                        # response logging, so that the same hit is not logged
                        # over and over again:
                        varSwtRspLog = 0

            elif (varSwtRspLog == 1) and (varTme02 > (varTme03 + varHitTme)):

                # Log miss:
                logging.data('Miss')

                # Count miss:
                varCntMis += 1

                # If the subject does not respond to the target within time, we
                # log this as a miss and set varSwtRspLog to zero (so that the
                # response won't be logged as a hit anymore afterwards):
                varSwtRspLog = 0

            # *****************************************************************
            # *** Grating control

            # If a grating is shown, which orientation, position, and contrast?
            if lgcOn:

                # Change grating polarity:
                if (varTme04 + varGrtDur) <= varTme05:

                    if varSwtGrt == 0:
                        varSwtGrt = 1
                        objBar.contrast = 1.0

                    else:
                        varSwtGrt = 0
                        objBar.contrast = -1.0

                    # Remember time at which grating polarity was switched:
                    varTme04 = objClck.getTime()

            # Update current time:
            # varTme02 = objClck.getTime()

            # Update current time:
            # varTme05 = objClck.getTime()

        if lgcLogMde:

            # Temporary array for single frame (3 values per pixel - RGB):
            aryBuff[:, :, :] = objWin.getMovieFrame(buffer='front')

            # Clear frames (otherwise stack of frames will pile up in memory):
            objWin.movieFrames = []

            # We only save one value per pixel per volume (because the stimuli
            # are greyscale we discard 2nd and 3rd RGB dimension):
            aryRgb = aryBuff[:, :, 0]

            # Sample the relevant part of the screen (all the screen if in
            # full screen mode, central square otherwise).0
            aryRgb = aryRgb[:, varCrpX:(varPixX - varCrpX)]

            # Only sample every second pixel:
            aryRgb = aryRgb[::2, ::2]

            # On first frame, get pixel value of background intensity:
            if idxVol == 0:
                varBck = mode(aryRgb, axis=None)[0]

            # The stimulus log is supposed to contain information about where
            # the stimulus was presented on each volume, and at which contrast.
            # The pattern inside the stimulus (chequerboard) is not of
            # interest. Therefore, we create a logical array (True = stimulus
            # was present on this pixel).
            aryRgb = np.not_equal(aryRgb, varBck).astype(np.int8)

            # Contrast value on current volume:
            varTmpMax = int(np.around(255.0 * aryDsg[idxVol, 3]))

            # Rescale to range 0 to 255:
            aryRgb = np.multiply(aryRgb, varTmpMax).astype(np.uint8)

            # Hard copy:
            aryFrames[:, :, idxFrame] = np.copy(aryRgb)

            idxFrame = idxFrame + 1

        # Check whether exit keys have been pressed:
        if func_exit() == 1:
            break

    # *************************************************************************
    # *** Feedback

    logging.data('------End of the experiment.------')

    # Performance feedback only if there were any targets:
    if 0.0 < float(varCntHit + varCntMis):

        # Ratio of hits:
        varHitRatio = float(varCntHit) / float(varCntHit + varCntMis)

        # Present participant with feedback on her target detection
        # performance:
        if 0.99 < varHitRatio:
            # Perfect performance:
            strFeedback = ('You have detected ' + str(varCntHit) +
                           ' targets out of ' + str(varCntHit + varCntMis) +
                           '\n' + 'Keep up the good work :)')
        elif 0.9 < varHitRatio:
            # OKish performance:
            strFeedback = ('You have detected ' + str(varCntHit) +
                           ' targets out of ' + str(varCntHit + varCntMis) +
                           '\n' + 'There is still room for improvement ;)')
        else:
            # Low performance:
            strFeedback = ('You have detected ' + str(varCntHit) +
                           ' targets out of ' + str(varCntHit + varCntMis) +
                           '\n' + 'Please try to focus more :(')

        # Create text object:
        objTxtTmr = visual.TextStim(objWin,
                                    text=strFeedback,
                                    font="Courier New",
                                    pos=(0.0, 0.0),
                                    color=(1.0, 1.0, 1.0),
                                    colorSpace='rgb',
                                    opacity=1.0,
                                    contrast=1.0,
                                    ori=0.0,
                                    height=0.5,
                                    antialias=True,
                                    alignHoriz='center',
                                    alignVert='center',
                                    flipHoriz=False,
                                    flipVert=False,
                                    autoLog=False)

        if not (lgcLogMde):

            # Show feedback text:
            varTme04 = objClck.getTime()
            while varTme02 < (varTme04 + 3.0):
                objTxtTmr.draw()
                objWin.flip()
                varTme02 = objClck.getTime()

        # Log total number of hits and misses:
        logging.data(('Number of hits: ' + str(varCntHit)))
        logging.data(('Number of misses: ' + str(varCntMis)))
        logging.data(('Percentage of hits: ' +
                      str(np.around((varHitRatio * 100.0), decimals=1))))

    # *************************************************************************
    # *** End of the experiment

    # Make the mouse cursor visible again:
    event.Mouse(visible=True)

    # Close window:
    objWin.close()

    # *************************************************************************
    # *** Logging mode

    # Save screenshots (logging mode):
    if lgcLogMde:

        print('Saving screenshots')

        # Check whether target directory for frames (screenshots) for frames
        # exists, if not create it:
        lgcDir = os.path.isdir(strPthFrm)

        # If directory does not exist, create it:
        if not (lgcDir):
            # Create direcotry for segments:
            os.mkdir(strPthFrm)

        # Save stimulus frame array to npy file:
        np.savez_compressed((strPthFrm + os.path.sep + 'stimulus_log'),
                            aryFrames=aryFrames)

        # Loop through volumes and save PNGs:
        for idxVol in range(varNumVol):

            # print(('---Frame '
            #       + str(idxVol)
            #       + ' out of '
            #       + str(int(varNumVol))))

            # Create image:
            objImg = Image.fromarray(aryFrames[:, :, idxVol], mode='L')

            # File name (with leading zeros, e.g. '*_004' or '*_042'). For
            # consistency with earlier versions, the numbering of frames (PNG
            # files  corresponding to fMRI volumes) starts at '1' (not at '0').
            strTmpPth = (strPthFrm + os.path.sep + 'frame_' +
                         str(idxVol + 1).zfill(3) + '.png')

            # Save image to disk:
            objImg.save(strTmpPth)

    # *************************************************************************
    # *** Close everyting

    core.quit()
    monitors.quit()
    logging.quit()
    event.quit()
Exemplo n.º 22
0
if refr_rate is not None:
    print 'refresh rate: %i' % refr_rate
    frameDur = 1.0 / round(refr_rate)
    print 'actual frame dur: %f' % frameDur
else:
    # couldnt get reliable measure, guess
    frameDur = 1.0 / 60.0
    print 'fake frame dur: %f' % frameDur

logFile.write('RefreshRate=' + unicode(refr_rate) + '\n')
logFile.write('FrameDuration=' + unicode(frameDur) + '\n')

# define clock
clock = core.Clock()
logging.setDefaultClock(clock)

# %%
"""STIMULI"""
# divide the dotSpeed by the refresh rate
dotSpeed = dotSpeed / refr_rate

# log stimulus properties defined above
logFile.write('nDots=' + unicode(nDots) + '\n')
logFile.write('speed=' + unicode(dotSpeed) + '\n')
logFile.write('dotSize=' + unicode(dotSize) + '\n')
logFile.write('fieldSizeRadius=' + unicode(FieldSizeRadius) + '\n')

# initialise moving dot stimuli
dotPatch = visual.ElementArrayStim(myWin,
                                   fieldPos=(0.0, 0.0),
Exemplo n.º 23
0
    print 'User Cancelled'
#    win.close()
    core.quit()

from target_time_cyclone_parameters import*
#try: key = pradigm_ver
#actual= var_chanign[key]

from target_time_cyclone_variables import*


#============================
# LOG PARADIGM PARAMETERS
#============================

logging.setDefaultClock(exp_clock)                                       #use this for
logging.console.setLevel(logging.DATA)                               #do NOT set to INFO! Way too much logging, crashes system
logger = logging.LogFile(log_filename,logging.DATA,'w')
win.setRecordFrameIntervals(True)                                    #capture frame intervals
win.saveFrameIntervals(fileName=log_filename, clear=False)           #write frame intervals to log_filename

#Vars to log:
win.logOnFlip('paradigm_name = '+str(paradigm_name), logging.DATA)
win.logOnFlip('paradigm_version = '+str(paradigm_version), logging.DATA)
win.logOnFlip('paradigm_type = '+str(paradigm_type), logging.DATA)
win.logOnFlip('use_rtbox = '+str(use_rtbox), logging.DATA)
win.logOnFlip('debug_mode = '+str(debug_mode), logging.DATA)
win.logOnFlip('starting_block = '+str(starting_block), logging.DATA)
win.logOnFlip('n_blocks = '+str(n_blocks), logging.DATA)
win.logOnFlip('n_trials = '+str(n_trials), logging.DATA)
win.logOnFlip('n_fullvis = '+str(n_fullvis), logging.DATA)
Exemplo n.º 24
0
        while condition_order[0]=='REST':
            random.shuffle(condition_order)
            #print condition_order

        for trial_type in condition_order:
            runs[run].append(stimuli[trial_type].pop())




# setup logging #
log_file = logging.LogFile("logs/%s.log" % (subj_id),  level=logging.DATA, filemode="w")

globalClock = core.Clock()
logging.setDefaultClock(globalClock)


def do_run(run_number, trials):

    timer = core.Clock()

    # 1. add ready screen and wait for trigger
    ready_screen.draw()
    win.flip()
    event.waitKeys(keyList='t')

    # reset globalClock
    globalClock.reset()

    # send START log event
Exemplo n.º 25
0
# Switch that is used to control the logging of target events:
varSwtTrgtLog = 1

# Control the logging of participant responses:
varSwtRspLog = 0

# The key that the participant has to press after a target event:
strTrgtKey = '1'

# Counter for correct/incorrect responses:
varCntHit = 0  # Counter for hits
varCntMis = 0  # Counter for misses

# Set clock for logging:
logging.setDefaultClock(objClck)

# Add time stamp and experiment name to metadata:
dicExpInfo['Date'] = data.getDateStr().encode('utf-8')
dicExpInfo['Experiment_Name'] = strExpNme

# Path of this file:
strPthMain = os.path.dirname(os.path.abspath(__file__))

# Get parent path:
strPthPrnt = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

# Path of logging folder (parent to subject folder):
strPthLog = (strPthPrnt + os.path.sep + 'log')

# If it does not exist, create subject folder for logging information
Exemplo n.º 26
0
waitStim = visual.TextStim(currWindow,
                           text=readyMessage[infos['language']],
                           color='gold',
                           wrapWidth=100,
                           pos=(0, 0))

waitStim.draw()
currWindow.flip()

# Wait for trigger
out = event.waitKeys(maxWait=inf, keyList=['5'], timeStamped=True)

# Reset Clock
globalClock = core.Clock()
logging.setDefaultClock(globalClock)

#First RED Cross
currWindow.logOnFlip('', level=logging.EXP + 1)
cross.draw()
currWindow.flip()
core.wait(infos['durRest'])

nbBlock = 0

while nbBlock <= infos['nbBlocks']:
    currWindow.logOnFlip('', level=logging.EXP + 2)
    cross.setLineColor('green')
    cross.draw()
    currWindow.flip()
    startBlock = core.getTime()
Exemplo n.º 27
0
# store info about the experiment session
expName = "None"  # from the Builder filename that created this script
expInfo = {"participant": "", "session": "01"}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo["date"] = data.getDateStr()  # add a simple timestamp
expInfo["expName"] = expName
# setup files for saving
if not os.path.isdir("data"):
    os.makedirs("data")  # if this fails (e.g. permissions) we will get error
filename = "data" + os.path.sep + "%s_%s" % (expInfo["participant"], expInfo["date"])
logFile = logging.LogFile(filename + ".log", level=logging.INFO)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file
logging.setDefaultClock(experimentClock)
# setup the Window
win = visual.Window(
    size=(1920, 1080),
    fullscr=True,
    screen=0,
    allowGUI=False,
    allowStencil=False,
    monitor="testMonitor",
    color="black",
    colorSpace="rgb",
    units="norm",
)

errorCircle = visual.Circle(win, radius=0.5, edges=100)
errorCircle.setAutoDraw(True)