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