Distance ElementWise 3D

This example calculates the 3D euclidean distance over a set of points from a single point using an ElementWise kernel.

Christen Ford

License of this example:

Public Domain

Date:

30/1/2018

PyCUDA version:

2017.1.1

   1 import pycuda.gpuarray as gpuarray
   2 import pycuda.driver as cuda
   3 import pycuda.tools as tools
   4 import pycuda.autoinit
   5 import numpy, random, time
   6 from pycuda.curandom import rand as curand
   7 from pycuda.elementwise import ElementwiseKernel as Elementwise
   8 
   9 x = 50
  10 y = 50
  11 z = 2
  12 width = 100
  13 height = 100
  14 depth = 100
  15 
  16 def main():
  17     """
  18     Computes a set of distances from a given point in a search space in parallel on a GPU.
  19     """
  20 
  21     # Create an empty array to hold our points.
  22     n = gpuarray.zeros(shape=(x, y, z),
  23                     dtype=gpuarray.vec.float3)
  24 
  25     # Populate the array with randomized points from the search space.
  26     for k in range(z):
  27         for j in range(y):
  28             for i in range(x):
  29                 n[i, j, k] = gpuarray.vec.make_float3(random.uniform(-width, width),
  30                                                     random.uniform(-height, height),
  31                                                     random.uniform(-depth, depth))
  32 
  33     # Declare our elementwise CUDA kernel.
  34     mod = Elementwise(
  35         arguments="float3 pt, float3 *ns, float *rs",
  36         operation="rs[i] = sqrt(pow(pt.x-ns[i].x,2)+pow(pt.y-ns[i].y,2)+pow(pt.z-ns[i].z,2))",
  37         name="euclidean_distance",
  38         preamble="#include <math.h>"
  39     )
  40 
  41     # Declare an empty results array.
  42     r = gpuarray.zeros(shape=(50, 50, 2), dtype=numpy.float32)
  43     start = cuda.Event()
  44     end = cuda.Event()
  45     start.record()
  46     # Call the kernel with a randomize point from the search space.
  47     mod(gpuarray.vec.make_float3(random.uniform(-width, width),
  48                                  random.uniform(-height, height),
  49                                  random.uniform(-width, width)), n, r)
  50     end.record()
  51     end.synchronize()
  52     print(start.time_till(end))
  53     print(r)
  54 
  55 if __name__ == '__main__':
  56     main()


CategoryPyCuda

PyCuda/Examples/DistanceElementWise3D (last edited 2018-01-30 21:17:56 by 192)