comparison ext/kissfft/test/compfft.py @ 184:76ec2365b250

Bring in kissfft into this repo (formerly a subrepo, but the remote is not responding)
author Chris Cannam
date Tue, 21 Jul 2015 07:34:15 +0100
parents
children
comparison
equal deleted inserted replaced
183:7ab3539e92e3 184:76ec2365b250
1 #!/usr/bin/env python
2
3 # use FFTPACK as a baseline
4 import FFT
5 from Numeric import *
6 import math
7 import random
8 import sys
9 import struct
10 import fft
11
12 pi=math.pi
13 e=math.e
14 j=complex(0,1)
15 lims=(-32768,32767)
16
17 def randbuf(n,cpx=1):
18 res = array( [ random.uniform( lims[0],lims[1] ) for i in range(n) ] )
19 if cpx:
20 res = res + j*randbuf(n,0)
21 return res
22
23 def main():
24 from getopt import getopt
25 import popen2
26 opts,args = getopt( sys.argv[1:],'u:n:Rt:' )
27 opts=dict(opts)
28 exitcode=0
29
30 util = opts.get('-u','./kf_float')
31
32 try:
33 dims = [ int(d) for d in opts['-n'].split(',')]
34 cpx = opts.get('-R') is None
35 fmt=opts.get('-t','f')
36 except KeyError:
37 sys.stderr.write("""
38 usage: compfft.py
39 -n d1[,d2,d3...] : FFT dimension(s)
40 -u utilname : see sample_code/fftutil.c, default = ./kf_float
41 -R : real-optimized version\n""")
42 sys.exit(1)
43
44 x = fft.make_random( dims )
45
46 cmd = '%s -n %s ' % ( util, ','.join([ str(d) for d in dims]) )
47 if cpx:
48 xout = FFT.fftnd(x)
49 xout = reshape(xout,(size(xout),))
50 else:
51 cmd += '-R '
52 xout = FFT.real_fft(x)
53
54 proc = popen2.Popen3( cmd , bufsize=len(x) )
55
56 proc.tochild.write( dopack( x , fmt ,cpx ) )
57 proc.tochild.close()
58 xoutcomp = dounpack( proc.fromchild.read( ) , fmt ,1 )
59 #xoutcomp = reshape( xoutcomp , dims )
60
61 sig = xout * conjugate(xout)
62 sigpow = sum( sig )
63
64 diff = xout-xoutcomp
65 noisepow = sum( diff * conjugate(diff) )
66
67 snr = 10 * math.log10(abs( sigpow / noisepow ) )
68 if snr<100:
69 print xout
70 print xoutcomp
71 exitcode=1
72 print 'NFFT=%s,SNR = %f dB' % (str(dims),snr)
73 sys.exit(exitcode)
74
75 def dopack(x,fmt,cpx):
76 x = reshape( x, ( size(x),) )
77 if cpx:
78 s = ''.join( [ struct.pack('ff',c.real,c.imag) for c in x ] )
79 else:
80 s = ''.join( [ struct.pack('f',c) for c in x ] )
81 return s
82
83 def dounpack(x,fmt,cpx):
84 uf = fmt * ( len(x) / 4 )
85 s = struct.unpack(uf,x)
86 if cpx:
87 return array(s[::2]) + array( s[1::2] )*j
88 else:
89 return array(s )
90
91 if __name__ == "__main__":
92 main()