_peak_finding.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. """
  2. Functions for identifying peaks in signals.
  3. """
  4. from __future__ import division, print_function, absolute_import
  5. import math
  6. import numpy as np
  7. from scipy._lib.six import xrange
  8. from scipy.signal.wavelets import cwt, ricker
  9. from scipy.stats import scoreatpercentile
  10. from ._peak_finding_utils import (
  11. _local_maxima_1d,
  12. _select_by_peak_distance,
  13. _peak_prominences,
  14. _peak_widths
  15. )
  16. __all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences',
  17. 'peak_widths', 'find_peaks', 'find_peaks_cwt']
  18. def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'):
  19. """
  20. Calculate the relative extrema of `data`.
  21. Relative extrema are calculated by finding locations where
  22. ``comparator(data[n], data[n+1:n+order+1])`` is True.
  23. Parameters
  24. ----------
  25. data : ndarray
  26. Array in which to find the relative extrema.
  27. comparator : callable
  28. Function to use to compare two data points.
  29. Should take two arrays as arguments.
  30. axis : int, optional
  31. Axis over which to select from `data`. Default is 0.
  32. order : int, optional
  33. How many points on each side to use for the comparison
  34. to consider ``comparator(n,n+x)`` to be True.
  35. mode : str, optional
  36. How the edges of the vector are treated. 'wrap' (wrap around) or
  37. 'clip' (treat overflow as the same as the last (or first) element).
  38. Default 'clip'. See numpy.take
  39. Returns
  40. -------
  41. extrema : ndarray
  42. Boolean array of the same shape as `data` that is True at an extrema,
  43. False otherwise.
  44. See also
  45. --------
  46. argrelmax, argrelmin
  47. Examples
  48. --------
  49. >>> testdata = np.array([1,2,3,2,1])
  50. >>> _boolrelextrema(testdata, np.greater, axis=0)
  51. array([False, False, True, False, False], dtype=bool)
  52. """
  53. if((int(order) != order) or (order < 1)):
  54. raise ValueError('Order must be an int >= 1')
  55. datalen = data.shape[axis]
  56. locs = np.arange(0, datalen)
  57. results = np.ones(data.shape, dtype=bool)
  58. main = data.take(locs, axis=axis, mode=mode)
  59. for shift in xrange(1, order + 1):
  60. plus = data.take(locs + shift, axis=axis, mode=mode)
  61. minus = data.take(locs - shift, axis=axis, mode=mode)
  62. results &= comparator(main, plus)
  63. results &= comparator(main, minus)
  64. if(~results.any()):
  65. return results
  66. return results
  67. def argrelmin(data, axis=0, order=1, mode='clip'):
  68. """
  69. Calculate the relative minima of `data`.
  70. Parameters
  71. ----------
  72. data : ndarray
  73. Array in which to find the relative minima.
  74. axis : int, optional
  75. Axis over which to select from `data`. Default is 0.
  76. order : int, optional
  77. How many points on each side to use for the comparison
  78. to consider ``comparator(n, n+x)`` to be True.
  79. mode : str, optional
  80. How the edges of the vector are treated.
  81. Available options are 'wrap' (wrap around) or 'clip' (treat overflow
  82. as the same as the last (or first) element).
  83. Default 'clip'. See numpy.take
  84. Returns
  85. -------
  86. extrema : tuple of ndarrays
  87. Indices of the minima in arrays of integers. ``extrema[k]`` is
  88. the array of indices of axis `k` of `data`. Note that the
  89. return value is a tuple even when `data` is one-dimensional.
  90. See Also
  91. --------
  92. argrelextrema, argrelmax, find_peaks
  93. Notes
  94. -----
  95. This function uses `argrelextrema` with np.less as comparator. Therefore it
  96. requires a strict inequality on both sides of a value to consider it a
  97. minimum. This means flat minima (more than one sample wide) are not detected.
  98. In case of one-dimensional `data` `find_peaks` can be used to detect all
  99. local minima, including flat ones, by calling it with negated `data`.
  100. .. versionadded:: 0.11.0
  101. Examples
  102. --------
  103. >>> from scipy.signal import argrelmin
  104. >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
  105. >>> argrelmin(x)
  106. (array([1, 5]),)
  107. >>> y = np.array([[1, 2, 1, 2],
  108. ... [2, 2, 0, 0],
  109. ... [5, 3, 4, 4]])
  110. ...
  111. >>> argrelmin(y, axis=1)
  112. (array([0, 2]), array([2, 1]))
  113. """
  114. return argrelextrema(data, np.less, axis, order, mode)
  115. def argrelmax(data, axis=0, order=1, mode='clip'):
  116. """
  117. Calculate the relative maxima of `data`.
  118. Parameters
  119. ----------
  120. data : ndarray
  121. Array in which to find the relative maxima.
  122. axis : int, optional
  123. Axis over which to select from `data`. Default is 0.
  124. order : int, optional
  125. How many points on each side to use for the comparison
  126. to consider ``comparator(n, n+x)`` to be True.
  127. mode : str, optional
  128. How the edges of the vector are treated.
  129. Available options are 'wrap' (wrap around) or 'clip' (treat overflow
  130. as the same as the last (or first) element).
  131. Default 'clip'. See `numpy.take`.
  132. Returns
  133. -------
  134. extrema : tuple of ndarrays
  135. Indices of the maxima in arrays of integers. ``extrema[k]`` is
  136. the array of indices of axis `k` of `data`. Note that the
  137. return value is a tuple even when `data` is one-dimensional.
  138. See Also
  139. --------
  140. argrelextrema, argrelmin, find_peaks
  141. Notes
  142. -----
  143. This function uses `argrelextrema` with np.greater as comparator. Therefore
  144. it requires a strict inequality on both sides of a value to consider it a
  145. maximum. This means flat maxima (more than one sample wide) are not detected.
  146. In case of one-dimensional `data` `find_peaks` can be used to detect all
  147. local maxima, including flat ones.
  148. .. versionadded:: 0.11.0
  149. Examples
  150. --------
  151. >>> from scipy.signal import argrelmax
  152. >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
  153. >>> argrelmax(x)
  154. (array([3, 6]),)
  155. >>> y = np.array([[1, 2, 1, 2],
  156. ... [2, 2, 0, 0],
  157. ... [5, 3, 4, 4]])
  158. ...
  159. >>> argrelmax(y, axis=1)
  160. (array([0]), array([1]))
  161. """
  162. return argrelextrema(data, np.greater, axis, order, mode)
  163. def argrelextrema(data, comparator, axis=0, order=1, mode='clip'):
  164. """
  165. Calculate the relative extrema of `data`.
  166. Parameters
  167. ----------
  168. data : ndarray
  169. Array in which to find the relative extrema.
  170. comparator : callable
  171. Function to use to compare two data points.
  172. Should take two arrays as arguments.
  173. axis : int, optional
  174. Axis over which to select from `data`. Default is 0.
  175. order : int, optional
  176. How many points on each side to use for the comparison
  177. to consider ``comparator(n, n+x)`` to be True.
  178. mode : str, optional
  179. How the edges of the vector are treated. 'wrap' (wrap around) or
  180. 'clip' (treat overflow as the same as the last (or first) element).
  181. Default is 'clip'. See `numpy.take`.
  182. Returns
  183. -------
  184. extrema : tuple of ndarrays
  185. Indices of the maxima in arrays of integers. ``extrema[k]`` is
  186. the array of indices of axis `k` of `data`. Note that the
  187. return value is a tuple even when `data` is one-dimensional.
  188. See Also
  189. --------
  190. argrelmin, argrelmax
  191. Notes
  192. -----
  193. .. versionadded:: 0.11.0
  194. Examples
  195. --------
  196. >>> from scipy.signal import argrelextrema
  197. >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
  198. >>> argrelextrema(x, np.greater)
  199. (array([3, 6]),)
  200. >>> y = np.array([[1, 2, 1, 2],
  201. ... [2, 2, 0, 0],
  202. ... [5, 3, 4, 4]])
  203. ...
  204. >>> argrelextrema(y, np.less, axis=1)
  205. (array([0, 2]), array([2, 1]))
  206. """
  207. results = _boolrelextrema(data, comparator,
  208. axis, order, mode)
  209. return np.nonzero(results)
  210. def _arg_x_as_expected(value):
  211. """Ensure argument `x` is a 1D C-contiguous array of dtype('float64').
  212. Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x`
  213. compatible with the signature of the wrapped Cython functions.
  214. Returns
  215. -------
  216. value : ndarray
  217. A one-dimensional C-contiguous array with dtype('float64').
  218. """
  219. value = np.asarray(value, order='C', dtype=np.float64)
  220. if value.ndim != 1:
  221. raise ValueError('`x` must be a 1D array')
  222. return value
  223. def _arg_peaks_as_expected(value):
  224. """Ensure argument `peaks` is a 1D C-contiguous array of dtype('intp').
  225. Used in `peak_prominences` and `peak_widths` to make `peaks` compatible
  226. with the signature of the wrapped Cython functions.
  227. Returns
  228. -------
  229. value : ndarray
  230. A one-dimensional C-contiguous array with dtype('intp').
  231. """
  232. value = np.asarray(value)
  233. if value.size == 0:
  234. # Empty arrays default to np.float64 but are valid input
  235. value = np.array([], dtype=np.intp)
  236. try:
  237. # Safely convert to C-contiguous array of type np.intp
  238. value = value.astype(np.intp, order='C', casting='safe',
  239. subok=False, copy=False)
  240. except TypeError:
  241. raise TypeError("cannot safely cast `peaks` to dtype('intp')")
  242. if value.ndim != 1:
  243. raise ValueError('`peaks` must be a 1D array')
  244. return value
  245. def _arg_wlen_as_expected(value):
  246. """Ensure argument `wlen` is of type `np.intp` and larger than 1.
  247. Used in `peak_prominences` and `peak_widths`.
  248. Returns
  249. -------
  250. value : np.intp
  251. The original `value` rounded up to an integer or -1 if `value` was
  252. None.
  253. """
  254. if value is None:
  255. # _peak_prominences expects an intp; -1 signals that no value was
  256. # supplied by the user
  257. value = -1
  258. elif 1 < value:
  259. # Round up to a positive integer
  260. if not np.can_cast(value, np.intp, "safe"):
  261. value = math.ceil(value)
  262. value = np.intp(value)
  263. else:
  264. raise ValueError('`wlen` must be larger than 1, was {}'
  265. .format(value))
  266. return value
  267. def peak_prominences(x, peaks, wlen=None):
  268. """
  269. Calculate the prominence of each peak in a signal.
  270. The prominence of a peak measures how much a peak stands out from the
  271. surrounding baseline of the signal and is defined as the vertical distance
  272. between the peak and its lowest contour line.
  273. Parameters
  274. ----------
  275. x : sequence
  276. A signal with peaks.
  277. peaks : sequence
  278. Indices of peaks in `x`.
  279. wlen : int, optional
  280. A window length in samples that optionally limits the evaluated area for
  281. each peak to a subset of `x`. The peak is always placed in the middle of
  282. the window therefore the given length is rounded up to the next odd
  283. integer. This parameter can speed up the calculation (see Notes).
  284. Returns
  285. -------
  286. prominences : ndarray
  287. The calculated prominences for each peak in `peaks`.
  288. left_bases, right_bases : ndarray
  289. The peaks' bases as indices in `x` to the left and right of each peak.
  290. The higher base of each pair is a peak's lowest contour line.
  291. Raises
  292. ------
  293. ValueError
  294. If a value in `peaks` is an invalid index for `x`.
  295. Warns
  296. -----
  297. PeakPropertyWarning
  298. For indices in `peaks` that don't point to valid local maxima in `x`
  299. the returned prominence will be 0 and this warning is raised. This
  300. also happens if `wlen` is smaller than the plateau size of a peak.
  301. Warnings
  302. --------
  303. This function may return unexpected results for data containing NaNs. To
  304. avoid this, NaNs should either be removed or replaced.
  305. See Also
  306. --------
  307. find_peaks
  308. Find peaks inside a signal based on peak properties.
  309. peak_widths
  310. Calculate the width of peaks.
  311. Notes
  312. -----
  313. Strategy to compute a peak's prominence:
  314. 1. Extend a horizontal line from the current peak to the left and right
  315. until the line either reaches the window border (see `wlen`) or
  316. intersects the signal again at the slope of a higher peak. An
  317. intersection with a peak of the same height is ignored.
  318. 2. On each side find the minimal signal value within the interval defined
  319. above. These points are the peak's bases.
  320. 3. The higher one of the two bases marks the peak's lowest contour line. The
  321. prominence can then be calculated as the vertical difference between the
  322. peaks height itself and its lowest contour line.
  323. Searching for the peak's bases can be slow for large `x` with periodic
  324. behavior because large chunks or even the full signal need to be evaluated
  325. for the first algorithmic step. This evaluation area can be limited with the
  326. parameter `wlen` which restricts the algorithm to a window around the
  327. current peak and can shorten the calculation time if the window length is
  328. short in relation to `x`.
  329. However this may stop the algorithm from finding the true global contour
  330. line if the peak's true bases are outside this window. Instead a higher
  331. contour line is found within the restricted window leading to a smaller
  332. calculated prominence. In practice this is only relevant for the highest set
  333. of peaks in `x`. This behavior may even be used intentionally to calculate
  334. "local" prominences.
  335. .. versionadded:: 1.1.0
  336. References
  337. ----------
  338. .. [1] Wikipedia Article for Topographic Prominence:
  339. https://en.wikipedia.org/wiki/Topographic_prominence
  340. Examples
  341. --------
  342. >>> from scipy.signal import find_peaks, peak_prominences
  343. >>> import matplotlib.pyplot as plt
  344. Create a test signal with two overlayed harmonics
  345. >>> x = np.linspace(0, 6 * np.pi, 1000)
  346. >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)
  347. Find all peaks and calculate prominences
  348. >>> peaks, _ = find_peaks(x)
  349. >>> prominences = peak_prominences(x, peaks)[0]
  350. >>> prominences
  351. array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 ,
  352. 0.47822491, 2.48340261, 0.47822491])
  353. Calculate the height of each peak's contour line and plot the results
  354. >>> contour_heights = x[peaks] - prominences
  355. >>> plt.plot(x)
  356. >>> plt.plot(peaks, x[peaks], "x")
  357. >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks])
  358. >>> plt.show()
  359. Let's evaluate a second example that demonstrates several edge cases for
  360. one peak at index 5.
  361. >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0])
  362. >>> peaks = np.array([5])
  363. >>> plt.plot(x)
  364. >>> plt.plot(peaks, x[peaks], "x")
  365. >>> plt.show()
  366. >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases)
  367. (array([3.]), array([2]), array([6]))
  368. Note how the peak at index 3 of the same height is not considered as a
  369. border while searching for the left base. Instead two minima at 0 and 2
  370. are found in which case the one closer to the evaluated peak is always
  371. chosen. On the right side however the base must be placed at 6 because the
  372. higher peak represents the right border to the evaluated area.
  373. >>> peak_prominences(x, peaks, wlen=3.1)
  374. (array([2.]), array([4]), array([6]))
  375. Here we restricted the algorithm to a window from 3 to 7 (the length is 5
  376. samples because `wlen` was rounded up to the next odd integer). Thus the
  377. only two candidates in the evaluated area are the two neighbouring samples
  378. and a smaller prominence is calculated.
  379. """
  380. x = _arg_x_as_expected(x)
  381. peaks = _arg_peaks_as_expected(peaks)
  382. wlen = _arg_wlen_as_expected(wlen)
  383. return _peak_prominences(x, peaks, wlen)
  384. def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None):
  385. """
  386. Calculate the width of each peak in a signal.
  387. This function calculates the width of a peak in samples at a relative
  388. distance to the peak's height and prominence.
  389. Parameters
  390. ----------
  391. x : sequence
  392. A signal with peaks.
  393. peaks : sequence
  394. Indices of peaks in `x`.
  395. rel_height : float, optional
  396. Chooses the relative height at which the peak width is measured as a
  397. percentage of its prominence. 1.0 calculates the width of the peak at
  398. its lowest contour line while 0.5 evaluates at half the prominence
  399. height. Must be at least 0. See notes for further explanation.
  400. prominence_data : tuple, optional
  401. A tuple of three arrays matching the output of `peak_prominences` when
  402. called with the same arguments `x` and `peaks`. This data is calculated
  403. internally if not provided.
  404. wlen : int, optional
  405. A window length in samples passed to `peak_prominences` as an optional
  406. argument for internal calculation of `prominence_data`. This argument
  407. is ignored if `prominence_data` is given.
  408. Returns
  409. -------
  410. widths : ndarray
  411. The widths for each peak in samples.
  412. width_heights : ndarray
  413. The height of the contour lines at which the `widths` where evaluated.
  414. left_ips, right_ips : ndarray
  415. Interpolated positions of left and right intersection points of a
  416. horizontal line at the respective evaluation height.
  417. Raises
  418. ------
  419. ValueError
  420. If `prominence_data` is supplied but doesn't satisfy the condition
  421. ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak,
  422. has the wrong dtype, is not C-contiguous or does not have the same
  423. shape.
  424. Warns
  425. -----
  426. PeakPropertyWarning
  427. Raised if any calculated width is 0. This may stem from the supplied
  428. `prominence_data` or if `rel_height` is set to 0.
  429. Warnings
  430. --------
  431. This function may return unexpected results for data containing NaNs. To
  432. avoid this, NaNs should either be removed or replaced.
  433. See Also
  434. --------
  435. find_peaks
  436. Find peaks inside a signal based on peak properties.
  437. peak_prominences
  438. Calculate the prominence of peaks.
  439. Notes
  440. -----
  441. The basic algorithm to calculate a peak's width is as follows:
  442. * Calculate the evaluation height :math:`h_{eval}` with the formula
  443. :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the
  444. height of the peak itself, :math:`P` is the peak's prominence and
  445. :math:`R` a positive ratio specified with the argument `rel_height`.
  446. * Draw a horizontal line at the evaluation height to both sides, starting at
  447. the peak's current vertical position until the lines either intersect a
  448. slope, the signal border or cross the vertical position of the peak's
  449. base (see `peak_prominences` for an definition). For the first case,
  450. intersection with the signal, the true intersection point is estimated
  451. with linear interpolation.
  452. * Calculate the width as the horizontal distance between the chosen
  453. endpoints on both sides. As a consequence of this the maximal possible
  454. width for each peak is the horizontal distance between its bases.
  455. As shown above to calculate a peak's width its prominence and bases must be
  456. known. You can supply these yourself with the argument `prominence_data`.
  457. Otherwise they are internally calculated (see `peak_prominences`).
  458. .. versionadded:: 1.1.0
  459. Examples
  460. --------
  461. >>> from scipy.signal import chirp, find_peaks, peak_widths
  462. >>> import matplotlib.pyplot as plt
  463. Create a test signal with two overlayed harmonics
  464. >>> x = np.linspace(0, 6 * np.pi, 1000)
  465. >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)
  466. Find all peaks and calculate their widths at the relative height of 0.5
  467. (contour line at half the prominence height) and 1 (at the lowest contour
  468. line at full prominence height).
  469. >>> peaks, _ = find_peaks(x)
  470. >>> results_half = peak_widths(x, peaks, rel_height=0.5)
  471. >>> results_half[0] # widths
  472. array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081,
  473. 35.46729324, 41.30429622, 181.93835853, 45.37078546])
  474. >>> results_full = peak_widths(x, peaks, rel_height=1)
  475. >>> results_full[0] # widths
  476. array([181.9396084 , 72.99284945, 61.28657872, 373.84622694,
  477. 61.78404617, 72.48822812, 253.09161876, 79.36860878])
  478. Plot signal, peaks and contour lines at which the widths where calculated
  479. >>> plt.plot(x)
  480. >>> plt.plot(peaks, x[peaks], "x")
  481. >>> plt.hlines(*results_half[1:], color="C2")
  482. >>> plt.hlines(*results_full[1:], color="C3")
  483. >>> plt.show()
  484. """
  485. x = _arg_x_as_expected(x)
  486. peaks = _arg_peaks_as_expected(peaks)
  487. if prominence_data is None:
  488. # Calculate prominence if not supplied and use wlen if supplied.
  489. wlen = _arg_wlen_as_expected(wlen)
  490. prominence_data = _peak_prominences(x, peaks, wlen)
  491. return _peak_widths(x, peaks, rel_height, *prominence_data)
  492. def _unpack_condition_args(interval, x, peaks):
  493. """
  494. Parse condition arguments for `find_peaks`.
  495. Parameters
  496. ----------
  497. interval : number or ndarray or sequence
  498. Either a number or ndarray or a 2-element sequence of the former. The
  499. first value is always interpreted as `imin` and the second, if supplied,
  500. as `imax`.
  501. x : ndarray
  502. The signal with `peaks`.
  503. peaks : ndarray
  504. An array with indices used to reduce `imin` and / or `imax` if those are
  505. arrays.
  506. Returns
  507. -------
  508. imin, imax : number or ndarray or None
  509. Minimal and maximal value in `argument`.
  510. Raises
  511. ------
  512. ValueError :
  513. If interval border is given as array and its size does not match the size
  514. of `x`.
  515. Notes
  516. -----
  517. .. versionadded:: 1.1.0
  518. """
  519. try:
  520. imin, imax = interval
  521. except (TypeError, ValueError):
  522. imin, imax = (interval, None)
  523. # Reduce arrays if arrays
  524. if isinstance(imin, np.ndarray):
  525. if imin.size != x.size:
  526. raise ValueError('array size of lower interval border must match x')
  527. imin = imin[peaks]
  528. if isinstance(imax, np.ndarray):
  529. if imax.size != x.size:
  530. raise ValueError('array size of upper interval border must match x')
  531. imax = imax[peaks]
  532. return imin, imax
  533. def _select_by_property(peak_properties, pmin, pmax):
  534. """
  535. Evaluate where the generic property of peaks confirms to an interval.
  536. Parameters
  537. ----------
  538. peak_properties : ndarray
  539. An array with properties for each peak.
  540. pmin : None or number or ndarray
  541. Lower interval boundary for `peak_properties`. ``None`` is interpreted as
  542. an open border.
  543. pmax : None or number or ndarray
  544. Upper interval boundary for `peak_properties`. ``None`` is interpreted as
  545. an open border.
  546. Returns
  547. -------
  548. keep : bool
  549. A boolean mask evaluating to true where `peak_properties` confirms to the
  550. interval.
  551. See Also
  552. --------
  553. find_peaks
  554. Notes
  555. -----
  556. .. versionadded:: 1.1.0
  557. """
  558. keep = np.ones(peak_properties.size, dtype=bool)
  559. if pmin is not None:
  560. keep &= (pmin <= peak_properties)
  561. if pmax is not None:
  562. keep &= (peak_properties <= pmax)
  563. return keep
  564. def _select_by_peak_threshold(x, peaks, tmin, tmax):
  565. """
  566. Evaluate which peaks fulfill the threshold condition.
  567. Parameters
  568. ----------
  569. x : ndarray
  570. A one-dimensional array which is indexable by `peaks`.
  571. peaks : ndarray
  572. Indices of peaks in `x`.
  573. tmin, tmax : scalar or ndarray or None
  574. Minimal and / or maximal required thresholds. If supplied as ndarrays
  575. their size must match `peaks`. ``None`` is interpreted as an open
  576. border.
  577. Returns
  578. -------
  579. keep : bool
  580. A boolean mask evaluating to true where `peaks` fulfill the threshold
  581. condition.
  582. left_thresholds, right_thresholds : ndarray
  583. Array matching `peak` containing the thresholds of each peak on
  584. both sides.
  585. Notes
  586. -----
  587. .. versionadded:: 1.1.0
  588. """
  589. # Stack thresholds on both sides to make min / max operations easier:
  590. # tmin is compared with the smaller, and tmax with the greater thresold to
  591. # each peak's side
  592. stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1],
  593. x[peaks] - x[peaks + 1]])
  594. keep = np.ones(peaks.size, dtype=bool)
  595. if tmin is not None:
  596. min_thresholds = np.min(stacked_thresholds, axis=0)
  597. keep &= (tmin <= min_thresholds)
  598. if tmax is not None:
  599. max_thresholds = np.max(stacked_thresholds, axis=0)
  600. keep &= (max_thresholds <= tmax)
  601. return keep, stacked_thresholds[0], stacked_thresholds[1]
  602. def find_peaks(x, height=None, threshold=None, distance=None,
  603. prominence=None, width=None, wlen=None, rel_height=0.5,
  604. plateau_size=None):
  605. """
  606. Find peaks inside a signal based on peak properties.
  607. This function takes a one-dimensional array and finds all local maxima by
  608. simple comparison of neighbouring values. Optionally, a subset of these
  609. peaks can be selected by specifying conditions for a peak's properties.
  610. Parameters
  611. ----------
  612. x : sequence
  613. A signal with peaks.
  614. height : number or ndarray or sequence, optional
  615. Required height of peaks. Either a number, ``None``, an array matching
  616. `x` or a 2-element sequence of the former. The first element is
  617. always interpreted as the minimal and the second, if supplied, as the
  618. maximal required height.
  619. threshold : number or ndarray or sequence, optional
  620. Required threshold of peaks, the vertical distance to its neighbouring
  621. samples. Either a number, ``None``, an array matching `x` or a
  622. 2-element sequence of the former. The first element is always
  623. interpreted as the minimal and the second, if supplied, as the maximal
  624. required threshold.
  625. distance : number, optional
  626. Required minimal horizontal distance (>= 1) in samples between
  627. neighbouring peaks. The removal order is explained in the notes section.
  628. prominence : number or ndarray or sequence, optional
  629. Required prominence of peaks. Either a number, ``None``, an array
  630. matching `x` or a 2-element sequence of the former. The first
  631. element is always interpreted as the minimal and the second, if
  632. supplied, as the maximal required prominence.
  633. width : number or ndarray or sequence, optional
  634. Required width of peaks in samples. Either a number, ``None``, an array
  635. matching `x` or a 2-element sequence of the former. The first
  636. element is always interpreted as the minimal and the second, if
  637. supplied, as the maximal required prominence.
  638. wlen : int, optional
  639. Used for calculation of the peaks prominences, thus it is only used if
  640. one of the arguments `prominence` or `width` is given. See argument
  641. `wlen` in `peak_prominences` for a full description of its effects.
  642. rel_height : float, optional
  643. Used for calculation of the peaks width, thus it is only used if `width`
  644. is given. See argument `rel_height` in `peak_widths` for a full
  645. description of its effects.
  646. plateau_size : number or ndarray or sequence, optional
  647. Required size of the flat top of peaks in samples. Either a number,
  648. ``None``, an array matching `x` or a 2-element sequence of the former.
  649. The first element is always interpreted as the minimal and the second,
  650. if supplied as the maximal required plateau size.
  651. .. versionadded:: 1.2.0
  652. Returns
  653. -------
  654. peaks : ndarray
  655. Indices of peaks in `x` that satisfy all given conditions.
  656. properties : dict
  657. A dictionary containing properties of the returned peaks which were
  658. calculated as intermediate results during evaluation of the specified
  659. conditions:
  660. * 'peak_heights'
  661. If `height` is given, the height of each peak in `x`.
  662. * 'left_thresholds', 'right_thresholds'
  663. If `threshold` is given, these keys contain a peaks vertical
  664. distance to its neighbouring samples.
  665. * 'prominences', 'right_bases', 'left_bases'
  666. If `prominence` is given, these keys are accessible. See
  667. `peak_prominences` for a description of their content.
  668. * 'width_heights', 'left_ips', 'right_ips'
  669. If `width` is given, these keys are accessible. See `peak_widths`
  670. for a description of their content.
  671. * 'plateau_sizes', left_edges', 'right_edges'
  672. If `plateau_size` is given, these keys are accessible and contain
  673. the indices of a peak's edges (edges are still part of the
  674. plateau) and the calculated plateau sizes.
  675. .. versionadded:: 1.2.0
  676. To calculate and return properties without excluding peaks, provide the
  677. open interval ``(None, None)`` as a value to the appropriate argument
  678. (excluding `distance`).
  679. Warns
  680. -----
  681. PeakPropertyWarning
  682. Raised if a peak's properties have unexpected values (see
  683. `peak_prominences` and `peak_widths`).
  684. Warnings
  685. --------
  686. This function may return unexpected results for data containing NaNs. To
  687. avoid this, NaNs should either be removed or replaced.
  688. See Also
  689. --------
  690. find_peaks_cwt
  691. Find peaks using the wavelet transformation.
  692. peak_prominences
  693. Directly calculate the prominence of peaks.
  694. peak_widths
  695. Directly calculate the width of peaks.
  696. Notes
  697. -----
  698. In the context of this function, a peak or local maximum is defined as any
  699. sample whose two direct neighbours have a smaller amplitude. For flat peaks
  700. (more than one sample of equal amplitude wide) the index of the middle
  701. sample is returned (rounded down in case the number of samples is even).
  702. For noisy signals the peak locations can be off because the noise might
  703. change the position of local maxima. In those cases consider smoothing the
  704. signal before searching for peaks or use other peak finding and fitting
  705. methods (like `find_peaks_cwt`).
  706. Some additional comments on specifying conditions:
  707. * Almost all conditions (excluding `distance`) can be given as half-open or
  708. closed intervals, e.g ``1`` or ``(1, None)`` defines the half-open
  709. interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval
  710. :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified
  711. as well, which returns the matching properties without exclusion of peaks.
  712. * The border is always included in the interval used to select valid peaks.
  713. * For several conditions the interval borders can be specified with
  714. arrays matching `x` in shape which enables dynamic constrains based on
  715. the sample position.
  716. * The conditions are evaluated in the following order: `plateau_size`,
  717. `height`, `threshold`, `distance`, `prominence`, `width`. In most cases
  718. this order is the fastest one because faster operations are applied first
  719. to reduce the number of peaks that need to be evaluated later.
  720. * Satisfying the distance condition is accomplished by iterating over all
  721. peaks in descending order based on their height and removing all lower
  722. peaks that are too close.
  723. * Use `wlen` to reduce the time it takes to evaluate the conditions for
  724. `prominence` or `width` if `x` is large or has many local maxima
  725. (see `peak_prominences`).
  726. .. versionadded:: 1.1.0
  727. Examples
  728. --------
  729. To demonstrate this function's usage we use a signal `x` supplied with
  730. SciPy (see `scipy.misc.electrocardiogram`). Let's find all peaks (local
  731. maxima) in `x` whose amplitude lies above 0.
  732. >>> import matplotlib.pyplot as plt
  733. >>> from scipy.misc import electrocardiogram
  734. >>> from scipy.signal import find_peaks
  735. >>> x = electrocardiogram()[2000:4000]
  736. >>> peaks, _ = find_peaks(x, height=0)
  737. >>> plt.plot(x)
  738. >>> plt.plot(peaks, x[peaks], "x")
  739. >>> plt.plot(np.zeros_like(x), "--", color="gray")
  740. >>> plt.show()
  741. We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching
  742. `x` in size to reflect a changing condition for different parts of the
  743. signal.
  744. >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size))
  745. >>> peaks, _ = find_peaks(x, height=(-border, border))
  746. >>> plt.plot(x)
  747. >>> plt.plot(-border, "--", color="gray")
  748. >>> plt.plot(border, ":", color="gray")
  749. >>> plt.plot(peaks, x[peaks], "x")
  750. >>> plt.show()
  751. Another useful condition for periodic signals can be given with the
  752. `distance` argument. In this case we can easily select the positions of
  753. QRS complexes within the electrocardiogram (ECG) by demanding a distance of
  754. at least 150 samples.
  755. >>> peaks, _ = find_peaks(x, distance=150)
  756. >>> np.diff(peaks)
  757. array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172])
  758. >>> plt.plot(x)
  759. >>> plt.plot(peaks, x[peaks], "x")
  760. >>> plt.show()
  761. Especially for noisy signals peaks can be easily grouped by their
  762. prominence (see `peak_prominences`). E.g. we can select all peaks except
  763. for the mentioned QRS complexes by limiting the allowed prominenence to 0.6.
  764. >>> peaks, properties = find_peaks(x, prominence=(None, 0.6))
  765. >>> properties["prominences"].max()
  766. 0.5049999999999999
  767. >>> plt.plot(x)
  768. >>> plt.plot(peaks, x[peaks], "x")
  769. >>> plt.show()
  770. And finally let's examine a different section of the ECG which contains
  771. beat forms of different shape. To select only the atypical heart beats we
  772. combine two conditions: a minimal prominence of 1 and width of at least 20
  773. samples.
  774. >>> x = electrocardiogram()[17000:18000]
  775. >>> peaks, properties = find_peaks(x, prominence=1, width=20)
  776. >>> properties["prominences"], properties["widths"]
  777. (array([1.495, 2.3 ]), array([36.93773946, 39.32723577]))
  778. >>> plt.plot(x)
  779. >>> plt.plot(peaks, x[peaks], "x")
  780. >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"],
  781. ... ymax = x[peaks], color = "C1")
  782. >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"],
  783. ... xmax=properties["right_ips"], color = "C1")
  784. >>> plt.show()
  785. """
  786. # _argmaxima1d expects array of dtype 'float64'
  787. x = _arg_x_as_expected(x)
  788. if distance is not None and distance < 1:
  789. raise ValueError('`distance` must be greater or equal to 1')
  790. peaks, left_edges, right_edges = _local_maxima_1d(x)
  791. properties = {}
  792. if plateau_size is not None:
  793. # Evaluate plateau size
  794. plateau_sizes = right_edges - left_edges + 1
  795. pmin, pmax = _unpack_condition_args(plateau_size, x, peaks)
  796. keep = _select_by_property(plateau_sizes, pmin, pmax)
  797. peaks = peaks[keep]
  798. properties["plateau_sizes"] = plateau_sizes
  799. properties["left_edges"] = left_edges
  800. properties["right_edges"] = right_edges
  801. properties = {key: array[keep] for key, array in properties.items()}
  802. if height is not None:
  803. # Evaluate height condition
  804. peak_heights = x[peaks]
  805. hmin, hmax = _unpack_condition_args(height, x, peaks)
  806. keep = _select_by_property(peak_heights, hmin, hmax)
  807. peaks = peaks[keep]
  808. properties["peak_heights"] = peak_heights
  809. properties = {key: array[keep] for key, array in properties.items()}
  810. if threshold is not None:
  811. # Evaluate threshold condition
  812. tmin, tmax = _unpack_condition_args(threshold, x, peaks)
  813. keep, left_thresholds, right_thresholds = _select_by_peak_threshold(
  814. x, peaks, tmin, tmax)
  815. peaks = peaks[keep]
  816. properties["left_thresholds"] = left_thresholds
  817. properties["right_thresholds"] = right_thresholds
  818. properties = {key: array[keep] for key, array in properties.items()}
  819. if distance is not None:
  820. # Evaluate distance condition
  821. keep = _select_by_peak_distance(peaks, x[peaks], distance)
  822. peaks = peaks[keep]
  823. properties = {key: array[keep] for key, array in properties.items()}
  824. if prominence is not None or width is not None:
  825. # Calculate prominence (required for both conditions)
  826. wlen = _arg_wlen_as_expected(wlen)
  827. properties.update(zip(
  828. ['prominences', 'left_bases', 'right_bases'],
  829. _peak_prominences(x, peaks, wlen=wlen)
  830. ))
  831. if prominence is not None:
  832. # Evaluate prominence condition
  833. pmin, pmax = _unpack_condition_args(prominence, x, peaks)
  834. keep = _select_by_property(properties['prominences'], pmin, pmax)
  835. peaks = peaks[keep]
  836. properties = {key: array[keep] for key, array in properties.items()}
  837. if width is not None:
  838. # Calculate widths
  839. properties.update(zip(
  840. ['widths', 'width_heights', 'left_ips', 'right_ips'],
  841. _peak_widths(x, peaks, rel_height, properties['prominences'],
  842. properties['left_bases'], properties['right_bases'])
  843. ))
  844. # Evaluate width condition
  845. wmin, wmax = _unpack_condition_args(width, x, peaks)
  846. keep = _select_by_property(properties['widths'], wmin, wmax)
  847. peaks = peaks[keep]
  848. properties = {key: array[keep] for key, array in properties.items()}
  849. return peaks, properties
  850. def _identify_ridge_lines(matr, max_distances, gap_thresh):
  851. """
  852. Identify ridges in the 2-D matrix.
  853. Expect that the width of the wavelet feature increases with increasing row
  854. number.
  855. Parameters
  856. ----------
  857. matr : 2-D ndarray
  858. Matrix in which to identify ridge lines.
  859. max_distances : 1-D sequence
  860. At each row, a ridge line is only connected
  861. if the relative max at row[n] is within
  862. `max_distances`[n] from the relative max at row[n+1].
  863. gap_thresh : int
  864. If a relative maximum is not found within `max_distances`,
  865. there will be a gap. A ridge line is discontinued if
  866. there are more than `gap_thresh` points without connecting
  867. a new relative maximum.
  868. Returns
  869. -------
  870. ridge_lines : tuple
  871. Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the
  872. ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none
  873. found. Each ridge-line will be sorted by row (increasing), but the
  874. order of the ridge lines is not specified.
  875. References
  876. ----------
  877. Bioinformatics (2006) 22 (17): 2059-2065.
  878. :doi:`10.1093/bioinformatics/btl355`
  879. http://bioinformatics.oxfordjournals.org/content/22/17/2059.long
  880. Examples
  881. --------
  882. >>> data = np.random.rand(5,5)
  883. >>> ridge_lines = _identify_ridge_lines(data, 1, 1)
  884. Notes
  885. -----
  886. This function is intended to be used in conjunction with `cwt`
  887. as part of `find_peaks_cwt`.
  888. """
  889. if(len(max_distances) < matr.shape[0]):
  890. raise ValueError('Max_distances must have at least as many rows '
  891. 'as matr')
  892. all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1)
  893. # Highest row for which there are any relative maxima
  894. has_relmax = np.nonzero(all_max_cols.any(axis=1))[0]
  895. if(len(has_relmax) == 0):
  896. return []
  897. start_row = has_relmax[-1]
  898. # Each ridge line is a 3-tuple:
  899. # rows, cols,Gap number
  900. ridge_lines = [[[start_row],
  901. [col],
  902. 0] for col in np.nonzero(all_max_cols[start_row])[0]]
  903. final_lines = []
  904. rows = np.arange(start_row - 1, -1, -1)
  905. cols = np.arange(0, matr.shape[1])
  906. for row in rows:
  907. this_max_cols = cols[all_max_cols[row]]
  908. # Increment gap number of each line,
  909. # set it to zero later if appropriate
  910. for line in ridge_lines:
  911. line[2] += 1
  912. # XXX These should always be all_max_cols[row]
  913. # But the order might be different. Might be an efficiency gain
  914. # to make sure the order is the same and avoid this iteration
  915. prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines])
  916. # Look through every relative maximum found at current row
  917. # Attempt to connect them with existing ridge lines.
  918. for ind, col in enumerate(this_max_cols):
  919. # If there is a previous ridge line within
  920. # the max_distance to connect to, do so.
  921. # Otherwise start a new one.
  922. line = None
  923. if(len(prev_ridge_cols) > 0):
  924. diffs = np.abs(col - prev_ridge_cols)
  925. closest = np.argmin(diffs)
  926. if diffs[closest] <= max_distances[row]:
  927. line = ridge_lines[closest]
  928. if(line is not None):
  929. # Found a point close enough, extend current ridge line
  930. line[1].append(col)
  931. line[0].append(row)
  932. line[2] = 0
  933. else:
  934. new_line = [[row],
  935. [col],
  936. 0]
  937. ridge_lines.append(new_line)
  938. # Remove the ridge lines with gap_number too high
  939. # XXX Modifying a list while iterating over it.
  940. # Should be safe, since we iterate backwards, but
  941. # still tacky.
  942. for ind in xrange(len(ridge_lines) - 1, -1, -1):
  943. line = ridge_lines[ind]
  944. if line[2] > gap_thresh:
  945. final_lines.append(line)
  946. del ridge_lines[ind]
  947. out_lines = []
  948. for line in (final_lines + ridge_lines):
  949. sortargs = np.array(np.argsort(line[0]))
  950. rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs)
  951. rows[sortargs] = line[0]
  952. cols[sortargs] = line[1]
  953. out_lines.append([rows, cols])
  954. return out_lines
  955. def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None,
  956. min_snr=1, noise_perc=10):
  957. """
  958. Filter ridge lines according to prescribed criteria. Intended
  959. to be used for finding relative maxima.
  960. Parameters
  961. ----------
  962. cwt : 2-D ndarray
  963. Continuous wavelet transform from which the `ridge_lines` were defined.
  964. ridge_lines : 1-D sequence
  965. Each element should contain 2 sequences, the rows and columns
  966. of the ridge line (respectively).
  967. window_size : int, optional
  968. Size of window to use to calculate noise floor.
  969. Default is ``cwt.shape[1] / 20``.
  970. min_length : int, optional
  971. Minimum length a ridge line needs to be acceptable.
  972. Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
  973. min_snr : float, optional
  974. Minimum SNR ratio. Default 1. The signal is the value of
  975. the cwt matrix at the shortest length scale (``cwt[0, loc]``), the
  976. noise is the `noise_perc`th percentile of datapoints contained within a
  977. window of `window_size` around ``cwt[0, loc]``.
  978. noise_perc : float, optional
  979. When calculating the noise floor, percentile of data points
  980. examined below which to consider noise. Calculated using
  981. scipy.stats.scoreatpercentile.
  982. References
  983. ----------
  984. Bioinformatics (2006) 22 (17): 2059-2065. :doi:`10.1093/bioinformatics/btl355`
  985. http://bioinformatics.oxfordjournals.org/content/22/17/2059.long
  986. """
  987. num_points = cwt.shape[1]
  988. if min_length is None:
  989. min_length = np.ceil(cwt.shape[0] / 4)
  990. if window_size is None:
  991. window_size = np.ceil(num_points / 20)
  992. window_size = int(window_size)
  993. hf_window, odd = divmod(window_size, 2)
  994. # Filter based on SNR
  995. row_one = cwt[0, :]
  996. noises = np.zeros_like(row_one)
  997. for ind, val in enumerate(row_one):
  998. window_start = max(ind - hf_window, 0)
  999. window_end = min(ind + hf_window + odd, num_points)
  1000. noises[ind] = scoreatpercentile(row_one[window_start:window_end],
  1001. per=noise_perc)
  1002. def filt_func(line):
  1003. if len(line[0]) < min_length:
  1004. return False
  1005. snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]])
  1006. if snr < min_snr:
  1007. return False
  1008. return True
  1009. return list(filter(filt_func, ridge_lines))
  1010. def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,
  1011. gap_thresh=None, min_length=None, min_snr=1, noise_perc=10):
  1012. """
  1013. Find peaks in a 1-D array with wavelet transformation.
  1014. The general approach is to smooth `vector` by convolving it with
  1015. `wavelet(width)` for each width in `widths`. Relative maxima which
  1016. appear at enough length scales, and with sufficiently high SNR, are
  1017. accepted.
  1018. Parameters
  1019. ----------
  1020. vector : ndarray
  1021. 1-D array in which to find the peaks.
  1022. widths : sequence
  1023. 1-D array of widths to use for calculating the CWT matrix. In general,
  1024. this range should cover the expected width of peaks of interest.
  1025. wavelet : callable, optional
  1026. Should take two parameters and return a 1-D array to convolve
  1027. with `vector`. The first parameter determines the number of points
  1028. of the returned wavelet array, the second parameter is the scale
  1029. (`width`) of the wavelet. Should be normalized and symmetric.
  1030. Default is the ricker wavelet.
  1031. max_distances : ndarray, optional
  1032. At each row, a ridge line is only connected if the relative max at
  1033. row[n] is within ``max_distances[n]`` from the relative max at
  1034. ``row[n+1]``. Default value is ``widths/4``.
  1035. gap_thresh : float, optional
  1036. If a relative maximum is not found within `max_distances`,
  1037. there will be a gap. A ridge line is discontinued if there are more
  1038. than `gap_thresh` points without connecting a new relative maximum.
  1039. Default is the first value of the widths array i.e. widths[0].
  1040. min_length : int, optional
  1041. Minimum length a ridge line needs to be acceptable.
  1042. Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
  1043. min_snr : float, optional
  1044. Minimum SNR ratio. Default 1. The signal is the value of
  1045. the cwt matrix at the shortest length scale (``cwt[0, loc]``), the
  1046. noise is the `noise_perc`th percentile of datapoints contained within a
  1047. window of `window_size` around ``cwt[0, loc]``.
  1048. noise_perc : float, optional
  1049. When calculating the noise floor, percentile of data points
  1050. examined below which to consider noise. Calculated using
  1051. `stats.scoreatpercentile`. Default is 10.
  1052. Returns
  1053. -------
  1054. peaks_indices : ndarray
  1055. Indices of the locations in the `vector` where peaks were found.
  1056. The list is sorted.
  1057. See Also
  1058. --------
  1059. cwt
  1060. Continuous wavelet transform.
  1061. find_peaks
  1062. Find peaks inside a signal based on peak properties.
  1063. Notes
  1064. -----
  1065. This approach was designed for finding sharp peaks among noisy data,
  1066. however with proper parameter selection it should function well for
  1067. different peak shapes.
  1068. The algorithm is as follows:
  1069. 1. Perform a continuous wavelet transform on `vector`, for the supplied
  1070. `widths`. This is a convolution of `vector` with `wavelet(width)` for
  1071. each width in `widths`. See `cwt`
  1072. 2. Identify "ridge lines" in the cwt matrix. These are relative maxima
  1073. at each row, connected across adjacent rows. See identify_ridge_lines
  1074. 3. Filter the ridge_lines using filter_ridge_lines.
  1075. .. versionadded:: 0.11.0
  1076. References
  1077. ----------
  1078. .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
  1079. :doi:`10.1093/bioinformatics/btl355`
  1080. http://bioinformatics.oxfordjournals.org/content/22/17/2059.long
  1081. Examples
  1082. --------
  1083. >>> from scipy import signal
  1084. >>> xs = np.arange(0, np.pi, 0.05)
  1085. >>> data = np.sin(xs)
  1086. >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10))
  1087. >>> peakind, xs[peakind], data[peakind]
  1088. ([32], array([ 1.6]), array([ 0.9995736]))
  1089. """
  1090. widths = np.asarray(widths)
  1091. if gap_thresh is None:
  1092. gap_thresh = np.ceil(widths[0])
  1093. if max_distances is None:
  1094. max_distances = widths / 4.0
  1095. if wavelet is None:
  1096. wavelet = ricker
  1097. cwt_dat = cwt(vector, wavelet, widths)
  1098. ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh)
  1099. filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length,
  1100. min_snr=min_snr, noise_perc=noise_perc)
  1101. max_locs = np.asarray([x[1][0] for x in filtered])
  1102. max_locs.sort()
  1103. return max_locs