Random selection of image based on trial type

Hi all,

I am trying to write an experiment that presents stimuli at random times, half of which are negative and the other half are neutral.
The trial type itself is been decided per row in the stimuli table. but instead of having to manually assign specific stimuli to specific row in the table I want the stimuli to be randomly selected from a list of negative or neutral images (according the the trial type).

My table has columns for trial type, and stimuli name (among other things)

This is the part of my code that initialize the images, and i am assuming that a good way to go about it is to add some if statement here, but i a not sure where, and how to refer to the variables from the table in this part of the code.


image_1 = visual.ImageStim(
    win=win,
    name='image_1', 
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(1, 1),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-4.0)

Thank you

Something like this, although I’d probably advise that you do link all of the values for a trial together (e.g. in a dictionary), rather than have them in separate lists:

from numpy.random import shuffle

number_of_trials = 20
half_trials = number_of_trials/2

trial_types = ['neutral', 'negative'] * half_trials # balanced list of 20 entries
shuffle(trial_types) # randomise it

neutral_images = [f'neutral_{i}.jpg' for i in range(half_trials)]
shuffle(neutral_images)

negative_images = [f'negative_{i}.jpg' for i in range(half_trials)]
shuffle(negative_images)

# create image stimulus just once, with placeholder image:

image_1 = visual.ImageStim(
    win=win,
    name='image_1', 
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(1, 1),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-4.0)

for trial_type in trial_types:
    if trial_type == 'neutral':
        file_name = neutral_images.pop()
    else:
        file_name = negative_images.pop()
    
    image_1.image = file_name

    for frame in range(60) # draw for say 1 second:
        image_1.draw()
        win.flip()