-
Notifications
You must be signed in to change notification settings - Fork 13
/
PhilipsRawRead.m
2309 lines (1946 loc) · 79.8 KB
/
PhilipsRawRead.m
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
% script for unfolding dual volume data for MRS on PHILIPS
% vincent - UMCU - apr 2014
%
% the function will generate some folders with output in SDAT/SPAR and txt
%
% input:
% (1) folder example: 'D:\DATA\multiband_mrs\20140320_TB'
% it expects a 'raw' folder in this folder where the raw data is stored
% needs for the ref scan: cpx or raw and sin and lab
% for MRS: raw+sin+lab data
%
% (2) reconstructed voxel;
% % - 1 for only the original/single voxel location, typically the right one for dual volume scans
% % - 2 for only the second voxel location: MANUALLY PROVIDE OFFSET FOR SECOND VOXEL (mrs_offset2)
% % - 0 or any other number for 2-voxel recon (default)
%
% (3) editing yes/no
% % - 0 for default MRS data, output is summed over averages
% % - 1 for editing data, output is not summed over averages yet
%
%
% Version 1.0: Loads Philips raw PRIAM data and creates a Gannet
% MRS_struct. (GO 11/01/2016)
%
function MRS_struct = PhilipsRawRead(MRS_struct, rawfile, recon_voxel, editing)
ii = MRS_struct.ii;
% Clear previous instances
signalunf = [];
% REMOVE OR PARSE THE THREE INPUT ARGUMENTS
if(nargin == 0)
disp('ERROR - provide data folder:')
disp(' recon_dual_volume(''D:\data\spectro\'')')
return
end
if(nargin == 1)
%only folder input
recon_voxel = 1; %recon one voxel
editing = 0;
end
if(nargin == 2)
%only folder and voxel input
editing = 0;
end
if MRS_struct.p.PRIAM == 1 % GO 11/01/2016
recon_voxel = 3; % reconstruct 2 voxels % GO 11/01/2016
sense_recon = 1; % do SENSE recon % GO 11/01/2016
else % GO 11/01/2016
recon_voxel = 1; % reconstruct 1 voxel % GO 11/01/2016
sense_recon = 0; % do classic coil combination % GO 11/01/2016
end % GO 11/01/2016
%% Setup paths and filenames
% Get path, filename, extension
rawpath = pwd;
raw_file = [rawpath filesep rawfile];
if ~(exist([rawpath filesep 'mfiles'])==7)
mkdir([rawpath filesep 'mfiles']);
end
% Check whether the input *.raw file exists
if ~(exist(raw_file)==2)
disp('Unable to locate find the specified *.raw file:')
disp(raw_file)
return
end
% Put together the filenames for the reference image and the MRS scan.
clc
disp('=== reference scan ===')
files = dir([rawpath, '/*.cpx']);
if(length(files)>1)
result = input('select ref scan: ');
if isempty(result)
return
end
else
result = 1;
end
reffile = files(result).name;
disp('=== MRS scan ===')
% GO 11/01/2016: commented out batch processing, only one scan at a time for now
% files = dir([rawpath,'/*.raw']);
files.name = rawfile;
if(length(files)>1)
result = input('More than one *.raw file found. Select MRS scans (comma separated): ','s');
else
result = '1';
end
tmp = regexp(result,'([^ ,:]*)','tokens');
array_MRS_files = str2double(cat(2,tmp{:}));
%%spatial separation RE
vox_sep = -input('What is the separation of the voxels in mm? ');
vox_ang = input('What is the angulation about FH? ');
%% some more recon and save options
%take coil info from reference imaging scan, or from water MRS scan
%if from water ref scan, first reconstruct sensitivities of two seperate
% voxels and save to mfiles/sens1 and sens2
% 0 = reference imaging scan
% 1 = water MRS scan
sens_from_ref_scan = 0; % 1 not implemented yet, GO 11/01/2016
%processing parameters
perform_ecc = 1; %eddy current correction
perform_watersubtraction = 1; %subtraction of scaled water scan for sideband reduction
perform_waterremoval_HSVD = 0; %HSVD water removal
save_files_txt = 1; %store txt file (re,im time domain)
save_files_sdat = 1; %store philips SDAT SPAR file
save_images = 1; %store preprocessing plots (histograms, voxel locations)
%% Loop over list of MRS files selected
for MRS_index = 1:length(array_MRS_files)
% Get name of *.raw file to be processed.
MRSfile = files(array_MRS_files(MRS_index)).name;
%% Read reference imaging scan (*.cpx)
% Check whether *.mat files from previous loading are present in the
% mfiles sub-directory.
% If no such files exists, load the *.cpx file first and save the *.mat files.
if(~exist([rawpath filesep 'mfiles' filesep 'ref_scan_sense_coil_img.mat'],'file') || ...
~exist([rawpath filesep 'mfiles' filesep 'ref_scan_volume_coil_img.mat'],'file'))
disp('loading reference scan: ' )
disp([rawpath filesep reffile]);
img = read_cpx([rawpath filesep reffile]);
% If there is a *.raw file for the reference image, extract the
% noise from this scan.
norawfile = 1;
if exist([rawpath filesep 'ref_scan_sense_coil_img.mat'],'file')
norawfile = 0;
[~, info] = read_noise([rawpath filesep reffile(1:end-4) '.raw']);
noise1 = info.FRC_NOISE_DATA(:,:,1);
noise2 = info.FRC_NOISE_DATA(:,:,2);
end
img = permute(img,[5 1 2 4 3]);
% Image dimensions now are:
% 1 - number of coils
% 2-4 - image dimensions x, y, z
% 5 - number of stacks:
% 1st stack contains receiver coil images
% 2nd stack, 1st element is body coil image
ncoils = size(img,1);
dimx = size(img,2);
dimy = size(img,3);
dimz = size(img,4);
img2 = double(img(:,:,:,:,2));
img = double(img(:,:,:,:,1));
img = img/max(abs(img(:)));
img2 = img2/max(abs(img2(:)));
% Extract noise levels from outermost slice.
if norawfile
disp('no raw file, getting noise from edge of image')
noise1 = squeeze(img(:,1:30,:,1));
noise1 = reshape(noise1,[ncoils size(noise1,2)*size(noise1,3)]);
noise2 = squeeze(img2(:,1:30,:,1));
noise2 = reshape(noise2,[ncoils size(noise2,2)*size(noise2,3)]);
end
save([rawpath filesep 'mfiles' filesep 'ref_scan_sense_coil_img.mat'],'img','ncoils','dimx','dimy','dimz','noise1','noise2');
img = img2;
clear img2
save([rawpath filesep 'mfiles' filesep 'ref_scan_volume_coil_img.mat'],'img','ncoils','dimx','dimy','dimz','noise1','noise2');
clear img1
disp('done loading ref scan')
end
%% Load the previously established reference image and plot the receiver and volume coil noise
load([rawpath filesep 'mfiles' filesep 'ref_scan_sense_coil_img.mat'])
figure(1)
subplot(2,2,1)
bar(std(noise1'))
title(['noise ' num2str(ncoils) 'ch receiver']);
subplot(2,2,2)
bar(std(noise2'))
title(['noise volume coil (ch1)']); %what is in the other 31 channels?
subplot(2,1,2)
imagesc(real(noise1*noise1'))
daspect([1 1 1])
%% Extract voxel size and orientation data from *.sin files.
% Get dimensions from reference image scan
refsc_voxel_size = get_sin_voxel_size([rawpath filesep reffile(1:end-4) '.sin']);
refsc_orientation = get_sin_orientation([rawpath filesep reffile(1:end-4) '.sin']);
% ap_rl_fh
refsc_offset = get_sin_voxel_offset([rawpath filesep reffile(1:end-4) '.sin']);
% Reorder: FH, AP, LR
refsc_offset1 = [refsc_offset(3); refsc_offset(1); refsc_offset(2)];
% ap_rl_fh
mrs_offset = get_sin_voxel_offset([rawpath filesep MRSfile(1:end-4) '.sin']);
mrs_voxelsize = get_sin_voxel_size([rawpath filesep MRSfile(1:end-4) '.sin']);
disp('NOT CHECKING ON R/P direction')
switch refsc_orientation
case 1 %saggital
%voxel offsets ref scan: FH AP LR
img = flip(img,4);
mrs_offset1 = [ mrs_offset(3); mrs_offset(1); mrs_offset(2)];
disp('MRS offset 2 for 20140307_vol_KK_hippocampus_7T')
mrs_offset2 = [ mrs_offset(3) + vox_sep; mrs_offset(1); mrs_offset(2)];
case 2 %coronal
img = permute(img,[1 2 4 3]);
dimx = size(img,2);
dimy = size(img,3);
dimz = size(img,4);
%final order: FH, AP, LR
refsc_voxel_size = [refsc_voxel_size(1); refsc_voxel_size(3); refsc_voxel_size(2)];
%final order: FH, AP, LR
disp('Offset Voxel 1:')
mrs_offset1 = [ mrs_offset(3); mrs_offset(1); mrs_offset(2)]
disp('Offset Voxel 2:')
mrs_offset2 = [ mrs_offset(3); mrs_offset(1)+vox_sep*sin(vox_ang*pi/180); mrs_offset(2) - vox_sep*cos(vox_ang*pi/180)]
case 3
disp('ORIENTATION NOT IMPLEMENTED yet')
return
end
mrs_offset1 = mrs_offset1 - refsc_offset1;
mrs_offset2 = mrs_offset2 - refsc_offset1;
lb1 = (mrs_offset1 - mrs_voxelsize/2) ./refsc_voxel_size;
ub1 = (mrs_offset1 + mrs_voxelsize/2) ./refsc_voxel_size;
xrange = round([dimx/2 + 0.5 + lb1(1):dimx/2 + 0.5 + ub1(1)]); %FH
yrange = round([dimy/2 + 0.5 + lb1(2):dimy/2 + 0.5 + ub1(2)]); %AP
zrange = round([dimz/2 + 0.5 + lb1(3):dimz/2 + 0.5 + ub1(3)]); %LR
% second voxel: fill in correct values!
lb2 = (mrs_offset2 - mrs_voxelsize/2) ./refsc_voxel_size;
ub2 = (mrs_offset2 + mrs_voxelsize/2) ./refsc_voxel_size;
xrange2 = round([dimx/2 + 0.5 + lb2(1):dimx/2 + 0.5 + ub2(1)]); %FH
yrange2 = round([dimy/2 + 0.5 + lb2(2):dimy/2 + 0.5 + ub2(2)]); %AP
zrange2 = round([dimz/2 + 0.5 + lb2(3):dimz/2 + 0.5 + ub2(3)]); %LR
%% Plot an overlay of the voxel on the body coil image
SOS = squeeze(sqrt(sum(abs(img).^2,1)));
gray2 = gray;
gray2(64,:) = [1 0 0];
gray2(1,:) = [0 1 0];
figure(2)
clf
SOSdisplay = SOS;
SOSdisplay(xrange,yrange,zrange) = 2;
subplot(2,3,1)
imagesc(squeeze(squeeze(SOSdisplay(round(mean(xrange)),:,:))),[-0.2 1.3])
title(' TRA A/L')
axis off;
axis square;
subplot(2,3,2)
imagesc(flipud(squeeze(SOSdisplay(:,round(mean(yrange)),:))),[-0.2 1.3])
title(' SAG H/L')
axis off;
axis square;
subplot(2,3,3)
imagesc(flipud(squeeze(SOSdisplay(:,:,round(mean(zrange))))),[-0.2 1.3])
title(' COR H/P')
axis off;
axis square;
SOSdisplay = SOS;
SOSdisplay(xrange2,yrange2,zrange2) =-2;
subplot(2,3,4)
imagesc(squeeze(SOSdisplay(round(mean(xrange2)),:,:)),[-0.2 1.3])
title(' TRA A/L')
axis off;
axis square;
subplot(2,3,5)
imagesc(flipud(squeeze(SOSdisplay(:,round(mean(yrange2)),:))),[-0.2 1.3])
title(' SAG H/L')
axis off;
axis square;
subplot(2,3,6)
imagesc(flipud(squeeze(SOSdisplay(:,:,round(mean(zrange2))))),[-0.2 1.3])
title(' COR H/P')
axis off;
axis square;
colormap(gray2)
mask = (SOS/max(SOS(:)))>0.04;
save([rawpath filesep 'mfiles' filesep 'mask.mat'],'mask');
save([rawpath filesep 'mfiles' filesep 'SOS_sense'],'SOS');
%% generate sensitivity maps
sensitivities = zeros(ncoils,dimx,dimy,dimz);
for c=1:ncoils
sensitivities(c,:,:,:) = mask.*squeeze(img(c,:,:,:))./SOS;
end
%% load MRS data
if ~exist([rawpath filesep 'mfiles' filesep MRSfile(1:end-4) '.mat'],'file')
[FID, infow1] = loadLabRaw([rawpath filesep MRSfile]);
ncoils = double(infow1.dims.nCoils);
npoints = double(infow1.dims.nKx);
nmixes = double(infow1.dims.nMixes); % KLC Change nMixes to nRows
nmeasurements = double(infow1.dims.nMeasurements);
nrows = infow1.dims.nRows;
naveragesw1 = nmeasurements*nrows;
FID = squeeze(FID);
% First dimension: coils (32)
% Second dimension: data points
% Third dimension: rows
% Fourth dimension: Measurements (Water-suppressed ON (1) and OFF (2))
% Fifth dimension: Mixes (ON and OFF spectra)
FID = reshape(double(FID),ncoils,npoints,nrows,nmixes,nmeasurements);
FID = permute(FID,[1 2 3 5 4]);
FID = reshape(FID,ncoils,npoints,nrows*nmeasurements,nmixes);
FID = permute(FID,[1 2 4 3]);
figure(14)
clf
plot(real(FID(:,1:500,2,1))'); % KLC changed 2 to one in second to last dimension
ylim([-100 100])
% nshift = input('number of zeros: ');
nshift = 0;
% nshift = 32;
disp(['SHIFTING: ' num2str(nshift) ' points'])
FID = circshift(FID,[0 -nshift 0 0]);
nwaterfiles = sum(squeeze(sum(sum(abs(FID(:,:,2,:)),1),2))~=0);
sw = 5e3;
% downsampling
tic
[noversamples, npoints]=get_sin_samples([rawpath filesep MRSfile(1:end-4) '.sin']);
% FIR filter
clear C
C(1)= -2.74622659936243e-2;
C(2)= -3.16256052372452e-2;
C(3)= 6.00081666037503e-3;
C(4)= 9.10571641138698e-2;
C(5)= 1.94603313644247e-1;
C(6)= 2.66010793957549e-1;
C(7)= 2.66010793957549e-1;
C(8)= 1.94603313644247e-1;
C(9)= 9.10571641138698e-2;
C(10)= 6.00081666037503e-3;
C(11)= -3.16256052372452e-2;
C(12)= -2.74622659936243e-2;
N_tabs = length(C);
N_delay = floor(N_tabs/2);
R_fir = 4;
R_hdf = 1. * noversamples / npoints / 4;
% naveragesw1=nrows*nmeasurements;
% two step undersampling, first R_hdf undersampling
H_ref_out = squeeze(sum(reshape(FID,[ncoils,R_hdf,noversamples/R_hdf nmixes naveragesw1]),2));
% second, FIR filter with coefficients from C
S_ref_out = zeros(ncoils,npoints,nmixes,naveragesw1);
n = 0:npoints-1;
n1 = n*R_fir+1+N_delay;
nmax = noversamples/R_hdf-1;
for k=1:N_tabs
n2 = n1-k;
idx = find(n2>=0 & n2<nmax);
S_ref_out(:,n(idx)+1,:,:) = S_ref_out(:,n(idx)+1,:,:) + C(k)*H_ref_out(:,n2(idx)+1,:,:);
end
FID = S_ref_out;
disp(['downsampling: ' num2str(toc) ' sec'])
save([rawpath filesep 'mfiles' filesep MRSfile(1:end-4) '.mat'],'FID','sw','naveragesw1','nwaterfiles','npoints','ncoils');
else
load([rawpath filesep 'mfiles' filesep MRSfile(1:end-4) '.mat'])
end
%% Calculate MRS sensitivities from first 20 points of water signal (alternative to SENSE reference image)
% sens1 = mean(FID(:,1:20,2),2);
% save([folder filesep 'mfiles' filesep 'sens1.mat'],'sens1');
% %% save MRS sensitivities
% sens2 = mean(FID(:,1:20,2),2);
% save([folder filesep 'mfiles' filesep 'sens2.mat'],'sens2');
%% generate SENSE matrix
sens1 = squeeze(mean(mean(mean(sensitivities(:,xrange,yrange,zrange),2),3),4));
sens2 = squeeze(mean(mean(mean(sensitivities(:,xrange2,yrange2,zrange2),2),3),4));
%get sensitivities
if ~sens_from_ref_scan
if exist([rawpath filesep 'mfiles' filesep 'sens1.mat'],'file')
load([rawpath filesep 'mfiles' filesep 'sens1.mat'],'sens1');
else
disp(' !!! NO SENS1 MATRIX FOUND !!!')
disp(' !!! using ref-scan !!!')
end
if exist([rawpath filesep 'mfiles' filesep 'sens2.mat'],'file')
load([rawpath filesep 'mfiles' filesep 'sens2.mat'],'sens2');
else
disp(' !!! NO SENS2 MATRIX FOUND !!!')
disp(' !!! using ref-scan !!!')
end
ix = round(mean(xrange));
iy = round(mean(yrange));
iz = round(mean(zrange));
ix2 = round(mean(xrange2));
iy2 = round(mean(yrange2));
iz2 = round(mean(zrange2));
signal = sens1;
signal = signal./sqrt(sum(abs(signal).^2));
tmpimage = squeeze(sum(bsxfun(@times, sensitivities, conj(signal)),1));
disp( ['orig. voxel positions; x1=' num2str(ix) '; y1=' num2str(iy) '; z1=' num2str(iz) ';'])
[max_val, position] = max(abs(tmpimage(:)));
[tx,ty,tz] = ind2sub(size(tmpimage),position);
disp( ['opt. voxel positions; x1=' num2str(tx) '; y1=' num2str(ty) '; z1=' num2str(tz) ';'])
disp(['similarity: ' num2str(max_val) ' vs ' num2str(abs(tmpimage(ix,iy,iz)))])
figure(17)
clf
jet2 = jet;
jet2(1,:) = [0;0;0];
colormap(jet2)
minpl = 0;
maxpl = 1;
subplot(2,3,1)
imagesc(abs(squeeze(tmpimage(ix,:,:))),[minpl maxpl])
line([0 100],[iy iy],'Color',[1 1 1])
line([iz iz],[0 100],'Color',[1 1 1])
ylabel('y');ylabel('FH')
xlabel('z');xlabel('LR')
axis square;
title('MPR')
subplot(2,3,2)
imagesc(abs(squeeze(tmpimage(:,iy,:))),[minpl maxpl])
line([0 100],[ix ix],'Color',[1 1 1])
line([iz iz],[0 100],'Color',[1 1 1])
ylabel('x');ylabel('AP')
xlabel('z');xlabel('LR')
axis square;
set(gca,'YDir','normal');
title('MPR')
subplot(2,3,3)
imagesc(abs(squeeze(tmpimage(:,:,iz))),[minpl maxpl])
line([0 100],[ix ix],'Color',[1 1 1])
line([iy iy],[0 100],'Color',[1 1 1])
ylabel('x');ylabel('AP')
xlabel('y');xlabel('FH')
axis square;
set(gca,'YDir','normal');
title('MPR')
signal = sens2;
signal = signal./sqrt(sum(abs(signal).^2));
tmpimage = squeeze(sum(bsxfun(@times, sensitivities, conj(signal)),1));
disp( ['orig. voxel positions; x1=' num2str(ix2) '; y1=' num2str(iy2) '; z1=' num2str(iz2) ';'])
[max_val, position] = max(abs(tmpimage(:)));
[tx,ty,tz] = ind2sub(size(tmpimage),position);
disp( ['opt. voxel positions; x2=' num2str(tx) '; y2=' num2str(ty) '; z2=' num2str(tz) ';'])
disp(['similarity: ' num2str(max_val) ' vs ' num2str(abs(tmpimage(ix2,iy2,iz2)))])
disp(' ')
subplot(2,3,4)
imagesc(abs(squeeze(tmpimage(ix2,:,:))),[minpl maxpl])
line([0 100],[iy2 iy2],'Color',[1 1 1])
line([iz2 iz2],[0 100],'Color',[1 1 1])
axis square;
ylabel('y')
xlabel('z')
title('MPR')
subplot(2,3,5)
imagesc(abs(squeeze(tmpimage(:,iy2,:))),[minpl maxpl])
line([0 100],[ix2 ix2],'Color',[1 1 1])
line([iz2 iz2],[0 100],'Color',[1 1 1])
axis square;
ylabel('x')
xlabel('z')
set(gca,'YDir','normal');
title('MPR')
subplot(2,3,6)
imagesc(abs(squeeze(tmpimage(:,:,iz2))),[minpl maxpl])
line([0 100],[ix2 ix2],'Color',[1 1 1])
line([iy2 iy2],[0 100],'Color',[1 1 1])
axis square;
ylabel('x')
xlabel('y')
set(gca,'YDir','normal');
title('MPR')
end
%normalize
sens1 = sens1./squeeze(sqrt(sum(abs(sens1).^2,1)));
sens2 = sens2./squeeze(sqrt(sum(abs(sens2).^2,1)));
% form S matrix
if recon_voxel == 1
S = [sens1];
elseif recon_voxel == 2
S = [ sens2];
else
S = [ sens1 ...
sens2 ...
];
end
PSY = noise1*noise1';
U = inv(S'*inv(PSY)*S)*S'*inv(PSY);
ga = inv(S'*inv(PSY)*S);
gb = S'*inv(PSY)*S;
g = sqrt(ga.*gb);
disp(['gfactors: ' num2str(diag(real(g))')])
%% perform SENSE unfolding
% m=1 %1 for metab, 2 for water ref
disp('sense unfolding...');
% clear signalunf signalres
for m=1:2
for a =1:naveragesw1
signal = FID(:,:,m,a);
signalunf(:,:,m,a) = U*signal;
signalres(:,:,m,a) = signal - S*signalunf(:,:,m);
end
end
nspec = size(signalunf,1);
%% water subtraction
searchwindow = [-200 200]; %Hz
searchwindow = (searchwindow/sw+0.5)*npoints;
waterfid = mean(signalunf(:,:,2,1:nwaterfiles),4);
if perform_watersubtraction
% waterremoval - subtract scaled water scan
for t=1:nspec
%
nruns = 0;
apo = 5;
t1 = [0:npoints-1]/sw;
filt = exp(-t1*apo);
while(nruns < 5)
nruns = nruns+1;
specw = fftshift(fft(waterfid(t,:,:,:).*filt,[],2),2);
specm = fftshift(fft(mean(signalunf(t,:,1,:),4).*filt,[],2),2);
[a b] = max(abs(specw));
[a2 b2] = max(abs(specm));
corr = specm(b2)./specw(b);
% figure(7)
% clf
% plot([1:2048],circshift(real(specw*corr),[0 b2-b]),[1:2048],real(mean(specm,4)))
if(b2>max(searchwindow) || b2<min(searchwindow))
% disp([num2str(nruns) ' out of range, stopping'])
% pause(1)
continue
else
% disp([num2str(nruns) ' subtracting'])
% pause(2)
end
%
for a = 1:naveragesw1
signalunf(t,:,1,a) = signalunf(t,:,1,a) - corr.*ifft(ifftshift(circshift(specw,[0 b2-b]),2),[],2).*filt;
end
end
end
end
%% eddy current correction
if perform_ecc
% w_unf = mean(signalunf(:,:,2,1:nwaterfiles),4);
w_unf = waterfid;
wcorr = abs(w_unf)./w_unf;
wcorr(isnan(wcorr)) = 1;
for a=1:naveragesw1
signalunf(:,:,1,a) = signalunf(:,:,1,a).*wcorr;
end
for a=1:nwaterfiles
signalunf(:,:,2,a) = signalunf(:,:,2,a).*wcorr;
end
end
%% water removal
if perform_waterremoval_HSVD
% waterremoval
for t=1:nspec
for a=1:naveragesw1
signalunf(t,:,1,a) = waterremovalSVD(signalunf(t,:,1,a).', sw/1000, 32, -0.12, 0.12, 0).';
end
end
end
%% save spectra to disk
save([rawpath filesep 'mfiles' filesep MRSfile(1:end-4) '.mat'],'signalunf','-append'); % GO 02/18/16 save signal output to mat file (easier for GannetLoad to process)
if ~(exist([rawpath filesep 'rec_spectra_txt'])==7)
mkdir([rawpath filesep 'rec_spectra_txt']);
end
if ~(exist([rawpath filesep 'rec_SDATSPAR'])==7)
mkdir([rawpath filesep 'rec_SDATSPAR']);
end
for m=1:2
if m==2 ;%water
saveaverages = nwaterfiles;
else %metabolites
saveaverages = naveragesw1;
end
for s=1:nspec
% for a =1:naveragesw1
%water or metabolite file
if(m==2)
watermetstr = 'ref';
else
watermetstr = 'act';
end
%voxel number 1 for original, 2 for end one or no number for only one
if (recon_voxel == 2) || (recon_voxel ==1)
savefile = [MRSfile(1:end-4) '_unf_' watermetstr]; %reconstructing only 1 voxel
else
savefile = [MRSfile(1:end-4) '_unf_' watermetstr '_' num2str(s)];
end
signalsave = signalunf(s,:,m,1:saveaverages);
specsave = fftshift(fft(signalsave,[],2),2);
if(m==1)
if editing
NAA = max(abs(mean(specsave(1,550:680,:,:),4)));
else
NAA = max(abs(mean(specsave(1,550:680,:,1:2:end),4)));
end
disp(['NAA peak intensity: ' num2str(NAA)])
tmp = reshape(mean(signalsave,4),256,npoints/256);
tmp = std(tmp,[],1);
noise = min(real(tmp(:)));
disp(['noise (time domain): ' num2str(noise)])
noiserec = U*noise1;
disp(['noise (FRCnoise): ' num2str(std(noiserec(s,:)))])
else
figure(5)
water = max(abs(sum(specsave,4)));
f = polyfit([2:15],abs(sum(signalsave(1,2:15,1,:),4)),1);
plot([1:15],abs(sum(signalsave(1,1:15,1,:),4)),[1:15],polyval(f,[1:15]));
water = polyval(f,1);
disp(['water peak intensity (t): ' num2str(water)])
end
if ~editing %just store the mean
saveaverages = 1;
signalsave = mean(signalsave,4);
specsave = mean(specsave,4);
end
%save txt file
if save_files_txt
for n=1:saveaverages
% if saveaverages ~= 1
savefile1 = [savefile '_' num2str(n,'%03d')];
% else
% savefile1 = savefile;
% end
disp(['saving: ' savefile1 '.txt'])
fid = fopen([rawpath filesep 'rec_spectra_txt' filesep savefile1 '.txt'],'w');
if fid == -1
disp(['Cannot open file: ' savefile1])
continue
end
for p=1:npoints
fprintf(fid,'%f \t %f\r\n',real(signalsave(1,p,1,n)),imag(signalsave(1,p,1,n)));
end
fclose(fid);
end
end
if save_files_sdat
%save sdatspar
fname_p = 'example.SPAR'; %check if this is in the right location
fname_out = [rawpath filesep 'rec_SDATSPAR' filesep savefile '.sdat'];
disp(['saving: ' fname_out])
fname_out_spar = [rawpath filesep 'rec_SDATSPAR' filesep savefile '.spar'];
write_sdat_spar(signalsave, fname_p, fname_out, fname_out_spar, saveaverages, npoints)
end
% end
end
end
%% plot unfolded voxels
% if editing
% ncols = 3;
% else
ncols = 2;
% end
disp(['naverages = ' num2str(naveragesw1)])
disp(['nwaterfiles = ' num2str(nwaterfiles)])
% averages
m_unfdisp = signalunf(:,:,1,:);
w_unfdisp = signalunf(:,:,2,1:nwaterfiles);
figure(4);
subplot(2,1,1)
imagesc(abs(squeeze(m_unfdisp(1,:,:,:))))
subplot(2,1,2)
imagesc(abs(squeeze(w_unfdisp(1,:,:,:))))
m_unfdisp = mean(m_unfdisp(:,:,:,:),4);
w_unfdisp = mean(w_unfdisp(:,:,:,:),4);
% noise = std(signalunfdisp(:,1000:1500,1),[],2).';
% disp(['noise = ' num2str(noise)])
% for t=1:nspec
% signalunfdisp(t,:,:) = signalunfdisp(t,:,:)./noise(t);
% end
% for t=1:nspec
% signalunfdisp(t,:,1) = signalunfdisp(t,:,1)/max(abs(signalunfdisp(t,:,1)));
% end
zff = 2;
apo = 1;
t = [0:npoints-1]/sw;
fs = 7;
ppm = ([0:npoints*zff-1]/(npoints*zff-1)-0.5)*sw / (298/7*fs)+4.68;
filt = exp(-t*apo);
filt = repmat(filt,[nspec 1]);
% specunfodd = fftshift(fft(signalunfdispodd.*filt,[],2),2);
% specunfeven = fftshift(fft(signalunfdispeven.*filt,[],2),2);
m_specunf = fftshift(fft(m_unfdisp.*filt,[npoints*zff],2),2);
w_specunf = fftshift(fft(w_unfdisp.*filt,[npoints*zff],2),2);
% angle(signalunfdisp(1,1))/pi*180
ph(1) = 0;
ph(2) = 0;
figure(3)
clf
xmin = 4;
% xmax = 5.36;
xmax = 5.5;
% plot water
% axis1 = [xmin xmax 1.1*min([real(w_specunf(:)); imag(w_specunf(:))]) 1.1*max([real(w_specunf(:)); imag(w_specunf(:))])];
axis1 = [xmin xmax 1.1*min(real(w_specunf(:))) 1.1*max(real(w_specunf(:)))];
% axis1 = [xmin xmax -1.5e5 4e5];
for t=1:nspec
subplot(ncols,nspec,t)
% plot(ppm,imag(exp(-1i*ph(t))*w_specunf(t,:)),'g')
% hold on
plot(ppm,real(exp(-1i*ph(t))*w_specunf(t,:)))
% hold off
set(gca,'XDir','reverse');
axis(axis1);
title(['water spectrum, voxel: ' num2str(t)])
% disp(['water signal intensity: ' num2str(max(abs(w_specunf(t,:))))])
end
xmin = 0;
xmax = 4.2;
% plot metabolites
axis1 = [xmin xmax 1.1*min(real(m_specunf(:))) 1.1*max(real(m_specunf(:)))];
for t=1:nspec
subplot(ncols,nspec,t+nspec)
plot(ppm,real(exp(-1i*ph(t))*m_specunf(t,:)))
set(gca,'XDir','reverse');
axis(axis1)
title(['metabolite spectrum, voxel: ' num2str(t)])
end
%% store images
if save_images
if ~exist([rawpath filesep 'images'],'dir')
mkdir([rawpath filesep 'images']);
end
% store figures
filename = [rawpath filesep 'images' filesep MRSfile(1:end-4)];
figure(1)
file = [filename '_noise'];
print('-vector','-r300','-dpng',file);
print('-vector','-depsc2',file);
figure(2)
file = [filename '_location'];
print('-vector','-r300','-dpng',file);
print('-dpsc2', '-noui', '-vector', file);
print('-vector','-depsc2',file);
figure(3)
if(recon_voxel == 2) || (recon_voxel ==1)
file = filename;
else
file = [filename '_unfolded'];
end
print('-vector','-r300','-dpng',file);
print('-vector','-depsc2',file);
end
end
disp(' ')
disp('recon_dual_volume: finished')
% FIDs may be in the wrong order depending on NMixes, correct that here for now, fix later %
% GO 11/03/2016
signalunf(:,:,:,2:2:end) = -signalunf(:,:,:,2:2:end);
a = signalunf(:,:,:,1:end/2);
b = signalunf(:,:,:,1+end/2:end);
c = zeros(size(signalunf));
c(:,:,:,1:2:end) = a;
c(:,:,:,2:2:end) = b;
signalunf = c;
clear a b c;
a = zeros(size(signalunf));
a(:,:,:,1:4:end) = signalunf(:,:,:,1:4:end);
a(:,:,:,2:4:end) = signalunf(:,:,:,3:4:end);
a(:,:,:,3:4:end) = signalunf(:,:,:,2:4:end);
a(:,:,:,4:4:end) = signalunf(:,:,:,4:4:end);
signalunf = a;
clear a;
% Save all relevant data/information to MRS_struct % GO 11/01/2016
MRS_struct.p.NVoxels = size(signalunf,1);
MRS_struct.p.npoints(ii) = npoints; % GO 11/01/2016
MRS_struct.p.nrows(ii) = size(signalunf,4); % GO 11/01/2016
MRS_struct.p.ncoils = ncoils; % GO 11/01/2016
MRS_struct.p.Navg(ii) = size(signalunf,4); % GO 11/01/2016
MRS_struct.p.Nwateravg(ii) = nwaterfiles; % GO 11/01/2016
MRS_struct.p.voxdim(ii,:) = [mrs_voxelsize(1) mrs_voxelsize(2) mrs_voxelsize(3)]; %AP, RL, FH - preliminary, TEST! % GO 11/01/2016
MRS_struct.p.voxoff(ii,:) = [mrs_offset(1) mrs_offset(2) mrs_offset(3)]; %AP, RL, FH - preliminary, TEST! % GO 11/01/2016
MRS_struct.p.voxang(ii,:) = vox_ang; % voxel angulation (1 dimension only so far) % GO 11/01/2016
MRS_struct.p.TR(ii) = get_sin_TR([rawpath filesep MRSfile(1:end-4) '.sin']);% GO 11/01/2016
MRS_struct.p.TE(ii) = get_sin_TE([rawpath filesep MRSfile(1:end-4) '.sin']);% GO 11/01/2016
MRS_struct.p.LarmorFreq(ii) = 127; % Need to get that from somewhere! GO 11/01/2016
MRS_struct.p.sw(ii) = 2e3; % Need to parse that from somewhere! GO 11/01/2016
MRS_struct.multivoxel.sensitivities = sensitivities; % GO 11/01/2016
MRS_struct.multivoxel.voxsep = vox_sep; % voxel separation (1 dimension only so far) % GO 11/01/2016
% save all unfolded signals to MRS_struct
MRS_struct.multivoxel.allsignals = signalunf; % GO 11/01/2016
% work up water data to plug back into GannetLoad % GO 11/02/2016
MRS_struct.fids.data_water = conj(squeeze(MRS_struct.multivoxel.allsignals(:,:,2,1:MRS_struct.p.Nwateravg))); % select non-zero water spectra % GO 11/02/2016
MRS_struct.out.phase_water = conj(MRS_struct.fids.data_water(1))./abs(MRS_struct.fids.data_water(1));
save([pwd filesep 'MRS_struct.mat'],'MRS_struct')
end
%% END OF RECONSTRUCTION CODE
%% ADDITIONAL FUNCTIONS FOR DATA PROCESSING
%%display file types
function a = display_file_names(folder,filetype)
if ~(exist([folder filesep 'mfiles'])==7)
mkdir([folder filesep 'mfiles']);
end
a = dir([folder filesep 'raw\*' filetype]);
for n=1:length(a)
disp(['(' num2str(n) ') file = ''' a(n).name(1:end-4) ''';'])
end
end
%%read sin file voxel size
function [voxel_sizes]=get_sin_voxel_size(filename)
toks = regexpi(filename,'^(.*?)(\.sin|\.lab|\.raw)?$','tokens');
prefix = toks{1}{1};
sinfilename = sprintf('%s.sin',prefix);
sinfid=fopen(sinfilename);
if(sinfid == -1)
disp(['file not found: ' sinfilename])
voxel_sizes = -1;
return
end
while ~feof(sinfid)
line=fgetl(sinfid);
if(strfind(line,'voxel_sizes') ~= 0)
if line(12:22)=='voxel_sizes'
voxel_sizes = sscanf(line, '%*s %*s %*s %*s %*s %f %f %f');
end
end
end
fclose(sinfid);
end
%%read sin file voxel offset
function [voxel_offset]=get_sin_voxel_offset(filename)
toks = regexpi(filename,'^(.*?)(\.sin|\.lab|\.raw)?$','tokens');
prefix = toks{1}{1};
sinfilename = sprintf('%s.sin',prefix);
sinfid=fopen(sinfilename);
if(sinfid == -1)
disp(['file not found: ' sinfilename])
voxel_sizes = -1;
return
end
while ~feof(sinfid)
line=fgetl(sinfid);
if(strfind(line,'loc_ap_rl_fh_offcentres') ~= 0)
if line(12:34)=='loc_ap_rl_fh_offcentres'
voxel_offset = sscanf(line, '%*s %*s %*s %*s %*s %f %f %f');
end
end
% if(strfind(line,'loc_ap_rl_fh_offcentr_incrs') ~= 0)
% if line(12:38)=='loc_ap_rl_fh_offcentr_incrs'
% voxel_offset = sscanf(line, '%*s %*s %*s %*s %*s %f %f %f');
% end
% end
end
fclose(sinfid);
end
%%read sin file voxel offset