-
Notifications
You must be signed in to change notification settings - Fork 159
/
bst_memory.m
3552 lines (3348 loc) · 152 KB
/
bst_memory.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
function [ varargout ] = bst_memory( varargin )
% BST_MEMORY: Manages all loaded data (GlobalData variable).
%
% USAGE: iDS = bst_memory('LoadDataFile', DataFile, isReloadForced)
% bst_memory('LoadRecordingsMatrix', iDS)
% [iDS, iResult] = bst_memory('LoadResultsFile', ResultsFile)
% bst_memory('LoadResultsMatrix', iDS, iResult)
% [iDS, iResult] = bst_memory('LoadResultsFileFull', ResultsFile)
% [iDS, iDipole] = bst_memory('LoadDipolesFile', DipolesFile)
% [iDS, iTimef] = bst_memory('LoadTimefreqFile', TimefreqFile)
% [sMri, iMri] = bst_memory('LoadMri', iDS, MriFile);
% [sSurf, iSurf] = bst_memory('LoadSurface', iSubject, SurfaceType)
% [sSurf, iSurf] = bst_memory('LoadSurface', MriFile, SurfaceType)
% [sSurf, iSurf] = bst_memory('LoadSurface', SurfaceFile)
% [sFib,iFib] = bst_memory('LoadFiber', FibFile)
% [sFib,iFib] = bst_memory('LoadFiber', iSubject)
%
% DataValues = bst_memory('GetRecordingsValues', iDS, iChannel, iTime)
% ResultsValues = bst_memory('GetResultsValues', iDS, iRes, iVertices, TimeValues)
% DipolesValues = bst_memory('GetDipolesValues', iDS, iDipoles, TimeValues)
% TimefreqValues = bst_memory('GetTimefreqValues', iDS, iTimefreq, TimeValues)
% minmax = bst_memory('GetResultsMaximum', iDS, iTimefreq)
% minmax = bst_memory('GetTimefreqMaximum', iDS, iTimefreq, Function)
% iDS = bst_memory('GetDataSetData', DataFile, isStatic)
% iDS = bst_memory('GetDataSetData', DataFile)
% iDS = bst_memory('GetDataSetStudyNoData',StudyFile)
% iDS = bst_memory('GetDataSetStudy', StudyFile)
% iDS = bst_memory('GetDataSetChannel', ChannelFile)
% iDS = bst_memory('GetDataSetSubject', SubjectFile, createSubject)
% iDS = bst_memory('GetDataSetEmpty')
% [iDS, iResult] = bst_memory('GetDataSetResult', ResultsFile)
% [iDS, iResult] = bst_memory('GetDataSetDipoles', DipolesFile)
% [iDS, iTimefr] = bst_memory('GetDataSetTimefreq', TimefreqFile)
% iResult = bst_memory('GetResultInDataSet', iDS, ResultsFile)
% iResult = bst_memory('GetDipolesInDataSet', iDS, DipolesFile)
% iTimefreq = bst_memory('GetTimefreqInDataSet', iDS, TimefreqFile)
% iDS = bst_memory('GetRawDataSet');
% [TimeVector, iTime] = bst_memory('GetTimeVector', ...)
% isOk = bst_memory('CheckTimeWindows')
% isOk = bst_memory('CheckFrequencies')
% bst_memory('ReloadAllDataSets')
% bst_memory('ReloadStatDataSets')
% bst_memory('UnloadAll', OPTIONS)
% bst_memory('UnloadDataSets', iDS)
% bst_memory('UnloadDataSetResult, ResultsFile)
% bst_memory('UnloadDataSetResult, iDS, iResult)
% bst_memory('UnloadSubject', SubjectFile)
% bst_memory('UnloadMri', MriFile)
% bst_memory('UnloadSurface', SurfaceFile, isCloseFig=0)
% bst_memory('UnloadSurface')
% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2008-2023
% Martin Cousineau, 2019
eval(macro_method);
end
%% =========================================================================================
% ===== ANATOMY ===========================================================================
% =========================================================================================
%% ===== LOAD MRI =====
% USAGE: [sMri,iMri] = bst_memory('LoadMri', MriFile)
% [sMri,iMri] = bst_memory('LoadMri', iSubject)
function [sMri,iMri] = LoadMri(MriFile)
global GlobalData;
% ===== PARSE INPUTS =====
% If argument is a subject indice
if isnumeric(MriFile)
% Get subject
iSubject = MriFile;
sSubject = bst_get('Subject', iSubject);
% If subject does not have a MRI
if isempty(sSubject.Anatomy) || isempty(sSubject.iAnatomy)
error('No MRI avaialable for subject "%s".', sSubject.Name);
end
% Get MRI file
MriFile = sSubject.Anatomy(sSubject.iAnatomy).FileName;
else
sSubject = bst_get('MriFile', MriFile);
end
% ===== CHECK IF LOADED =====
% Use short file name
MriFile = file_short(MriFile);
% Check if surface is already loaded
iMri = find(file_compare({GlobalData.Mri.FileName}, MriFile));
% If MRI is not loaded yet: load it
if isempty(iMri)
% Unload the unused Anatomies (surfaces + MRIs)
UnloadAll('KeepSurface');
% Create default structure
sMri = db_template('LoadedMri');
% Load MRI matrix
MriMat = in_mri_bst(MriFile);
% Build MRI structure
for field = fieldnames(sMri)'
if isfield(MriMat, field{1})
sMri.(field{1}) = MriMat.(field{1});
end
end
% Set filename
sMri.FileName = file_win2unix(MriFile);
% === MULTIPLE VOLUMES ===
n4 = size(sMri.Cube,4);
if (n4 > 1)
% If there is another volume with the same 4th dimension loaded: keep as it is
if isequal(GlobalData.UserTimeWindow.Time, [1, n4])
% Keep loading
% If there is no time data loaded: load as time-varying volume
elseif isempty(GlobalData.UserTimeWindow.Time)
% Create Measures structure
Measures = db_template('Measures');
Measures.Time = [1, n4];
Measures.SamplingRate = 1;
Measures.NumberOfSamples = n4;
Measures.DataType = 'volume';
Measures.DisplayUnits = 'vol';
% Get existing dataset for this subject, or create new dataset
iDS = GetDataSetSubject(sSubject.FileName, 1);
GlobalData.DataSet(iDS).Measures = Measures;
GlobalData.DataSet(iDS).SubjectFile = file_short(sSubject.FileName);
GlobalData.DataSet(iDS).Measures = Measures;
% Update time window
CheckTimeWindows();
% Otherwise: keep only the first one, discard all the other volumes
else
sMri.Cube = sMri.Cube(:,:,:,1);
end
end
% === REFERENCE VOLUME ===
% Copy SCS and NCS fields from reference volume
if ~isempty(sSubject.iAnatomy) && ~file_compare(MriFile, sSubject.Anatomy(sSubject.iAnatomy).FileName) && ...
(~isfield(sMri, 'SCS') || isempty(sMri.SCS) || isempty(sMri.SCS.NAS) || ~isfield(sMri, 'NCS') || isempty(sMri.NCS) || isempty(sMri.NCS.AC))
% Load reference volume for this subject
sMriRef = bst_memory('LoadMri', sSubject.Anatomy(sSubject.iAnatomy).FileName);
% Copy SCS field
if (~isfield(sMri, 'SCS') || isempty(sMri.SCS) || isempty(sMri.SCS.NAS)) && isfield(sMriRef, 'SCS') && ~isempty(sMriRef.SCS) && ~isempty(sMriRef.SCS.NAS)
sMri.SCS = sMriRef.SCS;
end
% Copy NCS field
if (~isfield(sMri, 'NCS') || isempty(sMri.NCS) || isempty(sMri.NCS.AC)) && isfield(sMriRef, 'NCS') && ~isempty(sMriRef.NCS) && ~isempty(sMriRef.NCS.AC)
sMri.NCS = sMriRef.NCS;
end
end
% === REGISTER NEW MRI ===
% Add MRI to loaded MRIs in this protocol
iMri = length(GlobalData.Mri) + 1;
% Save MRI in memory
GlobalData.Mri(iMri) = sMri;
% Else: Return the existing instance
else
sMri = GlobalData.Mri(iMri);
end
end
%% ===== GET MRI =====
function [sMri, iMri] = GetMri(MriFile) %#ok<DEFNU>
global GlobalData;
% Check if surface is already loaded
iMri = find(file_compare({GlobalData.Mri.FileName}, MriFile));
if ~isempty(iMri)
sMri = GlobalData.Mri(iMri);
else
sMri = [];
end
end
%% ===== LOAD FIBERS =====
% USAGE: [sFib,iFib] = bst_memory('LoadFiber', FibFile)
% [sFib,iFib] = bst_memory('LoadFiber', iSubject)
function [sFib,iFib] = LoadFibers(FibFile)
global GlobalData;
% ===== PARSE INPUTS =====
% If argument is a subject indice
if isnumeric(FibFile)
% Get subject
iSubject = FibFile;
sSubject = bst_get('Subject', iSubject);
% If subject does not have fibers
if isempty(sSubject.Surface) || isempty(sSubject.iFibers)
error('No fiber available for subject "%s".', sSubject.Name);
end
% Get fibers file
FibFile = sSubject.Surface(sSubject.iFibers).FileName;
else
[sSubject, iSubject, iSurfDb] = bst_get('SurfaceFile', FibFile);
end
% ===== CHECK IF LOADED =====
% Check if surface is already loaded
iFib = find(file_compare({GlobalData.Fibers.FileName}, FibFile));
% If fiber is not loaded yet: load it
if isempty(iFib)
% Unload the unused Anatomies (surfaces + MRIs)
UnloadAll('KeepSurface');
% Create default structure
sFib = db_template('LoadedFibers');
% Load fibers matrix
FibMat = load(file_fullpath(FibFile));
% Build fibers structure
for field = fieldnames(sFib)'
if isfield(FibMat, field{1})
sFib.(field{1}) = FibMat.(field{1});
end
end
% Set filename
sFib.FileName = file_win2unix(FibFile);
iFib = length(GlobalData.Fibers) + 1;
% Save fibers in memory
GlobalData.Fibers(iFib) = sFib;
% Else: Return the existing instance
else
sFib = GlobalData.Fibers(iFib);
end
end
%% ===== GET FIBERS =====
function [sFib, iFib] = GetFibers(FibFile) %#ok<DEFNU>
global GlobalData;
% Check if surface is already loaded
iFib = find(file_compare({GlobalData.Fibers.FileName}, FibFile));
if ~isempty(iFib)
sFib = GlobalData.Fibers(iFib);
else
sFib = [];
end
end
%% ===== LOAD SURFACE =====
% Load a surface in memory, or get a loaded surface
% Usage: [sSurf, iSurf] = LoadSurface(iSubject, SurfaceType)
% [sSurf, iSurf] = LoadSurface(MriFile, SurfaceType)
% [sSurf, iSurf] = LoadSurface(SurfaceFile)
function [sSurf, iSurf] = LoadSurface(varargin)
global GlobalData;
% ===== PARSE INPUTS =====
if (nargin == 1)
SurfaceFile = varargin{1};
elseif (nargin == 2)
% Get inputs
iSubject = varargin{1};
SurfaceType = varargin{2};
% Get surface
sDbSurf = bst_get('SurfaceFileByType', iSubject, SurfaceType);
SurfaceFile = sDbSurf.FileName;
end
% Get subject and surface type
[sSubject, iSubject, iSurfDb] = bst_get('SurfaceFile', SurfaceFile);
if isempty(iSubject)
SurfaceType = 'Other';
else
SurfaceType = sSubject.Surface(iSurfDb).SurfaceType;
end
% ===== LOAD FILE =====
% Check if surface is already loaded
if ~isempty(GlobalData.Surface)
iSurf = find(file_compare({GlobalData.Surface.FileName}, SurfaceFile));
else
iSurf = [];
end
% If file not loaded: load it
if isempty(iSurf)
% Check if progressbar is visible
isProgressBar = bst_progress('isVisible');
% Unload the unused Anatomies (surfaces + MRIs)
UnloadAll('KeepMri', 'KeepRegSurface');
% Re-open progress bar
if isProgressBar
bst_progress('show');
bst_progress('text', 'Loading surface file...');
end
% Create default structure
sSurf = db_template('LoadedSurface');
% Load surface matrix
surfMat = in_tess_bst(SurfaceFile);
% Get interesting fields
sSurf.Comment = surfMat.Comment;
sSurf.Faces = double(surfMat.Faces);
sSurf.Vertices = double(surfMat.Vertices);
sSurf.VertConn = surfMat.VertConn;
sSurf.VertNormals = surfMat.VertNormals;
[tmp, sSurf.VertArea] = tess_area(surfMat.Vertices, surfMat.Faces);
sSurf.SulciMap = double(surfMat.SulciMap);
% Get interpolation matrix MRI<->Surface if it exists
if isfield(surfMat, 'tess2mri_interp')
sSurf.tess2mri_interp = surfMat.tess2mri_interp;
end
% Get the mrimask for this surface, if it exists
if isfield(surfMat, 'mrimask')
sSurf.mrimask = surfMat.mrimask;
end
% Fix atlas structure
sSurf.Atlas = panel_scout('FixAtlasStruct', surfMat.Atlas);
% Default atlas
if isempty(surfMat.iAtlas) || (surfMat.iAtlas < 1) || (surfMat.iAtlas > length(sSurf.Atlas))
sSurf.iAtlas = 1;
else
sSurf.iAtlas = surfMat.iAtlas;
end
% Save surface file and type
sSurf.FileName = file_win2unix(SurfaceFile);
sSurf.Name = SurfaceType;
% Add surface to loaded surfaces list in this protocol (if not already loaded)
iSurf = length(GlobalData.Surface) + 1;
% Save surface in memory
GlobalData.Surface(iSurf) = sSurf;
% Else, return the existing instance
else
sSurf = GlobalData.Surface(iSurf);
end
end
%% ===== GET INTERPOLATION SURF-MRI =====
% USAGE: [tess2mri_interp, sMri] = GetTess2MriInterp(iSurf, MriFile)
% [tess2mri_interp, sMri] = GetTess2MriInterp(iSurf) : Use the database to get MriFile
function [tess2mri_interp, sMri] = GetTess2MriInterp(iSurf, MriFile)
global GlobalData;
if (nargin < 2) || isempty(MriFile)
MriFile = [];
end
% Get existing interpolation
tess2mri_interp = GlobalData.Surface(iSurf).tess2mri_interp;
% Get anatomy
if (nargout >= 2) || isempty(tess2mri_interp)
% Get surface file name
SurfaceFile = GlobalData.Surface(iSurf).FileName;
% Load subject MRI
if ~isempty(MriFile)
sMri = LoadMri(MriFile);
else
[sSubject, iSubject] = bst_get('SurfaceFile', SurfaceFile);
sMri = LoadMri(iSubject);
end
end
% If interpolation matrix was not lready computed: return it
if isempty(tess2mri_interp)
% Compute or load interpolation matrix
tess2mri_interp = tess_interp_mri(SurfaceFile, sMri);
% Store result for future use
GlobalData.Surface(iSurf).tess2mri_interp = tess2mri_interp;
end
end
%% ===== GET INTERPOLATION GRID-MRI =====
function grid2mri_interp = GetGrid2MriInterp(iDS, iResult, GridSmooth) %#ok<DEFNU>
global GlobalData;
% Default grid smooth: yes
if (nargin < 3) || isempty(GridSmooth)
GridSmooth = 1;
end
% If matrix was already computed: return it
if ~isempty(GlobalData.DataSet(iDS).Results(iResult).grid2mri_interp)
grid2mri_interp = GlobalData.DataSet(iDS).Results(iResult).grid2mri_interp;
% Else: compute it
else
% Get subject
[sSubject, iSubject] = bst_get('Subject', GlobalData.DataSet(iDS).SubjectFile);
SurfaceFile = GlobalData.DataSet(iDS).Results(iResult).SurfaceFile;
% Load MRI
sMri = LoadMri(iSubject);
% Get the grid points to interpolate
switch (GlobalData.DataSet(iDS).Results(iResult).HeadModelType)
case 'volume'
GridLoc = GlobalData.DataSet(iDS).Results(iResult).GridLoc;
% Compute interpolation
grid2mri_interp = grid_interp_mri(GridLoc, sMri, SurfaceFile, 1, [], [], GridSmooth);
case 'mixed'
% Compute the surface interpolation
tess2mri_interp = tess_interp_mri(SurfaceFile, sMri);
% Initialize returned interpolation matrix
GridAtlas = GlobalData.DataSet(iDS).Results(iResult).GridAtlas;
grid2mri_interp = sparse(numel(sMri.Cube(:,:,:,1)), size(GridAtlas.Grid2Source,1));
% Process each region separately
ind = 1;
sScouts = GlobalData.DataSet(iDS).Results(iResult).GridAtlas.Scouts;
for i = 1:length(sScouts)
% Indices in the interpolation matrix
iGrid = ind + (0:length(sScouts(i).GridRows) - 1);
ind = ind + length(sScouts(i).GridRows);
% Interpolation depends on the type of region (volume or surface)
switch (sScouts(i).Region(2))
case 'V'
GridLoc = GlobalData.DataSet(iDS).Results(iResult).GridLoc(sScouts(i).GridRows,:);
grid2mri_interp(:,iGrid) = grid_interp_mri(GridLoc, sMri, SurfaceFile, 1, [], [], GridSmooth);
case 'S'
grid2mri_interp(:,iGrid) = tess2mri_interp(:, sScouts(i).Vertices);
end
end
otherwise
error('Invalid headmodel.');
end
% Store result for future use
GlobalData.DataSet(iDS).Results(iResult).grid2mri_interp = grid2mri_interp;
end
end
%% ===== GET SURFACE MASK =====
% USAGE: GetSurfaceMask(SurfaceFile, MriFile)
% GetSurfaceMask(SurfaceFile) : MriFile is retrieved from the database
function [mrimask, sMri, sSurf] = GetSurfaceMask(SurfaceFile, MriFile) %#ok<DEFNU>
global GlobalData;
if (nargin < 2) || isempty(MriFile)
MriFile = [];
end
% Load surface
[sSurf, iSurf] = LoadSurface(SurfaceFile);
% Get the tess -> MRI interpolation
[tess2mri_interp, sMri] = GetTess2MriInterp(iSurf, MriFile);
% Get an existing mrimask
if ~isempty(sSurf.mrimask)
mrimask = sSurf.mrimask;
% MRI mask do not exist yet
else
% Compute mrimask
mrimask = tess_mrimask(size(sMri.Cube(:,:,:,1)), tess2mri_interp);
% Add it to loaded structure
GlobalData.Surface(iSurf).mrimask = mrimask;
% Save new mrimask into file
SurfaceFile = file_fullpath(SurfaceFile);
s.mrimask = mrimask;
if file_exist(SurfaceFile)
bst_save(SurfaceFile, s, 'v7', 1);
end
end
end
%% ===== GET SURFACE =====
function [sSurf, iSurf] = GetSurface(SurfaceFile)
global GlobalData;
% Check if surface is already loaded
iSurf = find(file_compare({GlobalData.Surface.FileName}, SurfaceFile));
if ~isempty(iSurf)
sSurf = GlobalData.Surface(iSurf);
else
% Remove full path
SurfaceFile = file_short(SurfaceFile);
% Check again
iSurf = find(file_compare({GlobalData.Surface.FileName}, SurfaceFile));
if ~isempty(iSurf)
sSurf = GlobalData.Surface(iSurf);
else
sSurf = [];
end
end
end
%% ===== GET SURFACE ENVELOPE =====
function [sEnvelope, sSurf] = GetSurfaceEnvelope(SurfaceFile, nVertices, isRemesh, dilateMask)
global GlobalData;
% Parse inputs
if (nargin < 4) || isempty(dilateMask)
dilateMask = 1;
end
if (nargin < 3) || isempty(isRemesh)
isRemesh = 1;
end
% Load surface
[sSurf, iSurf] = LoadSurface(SurfaceFile);
% Get an existing mrimask
fieldName = sprintf('v%d', nVertices);
if ~isempty(sSurf.envelope) && isfield(sSurf.envelope, fieldName) && ~isempty(sSurf.envelope.(fieldName))
sEnvelope = sSurf.envelope.(fieldName);
% MRI mask do not exist yet
else
% Compute mrimask
sEnvelope = tess_envelope(SurfaceFile, 'mask_cortex', nVertices, [], [], isRemesh, dilateMask);
% Add it to loaded structure
GlobalData.Surface(iSurf).envelope.(fieldName) = sEnvelope;
end
end
%% =========================================================================================
% ===== FUNCTIONAL DATA ===================================================================
% =========================================================================================
%% ===== GET FILE INFORMATION =====
% Get all the information related with a DataFile.
function [sStudy, iData, ChannelFile, FileType, sItem] = GetFileInfo(DataFile)
% Get file in database
[sStudy, iStudy, iData, FileType, sItem] = bst_get('AnyFile', DataFile);
% If this data file does not belong to any study
if isempty(sStudy)
error('File is not registered in database.');
end
% If Channel is not defined yet : get it from Study description
Channel = bst_get('ChannelForStudy', iStudy);
if ~isempty(Channel)
ChannelFile = Channel.FileName;
else
ChannelFile = '';
end
end
%% ===== LOAD CHANNEL FILE =====
function LoadChannelFile(iDS, ChannelFile)
global GlobalData;
% If a channel file is defined
if ~isempty(ChannelFile)
% Check if this channel file is already loaded and modified in another DataSet
iDSother = setdiff(1:length(GlobalData.DataSet), iDS);
if ~isempty(iDSother) && any([GlobalData.DataSet(iDSother).isChannelModified])
% Ask user
isSave = java_dialog('confirm', ...
['This channel file is being edited in another window.' 10 ...
'Save the modifications so the new figure can show updated positions?'], 'Save modifications');
% Force saving of the modifications
if isSave
bst_memory('SaveChannelFile', iDSother(1));
end
end
% Load channel
ChannelMat = in_bst_channel(ChannelFile);
% Check coherence between Channel and Measures.F dimensions
nChannels = length(ChannelMat.Channel);
nDataChan = length(GlobalData.DataSet(iDS).Measures.ChannelFlag);
if (nDataChan > 0) && (nDataChan ~= nChannels)
error('Number of channels in ChannelFile (%d) and DataFile (%d) do not match. Aborting...', nChannels, nDataChan);
end
% Save in DataSet structure
GlobalData.DataSet(iDS).ChannelFile = file_win2unix(ChannelFile);
GlobalData.DataSet(iDS).Channel = ChannelMat.Channel;
GlobalData.DataSet(iDS).Clusters = ChannelMat.Clusters;
GlobalData.DataSet(iDS).IntraElectrodes = ChannelMat.IntraElectrodes;
GlobalData.DataSet(iDS).MegRefCoef = ChannelMat.MegRefCoef;
GlobalData.DataSet(iDS).Projector = ChannelMat.Projector;
% If extra channel info available (such as head points in FIF format)
if isfield(ChannelMat, 'HeadPoints')
GlobalData.DataSet(iDS).HeadPoints = ChannelMat.HeadPoints;
end
% If there are some ECOG/SEEG channels: Create new temporary montages automatically
if any(ismember({'ECOG', 'SEEG'}, {ChannelMat.Channel.Type}))
SubjectName = bst_fileparts(GlobalData.DataSet(iDS).SubjectFile);
panel_montage('AddAutoMontagesSeeg', SubjectName, ChannelMat);
end
% If there are some NIRS channels: Create new temporary montages automatically
if ismember('NIRS', {ChannelMat.Channel.Type})
panel_montage('AddAutoMontagesNirs', ChannelMat);
end
% No channel file: create a fake structure
elseif ~isempty(GlobalData.DataSet(iDS).Measures.ChannelFlag)
nChan = length(GlobalData.DataSet(iDS).Measures.ChannelFlag);
GlobalData.DataSet(iDS).Channel = repmat(db_template('ChannelDesc'), [1 nChan]);
for i = 1:nChan
GlobalData.DataSet(iDS).Channel(i).Name = sprintf('E%d', i);
GlobalData.DataSet(iDS).Channel(i).Loc = [0;0;0];
GlobalData.DataSet(iDS).Channel(i).Type = 'EEG';
end
GlobalData.DataSet(iDS).MegRefCoef = [];
GlobalData.DataSet(iDS).Projector = [];
GlobalData.DataSet(iDS).Clusters = [];
GlobalData.DataSet(iDS).IntraElectrodes = [];
end
end
%% ===== LOAD DATA FILE (& CREATE DATASET) =====
% Load all recordings information but the recordings matrix itself (F).
% USAGE: [iDS, ChannelFile] = LoadDataFile(DataFile, isReloadForced, isTimeCheck)
% [iDS, ChannelFile] = LoadDataFile(DataFile, isReloadForced)
% [iDS, ChannelFile] = LoadDataFile(DataFile)
function [iDS, ChannelFile] = LoadDataFile(DataFile, isReloadForced, isTimeCheck)
global GlobalData;
% ===== PARSE INPUTS =====
if (nargin < 3)
isTimeCheck = 1;
end
if (nargin < 2)
isReloadForced = 0;
end
% Get data file information from database
[sStudy, iData, ChannelFile, FileType] = GetFileInfo(DataFile);
% Get data type
switch lower(FileType)
case 'data'
DataType = sStudy.Data(iData).DataType;
DataFile = sStudy.Data(iData).FileName;
case 'pdata'
DataType = 'stat';
DataFile = sStudy.Stat(iData).FileName;
% Show "stat" tab
gui_brainstorm('ShowToolTab', 'Stat');
otherwise
error('Invalid file type.');
end
% ===== LOAD DATA =====
% Create Measures structure
Measures = db_template('Measures');
% Load file description
if strcmpi(DataType, 'raw')
% Is loaded dataset
iDS = GetDataSetData(DataFile, 0);
% Load file
if isempty(iDS)
bst_progress('start', 'Loading raw file', 'Reading file header...');
MeasuresMat = in_bst_data(DataFile, 'F', 'ChannelFlag', 'ColormapType', 'DisplayUnits');
sFile = MeasuresMat.F;
else
MeasuresMat = GlobalData.DataSet(iDS).Measures;
sFile = MeasuresMat.sFile;
end
% Rebuild Time vector
Time = panel_time('GetRawTimeVector', sFile);
% Check if file exists
isRetry = 1;
while isRetry
if ~file_exist(sFile.filename)
% File does not exist: ask the user what to do
res = java_dialog('question', [...
'The following file has been moved, deleted, is used by another program,', 10, ...
'or is on a drive that is currently not connected to your computer.' 10 ...
'If the file is accessible at another location, click on "Pick file".' 10 10 ...
sFile.filename 10 10], ...
'Load continuous file', [], {'Pick file...', 'Retry', 'Cancel'}, 'Cancel');
% Cancel
if isempty(res) || strcmpi(res, 'Cancel')
iDS = [];
bst_progress('stop');
return;
end
% Retry
if strcmpi(res, 'Retry')
continue;
% Pick file
else
sFile = panel_record('FixFileLink', DataFile, sFile);
if isempty(sFile)
iDS = [];
bst_progress('stop');
return;
end
end
else
isRetry = 0;
end
end
% Check version of Nicolet object (after change introduced on 5-Sep-2022)
NICOLET_VER = 2;
if strcmpi(sFile.format, 'EEG-NICOLET') && (~isfield(sFile.header, 'objversion') || isempty(sFile.header.objversion) || (sFile.header.objversion < NICOLET_VER))
disp(['BST> Updating outdated NicoletFile object: ', DataFile]);
% Update NicoletFile object
sFile.header.obj = NicoletFile(sFile.filename);
sFile.header.objversion = NICOLET_VER;
% Save modifications in file
DataMat.F = sFile;
bst_save(file_fullpath(DataFile), DataMat, 'v6', 1);
end
else
MeasuresMat = in_bst_data(DataFile, 'Time', 'ChannelFlag', 'ColormapType', 'Events', 'DisplayUnits');
Time = MeasuresMat.Time;
% Duplicate time if only one time frame
if (length(Time) == 1)
Time = [0,0.001] + Time;
end
% Create fake "sFile" structure
sFile = db_template('sFile');
% Store events
if ~isempty(MeasuresMat.Events)
sFile.events = MeasuresMat.Events;
else
sFile.events = repmat(db_template('event'), 0);
end
sFile.format = 'BST';
sFile.filename = DataFile;
sFile.prop.times = Time([1 end]);
sFile.prop.sfreq = 1 ./ (Time(2) - Time(1));
end
Measures.DataType = DataType;
Measures.ChannelFlag = MeasuresMat.ChannelFlag;
Measures.sFile = sFile;
Measures.ColormapType = MeasuresMat.ColormapType;
Measures.DisplayUnits = MeasuresMat.DisplayUnits;
clear MeasuresMat;
% ===== TIME =====
if (length(Time) > 1)
% Default time selection: all the samples
iTime = [1, length(Time)];
% For raw recordings: limit to the user option
if strcmpi(DataType, 'raw')
RawViewerOptions = bst_get('RawViewerOptions', sFile);
% If current time window can be re-used
if ~isempty(GlobalData.UserTimeWindow.Time) && (GlobalData.UserTimeWindow.NumberOfSamples > 2) && (GlobalData.UserTimeWindow.Time(1) >= Time(1)) && (GlobalData.UserTimeWindow.Time(2) <= Time(end))
iTime = bst_closest(GlobalData.UserTimeWindow.Time, Time);
elseif (length(Time) > floor(RawViewerOptions.PageDuration * sFile.prop.sfreq))
iTime = [1, floor(RawViewerOptions.PageDuration * sFile.prop.sfreq)];
end
end
Measures.Time = double(Time([iTime(1), iTime(2)]));
Measures.SamplingRate = double(Time(2) - Time(1));
Measures.NumberOfSamples = iTime(2) - iTime(1) + 1;
else
Measures.Time = [0 0.001];
Measures.SamplingRate = 0.002;
Measures.NumberOfSamples = 2;
end
% ===== EXISTING DATASET ? =====
% Check if a DataSet already exists for this DataFile
isStatic = (Measures.NumberOfSamples <= 2);
iDS = GetDataSetData(DataFile, isStatic);
if (length(iDS) > 1)
iDS = iDS(1);
end
% If dataset already exist AND IS DEFINED FOR THE RIGHT SUBJECT, just return its index
if ~isempty(iDS) && ~isReloadForced
if ~isempty(sStudy.BrainStormSubject) && ~file_compare(sStudy.BrainStormSubject, GlobalData.DataSet(iDS).SubjectFile)
iDS = [];
else
GlobalData.DataSet(iDS).Measures.DataType = Measures.DataType;
GlobalData.DataSet(iDS).Measures.ChannelFlag = Measures.ChannelFlag;
if ~isempty(Measures.sFile) && isempty(GlobalData.DataSet(iDS).Measures.sFile)
GlobalData.DataSet(iDS).Measures.sFile = Measures.sFile;
end
return
end
end
% ===== CHECK FOR OTHER RAW FILES =====
if strcmpi(DataType, 'raw') && ~isempty(GlobalData.FullTimeWindow) && ~isempty(GlobalData.FullTimeWindow.CurrentEpoch) && ~isReloadForced
res = java_dialog('question', [...
'Cannot open two continuous viewers at the same time.' 10 ...
'Unload all the other files first?' 10 10], 'Load recordings', [], {'Unload other files', 'Cancel'});
% Cancel: Unload the new dataset
if isempty(res) || strcmpi(res, 'Cancel')
iDS = [];
return;
% Otherwise: unload all the other datasets
else
% Unload everything
UnloadAll('Forced');
% If not everything was unloaded correctly (eg. the user cancelled half way when asked to save the modifications)
if ~isempty(GlobalData.DataSet)
iDS = [];
return;
end
% New dataset = only dataset
iDS = 1;
end
end
% ===== STORE IN GLOBALDATA =====
% If no DataSet is available for this data file
if isempty(iDS)
% Create new dataset
iDS = length(GlobalData.DataSet) + 1;
GlobalData.DataSet(iDS) = db_template('DataSet');
end
% Store DataSet in GlobalData
GlobalData.DataSet(iDS).SubjectFile = file_short(sStudy.BrainStormSubject);
GlobalData.DataSet(iDS).StudyFile = file_short(sStudy.FileName);
GlobalData.DataSet(iDS).DataFile = file_short(DataFile);
GlobalData.DataSet(iDS).Measures = Measures;
% ===== LOAD CHANNEL FILE =====
LoadChannelFile(iDS, ChannelFile);
% ===== Check time window consistency with previously loaded data =====
if isTimeCheck
% Update time window
isTimeCoherent = CheckTimeWindows();
% If loaded data is not coherent with previous data
if ~isTimeCoherent
res = java_dialog('question', [...
'The time definition is not compatible with previously loaded files.' 10 ...
'Unload all the other files first?' 10 10], 'Load recordings', [], {'Unload other files', 'Cancel'});
% Cancel: Unload the new dataset
if isempty(res) || strcmpi(res, 'Cancel')
UnloadDataSets(iDS);
iDS = [];
return;
% Otherwise: unload all the other datasets
else
% Save newly created dataset
bakDS = GlobalData.DataSet(iDS);
% Unload everything
UnloadAll('Forced');
% If not everything was unloaded correctly (eg. the user cancelled half way when asked to save the modifications)
if ~isempty(GlobalData.DataSet)
% Unload the new dataset
UnloadDataSets(iDS);
iDS = [];
return;
end
% Restore new dataset
GlobalData.DataSet = bakDS;
iDS = 1;
% Update time window
isTimeCoherent = CheckTimeWindows();
end
end
end
% ===== UPDATE TOOL TABS =====
if ~isempty(iDS) && strcmpi(GlobalData.DataSet(iDS).Measures.DataType, 'raw')
% Initialize tab with new RAW information
panel_record('InitializePanel');
end
panel_cluster('UpdatePanel');
panel_time('UpdatePanel');
end
%% ===== GET RAW DATASET =====
function iDS = GetRawDataSet() %#ok<DEFNU>
global GlobalData;
iDS = [];
% No raw data loaded
if isempty(GlobalData.FullTimeWindow) || isempty(GlobalData.FullTimeWindow.CurrentEpoch)
return
end
% Look for the raw data loaded in all the datasets
for i = 1:length(GlobalData.DataSet)
if isequal(GlobalData.DataSet(i).Measures.DataType, 'raw')
iDS = i;
return;
end
end
end
%% ===== LOAD F MATRIX FOR A GIVEN DATA FILE =====
% Load the F matrix for a dataset that has already been pre-loaded (with LoadDataFile)
function LoadRecordingsMatrix(iDS)
global GlobalData;
% Check dataset index integrity
if isempty(iDS) || (iDS <= 0) || (iDS > length(GlobalData.DataSet))
error('Invalid DataSet index : %d', iDS);
end
% Relative filename : add the SUBJECTS path
DataFile = file_fullpath(GlobalData.DataSet(iDS).DataFile);
% Load F Matrix
if strcmpi(GlobalData.DataSet(iDS).Measures.DataType, 'stat')
% Load stat file
StatMat = in_bst_data(DataFile, 'pmap', 'tmap', 'df', 'SPM', 'ChannelFlag', 'Correction', 'StatClusters', 'Time');
% Get only relevant sensors as multiple tests
iChannels = good_channel(GlobalData.DataSet(iDS).Channel, StatMat.ChannelFlag, {'MEG', 'EEG', 'SEEG', 'ECOG', 'NIRS'});
if isfield(StatMat, 'pmap') && ~isempty(StatMat.pmap)
StatMat.pmap = StatMat.pmap(iChannels,:,:);
end
if isfield(StatMat, 'tmap') && ~isempty(StatMat.tmap)
StatMat.tmap = StatMat.tmap(iChannels,:,:);
end
if isfield(StatMat, 'df') && ~isempty(StatMat.df) && (numel(StatMat.df) > 1)
StatMat.df = StatMat.df(iChannels,:,:);
end
% Initialize matrix
GlobalData.DataSet(iDS).Measures.F = zeros(length(GlobalData.DataSet(iDS).Measures.ChannelFlag), GlobalData.DataSet(iDS).Measures.NumberOfSamples);
% Apply threshold, and duplicate time if there is only one time point
[threshMap, tThreshUnder, tThreshOver] = process_extract_pthresh('Compute', StatMat);
if ( size(threshMap,2) == 1) && (GlobalData.DataSet(iDS).Measures.NumberOfSamples == 2)
threshMap = cat(2, threshMap, threshMap);
end
GlobalData.DataSet(iDS).Measures.F(iChannels,:,:) = threshMap;
GlobalData.DataSet(iDS).Measures.StatThreshUnder = tThreshUnder;
GlobalData.DataSet(iDS).Measures.StatThreshOver = tThreshOver;
% Copy stat clusters
GlobalData.DataSet(iDS).Measures.StatClusters = StatMat.StatClusters;
GlobalData.DataSet(iDS).Measures.StatClusters.Correction = StatMat.Correction;
else
% If RAW file: load a block from the file
if strcmpi(GlobalData.DataSet(iDS).Measures.DataType, 'raw')
DataMat.F = LoadRecordingsRaw(iDS);
% If not data could be loaded from the file: return
if isempty(DataMat.F)
return
end
% Else: Load data file
else
DataMat = in_bst_data(DataFile, 'F', 'Std');
end
% ===== APPLY FILTERING =====
% Check if the online filters should be applied to the recordings
ColormapType = GlobalData.DataSet(iDS).Measures.ColormapType;
UseFilterData = ~ismember(GlobalData.DataSet(iDS).Measures.DataType, {'zscore','stat'}) && (isempty(ColormapType) || ~ismember(ColormapType, {'stat1','stat2'}));
% Check if the online filters should be applied on the sources
UseFilterResults = 1;
for iRes = 1:length(GlobalData.DataSet(iDS).Results)
% Is this a Z-score file?
ColormapTypeRes = GlobalData.DataSet(iDS).Results(iRes).ColormapType;
isZscore = ~isempty(GlobalData.DataSet(iDS).Results(iRes).ZScore) || ...
~isempty(strfind(GlobalData.DataSet(iDS).Results(iRes).FileName, '_zscore')) || ...
(~isempty(ColormapTypeRes) && ismember(ColormapTypeRes, {'stat1', 'stat2'}));
% Do not figure recordings if it is attached to a Z-scored source file
if ~isempty(GlobalData.DataSet(iDS).Results(iRes).ImagingKernel) && isZscore
UseFilterResults = 0;
end
end
% Apply filters
if UseFilterData && UseFilterResults
sfreq = 1./GlobalData.DataSet(iDS).Measures.SamplingRate;
DataMat.F = FilterLoadedData(DataMat.F, sfreq);
GlobalData.DataSet(iDS).Measures.isFiltered = 1;
else
GlobalData.DataSet(iDS).Measures.isFiltered = 0;
end
% If data was loaded : store it in GlobalData
if ~isempty(DataMat.F)
GlobalData.DataSet(iDS).Measures.F = double(DataMat.F);
end
if isfield(DataMat, 'Std') && ~isempty(DataMat.Std)
GlobalData.DataSet(iDS).Measures.Std = double(DataMat.Std);
end
end
% If there is only one time sample : copy it to get 2 time samples
if (size(GlobalData.DataSet(iDS).Measures.F, 2) == 1)
GlobalData.DataSet(iDS).Measures.F = repmat(GlobalData.DataSet(iDS).Measures.F, [1,2]);
% Also duplicate Std if present
if isfield(DataMat, 'Std') && ~isempty(DataMat.Std)
GlobalData.DataSet(iDS).Measures.Std = repmat(GlobalData.DataSet(iDS).Measures.Std, [1,2]);
end
end
end
%% ===== LOAD RAW DATA ====
% Load a block of
function F = LoadRecordingsRaw(iDS)
global GlobalData;
% Get values data to read
iEpoch = GlobalData.FullTimeWindow.CurrentEpoch;
TimeRange = GlobalData.DataSet(iDS).Measures.Time;
% Get raw viewer options
RawViewerOptions = bst_get('RawViewerOptions');
UseSsp = 1;
% Rebuild a minimalist ChannelMat
ChannelMat = struct('Channel', GlobalData.DataSet(iDS).Channel, ...
'Projector', GlobalData.DataSet(iDS).Projector, ...
'MegRefCoef', GlobalData.DataSet(iDS).MegRefCoef);
% Read data block
F = panel_record('ReadRawBlock', GlobalData.DataSet(iDS).Measures.sFile, ChannelMat, iEpoch, TimeRange, 1, RawViewerOptions.UseCtfComp, RawViewerOptions.RemoveBaseline, UseSsp);
end
%% ===== FILTER LOADED DATA =====
function F = FilterLoadedData(F, sfreq)
global GlobalData;
isLowPass = GlobalData.VisualizationFilters.LowPassEnabled;
isHighPass = GlobalData.VisualizationFilters.HighPassEnabled;
isSinRemoval = GlobalData.VisualizationFilters.SinRemovalEnabled;
% isMirror = GlobalData.VisualizationFilters.MirrorEnabled;
isMirror = 0;
% Get time vector
nTime = size(F,2);
% Band-pass filter is active: apply it (only if real recordings => ignore time averages)
if (isHighPass || isLowPass) && (nTime > 2)
% LOW-PASS
if ~isLowPass || isequal(GlobalData.VisualizationFilters.LowPassValue, 0)
LowPass = [];
else
LowPass = GlobalData.VisualizationFilters.LowPassValue;
end
% HI-PASS
if ~isHighPass || isequal(GlobalData.VisualizationFilters.HighPassValue, 0)
HighPass = [];
else
HighPass = GlobalData.VisualizationFilters.HighPassValue;