What are you trying to achieve?:
I’m trying to do a test where:
- one word among six is first shown on the screen, and the candidate needs to hit one of two buttons (only one correct), and then
- one image among six is shown, and the candidate needs to hit one of two buttons (only one correct).
- This loop is repeated six times, until each of the six words and images have been selected (random mode).
What did you try to make it work?:
I did the following code (corresponds to a builder of two sequential routines, one for the words, one for the images, and one loop with the conditions excel file associated):
#!/usr/bin/env python
-- coding: utf-8 --
“”"
This experiment was created using PsychoPy2 Experiment Builder (v1.90.1),
on Thu Apr 26 16:05:08 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
Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(file)).decode(sys.getfilesystemencoding())
os.chdir(_thisDir)
Store info about the experiment session
expName = ‘finalversion’ # 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 = 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=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 “Words”
WordsClock = core.Clock()
WordStimuli = visual.TextStim(win=win, name=‘WordStimuli’,
text=‘default text’,
font=‘Arial’,
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=‘black’, colorSpace=‘rgb’, opacity=1,
depth=0.0);
Initialize components for Routine “Images”
ImagesClock = 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
trials = data.TrialHandler(nReps=2, method=‘random’,
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(‘PsychoPyProgram/ConditionsBlock1.xlsx’),
seed=None, 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 "Words"-------
t = 0
WordsClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.500000)
# update component parameters for each repeat
WordStimuli.setText(StimulusPresented)
WordResponse = event.BuilderKeyResponse()
# keep track of which components have finished
WordsComponents = [WordStimuli, WordResponse]
for thisComponent in WordsComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "Words"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = WordsClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *WordStimuli* updates
if t >= 0.0 and WordStimuli.status == NOT_STARTED:
# keep track of start time/frame for later
WordStimuli.tStart = t
WordStimuli.frameNStart = frameN # exact frame index
WordStimuli.setAutoDraw(True)
frameRemains = 0.0 + 1.5- win.monitorFramePeriod * 0.75 # most of one frame period left
if WordStimuli.status == STARTED and t >= frameRemains:
WordStimuli.setAutoDraw(False)
# *WordResponse* updates
if t >= 0.0 and WordResponse.status == NOT_STARTED:
# keep track of start time/frame for later
WordResponse.tStart = t
WordResponse.frameNStart = frameN # exact frame index
WordResponse.status = STARTED
# keyboard checking is just starting
win.callOnFlip(WordResponse.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 WordResponse.status == STARTED and t >= frameRemains:
WordResponse.status = STOPPED
if WordResponse.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 WordResponse.keys == []: # then this was the first keypress
WordResponse.keys = theseKeys[0] # just the first key pressed
WordResponse.rt = WordResponse.clock.getTime()
# was this 'correct'?
if (WordResponse.keys == str(AnswerStimulus)) or (WordResponse.keys == AnswerStimulus):
WordResponse.corr = 1
else:
WordResponse.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 WordsComponents:
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 "Words"-------
for thisComponent in WordsComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if WordResponse.keys in ['', [], None]: # No response was made
WordResponse.keys=None
# was no response the correct answer?!
if str(AnswerStimulus).lower() == 'none':
WordResponse.corr = 1 # correct non-response
else:
WordResponse.corr = 0 # failed to respond (incorrectly)
# store data for trials (TrialHandler)
trials.addData('WordResponse.keys',WordResponse.keys)
trials.addData('WordResponse.corr', WordResponse.corr)
if WordResponse.keys != None: # we had a response
trials.addData('WordResponse.rt', WordResponse.rt)
# ------Prepare to start Routine "Images"-------
t = 0
ImagesClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.500000)
# update component parameters for each repeat
ImageStimuli.setImage(ImagePresented)
ImageResponse = event.BuilderKeyResponse()
# keep track of which components have finished
ImagesComponents = [ImageStimuli, ImageResponse]
for thisComponent in ImagesComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "Images"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = ImagesClock.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)
# *ImageResponse* updates
if t >= 0.0 and ImageResponse.status == NOT_STARTED:
# keep track of start time/frame for later
ImageResponse.tStart = t
ImageResponse.frameNStart = frameN # exact frame index
ImageResponse.status = STARTED
# keyboard checking is just starting
win.callOnFlip(ImageResponse.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 ImageResponse.status == STARTED and t >= frameRemains:
ImageResponse.status = STOPPED
if ImageResponse.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 ImageResponse.keys == []: # then this was the first keypress
ImageResponse.keys = theseKeys[0] # just the first key pressed
ImageResponse.rt = ImageResponse.clock.getTime()
# was this 'correct'?
if (ImageResponse.keys == str(AnswerImage)) or (ImageResponse.keys == AnswerImage):
ImageResponse.corr = 1
else:
ImageResponse.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 ImagesComponents:
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 "Images"-------
for thisComponent in ImagesComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if ImageResponse.keys in ['', [], None]: # No response was made
ImageResponse.keys=None
# was no response the correct answer?!
if str(AnswerImage).lower() == 'none':
ImageResponse.corr = 1 # correct non-response
else:
ImageResponse.corr = 0 # failed to respond (incorrectly)
# store data for trials (TrialHandler)
trials.addData('ImageResponse.keys',ImageResponse.keys)
trials.addData('ImageResponse.corr', ImageResponse.corr)
if ImageResponse.keys != None: # we had a response
trials.addData('ImageResponse.rt', ImageResponse.rt)
thisExp.nextEntry()
completed 2 repeats of ‘trials’
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()
What specifically went wrong when you tried that?:
Everything worked perfectly, except that: given that there is only one condition file, it always selects the word and then the Image of the same row of the Excel file associated to the conidtions. But I need that this choice is made completely randomly, i.e. that one random row is selected for the words routine, and then one random row is selected for the image routine. In other words, I would need to indicate specfic selection conditions to each of the two trials, without creating new loops. Is that possible?