example.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import cmsisdsp as dsp
  2. import numpy as np
  3. from scipy import signal
  4. from pylab import figure, clf, plot, xlabel, ylabel, xlim, ylim, title, grid, axes, show,semilogx, semilogy
  5. # Data file from https://archive.physionet.org/pn3/ecgiddb/Person_87/rec_2.dat
  6. def q31sat(x):
  7. if x > 0x7FFFFFFF:
  8. return(np.int32(0x7FFFFFFF))
  9. elif x < -0x80000000:
  10. return(np.int32(0x80000000))
  11. else:
  12. return(np.int32(x))
  13. q31satV=np.vectorize(q31sat)
  14. def toQ31(x):
  15. return(q31satV(np.round(x * (1<<31))))
  16. def Q31toF32(x):
  17. return(1.0*x / 2**31)
  18. filename = 'rec_2.dat'
  19. f = open(filename,"r")
  20. sig = np.fromfile(f, dtype=np.int16)
  21. f.closed
  22. sig = 1.0*sig / (1 << 12)
  23. p0 = np.exp(1j*0.05) * 0.98
  24. p1 = np.exp(1j*0.25) * 0.9
  25. p2 = np.exp(1j*0.45) * 0.97
  26. z0 = np.exp(1j*0.02)
  27. z1 = np.exp(1j*0.65)
  28. z2 = np.exp(1j*1.0)
  29. g = 0.02
  30. nb = 300
  31. sos = signal.zpk2sos(
  32. [z0,np.conj(z0),z1,np.conj(z1),z2,np.conj(z2)]
  33. ,[p0, np.conj(p0),p1, np.conj(p1),p2, np.conj(p2)]
  34. ,g)
  35. res=signal.sosfilt(sos,sig)
  36. figure()
  37. plot(sig[1:nb])
  38. figure()
  39. plot(res[1:nb])
  40. biquadQ31 = dsp.arm_biquad_casd_df1_inst_q31()
  41. numStages=3
  42. state=np.zeros(numStages*4)
  43. # For use in CMSIS, denominator coefs must be negated
  44. # and first a0 coef wihich is always 1 must be removed
  45. coefs=np.reshape(np.hstack((sos[:,:3],-sos[:,4:])),15)
  46. coefs = coefs / 4.0
  47. coefsQ31 = toQ31(coefs)
  48. postshift = 2
  49. dsp.arm_biquad_cascade_df1_init_q31(biquadQ31,numStages,coefsQ31,state,postshift)
  50. sigQ31=toQ31(sig)
  51. nbSamples=sigQ31.shape[0]
  52. # Here we demonstrate how we can process a long sequence of samples per block
  53. # and thus check that the state of the biquad is well updated and preserved
  54. # between the calls.
  55. half = int(round(nbSamples / 2))
  56. res2a=dsp.arm_biquad_cascade_df1_q31(biquadQ31,sigQ31[1:half])
  57. res2b=dsp.arm_biquad_cascade_df1_q31(biquadQ31,sigQ31[half+1:nbSamples])
  58. res2=Q31toF32(np.hstack((res2a,res2b)))
  59. figure()
  60. plot(res2[1:nb])
  61. show()#