Translated from karrikuh's Matlab code: Struggling with MZTi lowpass
Last active
August 2, 2019 19:30
-
-
Save endolith/00c6770238b83369127b101102121070 to your computer and use it in GitHub Desktop.
MZTi Matched Z-Transform improved lowpass example [by karrikuh, Matlab→Python translation]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from numpy import pi, exp, tan, sqrt, log10 | |
import numpy as np | |
from scipy import signal | |
import matplotlib.pyplot as plt | |
def lp2_mzti(w0=None, K=None): | |
""" | |
Digital 2nd order lowpass filter design using | |
improved Matched Z transform (MZTi) | |
Analog prototype is | |
1 | |
H(s) = ----------------------- | |
(s/w0)^2 + K*(s/w0) + 1 | |
Returns coeffs of biquadratic digital filter | |
""" | |
# Pole mapping via conventional Matched Z transform | |
aa = [1 / w0**2, K / w0, 1] | |
p = np.roots(aa) # analog poles | |
a = signal.convolve([1, -exp(p[0])], [1, -exp(p[1])]) | |
# FIR correction filter | |
w = pi * np.arange(3) / 3 | |
H = abs(signal.freqs([1], aa, w)[1] / | |
signal.freqz([1], a, w)[1]) # relative magnitude error | |
b1 = 0.5 * (H[0] - sqrt(H[0] ** 2 - 2 * H[1] ** 2 + 2 * H[2] ** 2)) | |
b2 = (3 * (H[0] - b1) - | |
sqrt(-3 * H[0] ** 2 + 12 * H[1] ** 2 - 6 * H[0] * b1 - 3 * b1 ** 2) | |
) / 6 | |
b0 = H[0] - b1 - b2 | |
b = np.array([b0, b1, b2]) | |
return b, a | |
if __name__ == '__main__': | |
w0 = 0.4 * pi | |
Q = 4 | |
w = np.logspace(-1, 0, 1024) * pi | |
# analog prototype | |
Hs = signal.freqs([1], [1 / w0 ** 2, 1 / (w0 * Q), 1], w)[1] | |
# bilinear Z transform (BLT) | |
z = exp(-1j * w) | |
s = 2 * (1 - z) / (1 + z) / (2 * tan(w0 / 2)) | |
Hblt = 1 / (s ** 2 + s / Q + 1) | |
[b, a] = lp2_mzti(w0, 1 / Q) | |
Hmzti = signal.freqz(b, a, w)[1] | |
plt.semilogx(w / pi, 20*log10(abs(Hs)), label='Analog') | |
plt.semilogx(w / pi, 20*log10(abs(Hblt)), 'g', label='BLT') | |
plt.semilogx(w / pi, 20*log10(abs(Hmzti)), 'r', label='MZTi') | |
plt.grid(True, which='both') | |
plt.ylim([-40, 20]) | |
plt.legend() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment