Search code examples
pythonrandom2dsimulation

Is there a way to make sure randomly distributed particles are not within certain intervalls?


I am currently making a simulation of particle movements on a 2d plane of size LxL. I am trying to add obstacles that the particles can not move through.

My problem is with the very first part of the simulation. I start by randomly distributing particles in the plane using this code:

positions = np.random.random(size = (n,3))
positions[:, 0] = L*positions[:, 0]
positions[:, 1] = L*positions[:, 1]
positions[:, 2] = 2*np.pi*positions[:, 2]

Where the first two columns are the x and y position of the particle and the third column is unimportant to this question.

Now obviously the particles should not start off within the obstacles, but outside of them. I'm trying to do that this way:

for i in range (n):
        for rec in rect:
            while rec[0]<=positions[i][0] and (rec[0]+rec[2])>=positions[i][0] and rec[1]<=positions[i][1] and (rec[1]+rec[3])>=positions[i][1]:
                positions[i, 0] = L*np.random.random()
                positions[i, 1] = L*np.random.random()

rec[0] and rec[1] are the coordinates of a corner of a rectangle, rec[2] and rec[3] are its side lengths.

Obviously this code is very clunky and I would like to improve that, but the main problem is that it doesn't work for more than one obstacle at a time. If there are two obstacles, the code will check if the particle is in the first obstacle and if so, give it a new position. Then it will move on to checking the next rectangle and reassign the particle a new, random position if it is inside - a position that might just be back in the rectangle that was checked first. This will not be noticed as the first rectangle will not be rechecked.

My question is: How can I solve this problem? Is there a way to directly assign random numbers that cannot be in certain intervals? Is there a better way to check if the particles are in any obstacles? How can I make this code less clunky in general?


Solution

  • Instead of checking rectangles one by one, check if a point is within any of them.

    while any('conditions for being inside rect' for rec in rect):
        positions[i, 0] = L*np.random.random()
        positions[i, 1] = L*np.random.random()