"""Example 10 — Dynamic shared memory, constant memory and block votes.

* *dynamic* shared memory: size chosen at launch
  (``kernel[grid, block, stream, nbytes]``, then ``shared.array(0, dtype)``);
* *constant* memory: ``const.array_like`` copies a global array, read-only,
  visible to every thread;
* ``syncthreads_count`` / ``_and`` / ``_or``: barrier + vote of the block.

    python examples/10_dynamic_constant_memory.py [device]
"""

import numpy as np
from common import choose_device

import unigpu as gpu

WEIGHTS = np.array([1, 4, 6, 4, 1], dtype=np.float32) / 16   # smoothing filter


@gpu.jit
def smooth(a, output, positives):
    cache = gpu.shared.array(0, gpu.float32)       # size set at launch
    w = gpu.const.array_like(WEIGHTS)              # constant memory
    tid = gpu.threadIdx.x
    i = gpu.grid(1)
    cache[tid] = a[i]
    gpu.syncthreads()
    acc = gpu.float32(0)
    for k in range(-2, 3):
        j = tid + k
        if 0 <= j < cache.size:
            acc += w[k + 2] * cache[j]
    output[i] = acc
    count = gpu.syncthreads_count(int(acc > 0.5))  # vote: how many values > 0.5?
    if tid == 0:
        positives[gpu.blockIdx.x] = count


def smooth_numpy(a, block):
    """The same smoothing with NumPy: block by block, neighbours outside the block are 0.

    Each value is the average of its neighbours weighted by WEIGHTS; it is obtained by
    adding shifted copies of the array (like np.convolve, "same" mode).
    """
    blocks = np.pad(a.reshape(-1, block), ((0, 0), (2, 2)))
    return sum(WEIGHTS[k] * blocks[:, k: k + block] for k in range(5)).ravel()


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    block, blocks = 64, 4
    a = np.random.rand(block * blocks).astype(np.float32)
    d_output = gpu.device_array_like(a)
    d_positives = gpu.device_array(blocks, np.int32)
    nbytes = block * a.itemsize
    smooth[blocks, block, 0, nbytes](gpu.to_device(a), d_output, d_positives)

    expected = smooth_numpy(a, block)
    assert np.allclose(d_output.copy_to_host(), expected, atol=1e-6)
    assert (d_positives.copy_to_host() == (expected.reshape(blocks, block) > 0.5).sum(axis=1)).all()
    print("smoothing and votes: OK —", d_positives.copy_to_host())


if __name__ == "__main__":
    main()
