"""
概要:
    DFTおよびFFTのベンチマークを実行するスクリプトです。
詳細説明:
    直接計算によるDFT、CPUを利用したFFT、GPUを利用したFFT、およびRGB画像に対するFFTの計算速度を比較します。
    オプションパッケージとして numba、cupy、Pillow、psutil が利用可能です。
    実行例:
    python dft.py
    python dft.py --nmax 1048576 --no-gpu
    python dft.py image.png --repeat 10
"""
import argparse
import csv
import math
import os
import platform
import statistics
import sys
from pathlib import Path
from time import perf_counter

import matplotlib.pyplot as plt
import numpy as np

try:
    import psutil
except ImportError:
    psutil = None
try:
    import numba
    from numba import njit
    HAVE_NUMBA = True
except ImportError:
    numba = None
    njit = None
    HAVE_NUMBA = False
try:
    import cupy as cp
    try:
        HAVE_GPU = cp.cuda.runtime.getDeviceCount() > 0
        GPU_ERROR = ""
    except Exception as exc:
        HAVE_GPU, GPU_ERROR = False, str(exc)
except ImportError:
    cp = None
    HAVE_GPU, GPU_ERROR = False, "CuPy is not installed"


def dft_python(y):
    """
    概要:
        直接計算による離散フーリエ変換を行います。
    詳細説明:
        計算量はO(N^2)、追加メモリはO(N)です。
    引数:
        :param y: 入力信号の配列
        :type y: numpy.ndarray
    戻り値:
        :returns: フーリエ変換後の複素数配列
        :rtype: numpy.ndarray
    """
    size = len(y)
    result = np.zeros(size, dtype=np.complex128)
    for k in range(size):
        value = 0j
        for j in range(size):
            phase = -2.0 * math.pi * j * k / size
            value += y[j] * complex(math.cos(phase), math.sin(phase))
        result[k] = value
    return result


if HAVE_NUMBA:
    @njit(cache=True)
    def dft_numba(y):
        """
        概要:
            Numbaを使用してコンパイルされた直接計算による離散フーリエ変換です。
        詳細説明:
            計算量はO(N^2)であり、dft_pythonと同じ処理を高速化して実行します。
        引数:
            :param y: 入力信号の配列
            :type y: numpy.ndarray
        戻り値:
            :returns: フーリエ変換後の複素数配列
            :rtype: numpy.ndarray
        """
        size = len(y)
        result = np.zeros(size, dtype=np.complex128)
        for k in range(size):
            value = 0j
            for j in range(size):
                phase = -2.0 * np.pi * j * k / size
                value += y[j] * (np.cos(phase) + 1j * np.sin(phase))
            result[k] = value
        return result
else:
    dft_numba = None


def human_bytes(value):
    """
    概要:
        バイト数を人間が読みやすい単位の文字列に変換します。
    引数:
        :param value: バイト数
        :type value: int または float または None
    戻り値:
        :returns: 単位付きのバイト数文字列
        :rtype: str
    """
    if value is None:
        return "unknown"
    value = float(value)
    for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
        if value < 1024 or unit == "TiB":
            return f"{value:.2f} {unit}"
        value /= 1024


def cuda_version(value):
    """
    概要:
        CUDAのバージョン数値を文字列に変換します。
    引数:
        :param value: CUDAのバージョンを表す整数
        :type value: int
    戻り値:
        :returns: バージョン文字列
        :rtype: str
    """
    return f"{value // 1000}.{(value % 1000) // 10}"


def system_information(want_gpu):
    """
    概要:
        システム情報を標準出力に表示します。
    詳細説明:
        OS、Python、NumPyのバージョン、CPU、メモリ、NumbaやGPUの利用可能状況を出力します。
    引数:
        :param want_gpu: GPU情報を取得するかどうかのフラグ
        :type want_gpu: bool
    戻り値:
        :returns: なし
        :rtype: None
    """
    print("\n=== System information ===")
    print(f"OS              : {platform.platform()}")
    print(f"Python          : {platform.python_version()}")
    print(f"NumPy           : {np.__version__}")
    print(f"CPU             : {platform.processor() or platform.machine() or 'unknown'}")
    print(f"Logical CPUs    : {os.cpu_count() or 'unknown'}")
    if psutil:
        print(f"Physical cores  : {psutil.cpu_count(logical=False) or 'unknown'}")
        print(f"System memory   : {human_bytes(psutil.virtual_memory().total)}")
    else:
        print("Physical cores  : unavailable (install psutil)")
        print("System memory   : unavailable (install psutil)")
    print(f"Numba           : {numba.__version__ if HAVE_NUMBA else 'unavailable'}")
    if not want_gpu:
        print("GPU FFT         : disabled by --no-gpu")
    elif not HAVE_GPU:
        print(f"GPU FFT         : unavailable ({GPU_ERROR})")
    else:
        device = cp.cuda.Device().id
        prop = cp.cuda.runtime.getDeviceProperties(device)
        name = prop["name"]
        if isinstance(name, bytes):
            name = name.decode(errors="replace")
        free, total = cp.cuda.runtime.memGetInfo()
        print(f"CuPy            : {cp.__version__}")
        print(f"GPU device      : {device}: {name}")
        print(f"GPU memory      : {human_bytes(total)} total, {human_bytes(free)} free")
        print(f"CUDA runtime    : {cuda_version(cp.cuda.runtime.runtimeGetVersion())}")
        print(f"CUDA driver     : {cuda_version(cp.cuda.runtime.driverGetVersion())}")


def make_signal(size, seed):
    """
    概要:
        指定されたサイズとシード値でテスト用の1次元信号を生成します。
    詳細説明:
        複数の正弦波と正規分布ノイズを組み合わせた複素数配列を生成します。
    引数:
        :param size: 信号のサンプル数
        :type size: int
        :param seed: 乱数生成のシード値
        :type seed: int
    戻り値:
        :returns: テスト用信号の複素数配列
        :rtype: numpy.ndarray
    """
    rng = np.random.default_rng(seed)
    x = np.arange(size, dtype=np.float64) / size
    y = (np.sin(2*np.pi*7*x + np.pi/4)
         + 0.3*np.sin(2*np.pi*31*x + np.pi/3)
         + 0.5*np.sin(2*np.pi*113*x + np.pi/6)
         + 0.02*rng.standard_normal(size))
    return y.astype(np.complex128)


def timed(function, repeat):
    """
    概要:
        関数の実行時間を測定します。
    詳細説明:
        指定された関数を複数回実行し、実行時間の中央値と関数の戻り値を取得します。
    引数:
        :param function: 実行時間を測定する対象の関数
        :type function: callable
        :param repeat: 関数の実行回数
        :type repeat: int
    戻り値:
        :returns: 実行時間の中央値と関数の戻り値のタプル
        :rtype: tuple
    """
    times, result = [], None
    for _ in range(repeat):
        start = perf_counter()
        result = function()
        times.append(perf_counter() - start)
    return statistics.median(times), result


def relative_error(reference, result):
    """
    概要:
        基準値と計算結果の間の相対誤差の最大値を計算します。
    引数:
        :param reference: 基準となる配列
        :type reference: numpy.ndarray
        :param result: 計算結果の配列
        :type result: numpy.ndarray
    戻り値:
        :returns: 相対誤差の最大値
        :rtype: float
    """
    scale = max(float(np.max(np.abs(reference))), np.finfo(float).tiny)
    return float(np.max(np.abs(reference-result)) / scale)


def gpu_fft1(y, repeat):
    """
    概要:
        GPUを利用して1次元配列のFFTを計算し、実行時間を測定します。
    詳細説明:
        カーネル実行時間とデータ転送を含む全体実行時間の両方を測定し、中央値を返します。
    引数:
        :param y: 入力信号の配列
        :type y: numpy.ndarray または list
        :param repeat: 実行回数
        :type repeat: int
    戻り値:
        :returns: カーネル実行時間の中央値、全体実行時間の中央値、計算結果配列のタプル
        :rtype: tuple
    """
    yg = cp.asarray(y)
    cp.fft.fft(yg)
    cp.cuda.Stream.null.synchronize()
    kernel = []
    for _ in range(repeat):
        cp.cuda.Stream.null.synchronize()
        start = perf_counter()
        resultg = cp.fft.fft(yg)
        cp.cuda.Stream.null.synchronize()
        kernel.append(perf_counter()-start)
    total = []
    for _ in range(repeat):
        cp.cuda.Stream.null.synchronize()
        start = perf_counter()
        result = cp.asnumpy(cp.fft.fft(cp.asarray(y)))
        cp.cuda.Stream.null.synchronize()
        total.append(perf_counter()-start)
    return statistics.median(kernel), statistics.median(total), result


def sizes(nmin, nmax, factor):
    """
    概要:
        ベンチマーク用のデータサイズリストを生成します。
    詳細説明:
        最小値から最大値まで、指定した係数を掛けて増加させたサイズのリストを作成します。
    引数:
        :param nmin: 最小サイズ
        :type nmin: int
        :param nmax: 最大サイズ
        :type nmax: int
        :param factor: サイズを増加させる際の乗数
        :type factor: int または float
    戻り値:
        :returns: サイズのリスト
        :rtype: list
    """
    result = []
    while nmin <= nmax:
        result.append(nmin)
        nmin *= factor
    return result


def signal_benchmark(args):
    """
    概要:
        1次元信号データに対するDFTとFFTのベンチマークを実行します。
    詳細説明:
        Python、Numba、CPU、GPUを用いた計算時間を測定し、結果をCSVファイルと画像ファイルに出力します。
    引数:
        :param args: コマンドライン引数を格納したNamespaceオブジェクト
        :type args: argparse.Namespace
    戻り値:
        :returns: なし
        :rtype: None
    """
    print("\n=== 1D DFT/FFT benchmark ===")
    if HAVE_NUMBA:
        start = perf_counter()
        dft_numba(make_signal(8, args.seed))
        print(f"Numba first call (JIT/cache startup): {perf_counter()-start:.6g} s")
    rows, gpu_ok = [], args.gpu and HAVE_GPU
    header = (f"{'N':>10} {'Python DFT':>13} {'Numba DFT':>13} "
              f"{'CPU FFT':>13} {'GPU kernel':>13} {'GPU total':>13}")
    print("\n"+header)
    print("-"*len(header))
    for size in sizes(args.nmin, args.nmax, args.factor):
        y = make_signal(size, args.seed)
        np.fft.fft(y)  # warm-up
        tcpu, reference = timed(lambda: np.fft.fft(y), args.repeat)
        tp = tn = tg = tt = ep = en = eg = None
        if size <= args.python_max:
            tp, result = timed(lambda: dft_python(y), args.dft_repeat)
            ep = relative_error(reference, result)
        if HAVE_NUMBA and size <= args.numba_max:
            tn, result = timed(lambda: dft_numba(y), args.dft_repeat)
            en = relative_error(reference, result)
        if gpu_ok:
            try:
                tg, tt, result = gpu_fft1(y, args.repeat)
                eg = relative_error(reference, result)
            except Exception as exc:
                print(f"GPU measurement stopped at N={size}: {exc}")
                gpu_ok = False
        row = dict(N=size, python_dft_s=tp, numba_dft_s=tn, cpu_fft_s=tcpu,
                   gpu_fft_kernel_s=tg, gpu_fft_total_s=tt,
                   python_rel_error=ep, numba_rel_error=en, gpu_rel_error=eg)
        rows.append(row)
        show = lambda v: "skip" if v is None else f"{v:.6g}"
        print(f"{size:10d} {show(tp):>13} {show(tn):>13} {show(tcpu):>13} "
              f"{show(tg):>13} {show(tt):>13}")
    csv_path = Path(args.output_prefix+".csv")
    with csv_path.open("w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=rows[0].keys())
        writer.writeheader()
        writer.writerows(rows)
    fig, ax = plt.subplots(figsize=(8, 6))
    plots = [("python_dft_s", "Python DFT", "o-"),
             ("numba_dft_s", "Numba DFT", "s-"),
             ("cpu_fft_s", "CPU FFT", "^-"),
             ("gpu_fft_kernel_s", "GPU FFT (kernel)", "D-"),
             ("gpu_fft_total_s", "GPU FFT (transfer included)", "v-")]
    for key, label, style in plots:
        points = [(r["N"], r[key]) for r in rows if r[key] is not None]
        if points:
            ax.loglog(*zip(*points), style, label=label)
    ax.set(xlabel="Number of samples N", ylabel="Median execution time (s)",
           title="DFT / FFT benchmark")
    ax.grid(True, which="both", alpha=.3)
    ax.legend()
    fig.tight_layout()
    png_path = Path(args.output_prefix+".png")
    fig.savefig(png_path, dpi=160)
    if args.show:
        plt.show()
    else:
        plt.close(fig)
    print(f"\nCSV             : {csv_path}")
    print(f"Benchmark plot  : {png_path}")
    print("CSV errors are relative maximum errors against the CPU FFT.")


def load_image(path):
    """
    概要:
        指定されたパスの画像ファイルを読み込みます。
    詳細説明:
        Pillowを使用して画像を開き、RGB形式の浮動小数点数配列として返します。
    引数:
        :param path: 画像ファイルのパス
        :type path: str または pathlib.Path
    戻り値:
        :returns: 画像データの配列
        :rtype: numpy.ndarray
    例外:
        :raises RuntimeError: Pillowがインストールされていない場合に発生
    """
    try:
        from PIL import Image
    except ImportError as exc:
        raise RuntimeError("Image mode requires Pillow: pip install pillow") from exc
    with Image.open(path) as image:
        return np.asarray(image.convert("RGB"), dtype=np.float32)


def gpu_fft2(image, repeat):
    """
    概要:
        GPUを利用して画像データの2次元FFTを計算し、実行時間を測定します。
    詳細説明:
        カーネル実行時間とデータ転送を含む全体実行時間の両方を測定し、中央値を返します。
    引数:
        :param image: 入力画像データの配列
        :type image: numpy.ndarray
        :param repeat: 実行回数
        :type repeat: int
    戻り値:
        :returns: カーネル実行時間の中央値、全体実行時間の中央値、計算結果配列のタプル
        :rtype: tuple
    """
    imageg = cp.asarray(image)
    cp.fft.fft2(imageg, axes=(0, 1))
    cp.cuda.Stream.null.synchronize()
    kernel = []
    for _ in range(repeat):
        cp.cuda.Stream.null.synchronize()
        start = perf_counter()
        resultg = cp.fft.fft2(imageg, axes=(0, 1))
        cp.cuda.Stream.null.synchronize()
        kernel.append(perf_counter()-start)
    total = []
    for _ in range(repeat):
        cp.cuda.Stream.null.synchronize()
        start = perf_counter()
        result = cp.asnumpy(cp.fft.fft2(cp.asarray(image), axes=(0, 1)))
        cp.cuda.Stream.null.synchronize()
        total.append(perf_counter()-start)
    return statistics.median(kernel), statistics.median(total), result


def normalized_spectrum(channel):
    """
    概要:
        FFT結果のチャンネルデータを対数スケールで正規化します。
    詳細説明:
        画像のスペクトルを表示用に0から1の範囲にスケーリングします。
    引数:
        :param channel: FFT結果の1チャンネル分の配列
        :type channel: numpy.ndarray
    戻り値:
        :returns: 正規化されたスペクトル配列
        :rtype: numpy.ndarray
    """
    value = np.log1p(np.abs(channel))
    lo, hi = float(value.min()), float(value.max())
    return np.zeros_like(value) if hi <= lo else (value-lo)/(hi-lo)


def image_benchmark(args):
    """
    概要:
        RGB画像に対する2次元FFTのベンチマークを実行します。
    詳細説明:
        CPUおよびGPUを用いた計算時間を測定し、結果をCSVファイルとスペクトル画像ファイルに出力します。
    引数:
        :param args: コマンドライン引数を格納したNamespaceオブジェクト
        :type args: argparse.Namespace
    戻り値:
        :returns: なし
        :rtype: None
    例外:
        :raises FileNotFoundError: 指定された画像ファイルが存在しない場合に発生
    """
    path = Path(args.image)
    if not path.is_file():
        raise FileNotFoundError(f"Image file not found: {path}")
    image = load_image(path)
    height, width, channels = image.shape
    print("\n=== RGB image 2D FFT benchmark ===")
    print(f"Image           : {path}")
    print(f"Shape           : {width} x {height} x {channels}")
    print(f"Input dtype     : {image.dtype}")
    print(f"Input size      : {human_bytes(image.nbytes)}")
    np.fft.fft2(image, axes=(0, 1))
    tcpu, reference = timed(lambda: np.fft.fft2(image, axes=(0, 1)), args.repeat)
    tg = tt = error = None
    print(f"CPU FFT         : {tcpu:.6g} s (median)")
    if args.gpu and HAVE_GPU:
        tg, tt, result = gpu_fft2(image, args.repeat)
        error = relative_error(reference, result)
        print(f"GPU FFT kernel  : {tg:.6g} s (median)")
        print(f"GPU FFT total   : {tt:.6g} s (transfers included)")
        print(f"GPU rel. error  : {error:.6g}")
    elif args.gpu:
        print(f"GPU FFT         : unavailable ({GPU_ERROR})")
    else:
        print("GPU FFT         : disabled")
    csv_path = Path(args.output_prefix+".csv")
    fields = ["file", "width", "height", "channels", "cpu_fft_s",
              "gpu_fft_kernel_s", "gpu_fft_total_s", "gpu_rel_error"]
    with csv_path.open("w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=fields)
        writer.writeheader()
        writer.writerow(dict(zip(fields, [str(path), width, height, channels,
                                          tcpu, tg, tt, error])))
    shifted = np.fft.fftshift(reference, axes=(0, 1))
    fig, axes = plt.subplots(2, 2, figsize=(11, 9))
    axes[0, 0].imshow(np.clip(image/255, 0, 1))
    axes[0, 0].set_title("Original RGB image")
    axes[0, 0].axis("off")
    for index, (name, cmap, ax) in enumerate(
            zip("RGB", ("Reds", "Greens", "Blues"), axes.flat[1:])):
        ax.imshow(normalized_spectrum(shifted[:, :, index]), cmap=cmap)
        ax.set_title(f"{name}: log(1 + |FFT|)")
        ax.axis("off")
    title = f"2D FFT: {width} x {height} RGB\nCPU {tcpu:.4g} s"
    if tg is not None:
        title += f", GPU kernel {tg:.4g} s, total {tt:.4g} s"
    fig.suptitle(title)
    fig.tight_layout()
    png_path = Path(args.output_prefix+"_spectrum.png")
    fig.savefig(png_path, dpi=160)
    if args.show:
        plt.show()
    else:
        plt.close(fig)
    print(f"CSV             : {csv_path}")
    print(f"FFT image       : {png_path}")


def positive(text):
    """
    概要:
        入力文字列を正の整数に変換して検証します。
    引数:
        :param text: 変換対象の文字列
        :type text: str
    戻り値:
        :returns: 正の整数
        :rtype: int
    例外:
        :raises argparse.ArgumentTypeError: 値が0以下の場合に発生
    """
    value = int(text)
    if value <= 0:
        raise argparse.ArgumentTypeError("must be positive")
    return value


def arguments():
    """
    概要:
        コマンドライン引数を解析します。
    戻り値:
        :returns: 解析済みの引数オブジェクト
        :rtype: argparse.Namespace
    """
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("image", nargs="?", help="image file: enable RGB 2D FFT mode")
    parser.add_argument("--nmin", type=positive, default=64)
    parser.add_argument("--nmax", type=positive, default=1_048_576)
    parser.add_argument("--factor", type=positive, default=2)
    parser.add_argument("--python-max", type=positive, default=1024)
    parser.add_argument("--numba-max", type=positive, default=8192)
    parser.add_argument("--repeat", type=positive, default=5)
    parser.add_argument("--dft-repeat", type=positive, default=1)
    parser.add_argument("--seed", type=int, default=12345)
    parser.add_argument("--no-gpu", dest="gpu", action="store_false")
    parser.set_defaults(gpu=True)
    parser.add_argument("--output-prefix")
    parser.add_argument("--show", action="store_true")
    args = parser.parse_args()
    if args.factor < 2:
        parser.error("--factor must be at least 2")
    if args.nmin > args.nmax:
        parser.error("--nmin must not exceed --nmax")
    if not args.output_prefix:
        args.output_prefix = f"{Path(args.image).stem}_fft" if args.image else "dft_benchmark"
    return args


def main():
    """
    概要:
        ベンチマークスクリプトのメイン処理を実行します。
    詳細説明:
        システム情報を表示したのち、画像が指定されていれば画像ベンチマークを、
        指定されていなければ1次元信号ベンチマークを実行します。
    戻り値:
        :returns: 終了コード
        :rtype: int
    """
    args = arguments()
    system_information(args.gpu)
    try:
        image_benchmark(args) if args.image else signal_benchmark(args)
    except (FileNotFoundError, RuntimeError, MemoryError) as exc:
        print(f"\nError: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())