_upfirdn.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # Code adapted from "upfirdn" python library with permission:
  2. #
  3. # Copyright (c) 2009, Motorola, Inc
  4. #
  5. # All Rights Reserved.
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions are
  9. # met:
  10. #
  11. # * Redistributions of source code must retain the above copyright notice,
  12. # this list of conditions and the following disclaimer.
  13. #
  14. # * Redistributions in binary form must reproduce the above copyright
  15. # notice, this list of conditions and the following disclaimer in the
  16. # documentation and/or other materials provided with the distribution.
  17. #
  18. # * Neither the name of Motorola nor the names of its contributors may be
  19. # used to endorse or promote products derived from this software without
  20. # specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  23. # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  24. # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  25. # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  26. # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  27. # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  28. # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  29. # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  30. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  31. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  32. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. import numpy as np
  34. from ._upfirdn_apply import _output_len, _apply, mode_enum
  35. __all__ = ['upfirdn', '_output_len']
  36. _upfirdn_modes = [
  37. 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',
  38. 'antisymmetric', 'antireflect', 'line',
  39. ]
  40. def _pad_h(h, up):
  41. """Store coefficients in a transposed, flipped arrangement.
  42. For example, suppose upRate is 3, and the
  43. input number of coefficients is 10, represented as h[0], ..., h[9].
  44. Then the internal buffer will look like this::
  45. h[9], h[6], h[3], h[0], // flipped phase 0 coefs
  46. 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded)
  47. 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded)
  48. """
  49. h_padlen = len(h) + (-len(h) % up)
  50. h_full = np.zeros(h_padlen, h.dtype)
  51. h_full[:len(h)] = h
  52. h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()
  53. return h_full
  54. def _check_mode(mode):
  55. mode = mode.lower()
  56. enum = mode_enum(mode)
  57. return enum
  58. class _UpFIRDn:
  59. """Helper for resampling."""
  60. def __init__(self, h, x_dtype, up, down):
  61. h = np.asarray(h)
  62. if h.ndim != 1 or h.size == 0:
  63. raise ValueError('h must be 1-D with non-zero length')
  64. self._output_type = np.result_type(h.dtype, x_dtype, np.float32)
  65. h = np.asarray(h, self._output_type)
  66. self._up = int(up)
  67. self._down = int(down)
  68. if self._up < 1 or self._down < 1:
  69. raise ValueError('Both up and down must be >= 1')
  70. # This both transposes, and "flips" each phase for filtering
  71. self._h_trans_flip = _pad_h(h, self._up)
  72. self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)
  73. self._h_len_orig = len(h)
  74. def apply_filter(self, x, axis=-1, mode='constant', cval=0):
  75. """Apply the prepared filter to the specified axis of N-D signal x."""
  76. output_len = _output_len(self._h_len_orig, x.shape[axis],
  77. self._up, self._down)
  78. # Explicit use of np.int64 for output_shape dtype avoids OverflowError
  79. # when allocating large array on platforms where np.int_ is 32 bits
  80. output_shape = np.asarray(x.shape, dtype=np.int64)
  81. output_shape[axis] = output_len
  82. out = np.zeros(output_shape, dtype=self._output_type, order='C')
  83. axis = axis % x.ndim
  84. mode = _check_mode(mode)
  85. _apply(np.asarray(x, self._output_type),
  86. self._h_trans_flip, out,
  87. self._up, self._down, axis, mode, cval)
  88. return out
  89. def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
  90. """Upsample, FIR filter, and downsample.
  91. Parameters
  92. ----------
  93. h : array_like
  94. 1-D FIR (finite-impulse response) filter coefficients.
  95. x : array_like
  96. Input signal array.
  97. up : int, optional
  98. Upsampling rate. Default is 1.
  99. down : int, optional
  100. Downsampling rate. Default is 1.
  101. axis : int, optional
  102. The axis of the input data array along which to apply the
  103. linear filter. The filter is applied to each subarray along
  104. this axis. Default is -1.
  105. mode : str, optional
  106. The signal extension mode to use. The set
  107. ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to
  108. modes provided by `numpy.pad`. ``"smooth"`` implements a smooth
  109. extension by extending based on the slope of the last 2 points at each
  110. end of the array. ``"antireflect"`` and ``"antisymmetric"`` are
  111. anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode
  112. `"line"` extends the signal based on a linear trend defined by the
  113. first and last points along the ``axis``.
  114. .. versionadded:: 1.4.0
  115. cval : float, optional
  116. The constant value to use when ``mode == "constant"``.
  117. .. versionadded:: 1.4.0
  118. Returns
  119. -------
  120. y : ndarray
  121. The output signal array. Dimensions will be the same as `x` except
  122. for along `axis`, which will change size according to the `h`,
  123. `up`, and `down` parameters.
  124. Notes
  125. -----
  126. The algorithm is an implementation of the block diagram shown on page 129
  127. of the Vaidyanathan text [1]_ (Figure 4.3-8d).
  128. The direct approach of upsampling by factor of P with zero insertion,
  129. FIR filtering of length ``N``, and downsampling by factor of Q is
  130. O(N*Q) per output sample. The polyphase implementation used here is
  131. O(N/P).
  132. .. versionadded:: 0.18
  133. References
  134. ----------
  135. .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,
  136. Prentice Hall, 1993.
  137. Examples
  138. --------
  139. Simple operations:
  140. >>> import numpy as np
  141. >>> from scipy.signal import upfirdn
  142. >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter
  143. array([ 1., 2., 3., 2., 1.])
  144. >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion
  145. array([ 1., 0., 0., 2., 0., 0., 3.])
  146. >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold
  147. array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.])
  148. >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation
  149. array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5])
  150. >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3
  151. array([ 0., 3., 6., 9.])
  152. >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3
  153. array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5])
  154. Apply a single filter to multiple signals:
  155. >>> x = np.reshape(np.arange(8), (4, 2))
  156. >>> x
  157. array([[0, 1],
  158. [2, 3],
  159. [4, 5],
  160. [6, 7]])
  161. Apply along the last dimension of ``x``:
  162. >>> h = [1, 1]
  163. >>> upfirdn(h, x, 2)
  164. array([[ 0., 0., 1., 1.],
  165. [ 2., 2., 3., 3.],
  166. [ 4., 4., 5., 5.],
  167. [ 6., 6., 7., 7.]])
  168. Apply along the 0th dimension of ``x``:
  169. >>> upfirdn(h, x, 2, axis=0)
  170. array([[ 0., 1.],
  171. [ 0., 1.],
  172. [ 2., 3.],
  173. [ 2., 3.],
  174. [ 4., 5.],
  175. [ 4., 5.],
  176. [ 6., 7.],
  177. [ 6., 7.]])
  178. """
  179. x = np.asarray(x)
  180. ufd = _UpFIRDn(h, x.dtype, up, down)
  181. # This is equivalent to (but faster than) using np.apply_along_axis
  182. return ufd.apply_filter(x, axis, mode, cval)