Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132922 views
License: OTHER
1
""" Code example from Complexity and Computation, a book about
2
exploring complexity science with Python. Available free from
3
4
http://greenteapress.com/complexity
5
6
Copyright 2011 Allen B. Downey.
7
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
8
"""
9
10
# importing cmath makes exp and other math functions handle
11
# complex numbers
12
from cmath import *
13
14
import numpy
15
import matplotlib.pyplot as pyplot
16
17
18
def fft(h):
19
"""Computes the discrete Fourier transform of the sequence h.
20
Assumes that len(h) is a power of two.
21
"""
22
N = len(h)
23
24
# the Fourier transform of a single value is itself
25
if N == 1: return h
26
27
# recursively compute the FFT of the even and odd values
28
He = fft(h[0:N:2])
29
Ho = fft(h[1:N:2])
30
31
# merge the half-FFTs
32
i = complex(0,1)
33
W = exp(2*pi*i/N)
34
ws = [pow(W,k) for k in range(N)]
35
H = [e + w*o for w, e, o in zip(ws, He+He, Ho+Ho)]
36
return H
37
38
def psd(H, N):
39
p = [Hn * Hn.conjugate() for Hn in H]
40
freqs = range(N/2 + 1)
41
p = [p[f].real for f in freqs]
42
return freqs, p
43
44
def main(script, use_numpy=False):
45
# make a signal with two sine components, f=6 and f=12
46
N = 128
47
t = [1.0*n/N for n in range(N)]
48
h = [sin(2*pi*6*tn) + sin(2*pi*12*tn) for tn in t]
49
50
# compute the Fourier transform
51
if use_numpy:
52
H = numpy.fft.fft(h)
53
else:
54
H = fft(h)
55
56
# compute the power spectral density
57
freqs, p = psd(H, N)
58
59
# plot the real part
60
pyplot.bar(freqs, p)
61
pyplot.xlabel('frequency')
62
pyplot.ylabel('amplitude')
63
pyplot.show()
64
65
# estimate the power spectral density by Welches average
66
# periodogram method using the psd function provided by pylab.
67
pyplot.show()
68
69
if __name__ == '__main__':
70
import sys
71
main(*sys.argv)
72
73
74