"""Magnitude responses for the filter figures of this page.

    python filters.py     writes the .dat files the .tex drawings read (needs numpy, scipy)

3002: order-5 IIR filters at fs = 8000 Hz, passband edge 800 Hz (band-pass 800-1500 Hz),
      3 dB passband ripple, 30 dB stopband attenuation, as in my Matlab plots.
3002d: order-27 low-pass FIR at fs = 2000 Hz, pass 500 Hz, stop 600 Hz:
      window method (Hamming) and Parks-McClellan (Remez).
"""
import numpy as np
from scipy import signal

fs = 8000
f = np.linspace(1, fs / 2, 800)
kinds = {
    "butter": lambda b, t: signal.butter(5, b, t, fs=fs),
    "cheby1": lambda b, t: signal.cheby1(5, 3, b, t, fs=fs),
    "cheby2": lambda b, t: signal.cheby2(5, 30, b, t, fs=fs),
    "ellip": lambda b, t: signal.ellip(5, 3, 30, b, t, fs=fs),
}
cheby2_edge = {"lowpass": 1000, "highpass": 650, "bandpass": [700, 1650]}
for t, band in (("lowpass", 800), ("highpass", 800), ("bandpass", [800, 1500])):
    cols = [f]
    for k, design in kinds.items():
        b, a = design(cheby2_edge[t] if k == "cheby2" else band, t)
        _, h = signal.freqz(b, a, worN=f, fs=fs)
        cols.append(np.maximum(20 * np.log10(np.abs(h) + 1e-12), -60))
    np.savetxt(f"{t}.dat", np.column_stack(cols), fmt="%.4g", header="f " + " ".join(kinds), comments="")

fs2 = 2000
f2 = np.linspace(0, fs2 / 2, 800)
b_win = signal.firwin(28, 550, window="hamming", fs=fs2)
b_pm = signal.remez(28, [0, 500, 600, fs2 / 2], [1, 0], weight=[1, 10], fs=fs2)
cols = [f2]
for b in (b_win, b_pm):
    _, h = signal.freqz(b, 1, worN=f2, fs=fs2)
    cols.append(np.maximum(20 * np.log10(np.abs(h) + 1e-12), -80))
np.savetxt("fir.dat", np.column_stack(cols), fmt="%.4g", header="f window remez", comments="")

