"""Four reproducible synthetic DSP experiments. No measured hardware data.

Python 3.12; see requirements.txt. Run:
    python digital_filter_methods.py --out results
The clean_* columns are simulation truth for evaluation, never filter inputs.
"""
from pathlib import Path
import argparse
import hashlib
import json
import platform
import zipfile

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

BLUE, ORANGE, GRAY, TEAL = "#1768AC", "#D05A13", "#73808C", "#087F8C"
plt.rcParams.update({"font.family": ["Microsoft YaHei", "DejaVu Sans"],
    "axes.unicode_minus": False, "font.size": 11, "axes.spines.top": False,
    "axes.spines.right": False, "figure.facecolor": "white", "savefig.dpi": 160})


def snr(clean, estimate):
    return float(10 * np.log10(np.mean(clean**2) / np.mean((estimate-clean)**2)))


def spectrum(x, fs):
    """Hann-window, coherent-gain corrected, one-sided peak amplitude."""
    w = signal.windows.hann(len(x), sym=False)
    a = np.abs(np.fft.rfft((x-x.mean()) * w)) / w.sum()
    a[1:-1] *= 2
    if len(x) % 2:
        a[-1] *= 2
    return np.fft.rfftfreq(len(x), 1/fs), a


def save_csv(out, name, names, *columns):
    np.savetxt(out/name, np.column_stack(columns), delimiter=",",
               header=",".join(names), comments="", fmt="%.12g", encoding="utf-8")


def finish(fig, out, name):
    fig.tight_layout(pad=1.6)
    fig.savefig(out/name, metadata={"Software": "digital_filter_methods.py"})
    plt.close(fig)


def nlms(reference, primary, taps=32, mu=0.12, freeze=None):
    """Causal reference-noise estimator. primary contains desired signal + noise.
    freeze is the first sample whose weights are no longer adapted.
    """
    w, u = np.zeros(taps), np.zeros(taps)
    estimated, error = np.zeros_like(primary), np.zeros_like(primary)
    for n in range(len(primary)):
        u[1:] = u[:-1]
        u[0] = reference[n]
        estimated[n] = w @ u
        error[n] = primary[n] - estimated[n]
        if freeze is None or n < freeze:
            w += mu * error[n] * u / (1e-8 + u @ u)
    return error, estimated, w


def tone_experiment(out):
    rng = np.random.default_rng(2026102601)
    fs, duration, f0, amplitude, phi = 4096, 4, 123, 0.25, np.deg2rad(35)
    t = np.arange(fs*duration)/fs
    clean = amplitude*np.cos(2*np.pi*f0*t+phi)
    disturbance = (1.3*np.cos(2*np.pi*450*t) + 0.8*np.cos(2*np.pi*50*t)
                   + rng.normal(0, 1.3, len(t)))
    raw = clean + disturbance
    bp = signal.butter(4, [118, 128], btype="bandpass", fs=fs, output="sos")
    filtered = signal.sosfiltfilt(bp, raw)
    lp = signal.butter(4, 2, fs=fs, output="sos")
    i = signal.sosfiltfilt(lp, 2*raw*np.cos(2*np.pi*f0*t))
    q = signal.sosfiltfilt(lp, -2*raw*np.sin(2*np.pi*f0*t))
    use = (t >= 0.5) & (t < 3.5)
    i0, q0 = i[use].mean(), q[use].mean()
    measured_a = float(np.hypot(i0, q0))
    measured_phi = float(np.rad2deg(np.arctan2(q0, i0)))
    # A streaming SOS must preserve zi between blocks. Compare to whole causal pass.
    causal = signal.sosfilt(bp, raw)
    zi = np.zeros((len(bp), 2))
    blocks = []
    for start in range(0, len(raw), 257):
        block, zi = signal.sosfilt(bp, raw[start:start+257], zi=zi)
        blocks.append(block)
    block_error = float(np.max(np.abs(np.concatenate(blocks)-causal)))
    m = dict(fs_hz=fs, samples=len(t), seed=2026102601, f0_hz=f0,
        true_peak_amplitude=amplitude, true_phase_deg=35,
        raw_snr_db=snr(clean[use], raw[use]),
        bandpass_snr_db=snr(clean[use], filtered[use]),
        lockin_peak_amplitude=measured_a, lockin_phase_deg=measured_phi,
        amplitude_error_percent=float(100*(measured_a/amplitude-1)),
        phase_error_deg=float((measured_phi-35+180)%360-180),
        evaluation_interval_s=[0.5, 3.5], causal_block_max_abs_error=block_error)
    save_csv(out, "01-tone-raw.csv", ["time_s", "measured", "clean_target", "disturbance"],
             t, raw, clean, disturbance)
    save_csv(out, "01-tone-results.csv", ["time_s", "bandpass", "I", "Q", "peak_amplitude"],
             t, filtered, i, q, np.hypot(i,q))
    fig, ax = plt.subplots(2,2,figsize=(12,7))
    view=(t>=1)&(t<1.12)
    ax[0,0].plot(t[view],raw[view],c=GRAY,lw=0.9,label="原始观测")
    ax[0,0].plot(t[view],clean[view],c=ORANGE,label="目标真值")
    ax[0,0].set(title="原始观测：目标淹没在干扰中",xlabel="时间 / s",ylabel="幅值 / a.u.")
    ax[0,1].plot(t[view],clean[view],c=ORANGE,lw=2,label="目标真值")
    ax[0,1].plot(t[view],filtered[view],c=BLUE,ls="--",label="118–128 Hz 带通")
    ax[0,1].set(title="窄带滤波：保留目标附近波形",xlabel="时间 / s",ylabel="幅值 / a.u.")
    for x,label,color in [(raw,"原始观测",GRAY),(filtered,"带通输出",BLUE)]:
        f,a=spectrum(x[use],fs)
        ax[1,0].semilogy(f,a,c=color,label=label)
    ax[1,0].set(xlim=(0,520),ylim=(1e-5,2),title="同一评价区间的单边幅度谱",xlabel="频率 / Hz",ylabel="峰值幅度 / a.u.")
    ax[1,1].plot(t,np.hypot(i,q),c=BLUE,label="锁相幅值")
    ax[1,1].axhline(amplitude,c=ORANGE,ls="--",label="0.25 真值")
    ax[1,1].axvspan(0,0.5,color=GRAY,alpha=.15)
    ax[1,1].axvspan(3.5,4,color=GRAY,alpha=.15)
    ax[1,1].set(xlim=(0,4),ylim=(0,0.6),title="2 Hz 低通后的 I/Q 幅值；灰区不评分",xlabel="时间 / s",ylabel="峰值幅度 / a.u.")
    for a in ax.flat:a.legend(fontsize=9);a.grid(alpha=.18)
    finish(fig,out,"01-narrowband-lockin.png")
    return m


def matched_experiment(out):
    rng=np.random.default_rng(2026102602)
    fs, size, length, start, sigma, amplitude=4096,8192,512,3072,0.8,0.9
    t=np.arange(size)/fs
    tau=np.arange(length)/fs
    template=signal.chirp(tau,250,tau[-1],650)*signal.windows.hann(length,sym=False)
    clean=np.zeros(size);clean[start:start+length]=amplitude*template
    raw=clean+rng.normal(0,sigma,size)
    energy=float(template@template)
    corr=signal.correlate(raw,template,mode="valid",method="fft")
    score=corr/(sigma*np.sqrt(energy))
    detected=int(np.argmax(np.abs(score)))
    peaks,_=signal.find_peaks(np.abs(score),height=5,distance=length)
    outside=np.abs(peaks-start)>=length
    m=dict(fs_hz=fs,samples=size,seed=2026102602,template_samples=length,
        noise_sigma=sigma,template_energy=energy,true_start_s=start/fs,
        detected_start_s=detected/fs,start_error_samples=detected-start,
        true_amplitude=amplitude,estimated_amplitude=float(corr[detected]/energy),
        true_start_score=float(score[start]),max_abs_score=float(np.abs(score).max()),
        demonstration_threshold=5,false_peaks_in_this_record=int(outside.sum()))
    save_csv(out,"02-pulse-raw.csv",["time_s","measured","clean_target"],t,raw,clean)
    save_csv(out,"02-template.csv",["relative_time_s","template"],tau,template)
    save_csv(out,"02-matched-results.csv",["candidate_start_s","correlation","score","amplitude_estimate"],
             np.arange(len(corr))/fs,corr,score,corr/energy)
    fig,ax=plt.subplots(3,1,figsize=(12,8))
    ax[0].plot(t,raw,c=GRAY,lw=.7,label="原始观测")
    ax[0].plot(t,clean,c=ORANGE,label="埋入的目标真值")
    ax[0].set(title="脉冲检测：原始波形中的 chirp 回波",xlabel="时间 / s",ylabel="幅值 / a.u.")
    ax[1].plot(tau*1000,template,c=BLUE,label="Hann 加窗 chirp 模板")
    ax[1].set(xlabel="模板相对时间 / ms",ylabel="幅值 / a.u.")
    ax[2].plot(np.arange(len(score))/fs,np.abs(score),c=BLUE,label="绝对标准化相关统计量")
    ax[2].axhline(5,c=GRAY,ls=":",label="演示门限 5")
    ax[2].axvline(start/fs,c=ORANGE,ls="--",label=f"真实起点 {start/fs:.3f} s")
    ax[2].set(title="valid 输出横轴是模板起点，免去卷积峰值的 M−1 延迟换算",xlabel="候选起点 / s",ylabel="统计量 / 无量纲")
    for a in ax:a.legend(fontsize=9);a.grid(alpha=.18)
    finish(fig,out,"02-matched-filter.png")
    return m


def envelope_experiment(out):
    rng=np.random.default_rng(2026102603)
    fs,duration,repeat,carrier=12000,4,40,3000
    t=np.arange(fs*duration)/fs
    train=np.zeros(len(t));train[1500::fs//repeat]=1
    tau=np.arange(300)/fs
    ring=.45*np.exp(-tau/.003)*np.sin(2*np.pi*carrier*tau)
    clean=signal.lfilter(ring,[1],train)
    disturbance=.9*np.cos(2*np.pi*30*t)+.65*np.cos(2*np.pi*140*t)+rng.normal(0,.18,len(t))
    raw=clean+disturbance
    sos=signal.butter(4,[2000,4000],btype="bandpass",fs=fs,output="sos")
    bp=signal.sosfiltfilt(sos,raw)
    envelope=np.abs(signal.hilbert(bp))
    use=(t>=.25)&(t<3.75)
    f,a=spectrum(envelope[use],fs)
    region=(f>=20)&(f<=80)
    peak=int(np.flatnonzero(region)[np.argmax(a[region])])
    floor=(f>=5)&(f<=200)
    for h in range(1,6):floor &= np.abs(f-h*repeat)>2
    m=dict(fs_hz=fs,samples=len(t),seed=2026102603,repeat_hz=repeat,
        resonance_hz=carrier,decay_time_s=.003,bandpass_hz=[2000,4000],
        evaluation_interval_s=[.25,3.75],fft_bin_spacing_hz=fs/int(use.sum()),
        search_interval_hz=[20,80],detected_repeat_hz=float(f[peak]),
        envelope_peak_amplitude=float(a[peak]),
        envelope_peak_to_median_db=float(20*np.log10(a[peak]/np.median(a[floor]))))
    save_csv(out,"03-impact-raw.csv",["time_s","measured","clean_ringing","disturbance","impact_train"],
             t,raw,clean,disturbance,train)
    save_csv(out,"03-envelope-results.csv",["time_s","bandpass","envelope"],t,bp,envelope)
    save_csv(out,"03-envelope-spectrum.csv",["frequency_hz","peak_amplitude"],f,a)
    fig,ax=plt.subplots(2,2,figsize=(12,7))
    view=(t>=1)&(t<1.15)
    ax[0,0].plot(t[view],raw[view],c=GRAY,lw=.8,label="原始观测")
    ax[0,0].set(title="重复冲击被低频干扰掩盖",xlabel="时间 / s",ylabel="幅值 / a.u.")
    ax[0,1].plot(t[view],bp[view],c=GRAY,lw=.6,label="2–4 kHz 带通")
    ax[0,1].plot(t[view],envelope[view],c=BLUE,label="Hilbert 包络")
    ax[0,1].set(title="取出共振带，再读振铃强弱",xlabel="时间 / s",ylabel="幅值 / a.u.")
    fr,ar=spectrum(raw[use],fs)
    ax[1,0].plot(fr,ar,c=GRAY,label="原始幅度谱")
    ax[1,0].axvline(repeat,c=ORANGE,ls="--",label="40 Hz 重复频率")
    ax[1,0].set(xlim=(0,200),title="原始低频谱主要显示 30 / 140 Hz 干扰",xlabel="频率 / Hz",ylabel="峰值幅度 / a.u.")
    ax[1,1].plot(f,a,c=BLUE,label="去均值包络幅度谱")
    for h in range(1,5):ax[1,1].axvline(h*repeat,c=ORANGE,ls="--",lw=.8)
    ax[1,1].set(xlim=(0,200),title="包络谱：40 Hz 及其谐波",xlabel="频率 / Hz",ylabel="包络峰值幅度 / a.u.")
    for a0 in ax.flat:a0.legend(fontsize=9);a0.grid(alpha=.18)
    finish(fig,out,"03-envelope-spectrum.png")
    return m


def adaptive_experiment(out):
    rng=np.random.default_rng(2026102604)
    fs,duration=2048,8
    t=np.arange(fs*duration)/fs
    clean=.35*np.cos(2*np.pi*80*t)+.2*np.sin(2*np.pi*135*t)+.12*signal.chirp(t,30,8,180)
    reference=rng.normal(0,1,len(t))+.6*np.sin(2*np.pi*60*t)
    path=np.zeros(14);path[[5,8,13]]=[.8,-.5,.25]
    disturbance=signal.lfilter(path,[1],reference)
    independent=rng.normal(0,.1,len(t))
    primary=clean+disturbance+independent
    freeze=4*fs
    error,estimated,w=nlms(reference,primary,freeze=freeze)
    use=t>=4
    before,after=snr(clean[use],primary[use]),snr(clean[use],error[use])
    m=dict(fs_hz=fs,samples=len(t),seed=2026102604,taps=32,mu=.12,epsilon=1e-8,
        adaptation_interval_s=[0,4],evaluation_interval_s=[4,8],weights_frozen_for_evaluation=True,
        raw_snr_db=before,output_snr_db=after,improvement_db=after-before,
        residual_rmse=float(np.sqrt(np.mean((error[use]-clean[use])**2))),
        independent_noise_sigma=.1,true_path=path.tolist(),estimated_weights=w.tolist())
    save_csv(out,"04-adaptive-raw.csv",["time_s","primary","reference","clean_target","correlated_disturbance","independent_noise"],
             t,primary,reference,clean,disturbance,independent)
    save_csv(out,"04-adaptive-results.csv",["time_s","estimated_disturbance","output"],t,estimated,error)
    fig,ax=plt.subplots(2,2,figsize=(12,7))
    view=(t>=6)&(t<6.12)
    ax[0,0].plot(t[view],primary[view],c=GRAY,label="主通道")
    ax[0,0].plot(t[view],clean[view],c=ORANGE,label="目标真值")
    ax[0,0].set(title="同时采样的参考通道提供干扰线索",xlabel="时间 / s",ylabel="幅值 / a.u.")
    ax[0,1].plot(t[view],clean[view],c=ORANGE,lw=2,label="目标真值")
    ax[0,1].plot(t[view],error[view],c=BLUE,ls="--",label="NLMS 残差输出")
    ax[0,1].set(title="冻结权值后，在后 4 秒独立评价",xlabel="时间 / s",ylabel="幅值 / a.u.")
    for x,label,c in [(primary,"主通道",GRAY),(error,"残差输出",BLUE),(clean,"目标真值",ORANGE)]:
        f,p=signal.welch(x[use],fs,nperseg=1024)
        ax[1,0].semilogy(f,p,c=c,label=label)
    ax[1,0].set(xlim=(0,300),title="Welch PSD：保留目标频带中的有效分量",xlabel="频率 / Hz",ylabel="功率谱密度 / a.u.²/Hz")
    ax[1,1].stem(np.arange(len(path)),path,linefmt=ORANGE,markerfmt="o",basefmt=" ",label="未知路径真值")
    ax[1,1].plot(np.arange(len(w)),w,"x--",c=BLUE,label="4 秒后学到的权值")
    ax[1,1].set(title="自适应 FIR 学习参考到主通道的路径",xlabel="延迟 / 样点",ylabel="系数 / 无量纲")
    for a in ax.flat:a.legend(fontsize=9);a.grid(alpha=.18)
    finish(fig,out,"04-adaptive-cancellation.png")
    return m


def tradeoff_figure(out):
    fig,ax=plt.subplots(1,2,figsize=(12,4))
    fs=4096
    sos=signal.butter(4,[118,128],btype="bandpass",fs=fs,output="sos")
    f=np.linspace(105,140,2500)
    _,h=signal.sosfreqz(sos,worN=f,fs=fs)
    ax[0].plot(f,20*np.log10(np.maximum(np.abs(h),1e-8)),c=BLUE,label="单向 8 阶带通")
    ax[0].plot(f,40*np.log10(np.maximum(np.abs(h),1e-8)),c=ORANGE,ls="--",label="双向：幅度响应平方")
    ax[0].axhline(-3,c=GRAY,ls=":");ax[0].axhline(-6,c=GRAY,ls="-.")
    ax[0].set(xlim=(105,140),ylim=(-65,2),xlabel="频率 / Hz",ylabel="幅度增益 / dB",title="sosfiltfilt 的截止点变为约 −6 dB")
    df=np.linspace(-4,4,1500)
    for duration,c in [(1,BLUE),(4,ORANGE)]:
        ax[1].plot(df,np.abs(np.sinc(df*duration)),c=c,label=f"矩形积分 T = {duration} s")
    ax[1].set(xlabel="目标与参考频差 / Hz",ylabel="归一化幅值 / 无量纲",title="基带分量的积分响应：|sinc(Δf T)|",ylim=(0,1.05))
    for a in ax:a.legend(fontsize=9);a.grid(alpha=.18)
    finish(fig,out,"05-response-and-frequency-error.png")


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out",type=Path,default=Path("results"))
    out=parser.parse_args().out;out.mkdir(parents=True,exist_ok=True)
    results={"data_kind":"synthetic; not hardware measurements", "units":"arbitrary units (a.u.)",
        "environment":{"python":platform.python_version(),"numpy":np.__version__,
                       "scipy":scipy.__version__,"matplotlib":matplotlib.__version__},
        "tone":tone_experiment(out),"matched":matched_experiment(out),
        "envelope":envelope_experiment(out),"adaptive":adaptive_experiment(out)}
    tradeoff_figure(out)
    assert results["tone"]["bandpass_snr_db"] > results["tone"]["raw_snr_db"]+10
    assert abs(results["tone"]["amplitude_error_percent"]) < 15
    assert abs(results["tone"]["phase_error_deg"]) < 10
    assert results["tone"]["causal_block_max_abs_error"] < 1e-12
    assert abs(results["matched"]["start_error_samples"]) <= 1
    assert results["matched"]["true_start_score"] > 5
    assert abs(results["envelope"]["detected_repeat_hz"]-40) < 0.5
    assert results["adaptive"]["improvement_db"] > 10
    results["checks"]={"passed":True,"count":8,"scope":"one deterministic synthetic run; no hardware acceptance or false-alarm guarantee"}
    (out/"metrics.json").write_text(json.dumps(results,ensure_ascii=False,indent=2)+"\n",encoding="utf-8",newline="\n")
    paths=sorted(out.glob("*.csv"))+sorted(out.glob("*.png"))+[out/"metrics.json"]
    manifest={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
    (out/"SHA256SUMS.json").write_text(json.dumps(manifest,indent=2)+"\n",encoding="utf-8",newline="\n")
    source=Path(__file__).resolve()
    with zipfile.ZipFile(out/"digital-filter-lab.zip","w",compression=zipfile.ZIP_DEFLATED,compresslevel=9) as z:
        files=[(source,"digital_filter_methods.py"),(source.with_name("requirements.txt"),"requirements.txt")]
        files += [(p,"results/"+p.name) for p in paths+[out/"SHA256SUMS.json"]]
        for path,name in files:
            info=zipfile.ZipInfo(name,date_time=(2026,10,26,0,0,0))
            info.compress_type=zipfile.ZIP_DEFLATED
            z.writestr(info,path.read_bytes())
    print(json.dumps(results,ensure_ascii=False,indent=2))


if __name__=="__main__":
    main()
