DebugTools.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import struct
  2. import numpy as np
  3. # Tools to read the generated pattern files and the hex output files
  4. def readQ31Pattern(r):
  5. l = []
  6. with open(r, 'r') as f:
  7. f.readline()
  8. nb = int(f.readline())
  9. for i in range(nb):
  10. f.readline()
  11. # Read the hex and interpret the sign
  12. r=int(f.readline(),16)
  13. r=struct.unpack('<i', struct.pack('<I',r))[0]
  14. l.append(r)
  15. l = (1.0*np.array(l)) / 2**31
  16. #print(l)
  17. return(l)
  18. def readQ15Pattern(r):
  19. l = []
  20. with open(r, 'r') as f:
  21. f.readline()
  22. nb = int(f.readline())
  23. for i in range(nb):
  24. f.readline()
  25. # Read the hex and interpret the sign
  26. r=int(f.readline(),16)
  27. r=struct.unpack('<h', struct.pack('<H',r))[0]
  28. l.append(r)
  29. l = (1.0*np.array(l)) / 2**15
  30. #print(l)
  31. return(l)
  32. def hex2float(h):
  33. return(struct.unpack('<f', struct.pack('<I', int(h,16)))[0])
  34. def hex2f16(h):
  35. return(struct.unpack('<e', struct.pack('<H', int(h,16)))[0])
  36. def readF32Pattern(r):
  37. l = []
  38. with open(r, 'r') as f:
  39. f.readline()
  40. nb = int(f.readline())
  41. for i in range(nb):
  42. f.readline()
  43. l.append(hex2float(f.readline()))
  44. l = (1.0*np.array(l))
  45. #print(l)
  46. return(l)
  47. def readF16Pattern(r):
  48. l = []
  49. with open(r, 'r') as f:
  50. f.readline()
  51. nb = int(f.readline())
  52. for i in range(nb):
  53. f.readline()
  54. l.append(hex2f16(f.readline()))
  55. l = (1.0*np.array(l))
  56. #print(l)
  57. return(l)
  58. # Read the hex and interpret the sign
  59. def hexToQ31(s):
  60. r = int(s,0)
  61. r=struct.unpack('<i', struct.pack('<I',r))[0]
  62. return(r)
  63. # Read the hex and interpret the sign
  64. def hexToQ15(s):
  65. r = int(s,0)
  66. r=struct.unpack('<i', struct.pack('<I',r))[0]
  67. return(r)
  68. def readQ31Output(path):
  69. sig = np.loadtxt(path, delimiter=',',dtype="int64",converters= {0:hexToQ31})
  70. sig = 1.0 * sig / 2**31
  71. return(sig)
  72. def readQ15Output(path):
  73. sig = np.loadtxt(path, delimiter=',',dtype="int64",converters= {0:hexToQ15})
  74. sig = 1.0 * sig / 2**15
  75. return(sig)
  76. def readF32Output(path):
  77. sig = np.loadtxt(path, delimiter=',',dtype="float",converters= {0:hex2float})
  78. sig = 1.0 * sig
  79. return(sig)
  80. def readF16Output(path):
  81. sig = np.loadtxt(path, delimiter=',',dtype="float",converters= {0:hex2f16})
  82. sig = 1.0 * sig
  83. return(sig)
  84. def SNR(ref,sig):
  85. energy = np.dot(ref,np.conj(ref))
  86. error = np.dot(ref-sig,np.conj(ref-sig))
  87. snr = 10 * np.log10(energy/error)
  88. return(snr)