| Reference | Downloads | Github

Randomization with constant distance between images

I’m very very new with Python. I’m using Psychopy for a cognitive task in which same squares appear in a randomly selected position. I need that this squares are not overlapped. How can I say to psychopy :

  • chose a random position;
  • check if another square is in that position
  • if there is another square go back and check again for another position
  • if is an empty place: ok put the square.

You can create a visual.Rect in a random location, then use the method overlaps() to test if it overlaps with another one.

So roughly along the lines of:

import numpy as np
stim1 = visual.Rect(win, width=0.1, height=0.1, pos = (np.random.uniform(low=-1, high=1), np.random.uniform(low=-1, high=1)))
stim2 = visual.Rect(win, width=0.1, height=0.1, pos = (np.random.uniform(low=-1, high=1), np.random.uniform(low=-1, high=1)))
while stim2.overlaps(stim1):
    stim2.pos = (np.random.uniform(low=-1, high=1), np.random.uniform(low=-1, high=1)

Thank you Jan
I have different condition:

  • 2 squares left and 2 right;
  • 4 and 4;
  • 4 and 2;
  • 2 and 4;
    does it works even in this case?

I would suggest an alternative approach which will guarantee that your stimuli won’t overlap, without having to create positions and test them iteratively. Make lists of non overlapping x and y coordinates and shuffle them on each routine so you get an apparently random location. e.g.

from numpy.random import shuffle

x_coords = [-400, -300, -200, -100, 0, 100, 200, 300, 400]
x_coords = [-400, -300, -200, -100, 0, 100, 200, 300, 400]

for trial in trials:

    some_stimulus.pos = [x_coords[0], y_coords[0])
    other_stimulus.pos = [x_coords[1], y_coords[1])
    # etc

You could maintain separate lists of coordinates to match your constraints of having some on the left and the right, and so on.

1 Like

I agree that it’d be much better to have a list of places the stimuli could be. The iterative way I posted above is super inefficient and if you have the wrong dimensions on your stimuli, the loop could run forever (always a bad thing!)


You are right. I fixed it. but now I have a new question. I will open a new topic

There are certainly many times where I can’t see any alternative to brute-force iteration to implement randomisation constraints, but it always feels a bit like some sort of defeat :wink:

1 Like