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