"""
概要:
    ガウス過程回帰を用いた能動学習のアニメーションを生成するスクリプトです。
詳細説明:
    設定された探索モードに従ってデータ点を追加し、ガウス過程の予測平均と分散の推移をアニメーション化します。
    コマンドライン引数で探索モードや反復回数などを指定できます。
"""
import sys
import numpy as np
from scipy.stats import norm

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import PillowWriter
#from matplotlib.animation import FuncAnimation, FFMpegWriter


# mode = "random" / "std" / "max" / "ucb" / "ei" / "target" / "target_ucb" / "target_sq"
# target    : GP を元の y に対して作り、P(v0-eps < y < v0+eps) を最大化する。
# target_ucb: -abs(mu-v0) + kappa*std を最大化し、目標値探索に探索性を加える。
# target_sq : score = -(y-v0)^2 を GP で直接近似し、UCB を最大化する。
#mode = "random"
#mode = "std"
#mode = "max"
mode = "ucb"

outfile = ""
#outfile = "gp_std_mode.gif"
nmaxiter = 20
v0 = 0.30
eps_target = 0.10
kappa = 2.0

argv = sys.argv
nargs = len(argv)
if nargs >= 2: mode = argv[1]
if nargs >= 3: nmaxiter = int(argv[2])
if nargs >= 4: outfile = argv[3]
if nargs >= 5: v0 = float(argv[4])
if nargs >= 6: eps_target = float(argv[5])


plt.rcParams['font.family'] = 'MS Gothic'
plt.rcParams['axes.unicode_minus'] = False

# ==== 真の関数 ====
def f_true(x):
    """
    概要:
        真の関数値を計算します。
    詳細説明:
        入力xに対して正弦波と余弦波の和を計算して返します。
    引数:
        :param x: 入力値。
        :type x: float または numpy.ndarray
    戻り値:
        :returns: 真の関数値。
        :rtype: float または numpy.ndarray
    """
    return np.sin(2 * np.pi * x) + 0.3 * np.cos(4 * np.pi * x)

def target_square_score(y, v0):
    """
    概要:
        目標値との二乗誤差に基づくスコアを計算します。
    詳細説明:
        目標値に近いほど0に近づき、遠いほど負の大きな値になります。
    引数:
        :param y: 観測値。
        :type y: float または numpy.ndarray
        :param v0: 目標値。
        :type v0: float
    戻り値:
        :returns: 目標値v0からの負の二乗誤差。
        :rtype: float または numpy.ndarray
    """
    """目標値に近いほど大きい（最大値 0）スコア。"""
    return -(y - v0) ** 2

# ==== RBFカーネル ====
def rbf_kernel(x1, x2, length_scale=0.2, sigma_f=1.0):
    """
    概要:
        RBFカーネル行列を計算します。
    詳細説明:
        2つの入力データ群に対して、指定されたlength_scaleとsigma_fを用いてカーネル行列を生成します。
    引数:
        :param x1: 第1の入力データ配列。
        :type x1: numpy.ndarray
        :param x2: 第2の入力データ配列。
        :type x2: numpy.ndarray
        :param length_scale: カーネルの長さスケールパラメータ。
        :type length_scale: float
        :param sigma_f: カーネルの信号分散パラメータ。
        :type sigma_f: float
    戻り値:
        :returns: 計算されたカーネル行列。
        :rtype: numpy.ndarray
    """
    x1 = np.atleast_2d(x1).T
    x2 = np.atleast_2d(x2).T
    d2 = (x1 - x2.T) ** 2
    return sigma_f**2 * np.exp(-0.5 * d2 / length_scale**2)

# ==== ガウス過程回帰 ====
def gp_posterior(x_train, y_train, x_test, noise_sigma,
                 length_scale=0.2, sigma_f=1.0):
    """
    概要:
        ガウス過程回帰の事後分布を計算します。
    詳細説明:
        訓練データを用いてテストデータに対する予測平均と予測分散を計算します。
    引数:
        :param x_train: 訓練データの入力。
        :type x_train: numpy.ndarray
        :param y_train: 訓練データの出力。
        :type y_train: numpy.ndarray
        :param x_test: テストデータの入力。
        :type x_test: numpy.ndarray
        :param noise_sigma: 観測ノイズの標準偏差。
        :type noise_sigma: float
        :param length_scale: RBFカーネルの長さスケール。
        :type length_scale: float
        :param sigma_f: RBFカーネルの信号分散。
        :type sigma_f: float
    戻り値:
        :returns: 予測平均配列と予測分散配列のタプル。
        :rtype: tuple
    """

    K = rbf_kernel(x_train, x_train, length_scale, sigma_f)
    K_s = rbf_kernel(x_train, x_test, length_scale, sigma_f)
    K_ss = rbf_kernel(x_test, x_test, length_scale, sigma_f)

    K_y = K + (noise_sigma**2) * np.eye(len(x_train))

    L = np.linalg.cholesky(K_y)
    alpha = np.linalg.solve(L.T, np.linalg.solve(L, y_train))

    mu = K_s.T @ alpha

    v = np.linalg.solve(L, K_s)
    cov = K_ss - v.T @ v
    var = np.clip(np.diag(cov), 0, np.inf)

    return mu, var

# ==== 既存点に近すぎる場合のオフセット ====
def avoid_duplicate(x_new, x_train, eps=1e-3):
    """
    概要:
        新しい入力点が既存の点に近すぎる場合にオフセットを加えます。
    詳細説明:
        既存の訓練データとの距離がeps未満の場合、ランダムな微小な値を加算し範囲を0から1にクリップします。
    引数:
        :param x_new: 新たに提案された入力点。
        :type x_new: float
        :param x_train: 既存の訓練データの配列。
        :type x_train: numpy.ndarray
        :param eps: 重複と判定する距離の閾値。
        :type eps: float
    戻り値:
        :returns: オフセット調整された新しい入力点。
        :rtype: float
    """
    if len(x_train) == 0:
        return x_new
    while np.min(np.abs(x_train - x_new)) < eps:
        x_new += np.random.uniform(-0.01, 0.01)
        x_new = np.clip(x_new, 0.0, 1.0)
    return x_new

# ==== メイン ====
def main(mode="random", nmaxiter=40, savefile="gp_animation.mp4",
         v0=0.30, eps_target=0.10):
    """
    概要:
        ガウス過程回帰のアニメーションを生成および実行します。
    詳細説明:
        指定された探索モードで新しいデータ点を逐次追加し、結果をプロットします。
    引数:
        :param mode: 探索モード。random, std, max, ucb, ei, target, target_ucb, target_sq のいずれかを指定します。
        :type mode: str
        :param nmaxiter: アニメーションの最大反復回数。
        :type nmaxiter: int
        :param savefile: 保存するアニメーションファイルのパス。空文字列の場合は保存しません。
        :type savefile: str
        :param v0: 探索の目標値。
        :type v0: float
        :param eps_target: 目標値の許容誤差。
        :type eps_target: float
    戻り値:
        :returns: なし。
        :rtype: None
    例外:
        :raises ValueError: 無効なモード文字列が指定された場合に発生します。
    """
    rng = np.random.default_rng(1)

    x_data = []
    y_data = []             # 実際に観測した元の y
    model_data = []         # GP に学習させる量（通常は y、target_sq では score）
    noise_sigma = 0.15

    x_plot = np.linspace(0, 1, 200)
    y_true = f_true(x_plot)
    score_mode = (mode == "target_sq")
    y_display_true = target_square_score(y_true, v0) if score_mode else y_true

    fig, ax = plt.subplots(figsize=(8, 5))
    ax.set_xlabel("x")
    ax.set_ylabel("score = -(y-v0)^2" if score_mode else "y")

    true_label = "真の score" if score_mode else "真の関数 f(x)"
    ax.plot(x_plot, y_display_true, "k--", label=true_label)
    scatter = ax.scatter([], [], color="black", label="観測データ")
    mean_line, = ax.plot([], [], color="C0", label="GP 予測平均")

    uncert_band = None

    ax.legend(loc="upper right")
    ax.set_xlim(0, 1)
    if score_mode:
        ax.set_ylim(-3.0, 0.4)
    else:
        ax.set_ylim(-2.0, 2.0)
        if mode in ("target", "target_ucb"):
            ax.axhspan(v0 - eps_target, v0 + eps_target,
                       color="C2", alpha=0.12, label="目標範囲")
            ax.axhline(v0, color="C2", ls=":", lw=1)
            ax.legend(loc="upper right")

    # ---- アニメーション更新 ----
    def update(frame):
        """
        概要:
            アニメーションの各フレームの状態を更新します。
        詳細説明:
            新しい入力点を選択して観測を行い、ガウス過程のモデルを更新した上で描画データを再設定します。
        引数:
            :param frame: アニメーションのフレーム番号。
            :type frame: int
        戻り値:
            :returns: 更新された描画オブジェクトのタプル。
            :rtype: tuple
        """
        nonlocal uncert_band, x_data, y_data, model_data

        # 最初の1点はランダム
        if len(x_data) == 0:
            x_new = rng.uniform(0, 1)
        else:
            x_train = np.array(x_data)
            y_train = np.array(model_data)
            mu, var = gp_posterior(x_train, y_train, x_plot, noise_sigma)
            std = np.sqrt(var)

            if mode == "random":
                x_new = rng.uniform(0, 1)

            elif mode == "std":
                idx = np.argmax(std)
                x_new = x_plot[idx]

            elif mode == "max":
                idx = np.argmax(mu)
                x_new = x_plot[idx]

            elif mode == "ucb":
                ucb = mu + kappa * std
                idx = np.argmax(ucb)
                x_new = x_plot[idx]

            elif mode == "ei":
                y_best = np.max(y_train)
                improvement = mu - y_best
                Z = improvement / (std + 1e-9)
                ei = improvement * norm.cdf(Z) + std * norm.pdf(Z)
                ei[std < 1e-12] = 0.0
                idx = np.argmax(ei)
                x_new = x_plot[idx]

            elif mode == "target":
                # 次の「観測値」が許容範囲に入る確率。
                # var は潜在関数の予測分散なので、観測ノイズも加える。
                sigma_pred = np.sqrt(var + noise_sigma**2)
                p_target = (
                    norm.cdf((v0 + eps_target - mu) / sigma_pred)
                    - norm.cdf((v0 - eps_target - mu) / sigma_pred)
                )
                idx = np.argmax(p_target)
                x_new = x_plot[idx]

            elif mode == "target_ucb":
                # 目標値への近さ（exploit）と、未測定領域の
                # 不確かさ（explore）を同じ y の単位で加える。
                target_ucb = -np.abs(mu - v0) + kappa * std
                idx = np.argmax(target_ucb)
                x_new = x_plot[idx]

            elif mode == "target_sq":
                # score = -(y-v0)^2 を直接 GP 化する比較用の方法。
                # スコアを最大化する UCB を使う。
                score_ucb = mu + kappa * std
                idx = np.argmax(score_ucb)
                x_new = x_plot[idx]

            else:
                raise ValueError(
                    "mode must be random, std, max, ucb, ei, "
                    "target, target_ucb, or target_sq"
                )

        # 既存点と近すぎる場合はオフセット
        x_new = avoid_duplicate(x_new, np.array(x_data))

        # 新しい観測値
        y_new = f_true(x_new) + rng.normal(0.0, noise_sigma)

        x_data.append(x_new)
        y_data.append(y_new)
        model_data.append(target_square_score(y_new, v0) if score_mode else y_new)

        # ---- GP posterior 再計算 ----
        x_train = np.array(x_data)
        y_train = np.array(model_data)
        mu, var = gp_posterior(x_train, y_train, x_plot, noise_sigma)
        std = np.sqrt(var)

        scatter.set_offsets(np.column_stack([x_train, y_train]))
        mean_line.set_data(x_plot, mu)

        if uncert_band is not None:
            uncert_band.remove()

        uncert_band = ax.fill_between(
            x_plot,
            mu - 2 * std,
            mu + 2 * std,
            color="C0",
            alpha=0.2
        )

        ax.set_title(
            f"mode={mode} | v0={v0:g}, eps={eps_target:g} | "
            f"データ数 n = {len(x_train)}"
        )
        return scatter, mean_line, uncert_band

    # ---- アニメーション作成 ----
    anim = FuncAnimation(
        fig,
        update,
        frames=nmaxiter,
        interval=500,
        blit=False,
        repeat=False
    )

    # ---- 動画保存 ----
    if savefile is None or savefile == "":
        pass
    else:
    # GIF で保存
        writer = PillowWriter(fps=2)
        anim.save(savefile, writer=writer)
# mp4に保存
#        writer = FFMpegWriter(fps=2)
#        anim.save(savefile, writer=writer)
        print(f"Saved animation to {savefile}")

    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    main(mode=mode, nmaxiter=nmaxiter, savefile=outfile,
         v0=v0, eps_target=eps_target)