"""Example 7 — Mandelbrot set.

Concepts: device function, 2D grid, irregular workload (divergence:
neighbouring threads do not iterate the same number of times).

    python examples/07_mandelbrot.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu


@gpu.jit(device=True)
def iterations(cr, ci, max_iter):
    zr = gpu.float32(0)
    zi = gpu.float32(0)
    for k in range(max_iter):
        if zr * zr + zi * zi > 4:
            return k
        zr, zi = zr * zr - zi * zi + cr, 2 * zr * zi + ci
    return max_iter


@gpu.jit
def mandelbrot(image, xmin, xmax, ymin, ymax, max_iter):
    x, y = gpu.grid(2)
    h, w = image.shape
    if x < w and y < h:
        cr = xmin + x * (xmax - xmin) / w
        ci = ymin + y * (ymax - ymin) / h
        image[y, x] = iterations(cr, ci, max_iter)


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    w, h = size((1024, 768), (64, 48))
    d_image = gpu.device_array((h, w), np.int32)
    f32 = np.float32
    mandelbrot[((w + 15) // 16, (h + 15) // 16), (16, 16)](
        d_image, f32(-2.0), f32(1.0), f32(-1.2), f32(1.2), np.int32(200))
    image = d_image.copy_to_host()
    print("mean iterations:", image.mean())


if __name__ == "__main__":
    main()
