-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSequence.html
More file actions
953 lines (843 loc) · 48.1 KB
/
Copy pathSequence.html
File metadata and controls
953 lines (843 loc) · 48.1 KB
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
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--
This HTML was auto-generated from MATLAB code.
To make changes, update the MATLAB code and republish this document.
--><title>Sequence</title><meta name="generator" content="MATLAB 8.5"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2015-12-14"><meta name="DC.source" content="Sequence.m"><style type="text/css">
html,body,div.content,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:'';content:none}:focus{outine:0}ins{text-decoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0}
html { min-height:100%; margin-bottom:1px; }
html body { height:100%; margin:0px; font-family:Arial, Helvetica, sans-serif; font-size:10px; color:#000; line-height:140%; background:#fff none; overflow-y:scroll; }
html body td { vertical-align:top; text-align:left; }
h1 { padding:0px; margin:0px 0px 25px; font-family:Arial, Helvetica, sans-serif; font-size:1.5em; color:#d55000; line-height:100%; font-weight:normal; }
h2 { padding:0px; margin:0px 0px 8px; font-family:Arial, Helvetica, sans-serif; font-size:1.2em; color:#000; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }
h3 { padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; color:#000; font-weight:bold; line-height:140%; }
a { color:#005fce; text-decoration:none; }
a:hover { color:#005fce; text-decoration:underline; }
a:visited { color:#004aa0; text-decoration:none; }
p { padding:0px; margin:0px 0px 20px; }
img { padding:0px; margin:0px 0px 20px; border:none; }
p img, pre img, tt img, li img, h1 img, h2 img { margin-bottom:0px; }
ul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }
ul li { padding:0px; margin:0px 0px 7px 0px; }
ul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }
ul li ol li { list-style:decimal; }
ol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }
ol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }
ol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }
ol li ol li { list-style-type:lower-alpha; }
ol li ul { padding-top:7px; }
ol li ul li { list-style:square; }
.content { font-size:1.2em; line-height:140%; padding: 20px; }
pre, code { font-size:12px; }
tt { font-size: 1.2em; }
pre { margin:0px 0px 20px; }
pre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }
pre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }
pre.error { color:red; }
@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }
span.keyword { color:#0000FF }
span.comment { color:#228B22 }
span.string { color:#A020F0 }
span.untermstring { color:#B20000 }
span.syscmd { color:#B28C00 }
.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }
.footer p { margin:0px; }
.footer a { color:#878787; }
.footer a:hover { color:#878787; text-decoration:underline; }
.footer a:visited { color:#878787; }
table.content th { padding:7px 5px; text-align:left; vertical-align:middle; border: 1px solid #d6d4d4; font-weight:bold; }
table.content td { padding:7px 5px; text-align:left; vertical-align:top; border:1px solid #d6d4d4; }
</style></head><body><div class="content"><pre class="codeinput"><span class="keyword">classdef</span> Sequence < handle
<span class="comment">% Sequence Generate sequences and read/write sequence files.</span>
<span class="comment">% This class defines properties and methods to define a complete</span>
<span class="comment">% MR sequence including RF pulses, gradients, ADC events, etc.</span>
<span class="comment">%</span>
<span class="comment">% The class provides an implementation of the open MR sequence format</span>
<span class="comment">% defined by the Pulseq project.</span>
<span class="comment">% See http://pulseq.github.io/</span>
<span class="comment">%</span>
<span class="comment">% Sequence Properties:</span>
<span class="comment">% definitions - A list of custom definitions</span>
<span class="comment">%</span>
<span class="comment">% Sequence Methods:</span>
<span class="comment">% read - Load sequence from open MR sequence format</span>
<span class="comment">% write - Write sequence to open MR sequence format</span>
<span class="comment">%</span>
<span class="comment">% Sequence Static Methods:</span>
<span class="comment">% makeTrapezoid - Create a trapezoid gradient structure</span>
<span class="comment">%</span>
<span class="comment">% Examples:</span>
<span class="comment">%</span>
<span class="comment">% To read a sequence from file:</span>
<span class="comment">% read(seqObj,'my_sequences/gre.seq');</span>
<span class="comment">%</span>
<span class="comment">% To plot a sequence:</span>
<span class="comment">% plot(seqObj)</span>
<span class="comment">%</span>
<span class="comment">% See also demoRead.m, demoWrite.m</span>
<span class="comment">% Examples defining an MRI sequence and reading/writing files</span>
<span class="comment">%</span>
<span class="comment">% Kelvin Layton <kelvin.layton@uniklinik-freiburg.de></span>
<span class="comment">% Private properties</span>
<span class="comment">%</span>
<span class="keyword">properties</span>(GetAccess = public, SetAccess = private)
rfRasterTime; <span class="comment">% RF raster time (system dependent)</span>
gradRasterTime; <span class="comment">% Gradient raster time (system dependent)</span>
definitions <span class="comment">% Optional sequence definitions</span>
blockEvents; <span class="comment">% Event table (references to events)</span>
rfLibrary; <span class="comment">% Library of RF events</span>
gradLibrary; <span class="comment">% Library of gradient events</span>
adcLibrary; <span class="comment">% Library of ADC readouts</span>
delayLibrary; <span class="comment">% Library of delay events</span>
shapeLibrary; <span class="comment">% Library of compressed shapes</span>
<span class="keyword">end</span>
<span class="keyword">methods</span>
<span class="keyword">function</span> obj = Sequence(varargin)
obj.definitions=containers.Map();
obj.gradLibrary=mr.EventLibrary();
obj.shapeLibrary=mr.EventLibrary();
obj.rfLibrary=mr.EventLibrary();
obj.adcLibrary=mr.EventLibrary();
obj.delayLibrary=mr.EventLibrary();
<span class="keyword">if</span> nargin<1
sys=mr.opts();
<span class="keyword">else</span>
sys=varargin{1};
<span class="keyword">end</span>
obj.rfRasterTime = sys.rfRasterTime;
obj.gradRasterTime = sys.gradRasterTime;
<span class="keyword">end</span>
<span class="comment">% See read.m</span>
read(obj,filename)
<span class="comment">% See write.m</span>
write(obj,filename)
<span class="comment">% See readBinary.m</span>
readBinary(obj,filename);
<span class="comment">% See writeBinary.m</span>
writeBinary(obj,filename);
<span class="keyword">function</span> value=getDefinition(obj,key)
<span class="comment">%getDefinition Return the values of custom definition.</span>
<span class="comment">% val=getDefinitions(seqObj,key) Return value of the</span>
<span class="comment">% definition specified by the key.</span>
<span class="comment">% These definitions can be added manually or read from the</span>
<span class="comment">% header of a sequence file defined in the sequence header.</span>
<span class="comment">% An empty array is return if the key is not defined.</span>
<span class="comment">%</span>
<span class="comment">% See also setDefinition</span>
<span class="keyword">if</span> isKey(obj.definitions,key)
value = obj.definitions(key);
<span class="keyword">else</span>
value = [];
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">function</span> setDefinition(seqObj,key,val)
<span class="comment">%setDefinition Modify a custom definition of the sequence.</span>
<span class="comment">% setDefinition(seqObj,def,val) Set the user definition 'key'</span>
<span class="comment">% to value 'val'. If the definition does not exist it will be</span>
<span class="comment">% created.</span>
<span class="comment">%</span>
<span class="comment">% See also getDefinition</span>
seqObj.definitions(key)=val;
<span class="keyword">end</span>
<span class="keyword">function</span> addBlock(obj,varargin)
<span class="comment">%addBlock Add a new block to the sequence.</span>
<span class="comment">% addBlock(obj, blockStruct) Adds a sequence block with</span>
<span class="comment">% provided as a block struture</span>
<span class="comment">%</span>
<span class="comment">% addBlock(obj, e1, e2, ...) Adds a block with multiple</span>
<span class="comment">% events e1, e2, etc.</span>
<span class="comment">%</span>
<span class="comment">% See also setBlock, makeAdc, makeTrapezoid, makeSincPulse</span>
setBlock(obj,size(obj.blockEvents,1)+1,varargin{:});
<span class="keyword">end</span>
<span class="comment">%TODO: Replacing blocks in the middle of sequence can cause unused</span>
<span class="comment">%events in the libraries. These can be detected and pruned.</span>
<span class="keyword">function</span> setBlock(obj,index,varargin)
<span class="comment">%setBlock Replace sequence block.</span>
<span class="comment">% setBlock(obj, index, bStruct) Replace block at index with new</span>
<span class="comment">% block provided as block structure.</span>
<span class="comment">%</span>
<span class="comment">% setBlock(obj, index, e1, e2, ...) Create a new block from</span>
<span class="comment">% events and store at position given by index.</span>
<span class="comment">%</span>
<span class="comment">% The block or events are provided in uncompressed form and</span>
<span class="comment">% will be stored in the compressed, non-redundant internal</span>
<span class="comment">% libraries.</span>
<span class="comment">%</span>
<span class="comment">% See also getBlock, addBlock</span>
<span class="comment">% Convert block structure to cell array of events</span>
varargin=mr.block2events(varargin);
varargin(cellfun(@(C)isempty(C),varargin))=[];
obj.blockEvents(index,:) = zeros(1,6);
duration = 0;
<span class="comment">% Loop over events adding to library if necessary and creating</span>
<span class="comment">% block event structure.</span>
<span class="keyword">for</span> i=1:length(varargin)
event = varargin{i};
<span class="keyword">switch</span> event.type
<span class="keyword">case</span> <span class="string">'rf'</span>
<span class="comment">% TODO: Interpolate to 1us time grid using event.t</span>
<span class="comment">% if required.</span>
mag = abs(event.signal);
amplitude=max(mag);
mag = mag/amplitude;
phase = angle(event.signal);
phase(phase<0)=phase(phase<0)+2*pi;
phase=phase/(2*pi);
magShape = mr.compressShape(mag(:));
data = [magShape.num_samples magShape.data];
[magId,found] = obj.shapeLibrary.find(data);
<span class="keyword">if</span> ~found
obj.shapeLibrary.insert(magId,data);
<span class="keyword">end</span>
phaseShape = mr.compressShape(phase);
data = [phaseShape.num_samples phaseShape.data];
[phaseId,found] = obj.shapeLibrary.find(data);
<span class="keyword">if</span> ~found
obj.shapeLibrary.insert(phaseId,data);
<span class="keyword">end</span>
data = [amplitude magId phaseId event.freqOffset event.phaseOffset event.deadTime];
[id,found] = obj.rfLibrary.find(data);
<span class="keyword">if</span> ~found
obj.rfLibrary.insert(id,data);
<span class="keyword">end</span>
obj.blockEvents(index,2)=id;
duration=max(duration,length(mag)*obj.rfRasterTime+event.deadTime);
<span class="keyword">case</span> <span class="string">'grad'</span>
channelNum = find(strcmp(event.channel,{<span class="string">'x'</span>,<span class="string">'y'</span>,<span class="string">'z'</span>}));
amplitude = max(abs(event.waveform));
g = event.waveform./amplitude;
shape = mr.compressShape(g);
data = [shape.num_samples shape.data];
[shapeId,found] = obj.shapeLibrary.find(data);
<span class="keyword">if</span> ~found
obj.shapeLibrary.insert(shapeId,data);
<span class="keyword">end</span>
data = [amplitude shapeId];
[id,found] = obj.gradLibrary.find(data);
<span class="keyword">if</span> ~found
obj.gradLibrary.insert(id,data,<span class="string">'g'</span>);
<span class="keyword">end</span>
idx = 2+channelNum;
obj.blockEvents(index,idx)=id;
duration=max(duration,length(g)*obj.gradRasterTime);
<span class="keyword">case</span> <span class="string">'trap'</span>
channelNum = find(strcmp(event.channel,{<span class="string">'x'</span>,<span class="string">'y'</span>,<span class="string">'z'</span>}));
data = [event.amplitude event.riseTime event.flatTime event.fallTime];
[id,found] = obj.gradLibrary.find(data);
<span class="keyword">if</span> ~found
obj.gradLibrary.insert(id,data,<span class="string">'t'</span>);
<span class="keyword">end</span>
idx = 2+channelNum;
obj.blockEvents(index,idx)=id;
duration=max(duration,event.riseTime+event.flatTime+event.fallTime);
<span class="keyword">case</span> <span class="string">'adc'</span>
data = [event.numSamples event.dwell event.delay <span class="keyword">...</span>
event.freqOffset event.phaseOffset event.deadTime];
[id,found] = obj.adcLibrary.find(data);
<span class="keyword">if</span> ~found
obj.adcLibrary.insert(id,data);
<span class="keyword">end</span>
obj.blockEvents(index,6)=id;
duration=max(duration,event.delay+event.numSamples*event.dwell+event.deadTime);
<span class="keyword">case</span> <span class="string">'delay'</span>
data = [event.delay];
[id,found] = obj.delayLibrary.find(data);
<span class="keyword">if</span> ~found
obj.delayLibrary.insert(id,data);
<span class="keyword">end</span>
obj.blockEvents(index,1)=id;
duration=max(duration,event.delay);
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">function</span> block = getBlock(obj,index)
<span class="comment">%getBlock Return a block of the sequence.</span>
<span class="comment">% b=getBlock(obj, index) Return the block specified by the</span>
<span class="comment">% index.</span>
<span class="comment">%</span>
<span class="comment">% The block is created from the sequence data with all</span>
<span class="comment">% events and shapes decompressed.</span>
<span class="comment">%</span>
<span class="comment">% See also setBlock, addBlock</span>
block=struct(<span class="string">'rf'</span>,{},<span class="string">'gx'</span>,{},<span class="string">'gy'</span>,{},<span class="string">'gz'</span>,{},<span class="string">'adc'</span>,{},<span class="string">'delay'</span>,{});
block(1).rf=[];
eventInd = obj.blockEvents(index,:);
<span class="keyword">if</span> eventInd(1)>0
delay.type = <span class="string">'delay'</span>;
delay.delay = obj.delayLibrary.data(eventInd(1)).array;
block.delay = delay;
<span class="keyword">end</span>
<span class="keyword">if</span> eventInd(2)>0
rf.type=<span class="string">'rf'</span>;
libData = obj.rfLibrary.data(eventInd(2)).array;
amplitude = libData(1);
magShape = libData(2);
phaseShape = libData(3);
shapeData = obj.shapeLibrary.data(magShape).array;
compressed.num_samples = shapeData(1);
compressed.data=shapeData(2:end);
mag = mr.decompressShape(compressed);
shapeData = obj.shapeLibrary.data(phaseShape).array;
compressed.num_samples = shapeData(1);
compressed.data=shapeData(2:end);
phase = mr.decompressShape(compressed);
rf.signal = amplitude*mag.*exp(1j*2*pi*phase);
rf.t = (1:length(mag))'*obj.rfRasterTime;
rf.freqOffset = libData(4);
rf.phaseOffset = libData(5);
<span class="keyword">if</span> length(libData)<6
libData(end+1)=0;
<span class="keyword">end</span>
rf.deadTime = libData(6);
block.rf = rf;
<span class="keyword">end</span>
gradChannels = {<span class="string">'gx'</span>,<span class="string">'gy'</span>,<span class="string">'gz'</span>};
<span class="keyword">for</span> i=1:length(gradChannels)
<span class="keyword">if</span> eventInd(2+i)>0
type = obj.gradLibrary.type(eventInd(2+i));
libData = obj.gradLibrary.data(eventInd(2+i)).array;
<span class="keyword">if</span> type==<span class="string">'t'</span>
grad.type = <span class="string">'trap'</span>;
<span class="keyword">else</span>
grad.type = <span class="string">'grad'</span>;
<span class="keyword">end</span>
grad.channel = gradChannels{i}(2);
<span class="keyword">if</span> strcmp(grad.type,<span class="string">'grad'</span>)
amplitude = libData(1);
shapeId = libData(2);
shapeData = obj.shapeLibrary.data(shapeId).array;
compressed.num_samples = shapeData(1);
compressed.data=shapeData(2:end);
g = mr.decompressShape(compressed);
grad.waveform = amplitude*g;
grad.t = (1:length(g))'*obj.gradRasterTime;
<span class="keyword">else</span>
grad.amplitude = libData(1);
grad.riseTime = libData(2);
grad.flatTime = libData(3);
grad.fallTime = libData(4);
grad.area = grad.amplitude*(grad.flatTime+grad.riseTime/2+grad.fallTime/2);
grad.flatArea = grad.amplitude*grad.flatTime;
<span class="keyword">end</span>
block.(gradChannels{i}) = grad;
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">if</span> eventInd(6)>0
libData = obj.adcLibrary.data(eventInd(6)).array;
<span class="keyword">if</span> length(libData)<6
libData(end+1)=0;
<span class="keyword">end</span>
adc = cell2struct(num2cell(libData),<span class="keyword">...</span>
{<span class="string">'numSamples'</span>,<span class="string">'dwell'</span>,<span class="string">'delay'</span>,<span class="string">'freqOffset'</span>,<span class="string">'phaseOffset'</span>,<span class="string">'deadTime'</span>},2);
adc.type=<span class="string">'adc'</span>;
block.adc = adc;
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">function</span> f=plot(obj,varargin)
<span class="comment">%plot Plot the sequence in a new figure.</span>
<span class="comment">% plot(seqObj) Plot the sequence</span>
<span class="comment">%</span>
<span class="comment">% plot(...,'Type',type) Plot the sequence with gradients</span>
<span class="comment">% displayed according to type: 'Gradient' or 'Kspace'.</span>
<span class="comment">%</span>
<span class="comment">% plot(...,'TimeRange',[start stop]) Plot the sequence</span>
<span class="comment">% between the times specified by start and stop.</span>
<span class="comment">%</span>
<span class="comment">% plot(...,'TimeDisp',unit) Display time in:</span>
<span class="comment">% 's', 'ms' or 'us'.</span>
<span class="comment">%</span>
<span class="comment">% f=plot(...) Return the new figure handle.</span>
<span class="comment">%</span>
validPlotTypes = {<span class="string">'Gradient'</span>,<span class="string">'Kspace'</span>};
validTimeUnits = {<span class="string">'s'</span>,<span class="string">'ms'</span>,<span class="string">'us'</span>};
<span class="keyword">persistent</span> parser
<span class="keyword">if</span> isempty(parser)
parser = inputParser;
parser.FunctionName = <span class="string">'plot'</span>;
parser.addParamValue(<span class="string">'type'</span>,validPlotTypes{1},<span class="keyword">...</span>
@(x) any(validatestring(x,validPlotTypes)));
parser.addParamValue(<span class="string">'timeRange'</span>,[0 inf],@(x)(isnumeric(x) && length(x)==2));
parser.addParamValue(<span class="string">'timeDisp'</span>,validTimeUnits{1},<span class="keyword">...</span>
@(x) any(validatestring(x,validTimeUnits)));
<span class="keyword">end</span>
parse(parser,varargin{:});
opt = parser.Results;
fig=figure;
<span class="keyword">if</span> nargout>0
f=fig;
<span class="keyword">end</span>
ax=zeros(1,6);
<span class="keyword">for</span> i=1:6
ax(i)=subplot(3,2,i);
<span class="keyword">end</span>
ax=ax([1 3 5 2 4 6]); <span class="comment">% Re-order axes</span>
arrayfun(@(x)hold(x,<span class="string">'on'</span>),ax);
arrayfun(@(x)grid(x,<span class="string">'on'</span>),ax);
labels={<span class="string">'ADC'</span>,<span class="string">'RF mag (Hz)'</span>,<span class="string">'RF ph (rad)'</span>,<span class="string">'Gx (kHz/m)'</span>,<span class="string">'Gy (kHz/m)'</span>,<span class="string">'Gz (kHz/m)'</span>};
arrayfun(@(x)ylabel(ax(x),labels{x}),1:6);
tFactorList = [1 1e3 1e6];
tFactor = tFactorList(strcmp(opt.timeDisp,validTimeUnits));
xlabel(ax(3),[<span class="string">'t ('</span> opt.timeDisp <span class="string">')'</span>]);
xlabel(ax(6),[<span class="string">'t ('</span> opt.timeDisp <span class="string">')'</span>]);
t0=0;
<span class="keyword">for</span> iB=1:size(obj.blockEvents,1)
block = obj.getBlock(iB);
isValid = t0>=opt.timeRange(1) && t0<=opt.timeRange(2);
<span class="keyword">if</span> isValid
<span class="keyword">if</span> ~isempty(block.adc)
adc=block.adc;
t=adc.delay + (0:adc.numSamples-1)*adc.dwell;
plot(tFactor*(t0+t),zeros(size(t)),<span class="string">'rx'</span>,<span class="string">'Parent'</span>,ax(1));
<span class="keyword">end</span>
<span class="keyword">if</span> ~isempty(block.rf)
rf=block.rf;
t=rf.t;
plot(tFactor*(t0+t),abs(rf.signal),<span class="string">'Parent'</span>,ax(2));
plot(tFactor*(t0+t),angle(rf.signal),<span class="string">'Parent'</span>,ax(3));
<span class="keyword">end</span>
gradChannels={<span class="string">'gx'</span>,<span class="string">'gy'</span>,<span class="string">'gz'</span>};
<span class="keyword">for</span> j=1:length(gradChannels)
grad=block.(gradChannels{j});
<span class="keyword">if</span> ~isempty(block.(gradChannels{j}))
<span class="keyword">if</span> strcmp(grad.type,<span class="string">'grad'</span>)
t=grad.t;
waveform=1e-3*grad.waveform;
<span class="keyword">else</span>
t=cumsum([0 grad.riseTime grad.flatTime grad.fallTime]);
waveform=1e-3*grad.amplitude*[0 1 1 0];
<span class="keyword">end</span>
plot(tFactor*(t0+t),waveform,<span class="string">'Parent'</span>,ax(3+j));
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">end</span>
t0=t0+mr.calcDuration(block);
<span class="keyword">end</span>
<span class="comment">% Set axis limits and zoom properties</span>
dispRange = tFactor*[opt.timeRange(1) min(opt.timeRange(2),t0)];
arrayfun(@(x)xlim(x,dispRange),ax);
linkaxes(ax(:),<span class="string">'x'</span>)
h = zoom(fig);
setAxesZoomMotion(h,ax(1),<span class="string">'horizontal'</span>);
<span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">methods</span> (Static)
<span class="keyword">function</span> codes=getBinaryCodes()
<span class="comment">%getBinaryCodes Return binary codes for section headers in</span>
<span class="comment">% in a binary sequence file.</span>
<span class="comment">%</span>
<span class="comment">% See also writeBinary</span>
codes.fileHeader = [1 <span class="string">'pulseq'</span> 2];
codes.version = int64(1);
prefix = bitshift(int64(hex2dec(<span class="string">'FFFFFFFF'</span>)),32);
codes.section.definitions = bitor(prefix,int64(1));
codes.section.blocks = bitor(prefix,int64(2));
codes.section.rf = bitor(prefix,int64(3));
codes.section.gradients = bitor(prefix,int64(4));
codes.section.trapezoids = bitor(prefix,int64(5));
codes.section.adc = bitor(prefix,int64(6));
codes.section.delays = bitor(prefix,int64(7));
codes.section.shapes = bitor(prefix,int64(8));
<span class="keyword">end</span>
<span class="keyword">end</span> <span class="comment">% Static methods</span>
<span class="keyword">end</span> <span class="comment">% classdef</span>
</pre><p class="footer"><br><a href="http://www.mathworks.com/products/matlab/">Published with MATLAB® R2015a</a><br></p></div><!--
##### SOURCE BEGIN #####
classdef Sequence < handle
% 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/
%
% Sequence Properties:
% definitions - A list of custom definitions
%
% Sequence Methods:
% read - Load sequence from open MR sequence format
% write - Write sequence to open MR sequence format
%
% Sequence Static Methods:
% makeTrapezoid - Create a trapezoid gradient structure
%
% Examples:
%
% To read a sequence from file:
% read(seqObj,'my_sequences/gre.seq');
%
% To plot a sequence:
% plot(seqObj)
%
% See also demoRead.m, demoWrite.m
% Examples defining an MRI sequence and reading/writing files
%
% Kelvin Layton <kelvin.layton@uniklinik-freiburg.de>
% Private properties
%
properties(GetAccess = public, SetAccess = private)
rfRasterTime; % RF raster time (system dependent)
gradRasterTime; % Gradient raster time (system dependent)
definitions % Optional sequence definitions
blockEvents; % Event table (references to events)
rfLibrary; % Library of RF events
gradLibrary; % Library of gradient events
adcLibrary; % Library of ADC readouts
delayLibrary; % Library of delay events
shapeLibrary; % Library of compressed shapes
end
methods
function obj = Sequence(varargin)
obj.definitions=containers.Map();
obj.gradLibrary=mr.EventLibrary();
obj.shapeLibrary=mr.EventLibrary();
obj.rfLibrary=mr.EventLibrary();
obj.adcLibrary=mr.EventLibrary();
obj.delayLibrary=mr.EventLibrary();
if nargin<1
sys=mr.opts();
else
sys=varargin{1};
end
obj.rfRasterTime = sys.rfRasterTime;
obj.gradRasterTime = sys.gradRasterTime;
end
% See read.m
read(obj,filename)
% See write.m
write(obj,filename)
% See readBinary.m
readBinary(obj,filename);
% See writeBinary.m
writeBinary(obj,filename);
function value=getDefinition(obj,key)
%getDefinition Return the values of custom definition.
% val=getDefinitions(seqObj,key) 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 return if the key is not defined.
%
% See also setDefinition
if isKey(obj.definitions,key)
value = obj.definitions(key);
else
value = [];
end
end
function setDefinition(seqObj,key,val)
%setDefinition Modify a custom definition of the sequence.
% setDefinition(seqObj,def,val) Set the user definition 'key'
% to value 'val'. If the definition does not exist it will be
% created.
%
% See also getDefinition
seqObj.definitions(key)=val;
end
function addBlock(obj,varargin)
%addBlock Add a new block to the sequence.
% addBlock(obj, blockStruct) Adds a sequence block with
% provided as a block struture
%
% addBlock(obj, e1, e2, ...) Adds a block with multiple
% events e1, e2, etc.
%
% See also setBlock, makeAdc, makeTrapezoid, makeSincPulse
setBlock(obj,size(obj.blockEvents,1)+1,varargin{:});
end
%TODO: Replacing blocks in the middle of sequence can cause unused
%events in the libraries. These can be detected and pruned.
function setBlock(obj,index,varargin)
%setBlock Replace sequence block.
% setBlock(obj, index, bStruct) Replace block at index with new
% block provided as block structure.
%
% setBlock(obj, index, e1, e2, ...) Create a new block from
% events and store at position given by index.
%
% The block or events are provided in uncompressed form and
% will be stored in the compressed, non-redundant internal
% libraries.
%
% See also getBlock, addBlock
% Convert block structure to cell array of events
varargin=mr.block2events(varargin);
varargin(cellfun(@(C)isempty(C),varargin))=[];
obj.blockEvents(index,:) = zeros(1,6);
duration = 0;
% Loop over events adding to library if necessary and creating
% block event structure.
for i=1:length(varargin)
event = varargin{i};
switch event.type
case 'rf'
% TODO: Interpolate to 1us time grid using event.t
% if required.
mag = abs(event.signal);
amplitude=max(mag);
mag = mag/amplitude;
phase = angle(event.signal);
phase(phase<0)=phase(phase<0)+2*pi;
phase=phase/(2*pi);
magShape = mr.compressShape(mag(:));
data = [magShape.num_samples magShape.data];
[magId,found] = obj.shapeLibrary.find(data);
if ~found
obj.shapeLibrary.insert(magId,data);
end
phaseShape = mr.compressShape(phase);
data = [phaseShape.num_samples phaseShape.data];
[phaseId,found] = obj.shapeLibrary.find(data);
if ~found
obj.shapeLibrary.insert(phaseId,data);
end
data = [amplitude magId phaseId event.freqOffset event.phaseOffset event.deadTime];
[id,found] = obj.rfLibrary.find(data);
if ~found
obj.rfLibrary.insert(id,data);
end
obj.blockEvents(index,2)=id;
duration=max(duration,length(mag)*obj.rfRasterTime+event.deadTime);
case 'grad'
channelNum = find(strcmp(event.channel,{'x','y','z'}));
amplitude = max(abs(event.waveform));
g = event.waveform./amplitude;
shape = mr.compressShape(g);
data = [shape.num_samples shape.data];
[shapeId,found] = obj.shapeLibrary.find(data);
if ~found
obj.shapeLibrary.insert(shapeId,data);
end
data = [amplitude shapeId];
[id,found] = obj.gradLibrary.find(data);
if ~found
obj.gradLibrary.insert(id,data,'g');
end
idx = 2+channelNum;
obj.blockEvents(index,idx)=id;
duration=max(duration,length(g)*obj.gradRasterTime);
case 'trap'
channelNum = find(strcmp(event.channel,{'x','y','z'}));
data = [event.amplitude event.riseTime event.flatTime event.fallTime];
[id,found] = obj.gradLibrary.find(data);
if ~found
obj.gradLibrary.insert(id,data,'t');
end
idx = 2+channelNum;
obj.blockEvents(index,idx)=id;
duration=max(duration,event.riseTime+event.flatTime+event.fallTime);
case 'adc'
data = [event.numSamples event.dwell event.delay ...
event.freqOffset event.phaseOffset event.deadTime];
[id,found] = obj.adcLibrary.find(data);
if ~found
obj.adcLibrary.insert(id,data);
end
obj.blockEvents(index,6)=id;
duration=max(duration,event.delay+event.numSamples*event.dwell+event.deadTime);
case 'delay'
data = [event.delay];
[id,found] = obj.delayLibrary.find(data);
if ~found
obj.delayLibrary.insert(id,data);
end
obj.blockEvents(index,1)=id;
duration=max(duration,event.delay);
end
end
end
function block = getBlock(obj,index)
%getBlock Return a block of the sequence.
% b=getBlock(obj, index) Return the block specified by the
% index.
%
% The block is created from the sequence data with all
% events and shapes decompressed.
%
% See also setBlock, addBlock
block=struct('rf',{},'gx',{},'gy',{},'gz',{},'adc',{},'delay',{});
block(1).rf=[];
eventInd = obj.blockEvents(index,:);
if eventInd(1)>0
delay.type = 'delay';
delay.delay = obj.delayLibrary.data(eventInd(1)).array;
block.delay = delay;
end
if eventInd(2)>0
rf.type='rf';
libData = obj.rfLibrary.data(eventInd(2)).array;
amplitude = libData(1);
magShape = libData(2);
phaseShape = libData(3);
shapeData = obj.shapeLibrary.data(magShape).array;
compressed.num_samples = shapeData(1);
compressed.data=shapeData(2:end);
mag = mr.decompressShape(compressed);
shapeData = obj.shapeLibrary.data(phaseShape).array;
compressed.num_samples = shapeData(1);
compressed.data=shapeData(2:end);
phase = mr.decompressShape(compressed);
rf.signal = amplitude*mag.*exp(1j*2*pi*phase);
rf.t = (1:length(mag))'*obj.rfRasterTime;
rf.freqOffset = libData(4);
rf.phaseOffset = libData(5);
if length(libData)<6
libData(end+1)=0;
end
rf.deadTime = libData(6);
block.rf = rf;
end
gradChannels = {'gx','gy','gz'};
for i=1:length(gradChannels)
if eventInd(2+i)>0
type = obj.gradLibrary.type(eventInd(2+i));
libData = obj.gradLibrary.data(eventInd(2+i)).array;
if type=='t'
grad.type = 'trap';
else
grad.type = 'grad';
end
grad.channel = gradChannels{i}(2);
if strcmp(grad.type,'grad')
amplitude = libData(1);
shapeId = libData(2);
shapeData = obj.shapeLibrary.data(shapeId).array;
compressed.num_samples = shapeData(1);
compressed.data=shapeData(2:end);
g = mr.decompressShape(compressed);
grad.waveform = amplitude*g;
grad.t = (1:length(g))'*obj.gradRasterTime;
else
grad.amplitude = libData(1);
grad.riseTime = libData(2);
grad.flatTime = libData(3);
grad.fallTime = libData(4);
grad.area = grad.amplitude*(grad.flatTime+grad.riseTime/2+grad.fallTime/2);
grad.flatArea = grad.amplitude*grad.flatTime;
end
block.(gradChannels{i}) = grad;
end
end
if eventInd(6)>0
libData = obj.adcLibrary.data(eventInd(6)).array;
if length(libData)<6
libData(end+1)=0;
end
adc = cell2struct(num2cell(libData),...
{'numSamples','dwell','delay','freqOffset','phaseOffset','deadTime'},2);
adc.type='adc';
block.adc = adc;
end
end
function f=plot(obj,varargin)
%plot Plot the sequence in a new figure.
% plot(seqObj) Plot the sequence
%
% plot(...,'Type',type) Plot the sequence with gradients
% displayed according to type: 'Gradient' or 'Kspace'.
%
% plot(...,'TimeRange',[start stop]) Plot the sequence
% between the times specified by start and stop.
%
% plot(...,'TimeDisp',unit) Display time in:
% 's', 'ms' or 'us'.
%
% f=plot(...) Return the new figure handle.
%
validPlotTypes = {'Gradient','Kspace'};
validTimeUnits = {'s','ms','us'};
persistent parser
if isempty(parser)
parser = inputParser;
parser.FunctionName = 'plot';
parser.addParamValue('type',validPlotTypes{1},...
@(x) any(validatestring(x,validPlotTypes)));
parser.addParamValue('timeRange',[0 inf],@(x)(isnumeric(x) && length(x)==2));
parser.addParamValue('timeDisp',validTimeUnits{1},...
@(x) any(validatestring(x,validTimeUnits)));
end
parse(parser,varargin{:});
opt = parser.Results;
fig=figure;
if nargout>0
f=fig;
end
ax=zeros(1,6);
for i=1:6
ax(i)=subplot(3,2,i);
end
ax=ax([1 3 5 2 4 6]); % Re-order axes
arrayfun(@(x)hold(x,'on'),ax);
arrayfun(@(x)grid(x,'on'),ax);
labels={'ADC','RF mag (Hz)','RF ph (rad)','Gx (kHz/m)','Gy (kHz/m)','Gz (kHz/m)'};
arrayfun(@(x)ylabel(ax(x),labels{x}),1:6);
tFactorList = [1 1e3 1e6];
tFactor = tFactorList(strcmp(opt.timeDisp,validTimeUnits));
xlabel(ax(3),['t (' opt.timeDisp ')']);
xlabel(ax(6),['t (' opt.timeDisp ')']);
t0=0;
for iB=1:size(obj.blockEvents,1)
block = obj.getBlock(iB);
isValid = t0>=opt.timeRange(1) && t0<=opt.timeRange(2);
if isValid
if ~isempty(block.adc)
adc=block.adc;
t=adc.delay + (0:adc.numSamples-1)*adc.dwell;
plot(tFactor*(t0+t),zeros(size(t)),'rx','Parent',ax(1));
end
if ~isempty(block.rf)
rf=block.rf;
t=rf.t;
plot(tFactor*(t0+t),abs(rf.signal),'Parent',ax(2));
plot(tFactor*(t0+t),angle(rf.signal),'Parent',ax(3));
end
gradChannels={'gx','gy','gz'};
for j=1:length(gradChannels)
grad=block.(gradChannels{j});
if ~isempty(block.(gradChannels{j}))
if strcmp(grad.type,'grad')
t=grad.t;
waveform=1e-3*grad.waveform;
else
t=cumsum([0 grad.riseTime grad.flatTime grad.fallTime]);
waveform=1e-3*grad.amplitude*[0 1 1 0];
end
plot(tFactor*(t0+t),waveform,'Parent',ax(3+j));
end
end
end
t0=t0+mr.calcDuration(block);
end
% Set axis limits and zoom properties
dispRange = tFactor*[opt.timeRange(1) min(opt.timeRange(2),t0)];
arrayfun(@(x)xlim(x,dispRange),ax);
linkaxes(ax(:),'x')
h = zoom(fig);
setAxesZoomMotion(h,ax(1),'horizontal');
end
end
methods (Static)
function codes=getBinaryCodes()
%getBinaryCodes Return binary codes for section headers in
% in a binary sequence file.
%
% See also writeBinary
codes.fileHeader = [1 'pulseq' 2];
codes.version = int64(1);
prefix = bitshift(int64(hex2dec('FFFFFFFF')),32);
codes.section.definitions = bitor(prefix,int64(1));
codes.section.blocks = bitor(prefix,int64(2));
codes.section.rf = bitor(prefix,int64(3));
codes.section.gradients = bitor(prefix,int64(4));
codes.section.trapezoids = bitor(prefix,int64(5));
codes.section.adc = bitor(prefix,int64(6));
codes.section.delays = bitor(prefix,int64(7));
codes.section.shapes = bitor(prefix,int64(8));
end
end % Static methods
end % classdef
##### SOURCE END #####
--></body></html>