"""
概要:
    要素ごとの計算処理についてPython、NumPy、numpy.vectorize、Numbaを比較します。
詳細説明:
    NumPyが必須ですが、Numbaのインストールは任意です。GPUや並列実行は行いません。
    すべての実装はfloat64精度で sin(x) + x*x + 1 を計算し、配列を返します。
    入力データの作成、ウォームアップ、結果の検証、標準出力への表示は計測時間に含まれません。
    出力用配列のメモリ割り当てや計算中の中間配列生成は計測時間に含まれます。
    実行例は python ufunc_benchmark.py -n 1000000 --repeat 5 です。
関連リンク:
    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):
    """
    概要:
        要素ごとのスカラー計算を行います。
    詳細説明:
        入力値xに対して sin(x) + x*x + 1.0 の結果を返します。
    引数:
        :param x: 計算対象の数値。
        :type x: float
    戻り値:
        :returns: 数式を適用した計算結果。
        :rtype: float
    """
    return math.sin(x) + x*x + 1.0


def python_loop(x):
    """
    概要:
        Pythonのforループを用いて要素ごとの計算を行います。
    詳細説明:
        入力配列と同じサイズの空配列を作成し、各要素に対して scalar_function を呼び出します。
    引数:
        :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):
    """
    概要:
        リスト内包表記を用いて要素ごとの計算を行います。
    詳細説明:
        入力配列の各要素に対して scalar_function を呼び出し、結果をNumPy配列に変換して返します。
    引数:
        :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():
    """
    概要:
        ベンチマークのメイン処理を実行します。
    詳細説明:
        コマンドライン引数を解析して入力データを生成し、各計算手法のウォームアップおよび
        実行時間の計測を繰り返し行います。最後に各手法の計算時間の中央値、最小値、速度向上率などを出力します。
    例外:
        :raises SystemExit: コマンドライン引数の指定が不正な場合に発生します。
        :raises AssertionError: 実行結果がNumPyの基準値と一致しない場合に発生します。
    """
    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()