"""Example 5 — Histogram with atomic operations.

Version 1: atomics in global memory (a lot of contention).
Version 2: histogram private to the block in shared memory, then merged.

Concepts: atomic.add, access conflicts, privatization in shared memory.

    python examples/05_histogram.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu

NUM_BINS = 64


@gpu.jit
def histo_global(data, histo):
    for i in range(gpu.grid(1), data.size, gpu.gridsize(1)):
        gpu.atomic.add(histo, data[i], 1)


@gpu.jit
def histo_shared(data, histo):
    local_h = gpu.shared.array(NUM_BINS, gpu.int32)
    tid = gpu.threadIdx.x
    for k in range(tid, NUM_BINS, gpu.blockDim.x):
        local_h[k] = 0
    gpu.syncthreads()
    for i in range(gpu.grid(1), data.size, gpu.gridsize(1)):
        gpu.atomic.add(local_h, data[i], 1)       # atomic in shared memory
    gpu.syncthreads()
    for k in range(tid, NUM_BINS, gpu.blockDim.x):
        gpu.atomic.add(histo, k, local_h[k])      # merge into the global histogram


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n = size(5_000_000, 3_000)
    data = np.random.randint(0, NUM_BINS, n).astype(np.int32)
    d_data = gpu.to_device(data)
    expected = np.bincount(data, minlength=NUM_BINS)

    for kernel in (histo_global, histo_shared):
        d_histo = gpu.to_device(np.zeros(NUM_BINS, np.int32))
        kernel[32, 128](d_data, d_histo)
        assert (d_histo.copy_to_host() == expected).all()
        print(kernel.__name__, "OK")


if __name__ == "__main__":
    main()
