debug.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import cmsisdsp as dsp
  2. import cmsisdsp.fixedpoint as f
  3. import numpy as np
  4. from scipy import signal
  5. import matplotlib.pyplot as plt
  6. import scipy.fft
  7. import colorama
  8. from colorama import init,Fore, Back, Style
  9. from numpy.testing import assert_allclose
  10. init()
  11. def printTitle(s):
  12. print("\n" + Fore.GREEN + Style.BRIGHT + s + Style.RESET_ALL)
  13. def printSubTitle(s):
  14. print("\n" + Style.BRIGHT + s + Style.RESET_ALL)
  15. def chop(A, eps = 1e-6):
  16. B = np.copy(A)
  17. B[np.abs(A) < eps] = 0
  18. return B
  19. nb = 32
  20. signal = np.cos(2 * np.pi * np.arange(nb) / nb)*np.cos(0.2*2 * np.pi * np.arange(nb) / nb)
  21. ref=scipy.fft.rfft(signal)
  22. invref = scipy.fft.irfft(ref)
  23. print(f"ref length = {len(ref)}")
  24. print(ref)
  25. # Convert ref to CMSIS-DSP format
  26. referenceFloat=np.zeros(2*len(ref))
  27. print(f"referenceFloat length = {len(referenceFloat)}")
  28. # Replace complex datatype by real datatype
  29. referenceFloat[0::2] = np.real(ref)
  30. referenceFloat[1::2] = np.imag(ref)
  31. # Copy Nyquist frequency value into first
  32. # sample.This is just a storage trick so that the
  33. # output of the RFFT has same length as input
  34. # It is legacy behavior that we need to keep
  35. # for backward compatibility but it is not
  36. # very pretty
  37. #referenceFloat[1] = np.real(ref[-1])
  38. rifftQ31=dsp.arm_rfft_instance_q31()
  39. status=dsp.arm_rfft_init_q31(rifftQ31,nb,1,1)
  40. # Apply CMSIS-DSP scaling
  41. referenceQ31 = f.toQ31(referenceFloat / nb)
  42. resultQ31 = dsp.arm_rfft_q31(rifftQ31,referenceQ31)
  43. resultF = f.Q31toF32(resultQ31)
  44. print(f"resultF length = {len(resultF)}")
  45. assert_allclose(invref/nb,resultF,atol=1e-6)
  46. signalQ31 = f.toQ31(signal)
  47. rfftQ31=dsp.arm_rfft_instance_q31()
  48. status=dsp.arm_rfft_init_q31(rfftQ31,nb,0,1)
  49. resultQ31 = dsp.arm_rfft_q31(rfftQ31,signalQ31)
  50. print(len(resultQ31))
  51. print(2*nb)
  52. resultF = f.Q31toF32(resultQ31) * nb
  53. def compareWithConjugatePart(r):
  54. res = r[0::2] + 1j * r[1::2]
  55. conjPart = res[nb:nb//2:-1].conj()
  56. refPart = res[1:nb//2]
  57. assert(np.equal(refPart , conjPart).all())
  58. compareWithConjugatePart(resultF)
  59. res = resultF[0::2] + 1j * resultF[1::2]
  60. print(res)
  61. print(res[0:nb//2+1])
  62. print(res[0:nb//2+1].shape)