Python Forum

Full Version: Random coordinate generator speed improvement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to generate random coordinates for spheres in a box geometry. I'm using while loop and i have 2 condition. First one is the distance. Coordinates should not be closer to each other than the diameter of the sphere. Second one is the porosity. When the porosity is less than 0.42 generating should stop. Code is working correctly but when i reduce porosity condition less than 0.70 the algorithm stucks but I need 0.42 porosity. It cannot reach that porosity even after hours. How can I improve it to generate coordinates faster? Any suggestions are appreciated.

import math
import random
import numpy as np
import matplotlib.pyplot as plt

#dist = math.sqrt(((x2-x1)**2) + ((y2-y1)**2) + ((z2-z1)**2))

A = 0.04       # x border.
B = 0.04       # y border.
C = 0.125      # z border.
V_total = A*B*C # volume
r = 0.006    # min distance of spheres.
r_square = r**2
radius = 0.003  # radius of spheres.
wall_distance = 0.003
sphere_Val = (4/3) * (np.pi) * (radius**3) # part of porosity formula

Porosity = 1.0
coordinates = np.empty((0,3)) # initialize array with correct shape
while Porosity >= 0.70:
    # coordinates
    x = random.uniform(wall_distance, A-wall_distance)
    y = random.uniform(wall_distance, B-wall_distance)
    z = random.uniform(wall_distance, C-wall_distance)
    is_invalid = (True in [
                                      ((x - coordinates[i_coor,0])**2) + 
                                      ((y - coordinates[i_coor,1])**2) + 
                                      ((z - coordinates[i_coor,2])**2) <= r_square
                            for i_coor in range(coordinates.shape[0]) ])
    if not is_invalid:
        coordinates = np.append(coordinates,[[x,y,z]], axis = 0)
    else:
        continue
    Porosity = (V_total - (sphere_Val * len(coordinates))) / V_total
    print(f"Placed coordinates: {len(coordinates)}, Porosity: = {Porosity}")

print("Porosity: {}".format(Porosity))
print("Number of spheres: {}".format(len(coordinates)))
    
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.set_xlim([0, A])
ax.set_ylim([0, B])
ax.set_zlim([0, C])
ax.set_title('Coordinates for spheres')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
p = ax.scatter(coordinates[:,0], coordinates[:,1], coordinates[:,2])
np.savetxt('Coordinates.csv', coordinates)
fig.colorbar(p)
plt.show()