"""Original beginner signal-classification experiments. All data are synthetic.

Run: python signal_types_lab.py --out reproduced
No network, device access, or measured/private data are used.
"""
from pathlib import Path
import argparse
import hashlib
import json
import platform

import numpy as np
import scipy
from scipy import signal
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager


SEED = 20261027
BLUE, ORANGE, GREEN, RED = "#2463a6", "#c56a1b", "#16826c", "#b7474a"


def configure():
    available = {f.name for f in font_manager.fontManager.ttflist}
    fonts = [f for f in ("Microsoft YaHei", "Noto Sans CJK SC", "SimHei", "DejaVu Sans") if f in available]
    plt.rcParams.update({"font.family": fonts, "font.size": 11,
                         "axes.unicode_minus": False, "figure.dpi": 120,
                         "axes.spines.top": False, "axes.spines.right": False,
                         "axes.grid": True, "grid.alpha": .2,
                         "savefig.facecolor": "white"})


def save(fig, out, name):
    fig.savefig(out / name, dpi=150, bbox_inches="tight")
    plt.close(fig)


def amplitude(x, fs, window="hann", nfft=None):
    """One-sided peak amplitude; exact tone amplitude only under stated conditions."""
    w = signal.get_window(window, len(x), fftbins=True)
    y = np.abs(np.fft.rfft(x * w, n=nfft)) / w.sum()
    if (nfft or len(x)) % 2 == 0:
        y[1:-1] *= 2
    else:
        y[1:] *= 2
    return np.fft.rfftfreq(nfft or len(x), 1 / fs), y


def psd(x, fs, segment=1024):
    return signal.welch(x, fs=fs, window="hann", nperseg=segment,
                        noverlap=segment // 2, detrend="constant", scaling="density")


def rms(x):
    return float(np.sqrt(np.mean(np.square(x))))


def save_csv(file, columns, header):
    with file.open("w", encoding="utf-8", newline="\n") as handle:
        np.savetxt(handle, np.column_stack(columns), delimiter=",", header=header,
                   comments="", fmt="%.10g")


def run(out):
    out.mkdir(parents=True, exist_ok=True)
    configure()
    metrics = {"seed": SEED, "data": "synthetic; amplitude unit a.u.",
               "environment": {"python": platform.python_version(), "numpy": np.__version__,
                               "scipy": scipy.__version__, "matplotlib": matplotlib.__version__}}

    fs = 2048
    t = np.arange(fs * 4) / fs
    sine = 1 + 2 * np.sin(2 * np.pi * 5 * t)
    fig, ax = plt.subplots(2, 1, figsize=(11, 6), constrained_layout=True)
    mask = t < .65
    ax[0].plot(t[mask], sine[mask], color=BLUE)
    ax[0].axhline(1, color=GREEN, ls="--", label="均值 b = 1")
    ax[0].annotate("", xy=(.05, 3.4), xytext=(.25, 3.4),
                   arrowprops={"arrowstyle": "<->"})
    ax[0].text(.15, 3.52, "周期 T₀ = 0.2 s", ha="center")
    ax[0].annotate("", xy=(.05, 1), xytext=(.05, 3),
                   arrowprops={"arrowstyle": "<->"})
    ax[0].text(.065, 2.05, "峰值振幅 A = 2", ha="left")
    ax[0].set(xlabel="时间 t / s", ylabel="x / a.u.", ylim=(-1.5, 4),
              title="① 正弦的参数：b + A sin(2πft + φ)")
    ax[0].legend(loc="upper right")
    ax[1].plot(t[mask], 2*np.sin(2*np.pi*5*t[mask]), label="φ = 0°", color=BLUE)
    ax[1].plot(t[mask], 2*np.sin(2*np.pi*5*t[mask]+np.pi/2),
               label="φ = +90°：相同参考下提前 0.05 s", color=ORANGE)
    ax[1].set(xlabel="时间 / s", ylabel="x / a.u.", title="相位改变时间位置；振幅与频率保持相同")
    ax[1].legend(loc="upper right")
    save(fig, out, "01-sine-parameters.png")
    metrics["sine"] = {"mean": float(sine.mean()), "rms_total": rms(sine),
                        "rms_ac": rms(sine-sine.mean()), "pp": float(np.ptp(sine)),
                        "period_s": .2}
    assert np.isclose(rms(sine), np.sqrt(3), atol=1e-12)

    tone = np.sin(2*np.pi*5*t)
    complex_periodic = tone + .5*np.sin(2*np.pi*10*t) + .25*np.sin(2*np.pi*15*t)
    quasi = tone + .6*np.sin(2*np.pi*5*np.sqrt(2)*t)
    dt = t - .5
    transient = np.where(dt >= 0, np.exp(-5*np.maximum(dt, 0))*np.sin(2*np.pi*35*dt), 0)
    cases = [("简谐：5 Hz", tone), ("复杂周期：5、10、15 Hz", complex_periodic),
             ("准周期：5、5√2 Hz；连续时间模型", quasi), ("瞬变：0.5 s 后衰减振铃", transient)]
    fig, ax = plt.subplots(4, 2, figsize=(12, 11), constrained_layout=True)
    for row, (label, x) in enumerate(cases):
        ax[row, 0].plot(t, x, lw=.8, color=BLUE)
        ax[row, 0].set(xlim=(0, 1.2), ylabel="x / a.u.", title=label)
        if row < 3:
            f, a = amplitude(x, fs)
            ax[row, 1].plot(f, a, color=ORANGE)
            ax[row, 1].set(xlim=(0, 45), ylabel="峰值幅度 / a.u.", title="有限记录 + Hann 窗的幅度谱")
        else:
            energy_density = np.abs(np.fft.rfft(x) / fs)**2
            energy_density[1:-1] *= 2
            ax[row, 1].plot(np.fft.rfftfreq(len(x), 1/fs), energy_density, color=ORANGE)
            ax[row, 1].set(xlim=(0, 70), ylabel="能量谱密度 / a.u.²·s²", title="瞬变：有限记录的一侧能量谱密度")
        ax[row, 0].set_xlabel("时间 / s")
        ax[row, 1].set_xlabel("频率 / Hz")
    save(fig, out, "02-deterministic-gallery.png")
    metrics["periodic_rms"] = {"measured": rms(complex_periodic), "theory": float(np.sqrt((1+.5**2+.25**2)/2))}
    assert np.isclose(rms(complex_periodic), metrics["periodic_rms"]["theory"], atol=1e-12)

    fsn = 2048
    tn = np.arange(fsn*8)/fsn
    rng = np.random.default_rng(SEED)
    broad = rng.normal(size=len(tn))
    # Warm up and trim the filter, so finite-record startup is not mistaken for stationarity.
    padded = rng.normal(size=len(tn)+fsn*4)
    sos = signal.butter(4, [190, 210], btype="bandpass", fs=fsn, output="sos")
    narrow = signal.sosfilt(sos, padded)[fsn*4:]
    narrow /= narrow.std()
    nonstationary = (.3+2.7*tn/tn[-1])*rng.normal(size=len(tn))
    fig, ax = plt.subplots(3, 2, figsize=(12, 8.5), constrained_layout=True)
    for row, (label, x) in enumerate([("宽带随机：独立高斯序列", broad),
                                      ("窄带随机：190–210 Hz 带通后的噪声", narrow),
                                      ("非平稳随机：噪声标准差随时间增大", nonstationary)]):
        mask = tn < (.12 if row < 2 else 8)
        ax[row, 0].plot(tn[mask], x[mask], color=BLUE, lw=.8)
        ax[row, 0].set(title=label, xlabel="时间 / s", ylabel="x / a.u.")
        f, p = psd(x, fsn, 2048)
        ax[row, 1].plot(f, 10*np.log10(np.maximum(p, 1e-16)), color=ORANGE)
        ax[row, 1].set(xlim=(0, 1024), ylim=(-130, 0), xlabel="频率 / Hz",
                      ylabel="PSD / dB re 1 a.u.²/Hz",
                      title="Welch PSD" if row < 2 else "整段 PSD 混合了不同时段的强弱")
    save(fig, out, "03-random-gallery.png")
    fig, ax = plt.subplots(2, 1, figsize=(11, 6), constrained_layout=True)
    window = fsn//2
    bt = tn[:len(tn)//window*window].reshape(-1, window)
    for label, x, color in [("宽带平稳模型", broad, BLUE), ("方差增长模型", nonstationary, ORANGE)]:
        blocks = x[:len(bt)*window].reshape(-1, window)
        ax[0].plot(bt.mean(axis=1), blocks.mean(axis=1), "o-", color=color, label=label)
        ax[1].plot(bt.mean(axis=1), blocks.std(axis=1), "o-", color=color, label=label)
    ax[0].set(title="④ 分块均值：波动接近零不能单独证明平稳", ylabel="分块均值 / a.u.")
    ax[1].set(title="分块标准差揭示强弱变化；每块 0.5 s", xlabel="时间 / s", ylabel="分块标准差 / a.u.")
    for a in ax: a.legend()
    save(fig, out, "04-stationarity-blocks.png")
    metrics["random_blocks"] = {"stationary_std": broad.reshape(-1,window).std(axis=1).tolist(),
                                 "growing_std": nonstationary.reshape(-1,window).std(axis=1).tolist()}

    rng_e = np.random.default_rng(SEED+1)
    count = 12000
    k = np.arange(1, count+1)
    independent = rng_e.normal(size=(4, count))
    # Each offset is drawn once per realization from {-2, 2}; stays fixed for all n.
    offsets = np.random.default_rng(SEED+4).choice([-2., 2.], size=4)
    shifted = independent+offsets[:,None]
    fig, ax = plt.subplots(2, 2, figsize=(12, 7), constrained_layout=True)
    for col, (label, data) in enumerate([("各态历经示例：IID 零均值噪声", independent),
                                         ("非均值各态历经：随机固定偏置 + 噪声", shifted)]):
        for j, record in enumerate(data):
            ax[0,col].plot(k[:120], record[:120], lw=.8, label=f"记录 {j+1}" + (f"，C={offsets[j]:+.0f}" if col else ""))
            ax[1,col].plot(k, np.cumsum(record)/k, lw=1)
        ax[0,col].set(title=label, xlabel="样本序号", ylabel="x / a.u.")
        ax[0,col].legend(fontsize=9)
        ax[1,col].axhline(0, color="black", ls="--", label="总体均值 E[X] = 0")
        ax[1,col].set(xlabel="已累计样本数", ylabel="累计时间均值 / a.u.", ylim=(-3,3))
        ax[1,col].legend()
    save(fig, out, "05-ergodicity.png")
    metrics["ergodicity"] = {"offsets": offsets.tolist(), "iid_record_means": independent.mean(axis=1).tolist(),
                             "offset_record_means": shifted.mean(axis=1).tolist()}

    fsc = 2048
    tc = np.arange(fsc*4)/fsc
    chirp = signal.chirp(tc, f0=40, f1=300, t1=4, method="linear")
    fig, ax = plt.subplots(1, 2, figsize=(12, 4.8), constrained_layout=True)
    for a, length in zip(ax, [128, 512]):
        st = signal.ShortTimeFFT.from_window("hann", fsc, length, length*3//4,
                                             fft_mode="onesided2X", scale_to="psd")
        z = st.stft(chirp)
        p = np.abs(z)**2
        times = st.t(len(chirp))
        im = a.pcolormesh(times, st.f, 10*np.log10(np.maximum(p,1e-12)),
                          vmin=-70, vmax=-10, cmap="viridis", shading="auto", rasterized=True)
        a.plot(tc, 40+65*tc, "w--", lw=1, label="真实瞬时频率 40 + 65t")
        a.set(xlim=(.3,3.7), ylim=(0,400), xlabel="时间 / s", ylabel="频率 / Hz",
              title=f"窗 {length} 点 / {length/fsc:.4f} s；频率格 {fsc/length:g} Hz")
        a.legend(fontsize=9)
    fig.colorbar(im, ax=ax, label="局部 PSD / dB re 1 a.u.²/Hz", shrink=.85)
    save(fig, out, "06-time-frequency.png")
    metrics["chirp"] = {"f_start_hz":40, "f_end_hz":300, "duration_s":4, "slope_hz_per_s":65}

    fsl = 1024
    short_t = np.arange(fsl)/fsl
    long_t = np.arange(fsl*8)/fsl
    fig, ax = plt.subplots(3, 1, figsize=(11, 9), constrained_layout=True)
    for window_name, color in [("boxcar", ORANGE), ("hann", BLUE)]:
        f,a = amplitude(np.sin(2*np.pi*50.35*short_t), fsl, window_name, 8192)
        ax[0].plot(f,a,color=color,label=window_name)
    ax[0].set(xlim=(40,60), title="① 50.35 Hz 单音：Hann 降低远处旁瓣，但主瓣更宽", ylabel="峰值幅度 / a.u.")
    pair_s = np.sin(2*np.pi*50*short_t)+np.sin(2*np.pi*50.75*short_t)
    for nfft,label,color in [(1024,"1 s：原始 FFT 格点 1 Hz",ORANGE),(16384,"1 s：补零后格点 0.0625 Hz",BLUE)]:
        f,a=amplitude(pair_s,fsl,"hann",nfft)
        ax[1].plot(f,a,".-" if nfft==1024 else "-",color=color,label=label)
    ax[1].set(xlim=(47,54), title="② 补零让同一条谱曲线更密；两个近邻成分仍混在一起", ylabel="峰值幅度 / a.u.")
    pair_l=np.sin(2*np.pi*50*long_t)+np.sin(2*np.pi*50.75*long_t)
    f,a=amplitude(pair_l,fsl,"hann",65536)
    ax[2].plot(f,a,color=GREEN,label="8 s：真实格点间距 0.125 Hz")
    ax[2].set(xlim=(47,54), title="③ 延长实际记录：50 和 50.75 Hz 分开", ylabel="峰值幅度 / a.u.")
    for a in ax: a.set_xlabel("频率 / Hz"); a.legend(fontsize=9)
    save(fig,out,"07-window-and-resolution.png")

    fig, ax = plt.subplots(2, 1, figsize=(11,6), constrained_layout=True)
    for x,label,color in [(broad,"宽带：相关迅速消失",BLUE),(narrow,"窄带：振荡相关延续多个周期",ORANGE)]:
        centered=x-x.mean()
        corr=signal.correlate(centered,centered,mode="full",method="fft")[len(x)-1:]
        corr=corr/corr[0]  # Biased finite-record normalized estimator, display only.
        ax[0].plot(np.arange(300)/fsn,corr[:300],color=color,label=label)
    ax[0].set(xlabel="延迟 τ / s", ylabel="归一化自相关", title="⑧ 自相关：把信号与延迟后的自己比较")
    ax[0].legend()
    psdf,psdp=psd(broad,fsn,2048)
    ax[1].plot(psdf,psdp,color=BLUE)
    band=(psdf>=100)&(psdf<=400)
    ax[1].fill_between(psdf[band],psdp[band],color=GREEN,alpha=.35,label="100–400 Hz：PSD 曲线下面积是带内均方")
    ax[1].set(xlabel="频率 / Hz",ylabel="PSD / a.u.²/Hz",title="密度的高度不是 RMS；先对频率积分，再开方")
    ax[1].legend(fontsize=10)
    save(fig,out,"08-correlation-and-psd.png")
    full_ms=float(np.sum(psdp)*(psdf[1]-psdf[0]))
    band_rms=float(np.sqrt(np.sum(psdp[band])*(psdf[1]-psdf[0])))
    metrics["psd"]={"time_variance":float(np.var(broad)),"welch_integrated_mean_square":full_ms,
                     "relative_difference":abs(full_ms-np.var(broad))/np.var(broad),
                     "band_100_400_rms":band_rms,"df_hz":float(psdf[1]-psdf[0])}
    assert metrics["psd"]["relative_difference"] < .04

    r = np.random.default_rng(SEED+2)
    tf = np.arange(fsn*4)/fsn
    clean=np.sin(2*np.pi*50*tf)
    measured=clean+.65*np.sin(2*np.pi*400*tf)+.3*r.normal(size=len(tf))
    bp=signal.butter(4,[40,60],btype="bandpass",fs=fsn,output="sos")
    filtered=signal.sosfiltfilt(bp,measured)
    interior=(tf>=.5)&(tf<3.5)
    metrics["filter"]={"before_rmse":rms(measured[interior]-clean[interior]),
                        "after_rmse":rms(filtered[interior]-clean[interior]),
                        "evaluation_interval_s":[.5,3.5],"passband_hz":[40,60]}
    assert metrics["filter"]["after_rmse"] < metrics["filter"]["before_rmse"]*.5
    fig,ax=plt.subplots(2,1,figsize=(11,6),constrained_layout=True)
    view=(tf>=1)&(tf<1.18)
    ax[0].plot(tf[view],measured[view],color="#8897aa",label="观测：50 Hz + 400 Hz + 随机噪声",lw=.8)
    ax[0].plot(tf[view],clean[view],color=ORANGE,label="已知仿真真值",lw=1.2)
    ax[0].plot(tf[view],filtered[view],color=BLUE,label="40–60 Hz 离线带通",lw=1.4)
    ax[0].set(xlabel="时间 / s",ylabel="x / a.u.",title="⑨ 滤波只保留目标频带；带内噪声仍然存在")
    ax[0].legend(fontsize=9,loc="upper right")
    for x,label,color in [(measured,"处理前",ORANGE),(filtered,"处理后",BLUE)]:
        f,a=amplitude(x,fsn)
        ax[1].semilogy(f,np.maximum(a,1e-8),color=color,label=label)
    ax[1].set(xlim=(0,500),ylim=(1e-5,2),xlabel="频率 / Hz",ylabel="峰值幅度 / a.u.",title="双向滤波是离线方法；端点过渡区单独剔除后评价")
    ax[1].legend()
    save(fig,out,"09-filter-example.png")

    fsa=12000
    ta=np.arange(fsa*2)/fsa
    ring=np.zeros_like(ta)
    for start in np.arange(.1,1.9,.1):
        d=ta-start
        valid=(d>=0)&(d<.08)
        ring[valid]+=np.exp(-90*d[valid])*np.sin(2*np.pi*2000*d[valid])
    ra=np.random.default_rng(SEED+3)
    observed=ring+.07*ra.normal(size=len(ta))
    bandpass=signal.butter(4,[1600,2400],btype="bandpass",fs=fsa,output="sos")
    carrier=signal.sosfiltfilt(bandpass,observed)
    envelope=np.abs(signal.hilbert(carrier))
    inner=(ta>=.25)&(ta<1.75)
    ef,ea=amplitude(envelope[inner]-envelope[inner].mean(),fsa)
    positive=(ef>=5)&(ef<=30)
    peak=float(ef[positive][np.argmax(ea[positive])])
    assert abs(peak-10)<.7
    fig,ax=plt.subplots(3,1,figsize=(11,8),constrained_layout=True)
    v=(ta>=.4)&(ta<.7)
    ax[0].plot(ta[v],observed[v],color=BLUE,lw=.8)
    ax[0].set(title="⑩ 重复冲击：每 0.1 s 激发一次约 2000 Hz 的振铃",ylabel="观测 / a.u.")
    ax[1].plot(ta[v],carrier[v],color="#9caec4",lw=.6)
    ax[1].plot(ta[v],envelope[v],color=ORANGE,label="带通后 Hilbert 包络")
    ax[1].set(ylabel="带通信号 / a.u.");ax[1].legend()
    for a in ax[:2]: a.set_xlabel("时间 / s")
    ax[2].plot(ef,ea,color=GREEN)
    ax[2].set(xlim=(0,60),xlabel="包络的频率 / Hz",ylabel="包络峰值幅度 / a.u.",title="包络谱约 10 Hz 的间隔：冲击重复率；不等于载波频率")
    save(fig,out,"10-envelope-example.png")
    metrics["envelope"]={"carrier_hz":2000,"repetition_hz":10,"estimated_repetition_hz":peak}

    # Compact raw and processed data make the three processing examples reproducible.
    save_csv(out/"deterministic.csv",[t,tone,complex_periodic,quasi,transient],
             "time_s,sine,complex_periodic,quasi,transient")
    save_csv(out/"random.csv",[tn,broad,narrow,nonstationary],
             "time_s,broad,narrow,growing_variance")
    save_csv(out/"filter.csv",[tf,measured,filtered,clean],
             "time_s,measured,filtered,simulation_truth")
    save_csv(out/"chirp.csv",[tc,chirp,40+65*tc],
             "time_s,chirp,instantaneous_frequency_hz")
    save_csv(out/"envelope.csv",[ta,observed,carrier,envelope],
             "time_s,observed,bandpassed,envelope")
    (out/"metrics.json").write_text(json.dumps(metrics,indent=2,ensure_ascii=False)+"\n",encoding="utf-8",newline="\n")
    sums=[]
    for p in sorted(out.iterdir()):
        if p.is_file() and p.name!="SHA256SUMS.txt":
            sums.append(f"{hashlib.sha256(p.read_bytes()).hexdigest()}  {p.name}")
    (out/"SHA256SUMS.txt").write_text("\n".join(sums)+"\n",encoding="utf-8",newline="\n")
    print(json.dumps(metrics,ensure_ascii=False,indent=2))


if __name__=="__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out",type=Path,default=Path("results"))
    run(parser.parse_args().out)
