compfft.py 2.1 KB

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