mlab.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. """
  2. Numerical python functions written for compatibility with MATLAB
  3. commands with the same names. Most numerical python functions can be found in
  4. the `numpy` and `scipy` libraries. What remains here is code for performing
  5. spectral computations.
  6. Spectral functions
  7. -------------------
  8. `cohere`
  9. Coherence (normalized cross spectral density)
  10. `csd`
  11. Cross spectral density using Welch's average periodogram
  12. `detrend`
  13. Remove the mean or best fit line from an array
  14. `psd`
  15. Power spectral density using Welch's average periodogram
  16. `specgram`
  17. Spectrogram (spectrum over segments of time)
  18. `complex_spectrum`
  19. Return the complex-valued frequency spectrum of a signal
  20. `magnitude_spectrum`
  21. Return the magnitude of the frequency spectrum of a signal
  22. `angle_spectrum`
  23. Return the angle (wrapped phase) of the frequency spectrum of a signal
  24. `phase_spectrum`
  25. Return the phase (unwrapped angle) of the frequency spectrum of a signal
  26. `detrend_mean`
  27. Remove the mean from a line.
  28. `detrend_linear`
  29. Remove the best fit line from a line.
  30. `detrend_none`
  31. Return the original line.
  32. `stride_windows`
  33. Get all windows in an array in a memory-efficient manner
  34. `stride_repeat`
  35. Repeat an array in a memory-efficient manner
  36. `apply_window`
  37. Apply a window along a given axis
  38. """
  39. import csv
  40. import inspect
  41. from numbers import Number
  42. import numpy as np
  43. import matplotlib.cbook as cbook
  44. from matplotlib import docstring
  45. def window_hanning(x):
  46. '''
  47. Return x times the hanning window of len(x).
  48. See Also
  49. --------
  50. window_none : Another window algorithm.
  51. '''
  52. return np.hanning(len(x))*x
  53. def window_none(x):
  54. '''
  55. No window function; simply return x.
  56. See Also
  57. --------
  58. window_hanning : Another window algorithm.
  59. '''
  60. return x
  61. @cbook.deprecated("3.2")
  62. def apply_window(x, window, axis=0, return_window=None):
  63. '''
  64. Apply the given window to the given 1D or 2D array along the given axis.
  65. Parameters
  66. ----------
  67. x : 1D or 2D array or sequence
  68. Array or sequence containing the data.
  69. window : function or array.
  70. Either a function to generate a window or an array with length
  71. *x*.shape[*axis*]
  72. axis : integer
  73. The axis over which to do the repetition.
  74. Must be 0 or 1. The default is 0
  75. return_window : bool
  76. If true, also return the 1D values of the window that was applied
  77. '''
  78. x = np.asarray(x)
  79. if x.ndim < 1 or x.ndim > 2:
  80. raise ValueError('only 1D or 2D arrays can be used')
  81. if axis+1 > x.ndim:
  82. raise ValueError('axis(=%s) out of bounds' % axis)
  83. xshape = list(x.shape)
  84. xshapetarg = xshape.pop(axis)
  85. if np.iterable(window):
  86. if len(window) != xshapetarg:
  87. raise ValueError('The len(window) must be the same as the shape '
  88. 'of x for the chosen axis')
  89. windowVals = window
  90. else:
  91. windowVals = window(np.ones(xshapetarg, dtype=x.dtype))
  92. if x.ndim == 1:
  93. if return_window:
  94. return windowVals * x, windowVals
  95. else:
  96. return windowVals * x
  97. xshapeother = xshape.pop()
  98. otheraxis = (axis+1) % 2
  99. windowValsRep = stride_repeat(windowVals, xshapeother, axis=otheraxis)
  100. if return_window:
  101. return windowValsRep * x, windowVals
  102. else:
  103. return windowValsRep * x
  104. def detrend(x, key=None, axis=None):
  105. '''
  106. Return x with its trend removed.
  107. Parameters
  108. ----------
  109. x : array or sequence
  110. Array or sequence containing the data.
  111. key : {'default', 'constant', 'mean', 'linear', 'none'} or function
  112. Specifies the detrend algorithm to use. 'default' is 'mean', which is
  113. the same as `detrend_mean`. 'constant' is the same. 'linear' is
  114. the same as `detrend_linear`. 'none' is the same as
  115. `detrend_none`. The default is 'mean'. See the corresponding
  116. functions for more details regarding the algorithms. Can also be a
  117. function that carries out the detrend operation.
  118. axis : integer
  119. The axis along which to do the detrending.
  120. See Also
  121. --------
  122. detrend_mean : Implementation of the 'mean' algorithm.
  123. detrend_linear : Implementation of the 'linear' algorithm.
  124. detrend_none : Implementation of the 'none' algorithm.
  125. '''
  126. if key is None or key in ['constant', 'mean', 'default']:
  127. return detrend(x, key=detrend_mean, axis=axis)
  128. elif key == 'linear':
  129. return detrend(x, key=detrend_linear, axis=axis)
  130. elif key == 'none':
  131. return detrend(x, key=detrend_none, axis=axis)
  132. elif callable(key):
  133. x = np.asarray(x)
  134. if axis is not None and axis + 1 > x.ndim:
  135. raise ValueError(f'axis(={axis}) out of bounds')
  136. if (axis is None and x.ndim == 0) or (not axis and x.ndim == 1):
  137. return key(x)
  138. # try to use the 'axis' argument if the function supports it,
  139. # otherwise use apply_along_axis to do it
  140. try:
  141. return key(x, axis=axis)
  142. except TypeError:
  143. return np.apply_along_axis(key, axis=axis, arr=x)
  144. else:
  145. raise ValueError(
  146. f"Unknown value for key: {key!r}, must be one of: 'default', "
  147. f"'constant', 'mean', 'linear', or a function")
  148. @cbook.deprecated("3.1", alternative="detrend_mean")
  149. def demean(x, axis=0):
  150. '''
  151. Return x minus its mean along the specified axis.
  152. Parameters
  153. ----------
  154. x : array or sequence
  155. Array or sequence containing the data
  156. Can have any dimensionality
  157. axis : integer
  158. The axis along which to take the mean. See numpy.mean for a
  159. description of this argument.
  160. See Also
  161. --------
  162. detrend_mean : Same as `demean` except for the default *axis*.
  163. '''
  164. return detrend_mean(x, axis=axis)
  165. def detrend_mean(x, axis=None):
  166. '''
  167. Return x minus the mean(x).
  168. Parameters
  169. ----------
  170. x : array or sequence
  171. Array or sequence containing the data
  172. Can have any dimensionality
  173. axis : integer
  174. The axis along which to take the mean. See numpy.mean for a
  175. description of this argument.
  176. See Also
  177. --------
  178. detrend_linear : Another detrend algorithm.
  179. detrend_none : Another detrend algorithm.
  180. detrend : A wrapper around all the detrend algorithms.
  181. '''
  182. x = np.asarray(x)
  183. if axis is not None and axis+1 > x.ndim:
  184. raise ValueError('axis(=%s) out of bounds' % axis)
  185. return x - x.mean(axis, keepdims=True)
  186. def detrend_none(x, axis=None):
  187. '''
  188. Return x: no detrending.
  189. Parameters
  190. ----------
  191. x : any object
  192. An object containing the data
  193. axis : integer
  194. This parameter is ignored.
  195. It is included for compatibility with detrend_mean
  196. See Also
  197. --------
  198. detrend_mean : Another detrend algorithm.
  199. detrend_linear : Another detrend algorithm.
  200. detrend : A wrapper around all the detrend algorithms.
  201. '''
  202. return x
  203. def detrend_linear(y):
  204. '''
  205. Return x minus best fit line; 'linear' detrending.
  206. Parameters
  207. ----------
  208. y : 0-D or 1-D array or sequence
  209. Array or sequence containing the data
  210. axis : integer
  211. The axis along which to take the mean. See numpy.mean for a
  212. description of this argument.
  213. See Also
  214. --------
  215. detrend_mean : Another detrend algorithm.
  216. detrend_none : Another detrend algorithm.
  217. detrend : A wrapper around all the detrend algorithms.
  218. '''
  219. # This is faster than an algorithm based on linalg.lstsq.
  220. y = np.asarray(y)
  221. if y.ndim > 1:
  222. raise ValueError('y cannot have ndim > 1')
  223. # short-circuit 0-D array.
  224. if not y.ndim:
  225. return np.array(0., dtype=y.dtype)
  226. x = np.arange(y.size, dtype=float)
  227. C = np.cov(x, y, bias=1)
  228. b = C[0, 1]/C[0, 0]
  229. a = y.mean() - b*x.mean()
  230. return y - (b*x + a)
  231. def stride_windows(x, n, noverlap=None, axis=0):
  232. '''
  233. Get all windows of x with length n as a single array,
  234. using strides to avoid data duplication.
  235. .. warning::
  236. It is not safe to write to the output array. Multiple
  237. elements may point to the same piece of memory,
  238. so modifying one value may change others.
  239. Parameters
  240. ----------
  241. x : 1D array or sequence
  242. Array or sequence containing the data.
  243. n : integer
  244. The number of data points in each window.
  245. noverlap : integer
  246. The overlap between adjacent windows.
  247. Default is 0 (no overlap)
  248. axis : integer
  249. The axis along which the windows will run.
  250. References
  251. ----------
  252. `stackoverflow: Rolling window for 1D arrays in Numpy?
  253. <http://stackoverflow.com/a/6811241>`_
  254. `stackoverflow: Using strides for an efficient moving average filter
  255. <http://stackoverflow.com/a/4947453>`_
  256. '''
  257. if noverlap is None:
  258. noverlap = 0
  259. if noverlap >= n:
  260. raise ValueError('noverlap must be less than n')
  261. if n < 1:
  262. raise ValueError('n cannot be less than 1')
  263. x = np.asarray(x)
  264. if x.ndim != 1:
  265. raise ValueError('only 1-dimensional arrays can be used')
  266. if n == 1 and noverlap == 0:
  267. if axis == 0:
  268. return x[np.newaxis]
  269. else:
  270. return x[np.newaxis].transpose()
  271. if n > x.size:
  272. raise ValueError('n cannot be greater than the length of x')
  273. # np.lib.stride_tricks.as_strided easily leads to memory corruption for
  274. # non integer shape and strides, i.e. noverlap or n. See #3845.
  275. noverlap = int(noverlap)
  276. n = int(n)
  277. step = n - noverlap
  278. if axis == 0:
  279. shape = (n, (x.shape[-1]-noverlap)//step)
  280. strides = (x.strides[0], step*x.strides[0])
  281. else:
  282. shape = ((x.shape[-1]-noverlap)//step, n)
  283. strides = (step*x.strides[0], x.strides[0])
  284. return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
  285. @cbook.deprecated("3.2")
  286. def stride_repeat(x, n, axis=0):
  287. '''
  288. Repeat the values in an array in a memory-efficient manner. Array x is
  289. stacked vertically n times.
  290. .. warning::
  291. It is not safe to write to the output array. Multiple
  292. elements may point to the same piece of memory, so
  293. modifying one value may change others.
  294. Parameters
  295. ----------
  296. x : 1D array or sequence
  297. Array or sequence containing the data.
  298. n : integer
  299. The number of time to repeat the array.
  300. axis : integer
  301. The axis along which the data will run.
  302. References
  303. ----------
  304. `stackoverflow: Repeat NumPy array without replicating data?
  305. <http://stackoverflow.com/a/5568169>`_
  306. '''
  307. if axis not in [0, 1]:
  308. raise ValueError('axis must be 0 or 1')
  309. x = np.asarray(x)
  310. if x.ndim != 1:
  311. raise ValueError('only 1-dimensional arrays can be used')
  312. if n == 1:
  313. if axis == 0:
  314. return np.atleast_2d(x)
  315. else:
  316. return np.atleast_2d(x).T
  317. if n < 1:
  318. raise ValueError('n cannot be less than 1')
  319. # np.lib.stride_tricks.as_strided easily leads to memory corruption for
  320. # non integer shape and strides, i.e. n. See #3845.
  321. n = int(n)
  322. if axis == 0:
  323. shape = (n, x.size)
  324. strides = (0, x.strides[0])
  325. else:
  326. shape = (x.size, n)
  327. strides = (x.strides[0], 0)
  328. return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
  329. def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
  330. window=None, noverlap=None, pad_to=None,
  331. sides=None, scale_by_freq=None, mode=None):
  332. '''
  333. This is a helper function that implements the commonality between the
  334. psd, csd, spectrogram and complex, magnitude, angle, and phase spectrums.
  335. It is *NOT* meant to be used outside of mlab and may change at any time.
  336. '''
  337. if y is None:
  338. # if y is None use x for y
  339. same_data = True
  340. else:
  341. # The checks for if y is x are so that we can use the same function to
  342. # implement the core of psd(), csd(), and spectrogram() without doing
  343. # extra calculations. We return the unaveraged Pxy, freqs, and t.
  344. same_data = y is x
  345. if Fs is None:
  346. Fs = 2
  347. if noverlap is None:
  348. noverlap = 0
  349. if detrend_func is None:
  350. detrend_func = detrend_none
  351. if window is None:
  352. window = window_hanning
  353. # if NFFT is set to None use the whole signal
  354. if NFFT is None:
  355. NFFT = 256
  356. if mode is None or mode == 'default':
  357. mode = 'psd'
  358. cbook._check_in_list(
  359. ['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'],
  360. mode=mode)
  361. if not same_data and mode != 'psd':
  362. raise ValueError("x and y must be equal if mode is not 'psd'")
  363. # Make sure we're dealing with a numpy array. If y and x were the same
  364. # object to start with, keep them that way
  365. x = np.asarray(x)
  366. if not same_data:
  367. y = np.asarray(y)
  368. if sides is None or sides == 'default':
  369. if np.iscomplexobj(x):
  370. sides = 'twosided'
  371. else:
  372. sides = 'onesided'
  373. cbook._check_in_list(['default', 'onesided', 'twosided'], sides=sides)
  374. # zero pad x and y up to NFFT if they are shorter than NFFT
  375. if len(x) < NFFT:
  376. n = len(x)
  377. x = np.resize(x, NFFT)
  378. x[n:] = 0
  379. if not same_data and len(y) < NFFT:
  380. n = len(y)
  381. y = np.resize(y, NFFT)
  382. y[n:] = 0
  383. if pad_to is None:
  384. pad_to = NFFT
  385. if mode != 'psd':
  386. scale_by_freq = False
  387. elif scale_by_freq is None:
  388. scale_by_freq = True
  389. # For real x, ignore the negative frequencies unless told otherwise
  390. if sides == 'twosided':
  391. numFreqs = pad_to
  392. if pad_to % 2:
  393. freqcenter = (pad_to - 1)//2 + 1
  394. else:
  395. freqcenter = pad_to//2
  396. scaling_factor = 1.
  397. elif sides == 'onesided':
  398. if pad_to % 2:
  399. numFreqs = (pad_to + 1)//2
  400. else:
  401. numFreqs = pad_to//2 + 1
  402. scaling_factor = 2.
  403. if not np.iterable(window):
  404. window = window(np.ones(NFFT, x.dtype))
  405. if len(window) != NFFT:
  406. raise ValueError(
  407. "The window length must match the data's first dimension")
  408. result = stride_windows(x, NFFT, noverlap, axis=0)
  409. result = detrend(result, detrend_func, axis=0)
  410. result = result * window.reshape((-1, 1))
  411. result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :]
  412. freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
  413. if not same_data:
  414. # if same_data is False, mode must be 'psd'
  415. resultY = stride_windows(y, NFFT, noverlap)
  416. resultY = detrend(resultY, detrend_func, axis=0)
  417. resultY = resultY * window.reshape((-1, 1))
  418. resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :]
  419. result = np.conj(result) * resultY
  420. elif mode == 'psd':
  421. result = np.conj(result) * result
  422. elif mode == 'magnitude':
  423. result = np.abs(result) / np.abs(window).sum()
  424. elif mode == 'angle' or mode == 'phase':
  425. # we unwrap the phase later to handle the onesided vs. twosided case
  426. result = np.angle(result)
  427. elif mode == 'complex':
  428. result /= np.abs(window).sum()
  429. if mode == 'psd':
  430. # Also include scaling factors for one-sided densities and dividing by
  431. # the sampling frequency, if desired. Scale everything, except the DC
  432. # component and the NFFT/2 component:
  433. # if we have a even number of frequencies, don't scale NFFT/2
  434. if not NFFT % 2:
  435. slc = slice(1, -1, None)
  436. # if we have an odd number, just don't scale DC
  437. else:
  438. slc = slice(1, None, None)
  439. result[slc] *= scaling_factor
  440. # MATLAB divides by the sampling frequency so that density function
  441. # has units of dB/Hz and can be integrated by the plotted frequency
  442. # values. Perform the same scaling here.
  443. if scale_by_freq:
  444. result /= Fs
  445. # Scale the spectrum by the norm of the window to compensate for
  446. # windowing loss; see Bendat & Piersol Sec 11.5.2.
  447. result /= (np.abs(window)**2).sum()
  448. else:
  449. # In this case, preserve power in the segment, not amplitude
  450. result /= np.abs(window).sum()**2
  451. t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
  452. if sides == 'twosided':
  453. # center the frequency range at zero
  454. freqs = np.concatenate((freqs[freqcenter:], freqs[:freqcenter]))
  455. result = np.concatenate((result[freqcenter:, :],
  456. result[:freqcenter, :]), 0)
  457. elif not pad_to % 2:
  458. # get the last value correctly, it is negative otherwise
  459. freqs[-1] *= -1
  460. # we unwrap the phase here to handle the onesided vs. twosided case
  461. if mode == 'phase':
  462. result = np.unwrap(result, axis=0)
  463. return result, freqs, t
  464. def _single_spectrum_helper(x, mode, Fs=None, window=None, pad_to=None,
  465. sides=None):
  466. '''
  467. This is a helper function that implements the commonality between the
  468. complex, magnitude, angle, and phase spectrums.
  469. It is *NOT* meant to be used outside of mlab and may change at any time.
  470. '''
  471. cbook._check_in_list(['complex', 'magnitude', 'angle', 'phase'], mode=mode)
  472. if pad_to is None:
  473. pad_to = len(x)
  474. spec, freqs, _ = _spectral_helper(x=x, y=None, NFFT=len(x), Fs=Fs,
  475. detrend_func=detrend_none, window=window,
  476. noverlap=0, pad_to=pad_to,
  477. sides=sides,
  478. scale_by_freq=False,
  479. mode=mode)
  480. if mode != 'complex':
  481. spec = spec.real
  482. if spec.ndim == 2 and spec.shape[1] == 1:
  483. spec = spec[:, 0]
  484. return spec, freqs
  485. # Split out these keyword docs so that they can be used elsewhere
  486. docstring.interpd.update(Spectral=inspect.cleandoc("""
  487. Fs : scalar
  488. The sampling frequency (samples per time unit). It is used
  489. to calculate the Fourier frequencies, freqs, in cycles per time
  490. unit. The default value is 2.
  491. window : callable or ndarray
  492. A function or a vector of length *NFFT*. To create window vectors see
  493. `window_hanning`, `window_none`, `numpy.blackman`, `numpy.hamming`,
  494. `numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc. The
  495. default is `window_hanning`. If a function is passed as the argument,
  496. it must take a data segment as an argument and return the windowed
  497. version of the segment.
  498. sides : {'default', 'onesided', 'twosided'}
  499. Specifies which sides of the spectrum to return. Default gives the
  500. default behavior, which returns one-sided for real data and both
  501. for complex data. 'onesided' forces the return of a one-sided
  502. spectrum, while 'twosided' forces two-sided.
  503. """))
  504. docstring.interpd.update(Single_Spectrum=inspect.cleandoc("""
  505. pad_to : int
  506. The number of points to which the data segment is padded when
  507. performing the FFT. While not increasing the actual resolution of
  508. the spectrum (the minimum distance between resolvable peaks),
  509. this can give more points in the plot, allowing for more
  510. detail. This corresponds to the *n* parameter in the call to fft().
  511. The default is None, which sets *pad_to* equal to the length of the
  512. input signal (i.e. no padding).
  513. """))
  514. docstring.interpd.update(PSD=inspect.cleandoc("""
  515. pad_to : int
  516. The number of points to which the data segment is padded when
  517. performing the FFT. This can be different from *NFFT*, which
  518. specifies the number of data points used. While not increasing
  519. the actual resolution of the spectrum (the minimum distance between
  520. resolvable peaks), this can give more points in the plot,
  521. allowing for more detail. This corresponds to the *n* parameter
  522. in the call to fft(). The default is None, which sets *pad_to*
  523. equal to *NFFT*
  524. NFFT : int
  525. The number of data points used in each block for the FFT.
  526. A power 2 is most efficient. The default value is 256.
  527. This should *NOT* be used to get zero padding, or the scaling of the
  528. result will be incorrect. Use *pad_to* for this instead.
  529. detrend : {'none', 'mean', 'linear'} or callable, default 'none'
  530. The function applied to each segment before fft-ing, designed to
  531. remove the mean or linear trend. Unlike in MATLAB, where the
  532. *detrend* parameter is a vector, in Matplotlib is it a function.
  533. The :mod:`~matplotlib.mlab` module defines `.detrend_none`,
  534. `.detrend_mean`, and `.detrend_linear`, but you can use a custom
  535. function as well. You can also use a string to choose one of the
  536. functions: 'none' calls `.detrend_none`. 'mean' calls `.detrend_mean`.
  537. 'linear' calls `.detrend_linear`.
  538. scale_by_freq : bool, optional
  539. Specifies whether the resulting density values should be scaled
  540. by the scaling frequency, which gives density in units of Hz^-1.
  541. This allows for integration over the returned frequency values.
  542. The default is True for MATLAB compatibility.
  543. """))
  544. @docstring.dedent_interpd
  545. def psd(x, NFFT=None, Fs=None, detrend=None, window=None,
  546. noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
  547. r"""
  548. Compute the power spectral density.
  549. The power spectral density :math:`P_{xx}` by Welch's average
  550. periodogram method. The vector *x* is divided into *NFFT* length
  551. segments. Each segment is detrended by function *detrend* and
  552. windowed by function *window*. *noverlap* gives the length of
  553. the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
  554. of each segment :math:`i` are averaged to compute :math:`P_{xx}`.
  555. If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
  556. Parameters
  557. ----------
  558. x : 1-D array or sequence
  559. Array or sequence containing the data
  560. %(Spectral)s
  561. %(PSD)s
  562. noverlap : integer
  563. The number of points of overlap between segments.
  564. The default value is 0 (no overlap).
  565. Returns
  566. -------
  567. Pxx : 1-D array
  568. The values for the power spectrum `P_{xx}` (real valued)
  569. freqs : 1-D array
  570. The frequencies corresponding to the elements in *Pxx*
  571. References
  572. ----------
  573. Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
  574. Wiley & Sons (1986)
  575. See Also
  576. --------
  577. specgram
  578. `specgram` differs in the default overlap; in not returning the mean of
  579. the segment periodograms; and in returning the times of the segments.
  580. magnitude_spectrum : returns the magnitude spectrum.
  581. csd : returns the spectral density between two signals.
  582. """
  583. Pxx, freqs = csd(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend=detrend,
  584. window=window, noverlap=noverlap, pad_to=pad_to,
  585. sides=sides, scale_by_freq=scale_by_freq)
  586. return Pxx.real, freqs
  587. @docstring.dedent_interpd
  588. def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None,
  589. noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
  590. """
  591. Compute the cross-spectral density.
  592. The cross spectral density :math:`P_{xy}` by Welch's average
  593. periodogram method. The vectors *x* and *y* are divided into
  594. *NFFT* length segments. Each segment is detrended by function
  595. *detrend* and windowed by function *window*. *noverlap* gives
  596. the length of the overlap between segments. The product of
  597. the direct FFTs of *x* and *y* are averaged over each segment
  598. to compute :math:`P_{xy}`, with a scaling to correct for power
  599. loss due to windowing.
  600. If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
  601. padded to *NFFT*.
  602. Parameters
  603. ----------
  604. x, y : 1-D arrays or sequences
  605. Arrays or sequences containing the data
  606. %(Spectral)s
  607. %(PSD)s
  608. noverlap : integer
  609. The number of points of overlap between segments.
  610. The default value is 0 (no overlap).
  611. Returns
  612. -------
  613. Pxy : 1-D array
  614. The values for the cross spectrum `P_{xy}` before scaling (real valued)
  615. freqs : 1-D array
  616. The frequencies corresponding to the elements in *Pxy*
  617. References
  618. ----------
  619. Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
  620. Wiley & Sons (1986)
  621. See Also
  622. --------
  623. psd : equivalent to setting ``y = x``.
  624. """
  625. if NFFT is None:
  626. NFFT = 256
  627. Pxy, freqs, _ = _spectral_helper(x=x, y=y, NFFT=NFFT, Fs=Fs,
  628. detrend_func=detrend, window=window,
  629. noverlap=noverlap, pad_to=pad_to,
  630. sides=sides, scale_by_freq=scale_by_freq,
  631. mode='psd')
  632. if Pxy.ndim == 2:
  633. if Pxy.shape[1] > 1:
  634. Pxy = Pxy.mean(axis=1)
  635. else:
  636. Pxy = Pxy[:, 0]
  637. return Pxy, freqs
  638. @docstring.dedent_interpd
  639. def complex_spectrum(x, Fs=None, window=None, pad_to=None,
  640. sides=None):
  641. """
  642. Compute the complex-valued frequency spectrum of *x*. Data is padded to a
  643. length of *pad_to* and the windowing function *window* is applied to the
  644. signal.
  645. Parameters
  646. ----------
  647. x : 1-D array or sequence
  648. Array or sequence containing the data
  649. %(Spectral)s
  650. %(Single_Spectrum)s
  651. Returns
  652. -------
  653. spectrum : 1-D array
  654. The values for the complex spectrum (complex valued)
  655. freqs : 1-D array
  656. The frequencies corresponding to the elements in *spectrum*
  657. See Also
  658. --------
  659. magnitude_spectrum
  660. Returns the absolute value of this function.
  661. angle_spectrum
  662. Returns the angle of this function.
  663. phase_spectrum
  664. Returns the phase (unwrapped angle) of this function.
  665. specgram
  666. Can return the complex spectrum of segments within the signal.
  667. """
  668. return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
  669. sides=sides, mode='complex')
  670. @docstring.dedent_interpd
  671. def magnitude_spectrum(x, Fs=None, window=None, pad_to=None,
  672. sides=None):
  673. """
  674. Compute the magnitude (absolute value) of the frequency spectrum of
  675. *x*. Data is padded to a length of *pad_to* and the windowing function
  676. *window* is applied to the signal.
  677. Parameters
  678. ----------
  679. x : 1-D array or sequence
  680. Array or sequence containing the data
  681. %(Spectral)s
  682. %(Single_Spectrum)s
  683. Returns
  684. -------
  685. spectrum : 1-D array
  686. The values for the magnitude spectrum (real valued)
  687. freqs : 1-D array
  688. The frequencies corresponding to the elements in *spectrum*
  689. See Also
  690. --------
  691. psd
  692. Returns the power spectral density.
  693. complex_spectrum
  694. This function returns the absolute value of `complex_spectrum`.
  695. angle_spectrum
  696. Returns the angles of the corresponding frequencies.
  697. phase_spectrum
  698. Returns the phase (unwrapped angle) of the corresponding frequencies.
  699. specgram
  700. Can return the complex spectrum of segments within the signal.
  701. """
  702. return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
  703. sides=sides, mode='magnitude')
  704. @docstring.dedent_interpd
  705. def angle_spectrum(x, Fs=None, window=None, pad_to=None,
  706. sides=None):
  707. """
  708. Compute the angle of the frequency spectrum (wrapped phase spectrum) of
  709. *x*. Data is padded to a length of *pad_to* and the windowing function
  710. *window* is applied to the signal.
  711. Parameters
  712. ----------
  713. x : 1-D array or sequence
  714. Array or sequence containing the data
  715. %(Spectral)s
  716. %(Single_Spectrum)s
  717. Returns
  718. -------
  719. spectrum : 1-D array
  720. The values for the angle spectrum in radians (real valued)
  721. freqs : 1-D array
  722. The frequencies corresponding to the elements in *spectrum*
  723. See Also
  724. --------
  725. complex_spectrum
  726. This function returns the angle value of `complex_spectrum`.
  727. magnitude_spectrum
  728. Returns the magnitudes of the corresponding frequencies.
  729. phase_spectrum
  730. Returns the phase (unwrapped angle) of the corresponding frequencies.
  731. specgram
  732. Can return the complex spectrum of segments within the signal.
  733. """
  734. return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
  735. sides=sides, mode='angle')
  736. @docstring.dedent_interpd
  737. def phase_spectrum(x, Fs=None, window=None, pad_to=None,
  738. sides=None):
  739. """
  740. Compute the phase of the frequency spectrum (unwrapped angle spectrum) of
  741. *x*. Data is padded to a length of *pad_to* and the windowing function
  742. *window* is applied to the signal.
  743. Parameters
  744. ----------
  745. x : 1-D array or sequence
  746. Array or sequence containing the data
  747. %(Spectral)s
  748. %(Single_Spectrum)s
  749. Returns
  750. -------
  751. spectrum : 1-D array
  752. The values for the phase spectrum in radians (real valued)
  753. freqs : 1-D array
  754. The frequencies corresponding to the elements in *spectrum*
  755. See Also
  756. --------
  757. complex_spectrum
  758. This function returns the phase value of `complex_spectrum`.
  759. magnitude_spectrum
  760. Returns the magnitudes of the corresponding frequencies.
  761. angle_spectrum
  762. Returns the angle (wrapped phase) of the corresponding frequencies.
  763. specgram
  764. Can return the complex spectrum of segments within the signal.
  765. """
  766. return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
  767. sides=sides, mode='phase')
  768. @docstring.dedent_interpd
  769. def specgram(x, NFFT=None, Fs=None, detrend=None, window=None,
  770. noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
  771. mode=None):
  772. """
  773. Compute a spectrogram.
  774. Compute and plot a spectrogram of data in x. Data are split into
  775. NFFT length segments and the spectrum of each section is
  776. computed. The windowing function window is applied to each
  777. segment, and the amount of overlap of each segment is
  778. specified with noverlap.
  779. Parameters
  780. ----------
  781. x : array-like
  782. 1-D array or sequence.
  783. %(Spectral)s
  784. %(PSD)s
  785. noverlap : int, optional
  786. The number of points of overlap between blocks. The default
  787. value is 128.
  788. mode : str, optional
  789. What sort of spectrum to use, default is 'psd'.
  790. 'psd'
  791. Returns the power spectral density.
  792. 'complex'
  793. Returns the complex-valued frequency spectrum.
  794. 'magnitude'
  795. Returns the magnitude spectrum.
  796. 'angle'
  797. Returns the phase spectrum without unwrapping.
  798. 'phase'
  799. Returns the phase spectrum with unwrapping.
  800. Returns
  801. -------
  802. spectrum : array-like
  803. 2-D array, columns are the periodograms of successive segments.
  804. freqs : array-like
  805. 1-D array, frequencies corresponding to the rows in *spectrum*.
  806. t : array-like
  807. 1-D array, the times corresponding to midpoints of segments
  808. (i.e the columns in *spectrum*).
  809. See Also
  810. --------
  811. psd : differs in the overlap and in the return values.
  812. complex_spectrum : similar, but with complex valued frequencies.
  813. magnitude_spectrum : similar single segment when mode is 'magnitude'.
  814. angle_spectrum : similar to single segment when mode is 'angle'.
  815. phase_spectrum : similar to single segment when mode is 'phase'.
  816. Notes
  817. -----
  818. detrend and scale_by_freq only apply when *mode* is set to 'psd'.
  819. """
  820. if noverlap is None:
  821. noverlap = 128 # default in _spectral_helper() is noverlap = 0
  822. if NFFT is None:
  823. NFFT = 256 # same default as in _spectral_helper()
  824. if len(x) <= NFFT:
  825. cbook._warn_external("Only one segment is calculated since parameter "
  826. "NFFT (=%d) >= signal length (=%d)." %
  827. (NFFT, len(x)))
  828. spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs,
  829. detrend_func=detrend, window=window,
  830. noverlap=noverlap, pad_to=pad_to,
  831. sides=sides,
  832. scale_by_freq=scale_by_freq,
  833. mode=mode)
  834. if mode != 'complex':
  835. spec = spec.real # Needed since helper implements generically
  836. return spec, freqs, t
  837. @docstring.dedent_interpd
  838. def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
  839. noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
  840. r"""
  841. The coherence between *x* and *y*. Coherence is the normalized
  842. cross spectral density:
  843. .. math::
  844. C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
  845. Parameters
  846. ----------
  847. x, y
  848. Array or sequence containing the data
  849. %(Spectral)s
  850. %(PSD)s
  851. noverlap : integer
  852. The number of points of overlap between blocks. The default value
  853. is 0 (no overlap).
  854. Returns
  855. -------
  856. The return value is the tuple (*Cxy*, *f*), where *f* are the
  857. frequencies of the coherence vector. For cohere, scaling the
  858. individual densities by the sampling frequency has no effect,
  859. since the factors cancel out.
  860. See Also
  861. --------
  862. :func:`psd`, :func:`csd` :
  863. For information about the methods used to compute :math:`P_{xy}`,
  864. :math:`P_{xx}` and :math:`P_{yy}`.
  865. """
  866. if len(x) < 2 * NFFT:
  867. raise ValueError(
  868. "Coherence is calculated by averaging over *NFFT* length "
  869. "segments. Your signal is too short for your choice of *NFFT*.")
  870. Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
  871. scale_by_freq)
  872. Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
  873. scale_by_freq)
  874. Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
  875. scale_by_freq)
  876. Cxy = np.abs(Pxy) ** 2 / (Pxx * Pyy)
  877. return Cxy, f
  878. def _csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',',
  879. converterd=None, names=None, missing='', missingd=None,
  880. use_mrecords=False, dayfirst=False, yearfirst=False):
  881. """
  882. Load data from comma/space/tab delimited file in *fname* into a
  883. numpy record array and return the record array.
  884. If *names* is *None*, a header row is required to automatically
  885. assign the recarray names. The headers will be lower cased,
  886. spaces will be converted to underscores, and illegal attribute
  887. name characters removed. If *names* is not *None*, it is a
  888. sequence of names to use for the column names. In this case, it
  889. is assumed there is no header row.
  890. - *fname*: can be a filename or a file handle. Support for gzipped
  891. files is automatic, if the filename ends in '.gz'
  892. - *comments*: the character used to indicate the start of a comment
  893. in the file, or *None* to switch off the removal of comments
  894. - *skiprows*: is the number of rows from the top to skip
  895. - *checkrows*: is the number of rows to check to validate the column
  896. data type. When set to zero all rows are validated.
  897. - *converterd*: if not *None*, is a dictionary mapping column number or
  898. munged column name to a converter function.
  899. - *names*: if not None, is a list of header names. In this case, no
  900. header will be read from the file
  901. - *missingd* is a dictionary mapping munged column names to field values
  902. which signify that the field does not contain actual data and should
  903. be masked, e.g., '0000-00-00' or 'unused'
  904. - *missing*: a string whose value signals a missing field regardless of
  905. the column it appears in
  906. - *use_mrecords*: if True, return an mrecords.fromrecords record array if
  907. any of the data are missing
  908. - *dayfirst*: default is False so that MM-DD-YY has precedence over
  909. DD-MM-YY. See
  910. http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47
  911. for further information.
  912. - *yearfirst*: default is False so that MM-DD-YY has precedence over
  913. YY-MM-DD. See
  914. http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47
  915. for further information.
  916. If no rows are found, *None* is returned
  917. """
  918. if converterd is None:
  919. converterd = dict()
  920. if missingd is None:
  921. missingd = {}
  922. import dateutil.parser
  923. import datetime
  924. fh = cbook.to_filehandle(fname)
  925. delimiter = str(delimiter)
  926. class FH:
  927. """
  928. For space-delimited files, we want different behavior than
  929. comma or tab. Generally, we want multiple spaces to be
  930. treated as a single separator, whereas with comma and tab we
  931. want multiple commas to return multiple (empty) fields. The
  932. join/strip trick below effects this.
  933. """
  934. def __init__(self, fh):
  935. self.fh = fh
  936. def close(self):
  937. self.fh.close()
  938. def seek(self, arg):
  939. self.fh.seek(arg)
  940. def fix(self, s):
  941. return ' '.join(s.split())
  942. def __next__(self):
  943. return self.fix(next(self.fh))
  944. def __iter__(self):
  945. for line in self.fh:
  946. yield self.fix(line)
  947. if delimiter == ' ':
  948. fh = FH(fh)
  949. reader = csv.reader(fh, delimiter=delimiter)
  950. def process_skiprows(reader):
  951. if skiprows:
  952. for i, row in enumerate(reader):
  953. if i >= (skiprows-1):
  954. break
  955. return fh, reader
  956. process_skiprows(reader)
  957. def ismissing(name, val):
  958. "Should the value val in column name be masked?"
  959. return val == missing or val == missingd.get(name) or val == ''
  960. def with_default_value(func, default):
  961. def newfunc(name, val):
  962. if ismissing(name, val):
  963. return default
  964. else:
  965. return func(val)
  966. return newfunc
  967. def mybool(x):
  968. if x == 'True':
  969. return True
  970. elif x == 'False':
  971. return False
  972. else:
  973. raise ValueError('invalid bool')
  974. dateparser = dateutil.parser.parse
  975. def mydateparser(x):
  976. # try and return a datetime object
  977. d = dateparser(x, dayfirst=dayfirst, yearfirst=yearfirst)
  978. return d
  979. mydateparser = with_default_value(mydateparser, datetime.datetime(1, 1, 1))
  980. myfloat = with_default_value(float, np.nan)
  981. myint = with_default_value(int, -1)
  982. mystr = with_default_value(str, '')
  983. mybool = with_default_value(mybool, None)
  984. def mydate(x):
  985. # try and return a date object
  986. d = dateparser(x, dayfirst=dayfirst, yearfirst=yearfirst)
  987. if d.hour > 0 or d.minute > 0 or d.second > 0:
  988. raise ValueError('not a date')
  989. return d.date()
  990. mydate = with_default_value(mydate, datetime.date(1, 1, 1))
  991. def get_func(name, item, func):
  992. # promote functions in this order
  993. funcs = [mybool, myint, myfloat, mydate, mydateparser, mystr]
  994. for func in funcs[funcs.index(func):]:
  995. try:
  996. func(name, item)
  997. except Exception:
  998. continue
  999. return func
  1000. raise ValueError('Could not find a working conversion function')
  1001. # map column names that clash with builtins -- TODO - extend this list
  1002. itemd = {
  1003. 'return': 'return_',
  1004. 'file': 'file_',
  1005. 'print': 'print_',
  1006. }
  1007. def get_converters(reader, comments):
  1008. converters = None
  1009. i = 0
  1010. for row in reader:
  1011. if (len(row) and comments is not None and
  1012. row[0].startswith(comments)):
  1013. continue
  1014. if i == 0:
  1015. converters = [mybool]*len(row)
  1016. if checkrows and i > checkrows:
  1017. break
  1018. i += 1
  1019. for j, (name, item) in enumerate(zip(names, row)):
  1020. func = converterd.get(j)
  1021. if func is None:
  1022. func = converterd.get(name)
  1023. if func is None:
  1024. func = converters[j]
  1025. if len(item.strip()):
  1026. func = get_func(name, item, func)
  1027. else:
  1028. # how should we handle custom converters and defaults?
  1029. func = with_default_value(func, None)
  1030. converters[j] = func
  1031. return converters
  1032. # Get header and remove invalid characters
  1033. needheader = names is None
  1034. if needheader:
  1035. for row in reader:
  1036. if (len(row) and comments is not None and
  1037. row[0].startswith(comments)):
  1038. continue
  1039. headers = row
  1040. break
  1041. # remove these chars
  1042. delete = set(r"""~!@#$%^&*()-=+~\|}[]{';: /?.>,<""")
  1043. delete.add('"')
  1044. names = []
  1045. seen = dict()
  1046. for i, item in enumerate(headers):
  1047. item = item.strip().lower().replace(' ', '_')
  1048. item = ''.join([c for c in item if c not in delete])
  1049. if not len(item):
  1050. item = 'column%d' % i
  1051. item = itemd.get(item, item)
  1052. cnt = seen.get(item, 0)
  1053. if cnt > 0:
  1054. names.append(item + '_%d' % cnt)
  1055. else:
  1056. names.append(item)
  1057. seen[item] = cnt+1
  1058. else:
  1059. if isinstance(names, str):
  1060. names = [n.strip() for n in names.split(',')]
  1061. # get the converter functions by inspecting checkrows
  1062. converters = get_converters(reader, comments)
  1063. if converters is None:
  1064. raise ValueError('Could not find any valid data in CSV file')
  1065. # reset the reader and start over
  1066. fh.seek(0)
  1067. reader = csv.reader(fh, delimiter=delimiter)
  1068. process_skiprows(reader)
  1069. if needheader:
  1070. while True:
  1071. # skip past any comments and consume one line of column header
  1072. row = next(reader)
  1073. if (len(row) and comments is not None and
  1074. row[0].startswith(comments)):
  1075. continue
  1076. break
  1077. # iterate over the remaining rows and convert the data to date
  1078. # objects, ints, or floats as appropriate
  1079. rows = []
  1080. rowmasks = []
  1081. for i, row in enumerate(reader):
  1082. if not len(row):
  1083. continue
  1084. if comments is not None and row[0].startswith(comments):
  1085. continue
  1086. # Ensure that the row returned always has the same nr of elements
  1087. row.extend([''] * (len(converters) - len(row)))
  1088. rows.append([func(name, val)
  1089. for func, name, val in zip(converters, names, row)])
  1090. rowmasks.append([ismissing(name, val)
  1091. for name, val in zip(names, row)])
  1092. fh.close()
  1093. if not len(rows):
  1094. return None
  1095. if use_mrecords and np.any(rowmasks):
  1096. r = np.ma.mrecords.fromrecords(rows, names=names, mask=rowmasks)
  1097. else:
  1098. r = np.rec.fromrecords(rows, names=names)
  1099. return r
  1100. class GaussianKDE:
  1101. """
  1102. Representation of a kernel-density estimate using Gaussian kernels.
  1103. Parameters
  1104. ----------
  1105. dataset : array-like
  1106. Datapoints to estimate from. In case of univariate data this is a 1-D
  1107. array, otherwise a 2-D array with shape (# of dims, # of data).
  1108. bw_method : str, scalar or callable, optional
  1109. The method used to calculate the estimator bandwidth. This can be
  1110. 'scott', 'silverman', a scalar constant or a callable. If a
  1111. scalar, this will be used directly as `kde.factor`. If a
  1112. callable, it should take a `GaussianKDE` instance as only
  1113. parameter and return a scalar. If None (default), 'scott' is used.
  1114. Attributes
  1115. ----------
  1116. dataset : ndarray
  1117. The dataset with which `gaussian_kde` was initialized.
  1118. dim : int
  1119. Number of dimensions.
  1120. num_dp : int
  1121. Number of datapoints.
  1122. factor : float
  1123. The bandwidth factor, obtained from `kde.covariance_factor`, with which
  1124. the covariance matrix is multiplied.
  1125. covariance : ndarray
  1126. The covariance matrix of *dataset*, scaled by the calculated bandwidth
  1127. (`kde.factor`).
  1128. inv_cov : ndarray
  1129. The inverse of *covariance*.
  1130. Methods
  1131. -------
  1132. kde.evaluate(points) : ndarray
  1133. Evaluate the estimated pdf on a provided set of points.
  1134. kde(points) : ndarray
  1135. Same as kde.evaluate(points)
  1136. """
  1137. # This implementation with minor modification was too good to pass up.
  1138. # from scipy: https://github.com/scipy/scipy/blob/master/scipy/stats/kde.py
  1139. def __init__(self, dataset, bw_method=None):
  1140. self.dataset = np.atleast_2d(dataset)
  1141. if not np.array(self.dataset).size > 1:
  1142. raise ValueError("`dataset` input should have multiple elements.")
  1143. self.dim, self.num_dp = np.array(self.dataset).shape
  1144. if bw_method is None:
  1145. pass
  1146. elif cbook._str_equal(bw_method, 'scott'):
  1147. self.covariance_factor = self.scotts_factor
  1148. elif cbook._str_equal(bw_method, 'silverman'):
  1149. self.covariance_factor = self.silverman_factor
  1150. elif isinstance(bw_method, Number):
  1151. self._bw_method = 'use constant'
  1152. self.covariance_factor = lambda: bw_method
  1153. elif callable(bw_method):
  1154. self._bw_method = bw_method
  1155. self.covariance_factor = lambda: self._bw_method(self)
  1156. else:
  1157. raise ValueError("`bw_method` should be 'scott', 'silverman', a "
  1158. "scalar or a callable")
  1159. # Computes the covariance matrix for each Gaussian kernel using
  1160. # covariance_factor().
  1161. self.factor = self.covariance_factor()
  1162. # Cache covariance and inverse covariance of the data
  1163. if not hasattr(self, '_data_inv_cov'):
  1164. self.data_covariance = np.atleast_2d(
  1165. np.cov(
  1166. self.dataset,
  1167. rowvar=1,
  1168. bias=False))
  1169. self.data_inv_cov = np.linalg.inv(self.data_covariance)
  1170. self.covariance = self.data_covariance * self.factor ** 2
  1171. self.inv_cov = self.data_inv_cov / self.factor ** 2
  1172. self.norm_factor = (np.sqrt(np.linalg.det(2 * np.pi * self.covariance))
  1173. * self.num_dp)
  1174. def scotts_factor(self):
  1175. return np.power(self.num_dp, -1. / (self.dim + 4))
  1176. def silverman_factor(self):
  1177. return np.power(
  1178. self.num_dp * (self.dim + 2.0) / 4.0, -1. / (self.dim + 4))
  1179. # Default method to calculate bandwidth, can be overwritten by subclass
  1180. covariance_factor = scotts_factor
  1181. def evaluate(self, points):
  1182. """Evaluate the estimated pdf on a set of points.
  1183. Parameters
  1184. ----------
  1185. points : (# of dimensions, # of points)-array
  1186. Alternatively, a (# of dimensions,) vector can be passed in and
  1187. treated as a single point.
  1188. Returns
  1189. -------
  1190. values : (# of points,)-array
  1191. The values at each point.
  1192. Raises
  1193. ------
  1194. ValueError : if the dimensionality of the input points is different
  1195. than the dimensionality of the KDE.
  1196. """
  1197. points = np.atleast_2d(points)
  1198. dim, num_m = np.array(points).shape
  1199. if dim != self.dim:
  1200. raise ValueError("points have dimension {}, dataset has dimension "
  1201. "{}".format(dim, self.dim))
  1202. result = np.zeros(num_m)
  1203. if num_m >= self.num_dp:
  1204. # there are more points than data, so loop over data
  1205. for i in range(self.num_dp):
  1206. diff = self.dataset[:, i, np.newaxis] - points
  1207. tdiff = np.dot(self.inv_cov, diff)
  1208. energy = np.sum(diff * tdiff, axis=0) / 2.0
  1209. result = result + np.exp(-energy)
  1210. else:
  1211. # loop over points
  1212. for i in range(num_m):
  1213. diff = self.dataset - points[:, i, np.newaxis]
  1214. tdiff = np.dot(self.inv_cov, diff)
  1215. energy = np.sum(diff * tdiff, axis=0) / 2.0
  1216. result[i] = np.sum(np.exp(-energy), axis=0)
  1217. result = result / self.norm_factor
  1218. return result
  1219. __call__ = evaluate