Wakefield's Daily Tips

Preloading stimuli in code

Sometimes I want to load the stimuli before the main loop starts, so that I can, for example, insert prospective memory targets or N-Back trials, or apply constraints to the randomisation. The easiest way to do this is to use add a trial handler in a code component. This solution is taken from my PsychoPy Code Component Snippets - Google Docs.

In Python, the code for a trial handler is:

myData = data.TrialHandler(
nReps=1, 
method='sequential', # or 'random'
extraInfo=expInfo, 
originPath=-1, 
trialList=data.importConditions('conditions.xlsx'), # Add ", selection=useRows" inside the brackets for selected rows
seed=None, 
name='myData')

# Add the following for random

sequenceIndices = [ ]
for Idx in myData.sequenceIndices:
    sequenceIndices.append( Idx[0] )

This auto translates to:

myData = new data.TrialHandler({
    "nReps": 1, 
    "method": "sequential", 
    "extraInfo": expInfo, 
    "originPath": (- 1), 
    "trialList": data.importConditions("conditions.xlsx"), 
    "seed": null, 
    "name": "myData"});

However, the correct translation is:

myData = new TrialHandler({
    psychoJS: psychoJS,
    nReps: 1, 
    method: TrialHandler.Method.SEQUENTIAL, // or .RANDOM
    extraInfo: expInfo, 
    originPath: undefined,
    trialList: 'conditions.xlsx',
// or trialList: TrialHandler.importConditions(psychoJS.serverManager, 'conditions.xlsx', useRows),
    seed: undefined, 
    name: 'myData'});

// Add the following for random

sequenceIndices = myData._trialSequence[0];

Access individual values using: aValue = myData.trialList[Idx]['variableName'] for sequential and aValue = myData.trialList[sequenceIndices[Idx]]['variableName'] for random.

The spreadsheet can be replaced with a list of dictionaries, e.g.

conditions=[ ]
for Idx in range (10):
    conditions.append({"cue_ori": 10*Idx, "target_x": 300*(Idx%2)})