psychopy.org | Reference | Downloads | Github

Stimulus Timing issue

OS : Win10
PsychoPy version: 2020.2.10
Standard Standalone? (y)
What are you trying to achieve?:
Running a script with twenty blocks of (30s video + 15s ratings + 15s fixation ) . This has been running well for a couple of years on the same PC.

What specifically went wrong?:
The script starts with a 15s fixation but then there is very brief flicker followed by continuation of fixation for an extra ~5s which is followed by a 30s video. In the subsequent blocks the fixation period lasts for ~18s rather than 15s. However, the video and rating trial durations are presented correctly. My guess is that there seems to be a delay loading the videos. However I cannot figure out why this issue occurred suddenly if the PsychoPy version/PC etc has remained the same. I ran it on an older (3.2.1) and the latest (2021.2.3) version of PsychoPy as well and it still causes this delay. I ran it on a Mac and the stim duration for fixation is accurate. I could switch machines but it is important that I diagnose the issue on that PC so that this does not affect other users of that machine in the future. I’ve attached my script below. Any suggestions regarding what PC settings may have caused this? and/or if I can update some of the functions in the script ( which was written on PsychoPy1.8 and then edited to make it work on recent versions) to make it more “PC proof” so to speak. Thank you

#!/usr/bin/env python
from psychopy import visual, core, event, gui, logging
logging.console.setLevel(logging.CRITICAL)
from time import strftime
import random
import numpy
import linecache
from collections import defaultdict
from operator import itemgetter, sub
from random import shuffle
import os, sys

WINDOW_WIDTH = 1920
WINDOW_HEIGHT = 1080

DEBUG = False
PARTICIPANT_DATA = None
FRAME_RATE = None
GLOBAL_CLOCK = core.MonotonicClock()

h_videoList = ['H0.mp4',
'H1.mp4',
'H2.mp4',
'H5.mp4',
'H6.mp4',
'H7.mp4',
'H8.mp4',
'H9.mp4',
'HH3.mp4',
'HH7.mp4']

n_videoList = ['N0.mp4',
'N1.mp4',
'N3.mp4',
'N5.mp4',
'N6.mp4',
'N7.mp4',
'N8.mp4',
'N9.mp4' ,
'NN1.mp4' ,
'NN3.mp4']


random.shuffhle(h_videoList)
random.shuffle(n_videoList)
print('h_videoList is ', h_videoList)
print('n_videoList is ', n_videoList)
#################################
#VARIABLE BLOCK VIDEO LIST SETUP
#################################

n_first = n_videoList[0:1] #the first video is always n
n_rem = n_videoList[1:10] 
print('n_rem is ', n_rem)


###################################################################################
#SCHEME 1 : SEE vid2019.xls file for more info
#concatenating - present 1 n video first, then randomly present the remaining
#videos from the 4 conditions
###################################################################################

variable_scheme1 = n_first + \
                                 h_videoList[0:1] + \
                                 n_rem[0:1] + \
                                 n_rem[1:2] + \
                                 h_videoList[1:2] + \
                                 n_rem[2:3] + \
                                 h_videoList[2:3] + \
                                 n_rem[3:4] + \
                                 h_videoList[3:4] + \
                                 h_videoList[4:5] + \
                                 n_rem[4:5] + \
                                 h_videoList[5:6] + \
                                 n_rem[5:6] + \
                                 h_videoList[6:7] + \
                                 h_videoList[7:8] + \
                                 n_rem[6:7] + \
                                 n_rem[7:8] + \
                                 h_videoList[8:9] + \
                                 h_videoList[9:10] + \
                                 n_rem[8:9]

file1 = open("scheme1.txt","a")
file1.write(str(variable_scheme1))
file1.write('\n')
file1.close()
#print (str(variable_scheme1))
#######################################
##END OF SCHEME 1
#######################################

#################
#Setup Functions#
#################

# Prompts for subject input
def experimentSetup():
    dialogInfo = {'Participant Number': ''}
    dialog = gui.DlgFromDict(dictionary = dialogInfo, title = 'VideoScheme1')
    if dialog.OK and dialogInfo['Participant Number'] != '':
        globals()['PARTICIPANT_DATA'] = {'time': strftime("%Y-%m-%d  %H:%M:%S"),
            'subject': dialogInfo['Participant Number']}

def fileSetup():
    participantFile = 'scheme1_sub{}.csv'.format(PARTICIPANT_DATA['subject'])
    fh = open(participantFile, 'a')
    fh.write('Participant,onsetTime,instruction,videoFile,rating\n')
    return fh

# Sets up visual window and GUI for experiment
def windowSetup():
    win = visual.Window(size=(WINDOW_WIDTH, WINDOW_HEIGHT), color="black", units='pix', allowGUI='False', winType='pyglet')
    event.Mouse(visible=False)
    globals()['FRAME_RATE'] = win.getActualFrameRate()
    if DEBUG:
        print('FRAME_RATE: ', FRAME_RATE)

    return win

	
def writeToFile(fh, instruction, videoFile, rating):
    trialList = [PARTICIPANT_DATA['subject'], GLOBAL_CLOCK.getTime(), instruction, videoFile, rating]

    for i in range(0,len(trialList)):
        if trialList[i] is None:
            trialList[i] = 'None'

    trialString = ','.join(map(str,trialList))
    fh.write('{}\n'.format(trialString))	
	

###Experiment Functions###

#shows experiment instructions
def myInstructions1():
    psychopyTxt = visual.TextStim(win, color='white', 
        text = "Welcome to our MRI study. \n \
        \n \
        In this study, you will watch videos that may elicit different symptoms that may vary in their intensity. \n \
        \n \
        After you watch each video, you will be asked to rate which symptom, if any, feels the strongest. You will also be asked to rate the strength of that symptom.", units='norm', height=0.1, pos=[0.0, 0.0], alignHoriz='center',alignVert='center', wrapWidth=1.75)
    psychopyTxt.draw()
    win.flip()
    event.waitKeys(keyList=['space'])

def myInstructions2():
    psychopyTxt = visual.TextStim(win, color='white', 
        text = "After each video, you will first see a prompt that asks you to indicate which symptom, if any, feels the strongest.", units = 'norm', height=0.1, pos=[0.0, .65], alignHoriz='center',alignVert='center', wrapWidth=1.75)
    psychopyImage = visual.ImageStim(win, image = 'first_prompt.jpg', units = 'norm', size = [1.5, 1.5], pos = [0.0, -.35])
    psychopyTxt.draw()
    psychopyImage.draw()
    win.flip()
    event.waitKeys(keyList=['space'])
    
    
def myInstructions3():
    psychopyTxt = visual.TextStim(win, color='white', 
        text = "After you select the strongest symptom, you will be asked to rate how intense it is with the following scale.", units = 'norm', height=0.1, pos=[0.0, .65], alignHoriz='center',alignVert='center', wrapWidth=1.75)
    psychopyImage = visual.ImageStim(win, image = 'second_prompt.jpg', units = 'norm', size = [1.5, 1.5], pos = [0.0, -.35])
    psychopyTxt.draw()
    psychopyImage.draw()
    win.flip()
    event.waitKeys(keyList=['space'])
    

        
def myInstructions4():
		psychopyTxt = visual.TextStim(win, color='white',
			text = "After you enter your responses, you can relax and remain focused on the screen. \n \
			\n \
			After the prompts go away, a fixation cross (+) will appear. Please relax and stay focused on this fixation. Soon the next video will start. \n \
            \n \
            Across the duration of the task, make sure to keep your eyes open and try to stay as still as possible", units='norm', height=0.1, pos=[0.0, 0.0], alignHoriz='center',alignVert='center', wrapWidth=1.75)
		psychopyTxt.draw()
		win.flip()
		event.waitKeys(keyList=['space'])        

        
def endExp():
		psychopyTxt = visual.TextStim(win, color='white', text = "You have reached the end of the experiment. Please wait for further instructions from the researcher", 
		units='norm', height=0.1, pos=[0.0, 0.0], alignHoriz='center',alignVert='center', wrapWidth=1.75)
		psychopyTxt.draw()
		win.flip()
		event.waitKeys(keyList=['space'])
		
		
#sync with mri scanner		
def performMRISync():
	psychopyTxt = visual.TextStim(win, text = "Syncing with scanner - Get ready!", units='norm', height = .1, color = 'white', pos = [0.0,0.0], alignHoriz='center',alignVert='center', wrapWidth=1.75)
	psychopyTxt.draw()
	win.flip()
	event.waitKeys(keyList=['5'])
	writeToFile(fh, 'performMRISync', None, None)

							

#plays a movie for 30 seconds;
def playMovies_variable(j):
	global videoFile
	videoFile = variable_scheme1[j]
	writeToFile(fh, 'view_movie_variable', videoFile, None)
	mov = visual.MovieStim3(win, videoFile, size=[1920, 1080],flipVert=False, flipHoriz=True)
	globalClock = core.Clock()

	while globalClock.getTime()<30:    #movie duration is 30 seconds
		mov.draw()
		win.flip()   #win.update
		
#displays a fixation (rest period) for 15 seconds		
def fixationBlock():
	writeToFile(fh, 'fixation', None, None)				
	win.setRecordFrameIntervals()

	psychopyTxt = visual.TextStim(win, color='white',
							text = "+",
							units='norm', height=0.3,
							pos=[0.0, 0.0], alignHoriz='center',alignVert='center')					
	trialClock = core.Clock()
	t=lastFPSupdate=0;
	while t<15:#quits after 15 secs
		t=trialClock.getTime()
		psychopyTxt.draw()
		win.flip()

    
#participant gives rating; 10-second time limit        
def getRating1():
        writeToFile(fh, 'prompt1', videoFile, None)
        myRatingScale = visual.RatingScale(win, pos = [0, -400], scale=None, high = 5, labels=[" ", " "], showAccept=False)
    
        ratingImage = visual.ImageStim(win, image = 'first_prompt.jpg', units = 'norm', size = [1.5, 1.5], pos = [0.0, .15])

        event.clearEvents()
        trialClock = core.Clock()
        t=lastFPSupdate=0;
        while t<7.5: # show for 7.5 seconds
            t=trialClock.getTime()
            ratingImage.draw()
            myRatingScale.draw()
            win.flip()
        
        rating = myRatingScale.getHistory() # get the response and RT indicated by the subject
        #ratingRT = myRatingScale.getRT() #get reaction time of subject's rating
        writeToFile(fh, 'prompt1', videoFile, rating)
        

def getRating2():
        writeToFile(fh, 'prompt2', videoFile, None)
        myRatingScale = visual.RatingScale(win, pos = [0, -400], scale=None, labels=[" ", " "], high = 5, showAccept=False)
    
        ratingImage = visual.ImageStim(win, image = 'second_prompt.jpg', units = 'norm', size = [1.5, 1.5], pos = [0.0, .15])

        event.clearEvents()
        trialClock = core.Clock()
        t=lastFPSupdate=0;
        while t<7.5: # show for 17.5 seconds
            t=trialClock.getTime()
            ratingImage.draw()
            myRatingScale.draw()
            win.flip()
        
        rating = myRatingScale.getHistory() # get the response and RT indicated by the subject
        writeToFile(fh, 'prompt2', videoFile, rating)

##########
##########
##########
		
#Main Experiment

experimentSetup()
from psychopy import visual
win = windowSetup()
fh = fileSetup()


myInstructions1()
myInstructions2()
myInstructions3()
myInstructions4()

performMRISync()
fixationBlock()
for i in range(0,len(variable_scheme1)):
    playMovies_variable(i)
    getRating1()
    getRating2()
    fixationBlock()
    
endExp()

win.close()

1 Like

Any suggestions regarding this issue? I’ve tried a few things since i last posted this but it doesnt seem to affect the output. Another researcher with a script using videos is experiencing the same issues: At the start of the paradigm, a window pops up for a millisecond and then the initial fixation is extended by 4-5 seconds before the first video and then there is similar duration issue (~ +3s) for fixation prior to each video without the popup window. This seems similar to the issue reported in Loading times for routines with videos are slow except that they used builder. I tried using TextBox instead of TextStim but that did nothing.
Any suggestions would be helpful. Thank you.

Been stuck with the same problem for about 4 months . Tried about everything I could think of. No solution. Psychopy, regardless of the PC I use, always takes around ~3s to load videos in each trial (and I’m talking about 400kb .mp4 video files). And this, as you mentioned, also happened out of nowhere. One day it was fine (videos loaded instantly), the other all experiments with videos started having issues. I’m keeping an eye on this forum, but so far have found nothing.