Semirandomization of video stimuli

Hi,

I am trying to program an experiment with 2 experimental groups: “Negative” and “Positive”. The experiment has 5 blocks. In each block a different video is shown, followed by 15 faces.

There are 3 types of videos: “Negative”, “Neutral” and “Positive”.

Therefore, the general structure looks like this:
Block 1: Neutral Video + Set of faces 1
Block 2: Target Video (positive or negative) + Set of faces 2
Block 3: Neutral Video + Set of faces 3
Block 4: Target Video (positive or negative) + Set of faces 4
Block 5: Neutral Video + Set of faces 5

Participants are assigned to either the negative or positive experimental group using the initial dialogue box. For this I have created a custom “condition” field in the initial dialogue box. If “condition” is set to 1, participant is assigned to the Negative Group. If “condition” is set to 2, participant is assigned to the Positive Group.

I would like to randomize the presentation of the videos with the following conditions:

  1. In the negative group, the negative video should always be shown in Block 2, and positive video should always be shown in block 4.
  2. In the positive group, the positive video should always be shown in Block 2, and the negative video should always be shown in block 4.
  3. Neutral videos should always be shown in blocks 1, 2 and 3, but their order should be aleatory (for example, Neutral Video 1 should not be presented always in block 1).

This is my code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.2),
    on Thu Aug  1 14:01:12 2019
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

from psychopy.hardware import keyboard

from pylsl import StreamInfo, StreamOutlet
from pylsl import StreamInlet, resolve_stream

# Dictionary with LSL markers
markers = {
    'instruction': [0],
    'video': [1],
    'cross': [2],
    'face': [3],
    'test': [99],
}

# init von marker stream
info = StreamInfo(name='psychopy_marker_oddball', type='Markers', channel_count=1,
                  channel_format='int32', source_id='uniqueid12345')

outlet = StreamOutlet(info)
outlet.push_sample(markers['test'])


# 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 = '3.1.2'
expName = 'blockedTrials'  # from the Builder filename that created this script
expInfo = {'condition': '1', 'participant': ''}
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='/Users/andresp/Documents/Experiments/affective-states/affective-states-expetiment/blockedTrials.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

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

# Setup the Window
win = visual.Window(
    size=[1440, 900], fullscr=True, screen=0, 
    winType='pyglet', allowGUI=True, 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

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

# Initialize components for Routine "video"
videoClock = core.Clock()

# Initialize components for Routine "faces"
facesClock = core.Clock()
cross = visual.ShapeStim(
    win=win, name='cross', vertices='cross',units='cm', 
    size=(3, 3),
    ori=0, pos=(0, 0),
    lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',
    fillColor=[1,1,1], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)
face = visual.ImageStim(
    win=win,
    name='face', units='cm', 
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(12.2, 18.1),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
sound_1 = sound.Sound('A', secs=-1, stereo=True)
sound_1.setVolume(1)

# 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
if expInfo['condition'] == '1':
    expCondition = 'negativeGroup.csv'
else:
    expCondition = 'positiveGroup.csv'
    
trialsVideo = data.TrialHandler(nReps=1, method='sequential', 
    extraInfo=expInfo, originPath=-1,
    trialList=expCondition,
    seed=None, name='trialsVideo')
thisExp.addLoop(trialsVideo)  # add the loop to the experiment
thisTrialsVideo = trialsVideo.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrialsVideo.rgb)
if thisTrialsVideo != None:
    for paramName in thisTrialsVideo:
        exec('{} = thisTrialsVideo[paramName]'.format(paramName))

for thisTrialsVideo in trialsVideo:
    currentLoop = trialsVideo
    # abbreviate parameter names if possible (e.g. rgb = thisTrialsVideo.rgb)
    if thisTrialsVideo != None:
        for paramName in thisTrialsVideo:
            exec('{} = thisTrialsVideo[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "video"-------
    t = 0
    videoClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    movie = visual.MovieStim3(
        win=win, name='movie',units='height', 
        noAudio = False,
        filename=videoFile,
        ori=0, pos=(0, 0), opacity=1,
        loop=False,
        size=(1,0.6),
        depth=0.0,
        )
    # keep track of which components have finished
    videoComponents = [movie]
    for thisComponent in videoComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    
    # -------Start Routine "video"-------
    while continueRoutine:
        # get current time
        t = videoClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # *movie* updates
        if t >= 0.5 and movie.status == NOT_STARTED:
            # keep track of start time/frame for later
            movie.tStart = t  # not accounting for scr refresh
            movie.frameNStart = frameN  # exact frame index
            win.timeOnFlip(movie, 'tStartRefresh')  # time at next scr refresh
            movie.setAutoDraw(True)
            outlet.push_sample(markers['video'])
        
        # 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 videoComponents:
            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 "video"-------
    for thisComponent in videoComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    trialsVideo.addData('movie.started', movie.tStartRefresh)
    trialsVideo.addData('movie.stopped', movie.tStopRefresh)
    # the Routine "video" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # set up handler to look after randomisation of conditions etc
    trialsFaces = data.TrialHandler(nReps=1, method='random', 
        extraInfo=expInfo, originPath=-1,
        trialList=data.importConditions('facesBlock.csv'),
        seed=None, name='trialsFaces')
    thisExp.addLoop(trialsFaces)  # add the loop to the experiment
    thisTrialsFace = trialsFaces.trialList[0]  # so we can initialise stimuli with some values
    # abbreviate parameter names if possible (e.g. rgb = thisTrialsFace.rgb)
    if thisTrialsFace != None:
        for paramName in thisTrialsFace:
            exec('{} = thisTrialsFace[paramName]'.format(paramName))
    
    for thisTrialsFace in trialsFaces:
        currentLoop = trialsFaces
        # abbreviate parameter names if possible (e.g. rgb = thisTrialsFace.rgb)
        if thisTrialsFace != None:
            for paramName in thisTrialsFace:
                exec('{} = thisTrialsFace[paramName]'.format(paramName))
        
        # ------Prepare to start Routine "faces"-------
        t = 0
        facesClock.reset()  # clock
        frameN = -1
        continueRoutine = True
        routineTimer.add(4.000000)
        # update component parameters for each repeat
        face.setImage(faceFile)
        sound_1.setSound('A', secs=3)
        sound_1.setVolume(1, log=False)
        # keep track of which components have finished
        facesComponents = [cross, face, sound_1]
        for thisComponent in facesComponents:
            thisComponent.tStart = None
            thisComponent.tStop = None
            thisComponent.tStartRefresh = None
            thisComponent.tStopRefresh = None
            if hasattr(thisComponent, 'status'):
                thisComponent.status = NOT_STARTED
        
        # -------Start Routine "faces"-------
        while continueRoutine and routineTimer.getTime() > 0:
            # get current time
            t = facesClock.getTime()
            frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
            # update/draw components on each frame
            
            # *cross* updates
            if t >= 0.0 and cross.status == NOT_STARTED:
                # keep track of start time/frame for later
                cross.tStart = t  # not accounting for scr refresh
                cross.frameNStart = frameN  # exact frame index
                win.timeOnFlip(cross, 'tStartRefresh')  # time at next scr refresh
                cross.setAutoDraw(True)
                outlet.push_sample(markers['cross'])
            frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75  # most of one frame period left
            if cross.status == STARTED and t >= frameRemains:
                # keep track of stop time/frame for later
                cross.tStop = t  # not accounting for scr refresh
                cross.frameNStop = frameN  # exact frame index
                win.timeOnFlip(cross, 'tStopRefresh')  # time at next scr refresh
                cross.setAutoDraw(False)
                
            
            # *face* updates
            if t >= 1 and face.status == NOT_STARTED:
                # keep track of start time/frame for later
                face.tStart = t  # not accounting for scr refresh
                face.frameNStart = frameN  # exact frame index
                win.timeOnFlip(face, 'tStartRefresh')  # time at next scr refresh
                face.setAutoDraw(True)
                outlet.push_sample(markers['face'])
            frameRemains = 1 + 3- win.monitorFramePeriod * 0.75  # most of one frame period left
            if face.status == STARTED and t >= frameRemains:
                # keep track of stop time/frame for later
                face.tStop = t  # not accounting for scr refresh
                face.frameNStop = frameN  # exact frame index
                win.timeOnFlip(face, 'tStopRefresh')  # time at next scr refresh
                face.setAutoDraw(False)
            # start/stop sound_1
            if t >= 1 and sound_1.status == NOT_STARTED:
                # keep track of start time/frame for later
                sound_1.tStart = t  # not accounting for scr refresh
                sound_1.frameNStart = frameN  # exact frame index
                win.timeOnFlip(sound_1, 'tStartRefresh')  # time at next scr refresh
                win.callOnFlip(sound_1.play)  # screen flip
            frameRemains = 1 + 3- win.monitorFramePeriod * 0.75  # most of one frame period left
            if sound_1.status == STARTED and t >= frameRemains:
                # keep track of stop time/frame for later
                sound_1.tStop = t  # not accounting for scr refresh
                sound_1.frameNStop = frameN  # exact frame index
                win.timeOnFlip(sound_1, 'tStopRefresh')  # time at next scr refresh
                if 3 > 0.5:  # don't force-stop brief sounds
                    sound_1.stop()
                    
            
            # 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 facesComponents:
                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 "faces"-------
        for thisComponent in facesComponents:
            if hasattr(thisComponent, "setAutoDraw"):
                thisComponent.setAutoDraw(False)
        trialsFaces.addData('cross.started', cross.tStartRefresh)
        trialsFaces.addData('cross.stopped', cross.tStopRefresh)
        trialsFaces.addData('face.started', face.tStartRefresh)
        trialsFaces.addData('face.stopped', face.tStopRefresh)
        sound_1.stop()  # ensure sound has stopped at end of routine
        trialsFaces.addData('sound_1.started', sound_1.tStartRefresh)
        trialsFaces.addData('sound_1.stopped', sound_1.tStopRefresh)
        thisExp.nextEntry()
        
    # completed 1 repeats of 'trialsFaces'
    
# completed 1 repeats of 'trialsVideo'


# 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()

This is the facesBlock.csv file:

faceFile
stims/negative-1.TIF
stims/negative-2.TIF
stims/negative-3.TIF
stims/negative-4.TIF
stims/negative-5.TIF
stims/negative-6.TIF
stims/negative-7.TIF
stims/negative-8.TIF
stims/negative-9.TIF
stims/negative-10.TIF
stims/negative-11.TIF
stims/negative-12.TIF
stims/negative-13.TIF
stims/negative-14.TIF
stims/negative-15.TIF
stims/negative-16.TIF
stims/negative-17.TIF
stims/negative-18.TIF
stims/negative-19.TIF
stims/negative-20.TIF
stims/negative-21.TIF
stims/negative-22.TIF
stims/negative-23.TIF
stims/negative-24.TIF
stims/negative-25.TIF

stims/neutral-1.TIF
stims/neutral-2.TIF
stims/neutral-3.TIF
stims/neutral-4.TIF
stims/neutral-5.TIF
stims/neutral-6.TIF
stims/neutral-7.TIF
stims/neutral-8.TIF
stims/neutral-9.TIF
stims/neutral-10.TIF
stims/neutral-11.TIF
stims/neutral-12.TIF
stims/neutral-13.TIF
stims/neutral-14.TIF
stims/neutral-15.TIF
stims/neutral-16.TIF
stims/neutral-17.TIF
stims/neutral-18.TIF
stims/neutral-19.TIF
stims/neutral-20.TIF
stims/neutral-21.TIF
stims/neutral-22.TIF
stims/neutral-23.TIF
stims/neutral-24.TIF
stims/neutral-25.TIF

stims/positive-1.TIF
stims/positive-2.TIF
stims/positive-3.TIF
stims/positive-4.TIF
stims/positive-5.TIF
stims/positive-6.TIF
stims/positive-7.TIF
stims/positive-8.TIF
stims/positive-9.TIF
stims/positive-10.TIF
stims/positive-11.TIF
stims/positive-12.TIF
stims/positive-13.TIF
stims/positive-14.TIF
stims/positive-15.TIF
stims/positive-16.TIF
stims/positive-17.TIF
stims/positive-18.TIF
stims/positive-19.TIF
stims/positive-20.TIF
stims/positive-21.TIF
stims/positive-22.TIF
stims/positive-23.TIF
stims/positive-24.TIF
stims/positive-25.TIF

This is the negativeGroup.csv file:

videoFile
stims/neutral_video1.mov
stims/negative_video.mov
stims/neutral_video2.mov
stims/positive_video.mov
stims/neutral_video3.mov

And this is the positiveGroup.csv file:

videoFile
stims/neutral_video1.mov
stims/positive_video.mov
stims/neutral_video2.mov
stims/negative_video.mov
stims/neutral_video3.mov