doodle_lastrun.py 13.2 KB
Newer Older
Ruben van Bergen's avatar
Ruben van Bergen committed
1 2 3 4
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2021.2.0),
5
    on augustus 03, 2021, at 17:29
Ruben van Bergen's avatar
Ruben van Bergen committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
If you publish work using this script the most relevant publication is:

    Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019) 
        PsychoPy2: Experiments in behavior made easy Behav Res 51: 195. 
        https://doi.org/10.3758/s13428-018-01193-y

"""

from __future__ import absolute_import, division

from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock, colors
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
                                STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
                   sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle, choice as randchoice
import os  # handy system and path functions
import sys  # to get file system encoding

from psychopy.hardware import keyboard



# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '2021.2.0'
expName = 'doodle'  # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion

# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath='C:\\Users\\ruben\\Dropbox\\Kriegeskorte_Postdoc\\OcclusionTask\\doodle_lastrun.py',
    savePickle=True, saveWideText=True,
    dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp
frameTolerance = 0.001  # how close to onset before 'same' frame

# Start Code - component code to be run after the window creation

# Setup the Window
win = visual.Window(
    size=(1024, 768), fullscr=True, screen=0, 
    winType='pyglet', allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# Setup eyetracking
ioDevice = ioConfig = ioSession = ioServer = eyetracker = None

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
88 89 90 91
import random

random.seed(1234) #This needs to be removed!! 

Ruben van Bergen's avatar
Ruben van Bergen committed
92 93
font='Arial'
stim_size=0.25
94 95 96
fix_size=0.05
stim_win_size = stim_size*1.25 #Size of (square) window in which digits can appear (window applies to digit borders - not digit centers)

97
frame_rate = win.getActualFrameRate()
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
frame_dur = 1/frame_rate
slack = frame_dur*0.25

stim_dur = 0.500
stim_frames = round(stim_dur/frame_dur)
stim_dur = stim_frames * frame_dur #Correct stimulus duration so it's an integer number of frames

mask_dur = 0.5
mask_frames = round(mask_dur/frame_dur)
mask_num_crops = 100

crop_frac = 0.2 #Crop size is determined as a fraction of the height of the digit
crop_size = stim_size*crop_frac
crop_center_win = stim_win_size-crop_size/2

pos_digits = list(np.arange(10))
num_digits = 4

rsp_dur = 3

font = 'Arial'
kb = keyboard.Keyboard()

numKeys = [str(x) for x in range(10)]
listenKeys = numKeys.copy()
listenKeys.extend(['return', 'space', 'escape', 'backspace'])

visual.TextStim(win, text="Generating stimuli, please wait...", height=0.05).draw()
win.flip()
Ruben van Bergen's avatar
Ruben van Bergen committed
127 128 129

digit_stims = list()
crop_stims = list()
130
for d in range(10):    
Ruben van Bergen's avatar
Ruben van Bergen committed
131
    image_path = 'digit_ims/font_' + font + '-size_512x512-digit_' + str(d) +'.png'
132 133
    digit_stims.append(visual.ImageStim(win=win, image=image_path, interpolate=True)) #Opening stims without size specification loads them in original aspect ratio
    siz = digit_stims[-1].size #This allows us to change the height of the digit while maintaining the aspect ratio
134
    siz /= siz[1]/stim_size #Because of python weirdness this also modifies the size property of the stimulus
135 136 137 138 139 140
        
    crop_path = image_path.replace('.png', '') + '_crops/'
    for crop_file in os.listdir(crop_path):
        if '.png' in crop_file:
            crop_stims.append(visual.ImageStim(win=win, image=crop_path+crop_file, size=stim_size*crop_frac, interpolate=True))           

141
digit_sizes = [digit_stims[d].size for d in range(10)]
142 143 144 145 146 147 148 149

fixation = visual.ShapeStim(win, 
    vertices=((0, -fix_size), (0, fix_size), (0,0), (-fix_size,0), (fix_size, 0)),
    lineWidth=2,
    closeShape=False,
    lineColor="white"
)

150
digit_center_wins = [stim_win_size-d/2 for d in digit_sizes]
151 152 153 154 155

rsp_prompt = visual.TextStim(win, text='Digits recognized:', height=0.03, pos=(0, 0.05))
rsp_bar = visual.Rect(win, rsp_prompt.boundingBox[0]*1, rsp_prompt.boundingBox[1]*1.5, fillColor=1, units='pix')
prog_bar = visual.Rect(win, rsp_bar.width, rsp_prompt.boundingBox[1]*0.25, fillColor='red', units='pix')
prog_bar.pos[1] = -rsp_prompt.boundingBox[1]*(1.5/2 + 0.25/2)
Ruben van Bergen's avatar
Ruben van Bergen committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

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

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=5.0, method='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=[None],
    seed=1234, name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial:
        exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial:
            exec('{} = thisTrial[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "trial"-------
    continueRoutine = True
    # update component parameters for each repeat
183 184 185 186
    fixation.draw()
    win.flip()
    core.wait(1)
    
187 188 189 190
    this_digits = random.sample(pos_digits, num_digits)
    #digit_pos = np.random.rand(num_digits,2)*digit_center_wins[this_digits] - digit_center_wins[this_digits]/2
    digit_pos_x = [random.random()*digit_center_wins[d][0] - digit_center_wins[d][0]/2 for d in this_digits]
    digit_pos_y = [random.random()*digit_center_wins[d][1] - digit_center_wins[d][1]/2 for d in this_digits]
191 192 193
        
    for di in range(len(this_digits)):
        this_digit = this_digits[di]
194
        digit_stims[this_digit].setPos((digit_pos_x[di],digit_pos_y[di]))
195 196 197 198 199 200 201 202
        digit_stims[this_digit].draw()
    
    stim_tstart = win.flip() #Flip screen and record estimated time
    
    """ 
    Pre-draw the mask stimulus since we presumably have some time to do so while we're 
    waiting for the stimulus to stop being on screen.
    """
203 204 205
    crop_indices = [random.randint(0, len(crop_stims)-1) for i in range(mask_num_crops)]
    crop_pos_x = [random.random()*crop_center_win-crop_center_win/2 for i in range(mask_num_crops)]
    crop_pos_y = [random.random()*crop_center_win-crop_center_win/2 for i in range(mask_num_crops)]
206 207 208
    
    for i in range(mask_num_crops):
        this_ind = crop_indices[i]
209
        crop_stims[this_ind].setPos((crop_pos_x[i],crop_pos_y[i]))    
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        crop_stims[this_ind].draw()
    
    t = core.getTime()
    
    while t < stim_tstart + stim_dur - slack:
        t = core.getTime()
    
    mask_tstart = win.flip()
    
    rsp_prompt.draw() #Do this ahead of time 
    rsp_bar.draw()
    
    t = core.getTime()
    while t < mask_tstart + mask_dur - slack:
        t = core.getTime()
    
    mask_tend = win.flip()
    
    ################# Response ################
    
    keystr = ''
    rsp_vis = visual.TextStim(win, text=keystr, height=0.03, color='black')
    confirmed=False
    stop_exp=False
    
    rsp_tstart = core.getTime()
    while not confirmed and core.getTime()<rsp_tstart+rsp_dur:    
        keys = kb.getKeys(keyList = listenKeys)
        old_keystr = keystr
    
        t_elap = core.getTime()-rsp_tstart
        t_elap_frac = t_elap/rsp_dur        
        prog_bar.pos[0] = (t_elap_frac-1)*rsp_bar.width/2 
        prog_bar.width = rsp_bar.width*t_elap_frac
    
        for thisKey in keys:
            if thisKey == 'return' or thisKey == 'space' or thisKey=='escape':
                confirmed = True
                if thisKey=='escape':                     
                    visual.TextStim(win, 'Really quit (y/n)?', height=0.03).draw()
                    win.flip()
                    keys2 = kb.waitKeys(keyList=['y','n'])
252
                    for kk in keys2:
253 254 255 256 257
                        if kk=='y': stop_exp=True
                    if not stop_exp:
                        confirmed=False                    
    
            if not confirmed:
258
                if thisKey.name in numKeys:
259 260 261 262 263 264 265 266 267 268 269 270
                    keystr+=thisKey.name
                if thisKey=='backspace':
                    keystr=keystr[:-1]
        
        if old_keystr != keystr and not confirmed:
            rsp_vis.setText(keystr)
        rsp_prompt.draw()
        rsp_bar.draw()
        rsp_vis.draw()
        prog_bar.draw()
        win.flip()
    
271
    #if stop_exp: break
272
    
273 274
    #rsp_int = np.unique(np.asarray([int(c) for c in keystr]))
    rsp_int = list(set([int(c) for c in keystr]))
275 276 277
    
    ################# Feedback ################
    
278 279 280 281 282 283
    #all_d = np.unique(np.concatenate((rsp_int, this_digits)))
    all_d = list(set(rsp_int + this_digits))
    num_correct=0
    for x in rsp_int:
        if x in this_digits: num_correct+=1 
    #num_correct = np.isin(rsp_int, this_digits).sum()    
284 285 286 287 288 289 290
    perc_correct = num_correct/len(all_d)
    
    fbstr = str(round(perc_correct*100)) + '% correct'
    visual.TextStim(win, text=fbstr, height=0.03).draw()
    win.flip()
    core.wait(1)
    
Ruben van Bergen's avatar
Ruben van Bergen committed
291
    # keep track of which components have finished
292
    trialComponents = []
Ruben van Bergen's avatar
Ruben van Bergen committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306
    for thisComponent in trialComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "trial"-------
307
    while continueRoutine:
Ruben van Bergen's avatar
Ruben van Bergen committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        # get current time
        t = trialClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=trialClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in trialComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "trial"-------
    for thisComponent in trialComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
336 337
    # the Routine "trial" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
Ruben van Bergen's avatar
Ruben van Bergen committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    thisExp.nextEntry()
    
# completed 5.0 repeats of 'trials'


# Flip one final time so any remaining win.callOnFlip() 
# and win.timeOnFlip() tasks get executed before quitting
win.flip()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv', delim='auto')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()