import matplotlib.pyplot as plt
import pandas as pd
from scipy.signal import find_peaks
import sys

file_path = "J125188_0508_500Hz.txt"

MIN_HEIGHT = 3.5
MIN_DISTANCE = 10

try:df = pd.read_csv(file_path, header=None, names=["Time", "Voltage"])
except FileNotFoundError:
	print("エラー")
    exit()

times = df["Time"].values
voltages = df["Voltage"].values

peak_indices, _ = find_peaks(
    voltages, height=MIN_HEIGHT, distance=MIN_DISTANCE
)

print("【実験2 ピーク検出結果】")
print(f"ファイル名: {file_path}")
print("-" * 35)
print(f"{'波形番号':<6}\t{'時刻[秒]':<10}\t{'電位[V]'}")
print("-" * 35)

for i, idx in enumerate(peak_indices, start=1):
    peak_time = times[idx]
    peak_voltage = voltages[idx]
    print(f"{i:<8}\t{peak_time:<12.2f}\t{peak_voltage:.2f}")

print("-" * 35)
print(f"合計検出数: {len(peak_indices)} 回")

plt.figure(figsize=(10, 5))
plt.plot(times, voltages, label="Measured Signal", color="blue")
plt.plot(
    times[peak_indices],
    voltages[peak_indices],
    "x",
    label="Detected Peaks",
    color="red",
    markersize=10,
)

plt.title(f"Peak Detection Result ({file_path})")
plt.xlabel("Time [seconds]")
plt.ylabel("Voltage [V]")
plt.grid(True)
plt.legend()
plt.ylim(0, 5)
plt.show()