pulseq_library.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. # Copyright of the Board of Trustees of Columbia University in the City of New York
  2. """
  3. Library for generating pulseq sequences: GRE, SE, IRSE, EPI
  4. """
  5. # TODO update for PyPulseq 1.2.1
  6. import copy
  7. from math import pi, sqrt, ceil, floor
  8. import numpy as np
  9. from pypulseq.Sequence.sequence import Sequence
  10. from pypulseq.calc_duration import calc_duration
  11. from pypulseq.make_adc import make_adc
  12. from pypulseq.make_delay import make_delay
  13. from pypulseq.make_sinc_pulse import make_sinc_pulse
  14. from pypulseq.make_trap_pulse import make_trapezoid
  15. from pypulseq.opts import Opts
  16. GAMMA_BAR = 42.5775e6
  17. GAMMA = 2*pi*GAMMA_BAR
  18. def make_pulseq_gre(fov,n,thk,fa,tr,te,enc='xyz',slice_locs=None,write=False):
  19. """Makes a gradient-echo sequence
  20. 2D orthogonal multi-slice gradient-echo pulse sequence with Cartesian encoding
  21. Orthogonal means that each of slice-selection, phase encoding, and frequency encoding
  22. aligns with the x, y, or z directions
  23. Parameters
  24. ----------
  25. fov : float
  26. Field-of-view in meters (isotropic)
  27. n : int
  28. Matrix size (isotropic)
  29. thk : float
  30. Slice thickness in meters
  31. fa : float
  32. Flip angle in degrees
  33. tr : float
  34. Repetition time in seconds
  35. te : float
  36. Echo time in seconds
  37. enc : str, optional
  38. Spatial encoding directions
  39. 1st - readout; 2nd - phase encoding; 3rd - slice select
  40. Default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  41. slice_locs : array_like, optional
  42. Slice locations from isocenter in meters
  43. Default is None which means a single slice at the center
  44. write : bool, optional
  45. Whether to write seq into file; default is False
  46. Returns
  47. -------
  48. seq : Sequence
  49. Pulse sequence as a Pulseq object
  50. """
  51. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  52. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  53. rf_dead_time=100e-6, adc_dead_time=20e-6)
  54. seq = Sequence(system)
  55. Nf = n
  56. Np = n
  57. flip = fa * pi / 180
  58. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip, system=system, duration=4e-3, slice_thickness=thk,
  59. apodization=0.5, time_bw_product=4)
  60. g_ss.channel = enc[2]
  61. delta_k = 1 / fov
  62. kWidth = Nf * delta_k
  63. # Readout and ADC
  64. readoutTime = 6.4e-3
  65. g_ro= make_trapezoid(channel=enc[0],system=system,flat_area=kWidth,flat_time=readoutTime)
  66. adc = make_adc(num_samples=Nf, duration=g_ro.flat_time, delay=g_ro.rise_time)
  67. # Readout rewinder
  68. g_ro_pre = make_trapezoid(channel=enc[0],system=system,area=-g_ro.area/2,duration=2e-3)
  69. # Slice refocusing
  70. g_ss_reph = make_trapezoid(channel=enc[2],system=system,area=-g_ss.area/2,duration=2e-3)
  71. phase_areas = (np.arange(Np) - (Np / 2)) * delta_k
  72. # TE, TR = 10e-3, 1000e-3
  73. TE, TR = te,tr
  74. delayTE = TE - calc_duration(g_ro_pre) - calc_duration(g_ss) / 2 - calc_duration(g_ro) / 2
  75. delayTR = TR - calc_duration(g_ro_pre) - calc_duration(g_ss) - calc_duration(g_ro) - delayTE
  76. delay1 = make_delay(delayTE)
  77. delay2 = make_delay(delayTR)
  78. if slice_locs is None:
  79. locs = [0]
  80. else:
  81. locs = slice_locs
  82. for u in range(len(locs)):
  83. # add frequency offset
  84. rf.freq_offset = g_ss.amplitude * locs[u]
  85. for i in range(Np):
  86. seq.add_block(rf, g_ss)
  87. g_pe = make_trapezoid(channel=enc[1],system=system,area=phase_areas[i],duration=2e-3)
  88. seq.add_block(g_ro_pre, g_pe, g_ss_reph)
  89. seq.add_block(delay1)
  90. seq.add_block(g_ro,adc)
  91. seq.add_block(delay2)
  92. if write:
  93. seq.write("gre_fov{:.0f}mm_Nf{:d}_Np{:d}_TE{:.0f}ms_TR{:.0f}ms_FA{:.0f}deg.seq".format(fov * 1000, Nf, Np, TE * 1000,
  94. TR * 1000, flip * 180 / pi))
  95. print('GRE sequence constructed')
  96. return seq
  97. def make_pulseq_gre_oblique(fov,n,thk,fa,tr,te,enc='xyz',slice_locs=None,write=False):
  98. """Makes a gradient-echo sequence in any plane
  99. 2D oblique multi-slice gradient-echo pulse sequence with Cartesian encoding
  100. Oblique means that each of slice-selection, phase encoding, and frequency encoding
  101. can point in any specified direction
  102. Parameters
  103. ----------
  104. fov : array_like
  105. Isotropic field-of-view, or length-2 list [fov_readout, fov_phase], in meters
  106. n : array_like
  107. Isotropic matrix size, or length-2 list [n_readout, n_phase]
  108. thk : float
  109. Slice thickness in meters
  110. fa : float
  111. Flip angle in degrees
  112. tr : float
  113. Repetition time in seconds
  114. te : float
  115. Echo time in seconds
  116. enc : str or array_like, optional
  117. Spatial encoding directions
  118. 1st - readout; 2nd - phase encoding; 3rd - slice select
  119. - Use str with any permutation of x, y, and z to obtain orthogonal slices
  120. e.g. The default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  121. - Use list to indicate vectors in the encoding directions for oblique slices
  122. They should be perpendicular to each other, but not necessarily unit vectors
  123. e.g. [(2,1,0),(-1,2,0),(0,0,1)] rotates the two in-plane encoding directions for an axial slice
  124. slice_locs : array_like, optional
  125. Slice locations from isocenter in meters
  126. Default is None which means a single slice at the center
  127. write : bool, optional
  128. Whether to write seq into file; default is False
  129. Returns
  130. -------
  131. seq : Sequence
  132. Pulse sequence as a Pulseq object
  133. """
  134. # System options
  135. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  136. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  137. rf_dead_time=100e-6, adc_dead_time=20e-6)
  138. seq = Sequence(system)
  139. # Calculate unit gradients for ss, fe, pe
  140. ug_fe, ug_pe, ug_ss = parse_enc(enc)
  141. # Sequence parameters
  142. Nf, Np = (n,n) if isinstance(n,int) else (n[0], n[1])
  143. delta_k_ro, delta_k_pe = (1/fov,1/fov) if isinstance(fov,float) else (1/fov[0], 1/fov[1])
  144. kWidth_ro = Nf * delta_k_ro
  145. flip = fa * pi / 180
  146. # Slice select: RF and gradient
  147. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip,system=system,duration=4e-3,slice_thickness=thk,
  148. apodization=0.5, time_bw_product=4)
  149. g_ss_x, g_ss_y, g_ss_z = make_oblique_gradients(g_ss,ug_ss)
  150. # Readout and ADC
  151. # readoutTime = 6.4e-3
  152. dwell = 10e-6
  153. g_ro= make_trapezoid(channel='x',system=system,flat_area=kWidth_ro, flat_time=dwell*Nf)
  154. g_ro_x, g_ro_y, g_ro_z = make_oblique_gradients(g_ro,ug_fe)#
  155. adc = make_adc(num_samples=Nf, duration=g_ro.flat_time,delay=g_ro.rise_time)
  156. # Readout rewinder
  157. g_ro_pre = make_trapezoid(channel='x',system=system,area=-g_ro.area/2,duration=2e-3)
  158. g_ro_pre_x, g_ro_pre_y, g_ro_pre_z = make_oblique_gradients(g_ro_pre,ug_fe)#
  159. # Slice refocusing
  160. g_ss_reph = make_trapezoid(channel='z',system=system,area=-g_ss.area/2,duration=2e-3)
  161. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z = make_oblique_gradients(g_ss_reph, ug_ss)
  162. # Prepare phase areas
  163. phase_areas = (np.arange(Np) - (Np / 2)) * delta_k_pe
  164. TE, TR = te,tr
  165. delayTE = TE - calc_duration(g_ro_pre) - calc_duration(g_ss) / 2 - calc_duration(g_ro) / 2
  166. delayTR = TR - calc_duration(g_ro_pre) - calc_duration(g_ss) - calc_duration(g_ro) - delayTE
  167. delay1 = make_delay(delayTE)
  168. delay2 = make_delay(delayTR)
  169. if slice_locs is None:
  170. locs = [0]
  171. else:
  172. locs = slice_locs
  173. # Construct sequence!
  174. for u in range(len(locs)):
  175. # add frequency offset
  176. rf.freq_offset = g_ss.amplitude * locs[u]
  177. for i in range(Np):
  178. seq.add_block(rf,g_ss_x, g_ss_y, g_ss_z)
  179. g_pe = make_trapezoid(channel='y',system=system,area=phase_areas[i],duration=2e-3)
  180. g_pe_x, g_pe_y, g_pe_z = make_oblique_gradients(g_pe,ug_pe)
  181. pre_grads_list = [g_ro_pre_x, g_ro_pre_y, g_ro_pre_z,
  182. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z,
  183. g_pe_x, g_pe_y, g_pe_z]
  184. gtx, gty, gtz = combine_trap_grad_xyz(gradients=pre_grads_list,system=system, dur=2e-3)
  185. seq.add_block(gtx, gty, gtz)
  186. seq.add_block(delay1)
  187. seq.add_block(g_ro_x, g_ro_y, g_ro_z, adc)
  188. seq.add_block(delay2)
  189. if write:
  190. seq.write("gre_fov{:.0f}mm_Nf{:d}_Np{:d}_TE{:.0f}ms_TR{:.0f}ms_FA{:.0f}deg.seq".format(fov * 1000, Nf, Np, TE * 1000,
  191. TR * 1000, flip * 180 / pi))
  192. print('GRE sequence constructed')
  193. return seq
  194. def make_pulseq_irse(fov,n,thk,fa,tr,te,ti,enc='xyz',slice_locs=None,write=False):
  195. """Makes an Inversion Recovery Spin Echo (IRSE) sequence
  196. 2D orthogonal multi-slice IRSE pulse sequence with Cartesian encoding
  197. Orthogonal means that each of slice-selection, phase encoding, and frequency encoding
  198. aligns with the x, y, or z directions
  199. Parameters
  200. ----------
  201. fov : float
  202. Field-of-view in meters (isotropic)
  203. n : int
  204. Matrix size (isotropic)
  205. thk : float
  206. Slice thickness in meters
  207. fa : float
  208. Flip angle in degrees
  209. tr : float
  210. Repetition time in seconds
  211. te : float
  212. Echo time in seconds
  213. ti : float
  214. Inversion time in seconds
  215. enc : str, optional
  216. Spatial encoding directions
  217. 1st - readout; 2nd - phase encoding; 3rd - slice select
  218. Default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  219. slice_locs : array_like, optional
  220. Slice locations from isocenter in meters
  221. Default is None which means a single slice at the center
  222. write : bool, optional
  223. Whether to write seq into file; default is False
  224. Returns
  225. -------
  226. seq : Sequence
  227. Pulse sequence as a Pulseq object
  228. """
  229. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  230. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  231. rf_dead_time=100e-6, adc_dead_time=20e-6)
  232. seq = Sequence(system)
  233. # Parameters
  234. Nf = n
  235. Np = n
  236. delta_k = 1 / fov
  237. kWidth = Nf * delta_k
  238. TI,TE,TR = ti,te,tr
  239. if np.shape(TI) == ():
  240. TI = [TI]
  241. # Non-180 pulse
  242. flip1 = fa * pi / 180
  243. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip1, system=system, duration=2e-3, slice_thickness=thk,
  244. apodization=0.5, time_bw_product=4)
  245. g_ss.channel = enc[2]
  246. # 180 pulse
  247. flip2 = 180 * pi / 180
  248. rf180, g_ss180, __ = make_sinc_pulse(flip_angle=flip2, system=system,duration=2e-3, slice_thickness=thk,
  249. apodization=0.5, time_bw_product=4)
  250. g_ss180.channel = enc[2]
  251. # Readout gradient & ADC
  252. readoutTime = 6.4e-3
  253. g_ro = make_trapezoid(channel=enc[0],system=system, flat_area=kWidth, flat_time=readoutTime)
  254. adc = make_adc(num_samples=Nf, system=system, duration=g_ro.flat_time, delay=g_ro.rise_time)
  255. # RO rewinder gradient
  256. g_ro_pre = make_trapezoid(channel=enc[0],system=system,area=g_ro.area/2,duration=2e-3)
  257. # Slice refocusing gradient
  258. g_ss_reph = make_trapezoid(channel=enc[2],system=system,area=-g_ss.area/2,duration=2e-3)
  259. # Delays
  260. delayTE1 = TE / 2 - max(calc_duration(g_ss_reph), calc_duration(g_ro_pre)) - calc_duration(g_ss) / 2 - calc_duration(
  261. g_ss180) / 2
  262. delayTE2 = TE / 2 - calc_duration(g_ro) / 2 - calc_duration(g_ss180) / 2
  263. delayTE3 = TR - TE - calc_duration(g_ss) / 2 - calc_duration(g_ro) / 2
  264. print('dur rf', calc_duration(rf),'dur gss:' ,calc_duration(g_ss))
  265. delay1 = make_delay(delayTE1)
  266. delay2 = make_delay(delayTE2)
  267. delay3 = make_delay(delayTE3)
  268. # Construct sequence
  269. if slice_locs is None:
  270. locs = [0]
  271. else:
  272. locs = slice_locs
  273. for inv in range(len(TI)):
  274. for u in range(len(locs)):
  275. rf180.freq_offset = g_ss180.amplitude * locs[u]
  276. rf.freq_offset = g_ss.amplitude * locs[u]
  277. for i in range(Np):
  278. # Inversion Recovery part
  279. seq.add_block(rf180, g_ss180)# Selective; potentially extended to be non-selective or adiabatic
  280. seq.add_block(make_delay(TI[inv] - calc_duration(rf) / 2 - calc_duration(rf180) / 2)) # Inversion time delay
  281. # Spin echo part
  282. seq.add_block(rf, g_ss) # 90-deg pulse
  283. g_pe_pre = make_trapezoid(channel=enc[1],system=system,area=-(Np/2-i)*delta_k,
  284. duration=2e-3) # Phase encoding gradient
  285. seq.add_block(g_ro_pre, g_pe_pre, g_ss_reph) # Add a combination of ro rewinder, phase encoding, and slice refocusing
  286. seq.add_block(delay1) # Delay 1: until 180-deg pulse
  287. seq.add_block(rf180, g_ss180) # 180 deg pulse for SE
  288. seq.add_block(delay2) # Delay 2: until readout
  289. seq.add_block(g_ro, adc) # Readout!
  290. seq.add_block(delay3) # Delay 3: until next inversion pulse
  291. if write:
  292. if len(TI) == 1:
  293. seq.write("irse_fov{:.0f}mm_Nf{:d}_Np{:d}_TI{:.0f}ms_TE{:.0f}ms_TR{:.0f}ms.seq".format(fov * 1000, Nf, Np, TI[0] * 1000, TE * 1000, TR * 1000))
  294. else:
  295. seq.write("irse_fov{:.0f}mm_Nf{:d}_Np{:d}_multiTI_TE{:.0f}ms_TR{:.0f}ms.seq".format(fov * 1000, Nf, Np, TE * 1000, TR * 1000))
  296. print('IRSE sequence constructed')
  297. return seq
  298. def make_pulseq_irse_oblique(fov,n,thk,fa,tr,te,ti,enc='xyz',slice_locs=None,write=False):
  299. """Makes an Inversion Recovery Spin Echo (IRSE) sequence in any plane
  300. 2D oblique multi-slice IRSE pulse sequence with Cartesian encoding
  301. Oblique means that each of slice-selection, phase encoding, and frequency encoding
  302. can point in any specified direction
  303. Parameters
  304. ----------
  305. fov : array_like
  306. Isotropic field-of-view, or length-2 list [fov_readout, fov_phase], in meters
  307. n : array_like
  308. Isotropic matrix size, or length-2 list [n_readout, n_phase]
  309. thk : float
  310. Slice thickness in meters
  311. fa : float
  312. Flip angle in degrees
  313. tr : float
  314. Repetition time in seconds
  315. te : float
  316. Echo time in seconds
  317. ti : float
  318. Inversion time in seconds
  319. enc : str or array_like, optional
  320. Spatial encoding directions
  321. 1st - readout; 2nd - phase encoding; 3rd - slice select
  322. - Use str with any permutation of x, y, and z to obtain orthogonal slices
  323. e.g. The default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  324. - Use list to indicate vectors in the encoding directions for oblique slices
  325. They should be perpendicular to each other, but not necessarily unit vectors
  326. e.g. [(2,1,0),(-1,2,0),(0,0,1)] rotates the two in-plane encoding directions for an axial slice
  327. slice_locs : array_like, optional
  328. Slice locations from isocenter in meters
  329. Default is None which means a single slice at the center
  330. write : bool, optional
  331. Whether to write seq into file; default is False
  332. Returns
  333. -------
  334. seq : Sequence
  335. Pulse sequence as a Pulseq object
  336. """
  337. # System options
  338. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  339. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  340. rf_dead_time=100e-6, adc_dead_time=20e-6)
  341. seq = Sequence(system)
  342. # Sequence parameters
  343. ug_fe, ug_pe, ug_ss = parse_enc(enc)
  344. Nf, Np = (n,n) if isinstance(n,int) else (n[0], n[1])
  345. delta_k_ro, delta_k_pe = (1/fov,1/fov) if isinstance(fov,float) else (1/fov[0], 1/fov[1])
  346. kWidth_ro = Nf * delta_k_ro
  347. TI,TE,TR = ti,te,tr
  348. if np.shape(TI) == ():
  349. TI = [TI]
  350. # Non-180 pulse
  351. flip1 = fa * pi / 180
  352. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip1, system=system, duration=2e-3, slice_thickness=thk,
  353. apodization=0.5, time_bw_product=4)
  354. g_ss_x, g_ss_y, g_ss_z = make_oblique_gradients(g_ss, ug_ss)
  355. # 180 pulse
  356. flip2 = 180 * pi / 180
  357. rf180, g_ss180, __ = make_sinc_pulse(flip_angle=flip2, system=system, duration=2e-3, slice_thickness=thk,
  358. apodization=0.5, time_bw_product=4)
  359. g_ss180_x, g_ss180_y, g_ss180_z = make_oblique_gradients(g_ss180, ug_ss)
  360. # Readout gradient & ADC
  361. readoutTime = 6.4e-3
  362. g_ro = make_trapezoid(channel='x', system=system, flat_area=kWidth_ro, flat_time= readoutTime)
  363. g_ro_x, g_ro_y, g_ro_z = make_oblique_gradients(g_ro, ug_fe)
  364. adc = make_adc(num_samples=Nf, system=system, duration=g_ro.flat_time, delay=g_ro.rise_time)
  365. # RO rewinder gradient
  366. g_ro_pre = make_trapezoid(channel=enc[0], system=system, area=g_ro.area/2,duration=2e-3)
  367. g_ro_pre_x, g_ro_pre_y, g_ro_pre_z = make_oblique_gradients(g_ro_pre,ug_fe)#
  368. # Slice refocusing gradient
  369. g_ss_reph = make_trapezoid(channel=enc[2],system=system,area=-g_ss.area/2,duration=2e-3)
  370. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z = make_oblique_gradients(g_ss_reph, ug_ss)
  371. # Delays
  372. delayTE1 = TE / 2 - max(calc_duration(g_ss_reph), calc_duration(g_ro_pre))\
  373. - calc_duration(g_ss) / 2 - calc_duration(g_ss180) / 2
  374. delayTE2 = TE / 2 - calc_duration(g_ro) / 2 - calc_duration(g_ss180) / 2
  375. delayTE3 = TR - TE - calc_duration(g_ss) / 2 - calc_duration(g_ro) / 2
  376. delay1 = make_delay(delayTE1)
  377. delay2 = make_delay(delayTE2)
  378. delay3 = make_delay(delayTE3)
  379. # Construct sequence
  380. if slice_locs is None:
  381. locs = [0]
  382. else:
  383. locs = slice_locs
  384. for inv in range(len(TI)):
  385. for u in range(len(locs)):
  386. rf180.freq_offset = g_ss180.amplitude * locs[u]
  387. rf.freq_offset = g_ss.amplitude * locs[u]
  388. for i in range(Np):
  389. # Inversion Recovery part
  390. seq.add_block(rf180, g_ss180_x, g_ss180_y, g_ss180_z)# Non-selective at the moment; could be extended to make this selective/adiabatic
  391. seq.add_block(make_delay(TI[inv] - calc_duration(rf) / 2 - calc_duration(rf180) / 2)) # Inversion time delay
  392. # Spin echo part
  393. seq.add_block(rf, g_ss_x, g_ss_y, g_ss_z) # 90-deg pulse
  394. g_pe = make_trapezoid(channel='y', system=system, area=-(Np /2 - i)*delta_k_pe, duration=2e-3) # Phase encoding gradient
  395. g_pe_x, g_pe_y, g_pe_z = make_oblique_gradients(g_pe, ug_pe)
  396. pre_grads_list = [g_ro_pre_x, g_ro_pre_y, g_ro_pre_z,
  397. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z,
  398. g_pe_x, g_pe_y, g_pe_z]
  399. gtx, gty, gtz = combine_trap_grad_xyz(pre_grads_list,system,2e-3)
  400. seq.add_block(gtx, gty, gtz) # Add a combination of ro rewinder, phase encoding, and slice refocusing
  401. seq.add_block(delay1) # Delay 1: until 180-deg pulse
  402. seq.add_block(rf180, g_ss180_x, g_ss180_y, g_ss180_z) # 180 deg pulse for SE
  403. seq.add_block(delay2) # Delay 2: until readout
  404. seq.add_block(g_ro_x, g_ro_y, g_ro_z, adc) # Readout!
  405. seq.add_block(delay3) # Delay 3: until next inversion pulse
  406. if write:
  407. if len(TI) == 1:
  408. seq.write("irse_fov{:.0f}mm_Nf{:d}_Np{:d}_TI{:.0f}ms_TE{:.0f}ms_TR{:.0f}ms_FA{:d}deg.seq".format(fov * 1000,
  409. Nf, Np, TI[0] * 1000, TE * 1000, TR * 1000, fa))
  410. else:
  411. seq.write("irse_fov{:.0f}mm_Nf{:d}_Np{:d}_multiTI_TE{:.0f}ms_TR{:.0f}ms_FA{:d}deg.seq".format(fov * 1000,
  412. Nf, Np, TE * 1000, TR * 1000, fa))
  413. print('IRSE (oblique) sequence constructed')
  414. return seq
  415. def make_pulseq_se(fov,n,thk,fa,tr,te,enc='xyz',slice_locs=None,write=False):
  416. """Makes a Spin Echo (SE) sequence
  417. 2D orthogonal multi-slice Spin-Echo pulse sequence with Cartesian encoding
  418. Orthogonal means that each of slice-selection, phase encoding, and frequency encoding
  419. aligns with the x, y, or z directions
  420. Parameters
  421. ----------
  422. fov : float
  423. Field-of-view in meters (isotropic)
  424. n : int
  425. Matrix size (isotropic)
  426. thk : float
  427. Slice thickness in meters
  428. fa : float
  429. Flip angle in degrees
  430. tr : float
  431. Repetition time in seconds
  432. te : float
  433. Echo time in seconds
  434. enc : str, optional
  435. Spatial encoding directions
  436. 1st - readout; 2nd - phase encoding; 3rd - slice select
  437. Default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  438. slice_locs : array_like, optional
  439. Slice locations from isocenter in meters
  440. Default is None which means a single slice at the center
  441. write : bool, optional
  442. Whether to write seq into file; default is False
  443. Returns
  444. -------
  445. seq : Sequence
  446. Pulse sequence as a Pulseq object
  447. """
  448. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  449. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  450. rf_dead_time=100e-6, adc_dead_time=20e-6)
  451. seq = Sequence(system)
  452. # Parameters
  453. Nf = n
  454. Np = n
  455. delta_k = 1 / fov
  456. kWidth = Nf * delta_k
  457. TE,TR = te,tr
  458. # Non-180 pulse
  459. flip1 = fa * pi / 180
  460. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip1, system=system, duration=2e-3, slice_thickness=thk,
  461. apodization=0.5, time_bw_product=4)
  462. g_ss.channel = enc[2]
  463. # 180 pulse
  464. flip2 = 180 * pi / 180
  465. rf180, g_ss180, __ = make_sinc_pulse(flip_angle=flip2, system=system, duration=2e-3, slice_thickness=thk,
  466. apodization=0.5, time_bw_product=4)
  467. g_ss180.channel = enc[2]
  468. # Readout gradient & ADC
  469. # readoutTime = system.grad_raster_time * Nf
  470. readoutTime = 6.4e-3
  471. g_ro = make_trapezoid(channel=enc[0],system=system,flat_area=kWidth,flat_time=readoutTime)
  472. adc = make_adc(num_samples=Nf, system=system, duration=g_ro.flat_time, delay=g_ro.rise_time)
  473. # RO rewinder gradient
  474. g_ro_pre = make_trapezoid(channel=enc[0],system=system,area=g_ro.area/2,duration=2e-3)
  475. # Slice refocusing gradient
  476. g_ss_reph = make_trapezoid(channel=enc[2],system=system,area=-g_ss.area/2,duration=2e-3)
  477. # Delays
  478. delayTE1 = (TE - 2*max(calc_duration(g_ss_reph), calc_duration(g_ro_pre)) - calc_duration(g_ss) - calc_duration(
  479. g_ss180))/2
  480. # delayTE2 = TE / 2 - calc_duration(g_ro) / 2 - calc_duration(g_ss180) / 2
  481. delayTE2 = (TE - calc_duration(g_ro) - calc_duration(g_ss180))/2
  482. delayTE3 = TR - TE - (calc_duration(g_ss) + calc_duration(g_ro)) / 2
  483. delay1 = make_delay(delayTE1)
  484. delay2 = make_delay(delayTE2)
  485. delay3 = make_delay(delayTE3)
  486. # Construct sequence
  487. if slice_locs is None:
  488. locs = [0]
  489. else:
  490. locs = slice_locs
  491. for u in range(len(locs)):
  492. rf180.freq_offset = g_ss180.amplitude * locs[u]
  493. rf.freq_offset = g_ss.amplitude * locs[u]
  494. for i in range(Np):
  495. seq.add_block(rf, g_ss) # 90-deg pulse
  496. g_pe_pre = make_trapezoid(channel=enc[1],system=system,area=-(Np/2-i)*delta_k,duration=2e-3) # Phase encoding gradient
  497. seq.add_block(g_ro_pre, g_pe_pre, g_ss_reph) # Add a combination of ro rewinder, phase encoding, and slice refocusing
  498. seq.add_block(delay1) # Delay 1: until 180-deg pulse
  499. seq.add_block(rf180, g_ss180) # 180 deg pulse for SE
  500. seq.add_block(delay2) # Delay 2: until readout
  501. seq.add_block(g_ro, adc) # Readout!
  502. seq.add_block(delay3) # Delay 3: until next inversion pulse
  503. if write:
  504. seq.write("se_fov{:.0f}mm_Nf{:d}_Np{:d}_TE{:.0f}ms_TR{:.0f}ms.seq".format(fov * 1000, Nf, Np, TE * 1000, TR * 1000))
  505. print('Spin echo sequence constructed')
  506. return seq
  507. def make_pulseq_se_oblique(fov,n,thk,fa,tr,te,enc='xyz',slice_locs=None,write=False):
  508. """Makes a Spin Echo (SE) sequence in any plane
  509. 2D oblique multi-slice Spin-Echo pulse sequence with Cartesian encoding
  510. Oblique means that each of slice-selection, phase encoding, and frequency encoding
  511. can point in any specified direction
  512. Parameters
  513. ----------
  514. fov : array_like
  515. Isotropic field-of-view, or length-2 list [fov_readout, fov_phase], in meters
  516. n : array_like
  517. Isotropic matrix size, or length-2 list [n_readout, n_phase]
  518. thk : float
  519. Slice thickness in meters
  520. fa : float
  521. Flip angle in degrees
  522. tr : float
  523. Repetition time in seconds
  524. te : float
  525. Echo time in seconds
  526. enc : str or array_like, optional
  527. Spatial encoding directions
  528. 1st - readout; 2nd - phase encoding; 3rd - slice select
  529. - Use str with any permutation of x, y, and z to obtain orthogonal slices
  530. e.g. The default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  531. - Use list to indicate vectors in the encoding directions for oblique slices
  532. They should be perpendicular to each other, but not necessarily unit vectors
  533. e.g. [(2,1,0),(-1,2,0),(0,0,1)] rotates the two in-plane encoding directions for an axial slice
  534. slice_locs : array_like, optional
  535. Slice locations from isocenter in meters
  536. Default is None which means a single slice at the center
  537. write : bool, optional
  538. Whether to write seq into file; default is False
  539. Returns
  540. -------
  541. seq : Sequence
  542. Pulse sequence as a Pulseq object
  543. """
  544. # System options
  545. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  546. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  547. rf_dead_time=100e-6, adc_dead_time=20e-6)
  548. seq = Sequence(system)
  549. # Sequence parameters
  550. ug_fe, ug_pe, ug_ss = parse_enc(enc)
  551. Nf, Np = (n,n) if isinstance(n,int) else (n[0], n[1])
  552. delta_k_ro, delta_k_pe = (1/fov,1/fov) if isinstance(fov,float) else (1/fov[0], 1/fov[1])
  553. kWidth_ro = Nf * delta_k_ro
  554. TE,TR = te,tr
  555. # Non-180 pulse
  556. flip1 = fa * pi / 180
  557. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip1, system=system, duration=2e-3, slice_thickness=thk,
  558. apodization=0.5, time_bw_product=4)
  559. g_ss_x, g_ss_y, g_ss_z = make_oblique_gradients(g_ss,ug_ss)
  560. # 180 pulse
  561. flip2 = 180 * pi / 180
  562. rf180, g_ss180, __ = make_sinc_pulse(flip_angle=flip2, system=system, duration=2e-3, slice_thickness=thk,
  563. apodization=0.5, time_bw_product=4)
  564. g_ss180_x, g_ss180_y, g_ss180_z = make_oblique_gradients(g_ss180,ug_ss)
  565. # Readout gradient & ADC
  566. readoutTime = 6.4e-3
  567. g_ro = make_trapezoid(channel='x',system=system,flat_area=kWidth_ro, flat_time=readoutTime)
  568. g_ro_x, g_ro_y, g_ro_z = make_oblique_gradients(g_ro, ug_fe)
  569. adc = make_adc(num_samples=Nf, system=system, duration=g_ro.flat_time, delay=g_ro.rise_time)
  570. # RO rewinder gradient
  571. g_ro_pre = make_trapezoid(channel='x',system=system,area=g_ro.area/2,duration=2e-3)
  572. g_ro_pre_x, g_ro_pre_y, g_ro_pre_z = make_oblique_gradients(g_ro_pre, ug_fe)
  573. # Slice refocusing gradient
  574. g_ss_reph = make_trapezoid(channel='z',system=system,area=-g_ss.area/2,duration=2e-3)
  575. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z = make_oblique_gradients(g_ss_reph, ug_ss)
  576. # Delays
  577. delayTE1 = (TE - 2*max(calc_duration(g_ss_reph), calc_duration(g_ro_pre)) - calc_duration(g_ss) - calc_duration(
  578. g_ss180))/2
  579. delayTE2 = (TE - calc_duration(g_ro) - calc_duration(g_ss180))/2
  580. delayTE3 = TR - TE - (calc_duration(g_ss) + calc_duration(g_ro)) / 2
  581. delay1 = make_delay(delayTE1)
  582. delay2 = make_delay(delayTE2)
  583. delay3 = make_delay(delayTE3)
  584. # Construct sequence
  585. if slice_locs is None:
  586. locs = [0]
  587. else:
  588. locs = slice_locs
  589. for u in range(len(locs)):
  590. rf180.freq_offset = g_ss180.amplitude * locs[u]
  591. rf.freq_offset = g_ss.amplitude * locs[u]
  592. for i in range(Np):
  593. seq.add_block(rf, g_ss_x, g_ss_y, g_ss_z) # 90-deg pulse
  594. g_pe = make_trapezoid(channel='y',system=system,area=-(Np/2 - i)*delta_k_pe, duration=2e-3) # Phase encoding gradient
  595. g_pe_x, g_pe_y, g_pe_z = make_oblique_gradients(g_pe, ug_pe)
  596. pre_grads_list = [g_ro_pre_x, g_ro_pre_y, g_ro_pre_z,
  597. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z,
  598. g_pe_x, g_pe_y, g_pe_z]
  599. gtx, gty, gtz = combine_trap_grad_xyz(pre_grads_list, system, 2e-3)
  600. seq.add_block(gtx,gty,gtz) # Add a combination of ro rewinder, phase encoding, and slice refocusing
  601. seq.add_block(delay1) # Delay 1: until 180-deg pulse
  602. seq.add_block(rf180, g_ss180_x, g_ss180_y, g_ss180_z) # 180 deg pulse for SE
  603. seq.add_block(delay2) # Delay 2: until readout
  604. seq.add_block(g_ro_x, g_ro_y, g_ro_z, adc) # Readout!
  605. seq.add_block(delay3) # Delay 3: until next inversion pulse
  606. if write:
  607. seq.write("se_fov{:.0f}mm_Nf{:d}_Np{:d}_TE{:.0f}ms_TR{:.0f}ms_FA{:d}deg.seq".format(fov * 1000, Nf, Np, TE * 1000, TR * 1000, fa))
  608. print('Spin echo sequence (oblique) constructed')
  609. return seq
  610. # TODO multi-shot epi needs to be tested on scanner! : )
  611. def make_pulseq_epi_oblique(fov,n,thk,fa,tr,te,enc='xyz',slice_locs=None,echo_type="se",n_shots=1,seg_type='blocked',write=False):
  612. """Makes an Echo Planar Imaging (EPI) sequence in any plane
  613. 2D oblique multi-slice EPI pulse sequence with Cartesian encoding
  614. Oblique means that each of slice-selection, phase encoding, and frequency encoding
  615. can point in any specified direction
  616. Parameters
  617. ----------
  618. fov : array_like
  619. Isotropic field-of-view, or length-2 list [fov_readout, fov_phase], in meters
  620. n : array_like
  621. Isotropic matrix size, or length-2 list [n_readout, n_phase]
  622. thk : float
  623. Slice thickness in meters
  624. fa : float
  625. Flip angle in degrees
  626. tr : float
  627. Repetition time in seconds
  628. te : float
  629. Echo time in seconds
  630. enc : str or array_like, optional
  631. Spatial encoding directions
  632. 1st - readout; 2nd - phase encoding; 3rd - slice select
  633. - Use str with any permutation of x, y, and z to obtain orthogonal slices
  634. e.g. The default 'xyz' means axial(z) slice with readout in x and phase encoding in y
  635. - Use list to indicate vectors in the encoding directions for oblique slices
  636. They should be perpendicular to each other, but not necessarily unit vectors
  637. e.g. [(2,1,0),(-1,2,0),(0,0,1)] rotates the two in-plane encoding directions for an axial slice
  638. slice_locs : array_like, optional
  639. Slice locations from isocenter in meters
  640. Default is None which means a single slice at the center
  641. echo_type : str, optional {'se','gre'}
  642. Type of echo generated
  643. se (default) - spin echo (an 180 deg pulse is used)
  644. gre - gradient echo
  645. n_shots : int, optional
  646. Number of shots used to encode each slicel; default is 1
  647. seg_type : str, optional {'blocked','interleaved'}
  648. Method to divide up k-space in the case of n_shots > 1; default is 'blocked'
  649. 'blocked' - each shot covers a rectangle, with no overlap between shots
  650. 'interleaved' - each shot samples the full k-space but with wider phase steps
  651. write : bool, optional
  652. Whether to write seq into file; default is False
  653. Returns
  654. -------
  655. seq : Sequence
  656. Pulse sequence as a Pulseq object
  657. ro_dirs : numpy.ndarray
  658. List of 0s and 1s indicating direction of readout
  659. 0 - left to right
  660. 1 - right to left (needs to be reversed at recon)
  661. ro_order : numpy.ndarray
  662. Order in which to re-arrange the readout lines
  663. It is [] for blocked acquisition (retain original order)
  664. """
  665. # Multi-slice, multi-shot (>=1)
  666. # TE is set to be where the trajectory crosses the center of k-space
  667. # System options
  668. system = Opts(max_grad=32, grad_unit='mT/m', max_slew=130,
  669. slew_unit='T/m/s', rf_ringdown_time=30e-6,
  670. rf_dead_time=100e-6, adc_dead_time=20e-6)
  671. seq = Sequence(system)
  672. ug_fe, ug_pe, ug_ss = parse_enc(enc)
  673. # Sequence parameters
  674. Nf, Np = (n,n) if isinstance(n,int) else (n[0], n[1])
  675. delta_k_ro, delta_k_pe = (1/fov,1/fov) if isinstance(fov,float) else (1/fov[0], 1/fov[1])
  676. kWidth_ro = Nf * delta_k_ro
  677. TE,TR = te,tr
  678. flip = fa * pi / 180
  679. # RF Pulse (first)
  680. rf, g_ss, __ = make_sinc_pulse(flip_angle=flip, system=system,duration=2.5e-3, slice_thickness=thk,
  681. apodization=0.5, time_bw_product=4)
  682. g_ss_x, g_ss_y, g_ss_z = make_oblique_gradients(g_ss, ug_ss)
  683. # Readout gradients
  684. # readoutTime = Nf * 4e-6
  685. dwell=1e-5
  686. readoutTime = Nf*dwell
  687. g_ro_pos = make_trapezoid(channel='x',system=system,flat_area=kWidth_ro,flat_time=readoutTime)
  688. g_ro_pos_x, g_ro_pos_y, g_ro_pos_z = make_oblique_gradients(g_ro_pos,ug_fe)
  689. g_ro_neg = copy.deepcopy(g_ro_pos)
  690. modify_gradient(g_ro_neg,scale=-1)
  691. g_ro_neg_x, g_ro_neg_y, g_ro_neg_z = make_oblique_gradients(g_ro_neg,ug_fe)
  692. # TODO make sure delay is a multiple of gradient raster time
  693. # adc = make_adc(num_samples=Nf, system=system, duration=g_ro_pos.flat_time, delay=g_ro_pos.rise_time+dwell/2)
  694. adc = make_adc(num_samples=Nf, system=system, duration=g_ro_pos.flat_time, delay=g_ro_pos.rise_time)
  695. print("ADC delay: ", adc.delay)
  696. pre_time = 8e-4
  697. # 180 deg pulse for SE
  698. if echo_type == "se":
  699. # RF Pulse (180 deg for SE)
  700. flip180 = 180 * pi / 180
  701. rf180, g_ss180, __ = make_sinc_pulse(flip_angle=flip180, system=system,duration=2.5e-3,slice_thickness=thk,
  702. apodization=0.5, time_bw_product=4)
  703. g_ss180_x, g_ss180_y, g_ss180_z = make_oblique_gradients(g_ss180, ug_ss)
  704. # Slice-select direction spoilers
  705. g_ss_spoil = make_trapezoid(channel='z',system=system,area=g_ss.area*2,duration=3*pre_time)
  706. ##
  707. modify_gradient(g_ss_spoil,0)
  708. ##
  709. g_ss_spoil_x, g_ss_spoil_y, g_ss_spoil_z = make_oblique_gradients(g_ss_spoil, ug_ss)
  710. # Readout rewinder
  711. ro_pre_area = g_ro_neg.area / 2 if echo_type == 'gre' else g_ro_pos.area / 2
  712. g_ro_pre = make_trapezoid(channel='x',system=system, area=ro_pre_area, duration=pre_time)
  713. g_ro_pre_x, g_ro_pre_y, g_ro_pre_z = make_oblique_gradients(g_ro_pre,ug_fe)
  714. # Slice-selective rephasing
  715. g_ss_reph = make_trapezoid(channel='z',system=system,area=-g_ss.area/2,duration=pre_time)
  716. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z = make_oblique_gradients(g_ss_reph, ug_ss)
  717. # Phase encode rewinder
  718. if echo_type == 'gre':
  719. pe_max_area = (Np/2)*delta_k_pe
  720. elif echo_type == 'se':
  721. pe_max_area = -(Np/2)*delta_k_pe
  722. g_pe_max = make_trapezoid(channel='y',system=system,area=pe_max_area,duration=pre_time)
  723. # Phase encoding blips
  724. dur = ceil(2 * sqrt(delta_k_pe/ system.max_slew) / 10e-6) * 10e-6
  725. g_blip = make_trapezoid(channel='y',system=system,area=delta_k_pe,duration=dur)
  726. # Delays
  727. duration_to_center = (Np/ 2 ) * calc_duration(g_ro_pos) + (Np-1) / 2 * calc_duration(g_blip) # why?
  728. if echo_type == 'se':
  729. delayTE1 = TE / 2 - calc_duration(g_ss) / 2 - pre_time - calc_duration(g_ss_spoil) - calc_duration(rf180) / 2
  730. delayTE2 = TE / 2 - calc_duration(rf180) / 2 - calc_duration(g_ss_spoil) - duration_to_center
  731. delay1 = make_delay(delayTE1)
  732. delay2 = make_delay(delayTE2)
  733. elif echo_type == 'gre':
  734. delayTE = TE - calc_duration(g_ss)/2 - pre_time - duration_to_center
  735. delay12 = make_delay(delayTE)
  736. delayTR = TR - TE - calc_duration(rf) / 2 - duration_to_center
  737. delay3 = make_delay(delayTR) # This might be different for each rep though. Fix later
  738. #####################################################################################################
  739. # Multi-shot calculations
  740. ro_dirs = []
  741. ro_order = []
  742. # Find number of lines in each block
  743. if seg_type == 'blocked':
  744. # Number of lines in each full readout block
  745. nl = ceil(Np / n_shots)
  746. # Number of k-space lines per readout
  747. if Np%nl == 0:
  748. nlines_list = nl*np.ones(n_shots)
  749. else:
  750. nlines_list = nl*np.ones(n_shots-1)
  751. nlines_list = np.append(nlines_list,Np%nl)
  752. pe_scales = 2*np.append([0],np.cumsum(nlines_list)[:-1])/Np - 1
  753. g_blip_x, g_blip_y, g_blip_z = make_oblique_gradients(g_blip, ug_pe)
  754. for nlines in nlines_list:
  755. ro_dirs = np.append(ro_dirs, ((-1)**(np.arange(0,nlines)+1)+1)/2)
  756. elif seg_type == 'interleaved':
  757. # Minimum number of lines per readout
  758. nb = floor(Np / n_shots)
  759. # Number of k-space lines per readout
  760. nlines_list = np.ones(n_shots)*nb
  761. nlines_list[:Np%n_shots] += 1
  762. # Phase encoding scales (starts from -1; i.e. bottom left combined with pre-readout)
  763. pe_scales = 2*np.arange(0,(Np-n_shots)/Np,1/Np)[0:n_shots]-1
  764. print(pe_scales)
  765. # Larger blips
  766. modify_gradient(g_blip, scale=n_shots)
  767. g_blip_x, g_blip_y, g_blip_z = make_oblique_gradients(g_blip, ug_pe)
  768. # ro_order = np.reshape(np.reshape(np.arange(0,Np),(),order='F'),(0,Np))
  769. ro_order = np.zeros((nb+1,n_shots))
  770. ro_inds = np.arange(Np)
  771. # Readout order for recon
  772. for k in range(n_shots):
  773. cs = int(nlines_list[k])
  774. ro_order[:cs,k] = ro_inds[:cs]
  775. ro_inds = np.delete(ro_inds,range(cs))
  776. ro_order = ro_order.flatten()[:Np].astype(int)
  777. np.save('readout_order_for_interleaving.npy', ro_order)
  778. print(ro_order)
  779. # Readout directions in original (interleaved) order
  780. for nlines in nlines_list:
  781. ro_dirs = np.append(ro_dirs, ((-1)**(np.arange(0,nlines)+1)+1)/2)
  782. #####################################################################################################
  783. # Add blocks
  784. for u in range(len(slice_locs)): # For each slice
  785. # Offset rf
  786. rf.freq_offset = g_ss.amplitude * slice_locs[u]
  787. for v in range(n_shots):
  788. # Find init. phase encode
  789. g_pe = copy.deepcopy(g_pe_max)
  790. modify_gradient(g_pe, pe_scales[v])
  791. g_pe_x, g_pe_y, g_pe_z = make_oblique_gradients(g_pe, ug_pe)
  792. # First RF
  793. seq.add_block(rf, g_ss_x, g_ss_y, g_ss_z)
  794. # Pre-winder gradients
  795. pre_grads_list = [g_ro_pre_x, g_ro_pre_y, g_ro_pre_z,
  796. g_pe_x, g_pe_y, g_pe_z,
  797. g_ss_reph_x, g_ss_reph_y, g_ss_reph_z]
  798. gtx, gty, gtz = combine_trap_grad_xyz(pre_grads_list, system, pre_time)
  799. seq.add_block(gtx, gty, gtz)
  800. # 180 deg pulse and spoilers, only for Spin Echo
  801. if echo_type == 'se':
  802. # First delay
  803. seq.add_block(delay1)
  804. # Second RF : 180 deg with spoilers on both sides
  805. seq.add_block(g_ss_spoil_x, g_ss_spoil_y, g_ss_spoil_z)#why?
  806. seq.add_block(rf180, g_ss180_x, g_ss180_y, g_ss180_z)
  807. seq.add_block(g_ss_spoil_x, g_ss_spoil_y, g_ss_spoil_z)
  808. # Delay between rf180 and beginning of readout
  809. seq.add_block(delay2)
  810. # For gradient echo it's just a delay
  811. elif echo_type == 'gre':
  812. seq.add_block(delay12)
  813. # EPI readout with blips
  814. for i in range(int(nlines_list[v])):
  815. if i%2 == 0:
  816. seq.add_block(g_ro_pos_x, g_ro_pos_y, g_ro_pos_z, adc) # ro line in the positive direction
  817. else:
  818. seq.add_block(g_ro_neg_x, g_ro_neg_y, g_ro_neg_z, adc) # ro line backwards
  819. seq.add_block(g_blip_x, g_blip_y, g_blip_z) # blip
  820. seq.add_block(delay3)
  821. # Display 1 TR
  822. #seq.plot(time_range=(0, TR))
  823. if write:
  824. seq.write("epi_{}_FOV{:.0f}mm_Nf{:d}_Np{:d}_TE{:.0f}ms_TR{:.0f}ms_FA{:d}deg_{:d}shots.seq"\
  825. .format(echo_type, fov*1000, Nf, Np, TE * 1000, TR * 1000, fa, n_shots))
  826. print('EPI sequence (oblique) constructed')
  827. return seq, ro_dirs, ro_order
  828. def parse_enc(enc):
  829. """Helper function for decoding enc parameter
  830. Parameters
  831. ----------
  832. enc : str or array_like
  833. Inputted encoding scheme to parse
  834. Returns
  835. -------
  836. ug_fe : numpy.ndarray
  837. Length-3 vector of readout direction
  838. ug_pe : numpy.ndarray
  839. Length-3 vector of phase encoding direction
  840. ug_ss : numpy.ndarray
  841. Length-3 vector of slice selecting direction
  842. """
  843. if isinstance(enc, str):
  844. xyz_dict = {'x': (1, 0, 0), 'y': (0, 1, 0), 'z': (0, 0, 1)}
  845. ug_fe = xyz_dict[enc[0]]
  846. ug_pe = xyz_dict[enc[1]]
  847. ug_ss = xyz_dict[enc[2]]
  848. else:
  849. ug_fe = np.array(enc[0])
  850. ug_pe = np.array(enc[1])
  851. ug_ss = np.array(enc[2])
  852. ug_fe = ug_fe / np.linalg.norm(ug_fe)
  853. ug_pe = ug_pe / np.linalg.norm(ug_pe)
  854. ug_ss = ug_ss / np.linalg.norm(ug_ss)
  855. print('ug_fe: ', ug_fe)
  856. print('ug_pe: ', ug_pe)
  857. print('ug_ss: ', ug_ss)
  858. return ug_fe, ug_pe, ug_ss
  859. def make_oblique_gradients(gradient,unit_grad):
  860. """Helper function to make oblique gradients
  861. (Gx, Gy, Gz) are generated from a single orthogonal gradient
  862. and a direction indicated by unit vector
  863. Parameters
  864. ----------
  865. gradient : Gradient
  866. Pulseq gradient object
  867. unit_grad: array_like
  868. Length-3 unit vector indicating direction of resulting oblique gradient
  869. Returns
  870. -------
  871. ngx, ngy, ngz : Gradient
  872. Oblique gradients in x, y, and z directions
  873. """
  874. ngx = copy.deepcopy(gradient)
  875. ngy = copy.deepcopy(gradient)
  876. ngz = copy.deepcopy(gradient)
  877. modify_gradient(ngx, unit_grad[0],'x')
  878. modify_gradient(ngy, unit_grad[1],'y')
  879. modify_gradient(ngz, unit_grad[2],'z')
  880. return ngx, ngy, ngz
  881. def modify_gradient(gradient,scale,channel=None):
  882. """Helper function to modify the strength and channel of an existing gradient
  883. Parameters
  884. ----------
  885. gradient : Gradient
  886. Pulseq gradient object to be modified
  887. scale : float
  888. Scalar to multiply the gradient strength by
  889. channel : str, optional {None, 'x','y','z'}
  890. Channel to switch gradient into
  891. Default is None which keeps the original channel
  892. """
  893. gradient.amplitude *= scale
  894. gradient.area *= scale
  895. if gradient.type == 'trap':
  896. gradient.flat_area *= scale
  897. if channel != None:
  898. gradient.channel = channel
  899. def combine_trap_grad_xyz(gradients,system,dur):
  900. """Helper function that merges multiple gradients
  901. A list of gradients are combined into one set of 3 oblique gradients (Gx, Gy, Gz) with equivalent areas
  902. Note that the waveforms are not preserved : the outputs will always be trapezoidal gradients
  903. Parameters
  904. ----------
  905. gradients : list
  906. List of gradients to be combined; there can be any number of x, y, or z gradients
  907. system : Opts
  908. Pulseq object that indicates system constraints for gradient parameters
  909. dur : float
  910. Duration of the output oblique gradients
  911. Returns
  912. -------
  913. gtx, gty, gtz : Gradient
  914. Oblique pulseq gradients with equivalent areas to all input gradients combined
  915. """
  916. gx_area, gy_area, gz_area = (0,0,0)
  917. for g in gradients:
  918. if g.channel == 'x':
  919. gx_area += g.area
  920. elif g.channel == 'y':
  921. gy_area += g.area
  922. elif g.channel == 'z':
  923. gz_area += g.area
  924. gtx = make_trapezoid(channel='x',system=system,area=gx_area,duration=dur)
  925. gty = make_trapezoid(channel='y',system=system,area=gy_area,duration=dur)
  926. gtz = make_trapezoid(channel='z',system=system,area=gz_area,duration=dur)
  927. return gtx, gty, gtz