1 # Copyright (C) 2008-2012 W. Trevor King
2 # This program is free software: you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation, either version 3 of the License, or
5 # (at your option) any later version.
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
12 # You should have received a copy of the GNU General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 """Wrap Numpy's fft module to reduce clutter.
17 Provides a unitary discrete FFT and a windowed version based on
18 :func:`numpy.fft.rfft`.
22 * :func:`unitary_rfft`
23 * :func:`power_spectrum`
24 * :func:`unitary_power_spectrum`
25 * :func:`avg_power_spectrum`
26 * :func:`unitary_avg_power_spectrum`
29 import unittest as _unittest
31 import numpy as _numpy
36 # Display time- and freq-space plots of the test transforms if True
40 def floor_pow_of_two(num):
41 """Round `num` down to the closest exact a power of two.
46 >>> floor_pow_of_two(3)
48 >>> floor_pow_of_two(11)
50 >>> floor_pow_of_two(15)
53 lnum = _numpy.log2(num)
55 num = 2**_numpy.floor(lnum)
59 def round_pow_of_two(num):
60 """Round `num` to the closest exact a power of two on a log scale.
65 >>> round_pow_of_two(2.9) # Note rounding on *log scale*
67 >>> round_pow_of_two(11)
69 >>> round_pow_of_two(15)
72 lnum = _numpy.log2(num)
74 num = 2**_numpy.round(lnum)
78 def ceil_pow_of_two(num):
79 """Round `num` up to the closest exact a power of two.
84 >>> ceil_pow_of_two(3)
86 >>> ceil_pow_of_two(11)
88 >>> ceil_pow_of_two(15)
91 lnum = _numpy.log2(num)
93 num = 2**_numpy.ceil(lnum)
97 def unitary_rfft(data, freq=1.0):
98 """Compute the unitary Fourier transform of real data.
100 Unitary = preserves power [Parseval's theorem].
105 Real (not complex) data taken with a sampling frequency `freq`.
111 freq_axis,trans : numpy.ndarray
112 Arrays ready for plotting.
116 If the units on your data are Volts,
117 and your sampling frequency is in Hz,
118 then `freq_axis` will be in Hz,
119 and `trans` will be in Volts.
121 nsamps = floor_pow_of_two(len(data))
122 # Which should satisfy the discrete form of Parseval's theorem
124 # SUM |x_m|^2 = 1/n SUM |X_k|^2.
126 # However, we want our FFT to satisfy the continuous Parseval eqn
127 # int_{-infty}^{infty} |x(t)|^2 dt = int_{-infty}^{infty} |X(f)|^2 df
128 # which has the discrete form
130 # SUM |x_m|^2 dt = SUM |X'_k|^2 df
132 # with X'_k = AX, this gives us
134 # SUM |x_m|^2 = A^2 df/dt SUM |X'_k|^2
139 # From Numerical Recipes (http://www.fizyka.umk.pl/nrbook/bookcpdf.html),
140 # Section 12.1, we see that for a sampling rate dt, the maximum frequency
141 # f_c in the transformed data is the Nyquist frequency (12.1.2)
143 # and the points are spaced out by (12.1.5)
149 # A = 1/ndf = ndt/n = dt
150 # so we can convert the Numpy transformed data to match our unitary
151 # continuous transformed data with (also NR 12.1.8)
152 # X'_k = dtX = X / <sampling freq>
153 trans = _numpy.fft.rfft(data[0:nsamps]) / _numpy.float(freq)
154 freq_axis = _numpy.linspace(0, freq / 2, nsamps / 2 + 1)
155 return (freq_axis, trans)
158 def power_spectrum(data, freq=1.0):
159 """Compute the power spectrum of the time series `data`.
164 Real (not complex) data taken with a sampling frequency `freq`.
170 freq_axis,power : numpy.ndarray
171 Arrays ready for plotting.
175 If the number of samples in `data` is not an integer power of two,
176 the FFT ignores some of the later points.
180 unitary_power_spectrum,avg_power_spectrum
182 nsamps = floor_pow_of_two(len(data))
184 freq_axis = _numpy.linspace(0, freq / 2, nsamps / 2 + 1)
185 # nsamps/2+1 b/c zero-freq and nyqist-freq are both fully real.
186 # >>> help(numpy.fft.fftpack.rfft) for Numpy's explaination.
187 # See Numerical Recipies for a details.
188 trans = _numpy.fft.rfft(data[0:nsamps])
189 power = (trans * trans.conj()).real # we want the square of the amplitude
190 return (freq_axis, power)
193 def unitary_power_spectrum(data, freq=1.0):
194 """Compute the unitary power spectrum of the time series `data`.
198 power_spectrum,unitary_avg_power_spectrum
200 freq_axis,power = power_spectrum(data, freq)
201 # One sided power spectral density, so 2|H(f)|**2
202 # (see NR 2nd edition 12.0.14, p498)
204 # numpy normalizes with 1/N on the inverse transform ifft,
205 # so we should normalize the freq-space representation with 1/sqrt(N).
206 # But we're using the rfft, where N points are like N/2 complex points,
208 # So the power gets normalized by that twice and we have 2/N
210 # On top of this, the FFT assumes a sampling freq of 1 per second,
211 # and we want to preserve area under our curves.
212 # If our total time T = len(data)/freq is smaller than 1,
213 # our df_real = freq/len(data) is bigger that the FFT expects
214 # (dt_fft = 1/len(data)),
215 # and we need to scale the powers down to conserve area.
216 # df_fft * F_fft(f) = df_real *F_real(f)
217 # F_real = F_fft(f) * (1/len)/(freq/len) = F_fft(f)*freq
218 # So the power gets normalized by *that* twice and we have 2/N * freq**2
220 # power per unit time
221 # measure x(t) for time T
222 # X(f) = int_0^T x(t) exp(-2 pi ift) dt
223 # PSD(f) = 2 |X(f)|**2 / T
225 # total_time = len(data)/float(freq)
226 # power *= 2.0 / float(freq)**2 / total_time
227 # power *= 2.0 / freq**2 * freq / len(data)
228 power *= 2.0 / (freq * _numpy.float(len(data)))
230 return (freq_axis, power)
233 def window_hann(length):
234 r"""Returns a Hann window array with length entries
238 The Hann window with length :math:`L` is defined as
240 .. math:: w_i = \frac{1}{2} (1-\cos(2\pi i/L))
242 win = _numpy.zeros((length,), dtype=_numpy.float)
243 for i in range(length):
245 1.0 - _numpy.cos(2.0 * _numpy.pi * _numpy.float(i) / (length)))
246 # avg value of cos over a period is 0
247 # so average height of Hann window is 0.5
251 def avg_power_spectrum(data, freq=1.0, chunk_size=2048,
252 overlap=True, window=window_hann):
253 """Compute the avgerage power spectrum of `data`.
258 Real (not complex) data taken with a sampling frequency `freq`.
262 Number of samples per chunk. Use a power of two.
263 overlap: {True,False}
264 If `True`, each chunk overlaps the previous chunk by half its
265 length. Otherwise, the chunks are end-to-end, and not
268 Weights used to "smooth" the chunks, there is a whole science
269 behind windowing, but if you're not trying to squeeze every
270 drop of information out of your data, you'll be OK with the
275 freq_axis,power : numpy.ndarray
276 Arrays ready for plotting.
280 The average power spectrum is computed by breaking `data` into
281 chunks of length `chunk_size`. These chunks are transformed
282 individually into frequency space and then averaged together.
284 See Numerical Recipes 2 section 13.4 for a good introduction to
287 If the number of samples in `data` is not a multiple of
288 `chunk_size`, we ignore the extra points.
290 if chunk_size != floor_pow_of_two(chunk_size):
292 'chunk_size {} should be a power of 2'.format(chunk_size))
294 nchunks = len(data) // chunk_size # integer division = implicit floor
296 chunk_step = chunk_size / 2
298 chunk_step = chunk_size
300 win = window(chunk_size) # generate a window of the appropriate size
301 freq_axis = _numpy.linspace(0, freq / 2, chunk_size / 2 + 1)
302 # nsamps/2+1 b/c zero-freq and nyqist-freq are both fully real.
303 # >>> help(numpy.fft.fftpack.rfft) for Numpy's explaination.
304 # See Numerical Recipies for a details.
305 power = _numpy.zeros((chunk_size / 2 + 1, ), dtype=_numpy.float)
306 for i in range(nchunks):
307 starti = i * chunk_step
308 stopi = starti + chunk_size
309 fft_chunk = _numpy.fft.rfft(data[starti:stopi] * win)
310 p_chunk = (fft_chunk * fft_chunk.conj()).real
311 power += p_chunk.astype(_numpy.float)
312 power /= _numpy.float(nchunks)
313 return (freq_axis, power)
316 def unitary_avg_power_spectrum(data, freq=1.0, chunk_size=2048,
317 overlap=True, window=window_hann):
318 """Compute the unitary average power spectrum of `data`.
322 avg_power_spectrum,unitary_power_spectrum
324 freq_axis,power = avg_power_spectrum(
325 data, freq, chunk_size, overlap, window)
326 # 2.0 / (freq * chunk_size) |rfft()|**2 --> unitary_power_spectrum
327 # see unitary_power_spectrum()
328 power *= 2.0 / (freq * _numpy.float(chunk_size)) * 8.0 / 3
329 # * 8/3 to remove power from windowing
330 # <[x(t)*w(t)]**2> = <x(t)**2 * w(t)**2> ~= <x(t)**2> * <w(t)**2>
331 # where the ~= is because the frequency of x(t) >> the frequency of w(t).
332 # So our calulated power has and extra <w(t)**2> in it.
333 # For the Hann window,
334 # <w(t)**2> = <0.5(1 + 2cos + cos**2)> = 1/4 + 0 + 1/8 = 3/8
335 # For low frequency components,
336 # where the frequency of x(t) is ~= the frequency of w(t),
337 # the normalization is not perfect. ??
338 # The normalization approaches perfection as chunk_size -> infinity.
339 return (freq_axis, power)
342 class TestRFFT (_unittest.TestCase):
343 r"""Ensure Numpy's FFT algorithm acts as expected.
347 The expected return values are [#dft]_:
349 .. math:: X_k = \sum_{m=0}^{n-1} x_m \exp^{-2\pi imk/n}
351 .. [#dft] See the *Background information* section of :mod:`numpy.fft`.
353 def run_rfft(self, xs, Xs):
354 i = _numpy.complex(0, 1)
358 Xa.append(sum([x * _numpy.exp(-2 * _numpy.pi * i * m * k / n)
359 for x,m in zip(xs, range(n))]))
361 if (Xs[k] - Xa[k]) / _numpy.abs(Xa[k]) >= 1e-6:
363 ('rfft mismatch on element {}: {} != {}, '
364 'relative error {}').format(
366 (Xs[k] - Xa[k]) / _numpy.abs(Xa[k])))
367 # Which should satisfy the discrete form of Parseval's theorem
369 # SUM |x_m|^2 = 1/n SUM |X_k|^2.
371 timeSum = sum([_numpy.abs(x)**2 for x in xs])
372 freqSum = sum([_numpy.abs(X)**2 for X in Xa])
373 if _numpy.abs(freqSum / _numpy.float(n) - timeSum) / timeSum >= 1e-6:
375 "Mismatch on Parseval's, {} != 1/{} * {}".format(
376 timeSum, n, freqSum))
379 xs = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
380 self.run_rfft(xs, _numpy.fft.rfft(xs))
383 class TestUnitaryRFFT (_unittest.TestCase):
384 """Verify `unitary_rfft`.
386 def run_parsevals(self, xs, freq, freqs, Xs):
387 """Check the discretized integral form of Parseval's theorem
393 .. math:: \sum_{m=0}^{n-1} |x_m|^2 dt = \sum_{k=0}^{n-1} |X_k|^2 df
396 df = freqs[1] - freqs[0]
397 if (df - 1 / (len(xs) * dt)) / df >= 1e-6:
399 'Mismatch in spacing, {} != 1/({}*{})'.format(df, len(xs), dt))
401 for k in range(len(Xs) - 1, 1, -1):
403 if len(xs) != len(Xa):
405 'Length mismatch {} != {}'.format(len(xs), len(Xa)))
406 lhs = sum([_numpy.abs(x)**2 for x in xs]) * dt
407 rhs = sum([_numpy.abs(X)**2 for X in Xa]) * df
408 if _numpy.abs(lhs - rhs) / lhs >= 1e-4:
410 "Mismatch on Parseval's, {} != {}".format(lhs, rhs))
412 def test_parsevals(self):
413 "Test unitary rfft on Parseval's theorem"
414 xs = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
416 freqs,Xs = unitary_rfft(xs, 1.0 / dt)
417 self.run_parsevals(xs, 1.0 / dt, freqs, Xs)
420 r"""Rectangle function.
427 \rect(t) = \begin{cases}
428 1& \text{if $|t| < 0.5$}, \\
429 0& \text{if $|t| \ge 0.5$}.
432 if _numpy.abs(t) < 0.5:
437 def run_rect(self, a=1.0, time_shift=5.0, samp_freq=25.6, samples=256):
438 r"""Test `unitary_rttf` on known function `rect(at)`.
444 .. math:: \rfft(\rect(at)) = 1/|a|\cdot\sinc(f/a)
446 samp_freq = _numpy.float(samp_freq)
449 x = _numpy.zeros((samples,), dtype=_numpy.float)
451 for i in range(samples):
453 x[i] = self.rect(a * (t - time_shift))
454 freq_axis,X = unitary_rfft(x, samp_freq)
456 # remove the phase due to our time shift
457 j = _numpy.complex(0.0, 1.0) # sqrt(-1)
458 for i in range(len(freq_axis)):
460 inverse_phase_shift = _numpy.exp(
461 j * 2.0 * _numpy.pi * time_shift * f)
462 X[i] *= inverse_phase_shift
464 expected = _numpy.zeros((len(freq_axis),), dtype=_numpy.float)
465 # normalized sinc(x) = sin(pi x)/(pi x)
466 # so sinc(0.5) = sin(pi/2)/(pi/2) = 2/pi
467 if _numpy.sinc(0.5) != 2.0 / _numpy.pi:
468 raise ValueError('abnormal sinc()')
469 for i in range(len(freq_axis)):
471 expected[i] = 1.0 / _numpy.abs(a) * _numpy.sinc(f / a)
474 figure = _pyplot.figure()
475 time_axes = figure.add_subplot(2, 1, 1)
476 time_axes.plot(_numpy.arange(0, dt * samples, dt), x)
477 time_axes.set_title('time series')
478 freq_axes = figure.add_subplot(2, 1, 2)
479 freq_axes.plot(freq_axis, X.real, 'r.')
480 freq_axes.plot(freq_axis, X.imag, 'g.')
481 freq_axes.plot(freq_axis, expected, 'b-')
482 freq_axes.set_title('freq series')
485 "Test unitary FFTs on variously shaped rectangular functions."
488 self.run_rect(a=0.7, samp_freq=50, samples=512)
489 self.run_rect(a=3.0, samp_freq=60, samples=1024)
491 def gaussian(self, a, t):
492 r"""Gaussian function.
497 .. math:: \gaussian(a,t) = \exp^{-at^2}
499 return _numpy.exp(-a * t**2)
501 def run_gaussian(self, a=1.0, time_shift=5.0, samp_freq=25.6, samples=256):
502 r"""Test `unitary_rttf` on known function `gaussian(a,t)`.
510 \rfft(\gaussian(a,t)) = \sqrt{\pi/a} \cdot \gaussian(1/a,\pi f)
512 samp_freq = _numpy.float(samp_freq)
515 x = _numpy.zeros((samples,), dtype=_numpy.float)
517 for i in range(samples):
519 x[i] = self.gaussian(a, (t - time_shift))
520 freq_axis,X = unitary_rfft(x, samp_freq)
522 # remove the phase due to our time shift
523 j = _numpy.complex(0.0, 1.0) # sqrt(-1)
524 for i in range(len(freq_axis)):
526 inverse_phase_shift = _numpy.exp(
527 j * 2.0 * _numpy.pi * time_shift * f)
528 X[i] *= inverse_phase_shift
530 expected = _numpy.zeros((len(freq_axis),), dtype=_numpy.float)
531 for i in range(len(freq_axis)):
533 # see Wikipedia, or do the integral yourself.
534 expected[i] = _numpy.sqrt(_numpy.pi / a) * self.gaussian(
535 1.0 / a, _numpy.pi * f)
538 figure = _pyplot.figure()
539 time_axes = figure.add_subplot(2, 1, 1)
540 time_axes.plot(_numpy.arange(0, dt * samples, dt), x)
541 time_axes.set_title('time series')
542 freq_axes = figure.add_subplot(2, 1, 2)
543 freq_axes.plot(freq_axis, X.real, 'r.')
544 freq_axes.plot(freq_axis, X.imag, 'g.')
545 freq_axes.plot(freq_axis, expected, 'b-')
546 freq_axes.set_title('freq series')
548 def test_gaussian(self):
549 "Test unitary FFTs on variously shaped gaussian functions."
550 self.run_gaussian(a=0.5)
551 self.run_gaussian(a=2.0)
552 self.run_gaussian(a=0.7, samp_freq=50, samples=512)
553 self.run_gaussian(a=3.0, samp_freq=60, samples=1024)
556 class TestUnitaryPowerSpectrum (_unittest.TestCase):
557 def run_sin(self, sin_freq=10, samp_freq=512, samples=1024):
558 x = _numpy.zeros((samples,), dtype=_numpy.float)
559 samp_freq = _numpy.float(samp_freq)
560 for i in range(samples):
561 x[i] = _numpy.sin(2.0 * _numpy.pi * (i / samp_freq) * sin_freq)
562 freq_axis,power = unitary_power_spectrum(x, samp_freq)
563 imax = _numpy.argmax(power)
565 expected = _numpy.zeros((len(freq_axis),), dtype=_numpy.float)
566 # df = 1/T, where T = total_time
567 df = samp_freq / _numpy.float(samples)
568 i = int(sin_freq / df)
569 # average power per unit time is
571 # average value of sin(t)**2 = 0.5 (b/c sin**2+cos**2 == 1)
572 # so average value of (int sin(t)**2 dt) per unit time is 0.5
574 # we spread that power over a frequency bin of width df, sp
576 # where f0 is the sin's frequency
579 # FFT of sin(2*pi*t*f0) gives
580 # X(f) = 0.5 i (delta(f-f0) - delta(f-f0)),
581 # (area under x(t) = 0, area under X(f) = 0)
582 # so one sided power spectral density (PSD) per unit time is
583 # P(f) = 2 |X(f)|**2 / T
584 # = 2 * |0.5 delta(f-f0)|**2 / T
585 # = 0.5 * |delta(f-f0)|**2 / T
586 # but we're discrete and want the integral of the 'delta' to be 1,
587 # so 'delta'*df = 1 --> 'delta' = 1/df, and
588 # P(f) = 0.5 / (df**2 * T)
589 # = 0.5 / df (T = 1/df)
590 expected[i] = 0.5 / df
592 print('The power should be a peak at {} Hz of {} ({}, {})'.format(
593 sin_freq, expected[i], freq_axis[imax], power[imax]))
595 for i in range(len(freq_axis)):
596 Pexp += expected[i] * df
598 print('The total power should be {} ({})'.format(Pexp, P))
601 figure = _pyplot.figure()
602 time_axes = figure.add_subplot(2, 1, 1)
604 _numpy.arange(0, samples / samp_freq, 1.0 / samp_freq), x, 'b-')
605 time_axes.set_title('time series')
606 freq_axes = figure.add_subplot(2, 1, 2)
607 freq_axes.plot(freq_axis, power, 'r.')
608 freq_axes.plot(freq_axis, expected, 'b-')
610 '{} samples of sin at {} Hz'.format(samples, sin_freq))
613 "Test unitary power spectrums on variously shaped sin functions"
614 self.run_sin(sin_freq=5, samp_freq=512, samples=1024)
615 self.run_sin(sin_freq=5, samp_freq=512, samples=2048)
616 self.run_sin(sin_freq=5, samp_freq=512, samples=4098)
617 self.run_sin(sin_freq=7, samp_freq=512, samples=1024)
618 self.run_sin(sin_freq=5, samp_freq=1024, samples=2048)
619 # finally, with some irrational numbers, to check that I'm not
622 sin_freq=_numpy.pi, samp_freq=100 * _numpy.exp(1), samples=1024)
623 # test with non-integer number of periods
624 self.run_sin(sin_freq=5, samp_freq=512, samples=256)
626 def run_delta(self, amp=1, samp_freq=1, samples=256):
629 x = _numpy.zeros((samples,), dtype=_numpy.float)
630 samp_freq = _numpy.float(samp_freq)
632 freq_axis,power = unitary_power_spectrum(x, samp_freq)
634 # power = <x(t)**2> = (amp)**2 * dt/T
635 # we spread that power over the entire freq_axis [0,fN], so
636 # P(f) = (amp)**2 dt / (T fN)
638 # dt = 1/samp_freq (sample period)
639 # T = samples/samp_freq (total time of data aquisition)
640 # fN = 0.5 samp_freq (Nyquist frequency)
642 # P(f) = amp**2 / (samp_freq * samples/samp_freq * 0.5 samp_freq)
643 # = 2 amp**2 / (samp_freq*samples)
644 expected_amp = 2.0 * amp**2 / (samp_freq * samples)
645 expected = _numpy.ones(
646 (len(freq_axis),), dtype=_numpy.float) * expected_amp
648 print('The power should be flat at y = {} ({})'.format(
649 expected_amp, power[0]))
652 figure = _pyplot.figure()
653 time_axes = figure.add_subplot(2, 1, 1)
655 _numpy.arange(0, samples / samp_freq, 1.0 / samp_freq), x, 'b-')
656 time_axes.set_title('time series')
657 freq_axes = figure.add_subplot(2, 1, 2)
658 freq_axes.plot(freq_axis, power, 'r.')
659 freq_axes.plot(freq_axis, expected, 'b-')
660 freq_axes.set_title('{} samples of delta amp {}'.format(samples, amp))
662 def test_delta(self):
663 "Test unitary power spectrums on various delta functions"
664 self.run_delta(amp=1, samp_freq=1.0, samples=1024)
665 self.run_delta(amp=1, samp_freq=1.0, samples=2048)
666 # expected = 2*computed
667 self.run_delta(amp=1, samp_freq=0.5, samples=2048)
668 # expected = 0.5*computed
669 self.run_delta(amp=1, samp_freq=2.0, samples=2048)
670 self.run_delta(amp=3, samp_freq=1.0, samples=1024)
671 self.run_delta(amp=_numpy.pi, samp_freq=_numpy.exp(1), samples=1024)
673 def gaussian(self, area, mean, std, t):
674 "Integral over all time = area (i.e. normalized for area=1)"
675 return area / (std * _numpy.sqrt(2.0 * _numpy.pi)) * _numpy.exp(
676 -0.5 * ((t-mean)/std)**2)
678 def run_gaussian(self, area=2.5, mean=5, std=1, samp_freq=10.24,
682 x = _numpy.zeros((samples,), dtype=_numpy.float)
683 mean = _numpy.float(mean)
684 for i in range(samples):
685 t = i / _numpy.float(samp_freq)
686 x[i] = self.gaussian(area, mean, std, t)
687 freq_axis,power = unitary_power_spectrum(x, samp_freq)
689 # generate the predicted curve by comparing our
690 # TestUnitaryPowerSpectrum.gaussian() form to
691 # TestUnitaryRFFT.gaussian(),
692 # we see that the Fourier transform of x(t) has parameters:
693 # std' = 1/(2 pi std) (references declaring std' = 1/std are
694 # converting to angular frequency,
695 # not frequency like we are)
696 # area' = area/[std sqrt(2*pi)] (plugging into FT of
697 # TestUnitaryRFFT.gaussian() above)
698 # mean' = 0 (changing the mean in the time-domain just
699 # changes the phase in the freq-domain)
700 # So our power spectral density per unit time is given by
701 # P(f) = 2 |X(f)|**2 / T
703 # T = samples/samp_freq (total time of data aquisition)
705 area = area / (std * _numpy.sqrt(2.0 * _numpy.pi))
706 std = 1.0 / (2.0 * _numpy.pi * std)
707 expected = _numpy.zeros((len(freq_axis),), dtype=_numpy.float)
708 # 1/total_time ( = freq_axis[1]-freq_axis[0] = freq_axis[1])
709 df = _numpy.float(samp_freq) / samples
710 for i in range(len(freq_axis)):
712 gaus = self.gaussian(area, mean, std, f)
713 expected[i] = 2.0 * gaus**2 * samp_freq / samples
714 print(('The power should be a half-gaussian, '
715 'with a peak at 0 Hz with amplitude {} ({})').format(
716 expected[0], power[0]))
719 figure = _pyplot.figure()
720 time_axes = figure.add_subplot(2, 1, 1)
722 _numpy.arange(0, samples / samp_freq, 1.0 / samp_freq),
724 time_axes.set_title('time series')
725 freq_axes = figure.add_subplot(2, 1, 2)
726 freq_axes.plot(freq_axis, power, 'r.')
727 freq_axes.plot(freq_axis, expected, 'b-')
728 freq_axes.set_title('freq series')
730 def test_gaussian(self):
731 "Test unitary power spectrums on various gaussian functions"
732 for area in [1, _numpy.pi]:
733 for std in [1, _numpy.sqrt(2)]:
734 for samp_freq in [10.0, _numpy.exp(1)]:
735 for samples in [1024, 2048]:
737 area=area, std=std, samp_freq=samp_freq,
741 class TestUnitaryAvgPowerSpectrum (_unittest.TestCase):
742 def run_sin(self, sin_freq=10, samp_freq=512, samples=1024, chunk_size=512,
743 overlap=True, window=window_hann):
746 x = _numpy.zeros((samples,), dtype=_numpy.float)
747 samp_freq = _numpy.float(samp_freq)
748 for i in range(samples):
749 x[i] = _numpy.sin(2.0 * _numpy.pi * (i / samp_freq) * sin_freq)
750 freq_axis,power = unitary_avg_power_spectrum(
751 x, samp_freq, chunk_size, overlap, window)
752 imax = _numpy.argmax(power)
754 expected = _numpy.zeros((len(freq_axis),), dtype=_numpy.float)
755 # df = 1/T, where T = total_time
756 df = samp_freq / _numpy.float(chunk_size)
757 i = int(sin_freq / df)
758 # see TestUnitaryPowerSpectrum.run_unitary_power_spectrum_sin()
759 expected[i] = 0.5 / df
761 print('The power should peak at {} Hz of {} ({}, {})'.format(
762 sin_freq, expected[i], freq_axis[imax], power[imax]))
764 for i in range(len(freq_axis)):
765 Pexp += expected[i] * df
767 print('The total power should be {} ({})'.format(Pexp, P))
770 figure = _pyplot.figure()
771 time_axes = figure.add_subplot(2, 1, 1)
773 _numpy.arange(0, samples / samp_freq, 1.0 / samp_freq),
775 time_axes.set_title('time series')
776 freq_axes = figure.add_subplot(2, 1, 2)
777 freq_axes.plot(freq_axis, power, 'r.')
778 freq_axes.plot(freq_axis, expected, 'b-')
780 '{} samples of sin at {} Hz'.format(samples, sin_freq))
783 "Test unitary avg power spectrums on variously shaped sin functions."
784 self.run_sin(sin_freq=5, samp_freq=512, samples=1024)
785 self.run_sin(sin_freq=5, samp_freq=512, samples=2048)
786 self.run_sin(sin_freq=5, samp_freq=512, samples=4098)
787 self.run_sin(sin_freq=17, samp_freq=512, samples=1024)
788 self.run_sin(sin_freq=5, samp_freq=1024, samples=2048)
789 # test long wavelenth sin, so be closer to window frequency
790 self.run_sin(sin_freq=1, samp_freq=1024, samples=2048)
791 # finally, with some irrational numbers, to check that I'm not
794 sin_freq=_numpy.pi, samp_freq=100 * _numpy.exp(1), samples=1024)