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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 = 2000
  8. voxel_num = 15
  9. phase_range = mp.pi/2
  10. phase_init = mp.pi/4 #mpf(0.0)
  11. U_points = voxel_num * 3000
  12. noise_ratio = mpf(0.0*1e-38) #1e8
  13. total_periods=10#DO NOT CHANGE to fit T2s_scale autoscale
  14. rf_samples_per_period = 80
  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/rf_samples_per_period/voxel_num*8 #ms # need to be 10ms
  21. T2s_min = T2s_scale/20.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()*0.0+mpf(1.0) 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.sort(np.array(tmp))*(T2s_scale-2*T2s_min) + T2s_min
  29. voxel_all = np.append(voxel_amplitudes,voxel_T2s_decay/T2s_scale)
  30. if voxel_num == 5:
  31. # voxel_all = np.array([mpf(0.2),mpf(0.6),mpf(0.02),mpf(0.1)])
  32. 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)])
  33. #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)])
  34. voxel_amplitudes = voxel_all[:voxel_num]
  35. voxel_T2s_decay = voxel_all[voxel_num:]*T2s_scale
  36. # a_i = np.array([mpf(0.3),mpf(0.1),mpf(0.15),mpf(0.1)])
  37. # d_i = np.array([mpf(0.7),mpf(0.9),mpf(0.2),mpf(0.67)])
  38. # voxel_num = len(a_i)
  39. voxel_phases = np.array(mp.linspace(0,phase_range, voxel_num))
  40. # if len(voxel_amplitudes) != len(voxel_phases):
  41. # print("ERROR! Size of amplitude and phase arrays do not match!")
  42. # raise
  43. ampl = []
  44. def gen_rf_signal(time):
  45. '''Generates demodulated signal at radio frequence using voxels
  46. amplitudes, T2s decays, and phases.
  47. '''
  48. tmp = [mpf(0.0) for n in range(len(time))]
  49. mag_sin = np.array(tmp)
  50. mag_cos = np.array(tmp)
  51. for t in range(len(time)):
  52. #print("time",float(time[t]))
  53. for i in range(voxel_num):
  54. # mag_sin[t] += a_i[i]*(
  55. # (d_i[i] + np.random.rand()*noise_ratio)**time[t]
  56. # )
  57. # print("a_{:d} =".format(i),float(a_i[i]),", ",
  58. # "d_{:d} =".format(i),float(d_i[i]),"+", np.random.rand()*noise_ratio)
  59. amp = voxel_amplitudes[i] * (
  60. mp.exp(-time[t]/voxel_T2s_decay[i])
  61. ) + ( 0.0
  62. # + np.random.rand()*noise_ratio
  63. )
  64. if t == 0:
  65. #print("a_{:d}".format(i),float(voxel_amplitudes[i]* mp.sin(voxel_phases[i] + phase_init)))
  66. print("d_{:d}".format(i),float( mp.exp(-(period/rf_samples_per_period)/voxel_T2s_decay[i]) ))
  67. mag_sin[t] += amp * mp.sin(
  68. voxel_phases[i] + phase_init
  69. )
  70. mag_cos[t] += amp * mp.cos(
  71. voxel_phases[i] + phase_init
  72. )
  73. return mag_sin, mag_cos
  74. def factorial(n):
  75. return mp.gamma(n+1)
  76. def binom(n,k):
  77. return factorial(n)/(factorial(k)*factorial(n-k))
  78. def shiftedLegendre(n):
  79. coeffs = []
  80. for k in range(n+1):
  81. val = mpf(-1)**n * binom(mpf(n),mpf(k)) * binom(n+k,k) * (-1)**k
  82. coeffs.insert(0,val*mp.sqrt(2*n+1))
  83. return np.poly1d(coeffs)
  84. def K ( i, j):
  85. polyL = L[i] #precomputed shiftedLegendre(i)
  86. return polyL.coeffs[-j-1]
  87. def GetU (lambdas):
  88. n_max = len(lambdas)
  89. P = np.ones((n_max+1,U_points))
  90. x = np.linspace(0,1, U_points)
  91. P[1] = 2*x-1
  92. for n in range(1,n_max):
  93. P[n+1] = ((2*n+1)/(n+1)) * (2*x-1) * P[n] - (n/(n+1))*P[n-1]
  94. U = np.zeros(U_points)
  95. for i in range (len(lambdas)):
  96. if i%10 == 0: print(i)
  97. U += lambdas[i]*P[i]*np.sqrt(2*i+1)
  98. #polyL = L[i] #shiftedLegendre(i)
  99. #U += lambdas[i]*polyL(x)
  100. return U
  101. def GetLambda(mag_rf):
  102. M_cutoff = len(mag_rf)
  103. all_lambda = []
  104. for i in range(M_cutoff):
  105. # print("M = ", i)
  106. lambd = (0)
  107. for j in range(i+1):
  108. lambd += K(i,j)*mag_rf[j]
  109. # print("K({:d},{:d}) =".format(i,j), float(K(i,j)))
  110. all_lambda.append(float(lambd))
  111. # tmp = [mpf(0.0) for n in range(M_cutoff)]
  112. # all_lambda = np.array(tmp)
  113. # all_lambda[10] = mpf(1.0)
  114. return all_lambda
  115. mag_sin, mag_cos = gen_rf_signal(time_steps)
  116. sign = ""
  117. # for i in range(voxel_num):
  118. # if i%5 == 0:
  119. # sign+="\n"
  120. # sign = sign + '{:3.2g}'.format(float(a_i[i]))+"/"+'{:3.2g}'.format(float(d_i[i]))+", "
  121. # # print(mp.exp(-1.0/voxel_T2s_decay[i]))
  122. plt.plot(mag_sin, ls=' ', marker='o')
  123. plt.title("Signal to restore amp/decay_T:"+sign)
  124. plt.savefig("signal.pdf")
  125. plt.clf()
  126. L = [] # Shifted Legendre polinomials
  127. for i in range(len(mag_sin)):
  128. polyL = shiftedLegendre(i)
  129. # print("i=",i," L_i:")
  130. # print(polyL)
  131. L += [polyL]
  132. x = np.linspace(0,1, U_points)
  133. # polyL_val = np.array([float(L[-1](x[n])) for n in range(U_points)])
  134. # plt.plot(x,polyL_val)
  135. # plt.title("Legendre polynom of order "+str(len(L)))
  136. # plt.savefig("polyL.pdf")
  137. # plt.clf()
  138. print("Before lambda.")
  139. lambdas = GetLambda(mag_sin)
  140. print(lambdas)
  141. U = GetU(lambdas)
  142. sign =""
  143. for i in range(voxel_num):
  144. sign+="{:4.3g}, ".format(float( mp.exp(-(period/rf_samples_per_period)/voxel_T2s_decay[i]) ))
  145. print(sign)
  146. x = np.linspace(0,1, U_points)
  147. mag_x = np.linspace(0,1, len(mag_sin))
  148. import matplotlib as matplotlib
  149. matplotlib.rcParams.update({'font.size': 28})
  150. plt.figure(figsize=(30, 20))
  151. plt.plot(x,U, lw=0.2)
  152. plt.title(r"$\sum^M \lambda_i L_i(x)$", y=1.02)
  153. plt.xlim(0,1)
  154. plt.xlabel(sign, fontsize=28)
  155. plt.savefig("plt.pdf")
  156. plt.clf()