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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 = 1000
  8. voxel_num = 2
  9. phase_range = mp.pi/2
  10. phase_init = mp.pi/20 #mpf(0.0)
  11. U_points = voxel_num * 1000
  12. # noise_ratio = mpf(0.0) #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(1/(total_periods*rf_samples_per_period)) #ms
  18. omega = 2.0*mp.pi/period
  19. #T2s_scale = 0.01 #ms # need to be 10ms
  20. T2s_scale = total_periods*period #ms # need to be 10ms
  21. T2s_min = T2s_scale/1000.0
  22. #print(period)
  23. #ms
  24. time_steps = np.array(mp.linspace(mpf(0), mpf(rf_samples_per_period*total_periods), rf_samples_per_period*total_periods+1))
  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-T2s_min) + T2s_min
  29. voxel_all = np.append(voxel_amplitudes,voxel_T2s_decay/T2s_scale)
  30. a_i = np.array([mpf(0.3),mpf(0.1),mpf(0.15),mpf(0.1)])
  31. d_i = np.array([mpf(0.7),mpf(0.9),mpf(0.2),mpf(0.6)])
  32. voxel_num = len(a_i)
  33. voxel_phases = np.array(mp.linspace(0,phase_range, voxel_num))
  34. # if len(voxel_amplitudes) != len(voxel_phases):
  35. # print("ERROR! Size of amplitude and phase arrays do not match!")
  36. # raise
  37. ampl = []
  38. def gen_rf_signal(time):
  39. '''Generates demodulated signal at radio frequence using voxels
  40. amplitudes, T2s decays, and phases.
  41. '''
  42. tmp = [mpf(0.0) for n in range(len(time))]
  43. mag_sin = np.array(tmp)
  44. mag_cos = np.array(tmp)
  45. for t in range(len(time)):
  46. #print("time",float(time[t]))
  47. for i in range(voxel_num):
  48. mag_sin[t] += a_i[i]*(d_i[i]**time[t])
  49. # print("a_{:d} =".format(i),float(a_i[i]),", ",
  50. # "d_{:d} =".format(i),float(d_i[i]))
  51. # amp = voxel_amplitudes[i] * (
  52. # mp.exp(-time[t]/voxel_T2s_decay[i])
  53. # ) + ( 0.0
  54. # # + np.random.rand()*noise_ratio
  55. # )
  56. # print("a_{:d}".format(i),float(voxel_amplitudes[i]* mp.sin(
  57. # voxel_phases[i] + phase_init
  58. # )))
  59. # print("d_{:d}".format(i),float( mp.exp(-1.0/voxel_T2s_decay[i]) ))
  60. # mag_sin[t] += amp * mp.sin(
  61. # voxel_phases[i] + phase_init
  62. # )
  63. # mag_cos[t] += amp * mp.cos(
  64. # voxel_phases[i] + phase_init
  65. # )
  66. return mag_sin, mag_cos
  67. def factorial(n):
  68. return mp.gamma(n+1)
  69. def binom(n,k):
  70. return factorial(n)/(factorial(k)*factorial(n-k))
  71. def shiftedLegendre(n):
  72. coeffs = []
  73. for k in range(n+1):
  74. val = mpf(-1)**n * binom(mpf(n),mpf(k)) * binom(n+k,k) * (-1)**k
  75. coeffs.insert(0,val*mp.sqrt(2*n+1))
  76. return np.poly1d(coeffs)
  77. def K ( i, j):
  78. polyL = L[i] #precomputed shiftedLegendre(i)
  79. return polyL.coeffs[-j-1]
  80. def GetU (lambdas):
  81. x = np.array(mp.linspace(0,1, U_points))
  82. tmp = [mpf(0.0) for n in range(len(lambdas))]
  83. mag_sin = np.array(tmp)
  84. tmp = [mpf(0.0) for n in range(U_points)]
  85. U = np.array(tmp)
  86. for i in range (len(lambdas)):
  87. polyL = L[i] #shiftedLegendre(i)
  88. U += lambdas[i]*polyL(x)
  89. return U
  90. def GetLambda(mag_rf):
  91. M_cutoff = len(mag_rf)
  92. all_lambda = []
  93. for i in range(M_cutoff):
  94. # print("M = ", i)
  95. lambd = mpf(0)
  96. for j in range(i+1):
  97. lambd += K(i,j)*mag_rf[j]
  98. # print("K({:d},{:d}) =".format(i,j), float(K(i,j)))
  99. all_lambda.append(lambd)
  100. # tmp = [mpf(0.0) for n in range(M_cutoff)]
  101. # all_lambda = np.array(tmp)
  102. # all_lambda[10] = mpf(1.0)
  103. return all_lambda
  104. mag_sin, mag_cos = gen_rf_signal(time_steps)
  105. sign = ""
  106. for i in range(voxel_num):
  107. if i%5 == 0:
  108. sign+="\n"
  109. sign = sign + '{:3.2g}'.format(float(a_i[i]))+"/"+'{:3.2g}'.format(float(d_i[i]))+", "
  110. # print(mp.exp(-1.0/voxel_T2s_decay[i]))
  111. plt.plot(mag_sin, ls=' ', marker='o')
  112. plt.title("Signal to restore amp/decay_T:"+sign)
  113. plt.savefig("signal.pdf")
  114. plt.clf()
  115. L = [] # Shifted Legendre polinomials
  116. for i in range(len(mag_sin)):
  117. polyL = shiftedLegendre(i)
  118. # print("i=",i," L_i:")
  119. # print(polyL)
  120. L += [polyL]
  121. x = np.linspace(0,1, U_points)
  122. polyL_val = np.array([float(L[-1](x[n])) for n in range(U_points)])
  123. plt.plot(x,polyL_val)
  124. plt.title("Legendre polynom of order "+str(len(L)))
  125. plt.savefig("polyL.pdf")
  126. plt.clf()
  127. print("Output of last poly done.")
  128. lambdas = GetLambda(mag_sin)
  129. print(len(lambdas))
  130. U = GetU(lambdas)
  131. x = np.linspace(0,1, U_points)
  132. mag_x = np.linspace(0,1, len(mag_sin))
  133. plt.plot(x,U)
  134. plt.title(r"$\sum^M \lambda_i L_i(x)$", y=1.02)
  135. plt.savefig("plt.pdf")
  136. plt.clf()