Advertisement
Guest User

OpenCL Mandelbrot fixed

a guest
Jan 11th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import pyopencl as cl
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7.  
  8. ctx = cl.create_some_context(interactive=True)
  9.  
  10. def mandelbrot_opencl(q, maxiter):
  11.     global ctx
  12.     queue = cl.CommandQueue(ctx)
  13.    
  14.     output = np.empty(q.shape, dtype=np.uint16)
  15.     prg = cl.Program(ctx, """
  16.    #pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable
  17.    __kernel void mandelbrot(__global float2 *q,
  18.                     __global ushort *output, ushort const maxiter, int const width)
  19.    {
  20.        int gid = get_global_id(0)*width + get_global_id(1);
  21.        float nreal, real = 0;
  22.        float imag = 0;
  23.        output[gid] = 0;
  24.        for(int curiter = 0; curiter < maxiter; curiter++) {
  25.            nreal = real*real - imag*imag + q[gid].x;
  26.            imag = 2* real*imag + q[gid].y;
  27.            real = nreal;
  28.            if (real*real + imag*imag > 4.0f) {
  29.                 output[gid] = curiter;
  30.                 return;
  31.            }
  32.        }
  33.        output[gid] = maxiter;
  34.    }
  35.    """).build()
  36.     mf = cl.mem_flags
  37.     q_opencl = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q)
  38.     output_opencl = cl.Buffer(ctx, mf.WRITE_ONLY, output.nbytes)
  39.  
  40.     prg.mandelbrot(queue, output.shape, None, q_opencl,
  41.                    output_opencl, np.uint16(maxiter), np.int32(output.shape[1]))
  42.     cl.enqueue_copy(queue, output, output_opencl).wait()
  43.     return output
  44.  
  45. if __name__ == '__main__':
  46.     width, height = 750, 500
  47.     ys, xs = np.mgrid[1:-1:height*1j, -2:1:width*1j]
  48.     data = (xs + 1j*ys).astype('complex64')
  49.     out = mandelbrot_opencl(data, 100)
  50.     plt.imshow(abs(out), cmap=plt.cm.nipy_spectral_r)
  51.     plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement