OS (e.g. Win10):
PsychoPy version v2020.1.3
What are you trying to achieve?:
I am trying to get psychopy to compare user input to the correct answer in a conditions file and be able to display that to them at the end of the experiement. I’m trying to save just their scores and be able to test if this feedback helps them improve, etc.
What did you try to make it work?:
I have observed other code but I am not using the keyboard but a rating slider with categories.
Here is the total code so far:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2020.1.3),
on November 06, 2020, at 10:53
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
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
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 = '2020.1.3'
expName = 'blockedTrials' # from the Builder filename that created this script
expInfo = {'session': '001', 'participant': '', 'age': '', 'gender': '', 'ethnicity': ''}
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\\micha\\Desktop\\1_BASE_TEMPLATE_PSYCHOPY\\1_template.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 before the window creation
# Setup the Window
win = visual.Window(
size=[1920, 1080], fullscr=True, screen=4,
winType='pyglet', allowGUI=True, allowStencil=False,
monitor='testMonitor', color=[-0.396,-0.396,-0.396], 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
# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()
# Initialize components for Routine "readyMessage"
readyMessageClock = core.Clock()
Instructions = visual.TextStim(win=win, name='Instructions',
text="I am going to show you some people's faces and I want you to tell me how they feel. I want you to tell me if they are happy, sad, angry, or fearful (scared). Let's get started.\n(Esc will quit)\n\n\nPress any key to continue",
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
starttest = keyboard.Keyboard()
mouse = event.Mouse(win=win)
x, y = [None, None]
mouse.mouseClock = core.Clock()
# Initialize components for Routine "trial"
trialClock = core.Clock()
image = visual.ImageStim(
win=win,
name='image', units='height',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(0.6936,0.4704) ,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
rating = visual.RatingScale(win=win, name='rating', marker='triangle', size=1.0, pos=[0.0, -0.6], choices=['HAPPY', 'SAD', 'ANGRY', 'FEARFUL'], tickHeight=-1)
score = 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
# ------Prepare to start Routine "readyMessage"-------
continueRoutine = True
# update component parameters for each repeat
starttest.keys = []
starttest.rt = []
_starttest_allKeys = []
# setup some python lists for storing info about the mouse
gotValidClick = False # until a click is received
# keep track of which components have finished
readyMessageComponents = [Instructions, starttest, mouse]
for thisComponent in readyMessageComponents:
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")
readyMessageClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
# -------Run Routine "readyMessage"-------
while continueRoutine:
# get current time
t = readyMessageClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=readyMessageClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *Instructions* updates
if Instructions.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Instructions.frameNStart = frameN # exact frame index
Instructions.tStart = t # local t and not account for scr refresh
Instructions.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Instructions, 'tStartRefresh') # time at next scr refresh
Instructions.setAutoDraw(True)
# *starttest* updates
waitOnFlip = False
if starttest.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
starttest.frameNStart = frameN # exact frame index
starttest.tStart = t # local t and not account for scr refresh
starttest.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(starttest, 'tStartRefresh') # time at next scr refresh
starttest.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(starttest.clock.reset) # t=0 on next screen flip
win.callOnFlip(starttest.clearEvents, eventType='keyboard') # clear events on next screen flip
if starttest.status == STARTED and not waitOnFlip:
theseKeys = starttest.getKeys(keyList=None, waitRelease=False)
_starttest_allKeys.extend(theseKeys)
if len(_starttest_allKeys):
starttest.keys = _starttest_allKeys[-1].name # just the last key pressed
starttest.rt = _starttest_allKeys[-1].rt
# a response ends the routine
continueRoutine = False
# *mouse* updates
if mouse.status == NOT_STARTED and t >= 0.0-frameTolerance:
# keep track of start time/frame for later
mouse.frameNStart = frameN # exact frame index
mouse.tStart = t # local t and not account for scr refresh
mouse.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(mouse, 'tStartRefresh') # time at next scr refresh
mouse.status = STARTED
mouse.mouseClock.reset()
prevButtonState = mouse.getPressed() # if button is down already this ISN'T a new click
if mouse.status == STARTED: # only update if started and not finished!
buttons = mouse.getPressed()
if buttons != prevButtonState: # button state changed?
prevButtonState = buttons
if sum(buttons) > 0: # state changed to a new click
continueRoutine = False
# 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 readyMessageComponents:
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 "readyMessage"-------
for thisComponent in readyMessageComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('Instructions.started', Instructions.tStartRefresh)
thisExp.addData('Instructions.stopped', Instructions.tStopRefresh)
# store data for thisExp (ExperimentHandler)
thisExp.addData('mouse.started', mouse.tStart)
thisExp.addData('mouse.stopped', mouse.tStop)
thisExp.nextEntry()
# the Routine "readyMessage" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
EmotionTests = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('facesBlock.csv'),
seed=None, name='EmotionTests')
thisExp.addLoop(EmotionTests) # add the loop to the experiment
thisEmotionTest = EmotionTests.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisEmotionTest.rgb)
if thisEmotionTest != None:
for paramName in thisEmotionTest:
exec('{} = thisEmotionTest[paramName]'.format(paramName))
for thisEmotionTest in EmotionTests:
currentLoop = EmotionTests
# abbreviate parameter names if possible (e.g. rgb = thisEmotionTest.rgb)
if thisEmotionTest != None:
for paramName in thisEmotionTest:
exec('{} = thisEmotionTest[paramName]'.format(paramName))
# ------Prepare to start Routine "trial"-------
continueRoutine = True
# update component parameters for each repeat
image.setImage(stimFile)
rating.reset()
# keep track of which components have finished
trialComponents = [image, rating]
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"-------
while continueRoutine:
# 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
# *image* updates
if image.status == NOT_STARTED and tThisFlip >= .1-frameTolerance:
# keep track of start time/frame for later
image.frameNStart = frameN # exact frame index
image.tStart = t # local t and not account for scr refresh
image.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(image, 'tStartRefresh') # time at next scr refresh
image.setAutoDraw(True)
if image.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > image.tStartRefresh + 2-frameTolerance:
# keep track of stop time/frame for later
image.tStop = t # not accounting for scr refresh
image.frameNStop = frameN # exact frame index
win.timeOnFlip(image, 'tStopRefresh') # time at next scr refresh
image.setAutoDraw(False)
# *rating* updates
if rating.status == NOT_STARTED and t >= 0.0-frameTolerance:
# keep track of start time/frame for later
rating.frameNStart = frameN # exact frame index
rating.tStart = t # local t and not account for scr refresh
rating.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(rating, 'tStartRefresh') # time at next scr refresh
rating.setAutoDraw(True)
continueRoutine &= rating.noResponse # a response ends the trial
# 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)
EmotionTests.addData('image.started', image.tStartRefresh)
EmotionTests.addData('image.stopped', image.tStopRefresh)
# store data for EmotionTests (TrialHandler)
EmotionTests.addData('rating.response', rating.getRating())
EmotionTests.addData('rating.rt', rating.getRT())
EmotionTests.addData('rating.started', rating.tStart)
EmotionTests.addData('rating.stopped', rating.tStop)
score = 0
print ("RatingScale rating")
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'EmotionTests'
# 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')
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()
Please Note: I have used the keyboard only as an option to begin the experiment, it is not used to record answers.
Here’s screenshots of about everything, and please note the current custom code is not intended to do anything like scoring I was just trying LOTS of things to see if I could get it to do anything and go from there. Here’s the screenshots:



Also two questions,
- would the three day workshop help me learn how to do this custom code?
- is this the best place to put this question?