"""
概要:
    要素ごとの計算方法を比較するベンチマークスクリプトです。
詳細説明:
    Python、NumPy、numpy.vectorize、およびNumbaの実行速度を比較します。
    使用方法として python ufunc_benchmark.py -n 1000000 --repeat 5 のように実行します。
    NumPyは必須ですが、Numbaはオプションです。GPUや並列処理は使用しません。
    すべての実装において float64 型で sin(x) + x*x + 1.0 を計算し、配列を返します。
    入力の作成、ウォームアップ、結果の検証、表示にかかる時間はトライアルの計測には含まれず、
    出力のメモリ割り当てや中間配列の作成はトライアルの計測に含まれます。
関連リンク:
    ufunc_benchmark_usage
"""
import argparse
import math
import platform
from statistics import median
from time import perf_counter
import numpy as np


def scalar_function(x):
    """
    概要:
        スカラー値に対して数式を計算します。
    引数:
        :param x: 計算対象の入力数値
        :type x: float
    戻り値:
        :returns: 計算結果の数値
        :rtype: float
    """
    return math.sin(x) + x*x + 1.0


def python_loop(x):
    """
    概要:
        Pythonのforループを使用して配列の各要素を計算します。
    引数:
        :param x: 計算対象の入力配列
        :type x: numpy.ndarray
    戻り値:
        :returns: 計算結果が格納された新しい配列
        :rtype: numpy.ndarray
    """
    out = np.empty_like(x)
    for i in range(x.size):
        out[i] = scalar_function(float(x[i]))
    return out


def python_listcomp(x):
    """
    概要:
        Pythonのリスト内包表記を使用して配列の各要素を計算します。
    引数:
        :param x: 計算対象の入力配列
        :type x: numpy.ndarray
    戻り値:
        :returns: 計算結果が格納された新しい配列
        :rtype: numpy.ndarray
    """
    return np.array([scalar_function(float(t)) for t in x], dtype=np.float64)


def numpy_ufunc(x):
    """
    概要:
        NumPyのufuncを使用して配列全体を一度に計算します。
    引数:
        :param x: 計算対象の入力配列
        :type x: numpy.ndarray
    戻り値:
        :returns: 計算結果が格納された新しい配列
        :rtype: numpy.ndarray
    """
    # Multiple compiled ufunc calls; temporary arrays are created.
    return np.sin(x) + x*x + 1.0


# Convenience wrapper: this still calls Python once per element.
numpy_vectorize = np.vectorize(scalar_function, otypes=[np.float64])


def numba_loop_source(x):
    """
    概要:
        NumbaのJITコンパイル対象となるループ計算関数のソースです。
    引数:
        :param x: 計算対象の入力配列
        :type x: numpy.ndarray
    戻り値:
        :returns: 計算結果が格納された新しい配列
        :rtype: numpy.ndarray
    """
    out = np.empty_like(x)
    for i in range(x.size):
        out[i] = math.sin(x[i]) + x[i]*x[i] + 1.0
    return out


def main():
    """
    概要:
        ベンチマークのメイン処理を実行します。
    詳細説明:
        コマンドライン引数をパースし、指定された回数だけ各手法による計算を繰り返し実行します。
        Numbaがインストールされている場合は、Numbaを用いた手法も比較対象に加えます。
        ウォームアップ実行による検証を行い、トライアル実行の処理時間を中央値等で表示します。
    例外:
        :raises AssertionError: 検証で計算結果が基準値と一致しない場合に発生します。
    """
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-n', '--count', type=int, default=1_000_000)
    parser.add_argument('--repeat', type=int, default=5)
    parser.add_argument('--no-numba', action='store_true')
    args = parser.parse_args()
    if args.count < 1 or args.repeat < 1:
        parser.error('count and repeat must be positive')
    x = np.linspace(-3.0, 3.0, args.count, dtype=np.float64)
    reference = numpy_ufunc(x)
    methods = [('Python for', python_loop), ('list comprehension', python_listcomp),
               ('NumPy ufunc', numpy_ufunc), ('np.vectorize', numpy_vectorize)]
    startup = {}
    print(f'Python {platform.python_version()}, NumPy {np.__version__}, {platform.system()}')
    print(f'f(x)=sin(x)+x*x+1; float64; n={args.count:,}; repeat={args.repeat}')
    print('Numba: CPU, serial, fastmath=False, cache=False', flush=True)
    if not args.no_numba:
        try:
            import numba
        except ImportError as exc:
            print(f'Numba skipped: {exc} (install: python -m pip install numba)')
        else:
            print(f'Numba {numba.__version__}')
            # No explicit signatures: compilation is deferred until first use.
            # Time decorator creation + first call together for each method.
            t0 = perf_counter()
            jit_ufunc = numba.vectorize(target='cpu', cache=False)(scalar_function)
            jit_ufunc(x[:1])
            startup['Numba @vectorize'] = perf_counter()-t0
            t0 = perf_counter()
            jit_loop = numba.njit(cache=False, fastmath=False)(numba_loop_source)
            jit_loop(x[:1])
            startup['Numba @njit'] = perf_counter()-t0
            methods += [('Numba @vectorize', jit_ufunc), ('Numba @njit', jit_loop)]
    # Exercise the full input before measuring any trials.
    # For Numba this follows the one-element compilation warmup above.
    for name, func in methods:
        t0 = perf_counter()
        y = func(x)
        startup[name] = startup.get(name, 0.0) + perf_counter()-t0
        if not np.all(np.isfinite(y)) or not np.allclose(y, reference, rtol=1e-12, atol=1e-12):
            raise AssertionError(f'{name}: warmup result mismatch')
        del y
    print('\nStartup/warmup (separate from trials; Numba includes JIT):')
    for name, _ in methods:
        print(f'  {name:20s} {startup[name]:.6f} s')
    times = {name: [] for name, _ in methods}
    errors = {name: 0.0 for name, _ in methods}
    # Rotate execution order across trials to reduce fixed-order bias.
    for trial in range(args.repeat):
        offset = trial % len(methods)
        for name, func in methods[offset:] + methods[:offset]:
            t0 = perf_counter()
            y = func(x)
            elapsed = perf_counter()-t0
            times[name].append(elapsed)
            if not np.all(np.isfinite(y)) or not np.allclose(y, reference, rtol=1e-12, atol=1e-12):
                raise AssertionError(f'{name}: trial {trial+1} mismatch')
            errors[name] = max(errors[name], float(np.max(np.abs(y-reference))))
            del y
        print(f'Trial {trial+1}/{args.repeat} complete', flush=True)
    base = median(times[methods[0][0]])
    print('\nmethod                  median(s)   minimum(s)    speedup    max.abs.err   match')
    for name, _ in methods:
        med = median(times[name])
        ratio = base/med if med else float('inf')
        print(f'{name:22s} {med:11.6f} {min(times[name]):12.6f} {ratio:9.2f}x {errors[name]:14.3e}    True')
    print('\nnp.vectorize is a convenience wrapper, not compilation.')
    print('NumPy expression uses multiple passes; Numba can fuse this expression into one loop.')
    print('Speedups compare these implementations, including allocation, on this machine.')


if __name__ == '__main__':
    main()