"""Example 8 — The same kernel in OpenCL C and in Metal (no GPU needed).

One Python kernel, three GPU languages: compare CUDA C (in comments),
OpenCL C and Metal Shading Language.

    python examples/08_generated_code.py
"""

import numpy as np
import common  # noqa: F401  (makes unigpu importable without installing it, e.g. on iPad)

import unigpu as gpu

BLOCK = 128


@gpu.jit
def block_sum(a, partial_sums):
    # CUDA C:
    #   __shared__ float cache[128];
    #   int tid = threadIdx.x;
    #   int i = blockIdx.x * blockDim.x + threadIdx.x;
    #   cache[tid] = (i < n) ? a[i] : 0;
    #   __syncthreads();
    #   ...
    cache = gpu.shared.array(BLOCK, gpu.float32)
    tid = gpu.threadIdx.x
    i = gpu.grid(1)
    cache[tid] = a[i] if i < a.size else 0
    gpu.syncthreads()
    s = BLOCK // 2
    while s > 0:
        if tid < s:
            cache[tid] += cache[tid + s]
        gpu.syncthreads()
        s //= 2
    if tid == 0:
        partial_sums[gpu.blockIdx.x] = cache[0]


a = np.zeros(1024, np.float32)
p = np.zeros(8, np.float32)
for target in ("opencl", "metal"):
    print("=" * 30, target, "=" * 30)
    print(gpu.translate(block_sum, a, p, target=target))
