_upfirdn.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 scipy._lib._array_api import array_namespace
  35. from ._upfirdn_apply import _output_len, _apply, mode_enum
  36. __all__ = ['upfirdn', '_output_len']
  37. _upfirdn_modes = [
  38. 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',
  39. 'antisymmetric', 'antireflect', 'line',
  40. ]
  41. def _pad_h(h, up):
  42. """Store coefficients in a transposed, flipped arrangement.
  43. For example, suppose upRate is 3, and the
  44. input number of coefficients is 10, represented as h[0], ..., h[9].
  45. Then the internal buffer will look like this::
  46. h[9], h[6], h[3], h[0], // flipped phase 0 coefs
  47. 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded)
  48. 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded)
  49. """
  50. h_padlen = len(h) + (-len(h) % up)
  51. h_full = np.zeros(h_padlen, h.dtype)
  52. h_full[:len(h)] = h
  53. h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()
  54. return h_full
  55. def _check_mode(mode):
  56. mode = mode.lower()
  57. enum = mode_enum(mode)
  58. return enum
  59. class _UpFIRDn:
  60. """Helper for resampling."""
  61. def __init__(self, h, x_dtype, up, down):
  62. h = np.asarray(h)
  63. if h.ndim != 1 or h.size == 0:
  64. raise ValueError('h must be 1-D with non-zero length')
  65. self._output_type = np.result_type(h.dtype, x_dtype, np.float32)
  66. h = np.asarray(h, self._output_type)
  67. self._up = int(up)
  68. self._down = int(down)
  69. if self._up < 1 or self._down < 1:
  70. raise ValueError('Both up and down must be >= 1')
  71. # This both transposes, and "flips" each phase for filtering
  72. self._h_trans_flip = _pad_h(h, self._up)
  73. self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)
  74. self._h_len_orig = len(h)
  75. def apply_filter(self, x, axis=-1, mode='constant', cval=0):
  76. """Apply the prepared filter to the specified axis of N-D signal x."""
  77. output_len = _output_len(self._h_len_orig, x.shape[axis],
  78. self._up, self._down)
  79. # Explicit use of np.int64 for output_shape dtype avoids OverflowError
  80. # when allocating large array on platforms where intp is 32 bits.
  81. output_shape = np.asarray(x.shape, dtype=np.int64)
  82. output_shape[axis] = output_len
  83. out = np.zeros(output_shape, dtype=self._output_type, order='C')
  84. axis = axis % x.ndim
  85. mode = _check_mode(mode)
  86. _apply(np.asarray(x, self._output_type),
  87. self._h_trans_flip, out,
  88. self._up, self._down, axis, mode, cval)
  89. return out
  90. def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
  91. """Upsample, FIR filter, and downsample.
  92. Parameters
  93. ----------
  94. h : array_like
  95. 1-D FIR (finite-impulse response) filter coefficients.
  96. x : array_like
  97. Input signal array.
  98. up : int, optional
  99. Upsampling rate. Default is 1.
  100. down : int, optional
  101. Downsampling rate. Default is 1.
  102. axis : int, optional
  103. The axis of the input data array along which to apply the
  104. linear filter. The filter is applied to each subarray along
  105. this axis. Default is -1.
  106. mode : str, optional
  107. The signal extension mode to use. The set
  108. ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to
  109. modes provided by `numpy.pad`. ``"smooth"`` implements a smooth
  110. extension by extending based on the slope of the last 2 points at each
  111. end of the array. ``"antireflect"`` and ``"antisymmetric"`` are
  112. anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode
  113. `"line"` extends the signal based on a linear trend defined by the
  114. first and last points along the ``axis``.
  115. .. versionadded:: 1.4.0
  116. cval : float, optional
  117. The constant value to use when ``mode == "constant"``.
  118. .. versionadded:: 1.4.0
  119. Returns
  120. -------
  121. y : ndarray
  122. The output signal array. Dimensions will be the same as `x` except
  123. for along `axis`, which will change size according to the `h`,
  124. `up`, and `down` parameters.
  125. Notes
  126. -----
  127. The algorithm is an implementation of the block diagram shown on page 129
  128. of the Vaidyanathan text [1]_ (Figure 4.3-8d).
  129. The direct approach of upsampling by factor of P with zero insertion,
  130. FIR filtering of length ``N``, and downsampling by factor of Q is
  131. O(N*Q) per output sample. The polyphase implementation used here is
  132. O(N/P).
  133. .. versionadded:: 0.18
  134. References
  135. ----------
  136. .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,
  137. Prentice Hall, 1993.
  138. Examples
  139. --------
  140. Simple operations:
  141. >>> import numpy as np
  142. >>> from scipy.signal import upfirdn
  143. >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter
  144. array([ 1., 2., 3., 2., 1.])
  145. >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion
  146. array([ 1., 0., 0., 2., 0., 0., 3.])
  147. >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold
  148. array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.])
  149. >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation
  150. array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5])
  151. >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3
  152. array([ 0., 3., 6., 9.])
  153. >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3
  154. array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5])
  155. Apply a single filter to multiple signals:
  156. >>> x = np.reshape(np.arange(8), (4, 2))
  157. >>> x
  158. array([[0, 1],
  159. [2, 3],
  160. [4, 5],
  161. [6, 7]])
  162. Apply along the last dimension of ``x``:
  163. >>> h = [1, 1]
  164. >>> upfirdn(h, x, 2)
  165. array([[ 0., 0., 1., 1.],
  166. [ 2., 2., 3., 3.],
  167. [ 4., 4., 5., 5.],
  168. [ 6., 6., 7., 7.]])
  169. Apply along the 0th dimension of ``x``:
  170. >>> upfirdn(h, x, 2, axis=0)
  171. array([[ 0., 1.],
  172. [ 0., 1.],
  173. [ 2., 3.],
  174. [ 2., 3.],
  175. [ 4., 5.],
  176. [ 4., 5.],
  177. [ 6., 7.],
  178. [ 6., 7.]])
  179. """
  180. xp = array_namespace(h, x)
  181. x = np.asarray(x)
  182. ufd = _UpFIRDn(h, x.dtype, up, down)
  183. # This is equivalent to (but faster than) using np.apply_along_axis
  184. return xp.asarray(ufd.apply_filter(x, axis, mode, cval))