dft_comparison.py ダウンロード/コピー

dft_comparison.py をダウンロード

dft_comparison.py
dft_comparison.py
  1"""
  2概要:
  3    DFTおよびFFTのベンチマークを実行するスクリプトです。
  4詳細説明:
  5    Python標準の直接DFT、NumbaコンパイルされたDFT、CPUでのFFT、GPUでのFFT、
  6    およびRGB画像の2D FFTのパフォーマンスを比較・計測します。
  7    numba、cupy、Pillow、psutilなどのオプションパッケージを利用して拡張機能を提供します。
  8"""
  9import argparse
 10import csv
 11import math
 12import os
 13import platform
 14import statistics
 15import sys
 16from pathlib import Path
 17from time import perf_counter
 18
 19import matplotlib.pyplot as plt
 20import numpy as np
 21
 22try:
 23    import psutil
 24except ImportError:
 25    psutil = None
 26try:
 27    import numba
 28    from numba import njit
 29    HAVE_NUMBA = True
 30except ImportError:
 31    numba = None
 32    njit = None
 33    HAVE_NUMBA = False
 34try:
 35    import cupy as cp
 36    try:
 37        HAVE_GPU = cp.cuda.runtime.getDeviceCount() > 0
 38        GPU_ERROR = ""
 39    except Exception as exc:
 40        HAVE_GPU, GPU_ERROR = False, str(exc)
 41except ImportError:
 42    cp = None
 43    HAVE_GPU, GPU_ERROR = False, "CuPy is not installed"
 44
 45
 46def dft_python(y):
 47    """
 48    概要:
 49        直接計算による離散フーリエ変換(DFT)を実行します。
 50    詳細説明:
 51        計算量はO(N^2)であり、追加メモリはO(N)必要です。
 52    引数:
 53        :param y: 変換対象の入力1次元配列。
 54        :type y: list または numpy.ndarray
 55    戻り値:
 56        :returns: フーリエ変換後の複素数配列。
 57        :rtype: numpy.ndarray
 58    """
 59    size = len(y)
 60    result = np.zeros(size, dtype=np.complex128)
 61    for k in range(size):
 62        value = 0j
 63        for j in range(size):
 64            phase = -2.0 * math.pi * j * k / size
 65            value += y[j] * complex(math.cos(phase), math.sin(phase))
 66        result[k] = value
 67    return result
 68
 69
 70if HAVE_NUMBA:
 71    @njit(cache=True)
 72    def dft_numba(y):
 73        """
 74        概要:
 75            Numbaでコンパイルされた直接DFT関数です。
 76        詳細説明:
 77            dft_pythonと同じく計算量O(N^2)のアルゴリズムですが、JITコンパイルにより高速化されています。
 78        引数:
 79            :param y: 変換対象の入力1次元配列。
 80            :type y: numpy.ndarray
 81        戻り値:
 82            :returns: フーリエ変換後の複素数配列。
 83            :rtype: numpy.ndarray
 84        """
 85        size = len(y)
 86        result = np.zeros(size, dtype=np.complex128)
 87        for k in range(size):
 88            value = 0j
 89            for j in range(size):
 90                phase = -2.0 * np.pi * j * k / size
 91                value += y[j] * (np.cos(phase) + 1j * np.sin(phase))
 92            result[k] = value
 93        return result
 94else:
 95    dft_numba = None
 96
 97
 98def human_bytes(value):
 99    """
100    概要:
101        バイト数を人間が読みやすい単位の文字列に変換します。
102    引数:
103        :param value: バイト数。
104        :type value: int または float または None
105    戻り値:
106        :returns: B、KiB、MiBなどの単位を付与した文字列。
107        :rtype: str
108    """
109    if value is None:
110        return "unknown"
111    value = float(value)
112    for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
113        if value < 1024 or unit == "TiB":
114            return f"{value:.2f} {unit}"
115        value /= 1024
116
117
118def cuda_version(value):
119    """
120    概要:
121        CUDAバージョンの整数値を文字列形式に変換します。
122    引数:
123        :param value: バージョン情報を示す整数値。
124        :type value: int
125    戻り値:
126        :returns: メジャーバージョンとマイナーバージョンをドットで繋いだ文字列。
127        :rtype: str
128    """
129    return f"{value // 1000}.{(value % 1000) // 10}"
130
131
132def system_information(want_gpu):
133    """
134    概要:
135        システムのOSやハードウェア、ライブラリ環境の情報を出力します。
136    引数:
137        :param want_gpu: GPUの使用を希望するかどうかを示すフラグ。
138        :type want_gpu: bool
139    戻り値:
140        :returns: なし
141        :rtype: None
142    """
143    print("\n=== System information ===")
144    print(f"OS              : {platform.platform()}")
145    print(f"Python          : {platform.python_version()}")
146    print(f"NumPy           : {np.__version__}")
147    print(f"CPU             : {platform.processor() or platform.machine() or 'unknown'}")
148    print(f"Logical CPUs    : {os.cpu_count() or 'unknown'}")
149    if psutil:
150        print(f"Physical cores  : {psutil.cpu_count(logical=False) or 'unknown'}")
151        print(f"System memory   : {human_bytes(psutil.virtual_memory().total)}")
152    else:
153        print("Physical cores  : unavailable (install psutil)")
154        print("System memory   : unavailable (install psutil)")
155    print(f"Numba           : {numba.__version__ if HAVE_NUMBA else 'unavailable'}")
156    if not want_gpu:
157        print("GPU FFT         : disabled by --no-gpu")
158    elif not HAVE_GPU:
159        print(f"GPU FFT         : unavailable ({GPU_ERROR})")
160    else:
161        device = cp.cuda.Device().id
162        prop = cp.cuda.runtime.getDeviceProperties(device)
163        name = prop["name"]
164        if isinstance(name, bytes):
165            name = name.decode(errors="replace")
166        free, total = cp.cuda.runtime.memGetInfo()
167        print(f"CuPy            : {cp.__version__}")
168        print(f"GPU device      : {device}: {name}")
169        print(f"GPU memory      : {human_bytes(total)} total, {human_bytes(free)} free")
170        print(f"CUDA runtime    : {cuda_version(cp.cuda.runtime.runtimeGetVersion())}")
171        print(f"CUDA driver     : {cuda_version(cp.cuda.runtime.driverGetVersion())}")
172
173
174def make_signal(size, seed):
175    """
176    概要:
177        テスト用の1次元信号を生成します。
178    詳細説明:
179        複数の正弦波と正規分布ノイズを合成してテスト用信号を作成します。
180    引数:
181        :param size: 生成する信号のサンプル数。
182        :type size: int
183        :param seed: 乱数生成器のシード値。
184        :type seed: int
185    戻り値:
186        :returns: 生成された複素数配列。
187        :rtype: numpy.ndarray
188    """
189    rng = np.random.default_rng(seed)
190    x = np.arange(size, dtype=np.float64) / size
191    y = (np.sin(2*np.pi*7*x + np.pi/4)
192         + 0.3*np.sin(2*np.pi*31*x + np.pi/3)
193         + 0.5*np.sin(2*np.pi*113*x + np.pi/6)
194         + 0.02*rng.standard_normal(size))
195    return y.astype(np.complex128)
196
197
198def timed(function, repeat):
199    """
200    概要:
201        指定された関数の実行時間を計測します。
202    詳細説明:
203        関数を複数回実行し、その実行時間の中心値(中央値)と最後に関数が返した結果を返します。
204    引数:
205        :param function: 実行する対象の関数。
206        :type function: callable
207        :param repeat: 実行を繰り返す回数。
208        :type repeat: int
209    戻り値:
210        :returns: 実行時間の中央値と関数の戻り値のタプル。
211        :rtype: tuple
212    """
213    times, result = [], None
214    for _ in range(repeat):
215        start = perf_counter()
216        result = function()
217        times.append(perf_counter() - start)
218    return statistics.median(times), result
219
220
221def relative_error(reference, result):
222    """
223    概要:
224        参照データに対する計算結果の相対誤差を算出します。
225    引数:
226        :param reference: 基準となる参照配列。
227        :type reference: numpy.ndarray
228        :param result: 評価対象の計算結果配列。
229        :type result: numpy.ndarray
230    戻り値:
231        :returns: 最大絶対誤差を基準値の最大振幅で割った相対誤差。
232        :rtype: float
233    """
234    scale = max(float(np.max(np.abs(reference))), np.finfo(float).tiny)
235    return float(np.max(np.abs(reference-result)) / scale)
236
237
238def gpu_fft1(y, repeat):
239    """
240    概要:
241        GPUを利用して1次元FFTのベンチマークを実行します。
242    詳細説明:
243        カーネルのみの実行時間と、CPU・GPU間のデータ転送を含めた全体実行時間の両方を計測します。
244    引数:
245        :param y: 変換対象の入力1次元配列。
246        :type y: numpy.ndarray
247        :param repeat: 計測を繰り返す回数。
248        :type repeat: int
249    戻り値:
250        :returns: カーネル実行時間の中央値、全体実行時間の中央値、FFT結果のタプル。
251        :rtype: tuple
252    """
253    yg = cp.asarray(y)
254    cp.fft.fft(yg)
255    cp.cuda.Stream.null.synchronize()
256    kernel = []
257    for _ in range(repeat):
258        cp.cuda.Stream.null.synchronize()
259        start = perf_counter()
260        resultg = cp.fft.fft(yg)
261        cp.cuda.Stream.null.synchronize()
262        kernel.append(perf_counter()-start)
263    total = []
264    for _ in range(repeat):
265        cp.cuda.Stream.null.synchronize()
266        start = perf_counter()
267        result = cp.asnumpy(cp.fft.fft(cp.asarray(y)))
268        cp.cuda.Stream.null.synchronize()
269        total.append(perf_counter()-start)
270    return statistics.median(kernel), statistics.median(total), result
271
272
273def sizes(nmin, nmax, factor):
274    """
275    概要:
276        テスト用信号のサイズ一覧を生成します。
277    詳細説明:
278        nminから開始し、nmaxを超えない範囲でfactorを乗算してサイズを増やします。
279    引数:
280        :param nmin: 最小サイズ。
281        :type nmin: int
282        :param nmax: 最大サイズ。
283        :type nmax: int
284        :param factor: サイズを増加させる倍率。
285        :type factor: int
286    戻り値:
287        :returns: テストサイズのリスト。
288        :rtype: list
289    """
290    result = []
291    while nmin <= nmax:
292        result.append(nmin)
293        nmin *= factor
294    return result
295
296
297def signal_benchmark(args):
298    """
299    概要:
300        1次元のDFTおよびFFTのベンチマークを実行します。
301    詳細説明:
302        設定されたサイズごとにPython直接計算、Numba、CPU FFT、GPU FFTの時間を計測します。
303        結果はCSVに出力され、グラフ画像として保存されます。
304    引数:
305        :param args: コマンドライン引数を格納した名前空間オブジェクト。
306        :type args: argparse.Namespace
307    戻り値:
308        :returns: なし
309        :rtype: None
310    """
311    print("\n=== 1D DFT/FFT benchmark ===")
312    if HAVE_NUMBA:
313        start = perf_counter()
314        dft_numba(make_signal(8, args.seed))
315        print(f"Numba first call (JIT/cache startup): {perf_counter()-start:.6g} s")
316    rows, gpu_ok = [], args.gpu and HAVE_GPU
317    header = (f"{'N':>10} {'Python DFT':>13} {'Numba DFT':>13} "
318              f"{'CPU FFT':>13} {'GPU kernel':>13} {'GPU total':>13}")
319    print("\n"+header)
320    print("-"*len(header))
321    for size in sizes(args.nmin, args.nmax, args.factor):
322        y = make_signal(size, args.seed)
323        np.fft.fft(y)  # warm-up
324        tcpu, reference = timed(lambda: np.fft.fft(y), args.repeat)
325        tp = tn = tg = tt = ep = en = eg = None
326        if size <= args.python_max:
327            tp, result = timed(lambda: dft_python(y), args.dft_repeat)
328            ep = relative_error(reference, result)
329        if HAVE_NUMBA and size <= args.numba_max:
330            tn, result = timed(lambda: dft_numba(y), args.dft_repeat)
331            en = relative_error(reference, result)
332        if gpu_ok:
333            try:
334                tg, tt, result = gpu_fft1(y, args.repeat)
335                eg = relative_error(reference, result)
336            except Exception as exc:
337                print(f"GPU measurement stopped at N={size}: {exc}")
338                gpu_ok = False
339        row = dict(N=size, python_dft_s=tp, numba_dft_s=tn, cpu_fft_s=tcpu,
340                   gpu_fft_kernel_s=tg, gpu_fft_total_s=tt,
341                   python_rel_error=ep, numba_rel_error=en, gpu_rel_error=eg)
342        rows.append(row)
343        show = lambda v: "skip" if v is None else f"{v:.6g}"
344        print(f"{size:10d} {show(tp):>13} {show(tn):>13} {show(tcpu):>13} "
345              f"{show(tg):>13} {show(tt):>13}")
346    csv_path = Path(args.output_prefix+".csv")
347    with csv_path.open("w", newline="", encoding="utf-8") as file:
348        writer = csv.DictWriter(file, fieldnames=rows[0].keys())
349        writer.writeheader()
350        writer.writerows(rows)
351    fig, ax = plt.subplots(figsize=(8, 6))
352    plots = [("python_dft_s", "Python DFT", "o-"),
353             ("numba_dft_s", "Numba DFT", "s-"),
354             ("cpu_fft_s", "CPU FFT", "^-"),
355             ("gpu_fft_kernel_s", "GPU FFT (kernel)", "D-"),
356             ("gpu_fft_total_s", "GPU FFT (transfer included)", "v-")]
357    for key, label, style in plots:
358        points = [(r["N"], r[key]) for r in rows if r[key] is not None]
359        if points:
360            ax.loglog(*zip(*points), style, label=label)
361    ax.set(xlabel="Number of samples N", ylabel="Median execution time (s)",
362           title="DFT / FFT benchmark")
363    ax.grid(True, which="both", alpha=.3)
364    ax.legend()
365    fig.tight_layout()
366    png_path = Path(args.output_prefix+".png")
367    fig.savefig(png_path, dpi=160)
368    if args.show:
369        plt.show()
370    else:
371        plt.close(fig)
372    print(f"\nCSV             : {csv_path}")
373    print(f"Benchmark plot  : {png_path}")
374    print("CSV errors are relative maximum errors against the CPU FFT.")
375
376
377def load_image(path):
378    """
379    概要:
380        画像ファイルを読み込み、RGBの浮動小数点数配列として返します。
381    詳細説明:
382        Pillowライブラリを利用して画像を読み込みます。
383    引数:
384        :param path: 読み込む画像のファイルパス。
385        :type path: str または pathlib.Path
386    戻り値:
387        :returns: 画像データが格納された配列。
388        :rtype: numpy.ndarray
389    例外:
390        :raises RuntimeError: Pillowがインストールされていない場合に発生します。
391    """
392    try:
393        from PIL import Image
394    except ImportError as exc:
395        raise RuntimeError("Image mode requires Pillow: pip install pillow") from exc
396    with Image.open(path) as image:
397        return np.asarray(image.convert("RGB"), dtype=np.float32)
398
399
400def gpu_fft2(image, repeat):
401    """
402    概要:
403        GPUを利用して2次元FFTのベンチマークを実行します。
404    詳細説明:
405        画像データを対象に、カーネル実行時間とデータ転送を含む全体実行時間を計測します。
406    引数:
407        :param image: 変換対象の入力画像配列。
408        :type image: numpy.ndarray
409        :param repeat: 計測を繰り返す回数。
410        :type repeat: int
411    戻り値:
412        :returns: カーネル実行時間の中央値、全体実行時間の中央値、FFT結果のタプル。
413        :rtype: tuple
414    """
415    imageg = cp.asarray(image)
416    cp.fft.fft2(imageg, axes=(0, 1))
417    cp.cuda.Stream.null.synchronize()
418    kernel = []
419    for _ in range(repeat):
420        cp.cuda.Stream.null.synchronize()
421        start = perf_counter()
422        resultg = cp.fft.fft2(imageg, axes=(0, 1))
423        cp.cuda.Stream.null.synchronize()
424        kernel.append(perf_counter()-start)
425    total = []
426    for _ in range(repeat):
427        cp.cuda.Stream.null.synchronize()
428        start = perf_counter()
429        result = cp.asnumpy(cp.fft.fft2(cp.asarray(image), axes=(0, 1)))
430        cp.cuda.Stream.null.synchronize()
431        total.append(perf_counter()-start)
432    return statistics.median(kernel), statistics.median(total), result
433
434
435def normalized_spectrum(channel):
436    """
437    概要:
438        2次元FFTの結果スペクトルを対数スケールで正規化します。
439    詳細説明:
440        可視化のために、複素数配列の絶対値の対数をとり、0から1の範囲に正規化します。
441    引数:
442        :param channel: FFT処理された1チャンネル分の複素数配列。
443        :type channel: numpy.ndarray
444    戻り値:
445        :returns: 正規化された画像配列。
446        :rtype: numpy.ndarray
447    """
448    value = np.log1p(np.abs(channel))
449    lo, hi = float(value.min()), float(value.max())
450    return np.zeros_like(value) if hi <= lo else (value-lo)/(hi-lo)
451
452
453def image_benchmark(args):
454    """
455    概要:
456        RGB画像を対象とした2次元FFTのベンチマークを実行します。
457    詳細説明:
458        入力画像に対してCPUとGPUで2次元FFTを実行して時間を計測し、
459        結果をCSVとスペクトルの可視化画像として出力します。
460    引数:
461        :param args: コマンドライン引数を格納した名前空間オブジェクト。
462        :type args: argparse.Namespace
463    戻り値:
464        :returns: なし
465        :rtype: None
466    例外:
467        :raises FileNotFoundError: 指定された画像ファイルが存在しない場合に発生します。
468    """
469    path = Path(args.image)
470    if not path.is_file():
471        raise FileNotFoundError(f"Image file not found: {path}")
472    image = load_image(path)
473    height, width, channels = image.shape
474    print("\n=== RGB image 2D FFT benchmark ===")
475    print(f"Image           : {path}")
476    print(f"Shape           : {width} x {height} x {channels}")
477    print(f"Input dtype     : {image.dtype}")
478    print(f"Input size      : {human_bytes(image.nbytes)}")
479    np.fft.fft2(image, axes=(0, 1))
480    tcpu, reference = timed(lambda: np.fft.fft2(image, axes=(0, 1)), args.repeat)
481    tg = tt = error = None
482    print(f"CPU FFT         : {tcpu:.6g} s (median)")
483    if args.gpu and HAVE_GPU:
484        tg, tt, result = gpu_fft2(image, args.repeat)
485        error = relative_error(reference, result)
486        print(f"GPU FFT kernel  : {tg:.6g} s (median)")
487        print(f"GPU FFT total   : {tt:.6g} s (transfers included)")
488        print(f"GPU rel. error  : {error:.6g}")
489    elif args.gpu:
490        print(f"GPU FFT         : unavailable ({GPU_ERROR})")
491    else:
492        print("GPU FFT         : disabled")
493    csv_path = Path(args.output_prefix+".csv")
494    fields = ["file", "width", "height", "channels", "cpu_fft_s",
495              "gpu_fft_kernel_s", "gpu_fft_total_s", "gpu_rel_error"]
496    with csv_path.open("w", newline="", encoding="utf-8") as file:
497        writer = csv.DictWriter(file, fieldnames=fields)
498        writer.writeheader()
499        writer.writerow(dict(zip(fields, [str(path), width, height, channels,
500                                          tcpu, tg, tt, error])))
501    shifted = np.fft.fftshift(reference, axes=(0, 1))
502    fig, axes = plt.subplots(2, 2, figsize=(11, 9))
503    axes[0, 0].imshow(np.clip(image/255, 0, 1))
504    axes[0, 0].set_title("Original RGB image")
505    axes[0, 0].axis("off")
506    for index, (name, cmap, ax) in enumerate(
507            zip("RGB", ("Reds", "Greens", "Blues"), axes.flat[1:])):
508        ax.imshow(normalized_spectrum(shifted[:, :, index]), cmap=cmap)
509        ax.set_title(f"{name}: log(1 + abs(FFT))")
510        ax.axis("off")
511    title = f"2D FFT: {width} x {height} RGB\nCPU {tcpu:.4g} s"
512    if tg is not None:
513        title += f", GPU kernel {tg:.4g} s, total {tt:.4g} s"
514    fig.suptitle(title)
515    fig.tight_layout()
516    png_path = Path(args.output_prefix+"_spectrum.png")
517    fig.savefig(png_path, dpi=160)
518    if args.show:
519        plt.show()
520    else:
521        plt.close(fig)
522    print(f"CSV             : {csv_path}")
523    print(f"FFT image       : {png_path}")
524
525
526def positive(text):
527    """
528    概要:
529        文字列を正の整数に変換し検証します。
530    引数:
531        :param text: 変換対象の文字列。
532        :type text: str
533    戻り値:
534        :returns: 変換された正の整数。
535        :rtype: int
536    例外:
537        :raises argparse.ArgumentTypeError: 0以下の値が指定された場合に発生します。
538    """
539    value = int(text)
540    if value <= 0:
541        raise argparse.ArgumentTypeError("must be positive")
542    return value
543
544
545def arguments():
546    """
547    概要:
548        コマンドライン引数を解析します。
549    戻り値:
550        :returns: 解析された引数が格納された名前空間オブジェクト。
551        :rtype: argparse.Namespace
552    """
553    parser = argparse.ArgumentParser(description=__doc__)
554    parser.add_argument("image", nargs="?", help="image file: enable RGB 2D FFT mode")
555    parser.add_argument("--nmin", type=positive, default=64)
556    parser.add_argument("--nmax", type=positive, default=1_048_576)
557    parser.add_argument("--factor", type=positive, default=2)
558    parser.add_argument("--python-max", type=positive, default=1024)
559    parser.add_argument("--numba-max", type=positive, default=8192)
560    parser.add_argument("--repeat", type=positive, default=5)
561    parser.add_argument("--dft-repeat", type=positive, default=1)
562    parser.add_argument("--seed", type=int, default=12345)
563    parser.add_argument("--no-gpu", dest="gpu", action="store_false")
564    parser.set_defaults(gpu=True)
565    parser.add_argument("--output-prefix")
566    parser.add_argument("--show", action="store_true")
567    args = parser.parse_args()
568    if args.factor < 2:
569        parser.error("--factor must be at least 2")
570    if args.nmin > args.nmax:
571        parser.error("--nmin must not exceed --nmax")
572    if not args.output_prefix:
573        args.output_prefix = f"{Path(args.image).stem}_fft" if args.image else "dft_benchmark"
574    return args
575
576
577def main():
578    """
579    概要:
580        スクリプトのメインエントリポイントです。
581    詳細説明:
582        引数を解析し、環境情報を出力した上で、指定に応じて1次元信号または画像のベンチマークを実行します。
583    戻り値:
584        :returns: 正常終了時は0、エラー時は1。
585        :rtype: int
586    """
587    args = arguments()
588    system_information(args.gpu)
589    try:
590        image_benchmark(args) if args.image else signal_benchmark(args)
591    except (FileNotFoundError, RuntimeError, MemoryError) as exc:
592        print(f"\nError: {exc}", file=sys.stderr)
593        return 1
594    return 0
595
596
597if __name__ == "__main__":
598    raise SystemExit(main())