mpsig.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """
  2. Some signal functions implemented using mpmath.
  3. """
  4. try:
  5. import mpmath
  6. except ImportError:
  7. mpmath = None
  8. def _prod(seq):
  9. """Returns the product of the elements in the sequence `seq`."""
  10. p = 1
  11. for elem in seq:
  12. p *= elem
  13. return p
  14. def _relative_degree(z, p):
  15. """
  16. Return relative degree of transfer function from zeros and poles.
  17. This is simply len(p) - len(z), which must be nonnegative.
  18. A ValueError is raised if len(p) < len(z).
  19. """
  20. degree = len(p) - len(z)
  21. if degree < 0:
  22. raise ValueError("Improper transfer function. "
  23. "Must have at least as many poles as zeros.")
  24. return degree
  25. def _zpkbilinear(z, p, k, fs):
  26. """Bilinear transformation to convert a filter from analog to digital."""
  27. degree = _relative_degree(z, p)
  28. fs2 = 2*fs
  29. # Bilinear transform the poles and zeros
  30. z_z = [(fs2 + z1) / (fs2 - z1) for z1 in z]
  31. p_z = [(fs2 + p1) / (fs2 - p1) for p1 in p]
  32. # Any zeros that were at infinity get moved to the Nyquist frequency
  33. z_z.extend([-1] * degree)
  34. # Compensate for gain change
  35. numer = _prod(fs2 - z1 for z1 in z)
  36. denom = _prod(fs2 - p1 for p1 in p)
  37. k_z = k * numer / denom
  38. return z_z, p_z, k_z.real
  39. def _zpklp2lp(z, p, k, wo=1):
  40. """Transform a lowpass filter to a different cutoff frequency."""
  41. degree = _relative_degree(z, p)
  42. # Scale all points radially from origin to shift cutoff frequency
  43. z_lp = [wo * z1 for z1 in z]
  44. p_lp = [wo * p1 for p1 in p]
  45. # Each shifted pole decreases gain by wo, each shifted zero increases it.
  46. # Cancel out the net change to keep overall gain the same
  47. k_lp = k * wo**degree
  48. return z_lp, p_lp, k_lp
  49. def _butter_analog_poles(n):
  50. """
  51. Poles of an analog Butterworth lowpass filter.
  52. This is the same calculation as scipy.signal.buttap(n) or
  53. scipy.signal.butter(n, 1, analog=True, output='zpk'), but mpmath is used,
  54. and only the poles are returned.
  55. """
  56. poles = [-mpmath.exp(1j*mpmath.pi*k/(2*n)) for k in range(-n+1, n, 2)]
  57. return poles
  58. def butter_lp(n, Wn):
  59. """
  60. Lowpass Butterworth digital filter design.
  61. This computes the same result as scipy.signal.butter(n, Wn, output='zpk'),
  62. but it uses mpmath, and the results are returned in lists instead of NumPy
  63. arrays.
  64. """
  65. zeros = []
  66. poles = _butter_analog_poles(n)
  67. k = 1
  68. fs = 2
  69. warped = 2 * fs * mpmath.tan(mpmath.pi * Wn / fs)
  70. z, p, k = _zpklp2lp(zeros, poles, k, wo=warped)
  71. z, p, k = _zpkbilinear(z, p, k, fs=fs)
  72. return z, p, k
  73. def zpkfreqz(z, p, k, worN=None):
  74. """
  75. Frequency response of a filter in zpk format, using mpmath.
  76. This is the same calculation as scipy.signal.freqz, but the input is in
  77. zpk format, the calculation is performed using mpath, and the results are
  78. returned in lists instead of NumPy arrays.
  79. """
  80. if worN is None or isinstance(worN, int):
  81. N = worN or 512
  82. ws = [mpmath.pi * mpmath.mpf(j) / N for j in range(N)]
  83. else:
  84. ws = worN
  85. h = []
  86. for wk in ws:
  87. zm1 = mpmath.exp(1j * wk)
  88. numer = _prod([zm1 - t for t in z])
  89. denom = _prod([zm1 - t for t in p])
  90. hk = k * numer / denom
  91. h.append(hk)
  92. return ws, h