window.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. import math
  14. from typing import List, Tuple, Union
  15. import numpy as np
  16. import paddle
  17. from paddle import Tensor
  18. class WindowFunctionRegister:
  19. def __init__(self):
  20. self._functions_dict = {}
  21. def register(self, func=None):
  22. def add_subfunction(func):
  23. name = func.__name__
  24. self._functions_dict[name] = func
  25. return func
  26. return add_subfunction
  27. def get(self, name):
  28. return self._functions_dict[name]
  29. window_function_register = WindowFunctionRegister()
  30. @window_function_register.register()
  31. def _cat(x: List[Tensor], data_type: str) -> Tensor:
  32. l = []
  33. for t in x:
  34. if np.isscalar(t) and not isinstance(t, str):
  35. l.append(paddle.to_tensor([t], data_type))
  36. else:
  37. l.append(paddle.to_tensor(t, data_type))
  38. return paddle.concat(l)
  39. @window_function_register.register()
  40. def _acosh(x: Union[Tensor, float]) -> Tensor:
  41. if isinstance(x, float):
  42. return math.log(x + math.sqrt(x**2 - 1))
  43. return paddle.log(x + paddle.sqrt(paddle.square(x) - 1))
  44. @window_function_register.register()
  45. def _extend(M: int, sym: bool) -> bool:
  46. """Extend window by 1 sample if needed for DFT-even symmetry."""
  47. if not sym:
  48. return M + 1, True
  49. else:
  50. return M, False
  51. @window_function_register.register()
  52. def _len_guards(M: int) -> bool:
  53. """Handle small or incorrect window lengths."""
  54. if int(M) != M or M < 0:
  55. raise ValueError('Window length M must be a non-negative integer')
  56. return M <= 1
  57. @window_function_register.register()
  58. def _truncate(w: Tensor, needed: bool) -> Tensor:
  59. """Truncate window by 1 sample if needed for DFT-even symmetry."""
  60. if needed:
  61. return w[:-1]
  62. else:
  63. return w
  64. @window_function_register.register()
  65. def _general_gaussian(
  66. M: int, p, sig, sym: bool = True, dtype: str = 'float64'
  67. ) -> Tensor:
  68. """Compute a window with a generalized Gaussian shape.
  69. This function is consistent with scipy.signal.windows.general_gaussian().
  70. """
  71. if _len_guards(M):
  72. return paddle.ones((M,), dtype=dtype)
  73. M, needs_trunc = _extend(M, sym)
  74. n = paddle.arange(0, M, dtype=dtype) - (M - 1.0) / 2.0
  75. w = paddle.exp(-0.5 * paddle.abs(n / sig) ** (2 * p))
  76. return _truncate(w, needs_trunc)
  77. @window_function_register.register()
  78. def _general_cosine(
  79. M: int, a: float, sym: bool = True, dtype: str = 'float64'
  80. ) -> Tensor:
  81. """Compute a generic weighted sum of cosine terms window.
  82. This function is consistent with scipy.signal.windows.general_cosine().
  83. """
  84. if _len_guards(M):
  85. return paddle.ones((M,), dtype=dtype)
  86. M, needs_trunc = _extend(M, sym)
  87. fac = paddle.linspace(-math.pi, math.pi, M, dtype=dtype)
  88. w = paddle.zeros((M,), dtype=dtype)
  89. for k in range(len(a)):
  90. w += a[k] * paddle.cos(k * fac)
  91. return _truncate(w, needs_trunc)
  92. @window_function_register.register()
  93. def _general_hamming(
  94. M: int, alpha: float, sym: bool = True, dtype: str = 'float64'
  95. ) -> Tensor:
  96. """Compute a generalized Hamming window.
  97. This function is consistent with scipy.signal.windows.general_hamming()
  98. """
  99. return _general_cosine(M, [alpha, 1.0 - alpha], sym, dtype=dtype)
  100. @window_function_register.register()
  101. def _taylor(
  102. M: int, nbar=4, sll=30, norm=True, sym: bool = True, dtype: str = 'float64'
  103. ) -> Tensor:
  104. """Compute a Taylor window.
  105. The Taylor window taper function approximates the Dolph-Chebyshev window's
  106. constant sidelobe level for a parameterized number of near-in sidelobes.
  107. """
  108. if _len_guards(M):
  109. return paddle.ones((M,), dtype=dtype)
  110. M, needs_trunc = _extend(M, sym)
  111. # Original text uses a negative sidelobe level parameter and then negates
  112. # it in the calculation of B. To keep consistent with other methods we
  113. # assume the sidelobe level parameter to be positive.
  114. B = 10 ** (sll / 20)
  115. A = _acosh(B) / math.pi
  116. s2 = nbar**2 / (A**2 + (nbar - 0.5) ** 2)
  117. ma = paddle.arange(1, nbar, dtype=dtype)
  118. Fm = paddle.empty((nbar - 1,), dtype=dtype)
  119. signs = paddle.empty_like(ma)
  120. signs[::2] = 1
  121. signs[1::2] = -1
  122. m2 = ma * ma
  123. for mi in range(len(ma)):
  124. numer = signs[mi] * paddle.prod(
  125. 1 - m2[mi] / s2 / (A**2 + (ma - 0.5) ** 2)
  126. )
  127. if mi == 0:
  128. denom = 2 * paddle.prod(1 - m2[mi] / m2[mi + 1 :])
  129. elif mi == len(ma) - 1:
  130. denom = 2 * paddle.prod(1 - m2[mi] / m2[:mi])
  131. else:
  132. denom = (
  133. 2
  134. * paddle.prod(1 - m2[mi] / m2[:mi])
  135. * paddle.prod(1 - m2[mi] / m2[mi + 1 :])
  136. )
  137. Fm[mi] = numer / denom
  138. def W(n):
  139. return 1 + 2 * paddle.matmul(
  140. Fm.unsqueeze(0),
  141. paddle.cos(2 * math.pi * ma.unsqueeze(1) * (n - M / 2.0 + 0.5) / M),
  142. )
  143. w = W(paddle.arange(0, M, dtype=dtype))
  144. # normalize (Note that this is not described in the original text [1])
  145. if norm:
  146. scale = 1.0 / W((M - 1) / 2)
  147. w *= scale
  148. w = w.squeeze()
  149. return _truncate(w, needs_trunc)
  150. @window_function_register.register()
  151. def _hamming(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor:
  152. """Compute a Hamming window.
  153. The Hamming window is a taper formed by using a raised cosine with
  154. non-zero endpoints, optimized to minimize the nearest side lobe.
  155. """
  156. return _general_hamming(M, 0.54, sym, dtype=dtype)
  157. @window_function_register.register()
  158. def _hann(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor:
  159. """Compute a Hann window.
  160. The Hann window is a taper formed by using a raised cosine or sine-squared
  161. with ends that touch zero.
  162. """
  163. return _general_hamming(M, 0.5, sym, dtype=dtype)
  164. @window_function_register.register()
  165. def _tukey(
  166. M: int, alpha=0.5, sym: bool = True, dtype: str = 'float64'
  167. ) -> Tensor:
  168. """Compute a Tukey window.
  169. The Tukey window is also known as a tapered cosine window.
  170. """
  171. if _len_guards(M):
  172. return paddle.ones((M,), dtype=dtype)
  173. if alpha <= 0:
  174. return paddle.ones((M,), dtype=dtype)
  175. elif alpha >= 1.0:
  176. return _hann(M, sym=sym)
  177. M, needs_trunc = _extend(M, sym)
  178. n = paddle.arange(0, M, dtype=dtype)
  179. width = int(alpha * (M - 1) / 2.0)
  180. n1 = n[0 : width + 1]
  181. n2 = n[width + 1 : M - width - 1]
  182. n3 = n[M - width - 1 :]
  183. w1 = 0.5 * (1 + paddle.cos(math.pi * (-1 + 2.0 * n1 / alpha / (M - 1))))
  184. w2 = paddle.ones(n2.shape, dtype=dtype)
  185. w3 = 0.5 * (
  186. 1
  187. + paddle.cos(math.pi * (-2.0 / alpha + 1 + 2.0 * n3 / alpha / (M - 1)))
  188. )
  189. w = paddle.concat([w1, w2, w3])
  190. return _truncate(w, needs_trunc)
  191. @window_function_register.register()
  192. def _gaussian(
  193. M: int, std: float, sym: bool = True, dtype: str = 'float64'
  194. ) -> Tensor:
  195. """Compute a Gaussian window.
  196. The Gaussian widows has a Gaussian shape defined by the standard deviation(std).
  197. """
  198. if _len_guards(M):
  199. return paddle.ones((M,), dtype=dtype)
  200. M, needs_trunc = _extend(M, sym)
  201. n = paddle.arange(0, M, dtype=dtype) - (M - 1.0) / 2.0
  202. sig2 = 2 * std * std
  203. w = paddle.exp(-(n**2) / sig2)
  204. return _truncate(w, needs_trunc)
  205. @window_function_register.register()
  206. def _exponential(
  207. M: int, center=None, tau=1.0, sym: bool = True, dtype: str = 'float64'
  208. ) -> Tensor:
  209. """Compute an exponential (or Poisson) window."""
  210. if sym and center is not None:
  211. raise ValueError("If sym==True, center must be None.")
  212. if _len_guards(M):
  213. return paddle.ones((M,), dtype=dtype)
  214. M, needs_trunc = _extend(M, sym)
  215. if center is None:
  216. center = (M - 1) / 2
  217. n = paddle.arange(0, M, dtype=dtype)
  218. w = paddle.exp(-paddle.abs(n - center) / tau)
  219. return _truncate(w, needs_trunc)
  220. @window_function_register.register()
  221. def _triang(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor:
  222. """Compute a triangular window."""
  223. if _len_guards(M):
  224. return paddle.ones((M,), dtype=dtype)
  225. M, needs_trunc = _extend(M, sym)
  226. n = paddle.arange(1, (M + 1) // 2 + 1, dtype=dtype)
  227. if M % 2 == 0:
  228. w = (2 * n - 1.0) / M
  229. w = paddle.concat([w, w[::-1]])
  230. else:
  231. w = 2 * n / (M + 1.0)
  232. w = paddle.concat([w, w[-2::-1]])
  233. return _truncate(w, needs_trunc)
  234. @window_function_register.register()
  235. def _bohman(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor:
  236. """Compute a Bohman window.
  237. The Bohman window is the autocorrelation of a cosine window.
  238. """
  239. if _len_guards(M):
  240. return paddle.ones((M,), dtype=dtype)
  241. M, needs_trunc = _extend(M, sym)
  242. fac = paddle.abs(paddle.linspace(-1, 1, M, dtype=dtype)[1:-1])
  243. w = (1 - fac) * paddle.cos(math.pi * fac) + 1.0 / math.pi * paddle.sin(
  244. math.pi * fac
  245. )
  246. w = _cat([0, w, 0], dtype)
  247. return _truncate(w, needs_trunc)
  248. @window_function_register.register()
  249. def _blackman(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor:
  250. """Compute a Blackman window.
  251. The Blackman window is a taper formed by using the first three terms of
  252. a summation of cosines. It was designed to have close to the minimal
  253. leakage possible. It is close to optimal, only slightly worse than a
  254. Kaiser window.
  255. """
  256. return _general_cosine(M, [0.42, 0.50, 0.08], sym, dtype=dtype)
  257. @window_function_register.register()
  258. def _cosine(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor:
  259. """Compute a window with a simple cosine shape."""
  260. if _len_guards(M):
  261. return paddle.ones((M,), dtype=dtype)
  262. M, needs_trunc = _extend(M, sym)
  263. w = paddle.sin(math.pi / M * (paddle.arange(0, M, dtype=dtype) + 0.5))
  264. return _truncate(w, needs_trunc)
  265. def get_window(
  266. window: Union[str, Tuple[str, float]],
  267. win_length: int,
  268. fftbins: bool = True,
  269. dtype: str = 'float64',
  270. ) -> Tensor:
  271. """Return a window of a given length and type.
  272. Args:
  273. window (Union[str, Tuple[str, float]]): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'gaussian', 'general_gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'.
  274. win_length (int): Number of samples.
  275. fftbins (bool, optional): If True, create a "periodic" window. Otherwise, create a "symmetric" window, for use in filter design. Defaults to True.
  276. dtype (str, optional): The data type of the return window. Defaults to 'float64'.
  277. Returns:
  278. Tensor: The window represented as a tensor.
  279. Examples:
  280. .. code-block:: python
  281. >>> import paddle
  282. >>> n_fft = 512
  283. >>> cosine_window = paddle.audio.functional.get_window('cosine', n_fft)
  284. >>> std = 7
  285. >>> gaussian_window = paddle.audio.functional.get_window(('gaussian',std), n_fft)
  286. """
  287. sym = not fftbins
  288. args = ()
  289. if isinstance(window, tuple):
  290. winstr = window[0]
  291. if len(window) > 1:
  292. args = window[1:]
  293. elif isinstance(window, str):
  294. if window in ['gaussian', 'exponential']:
  295. raise ValueError(
  296. "The '" + window + "' window needs one or "
  297. "more parameters -- pass a tuple."
  298. )
  299. else:
  300. winstr = window
  301. else:
  302. raise ValueError(
  303. "%s as window type is not supported." % str(type(window))
  304. )
  305. try:
  306. winfunc = window_function_register.get('_' + winstr)
  307. except KeyError as e:
  308. raise ValueError("Unknown window type.") from e
  309. params = (win_length,) + args
  310. kwargs = {'sym': sym}
  311. return winfunc(*params, dtype=dtype, **kwargs)