phase-encoding-method-of-moments.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. #from scipy.special import gamma, binom
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. from mpmath import mp, mpf
  7. mp.dps = 200
  8. voxel_num = 5
  9. phase_range = mp.pi/2
  10. phase_init = mp.pi/4 #mpf(0.0)
  11. U_points = voxel_num * 1000
  12. noise_ratio = mpf(0.0*1e-38) #1e8
  13. total_periods = 10
  14. rf_samples_per_period = 10
  15. # max polynomial order equals rf_samples_per_period * total_periods
  16. # B0=1.5T freq=64Mhz, period = 15.6 ns
  17. period = mpf(10) #ms
  18. omega = 2.0*mp.pi/period
  19. #T2s_scale = 0.01 #ms # need to be 10ms
  20. T2s_scale = total_periods*period/15 #ms # need to be 10ms
  21. T2s_min = T2s_scale/10.0
  22. #print(period)
  23. #ms
  24. time_steps = np.array(mp.linspace(mpf(0), mpf(period*total_periods), rf_samples_per_period*total_periods))
  25. tmp = [mp.rand() for n in range(voxel_num)]
  26. voxel_amplitudes = np.array(tmp)
  27. tmp = [mp.rand() for n in range(voxel_num)]
  28. voxel_T2s_decay = np.array(tmp)*(T2s_scale-2*T2s_min) + T2s_min
  29. print(voxel_T2s_decay)
  30. voxel_all = np.append(voxel_amplitudes,voxel_T2s_decay/T2s_scale)
  31. if voxel_num == 5:
  32. # voxel_all = np.array([mpf(0.2),mpf(0.6),mpf(0.02),mpf(0.1)])
  33. voxel_all = np.array([mpf(0.822628),mpf(0.691376),mpf(0.282906),mpf(0.226013),mpf(0.90703),mpf(0.144985),mpf(0.228563),mpf(0.340353),mpf(0.462462),mpf(0.720518)])
  34. #voxel_all = np.array([mpf(0.592606),mpf(0.135168),mpf(0.365712),mpf(0.667536),mpf(0.437378),mpf(0.918822),mpf(0.943879),mpf(0.590338),mpf(0.685997),mpf(0.658839)])
  35. voxel_amplitudes = voxel_all[:voxel_num]
  36. voxel_T2s_decay = voxel_all[voxel_num:]*T2s_scale
  37. # a_i = np.array([mpf(0.3),mpf(0.1),mpf(0.15),mpf(0.1)])
  38. # d_i = np.array([mpf(0.7),mpf(0.9),mpf(0.2),mpf(0.67)])
  39. # voxel_num = len(a_i)
  40. voxel_phases = np.array(mp.linspace(0,phase_range, voxel_num))
  41. # if len(voxel_amplitudes) != len(voxel_phases):
  42. # print("ERROR! Size of amplitude and phase arrays do not match!")
  43. # raise
  44. ampl = []
  45. def gen_rf_signal(time):
  46. '''Generates demodulated signal at radio frequence using voxels
  47. amplitudes, T2s decays, and phases.
  48. '''
  49. tmp = [mpf(0.0) for n in range(len(time))]
  50. mag_sin = np.array(tmp)
  51. mag_cos = np.array(tmp)
  52. for t in range(len(time)):
  53. #print("time",float(time[t]))
  54. for i in range(voxel_num):
  55. # mag_sin[t] += a_i[i]*(
  56. # (d_i[i] + np.random.rand()*noise_ratio)**time[t]
  57. # )
  58. # print("a_{:d} =".format(i),float(a_i[i]),", ",
  59. # "d_{:d} =".format(i),float(d_i[i]),"+", np.random.rand()*noise_ratio)
  60. amp = voxel_amplitudes[i] * (
  61. mp.exp(-time[t]/voxel_T2s_decay[i])
  62. ) + ( 0.0
  63. # + np.random.rand()*noise_ratio
  64. )
  65. if t == 0:
  66. #print("a_{:d}".format(i),float(voxel_amplitudes[i]* mp.sin(voxel_phases[i] + phase_init)))
  67. print("d_{:d}".format(i),float( mp.exp(-(period/rf_samples_per_period)/voxel_T2s_decay[i]) ))
  68. mag_sin[t] += amp * mp.sin(
  69. voxel_phases[i] + phase_init
  70. )
  71. mag_cos[t] += amp * mp.cos(
  72. voxel_phases[i] + phase_init
  73. )
  74. return mag_sin, mag_cos
  75. def factorial(n):
  76. return mp.gamma(n+1)
  77. def binom(n,k):
  78. return factorial(n)/(factorial(k)*factorial(n-k))
  79. def shiftedLegendre(n):
  80. coeffs = []
  81. for k in range(n+1):
  82. val = mpf(-1)**n * binom(mpf(n),mpf(k)) * binom(n+k,k) * (-1)**k
  83. coeffs.insert(0,val*mp.sqrt(2*n+1))
  84. return np.poly1d(coeffs)
  85. def K ( i, j):
  86. polyL = L[i] #precomputed shiftedLegendre(i)
  87. return polyL.coeffs[-j-1]
  88. def GetU (lambdas):
  89. x = np.array(mp.linspace(0,1, U_points))
  90. tmp = [mpf(0.0) for n in range(len(lambdas))]
  91. mag_sin = np.array(tmp)
  92. tmp = [mpf(0.0) for n in range(U_points)]
  93. U = np.array(tmp)
  94. for i in range (len(lambdas)):
  95. if i%10 == 0: print(i)
  96. polyL = L[i] #shiftedLegendre(i)
  97. U += lambdas[i]*polyL(x)
  98. return U
  99. def GetLambda(mag_rf):
  100. M_cutoff = len(mag_rf)
  101. all_lambda = []
  102. for i in range(M_cutoff):
  103. # print("M = ", i)
  104. lambd = mpf(0)
  105. for j in range(i+1):
  106. lambd += K(i,j)*mag_rf[j]
  107. # print("K({:d},{:d}) =".format(i,j), float(K(i,j)))
  108. all_lambda.append(lambd)
  109. # tmp = [mpf(0.0) for n in range(M_cutoff)]
  110. # all_lambda = np.array(tmp)
  111. # all_lambda[10] = mpf(1.0)
  112. return all_lambda
  113. mag_sin, mag_cos = gen_rf_signal(time_steps)
  114. sign = ""
  115. # for i in range(voxel_num):
  116. # if i%5 == 0:
  117. # sign+="\n"
  118. # sign = sign + '{:3.2g}'.format(float(a_i[i]))+"/"+'{:3.2g}'.format(float(d_i[i]))+", "
  119. # # print(mp.exp(-1.0/voxel_T2s_decay[i]))
  120. plt.plot(mag_sin, ls=' ', marker='o')
  121. plt.title("Signal to restore amp/decay_T:"+sign)
  122. plt.savefig("signal.pdf")
  123. plt.clf()
  124. L = [] # Shifted Legendre polinomials
  125. for i in range(len(mag_sin)):
  126. polyL = shiftedLegendre(i)
  127. # print("i=",i," L_i:")
  128. # print(polyL)
  129. L += [polyL]
  130. x = np.linspace(0,1, U_points)
  131. polyL_val = np.array([float(L[-1](x[n])) for n in range(U_points)])
  132. plt.plot(x,polyL_val)
  133. plt.title("Legendre polynom of order "+str(len(L)))
  134. plt.savefig("polyL.pdf")
  135. plt.clf()
  136. print("Output of last poly done.")
  137. lambdas = GetLambda(mag_sin)
  138. print(len(lambdas))
  139. U = GetU(lambdas)
  140. x = np.linspace(0,1, U_points)
  141. mag_x = np.linspace(0,1, len(mag_sin))
  142. plt.plot(x,U)
  143. plt.title(r"$\sum^M \lambda_i L_i(x)$", y=1.02)
  144. plt.savefig("plt.pdf")
  145. plt.clf()