-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathsequence.py
executable file
·1703 lines (1496 loc) · 69.1 KB
/
sequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import itertools
import math
from collections import OrderedDict
from copy import copy
from itertools import chain
from types import SimpleNamespace
from typing import Tuple, List, Iterable
from typing import Union
from warnings import warn
import matplotlib as mpl
import numpy as np
from matplotlib import pyplot as plt
from pypulseq import eps
from pypulseq.Sequence import block, parula
from pypulseq.Sequence.ext_test_report import ext_test_report
from pypulseq.Sequence.read_seq import read
from pypulseq.Sequence.write_seq import write as write_seq
from pypulseq.calc_rf_center import calc_rf_center
from pypulseq.check_timing import check_timing as ext_check_timing
from pypulseq.decompress_shape import decompress_shape
from pypulseq.event_lib import EventLibrary
from pypulseq.opts import Opts
from pypulseq.supported_labels_rf_use import get_supported_labels
from version import major, minor, revision
class Sequence:
"""
Generate sequences and read/write sequence files. This class defines properties and methods to define a complete MR
sequence including RF pulses, gradients, ADC events, etc. The class provides an implementation of the open MR
sequence format defined by the Pulseq project. See http://pulseq.github.io/.
See also `demo_read.py`, `demo_write.py`.
"""
version_major = major
version_minor = minor
version_revision = revision
def __init__(self, system=Opts()):
# =========
# EVENT LIBRARIES
# =========
self.adc_library = EventLibrary() # Library of ADC events
self.delay_library = EventLibrary() # Library of delay events
# Library of extension events. Extension events form single-linked zero-terminated lists
self.extensions_library = EventLibrary()
self.grad_library = EventLibrary() # Library of gradient events
self.label_inc_library = (
EventLibrary()
) # Library of Label(inc) events (reference from the extensions library)
self.label_set_library = (
EventLibrary()
) # Library of Label(set) events (reference from the extensions library)
self.rf_library = EventLibrary() # Library of RF events
self.shape_library = EventLibrary() # Library of compressed shapes
self.trigger_library = EventLibrary() # Library of trigger events
# =========
# OTHER
# =========
self.system = system
self.block_events = OrderedDict() # Event table
self.definitions = dict() # Optional sequence definitions
self.rf_raster_time = (
self.system.rf_raster_time
) # RF raster time (system dependent)
self.grad_raster_time = (
self.system.grad_raster_time
) # Gradient raster time (system dependent)
self.adc_raster_time = (
self.system.adc_raster_time
) # ADC raster time (system dependent)
self.block_duration_raster = self.system.block_duration_raster
self.set_definition("AdcRasterTime", self.adc_raster_time)
self.set_definition("BlockDurationRaster", self.block_duration_raster)
self.set_definition("GradientRasterTime", self.grad_raster_time)
self.set_definition("RadiofrequencyRasterTime", self.rf_raster_time)
self.signature_type = ""
self.signature_file = ""
self.signature_value = ""
self.block_durations = [] # Cache of block durations
self.extension_numeric_idx = [] # numeric IDs of the used extensions
self.extension_string_idx = [] # string IDs of the used extensions
def __str__(self) -> str:
s = "Sequence:"
s += "\nshape_library: " + str(self.shape_library)
s += "\nrf_library: " + str(self.rf_library)
s += "\ngrad_library: " + str(self.grad_library)
s += "\nadc_library: " + str(self.adc_library)
s += "\ndelay_library: " + str(self.delay_library)
s += "\nextensions_library: " + str(
self.extensions_library
) # inserted for trigger support by mveldmann
s += "\nrf_raster_time: " + str(self.rf_raster_time)
s += "\ngrad_raster_time: " + str(self.grad_raster_time)
s += "\nblock_events: " + str(len(self.block_events))
return s
def add_block(self, *args: SimpleNamespace) -> None:
"""
Add a new block/multiple events to the sequence. Adds a sequence block with provided as a block structure
See also:
- `pypulseq.Sequence.sequence.Sequence.set_block()`
- `pypulseq.make_adc.make_adc()`
- `pypulseq.make_trapezoid.make_trapezoid()`
- `pypulseq.make_sinc_pulse.make_sinc_pulse()`
Parameters
----------
args : SimpleNamespace
Block structure or events to be added as a block to `Sequence`.
"""
block.set_block(self, len(self.block_events) + 1, *args)
def calculate_kspace(
self, trajectory_delay: int = 0
) -> Tuple[np.array, np.array, np.array, np.array, np.array]:
"""
Calculates the k-space trajectory of the entire pulse sequence.
Parameters
----------
trajectory_delay : int, default=0
Compensation factor in seconds (s) to align ADC and gradients in the reconstruction.
Returns
-------
k_traj_adc : numpy.array
K-space trajectory sampled at `t_adc` timepoints.
k_traj : numpy.array
K-space trajectory of the entire pulse sequence.
t_excitation : numpy.array
Excitation timepoints.
t_refocusing : numpy.array
Refocusing timepoints.
t_adc : numpy.array
Sampling timepoints.
"""
if np.any(np.abs(trajectory_delay) > 100e-6):
raise Warning(
f"Trajectory delay of {trajectory_delay * 1e6} us is suspiciously high"
)
# Initialise the counters and accumulator objects
count_excitation = 0
count_refocusing = 0
count_adc_samples = 0
# Loop through the blocks to prepare preallocations
for block_counter in range(len(self.block_events)):
block = self.get_block(block_counter + 1)
if block.rf is not None:
if (
not hasattr(block.rf, "use")
or block.rf.use == "excitation"
or block.rf.use == "undefined"
):
count_excitation += 1
elif block.rf.use == "refocusing":
count_refocusing += 1
if block.adc is not None:
count_adc_samples += int(block.adc.num_samples)
t_excitation = np.zeros(count_excitation)
t_refocusing = np.zeros(count_refocusing)
k_time = np.zeros(count_adc_samples)
current_duration = 0
count_excitation = 0
count_refocusing = 0
kc_outer = 0
traj_recon_delay = trajectory_delay
# Go through the blocks and collect RF and ADC timing data
for block_counter in range(len(self.block_events)):
block = self.get_block(block_counter + 1)
if block.rf is not None:
rf = block.rf
rf_center, _ = calc_rf_center(rf)
t = rf.delay + rf_center
if (
not hasattr(block.rf, "use")
or block.rf.use == "excitation"
or block.rf.use == "undefined"
):
t_excitation[count_excitation] = current_duration + t
count_excitation += 1
elif block.rf.use == "refocusing":
t_refocusing[count_refocusing] = current_duration + t
count_refocusing += 1
if block.adc is not None:
_k_time = np.arange(block.adc.num_samples) + 0.5
_k_time = (
_k_time * block.adc.dwell
+ block.adc.delay
+ current_duration
+ traj_recon_delay
)
k_time[kc_outer : kc_outer + block.adc.num_samples] = _k_time
kc_outer += block.adc.num_samples
current_duration += self.block_durations[block_counter]
# Now calculate the actual k-space trajectory based on the gradient waveforms
gw = self.gradient_waveforms()
i_excitation = np.round(t_excitation / self.grad_raster_time)
i_refocusing = np.round(t_refocusing / self.grad_raster_time)
i_periods = np.sort(
[1, *(i_excitation + 1), *(i_refocusing + 1), gw.shape[1] + 1]
).astype(np.int32)
# i_periods -= 1 # Python is 0-indexed
ii_next_excitation = np.min((len(i_excitation), 1))
ii_next_refocusing = np.min((len(i_refocusing), 1))
k_traj = np.zeros_like(gw)
k = np.zeros((3, 1))
for i in range(len(i_periods) - 1):
i_period_end = i_periods[i + 1] - 1
k_period = np.concatenate(
(k, gw[:, i_periods[i] - 1 : i_period_end] * self.grad_raster_time),
axis=1,
)
k_period = np.cumsum(k_period, axis=1)
k_traj[:, i_periods[i] - 1 : i_period_end] = k_period[:, 1:]
k = k_period[:, -1]
if (
ii_next_excitation > 0
and i_excitation[ii_next_excitation - 1] == i_period_end
):
k[:] = 0
k_traj[:, i_period_end - 1] = np.nan
ii_next_excitation = min(len(i_excitation), ii_next_excitation + 1)
if (
ii_next_refocusing > 0
and i_refocusing[ii_next_refocusing - 1] == i_period_end
):
k = -k
ii_next_refocusing = min(len(i_refocusing), ii_next_refocusing + 1)
k = k.reshape((-1, 1)) # To be compatible with np.concatenate
k_traj_adc = []
for _k_traj_row in k_traj:
result = np.interp(
xp=np.array(range(1, k_traj.shape[1] + 1)) * self.grad_raster_time,
fp=_k_traj_row,
x=k_time,
)
k_traj_adc.append(result)
k_traj_adc = np.stack(k_traj_adc)
t_adc = k_time
return k_traj_adc, k_traj, t_excitation, t_refocusing, t_adc
def calculate_kspacePP(
self,
trajectory_delay: Union[int, float, np.ndarray] = 0,
gradient_offset: int = 0,
) -> Tuple[np.array, np.array, np.array, np.array, np.array]:
"""
Calculates the k-space trajectory of the entire pulse sequence.
Parameters
----------
trajectory_delay : int, default=0
Compensation factor in seconds (s) to align ADC and gradients in the reconstruction.
Returns
-------
k_traj_adc : numpy.array
K-space trajectory sampled at `t_adc` timepoints.
k_traj : numpy.array
K-space trajectory of the entire pulse sequence.
t_excitation : numpy.array
Excitation timepoints.
t_refocusing : numpy.array
Refocusing timepoints.
t_adc : numpy.array
Sampling timepoints.
"""
if np.any(np.abs(trajectory_delay) > 100e-6):
raise Warning(
f"Trajectory delay of {trajectory_delay * 1e6} us is suspiciously high"
)
total_duration = np.sum(self.block_durations)
gw_data, tfp_excitation, tfp_refocusing, t_adc, _ = self.waveforms_and_times()
ng = len(gw_data)
# Gradient delay handling
if isinstance(trajectory_delay, (int, float)):
gradient_delays = [trajectory_delay] * ng
else:
assert (
len(trajectory_delay) == ng
) # Need to have same number of gradient channels
gradient_delays = [trajectory_delay] * ng
# Gradient offset handling
if isinstance(gradient_offset, (int, float)):
gradient_offset = [gradient_offset] * ng
else:
assert (
len(gradient_offset) == ng
) # Need to have same number of gradient channels
# Convert data to piecewise polynomials
gw_pp = []
gw_pp_MATLAB = []
for j in range(ng):
wave_cnt = gw_data[j].shape[1]
if wave_cnt == 0:
if np.abs(gradient_offset[j]) <= eps:
continue
else:
gw = np.array(([0, total_duration], [0, 0]))
else:
gw = gw_data[j]
# Now gw contains the waveform from the current axis
if np.abs(gradient_delays[j]) > eps:
gw[1] = gw[1] - gradient_delays[j] # Anisotropic gradient delay support
if not np.all(np.isfinite(gw)):
raise Warning("Not all elements of the generated waveform are finite.")
teps = 1e-12
if gw[0, 0] > 0 and gw[1, -1] < total_duration:
# teps terms to avoid integration errors over extended periods of time
_temp1 = np.array(([-teps, gw[0, 0] - teps], [0, 0]))
_temp2 = np.array(([gw[0, -1] + teps, total_duration + teps], [0, 0]))
gw = np.hstack((_temp1, gw, _temp2))
elif gw[0, 0] > 0:
_temp = np.array(([-teps, gw[0, 0] - teps], [0, 0]))
gw = np.hstack((_temp, gw))
elif gw[0, -1] < total_duration:
_temp = np.array(([gw[0, -1] + teps, total_duration + teps], [0, 0]))
gw = np.hstack((gw, _temp))
if np.abs(gradient_offset[j]) > eps:
gw[1:] += gradient_offset[j]
gw[1][gw[1] == -0.0] = 0.0
# Specify window to be same as domain prevent numpy from remapping to [-1, 1]
polyfit = [
np.polynomial.Polynomial.fit(
gw[0, i : (i + 2)],
gw[1, i : (i + 2)],
deg=1,
window=gw[0, i : (i + 2)],
)
for i in range(len(gw[0]) - 1)
]
polyfit = np.stack(polyfit)
gw_pp.append(polyfit)
###
"""
Fix coefs for consistency with MATLAB:
1. MATLAB returns coefficients in descending order whereas Numpy returns coefficients in ascending order.
2. MATLAB returns local coefficients that will NOT match Numpy's outputs. Refer to the equation under the
"output arguments" section of `mkpp` MATLAB docs to convert and match coefficient outputs.
3. Finally, MATLAB seems to not store any -1 < x < 1 coefficients, so we zero them out.
"""
polyfit_MATLAB = []
for i in range(len(polyfit)):
polyfit_MATLAB_i = copy(polyfit[i])
lower = polyfit_MATLAB_i.domain[0]
co = polyfit_MATLAB_i.coef
co = co[::-1] # Reverse
a = co[0]
b = co[1] + (a * lower)
if -1 < a < 1: # to investigate
a = 0
if -1 < b < 1:
b = 0
# co = [b, a] # Un-reverse for Numpy
co = [a, b]
polyfit_MATLAB_i.coef = co
polyfit_MATLAB.append(polyfit_MATLAB_i)
gw_pp_MATLAB.append(polyfit_MATLAB)
###
# Calculate slice positions. For now we entirely rely on the excitation -- ignoring complicated interleaved
# refocused sequences
if len(tfp_excitation) > 0:
# Position in x, y, z
slice_pos = np.zeros((len(gw_data), tfp_excitation.shape[1]))
for j in range(len(gw_data)):
if gw_pp[j] is None:
slice_pos[j] = np.empty_like((1, slice_pos.shape[1]))
else:
slice_pos[j] = np.divide(
tfp_excitation[1], self.ppval_numpy(gw_pp[j], tfp_excitation[0])
)
slice_pos[~np.isfinite(slice_pos)] = 0 # Reset undefined to 0
t_slice_pos = tfp_excitation[0]
else:
slice_pos = []
t_slice_pos = []
# FNINT
def fnint(arr_poly):
pieces = len(arr_poly)
breaks = np.stack([pp.domain for pp in arr_poly])
breaks = np.append(breaks[:, 0], breaks[-1, 1])
coefs = np.stack([pp.coef for pp in arr_poly])
order = len(arr_poly[1].coef)
dim = 1
coefs = coefs / np.tile(range(order, 0, -1), (dim * pieces, 1))
xs = np.diff(breaks[:-1])
index = np.arange(pieces - 1)
vv = xs * coefs[index, 0]
for i in range(1, order):
vv = xs * (vv + coefs[index, i])
last = np.cumsum(np.insert(vv, 0, 0)).reshape((-1, 1))
coefs = np.hstack((coefs[:, :order], last))
arr_poly_integ = []
for i in range(pieces):
arr_poly_integ.append(
np.polynomial.Polynomial(
coefs[i],
domain=[breaks[i], breaks[i + 1]],
window=[breaks[i], breaks[i + 1]],
)
)
return arr_poly_integ, coefs, breaks
# =========
# Integrate waveforms as PPs to produce gradient moments
gm_pp = []
tc = []
for i in range(ng):
if gw_pp[i] is None:
continue
res_fnint, res_coefs, res_breaks = fnint(gw_pp_MATLAB[i])
gm_pp.append(res_fnint)
tc.append(res_breaks)
# "Sample" ramps for display purposes otherwise piecewise-linear display (plot) fails
ii = np.nonzero(np.abs(res_coefs[:, 0]) > eps)[0]
if len(ii) > 0:
tca = []
for j in range(len(ii)):
res = (
np.arange(
np.floor(float(res_breaks[ii[j]] / self.grad_raster_time)),
np.ceil(
(res_breaks[ii[j] + 1] / self.grad_raster_time) + 1
),
)
* self.grad_raster_time
)
tca.extend(res)
tc.append(tca)
tc = np.array(list(chain(*tc)))
if len(tfp_excitation) == 0:
t_excitation = np.array([])
else:
t_excitation = tfp_excitation[0]
if len(tfp_refocusing) == 0:
t_refocusing = np.array([])
else:
t_refocusing = tfp_refocusing[0]
t_acc = 1e-10 # Temporal accuracy
t_acc_inv = 1 / t_acc
# tc = self.__flatten_jagged_arr(tc)
t_ktraj = t_acc * np.unique(
np.round(
t_acc_inv
* np.array(
[
*tc,
0,
*np.array(t_excitation) * 2 - self.rf_raster_time,
*np.array(t_excitation) - self.rf_raster_time,
*t_excitation,
*np.array(t_refocusing) - self.rf_raster_time,
*t_refocusing,
*t_adc,
total_duration,
]
)
)
)
i_excitation = np.isin(t_ktraj, t_acc * np.round(t_acc_inv * t_excitation))
i_excitation = np.nonzero(i_excitation)[0] # Convert boolean array into indices
i_refocusing = np.isin(t_ktraj, t_acc * np.round(t_acc_inv * t_refocusing))
i_refocusing = np.nonzero(i_refocusing)[0] # Convert boolean array into indices
i_adc = np.isin(t_ktraj, t_acc * np.round(t_acc_inv * t_adc))
i_adc = np.nonzero(i_adc)[0] # Convert boolean array into indices
i_periods = np.unique([1, *i_excitation, *i_refocusing, len(t_ktraj) - 1])
if len(i_excitation) > 0:
ii_next_excitation = 1
else:
ii_next_excitation = 0
if len(i_refocusing) > 0:
ii_next_refocusing = 1
else:
ii_next_refocusing = 0
k_traj = np.zeros((3, len(t_ktraj)))
for i in range(ng):
if gw_pp_MATLAB[i] is None:
continue
it = np.logical_and(
t_ktraj >= t_acc * np.round(t_acc_inv * res_breaks[0]),
t_ktraj <= t_acc * np.round(t_acc_inv * res_breaks[-1]),
)
k_traj[i, it] = self.ppval_MATLAB(gm_pp[i], t_ktraj[it])
if t_ktraj[it[-1]] < t_ktraj[-1]:
k_traj[i, it[-1] + 1 :] = k_traj[i, it[-1]]
# Convert gradient moments to kspace
dk = -k_traj[:, 0]
for i in range(len(i_periods) - 1):
i_period = i_periods[i]
i_period_end = i_periods[i + 1]
if ii_next_excitation > 0 and i_excitation[ii_next_excitation] == i_period:
if np.abs(t_ktraj[i_period] - t_excitation[ii_next_excitation]) > t_acc:
raise Warning(
f"np.abs(t_ktraj[i_period]-t_excitation[ii_next_excitation]) < {t_acc} failed for ii_next_excitation={ii_next_excitation} error={t_ktraj(i_period) - t_excitation(ii_next_excitation)}"
)
dk = -k_traj[:, i_period]
if i_period > 1:
# Use nans to mark the excitation points since they interrupt the plots
k_traj[:, i_period - 1] = np.NaN
# -1 on len(i_excitation) for 0-based indexing
ii_next_excitation = np.minimum(
len(i_excitation) - 1, ii_next_excitation + 1
)
elif (
ii_next_refocusing > 0 and i_refocusing[ii_next_refocusing] == i_period
):
dk = -k_traj[:, i_period]
dk = -2 * k_traj[:, i_period] - dk
# -1 on len(i_excitation) for 0-based indexing
ii_next_refocusing = np.minimum(
len(i_refocusing) - 1, ii_next_refocusing + 1
)
k_traj[:, i_period:i_period_end] = (
k_traj[:, i_period:i_period_end] + dk[:, None]
)
k_traj[:, i_period_end] = k_traj[:, i_period_end] + dk
k_traj_adc = k_traj[:, i_adc]
return k_traj_adc, k_traj, t_excitation, t_refocusing, t_adc
def check_timing(self) -> Tuple[bool, List[str]]:
"""
Checks timing of all blocks and objects in the sequence optionally returns the detailed error log. This
function also modifies the sequence object by adding the field "TotalDuration" to sequence definitions.
Returns
-------
is_ok : bool
Boolean flag indicating timing errors.
error_report : str
Error report in case of timing errors.
"""
error_report = []
is_ok = True
num_blocks = len(self.block_events)
total_duration = 0
for block_counter in range(num_blocks):
block = self.get_block(block_counter + 1)
events = [e for e in vars(block).values() if e is not None]
res, rep, duration = ext_check_timing(self.system, *events)
is_ok = is_ok and res
# Check the stored total block duration
if np.abs(duration - self.block_durations[block_counter]) > eps:
rep += "Inconsistency between the stored block duration and the duration of the block content"
is_ok = False
duration = self.block_durations[block_counter]
# Check RF dead times
if block.rf is not None:
if block.rf.delay - block.rf.dead_time < -eps:
rep += (
f"Delay of {block.rf.delay * 1e6} us is smaller than the RF dead time "
f"{block.rf.dead_time * 1e6} us"
)
is_ok = False
if (
block.rf.delay + block.rf.t[-1] + block.rf.ringdown_time - duration
> eps
):
rep += (
f"Time between the end of the RF pulse at {block.rf.delay + block.rf.t[-1]} and the end "
f"of the block at {duration * 1e6} us is shorter than rf_ringdown_time"
)
is_ok = False
# Check ADC dead times
if block.adc is not None:
if block.adc.delay - self.system.adc_dead_time < -eps:
rep += "adc.delay < system.adc_dead_time"
is_ok = False
if (
block.adc.delay
+ block.adc.num_samples * block.adc.dwell
+ self.system.adc_dead_time
- duration
> eps
):
rep += "adc: system.adc_dead_time (post-ADC) violation"
is_ok = False
# Update report
if len(rep) != 0:
error_report.append(f"Event: {block_counter} - {rep}\n")
total_duration += duration
# Check if all the gradients in the last block are ramped down properly
if len(events) != 0 and all([isinstance(e, SimpleNamespace) for e in events]):
for e in range(len(events)):
if not isinstance(events[e], list) and events[e].type == "grad":
if events[e].last != 0:
error_report.append(
f"Event {num_blocks - 1} gradients do not ramp to 0 at the end of the sequence"
)
self.set_definition("TotalDuration", total_duration)
return is_ok, error_report
def duration(self) -> Tuple[int, int, np.ndarray]:
"""
Returns the total duration of this sequence, and the total count of blocks and events.
Returns
-------
duration : int
Duration of this sequence in seconds (s).
num_blocks : int
Number of blocks in this sequence.
event_count : np.ndarray
Number of events in this sequence.
"""
num_blocks = len(self.block_events)
event_count = np.zeros(len(self.block_events[1]))
duration = 0
for block_counter in range(num_blocks):
event_count += self.block_events[block_counter + 1] > 0
duration += self.block_durations[block_counter]
return duration, num_blocks, event_count
def __flatten_jagged_arr(self, arr: np.array) -> np.array:
# Sanity check: we don't need to do anything if we have a flat array
def __flat_check(arr: np.array) -> bool:
return all([not isinstance(x, Iterable) for x in arr])
if __flat_check(arr):
return arr
# Flatten the array simply -- 1 level deep
arr_flattened = list(itertools.chain(*arr))
# Not flat yet?
if __flat_check(arr_flattened):
return arr_flattened
# Flatten the array -- 2 levels deep
any_ragged = [isinstance(x, Iterable) for x in arr_flattened]
if np.any(any_ragged):
idx_ragged = np.array(np.where(any_ragged)[0])
for i in range(len(idx_ragged)):
ii = idx_ragged[i]
# If we are not at the end of the list, we need to update the indices of the remaining elements
# Because once we expand and insert this list element, the indices of the remaining elements
# will be shifted by len(this element)
if i != len(idx_ragged) - 1:
idx_ragged[i + 1 :] += len(arr_flattened[ii])
arr_flattened = np.insert(arr_flattened, ii, arr_flattened[ii])
return arr_flattened
def flip_grad_axis(self, axis: str) -> None:
"""
Invert all gradients along the corresponding axis/channel. The function acts on all gradient objects already
added to the sequence object.
Parameters
----------
axis : str
Gradients to invert or scale. Must be one of 'x', 'y' or 'z'.
"""
self.mod_grad_axis(axis, modifier=-1)
def get_block(self, block_index: int) -> SimpleNamespace:
"""
Return a block of the sequence specified by the index. The block is created from the sequence data with all
events and shapes decompressed.
See also:
- `pypulseq.Sequence.sequence.Sequence.set_block()`.
- `pypulseq.Sequence.sequence.Sequence.add_block()`.
Parameters
----------
block_index : int
Index of block to be retrieved from `Sequence`.
Returns
-------
SimpleNamespace
Event identified by `block_index`.
"""
return block.get_block(self, block_index)
def get_definition(self, key: str) -> str:
"""
Return value of the definition specified by the key. These definitions can be added manually or read from the
header of a sequence file defined in the sequence header. An empty array is returned if the key is not defined.
See also `pypulseq.Sequence.sequence.Sequence.set_definition()`.
Parameters
----------
key : str
Key of definition to retrieve.
Returns
-------
str
Definition identified by `key` if found, else returns ''.
"""
if key in self.definitions:
return self.definitions[key]
else:
return ""
def get_extension_type_ID(self, extension_string: str) -> int:
"""
Get numeric extension ID for `extension_string`. Will automatically create a new ID if unknown.
Parameters
----------
extension_string : str
Given string extension ID.
Returns
-------
extension_id : int
Numeric ID for given string extension ID.
"""
if extension_string not in self.extension_string_idx:
if len(self.extension_numeric_idx) == 0:
extension_id = 1
else:
extension_id = 1 + max(self.extension_numeric_idx)
self.extension_numeric_idx.append(extension_id)
self.extension_string_idx.append(extension_string)
assert len(self.extension_numeric_idx) == len(self.extension_string_idx)
else:
num = self.extension_string_idx.index(extension_string)
extension_id = self.extension_numeric_idx[num]
return extension_id
def get_extension_type_string(self, extension_id: int) -> str:
"""
Get string extension ID for `extension_id`.
Parameters
----------
extension_id : int
Given numeric extension ID.
Returns
-------
extension_str : str
String ID for the given numeric extension ID.
Raises
------
ValueError
If given numeric extension ID is unknown.
"""
if extension_id in self.extension_numeric_idx:
num = self.extension_numeric_idx.index(extension_id)
else:
raise ValueError(
f"Extension for the given ID - {extension_id} - is unknown."
)
extension_str = self.extension_string_idx[num]
return extension_str
def mod_grad_axis(self, axis: str, modifier: int) -> None:
"""
Invert or scale all gradients along the corresponding axis/channel. The function acts on all gradient objects
already added to the sequence object.
Parameters
----------
axis : str
Gradients to invert or scale. Must be one of 'x', 'y' or 'z'.
modifier : int
Scaling value.
Raises
------
ValueError
If invalid `axis` is passed. Must be one of 'x', 'y','z'.
RuntimeError
If same gradient event is used on multiple axes.
"""
if axis not in ["x", "y", "z"]:
raise ValueError(
f"Invalid axis. Must be one of 'x', 'y','z'. Passed: {axis}"
)
channel_num = ["x", "y", "z"].index(axis)
other_channels = [0, 1, 2]
other_channels.remove(channel_num)
# Go through all event table entries and list gradient objects in the library
all_grad_events = np.array(list(self.block_events.values()))
all_grad_events = all_grad_events[:, 2:5]
selected_events = np.unique(all_grad_events[:, channel_num])
selected_events = selected_events[selected_events != 0]
other_events = np.unique(all_grad_events[:, other_channels])
if len(np.intersect1d(selected_events, other_events)) > 0:
raise RuntimeError(
"mod_grad_axis does not yet support the same gradient event used on multiple axes."
)
for i in range(len(selected_events)):
self.grad_library.data[selected_events[i]][0] *= modifier
if (
self.grad_library.type[selected_events[i]] == "g"
and self.grad_library.lengths[selected_events[i]] == 5
):
# Need to update first and last fields
self.grad_library.data[selected_events[i]][3] *= modifier
self.grad_library.data[selected_events[i]][4] *= modifier
def plot(
self,
label: str = str(),
show_blocks: bool = False,
save: bool = False,
time_range=(0, np.inf),
time_disp: str = "s",
grad_disp: str = "kHz/m",
plot_now: bool = True
) -> None:
"""
Plot `Sequence`.
Parameters
----------
label : str, defualt=str()
Plot label values for ADC events: in this example for LIN and REP labels; other valid labes are accepted as
a comma-separated list.
save : bool, default=False
Boolean flag indicating if plots should be saved. The two figures will be saved as JPG with numerical
suffixes to the filename 'seq_plot'.
show_blocks : bool, default=False
Boolean flag to indicate if grid and tick labels at the block boundaries are to be plotted.
time_range : iterable, default=(0, np.inf)
Time range (x-axis limits) for plotting the sequence. Default is 0 to infinity (entire sequence).
time_disp : str, default='s'
Time display type, must be one of `s`, `ms` or `us`.
grad_disp : str, default='s'
Gradient display unit, must be one of `kHz/m` or `mT/m`.
plot_now : bool, default=True
If true, function immediately shows the plots, blocking the rest of the code until plots are exited.
If false, plots are shown when plt.show() is called. Useful if plots are to be modified.
plot_type : str, default='Gradient'
Gradients display type, must be one of either 'Gradient' or 'Kspace'.
"""
mpl.rcParams["lines.linewidth"] = 0.75 # Set default Matplotlib linewidth
valid_time_units = ["s", "ms", "us"]
valid_grad_units = ["kHz/m", "mT/m"]
valid_labels = get_supported_labels()
if (
not all([isinstance(x, (int, float)) for x in time_range])
or len(time_range) != 2
):
raise ValueError("Invalid time range")
if time_disp not in valid_time_units:
raise ValueError("Unsupported time unit")
if grad_disp not in valid_grad_units:
raise ValueError(
"Unsupported gradient unit. Supported gradient units are: "
+ str(valid_grad_units)
)
fig1, fig2 = plt.figure(1), plt.figure(2)
sp11 = fig1.add_subplot(311)
sp12 = fig1.add_subplot(312, sharex=sp11)
sp13 = fig1.add_subplot(313, sharex=sp11)
fig2_subplots = [
fig2.add_subplot(311, sharex=sp11),
fig2.add_subplot(312, sharex=sp11),
fig2.add_subplot(313, sharex=sp11),
]
t_factor_list = [1, 1e3, 1e6]
t_factor = t_factor_list[valid_time_units.index(time_disp)]
g_factor_list = [1e-3, 1e3 / self.system.gamma]
g_factor = g_factor_list[valid_grad_units.index(grad_disp)]
t0 = 0
label_defined = False
label_idx_to_plot = []
label_legend_to_plot = []
label_store = dict()
for i in range(len(valid_labels)):
label_store[valid_labels[i]] = 0
if valid_labels[i] in label.upper():
label_idx_to_plot.append(i)
label_legend_to_plot.append(valid_labels[i])
if len(label_idx_to_plot) != 0:
p = parula.main(len(label_idx_to_plot) + 1)
label_colors_to_plot = p(np.arange(len(label_idx_to_plot)))
label_colors_to_plot = np.roll(label_colors_to_plot, -1, axis=0).tolist()
# Block timings
block_edges = np.cumsum([0, *self.block_durations])
block_edges_in_range = block_edges[
(block_edges >= time_range[0]) * (block_edges <= time_range[1])
]
if show_blocks:
for sp in [sp11, sp12, sp13, *fig2_subplots]:
sp.set_xticks(t_factor * block_edges_in_range)
sp.set_xticklabels(rotation=90)
for block_counter in range(len(self.block_events)):
block = self.get_block(block_counter + 1)
is_valid = time_range[0] <= t0 <= time_range[1]
if is_valid:
if getattr(block, "label", None) is not None:
for i in range(len(block.label)):
if block.label[i].type == "labelinc":
label_store[block.label[i].label] += block.label[i].value
else:
label_store[block.label[i].label] = block.label[i].value
label_defined = True
if getattr(block, "adc", None) is not None: # ADC
adc = block.adc
# From Pulseq: According to the information from Klaus Scheffler and indirectly from Siemens this
# is the present convention - the samples are shifted by 0.5 dwell
t = adc.delay + (np.arange(int(adc.num_samples)) + 0.5) * adc.dwell
sp11.plot(t_factor * (t0 + t), np.zeros(len(t)), "rx")
sp13.plot(
t_factor * (t0 + t),
np.angle(
np.exp(1j * adc.phase_offset)
* np.exp(1j * 2 * np.pi * t * adc.freq_offset)
),
"b.",
markersize=0.25,
)
if label_defined and len(label_idx_to_plot) != 0:
cycler = mpl.cycler(color=label_colors_to_plot)
sp11.set_prop_cycle(cycler)
label_colors_to_plot = np.roll(
label_colors_to_plot, -1, axis=0
).tolist()
arr_label_store = list(label_store.values())