#!/usr/bin/env python3
import argparse
import numpy as np
import matplotlib.pyplot as plt

# 光速
c = 3.0e8

# フォントをMS Gothicに
plt.rcParams["font.family"] = "MS Gothic"

def lorentz_transform(t, x, v):
    """ローレンツ変換: S(t,x) → S1(t1,x1)"""
    gamma = 1.0 / np.sqrt(1 - (v/c)**2)
    t1 = gamma * (t - v*x/c**2)
    x1 = gamma * (x - v*t)
    return t1, x1

def main():
    parser = argparse.ArgumentParser(
        description="1次元特殊相対性理論のローレンツ変換を時空図で描画"
    )
    parser.add_argument("v_ratio", type=float, help="相対速度 v/c (例: 0.8)")
    parser.add_argument("dt", type=float, help="観測する経過時間 dt [s]")
    args = parser.parse_args()

    v = args.v_ratio * c   # v を光速比から実数値に変換
    dt = args.dt

    gamma = 1.0 / np.sqrt(1 - (v/c)**2)

    # 時間の範囲
    t = np.linspace(0, dt, 200)

    # S系の原点ワールドライン (x=0)
    x_origin = np.zeros_like(t)

    # S1系の原点ワールドライン (x=vt)
    x_moving = v * t

    # dt における点
    t_end, x_end = dt, v*dt
    t1_end, x1_end = lorentz_transform(t_end, x_end, v)

    # 軸描画用
    x_range = np.linspace(-c*dt, c*dt, 200)

    # x1軸 (t1=0 → t = v x / c²)
    t_x1 = (v/c**2) * x_range
    ct_x1 = c * t_x1

    # ct1軸 (x1=0 → x = v t)
    x_ct1 = v * t
    ct_ct1 = c * t

    # プロット
    fig, ax = plt.subplots()
    ax.set_xlabel("x [m]")
    ax.set_ylabel("ct [m]")
    ax.set_title("ミンコフスキー図 (S系とS1系の軸)")

    # S 系の軸
    ax.axhline(0, color="k", linestyle="--")  # x軸
    ax.axvline(0, color="k", linestyle="--")  # ct軸

    # S 系の原点ワールドライン
    ax.plot(x_origin, c*t, "k-", label="S: 原点 (x=0)")
    # S1 系の原点ワールドライン
    ax.plot(x_moving, c*t, "r-", label="S1: 原点 (x=vt)")

    # S1 系の軸
    ax.plot(x_range, ct_x1, "b--", label="x1軸 (t1=0)")
    ax.plot(x_ct1, ct_ct1, "g--", label="ct1軸 (x1=0)")

    # dt の点をマーカー
    ax.plot(x_end, c*t_end, "ro")
    ax.annotate(f"S1(dt):\n"
                f"t={t_end:.2e} s, x={x_end:.2e} m\n"
                f"t1={t1_end:.2e} s, x1={x1_end:.2e} m",
                xy=(x_end, c*t_end), xytext=(20,20),
                textcoords="offset points", arrowprops=dict(arrowstyle="->"))

    ax.legend()
    ax.grid(True)
    plt.show()

if __name__ == "__main__":
    main()
