psychopy.org | Reference | Downloads | Github

Convert Psychopy Output (Response Latencies) into int?

Hi guys! I did the code below and it worked perfectly in terms of presentation timings etc. and data storage. The only thing that I want is that the output of my column ‘Response_Images.rt’ is of int type, and not of string type. How can I do this? If that’s not possible, do you know how I could open the csv file in python later on and convert only that specific column from str into int?

#!/usr/bin/env python

-- coding: utf-8 --

“”"
This experiment was created using PsychoPy2 Experiment Builder (v1.90.1),
on Wed Apr 25 19:19:03 2018
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
“”"

from future import absolute_import, division
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
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
import os # handy system and path functions
import sys # to get file system encoding

Store info about the experiment session

expName = u’simplifiedlasttry’ # from the Builder filename that created this script
expInfo = {‘session’: ‘001’, ‘participant’: ‘’}
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

Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc

filename = “/Users/cezi/Desktop/ResultData/” + 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=None,
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

Start Code - component code to be run before the window creation

Setup the Window

win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
allowGUI=False, allowStencil=False,
monitor=‘testMonitor’, color=[0,0,0], colorSpace=‘rgb’,
blendMode=‘avg’, useFBO=True)

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

Initialize components for Routine “trial”

trialClock = core.Clock()
ImageStimuli = visual.ImageStim(
win=win, name=‘ImageStimuli’,units=‘cm’,
image=‘sin’, mask=None,
ori=0, pos=(0, 0), size=(6.35,8.89),
color=[1,1,1], colorSpace=‘rgb’, opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)

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

Block1 = data.TrialHandler(nReps=3, method=‘random’,
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u’PsychoPyProgram/ConditionsBlock1.xlsx’),
seed=None, name=‘Block1’)
thisExp.addLoop(Block1) # add the loop to the experiment
thisBlock1 = Block1.trialList[0] # so we can initialise stimuli with some values

abbreviate parameter names if possible (e.g. rgb = thisBlock1.rgb)

if thisBlock1 != None:
for paramName in thisBlock1:
exec(’{} = thisBlock1[paramName]’.format(paramName))

for thisBlock1 in Block1:
currentLoop = Block1
# abbreviate parameter names if possible (e.g. rgb = thisBlock1.rgb)
if thisBlock1 != None:
for paramName in thisBlock1:
exec(’{} = thisBlock1[paramName]’.format(paramName))

# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset()  # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.500000)
# update component parameters for each repeat
ImageStimuli.setImage(ImagePresented)
Response_Images = event.BuilderKeyResponse()
# keep track of which components have finished
trialComponents = [ImageStimuli, Response_Images]
for thisComponent in trialComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = trialClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *ImageStimuli* updates
    if t >= 0.0 and ImageStimuli.status == NOT_STARTED:
        # keep track of start time/frame for later
        ImageStimuli.tStart = t
        ImageStimuli.frameNStart = frameN  # exact frame index
        ImageStimuli.setAutoDraw(True)
    frameRemains = 0.0 + 1.5- win.monitorFramePeriod * 0.75  # most of one frame period left
    if ImageStimuli.status == STARTED and t >= frameRemains:
        ImageStimuli.setAutoDraw(False)
    
    # *Response_Images* updates
    if t >= 0.0 and Response_Images.status == NOT_STARTED:
        # keep track of start time/frame for later
        Response_Images.tStart = t
        Response_Images.frameNStart = frameN  # exact frame index
        Response_Images.status = STARTED
        # keyboard checking is just starting
        win.callOnFlip(Response_Images.clock.reset)  # t=0 on next screen flip
        event.clearEvents(eventType='keyboard')
    frameRemains = 0.0 + 1.5- win.monitorFramePeriod * 0.75  # most of one frame period left
    if Response_Images.status == STARTED and t >= frameRemains:
        Response_Images.status = STOPPED
    if Response_Images.status == STARTED:
        theseKeys = event.getKeys(keyList=['e', 'i'])
        
        # check for quit:
        if "escape" in theseKeys:
            endExpNow = True
        if len(theseKeys) > 0:  # at least one key was pressed
            if Response_Images.keys == []:  # then this was the first keypress
                Response_Images.keys = theseKeys[0]  # just the first key pressed
                Response_Images.rt = Response_Images.clock.getTime()
                # was this 'correct'?
                if (Response_Images.keys == str(AnswerImage)) or (Response_Images.keys == AnswerImage):
                    Response_Images.corr = 1
                else:
                    Response_Images.corr = 0
    
    # 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
    
    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()
    
    # 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)
# check responses
if Response_Images.keys in ['', [], None]:  # No response was made
    Response_Images.keys=None
    # was no response the correct answer?!
    if str(AnswerImage).lower() == 'none':
       Response_Images.corr = 1  # correct non-response
    else:
       Response_Images.corr = 0  # failed to respond (incorrectly)
# store data for Block1 (TrialHandler)
Block1.addData('Response_Images.keys',Response_Images.keys)
Block1.addData('Response_Images.corr', Response_Images.corr)
if Response_Images.keys != None:  # we had a response
    Block1.addData('Response_Images.rt', Response_Images.rt)
thisExp.nextEntry()

completed 3 repeats of ‘Block1’

these shouldn’t be strictly necessary (should auto-save)

thisExp.saveAsWideText(filename+’.csv’)
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()