Reputation: 61
I am working on finding the 3D distance from a specified point in python. Right now, I am using for loops. But it's a little slow to compute.
Here is python code:
for i_y in xrange(0,500,100):
y = round(i_y/100.00,2)
for i_x in xrange(0, 800, 1):
x = round(i_x/100.00,2)
for i_z in xrange(500, 0, -1):
z = round(i_z/100.00,2)
for key in specifiedPoints.keys():
a = specifiedPoints[key]
subx1 = x-a.p1.x
suby1 = y-a.p1.y
subz1 = z-a.p1.z
subx2 = x-a.p2.x
suby2 = y-a.p2.y
subz2 = z-a.p2.z
subx3 = x-a.p3.x
suby3 = y-a.p3.y
subz3 = z-a.p3.z
distver1 = math.sqrt(subx1*subx1+suby1*suby1+subz1*subz1)
distver2 = math.sqrt(subx2*subx2+suby2*suby2+subz2*subz2)
distver3 = math.sqrt(subx3*subx3+suby3*suby3+subz3*subz3)
if distver1 <= 1 or distver2<=1 or distver3<=1:
print "close point:", x, y, z
I worked a lot but I couldnt find a clear tutorial that shows an equal loop in numpy.
How can I make this in numpy to accelerate loop?
Thank you
Upvotes: 0
Views: 2079
Reputation: 68682
I would look at scipy.spatial.distance
and especially the cdist
and pdist
methods:
http://docs.scipy.org/doc/scipy/reference/spatial.distance.html
Upvotes: 2
Reputation: 1095
Your arange function could return the values you compute for x,y and z directly, what would save a lot of computations. The round function is not needed at all. You run the loop 5*800*500 = 2.000.000 times and every time you divide by 100 and round. Better do it like this:
for y in np.arange(0,5,1):
for x in np.arange(0,8,0.01):
for z in np.arange(5,0,-0.01):
Collect the points in one array like in the following code.
point = np.array([x,y,z])
a1 = np.array([a.p1.x,a.p1.y,a.p1.z])
a2 = np.array([a.p2.x,a.p2.y,a.p2.z])
a3 = np.array([a.p3.x,a.p3.y,a.p3.z])
if np.linalg.norm(point-a1) <=1:
print point
continue
if np.linalg.norm(point-a2) <=1:
print point
continue
if np.linalg.norm(point-a3) <=1:
print point
continue
It is better to store the points directly as numpy arrays in your object specifiedPoints[key] and not to collect them again and again in every loop. This would get you this code:
point = np.array([x,y,z])
if np.linalg.norm(point-a.p1) <=1:
print point
continue
if np.linalg.norm(point-a.p2) <=1:
print point
continue
if np.linalg.norm(point-a.p3) <=1:
print point
continue
Upvotes: 1