# Implementing the Closest Pair Algorithm in OpenCL and WebCL

I was looking for a fun geometry problem to solve and came across the closest pair of points problem.

The problem statement is:
Given a set of points, in 2D, compute the closest pair of points.

The brute force algorithm takes $O(n^2)$ time. There’s a better solution described at the Wikipedia page Closest pair of points problem, which takes $O(n \cdot \textrm{log}(n))$ time.
As far as I know, there aren’t any posted solutions using OpenCL to compute the closest pair. So I’ve implemented one, it’s posted at closest-pair.

There are a few challenges in adapting the algorithm for OpenCL. Namely, we can’t use recursion so we must convert the recursive algorithm to a procedural one. In this case it’s not to complicated because the structure of the solution is easily converted from the top-down recursive algorithm to a bottom-up parallel algorithm. There are some tricky issues when the number of points are not a power of 2. I’ve commented the code for those cases.

The second challenge is using WebCL. WebCL has an additional restriction that you can’t pass structures between Javascript and OpenCL kernels. Because of this I had to use dumb arrays of simple uint’s instead of using arrays of uint2, uint3, and uint4. This made the code more verbose. To help reduce the verbosity I added macros in the OpenCL ckStrips kernel. The WebCL version is posted at
closest_pair_ocl.html.

I hope the solution is useful to someone. Enjoy reading the code, it requires careful thought.
Check it out at closest-pair or view the WebCL one online at closest_pair_ocl.html.

# Enabling WebCL Highlighting in Emacs

When editing WebCL OpenCL kernels in Emacs I like to have the OpenCL kernel code highlighted as C code. This is easy to achieve using the multi-mode.el package.

The steps on Ubuntu (or any other modern Linux with Emacs 24) are

1. Enable the http://marmalade-repo.org/ elpa package archive by adding the below to your .emacs file and restarting Emacs
    (require 'package)
(package-initialize)

2. Install multi-web-mode by using “M-x package-list-packages” and scrolling down to “multi-web-mode”.
3. Add the below to the bottom of your .emacs file and restart Emacs
    (require 'multi-web-mode)
(setq mweb-default-major-mode 'html-mode)
(setq mweb-tags '((php-mode "<\\?php\\|<\\? \\|")
(js-mode "]*>" "")
(css-mode "]*>" "")
(c-mode "]* +type=\"text/x-opencl\"[^>]*>" "")))
(setq mweb-filename-extensions '("php" "htm" "html" "ctp" "phtml" "php4" "php5"))
(multi-web-global-mode 1)


The important part is the “c-mode” section that will enable C highlighting for OpenCL kernels in html files.

4. Start coding!