1 # Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Hooke. If not, see <http://www.gnu.org/licenses/>.
18 """Wrap :mod:`numpy.fft` to produce 1D unitary transforms and power spectra.
20 Define some FFT wrappers to reduce clutter.
21 Provides a unitary discrete FFT and a windowed version.
22 Based on :func:`numpy.fft.rfft`.
26 * :func:`unitary_rfft`
27 * :func:`power_spectrum`
28 * :func:`unitary_power_spectrum`
29 * :func:`avg_power_spectrum`
30 * :func:`unitary_avg_power_spectrum`
35 from numpy import log2, floor, round, ceil, abs, pi, exp, cos, sin, sqrt, \
36 sinc, arctan2, array, ones, arange, linspace, zeros, \
37 uint16, float, concatenate, fromfile, argmax, complex
38 from numpy.fft import rfft
43 def floor_pow_of_two(num):
44 """Round `num` down to the closest exact a power of two.
49 >>> floor_pow_of_two(3)
51 >>> floor_pow_of_two(11)
53 >>> floor_pow_of_two(15)
61 def round_pow_of_two(num):
62 """Round `num` to the closest exact a power of two on a log scale.
67 >>> round_pow_of_two(2.9) # Note rounding on *log scale*
69 >>> round_pow_of_two(11)
71 >>> round_pow_of_two(15)
79 def ceil_pow_of_two(num):
80 """Round `num` up to the closest exact a power of two.
85 >>> ceil_pow_of_two(3)
87 >>> ceil_pow_of_two(11)
89 >>> ceil_pow_of_two(15)
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 = rfft(data[0:nsamps]) / float(freq)
154 freq_axis = linspace(0, freq/2, nsamps/2+1)
155 return (freq_axis, trans)
157 def power_spectrum(data, freq=1.0):
158 """Compute the power spectrum of the time series `data`.
163 Real (not complex) data taken with a sampling frequency `freq`.
169 freq_axis,power : numpy.ndarray
170 Arrays ready for plotting.
174 If the number of samples in `data` is not an integer power of two,
175 the FFT ignores some of the later points.
179 unitary_power_spectrum,avg_power_spectrum
181 nsamps = floor_pow_of_two(len(data))
183 freq_axis = linspace(0, freq/2, nsamps/2+1)
184 # nsamps/2+1 b/c zero-freq and nyqist-freq are both fully real.
185 # >>> help(numpy.fft.fftpack.rfft) for Numpy's explaination.
186 # See Numerical Recipies for a details.
187 trans = rfft(data[0:nsamps])
188 power = trans * trans.conj() # We want the square of the amplitude.
189 return (freq_axis, power)
191 def unitary_power_spectrum(data, freq=1.0):
192 """Compute the unitary power spectrum of the time series `data`.
196 power_spectrum,unitary_avg_power_spectrum
198 freq_axis,power = power_spectrum(data, freq)
199 # One sided power spectral density, so 2|H(f)|**2 (see NR 2nd edition 12.0.14, p498)
201 # numpy normalizes with 1/N on the inverse transform ifft,
202 # so we should normalize the freq-space representation with 1/sqrt(N).
203 # But we're using the rfft, where N points are like N/2 complex points, so 1/sqrt(N/2)
204 # So the power gets normalized by that twice and we have 2/N
206 # On top of this, the FFT assumes a sampling freq of 1 per second,
207 # and we want to preserve area under our curves.
208 # If our total time T = len(data)/freq is smaller than 1,
209 # our df_real = freq/len(data) is bigger that the FFT expects (dt_fft = 1/len(data)),
210 # and we need to scale the powers down to conserve area.
211 # df_fft * F_fft(f) = df_real *F_real(f)
212 # F_real = F_fft(f) * (1/len)/(freq/len) = F_fft(f)*freq
213 # So the power gets normalized by *that* twice and we have 2/N * freq**2
215 # power per unit time
216 # measure x(t) for time T
217 # X(f) = int_0^T x(t) exp(-2 pi ift) dt
218 # PSD(f) = 2 |X(f)|**2 / T
220 # total_time = len(data)/float(freq)
221 # power *= 2.0 / float(freq)**2 / total_time
222 # power *= 2.0 / freq**2 * freq / len(data)
223 power *= 2.0 / (freq * float(len(data)))
225 return (freq_axis, power)
227 def window_hann(length):
228 r"""Returns a Hann window array with length entries
232 The Hann window with length :math:`L` is defined as
234 .. math:: w_i = \frac{1}{2} (1-\cos(2\pi i/L))
236 win = zeros((length,), dtype=float)
237 for i in range(length):
238 win[i] = 0.5*(1.0-cos(2.0*pi*float(i)/(length)))
239 # avg value of cos over a period is 0
240 # so average height of Hann window is 0.5
243 def avg_power_spectrum(data, freq=1.0, chunk_size=2048,
244 overlap=True, window=window_hann):
245 """Compute the avgerage power spectrum of `data`.
250 Real (not complex) data taken with a sampling frequency `freq`.
254 Number of samples per chunk. Use a power of two.
255 overlap: {True,False}
256 If `True`, each chunk overlaps the previous chunk by half its
257 length. Otherwise, the chunks are end-to-end, and not
260 Weights used to "smooth" the chunks, there is a whole science
261 behind windowing, but if you're not trying to squeeze every
262 drop of information out of your data, you'll be OK with the
267 freq_axis,power : numpy.ndarray
268 Arrays ready for plotting.
272 The average power spectrum is computed by breaking `data` into
273 chunks of length `chunk_size`. These chunks are transformed
274 individually into frequency space and then averaged together.
276 See Numerical Recipes 2 section 13.4 for a good introduction to
279 If the number of samples in `data` is not a multiple of
280 `chunk_size`, we ignore the extra points.
282 assert chunk_size == floor_pow_of_two(chunk_size), \
283 "chunk_size %d should be a power of 2" % chunk_size
285 nchunks = len(data)/chunk_size # integer division = implicit floor
287 chunk_step = chunk_size/2
289 chunk_step = chunk_size
291 win = window(chunk_size) # generate a window of the appropriate size
292 freq_axis = linspace(0, freq/2, chunk_size/2+1)
293 # nsamps/2+1 b/c zero-freq and nyqist-freq are both fully real.
294 # >>> help(numpy.fft.fftpack.rfft) for Numpy's explaination.
295 # See Numerical Recipies for a details.
296 power = zeros((chunk_size/2+1,), dtype=float)
297 for i in range(nchunks):
298 starti = i*chunk_step
299 stopi = starti+chunk_size
300 fft_chunk = rfft(data[starti:stopi]*win)
301 p_chunk = fft_chunk * fft_chunk.conj()
302 power += p_chunk.astype(float)
303 power /= float(nchunks)
304 return (freq_axis, power)
306 def unitary_avg_power_spectrum(data, freq=1.0, chunk_size=2048,
307 overlap=True, window=window_hann):
308 """Compute the unitary average power spectrum of `data`.
312 avg_power_spectrum,unitary_power_spectrum
314 freq_axis,power = avg_power_spectrum(data, freq, chunk_size,
316 # 2.0 / (freq * chunk_size) |rfft()|**2 --> unitary_power_spectrum
317 power *= 2.0 / (freq*float(chunk_size)) * 8/3 # see unitary_power_spectrum()
318 # * 8/3 to remove power from windowing
319 # <[x(t)*w(t)]**2> = <x(t)**2 * w(t)**2> ~= <x(t)**2> * <w(t)**2>
320 # where the ~= is because the frequency of x(t) >> the frequency of w(t).
321 # So our calulated power has and extra <w(t)**2> in it.
322 # For the Hann window, <w(t)**2> = <0.5(1 + 2cos + cos**2)> = 1/4 + 0 + 1/8 = 3/8
323 # For low frequency components, where the frequency of x(t) is ~= the frequency of w(t),
324 # The normalization is not perfect. ??
325 # The normalization approaches perfection as chunk_size -> infinity.
326 return (freq_axis, power)
330 class TestRFFT (unittest.TestCase):
331 r"""Ensure Numpy's FFT algorithm acts as expected.
335 The expected return values are [#dft]_:
337 .. math:: X_k = \sum_{m=0}^{n-1} x_m \exp^{-2\pi imk/n}
339 .. [#dft] See the *Background information* section of :mod:`numpy.fft`.
341 def run_rfft(self, xs, Xs):
346 Xa.append(sum([x*exp(-2*pi*i*m*k/n) for x,m in zip(xs,range(n))]))
348 assert (Xs[k]-Xa[k])/abs(Xa[k]) < 1e-6, \
349 "rfft mismatch on element %d: %g != %g, relative error %g" \
350 % (k, Xs[k], Xa[k], (Xs[k]-Xa[k])/abs(Xa[k]))
351 # Which should satisfy the discrete form of Parseval's theorem
353 # SUM |x_m|^2 = 1/n SUM |X_k|^2.
355 timeSum = sum([abs(x)**2 for x in xs])
356 freqSum = sum([abs(X)**2 for X in Xa])
357 assert abs(freqSum/float(n) - timeSum)/timeSum < 1e-6, \
358 "Mismatch on Parseval's, %g != 1/%d * %g" % (timeSum, n, freqSum)
361 xs = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1]
362 self.run_rfft(xs, rfft(xs))
364 class TestUnitaryRFFT (unittest.TestCase):
365 """Verify `unitary_rfft`.
367 def run_unitary_rfft_parsevals(self, xs, freq, freqs, Xs):
368 """Check the discretized integral form of Parseval's theorem
374 .. math:: \sum_{m=0}^{n-1} |x_m|^2 dt = \sum_{k=0}^{n-1} |X_k|^2 df
377 df = freqs[1]-freqs[0]
378 assert (df - 1/(len(xs)*dt))/df < 1e-6, \
379 "Mismatch in spacing, %g != 1/(%d*%g)" % (df, len(xs), dt)
381 for k in range(len(Xs)-1,1,-1):
383 assert len(xs) == len(Xa), "Length mismatch %d != %d" % (len(xs), len(Xa))
384 lhs = sum([abs(x)**2 for x in xs]) * dt
385 rhs = sum([abs(X)**2 for X in Xa]) * df
386 assert abs(lhs - rhs)/lhs < 1e-4, "Mismatch on Parseval's, %g != %g" \
389 def test_unitary_rfft_parsevals(self):
390 "Test unitary rfft on Parseval's theorem"
391 xs = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1]
393 freqs,Xs = unitary_rfft(xs, 1.0/dt)
394 self.run_unitary_rfft_parsevals(xs, 1.0/dt, freqs, Xs)
397 r"""Rectangle function.
404 \rect(t) = \begin{cases}
405 1& \text{if $|t| < 0.5$}, \\
406 0& \text{if $|t| \ge 0.5$}.
414 def run_unitary_rfft_rect(self, a=1.0, time_shift=5.0, samp_freq=25.6,
416 r"""Test `unitary_rttf` on known function `rect(at)`.
422 .. math:: \rfft(\rect(at)) = 1/|a|\cdot\sinc(f/a)
424 samp_freq = float(samp_freq)
427 x = zeros((samples,), dtype=float)
429 for i in range(samples):
431 x[i] = self.rect(a*(t-time_shift))
432 freq_axis, X = unitary_rfft(x, samp_freq)
433 #_test_unitary_rfft_parsevals(x, samp_freq, freq_axis, X)
435 # remove the phase due to our time shift
436 j = complex(0.0,1.0) # sqrt(-1)
437 for i in range(len(freq_axis)):
439 inverse_phase_shift = exp(j*2.0*pi*time_shift*f)
440 X[i] *= inverse_phase_shift
442 expected = zeros((len(freq_axis),), dtype=float)
443 # normalized sinc(x) = sin(pi x)/(pi x)
444 # so sinc(0.5) = sin(pi/2)/(pi/2) = 2/pi
445 assert sinc(0.5) == 2.0/pi, "abnormal sinc()"
446 for i in range(len(freq_axis)):
448 expected[i] = 1.0/abs(a) * sinc(f/a)
453 pylab.plot(arange(0, dt*samples, dt), x)
454 pylab.title('time series')
456 pylab.plot(freq_axis, X.real, 'r.')
457 pylab.plot(freq_axis, X.imag, 'g.')
458 pylab.plot(freq_axis, expected, 'b-')
459 pylab.title('freq series')
461 def test_unitary_rfft_rect(self):
462 "Test unitary FFTs on variously shaped rectangular functions."
463 self.run_unitary_rfft_rect(a=0.5)
464 self.run_unitary_rfft_rect(a=2.0)
465 self.run_unitary_rfft_rect(a=0.7, samp_freq=50, samples=512)
466 self.run_unitary_rfft_rect(a=3.0, samp_freq=60, samples=1024)
468 def gaussian(self, a, t):
469 r"""Gaussian function.
474 .. math:: \gaussian(a,t) = \exp^{-at^2}
476 return exp(-a * t**2)
478 def run_unitary_rfft_gaussian(self, a=1.0, time_shift=5.0, samp_freq=25.6,
480 r"""Test `unitary_rttf` on known function `gaussian(a,t)`.
488 \rfft(\gaussian(a,t)) = \sqrt{\pi/a} \cdot \gaussian(1/a,\pi f)
490 samp_freq = float(samp_freq)
493 x = zeros((samples,), dtype=float)
495 for i in range(samples):
497 x[i] = self.gaussian(a, (t-time_shift))
498 freq_axis, X = unitary_rfft(x, samp_freq)
499 #_test_unitary_rfft_parsevals(x, samp_freq, freq_axis, X)
501 # remove the phase due to our time shift
502 j = complex(0.0,1.0) # sqrt(-1)
503 for i in range(len(freq_axis)):
505 inverse_phase_shift = exp(j*2.0*pi*time_shift*f)
506 X[i] *= inverse_phase_shift
508 expected = zeros((len(freq_axis),), dtype=float)
509 for i in range(len(freq_axis)):
511 expected[i] = sqrt(pi/a) * self.gaussian(1.0/a, pi*f) # see Wikipedia, or do the integral yourself.
516 pylab.plot(arange(0, dt*samples, dt), x)
517 pylab.title('time series')
519 pylab.plot(freq_axis, X.real, 'r.')
520 pylab.plot(freq_axis, X.imag, 'g.')
521 pylab.plot(freq_axis, expected, 'b-')
522 pylab.title('freq series')
524 def test_unitary_rfft_gaussian(self):
525 "Test unitary FFTs on variously shaped gaussian functions."
526 self.run_unitary_rfft_gaussian(a=0.5)
527 self.run_unitary_rfft_gaussian(a=2.0)
528 self.run_unitary_rfft_gaussian(a=0.7, samp_freq=50, samples=512)
529 self.run_unitary_rfft_gaussian(a=3.0, samp_freq=60, samples=1024)
531 class TestUnitaryPowerSpectrum (unittest.TestCase):
532 def run_unitary_power_spectrum_sin(self, sin_freq=10, samp_freq=512,
534 x = zeros((samples,), dtype=float)
535 samp_freq = float(samp_freq)
536 for i in range(samples):
537 x[i] = sin(2.0 * pi * (i/samp_freq) * sin_freq)
538 freq_axis, power = unitary_power_spectrum(x, samp_freq)
541 expected = zeros((len(freq_axis),), dtype=float)
542 df = samp_freq/float(samples) # df = 1/T, where T = total_time
544 # average power per unit time is
546 # average value of sin(t)**2 = 0.5 (b/c sin**2+cos**2 == 1)
547 # so average value of (int sin(t)**2 dt) per unit time is 0.5
549 # we spread that power over a frequency bin of width df, sp
551 # where f0 is the sin's frequency
554 # FFT of sin(2*pi*t*f0) gives
555 # X(f) = 0.5 i (delta(f-f0) - delta(f-f0)),
556 # (area under x(t) = 0, area under X(f) = 0)
557 # so one sided power spectral density (PSD) per unit time is
558 # P(f) = 2 |X(f)|**2 / T
559 # = 2 * |0.5 delta(f-f0)|**2 / T
560 # = 0.5 * |delta(f-f0)|**2 / T
561 # but we're discrete and want the integral of the 'delta' to be 1,
562 # so 'delta'*df = 1 --> 'delta' = 1/df, and
563 # P(f) = 0.5 / (df**2 * T)
564 # = 0.5 / df (T = 1/df)
565 expected[i] = 0.5 / df
567 print "The power should be a peak at %g Hz of %g (%g, %g)" % \
568 (sin_freq, expected[i], freq_axis[imax], power[imax])
571 for i in range(len(freq_axis)):
572 Pexp += expected[i] *df
574 print " The total power should be %g (%g)" % (Pexp, P)
579 pylab.plot(arange(0, samples/samp_freq, 1.0/samp_freq), x, 'b-')
580 pylab.title('time series')
582 pylab.plot(freq_axis, power, 'r.')
583 pylab.plot(freq_axis, expected, 'b-')
584 pylab.title('%g samples of sin at %g Hz' % (samples, sin_freq))
586 def test_unitary_power_spectrum_sin(self):
587 "Test unitary power spectrums on variously shaped sin functions"
588 self.run_unitary_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=1024)
589 self.run_unitary_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=2048)
590 self.run_unitary_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=4098)
591 self.run_unitary_power_spectrum_sin(sin_freq=7, samp_freq=512, samples=1024)
592 self.run_unitary_power_spectrum_sin(sin_freq=5, samp_freq=1024, samples=2048)
593 # finally, with some irrational numbers, to check that I'm not getting lucky
594 self.run_unitary_power_spectrum_sin(sin_freq=pi, samp_freq=100*exp(1), samples=1024)
595 # test with non-integer number of periods
596 self.run_unitary_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=256)
598 def run_unitary_power_spectrum_delta(self, amp=1, samp_freq=1,
602 x = zeros((samples,), dtype=float)
603 samp_freq = float(samp_freq)
605 freq_axis, power = unitary_power_spectrum(x, samp_freq)
607 # power = <x(t)**2> = (amp)**2 * dt/T
608 # we spread that power over the entire freq_axis [0,fN], so
609 # P(f) = (amp)**2 dt / (T fN)
611 # dt = 1/samp_freq (sample period)
612 # T = samples/samp_freq (total time of data aquisition)
613 # fN = 0.5 samp_freq (Nyquist frequency)
615 # P(f) = amp**2 / (samp_freq * samples/samp_freq * 0.5 samp_freq)
616 # = 2 amp**2 / (samp_freq*samples)
617 expected_amp = 2.0 * amp**2 / (samp_freq * samples)
618 expected = ones((len(freq_axis),), dtype=float) * expected_amp
620 print "The power should be flat at y = %g (%g)" % (expected_amp, power[0])
625 pylab.plot(arange(0, samples/samp_freq, 1.0/samp_freq), x, 'b-')
626 pylab.title('time series')
628 pylab.plot(freq_axis, power, 'r.')
629 pylab.plot(freq_axis, expected, 'b-')
630 pylab.title('%g samples of delta amp %g' % (samples, amp))
632 def _test_unitary_power_spectrum_delta(self):
633 "Test unitary power spectrums on various delta functions"
634 _test_unitary_power_spectrum_delta(amp=1, samp_freq=1.0, samples=1024)
635 _test_unitary_power_spectrum_delta(amp=1, samp_freq=1.0, samples=2048)
636 _test_unitary_power_spectrum_delta(amp=1, samp_freq=0.5, samples=2048)# expected = 2*computed
637 _test_unitary_power_spectrum_delta(amp=1, samp_freq=2.0, samples=2048)# expected = 0.5*computed
638 _test_unitary_power_spectrum_delta(amp=3, samp_freq=1.0, samples=1024)
639 _test_unitary_power_spectrum_delta(amp=pi, samp_freq=exp(1), samples=1024)
641 def gaussian(self, area, mean, std, t):
642 "Integral over all time = area (i.e. normalized for area=1)"
643 return area/(std*sqrt(2.0*pi)) * exp(-0.5*((t-mean)/std)**2)
645 def run_unitary_power_spectrum_gaussian(self, area=2.5, mean=5, std=1,
646 samp_freq=10.24 ,samples=512):
649 x = zeros((samples,), dtype=float)
651 for i in range(samples):
652 t = i/float(samp_freq)
653 x[i] = self.gaussian(area, mean, std, t)
654 freq_axis, power = unitary_power_spectrum(x, samp_freq)
656 # generate the predicted curve
657 # by comparing our self.gaussian() form to _gaussian(),
658 # we see that the Fourier transform of x(t) has parameters:
659 # std' = 1/(2 pi std) (references declaring std' = 1/std are converting to angular frequency, not frequency like we are)
660 # area' = area/[std sqrt(2*pi)] (plugging into FT of _gaussian() above)
661 # mean' = 0 (changing the mean in the time-domain just changes the phase in the freq-domain)
662 # So our power spectral density per unit time is given by
663 # P(f) = 2 |X(f)|**2 / T
665 # T = samples/samp_freq (total time of data aquisition)
667 area = area /(std*sqrt(2.0*pi))
668 std = 1.0/(2.0*pi*std)
669 expected = zeros((len(freq_axis),), dtype=float)
670 df = float(samp_freq)/samples # 1/total_time ( = freq_axis[1]-freq_axis[0] = freq_axis[1])
671 for i in range(len(freq_axis)):
673 gaus = self.gaussian(area, mean, std, f)
674 expected[i] = 2.0 * gaus**2 * samp_freq/samples
675 print "The power should be a half-gaussian, ",
676 print "with a peak at 0 Hz with amplitude %g (%g)" % (expected[0], power[0])
681 pylab.plot(arange(0, samples/samp_freq, 1.0/samp_freq), x, 'b-')
682 pylab.title('time series')
684 pylab.plot(freq_axis, power, 'r.')
685 pylab.plot(freq_axis, expected, 'b-')
686 pylab.title('freq series')
688 def test_unitary_power_spectrum_gaussian(self):
689 "Test unitary power spectrums on various gaussian functions"
691 for std in [1,sqrt(2)]:
692 for samp_freq in [10.0, exp(1)]:
693 for samples in [1024,2048]:
694 self.run_unitary_power_spectrum_gaussian(
695 area=area, std=std, samp_freq=samp_freq,
698 class TestUnitaryAvgPowerSpectrum (unittest.TestCase):
699 def run_unitary_avg_power_spectrum_sin(self, sin_freq=10, samp_freq=512,
700 samples=1024, chunk_size=512,
701 overlap=True, window=window_hann):
704 x = zeros((samples,), dtype=float)
705 samp_freq = float(samp_freq)
706 for i in range(samples):
707 x[i] = sin(2.0 * pi * (i/samp_freq) * sin_freq)
708 freq_axis, power = unitary_avg_power_spectrum(x, samp_freq, chunk_size,
712 expected = zeros((len(freq_axis),), dtype=float)
713 df = samp_freq/float(chunk_size) # df = 1/T, where T = total_time
715 expected[i] = 0.5 / df # see _test_unitary_power_spectrum_sin()
717 print "The power should be a peak at %g Hz of %g (%g, %g)" % \
718 (sin_freq, expected[i], freq_axis[imax], power[imax])
721 for i in range(len(freq_axis)):
722 Pexp += expected[i] * df
724 print " The total power should be %g (%g)" % (Pexp, P)
729 pylab.plot(arange(0, samples/samp_freq, 1.0/samp_freq), x, 'b-')
730 pylab.title('time series')
732 pylab.plot(freq_axis, power, 'r.')
733 pylab.plot(freq_axis, expected, 'b-')
734 pylab.title('%g samples of sin at %g Hz' % (samples, sin_freq))
736 def test_unitary_avg_power_spectrum_sin(self):
737 "Test unitary avg power spectrums on variously shaped sin functions."
738 self.run_unitary_avg_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=1024)
739 self.run_unitary_avg_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=2048)
740 self.run_unitary_avg_power_spectrum_sin(sin_freq=5, samp_freq=512, samples=4098)
741 self.run_unitary_avg_power_spectrum_sin(sin_freq=17, samp_freq=512, samples=1024)
742 self.run_unitary_avg_power_spectrum_sin(sin_freq=5, samp_freq=1024, samples=2048)
743 # test long wavelenth sin, so be closer to window frequency
744 self.run_unitary_avg_power_spectrum_sin(sin_freq=1, samp_freq=1024, samples=2048)
745 # finally, with some irrational numbers, to check that I'm not getting lucky
746 self.run_unitary_avg_power_spectrum_sin(sin_freq=pi, samp_freq=100*exp(1), samples=1024)