plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
philippboehmsturm/antx-master
|
spm_latex_cfg.m
|
.m
|
antx-master/xspm8/config/spm_latex_cfg.m
| 6,676 |
utf_8
|
a47b123dac969fa8a766913b882670a1
|
function spm_latex_cfg(c)
% Convert a job configuration tree into a series of LaTeX documents
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_latex_cfg.m 3934 2010-06-17 14:58:25Z guillaume $
if ~nargin, c = spm_cfg; end
if nargin && ischar(c), clean_latex_compile; return; end
fp = fopen('spm_manual.tex','w');
fprintf(fp,'\\documentclass[a4paper,titlepage]{book}\n');
fprintf(fp,'\\usepackage{epsfig,amsmath,pifont,moreverb,minitoc}\n');
fprintf(fp,'%s\n%s\n%s\n%s\n%s\n%s\n%s\n',...
'\usepackage[colorlinks=true,',...
'pdfpagemode=UseOutlines,',...
'pdftitle={SPM Manual},','pdfauthor={The SPM Team},',...
'pdfsubject={Statistical Parametric Mapping},',...
'pdfkeywords={neuroimaging, MRI, PET, EEG, MEG, SPM}',...
']{hyperref}');
fprintf(fp,'\\pagestyle{headings}\n\\bibliographystyle{plain}\n\n');
fprintf(fp,'\\hoffset=15mm\n\\voffset=-5mm\n');
fprintf(fp,'\\oddsidemargin=0mm\n\\evensidemargin=0mm\n\\topmargin=0mm\n');
fprintf(fp,'\\headheight=12pt\n\\headsep=10mm\n\\textheight=240mm\n\\textwidth=148mm\n');
fprintf(fp,'\\marginparsep=5mm\n\\marginparwidth=21mm\n\\footskip=10mm\n\n');
fprintf(fp,'\\title{\\huge{SPM Manual}}\n');
fprintf(fp,'\\author{The FIL Methods Group (and honorary members)}\n');
fprintf(fp,'\\begin{document}\n');
fprintf(fp,'\\maketitle\n');
fprintf(fp,'\\dominitoc\\tableofcontents\n\n');
fprintf(fp,'\\newpage\n\\section*{The SPM User Interface}\n');
write_help(c,fp);
for i=1:numel(c.values),
% this is always false, and each cfg_item has a tag
%if isfield(c.values{i},'tag'),
part(c.values{i},fp);
%end;
end;
%fprintf(fp,'\\parskip=0mm\n\\bibliography{methods_macros,methods_group,external}\n\\end{document}\n\n');
fprintf(fp,'\\parskip=0mm\n');
bibcstr = get_bib(fullfile(spm('dir'),'man','biblio'));
tbxlist = dir(fullfile(spm('dir'),'toolbox'));
for k = 1:numel(tbxlist)
if tbxlist(k).isdir,
bibcstr=[bibcstr(:); get_bib(fullfile(spm('dir'),'toolbox', ...
tbxlist(k).name))];
end;
end;
bibcstr = strcat(bibcstr,',');
bibstr = strcat(bibcstr{:});
fprintf(fp,'\\bibliography{%s}\n',bibstr(1:end-1));
fprintf(fp,'\\end{document}\n\n');
fclose(fp);
return;
%==========================================================================
function part(c,fp)
% this is always false, and each cfg_item has a tag
%if isstruct(c) && isfield(c,'tag'),
fprintf(fp,'\\part{%s}\n',texify(c.name));
% write_help(c,fp);
if isa(c,'cfg_repeat')||isa(c,'cfg_choice')||isa(c,'cfg_menu'),
for i=1:numel(c.values),
%if isfield(c.values{i},'tag'),
fprintf(fp,'\\include{%s}\n',c.values{i}.tag);
chapter(c.values{i});
%end;
end;
end;
%if isfield(c,'val'),
for i=1:numel(c.val),
if isfield(c.val{i},'tag'),
if chapter(c.val{i}),
fprintf(fp,'\\include{%s}\n',c.val{i}.tag);
end;
end;
end;
%end;
%end;
return;
%==========================================================================
function sts = chapter(c)
bn = c.tag;
if strcmp(bn,'preproc') && ~isempty(strfind(c.name,'EEG'))
bn = ['MEEG_' bn]; % fix for name clash with other 'preproc'
end
fp = fopen([bn '.tex'],'w');
if fp==-1, sts = false; return; end;
fprintf(fp,'\\chapter{%s \\label{Chap:%s}}\n\\minitoc\n\n\\vskip 1.5cm\n\n',texify(c.name),c.tag);
write_help(c,fp);
switch class(c),
case {'cfg_branch','cfg_exbranch'},
for i=1:numel(c.val),
section(c.val{i},fp);
end;
case {'cfg_repeat','cfg_choice'},
for i=1:numel(c.values),
section(c.values{i},fp);
end;
end;
fclose(fp);
sts = true;
return;
%==========================================================================
function section(c,fp,lev)
if nargin<3, lev = 1; end;
sec = {'section','subsection','subsubsection','paragraph','subparagraph','textbf','textsc','textsl','textit'};
if lev<=length(sec),
fprintf(fp,'\n\\%s{%s}\n',sec{lev},texify(c.name));
write_help(c,fp);
switch class(c),
case {'cfg_branch','cfg_exbranch'},
for i=1:numel(c.val),
section(c.val{i},fp,lev+1);
end;
case {'cfg_repeat','cfg_choice'},
for i=1:numel(c.values),
section(c.values{i},fp,lev+1);
end;
end;
else
warning(['Too many nested levels... ' c.name]);
end;
return;
%==========================================================================
function write_help(hlp,fp)
if isa(hlp, 'cfg_item'),
if ~isempty(hlp.help),
hlp = hlp.help;
else
return;
end;
end;
if iscell(hlp),
for i=1:numel(hlp),
write_help(hlp{i},fp);
end;
return;
end;
str = texify(hlp);
fprintf(fp,'%s\n\n',str);
return;
%==========================================================================
function str = texify(str0)
st1 = strfind(str0,'/*');
en1 = strfind(str0,'*/');
st = [];
en = [];
for i=1:numel(st1),
en1 = en1(en1>st1(i));
if ~isempty(en1),
st = [st st1(i)];
en = [en en1(1)];
en1 = en1(2:end);
end;
end;
str = [];
pen = 1;
for i=1:numel(st),
str = [str clean_latex(str0(pen:st(i)-1)) str0(st(i)+2:en(i)-1)];
pen = en(i)+2;
end;
str = [str clean_latex(str0(pen:numel(str0)))];
return;
%==========================================================================
function str = clean_latex(str)
str = strrep(str,'$','\$');
str = strrep(str,'&','\&');
str = strrep(str,'^','\^');
str = strrep(str,'_','\_');
str = strrep(str,'#','\#');
%str = strrep(str,'\','$\\$');
str = strrep(str,'|','$|$');
str = strrep(str,'>','$>$');
str = strrep(str,'<','$<$');
return;
%==========================================================================
function bibcstr = get_bib(bibdir)
biblist = dir(fullfile(bibdir,'*.bib'));
bibcstr={};
for k = 1:numel(biblist)
[p n e v] = spm_fileparts(biblist(k).name);
bibcstr{k} = fullfile(bibdir,n);
end
%==========================================================================
function clean_latex_compile
p = fullfile(spm('Dir'),'man');
[f, d] = spm_select('FPlist',p,'.*\.aux$');
f = strvcat(f, spm_select('FPlist',p,'.*\.tex$'));
f = strvcat(f, spm_select('FPlist',p,'^manual\..*$'));
f(strcmp(cellstr(f),fullfile(spm('Dir'),'man','manual.tex')),:) = [];
f(strcmp(cellstr(f),fullfile(spm('Dir'),'man','manual.pdf')),:) = [];
for i=1:size(d,1)
f = strvcat(f, spm_select('FPlist',deblank(d(i,:)),'.*\.aux$'));
end
f(strcmp(cellstr(f),filesep),:) = [];
disp(f); pause
for i=1:size(f,1)
spm_unlink(deblank(f(i,:)));
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_convert.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_convert.m
| 7,130 |
utf_8
|
9bf1bea2b0e3690b8d396162b76d4d33
|
function S = spm_cfg_eeg_convert
% configuration file for data conversion
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_convert.m 3881 2010-05-07 21:02:57Z vladimir $
dataset = cfg_files;
dataset.tag = 'dataset';
dataset.name = 'File Name';
dataset.filter = 'any';
dataset.num = [1 1];
dataset.help = {'Select data set file.'};
timewindow = cfg_entry;
timewindow.tag = 'timing';
timewindow.name = 'Timing';
timewindow.strtype = 'r';
timewindow.num = [1 2];
timewindow.help = {'start and end of epoch [ms]'};
readall = cfg_const;
readall.tag = 'readall';
readall.name = 'Read all';
readall.val = {1};
read = cfg_choice;
read.tag = 'read';
read.name = 'Continuous';
read.values = {timewindow, readall};
read.val = {readall};
usetrials = cfg_const;
usetrials.tag = 'usetrials';
usetrials.name = 'Trials defined in data';
usetrials.val = {1};
trlfile = cfg_files;
trlfile.tag = 'trlfile';
trlfile.name = 'Trial File';
trlfile.filter = 'mat';
trlfile.num = [1 1];
conditionlabel = cfg_entry;
conditionlabel.tag = 'conditionlabel';
conditionlabel.name = 'Condition label';
conditionlabel.strtype = 's';
eventtype = cfg_entry;
eventtype.tag = 'eventtype';
eventtype.name = 'Event type';
eventtype.strtype = 's';
eventvalue = cfg_entry;
eventvalue.tag = 'eventvalue';
eventvalue.name = 'Event value';
eventvalue.strtype = 'e';
trialdef = cfg_branch;
trialdef.tag = 'trialdef';
trialdef.name = 'Trial';
trialdef.val = {conditionlabel, eventtype, eventvalue};
define1 = cfg_repeat;
define1.tag = 'unused';
define1.name = 'Trial definitions';
define1.values = {trialdef};
define = cfg_branch;
define.tag = 'define';
define.name = 'Define trial';
define.val = {timewindow define1};
trials = cfg_choice;
trials.tag = 'trials';
trials.name = 'Epoched';
trials.values = {usetrials trlfile define};
continuous = cfg_choice;
continuous.tag = 'continuous';
continuous.name = 'Reading mode';
continuous.values = {read trials};
continuous.val = {read};
continuous.help = {'Select whether you want to convert to continuous or epoched data.'};
chanall = cfg_const;
chanall.tag = 'chanall';
chanall.name = 'All';
chanall.val = {1};
chanmeg = cfg_const;
chanmeg.tag = 'chanmeg';
chanmeg.name = 'MEG';
chanmeg.val = {1};
chaneeg = cfg_const;
chaneeg.tag = 'chaneeg';
chaneeg.name = 'EEG';
chaneeg.val = {1};
chanfile = cfg_files;
chanfile.tag = 'chanfile';
chanfile.name = 'Channel file';
chanfile.filter = 'mat';
chanfile.num = [1 1];
channels = cfg_choice;
channels.tag = 'channels';
channels.name = 'Channel selection';
channels.values = {chanall,chanmeg,chaneeg,chanfile};
channels.val = {chanall};
outfile = cfg_entry;
outfile.tag = 'outfile';
outfile.name = 'Output filename';
outfile.strtype = 's';
outfile.num = [0 inf];
outfile.val = {''};
outfile.help = {'Choose filename. Leave empty to add ''spm8_'' to the input file name.'};
datatype = cfg_menu;
datatype.tag = 'datatype';
datatype.name = 'Data type';
datatype.labels = {'float32-le','float64-le'};
datatype.val = {'float32-le'};
datatype.values = {'float32-le','float64-le'};
datatype.help = {'Determine data type to save data in.'};
eventpadding = cfg_entry;
eventpadding.tag = 'eventpadding';
eventpadding.name = 'Event padding';
eventpadding.strtype = 'r';
eventpadding.val = {0};
eventpadding.num = [1 1];
eventpadding.help = {'in sec - the additional time period around each trial',...
'for which the events are saved with the trial (to let the',...
'user keep and use for analysis events which are outside',...
'trial borders). Default - 0'};
blocksize = cfg_entry;
blocksize.tag = 'blocksize';
blocksize.name = 'Block size';
blocksize.strtype = 'r';
blocksize.val = {3276800};
blocksize.num = [1 1];
blocksize.help = {'size of blocks used internally to split large files default ~100Mb'};
checkboundary = cfg_menu;
checkboundary.tag = 'checkboundary';
checkboundary.name = 'Check boundary';
checkboundary.labels = {'Check boundaries', 'Don''t check boundaries'};
checkboundary.val = {1};
checkboundary.values = {1,0};
checkboundary.help = {'1 - check if there are breaks in the file and do not read',...
'across those breaks (default).',...
'0 - ignore breaks (not recommended)'};
inputformat = cfg_entry;
inputformat.tag = 'inputformat';
inputformat.name = 'Input data format';
inputformat.strtype = 's';
inputformat.val = {'autodetect'};
inputformat.num = [1 inf];
inputformat.help = {'Force the reader to assume a particular data format (usually not necessary)'};
S = cfg_exbranch;
S.tag = 'convert';
S.name = 'M/EEG Conversion';
S.val = {dataset continuous channels outfile datatype eventpadding blocksize checkboundary inputformat};
S.help = {'Converts EEG/MEG data.'};
S.prog = @eeg_convert;
S.vout = @vout_eeg_convert;
S.modality = {'EEG'};
function out = eeg_convert(job)
% construct the S struct
S.dataset = job.dataset{1};
S.continuous = job.continuous;
S.channels = job.channels;
if ~isempty(job.outfile)
S.outfile = job.outfile;
end
S.datatype = job.datatype;
S.eventpadding = job.eventpadding;
S.blocksize = job.blocksize;
S.checkboundary = job.checkboundary;
if ~isequal(job.inputformat, 'autodetect')
S.inputformat = job.inputformat;
end
if isfield(S.continuous, 'read')
S.continuous = 1;
if isfield(job.continuous.read, 'timing')
S.timewindow = job.continuous.read.timing;
end
else
if isfield(S.continuous.trials, 'usetrials')
S.usetrials = S.continuous.trials.usetrials;
end
if isfield(S.continuous.trials, 'trlfile')
S.trlfile = char(S.continuous.trials.trlfile);
S.usetrials = 0;
end
if isfield(S.continuous.trials, 'define')
S.trialdef = S.continuous.trials.define.trialdef;
S.pretrig = S.continuous.trials.define.timing(1);
S.posttrig = S.continuous.trials.define.timing(2);
S.reviewtrials = 0;
S.save = 0;
S.usetrials = 0;
[S.trl, S.conditionlabel] = spm_eeg_definetrial(S);
end
S.continuous = 0;
end
if isfield(S.channels, 'chanmeg')
S.channels = 'MEG';
elseif isfield(S.channels, 'chaneeg')
S.channels = 'EEG';
elseif isfield(S.channels, 'chanall')
S.channels = 'all';
elseif isfield(S.channels, 'chanfile')
S.chanfile = S.channels.chanfile{1};
S.channels = 'file';
end
S.save = 0;
S.review = 0;
S = spm_eeg_channelselection(S);
S = rmfield(S, 'save');
S = rmfield(S, 'review');
out.D = spm_eeg_convert(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_convert(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Converted M/EEG Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Converted Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_cat.m
|
.m
|
antx-master/xspm8/config/spm_cfg_cat.m
| 2,707 |
utf_8
|
51b661dca39a9275dd0e770ae9c3cc6c
|
function cat = spm_cfg_cat
% SPM Configuration file for 3D to 4D volumes conversion
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_cfg_cat.m 3613 2009-12-04 18:47:59Z guillaume $
%--------------------------------------------------------------------------
% vols 3D Volumes
%--------------------------------------------------------------------------
vols = cfg_files;
vols.tag = 'vols';
vols.name = '3D Volumes';
vols.help = {'Select the volumes to concatenate'};
vols.filter = 'image';
vols.ufilter = '.*';
vols.num = [1 Inf];
%--------------------------------------------------------------------------
% dtype Data Type
%--------------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.help = {'Data-type of output image. SAME indicates the same datatype as the original images.'};
dtype.labels = {'SAME'
'UINT8 - unsigned char'
'INT16 - signed short'
'INT32 - signed int'
'FLOAT32 - single prec. float'
'FLOAT64 - double prec. float'}';
dtype.values = {0 spm_type('uint8') spm_type('int16') spm_type('int32') spm_type('float32') spm_type('float64')};
dtype.val = {spm_type('int16')}; % to match previous behaviour
%--------------------------------------------------------------------------
% name Output Filename
%--------------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Output Filename';
name.help = {'Specify the name of the output 4D volume file.'
'A ''.nii'' extension will be added if not specified.'}';
name.strtype = 's';
name.num = [1 Inf];
name.val = {'4D.nii'};
%--------------------------------------------------------------------------
% cat 3D to 4D File Conversion
%--------------------------------------------------------------------------
cat = cfg_exbranch;
cat.tag = 'cat';
cat.name = '3D to 4D File Conversion';
cat.val = {vols name dtype};
cat.help = {'Concatenate a number of 3D volumes into a single 4D file.'};
cat.prog = @spm_run_cat;
cat.vout = @vout;
%==========================================================================
function dep = vout(varargin)
% 4D output file will be saved in a struct with field .mergedfile
dep(1) = cfg_dep;
dep(1).sname = 'Concatenated 4D Volume';
dep(1).src_output = substruct('.','mergedfile');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_minc.m
|
.m
|
antx-master/xspm8/config/spm_cfg_minc.m
| 3,433 |
utf_8
|
db7b8cb0f154a59326a8d72eafdb6d94
|
function minc = spm_cfg_minc
% SPM Configuration file for MINC Import
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_minc.m 3691 2010-01-20 17:08:30Z guillaume $
rev = '$Rev: 3691 $';
% ---------------------------------------------------------------------
% data MINC files
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'MINC files';
data.help = {'Select the MINC files to convert.'};
data.filter = 'mnc';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% dtype Data Type
% ---------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.help = {'Data-type of output images. Note that the number of bits used determines the accuracy, and the amount of disk space needed.'};
dtype.labels = {
'UINT8 - unsigned char'
'INT16 - signed short'
'INT32 - signed int'
'FLOAT32 - single prec. float'
'FLOAT64 - double prec. float'
}';
dtype.values = {spm_type('uint8') spm_type('int16') spm_type('int32') ...
spm_type('float32') spm_type('float64')};
dtype.val = {spm_type('int16')};
% ---------------------------------------------------------------------
% ext Output image format
% ---------------------------------------------------------------------
ext = cfg_menu;
ext.tag = 'ext';
ext.name = 'Output image format';
ext.help = {'Output files can be written as .img + .hdr, or the two can be combined into a .nii file.'};
ext.labels = {
'Two file (img+hdr) NIfTI'
'Single file (nii) NIfTI'
}';
ext.values = {
'img'
'nii'
}';
ext.def = @(val)spm_get_defaults('images.format', val{:});
% ---------------------------------------------------------------------
% opts Options
% ---------------------------------------------------------------------
opts = cfg_branch;
opts.tag = 'opts';
opts.name = 'Options';
opts.val = {dtype ext };
opts.help = {'Conversion options'};
% ---------------------------------------------------------------------
% minc MINC Import
% ---------------------------------------------------------------------
minc = cfg_exbranch;
minc.tag = 'minc';
minc.name = 'MINC Import';
minc.val = {data opts };
minc.help = {'MINC Conversion. MINC is the image data format used for exchanging data within the ICBM community, and the format used by the MNI software tools. It is based on NetCDF, but due to be superceded by a new version relatively soon. MINC is no longer supported for reading images into SPM, so MINC files need to be converted to NIFTI format in order to use them. See http://www.bic.mni.mcgill.ca/software/ for more information.'};
minc.prog = @spm_run_minc;
minc.vout = @vout;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'Converted Images';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_tf_rescale.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_tf_rescale.m
| 6,005 |
utf_8
|
692deed1fb1ca3d56ae284ba0ae3850b
|
function S = spm_cfg_eeg_tf_rescale
% configuration file for rescaling spectrograms
%__________________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
% Will Penny
% $Id: spm_cfg_eeg_tf_rescale.m 4287 2011-04-04 13:55:54Z vladimir $
%--------------------------------------------------------------------------
% D
%--------------------------------------------------------------------------
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the M/EEG mat file.'};
%--------------------------------------------------------------------------
% Db
%--------------------------------------------------------------------------
Db = cfg_files;
Db.tag = 'Db';
Db.name = 'External baseline dataset';
Db.filter = 'mat';
Db.num = [0 1];
Db.val = {[]};
Db.help = {'Select the baseline M/EEG mat file. Leave empty to use the input dataset'};
%--------------------------------------------------------------------------
% Sbaseline
%--------------------------------------------------------------------------
Sbaseline = cfg_entry;
Sbaseline.tag = 'Sbaseline';
Sbaseline.name = 'Baseline';
Sbaseline.help = {'Start and stop of baseline [ms].'};
Sbaseline.strtype = 'e';
Sbaseline.num = [1 2];
%--------------------------------------------------------------------------
% baseline
%--------------------------------------------------------------------------
baseline = cfg_branch;
baseline.tag = 'baseline';
baseline.name = 'Baseline';
baseline.help = {'Baseline parameters.'};
baseline.val = {Sbaseline, Db};
%--------------------------------------------------------------------------
% method_logr
%--------------------------------------------------------------------------
method_logr = cfg_branch;
method_logr.tag = 'LogR';
method_logr.name = 'Log Ratio';
method_logr.val = {baseline};
method_logr.help = {'Log Ratio.'};
%--------------------------------------------------------------------------
% method_diff
%--------------------------------------------------------------------------
method_diff = cfg_branch;
method_diff.tag = 'Diff';
method_diff.name = 'Difference';
method_diff.val = {baseline};
method_diff.help = {'Difference.'};
%--------------------------------------------------------------------------
% method_rel
%--------------------------------------------------------------------------
method_rel = cfg_branch;
method_rel.tag = 'Rel';
method_rel.name = 'Relative';
method_rel.val = {baseline};
method_rel.help = {'Relative.'};
%--------------------------------------------------------------------------
% method_zscore
%--------------------------------------------------------------------------
method_zscore = cfg_branch;
method_zscore.tag = 'Zscore';
method_zscore.name = 'Zscore';
method_zscore.val = {baseline};
method_zscore.help = {'Z score'};
%--------------------------------------------------------------------------
% method_log
%--------------------------------------------------------------------------
method_log = cfg_const;
method_log.tag = 'Log';
method_log.name = 'Log';
method_log.val = {1};
method_log.help = {'Log.'};
%--------------------------------------------------------------------------
% method_sqrt
%--------------------------------------------------------------------------
method_sqrt = cfg_const;
method_sqrt.tag = 'Sqrt';
method_sqrt.name = 'Sqrt';
method_sqrt.val = {1};
method_sqrt.help = {'Square Root.'};
%--------------------------------------------------------------------------
% method
%--------------------------------------------------------------------------
method = cfg_choice;
method.tag = 'method';
method.name = 'Rescale method';
method.val = {method_logr};
method.help = {'Select the rescale method.'};
method.values = {method_logr method_diff method_rel method_zscore method_log method_sqrt};
%--------------------------------------------------------------------------
% S
%--------------------------------------------------------------------------
S = cfg_exbranch;
S.tag = 'rescale';
S.name = 'M/EEG Time-Frequency Rescale';
S.val = {D, method};
S.help = {'Rescale (avg) spectrogram with nonlinear and/or difference operator.'
'For ''Log'' and ''Sqrt'', these functions are applied to spectrogram.'
'For ''LogR'', ''Rel'' and ''Diff'' this function computes power in the baseline.'
'p_b and outputs:'
'(i) p-p_b for ''Diff'''
'(ii) 100*(p-p_b)/p_b for ''Rel'''
'(iii) log (p/p_b) for ''LogR'''}';
S.prog = @eeg_tf_rescale;
S.vout = @vout_eeg_tf_rescale;
S.modality = {'EEG'};
%==========================================================================
function out = eeg_tf_rescale(job)
% construct the S struct
S.D = job.D{1};
S.tf.method = fieldnames(job.method);
S.tf.method = S.tf.method{1};
switch lower(S.tf.method)
case {'logr','diff', 'rel', 'zscore'}
S.tf.Sbaseline = 1e-3*job.method.(S.tf.method).baseline.Sbaseline;
if ~(isempty(job.method.(S.tf.method).baseline.Db) || isequal(job.method.(S.tf.method).baseline.Db, {''}))
S.tf.Db = job.method.(S.tf.method).baseline.Db{1};
end
case {'log', 'sqrt'}
end
out.D = spm_eeg_tf_rescale(S);
out.Dfname = {fullfile(out.D.path,out.D.fname)};
%==========================================================================
function dep = vout_eeg_tf_rescale(job)
% return dependencies
dep(1) = cfg_dep;
dep(1).sname = 'Rescaled TF Data';
dep(1).src_output = substruct('.','D');
dep(1).tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Rescaled TF Datafile';
dep(2).src_output = substruct('.','Dfname');
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_fmri_data.m
|
.m
|
antx-master/xspm8/config/spm_cfg_fmri_data.m
| 3,059 |
utf_8
|
12045b3c567f606b6bfd8daba94e14d2
|
function fmri_data = spm_cfg_fmri_data
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_fmri_data.m 1517 2008-04-29 15:46:08Z volkmar $
rev = '$Rev: 1517 $';
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the fMRI scans for this session. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {'Select the SPM.mat file containing the specified design matrix.'};
spmmat.filter = 'mat';
spmmat.ufilter = '.*';
spmmat.num = [1 1];
% ---------------------------------------------------------------------
% mask Explicit mask
% ---------------------------------------------------------------------
mask = cfg_files;
mask.tag = 'mask';
mask.name = 'Explicit mask';
mask.val{1} = {''};
mask.help = {'Specify an image for explicitly masking the analysis. A sensible option here is to use a segmention of structural images to specify a within-brain mask. If you select that image as an explicit mask then only those voxels in the brain will be analysed. This both speeds the estimation and restricts SPMs/PPMs to within-brain voxels. Alternatively, if such structural images are unavailble or no masking is required, then leave this field empty.'};
mask.filter = 'image';
mask.ufilter = '.*';
mask.num = [0 1];
% ---------------------------------------------------------------------
% fmri_data fMRI data specification
% ---------------------------------------------------------------------
fmri_data = cfg_exbranch;
fmri_data.tag = 'fmri_data';
fmri_data.name = 'fMRI data specification';
fmri_data.val = {scans spmmat mask };
fmri_data.help = {'Select the data and optional explicit mask for a specified design'};
fmri_data.prog = @spm_run_fmri_data;
fmri_data.vout = @vout_stats;
fmri_data.modality = {'FMRI'};
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_movefile.m
|
.m
|
antx-master/xspm8/config/spm_cfg_movefile.m
| 2,964 |
utf_8
|
ed20756093eb13755fe0d764b20f3b79
|
function movefile = spm_cfg_movefile
% SPM Configuration file for 'move'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_movefile.m 4907 2012-09-06 19:33:21Z guillaume $
% ----------------------------------------------------------------------
% srcfiles Files to move
% ----------------------------------------------------------------------
srcfiles = cfg_files;
srcfiles.tag = 'srcfiles';
srcfiles.name = 'Files to move';
srcfiles.help = {'Select files to move.'};
srcfiles.filter = '.*';
srcfiles.ufilter = '.*';
srcfiles.num = [0 Inf];
% ----------------------------------------------------------------------
% targetdir Target directory
% ----------------------------------------------------------------------
targetdir = cfg_files;
targetdir.tag = 'targetdir';
targetdir.name = 'Target directory';
targetdir.help = {'Select target directory.'};
targetdir.filter = 'dir';
targetdir.ufilter = '.*';
targetdir.num = [1 1];
% ----------------------------------------------------------------------
% movefile Move Files (Deprecated)
% ----------------------------------------------------------------------
movefile = cfg_exbranch;
movefile.tag = 'movefile';
movefile.name = 'Move Files (DEPRECATED)';
movefile.val = {srcfiles targetdir };
movefile.help = {
'This module is DEPRECATED and has been moved to BasicIO.'
'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI.'
'Please switch to the BasicIO module instead.'
'This module will be REMOVED in the next major release of SPM.'
''
'This facility allows to move files in a batch. Note that moving files will not make them disappear from file selection lists.'
'Therefore one has to be careful not to select the original files after they have been programmed to be moved.'
'If image files (.*img or .*nii) are selected, corresponding hdr or mat files will be moved as well, if they exist.'
};
movefile.prog = @my_movefile;
movefile.hidden = true;
%=======================================================================
function my_movefile(varargin)
warning('"spm.util.movefile" is DEPRECATED and will be REMOVED in the next major release of SPM. Use BasicIO instead.');
job = varargin{1};
for k = 1:numel(job.srcfiles)
[p, n, e, v] = spm_fileparts(job.srcfiles{k});
if strncmp(e,'.img',4)||strncmp(e,'.nii',4)
try_movefile(fullfile(p,[n e]),job.targetdir{1});
try_movefile(fullfile(p,[n '.mat']),job.targetdir{1});
try_movefile(fullfile(p,[n '.hdr']),job.targetdir{1});
else
try_movefile(job.srcfiles{k},job.targetdir{1});
end
end
%=======================================================================
function try_movefile(src,dest)
% silently try to move files
try
movefile(src,dest);
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_fmri_spec.m
|
.m
|
antx-master/xspm8/config/spm_cfg_fmri_spec.m
| 41,739 |
utf_8
|
34ff7beb83f6e1476649d3ad6cd9fca6
|
function fmri_spec = spm_cfg_fmri_spec
% SPM Configuration file for fMRI model specification
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_fmri_spec.m 3691 2010-01-20 17:08:30Z guillaume $
rev = '$Rev: 3691 $';
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% units Units for design
% ---------------------------------------------------------------------
units = cfg_menu;
units.tag = 'units';
units.name = 'Units for design';
units.help = {'The onsets of events or blocks can be specified in either scans or seconds.'};
units.labels = {
'Scans'
'Seconds'
}';
units.values = {
'scans'
'secs'
}';
% ---------------------------------------------------------------------
% RT Interscan interval
% ---------------------------------------------------------------------
RT = cfg_entry;
RT.tag = 'RT';
RT.name = 'Interscan interval';
RT.help = {'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume and the same plane in the next volume. It is assumed to be constant throughout.'};
RT.strtype = 'e';
RT.num = [1 1];
% ---------------------------------------------------------------------
% fmri_t Microtime resolution
% ---------------------------------------------------------------------
fmri_t = cfg_entry;
fmri_t.tag = 'fmri_t';
fmri_t.name = 'Microtime resolution';
fmri_t.help = {
'The microtime resolution, t, is the number of time-bins per scan used when building regressors. '
''
'Do not change this parameter unless you have a long TR and wish to shift regressors so that they are aligned to a particular slice. '
}';
fmri_t.strtype = 'e';
fmri_t.num = [1 1];
fmri_t.def = @(val)spm_get_defaults('stats.fmri.fmri_t', val{:});
% ---------------------------------------------------------------------
% fmri_t0 Microtime onset
% ---------------------------------------------------------------------
fmri_t0 = cfg_entry;
fmri_t0.tag = 'fmri_t0';
fmri_t0.name = 'Microtime onset';
fmri_t0.help = {
'The microtime onset, t0, is the first time-bin at which the regressors are resampled to coincide with data acquisition. If t0 = 1 then the regressors will be appropriate for the first slice. If you want to temporally realign the regressors so that they match responses in the middle slice then make t0 = t/2 (assuming there is a negligible gap between volume acquisitions). '
''
'Do not change the default setting unless you have a long TR. '
}';
fmri_t0.strtype = 'e';
fmri_t0.num = [1 1];
fmri_t0.def = @(val)spm_get_defaults('stats.fmri.fmri_t0', val{:});
% ---------------------------------------------------------------------
% timing Timing parameters
% ---------------------------------------------------------------------
timing = cfg_branch;
timing.tag = 'timing';
timing.name = 'Timing parameters';
timing.val = {units RT fmri_t fmri_t0 };
timing.help = {
'Specify various timing parameters needed to construct the design matrix. This includes the units of the design specification and the interscan interval.'
''
'Also, with longs TRs you may want to shift the regressors so that they are aligned to a particular slice. This is effected by changing the microtime resolution and onset. '
}';
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the fMRI scans for this session. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Condition Name'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% onset Onsets
% ---------------------------------------------------------------------
onset = cfg_entry;
onset.tag = 'onset';
onset.name = 'Onsets';
onset.help = {'Specify a vector of onset times for this condition type. '};
onset.strtype = 'e';
onset.num = [Inf 1];
% ---------------------------------------------------------------------
% duration Durations
% ---------------------------------------------------------------------
duration = cfg_entry;
duration.tag = 'duration';
duration.name = 'Durations';
duration.help = {'Specify the event durations. Epoch and event-related responses are modeled in exactly the same way but by specifying their different durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration. If you have multiple different durations, then the number must match the number of onset times.'};
duration.strtype = 'e';
duration.num = [Inf 1];
% ---------------------------------------------------------------------
% tmod Time Modulation
% ---------------------------------------------------------------------
tmod = cfg_menu;
tmod.tag = 'tmod';
tmod.name = 'Time Modulation';
tmod.help = {
'This option allows for the characterisation of linear or nonlinear time effects. For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over time. Higher order modulation will introduce further columns that contain the stick functions scaled by time squared, time cubed etc.'
''
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
tmod.labels = {
'No Time Modulation'
'1st order Time Modulation'
'2nd order Time Modulation'
'3rd order Time Modulation'
'4th order Time Modulation'
'5th order Time Modulation'
'6th order Time Modulation'
}';
tmod.values = {0 1 2 3 4 5 6};
tmod.val = {0};
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name1 = cfg_entry;
name1.tag = 'name';
name1.name = 'Name';
name1.help = {'Enter a name for this parameter.'};
name1.strtype = 's';
name1.num = [1 Inf];
% ---------------------------------------------------------------------
% param Values
% ---------------------------------------------------------------------
param = cfg_entry;
param.tag = 'param';
param.name = 'Values';
param.help = {'Enter a vector of values, one for each occurence of the event.'};
param.strtype = 'e';
param.num = [Inf 1];
% ---------------------------------------------------------------------
% poly Polynomial Expansion
% ---------------------------------------------------------------------
poly = cfg_menu;
poly.tag = 'poly';
poly.name = 'Polynomial Expansion';
poly.help = {'For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over different values of the parameter. Higher order modulation will introduce further columns that contain the stick functions scaled by parameter squared, cubed etc.'};
poly.labels = {
'1st order'
'2nd order'
'3rd order'
'4th order'
'5th order'
'6th order'
}';
poly.values = {1 2 3 4 5 6};
% ---------------------------------------------------------------------
% pmod Parameter
% ---------------------------------------------------------------------
pmod = cfg_branch;
pmod.tag = 'pmod';
pmod.name = 'Parameter';
pmod.val = {name1 param poly };
pmod.help = {
'Model interractions with user specified parameters. This allows nonlinear effects relating to some other measure to be modelled in the design matrix.'
''
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
% ---------------------------------------------------------------------
% generic Parametric Modulations
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Parametric Modulations';
generic2.help = {'The stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate. The events can be modulated by zero or more parameters.'};
generic2.values = {pmod };
generic2.num = [0 Inf];
% ---------------------------------------------------------------------
% cond Condition
% ---------------------------------------------------------------------
cond = cfg_branch;
cond.tag = 'cond';
cond.name = 'Condition';
cond.val = {name onset duration tmod generic2 };
cond.check = @cond_check;
cond.help = {'An array of input functions is contructed, specifying occurrence events or epochs (or both). These are convolved with a basis set at a later stage to give regressors that enter into the design matrix. Interactions of evoked responses with some parameter (time or a specified variate) enter at this stage as additional columns in the design matrix with each trial multiplied by the [expansion of the] trial-specific parameter. The 0th order expansion is simply the main effect in the first column.'};
% ---------------------------------------------------------------------
% generic Conditions
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Conditions';
generic1.help = {'You are allowed to combine both event- and epoch-related responses in the same model and/or regressor. Any number of condition (event or epoch) types can be specified. Epoch and event-related responses are modeled in exactly the same way by specifying their onsets [in terms of onset times] and their durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration.For factorial designs, one can later associate these experimental conditions with the appropriate levels of experimental factors. '};
generic1.values = {cond };
generic1.num = [0 Inf];
% ---------------------------------------------------------------------
% multi Multiple conditions
% ---------------------------------------------------------------------
multi = cfg_files;
multi.tag = 'multi';
multi.name = 'Multiple conditions';
multi.val{1} = {''};
multi.help = {
'Select the *.mat file containing details of your multiple experimental conditions. '
''
'If you have multiple conditions then entering the details a condition at a time is very inefficient. This option can be used to load all the required information in one go. You will first need to create a *.mat file containing the relevant information. '
''
'This *.mat file must include the following cell arrays (each 1 x n): names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], durations{2}=[0 0 0 0], contain the required details of the second condition. These cell arrays may be made available by your stimulus delivery program, eg. COGENT. The duration vectors can contain a single entry if the durations are identical for all events.'
''
'Time and Parametric effects can also be included. For time modulation include a cell array (1 x n) called tmod. It should have a have a single number in each cell. Unused cells may contain either a 0 or be left empty. The number specifies the order of time modulation from 0 = No Time Modulation to 6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition by a linear time effect.'
''
'For parametric modulation include a structure array, which is up to 1 x n in size, called pmod. n must be less than or equal to the number of cells in the names/onsets/durations cell arrays. The structure array pmod must have the fields: name, param and poly. Each of these fields is in turn a cell array to allow the inclusion of one or more parametric effects per column of the design. The field name must be a cell array containing strings. The field param is a cell array containing a vector of parameters. Remember each parameter must be the same length as its corresponding onsets vector. The field poly is a cell array (for consistency) with each cell containing a single number specifying the order of the polynomial expansion from 1 to 6.'
''
'Note that each condition is assigned its corresponding entry in the structure array (condition 1 parametric modulators are in pmod(1), condition 2 parametric modulators are in pmod(2), etc. Within a condition multiple parametric modulators are accessed via each fields cell arrays. So for condition 1, parametric modulator 1 would be defined in pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, then remember the first modulator for that condition is in cell array 1: pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not all conditions are parametrically modulated, then the non-modulated indices in the pmod structure can be left blank. For example, if conditions 1 and 3 but not condition 2 are modulated, then specify pmod(1) and pmod(3). Similarly, if conditions 1 and 2 are modulated but there are 3 conditions overall, it is only necessary for pmod to be a 1 x 2 structure array.'
''
'EXAMPLE:'
'Make an empty pmod structure: '
' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'
'Specify one parametric regressor for the first condition: '
' pmod(1).name{1} = ''regressor1'';'
' pmod(1).param{1} = [1 2 4 5 6];'
' pmod(1).poly{1} = 1;'
'Specify 2 parametric regressors for the second condition: '
' pmod(2).name{1} = ''regressor2-1'';'
' pmod(2).param{1} = [1 3 5 7]; '
' pmod(2).poly{1} = 1;'
' pmod(2).name{2} = ''regressor2-2'';'
' pmod(2).param{2} = [2 4 6 8 10];'
' pmod(2).poly{2} = 1;'
''
'The parametric modulator should be mean corrected if appropriate. Unused structure entries should have all fields left empty.'
}';
multi.filter = 'mat';
multi.ufilter = '.*';
multi.num = [0 1];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Enter name of regressor eg. First movement parameter'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% val Value
% ---------------------------------------------------------------------
val = cfg_entry;
val.tag = 'val';
val.name = 'Value';
val.help = {'Enter the vector of regressor values'};
val.strtype = 'e';
val.num = [Inf 1];
% ---------------------------------------------------------------------
% regress Regressor
% ---------------------------------------------------------------------
regress = cfg_branch;
regress.tag = 'regress';
regress.name = 'Regressor';
regress.val = {name val };
regress.help = {'regressor'};
% ---------------------------------------------------------------------
% generic Regressors
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Regressors';
generic2.help = {'Regressors are additional columns included in the design matrix, which may model effects that would not be convolved with the haemodynamic response. One such example would be the estimated movement parameters, which may confound the data.'};
generic2.values = {regress };
generic2.num = [0 Inf];
% ---------------------------------------------------------------------
% multi_reg Multiple regressors
% ---------------------------------------------------------------------
multi_reg = cfg_files;
multi_reg.tag = 'multi_reg';
multi_reg.name = 'Multiple regressors';
multi_reg.val{1} = {''};
multi_reg.help = {
'Select the *.mat/*.txt file containing details of your multiple regressors. '
''
'If you have multiple regressors eg. realignment parameters, then entering the details a regressor at a time is very inefficient. This option can be used to load all the required information in one go. '
''
'You will first need to create a *.mat file containing a matrix R or a *.txt file containing the regressors. Each column of R will contain a different regressor. When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'
}';
multi_reg.filter = 'mat';
multi_reg.ufilter = '.*';
multi_reg.num = [0 1];
% ---------------------------------------------------------------------
% hpf High-pass filter
% ---------------------------------------------------------------------
hpf = cfg_entry;
hpf.tag = 'hpf';
hpf.name = 'High-pass filter';
hpf.help = {'The default high-pass filter cutoff is 128 seconds.Slow signal drifts with a period longer than this will be removed. Use ''explore design'' to ensure this cut-off is not removing too much experimental variance. High-pass filtering is implemented using a residual forming matrix (i.e. it is not a convolution) and is simply to a way to remove confounds without estimating their parameters explicitly. The constant term is also incorporated into this filter matrix.'};
hpf.strtype = 'e';
hpf.num = [1 1];
hpf.def = @(val)spm_get_defaults('stats.fmri.hpf', val{:});
% ---------------------------------------------------------------------
% sess Subject/Session
% ---------------------------------------------------------------------
sess = cfg_branch;
sess.tag = 'sess';
sess.name = 'Subject/Session';
sess.val = {scans generic1 multi generic2 multi_reg hpf };
sess.check = @sess_check;
sess.help = {'The design matrix for fMRI data consists of one or more separable, session-specific partitions. These partitions are usually either one per subject, or one per fMRI scanning session for that subject.'};
% ---------------------------------------------------------------------
% generic Data & Design
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data & Design';
generic.help = {
'The design matrix defines the experimental design and the nature of hypothesis testing to be implemented. The design matrix has one row for each scan and one column for each effect or explanatory variable. (e.g. regressor or stimulus function). '
''
'This allows you to build design matrices with separable session-specific partitions. Each partition may be the same (in which case it is only necessary to specify it once) or different. Responses can be either event- or epoch related, where the latter model involves prolonged and possibly time-varying responses to state-related changes in experimental conditions. Event-related response are modelled in terms of responses to instantaneous events. Mathematically they are both modelled by convolving a series of delta (stick) or box-car functions, encoding the input or stimulus function. with a set of hemodynamic basis functions.'
}';
generic.values = {sess };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of factor, eg. ''Repetition'' '};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% levels Levels
% ---------------------------------------------------------------------
levels = cfg_entry;
levels.tag = 'levels';
levels.name = 'Levels';
levels.help = {'Enter number of levels for this factor, eg. 2'};
levels.strtype = 'e';
levels.num = [Inf 1];
% ---------------------------------------------------------------------
% fact Factor
% ---------------------------------------------------------------------
fact = cfg_branch;
fact.tag = 'fact';
fact.name = 'Factor';
fact.val = {name levels };
fact.help = {'Add a new factor to your experimental design'};
% ---------------------------------------------------------------------
% generic Factorial design
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Factorial design';
generic1.help = {
'If you have a factorial design then SPM can automatically generate the contrasts necessary to test for the main effects and interactions. '
''
'This includes the F-contrasts necessary to test for these effects at the within-subject level (first level) and the simple contrasts necessary to generate the contrast images for a between-subject (second-level) analysis.'
''
'To use this option, create as many factors as you need and provide a name and number of levels for each. SPM assumes that the condition numbers of the first factor change slowest, the second factor next slowest etc. It is best to write down the contingency table for your design to ensure this condition is met. This table relates the levels of each factor to the conditions. '
''
'For example, if you have 2-by-3 design your contingency table has two rows and three columns where the the first factor spans the rows, and the second factor the columns. The numbers of the conditions are 1,2,3 for the first row and 4,5,6 for the second. '
}';
generic1.values = {fact };
generic1.num = [0 Inf];
% ---------------------------------------------------------------------
% derivs Model derivatives
% ---------------------------------------------------------------------
derivs = cfg_menu;
derivs.tag = 'derivs';
derivs.name = 'Model derivatives';
derivs.help = {'Model HRF Derivatives. The canonical HRF combined with time and dispersion derivatives comprise an ''informed'' basis set, as the shape of the canonical response conforms to the hemodynamic response that is commonly observed. The incorporation of the derivate terms allow for variations in subject-to-subject and voxel-to-voxel responses. The time derivative allows the peak response to vary by plus or minus a second and the dispersion derivative allows the width of the response to vary. The informed basis set requires an SPM{F} for inference. T-contrasts over just the canonical are perfectly valid but assume constant delay/dispersion. The informed basis set compares favourably with eg. FIR bases on many data sets. '};
derivs.labels = {
'No derivatives'
'Time derivatives'
'Time and Dispersion derivatives'
}';
derivs.values = {[0 0] [1 0] [1 1]};
derivs.val = {[0 0]};
% ---------------------------------------------------------------------
% hrf Canonical HRF
% ---------------------------------------------------------------------
hrf = cfg_branch;
hrf.tag = 'hrf';
hrf.name = 'Canonical HRF';
hrf.val = {derivs };
hrf.help = {'Canonical Hemodynamic Response Function. This is the default option. Contrasts of these effects have a physical interpretation and represent a parsimonious way of characterising event-related responses. This option is also useful if you wish to look separately at activations and deactivations (this is implemented using a t-contrast with a +1 or -1 entry over the canonical regressor). '};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fourier Fourier Set
% ---------------------------------------------------------------------
fourier = cfg_branch;
fourier.tag = 'fourier';
fourier.name = 'Fourier Set';
fourier.val = {length order };
fourier.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fourier_han Fourier Set (Hanning)
% ---------------------------------------------------------------------
fourier_han = cfg_branch;
fourier_han.tag = 'fourier_han';
fourier_han.name = 'Fourier Set (Hanning)';
fourier_han.val = {length order };
fourier_han.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% gamma Gamma Functions
% ---------------------------------------------------------------------
gamma = cfg_branch;
gamma.tag = 'gamma';
gamma.name = 'Gamma Functions';
gamma.val = {length order };
gamma.help = {'Gamma basis functions - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fir Finite Impulse Response
% ---------------------------------------------------------------------
fir = cfg_branch;
fir.tag = 'fir';
fir.name = 'Finite Impulse Response';
fir.val = {length order };
fir.help = {'Finite impulse response - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% bases Basis Functions
% ---------------------------------------------------------------------
bases = cfg_choice;
bases.tag = 'bases';
bases.name = 'Basis Functions';
bases.val = {hrf };
bases.help = {'The most common choice of basis function is the Canonical HRF with or without time and dispersion derivatives. '};
bases.values = {hrf fourier fourier_han gamma fir };
% ---------------------------------------------------------------------
% volt Model Interactions (Volterra)
% ---------------------------------------------------------------------
volt = cfg_menu;
volt.tag = 'volt';
volt.name = 'Model Interactions (Volterra)';
volt.help = {
'Generalized convolution of inputs (U) with basis set (bf).'
''
'For first order expansions the causes are simply convolved (e.g. stick functions) in U.u by the basis functions in bf to create a design matrix X. For second order expansions new entries appear in ind, bf and name that correspond to the interaction among the orginal causes. The basis functions for these efects are two dimensional and are used to assemble the second order kernel. Second order effects are computed for only the first column of U.u.'
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
volt.labels = {
'Do not model Interactions'
'Model Interactions'
}';
volt.values = {1 2};
volt.val = {1};
% ---------------------------------------------------------------------
% global Global normalisation
% ---------------------------------------------------------------------
xGlobal = cfg_menu;
xGlobal.tag = 'global';
xGlobal.name = 'Global normalisation';
xGlobal.help = {'Global intensity normalisation'};
xGlobal.labels = {
'Scaling'
'None'
}';
xGlobal.values = {
'Scaling'
'None'
}';
xGlobal.val = {'None'};
% ---------------------------------------------------------------------
% mask Explicit mask
% ---------------------------------------------------------------------
mask = cfg_files;
mask.tag = 'mask';
mask.name = 'Explicit mask';
mask.val{1} = {''};
mask.help = {'Specify an image for explicitly masking the analysis. A sensible option here is to use a segmention of structural images to specify a within-brain mask. If you select that image as an explicit mask then only those voxels in the brain will be analysed. This both speeds the estimation and restricts SPMs/PPMs to within-brain voxels. Alternatively, if such structural images are unavailble or no masking is required, then leave this field empty.'};
mask.filter = 'image';
mask.ufilter = '.*';
mask.num = [0 1];
% ---------------------------------------------------------------------
% cvi Serial correlations
% ---------------------------------------------------------------------
cvi = cfg_menu;
cvi.tag = 'cvi';
cvi.name = 'Serial correlations';
cvi.help = {
'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled neuronal activity can be accounted for using an autoregressive AR(1) model during Classical (ReML) parameter estimation. '
''
'This estimate assumes the same correlation structure for each voxel, within each session. ReML estimates are then used to correct for non-sphericity during inference by adjusting the statistics and degrees of freedom appropriately. The discrepancy between estimated and actual intrinsic (i.e. prior to filtering) correlations are greatest at low frequencies. Therefore specification of the high-pass filter is particularly important. '
''
'Serial correlation can be ignored if you choose the ''none'' option. Note that the above options only apply if you later specify that your model will be estimated using the Classical (ReML) approach. If you choose Bayesian estimation these options will be ignored. For Bayesian estimation, the choice of noisemodel (AR model order) is made under the estimation options. '
}';
cvi.labels = {
'none'
'AR(1)'
}';
cvi.values = {
'none'
'AR(1)'
}';
cvi.def = @(val)spm_get_defaults('stats.fmri.cvi', val{:});
% ---------------------------------------------------------------------
% fmri_spec fMRI model specification
% ---------------------------------------------------------------------
fmri_spec = cfg_exbranch;
fmri_spec.tag = 'fmri_spec';
fmri_spec.name = 'fMRI model specification';
fmri_spec.val = {dir timing generic generic1 bases volt xGlobal mask cvi };
fmri_spec.help = {
'Statistical analysis of fMRI data uses a mass-univariate approach based on General Linear Models (GLMs). It comprises the following steps (1) specification of the GLM design matrix, fMRI data files and filtering (2) estimation of GLM paramaters using classical or Bayesian approaches and (3) interrogation of results using contrast vectors to produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).'
''
'The design matrix defines the experimental design and the nature of hypothesis testing to be implemented. The design matrix has one row for each scan and one column for each effect or explanatory variable. (eg. regressor or stimulus function). You can build design matrices with separable session-specific partitions. Each partition may be the same (in which case it is only necessary to specify it once) or different. '
''
'Responses can be either event- or epoch related, the only distinction is the duration of the underlying input or stimulus function. Mathematically they are both modeled by convolving a series of delta (stick) or box functions (u), indicating the onset of an event or epoch with a set of basis functions. These basis functions model the hemodynamic convolution, applied by the brain, to the inputs. This convolution can be first-order or a generalized convolution modeled to second order (if you specify the Volterra option). The same inputs are used by the Hemodynamic model or Dynamic Causal Models which model the convolution explicitly in terms of hidden state variables. '
''
'Basis functions can be used to plot estimated responses to single events once the parameters (i.e. basis function coefficients) have been estimated. The importance of basis functions is that they provide a graceful transition between simple fixed response models (like the box-car) and finite impulse response (FIR) models, where there is one basis function for each scan following an event or epoch onset. The nice thing about basis functions, compared to FIR models, is that data sampling and stimulus presentation does not have to be synchronized thereby allowing a uniform and unbiased sampling of peri-stimulus time.'
''
'Event-related designs may be stochastic or deterministic. Stochastic designs involve one of a number of trial-types occurring with a specified probability at successive intervals in time. These probabilities can be fixed (stationary designs) or time-dependent (modulated or non-stationary designs). The most efficient designs obtain when the probabilities of every trial type are equal. A critical issue in stochastic designs is whether to include null events If you wish to estimate the evoked response to a specific event type (as opposed to differential responses) then a null event must be included (even if it is not modeled explicitly).'
''
'In SPM, analysis of data from multiple subjects typically proceeds in two stages using models at two ''levels''. The ''first level'' models are used to implement a within-subject analysis. Typically there will be as many first level models as there are subjects. Analysis proceeds as described using the ''Specify first level'' and ''Estimate'' options. The results of these analyses can then be presented as ''case studies''. More often, however, one wishes to make inferences about the population from which the subjects were drawn. This is an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' approach where contrast images from each subject are used as summary measures of subject responses. These are then entered as data into a ''second level'' model. '
}';
fmri_spec.prog = @spm_run_fmri_spec;
fmri_spec.vout = @vout_stats;
fmri_spec.modality = {'FMRI'};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function t = cond_check(job)
t = {};
if (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),
t = {sprintf('"%s": Number of event onsets (%d) does not match the number of durations (%d).',...
job.name, numel(job.onset),numel(job.duration))};
end;
for i=1:numel(job.pmod),
if numel(job.onset) ~= numel(job.pmod(i).param),
t = {t{:}, sprintf('"%s" & "%s":Number of event onsets (%d) does not equal the number of parameters (%d).',...
job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = sess_check(sess)
t = {};
for i=1:numel(sess.regress),
if numel(sess.scans) ~= numel(sess.regress(i).val),
t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.scans),i,numel(sess.regress(i).val))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_bms.m
|
.m
|
antx-master/xspm8/config/spm_cfg_bms.m
| 26,212 |
utf_8
|
e9c005333a71f641ae7d9147b7144d8d
|
function bms = spm_cfg_bms
% Configuration file for BMS interface.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Maria Joao Rosa
% $Id: spm_cfg_bms.m 3955 2010-06-29 17:26:29Z maria $
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {['Select the directory where the files containing the '...
'results from BMS (BMS.mat) will be written.']};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% mod_dcm Models (.mat)
% ---------------------------------------------------------------------
mod_dcm = cfg_files;
mod_dcm.tag = 'mod_dcm';
mod_dcm.name = 'Models';
mod_dcm.help = {['Select the DCM file (.mat) for each model. '...
'DCM.mat files (models) should be specified '...
'in the same order for each subject and session.']};
mod_dcm.filter = 'mat';
mod_dcm.ufilter = '.*';
mod_dcm.num = [0 Inf];
% ---------------------------------------------------------------------
% sess_dcm Sessions
% ---------------------------------------------------------------------
sess_dcm = cfg_branch;
sess_dcm.tag = 'sess_dcm';
sess_dcm.name = 'Session';
sess_dcm.val = {mod_dcm };
% ---------------------------------------------------------------------
% subj_dcm Subject
% ---------------------------------------------------------------------
subj_dcm = cfg_repeat;
subj_dcm.tag = 'subj_dcm';
subj_dcm.name = 'Subject';
subj_dcm.values = {sess_dcm };
% ---------------------------------------------------------------------
% dcm Data
% ---------------------------------------------------------------------
dcm = cfg_repeat;
dcm.tag = 'dcm';
dcm.name = 'Data';
dcm.help = {['Select DCM file (.mat) for each model, session and '...
'subject.']}';
dcm.values = {subj_dcm };
dcm.num = [0 Inf];
% ---------------------------------------------------------------------
% mod_map Models (.img)
% ---------------------------------------------------------------------
mod_map = cfg_files;
mod_map.tag = 'mod_map';
mod_map.name = 'Models';
mod_map.help = {['Specify the log. evidence map (.img) for each model. '...
'Log-evidence maps should be specified '...
'in the same order for each subject and session.']};
mod_map.filter = 'image';
mod_map.ufilter = '.*';
mod_map.num = [1 Inf];
% ---------------------------------------------------------------------
% sess_map Sessions (Maps)
% ---------------------------------------------------------------------
sess_map = cfg_branch;
sess_map.tag = 'sess_map';
sess_map.name = 'Session';
sess_map.val = {mod_map };
% ---------------------------------------------------------------------
% subj_dcm Subject (Maps)
% ---------------------------------------------------------------------
subj_map = cfg_repeat;
subj_map.tag = 'subj_map';
subj_map.name = 'Subject';
subj_map.values = {sess_map };
% ---------------------------------------------------------------------
% map Data
% ---------------------------------------------------------------------
map = cfg_repeat;
map.tag = 'map';
map.name = 'Data';
map.help = {['Select the log. evidence maps (.img) for each '...
'model, session and subject.']}';
map.values = {subj_map };
map.num = [1 Inf];
% ---------------------------------------------------------------------
% mod_name Name
% ---------------------------------------------------------------------
mod_name = cfg_entry;
mod_name.tag = 'mod_name';
mod_name.name = 'Name';
mod_name.help = {'Specify name for each model (optional).'};
mod_name.strtype = 's';
mod_name.num = [0 Inf];
mod_name.val = {''};
% ---------------------------------------------------------------------
% name_mod Name models
% ---------------------------------------------------------------------
name_mod = cfg_repeat;
name_mod.tag = 'name_mod';
name_mod.name = 'Name models';
name_mod.help = {'Specify name for each model (optional).'}';
name_mod.values = {mod_name };
name_mod.num = [0 Inf];
% ---------------------------------------------------------------------
% model_sp Load model space
% ---------------------------------------------------------------------
model_sp = cfg_files;
model_sp.tag = 'model_sp';
model_sp.name = 'Load model space';
model_sp.help = {['Optional: load .mat file with all subjects, sessions '...
'and models. This option is a faster alternative to selecting '...
'the DCM.mat files for each subject/model (above in '...
'''Data'').']
['This file is created if the ''Data'' option has been used. '...
'It is saved in the same directory as BMS.mat and can then be loaded '...
'for future BMS/BMA analyses with the same data.']
['The model space file should contain the structure ''subj''. ' ...
'This structure should have the field ''sess'' for sessions, '...
'then the subfield ''model'' and in ''model'' there should be '...
'five subfields: ''fname'' contains the path to the DCM.mat file, '...
'''.F'' the Free Energy of that model, '...
'''.Ep'' and ''Cp'' the mean and covariance of the parameters estimates. '...
'Finally the subfield ''.nonLin'' should be 1 if the model is non-linear and '...
'0 otherwise.']
['Example: subj(3).sess(1).model(4).fname contains the path to the DCM.mat '...
'file for subject 3, session 1 and model 4. subj(3).sess(1).model(4).F '...
'contains the value of the Free Energy for the same model/session/subject.']};
model_sp.filter = 'mat';
model_sp.ufilter = '.*';
model_sp.val = {{''}};
model_sp.num = [0 1];
% ---------------------------------------------------------------------
% load_f Log-evidence matrix
% ---------------------------------------------------------------------
load_f = cfg_files;
load_f.tag = 'load_f';
load_f.name = 'Log-evidence matrix';
load_f.help = {['Optional: load .mat file with log-evidence values for '...
'comparison. This option is a faster alternative to selecting '...
'the DCM.mat files for each subject/model (above in '...
'''Data'') but it does not allow for Bayesian Model Averaging. '...
'To compute BMA the user needs to specify the DCM.mat files '...
'or the model space. ']
['This file should contain an F matrix consisting ' ...
'of [s x m] log-evidence values, where s is the number '...
'of subjects and m the number of models.']};
load_f.filter = 'mat';
load_f.ufilter = '.*';
load_f.val = {{''}};
load_f.num = [0 1];
% ---------------------------------------------------------------------
% method Inference Method
% ---------------------------------------------------------------------
method = cfg_menu;
method.tag = 'method';
method.name = 'Inference method';
method.help = {['Specify inference method: random effects '...
'(2nd-level, RFX) or fixed effects (1st-level, FFX) analysis. '...
'RFX uses Gibbs sampling.']};
method.labels = {
'Fixed effects (FFX)'
'Random effects (RFX)'
}';
method.values = {
'FFX'
'RFX'
}';
% ---------------------------------------------------------------------
% method_maps Inference Method (maps)
% ---------------------------------------------------------------------
method_maps = cfg_menu;
method_maps.tag = 'method_maps';
method_maps.name = 'Inference method';
method_maps.help = {['Specify inference method: random effects '...
'(2nd-level, RFX) or fixed effects (1st-level, FFX) analysis. '...
'RFX uses a Variational Bayes approach.']};
method_maps.labels = {
'Fixed effects (FFX)'
'Random effects (RFX)'
}';
method_maps.values = {
'FFX'
'RFX'
}';
% % ---------------------------------------------------------------------
% % priors Priors
% % ---------------------------------------------------------------------
% priors = cfg_menu;
% priors.tag = 'priors';
% priors.name = 'Priors';
% priors.help = {['Specify priors for family-level inference (RFX only).
% '...
% 'Options: ''Family'' sets alpha0=1 for each family '...
% 'while ''Model'' sets alpha0=1 for each model (not '...
% 'advised).']};
% priors.labels = {
% 'Model'
% 'Family'
% }';
% priors.values = {
% 'M-unity'
% 'F-unity'
% }';
% priors.val = {'F-unity'};
% ---------------------------------------------------------------------
% family_file Family file
% ---------------------------------------------------------------------
family_file = cfg_files;
family_file.tag = 'family_file';
family_file.name = 'Load family';
family_file.help = {['Load family.mat file. This file should contain the '...
'structure ''family'' with fields ''names'' and '...
'''partition''. Example: family.names = {''F1'', '...
'''F2''} and family.partition = [1 2 2 1 1]. '...
' This structure specifies two families with names '...
'''F1'' and ''F2'' and assigns model 1, 4 and 5 to '...
'the first family and models 2 and 3 to the second '...
'family.']};
family_file.val{1} = {''};
family_file.filter = 'mat';
family_file.ufilter = '.*';
family_file.num = [0 1];
% ---------------------------------------------------------------------
% family_name Family name
% ---------------------------------------------------------------------
family_name = cfg_entry;
family_name.tag = 'family_name';
family_name.name = 'Name';
family_name.help = {'Specify name for family.'};
family_name.strtype = 's';
family_name.num = [0 Inf];
% ---------------------------------------------------------------------
% family_models family_models
% ---------------------------------------------------------------------
family_models = cfg_entry;
family_models.tag = 'family_models';
family_models.name = 'Models';
family_models.help = {['Specify models belonging to this family. '...
'Example: write ''2 6'' if the second and sixth model '...
'belong to this family.']};
family_models.strtype = 'e';
family_models.num = [Inf 1];
% ---------------------------------------------------------------------
% family Family
% ---------------------------------------------------------------------
family = cfg_branch;
family.tag = 'family';
family.name = 'Family';
family.val = {family_name family_models };
family.help = {'Specify family name and models.'};
% ---------------------------------------------------------------------
% select_family Specify family
% ---------------------------------------------------------------------
select_family = cfg_repeat;
select_family.tag = 'select_family';
select_family.name = 'Construct family';
select_family.values = {family };
select_family.help = {'Create family. Specify family name and models.'};
% ---------------------------------------------------------------------
% family_level Specify families
% ---------------------------------------------------------------------
family_level = cfg_choice;
family_level.tag = 'family_level';
family_level.name = 'Family inference';
family_level.help = {['Optional field to perform family level inference.'...
'Options: load family.mat '...
'or specify family names and models using '...
'the interface.']};
family_level.val = {family_file };
family_level.values = {family_file select_family };
% ---------------------------------------------------------------------
% bma_part Choose family
% ---------------------------------------------------------------------
bma_part = cfg_entry;
bma_part.tag = 'bma_part';
bma_part.name = 'Enter family';
bma_part.help = {['Specify family (integer). E.g. ''2'' for the second '...
'family to use in BMA. ']};
bma_part.strtype = 'e';
bma_part.num = [0 Inf];
% ---------------------------------------------------------------------
% bma_no no
% ---------------------------------------------------------------------
bma_all = cfg_const;
bma_all.tag = 'bma_all';
bma_all.name = 'All families';
bma_all.val = {'famwin'};
bma_all.help = {'Use all families for Bayesian Model Averaging (BMA).'}';
% ---------------------------------------------------------------------
% bma_no no
% ---------------------------------------------------------------------
bma_famwin = cfg_const;
bma_famwin.tag = 'bma_famwin';
bma_famwin.name = 'Winning family';
bma_famwin.val = {'fanwin'};
bma_famwin.help = {'Use winning family for Bayesian Model Averaging (BMA).'}';
% ---------------------------------------------------------------------
% bma_no no
% ---------------------------------------------------------------------
bma_no = cfg_const;
bma_no.tag = 'bma_no';
bma_no.name = 'Do not compute';
bma_no.val = {0};
bma_no.help = {'Do not compute Bayesian Model Averaging (BMA).'}';
% ---------------------------------------------------------------------
% bma_yes BMA set
% ---------------------------------------------------------------------
bma_yes = cfg_choice;
bma_yes.tag = 'bma_yes';
bma_yes.name = 'Choose family';
bma_yes.help = {['Specify family for Bayesian Model Averaging (BMA). '...
'Options: ''winning family'', ''enter family'' or '...
'''all families''.']};
bma_yes.val = {bma_famwin };
bma_yes.values = {bma_famwin bma_all bma_part };
% ---------------------------------------------------------------------
% bma BMA
% ---------------------------------------------------------------------
bma = cfg_choice;
bma.tag = 'bma';
bma.name = 'BMA';
bma.help = {'Optional field to compute Bayesian Model Averaging (BMA).'};
bma.val = {bma_no };
bma.values = {bma_no bma_yes };
% ---------------------------------------------------------------------
% verify_id Verify data ID
% ---------------------------------------------------------------------
verify_id = cfg_menu;
verify_id.tag = 'verify_id';
verify_id.name = 'Verify data identity';
verify_id.help = {['Verify whether the model comparison is valid '...
'i.e. whether the models have been fitted to the same data.']};
verify_id.labels = {
'Yes'
'No'
}';
verify_id.values = {
1
0
}';
verify_id.val = {0};
% ---------------------------------------------------------------------
% out_file Output files
% ---------------------------------------------------------------------
out_file = cfg_menu;
out_file.tag = 'out_file';
out_file.name = 'Output files (RFX)';
out_file.help = {['Specify which output files to save (only valid for'...
'RFX analyses). ']...
''...
['Default option (and faster option): '...
'PPM = xppm.img (Posterior Probability Maps) '...
'for each model. ']...
''...
['Second option: PPM + EPM = xppm.img + '...
'epm.img (Exceedance Probability '...
'Maps + Exceedance Probability Maps) for each model.']...
''...
['Third option: PPM + EPM + Alpha = xppm.img + '...
'epm.img + alpha.img (PPM, EPM and Map of Dirichlet '...
'Parameters) for each model.']};
out_file.labels = {
'PPM'
'PPM + EPM'
'PPM + EPM + Alpha'
}';
out_file.values = {
0
1
2
}';
out_file.val = {0};
% ---------------------------------------------------------------------
% mask Mask Image
% ---------------------------------------------------------------------
mask = cfg_files;
mask.tag = 'mask';
mask.name = 'Mask Image';
mask.help = {['Specify an image for explicitly masking the analysis. '...
'(optional). '...
'A sensible option here is to use a segmention of '...
'structural images to specify a within-brain mask. '...
'If you select that image as an explicit mask then only '...
'those voxels in the brain will be analysed. This both '...
'speeds the inference process and restricts BMS to '...
'within-brain voxels. Alternatively, if such structural '...
'images are unavailble or no masking is required, then '...
'leave this field empty.']};
mask.filter = 'image';
mask.ufilter = '.*';
mask.val = {{''}};
mask.num = [0 1];
% ---------------------------------------------------------------------
% nsamp Number of samples
% ---------------------------------------------------------------------
nsamp = cfg_entry;
nsamp.tag = 'nsamp';
nsamp.name = 'Number of samples';
nsamp.help = {['Number of samples used to compute exceedance '...
'probabilities (default: 1e6). '...
'To make computations faster reduce the number of '...
'samples when number of models is bigger than 3.']};
nsamp.strtype = 's';
nsamp.num = [1 Inf];
nsamp.val = {'1e6'};
% ---------------------------------------------------------------------
% file BMS.mat
% ---------------------------------------------------------------------
file = cfg_files;
file.tag = 'file';
file.name = 'BMS.mat';
file.help = {['Specify the BMS (.mat) file obtained from previous BMS '...
'analysis (optional). Leave field empty to work on '...
'serial mode.']};
file.filter = 'mat';
file.ufilter = '.*';
file.val = {{''}};
file.num = [0 1];
% ---------------------------------------------------------------------
% img Map to display
% ---------------------------------------------------------------------
img = cfg_files;
img.tag = 'img';
img.name = 'Map to display';
img.help = {['Specify map (.img) obtained from BMS Maps '...
'(optional). Leave field empty to work on serial mode.']};
img.filter = 'image';
img.ufilter = '.*';
img.val = {{''}};
img.num = [0 1];
% ---------------------------------------------------------------------
% thres Probability Threshold
% ---------------------------------------------------------------------
thres = cfg_entry;
thres.tag = 'thres';
thres.name = 'Probability threshold';
thres.help = {['Specify the probability threshold to apply to the '...
'image (optional). Leave field empty to work on '...
'serial mode.']};
thres.strtype = 'e';
thres.num = [0 Inf];
thres.val = {[]};
% ---------------------------------------------------------------------
% k Extent threshold
% ---------------------------------------------------------------------
k = cfg_entry;
k.tag = 'k';
k.name = 'Extent threshold';
k.help = {['Specify extent threshold (minimum number of voxels '...
'per cluster).']};
k.strtype = 'e';
k.num = [0 Inf];
k.val = {[]};
% ---------------------------------------------------------------------
% scale Map Scale
% ---------------------------------------------------------------------
scale = cfg_menu;
scale.tag = 'scale';
scale.name = 'Map scale';
scale.help = {['Specify scale to display maps (optional). Default: '...
'empty field to work on serial mode. Other options: '...
'''None'' will display image with original scale and '...
'''Log-odds'' will display image in a log-odds '...
' scale (in this case .img should be a '...
'probability map).']};
scale.labels = {
'Empty'
'None'
'Log-odds'
}';
scale.values = {
[]
0
1
}';
scale.val = {[]};
% ---------------------------------------------------------------------
% bms_dcm BMS: DCM, output is bar plot
% ---------------------------------------------------------------------
bms_dcm = cfg_exbranch;
bms_dcm.tag = 'bms_dcm';
bms_dcm.name = 'BMS: DCM';
bms_dcm.val = {dir dcm model_sp load_f method family_level bma verify_id};
bms_dcm.help = {['Bayesian Model Selection for Dynamic Causal Modelling '...
'(DCM) for fMRI or MEEG.']...
''...
['Input: DCM files (.mat) for each model, session and subject. '...
'Note that there must be identical numbers of models for all each '...
'sessions, and identical numbers of sessions for all subjects. ']...
''...
['Output: For the fixed effects analysis, the log-evidence for each '...
'model (relative to the worst model) is plotted in the graphics '...
'window, as well as the posterior probability for each model. In '...
'addition, the corresponding values are saved in the directory '...
'specified (BMS.mat). For the random effects analysis, the '...
'expected posterior probability and exceedance probability of each '...
'model (i.e. the probability that this model is more likely than '...
'any other model) are plotted in the graphics window, and the '...
'corresponding values are saved in the directory specified. If '...
'there are multiple sessions per subject, the random effects '...
'analysis operates on the subject-specific sums of log evidences '...
'across sessions.']};
bms_dcm.prog = @spm_run_bms_dcm;
bms_dcm.vout = @vout;
% ---------------------------------------------------------------------
% bms_dcm_vis: DCM (visualise results)
% ---------------------------------------------------------------------
bms_dcm_vis = cfg_exbranch;
bms_dcm_vis.tag = 'bms_dcm_vis';
bms_dcm_vis.name = 'BMS: DCM (Results)';
bms_dcm_vis.val = {file };
bms_dcm_vis.help = {['Bayesian Model Selection for DCM (Results). '...
'Show results from BMS for DCM.']};
bms_dcm_vis.prog = @spm_run_bms_dcm_vis;
% ---------------------------------------------------------------------
% bms_map_inf BMS: Maps (Inference), output is BMS map
% ---------------------------------------------------------------------
bms_map_inf = cfg_exbranch;
bms_map_inf.tag = 'bms_map_inf';
bms_map_inf.name = 'BMS: Maps';
bms_map_inf.val = {dir map name_mod method_maps out_file mask nsamp };
bms_map_inf.help = {'Bayesian Model Selection for Log-Evidence Maps. '...
''...
['Input: log-evidence maps (.img) for each model, session and '...
'subject. Note that there must be identical numbers of models for '...
'all sessions, and identical numbers of sessions for all '...
'subjects.']...
''...
['Output: For the fixed effects analysis, posterior probability maps '...
'(.img) are created for each model. '...
'For the random effects analysis, expected posterior probability '...
'and exceedance probability (i.e. the probability that this model '...
'is more likely than any other model) maps are created for each '...
'model. If there are multiple sessions per subject, the random '...
'effects analysis operates on the subject-specific sums of log '...
'evidences across sessions. In addition, a BMS.mat file will be save '...
'in the specified directory for both methods']};
bms_map_inf.prog = @spm_run_bms_map;
bms_map_inf.vout = @vout;
% ---------------------------------------------------------------------
% bms_map_vis BMS: Maps (Results), visualisation of BMS Maps results
% ---------------------------------------------------------------------
bms_map_vis = cfg_exbranch;
bms_map_vis.tag = 'bms_map_vis';
bms_map_vis.name = 'BMS: Maps (Results)';
bms_map_vis.val = {file img thres k scale};
bms_map_vis.help = {['Bayesian Model Selection Maps (Results). '...
'Show results from BMS Maps (Inference).']};
bms_map_vis.prog = @spm_run_bms_vis;
% ---------------------------------------------------------------------
% bms Bayesian Model Selection
% ---------------------------------------------------------------------
bms = cfg_choice;
bms.tag = 'bms';
bms.name = 'Bayesian Model Selection';
bms.help = {['Bayesian Model Selection for group studies (fixed '...
'effects and random effects analysis).']};
bms.values = {bms_dcm bms_dcm_vis bms_map_inf bms_map_vis };
%------------------------------------------------------------------------
function dep = vout(varargin)
% Output file names will be saved in a struct with field .files
dep(1) = cfg_dep;
dep(1).sname = 'BMS Maps';
dep(1).src_output = substruct('.','files');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_convert2images.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_convert2images.m
| 1,533 |
utf_8
|
278f08c7b6bc00ad2186e3d343a12b7c
|
function S = spm_cfg_eeg_convert2images
% configuration file for writing voxel-based images from SPM M/EEG format,
% as a time-series of 2Dimages
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_convert2images.m 3818 2010-04-13 14:36:31Z vladimir $
Fname = cfg_files;
Fname.tag = 'Fname';
Fname.name = 'File Names';
Fname.filter = 'mat';
Fname.num = [1 inf];
Fname.help = {'Select the M/EEG mat file.'};
n = cfg_entry;
n.tag = 'n';
n.name = 'Output dimension';
n.strtype = 'r';
n.num = [1 1];
n.val = {64};
n.help = {'Enter the Output image dimension'};
yes = cfg_const;
yes.tag = 'yes';
yes.name = 'Interpolate bad channels';
yes.val = {1};
no = cfg_const;
no.tag = 'no';
no.name = 'Mask out bad channels';
no.val = {1};
Interpolate = cfg_choice;
Interpolate.tag = 'interpolate_bad';
Interpolate.name = 'Interpolate';
Interpolate.values = {yes,no};
Interpolate.val = {yes};
Interpolate.help = {'Interpolate bad channels'};
S = cfg_exbranch;
S.tag = 'convert2images';
S.name = 'M/EEG Convert2Images';
S.val = {Fname n Interpolate};
S.help = {'Convert SPM M/EEG data to voxel-based images, as a time-series of 2D images'};
S.prog = @eeg_convert2images;
S.modality = {'EEG'};
function out = eeg_convert2images(job)
% construct the S struct
S = job;
S.Fname = strvcat(job.Fname);
if isfield(S.interpolate_bad, 'yes')
S.interpolate_bad = 1;
else
S.interpolate_bad = 0;
end
spm_eeg_convert2scalp(S);
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_results.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_inv_results.m
| 3,226 |
utf_8
|
4785178456ae76c108a54bc2b56a776c
|
function results = spm_cfg_eeg_inv_results
% configuration file for creating images from results of source
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_results.m 3976 2010-07-08 14:12:31Z karl $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the inversion results are be stored.'};
val.val = {1};
woi = cfg_entry;
woi.tag = 'woi';
woi.name = 'Time window of interest';
woi.strtype = 'r';
woi.num = [Inf 2];
woi.val = {[-Inf Inf]};
woi.help = {'Time window to average over (ms)'};
foi = cfg_entry;
foi.tag = 'foi';
foi.name = 'Frequency window of interest';
foi.strtype = 'r';
foi.num = [1 2];
foi.val = {[0 0]};
foi.help = {'Frequency window (Hz)'};
ctype = cfg_menu;
ctype.tag = 'ctype';
ctype.name = 'Contrast type';
ctype.help = {'Contrast type: evoked activity, induced activity or single trials.'};
ctype.labels = {'Evoked', 'Induced', 'Single trials'};
ctype.values = {'evoked', 'induced', 'trials'};
ctype.val = {'evoked'};
space = cfg_menu;
space.tag = 'space';
space.name = 'Image space';
space.help = {'Image space to wrote the results in.'};
space.labels = {'MNI', 'Native'};
space.values = {1, 0};
space.val = {1};
smoothing = cfg_entry;
smoothing.tag = 'smoothing';
smoothing.name = 'Smoothing kernel width (mm)';
smoothing.strtype = 'r';
smoothing.num = [1 1];
smoothing.val = {8};
results = cfg_exbranch;
results.tag = 'results';
results.name = 'M/EEG inversion results';
results.val = {D, val, woi, foi, ctype, space, smoothing};
results.help = {'Generate images from the results of imaging source reconstruction'};
results.prog = @run_results;
results.vout = @vout_results;
results.modality = {'EEG'};
function out = run_results(job)
contrast = [];
contrast.fboi = job.foi;
contrast.type = job.ctype;
contrast.space = job.space;
contrast.smoothing = job.smoothing;
files = {};
for i = 1:numel(job.D)
D = spm_eeg_load(job.D{i});
D.val = job.val;
if ~isfield(D.inv{D.val}, 'inverse') || ~isfield(D.inv{D.val}.inverse, 'J')
error(sprintf('Imaging source reconstruction is missing for subject %d', i));
end
contrast.woi = fix(sort(job.woi,2));
D.inv{D.val}.contrast = contrast;
D = spm_eeg_inv_results(D);
D = spm_eeg_inv_Mesh2Voxels(D);
save(D);
fname = D.inv{D.val}.contrast.fname;
for j = 1:numel(fname)
if iscell(fname{j})
for k = 1:numel(fname{j})
files = [files; fname{j}(k)];
end
else
files = [files; fname(j)];
end
end
end
out.files = files;
function dep = vout_results(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep(1) = cfg_dep;
dep(1).sname = 'Exported smoothed images';
dep(1).src_output = substruct('.','files');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_contrast.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_contrast.m
| 2,514 |
utf_8
|
5ef4acc26bd25c57a355ebd077aecc82
|
function S = spm_cfg_eeg_contrast
% configuration file for computing contrast over epochs
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_contrast.m 3881 2010-05-07 21:02:57Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
c = cfg_entry;
c.tag = 'c';
c.name = 'Contrast coefficients';
c.strtype = 'r';
c.num = [1 inf];
c.help = {'Enter the contrast vector.'};
label = cfg_entry;
label.tag = 'label';
label.name = 'New condition label';
label.strtype = 's';
label.help = {'Enter the label for the condition derived by applying the contrast.'};
contrast = cfg_branch;
contrast.tag = 'contrast';
contrast.name = 'Contrast';
contrast.val = {c label};
contrasts = cfg_repeat;
contrasts.tag = 'contrasts';
contrasts.name = 'Contrasts';
contrasts.help = {'Each contrast defines a new condition in the output file.'};
contrasts.values = {contrast};
contrasts.num = [1 Inf];
weight = cfg_menu;
weight.tag = 'weight';
weight.name = 'Weight average by repetition numbers';
weight.labels = {'yes', 'no'};
weight.values = {1 , 0};
weight.val = {1};
weight.help = {'This option will weight averages by the number of their occurences in the data set. This is only important when there are multiple occurences of a trial type, e.g. in single trial data.'};
S = cfg_exbranch;
S.tag = 'contrast';
S.name = 'M/EEG Contrast over epochs';
S.val = {D contrasts weight};
S.help = {'Computes contrasts over EEG/MEG epochs.'};
S.prog = @eeg_contrast;
S.vout = @vout_eeg_contrast;
S.modality = {'EEG'};
function out = eeg_contrast(job)
% construct the S struct
S.D = job.D{1};
S.c = cat(1, job.contrast(:).c);
S.label = {job.contrast.label};
S.WeightAve = job.weight;
out.D = spm_eeg_weight_epochs(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_contrast(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Contrast of M/EEG epochs';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Contrast Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_checkreg.m
|
.m
|
antx-master/xspm8/config/spm_cfg_checkreg.m
| 2,265 |
utf_8
|
c81f7c3223052066b263026099947cec
|
function checkreg = spm_cfg_checkreg
% SPM Configuration file for Check Reg
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_checkreg.m 4205 2011-02-21 15:39:08Z guillaume $
%--------------------------------------------------------------------------
% data Images to Display
%--------------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Images to Display';
data.help = {'Images to display.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 15];
%--------------------------------------------------------------------------
% checkreg Check Registration
%--------------------------------------------------------------------------
checkreg = cfg_exbranch;
checkreg.tag = 'checkreg';
checkreg.name = 'Check Registration';
checkreg.val = {data };
checkreg.help = {
'Orthogonal views of one or more images are displayed. Clicking in any image moves the centre of the orthogonal views. Images are shown in orientations relative to that of the first selected image. The first specified image is shown at the top-left, and the last at the bottom right. The fastest increment is in the left-to-right direction (the same as you are reading this).'
''
'If you have put your images in the correct file format, then (possibly after specifying some rigid-body rotations):'
' The top-left image is coronal with the top (superior) of the head displayed at the top and the left shown on the left. This is as if the subject is viewed from behind.'
' The bottom-left image is axial with the front (anterior) of the head at the top and the left shown on the left. This is as if the subject is viewed from above.'
' The top-right image is sagittal with the front (anterior) of the head at the left and the top of the head shown at the top. This is as if the subject is viewed from the left.'
}';
checkreg.prog = @check_reg;
%==========================================================================
function check_reg(job)
spm_check_registration(char(job.data));
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_deletefiles.m
|
.m
|
antx-master/xspm8/config/spm_cfg_deletefiles.m
| 2,355 |
utf_8
|
a52badd2dedc7ae616252beab2db79b1
|
function deletefiles = spm_cfg_deletefiles
% SPM Configuration file for 'rm'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_deletefiles.m 4907 2012-09-06 19:33:21Z guillaume $
rev = '$Rev: 4907 $';
% ---------------------------------------------------------------------
% deletefiles Files to delete
% ---------------------------------------------------------------------
deletefiles1 = cfg_files;
deletefiles1.tag = 'deletefiles';
deletefiles1.name = 'Files to delete';
deletefiles1.help = {'Select files to delete.'};
deletefiles1.filter = 'any';
deletefiles1.ufilter = '.*';
deletefiles1.num = [0 Inf];
% ---------------------------------------------------------------------
% deletefiles Delete Files (Deprecated)
% ---------------------------------------------------------------------
deletefiles = cfg_exbranch;
deletefiles.tag = 'deletefiles';
deletefiles.name = 'Delete Files (DEPRECATED)';
deletefiles.val = {deletefiles1 };
deletefiles.help = {
'This module is DEPRECATED and has been moved to BasicIO.'
'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI.'
'Please switch to the BasicIO module instead.'
'This module will be REMOVED in the next major release of SPM.'
''
'This facility allows to delete files in a batch. Note that deleting files will not make them disappear from file selection lists.'
'Therefore one has to be careful not to select the original files after they have been programmed to be deleted.'
'If image files (.img or .nii) are selected, corresponding .hdr or .mat files will be deleted as well, if they exist.'
};
deletefiles.prog = @my_deletefiles;
deletefiles.hidden = true;
%------------------------------------------------------------------------
function my_deletefiles(varargin)
warning('"spm.util.deletefiles" is DEPRECATED and will be REMOVED in the next major release of SPM. Use BasicIO instead.');
job = varargin{1};
for k = 1:numel(job.deletefiles)
[p, n, e] = spm_fileparts(job.deletefiles{k});
if strcmp(e,'.img') || strcmp(e,'.nii')
spm_unlink(fullfile(p,[n '.hdr']));
spm_unlink(fullfile(p,[n '.mat']));
end
spm_unlink(fullfile(p,[n e]));
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_md.m
|
.m
|
antx-master/xspm8/config/spm_cfg_md.m
| 2,106 |
utf_8
|
203b2cc952d61779c598ca8fd36abf74
|
function md = spm_cfg_md
% SPM Configuration file for 'mkdir'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_md.m 4907 2012-09-06 19:33:21Z guillaume $
% ----------------------------------------------------------------------
% basedir Select a base directory
% ----------------------------------------------------------------------
basedir = cfg_files;
basedir.tag = 'basedir';
basedir.name = 'Select a base directory';
basedir.help = {'Select a base directory.'};
basedir.filter = 'dir';
basedir.ufilter = '.*';
basedir.num = [1 1];
% ----------------------------------------------------------------------
% name Enter a directory name
% ----------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Enter a directory name';
name.help = {'Enter a directory name'};
name.strtype = 's';
name.num = [1 Inf];
% ----------------------------------------------------------------------
% md Make Directory (Deprecated)
% ----------------------------------------------------------------------
md = cfg_exbranch;
md.tag = 'md';
md.name = 'Make Directory (DEPRECATED)';
md.val = {basedir name};
md.help = {
'This module is DEPRECATED and has been moved to BasicIO.'
'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI.'
'Please switch to the BasicIO module instead.'
'This module will be REMOVED in the next major release of SPM.'
''
'This facility allows programming a directory change.'
}';
md.prog = @my_mkdir;
md.hidden = true;
%=======================================================================
function my_mkdir(varargin)
warning('"spm.util.md" is DEPRECATED and will be REMOVED in the next major release of SPM. Use BasicIO instead.');
job = varargin{1};
if ~isempty(job.basedir) && ~isempty(job.name)
mkdir(job.basedir{:},job.name);
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_normalise.m
|
.m
|
antx-master/xspm8/config/spm_cfg_normalise.m
| 25,506 |
utf_8
|
a01a87d691294117634f2d14d848977e
|
function normalise = spm_cfg_normalise
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_normalise.m 3804 2010-03-31 16:16:21Z ged $
rev = '$Rev: 3804 $';
% ---------------------------------------------------------------------
% source Source Image
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Image';
source.help = {'The image that is warped to match the template(s). The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 1];
% ---------------------------------------------------------------------
% wtsrc Source Weighting Image
% ---------------------------------------------------------------------
wtsrc = cfg_files;
wtsrc.tag = 'wtsrc';
wtsrc.name = 'Source Weighting Image';
wtsrc.val = {''};
wtsrc.help = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains. These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};
wtsrc.filter = 'image';
wtsrc.ufilter = '.*';
wtsrc.num = [0 1];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {source wtsrc };
subj.help = {'Data for this subject. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% esubjs Data
% ---------------------------------------------------------------------
esubjs = cfg_repeat;
esubjs.tag = 'esubjs';
esubjs.name = 'Data';
esubjs.help = {'List of subjects. Images of each subject should be warped differently.'};
esubjs.values = {subj };
esubjs.num = [1 Inf];
% ---------------------------------------------------------------------
% template Template Image
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template Image';
template.help = {'Specify a template image to match the source image with. The contrast in the template must be similar to that of the source image in order to achieve a good registration. It is also possible to select more than one template, in which case the registration algorithm will try to find the best linear combination of these images in order to best model the intensities in the source image.'};
template.filter = 'image';
template.ufilter = '.*';
template.dir = fullfile(spm('dir'),'templates');
template.num = [1 Inf];
% ---------------------------------------------------------------------
% weight Template Weighting Image
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Template Weighting Image';
weight.val = {''};
weight.help = {
'Applies a weighting mask to the template(s) during the parameter estimation. With the default brain mask, weights in and around the brain have values of one whereas those clearly outside the brain are zero. This is an attempt to base the normalisation purely upon the shape of the brain, rather than the shape of the head (since low frequency basis functions can not really cope with variations in skull thickness).'
''
'The option is now available for a user specified weighting image. This should have the same dimensions and mat file as the template images, with values in the range of zero to one.'
}';
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% smosrc Source Image Smoothing
% ---------------------------------------------------------------------
smosrc = cfg_entry;
smosrc.tag = 'smosrc';
smosrc.name = 'Source Image Smoothing';
smosrc.help = {'Smoothing to apply to a copy of the source image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};
smosrc.strtype = 'e';
smosrc.num = [1 1];
smosrc.def = @(val)spm_get_defaults('normalise.estimate.smosrc', val{:});
% ---------------------------------------------------------------------
% smoref Template Image Smoothing
% ---------------------------------------------------------------------
smoref = cfg_entry;
smoref.tag = 'smoref';
smoref.name = 'Template Image Smoothing';
smoref.help = {'Smoothing to apply to a copy of the template image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};
smoref.strtype = 'e';
smoref.num = [1 1];
smoref.def = @(val)spm_get_defaults('normalise.estimate.smoref', val{:});
% ---------------------------------------------------------------------
% regtype Affine Regularisation
% ---------------------------------------------------------------------
regtype = cfg_menu;
regtype.tag = 'regtype';
regtype.name = 'Affine Regularisation';
regtype.help = {'Affine registration into a standard space can be made more robust by regularisation (penalising excessive stretching or shrinking). The best solutions can be obtained by knowing the approximate amount of stretching that is needed (e.g. ICBM templates are slightly bigger than typical brains, so greater zooms are likely to be needed). If registering to an image in ICBM/MNI space, then choose the first option. If registering to a template that is close in size, then select the second option. If you do not want to regularise, then choose the third.'};
regtype.labels = {
'ICBM space template'
'Average sized template'
'No regularisation'
}';
regtype.values = {
'mni'
'subj'
'none'
}';
regtype.def = @(val)spm_get_defaults('normalise.estimate.regtype', val{:});
% ---------------------------------------------------------------------
% cutoff Nonlinear Frequency Cutoff
% ---------------------------------------------------------------------
cutoff = cfg_entry;
cutoff.tag = 'cutoff';
cutoff.name = 'Nonlinear Frequency Cutoff';
cutoff.help = {'Cutoff of DCT bases. Only DCT bases of periods longer than the cutoff are used to describe the warps. The number used will depend on the cutoff and the field of view of the template image(s).'};
cutoff.strtype = 'e';
cutoff.num = [1 1];
cutoff.def = @(val)spm_get_defaults('normalise.estimate.cutoff', val{:});
% ---------------------------------------------------------------------
% nits Nonlinear Iterations
% ---------------------------------------------------------------------
nits = cfg_entry;
nits.tag = 'nits';
nits.name = 'Nonlinear Iterations';
nits.help = {'Number of iterations of nonlinear warping performed.'};
nits.strtype = 'w';
nits.num = [1 1];
nits.def = @(val)spm_get_defaults('normalise.estimate.nits', val{:});
% ---------------------------------------------------------------------
% reg Nonlinear Regularisation
% ---------------------------------------------------------------------
reg = cfg_entry;
reg.tag = 'reg';
reg.name = 'Nonlinear Regularisation';
reg.help = {'The amount of regularisation for the nonlinear part of the spatial normalisation. Pick a value around one. However, if your normalised images appear distorted, then it may be an idea to increase the amount of regularisation (by an order of magnitude) - or even just use an affine normalisation. The regularisation influences the smoothness of the deformation fields.'};
reg.strtype = 'e';
reg.num = [1 1];
reg.def = @(val)spm_get_defaults('normalise.estimate.reg', val{:});
% ---------------------------------------------------------------------
% eoptions Estimation Options
% ---------------------------------------------------------------------
eoptions = cfg_branch;
eoptions.tag = 'eoptions';
eoptions.name = 'Estimation Options';
eoptions.val = {template weight smosrc smoref regtype cutoff nits reg };
eoptions.help = {'Various settings for estimating warps.'};
% ---------------------------------------------------------------------
% est Normalise: Estimate
% ---------------------------------------------------------------------
est = cfg_exbranch;
est.tag = 'est';
est.name = 'Normalise: Estimate';
est.val = {esubjs eoptions };
est.help = {'Computes the warp that best registers a source image (or series of source images) to match a template, saving it to a file imagename''_sn.mat''.'};
est.prog = @spm_run_normalise_estimate;
est.vout = @vout_estimate;
% ---------------------------------------------------------------------
% matname Parameter File
% ---------------------------------------------------------------------
matname = cfg_files;
matname.tag = 'matname';
matname.name = 'Parameter File';
matname.help = {'Select the ''_sn.mat'' file containing the spatial normalisation parameters for that subject.'};
matname.filter = 'mat';
matname.ufilter = '.*_sn\.mat$';
matname.num = [1 1];
% ---------------------------------------------------------------------
% resample Images to Write
% ---------------------------------------------------------------------
resample = cfg_files;
resample.tag = 'resample';
resample.name = 'Images to Write';
resample.help = {'These are the images for warping according to the estimated parameters. They can be any images that are in register with the "source" image used to generate the parameters.'};
resample.filter = 'image';
resample.ufilter = '.*';
resample.num = [1 Inf];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {matname resample };
subj.help = {'Data for this subject. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% wsubjs Data
% ---------------------------------------------------------------------
wsubjs = cfg_repeat;
wsubjs.tag = 'wsubjs';
wsubjs.name = 'Data';
wsubjs.help = {'List of subjects. Images of each subject should be warped differently.'};
wsubjs.values = {subj };
wsubjs.num = [1 Inf];
% ---------------------------------------------------------------------
% preserve Preserve
% ---------------------------------------------------------------------
preserve = cfg_menu;
preserve.tag = 'preserve';
preserve.name = 'Preserve';
preserve.help = {
'Preserve Concentrations: Spatially normalised images are not "modulated". The warped images preserve the intensities of the original images.'
''
'Preserve Total: Spatially normalised images are "modulated" in order to preserve the total amount of signal in the images. Areas that are expanded during warping are correspondingly reduced in intensity.'
}';
preserve.labels = {
'Preserve Concentrations'
'Preserve Amount'
}';
preserve.values = {0 1};
preserve.def = @(val)spm_get_defaults('normalise.write.preserve', val{:});
% ---------------------------------------------------------------------
% bb Bounding box
% ---------------------------------------------------------------------
bb = cfg_entry;
bb.tag = 'bb';
bb.name = 'Bounding box';
bb.help = {'The bounding box (in mm) of the volume which is to be written (relative to the anterior commissure).'};
bb.strtype = 'e';
bb.num = [2 3];
bb.def = @(val)spm_get_defaults('normalise.write.bb', val{:});
% ---------------------------------------------------------------------
% vox Voxel sizes
% ---------------------------------------------------------------------
vox = cfg_entry;
vox.tag = 'vox';
vox.name = 'Voxel sizes';
vox.help = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'};
vox.strtype = 'e';
vox.num = [1 3];
vox.def = @(val)spm_get_defaults('normalise.write.vox', val{:});
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {
['The method by which the images are sampled when ' ...
'being written in a different space. ' ...
'(Note that Inf or NaN values are treated as zero, ' ...
'rather than as missing data)']
' Nearest Neighbour:'
' - Fastest, but not normally recommended.'
' Bilinear Interpolation:'
' - OK for PET, realigned fMRI, or segmentations'
' B-spline Interpolation:'
[' - Better quality (but slower) interpolation' ...
'/* \cite{thevenaz00a}*/, especially with higher ' ...
'degree splines. Can produce values outside the ' ...
'original range (e.g. small negative values from an ' ...
'originally all positive image).']
}';
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-spline'
'3rd Degree B-Spline '
'4th Degree B-Spline '
'5th Degree B-Spline'
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
interp.values = {0 1 2 3 4 5 6 7};
interp.def = @(val)spm_get_defaults('normalise.write.interp', val{:});
% ---------------------------------------------------------------------
% wrap Wrapping
% ---------------------------------------------------------------------
wrap = cfg_menu;
wrap.tag = 'wrap';
wrap.name = 'Wrapping';
wrap.help = {
'These are typically:'
' No wrapping: for PET or images that have already been spatially transformed. '
' Wrap in Y: for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).'
}';
wrap.labels = {
'No wrap'
'Wrap X'
'Wrap Y'
'Wrap X & Y'
'Wrap Z'
'Wrap X & Z'
'Wrap Y & Z'
'Wrap X, Y & Z'
}';
wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]...
[1 1 1]};
wrap.def = @(val)spm_get_defaults('normalise.write.wrap', val{:});
% ---------------------------------------------------------------------
% prefix Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Filename Prefix';
prefix.help = {'Specify the string to be prepended to the filenames of the normalised image file(s). Default prefix is ''w''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('normalise.write.prefix', val{:});
% ---------------------------------------------------------------------
% roptions Writing Options
% ---------------------------------------------------------------------
roptions = cfg_branch;
roptions.tag = 'roptions';
roptions.name = 'Writing Options';
roptions.val = {preserve bb vox interp wrap prefix };
roptions.help = {'Various options for writing normalised images.'};
% ---------------------------------------------------------------------
% write Normalise: Write
% ---------------------------------------------------------------------
write = cfg_exbranch;
write.tag = 'write';
write.name = 'Normalise: Write';
write.val = {wsubjs roptions };
write.help = {'Allows previously estimated warps (stored in imagename''_sn.mat'' files) to be applied to series of images.'};
write.prog = @spm_run_normalise_write;
write.vout = @vout_write;
% ---------------------------------------------------------------------
% source Source Image
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Image';
source.help = {'The image that is warped to match the template(s). The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 1];
% ---------------------------------------------------------------------
% wtsrc Source Weighting Image
% ---------------------------------------------------------------------
wtsrc = cfg_files;
wtsrc.tag = 'wtsrc';
wtsrc.name = 'Source Weighting Image';
wtsrc.val = {''};
wtsrc.help = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains. These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};
wtsrc.filter = 'image';
wtsrc.ufilter = '.*';
wtsrc.num = [0 1];
% ---------------------------------------------------------------------
% resample Images to Write
% ---------------------------------------------------------------------
resample = cfg_files;
resample.tag = 'resample';
resample.name = 'Images to Write';
resample.help = {'These are the images for warping according to the estimated parameters. They can be any images that are in register with the "source" image used to generate the parameters.'};
resample.filter = 'image';
resample.ufilter = '.*';
resample.num = [1 Inf];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {source wtsrc resample };
subj.help = {'Data for this subject. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% ewsubjs Data
% ---------------------------------------------------------------------
ewsubjs = cfg_repeat;
ewsubjs.tag = 'ewsubjs';
ewsubjs.name = 'Data';
ewsubjs.help = {'List of subjects. Images of each subject should be warped differently.'};
ewsubjs.values = {subj };
ewsubjs.num = [1 Inf];
% ---------------------------------------------------------------------
% estwrite Normalise: Estimate & Write
% ---------------------------------------------------------------------
estwrite = cfg_exbranch;
estwrite.tag = 'estwrite';
estwrite.name = 'Normalise: Estimate & Write';
estwrite.val = {ewsubjs eoptions roptions };
estwrite.help = {'Computes the warp that best registers a source image (or series of source images) to match a template, saving it to the file imagename''_sn.mat''. This option also allows the contents of the imagename''_sn.mat'' files to be applied to a series of images.'};
estwrite.prog = @spm_run_normalise_estwrite;
estwrite.vout = @vout_estwrite;
% ---------------------------------------------------------------------
% normalise Normalise
% ---------------------------------------------------------------------
normalise = cfg_choice;
normalise.tag = 'normalise';
normalise.name = 'Normalise';
normalise.help = {
'This very ancient module spatially (stereotactically) normalises MRI, PET or SPECT images into a standard space defined by some ideal model or template image[s]. The template images supplied with SPM conform to the space defined by the ICBM, NIH P-20 project, and approximate that of the the space described in the atlas of Talairach and Tournoux (1988). The transformation can also be applied to any other image that has been coregistered with these scans. A few researchers may wish to continue using this strategy, but (when good quality anatomical MRI scans are available) the DARTEL approach is now generally recommended instead.'
''
'Generally, the algorithms work by minimising the sum of squares difference between the image which is to be normalised, and a linear combination of one or more template images. For the least squares registration to produce an unbiased estimate of the spatial transformation, the image contrast in the templates (or linear combination of templates) should be similar to that of the image from which the spatial normalisation is derived. The registration simply searches for an optimum solution. If the starting estimates are not good, then the optimum it finds may not find the global optimum.'
''
'The first step of the normalisation is to determine the optimum 12-parameter affine transformation. Initially, the registration is performed by matching the whole of the head (including the scalp) to the template. Following this, the registration proceeded by only matching the brains together, by appropriate weighting of the template voxels. This is a completely automated procedure (that does not require ``scalp editing'') that discounts the confounding effects of skull and scalp differences. A Bayesian framework is used, such that the registration searches for the solution that maximises the a posteriori probability of it being correct /* \cite{ashburner97b} */. i.e., it maximises the product of the likelihood function (derived from the residual squared difference) and the prior function (which is based on the probability of obtaining a particular set of zooms and shears).'
''
'The affine registration is followed by estimating nonlinear deformations, whereby the deformations are defined by a linear combination of three dimensional discrete cosine transform (DCT) basis functions /* \cite{ashburner99a} */. The default options result in each of the deformation fields being described by 1176parameters, where these represent the coefficients of the deformations in three orthogonal directions. The matching involved simultaneously minimising the membrane energies of the deformation fields and the residual squared difference between the images and template(s).'
''
'The primarily use is for stereotactic normalisation to facilitate inter-subject averaging and precise characterisation of functional anatomy /* \cite{ashburner97bir} */. It is not necessary to spatially normalise the data (this is only a pre-requisite for inter-subject averaging or reporting in the Talairach space). If you wish to circumnavigate this step (e.g. if you have single slice data or do not have an appropriate high resolution MRI scan) simply specify where you think the anterior commissure is with the ORIGIN in the header of the first scan (using the ''Display'' facility) and proceed directly to ''Smoothing''or ''Statistics''.'
''
'All normalised *.img scans are written to the same subdirectory as the original *.img, prefixed with a ''w'' (i.e. w*.img). The details of the transformations are displayed in the results window, and the parameters are saved in the "*_sn.mat" file.'
}';
normalise.values = {est write estwrite };
%normalise.num = [1 Inf];
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estimate(job)
for k=1:numel(job.subj)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Norm Params File (Subj %d)',k);
dep(k).src_output = substruct('()',{k},'.','params');
dep(k).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_write(job)
for k=1:numel(job.subj)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Normalised Images (Subj %d)',k);
dep(k).src_output = substruct('()',{k},'.','files');
dep(k).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estwrite(job)
depe = vout_estimate(job);
depw = vout_write(job);
dep = [depe depw];
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_disp.m
|
.m
|
antx-master/xspm8/config/spm_cfg_disp.m
| 4,719 |
utf_8
|
9f6f5adf2e1375a3f6df5d5daeb54bae
|
function disp = spm_cfg_disp
% SPM Configuration file for Image Display
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_disp.m 4205 2011-02-21 15:39:08Z guillaume $
%-------------------------------------------------------------------------
% data Image to Display
%-------------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Image to Display';
data.help = {'Image to display.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 1];
%--------------------------------------------------------------------------
% disp Display Image
%--------------------------------------------------------------------------
disp = cfg_exbranch;
disp.tag = 'disp';
disp.name = 'Display Image';
disp.val = {data};
disp.help = {
'This is an interactive facility that allows orthogonal sections from an image volume to be displayed. Clicking the cursor on either of the three images moves the point around which the orthogonal sections are viewed. The co-ordinates of the cursor are shown both in voxel co-ordinates and millimetres within some fixed framework. The intensity at that point in the image (sampled using the current interpolation scheme) is also given. The position of the cross-hairs can also be moved by specifying the co-ordinates in millimetres to which they should be moved. Clicking on the horizontal bar above these boxes will move the cursor back to the origin (analogous to setting the cross-hair position (in mm) to [0 0 0]).'
''
'The images can be re-oriented by entering appropriate translations, rotations and zooms into the panel on the left. The transformations can then be saved by hitting the "Reorient images..." button. The transformations that were applied to the image are saved to the header information of the selected images. The transformations are considered to be relative to any existing transformations that may be stored. Note that the order that the transformations are applied in is the same as in spm_matrix.m.'
''
'The "Reset..." button next to it is for setting the orientation of images back to transverse. It retains the current voxel sizes, but sets the origin of the images to be the centre of the volumes and all rotations back to zero.'
''
'The right panel shows miscellaneous information about the image. This includes:'
' Dimensions - the x, y and z dimensions of the image.'
' Datatype - the computer representation of each voxel.'
' Intensity - scale-factors and possibly a DC offset.'
' Miscellaneous other information about the image.'
' Vox size - the distance (in mm) between the centres of neighbouring voxels.'
' Origin - the voxel at the origin of the co-ordinate system'
' DIr Cos - Direction cosines. This is a widely used representation of the orientation of an image.'
''
'There are also a few options for different resampling modes, zooms etc. You can also flip between voxel space (as would be displayed by Analyze) or world space (the orientation that SPM considers the image to be in). If you are re-orienting the images, make sure that world space is specified. Blobs (from activation studies) can be superimposed on the images and the intensity windowing can also be changed.'
''
''
'If you have put your images in the correct file format, then (possibly after specifying some rigid-body rotations):'
' The top-left image is coronal with the top (superior) of the head displayed at the top and the left shown on the left. This is as if the subject is viewed from behind.'
' The bottom-left image is axial with the front (anterior) of the head at the top and the left shown on the left. This is as if the subject is viewed from above.'
' The top-right image is sagittal with the front (anterior) of the head at the left and the top of the head shown at the top. This is as if the subject is viewed from the left.'
'/*\begin{figure} \begin{center} \includegraphics[width=150mm]{images/disp1} \end{center} \caption{The Display routine. \label{disp1}}\end{figure} */'
}';
disp.prog = @disp_image;
%==========================================================================
function disp_image(job)
spm_image('Init', job.data{1});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_st.m
|
.m
|
antx-master/xspm8/config/spm_cfg_st.m
| 8,731 |
utf_8
|
16a36edc715d472d387db03f6733781d
|
function st = spm_cfg_st
% SPM Configuration file for Slice Timing Correction
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_st.m 4269 2011-03-29 16:03:43Z guillaume $
% ---------------------------------------------------------------------
% scans Session
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Session';
scans.help = {'Select images to slice-time correct.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [2 Inf];
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Subjects or sessions. The same parameters specified below will be applied to all sessions.'};
generic.values = {scans };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% nslices Number of Slices
% ---------------------------------------------------------------------
nslices = cfg_entry;
nslices.tag = 'nslices';
nslices.name = 'Number of Slices';
nslices.help = {'Enter the number of slices.'};
nslices.strtype = 'n';
nslices.num = [1 1];
% ---------------------------------------------------------------------
% tr TR
% ---------------------------------------------------------------------
tr = cfg_entry;
tr.tag = 'tr';
tr.name = 'TR';
tr.help = {'Enter the TR (in seconds).'};
tr.strtype = 'r';
tr.num = [1 1];
% ---------------------------------------------------------------------
% ta TA
% ---------------------------------------------------------------------
ta = cfg_entry;
ta.tag = 'ta';
ta.name = 'TA';
ta.help = {'Enter the TA (in seconds). It is usually calculated as TR-(TR/nslices). You can simply enter this equation with the variables replaced by appropriate numbers.'};
ta.strtype = 'e';
ta.num = [1 1];
% ---------------------------------------------------------------------
% so Slice order
% ---------------------------------------------------------------------
so = cfg_entry;
so.tag = 'so';
so.name = 'Slice order';
so.help = {
'Enter the slice order. Bottom slice = 1. Sequence types and examples of code to enter are given below.'
''
'ascending (first slice=bottom): [1:1:nslices]'
''
'descending (first slice=top): [nslices:-1:1]'
''
'interleaved (middle-top):'
' for k = 1:nslices,'
' round((nslices-k)/2 + (rem((nslices-k),2) * (nslices - 1)/2)) + 1,'
' end'
''
'interleaved (bottom -> up): [1:2:nslices 2:2:nslices]'
''
'interleaved (top -> down): [nslices:-2:1, nslices-1:-2:1]'
}';
so.strtype = 'e';
so.num = [1 Inf];
% ---------------------------------------------------------------------
% refslice Reference Slice
% ---------------------------------------------------------------------
refslice = cfg_entry;
refslice.tag = 'refslice';
refslice.name = 'Reference Slice';
refslice.help = {'Enter the reference slice'};
refslice.strtype = 'n';
refslice.num = [1 1];
% ---------------------------------------------------------------------
% prefix Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Filename Prefix';
prefix.help = {'Specify the string to be prepended to the filenames of the slice-time corrected image file(s). Default prefix is ''a''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('slicetiming.prefix', val{:});
% ---------------------------------------------------------------------
% st Slice Timing
% ---------------------------------------------------------------------
st = cfg_exbranch;
st.tag = 'st';
st.name = 'Slice Timing';
st.val = {generic nslices tr ta so refslice prefix };
st.help = {
'Correct differences in image acquisition time between slices. Slice-time corrected files are prepended with an ''a''.'
''
'Note: The sliceorder arg that specifies slice acquisition order is a vector of N numbers, where N is the number of slices per volume. Each number refers to the position of a slice within the image file. The order of numbers within the vector is the temporal order in which those slices were acquired. To check the order of slices within an image file, use the SPM Display option and move the cross-hairs to a voxel co-ordinate of z=1. This corresponds to a point in the first slice of the volume.'
''
'The function corrects differences in slice acquisition times. This routine is intended to correct for the staggered order of slice acquisition that is used during echo-planar scanning. The correction is necessary to make the data on each slice correspond to the same point in time. Without correction, the data on one slice will represent a point in time as far removed as 1/2 the TR from an adjacent slice (in the case of an interleaved sequence).'
''
'This routine "shifts" a signal in time to provide an output vector that represents the same (continuous) signal sampled starting either later or earlier. This is accomplished by a simple shift of the phase of the sines that make up the signal. Recall that a Fourier transform allows for a representation of any signal as the linear combination of sinusoids of different frequencies and phases. Effectively, we will add a constant to the phase of every frequency, shifting the data in time.'
''
'Shifter - This is the filter by which the signal will be convolved to introduce the phase shift. It is constructed explicitly in the Fourier domain. In the time domain, it may be described as an impulse (delta function) that has been shifted in time the amount described by TimeShift. The correction works by lagging (shifting forward) the time-series data on each slice using sinc-interpolation. This results in each time series having the values that would have been obtained had the slice been acquired at the same time as the reference slice. To make this clear, consider a neural event (and ensuing hemodynamic response) that occurs simultaneously on two adjacent slices. Values from slice "A" are acquired starting at time zero, simultaneous to the neural event, while values from slice "B" are acquired one second later. Without correction, the "B" values will describe a hemodynamic response that will appear to have began one second EARLIER on the "B" slice than on slice "A". To correct for this, the "B" values need to be shifted towards the Right, i.e., towards the last value.'
''
'This correction assumes that the data are band-limited (i.e. there is no meaningful information present in the data at a frequency higher than that of the Nyquist). This assumption is support by the study of Josephs et al (1997, NeuroImage) that obtained event-related data at an effective TR of 166 msecs. No physio-logical signal change was present at frequencies higher than our typical Nyquist (0.25 HZ).'
''
'When using the slice timing correction it is very important that you input the correct slice order, and if there is any uncertainty then users are encouraged to work with their physicist to determine the actual slice acquisition order.'
''
'One can also consider augmenting the model by including the temporal derivative in the informed basis set instead of slice timing, which can account for +/- 1 second of changes in timing.'
''
'Written by Darren Gitelman at Northwestern U., 1998. Based (in large part) on ACQCORRECT.PRO from Geoff Aguirre and Eric Zarahn at U. Penn.'
}';
st.prog = @spm_run_st;
st.vout = @vout;
st.modality = {'FMRI'};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
for k=1:numel(job.scans)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Slice Timing Corr. Images (Sess %d)', k);
dep(k).src_output = substruct('()',{k}, '.','files');
dep(k).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_invert.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_inv_invert.m
| 7,820 |
utf_8
|
d768c9182c47d6daeccc44b246268094
|
function invert = spm_cfg_eeg_inv_invert
% configuration file for configuring imaging source inversion
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_invert.m 4326 2011-05-13 14:13:17Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the forward model can be found and the results will be stored.'};
val.val = {1};
all = cfg_const;
all.tag = 'all';
all.name = 'All';
all.val = {1};
condlabel = cfg_entry;
condlabel.tag = 'condlabel';
condlabel.name = 'Condition label';
condlabel.strtype = 's';
condlabel.val = {''};
conditions = cfg_repeat;
conditions.tag = 'conditions';
conditions.name = 'Conditions';
conditions.help = {'Specify the labels of the conditions to be included in the inversion'};
conditions.num = [1 Inf];
conditions.values = {condlabel};
conditions.val = {condlabel};
whatconditions = cfg_choice;
whatconditions.tag = 'whatconditions';
whatconditions.name = 'What conditions to include?';
whatconditions.values = {all, conditions};
whatconditions.val = {all};
standard = cfg_const;
standard.tag = 'standard';
standard.name = 'Standard';
standard.help = {'Use default settings for the inversion'};
standard.val = {1};
invtype = cfg_menu;
invtype.tag = 'invtype';
invtype.name = 'Inversion type';
invtype.help = {'Select the desired inversion type'};
invtype.labels = {'GS', 'ARD', 'MSP (GS+ARD)' 'COH', 'IID'};
invtype.values = {'GS', 'ARD', 'MSP', 'LOR', 'IID'};
invtype.val = {'GS'};
woi = cfg_entry;
woi.tag = 'woi';
woi.name = 'Time window of interest';
woi.strtype = 'r';
woi.num = [1 2];
woi.val = {[-Inf Inf]};
woi.help = {'Time window to include in the inversion (ms)'};
foi = cfg_entry;
foi.tag = 'foi';
foi.name = 'Frequency window of interest';
foi.strtype = 'r';
foi.num = [1 2];
foi.val = {[0 256]};
foi.help = {'Frequency window (the same as high-pass and low-pass in the GUI)'};
hanning = cfg_menu;
hanning.tag = 'hanning';
hanning.name = 'PST Hanning window';
hanning.help = {'Multiply the time series by a Hanning taper to emphasize the central part of the response.'};
hanning.labels = {'yes', 'no'};
hanning.values = {1, 0};
hanning.val = {1};
priorsmask = cfg_files;
priorsmask.tag = 'priorsmask';
priorsmask.name = 'Priors file';
priorsmask.filter = '(.*\.gii$)|(.*\.mat$)|(.*\.nii(,\d+)?$)|(.*\.img(,\d+)?$)';
priorsmask.num = [0 1];
priorsmask.help = {'Select a mask or a mat file with priors.'};
priorsmask.val = {{''}};
space = cfg_menu;
space.tag = 'space';
space.name = 'Prior image space';
space.help = {'Space of the mask image.'};
space.labels = {'MNI', 'Native'};
space.values = {1, 0};
space.val = {1};
priors = cfg_branch;
priors.tag = 'priors';
priors.name = 'Source priors';
priors.help = {'Restrict solutions to pre-specified VOIs'};
priors.val = {priorsmask, space};
locs = cfg_entry;
locs.tag = 'locs';
locs.name = 'Source locations';
locs.strtype = 'r';
locs.num = [Inf 3];
locs.help = {'Input source locations as n x 3 matrix'};
locs.val = {zeros(0, 3)};
radius = cfg_entry;
radius.tag = 'radius';
radius.name = 'Radius of VOI (mm)';
radius.strtype = 'r';
radius.num = [1 1];
radius.val = {32};
restrict = cfg_branch;
restrict.tag = 'restrict';
restrict.name = 'Restrict solutions';
restrict.help = {'Restrict solutions to pre-specified VOIs'};
restrict.val = {locs, radius};
custom = cfg_branch;
custom.tag = 'custom';
custom.name = 'Custom';
custom.help = {'Define custom settings for the inversion'};
custom.val = {invtype, woi, foi, hanning, priors, restrict};
isstandard = cfg_choice;
isstandard.tag = 'isstandard';
isstandard.name = 'Inversion parameters';
isstandard.help = {'Choose whether to use standard or custom inversion parameters.'};
isstandard.values = {standard, custom};
isstandard.val = {standard};
modality = cfg_menu;
modality.tag = 'modality';
modality.name = 'Select modalities';
modality.help = {'Select modalities for the inversion (only relevant for multimodal datasets).'};
modality.labels = {'All', 'EEG', 'MEG', 'MEGPLANAR', 'EEG+MEG', 'MEG+MEGPLANAR', 'EEG+MEGPLANAR'};
modality.values = {
{'All'}
{'EEG'}
{'MEG'}
{'MEGPLANAR'}
{'EEG', 'MEG'}
{'MEG', 'MEGPLANAR'}
{'EEG', 'MEGPLANAR'}
}';
modality.val = {{'All'}};
invert = cfg_exbranch;
invert.tag = 'invert';
invert.name = 'M/EEG source inversion';
invert.val = {D, val, whatconditions, isstandard, modality};
invert.help = {'Run imaging source reconstruction'};
invert.prog = @run_inversion;
invert.vout = @vout_inversion;
invert.modality = {'EEG'};
function out = run_inversion(job)
D = spm_eeg_load(job.D{1});
inverse = [];
if isfield(job.whatconditions, 'condlabel')
inverse.trials = job.whatconditions.condlabel;
end
if isfield(job.isstandard, 'custom')
inverse.type = job.isstandard.custom.invtype;
inverse.woi = fix([max(min(job.isstandard.custom.woi), 1000*D.time(1)) min(max(job.isstandard.custom.woi), 1000*D.time(end))]);
inverse.Han = job.isstandard.custom.hanning;
inverse.lpf = fix(min(job.isstandard.custom.foi));
inverse.hpf = fix(max(job.isstandard.custom.foi));
P = char(job.isstandard.custom.priors.priorsmask);
if ~isempty(P)
[p,f,e] = fileparts(P);
switch lower(e)
case '.gii'
g = gifti(P);
inverse.pQ = cell(1,size(g.cdata,2));
for i=1:size(g.cdata,2)
inverse.pQ{i} = double(g.cdata(:,i));
end
case '.mat'
load(P);
inverse.pQ = pQ;
case {'.img', '.nii'}
S.D = D;
S.fmri = P;
S.space = job.isstandard.custom.priors.space;
D = spm_eeg_inv_fmripriors(S);
inverse.fmri = D.inv{D.val}.inverse.fmri;
load(inverse.fmri.priors);
inverse.pQ = pQ;
otherwise
error('Unknown file type.');
end
end
if ~isempty(job.isstandard.custom.restrict.locs)
inverse.xyz = job.isstandard.custom.restrict.locs;
inverse.rad = job.isstandard.custom.restrict.radius;
end
end
[mod, list] = modality(D, 1, 1);
if strcmp(job.modality{1}, 'All')
inverse.modality = list;
else
inverse.modality = intersect(list, job.modality);
end
if numel(inverse.modality) == 1
inverse.modality = inverse.modality{1};
end
D = {};
for i = 1:numel(job.D)
D{i} = spm_eeg_load(job.D{i});
D{i}.val = job.val;
D{i}.con = 1;
if ~isfield(D{i}, 'inv')
error(sprintf('Forward model is missing for subject %d', i));
elseif numel(D{i}.inv)<D{i}.val || ~isfield(D{i}.inv{D{i}.val}, 'forward')
if D{i}.val>1 && isfield(D{i}.inv{D{i}.val-1}, 'forward')
D{i}.inv{D{i}.val} = D{i}.inv{D{i}.val-1};
warning(sprintf('Duplicating the last forward model for subject %d', i));
else
error(sprintf('Forward model is missing for subject %d', i));
end
end
D{i}.inv{D{i}.val}.inverse = inverse;
end
D = spm_eeg_invert(D);
if ~iscell(D)
D = {D};
end
for i = 1:numel(D)
save(D{i});
end
out.D = job.D;
function dep = vout_inversion(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'M/EEG dataset(s) after imaging source reconstruction';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_extract.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_inv_extract.m
| 3,307 |
utf_8
|
42d3e193e87fc5b983a7382f3f7d68e4
|
function extract = spm_cfg_eeg_inv_extract
% configuration file for extracting source data from imaging source
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_extract.m 4257 2011-03-18 15:28:29Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the inversion results are be stored.'};
val.val = {1};
xyz = cfg_entry;
xyz.tag = 'xyz';
xyz.name = 'Source location';
xyz.strtype = 'r';
xyz.num = [1 3];
xyz.help = {'Source location (in MNI coordinates)'};
label = cfg_entry;
label.tag = 'label';
label.name = 'Source label';
label.strtype = 's';
label.num = [1 Inf];
label.help = {'Label for the source channel in the output file'};
source = cfg_branch;
source.tag = 'source';
source.name = 'Source';
source.val = {label, xyz};
sources = cfg_repeat;
sources.tag = 'sources';
sources.name = 'Sources to extract';
sources.values = {source};
sources.num = [1 Inf];
sources.help = {'Specify sources to extract data from'};
rad = cfg_entry;
rad.tag = 'rad';
rad.name = 'VOI radius';
rad.strtype = 'r';
rad.num = [1 1];
rad.val = {5};
woi.help = {'Radius around each location to extract an eigenvariate from (mm).'};
type = cfg_menu;
type.tag = 'type';
type.name = 'What to extract';
type.help = {'What to extract: evoked activity or single trials.'};
type.labels = {'Evoked', 'Single trials'};
type.values = {'evoked', 'trials'};
type.val = {'trials'};
fname = cfg_entry;
fname.tag = 'fname';
fname.name = 'Output dataset name';
fname.strtype = 's';
fname.num = [0 Inf];
fname.val = {''};
fname.help = {'Output file name (empty for default)'};
extract = cfg_exbranch;
extract.tag = 'extract';
extract.name = 'M/EEG source extraction';
extract.val = {D, val, sources, rad, type, fname};
extract.help = {'Extract source data from the results of inverse source reconstruction'};
extract.prog = @run_extract;
extract.vout = @vout_extract;
extract.modality = {'EEG'};
function out = run_extract(job)
source = [];
source.XYZ = cat(1, job.source.xyz);
source.label = {job.source.label};
source.rad = job.rad;
source.type = job.type;
if ~isempty(job.fname)
source.fname = job.fname;
end
out.D = {};
for i = 1:numel(job.D)
D = spm_eeg_load(job.D{i});
D.val = job.val;
if ~isfield(D.inv{D.val}, 'inverse') || ~isfield(D.inv{D.val}.inverse, 'J')
error(sprintf('Imaging source reconstruction is missing for subject %d', i));
end
D.inv{D.val}.source = source;
Ds = spm_eeg_inv_extract(D);
out.D{i, 1} = fullfile(Ds.path, Ds.fname);
end
function dep = vout_extract(job)
% Output is always in field "D", no matter how job is structured
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'M/EEG dataset(s) extracted source data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_fmri_est.m
|
.m
|
antx-master/xspm8/config/spm_cfg_fmri_est.m
| 24,501 |
utf_8
|
14607a45526013760c39408f23f0d2fa
|
function fmri_est = spm_cfg_fmri_est
% SPM Configuration file for Model Estimation
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_fmri_est.m 3753 2010-03-05 13:06:47Z guillaume $
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {
'Select the SPM.mat file that contains the design specification. '
'The directory containing this file is known as the input directory.'
}';
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 1];
% ---------------------------------------------------------------------
% Classical Classical
% ---------------------------------------------------------------------
Classical = cfg_const;
Classical.tag = 'Classical';
Classical.name = 'Classical';
Classical.val = {1};
Classical.help = {
'Model parameters are estimated using Restricted Maximum Likelihood (ReML). This assumes the error correlation structure is the same at each voxel. This correlation can be specified using either an AR(1) or an Independent and Identically Distributed (IID) error model. These options are chosen at the model specification stage. ReML estimation should be applied to spatially smoothed functional images.'
''
'After estimation, specific profiles of parameters are tested using a linear compound or contrast with the T or F statistic. The resulting statistical map constitutes an SPM. The SPM{T}/{F} is then characterised in terms of focal or regional differences by assuming that (under the null hypothesis) the components of the SPM (ie. residual fields) behave as smooth stationary Gaussian fields.'
}';
% ---------------------------------------------------------------------
% Volume Volume
% ---------------------------------------------------------------------
volBlocktype = cfg_menu;
volBlocktype.tag = 'block_type';
volBlocktype.name = 'Block type';
volBlocktype.val = {'Slices'};
volBlocktype.help = {'Enter the block type, i.e. "Slices" or "Subvolumes"'}';
volBlocktype.labels = {'Slices', 'Subvolumes'}';
volBlocktype.values = {'Slices', 'Subvolumes'}';
Volume = cfg_branch;
Volume.tag = 'volume';
Volume.name = 'Volume';
Volume.val = {volBlocktype};
Volume.help = {'A volume of data is analysed in "blocks", which can be a slice or 3D subvolume, where the extent of each subvolume is determined using a graph partitioning algorithm. Enter the block type, i.e. "Slices" or "Subvolumes".'};
% ---------------------------------------------------------------------
% Slices Slices
% ---------------------------------------------------------------------
SliceNs = cfg_entry;
SliceNs.tag = 'numbers';
SliceNs.name = 'Slice numbers';
SliceNs.help = {' '};
SliceNs.strtype = 'e';
SliceNs.num = [Inf 1];
slBlocktype = cfg_menu;
slBlocktype.tag = 'block_type';
slBlocktype.name = 'Block type';
slBlocktype.val = {'Slices'};
slBlocktype.help = {'Enter the block type, i.e. "Slices" or "Subvolumes"'}';
slBlocktype.labels = {'Slices', 'Subvolumes'}';
slBlocktype.values = {'Slices', 'Subvolumes'}';
Slices = cfg_branch;
Slices.tag = 'slices';
Slices.name = 'Slices';
Slices.val = {SliceNs slBlocktype};
Slices.help = {'Enter Slice Numbers. This can be a single slice or multiple slices. If you select a single slice or only a few slices you must be aware of the interpolation options when, after estimation, displaying the estimated images eg. images of contrasts or AR maps. The default interpolation option may need to be changed to nearest neighbour (NN) (see bottom right hand of graphics window) for you slice maps to be visible.'};
% ---------------------------------------------------------------------
% Clusters
% ---------------------------------------------------------------------
Clustermask = cfg_files;
Clustermask.tag = 'mask';
Clustermask.name = 'Cluster mask';
Clustermask.help = {'Select cluster image'}';
Clustermask.filter = 'image';
Clustermask.ufilter = '.*';
Clustermask.num = [0 1];
clBlocktype = cfg_menu;
clBlocktype.tag = 'block_type';
clBlocktype.name = 'Block type';
clBlocktype.val = {'Slices'};
clBlocktype.help = {'Enter the block type, i.e. "Slices" or "Subvolumes"'}';
clBlocktype.labels = {'Slices', 'Subvolumes'}';
clBlocktype.values = {'Slices', 'Subvolumes'}';
Clusters = cfg_branch;
Clusters.tag = 'clusters';
Clusters.name = 'Clusters';
Clusters.val = {Clustermask clBlocktype};
Clusters.help = {'Because estimation can be time consuming an option is provided to analyse selected clusters rather than the whole volume.'};
% ---------------------------------------------------------------------
% space Analysis Space
% ---------------------------------------------------------------------
space = cfg_choice;
space.tag = 'space';
space.name = 'Analysis Space';
space.val = {Volume};
space.help = {'Because estimation can be time consuming options are provided to analyse selected slices or clusters rather than the whole volume.'};
space.values = {Volume Slices Clusters};
% ---------------------------------------------------------------------
% LogEv - Compute F
% ---------------------------------------------------------------------
LogEv = cfg_menu;
LogEv.tag = 'LogEv';
LogEv.name = 'Log evidence map';
LogEv.val = {'No'};
LogEv.help = {'Computes the log evidence for each voxel'};
LogEv.labels = {'No','Yes'}';
LogEv.values = {'No','Yes'}';
% ---------------------------------------------------------------------
% signal Signal priors
% ---------------------------------------------------------------------
signal = cfg_menu;
signal.tag = 'signal';
signal.name = 'Signal priors';
signal.help = {
'[UGL] Unweighted Graph Laplacian. This spatial prior is the recommended option. Regression coefficients at a given voxel are (softly) constrained to be similar to those at nearby voxels. The strength of this constraint is determined by a spatial precision parameter that is estimated from the data. Different regression coefficients have different spatial precisions allowing each putative experimental effect to have its own spatial regularity. '
''
'[GMRF] Gaussian Markov Random Field. This is equivalent to a normalized UGL. '
''
'[LORETA] Low resolution Tomography Prior. This is equivalent to UGL squared. It is a standatd choice for EEG source localisation algorithms. '
''
'[WGL] Weighted Graph Laplacian. This is a generalization of the UGL, where weights can be used to preserve "edges" of functional responses.'
''
'[Global] Global Shrinkage prior. This is not a spatial prior in the sense that regression coefficients are constrained to be similar to neighboring voxels. Instead, the average effect over all voxels (global effect) is assumed to be zero and all regression coefficients are shrunk towards this value in proporation to the prior precision. This is the same prior that is used for Bayesian estimation at the second level models, except that here the prior precision is estimated separaetly for each slice. '
''
'[Uninformative] A flat prior. Essentially, no prior information is used. If you select this option then VB reduces to Maximum Likelihood (ML)estimation. This option is useful if, for example, you do not wish to use a spatial prior but wish to take advantage of the voxel-wise AR(P) modelling of noise processes. In this case, you would apply the algorithm to images that have been spatially smoothed. For P=0, ML estimation in turn reduces to Ordinary Least Squares (OLS) estimates, and for P>0 ML estimation is equivalent to a weighted least squares (WLS) but where the weights are different at each voxel (reflecting the different noise correlation at each voxel). '
}';
signal.labels = {
'UGL'
'GMRF'
'LORETA'
'WGL'
'Global'
'Uninformative'
}';
signal.values = {
'UGL'
'GMRF'
'LORETA'
'WGL'
'Global'
'Uninformative'
}';
signal.val = {'UGL'};
% ---------------------------------------------------------------------
% ARP AR model order
% ---------------------------------------------------------------------
ARP = cfg_entry;
ARP.tag = 'ARP';
ARP.name = 'AR model order';
ARP.help = {
'An AR model order of 3 is the default. Cardiac and respiratory artifacts are periodic in nature and therefore require an AR order of at least 2. In previous work, voxel-wise selection of the optimal model order showed that a value of 3 was the highest order required. '
''
'Higher model orders have little effect on the estimation time. If you select a model order of zero this corresponds to the assumption that the errors are IID. This AR specification overrides any choices that were made in the model specification stage.'
''
'Voxel-wise AR models are fitted separately for each session of data. For each session this therefore produces maps of AR(1), AR(2) etc coefficients in the output directory. '
}';
ARP.strtype = 'e';
ARP.num = [Inf 1];
ARP.val = {3};
% ---------------------------------------------------------------------
% UGL UGL
% ---------------------------------------------------------------------
UGL = cfg_const;
UGL.tag = 'UGL';
UGL.name = 'UGL';
UGL.val = {1};
UGL.help = {'[UGL] Unweighted graph-Laplacian. This is the default option. This spatial prior is the same as that used for the regression coefficients. Spatial precisions are estimated separately for each AR coefficient eg. the AR(1) coefficient over space, AR(2) over space etc. '};
% ---------------------------------------------------------------------
% GMRF GMRF
% ---------------------------------------------------------------------
GMRF = cfg_const;
GMRF.tag = 'GMRF';
GMRF.name = 'GMRF';
GMRF.val = {1};
GMRF.help = {'[GMRF] Gaussian Markov Random Field. See comments on GMRF priors for regresion coefficients. '};
% ---------------------------------------------------------------------
% LORETA LORETA
% ---------------------------------------------------------------------
LORETA = cfg_const;
LORETA.tag = 'LORETA';
LORETA.name = 'LORETA';
LORETA.val = {1};
LORETA.help = {'[LORETA] Low resolution Tomography Prior. See comments on LORETA priors for regresion coefficients.'};
% ---------------------------------------------------------------------
% tissue_type Tissue-type
% ---------------------------------------------------------------------
tissue_type = cfg_files;
tissue_type.tag = 'tissue_type';
tissue_type.name = 'Tissue-type';
tissue_type.help = {
'[Tissue-type] AR estimates at each voxel are biased towards typical values for that tissue type (eg. gray, white, CSF). If you select this option you will need to then select files that contain tissue type maps (see below). These are typically chosen to be Grey Matter, White Matter and CSF images derived from segmentation of registered structural scans.'
''
'Previous work has shown that there is significant variation in AR values with tissue type. However, GMRF priors have previously been favoured by Bayesian model comparison.'
}';
tissue_type.filter = 'image';
tissue_type.ufilter = '.*';
tissue_type.num = [1 Inf];
% ---------------------------------------------------------------------
% Robust Robust
% ---------------------------------------------------------------------
Robust = cfg_const;
Robust.tag = 'Robust';
Robust.name = 'Robust';
Robust.val = {1};
Robust.help = {'Robust GLM. Uses Mixture of Gaussians noise model.'};
% ---------------------------------------------------------------------
% noise Noise priors
% ---------------------------------------------------------------------
noise = cfg_choice;
noise.tag = 'noise';
noise.name = 'Noise priors';
noise.val = {UGL };
noise.help = {
'There are five noise prior options here (1) UGL, (2) GMRF, (3) LORETA '
'(4) Tissue-type and (5) Robust'
}';
noise.values = {UGL GMRF LORETA tissue_type Robust };
% ---------------------------------------------------------------------
% first First level
% ---------------------------------------------------------------------
first = cfg_menu;
first.tag = 'first';
first.name = 'First level';
first.val = {'No'};
first.help = {
'This is implemented using Bayesian model comparison. For example, to test for the main effect of a factor two models are compared, one where the levels are represented using different regressors and one using the same regressor. This therefore requires explicit fitting of several models at each voxel and is computationally demanding (requiring several hours of computation). The recommended option is therefore NO.'
''
'To use this option you must have already specified your factorial design during the model specification stage. '
}';
first.labels = {
'No'
'Yes'
}';
first.values = {
'No'
'Yes'
}';
% ---------------------------------------------------------------------
% second Second level
% ---------------------------------------------------------------------
second = cfg_menu;
second.tag = 'second';
second.name = 'Second level';
second.val = {'Yes'};
second.help = {
'This option tells SPM to automatically generate the simple contrasts that are necessary to produce the contrast images for a second-level (between-subject) ANOVA. Naturally, these contrasts can also be used to characterise simple effects for each subject. '
''
'With the Bayesian estimation option it is recommended that contrasts are computed during the parameter estimation stage (see ''simple contrasts'' below). The recommended option here is therefore YES.'
''
'To use this option you must have already specified your factorial design during the model specification stage. '
''
'If you wish to use these contrast images for a second-level analysis then you will need to spatially smooth them to take into account between-subject differences in functional anatomy ie. the fact that one persons V5 may be in a different position than anothers. '
}';
second.labels = {
'No'
'Yes'
}';
second.values = {
'No'
'Yes'
}';
% ---------------------------------------------------------------------
% anova ANOVA
% ---------------------------------------------------------------------
anova = cfg_branch;
anova.tag = 'anova';
anova.name = 'ANOVA';
anova.val = {first second };
anova.help = {'Perform 1st or 2nd level Analysis of Variance.'};
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of contrast eg. ''Positive Effect'''};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% convec Contrast vector
% ---------------------------------------------------------------------
convec = cfg_entry;
convec.tag = 'convec';
convec.name = 'Contrast vector';
convec.help = {'These contrasts are used to generate PPMs which characterise effect sizes at each voxel. This is in contrast to SPMs in which eg. maps of t-statistics show the ratio of the effect size to effect variability (standard deviation). SPMs are therefore a-dimensional. This is not the case for PPMs as the size of the effect is of primary interest. Some care is therefore needed about the scaling of contrast vectors. For example, if you are interested in the differential effect size averaged over conditions then the contrast 0.5 0.5 -0.5 -0.5 would be more suitable than the 1 1 -1 -1 contrast which looks at the differential effect size summed over conditions. '};
convec.strtype = 'e';
convec.num = [Inf 1];
% ---------------------------------------------------------------------
% gcon Simple contrast
% ---------------------------------------------------------------------
gcon = cfg_branch;
gcon.tag = 'gcon';
gcon.name = 'Simple contrast';
gcon.val = {name convec };
gcon.help = {''};
% ---------------------------------------------------------------------
% generic Simple contrasts
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Simple contrasts';
generic.help = {
'''Simple'' contrasts refers to a contrast that spans one-dimension ie. to assess an effect that is increasing or decreasing.'
''
'If you have a factoral design then the contrasts needed to generate the contrast images for a 2nd-level ANOVA (or to assess these simple effects within-subject) can be specified automatically using the ANOVA->Second level option.'
''
'When using the Bayesian estimation option it is computationally more efficient to compute the contrasts when the parameters are estimated. This is because estimated parameter vectors have potentially different posterior covariance matrices at different voxels and these matrices are not stored. If you compute contrasts post-hoc these matrices must be recomputed (an approximate reconstruction based on a Taylor series expansion is used). It is therefore recommended to specify as many contrasts as possible prior to parameter estimation.'
''
'If you wish to use these contrast images for a second-level analysis then you will need to spatially smooth them to take into account between-subject differences in functional anatomy ie. the fact that one persons V5 may be in a different position than anothers. '
}';
generic.values = {gcon };
generic.num = [0 Inf];
% ---------------------------------------------------------------------
% Bayesian Bayesian 1st-level
% ---------------------------------------------------------------------
Bayesian = cfg_branch;
Bayesian.tag = 'Bayesian';
Bayesian.name = 'Bayesian 1st-level';
Bayesian.val = {space signal ARP noise LogEv anova generic };
Bayesian.help = {
'Model parameters are estimated using Variational Bayes (VB). This allows you to specify spatial priors for regression coefficients and regularised voxel-wise AR(P) models for fMRI noise processes. The algorithm does not require functional images to be spatially smoothed. Estimation will take about 5 times longer than with the classical approach. This is why VB is not the default estimation option. '
''
'Model estimation using this option is only efficient if MATLAB can load a whole slice of data into physical memory. With modern PCs this is usually achieved if the within-plane voxel sizes are 3 by 3 mm. This is therefore the minimum recommended voxel size that your spatial normalisation process should produce. Within-plane voxel sizes of 2 by 2 mm usually result in too many voxels per slice and result in estimation times lasting several hours or days. Such a high resolution is therefore to be avoided. '
''
'After estimation, contrasts are used to find regions with effects larger than a user-specified size eg. 1 per cent of the global mean signal. These effects are assessed statistically using a Posterior Probability Map (PPM).'
}';
% ---------------------------------------------------------------------
% Bayesian2 Bayesian 2nd-level
% ---------------------------------------------------------------------
Bayesian2 = cfg_const;
Bayesian2.tag = 'Bayesian2';
Bayesian2.name = 'Bayesian 2nd-level';
Bayesian2.val = {1};
Bayesian2.help = {'Bayesian estimation of 2nd level models. This option uses the Empirical Bayes algorithm with global shrinkage priors that was previously implemented in SPM2. Use of the global shrinkage prior embodies a prior belief that, on average over all voxels, there is no net experimental effect. Some voxels will respond negatively and some positively with a variability determined by the prior precision. This prior precision can be estimated from the data using Empirical Bayes. '};
% ---------------------------------------------------------------------
% method Method
% ---------------------------------------------------------------------
method = cfg_choice;
method.tag = 'method';
method.name = 'Method';
method.val = {Classical };
method.help = {
'There are three possible estimation procedures for fMRI models (1) classical (ReML) estimation of first or second level models, (2) Bayesian estimation of first level models and (3) Bayesian estimation of second level models. Option (2) uses a Variational Bayes (VB) algorithm that is new to SPM5. Option (3) uses the Empirical Bayes algorithm with global shrinkage priors that was also in SPM2. '
''
'To use option (3) you must have already estimated the model using option (1). That is, for second-level models you must run a ReML estimation before running a Bayesian estimation. This is not necessary for option (2). Bayesian estimation of 1st-level models using VB does not require a prior ReML estimation.'
}';
method.values = {Classical Bayesian Bayesian2};
% ---------------------------------------------------------------------
% fmri_est Model estimation
% ---------------------------------------------------------------------
fmri_est = cfg_exbranch;
fmri_est.tag = 'fmri_est';
fmri_est.name = 'Model estimation';
fmri_est.val = {spmmat method };
fmri_est.help = {'Model parameters can be estimated using classical (ReML - Restricted Maximum Likelihood) or Bayesian algorithms. After parameter estimation, the RESULTS button can be used to specify contrasts that will produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs) and tables of statistics.'};
fmri_est.prog = @spm_run_fmri_est;
fmri_est.vout = @vout_stats;
fmri_est.modality = {'FMRI' 'PET' 'EEG'};
%==========================================================================
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
if isfield(job.method, 'Classical')
dep(2) = cfg_dep;
dep(2).sname = 'Beta Images';
dep(2).src_output = substruct('.','beta');
dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
dep(3) = cfg_dep;
dep(3).sname = 'Analysis Mask';
dep(3).src_output = substruct('.','mask');
dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
dep(4) = cfg_dep;
dep(4).sname = 'ResMS Image';
dep(4).src_output = substruct('.','resms');
dep(4).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
% can't check whether auto-generated contrasts are generated this is
% specified in input SPM.mat, not this job
end;
|
github
|
philippboehmsturm/antx-master
|
paint.m
|
.m
|
antx-master/xspm8/@slover/paint.m
| 10,669 |
utf_8
|
58c77775943c79df7da192623addf239
|
function obj = paint(obj, params)
% method to display slice overlay
% FORMAT paint(obj, params)
%
% Inputs
% obj - slice overlay object
% params - optional structure containing extra display parameters
% - refreshf - overrides refreshf in object
% - clf - overrides clf in object
% - userdata - if 0, does not add object to userdata field
% (see below)
%
% Outputs
% obj - which may have been filled with defaults
%
% paint attaches the object used for painting to the 'UserData' field of
% the figure handle, unless instructed not to with 0 in userdata flag
%
% $Id: paint.m,v 1.2 2005/05/06 22:59:56 matthewbrett Exp $
fig_struct_fields = {'Position', 'Units'};
if nargin < 2
params = [];
end
params = mars_struct('fillafromb', params, ...
struct('refreshf', obj.refreshf,...
'clf', obj.clf, ...
'userdata', obj.userdata));
% Fill any needed defaults
obj = fill_defaults(obj);
% check if object can be painted
if isempty(obj.img)
warning('slover:noImages', 'No images, object cannot be painted')
return
end
% get coordinates for plane
X=1;Y=2;Z=3;
dims = obj.slicedef;
xmm = dims(X,1):dims(X,2):dims(X,3);
ymm = dims(Y,1):dims(Y,2):dims(Y,3);
zmm = obj.slices;
[y x] = meshgrid(ymm,xmm');
vdims = [length(xmm),length(ymm),length(zmm)];
% no of slices, and panels (an extra for colorbars)
nslices = vdims(Z);
minnpanels = nslices;
cbars = 0;
if ~isempty(obj.cbar)
cbars = length(obj.cbar);
minnpanels = minnpanels+cbars;
end
% Get figure data. The figure may be dead, in which case we may want to
% revive it. If so, we set position etc as stored.
% If written to, the axes may be specified already
dead_f = ~ishandle(obj.figure);
figno = figure(obj.figure);
if dead_f
set(figno, obj.figure_struct);
end
% (re)initialize axes and stuff
% check if the figure is set up correctly
if ~params.refreshf
axisd = flipud(findobj(obj.figure, 'Type','axes','Tag', 'slice overlay panel'));
npanels = length(axisd);
if npanels < vdims(Z)+cbars;
params.refreshf = 1;
end
end
if params.refreshf
% clear figure, axis store
if params.clf, clf; end
% prevent print inversion problems
set(figno,'InvertHardCopy','off');
% put copy of object into UserData for callbacks
if params.userdata
set(figno, 'UserData', obj);
end
% calculate area of display in pixels
parea = obj.area.position;
if ~strcmp(obj.area.units, 'pixels')
ubu = get(obj.figure, 'units');
set(obj.figure, 'units','pixels');
tmp = get(obj.figure, 'Position');
ascf = tmp(3:4);
if ~strcmp(obj.area.units, 'normalized')
set(obj.figure, 'units',obj.area.units);
tmp = get(obj.figure, 'Position');
ascf = ascf ./ tmp(3:4);
end
set(figno, 'Units', ubu);
parea = parea .* repmat(ascf, 1, 2);
end
asz = parea(3:4);
% by default, make most parsimonious fit to figure
yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2));
if isempty(obj.xslices)
% iteration needed to optimize, surprisingly. Thanks to Ian NS
axlen(X,:)=asz(1):-1:1;
axlen(Y,:)=yxratio*axlen(X,:);
panels = floor(asz'*ones(1,size(axlen,2))./axlen);
estnpanels = prod(panels);
tmp = find(estnpanels >= minnpanels);
if isempty(tmp)
error('Whoops, cannot fit panels onto figure');
end
b = tmp(1); % best fitting scaling
panels = panels(:,b);
axlen = axlen(:, b);
else
% if xslices is specified, assume X is flush with X figure dimensions
panels(X:Y,1) = [obj.xslices; 0];
axlen(X:Y,1) = [asz(X)/panels(X); 0];
end
% Axis dimensions are in pixels. This prevents aspect ratio rescaling
panels(Y) = ceil(minnpanels/panels(X));
axlen(Y) = axlen(X)*yxratio;
% centre (etc) panels in display area as required
divs = [Inf 2 1];the_ds = [0;0];
the_ds(X) = divs(strcmp(obj.area.halign, {'left','center','right'}));
the_ds(Y) = divs(strcmp(obj.area.valign, {'bottom','middle','top'}));
startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds;
% make axes for panels
r=0;c=1;
npanels = prod(panels);
lastempty = npanels-cbars;
axisd = nan(1, npanels);
for i = 1:npanels
% panel userdata
if i<=nslices
u.type = 'slice';
u.no = zmm(i);
elseif i > lastempty
u.type = 'cbar';
u.no = i - lastempty;
else
u.type = 'empty';
u.no = i - nslices;
end
axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen'];
axisd(i) = axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'YTick',[],...
'YTickLabel',[],...
'Box','on',...
'XLim',[1 vdims(X)],...
'YLim',[1 vdims(Y)],...
'Units', 'pixels',...
'Position',axpos,...
'Tag','slice overlay panel',...
'UserData',u);
r = r+1;
if r >= panels(X)
r = 0;
c = c+1;
end
end
end
% sort out labels
if ischar(obj.labels)
do_labels = ~strcmpi(obj.labels, 'none');
else
do_labels = 1;
end
if do_labels
labels = obj.labels;
if iscell(labels.format)
if length(labels.format)~=vdims(Z)
error('Oh dear, expecting %d labels, but found %d', ...
vdims(Z), length(labels.contents));
end
else
% format string for mm from AC labelling
fstr = labels.format;
labels.format = cell(vdims(Z),1);
acpt = obj.transform * [0 0 0 1]';
for i = 1:vdims(Z)
labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))};
end
end
end
% split images into picture and contour
itypes = {obj.img(:).type};
tmp = strcmpi(itypes, 'contour');
contimgs = find(tmp);
pictimgs = find(~tmp);
% modify picture image colormaps with any new colours
npimgs = length(pictimgs);
lrn = zeros(npimgs,3);
cmaps = cell(npimgs);
for i = 1:npimgs
cmaps(i)={obj.img(pictimgs(i)).cmap};
lrnv = [obj.img(pictimgs(i)).outofrange, obj.img(pictimgs(i)).nancol];
for j = 1:length(lrnv)
if numel(lrnv{j})==1
lrn(i,j) = lrnv{j};
else
cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]};
lrn(i,j) = size(cmaps{i},1);
end
end
end
% cycle through slices displaying images
nvox = prod(vdims(1:2));
pandims = [vdims([2 1]) 3]; % NB XY transpose for display
zimg = zeros(pandims);
for i = 1:nslices
ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)];
img = zimg;
for j = 1:npimgs
thisimg = obj.img(pictimgs(j));
i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);
% rescale to colormap
[csdata badvals]= pr_scaletocmap(...
i1,...
thisimg.range(1),...
thisimg.range(2),...
thisimg.cmap,...
lrn(j,:));
% take indices from colormap to make true colour image
iimg = reshape(cmaps{j}(csdata(:),:),pandims);
tmp = repmat(logical(~badvals),[1 1 3]);
if strcmpi(thisimg.type, 'truecolour')
img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop;
else % split colormap effect
img(tmp) = iimg(tmp)*thisimg.prop;
end
end
% threshold out of range values
img(img>1) = 1;
image('Parent', axisd(i),...
'ButtonDownFcn', obj.callback,...
'CData',img);
% do contour plot
for j=1:length(contimgs)
thisimg = obj.img(contimgs(j));
i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);
if any(any(isfinite(i1)))
i1(i1<min(thisimg.range))=min(thisimg.range);
i1(i1>max(thisimg.range))=max(thisimg.range);
if ~any(diff(i1(isfinite(i1)))), continue, end % skip empty planes
if mars_struct('isthere', thisimg, 'linespec')
linespec = thisimg.linespec;
else
linespec = 'w-';
end
set(axisd(i),'NextPlot','add');
if mars_struct('isthere', thisimg, 'contours')
[c h] = contour(axisd(i), i1, thisimg.contours, linespec);
else
[c h] = contour(axisd(i), i1, linespec);
end
if ~isempty(h)
if ~mars_struct('isthere', thisimg, 'linespec')
% need to reset colours; contour assumes you just set the figure's
% colormap, but to overlay coloured contours on a greyscale image,
% one needs to have everything in truecolour, setting individual
% contour lines to their appropriate colour.
% (updated for MATLAB 7 and above)
convals = get(h, 'LevelList');
if ~isempty(convals)
csdata = pr_scaletocmap(...
convals,...
thisimg.range(1),...
thisimg.range(2),...
thisimg.cmap,...
[1 size(thisimg.cmap,1) 1]);
colvals = thisimg.cmap(csdata(:),:)*thisimg.prop;
for ch = get(h, 'Children')' % (NB: transpose needed to loop)
CData = get(ch, 'CData'); % (CData is constant with final NaN)
colval = colvals(find(convals == CData(1), 1), :);
set(ch, 'EdgeColor', colval)
end
end
end
if mars_struct('isthere', thisimg, 'linewidth')
set(h, 'LineWidth', thisimg.linewidth);
end
end
end
end
if do_labels
text('Parent',axisd(i),...
'Color', labels.colour,...
'FontUnits', 'normalized',...
'VerticalAlignment','bottom',...
'HorizontalAlignment','left',...
'Position', [1 1],...
'FontSize',labels.size,...
'ButtonDownFcn', obj.callback,...
'String', labels.format{i});
end
end
for i = (nslices+1):npanels
set(axisd(i),'Color',[0 0 0]);
end
% add colorbar(s)
for i = 1:cbars
axno = axisd(end-cbars+i);
cbari = obj.img(obj.cbar(i));
cml = size(cbari.cmap,1);
p = get(axno, 'Position'); % position of last axis
cw = p(3)*0.2;
ch = p(4)*0.75;
pc = p(3:4)/2;
[axlims idxs] = sort(cbari.range);
a=axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'Units', 'pixels',...
'YLim', axlims,...
'FontUnits', 'normalized',...
'FontSize', 0.075,...
'YColor',[1 1 1],...
'Tag', 'cbar',...
'Box', 'off',...
'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]...
);
image('Parent', a,...
'YData', axlims(idxs),...
'CData', reshape(cbari.cmap,[cml,1,3]));
end % colourbars
% Get stuff for figure, in case it dies later
obj.figure_struct = mars_struct('split', get(figno), fig_struct_fields);
return
% subfunctions
% ------------
function i1 = sf_slice2panel(img, xyzmm, transform, vdims)
% to voxel space of image
vixyz = (transform*img.vol.mat) \ xyzmm;
% raw data
if mars_struct('isthere', img.vol, 'imgdata')
V = img.vol.imgdata;
else
V = img.vol;
end
i1 = spm_sample_vol(V,vixyz(1,:),vixyz(2,:),vixyz(3,:), ...
[img.hold img.background]);
if mars_struct('isthere', img, 'func')
eval(img.func);
end
% transpose to reverse X and Y for figure
i1 = reshape(i1, vdims(1:2))';
return
|
github
|
philippboehmsturm/antx-master
|
pr_basic_ui.m
|
.m
|
antx-master/xspm8/@slover/private/pr_basic_ui.m
| 3,679 |
utf_8
|
88d91189a824825f094d4979cbdc7fb4
|
function obj = pr_basic_ui(imgs, dispf)
% GUI to request parameters for slover routine
% FORMAT obj = pr_basic_ui(imgs, dispf)
%
% GUI requests choices while accepting many defaults
%
% imgs - string or cell array of image names to display
% (defaults to GUI select if no arguments passed)
% dispf - optional flag: if set, displays overlay (default = 1)
%
% $Id: pr_basic_ui.m,v 1.1 2005/04/20 15:05:00 matthewbrett Exp $
if nargin < 1
imgs = '';
end
if isempty(imgs)
imgs = spm_select(Inf, 'image', 'Image(s) to display');
end
if ischar(imgs)
imgs = cellstr(imgs);
end
if nargin < 2
dispf = 1;
end
spm_input('!SetNextPos', 1);
% load images
nimgs = size(imgs);
% process names
nchars = 20;
imgns = spm_str_manip(imgs, ['rck' num2str(nchars)]);
% Get new default object
obj = slover;
% identify image types
cscale = [];
deftype = 1;
obj.cbar = [];
for i = 1:nimgs
obj.img(i).vol = spm_vol(imgs{i});
options = {'Structural','Truecolour', ...
'Blobs','Negative blobs','Contours'};
% if there are SPM results in the workspace, add this option
[XYZ Z M] = pr_get_spm_results;
if ~isempty(XYZ)
options = {'Structural with SPM blobs', options{:}};
end
itype = spm_input(sprintf('Img %d: %s - image type?', i, imgns{i}), '+1', ...
'm', char(options),options, deftype);
imgns(i) = {sprintf('Img %d (%s)',i,itype{1})};
[mx mn] = slover('volmaxmin', obj.img(i).vol);
if ~isempty(strmatch('Structural', itype))
obj.img(i).type = 'truecolour';
obj.img(i).cmap = gray;
obj.img(i).range = [mn mx];
deftype = 2;
cscale = [cscale i];
if strcmp(itype,'Structural with SPM blobs')
obj = add_spm(obj);
end
else
cprompt = ['Colormap: ' imgns{i}];
switch itype{1}
case 'Truecolour'
obj.img(i).type = 'truecolour';
dcmap = 'flow.lut';
drange = [mn mx];
cscale = [cscale i];
obj.cbar = [obj.cbar i];
case 'Blobs'
obj.img(i).type = 'split';
dcmap = 'hot';
drange = [0 mx];
obj.img(i).prop = 1;
obj.cbar = [obj.cbar i];
case 'Negative blobs'
obj.img(i).type = 'split';
dcmap = 'winter';
drange = [0 mn];
obj.img(i).prop = 1;
obj.cbar = [obj.cbar i];
case 'Contours'
obj.img(i).type = 'contour';
dcmap = 'white';
drange = [mn mx];
obj.img(i).prop = 1;
end
obj.img(i).cmap = sf_return_cmap(cprompt, dcmap);
obj.img(i).range = spm_input('Img val range for colormap','+1', 'e', drange, 2);
end
end
ncmaps=length(cscale);
if ncmaps == 1
obj.img(cscale).prop = 1;
else
remcol=1;
for i = 1:ncmaps
ino = cscale(i);
obj.img(ino).prop = spm_input(sprintf('%s intensity',imgns{ino}),...
'+1', 'e', ...
remcol/(ncmaps-i+1),1);
remcol = remcol - obj.img(ino).prop;
end
end
obj.transform = deblank(spm_input('Image orientation', '+1', ['Axial|' ...
' Coronal|Sagittal'], strvcat('axial','coronal','sagittal'), ...
1));
% use SPM figure window
obj.figure = spm_figure('GetWin', 'Graphics');
% slices for display
obj = fill_defaults(obj);
slices = obj.slices;
obj.slices = spm_input('Slices to display (mm)', '+1', 'e', ...
sprintf('%0.0f:%0.0f:%0.0f',...
slices(1),...
mean(diff(slices)),...
slices(end))...
);
% and do the display
if dispf, obj = paint(obj); end
return
% Subfunctions
% ------------
function cmap = sf_return_cmap(prompt,defmapn)
cmap = [];
while isempty(cmap)
[cmap w]= slover('getcmap', spm_input(prompt,'+1','s', defmapn));
if isempty(cmap), disp(w);end
end
return
|
github
|
philippboehmsturm/antx-master
|
delete.m
|
.m
|
antx-master/xspm8/@xmltree/delete.m
| 1,203 |
utf_8
|
f523d5fa52766f6af01c283da5bb87bf
|
function tree = delete(tree,uid)
% XMLTREE/DELETE Delete (delete a subtree given its UID)
%
% tree - XMLTree object
% uid - array of UID's of subtrees to be deleted
%_______________________________________________________________________
%
% Delete a subtree given its UID
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: delete.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(2,2,nargin));
uid = uid(:);
for i=1:length(uid)
if uid(i)==1
warning('[XMLTree] Cannot delete root element.');
else
p = tree.tree{uid(i)}.parent;
tree = sub_delete(tree,uid(i));
tree.tree{p}.contents(find(tree.tree{p}.contents==uid(i))) = [];
end
end
%=======================================================================
function tree = sub_delete(tree,uid)
if isfield(tree.tree{uid},'contents')
for i=1:length(tree.tree{uid}.contents)
tree = sub_delete(tree,tree.tree{uid}.contents(i));
end
end
tree.tree{uid} = struct('type','deleted');
|
github
|
philippboehmsturm/antx-master
|
save.m
|
.m
|
antx-master/xspm8/@xmltree/save.m
| 5,121 |
utf_8
|
fa70739c5d89fa5e5759fe4d0dd5d1b3
|
function varargout = save(tree, filename)
% XMLTREE/SAVE Save an XML tree in an XML file
% FORMAT varargout = save(tree,filename)
%
% tree - XMLTree
% filename - XML output filename
% varargout - XML string
%_______________________________________________________________________
%
% Convert an XML tree into a well-formed XML string and write it into
% a file or return it as a string if no filename is provided.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: save.m 4393 2011-07-18 14:52:32Z guillaume $
error(nargchk(1,2,nargin));
prolog = '<?xml version="1.0" ?>\n';
%- Return the XML tree as a string
if nargin == 1
varargout{1} = [sprintf(prolog) ...
print_subtree(tree,'',root(tree))];
%- Output specified
else
%- Filename provided
if ischar(filename)
[fid, msg] = fopen(filename,'w');
if fid==-1, error(msg); end
if isempty(tree.filename), tree.filename = filename; end
%- File identifier provided
elseif isnumeric(filename) && numel(filename) == 1
fid = filename;
prolog = ''; %- With this option, do not write any prolog
else
error('[XMLTree] Invalid argument.');
end
fprintf(fid,prolog);
save_subtree(tree,fid,root(tree));
if ischar(filename), fclose(fid); end
if nargout == 1
varargout{1} = print_subtree(tree,'',root(tree));
end
end
%=======================================================================
function xmlstr = print_subtree(tree,xmlstr,uid,order)
if nargin < 4, order = 0; end
xmlstr = [xmlstr blanks(3*order)];
switch tree.tree{uid}.type
case 'element'
xmlstr = sprintf('%s<%s',xmlstr,tree.tree{uid}.name);
for i=1:length(tree.tree{uid}.attributes)
xmlstr = sprintf('%s %s="%s"', xmlstr, ...
tree.tree{uid}.attributes{i}.key,...
tree.tree{uid}.attributes{i}.val);
end
if isempty(tree.tree{uid}.contents)
xmlstr = sprintf('%s/>\n',xmlstr);
else
xmlstr = sprintf('%s>\n',xmlstr);
for i=1:length(tree.tree{uid}.contents)
xmlstr = print_subtree(tree,xmlstr, ...
tree.tree{uid}.contents(i),order+1);
end
xmlstr = [xmlstr blanks(3*order)];
xmlstr = sprintf('%s</%s>\n',xmlstr,...
tree.tree{uid}.name);
end
case 'chardata'
xmlstr = sprintf('%s%s\n',xmlstr, ...
entity(tree.tree{uid}.value));
case 'cdata'
xmlstr = sprintf('%s<![CDATA[%s]]>\n',xmlstr, ...
tree.tree{uid}.value);
case 'pi'
xmlstr = sprintf('%s<?%s %s?>\n',xmlstr, ...
tree.tree{uid}.target, tree.tree{uid}.value);
case 'comment'
xmlstr = sprintf('%s<!-- %s -->\n',xmlstr,...
tree.tree{uid}.value);
otherwise
warning(sprintf('Type %s unknown: not saved', ...
tree.tree{uid}.type));
end
%=======================================================================
function save_subtree(tree,fid,uid,order)
if nargin < 4, order = 0; end
fprintf(fid,blanks(3*order));
switch tree.tree{uid}.type
case 'element'
fprintf(fid,'<%s',tree.tree{uid}.name);
for i=1:length(tree.tree{uid}.attributes)
fprintf(fid,' %s="%s"',...
tree.tree{uid}.attributes{i}.key, ...
tree.tree{uid}.attributes{i}.val);
end
if isempty(tree.tree{uid}.contents)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(tree.tree{uid}.contents)
save_subtree(tree,fid,...
tree.tree{uid}.contents(i),order+1)
end
fprintf(fid,blanks(3*order));
fprintf(fid,'</%s>\n',tree.tree{uid}.name);
end
case 'chardata'
fprintf(fid,'%s\n',entity(tree.tree{uid}.value));
case 'cdata'
fprintf(fid,'<![CDATA[%s]]>\n',tree.tree{uid}.value);
case 'pi'
fprintf(fid,'<?%s %s?>\n',tree.tree{uid}.target, ...
tree.tree{uid}.value);
case 'comment'
fprintf(fid,'<!-- %s -->\n',tree.tree{uid}.value);
otherwise
warning(sprintf('[XMLTree] Type %s unknown: not saved', ...
tree.tree{uid}.type));
end
%=======================================================================
function str = entity(str)
% This has the side effect of strtrim'ming the char array.
str = char(strrep(cellstr(str), '&', '&' ));
str = char(strrep(cellstr(str), '<', '<' ));
str = char(strrep(cellstr(str), '>', '>' ));
str = char(strrep(cellstr(str), '"', '"'));
str = char(strrep(cellstr(str), '''', '''));
|
github
|
philippboehmsturm/antx-master
|
branch.m
|
.m
|
antx-master/xspm8/@xmltree/branch.m
| 1,763 |
utf_8
|
f109760669fd1d0e0de8fc92a2a29e7d
|
function subtree = branch(tree,uid)
% XMLTREE/BRANCH Branch Method
% FORMAT uid = parent(tree,uid)
%
% tree - XMLTree object
% uid - UID of the root element of the subtree
% subtree - XMLTree object (a subtree from tree)
%_______________________________________________________________________
%
% Return a subtree from a tree.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: branch.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(2,2,nargin));
if uid > length(tree) || ...
numel(uid)~=1 || ...
~strcmp(tree.tree{uid}.type,'element')
error('[XMLTree] Invalid UID.');
end
subtree = xmltree;
subtree = set(subtree,root(subtree),'name',tree.tree{uid}.name);
%- fix by Piotr Dollar to copy attributes for the root node:
subtree = set(subtree,root(subtree),'attributes',tree.tree{uid}.attributes);
child = children(tree,uid);
for i=1:length(child)
l = length(subtree);
subtree = sub_branch(tree,subtree,child(i),root(subtree));
subtree.tree{root(subtree)}.contents = [subtree.tree{root(subtree)}.contents l+1];
end
%=======================================================================
function tree = sub_branch(t,tree,uid,p)
l = length(tree);
tree.tree{l+1} = t.tree{uid};
tree.tree{l+1}.uid = l + 1;
tree.tree{l+1}.parent = p;
tree.tree{l+1}.contents = [];
if isfield(t.tree{uid},'contents')
contents = get(t,uid,'contents');
m = length(tree);
for i=1:length(contents)
tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];
tree = sub_branch(t,tree,contents(i),l+1);
m = length(tree);
end
end
|
github
|
philippboehmsturm/antx-master
|
flush.m
|
.m
|
antx-master/xspm8/@xmltree/flush.m
| 1,426 |
utf_8
|
fe4b3a9c9e324178be9b06001c9fec8f
|
function tree = flush(tree,uid)
% XMLTREE/FLUSH Flush (Clear a subtree given its UID)
%
% tree - XMLTree object
% uid - array of UID's of subtrees to be cleared
% Default is root
%_______________________________________________________________________
%
% Clear a subtree given its UID (remove all the leaves of the tree)
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: flush.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(1,2,nargin));
if nargin == 1,
uid = root(tree);
end
uid = uid(:);
for i=1:length(uid)
tree = sub_flush(tree,uid(i));
end
%=======================================================================
function tree = sub_flush(tree,uid)
if isfield(tree.tree{uid},'contents')
% contents is parsed in reverse order because each child is
% deleted and the contents vector is then eventually reduced
for i=length(tree.tree{uid}.contents):-1:1
tree = sub_flush(tree,tree.tree{uid}.contents(i));
end
end
if strcmp(tree.tree{uid}.type,'chardata') ||...
strcmp(tree.tree{uid}.type,'pi') ||...
strcmp(tree.tree{uid}.type,'cdata') ||...
strcmp(tree.tree{uid}.type,'comment')
tree = delete(tree,uid);
end
|
github
|
philippboehmsturm/antx-master
|
copy.m
|
.m
|
antx-master/xspm8/@xmltree/copy.m
| 1,644 |
utf_8
|
8cbde6d7d6e761ad86ecb0379b54b269
|
function tree = copy(tree,subuid,uid)
% XMLTREE/COPY Copy Method (copy a subtree in another branch)
% FORMAT tree = copy(tree,subuid,uid)
%
% tree - XMLTree object
% subuid - UID of the subtree to copy
% uid - UID of the element where the subtree must be duplicated
%_______________________________________________________________________
%
% Copy a subtree to another branch
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: copy.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(2,3,nargin));
if nargin == 2
uid = parent(tree,subuid);
end
l = length(tree);
tree = sub_copy(tree,subuid,uid);
tree.tree{uid}.contents = [tree.tree{uid}.contents l+1];
% to have the copy next to the original and not at the end?
% contents = get(tree,parent,'contents');
% i = find(contents==uid);
% tree = set(tree,parent,'contents',[contents(1:i) l+1 contents(i+1:end)]);
%=======================================================================
function tree = sub_copy(tree,uid,p)
l = length(tree);
tree.tree{l+1} = tree.tree{uid};
tree.tree{l+1}.uid = l+1;
tree.tree{l+1}.parent = p;
tree.tree{l+1}.contents = [];
if isfield(tree.tree{uid},'contents')
contents = get(tree,uid,'contents');
m = length(tree);
for i=1:length(contents)
tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];
tree = sub_copy(tree,contents(i),l+1);
m = length(tree);
end
end
|
github
|
philippboehmsturm/antx-master
|
convert.m
|
.m
|
antx-master/xspm8/@xmltree/convert.m
| 5,612 |
utf_8
|
c2c0cfe54bad9ce85b1cccc7c53acfce
|
function s = convert(tree,uid)
% XMLTREE/CONVERT Converter an XML tree in a Matlab structure
%
% tree - XMLTree object
% uid - uid of the root of the subtree, if provided.
% Default is root
% s - converted structure
%_______________________________________________________________________
%
% Convert an xmltree into a Matlab structure, when possible.
% When several identical tags are present, a cell array is used.
% The root tag is not saved in the structure.
% If provided, only the structure corresponding to the subtree defined
% by the uid UID is returned.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: convert.m 3756 2010-03-05 18:43:37Z guillaume $
% Exemple:
% tree: <toto><titi>field1</titi><tutu>field2</tutu><titi>field3</titi></toto>
% toto = convert(tree);
% <=> toto = struct('titi',{{'field1', 'field3'}},'tutu','field2')
error(nargchk(1,2,nargin));
% Get the root uid of the output structure
if nargin == 1
% Get the root uid of the XML tree
root_uid = root(tree);
else
% Uid provided by user
root_uid = uid;
end
% Initialize the output structure
% struct([]) should be used but this only works with Matlab 6
% So we create a field that we delete at the end
%s = struct(get(tree,root_uid,'name'),''); % struct([])
s = struct('deletedummy','');
%s = sub_convert(tree,s,root_uid,{get(tree,root_uid,'name')});
s = sub_convert(tree,s,root_uid,{});
s = rmfield(s,'deletedummy');
%=======================================================================
function s = sub_convert(tree,s,uid,arg)
type = get(tree,uid,'type');
switch type
case 'element'
child = children(tree,uid);
l = {};
ll = {};
for i=1:length(child)
if isfield(tree,child(i),'name')
ll = { ll{:}, get(tree,child(i),'name') };
end
end
for i=1:length(child)
if isfield(tree,child(i),'name')
name = get(tree,child(i),'name');
nboccur = sum(ismember(l,name));
nboccur2 = sum(ismember(ll,name));
l = { l{:}, name };
if nboccur || (nboccur2>1)
arg2 = { arg{:}, name, {nboccur+1} };
else
arg2 = { arg{:}, name};
end
else
arg2 = arg;
end
s = sub_convert(tree,s,child(i),arg2);
end
if isempty(child)
s = sub_setfield(s,arg{:},'');
end
%- saving attributes : does not work with <a t='q'>b</a>
%- but ok with <a t='q'><c>b</c></a>
% attrb = attributes(tree,'get',uid); %-
% if ~isempty(attrb) %-
% arg2 = {arg{:} 'attributes'}; %-
% s = sub_setfield(s,arg2{:},attrb); %-
% end %-
case 'chardata'
s = sub_setfield(s,arg{:},get(tree,uid,'value'));
%- convert strings into their Matlab equivalent when possible
%- e.g. string '3.14159' becomes double scalar 3.14159
% v = get(tree,uid,'value'); %-
% cv = str2num(v); %-
% if isempty(cv) %-
% s = sub_setfield(s,arg{:},v); %-
% else %-
% s = sub_setfield(s,arg{:},cv); %-
% end %-
case 'cdata'
s = sub_setfield(s,arg{:},get(tree,uid,'value'));
case 'pi'
% Processing instructions are evaluated if possible
app = get(tree,uid,'target');
switch app
case {'matlab',''}
s = sub_setfield(s,arg{:},eval(get(tree,uid,'value')));
case 'unix'
s = sub_setfield(s,arg{:},unix(get(tree,uid,'value')));
case 'dos'
s = sub_setfield(s,arg{:},dos(get(tree,uid,'value')));
case 'system'
s = sub_setfield(s,arg{:},system(get(tree,uid,'value')));
otherwise
try
s = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value')));
catch
warning('[XMLTREE] Unknown target application');
end
end
case 'comment'
% Comments are forgotten
otherwise
warning(sprintf('Type %s unknown : not saved',get(tree,uid,'type')));
end
%=======================================================================
function s = sub_setfield(s,varargin)
% Same as setfield but using '{}' rather than '()'
%if (isempty(varargin) | length(varargin) < 2)
% error('Not enough input arguments.');
%end
subs = varargin(1:end-1);
for i = 1:length(varargin)-1
if (isa(varargin{i}, 'cell'))
types{i} = '{}';
elseif ischar(varargin{i})
types{i} = '.';
subs{i} = varargin{i}; %strrep(varargin{i},' ',''); % deblank field name
else
error('Inputs must be either cell arrays or strings.');
end
end
% Perform assignment
try
s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end});
catch
error(lasterr)
end
|
github
|
philippboehmsturm/antx-master
|
editor.m
|
.m
|
antx-master/xspm8/@xmltree/editor.m
| 12,428 |
utf_8
|
6344af0067d2405a13d1dabf8e96efc3
|
function editor(tree)
%XMLTREE/EDITOR A Graphical User Interface for an XML tree
% EDITOR(TREE) opens a new Matlab figure displaying the xmltree
% object TREE.
% H = EDITOR(TREE) also returns the figure handle H.
%
% This is a beta version of <xmltree/view> successor
%
% See also XMLTREE
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: editor.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(1,1,nargin));
if ~isempty(getfilename(tree))
title = getfilename(tree);
elseif ~isempty(inputname(1))
title = ['Variable ''' inputname(1) ''''];
else
title = 'Untitled';
end
h = initWindow(title);
setappdata(h,'handles',guihandles(h));
setappdata(h,'save',0);
tree = set(tree,root(tree),'show',1);
setappdata(h,'tree',tree);
doUpdate([],[],h);
set(h,'HandleVisibility','callback');
%=======================================================================
function h = initWindow(title)
wincolor = struct('bg', [0.8 0.8 0.8], ...
'fg', [1.0 1.0 1.0], ...
'title', [0.9 0.9 0.9]);
title = [':: XMLTree Editor :: ' title];
h = figure('Name', title, ...
'Units', 'Points', ...
'NumberTitle', 'off', ...
'Resize', 'on', ...
'Color', wincolor.bg,...
'Position', [200 200 440 330], ...
'MenuBar', 'none', ...
'Tag', mfilename);
set(h, 'CloseRequestFcn', {@doClose,h});
%- Left box
uicontrol('Style', 'listbox', ...
'HorizontalAlignment','left', ...
'Units','Normalized', ...
'Visible','on',...
'BackgroundColor', wincolor.fg, ...
'Max', 1, ...
'Value', 1 , ...
'Enable', 'on', ...
'Position', [0.04 0.12 0.3 0.84], ...
'Callback', {@doList,h}, ...
'String', ' ', ...
'Tag', 'xmllistbox');
%- Right box
uicontrol('Style', 'list', ...
'HorizontalAlignment','left', ...
'Units','Normalized', ...
'Visible','on',...
'BackgroundColor', wincolor.bg, ...
'Min', 0, ...
'Max', 2, ...
'Value', [], ...
'Enable', 'inactive', ...
'Position', [0.38 0.50 0.58 0.46], ...
'Callback', '', ...
'String', ' ', ...
'Tag', 'xmllist');
%- The Add button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.04 0.03 0.11 0.06], ...
'String', 'Add', ...
'Enable','on',...
'Tag', 'addbutton', ...
'Callback', {@doAdd,h});
%- The Modify button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.175 0.03 0.11 0.06], ...
'String', 'Modify', ...
'Enable','on',...
'Tag', 'modifybutton', ...
'Callback', {@doModify,h});
%- The Copy button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.310 0.03 0.11 0.06], ...
'String', 'Copy', ...
'Enable','on',...
'Tag', 'copybutton', ...
'Callback', {@doCopy,h});
%- The Delete button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.445 0.03 0.11 0.06], ...
'String', 'Delete', ...
'Enable','on',...
'Tag', 'delbutton', ...
'Callback', {@doDelete,h});
%- The Save button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.580 0.03 0.11 0.06], ...
'String', 'Save', ...
'Tag', 'savebutton', ...
'Callback', {@doSave,h});
%- The Run button
%uicontrol('Style', 'pushbutton', ...
% 'Units', 'Normalized', ...
% 'Position', [0.715 0.03 0.11 0.06], ...
% 'String', 'Run', ...
% 'Enable', 'off', ...
% 'Tag', 'runbutton', ...
% 'Callback', {@doRun,h});
%- The Attributes button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.715 0.03 0.11 0.06], ...
'String', 'Attr.', ...
'Enable', 'on', ...
'Tag', 'runbutton', ...
'Callback', {@doAttributes,h});
%- The Close button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.850 0.03 0.11 0.06], ...
'String', 'Close', ...
'Tag', 'closebutton', ...
'Callback', {@doClose,h});
%=======================================================================
function doClose(fig,evd,h)
s = getappdata(h, 'save');
status = 1;
if s
button = questdlg(sprintf('Save changes to the XML tree?'),...
'XMLTree Editor','Yes','No','Cancel','Yes');
if strcmp(button,'Yes')
status = doSave([],[],h);
elseif strcmp(button,'Cancel')
status = 0;
end
end
if status
delete(h);
end
function doAdd(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
answer = questdlg('Which kind of item to add?', ...
'XMLTree Editor :: Add','Node','Leaf','Node');
switch answer
case 'Node'
tree = add(tree,uid,'element','New_Node');
case 'Leaf'
tree = add(tree,uid,'element','New_Leaf');
l = length(tree);
tree = add(tree,l,'chardata','default');
end
tree = set(tree,uid,'show',1);
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
doUpdate([],[],h);
doList([],[],h);
function doModify(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
contents = children(tree,uid);
if length(contents) > 0 & ...
strcmp(get(tree,contents(1),'type'),'chardata')
str = get(tree,contents(1),'value');
prompt = {'Name :','New value:'};
def = {get(tree,uid,'name'),str};
title = sprintf('Modify %s',get(tree,uid,'name'));
lineNo = 1;
answer = inputdlg(prompt,title,lineNo,def);
if ~isempty(answer)
tree = set(tree,uid,'name',answer{1});
str = answer{2};
tree = set(tree,contents(1),'value',str);
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
end
else
str = ['Tag ' get(tree,uid,'name')];
prompt = {'Name :'};
def = {get(tree,uid,'name'),str};
title = sprintf('Modify %s tag',get(tree,uid,'name'));
lineNo = 1;
answer = inputdlg(prompt,title,lineNo,def);
if ~isempty(answer)
tree = set(tree,uid,'name',answer{1});
str = ['Tag ' get(tree,uid,'name')];
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
end
end
%- Trying to keep the slider active
set(handles.xmllist, 'Enable', 'on');
set(handles.xmllist, 'String', ' ');
set(handles.xmllist, 'Enable', 'Inactive');
set(handles.xmllist, 'String', str);
doUpdate([],[],h);
doList([],[],h);
function doCopy(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
if pos ~= 1
tree = copy(tree,uid);
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
doUpdate([],[],h);
doList([],[],h);
end
function doDelete(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
if pos > 1
tree = delete(tree,uid);
set(handles.xmllistbox,'value',pos-1);
setappdata(h, 'save', 1);
end
setappdata(h, 'tree', tree);
doUpdate([],[],h);
doList([],[],h);
function status = doSave(fig,evd,h)
tree = getappdata(h, 'tree');
[filename, pathname] = uiputfile({'*.xml' 'XML file (*.xml)'}, ...
'Save XML file as');
status = ~(isequal(filename,0) | isequal(pathname,0));
if status
save(tree,fullfile(pathname, filename));
set(h,'Name',[':: XMLTree Editor :: ' filename]);
setappdata(h, 'save', 0);
end
function doRun(fig,evd,h)
warndlg('Not implemented','XMLTree :: Run');
function doAttributes(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
attr = attributes(tree,'get',uid);
if ~isempty(attr)
fprintf('This element has %d attributes.\n',length(attr));
%%%
%%% Do what you want with 'attr'
%%% to modify them, use:
%%% tree = attributes(tree,'set',uid,n,key,val)
%%% to add one, use:
%%% tree = attributes(tree,'add',uid,key,val)
%%% to delete one, use:
%%% tree = attributes(tree,'del',uid[,n]);
%%%
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1); %- only if attributes have been modified
end
%=======================================================================
function doList(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
uid = uidList(get(handles.xmllistbox, 'value'));
%- Single mouse click
if strcmp(get(h,'SelectionType'),'normal')
contents = children(tree, uid);
if length(contents) > 0 & ...
strcmp(get(tree,contents(1),'type'),'chardata')
str = get(tree,contents(1),'value');
set(handles.addbutton,'Enable','off');
elseif length(contents) == 0
str = '';
tree = add(tree,uid,'chardata',str);
setappdata(h, 'tree', tree);
set(handles.addbutton,'Enable','off');
else
str = ['Tag ' get(tree,uid,'name')];
set(handles.addbutton,'Enable','on');
end
if get(handles.xmllistbox,'value') == 1
set(handles.copybutton,'Enable','off');
set(handles.delbutton,'Enable','off');
else
set(handles.copybutton,'Enable','on');
set(handles.delbutton,'Enable','on');
end
%- Trying to keep the slider active
set(handles.xmllist, 'Enable', 'on');
set(handles.xmllist, 'String', ' ');
set(handles.xmllist, 'Enable', 'Inactive');
set(handles.xmllist, 'String', str);
%- Double mouse click
else
tree = doFlip(tree, uid);
setappdata(h, 'tree', tree);
doUpdate([],[],h);
end
function doUpdate(fig,evd,h)
tree = getappdata(h, 'tree');
handles = getappdata(h, 'handles');
[batchString, uidList] = doUpdateR(tree);
set(handles.xmllistbox, 'String', batchString);
setappdata(h, 'uidlist', uidList);
%=======================================================================
function [batchString, uidList] = doUpdateR(tree, uid, o)
if nargin < 2, uid = root(tree); end
if nargin < 3 | o == 0
o = 0;
sep = ' ';
else
sep = blanks(4*o);
end
if attributes(tree,'length',uid) > 0
batchString = {[sep, get(tree, uid, 'name') ' *']};
else
batchString = {[sep, get(tree, uid, 'name')]};
end
uidList = [get(tree,uid,'uid')];
haselementchild = 0;
contents = get(tree, uid, 'contents');
if isfield(tree, uid, 'show') & get(tree, uid, 'show') == 1
for i=1:length(contents)
if strcmp(get(tree,contents(i),'type'),'element')
[subbatchString, subuidList] = doUpdateR(tree,contents(i),o+1);
batchString = {batchString{:} subbatchString{:}};
uidList = [uidList subuidList];
haselementchild = 1;
end
end
if haselementchild == 1, batchString{1}(length(sep)) = '-'; end
else
for i=1:length(contents)
if strcmp(get(tree,contents(i),'type'),'element')
haselementchild = 1;
end
end
if haselementchild == 1, batchString{1}(length(sep)) = '+'; end
end
function tree = doFlip(tree, uid)
if isfield(tree,uid,'show')
show = get(tree,uid,'show');
else
show = 0;
end
tree = set(tree,uid,'show',~show);
|
github
|
philippboehmsturm/antx-master
|
find.m
|
.m
|
antx-master/xspm8/@xmltree/find.m
| 5,904 |
utf_8
|
f06a6b831a6222020bfa34df1176ccaa
|
function list = find(varargin)
% XMLTREE/FIND Find elements in a tree with specified characteristics
% FORMAT list = find(varargin)
%
% tree - XMLTree object
% xpath - string path with specific grammar (XPath)
% uid - lists of root uid's
% parameter/value - pair of pattern
% list - list of uid's of matched elements
%
% list = find(tree,xpath)
% list = find(tree,parameter,value[,parameter,value])
% list = find(tree,uid,parameter,value[,parameter,value])
%
% Grammar for addressing parts of an XML document:
% XML Path Language XPath (http://www.w3.org/TR/xpath)
% Example: /element1//element2[1]/element3[5]/element4
%_______________________________________________________________________
%
% Find elements in an XML tree with specified characteristics or given
% a path (using a subset of XPath language).
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: find.m 3934 2010-06-17 14:58:25Z guillaume $
% TODO:
% - clean up subroutines
% - find should only be documented using XPath (other use is internal)
% - handle '*', 'last()' in [] and '@'
% - if a key is invalid, should rather return [] than error ?
if nargin==0
error('[XMLTree] A tree must be provided');
elseif nargin==1
list = 1:length(tree.tree);
return
elseif mod(nargin,2)
list = sub_find_subtree1(varargin{1}.tree,root(varargin{1}),varargin{2:end});
elseif isa(varargin{2},'double') && ...
ndims(varargin{2}) == 2 && ...
min(size(varargin{2})) == 1
list = unique(sub_find_subtree1(varargin{1}.tree,varargin{2:end}));
elseif nargin==2 && ischar(varargin{2})
list = sub_pathfinder(varargin{:});
else
error('[XMLTree] Arguments must be parameter/value pairs.');
end
%=======================================================================
function list = sub_find_subtree1(varargin)
list = [];
for i=1:length(varargin{2})
res = sub_find_subtree2(varargin{1},...
varargin{2}(i),varargin{3:end});
list = [list res];
end
%=======================================================================
function list = sub_find_subtree2(varargin)
uid = varargin{2};
list = [];
if sub_comp_element(varargin{1}{uid},varargin{3:end})
list = [list varargin{1}{uid}.uid];
end
if isfield(varargin{1}{uid},'contents')
list = [list sub_find_subtree1(varargin{1},...
varargin{1}{uid}.contents,varargin{3:end})];
end
%=======================================================================
function match = sub_comp_element(varargin)
match = 0;
try
% v = getfield(varargin{1}, varargin{2}); % slow...
for i=1:floor(nargin/2)
v = subsref(varargin{1}, struct('type','.','subs',varargin{i+1}));
if strcmp(v,varargin{i+2})
match = 1;
end
end
catch
end
% More powerful but much slower
%match = 0;
%for i=1:length(floor(nargin/2)) % bug: remove length !!!
% if isfield(varargin{1},varargin{i+1})
% if ischar(getfield(varargin{1},varargin{i+1})) & ischar(varargin{i+2})
% if strcmp(getfield(varargin{1},varargin{i+1}),char(varargin{i+2}))
% match = 1;
% end
% elseif isa(getfield(varargin{1},varargin{i+1}),'double') & ...
% isa(varargin{i+2},'double')
% if getfield(varargin{1},varargin{i+1}) == varargin{i+2}
% match = 1;
% end
% else
% warning('Cannot compare different objects');
% end
% end
%end
%=======================================================================
function list = sub_pathfinder(tree,pth)
%- Search for the delimiter '/' in the path
i = strfind(pth,'/');
%- Begin search by root
list = root(tree);
%- Walk through the tree
j = 1;
while j <= length(i)
%- Look for recursion '//'
if j<length(i) && i(j+1)==i(j)+1
recursive = 1;
j = j + 1;
else
recursive = 0;
end
%- Catch the current tag 'element[x]'
if j ~= length(i)
element = pth(i(j)+1:i(j+1)-1);
else
element = pth(i(j)+1:end);
end
%- Search for [] brackets
k = xml_findstr(element,'[',1,1);
%- If brackets are present in current element
if ~isempty(k)
l = xml_findstr(element,']',1,1);
val = str2num(element(k+1:l-1));
element = element(1:k-1);
end
%- Use recursivity
if recursive
list = find(tree,list,'name',element);
%- Just look at children
else
if i(j)==1 % if '/root/...' (list = root(tree) in that case)
if sub_comp_element(tree.tree{list},'name',element)
% list = 1; % list still contains root(tree)
else
list = [];
return;
end
else
list = sub_findchild(tree,list,element);
end
end
% If an element is specified using a key
if ~isempty(k)
if val < 1 || val > length(list)+1
error('[XMLTree] Bad key in the path.');
elseif val == length(list)+1
list = [];
return;
end
list = list(val);
end
if isempty(list), return; end
j = j + 1;
end
%=======================================================================
function list = sub_findchild(tree,listt,elmt)
list = [];
for a=1:length(listt)
for b=1:length(tree.tree{listt(a)}.contents)
if sub_comp_element(tree.tree{tree.tree{listt(a)}.contents(b)},'name',elmt)
list = [list tree.tree{tree.tree{listt(a)}.contents(b)}.uid];
end
end
end
|
github
|
philippboehmsturm/antx-master
|
xml_parser.m
|
.m
|
antx-master/xspm8/@xmltree/private/xml_parser.m
| 16,122 |
utf_8
|
e9c0fb44fd5c086cab09c4df5a6e0087
|
function tree = xml_parser(xmlstr)
% XML (eXtensible Markup Language) Processor
% FORMAT tree = xml_parser(xmlstr)
%
% xmlstr - XML string to parse
% tree - tree structure corresponding to the XML file
%_______________________________________________________________________
%
% xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser
% written in Matlab. It aims to be fully conforming. It is currently not
% a validating XML processor.
%
% A description of the tree structure provided in output is detailed in
% the header of this m-file.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: xml_parser.m 4013 2010-07-22 17:12:45Z guillaume $
% XML Processor for MATLAB (The Mathworks, Inc.).
% Copyright (C) 2002-2008 Guillaume Flandin <[email protected]>
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
%-----------------------------------------------------------------------
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% Check also the latest developments on the following webpage:
% <http://www.artefact.tk/software/matlab/xml/>
%-----------------------------------------------------------------------
% The implementation of this XML parser is much inspired from a
% Javascript parser available at <http://www.jeremie.com/>
% A mex-file xml_findstr.c is also required, to encompass some
% limitations of the built-in findstr Matlab function.
% Compile it on your architecture using 'mex -O xml_findstr.c' command
% if the compiled version for your system is not provided.
% If this function behaves badly (crash or wrong results), comment the
% line '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again.
%-----------------------------------------------------------------------
% Structure of the output tree:
% There are 5 types of nodes in an XML file: element, chardata, cdata,
% pi and comment.
% Each of them contains an UID (Unique Identifier): an integer between
% 1 and the number of nodes of the XML file.
%
% element (a tag <name key="value"> [contents] </name>
% |_ type: 'element'
% |_ name: string
% |_ attributes: cell array of struct 'key' and 'value' or []
% |_ contents: double array of uid's or [] if empty
% |_ parent: uid of the parent ([] if root)
% |_ uid: double
%
% chardata (a character array)
% |_ type: 'chardata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% cdata (a litteral string <![CDATA[value]]>)
% |_ type: 'cdata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% pi (a processing instruction <?target value ?>)
% |_ type: 'pi'
% |_ target: string (may be empty)
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% comment (a comment <!-- value -->)
% |_ type: 'comment'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
%-----------------------------------------------------------------------
% TODO/BUG/FEATURES:
% - [compile] only a warning if TagStart is empty ?
% - [attribution] should look for " and ' rather than only "
% - [main] with normalize as a preprocessing, CDATA are modified
% - [prolog] look for a DOCTYPE in the whole string even if it occurs
% only in a far CDATA tag, bug even if the doctype is inside a comment
% - [tag_element] erode should replace normalize here
% - remove globals? uppercase globals rather persistent (clear mfile)?
% - xml_findstr is indeed xml_strfind according to Mathworks vocabulary
% - problem with entities: do we need to convert them here? (é)
%-----------------------------------------------------------------------
%- XML string to parse and number of tags read
global xmlstring Xparse_count xtree;
%- Check input arguments
error(nargchk(1,1,nargin));
if isempty(xmlstr)
error('[XML] Not enough parameters.')
elseif ~ischar(xmlstr) || sum(size(xmlstr)>1)>1
error('[XML] Input must be a string.')
end
%- Initialize number of tags (<=> uid)
Xparse_count = 0;
%- Remove prolog and white space characters from the XML string
xmlstring = normalize(prolog(xmlstr));
%- Initialize the XML tree
xtree = {};
tree = fragment;
tree.str = 1;
tree.parent = 0;
%- Parse the XML string
tree = compile(tree);
%- Return the XML tree
tree = xtree;
%- Remove global variables from the workspace
clear global xmlstring Xparse_count xtree;
%=======================================================================
% SUBFUNCTIONS
%-----------------------------------------------------------------------
function frag = compile(frag)
global xmlstring xtree Xparse_count;
while 1,
if length(xmlstring)<=frag.str || ...
(frag.str == length(xmlstring)-1 && strcmp(xmlstring(frag.str:end),' '))
return
end
TagStart = xml_findstr(xmlstring,'<',frag.str,1);
if isempty(TagStart)
%- Character data
error('[XML] Unknown data at the end of the XML file.');
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = '';
elseif TagStart > frag.str
if strcmp(xmlstring(frag.str:TagStart-1),' ')
%- A single white space before a tag (ignore)
frag.str = TagStart;
else
%- Character data
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = TagStart;
end
else
if strcmp(xmlstring(frag.str+1),'?')
%- Processing instruction
frag = tag_pi(frag);
else
if length(xmlstring)-frag.str>4 && strcmp(xmlstring(frag.str+1:frag.str+3),'!--')
%- Comment
frag = tag_comment(frag);
else
if length(xmlstring)-frag.str>9 && strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[')
%- Litteral data
frag = tag_cdata(frag);
else
%- A tag element (empty (<.../>) or not)
if ~isempty(frag.end)
endmk = ['/' frag.end '>'];
else
endmk = '/>';
end
if strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) || ...
strcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk)
frag.str = frag.str + length(frag.end)+3;
return
else
frag = tag_element(frag);
end
end
end
end
end
end
%-----------------------------------------------------------------------
function frag = tag_element(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'>',frag.str,1);
if isempty(close)
error('[XML] Tag < opened but not closed.');
else
empty = strcmp(xmlstring(close-1:close),'/>');
if empty
close = close - 1;
end
starttag = normalize(xmlstring(frag.str+1:close-1));
nextspace = xml_findstr(starttag,' ',1,1);
attribs = '';
if isempty(nextspace)
name = starttag;
else
name = starttag(1:nextspace-1);
attribs = starttag(nextspace+1:end);
end
xtree{Xparse_count} = element;
xtree{Xparse_count}.name = strip(name);
if frag.parent
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
end
if ~isempty(attribs)
xtree{Xparse_count}.attributes = attribution(attribs);
end
if ~empty
contents = fragment;
contents.str = close+1;
contents.end = name;
contents.parent = Xparse_count;
contents = compile(contents);
frag.str = contents.str;
else
frag.str = close+2;
end
end
%-----------------------------------------------------------------------
function frag = tag_pi(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'?>',frag.str,1);
if isempty(close)
warning('[XML] Tag <? opened but not closed.')
else
nextspace = xml_findstr(xmlstring,' ',frag.str,1);
xtree{Xparse_count} = pri;
if nextspace > close || nextspace == frag.str+2
xtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1));
else
xtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1));
xtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace));
end
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+2;
end
%-----------------------------------------------------------------------
function frag = tag_comment(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'-->',frag.str,1);
if isempty(close)
warning('[XML] Tag <!-- opened but not closed.')
else
xtree{Xparse_count} = comment;
xtree{Xparse_count}.value = erode(xmlstring(frag.str+4:close-1));
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%-----------------------------------------------------------------------
function frag = tag_cdata(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,']]>',frag.str,1);
if isempty(close)
warning('[XML] Tag <![CDATA[ opened but not closed.')
else
xtree{Xparse_count} = cdata;
xtree{Xparse_count}.value = xmlstring(frag.str+9:close-1);
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%-----------------------------------------------------------------------
function all = attribution(str)
%- Initialize attributs
nbattr = 0;
all = cell(nbattr);
%- Look for 'key="value"' substrings
while 1,
eq = xml_findstr(str,'=',1,1);
if isempty(str) || isempty(eq), return; end
id = sort([xml_findstr(str,'"',1,1),xml_findstr(str,'''',1,1)]); id=id(1);
nextid = sort([xml_findstr(str,'"',id+1,1),xml_findstr(str,'''',id+1,1)]);nextid=nextid(1);
nbattr = nbattr + 1;
all{nbattr}.key = strip(str(1:(eq-1)));
all{nbattr}.val = entity(str((id+1):(nextid-1)));
str = str((nextid+1):end);
end
%-----------------------------------------------------------------------
function elm = element
global Xparse_count;
Xparse_count = Xparse_count + 1;
elm = struct('type','element','name','','attributes',[],'contents',[],'parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function cdat = chardata
global Xparse_count;
Xparse_count = Xparse_count + 1;
cdat = struct('type','chardata','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function cdat = cdata
global Xparse_count;
Xparse_count = Xparse_count + 1;
cdat = struct('type','cdata','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function proce = pri
global Xparse_count;
Xparse_count = Xparse_count + 1;
proce = struct('type','pi','value','','target','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function commt = comment
global Xparse_count;
Xparse_count = Xparse_count + 1;
commt = struct('type','comment','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function frg = fragment
frg = struct('str','','parent','','end','');
%-----------------------------------------------------------------------
function str = prolog(str)
%- Initialize beginning index of elements tree
b = 1;
%- Initial tag
start = xml_findstr(str,'<',1,1);
if isempty(start)
error('[XML] No tag found.')
end
%- Header (<?xml version="1.0" ... ?>)
if strcmpi(str(start:start+2),'<?x')
close = xml_findstr(str,'?>',1,1);
if ~isempty(close)
b = close + 2;
else
warning('[XML] Header tag incomplete.')
end
end
%- Doctype (<!DOCTYPE type ... [ declarations ]>)
start = xml_findstr(str,'<!DOCTYPE',b,1); % length('<!DOCTYPE') = 9
if ~isempty(start)
close = xml_findstr(str,'>',start+9,1);
if ~isempty(close)
b = close + 1;
dp = xml_findstr(str,'[',start+9,1);
if (~isempty(dp) && dp < b)
k = xml_findstr(str,']>',start+9,1);
if ~isempty(k)
b = k + 2;
else
warning('[XML] Tag [ in DOCTYPE opened but not closed.')
end
end
else
warning('[XML] Tag DOCTYPE opened but not closed.')
end
end
%- Skip prolog from the xml string
str = str(b:end);
%-----------------------------------------------------------------------
function str = strip(str)
a = isspace(str);
a = find(a==1);
str(a) = '';
%-----------------------------------------------------------------------
function str = normalize(str)
% Find white characters (space, newline, carriage return, tabs, ...)
i = isspace(str);
i = find(i == 1);
str(i) = ' ';
% replace several white characters by only one
if ~isempty(i)
j = i - [i(2:end) i(end)];
k = find(j == -1);
str(i(k)) = [];
end
%-----------------------------------------------------------------------
function str = entity(str)
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
str = strrep(str,''','''');
str = strrep(str,'&','&');
%-----------------------------------------------------------------------
function str = erode(str)
if ~isempty(str) && str(1)==' ', str(1)=''; end;
if ~isempty(str) && str(end)==' ', str(end)=''; end;
|
github
|
philippboehmsturm/antx-master
|
save.m
|
.m
|
antx-master/xspm8/@gifti/save.m
| 20,878 |
utf_8
|
9dda5745b44a50e7b47d1885c7e30435
|
function save(this,filename,encoding)
% Save GIfTI object in a GIfTI format file
% FORMAT save(this,filename)
% this - GIfTI object
% filename - name of GIfTI file to be created [Default: 'untitled.gii']
% encoding - optional argument to specify encoding format, among
% ASCII, Base64Binary, GZipBase64Binary, ExternalFileBinary,
% Collada (.dae), IDTF (.idtf). [Default: 'GZipBase64Binary']
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: save.m 4613 2012-01-08 12:04:11Z guillaume $
% Check filename and file format
%--------------------------------------------------------------------------
ext = '.gii';
if nargin == 1
filename = 'untitled.gii';
else
if nargin == 3 && strcmpi(encoding,'collada')
ext = '.dae';
end
if nargin == 3 && strcmpi(encoding,'idtf')
ext = '.idtf';
end
[p,f,e] = fileparts(filename);
if ~ismember(lower(e),{ext})
e = ext;
end
filename = fullfile(p,[f e]);
end
% Open file for writing
%--------------------------------------------------------------------------
fid = fopen(filename,'wt');
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
% Write file
%--------------------------------------------------------------------------
switch ext
case '.gii'
if nargin < 3, encoding = 'GZipBase64Binary'; end
fid = save_gii(fid,this,encoding);
case '.dae'
fid = save_dae(fid,this);
case '.idtf'
fid = save_idtf(fid,this);
otherwise
error('Unknown file format.');
end
% Close file
%--------------------------------------------------------------------------
fclose(fid);
%==========================================================================
% function fid = save_gii(fid,this,encoding)
%==========================================================================
function fid = save_gii(fid,this,encoding)
% Defaults for DataArray's attributes
%--------------------------------------------------------------------------
[unused,unused,mach] = fopen(fid);
if strncmp('ieee-be',mach,7)
def.Endian = 'BigEndian';
elseif strncmp('ieee-le',mach,7)
def.Endian = 'LittleEndian';
else
error('[GIFTI] Unknown byte order "%s".',mach);
end
def.Encoding = encoding;
def.Intent = 'NIFTI_INTENT_NONE';
def.DataType = 'NIFTI_TYPE_FLOAT32';
def.ExternalFileName = '';
def.ExternalFileOffset = '';
def.offset = 0;
% Edit object DataArray attributes
%--------------------------------------------------------------------------
for i=1:length(this.data)
% Revert the dimension storage
d = this.data{i}.attributes.Dim;
this.data{i}.attributes = rmfield(this.data{i}.attributes,'Dim');
this.data{i}.attributes.Dimensionality = num2str(length(d));
for j=1:length(d)
this.data{i}.attributes.(sprintf('Dim%d',j-1)) = num2str(d(j));
end
% Enforce some conventions
this.data{i}.attributes.ArrayIndexingOrder = 'ColumnMajorOrder';
if ~isfield(this.data{i}.attributes,'DataType') || ...
isempty(this.data{i}.attributes.DataType)
warning('DataType set to default: %s', def.DataType);
this.data{i}.attributes.DataType = def.DataType;
end
if ~isfield(this.data{i}.attributes,'Intent') || ...
isempty(this.data{i}.attributes.Intent)
warning('Intent code set to default: %s', def.Intent);
this.data{i}.attributes.Intent = def.Intent;
end
this.data{i}.attributes.Encoding = def.Encoding;
this.data{i}.attributes.Endian = def.Endian;
this.data{i}.attributes.ExternalFileName = def.ExternalFileName;
this.data{i}.attributes.ExternalFileOffset = def.ExternalFileOffset;
switch this.data{i}.attributes.Encoding
case {'ASCII', 'Base64Binary','GZipBase64Binary' }
case 'ExternalFileBinary'
extfilename = this.data{i}.attributes.ExternalFileName;
if isempty(extfilename)
[p,f] = fileparts(fopen(fid));
extfilename = [f '.dat'];
end
[p,f,e] = fileparts(extfilename);
this.data{i}.attributes.ExternalFileName = fullfile(fileparts(fopen(fid)),[f e]);
this.data{i}.attributes.ExternalFileOffset = num2str(def.offset);
otherwise
error('[GIFTI] Unknown data encoding: %s.',this.data{i}.attributes.Encoding);
end
end
% Prolog
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0" encoding="UTF-8"?>\n');
fprintf(fid,'<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">\n');
fprintf(fid,'<GIFTI Version="1.0" NumberOfDataArrays="%d">\n',numel(this.data));
o = @(x) blanks(x*3);
% MetaData
%--------------------------------------------------------------------------
fprintf(fid,'%s<MetaData',o(1));
if isempty(this.metadata)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(this.metadata)
fprintf(fid,'%s<MD>\n',o(2));
fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(3),...
this.metadata(i).name);
fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(3),...
this.metadata(i).value);
fprintf(fid,'%s</MD>\n',o(2));
end
fprintf(fid,'%s</MetaData>\n',o(1));
end
% LabelTable
%--------------------------------------------------------------------------
fprintf(fid,'%s<LabelTable',o(1));
if isempty(this.label)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(this.label.name)
if ~all(isnan(this.label.rgba(i,:)))
label_rgba = sprintf(' Red="%f" Green="%f" Blue="%f" Alpha="%f"',...
this.label.rgba(i,:));
else
label_rgba = '';
end
fprintf(fid,'%s<Label Key="%d"%s><![CDATA[%s]]></Label>\n',o(2),...
this.label.key(i), label_rgba, this.label.name{i});
end
fprintf(fid,'%s</LabelTable>\n',o(1));
end
% DataArray
%--------------------------------------------------------------------------
for i=1:length(this.data)
fprintf(fid,'%s<DataArray',o(1));
if def.offset
this.data{i}.attributes.ExternalFileOffset = num2str(def.offset);
end
fn = sort(fieldnames(this.data{i}.attributes));
oo = repmat({o(5) '\n'},length(fn),1); oo{1} = ' '; oo{end} = '';
for j=1:length(fn)
if strcmp(fn{j},'ExternalFileName')
[p,f,e] = fileparts(this.data{i}.attributes.(fn{j}));
attval = [f e];
else
attval = this.data{i}.attributes.(fn{j});
end
fprintf(fid,'%s%s="%s"%s',oo{j,1},...
fn{j},attval,sprintf(oo{j,2}));
end
fprintf(fid,'>\n');
% MetaData
%----------------------------------------------------------------------
fprintf(fid,'%s<MetaData>\n',o(2));
for j=1:length(this.data{i}.metadata)
fprintf(fid,'%s<MD>\n',o(3));
fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(4),...
this.data{i}.metadata(j).name);
fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(4),...
this.data{i}.metadata(j).value);
fprintf(fid,'%s</MD>\n',o(3));
end
fprintf(fid,'%s</MetaData>\n',o(2));
% CoordinateSystemTransformMatrix
%----------------------------------------------------------------------
for j=1:length(this.data{i}.space)
fprintf(fid,'%s<CoordinateSystemTransformMatrix>\n',o(2));
fprintf(fid,'%s<DataSpace><![CDATA[%s]]></DataSpace>\n',o(3),...
this.data{i}.space(j).DataSpace);
fprintf(fid,'%s<TransformedSpace><![CDATA[%s]]></TransformedSpace>\n',o(3),...
this.data{i}.space(j).TransformedSpace);
fprintf(fid,'%s<MatrixData>%s</MatrixData>\n',o(3),...
sprintf('%f ',this.data{i}.space(j).MatrixData));
fprintf(fid,'%s</CoordinateSystemTransformMatrix>\n',o(2));
end
% Data (saved using MATLAB's ColumnMajorOrder)
%----------------------------------------------------------------------
fprintf(fid,'%s<Data>',o(2));
tp = getdict;
try
tp = tp.(this.data{i}.attributes.DataType);
catch
error('[GIFTI] Unknown DataType.');
end
switch this.data{i}.attributes.Encoding
case 'ASCII'
fprintf(fid, [tp.format ' '], this.data{i}.data);
case 'Base64Binary'
fprintf(fid,base64encode(typecast(this.data{i}.data(:),'uint8')));
% uses native machine format
case 'GZipBase64Binary'
fprintf(fid,base64encode(dzip(typecast(this.data{i}.data(:),'uint8'))));
% uses native machine format
case 'ExternalFileBinary'
extfilename = this.data{i}.attributes.ExternalFileName;
dat = this.data{i}.data;
if isa(dat,'file_array')
dat = subsref(dat,substruct('()',repmat({':'},1,numel(dat.dim))));
end
if ~def.offset
fide = fopen(extfilename,'w'); % uses native machine format
else
fide = fopen(extfilename,'a'); % uses native machine format
end
if fide == -1
error('Unable to write file %s: permission denied.',extfilename);
end
fseek(fide,0,1);
fwrite(fide,dat,tp.class);
def.offset = ftell(fide);
fclose(fide);
otherwise
error('[GIFTI] Unknown data encoding.');
end
fprintf(fid,'</Data>\n');
fprintf(fid,'%s</DataArray>\n',o(1));
end
fprintf(fid,'</GIFTI>\n');
%==========================================================================
% function fid = save_dae(fid,this)
%==========================================================================
function fid = save_dae(fid,this)
o = inline('blanks(x*3)');
% Split the mesh into connected components
%--------------------------------------------------------------------------
s = struct(this);
try
C = spm_mesh_label(s.faces);
d = [];
for i=1:numel(unique(C))
d(i).faces = s.faces(C==i,:);
u = unique(d(i).faces);
d(i).vertices = s.vertices(u,:);
a = 1:max(d(i).faces(:));
a(u) = 1:size(d(i).vertices,1);
%a = sparse(1,double(u),1:1:size(d(i).vertices,1));
d(i).faces = a(d(i).faces);
end
s = d;
end
% Prolog & root of the Collada XML file
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0"?>\n');
fprintf(fid,'<COLLADA xmlns="http://www.collada.org/2008/03/COLLADASchema" version="1.5.0">\n');
% Assets
%--------------------------------------------------------------------------
fprintf(fid,'%s<asset>\n',o(1));
fprintf(fid,'%s<contributor>\n',o(2));
fprintf(fid,'%s<author_website>%s</author_website>\n',o(3),...
'http://www.fil.ion.ucl.ac.uk/spm/');
fprintf(fid,'%s<authoring_tool>%s</authoring_tool>\n',o(3),spm('Ver'));
fprintf(fid,'%s</contributor>\n',o(2));
fprintf(fid,'%s<created>%s</created>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ'));
fprintf(fid,'%s<modified>%s</modified>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ'));
fprintf(fid,'%s<unit name="millimeter" meter="0.001"/>\n',o(2));
fprintf(fid,'%s<up_axis>Z_UP</up_axis>\n',o(2));
fprintf(fid,'%s</asset>\n',o(1));
% Image, Materials, Effects
%--------------------------------------------------------------------------
%fprintf(fid,'%s<library_images/>\n',o(1));
fprintf(fid,'%s<library_materials>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<material id="material%d" name="material%d">\n',o(2),i,i);
fprintf(fid,'%s<instance_effect url="#material%d-effect"/>\n',o(3),i);
fprintf(fid,'%s</material>\n',o(2));
end
fprintf(fid,'%s</library_materials>\n',o(1));
fprintf(fid,'%s<library_effects>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<effect id="material%d-effect" name="material%d-effect">\n',o(2),i,i);
fprintf(fid,'%s<profile_COMMON>\n',o(3));
fprintf(fid,'%s<technique sid="COMMON">\n',o(4));
fprintf(fid,'%s<lambert>\n',o(5));
fprintf(fid,'%s<emission>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]);
fprintf(fid,'%s</emission>\n',o(6));
fprintf(fid,'%s<ambient>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]);
fprintf(fid,'%s</ambient>\n',o(6));
fprintf(fid,'%s<diffuse>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0.5 0.5 0.5 1]);
fprintf(fid,'%s</diffuse>\n',o(6));
fprintf(fid,'%s<transparent>\n',o(6));
fprintf(fid,'%s<color>%d %d %d %d</color>\n',o(7),[1 1 1 1]);
fprintf(fid,'%s</transparent>\n',o(6));
fprintf(fid,'%s<transparency>\n',o(6));
fprintf(fid,'%s<float>%f</float>\n',o(7),0);
fprintf(fid,'%s</transparency>\n',o(6));
fprintf(fid,'%s</lambert>\n',o(5));
fprintf(fid,'%s</technique>\n',o(4));
fprintf(fid,'%s</profile_COMMON>\n',o(3));
fprintf(fid,'%s</effect>\n',o(2));
end
fprintf(fid,'%s</library_effects>\n',o(1));
% Geometry
%--------------------------------------------------------------------------
fprintf(fid,'%s<library_geometries>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<geometry id="shape%d" name="shape%d">\n',o(2),i,i);
fprintf(fid,'%s<mesh>\n',o(3));
fprintf(fid,'%s<source id="shape%d-positions">\n',o(4),i);
fprintf(fid,'%s<float_array id="shape%d-positions-array" count="%d">',o(5),i,numel(s(i).vertices));
fprintf(fid,'%f ',repmat(s(i).vertices',1,[]));
fprintf(fid,'</float_array>\n');
fprintf(fid,'%s<technique_common>\n',o(5));
fprintf(fid,'%s<accessor count="%d" offset="0" source="#shape%d-positions-array" stride="3">\n',o(6),size(s(i).vertices,1),i);
fprintf(fid,'%s<param name="X" type="float" />\n',o(7));
fprintf(fid,'%s<param name="Y" type="float" />\n',o(7));
fprintf(fid,'%s<param name="Z" type="float" />\n',o(7));
fprintf(fid,'%s</accessor>\n',o(6));
fprintf(fid,'%s</technique_common>\n',o(5));
fprintf(fid,'%s</source>\n',o(4));
fprintf(fid,'%s<vertices id="shape%d-vertices">\n',o(4),i);
fprintf(fid,'%s<input semantic="POSITION" source="#shape%d-positions"/>\n',o(5),i);
fprintf(fid,'%s</vertices>\n',o(4));
fprintf(fid,'%s<triangles material="material%d" count="%d">\n',o(4),i,size(s(i).faces,1));
fprintf(fid,'%s<input semantic="VERTEX" source="#shape%d-vertices" offset="0"/>\n',o(5),i);
fprintf(fid,'%s<p>',o(5));
fprintf(fid,'%d ',repmat(s(i).faces',1,[])-1);
fprintf(fid,'</p>\n');
fprintf(fid,'%s</triangles>\n',o(4));
fprintf(fid,'%s</mesh>\n',o(3));
fprintf(fid,'%s</geometry>\n',o(2));
end
fprintf(fid,'%s</library_geometries>\n',o(1));
% Scene
%--------------------------------------------------------------------------
fprintf(fid,'%s<library_visual_scenes>\n',o(1));
fprintf(fid,'%s<visual_scene id="VisualSceneNode" name="SceneNode">\n',o(2));
for i=1:numel(s)
fprintf(fid,'%s<node id="node%d">\n',o(3),i);
fprintf(fid,'%s<instance_geometry url="#shape%d">\n',o(4),i);
fprintf(fid,'%s<bind_material>\n',o(5));
fprintf(fid,'%s<technique_common>\n',o(6));
fprintf(fid,'%s<instance_material symbol="material%d" target="#material%d"/>\n',o(7),i,i);
fprintf(fid,'%s</technique_common>\n',o(6));
fprintf(fid,'%s</bind_material>\n',o(5));
fprintf(fid,'%s</instance_geometry>\n',o(4));
fprintf(fid,'%s</node>\n',o(3));
end
fprintf(fid,'%s</visual_scene>\n',o(2));
fprintf(fid,'%s</library_visual_scenes>\n',o(1));
fprintf(fid,'%s<scene>\n',o(1));
fprintf(fid,'%s<instance_visual_scene url="#VisualSceneNode" />\n',o(2));
fprintf(fid,'%s</scene>\n',o(1));
% End of XML
%--------------------------------------------------------------------------
fprintf(fid,'</COLLADA>\n');
%==========================================================================
% function fid = save_idtf(fid,this)
%==========================================================================
function fid = save_idtf(fid,this)
o = inline('blanks(x*3)');
s = struct(this);
% Compute normals
%--------------------------------------------------------------------------
if ~isfield(s,'normals')
try
s.normals = spm_mesh_normals(...
struct('vertices',s.vertices,'faces',s.faces),true);
catch
s.normals = [];
end
end
% Split the mesh into connected components
%--------------------------------------------------------------------------
try
C = spm_mesh_label(s.faces);
d = [];
try
if size(s.cdata,2) == 1 && (any(s.cdata>1) || any(s.cdata<0))
mi = min(s.cdata); ma = max(s.cdata);
s.cdata = (s.cdata-mi)/ (ma-mi);
else
end
end
for i=1:numel(unique(C))
d(i).faces = s.faces(C==i,:);
u = unique(d(i).faces);
d(i).vertices = s.vertices(u,:);
d(i).normals = s.normals(u,:);
a = 1:max(d(i).faces(:));
a(u) = 1:size(d(i).vertices,1);
%a = sparse(1,double(u),1:1:size(d(i).vertices,1));
d(i).faces = a(d(i).faces);
d(i).mat = s.mat;
try
d(i).cdata = s.cdata(u,:);
if size(d(i).cdata,2) == 1
d(i).cdata = repmat(d(i).cdata,1,3);
end
end
end
s = d;
end
% FILE_HEADER
%--------------------------------------------------------------------------
fprintf(fid,'FILE_FORMAT "IDTF"\n');
fprintf(fid,'FORMAT_VERSION 100\n\n');
% NODES
%--------------------------------------------------------------------------
for i=1:numel(s)
fprintf(fid,'NODE "MODEL" {\n');
fprintf(fid,'%sNODE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i));
fprintf(fid,'%sPARENT_LIST {\n',o(1));
fprintf(fid,'%sPARENT_COUNT %d\n',o(2),1);
fprintf(fid,'%sPARENT %d {\n',o(2),0);
fprintf(fid,'%sPARENT_NAME "%s"\n',o(3),'<NULL>');
fprintf(fid,'%sPARENT_TM {\n',o(3));
I = s(i).mat; % eye(4);
for j=1:size(I,2)
fprintf(fid,'%s',o(4)); fprintf(fid,'%f ',I(:,j)'); fprintf(fid,'\n');
end
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%s}\n',o(2));
fprintf(fid,'%s}\n',o(1));
fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i));
%fprintf(fid,'%sMODEL_VISIBILITY "BOTH"\n',o(1));
fprintf(fid,'}\n\n');
end
% NODE_RESOURCES
%--------------------------------------------------------------------------
for i=1:numel(s)
fprintf(fid,'RESOURCE_LIST "MODEL" {\n');
fprintf(fid,'%sRESOURCE_COUNT %d\n',o(1),1);
fprintf(fid,'%sRESOURCE %d {\n',o(1),0);
fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(2),sprintf('Mesh%04d',i));
fprintf(fid,'%sMODEL_TYPE "MESH"\n',o(2));
fprintf(fid,'%sMESH {\n',o(2));
fprintf(fid,'%sFACE_COUNT %d\n',o(3),size(s(i).faces,1));
fprintf(fid,'%sMODEL_POSITION_COUNT %d\n',o(3),size(s(i).vertices,1));
fprintf(fid,'%sMODEL_NORMAL_COUNT %d\n',o(3),size(s(i).normals,1));
if ~isfield(s(i),'cdata') || isempty(s(i).cdata)
c = 0;
else
c = size(s(i).cdata,1);
end
fprintf(fid,'%sMODEL_DIFFUSE_COLOR_COUNT %d\n',o(3),c);
fprintf(fid,'%sMODEL_SPECULAR_COLOR_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_TEXTURE_COORD_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_BONE_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_SHADING_COUNT %d\n',o(3),1);
fprintf(fid,'%sMODEL_SHADING_DESCRIPTION_LIST {\n',o(3));
fprintf(fid,'%sSHADING_DESCRIPTION %d {\n',o(4),0);
fprintf(fid,'%sTEXTURE_LAYER_COUNT %d\n',o(5),0);
fprintf(fid,'%sSHADER_ID %d\n',o(5),0);
fprintf(fid,'%s}\n',o(4));
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_POSITION_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_NORMAL_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_SHADING_LIST {\n',o(3));
fprintf(fid,'%d\n',zeros(size(s(i).faces,1),1));
fprintf(fid,'%s}\n',o(3));
if c
fprintf(fid,'%sMESH_FACE_DIFFUSE_COLOR_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
end
fprintf(fid,'%sMODEL_POSITION_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).vertices');
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMODEL_NORMAL_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).normals');
fprintf(fid,'%s}\n',o(3));
if c
fprintf(fid,'%sMODEL_DIFFUSE_COLOR_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).cdata');
fprintf(fid,'%s}\n',o(3));
end
fprintf(fid,'%s}\n',o(2));
fprintf(fid,'%s}\n',o(1));
fprintf(fid,'}\n');
end
|
github
|
philippboehmsturm/antx-master
|
gifti.m
|
.m
|
antx-master/xspm8/@gifti/gifti.m
| 3,622 |
utf_8
|
770f3ed1f17658bff49edbacd0062416
|
function this = gifti(varargin)
% GIfTI Geometry file format class
% Geometry format under the Neuroimaging Informatics Technology Initiative
% (NIfTI):
% http://www.nitrc.org/projects/gifti/
% http://nifti.nimh.nih.gov/
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: gifti.m 3999 2010-07-19 10:54:18Z guillaume $
switch nargin
case 0
this = giftistruct;
this = class(this,'gifti');
case 1
if isa(varargin{1},'gifti')
this = varargin{1};
elseif isstruct(varargin{1})
f = {'faces', 'face', 'tri' 'vertices', 'vert', 'pnt', 'cdata'};
ff = {'faces', 'faces', 'faces', 'vertices', 'vertices', 'vertices', 'cdata'};
[c, ia] = intersect(f,fieldnames(varargin{1}));
if ~isempty(c)
this = gifti;
for i=1:length(c)
this = subsasgn(this,...
struct('type','.','subs',ff{ia(i)}),...
varargin{1}.(c{i}));
end
elseif isempty(setxor(fieldnames(varargin{1}),...
{'metadata','label','data'}))
this = class(varargin{1},'gifti');
else
error('[GIFTI] Invalid structure.');
end
elseif ishandle(varargin{1})
this = struct('vertices',get(varargin{1},'Vertices'), ...
'faces', get(varargin{1},'Faces'));
if ~isempty(get(varargin{1},'FaceVertexCData'));
this.cdata = get(varargin{1},'FaceVertexCData');
end
this = gifti(this);
elseif isnumeric(varargin{1})
this = gifti;
this = subsasgn(this,...
struct('type','.','subs','cdata'),...
varargin{1});
elseif ischar(varargin{1})
if size(varargin{1},1)>1
this = gifti(cellstr(varargin{1}));
return;
end
[p,n,e] = fileparts(varargin{1});
if strcmpi(e,'.mat')
try
this = gifti(load(varargin{1}));
catch
error('[GIFTI] Loading of file %s failed.', varargin{1});
end
else
this = read_gifti_file(varargin{1},giftistruct);
this = class(this,'gifti');
end
elseif iscellstr(varargin{1})
fnames = varargin{1};
this(numel(fnames)) = giftistruct;
this = class(this,'gifti');
for i=1:numel(fnames)
this(i) = gifti(fnames{i});
end
else
error('[GIFTI] Invalid object construction.');
end
otherwise
error('[GIFTI] Invalid object construction.');
end
%==========================================================================
function s = giftistruct
s = struct(...
'metadata', ...
struct(...
'name', {}, ...
'value', {} ...
), ...
'label', ...
struct(...
'name', {}, ...
'index', {} ...
), ...
'data', ...
struct(...
'attributes', {}, ...
'metadata', struct('name',{}, 'value',{}), ...
'space', {}, ...
'data', {} ...
) ...
);
|
github
|
philippboehmsturm/antx-master
|
read_gifti_file.m
|
.m
|
antx-master/xspm8/@gifti/private/read_gifti_file.m
| 6,672 |
utf_8
|
6b1ffd0854407b6710a55c2345f19d7e
|
function this = read_gifti_file(filename, this)
% Low level reader of GIfTI 1.0 files
% FORMAT this = read_gifti_file(filename, this)
% filename - XML GIfTI filename
% this - structure with fields 'metaData', 'label' and 'data'.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: read_gifti_file.m 4613 2012-01-08 12:04:11Z guillaume $
% Import XML-based GIfTI file
%--------------------------------------------------------------------------
try
t = xmltree(filename);
catch
error('[GIFTI] Loading of XML file %s failed.', filename);
end
% Root element of a GIFTI file
%--------------------------------------------------------------------------
if ~strcmp(get(t,root(t),'name'),'GIFTI')
error('[GIFTI] %s is not a GIFTI 1.0 file.', filename);
end
attr = cell2mat(attributes(t,'get',root(t)));
attr = cell2struct({attr.val},strrep({attr.key},':','___'),2);
if ~all(ismember({'Version','NumberOfDataArrays'},fieldnames(attr)))
error('[GIFTI] Missing mandatory attributes for GIFTI root element.');
end
if str2double(attr.Version) ~= 1
warning('[GIFTI] Unknown specification version of GIFTI file (%s).',attr.Version);
end
nbData = str2double(attr.NumberOfDataArrays);
% Read children elements
%--------------------------------------------------------------------------
uid = children(t,root(t));
for i=1:length(uid)
switch get(t,uid(i),'name')
case 'MetaData'
this.metadata = gifti_MetaData(t,uid(i));
case 'LabelTable'
this.label = gifti_LabelTable(t,uid(i));
case 'DataArray'
this.data{end+1} = gifti_DataArray(t,uid(i),filename);
otherwise
warning('[GIFTI] Unknown element "%s": ignored.',get(t,uid(i),'name'));
end
end
if nbData ~= length(this.data)
warning('[GIFTI] Mismatch between expected and effective number of datasets.');
end
%==========================================================================
function s = gifti_MetaData(t,uid)
s = struct('name',{}, 'value',{});
c = children(t,uid);
for i=1:length(c)
for j=children(t,c(i))
s(i).(lower(get(t,j,'name'))) = get(t,children(t,j),'value');
end
end
%==========================================================================
function s = gifti_LabelTable(t,uid)
s = struct('name',{}, 'key',[], 'rgba',[]);
c = children(t,uid);
for i=1:length(c)
a = attributes(t,'get',c(i));
s(1).rgba(i,1:4) = NaN;
for j=1:numel(a)
switch lower(a{j}.key)
case {'key','index'}
s(1).key(i) = str2double(a{j}.val);
case 'red'
s(1).rgba(i,1) = str2double(a{j}.val);
case 'green'
s(1).rgba(i,2) = str2double(a{j}.val);
case 'blue'
s(1).rgba(i,3) = str2double(a{j}.val);
case 'alpha'
s(1).rgba(i,4) = str2double(a{j}.val);
otherwise
end
end
s(1).name{i} = get(t,children(t,c(i)),'value');
end
%==========================================================================
function s = gifti_DataArray(t,uid,filename)
s = struct(...
'attributes', {}, ...
'data', {}, ...
'metadata', struct([]), ...
'space', {} ...
);
attr = cell2mat(attributes(t,'get',uid));
s(1).attributes = cell2struct({attr.val},{attr.key},2);
s(1).attributes.Dim = [];
for i=1:str2double(s(1).attributes.Dimensionality)
f = sprintf('Dim%d',i-1);
s(1).attributes.Dim(i) = str2double(s(1).attributes.(f));
s(1).attributes = rmfield(s(1).attributes,f);
end
s(1).attributes = rmfield(s(1).attributes,'Dimensionality');
if isfield(s(1).attributes,'ExternalFileName') && ...
~isempty(s(1).attributes.ExternalFileName)
s(1).attributes.ExternalFileName = fullfile(fileparts(filename),...
s(1).attributes.ExternalFileName);
end
c = children(t,uid);
for i=1:length(c)
switch get(t,c(i),'name')
case 'MetaData'
s(1).metadata = gifti_MetaData(t,c(i));
case 'CoordinateSystemTransformMatrix'
s(1).space(end+1) = gifti_Space(t,c(i));
case 'Data'
s(1).data = gifti_Data(t,c(i),s(1).attributes);
otherwise
error('[GIFTI] Unknown DataArray element "%s".',get(t,c(i),'name'));
end
end
%==========================================================================
function s = gifti_Space(t,uid)
s = struct('DataSpace','', 'TransformedSpace','', 'MatrixData',[]);
for i=children(t,uid)
s.(get(t,i,'name')) = get(t,children(t,i),'value');
end
s.MatrixData = reshape(str2num(s.MatrixData),4,4)';
%==========================================================================
function d = gifti_Data(t,uid,s)
tp = getdict;
try
tp = tp.(s.DataType);
catch
error('[GIFTI] Unknown DataType.');
end
[unused,unused,mach] = fopen(1);
sb = @deal; %inline('x');
try
if (strcmp(s.Endian,'LittleEndian') && ~isempty(strmatch('ieee-be',mach))) ...
|| (strcmp(s.Endian,'BigEndian') && ~isempty(strmatch('ieee-le',mach)))
sb = @swapbyte;
end
catch
% Byte Order can be absent if encoding is ASCII, assume native otherwise
end
switch s.Encoding
case 'ASCII'
d = sscanf(get(t,children(t,uid),'value'),tp.format);
case 'Base64Binary'
d = typecast(sb(base64decode(get(t,children(t,uid),'value'))), tp.cast);
case 'GZipBase64Binary'
d = typecast(dunzip(sb(base64decode(get(t,children(t,uid),'value')))), tp.cast);
case 'ExternalFileBinary'
[p,f,e] = fileparts(s.ExternalFileName);
if isempty(p)
s.ExternalFileName = fullfile(pwd,[f e]);
end
if true
fid = fopen(s.ExternalFileName,'r');
if fid == -1
error('[GIFTI] Unable to read binary file %s.',s.ExternalFileName);
end
fseek(fid,str2double(s.ExternalFileOffset),0);
d = sb(fread(fid,prod(s.Dim),['*' tp.class]));
fclose(fid);
else
d = file_array(s.ExternalFileName, s.Dim, tp.class, ...
str2double(s.ExternalFileOffset),1,0,'ro');
end
otherwise
error('[GIFTI] Unknown data encoding: %s.',s.Encoding);
end
if length(s.Dim) == 1, s.Dim(end+1) = 1; end
switch s.ArrayIndexingOrder
case 'RowMajorOrder'
d = permute(reshape(d,fliplr(s.Dim)),length(s.Dim):-1:1);
case 'ColumnMajorOrder'
d = reshape(d,s.Dim);
otherwise
error('[GIFTI] Unknown array indexing order.');
end
|
github
|
philippboehmsturm/antx-master
|
isintent.m
|
.m
|
antx-master/xspm8/@gifti/private/isintent.m
| 2,094 |
utf_8
|
558a3aa4dffb45d067e660999e803050
|
function [a, b] = isintent(this,intent)
% Correspondance between fieldnames and NIfTI intents
% FORMAT ind = isintent(this,intent)
% this - GIfTI object
% intent - fieldnames
% a - indices of found intent(s)
% b - indices of dataarrays of found intent(s)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: isintent.m 4717 2012-04-19 11:02:50Z guillaume $
a = [];
b = [];
if ischar(intent), intent = cellstr(intent); end
c = cdata;
for i=1:length(this(1).data)
switch this(1).data{i}.attributes.Intent(14:end)
case 'POINTSET'
[tf, loc] = ismember('vertices',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
[tf, loc] = ismember('mat',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'TRIANGLE'
[tf, loc] = ismember('faces',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'VECTOR'
[tf, loc] = ismember('normals',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case {'NONE', 'LABEL', 'SHAPE', 'TIME_SERIES', 'RGB_VECTOR', ...
'RGBA_VECTOR' c{:}}
[tf, loc] = ismember('cdata',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
otherwise
fprintf('Intent %s is ignored.\n',this.data{i}.attributes.Intent);
end
end
%[d,i] = unique(a);
%if length(d) < length(a)
% warning('Several fields match intent type. Using first.');
% a = a(i);
% b = b(i);
%end
function c = cdata
c = {
'CORREL'
'TTEST'
'FTEST'
'ZSCORE'
'CHISQ'
'BETA'
'BINOM'
'GAMMA'
'POISSON'
'NORMAL'
'FTEST_NONC'
'CHISQ_NONC'
'LOGISTIC'
'LAPLACE'
'UNIFORM'
'TTEST_NONC'
'WEIBULL'
'CHI'
'INVGAUSS'
'EXTVAL'
'PVAL'
'LOGPVAL'
'LOG10PVAL'
'ESTIMATE'
'LABEL'
'NEURONAMES'
};
|
github
|
philippboehmsturm/antx-master
|
mne_load_coil_def.m
|
.m
|
antx-master/xspm8/external/mne/mne_load_coil_def.m
| 8,644 |
utf_8
|
772b6afb3be6c17199d073e9078d092f
|
function [CoilDef,Header] = mne_load_coil_def(fname);
%
%
% [CoilDef,Header] = mne_load_coil_def(fname);
% CoilDef = mne_load_coil_def(fname);
%
% If file name is not specified, the standard coil definition file
% $MNE_ROOT/setup/mne/coil_def.dat or $MNE_ROOT/share/mne/coil_def.dat is read
%
% The content of the coil definition file is described in
% section 5.6 of the MNE manual
%
% This routine is modified from the original BrainStorm routine
% created by John C. Mosher
%
%
% John C. Mosher
% Los Alamos National Laboratory
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
% Copyright (c) 2005 BrainStorm MMIV by the University of Southern California
% Principal Investigator:
% ** Professor Richard M. Leahy, USC Signal & Image Processing Institute
%
%
% Revision 1.5 2006/09/08 19:27:13 msh
% Added KIT coil type to mne_load_coil_def
% Allow reading of measurement info by specifying just a file name.
%
% Revision 1.4 2006/04/25 12:29:10 msh
% Added Magnes and CTF reference coil drawings.
%
% Revision 1.3 2006/04/23 15:29:40 msh
% Added MGH to the copyright
%
% Revision 1.2 2006/04/17 15:01:34 msh
% More small improvements.
%
% Revision 1.1 2006/04/17 11:52:15 msh
% Added coil definition stuff
%
%
me='MNE:mne_load_coil_def';
%% Setup the default inputs
if nargin == 0
fname = mne_file_name('setup/mne/coil_def.dat');
if ~exist(fname,'file')
fname = mne_file_name('share/mne/coil_def.dat');
if ~exist(fname,'file')
error(me,'The standard coil definition file was not found');
end
end
end
% Read in the coil_def information
%% Open, Read in entire file, close
fid = fopen(fname,'rt');
if fid < 0
error(me,'Could not open coil definition file %s',fname);
end
istr = 1; % string indexer
str_array = cell(1000,1); % preallocate
str_array{istr} = fgetl(fid); % get first string
while ischar(str_array{istr}),
istr = istr + 1;
str_array{istr} = fgetl(fid); % get next string
end
fclose(fid);
str_array = str_array(1:(istr-1)); % trim allocation
%% Read the Header, find the structure
% Gather the header lines
HeaderLines = strmatch('#',str_array); % lines that begin with a comment
% where are the structure lines
StructureLines = strmatch('# struct',str_array); % subset of header lines
% should be two
if length(StructureLines) ~= 2,
error(me,'%s anticipates two lines of structures',mfilename)
end
% with each structure line is a format line
FormatLines = strmatch('# format',str_array); % subset of header lines
% assume there are also two
FieldNames = cell(1,2);
Format = cell(1,2);
% first structure is the coil information
% won't actually use the second structure, just its format
for i = 1:2,
FieldNames{i} = strread(str_array{StructureLines(i)},'%s');
FieldNames{i}(1:2) = []; % strip the comment symbol and struct keyword
[ignore,Format{i}] = strtok(str_array{FormatLines(i)},'''');
Format{i} = strrep(Format{i},'''',''); % strip the single quotes
end
%% Allocate the arrays for loading
% interleave every fieldname with a null value
struct_arg = [FieldNames{1} cell(length(FieldNames{1}),1)]';
% each column an argument pair
% Preallocate a structure
[CoilDef(1:100)] = deal(struct(struct_arg{:}));
% Convert the rest of the string array to a structure
iCoil = 0; % counter
iLine = HeaderLines(end); % next line after header
while iLine < length(str_array), % number of lines in file
iCoil = iCoil + 1; % next coil definition
iLine = iLine + 1; % next line
% first read the integer information on the coil
% begin by breaking the line into two parts, numeric and description
[numeric_items, description] = strtok(str_array{iLine},'"');
temp = sscanf(numeric_items,Format{1}); % extra %s doesn't matter
% assign temp in the order of the fields
for i = 1:(length(FieldNames{1})-1),
CoilDef(iCoil).(FieldNames{1}{i}) = temp(i);
end
% then assign the description
% let's strip the quotes first
description = strrep(description,'"','');
CoilDef(iCoil).(FieldNames{1}{end}) = description;
% now read the coil definition
CoilDef(iCoil).coildefs = zeros(CoilDef(iCoil).num_points,7);
for i = 1:CoilDef(iCoil).num_points,
iLine = iLine + 1;
CoilDef(iCoil).coildefs(i,:) = sscanf(str_array{iLine},...
Format{2})';
end
% now draw it
% local subfunction below
CoilDef(iCoil).FV = draw_sensor(CoilDef(iCoil));
end
CoilDef = CoilDef(1:iCoil); % trim allocation
Header = str_array(HeaderLines);
function FV = draw_sensor(CoilDef);
% create a patch based on the sensor type
% The definitions as of 14 October 2005:
% for i = 1:3:length(CoilDef),fprintf('%d %s\n',CoilDef(i).id,CoilDef(i).description);end
% 2 Neuromag-122 planar gradiometer size = 27.89 mm base = 16.20 mm
% 2000 Point magnetometer
% 3012 Vectorview planar gradiometer T1 size = 26.39 mm base = 16.80 mm
% 3013 Vectorview planar gradiometer T2 size = 26.39 mm base = 16.80 mm
% 3022 Vectorview magnetometer T1 size = 25.80 mm
% 3023 Vectorview magnetometer T2 size = 25.80 mm
% 3024 Vectorview magnetometer T3 size = 21.00 mm
% 4001 Magnes WH2500 magnetometer size = 11.50 mm
% 4002 Magnes WH3600 gradiometer size = 18.00 mm base = 50.00 mm
% 5001 CTF axial gradiometer size = 18.00 mm base = 50.00 mm
FV = struct('faces',[],'vertices',[]); % standard convention
% recall that vertices are 1 per ROW, not column, of matrix
switch CoilDef.id
case {2,3012,3013,3011}
% square figure eight
% wound by right hand rule such that +x side is "up" (+z)
LongSide = CoilDef.size*1000; % length of long side in mm
Offset = 2.5; % mm offset of the center portion of planar grad coil
FV.vertices = [0 0 0; Offset 0 0; ...
Offset -LongSide/2 0; LongSide/2 -LongSide/2 0; ...
LongSide/2 LongSide/2 0; ...
Offset LongSide/2 0; Offset 0 0; ...
0 0 0; -Offset 0 0; -Offset -LongSide/2 0; ...
-LongSide/2 -LongSide/2 0; ...
-LongSide/2 LongSide/2 0; ...
-Offset LongSide/2 0; -Offset 0 0]/1000;
FV.faces = [1:length(FV.vertices)];
case 2000
% point source
LongSide = 2; % mm, tiny square
FV.vertices = [-1 1 0;1 1 0;1 -1 0; -1 -1 0]*LongSide/1000/2;
FV.faces = [1:length(FV.vertices)];
case {3022, 3023, 3024}
% square magnetometer
LongSide = CoilDef.size*1000; % mm, length of one side
FV.vertices = [-1 1 0;1 1 0;1 -1 0; -1 -1 0]*LongSide/1000/2;
FV.faces = [1:length(FV.vertices)];
case {4001,4003,5002}
% round magnetometer
Radius = CoilDef.size*1000/2; % mm, radius of coil
Len_cir = 15; % number of points for circle
circle = cos(2*pi*[0:(Len_cir-1)]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:(Len_cir-1)]/Len_cir); % complex circle unit
FV.vertices = ...
[real(circle)' imag(circle)' zeros(Len_cir,1)]*Radius/1000;
FV.faces = [1:length(FV.vertices)];
case {4002, 5001, 5003, 4004, 6001}
% round coil 1st order gradiometer
Radius = CoilDef.size*1000/2; % mm radius
Baseline = CoilDef.baseline*1000; % axial separation
Len_cir = 15; % number of points for circle
% This time, go all the way around circle to close it fully
circle = cos(2*pi*[0:Len_cir]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:Len_cir]/Len_cir); % complex circle unit
circle = circle*Radius; % scaled
FV.vertices = ...
[[real(circle)' imag(circle)' zeros(Len_cir+1,1)];... % first coil
[real(circle)' -imag(circle)' zeros(Len_cir+1,1)+Baseline]]/1000; % 2nd coil
FV.faces = [1:length(FV.vertices)];
case {5004,4005}
% round coil 1st order off-diagonal gradiometer
Radius = CoilDef.size*1000/2; % mm radius
Baseline = CoilDef.baseline*1000; % axial separation
Len_cir = 15; % number of points for circle
% This time, go all the way around circle to close it fully
circle = cos(2*pi*[0:Len_cir]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:Len_cir]/Len_cir); % complex circle unit
circle = circle*Radius; % scaled
FV.vertices = ...
[[real(circle)'+Baseline/2.0 imag(circle)' zeros(Len_cir+1,1)];... % first coil
[real(circle)'-Baseline/2.0 -imag(circle)' zeros(Len_cir+1,1)]]/1000; % 2nd coil
FV.faces = [1:length(FV.vertices)];
otherwise
FV = [];
end
|
github
|
philippboehmsturm/antx-master
|
fiff_find_evoked.m
|
.m
|
antx-master/xspm8/external/mne/fiff_find_evoked.m
| 2,846 |
utf_8
|
f7c5e4fd4395754f0e87d3fe6e984d62
|
function [data_sets] = fiff_find_evoked(fname)
%
% [data_sets] = fiff_find_evoked(fname)
%
% Find all evoked data sets in a fif file and create a list of descriptors
%
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
global FIFF;
if isempty(FIFF)
FIFF = fiff_define_constants();
end
me = 'MNE:fiff_find_evoked';
%
% Open the file
%
[ fid, tree ] = fiff_open(fname);
data_sets = struct('comment',{},'aspect_kind',{},'aspect_name',{});
%
% Find all evoked data sets
%
evoked = fiff_dir_tree_find(tree, FIFF.FIFFB_EVOKED);
if length(evoked) == 0
fclose(fid);
return
end
%
% Identify the aspects
%
naspect = 0;
for k = 1:length(evoked)
sets(k).aspects = fiff_dir_tree_find(evoked(k), FIFF.FIFFB_ASPECT);
sets(k).naspect = length(sets(k).aspects);
naspect = naspect + sets(k).naspect;
end
%
% Collect the desired information
%
count = 1;
for k = 1:length(evoked)
evoked_comment = find_tag(evoked(k), FIFF.FIFF_COMMENT);
for a = 1:sets(k).naspect
aspect_comment = find_tag(sets(k).aspects(a), FIFF.FIFF_COMMENT);
aspect_kind = find_tag(sets(k).aspects(a), FIFF.FIFF_ASPECT_KIND);
if ~isempty(aspect_comment)
data_sets(count).comment = aspect_comment.data;
elseif ~isempty(evoked_comment)
data_sets(count).comment = evoked_comment.data;
else
data_sets(count).comment = 'No comment';
end
if ~isempty(aspect_kind)
data_sets(count).aspect_kind = aspect_kind.data;
else
data_sets(count).aspect_kind = -1;
end
switch data_sets(count).aspect_kind
case FIFF.FIFFV_ASPECT_AVERAGE
data_sets(count).aspect_name = 'Average';
case FIFF.FIFFV_ASPECT_STD_ERR
data_sets(count).aspect_name = 'Standard error';
case FIFF.FIFFV_ASPECT_SINGLE
data_sets(count).aspect_name = 'Single';
case FIFF.FIFFV_ASPECT_SUBAVERAGE
data_sets(count).aspect_name = 'Subaverage';
case FIFF.FIFFV_ASPECT_ALTAVERAGE
data_sets(count).aspect_name = 'Alt. subaverage';
case FIFF.FIFFV_ASPECT_SAMPLE
data_sets(count).aspect_name = 'Sample';
case FIFF.FIFFV_ASPECT_POWER_DENSITY
data_sets(count).aspect_name = 'Power density spectrum';
case FIFF.FIFFV_ASPECT_DIPOLE_WAVE
data_sets(count).aspect_name = 'Dipole source waveform';
otherwise
data_sets(count).aspect_name = 'Unknown';
end
count = count + 1;
end
end
fclose(fid);
return
function [tag] = find_tag(node, findkind)
for p = 1:node.nent
kind = node.dir(p).kind;
pos = node.dir(p).pos;
if kind == findkind
tag = fiff_read_tag(fid, pos);
return
end
end
tag = [];
return
end
end
|
github
|
philippboehmsturm/antx-master
|
bemcp_example.m
|
.m
|
antx-master/xspm8/external/bemcp/bemcp_example.m
| 21,718 |
utf_8
|
b6bc2bc4ee1696a4f8720bd0d79be654
|
function bemcp_example
% Simple function to test/demonstrate how the Boundary element functions are
% used in combination with Fildtrip/Forwinv routines.
%
% 1. A model is created as 3 concentric meshed spheres (using FT's
% icosahedron routines),
% 2. then random electrodes are placed on the upper part of the outer
% sphere.
% 3. the model is then "prepared" with 'ft_prepare_bemmodel', this bits
% takes most time as it requires LOTS of calculation.
% 4. sensors and volumes are plugged together by 'forwinv_prepare_vol_sens'
% 5. Finally the leadfiled for 3 orthogonal sources placed at one location
% is calculated with 'forwinv_compute_leadfield.m'
% 6. Display the 3 leadfields
%
% NOTE:
% this bit of code needs access to low level fieldtrip/forwinv routines
% which have been copy/pasted here under.
% Be aware that this way of programming is generally NOT advisable!
% I used it only to ensure a quick & dirty check of the BEM module...
% Christophe Phillips
% $Id: bemcp_example.m 4792 2012-07-19 11:33:21Z spm $
% create volume conductor starting from unit sphere
[pnt, tri] = icosahedron162;
vol = [];
vol.cond = [1 1/80 1];
vol.source = 1; % index of source compartment
vol.skin_surface = 3; % index of skin surface
% inner_skull_surface
vol.bnd(1).pnt = pnt*88;
vol.bnd(1).tri = tri;
% outer_skull_surface
vol.bnd(2).pnt = pnt*92;
vol.bnd(2).tri = tri;
% skin_surface
vol.bnd(3).pnt = pnt*100;
vol.bnd(3).tri = tri;
% create the BEM system matrix
cfg = [];
cfg.method = 'bemcp';
vol1 = ft_prepare_bemmodel(cfg, vol);
% create some random electrodes
pnt = randn(200,3);
pnt = pnt(pnt(:,3)>0, :); % only those on the upper half
sens = [];
for i=1:size(pnt,1)
sens.pnt(i,:) = pnt(i,:) / norm(pnt(i,:)); % scale towards the skin surface
sens.label{i} = sprintf('%02d', i);
end
% prepare the sensor array and volume conduction, i.e. set up the linear
% interpolation from vertices to electrodes
[vol2, sens] = forwinv_prepare_vol_sens(vol1, sens);
lf = forwinv_compute_leadfield([0 0 50], sens, vol2);
figure; triplot(sens.pnt, [], lf(:,1)); colorbar
figure; triplot(sens.pnt, [], lf(:,2)); colorbar
figure; triplot(sens.pnt, [], lf(:,3)); colorbar
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Subfunctions from FieldTrip
function [pnt, dhk] = icosahedron162
% ICOSAHEDRON162 creates a 2-fold refined icosahedron
% Copyright (C) 2003, Robert Oostenveld
%
% $Log: icosahedron162.m,v $
% Revision 1.3 2003/11/28 09:40:12 roberto
% added a single help line
%
% Revision 1.2 2003/03/04 21:46:18 roberto
% added CVS log entry and synchronized all copyright labels
%
[pnt, dhk] = icosahedron;
[pnt, dhk] = refine(pnt, dhk);
[pnt, dhk] = refine(pnt, dhk);
pnt = pnt ./ repmat(sqrt(sum(pnt.^2,2)), 1,3);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pnt, dhk] = icosahedron
% ICOSAHEDRON creates an icosahedron
%
% [pnt, dhk] = icosahedron
% creates an icosahedron with 12 vertices and 20 triangles
%
% See also OCTAHEDRON, ICOSAHEDRON42, ICOSAHEDRON162, ICOSAHEDRON642, ICOSAHEDRON2562
% Copyright (C) 2002, Robert Oostenveld
%
% $Log: icosahedron.m,v $
% Revision 1.4 2006/07/26 11:03:38 roboos
% added "see also octahedron"
%
% Revision 1.3 2003/03/11 15:35:20 roberto
% converted all files from DOS to UNIX
%
% Revision 1.2 2003/03/04 21:46:18 roberto
% added CVS log entry and synchronized all copyright labels
%
dhk = [
1 2 3
1 3 4
1 4 5
1 5 6
1 6 2
2 8 3
3 9 4
4 10 5
5 11 6
6 7 2
7 8 2
8 9 3
9 10 4
10 11 5
11 7 6
12 8 7
12 9 8
12 10 9
12 11 10
12 7 11
];
pnt = zeros(12, 3);
rho=0.4*sqrt(5);
phi=2*pi*(0:4)/5;
pnt( 1, :) = [0 0 1]; % top point
pnt(2:6, 1) = rho*cos(phi)';
pnt(2:6, 2) = rho*sin(phi)';
pnt(2:6, 3) = rho/2;
pnt(7:11, 1) = rho*cos(phi - pi/5)';
pnt(7:11, 2) = rho*sin(phi - pi/5)';
pnt(7:11, 3) = -rho/2;
pnt(12, :) = [0 0 -1]; % bottom point
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pntr, dhkr] = refine(pnt, dhk, method, varargin)
% REFINE a 3D surface that is described by a triangulation
%
% Use as
% [pnt, tri] = refine(pnt, tri)
% [pnt, tri] = refine(pnt, tri, 'updown', numtri)
%
% The default method is to refine the mesh globally by inserting a vertex at
% each edge according to the algorithm described in Banks, 1983.
%
% The alternative 'updown' method refines the mesh a couple of times
% using Banks' algorithm, followed by a downsampling using the REDUCEPATCH
% function.
% The Banks method is a memory efficient implementation which remembers
% the previously inserted vertices. The refinement algorithm executes in
% linear time with the number of triangles.
% Copyright (C) 2002-2005, Robert Oostenveld
%
% $Log: refine.m,v $
% Revision 1.4 2005/05/06 08:54:31 roboos
% added 'updown method, using matlab reducepatch function
%
% Revision 1.3 2003/03/11 15:35:20 roberto
% converted all files from DOS to UNIX
%
% Revision 1.2 2003/03/04 21:46:19 roberto
% added CVS log entry and synchronized all copyright labels
%
if nargin<3
method = 'banks';
end
switch lower(method)
case 'banks'
npnt = size(pnt,1);
ndhk = size(dhk,1);
insert = spalloc(3*npnt,3*npnt,3*ndhk);
dhkr = zeros(4*ndhk,3); % allocate memory for the new triangles
pntr = zeros(npnt+3*ndhk,3); % allocate memory for the maximum number of new vertices
pntr(1:npnt,:) = pnt; % insert the original vertices
current = npnt;
for i=1:ndhk
if ~insert(dhk(i,1),dhk(i,2))
current = current + 1;
pntr(current,:) = (pnt(dhk(i,1),:) + pnt(dhk(i,2),:))/2;
insert(dhk(i,1),dhk(i,2)) = current;
insert(dhk(i,2),dhk(i,1)) = current;
v12 = current;
else
v12 = insert(dhk(i,1),dhk(i,2));
end
if ~insert(dhk(i,2),dhk(i,3))
current = current + 1;
pntr(current,:) = (pnt(dhk(i,2),:) + pnt(dhk(i,3),:))/2;
insert(dhk(i,2),dhk(i,3)) = current;
insert(dhk(i,3),dhk(i,2)) = current;
v23 = current;
else
v23 = insert(dhk(i,2),dhk(i,3));
end
if ~insert(dhk(i,3),dhk(i,1))
current = current + 1;
pntr(current,:) = (pnt(dhk(i,3),:) + pnt(dhk(i,1),:))/2;
insert(dhk(i,3),dhk(i,1)) = current;
insert(dhk(i,1),dhk(i,3)) = current;
v31 = current;
else
v31 = insert(dhk(i,3),dhk(i,1));
end
% add the 4 new triangles with the correct indices
dhkr(4*(i-1)+1, :) = [dhk(i,1) v12 v31];
dhkr(4*(i-1)+2, :) = [dhk(i,2) v23 v12];
dhkr(4*(i-1)+3, :) = [dhk(i,3) v31 v23];
dhkr(4*(i-1)+4, :) = [v12 v23 v31];
end
% remove the space for the vertices that was not used
pntr = pntr(1:current, :);
case 'updown'
ndhk = size(dhk,1);
while ndhk<varargin{1}
% increase the number of triangles by a factor of 4
[pnt, dhk] = refine(pnt, dhk, 'banks');
ndhk = size(dhk,1);
end
% reduce number of triangles using Matlab function
[dhkr, pntr] = reducepatch(dhk, pnt, varargin{1});
otherwise
error(['unsupported method: ' method]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hs, hc, contour] = triplot(pnt, tri, val, mode, levels)
% TRIPLOT make 2D or 3D plot of triangulated surface and interpolated values
% The surface can be displayed with linear interpolated values or with
% linear interpolated contours of a potential distribution.
%
% Use as
% triplot(pnt, tri, value)
% triplot(pnt, tri, value, mode)
% triplot(pnt, tri, value, mode, levels)
% This will make a plot of value on the surface described by triangles
% tri with vertices pnt. The matrix tri can be [], in which case a
% it will be computed using a delaunay triangulation.
%
% The visualization mode can be
% 'surface' make interpolated plot of value on surface (default)
% 'faces' plot white triangles only (value can be [])
% 'faces_red' plot red triangles only (value can be [])
% 'faces_blue' plot blue triangles only (value can be [])
% 'faces_skin' plot skin-colored triangles only (value can be [])
% 'face_index' plot index of each triangle (value can be [])
% 'nodes' plot black vertices only (value can be [])
% 'node_index' plot index of each vertex (value can be [])
% 'node_label' plot label of each vertex (value should be cell array)
% 'edges' plot black edges only (value can be [])
% 'contour' make interpolated contour plot of value on surface
% 'contour_bw' make interpolated black-white contour plot
% 'contour_rb' make interpolated contour plot with red-blue
%
% With the optional levels, you can specify the levels at which contours will
% be plotted
%
% See also PATCH, COLORMAP, VIEW (general Matlab commands)
% updated on Mon Jul 23 12:41:44 MET DST 2001
% updated on Fri Jan 31 11:47:28 CET 2003
% Copyright (C) 2001=2006, Robert Oostenveld
%
% $Log: triplot.m,v $
% Revision 1.7 2008/06/24 13:37:51 roboos
% added option faces_blue
% always return handle to objects that were plotted
%
% Revision 1.6 2007/01/03 17:00:35 roboos
% updated documentation, changed layout of code and comments
%
% Revision 1.5 2006/09/19 16:11:35 roboos
% added support for line segments, removed "axis equal" at end
%
% Revision 1.4 2006/05/02 19:15:28 roboos
% added 'faces_red' style
%
% Revision 1.3 2004/06/28 07:51:39 roberto
% improved documentation, added faces_skin
%
% Revision 1.2 2003/03/17 10:37:29 roberto
% improved general help comments and added copyrights
%
% start with empty return values
hs = [];
hc = [];
contour = [];
% everything is added to the current figure
holdflag = ishold;
hold on
% check the input variables
if ~isempty(val)
val = val(:);
end
if nargin<4
mode = 'surface';
end
if isempty(tri) & ~strcmp(mode, 'nodes')
% no triangulation was specified but a triangulation is needed
if size(pnt,2)==2
% make a 2d triangulation of the points using delaunay
tri = delaunay(pnt(:,1), pnt(:,2));
else
% make a 2d triangulation of the projected points using delaunay
prj = elproj(pnt);
tri = delaunay(prj(:,1), prj(:,2));
end
end
if size(tri,2)==2
% lines are specified instead of triangles, convert to triangles
tri(:,3) = tri(:,2);
end
if nargin<3
warning('only displaying triangle edges')
mode='edges';
val = [];
elseif nargin<4
% warning('default displaying surface')
mode='surface';
elseif nargin<5
% determine contour levels
if ~isempty(val) & ~iscell(val)
absmax = max(abs([min(val) max(val)]));
levels = linspace(-absmax,absmax,21);
else
levels = [];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute contours for 2D or 3D triangulation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(mode, 'contour') || strcmp(mode, 'contour_bw') || strcmp(mode, 'contour_rb')
triangle_val = val(tri);
triangle_min = min(triangle_val, [], 2);
triangle_max = max(triangle_val, [], 2);
for cnt_indx=1:length(levels)
cnt = levels(cnt_indx);
use = cnt>=triangle_min & cnt<=triangle_max;
counter = 0;
intersect1 = [];
intersect2 = [];
for tri_indx=find(use)'
pos = pnt(tri(tri_indx,:), :);
v(1) = triangle_val(tri_indx,1);
v(2) = triangle_val(tri_indx,2);
v(3) = triangle_val(tri_indx,3);
la(1) = (cnt-v(1)) / (v(2)-v(1)); % abcissa between vertex 1 and 2
la(2) = (cnt-v(2)) / (v(3)-v(2)); % abcissa between vertex 2 and 3
la(3) = (cnt-v(3)) / (v(1)-v(3)); % abcissa between vertex 1 and 2
abc(1,:) = pos(1,:) + la(1) * (pos(2,:) - pos(1,:));
abc(2,:) = pos(2,:) + la(2) * (pos(3,:) - pos(2,:));
abc(3,:) = pos(3,:) + la(3) * (pos(1,:) - pos(3,:));
counter = counter + 1;
sel = find(la>=0 & la<=1);
intersect1(counter, :) = abc(sel(1),:);
intersect2(counter, :) = abc(sel(2),:);
end
% remember the details for external reference
contour(cnt_indx).level = cnt;
contour(cnt_indx).n = counter;
contour(cnt_indx).intersect1 = intersect1;
contour(cnt_indx).intersect2 = intersect2;
end
% collect all different contourlevels for plotting
intersect1 = [];
intersect2 = [];
cntlevel = [];
for cnt_indx=1:length(levels)
intersect1 = [intersect1; contour(cnt_indx).intersect1];
intersect2 = [intersect2; contour(cnt_indx).intersect2];
cntlevel = [cntlevel; ones(contour(cnt_indx).n,1) * levels(cnt_indx)];
end
X = [intersect1(:,1) intersect2(:,1)]';
Y = [intersect1(:,2) intersect2(:,2)]';
C = [cntlevel(:) cntlevel(:)]';
if size(pnt,2)>2
Z = [intersect1(:,3) intersect2(:,3)]';
else
Z = zeros(2, length(cntlevel));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot the desired detail
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(mode)
case 'faces'
% plot the faces of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', 'white');
set(hs, 'EdgeColor', 'none');
case 'faces_skin'
% plot the faces of the 2D or 3D triangulation
skin_surface = [255 213 119]/255;
inner_skull_surface = [202 100 100]/255;
cortex = [255 213 119]/255;
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', skin_surface);
set(hs, 'EdgeColor', 'none');
lighting gouraud
material shiny
camlight
case 'faces_red'
% plot the faces of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', [1 0 0]);
set(hs, 'EdgeColor', 'none');
lighting gouraud
material shiny
camlight
case 'faces_blue'
% plot the faces of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', [0 0 1]);
set(hs, 'EdgeColor', 'none');
lighting gouraud
material shiny
camlight
case 'face_index'
% plot the triangle indices (numbers) at each face
for face_indx=1:size(tri,1)
str = sprintf('%d', face_indx);
tri_x = (pnt(tri(face_indx,1), 1) + pnt(tri(face_indx,2), 1) + pnt(tri(face_indx,3), 1))/3;
tri_y = (pnt(tri(face_indx,1), 2) + pnt(tri(face_indx,2), 2) + pnt(tri(face_indx,3), 2))/3;
tri_z = (pnt(tri(face_indx,1), 3) + pnt(tri(face_indx,2), 3) + pnt(tri(face_indx,3), 3))/3;
h = text(tri_x, tri_y, tri_z, str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
hs = [hs; h];
end
case 'edges'
% plot the edges of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', 'none');
set(hs, 'EdgeColor', 'black');
case 'nodes'
% plot the nodes (vertices) only as points
if size(pnt, 2)==2
hs = plot(pnt(:,1), pnt(:,2), 'k.');
else
hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'k.');
end
case 'nodes_blue'
% plot the nodes (vertices) only as points
if size(pnt, 2)==2
hs = plot(pnt(:,1), pnt(:,2), 'b.', 'MarkerSize', 20);
else
hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'b.', 'MarkerSize', 20);
end
case 'nodes_red'
% plot the nodes (vertices) only as points
if size(pnt, 2)==2
hs = plot(pnt(:,1), pnt(:,2), 'r.', 'MarkerSize', 20);
else
hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'r.', 'MarkerSize', 20);
end
case 'node_index'
% plot the vertex indices (numbers) at each node
for node_indx=1:size(pnt,1)
str = sprintf('%d', node_indx);
if size(pnt, 2)==2
h = text(pnt(node_indx, 1), pnt(node_indx, 2), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
else
h = text(pnt(node_indx, 1), pnt(node_indx, 2), pnt(node_indx, 3), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
hs = [hs; h];
end
case 'node_label'
% plot the vertex indices (numbers) at each node
for node_indx=1:size(pnt,1)
str = val{node_indx};
if ~isempty(str)
if size(pnt, 2)==2
h = text(pnt(node_indx, 1), pnt(node_indx, 2), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
else
h = text(pnt(node_indx, 1), pnt(node_indx, 2), pnt(node_indx, 3), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
else
h = -1;
end
hs = [hs; h];
end
case 'surface'
% plot a 2D or 3D triangulated surface with linear interpolation
if length(val)==size(pnt,1)
hs = patch('Vertices', pnt, 'Faces', tri, 'FaceVertexCData', val, 'FaceColor', 'interp');
else
hs = patch('Vertices', pnt, 'Faces', tri, 'CData', val, 'FaceColor', 'flat');
end
set(hs, 'EdgeColor', 'none');
case 'contour_bw'
% make black-white contours
hc = [];
for i=1:length(cntlevel)
if cntlevel(i)>0
linestyle = '-';
linewidth = 1;
elseif cntlevel(i)<0
linestyle = '--';
linewidth = 1;
else
linestyle = '-';
linewidth = 2;
end
h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ...
'ZData', Z(:,i), 'CData', C(:,i), ...
'facecolor','none','edgecolor','black', ...
'linestyle', linestyle, 'linewidth', linewidth, ...
'userdata',cntlevel(i));
hc = [hc; h1];
end
case 'contour_rb'
% make red-blue contours
hc = [];
for i=1:length(cntlevel)
if cntlevel(i)>0
edgecolor = 'red';
elseif cntlevel(i)<0
edgecolor = 'blue';
else
edgecolor = 'black';
end
h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ...
'ZData', Z(:,i), 'CData', C(:,i), ...
'facecolor','none','edgecolor',edgecolor, ...
'linestyle', '-', 'linewidth', 3, ...
'userdata',cntlevel(i));
hc = [hc; h1];
end
case 'contour'
% make full-color contours
hc = [];
for i=1:length(cntlevel)
h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ...
'ZData', Z(:,i), 'CData', C(:,i), ...
'facecolor','none','edgecolor','flat',...
'userdata',cntlevel(i));
hc = [hc; h1];
end
end % switch
axis off
axis vis3d
axis equal
if nargout==0
clear contour hc hs
end
if ~holdflag
hold off
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [proj] = elproj(pos, method);
% ELPROJ makes a azimuthal projection of a 3D electrode cloud
% on a plane tangent to the sphere fitted through the electrodes
% the projection is along the z-axis
%
% [proj] = elproj([x, y, z], 'method');
%
% Method should be one of these:
% 'gnomic'
% 'stereographic'
% 'ortographic'
% 'inverse'
% 'polar'
%
% Imagine a plane being placed against (tangent to) a globe. If
% a light source inside the globe projects the graticule onto
% the plane the result would be a planar, or azimuthal, map
% projection. If the imaginary light is inside the globe a Gnomonic
% projection results, if the light is antipodal a Sterographic,
% and if at infinity, an Orthographic.
%
% The default projection is a polar projection (BESA like).
% An inverse projection is the opposite of the default polar projection.
% Copyright (C) 2000-2008, Robert Oostenveld
%
% $Log: elproj.m,v $
% Revision 1.4 2008/05/15 10:54:24 roboos
% updated documentation
%
% Revision 1.3 2007/03/20 10:29:35 roboos
% renamed method 'default' into 'polar'
%
% Revision 1.2 2003/03/17 10:37:28 roberto
% improved general help comments and added copyrights
%
x = pos(:,1);
y = pos(:,2);
if size(pos, 2)==3
z = pos(:,3);
end
if nargin<2
method='polar';
end
if nargin<3
secant=1;
end
if strcmp(method, 'orthographic')
% this method compresses the lowest electrodes very much
% electrodes on the bottom half of the sphere are folded inwards
xp = x;
yp = y;
num = length(find(z<0));
str = sprintf('%d electrodes may be folded inwards in orthographic projection\n', num);
if num
warning(str);
end
proj = [xp yp];
elseif strcmp(method, 'gnomic')
% the lightsource is in the middle of the sphere
% electrodes on the equator are projected at infinity
% electrodes below the equator are not projected at all
rad = mean(sqrt(x.^2 + y.^2 + z.^2));
phi = cart2pol(x, y);
th = atan(sqrt(x.^2 + y.^2) ./ z);
xp = cos(phi) .* tan(th) .* rad;
yp = sin(phi) .* tan(th) .* rad;
num = length(find(th==pi/2 | z<0));
str = sprintf('removing %d electrodes from gnomic projection\n', num);
if num
warning(str);
end
xp(find(th==pi/2 | z<0)) = NaN;
yp(find(th==pi/2 | z<0)) = NaN;
proj = [xp yp];
elseif strcmp(method, 'stereographic')
% the lightsource is antipodal (on the south-pole)
rad = mean(sqrt(x.^2 + y.^2 + z.^2));
z = z + rad;
phi = cart2pol(x, y);
th = atan(sqrt(x.^2 + y.^2) ./ z);
xp = cos(phi) .* tan(th) .* rad * 2;
yp = sin(phi) .* tan(th) .* rad * 2;
num = length(find(th==pi/2 | z<0));
str = sprintf('removing %d electrodes from stereographic projection\n', num);
if num
warning(str);
end
xp(find(th==pi/2 | z<0)) = NaN;
yp(find(th==pi/2 | z<0)) = NaN;
proj = [xp yp];
elseif strcmp(method, 'inverse')
% compute the inverse projection of the default angular projection
[th, r] = cart2pol(x, y);
[xi, yi, zi] = sph2cart(th, pi/2 - r, 1);
proj = [xi, yi, zi];
else
% use default angular projection
[az, el, r] = cart2sph(x, y, z);
[x, y] = pol2cart(az, pi/2 - el);
proj = [x, y];
end
|
github
|
philippboehmsturm/antx-master
|
writeCPersist.m
|
.m
|
antx-master/xspm8/external/ctf/writeCPersist.m
| 5,086 |
utf_8
|
0c56dc571aa56100f050678e5fe815ff
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%% Function writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeCPersist(filename,Tag)
% Version 1.2 24 April 2007. Removed terminating null characters from charatcer strings
% types 10,11)
% Version 1.1 13 April 2007
% Write a CTF CPersist file. See document CTF MEG File Format, PN900-0066
% Inputs : filename : Name of the output file name including path
% Tag: Structure array containing all of the tags, types, and data.
% 31 Aug 2006: Recognizes type=1,...,17. If other data types are specified,
% writeCPersist will print an error message.
% Delete existing file so the new file has the correct creation data/time.
if nargin==0
fprintf(['writeCPersist: Version 1.2 24 April 2007 Writes a CTF CPersist file.\n'...
'\twriteCPersist(filename,Tag) writes a CPersist file from the contents of\n',...
'\tstructure array Tag. Tag is in the format prepared by readCPersist.\n\n']);
Tag=[];
return
end
if exist(filename)==2
delete(filename);
end
startString='WS1_';
EOFstring='EndOfParameters';
startVal=256.^[3:-1:0]*double(startString)'; % Integer version of startString
fid=fopen(filename,'w','ieee-be');
EOFcount=0; % Make sure that the startString's and EOFstring's balance
count=0;
while count<length(Tag)
count=count+1;
if strcmp(Tag(count).name,startString) % start of Cpersist object
fwrite(fid,startVal,'int32');
EOFcount=EOFcount-1;
continue
end
fwrite(fid,length(Tag(count).name),'int32'); % end of CPersist object
fwrite(fid,Tag(count).name,'char');
if strcmp(Tag(count).name,EOFstring);
EOFcount=EOFcount+1;
continue;
end
fwrite(fid,Tag(count).type,'int32');
if Tag(count).type==1
fwrite(fid,Tag(count).data,'int32');
elseif Tag(count).type==2 % Start embedded CPersist object
elseif Tag(count).type==3 % binary list
fwrite(fid,2*length(Tag(count).data),'int32');
fwrite(fid,Tag(count).data,'int16');
elseif Tag(count).type==4 % double
fwrite(fid,Tag(count).data,'float64');
elseif Tag(count).type==5 % integer
fwrite(fid,Tag(count).data,'int32');
elseif Tag(count).type==6 % short integer
fwrite(fid,Tag(count).data,'int16');
elseif Tag(count).type==7 % unsigned short integer
fwrite(fid,Tag(count).data,'uint16');
elseif Tag(count).type==8 % Boolean byte
fwrite(fid,Tag(count).data,'uint8');
elseif Tag(count).type==9; % CStr32
nChar=min(32,length(Tag(count).data));
fwrite(fid,[double(Tag(count).data(1:nChar)) zeros(1,32-nChar)],'uint8');
elseif Tag(count).type==10; % CString
fwrite(fid,length(Tag(count).data),'int32');
fwrite(fid,double(Tag(count).data),'uint8');
elseif Tag(count).type==11; % Cstring list.
nList=size(Tag(count).data,1);
fwrite(fid,nList,'int32');
for k=1:nList
% Do not force termination of strings with nulls (char(0))
Cstring=[deblank(Tag(count).data(k,:))];
fwrite(fid,length(Cstring),'int32');
fwrite(fid,double(Cstring),'uint8');
end
clear k CString nList;
elseif Tag(count).type==12; % CStr32 list.
nList=size(Tag(count).data,1); %size(data)=[nList 32]
fwrite(fid,nList,'int32');
% Do not force termination of strings with nulls (char(0))
for k=1:nList
strng=deblank(Tag(count).data(k,:));
nChar=min(32,length(strng));
Tag(count).data(k,:)=[strng(1:nChar) char(zeros(1,32-nChar))];
end
fwrite(fid,double(Tag(count).data)','uint8');
clear k strng nChar nList;
elseif Tag(count).type==13; % SensorClass list.
fwrite(fid,length(Tag(count).data),'int32');
fwrite(fid,Tag(count).data,'int32')
elseif Tag(count).type==14 % long integer
fwrite(fid,Tag(count).data,'int32');
elseif Tag(count).type==15 % unsigned longinteger
fwrite(fid,Tag(count).data,'uint32');
elseif Tag(count).type==16 % unsigned integer
fwrite(fid,Tag(count).data,'uint32');
elseif Tag(count).type==17 % Boolean
if ~any(Tag(count).data==[0 1])
fprintf('writeCPersist: tagname=%s type=%d value=%d? (Must =0 or 1)\n',...
tagname,type,Tag(count).data);
Tag(count).data=(Tag(count).data~=0);
fprintf(' Set value=%d.\n',Tag(count).data);
end
fwrite(fid,Tag(count).data,'int32');
else
fprintf('writeCPersist: Tag(%d) name=%s type=%d\n',count,Tag(count).name,Tag(count).type);
fprintf('\t\t UNRECOGNIZED type.\n');
fclose(fid);
break;
end
end % Loop over tags
fclose(fid);
% EOF_count should be zero at the end of the file
if EOFcount~=0;
fprintf('write_CPerist: EOFcount=%d Stop strings do not balance start strings.\n',...
EOFcount);
fprintf(' Start string=%s Stop string=%s\n',startString,EOFstring);
end
return
%%%%%%%% End of writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
getCTFBalanceCoefs.m
|
.m
|
antx-master/xspm8/external/ctf/getCTFBalanceCoefs.m
| 20,490 |
utf_8
|
2c434fcbdb53fbc50ee3fbda72e98883
|
function [alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=...
getCTFBalanceCoefs(ds,balanceType,unit);
% Reads balance coefficients for SQUID data in phi0's, and converts to coefficients
% for data in physical units.
% Input : ds : (1) ds structure from readCTFds
% balanceType : 'NONE' : No balancing
% 'G1BR' : 1st order balancing
% 'G2BR' : 2nd order balancing
% 'G3BR' : 3rd order balancing
% 'G3AR' : 3rd order balancing + adaptive
% If only MEG balance table is requested, size(balanceType)=[1 5]
% If Gref balance table is requested also, size(balanceType)=[2 4]
% unit: Type of units. Option: 'fT','T','phi0','int'.
% If unit is not entered, of unit=[], the default is unit='fT'.
% Outputs :
% alphaMEG,MEGindex,MEGbalanceindex : MEG balancing coefficients for data in fT or T.
% Suppose data array returned by getTrial2 has size(data)=[npt nchan].
% nMEG = number of MEG channels in the data set.
% MEG channels have sensorTypeIndex==5.
%
% MEGindex = list of MEG channels referred to the channel numbering in
% the complete dataset (i.e. it is not referred to only the list of
% SQUID sensors).
% by looking for sensors with ds.res4.senres.sensorTypeIndex==5
% size(MEGindex)=[1 nMEG]
% MEG data = data(:,MEGindex)
% MEGbalanceindex = list of reference channels for MEG balancing.
% size(MEGbalanceindex)=[1 nRef]
% Reference data for MEG balancing = data(:,MEGbalanceindex)
% alphaMEG = balance coefficients. size(alphaMEG)=[nRef nMEG]
%
% Balancing MEG data :
% - Start with data AFTER converting to physical units.
% (I.e. SQUID data must be in fT or T.)
% - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,MEGbalanceindex)*alphaMEG
% If user specifies balanceType=[], ' ' or 'none', then getCTFBalanceCoefs returns
% alphaMEG=zeros(0,nMEG), MEGindex=list of MEG sensor channels,
% MEGbalanceindex=[], alphaGref=zeros(0,nGef), Grefindex=list of Gref channels
% and Gbalanceindex=[];
% alphaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients.
% These output arrays are optional. If the calling statement includes
% them, then this program extracts a table of balance coefficients for
% the reference gradiometers from the G1BR table in the coefficient files.
% nGref = no. of reference gradiometers channels in the data set
% (sensorTypeIndex=1)
% Grefindex = list of reference channels. size(Grefindex)=[1 nGref]
% Gradient reference data = data(:,Grefindex)
% Gbalanceindex = list of channels for balancing reference
% gradiometers. size(Gbalanceindex)=[1 nGbalcoef]
% Balancing reference data = data(:,Gbalanceindex)
% alphaGref = balance coefficients for ref. grads.
% size(alphaGref)=[nGbalcoef nGref]
%
% Balancing ref. gradiometer data :
% - Use data AFTER converting to physical units. (I.e. data in fT or T.)
% balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*alphaGref
% Calls function getRawCTFBalanceCoefs (included in this listing).
if nargout==0 & nargin==0
fprintf(['\ngetCTFBalanceCoefs: Version 1.1 17 April 2007 ',...
'Reads balance coefficients from ds.res4.scrr.\n\n',...
'\tMEG balancing : [alphaMEG,MEGindex,MEGbalanceindex]=',...
'getCTFBalanceCoefs(ds,balanceType,unit);\n\n',...
'\tMEG & Gref balancing : [alphaMEG,MEGindex,MEGbalanceindex,',...
'alphaGref,Grefindex,Gbalanceindex]=\n',...
'\t ',...
'getCTFBalanceCoefs(ds,balanceType,unit);\n\n']);
return
end
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR');
balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs.
physical_options=strvcat('fT','T');
raw_options=strvcat('phi0','int');
unit_options=strvcat(physical_options,raw_options);
default_unit='fT';
% Specify outputs in case of an early return due to an error.
MEGindex=[];
Grefindex=[];
alphaMEG=[];
MEGbalanceindex=[];
alphaGref=[];
Gbalanceindex=[];
% Check that the inputs are sensible.
if nargin<2
fprintf(['\ngetCTFBalanceCoefs: Only %d input arguments? ',...
'Must specify at least ds and balanceType.\n\n'],nargin);
return
elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType)
fprintf('\ngetCTFBalanceCoefs: Wrong argument types or sizes.\n\n');
whos ds balanceType
return
elseif ~isfield(ds,'res4')
fprintf('\ngetCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n');
ds
return
elseif size(balanceType,1)>2
fprintf('\ngetCTFBalanceCoefs: size(balanceType)=[');fprintf(' %d',size(balanceType));...
fprintf('] Must be[1 4] or [2 4].\n\n');
return
end
% Must have 3 or 6 output arguments. Set balanceType(2,:)='NONE' if necessary.
if ~any(nargout==[3 6]);
fprintf(['\ngetCTFBalanceCoefs: Called with %d output arguments. ',...
'Must be 3 or 6.\n\n'],nargout);
return
elseif (nargout==3 & size(balanceType,1)>1) | (nargout==6 & size(balanceType,1)==1)
balanceType=strvcat(deblank(balanceType(1,:)),'NONE');
end
% At this point, size(balanceType,1)=2.
% Check that balanceType has allowed values
for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs
if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:)))
fprintf('\ngetCTFBalanceCoefs: balanceType(%d,:)=%s Not an allowed option.\n\n',...
k,balanceType(k,:));
return
end
end
% Check the data units, convert to lower case and flag incorrect unit specification
if ~exist('unit');
unit=default_unit;
elseif isempty(unit);
unit=default_unit;
elseif ~ischar(unit)
fprintf('\ngetCTFBalanceCoefs: Input unit has the wrong type: class(unit)=%s\n\n',...
class(unit));
return
end
unit=lower(unit);
if isempty(strmatch(unit,lower(strvcat(physical_options,raw_options))))
fprintf('\ngetCTFBalanceCoefs: unit=%s. Must be one of ',unit);
for k=1:size(unit_options,1);fprintf(' %s,',deblank(unit_options(k,:)));end;
fprintf('\n\n');
return
end
physical=~isempty(strmatch(unit,lower(physical_options)));
balanceType=upper(deblank(balanceType));
[betaMEG,MEGindex,MEGbalanceindex,betaGref,Grefindex,Gbalanceindex]=...
getRawCTFBalanceCoefs(ds,balanceType);
% No balancing is requested, just return lists of MEGindex and Grefindex.
if isempty(MEGbalanceindex)
alphaMEG=zeros(0,length(MEGindex));
MEGbalanceindex=[]; % force size=[0 0]
end
if isempty(Gbalanceindex)
alphaGref=zeros(0,length(Grefindex));
Gbalanceindex=[]; % force size=[0 0]
end
if isempty(MEGbalanceindex) & isempty(Gbalanceindex)
return
end
% betaMEG and betaGref are the balance coefficients when signals are in phi0's.
% Convert to balance coefficients when signals are in physical units (T or fT).
% invproperGain is introduced to take care of situations where bad channels
% are labelled by setting their gain to zero.
if physical
properGain=zeros(1,ds.res4.no_channels);
invproperGain=zeros(1,ds.res4.no_channels);
for k=1:ds.res4.no_channels
if any(ds.res4.senres(k).sensorTypeIndex==[0 1 5:7]) % SQUIDs only
properGain(k)=ds.res4.senres(k).properGain; % properGain = phi0/T
if properGain(k)~=0
invproperGain(k)=1/properGain(k);
end
end
end
end
if ~isempty(MEGbalanceindex)
if physical
alphaMEG=betaMEG.*(properGain(MEGbalanceindex)'*invproperGain(MEGindex));
else
alphaMEG=betaMEG;
end
end
if ~isempty(Gbalanceindex)
if physical
alphaGref=betaGref.*(properGain(Gbalanceindex)'*invproperGain(Grefindex));
else
alphaGref=betaGref;
end
end
return
%%%%%%%%%%% End of getBalanceCoef %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Function getRawCTFBalanceCoefs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [betaMEG,MEGindex,Refindex,betaGref,Grefindex,Gbalanceindex]=...
getRawCTFBalanceCoefs(ds,balanceType);
% getRawCTFBalanceCoefs. Extracts raw-data (i.e. integer data) gradiometer balancing
% coefficients from structure array ds.res4.scrr (ds is produced
% by readCTFds).
% Date : 24 OCt 2006
% Author : Harold Wilson
% Inputs : ds : Structure returned by readCTFds.
% balanceType : 'NONE' : No balancing
% 'G1BR' : 1st order balancing
% 'G2BR' : 2nd order balancing
% 'G3BR' : 3rd order balancing
% 'G3AR' : 3rd order balancing + adaptive
% If only MEG balance table is requested, size(balanceType)=[1 4]
% If Gref balance table is requested also, size(balanceType)=[2 4]
% If balancing 'NONE' is specified, getRawCTFBalanceCoefs returns lists MEGindex and
% Grefindex, and sets Refindex=[], Gbalanceindex=[].
% The reference gradiometers have only G1BR balancing coefficients.
% Outputs :
% betaMEG,MEGindex,Refindex : MEG balancing coefficients.
% Suppose data array returned by getCTFdata has size(data)=[npt nchan].
% nMEG = number of MEG channels in the data set.
% MEG channels have sensorTypeIndex==5.
%
% MEGindex = list of MEG channels in the data set. It is assembled
% by looking for sensors with ds.res4.senres.sensorTypeIndex==5
% size(MEGindex)=[1 nMEG]
% MEG data = data(:,MEGindex)
% Refindex = list of reference channels for MEG balancing.
% size(Refindex)=[1 nRef]
% Reference data = data(:,Refindex)
% betaMEG = balance coefficients. size(betaMEG)=[nRef nMEG]
%
% Balancing MEG data :
% - Start with data BEFORE converting to physical units.
% (I.e. SQUID data must be in phi0's or raw integers.)
% - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,Refindex)*betaMEG
% If user specifies balanceType=[] or ' ', then getRawCTFBalanceCoefs returns
% betaMEG=zeros(1,nMEG),Refindex=3 and nRef=1;
% betaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients.
% These output arrays are optional. If the calling statement includes
% them, then this program extracts a table of balance coefficients for
% the reference gradiometers from the G1BR table in the coefficient files.
% nGref = no. of reference gradiometers channels in the data set
% (sensorTypeIndex=1)
% Grefindex = list of reference channels. size(Grefindex)=[1 nGref]
% Gradient reference data = data(:,Grefindex)
% Gbalanceindex = list of channels for balancing reference
% gradiometers. size(Gbalanceindex)=[1 nGbalcoef]
% Balancing reference data = data(:,Gbalanceindex)
% betaGref = balance coefficients for ref. grads.
% size(betaGref)=[nGbalcoef nGref]
%
% Balancing ref. gradiometer data :
% balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*betaGref
% No function calls.
missingMEGMessage=0;
missingGrefMessage=0;
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR');
balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs.
common_mode_only=0;
Brefindex=[]; % Index list of reference magnetometers in the data arrays
Grefindex=[]; % Index list of reference gradiometers in the data arrays
MEGindex=[]; % Index list of MEG sensors in the data arrays
Gbalanceindex=[]; % Index list of sensors used as references to balance the reference
% gradiometers
Refindex=[]; % Index list of sensors used to balance the MEG sensors
betaMEG=[];
betaGref=[];
% Check that the inputs are sensible.
if nargin<2
fprintf(['\ngetRawCTFBalanceCoefs: Only %d input arguments? ',...
'Must specify at least ds and balance.\n\n'],nargin);
return
elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType)
fprintf('\ngetRawCTFBalanceCoefs: Wrong argument types or sizes.\n\n');
whos ds balanceType
return
elseif ~isfield(ds,'res4')
fprintf('\ngetRawCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n');
ds
return
end
% Check that the output list is OK.
if nargout~=3 & nargout~=6
fprintf('\ngetRawCTFBalanceCoefs : Call specifies %d output arguments.\n',nargout);
fprintf('\t\tMust have 3 output arguments (MEG balance coefficients)\n');
fprintf('\t\tor 6 output arguments (reference gradiometer balancing also).\n\n');
return
elseif nargout==3
if size(balanceType,1)>1;balanceType=balanceType(1,:);end
else
if size(balanceType,1)==1;balanceType=strvcat(balanceType,'NONE');end
end
% Check that balanceType has allowed values
for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs
if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:)))
fprintf('\ngetRawCTFBalanceCoefs: balance(%d,:)=%s Not an allowed option.\n\n',...
k,balanceType(k,:));
return
end
end
% Make lists of reference magnetometers, reference gradiometers and MEG sensors.
for q=1:length(ds.res4.senres)
if ds.res4.senres(q).sensorTypeIndex==0
Brefindex=[Brefindex q];
elseif ds.res4.senres(q).sensorTypeIndex==1
Grefindex=[Grefindex q];
elseif ds.res4.senres(q).sensorTypeIndex==5 % Allow other MEG sensors?
MEGindex=[MEGindex q];
end
end
nBref=length(Brefindex); % Don't currently use Brefindex or nBref
nGref=length(Grefindex);
nMEG=length(MEGindex);
nGbalcoef=0; % Set to zero until we know the number by examining ds.res4.scrr
if nargout==6 & strcmp(balanceType(2,:),'NONE')
Gbalanceindex=[];
betaGref=zeros(0,nGref);
elseif nargout==6 & ~strcmp(balanceType(2,:),'NONE')
m1=1; % Get coefficients for balancing the reference gradiometers.
mtot=size(ds.res4.scrr,2);
for n=1:nGref
Gname=strtok(ds.res4.chanNames(Grefindex(n),:),['- ',char(0)]);
nGchar=length(Gname);
for m=[m1:mtot 1:(m1-1)]
if strncmp(Gname,char(ds.res4.scrr(m).sensorName),nGchar) & ...
strcmp('G1BR',char(ds.res4.scrr(m).coefType));
if nGbalcoef<=0 % 1st match. Initialize table and get list of references
nGbalcoef=ds.res4.scrr(m).numcoefs;
betaGref=zeros(nGbalcoef,nGref);
% Assemble index array for balancing the reference gradiometers
for q=1:nGbalcoef
Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]);
pRef=strmatch(Refname,ds.res4.chanNames);
if isempty(pRef)
fprintf(['getRawCTFBalanceCoefs : Sensor %s appears in ',...
'ds.res4.scrr, but not in ds.res4.chanNames\n'],Refname);
return
end
Gbalanceindex=[Gbalanceindex pRef];
end
end % end setup of balancing table for Ref. gradiometers
if ds.res4.scrr(m).numcoefs~=nGbalcoef
fprintf('\ngetRawCTFBalanceCoefs : %s has %d coefficients\n',...
ds.res4.chanNames(Grefindex(1),1:nGchar),nGbalcoef);
fprintf(' %s " %d " ????\n\n',...
ds.res4.chanNames(Grefindex(n),1:nGchar),ds.res4.scrr(m).numcoefs);
betaGref=[]; % Force useless output.
return
end
betaGref(:,n)=reshape(ds.res4.scrr(m).coefs(1:nGbalcoef),nGbalcoef,1);
m1=m+1;
break; % Break out of m-loop. Go to nect n value.
end
if (m==m1-1 & m1>1) | (m==mtot & m1==1)
if missingGrefMessage==0
if strncmp(balanceType(2,:), balanceOptions(5,:), 4)
% Avoid warning for all sensors for adaptive coefficients.
fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for reference sensors.\n',...
balanceType(2,:));
else
fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',...
' for sensor(s)'],balanceType(2,:));
fprintf('\n\t\t\t\t');
end
end
missingGrefMessage=missingGrefMessage+1;
if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4)
if missingGrefMessage==10*round(missingGrefMessage/10)
fprintf('\n\t\t\t\t');
end
fprintf(' %s',Gname);
end
betaGRef(:,n)=zeros(nGbalcoef,1);
return
end
end % End loop over m (searching for scrr(m).sensorName)
end % End loop over n (list of reference gradiometers)
end % End of section getting coefficients to balance the reference gradiometers.
if missingGrefMessage>0;fprintf('\n');end
if strcmp(balanceType(1,:),'NONE')
Refindex=[];
betaMEG=zeros(0,nMEG);
return
end
% Get balance coefficients for the MEG sensors
nRef=0;
% Pointers for search through ds.res4.scrr structure array.
m1=1;
mtot=size(ds.res4.scrr,2);
for n=1:nMEG
MEGname=strtok(ds.res4.chanNames(MEGindex(n),:),['- ',char(0)]);
nChar=length(MEGname);
for m=[m1:mtot 1:(m1-1)]
if strncmp(MEGname,char(ds.res4.scrr(m).sensorName),nChar) & ...
strcmp(balanceType(1,:),char(ds.res4.scrr(m).coefType));
if nRef<=0
nRef=ds.res4.scrr(m).numcoefs;
betaMEG=zeros(nRef,nMEG);
for q=1:nRef % Assemble index array for balancing the MEG sensors
Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]);
pRef=strmatch(Refname,ds.res4.chanNames);
if isempty(pRef)
fprintf(['\ngetRawCTFBalanceCoefs : Sensor %s appears in ',...
'ds.res4.scrr, but not in ds.res4.chanNames\n\n'],Refname);
return
end
Refindex=[Refindex pRef];
end
end % end setup of balancing table for MEG sensors
if ds.res4.scrr(m).numcoefs~=nRef
fprintf('\ngetRawCTFBalanceCoefs : %s - %s has %d coefficients\n',...
ds.res4.chanNames(MEGindex(1),1:nChar),balanceType,nRef);
fprintf(' %s - %s " %d " ????\n\n',...
ds.res4.chanNames(MEGindex(n),1:nChar),balanceType,...
ds.res4.scrr(m).numcoefs);
betaMEG=[]; % An output that will force an error in the calling program.
return
end
betaMEG(:,n)=reshape(ds.res4.scrr(m).coefs(1:nRef),nRef,1);
m1=m+1;
break;
end
if (m==m1-1 & m1>1) | (m==mtot & m1==1)
if missingMEGMessage==0
if strncmp(balanceType(2,:), balanceOptions(5,:), 4)
% Avoid warning for all sensors for adaptive coefficients.
fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for sensors.\n',...
balanceType(2,:));
else
fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',...
' for sensor(s)'],balanceType(1,:));
fprintf('\n\t\t\t\t');
end
end
missingMEGMessage=missingMEGMessage+1;
if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4)
if missingMEGMessage==10*round(missingMEGMessage/10)
fprintf('\n\t\t\t\t');
end
fprintf(' %s',MEGname);
end
betaMEG(:,n)=zeros(nRef,1);
end
end % End of loop over m (ds.res4.scrr table)
end % End of loop over MEG sensors
if missingMEGMessage>0;fprintf('\n');end
if common_mode_only
if size(betaMEG,1)>3 & nMEG>0
betaMEG=betaMEG(1:3,:);
Refindex=Refindex(1:3);
end
if size(betaGref,1)>3 & nGref>0
betaGref=betaGref(1:3,:);
Gbalanceindex=Gbalanceindex(1:3);
end
end
return
|
github
|
philippboehmsturm/antx-master
|
writeCTFds.m
|
.m
|
antx-master/xspm8/external/ctf/writeCTFds.m
| 68,946 |
utf_8
|
96615f4833d69490d5b3e47f6f86c538
|
function ds=writeCTFds(datasetname,ds,data,unit);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This program creates datasets that can be analyzed by CTF software. %
% %
% Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. %
% %
% Please do not redistribute it without permission from VSM MedTech Ltd. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Author : Harold Wilson
% Version 1.3 5 October 2007 Spelling errors in some variables corrected.
% Version 1.2 24 April 2007 Modified to write both MEG and fMEG .hc files.
% writeCTFds.m Version 1.1 Prepares a CTF-format data set. MATLAB to CTF conversion.
% Adds record of filter changes to hist and newds files.
% Adds no-clinical-use messages.
% Creates multiple meg4 files when the total size of the data array
% >536870910 elements.
% Operation :
% 1. User reads a data set using readCTFds and getTrial2.
% size(data)= [SAMPLES, CHANNELS, TRIALS].
% 2. After working on data in MATLAB, user adjusts ds structure to reflect changes.
% (writeCTFds will adjust the number of channels, channel names and trial structure.)
% 3. This program then creates a new CTF data set.
% datasetname must include the complete path description.
% If a data set with name datasetname already exists, writeCTFds will issue an error message.
% The new directory contains files for each field of structure ds. If the field is
% missing no file is created. If the field is empty, an empty file is created.
% Files default.* are not created by writeCTFds.
% 4. The following fields of structure ds.res4 are modified based on the size of array data :
% no_samples
% no_channels
% no_trials.
% If size(ds.res4.chanNames,1)<no_channels, additional channel names are created
% as required. The additional channels are called MXT%%%. It is assumed that
% there will be <1000 new channels.
% Inputs : datasetname : Output dataset including path. Extension '.ds' is optional.
% ds : Structure produced by readCTFds.
% data : MEG data array. size(data)=[no_samples no_channels no_trials]
% Array data may be single or double.
% unit : Determines the unit of the SQUID and EEG signals:
% If unit is missing or unit==[], the unit is set to 'fT'.
% 'ft' or 'fT' : Convert to fT (MEG), uV (EEG)
% 't' or 'T' : Convert to T (MEG), V (EEG)
% 'phi0' : Convert to phi0 (MEG), uV (EEG)
% 'int': Read plain integers from *.meg4-file
% Outputs : - ds : The ds structure of the output data set.
% - datasetout : the name of the output data set.
% - A data set. The .hz and .hz2 subdirectories are not included.
% Function calls
% Included in this listing:
% - check_senres: Does simple checks on the fields of the senres table.
% - writeHc: Creates the new .hc file
% - checkMrk: Checks structure ds.mrk to see if it is valid marker set.
% - writeEEG: Creates the new .EEG file.
% - writeBadSegments: Creates the new bad.segments file.
% - writeClassFile: Creates the new ClassFile.cls file.
% - writeVirtualChannels: Creates the new VirtualChannels file.
% - updateDescriptors: Adds non-clinical-use and creation software messages to
% infods, res4, newds and hist fields of ds.
% - updateHLC: Adds head-coil movement information to infods.
% - updateDateTime : Resets dattime fields of res4 and infods.
% - updateBandwidth: Resets bandwidth of newds and infods. Adds res4 filter
% description to ds.hist.
% - getArrayField : Extracts one field of a structure array to make it easier to
% manipulate.
% - writeMarkerFile: Creates the new MarkerFile.mrk file.
% - writeCPersist: Creates the new .acq and .infods files.
% Other calls:
% - writeRes4: Writes the new .res4 file.
% Output files are opened with 'w' permission and 'ieee-be' machine format in order
% to be compatible with the Linux acquisition and analysis software. Do not open files
% with 'wt' permission because this will add an extra char(13) byte at the end of each
% line of text.
persistent printWarning bandwidthMessage
delim=filesep;
if nargin==0 & nargout==0 % Print a version number
fprintf(['\twriteCTFds: Version 1.3 5 October 2007 ',...
'Creates v4.1 and v4.2 CTF data sets.\n',...
'\tCall: ds=writeCTFds(datasetname,ds,data,unit);\n',...
'\t\tdatasetname = Name of the new dataset including the path.\n',...
'\t\tds = Structure describing the new dataset (ds.hc must be v1.2 format).\n',...
'\t\tdata = data that will be written to the new dataset .meg4 file.\n',...
'\t\tunit = physical units of the data.\n\n']);
return
end
% Allowed 8-byte headers for res4 and meg4 files.
res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]);
meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]);
maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software)
MAX_COILS=8; % Parameter that determines the size of the ds.res.senres structure.
lenSensorName=32; % Channel names must be 32 characters
printDefaultBandwidthMessage=0; % Print a message about default bandwidth?
default_flp=0.25; % Default is flp=0.25*ds.res4.sample_rate
clinicalUseMessage='NOT FOR CLINICAL USE';
creatorSoftware='writeCTFds'; % Added to .infods file
meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes.
DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006
if ~exist('clinicalUseMessage');
clinicalUseMessage=char([]);
end
% Check inputs
if nargin<3
fprintf(['\nwriteCTFds: Must supply inputs datasetname,ds,data. ',...
'Only %d input arguments are present.\n\n'],nargin);
ds=-1; % Force an error in the calling program.
return
end
% Check input argument unit. Convert unit to lower case.
if exist('unit')~=1
unit='ft'; % default
elseif isempty(unit)
unit='ft'; % default
elseif ischar(unit)
unit=lower(unit);
if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0')
fprintf(['\nwriteCTFds : unit=%s Not a valid option. Must be ',...
'''fT'', ''T'', ''phi0'' or ''int''\n\n'],unit);
ds=-1; % Force an error in the calling program.
return
end
end
% Check argument type
if ~isstruct(ds) | ~isnumeric(data) | ~ischar(unit) | ~ischar(datasetname)
fprintf('\nwriteCTFds: Some of the inputs are the wrong type.\n');
whos datasetname ds data unit;
ds=-1;
return
elseif ~isfield(ds,'res4') | ~isfield(ds,'meg4')
fprintf('\nwriteCTFds: Fields res4 and meg4 must be present in structure ds.\n\n');
ds % List the fields of structure ds.
ds=-1; % Force an error in the calling program.
return
end
% Refuse to write a data set with balanced reference gradiometers.
balancedGref=0;
for k=1:ds.res4.no_channels
balancedGref=(ds.res4.senres(k).sensorTypeIndex==1 & ds.res4.senres(k).grad_order_no~=0);
end
if balancedGref
fprintf('\nwriteCTFds: ds.res4.senres indicates balanced reference gradiometers.\n\n');
ds=-1; % Force an error in the calling program.
return
end
clear k balancedGref;
% Separate datasetname into a path and the baseName
datasetname=deblank(datasetname);
ksep=max([0 findstr(datasetname,delim)]);
baseName=datasetname((ksep+1):length(datasetname));
path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]).
% Remove the last .ds from baseName.
kdot=max(findstr(baseName,'.ds'));
if kdot==(length(baseName)-2)
baseName=baseName(1:(max(kdot)-1));
else
datasetname=[datasetname,'.ds'];
end
clear ksep kdot;
% Save the name already in structure ds, and change to the new datset name.
if isfield(ds,'baseName')
olddatasetname=[ds.baseName,'.ds'];
if isfield(ds, 'path')
olddatasetname=[ds.path,olddatasetname];
end
else
olddatasetname=' None ';
end
ds.path=path;
ds.baseName=baseName;
% Does the dataset already exist?
if exist(datasetname)==7
fprintf('\nwriteCTFds: Dataset %s already exists. Use a different name.\n\n',...
datasetname);
ds=-1; % Force an error in the calling program.
return
end
if size(ds.res4.chanNames,2)~=lenSensorName
fprintf(['\nwriteCTFds : size(ds.res4.chanNames)=[%d %d] ? Must ',...
'have %d-character channel names.\n\n'],size(ds.res4.chanNames),lenSensorName);
ds=-1;
return
end
% Check that the channel names have a sensor-file identification extensions.
% If it is missing, print a warning message.
% Sensor type indices : SQUIDs (0:7), ADCs (10), DACs(14), Clock (17), HLC (13,28,29)
% See Document CTF MEG File Formats (PN 900-0088), RES4 File Format/
for index=[0:7 10 13 14 17 28 29]
for k=find([ds.res4.senres.sensorTypeIndex]==index);
if isempty(strfind(ds.res4.chanNames(k,:),'-'))
fprintf(['writeCTFds: Channel %3d %s No sensor-file identification.',...
' (''-xxxx'' appended to channel name).\n',...
'\t\tSome CTF software may not work with these channel names.\n'],...
k,deblank(ds.res4.chanNames(k,:)));
break;
end
end
if isempty(strfind(ds.res4.chanNames(k,:),'-'));break;end
end
clear index k chanName;
% Update the data description in the ds.res4 structure.
[nSample, nChan, trials]=size(data);
% Update ds.res4 fields to match the size of array data.
ds.res4.no_trials=trials;
ds.res4.no_channels=nChan;
ds.res4.no_samples=nSample;
ds.res4.epoch_time=nSample*trials/ds.res4.sample_rate;
% Check if channels have been added or removed from array data.
[no_chanNames len_chanNames]=size(ds.res4.chanNames);
if no_chanNames<nChan
% Assume that new channel are at the end of the data set. Add a fake extension.
for kx=1:(nChan-no_chanNames)
ds.res4.chanNames=...
strvcat(ds.res4.chanNames,['MXT' num2str(kx,'%3.3d') '-0001' char(0)]);
end
fprintf('\tAdded %d SQUID channels to the end of ds.res4.chanNames table.\n',...
nChan-no_chanNames);
elseif no_chanNames>nChan
fprintf(['\nlength(chanNames)=%d, but only %d channels of data. ',...
'writeCTFds cannot tell which channel names to remove.\n\n'],no_chanNames,nChan);
ds=-1;
return
end
clear no_chanNames len_chanNames;
% The senres table may have been changed, especially if channels are added or removed.
% Check structure senres, print error messages, and possibly fix the errors.
[ds.res4.senres,status]=check_senres(ds.res4.senres,ds.res4.no_channels);
if status<0;ds=-1;return;end
clear status;
% Check that ds.res4.numcoef is the size of structure array ds.res4.scrr.
if isfield(ds.res4,'scrr')
if ~isequal(size(ds.res4.scrr,2),ds.res4.numcoef)
fprintf('Error in ds.res4: ds.res4.numcoef=%d, but size(ds.res4.scrr)=[',...
ds.res4.numcoef);
fprintf(' %d',size(ds.res4.scrr));fprintf('] ?\n');
return
end
elseif ds.res4.numcoef~=0
fprintf(['Error in ds.res4: ds.res4.numcoef=%d,',...
' but scrr is not a field of ds.res4\n'],ds.res4.numcoef);
return
end
% Before converting data to integers, save HLC channels for motion analysis in function
% make_new_infods. Pass HLCdata to function make_new_infods
if isempty(strmatch('HLC',ds.res4.chanNames))
HLCdata=[];
else
% Make a list of head-coil channels
coil=0;
HLClist=[];
while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames))
coil=coil+1;
for k=1:3
HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)];
end
end
HLCdata=reshape(double(data(:,HLClist,:)),ds.res4.no_samples,3,coil,ds.res4.no_trials);
clear coil k HLClist;
end
% Convert data to integers because CTF data sets are stored as raw numbers and
% not as physical qunatities. The res4 file contains the calibrations for
% converting back to physical units. Array data may be single precision, so
% convert to double before doing any adjustments to the data.
% Already checked that unit is valid.
if strcmp(unit,'int')
data=reshape(data,nSample,nChan*trials);
for k=1:nChan*trials
if strcmp(class(data),'single')
data(:,k)=single(round(double(data(:,k))));
else
data(:,k)=round(double(data(:,k)));
end
end
data=reshape(data,nSample,nChan,trials);
clear k;
else
for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T
SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]);
EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]);
if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0'))
alphaG=1e-6;
elseif SQUIDtype & strcmp(unit,'ft')
alphaG=1e-15;
elseif SQUIDtype & strcmp(unit,'phi0')
alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain);
else
alphaG=1;
end
% Convert from physical units to integers using the gains in the senres table.
for kt=1:trials
buff=round(double(data(:,chan,kt))*(alphaG*...
(ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain)));
if strcmp(class(data),'single')
data(:,chan,kt)=single(buff);
else
data(:,chan,kt)=buff;
end
end
end
clear chan alphaG SQUIDtype EEGtype buff kt;
end
% Create the output dataset
[status,msg]=mkdir(path,[baseName '.ds']);
if status==0 | ~isempty(msg)
fprintf('\nwriteCTFds: Failed to create directory.\n');
fprintf(' [status,msg]=mkdir(%s)\n',datasetname);
fprintf(' returns status=%d, msg=%s',status,msg);fprintf('\n\n');
ds=-1;
return
end
clear msg status;
% Write the data file (meg4 file). Check ds.meg4.header and make sure that
% the output .meg4 file has an acceptable header.
headerMessage=1;
if ~isfield(ds.meg4,'header'); % If ds.meg4.header is missing, add it.
nChar=length(deblank(meg4_headers(1,:)));
ds.meg4.header=[meg4_headers(1,1:min(7,nChar)) char(zeros(1,7-nChar))];
elseif isempty(strmatch(ds.meg4.header(1:7),meg4_headers(:,1:7),'exact'))
ds.meg4.header=meg4_headers(1,1:7);
else
headerMessage=0;
end
if headerMessage;
fprintf('writeCTFds: Set ds.meg4.header=%s\n',ds.meg4.header);
end
clear headerMessage;
if isempty(printWarning)
fprintf(['\nwriteCTFds: The data you are writing have been processed by software not\n',...
'\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',...
'\tfor clinical applications. These data should not be later employed for clinical\n',...
'\tand/or diagnostic purposes.\n\n']);
printWarning=1;
end
% Write the meg4 file(s). If there are more than maxMEG4Size-8 bytes, then additional meg4
% files will be created.
% Convert data to a 1-D array
ndata=prod(size(data));
data=reshape(data,ndata,1);
ptsPerTrial=nSample*nChan;
maxPtsPerFile=ptsPerTrial*floor((maxMEG4Size-8)/(4*ptsPerTrial));
pt=0; % Last point written to the output file(s).
while pt<ndata
endPt=pt+min(ndata-pt,maxPtsPerFile);
if pt==0
meg4Ext='.meg4';
else
meg4Ext=['.',int2str(floor(pt/maxPtsPerFile)),'_meg4'];
end
fidMeg4=fopen([path,baseName,'.ds',delim,baseName,meg4Ext],'w','ieee-be');
fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8');
while pt<endPt
pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is
fwrite(fidMeg4,double(data((pt+1):pt1)),'int32'); % is single and write in short
pt=pt1; % pieces.
end
fclose(fidMeg4);
end
% Update the .meg4 part of structure ds.
ds.meg4.fileSize=4*ndata+8*(1+floor(ndata/maxPtsPerFile));
clear data pt pt1 ndata fidMeg4 ptsPerTrial maxPtsPerFile meg4Ext;
% Add dataset names to .hist
if ~isfield(ds,'hist');ds.hist=char([]);end
ds.hist=[ds.hist char(10) char(10) datestr(now) ' :' char(10) ...
' Read into MATLAB as data set ' olddatasetname char(10) ...
' Rewritten by writeCTFds as data set ' datasetname char(10)];
% If infods doesn't exist or is empty create it.
if ~isfield(ds,'infods');ds.infods=[];end
if isempty(ds.infods)
ds.infods=make_dummy_infods(isfield(ds,'hc'),~isempty(HLCdata),ds.res4.sample_rate);
end
% Update text fields of res4,infods, newds and hist.
ds=updateDescriptors(ds,clinicalUseMessage,creatorSoftware);
% Add HLC data to infods
ds.infods=updateHLC(ds.infods,HLCdata);
% Analyze structure array ds.res4.filters to make text info for .hist file and
% bandwidth parameters for .newds file.
fhp=0; % High-pass cutoff assuming no filters
flp=default_flp*ds.res4.sample_rate; % Assumed lowpass cutoff. SHOULD THIS BE CHANGED?
if isempty(bandwidthMessage) & printDefaultBandwidthMessage
fprintf('writeCTFds: Lowpass filter set to flp=%0.2f*sample_rate\n',default_flp);
bandwidthMessage=1;
end
ds=updateBandwidth(ds,fhp,flp);
% Update date/time fields of infods and res4
ds=updateDateTime(ds);
% Create the .res4 file in the output dataset.
ds.res4=writeRes4([path,baseName,'.ds',delim,baseName,'.res4'],ds.res4,MAX_COILS);
if ds.res4.numcoef<0
fprintf('\nwriteCTFds: writeRes4 returned ds.res4.numcoef=%d (<0??)\n\n',...
ds.res4.numcoef);
% Kill the output dataset.
rmdir([path,baseName,'.ds'],'s');
ds=-1;
return
end
% Create .hist file
histfile=[path,baseName,'.ds',delim,baseName,'.hist'];
fid=fopen(histfile,'w');
fwrite(fid,ds.hist,'uint8');
fclose(fid);
% New .newds file
if isfield(ds,'newds')
fid=fopen([path,baseName,'.ds',delim,baseName,'.newds'],'w');
fwrite(fid,ds.newds,'uint8');
fclose(fid);
end
% New infods file.
if isfield(ds,'infods')
writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods);
end
% new hc file
if isfield(ds,'hc')
ds.hc=writeHc([path,baseName,'.ds',delim,baseName,'.hc'],ds.hc,HLCdata(:,:,1));
end
clear HLCdata;
% MarkerFile.mrk
if checkMrk(ds)
writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],ds.mrk);
end
% .EEG
if isfield(ds,'EEG')
writeEEG([path,baseName,'.ds',delim,baseName,'.EEG'],ds.EEG);
end
% .acq
if isfield(ds,'acq');
% Check that ds.acq has the correct fields
if isfield(ds.acq,'name') & isfield(ds.acq,'type') & isfield(ds.acq,'data')
acqFilename=[path,baseName,'.ds',delim,baseName,'.acq'];
writeCPersist(acqFilename,ds.acq);
end
end
% bad.segments file
if isfield(ds,'badSegments')
writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,...
ds.res4.no_trials,ds.res4.no_samples/ds.res4.sample_rate);
end
% BadChannels
if isfield(ds,'BadChannels');
if ischar(ds.BadChannels) & ~isempty(ds.BadChannels)
fid=fopen([path,baseName,'.ds',delim,'BadChannels'],'w','ieee-be');
for k=1:size(ds.BadChannels,1)
fprintf(fid,'%s\n',deblank(ds.BadChannels(k,:)));
end
fclose(fid);
end
end
% ClassFile
if check_cls(ds)
writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],ds.TrialClass);
end
% VirtualChannels
if isfield(ds,'Virtual')
writeVirtualChannels([path,baseName,'.ds',delim,'VirtualChannels'],ds.Virtual);
end
% processing.cfg
if isfield(ds,'processing');
if ischar(ds.processing)
fid=fopen([datasetname,delim,'processing.cfg'],'w','ieee-be');
fwrite(fid,ds.processing,'uint8');
fclose(fid);
end
end
% Update the data set path and name
ds.path=path;
ds.baseName=baseName;
return
% *************** End of function writeCTFds ********************************************
% **************************************************************************************
% **************************************************************************************
% *************** Function check_senres **************************
function [senres,status]=check_senres(senres,numChan);
% A user may have augmented the senres table, so check that all the fields have the
% correct size. This will cause errors in programs that try to compute
% sensor response using the geometry in the senres table.
% Does "sanity" checks on the senres table. If there are obviously incorrect entries, it
% tries to fix them, and prints a message. If the senres table does not specify coil
% positions, orientations or areas, set them to zero, but give them the correct array
% size.
newChannelType=4; % Create the fake sensors as MEG magnetometers. This way offsets can be removed.
status=-1;
% Does the senres table have the correct no. of channels?
no_senres=length(senres);
if no_senres<numChan
% Add channels. Assume that they are gradiometers.
ioGain=1;
qGain=2^20;
gain=0.3;
properGain=1e15/(qGain*ioGain*gain); % sensor gain in phi0/fT
for kx=(no_senres+1):numChan
senres(kx)=struct(...
'sensorTypeIndex',newChannelType,'originalRunNum',0,'coilShape',0,...
'properGain',properGain,'qGain',qGain,'ioGain',ioGain,...
'ioOffset',0,'numCoils',1,...
'grad_order_no',0,...
'gain',gain,...
'pos0',zeros(3,1),'ori0',zeros(3,1),...
'area',0.1,'numturns',1,...
'pos',[0 0 21]','ori',zeros(3,1));
end
fprintf(['\tAdded %d SQUID channels to senres table. Nominal gain of each = ',...
'%8.4f fT/step\n'],numChan-no_senres,gain);
clear kx gain qGain ioGain properGain;
elseif no_senres>numChan
% Channels have been removed from the data set, but can't tell which elements of the
% senres table to remove.
fprintf(['length(senres)=%d, but only %d channels of data. writeCTFds can''t',...
' tell which channels to remove from senres table.\n'],no_senres,numChan);
return
end
no_senres=length(senres);
% Previous version of check_senres ensures that several fields had size [1 1].
% Seems unnecessary, so removed it.
for k=1:no_senres
% Check the fields that define pickup loops. Force the field defining the pickup
% loops to have the correct size. It is not clear why the EEG channels and
% the type=13,28,29 HLC channels need numCoils=1, and area>0.
if any(senres(k).sensorTypeIndex==[0:7]) % SQUID channels
correct_numCoils=rem(senres(k).sensorTypeIndex,4)+1;
elseif any(senres(k).sensorTypeIndex==[13 28 29]) % HLC channels
correct_numCoils=1;
elseif any(senres(k).sensorTypeIndex==[8 9]) % EEG channels
correct_numCoils=1;
else
correct_numCoils=0;
end
if senres(k).numCoils~=correct_numCoils & any(senres(k).sensorTypeIndex==[0:7])
fprintf('writeCTFds_test: senres(%d).sensorTypeIndex=%d but numCoils=%d??\n',...
k,senres(k).sensorTypeIndex,senres(k).numCoils);
fprintf(' Set numCoils=%d\n',correct_numCoils);
senres(k).numCoils=correct_numCoils;
end
numCoils=senres(k).numCoils;
if size(senres(k).pos0)~=[3 numCoils];pos0=zeros(3,numCoils);end
if size(senres(k).ori0)~=[3 numCoils];ori0=zeros(3,numCoils);end
if size(senres(k).pos)~=[3 numCoils];pos=zeros(3,numCoils);end
if size(senres(k).ori)~=[3 numCoils];ori=zeros(3,numCoils);end
if size(senres(k).numturns)~=[1 numCoils];numturns=zeros(1,numCoils);end
if size(senres(k).area)~=[1 numCoils];area=zeros(3,numCoils);end
end
status=1;
return
% ************* End of function check_senres*********************************************
% **************************************************************************************
% **************************************************************************************
% ************* function make_dummy_infods*********************************************
function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate);
% If the user does not supply ds.infos, this code makes a dummy version. It has all of
% the tags that Acq created in file Richard_SEF_20060606_04.infods.
% ***********************************************************************************
% ***********************************************************************************
DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006
fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n');
Tag(1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x');
Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000');
Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,...
'data','20060606164306');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,...
'data','19000100000000');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042');
Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,...
'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,...
'data','Unknown');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,...
'data','Dummy infods.');
Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
if exist_hc
nominalPositions=0; % Measured
else
nominalPositions=1; % Nominal
end
Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,...
'data',nominalPositions);
Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
'data','ds.res4.scrr');
Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
'data','ds.res4.senres');
%Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef');
%Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled');
Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',...
round(0.25*sample_rate));
Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0);
if exist_HLC
HZ_MODE=5;
elseif exist_hc
HZ_MODE=1;
else
HZ_MODE=DATASET_HZ_UNKNOWN;
end
Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE);
Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
return
% ************* End of function make_dummy_infods*********************************************
% **************************************************************************************
% **************************************************************************************
% ************* Function writeHc*********************************************
function hc=writeHc(hcFileName,hc,HLCdata);
% Modified for v1.2 ds.hc structures. ds.hc.names has the exact, complete names of the
% head coils. The coordinates relative to the subject may be ds.hc.head(MEG) OR
% ds.hc.abdomen (fMEG).
% Creates a .hc file in a CTF dataset
% Inputs: hcFileName : Complete name of .hc file including path, basename and .hc ext.
% hc : structure with nasion, left, right head coil positions in dewar and
% CTF head coordinates.
% HLCdata : head coil locations at the start of 1st trial. unit=m
% coordinates=dewar. Used only if structure hc is empty and it is MEG
% data (not fMEG data).
% Output : hc : hc structure. hc=struct([]) on failure. hc is set to the coil positions
% in array HLCdata if hc=[] on entry.
% Check inputs
if exist('hc')~=1
hc=struct([]);
elseif ~isstruct(hc)
hc=struct([]);
end
hcfields=fieldnames(hc);
if exist('HLCdata')~=1
HLCdata=[];
elseif ~isnumeric(HLCdata) | size(HLCdata,1)~=3 | size(HLCdata,2)<3
HLCdata=[];
end
% Check hc Filename
if exist('hcFileName')~=1;hcFileName=char([]);end
if ~ischar(hcFileName) | isempty(hcFileName)
fprintf('writeCTFds (writeHc): Called writeHc with bad file name.\n');
hcFileName
return
end
% Both hc and HLCdata bad?
if length(hcfields)~=4 & isempty(HLCdata)
fprintf('writeCTFds (writeHc): Called writeHc with bad hc and bad HLCdata.\n');
hc=struct([])
return
elseif length(hcfields)~=4
rstandard=8/sqrt(2)*[1 1 0;-1 1 0;1 -1 0]';
rstandard(3,:)=-27;
rdewar=100*HLCdata(:,1:3);
% Convert from dewar coordinates to CTF head coordinates.
originCTF=0.5*(hc.dewar(:,2)+hc.dewar(:,3));
% Unit vectors for the CTF coordinates
uCTF(:,1)=hc.dewar(:,1)-originCTF;
uCTF(:,3)=cross(uxCTF,hc.dewar(:,2)-hc.dewar(:,3));
uCTF(:,2)=cross(uCTF(:,3),uCTF(:,1));
uCTF=uCTF./(ones(3,1)*sqrt(sum(uCTF.^2,1)));
rCTF=uCTF'*(rdewar-originCTF*ones(1,3))
hc=struct('names',strvcat('nasion','left ear','right ear'),...
'standard',rstandard,'dewar',rdewar,'head',rCTF);
clear originCTF uCTF rstandard rdewar rCTF;
end
% Character strings for generating the .hc text file
% Should never have both 'head' and 'abdomen' fields.
labelword=strvcat('standard','measured','measured');
printField=[strmatch('standard',hcfields) strmatch('dewar',hcfields) ...
strmatch('head',hcfields) strmatch('abdomen',hcfields)];
if ~strmatch('names',hcfields) | length(printField)~=3
fprintf(['writeCTFds (writeHc): Structure hc does not have all of the required fields.\n',...
' No .hc file will appear in the output dataset.\n']);
hc;
hc=struct([]);
return
end
relative=strvcat('dewar','dewar',hcfields{printField(3)});
coilcoord=strvcat('standard','dewar',hcfields{printField(3)});
comp='xyz';
coilname=hc.names;
fid=fopen(hcFileName,'w','ieee-be');
for k=1:size(coilcoord,1)
rcoil=getfield(hc,coilcoord(k,:));
for coil=1:size(hc.names,1)
clName=deblank(hc.names(coil,:));
fwrite(fid,[labelword(k,:) ' ' clName ' coil position relative to ',...
deblank(relative(k,:)) ' (cm):' char(10)],'uint8');
for m=1:3
fwrite(fid,[char(9) comp(m) ' = ' num2str(rcoil(m,coil),'%7.5f') char(10)],'uint8');
end
end
end
fclose(fid);
status=0;
return
% ************* End of function writeHc*********************************************
% **************************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MarkerFileOK=checkMrk(ds);
% Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk.
% Output: MarkerFileOK=1 : ds.mrk looks OK
% MarkerFileOK=0 : ds.mrk cannot be a set of valid markers for these data.
MarkerFileOK=isfield(ds,'mrk');
if MarkerFileOK
MarkerFileOK=~isempty(ds.mrk);
end
if MarkerFileOK
% Are the markers appropriate?
minMarkerTrial=[];
minMarkerTime=[];
maxMarkerTrial=[];
maxMarkerTime=[];
for k=1:length(ds.mrk)
maxMarkerTrial=max([maxMarkerTrial max(ds.mrk(k).trial)]);
maxMarkerTime=max([maxMarkerTime max(ds.mrk(k).time)]);
minMarkerTrial=min([minMarkerTrial min(ds.mrk(k).trial)]);
minMarkerTime=min([minMarkerTime min(ds.mrk(k).time)]);
end
if isempty(maxMarkerTrial) | isempty(maxMarkerTime)
MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty.
else
MarkerFileOK=(maxMarkerTrial<=ds.res4.no_trials & minMarkerTrial>=1 & ...
maxMarkerTime<=(ds.res4.no_samples/ds.res4.sample_rate) & ...
minMarkerTime>=(-ds.res4.preTrigPts/ds.res4.sample_rate));
if ~MarkerFileOK
fprintf(['\nwriteCTFds (checkMrk): ds.mrk cannot possibly be a set of markers ',...
'for array(data).\n']);
fprintf([' minMarkerTrial=%d (must be >=1) ',...
'maxMarkerTrial=%d (must be <=%d)\n'],...
minMarkerTrial,maxMarkerTrial,ds.res4.no_trials);
fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',...
'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],...
minMarkerTime,-ds.res4.preTrigPts/ds.res4.sample_rate,...
maxMarkerTime,ds.res4.no_samples/ds.res4.sample_rate);
fprintf(' MarkerFile.mrk will not be created.\n\n');
end
end
end
return
%%%%%%%%%%%%%% end of checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeEEG(eegFileName,EEG);
% Reads the EEG file of a dtaset and stores the infoemation in strucure array EEG.
% EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number)
% EEG(k).name = channel name given by the user (e.g. Fp4)
% EEG(k).pos = electrode position in cm in CTF head coordinates
% Check inputs
if exist('eegFileName')~=1;eegFileName=char([]);end
if ~ischar(eegFileName) | isempty(eegFileName)
fprintf('writeCTFds (writeEEG): Called writeEEG with bad file name.\n');
eegFileName
EEG=struct([]);
end
if exist('EEG')~=1
EEG=struct([]);
elseif ~isstruct(EEG)
EEG=struct([]);
end
if isempty(EEG);return;end
fid=fopen(eegFileName,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeEEG): Could not open file %s\n',eegFileName);
return
end
nEEG=length(EEG);
for k=1:nEEG
fprintf(fid,'%d\t%s\t%7.5f\t%7.5f\t%7.5f\n',EEG(k).chanNum,EEG(k).name,EEG(k).pos);
end
fclose(fid);
return
%%%%%%%%% End of writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial);
% Creates a bad.segements file in a CTF data set from the information in structure
% badSegments which is created by read_badSegments, or by the user.
% If structure badSegments is empty, then the file is not created.
% badSegments structure:
% badSegments.trial = List of trial numbers
% badSegments.StartTime = List of bad segment start times (relative to trial).
% badSegments.EndTime = List of bad segment end times.
% Check badSegmentsFile
if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end
if isempty(badSegmentsFile) | ~ischar(badSegmentsFile)
fprintf('writeCTFds(writeBadSegments): Bad file name.\n');
badSegmentsFile
return
end
% Check that structure badSegments is defined correctly
if exist('badSegments')~=1 | exist('nTrial')~=1
return
elseif ~isstruct(badSegments) | isempty(badSegments)
return
elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ...
~isfield(badSegments,'EndTime')
return
elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ...
isempty(badSegments.EndTime)
return
elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),...
size(badSegments.EndTime))
fprintf(['\nwriteCTFds (writeBadSegments): ',...
'The fields of structure badSegments do not all have the same size.\n']);
return
elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ...
any(badSegments.EndTime>tTrial)
fprintf(['\nwriteCTFds (writeBadSegments): ds.badSegments cannot possibly describe ',...
'bad segments for these data.\n',...
'\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',...
'max(badSegments.EndTime)=%0.4f s\n\t\tDataset: nTrial=%d tTrial=%0.4f s\n'],...
min(badSegments.trial),max(badSegments.trial),max(badSegments.EndTime),...
nTrial,tTrial);
fprintf('\t\tbad.segments file will not be created.\n\n');
return
end
% Convert all fields to simple vectors
nSeg=prod(size(badSegments.trial));
trial=reshape(badSegments.trial,1,nSeg);
StartTime=reshape(badSegments.StartTime,1,nSeg);
EndTime=reshape(badSegments.EndTime,1,nSeg);
fid=fopen(badSegmentsFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile);
return
end
% Extra tabs are inserted to reproduce the format of bad.segments files produced by
% DataEditor (5.3.0-experimental-linux-20060918).
fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]);
fclose(fid);
return
%%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ClassFileOK=check_cls(ds);
% Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass.
ClassFileOK=isfield(ds,'TrialClass');
if ClassFileOK
ClassFileOK=~isempty(ds.TrialClass);
end
if ClassFileOK
% Are the class trials appropriate?
minClassTrial=[];
maxClassTrial=[];
for k=1:length(ds.TrialClass)
maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]);
minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]);
end
% Create ClassFile.cls even when the trail classes are empty.
if ~isempty(maxClassTrial)
ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1);
if ~ClassFileOK
fprintf(['\nwriteCTFds (check_cls): ds.TrialClass cannot possibly be a set of ',...
'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',...
'maxClassTrial=%d (must be <=%d)\n'],...
minClassTrial,maxClassTrial,ds.res4.no_trials);
fprintf(' ClassFile.cls will not be created.\n');
end
end
end
return
%%%%%%%%%%%%%% end of check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeClassFile(ClassFile,TrialClass);
% Write the ClassFile of a CTF data set.
% The CLassFile allows a user to store a list of trial classifications in a data set.
% The ClassFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid.
% Inputs :
% ClassFile : marker file including the full path and extension .mrk.
% TrialClass : Structure creted by read_ClassFile.
% Output : ClassFile.cls.
% Check input TrialClass.
if exist('TrialClass')~=1;TrialClass=[];end
if isempty(TrialClass) | ~isstruct(TrialClass)
fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n');
TrialClass
return
end
% Check ClassFile
if exist('ClassFile')~=1;ClassFile=char([]);end
if isempty(ClassFile) | ~ischar(ClassFile)
fprintf('writeCTFds (writeClassFile): Bad file name.\n');
ClassFile
end
fid=fopen(ClassFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile);
return
end
nClass=length(TrialClass);
% Generate datasetname from ClassFIle.
ksep=max([0 strfind(ClassFile,filesep)]);
datasetname=ClassFile(1:ksep-1);
if isempty(datasetname);datasetname=cd;end
fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname);
fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass);
for k=1:nClass
if k==1 % Add sign character to make output match the output of Acq.
sgn=char([]); % There should be no real significance to this.
else % Why does DataEditor places the + sign only on ClassID 2,3,...?
sgn='+';
end
No_of_Trials=prod(size(TrialClass(k).trial));
fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',...
sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment);
fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',...
TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials);
fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n');
% Subtract one so trial numbering starts at 0 in ClassFile.cls
fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1);
fprintf(fid,'\n\n');
end
fclose(fid);
return
%%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Function writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeVirtualChannels(VirtualChannelsFile,Virtual);
% Writes a VirtualChannels file using the information in structure Virtual.
% S\tructure Virtual is prepared by read_VirtualChannels
% Check VirtualChannelsFile
if exist('VirtualChannelsFile')~=1;VirtualChannelsFile=char([]);end
if isempty(VirtualChannelsFile) | ~ischar(VirtualChannelsFile)
fprintf('write_VirtualChannelsFile: Bad file name.\n');
VirtualChannelsFile
return
end
% Check structure array Virtual
if exist('Virtual')~=1
fprintf('writeVirtualChannels: Must specify structure Virtual.\n');
return
elseif isempty(Virtual) | ~isstruct(Virtual)
return
elseif ~isfield(Virtual,'Name') | ~isfield(Virtual,'wt');
return
elseif isempty(Virtual(1).Name)
return
end
fid=fopen(VirtualChannelsFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeVirtualChannels): Could not open file %s\n',VirtualChannelsFile);
return
end
fprintf(fid,'//Virtual channel configuration\n\n');
for k=1:length(Virtual)
fprintf(fid,'VirtualChannel\n{\n\tName:\t%s\n\tUnit:\t%s\n',...
Virtual(k).Name,Virtual(k).Unit);
for q=1:size(Virtual(k).wt)
% Floating format chosen to match VirtualChanels file creatd by
% DataEditor (5.3.0-experimental-linux-20060918).
fprintf(fid,'\tRef:\t%s,%0.6g\n',deblank(Virtual(k).chan(q,:)),Virtual(k).wt(q));
end
fprintf(fid,'}\n\n');
end
fclose(fid);
return
%%%%%%%%%%%%%% end of writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateDescriptors(ds,comment,creatorSoftware,HLCcntrl);
% Makes sure that certain tags are in structure infods, and makes sure that information
% is transfered to infods and newds from res4. Updates several fields of res4 with
% clinical use message (=comment) and name of creator program.
% Inputs: ds : ds structure produced by readCTFds.
% comment : Character string that is added to infods tags listed in addCommentTag
% and res4 fields listed in addCommentField
% creatorSoftware : Character string indicating that the data set was
% created by writeCTFds. Added to infods tags listed in addCreatorTag and
% appName field of res4.
% HLCcntrl: If ds.infods is missing or empty, HLCcntrl determines the
% _DATA_HZ_MODE tage of infods. if noit present or empty, HLCcntrl=0.
% Creates a dummy infods structure if necessary using function make_dummy_infods.
% Changes infods and newds to match information in
% ds.res4.nf_run_title
% ds.res4.collect_descriptor
% ds.res4.nf_subject_id
% ds.res4.nf_operator
% Adds comment (clinical use message) and creator software name to infods, newds and hist files.
if ~isfield(ds,'infods');ds.infods=[];end
% infods tags that will display the comment.
addCommentTag=strvcat('_PATIENT_ID','_PATIENT_INSTITUTE','_PROCEDURE_COMMENTS',...
'_DATASET_COMMENTS','_DATASET_STATUS','_DATASET_PROCSTEPTITLE');
% res4 text fields that will display the comment
addCommentField=strvcat('appName','dataOrigin','dataDescription',...
'nf_run_title','nf_subject_id','run_description');
% res4 text string lengths (from document "CTF MEG File Formats", PN900-0088)
addCommentLength=[256 256 256 256 32 -1]'; % -1 indicates variable length
% infods tags that will display the creator software.
addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',...
'_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE');
% res4 text fields that will display the creator software.
addCreatorField=strvcat('appName','run_description');
addCreatorLength=[256 -1]';
% List of infods tags that will be set to ds.res4.fields (not necessarily fields listed in
% addCommentField or addCreatorField
addRes4Tag=strvcat('_PATIENT_ID','_DATASET_PROCSTEPTITLE',...
'_DATASET_PROCSTEPDESCRIPTION','_DATASET_OPERATORNAME');
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add the Tags to infods. In most cases they will already be there, but just to be sure.
addTag=strvcat(addRes4Tag,addCommentTag,addCreatorTag);
tagClass=strvcat('_PATIENT','_PROCEDURE','_DATASET');
% List of all the tag names as a character array
tagName=getArrayField(ds.infods,'name')';
if length(ds.infods)==1;tagName=tagName';end
tagType=getArrayField(ds.infods,'type');
tagPtr=1; % If a class is missing, inject the class starting at tagPtr+1.
for k=1:size(tagClass,1)
addIndex=strmatch(deblank(tagClass(k,:)),addTag)';
% Are there any tags to be added in this class?
if isempty(addIndex);continue;end
% List of infods tags in the tagClass, but excluding the CPerist type (which marks the
% start of a class.
infodsIndex=strmatch(deblank(tagClass(k,:)),tagName);
if isempty(infodsIndex) % Create a new class of tags.
if strcmp(deblank(tagName(tagPtr+1,:)),'EndOfParameters') & k>1;
tagPtr=tagPtr+1;
end
nTag=length(ds.infods);
tagName((tagPtr+4):(nTag+3),:)=tagName((tagPtr+1):nTag,:);
ds.infods((tagPtr+4):(nTag+3))=ds.infods((tagPtr+1):nTag);
ds.infods(tagPtr+1)=struct('name',[deblank(tagClass(k,:)),'_INFO'],'type',2,'data',[]);
ds.infods(tagPtr+2)=struct('name','WS1_','type',0,'data',[]);
ds.infods(tagPtr+3)=struct('name','EndOfParameters','type',-1,'data',[]);
tagName=strvcat(tagName(1:tagPtr,:),...
strvcat([deblank(tagClass(k,:)),'_INFO'],'WS1_','EndOfParameters'),...
tagName(tagPtr+1:nTag,:));
nTag=nTag+3;
tagPtr=tagPtr+2;
else
if ds.infods(max(infodsIndex)).type==2
tagPtr=max(infodsIndex)+1; % Class consists of no tags beyond the CPersist definition
else
tagPtr=max(infodsIndex); % Class contains at least one real tag.
end
clear infodsIndex;
end
for q=addIndex
if isempty(strmatch(deblank(addTag(q,:)),tagName))
tagName=strvcat(tagName(1:tagPtr,:),deblank(addTag(q,:)),tagName(tagPtr+1:nTag,:));
ds.infods((tagPtr+2):(nTag+1))=ds.infods((tagPtr+1):nTag);
ds.infods(tagPtr+1)=struct('name',deblank(addTag(q,:)),'type',10,'data',char([]));
tagPtr=tagPtr+1;
nTag=nTag+1;
end
end
end
clear k q nTag tagPtr infodsIndex addIndex;
% All of the tags in addTag have been added to ds.infods.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if exist('creatorSoftware')~=1;
creatorSoftware=char([]);
elseif ~ischar(creatorSoftware)
creatorSoftware=char([]);
else
creatorSoftware=deblank(creatorSoftware);
end
if exist('comment')~=1;
comment=char([]);
elseif ~ischar(comment)
comment=char([]);
else
comment=deblank(comment);
end
tagName=getArrayField(ds.infods,'name')';
% Update the res4 fields : add creator message.
% Don't check field length, but truncate later.
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
if isempty(strfind(strng,creatorSoftware))
newStrng=creatorSoftware;
if ~isempty(strng);newStrng=[strng ' ' newStrng];end
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng);
end
end
clear q strng nChar strng0 ns;
% Update the res4 fields : add comment (= clinical use message)
% Don't check field length, but truncate later.
for q=1:size(addCommentField,1);
strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:))));
if isempty(strfind(strng,comment))
newStrng=comment;
if ~isempty(strng);newStrng=[strng ' ' newStrng];end
ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),newStrng);
end
end
clear strng newStrng q;
% Update res4.run_description
ds.res4.run_description=[ds.res4.run_description,char(0)];
ds.res4.rdlen=length(ds.res4.run_description);
% Update infods entries from .res4 fields
ds.infods(strmatch('_PATIENT_ID',tagName)).data=deblank(ds.res4.nf_subject_id);
ds.infods(strmatch('_DATASET_PROCSTEPTITLE',tagName)).data=deblank(ds.res4.nf_run_title);
ds.infods(strmatch('_DATASET_PROCSTEPDESCRIPTION',tagName)).data=...
deblank(ds.res4.nf_collect_descriptor);
ds.infods(strmatch('_DATASET_OPERATORNAME',tagName)).data=deblank(ds.res4.nf_operator);
% Truncate the .res4. fields. Leave room for a final char(0).
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),...
strng(length(strng)+[-addCreatorLength(q)+2:0]));
end
end
for q=1:size(addCommentField,1);
strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:))));
if length(strng)>addCommentLength(q)-1 & addCommentLength(q)>0
ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),...
strng(length(strng)+[-addCommentLength(q)+2:0]));
end
end
clear q strng;
% Add creator software to infods tags. Have already cheked that the tags are there.
for q=1:size(addCreatorTag,1)
if isempty(strmatch(deblank(addCreatorTag(q,:)),addRes4Tag))
k=strmatch(deblank(addCreatorTag(q,:)),tagName);
if length(k)==1
if isempty(strfind(ds.infods(k).data,creatorSoftware))
newStrng=creatorSoftware;
if ~isempty(deblank(ds.infods(k).data));
newStrng=[deblank(ds.infods(k).data) ' ' newStrng];
end
ds.infods(k).data=newStrng;
end
else
fprintf('writeCTFds: Tag %s appears %d times in ds.infods ??\n',...
deblank(addCreatorTag(q,:)),length(k));
end
end
end
clear q k;
% Add comment (clinical use statement) to ds.infods
for q=1:size(addCommentTag,1)
if isempty(strmatch(deblank(addCommentTag(q,:)),addRes4Tag))
k=strmatch(deblank(addCommentTag(q,:)),tagName);
if length(k)==1
if isempty(strfind(ds.infods(k).data,comment))
newStrng=comment;
if ~isempty(deblank(ds.infods(k).data));
newStrng=[deblank(ds.infods(k).data) ' ' newStrng];
end
ds.infods(k).data=newStrng;
end
else
fprintf(['writeCTFds (updateDescriptors): Tag %s appears %d times in ',...
'ds.infods ??\n'],deblank(addCommentTag(q,:)),length(k));
end
end
end
clear q k;
% Add the creator and comment information to the newds file
if isfield(ds,'newds');
nChar=length(ds.newds);
% Keyword positions
aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)]));
if isempty(aNpos)
fprintf(['writeCTFds (update_decsriptors): Keyword ''appName'' ',...
'does not appear in ds.newds.\n',...
' set ds.newds=[].\n']);
ds.newds=char([]);
else
eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]);
ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ' ' comment ...
ds.newds((aNpos+eol):length(ds.newds))];
end
clear nChar aNpos eol;
end
% Add clinical use message to hist file.
if isfield(ds,'hist') & ~isempty(comment)
ds.hist=[ds.hist char(10) comment char(10)];
end
return
%%%%%%%%%%%%%% End of updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [infods,status]=updateHLC(infods,HLCdata);
% Adds notes and continuous-head-localization tags to .infods file
% Inputs : infods : Structure of tags to be written to output infods file.
% HLCdata : 0 or [] or not defined - There are no HLC channels
% (head-coil position) in the data. Just pass the existing tags to
% the output dataset.
% HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial]
% Calculate the head motion tags.
% Outputs : status : 0: Everything looks OK
% 1: Couldn't find _DATASET tags.
% <0: There is a problem with the new infods file.
% Calls:
% - getArrayField: Extracts field names from structure array S.
% Defaults for the head localization tags.
% Might do this better with a structure.
HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006
% Should be -1.
% New dataset tags for HLC specification.
addTag=strvcat('_DATASET_HZ_MODE',...
'_DATASET_MOTIONTOLERANCE',...
'_DATASET_MAXHEADMOTION',...
'_DATASET_MAXHEADMOTIONTRIAL',...
'_DATASET_MAXHEADMOTIONCOIL');
addTagType=[5 4 4 7 10]';
% Check HLCdata array. HLCdata=[] indicates no continuous head localization.
if ~exist('HLCdata')==1
HLCdata=[];
elseif ~isempty(HLCdata)
[samplesPerTrial nDim Ncoil nTrial]=size(HLCdata);
if nDim~=3;
fprintf('writeCTFds (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata));
fprintf(']\n');
fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim);
HLCdata=[];
end
end
% Assume that all the tag names are different. There is no checking when a tag listed in
% addTag matches more than one entry in array name.
name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag]
DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag]
if isempty(DATASET_tags)
status=1; % No _DATASET tags. Don't add anything.
else
status=0;
if isempty(HLCdata)
TagValue(1)=HZ_MODE_UNKNOWN;
TextTagValue=char(0);
addTag=addTag(1,:); % Remove the other HLC tags
addTagType=addTagType(1);
else % ~isempty(HLCdata)
% Remove HLC offsets.
HLCoffset=squeeze(HLCdata(1,:,:,1));
for q=1:Ncoil
for k=1:3
HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLCoffset(k,q);
end
end
% Calculate motions as displacement from the start of the dataset.
absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial]
maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial]
maxHeadMotion=max(max(maxCoilMotion));
[mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2));
[mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1));
% Create a list of head motion tag values
TagValue(1)=5; % Indicates continuous head localization
TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE
TagValue(3)=maxHeadMotion; % _DATASET_MAXHEADMOTION
% Subtract 1 from the trial so trial numbering starts at 0.
TagValue(4)=maxHeadMotionTrial-1; % _DATASET_MAXHEADMOTIONTRIAL
TextTagValue=char(zeros(4,1)); % Placeholder since tags1:4 are numerical
% _MAXHEADMOTIONCOIL value
TextTagValue=strvcat(TextTagValue,sprintf('%d',maxHeadMotionCoil));
TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string.
end
% Add or insert tags.
for q=1:size(addTag,1)
nTag=length(infods);
tagName=deblank(addTag(q,:));
TagNo=strmatch(tagName,name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
infods((TagNo+1):(nTag+1))=infods(TagNo:nTag);
name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
end
if addTagType(q)~=10
infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q));
else
infods(TagNo)=struct('name',tagName,'type',addTagType(q),...
'data',deblank(TextTagValue(q,:)));
end
end % End loop over head position and head motion tags.
clear q TagNo TextTagValue TagValue;
end % End section add _DATASET tags
return
%%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateBandwidth(ds,fhp,flp);
% Updates the bandwidth fields of infods and newds.
% 3 possible dources of bandwidth:
% 1. fhp,flp inputs (default)
% 2. newds fiels
% 3. res4.filter
% 4. infods field
% Almost always, fhp,flp will have the default values, but it could be defined in the
% fields of ds, so check. Result: lots of code to achieve a simple result.
% read fhp,flp from newds (if it exists)
if isfield(ds,'newds')
BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)])); % Keyword position
if isempty(BWpos)
fprintf(['writeCTFds (updateBandwidth): Keyword ''bandwidth:''',...
'does not appear in ds.newds.\n',...
' Field newds removed from structure ds.\n']);
ds=rmfield(ds,'newds');
else
% Get the bandwidth parameters from ds.newds.
eol=max([13 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]);
buff=sscanf(ds.newds((BWpos+13):(BWpos+eol)),'%f%c%f');
fhp=max(fhp,buff(1));
flp=min(flp,buff(3));
end
clear eol buff BWpos;
end
% Get fhp, flp from res4.
if ~isempty(ds.res4.filters)
for kq=1:ds.res4.num_filters
freq=ds.res4.filters(kq).freq;
if ds.res4.filters(kq).fType==1;
flp=min(flp,freq);
elseif ds.res4.filters(kq).fType==2;
fhp=max(fhp,freq);
end
end
clear kq freq;
end
% Get fhp, flp from ds.infods
if isfield(ds,'infods')
name=getArrayField(ds.infods,'name')';
TagNo=strmatch('_DATASET_LOWERBANDWIDTH',name,'exact');
if ~isempty(TagNo);fhp=max(fhp,ds.infods(TagNo).data);end
TagNo=strmatch('_DATASET_UPPERBANDWIDTH',name,'exact');
if ~isempty(TagNo);flp=min(flp,ds.infods(TagNo).data);end
end
% Now have fhp,flp. Update hist. Add all the res4 filters.
if ~isempty(ds.res4.filters)
if ~isfield(ds,'hist');hist=char([]);end
ds.hist=[ds.hist 'Filters specified in res4 file :' char(10)];
for kq=1:ds.res4.num_filters
freq=ds.res4.filters(kq).freq;
if ds.res4.filters(kq).fType==1;
ds.hist=[ds.hist ...
num2str(kq,'%8d') ' Lowpass ' num2str(freq,'%6.2f') ' Hz' char(10)];
elseif ds.res4.filters(kq).fType==2;
ds.hist=[ds.hist ...
num2str(kq,'%8d') ' Highpass ' num2str(freq,'%6.2f') ' Hz' char(10)];
elseif ds.res4.filters(kq).fType==3;
ds.hist=[ds.hist num2str(kq,'%8d') ' Notch ' num2str(freq,'%6.2f') ...
' Hz width=' num2str(ds.res4.filters(kq).Param,'%6.2f') ' Hz' char(10)];
else
ds.hist=[ds.hist ' fType=',num2str(ds.res4.filters(kq).fType,'%d') char(10)];
end
end
ds.hist=[ds.hist ,...
'Bandwidth: ',num2str(fhp,'%0.3g'),' - ',num2str(flp,'%0.3g'),' Hz',char(10)];
clear kq freq;
end
% Update newds bandwidth
if isfield(ds,'newds')
BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)]));
eol=max([12 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]);
ds.newds=[ds.newds(1:BWpos+11) num2str(fhp,'%0.6f') ', ' num2str(flp,'%0.6f') ...
ds.newds((BWpos+eol):length(ds.newds))];
clear BWpos eol;
end
% Update infods bandwidth tags. Lots of coding becasue it's possible that infods does
% not already have bandwidth tags.
name=getArrayField(ds.infods,'name')';
DATASET_tags=strmatch('_DATASET_',name);
if ~isempty(DATASET_tags)
addTag=strvcat('_DATASET_LOWERBANDWIDTH','_DATASET_UPPERBANDWIDTH');
TagValue=[fhp flp];
% Add or update tags.
for q=1:size(addTag,1)
nTag=length(ds.infods);
TagNo=strmatch(deblank(addTag(q,:)),name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag);
ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',4,'data',TagValue(q));
name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
else
ds.infods(TagNo).data=TagValue(q); % Tag exists. Just update the value.
end
end % End loop over head position and head motion tags.
clear q nTag DATASET_tags;
else
fprintf(['writeCTFds (updateBandwidth): Found no _DATASET tags in infods.\n'...
'\t\t\tDid not add bandwidth tags.\n']);
end
return
%%%%%%%%%%%%%% End of updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateDateTime(ds);
% Update the dat/time fields of res4 and and infods
datetime=floor(clock);
if isfield(ds,'infods');
name=getArrayField(ds.infods,'name')';
DATASET_tags=strmatch('_DATASET_',name);
if ~isempty(DATASET_tags)
addTag=strvcat('_DATASET_CREATORDATETIME','_DATASET_LASTMODIFIEDDATETIME');
tagData=sprintf('%d%2.2d%2.2d%2.2d%2.2d%2.2d',datetime);
tagType=10;
for q=1:size(addTag,1)
nTag=length(ds.infods);
TagNo=strmatch(deblank(addTag(q,:)),name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag);
name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
end
ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',tagType,'data',tagData);
end
clear nTag TagNo name DATASET_tags addTag tagData tagType;
else
fprintf('writeCTFds (updateDateTime): Cannot find any _DATASET tags in ds.infods.\n');
end % End loop over head position and head motion tags.
else
fprintf('writeCTFds (updateDateTime): Cannot find ds.infods.\n');
end
ds.res4.data_date=sprintf('%4d/%2.2d/%2.2d',datetime(1:3));
ds.res4.data_time=sprintf('%2.2d:%2.2d:%2.2d',datetime(4:6));
return
%%%%%%%%%%%%%% End of updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=getArrayField(S,yfield)
% Extracts one field of a structure array.
% Inputs: S : structure array.
% yfield: name of field of S (string)
% Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)]
% Field sizes: Two options:
% 1. size(S(n).yfield) is the same for all n. Any size allowed.
% 2. S(n).yfield is a 2-D array for all structure elements S(n).
% Then yfield of different array elements S(n) can have different sizes.
% The array returned will be large enough to accomodate all of the data.
sizeS=size(S);
nS=prod(sizeS);
S=reshape(S,1,nS);
% Determine which array-size option to use.
sizey=size(getfield(S,{1},yfield));
option1=1;
option2=(length(sizey)==2);
for n=2:nS
sizeyn=size(getfield(S,{n},yfield));
option1=option1 & isequal(sizey,sizeyn);
option2=option2 & length(sizeyn)==2;
if option2
sizey=max([sizey;sizeyn],[],1);
end
end
if option1 % All fields have the same size
nY=prod(sizey);
if isnumeric(getfield(S,{1},yfield))
x=zeros(nY,nS);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros(nY,nS));
end
for n=1:nS
x(:,n)=reshape(getfield(S,{n},yfield),nY,1);
end
x=reshape(x,[sizey nS]);
elseif option2 % All fields have only two dimensions
if isnumeric(getfield(S,{1},yfield))
x=zeros([sizey nS]);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros([sizey nS]));
end
for n=1:nS
y=getfield(S,{n},yfield);
sizeyn=size(y);
x(1:sizeyn(1),1:sizeyn(2),n)=y;
end
else
fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',...
'and not all field have the same size.\n'],yfield);
x=[];
end
x=squeeze(x);
return
%%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
writeRes4.m
|
.m
|
antx-master/xspm8/external/ctf/writeRes4.m
| 8,560 |
utf_8
|
416bc2b62624835c63140e54415d2f49
|
function res4=writeRes4(res4File,res4,MAX_COILS);
% Write the new .res4 file. Use ieee-be (big endian) format
% Character-string output is done using function writeCTFstring which
% checks that strings are the correct length for the .res4 file format.
% Function calls: - writeCTFstring (included in this listing).
fid_res4=fopen(res4File,'w','ieee-be');
if fid_res4<0
fprintf('writeCTFds (writeRes4): Could not open file %s\n',res4File);
return
end
fwrite(fid_res4,[res4.header(1:7),char(0)],'uint8'); % 8-byte header
% meg41GeneralResRec
res4.appName=writeCTFstring(res4.appName,-256,fid_res4);
res4.dataOrigin=writeCTFstring(res4.dataOrigin,-256,fid_res4);
res4.dataDescription=writeCTFstring(res4.dataDescription,-256,fid_res4);
fwrite(fid_res4,res4.no_trials_avgd,'int16');
res4.data_time=writeCTFstring(res4.data_time,255,fid_res4);
res4.data_date=writeCTFstring(res4.data_date,255,fid_res4);
% new_general_setup_rec_ext part of meg41GeneralResRec
fwrite(fid_res4,res4.no_samples,'int32'); % 4
fwrite(fid_res4,[res4.no_channels 0],'int16'); % 2*2
fwrite(fid_res4,res4.sample_rate,'double'); % 8
fwrite(fid_res4,res4.epoch_time,'double'); % 8
fwrite(fid_res4,[res4.no_trials 0],'int16'); % 2*2
fwrite(fid_res4,res4.preTrigPts,'int32'); % 4
fwrite(fid_res4,res4.no_trials_done,'int16'); % 2
fwrite(fid_res4,res4.no_trials_display,'int16'); % 2
fwrite(fid_res4,res4.save_trials,'int32'); % 4 CTFBoolean
% meg41TriggerData part of new_general_setup_rec_ext 10 bytes total
fwrite(fid_res4,res4.primaryTrigger,'int32'); % 4
fwrite(fid_res4,res4.triggerPolarityMask,'int32'); % 4
fwrite(fid_res4,[0 0],'uint8'); % 2 bytes
% end of meg41TriggerData part of new_general_setup_rec_ext
fwrite(fid_res4,[0 0],'uint8'); % 2 bytes padding
fwrite(fid_res4,[res4.trigger_mode 0],'int16'); % 2*2
fwrite(fid_res4,res4.accept_reject_Flag,'int32'); % 4 CTFBoolean
fwrite(fid_res4,[res4.run_time_display 0],'int16');% 2*2
fwrite(fid_res4,res4.zero_Head_Flag,'int32'); % 4 CTFBoolean
fwrite(fid_res4,res4.artifact_mode,'int32'); % 4 CTFBoolean
% end of new_general_setup_rec_ext part of meg41GeneralResRec
% meg4FileSetup part of meg41GeneralResRec
res4.nf_run_name=writeCTFstring(res4.nf_run_name,32,fid_res4);
res4.nf_run_title=writeCTFstring(res4.nf_run_title,-256,fid_res4);
res4.nf_instruments=writeCTFstring(res4.nf_instruments,32,fid_res4);
res4.nf_collect_descriptor=writeCTFstring(res4.nf_collect_descriptor,32,fid_res4);
res4.nf_subject_id=writeCTFstring(res4.nf_subject_id,-32,fid_res4);
res4.nf_operator=writeCTFstring(res4.nf_operator,32,fid_res4);
res4.nf_sensorFileName=writeCTFstring(res4.nf_sensorFileName,56,fid_res4);
res4.rdlen=length(res4.run_description); % Run_description may have been changed.
fwrite(fid_res4,[0 res4.rdlen 0],'int32'); % 12-byte structure of the .res4 file.
res4.run_description=writeCTFstring(res4.run_description,res4.rdlen,fid_res4);
% end of meg4FileSetup part of meg41GeneralResRec
% filter descriptions
fwrite(fid_res4,res4.num_filters,'int16');
for kfilt=1:res4.num_filters
fwrite(fid_res4,res4.filters(kfilt).freq,'double');
fwrite(fid_res4,res4.filters(kfilt).fClass,'int32');
fwrite(fid_res4,res4.filters(kfilt).fType,'int32');
fwrite(fid_res4,res4.filters(kfilt).numParam,'int16');
for kparm=1:res4.filters(kfilt).numParam
fwrite(fid_res4,res4.filters(kfilt).Param(kparm),'double');
end
end
% Write channel names. Must have size(res4.chanNames)=[nChan 32]
[no_chanNames len_chanNames]=size(res4.chanNames);
for kchan=1:res4.no_channels
res4.chanNames(kchan,:)=writeCTFstring(res4.chanNames(kchan,:),len_chanNames,fid_res4);
end
% Write sensor resource table
for kchan=1:res4.no_channels
fwrite(fid_res4,res4.senres(kchan).sensorTypeIndex,'int16');
fwrite(fid_res4,res4.senres(kchan).originalRunNum,'int16');
fwrite(fid_res4,res4.senres(kchan).coilShape,'int32');
fwrite(fid_res4,res4.senres(kchan).properGain,'double');
fwrite(fid_res4,res4.senres(kchan).qGain,'double');
fwrite(fid_res4,res4.senres(kchan).ioGain,'double');
fwrite(fid_res4,res4.senres(kchan).ioOffset,'double');
fwrite(fid_res4,res4.senres(kchan).numCoils,'int16');
numCoils=res4.senres(kchan).numCoils;
fwrite(fid_res4,res4.senres(kchan).grad_order_no,'int16');
fwrite(fid_res4,0,'int32'); % Padding to 8-byte boundary
% coilTbl
for qx=1:numCoils
fwrite(fid_res4,[res4.senres(kchan).pos0(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).ori0(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).numturns(qx) 0 0 0],'int16');
fwrite(fid_res4,res4.senres(kchan).area(qx),'double');
end
if numCoils<MAX_COILS
fwrite(fid_res4,zeros(10*(MAX_COILS-numCoils),1),'double');
end
%HdcoilTbl
for qx=1:numCoils
fwrite(fid_res4,[res4.senres(kchan).pos(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).ori(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).numturns(qx) 0 0 0],'int16');
fwrite(fid_res4,res4.senres(kchan).area(qx),'double');
end
if numCoils<MAX_COILS
fwrite(fid_res4,zeros(10*(MAX_COILS-numCoils),1),'double');
end
end
% End writing sensor resource table
% Write the table of balance coefficients.
if res4.numcoef<=0
fwrite(fid_res4,res4.numcoef,'int16'); % Number of coefficient records
elseif res4.numcoef>0
scrx_out=[];
for kx=1:res4.numcoef
sName=strtok(char(res4.scrr(kx).sensorName),['- ',char(0)]);
if ~isempty(strmatch(sName,res4.chanNames))
scrx_out=[scrx_out kx];
end
end
% Remove the extra coefficient records
res4.scrr=res4.scrr(scrx_out);
res4.numcoef=size(res4.scrr,2);
fwrite(fid_res4,res4.numcoef,'int16'); % Number of coefficient records
% Convert res4.scrr to double before writing to output file. In MATLAB 5.3.1,
% when the 'ieee-be' option is applied, fwrite cannot write anything except
% doubles and character strings, even if fwrite does allow you to specify short
% integer formats in the output file.
for nx=1:res4.numcoef
fwrite(fid_res4,double(res4.scrr(nx).sensorName),'uint8');
fwrite(fid_res4,[double(res4.scrr(nx).coefType) 0 0 0 0],'uint8');
fwrite(fid_res4,double(res4.scrr(nx).numcoefs),'int16');
fwrite(fid_res4,double(res4.scrr(nx).sensor),'uint8');
fwrite(fid_res4,res4.scrr(nx).coefs,'double');
end
end
fclose(fid_res4);
return
% *************************************************************************************
%*************** Function writeCTFstring ************************************************
function strng=writeCTFstring(instrng,strlen,fid)
% Writes a character string to output unit fid. Append nulls to get the correct length.
% instrng : Character string. size(instrng)=[nLine nPerLine]. strng is reformulated as a
% long string of size [1 nChar]. Multiple lines are allowed so the user can
% easily append text. If necessary, characters are removed from
% instrng(1:nLine-1,:) so all of strng(nLine,:) can be accomodated.
% strlen: Number of characters to write. strlen<0 means remove leading characters.
% If abs(strlen)>length(strng) pad with nulls (char(0))
% If 0<strlen<length(strng), truncate strng and terminate with a null.
% If -length(string)<strlen<0, remove leading characters and terminate with a null.
% Form a single long string
nLine=size(instrng,1);
strng=deblank(instrng(1,:));
if nLine>1
% Concatenate lines 1:nLine-1
for k=2:nLine-1
if length(strng)>0
if ~strcmp(strng(length(strng)),'.') & ~strcmp(strng(length(strng)),',')
strng=[strng '.']; % Force a period at the end of the string.
end
end
strng=[strng ' ' deblank(instrng(k,:))];
end
if length(strng)>0
if ~strcmp(strng(length(strng)),'.') % Force a period at the end of the string.
strng=[strng '.'];
end
end
% Add all of the last line.
nChar=length(strng);
nLast=length(deblank(instrng(nLine,:)));
strng=[strng(1:min(nChar,abs(strlen)-nLast-4)) ' ' deblank(instrng(nLine,:))];
end
if length(strng)<abs(strlen)
strng=[strng char(zeros(1,abs(strlen)-length(strng)))];
elseif length(strng)>=strlen & strlen>0
strng=[strng(1:strlen-1) char(0)];
else
strng=[strng(nLast+[strlen+2:0]) char(0)];
end
fwrite(fid,strng,'char');
return
% ************* End of function writeCTFstring ***************************************
% ************************************************************************************
|
github
|
philippboehmsturm/antx-master
|
addCTFtrial.m
|
.m
|
antx-master/xspm8/external/ctf/addCTFtrial.m
| 51,483 |
utf_8
|
b59730fdb231f07741e7e87dea9e6c1c
|
function cntrl=addCTFtrial(datasetname,data,unit,mrk,cls,badSegments);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This program creates datasets that can be analyzed by CTF software. %
% %
% Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. %
% %
% Please do not redistribute it without permission from VSM MedTech Ltd. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% addCTFtrial.m Version 1.1 Adds trial(s) to a a CTF-format data set previously
% created from MATLAB by writeCTFds.m. The purpose of addCTFtrial is to allow
% users to write CTF data sets that are too large for the computer's memory.
% Date : 18 April 2007
% Author : Harold Wilson
% Operation :
% 1. Use writeCTFds to create a dataset (name = DATASET) consisting of one or
% more trials. size(data)= [SAMPLES, CHANNELS, TRIALS].
% 2. Later, a trial is to be added to DATASET. This program adds the new information
% to the .res4, .mrk, .cls and badSegements files and appends the new data to the
% existing .meg4 file.
% Inputs : datasetname : Dataset including path. Extension '.ds' is optional.
% data : MEG data array. size(data)=[no_samples no_channels no_trials_added]
% Array data may be single or double.
% unit : Determines the unit of the SQUID and EEG signals:
% If unit is missing or unit==[], the unit is set to 'fT'.
% 'ft' or 'fT' : Convert to fT (MEG), uV (EEG)
% 't' or 'T' : Convert to T (MEG), V (EEG)
% 'phi0' : Convert to phi0 (MEG), uV (EEG)
% 'int': Read plain integers from *.meg4-file
% mrk,cls,badSegments : Structures describing the markers, trial classes and bad
% segments of the new trials. Trial numbering refers to the new trials
% being added to the dataset, starting at trial=1. Markers are updated
% only when there is already as .mrk file in the dataset.
% Outputs : - Dataset with trial(s) added.
% - cntrl : 0 - failure. The dataset is not modified.
% 1 - success. The new data is added to the dataset
% Function calls
% Included in this listing:
% - combineMarkers: Combines marker specifications in structures ds.mrk and mrk.
% - combineClasses: Combines trial class specifications in structures
% ds.TrialClass and cls.
% - writeBadSegments: Creates the new bad.segments file.
% - writeClassFile: Creates the new ClassFile.cls file.
% - updateCreatorSoftware: Adds non-clinical-use and creation software messages to
% infods, res4, newds and hist fields of ds.
% - updateHLC: Adds head-coil movement information from the trials being added to an
% existing ds.infods.
% - getArrayField : Extracts one field of a structure array to make it easier to
% manipulate.
% Not included in this listing:
% - writeRes4: Writes the new .res4 file.
% - writeMarkerFile: Creates the new MarkerFile.mrk file.
% - writeCPersist: Creates the new .acq and .infods files.
% Output files are opened with 'w' permission and 'ieee-be' machine format in order
% to be compatible with the Linux acquisition and analysis software. Do not open files
% with 'wt' permission because this will add an extra byte (char(13)) at the end of each
% line of text.
%persistent printWarning % No clinical-use warning with addCTFtrial.
%printWarning=1;
delim=filesep;
if nargin==0 & nargout==0 % Print a version number
fprintf(['\taddCTFtrial: Version 1.1 18 April 2007 ',...
'Adds trials to v4.1 and v4.2 CTF data sets.\n',...
'\tCall: cntrl=addCTFtrial(datasetname,data,unit,mrk,cls,badSegments);\n',...
'\t\tdatasetname = Name of existing dataset including the path.\n',...
'\t\tdata = Data that will be written to the new dataset .meg4 file.\n',...
'\t\tunit = Physical units of the data.\n',...
'\t\tmrk,cls,badSegments = descriptions of markers, trial classes and',...
' bad segments of data.\n\n']);
return
end
% Indicate failure on an early return.
cntrl=0;
% Allowed 8-byte headers for res4 and meg4 files.
res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]);
meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]);
MAX_COILS=8; % Parameter that determines the size of the ds.res4.senres structure.
maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software)
% addCTFds will add trials to datasets only if they were created by writeCTFds.
originalCreatorSoftware='writeCTFds';
creatorSoftware='addCTFtrial'; % Added to .infods file
meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes.
clinical_use_message='NOT FOR CLINICAL USE';
if ~exist('clinical_use_message');
clinical_use_message=char([]);
end
% Check number of inputs
if nargin<2
fprintf(['addCTFtrial: Must supply inputs datasetname,data. ',...
'Only %d input arguments are present.\n'],nargin);
return
end
% Check input argument unit. Convert unit to lower case.
if exist('unit')~=1
unit='ft'; % default
elseif isempty(unit)
unit='ft'; % default
elseif ischar(unit)
unit=lower(unit);
if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0')
fprintf(['addCTFtrial : unit=%s Not a valid option. Must be ',...
'''fT'', ''T'', ''phi0'' or ''int''\n'],unit);
ds=-1; % Force an error in the calling program.
return
end
end
% Check argument type
if ~isnumeric(data)
fprintf('\naddCTFtrial: Input data is not numeric.\n');
return
elseif ~ischar(unit)
fprintf('\naddCTFtrial: Input unit is not char.\n');
return
elseif~ischar(datasetname)
fprintf('\naddCTFtrial: Input datasetname is not char.\n');
return
end
if exist('mrk')==1
if ~isstruct(mrk)
fprintf('\naddCTFtrial: Input mrk is not a structure.\n\n');
return
end
else
mrk=struct([]);
end
if exist('cls')==1
if ~isstruct(cls)
fprintf('\naddCTFtrial: Input cls is not a structure.\n\n');
return
end
else
cls=struct([]);
end
if exist('badSegments')==1
if ~isstruct(badSegments)
fprintf('\naddCTFtrial: Input badSegments is not a structure.\n\n');
return
end
else
badSegments=struct([]);
end
% Does the dataset exist?
if exist(datasetname)~=7
fprintf('addCTFtrial: Dataset %s does not exist.\n',datasetname);
return
end
% Separate datasetname into a path and the baseName
datasetname=deblank(datasetname);
ksep=max([0 findstr(datasetname,delim)]);
baseName=datasetname((ksep+1):length(datasetname));
path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]).
% Remove the last .ds from baseName.
kdot=max(findstr(baseName,'.ds'));
if kdot==(length(baseName)-2)
baseName=baseName(1:(max(kdot)-1));
else
datasetname=[datasetname,'.ds'];
end
clear ksep kdot;
% Get the ds structure of the dataset
ds=readCTFds(datasetname);
% Update text fields of res4,infods, newds.
ds=updateCreatorSoftware(ds,creatorSoftware,originalCreatorSoftware);
if isempty(ds);return;end
nSample=ds.res4.no_samples;
fSample=ds.res4.sample_rate;
nChan=ds.res4.no_channels;
% Check that the new data and the existing data have the same number of channels
% and points per trial.
if size(data,1)~=nSample | size(data,2)~=nChan | size(data,3)==0
fprintf(['addCTFtrial: size(data)=[%d %d %d], but existing data has no_samples=%d,',...
' no_channels=%d\n'],[size(data,1) size(data,2) size(data,3)],...
nSample,nChan);
return
end
% Update ds.res4 fields to match the size of array data.
nTrialNew=size(data,3);
nTrialOld=ds.res4.no_trials;
ds.res4.no_trials=nTrialOld+nTrialNew;
ds.res4.epoch_time=nSample*ds.res4.no_trials/fSample;
% Before converting data to integers, save the HLC channels for motion analysis in function
% function updateHLC.
if isempty(strmatch('HLC',ds.res4.chanNames))
HLCdata=[];
else
% Make a list of head-coil channels
coil=0;
HLClist=[];
while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames))
coil=coil+1;
for k=1:3
HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)];
end
end
HLCdata=reshape(double(data(:,HLClist,:)),nSample,3,coil,nTrialNew);
clear coil k HLClist;
end
% Convert data to integers because CTF data sets are stored as raw numbers and
% not as physical qunatities. The res4 file contains the calibrations for
% converting back to physical units. Array data may be single precision, so
% convert to double before doing any adjustments to the data.
% Already checked that unit is valid.
if strcmp(unit,'int')
data=reshape(data,nSample,nChan*nTrialNew);
for k=1:nChan*nTrialNew
if strcmp(class(data),'single')
data(:,k)=single(round(double(data(:,k))));
else
data(:,k)=round(double(data(:,k)));
end
end
data=reshape(data,nSample,nChan,nTrialNew);
clear k;
else
for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T
SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]);
EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]);
if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0'))
alphaG=1e-6;
elseif SQUIDtype & strcmp(unit,'ft')
alphaG=1e-15;
elseif SQUIDtype & strcmp(unit,'phi0')
alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain);
else
alphaG=1;
end
% Convert from physical units to integers using the gains in the senres table.
for kt=1:nTrialNew
buff=round(double(data(:,chan,kt))*(alphaG*...
(ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain)));
if strcmp(class(data),'single')
data(:,chan,kt)=single(buff);
else
data(:,chan,kt)=buff;
end
end
end
clear chan alphaG SQUIDtype EEGtype buff kt;
end
% Check the meg4 file header.
fidMeg4=fopen([path,baseName,'.ds\',baseName,'.meg4'],'r','ieee-be');
fileHeader=fread(fidMeg4,8,'char')';
fclose(fidMeg4);
if isempty(strmatch(fileHeader(1:7),meg4_headers(:,1:7),'exact'))
ds.meg4.header=meg4_headers(1,1:7);
fprintf('addCTFtrial: meg4 header=%s ?\n',fileHeader);
return
end
% Create the .res4 file in the output dataset.
ds.res4=writeRes4([path,baseName,'.ds\',baseName,'.res4'],ds.res4,MAX_COILS);
if ds.res4.numcoef<0
fprintf('addCTFtrial: writeRes4 returned ds.res4.numcoef=%d (<0??)\n',ds.res4.numcoef);
fprintf(' Deleting dataset %s\n',baseName);
rmdir([path,baseName,'.ds'],'s');
return
end
% Add trial(s) to the existing meg4 file. Complicated coding in case the use requests
% writing several trials, which fill up one meg4 file and start the next one.
ptsPerTrial=nSample*nChan;
data=reshape(data,ptsPerTrial,nTrialNew);
maxTrialPerFile=floor((maxMEG4Size-8)/(4*ptsPerTrial));
maxPtsPerFile=ptsPerTrial*maxTrialPerFile;
nExt=-1;
trial=0;
pt=0;
while trial<nTrialNew
nExt=nExt+1;
if nExt==0
meg4Ext='.meg4';
else
meg4Ext=['.',int2str(nExt),'_meg4'];
end
meg4File=[path,baseName,'.ds\',baseName,meg4Ext];
D=dir(meg4File);
if isempty(D)
% Create the next meg4 file and write the header.
fidMeg4=fopen(meg4File,'w','ieee-be');
fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8');
fclose(fidMeg4);
D=struct('bytes',8);
end
nWrite=min(nTrialNew-trial,floor((maxMEG4Size-D.bytes)/(4*ptsPerTrial)));
%fprintf('nExt=%d meg4File=%s\n\t\tsize=%d bytes nWrite=%d\n',nExt,meg4File,D.bytes,nWrite);
if nWrite>0
fidMeg4=fopen(meg4File,'a','ieee-be');
endPt=pt+nWrite*ptsPerTrial;
while pt<endPt
pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is
fwrite(fidMeg4,double(data(pt+1:pt1)),'int32'); % single. This may cause memory
pt=pt1; % problems so write in short pieces.
end
fclose(fidMeg4);
trial=trial+nWrite;
end
end
clear trial pt meg4Ext meg4File D fidMeg4 nWrite endPt pt1;
% Set variable cntrl to indicate that the meg4 and res4 files have been updated.
cntrl=1;
% Update the .meg4 part of structure ds.
ds.meg4.fileSize=8*(nExt+1);
clear data pt pt1 ndata fidMeg4;
% Add dataset names to .hist, and write new .hist file.
if ~isfield(ds,'hist');
ds.hist=char([]);
else
q0=max(strfind(ds.hist,originalCreatorSoftware));
if ~isempty(q0) & isempty(strfind(ds.hist(q0:length(ds.hist)),creatorSoftware))
ds.hist=[ds.hist(1:q0+length(originalCreatorSoftware)-1) ', ' creatorSoftware ...
ds.hist(q0+length(originalCreatorSoftware):length(ds.hist))];
end
% Create .hist file
histfile=[path,baseName,'.ds\',baseName,'.hist'];
fid=fopen(histfile,'w');
fwrite(fid,ds.hist,'char');
fclose(fid);
end
% Add HLC data and write new infods file.
if isfield(ds,'infods')
ds.infods=updateHLC(ds.infods,HLCdata);
writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods);
end
clear HLCdata;
% New .newds file.
if isfield(ds,'newds')
fid=fopen([path,baseName,'.ds\',baseName,'.newds'],'w');
fwrite(fid,ds.newds,'char');
fclose(fid);
end
% Add markers, and create new MarkerFile.mrk
if isfield(ds,'mrk')
mrk=combineMarkers(ds.mrk,nTrialOld,mrk,nTrialNew,ds.res4);
if ~isempty(mrk)
writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],mrk);
end
elseif ~isempty(mrk)
fprintf(['addCTFtrial: Existing dataset has no MarkerFile, but structure mrk is',...
' specified in call to addCTFtrial.\n',...
' MarkerFile.mrk not created.\n']);
end
% bad.segments file
if isfield(ds,'badSegments') & ~isempty(badSegments)
ds.badSegments.trial=[ds.badSegments.trial badSegments.trial+nTrialOld];
ds.badSegments.StartTime=[ds.badSegments.StartTime badSegments.StartTime];
ds.badSegments.EndTime=[ds.badSegments.EndTime badSegments.EndTime];
writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,...
ds.res4.no_trials,nSample/fSample);
end
% ClassFile. Add trial classes, and create new ClassFile.cls
if ~isempty(cls)
if isfield(ds,'TrialClass')
cls=combineClasses(ds.TrialClass,nTrialOld,cls,nTrialNew);
if ~isempty(cls)
writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],cls);
end
else
fprintf(['addCTFtrial: Existing dataset has no ClassFile, but structure cls is',...
' specified in call to addCTFtrial.\n',...
' ClassFile.cls not created.\n']);
end
end
return
% *************** End of function addCTFtrial ********************************************
% **************************************************************************************
% **************************************************************************************
% ************* function make_dummy_infods*********************************************
function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate);
% If the user does not supply ds.infos, this code makes a dummy version. It has all of
% the tags that Acq created in file Richard_SEF_20060606_04.infods.
% ***********************************************************************************
% ***********************************************************************************
DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006
fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n');
Tag(1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x');
Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000');
Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,...
'data','20060606164306');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,...
'data','19000100000000');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042');
Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,...
'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,...
'data','Unknown');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,...
'data','Dummy infods.');
Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
if exist_hc
nominalPositions=0; % Measured
else
nominalPositions=1; % Nominal
end
Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,...
'data',nominalPositions);
Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
'data','ds.res4.scrr');
Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
'data','ds.res4.senres');
%Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef');
%Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled');
Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',...
round(0.25*sample_rate));
Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0);
if exist_HLC
HZ_MODE=5;
elseif exist_hc
HZ_MODE=1;
else
HZ_MODE=DATASET_HZ_UNKNOWN;
end
Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE);
Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
return
% ************* End of function make_dummy_infods*********************************************
% **************************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function combineMarkers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mrkNew=combineMarkers(mrkOld,nTrialOld,mrk,nTrialNew,res4);
% Combines existing marker information with markers for new trial(s) being added to the
% dataset ny addCTFtral.
% Start by examining the new markers defined in structure mrk.
% Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk.
% Output: mrkNew : New marker structure. If the new markers are invlaid, or empty, then
% mrkNew=struct([]) is returned.
MarkerFileOK=~isempty(mrk);
if MarkerFileOK
if isempty([mrk.trial]) | isempty([mrk.time])
MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty.
else
% Are the markers appropriate?
minMarkerTrial=min(min([mrk.trial]));
maxMarkerTrial=max(max([mrk.trial]));
minMarkerTime=min(min([mrk.time]));
maxMarkerTime=max(max([mrk.time]));
MarkerFileOK=(maxMarkerTrial<=nTrialNew & minMarkerTrial>=1 & ...
maxMarkerTime<=(res4.no_samples/res4.sample_rate) & ...
minMarkerTime>=(-res4.preTrigPts/res4.sample_rate));
if ~MarkerFileOK
fprintf(['addCTFtrial: Structure mrk cannot possibly be a set of markers ',...
'for %d trial(s) in array(data).\n'],nTrialNew);
fprintf([' minMarkerTrial=%d (must be >=1) ',...
'maxMarkerTrial=%d (must be <=%d)\n'],...
minMarkerTrial,maxMarkerTrial,ds.res4.no_trials);
fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',...
'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],...
minMarkerTime,-res4.preTrigPts/res4.sample_rate,...
maxMarkerTime,res4.no_samples/res4.sample_rate);
fprintf(' MarkerFile.mrk will not be updated.\n');
end
end
end
if MarkerFileOK==0
mrkNew=struct([]); % return an empty marker structure
% Check mrkOld to see if each existing trial had at least one marker.
if isequal(unique([mrkOld.trial]),[1:nTrialOld])
fprintf(['addCTFtrial: All of the trials in the existing data have at least one\n',...
' marked point,but the new trials have no marker points?\n']);
end
return
end
% There are valid new markers. Add the new markers to the existing marker structure,
% and extend the marker definition if new markers have been defined.
% Check the Name
mrkNew=mrkOld;
maxClassId=max([mrkNew.ClassId]);
for k=1:length(mrk)
addq=1;
% Check if the marker is already defined.
for q=1:length(mrkOld)
if strcmp(mrkOld(q).Name,mrk(k).Name)
mrkNew(q).trial=[mrkNew(q).trial mrk(k).trial+nTrialOld];
mrkNew(q).time=[mrkNew(q).time mrk(k).time];
addq=0;
break;
end
end
if addq % Create a new marker class
newClassId=~isfield(mrk(k),'ClassId');
if ~newClassId
newClassId=any(mrk(k).ClassId==[mrkNew.ClassId]);
end
if newClassId
mrk(k).ClassId=max([mrkNew.ClassId])+1;
end
if ~isfield(mrk(k),'Color');mrk(k).Color='Red';end
if ~isfield(mrk(k),'Comment');mrk(k).Comment=char([]);end
if ~isfield(mrk(k),'ClassGroupId');mrk(k).ClassGroupId=3;end
if mrk(k).ClassGroupId==0
if ~isfield(mrk(k),'BitNumber') | ~isfield(mrk(k),'Polarity') | ...
~isfield(mrk(k),'Source') | ~isfield(mrk(k),'Threshold')
fprintf(['addCTFtrial: Structure mrk defines ClassGroupId=0 marker %s, ',...
'but not fields BitNumber, Polarity, Source or Threshold.\n'],mrk(k).Name);
fprintf(' Marker set %s will be defined with ClassGroupId=3.\n',...
mrk(k).Name);
mrk(k).ClassGroupId=3;
end
end
% ClassGroupId : make 4 fields empty.
if mrk(k).ClassGroupId==3
mrk(k).BitNumber=[];
mrk(k).Polarity=[];
mrk(k).Source=[];
mrk(k).Threshold=[];
end
q0=length(mrkNew)+1;
mrkNew(q0)=mrk(k);
mrkNew(q0).trial=mrk(k).trial+nTrialOld;
mrkNew(q0).time=mrk(k).time;
end
clear addq;
end
return
%%%%%%%%%%%%%% end of combineMarkers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial);
% Creates a bad.segments file in a CTF data set from the information in structure
% badSegments which is created by read_badSegments, or by the user.
% If structure badSegments is empty, then the file is not created.
% badSegments structure:
% badSegments.trial = List of trial numbers
% badSegments.StartTime = List of bad segment start times (relative to trial).
% badSegments.EndTime = List of bad segment end times.
% Check badSegmentsFile
if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end
if isempty(badSegmentsFile) | ~ischar(badSegmentsFile)
fprintf('addCTFtrial(writeBadSegments): Bad file name.\n');
badSegmentsFile
return
end
% Check that structure badSegments is defined correctly
if exist('badSegments')~=1 | exist('nTrial')~=1
return
elseif ~isstruct(badSegments) | isempty(badSegments)
return
elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ...
~isfield(badSegments,'EndTime')
return
elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ...
isempty(badSegments.EndTime)
return
elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),...
size(badSegments.EndTime))
fprintf(['\naddCTFtrial (writeBadSegments): ',...
'The fields of structure badSegments do not all have the same size.\n']);
return
elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ...
any(badSegments.StartTime<0) | any(badSegments.EndTime>tTrial)
fprintf(['\naddCTFtrial (writeBadSegments): badSegments cannot possibly describe ',...
'bad segments for these data.\n',...
'\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',...
'min(badSegments.StartTime)=%0.4f max(badSegments.EndTime)=%0.4f s\n\t\tDataset:',...
' nTrial=%d tTrial=%0.4f s\n'],...
min(badSegments.trial),max(badSegments.trial),min(badSegments.StartTime),...
max(badSegments.EndTime),nTrial,tTrial);
fprintf('\t\tNew bad.segments file will not be created.\n\n');
return
end
% Convert all fields to simple vectors
nSeg=prod(size(badSegments.trial));
trial=reshape(badSegments.trial,1,nSeg);
StartTime=reshape(badSegments.StartTime,1,nSeg);
EndTime=reshape(badSegments.EndTime,1,nSeg);
fid=fopen(badSegmentsFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile);
return
end
% Extra tabs are inserted to reproduce the format of bad.segments files produced by
% DataEditor (5.3.0-experimental-linux-20060918).
fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]);
fclose(fid);
return
%%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function checkCls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ClassFileOK=checkCls(ds);
% Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass.
ClassFileOK=isfield(ds,'TrialClass');
if ClassFileOK
ClassFileOK=~isempty(ds.TrialClass);
end
if ClassFileOK
% Are the class trials appropriate?
minClassTrial=[];
maxClassTrial=[];
for k=1:length(ds.TrialClass)
maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]);
minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]);
end
% Create ClassFile.cls even when the trail classes are empty.
if ~isempty(maxClassTrial)
ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1);
if ~ClassFileOK
fprintf(['\nwriteCTFds (checkCls): ds.TrialClass cannot possibly be a set of ',...
'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',...
'maxClassTrial=%d (must be <=%d)\n'],...
minClassTrial,maxClassTrial,ds.res4.no_trials);
fprintf(' ClassFile.cls will not be created.\n');
end
end
end
return
%%%%%%%%%%%%%% end of checkCls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function combineClasses %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function clsNew=combineClasses(clsOld,nTrialOld,cls,nTrialNew);
% Combines existing trial class information with classes for new trial(s) that are
% being added to the dataset by addCTFtral.
% Start by examining the new markers defined in structure mrk.
% Examines structure ds to see if a sensible CLassFile can be created from clsOld and cls.
% Output: clsNew : New class structure. If the new classes are invalid, or empty, then
% clsNew=struct([]) is returned.
ClassFileOK=~isempty(cls);
if ClassFileOK
if isempty([cls.trial])
ClassFileOK=0; % Do not create ClassFile.cls if all of the trial classes are empty.
else
% Are the markers appropriate?
minClassTrial=min(min([cls.trial]));
maxClassTrial=max(max([cls.trial]));
ClassFileOK=(maxClassTrial<=nTrialNew & minClassTrial>=1);
if ~ClassFileOK
fprintf(['addCTFtrial: Structure cls cannot possibly be a set of classes ',...
'for %d trial(s) in array data .\n'],nTrialNew);
fprintf([' minClassTrial=%d (must be >=1) ',...
'maxClassTrial=%d (must be <=%d)\n'],...
minClassTrial,maxClassTrial,nTrialNew);
fprintf(' ClassFile.cls will not be updated.\n');
end
end
end
if ClassFileOK==0
clsNew=struct([]); % return an empty class structure
% Check clsOld to see if each existing trial had at least one class.
if isequal(unique([clsOld.trial]),[1:nTrialOld])
fprintf(['addCTFtrial: All of the trials in the existing data are assigned to at ',...
'least one class\n',...
' but the new trials have no classes?\n']);
end
return
end
% There are valid new classes. Add the new classes to the existing class structure,
% and extend the class definition if new classes have been defined.
clsNew=clsOld;
maxClassId=max([clsNew.ClassId]);
for k=1:length(cls)
addq=1;
% Check if the class is already defined.
for q=1:length(clsOld)
if strcmp(clsOld(q).Name,cls(k).Name)
clsNew(q).trial=[clsNew(q).trial cls(k).trial+nTrialOld];
addq=0;
break;
end
end
if addq % Create a new trial class
newClassId=~isfield(cls(k),'ClassId');
if ~newClassId % Check if cls(k).ClassId is already in use.
newClassId=any(cls(k).ClassId==[clsNew.ClassId]);
end
if newClassId
cls(k).ClassId=max([clsNew.ClassId])+1;
end
if ~isfield(cls(k),'Color');cls(k).Color='Red';end
if ~isfield(cls(k),'Comment');cls(k).Comment=char([]);end
if ~isfield(cls(k),'ClassGroupId');cls(k).ClassGroupId=3;end
q0=length(clsNew)+1;
clsNew(q0)=cls(k);
clsNew(q0).trial=cls(k).trial+nTrialOld;
end
clear addq;
end
return
%%%%%%%%%%%%%% end of combineClasses %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeClassFile(ClassFile,TrialClass);
% Write the ClassFile of a CTF data set.
% The CLassFile allows a user to store a list of trial classifications in a data set.
% The ClassFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid.
% Inputs :
% ClassFile : marker file including the full path and extension .mrk.
% TrialClass : Structure creted by read_ClassFile.
% Output : ClassFile.cls.
% Check input TrialClass.
if exist('TrialClass')~=1;TrialClass=[];end
if isempty(TrialClass) | ~isstruct(TrialClass)
fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n');
TrialClass
return
end
% Check ClassFile
if exist('ClassFile')~=1;ClassFile=char([]);end
if isempty(ClassFile) | ~ischar(ClassFile)
fprintf('writeCTFds (writeClassFile): Bad file name.\n');
ClassFile
end
fid=fopen(ClassFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile);
return
end
nClass=length(TrialClass);
% Generate datasetname from ClassFIle.
ksep=max([0 strfind(ClassFile,filesep)]);
datasetname=ClassFile(1:ksep-1);
if isempty(datasetname);datasetname=cd;end
fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname);
fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass);
for k=1:nClass
if k==1 % Add sign character to make output match the output of Acq.
sgn=char([]); % There should be no real significance to this.
else % Why does DataEditor places the + sign only on ClassID 2,3,...?
sgn='+';
end
No_of_Trials=prod(size(TrialClass(k).trial));
fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',...
sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment);
fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',...
TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials);
fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n');
% Subtract one so trial numbering starts at 0 in ClassFile.cls
fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1);
fprintf(fid,'\n\n');
end
fclose(fid);
return
%%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateCreatorSoftware %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateCreatorSoftware(ds,creatorSoftware,originalCreatorSoftware);
% Changes the creator software fields of the ds structure, and returns ds=struct([]) if
% field infods is missing from structure ds, or if it thinks that the dataset was not
% created by the MATLAB code specified by originalCreatorSoftware (i.e. writeCTFds).
% Makes sure that creatorSoftware info is changed in structure infods, newds and res4.
% Inputs: ds : ds structure produced by readCTFds.
% creatorSoftware : Character string indicating that the data set was
% modified by addCTFtrial. Added to infods tags listed in addCreatorTag and
% appName field of res4.
% originalCreatorSoftware : Character string indicating that the data set was
% created by writeCTFds. Added to infods tags listed in addCreatorTag and
% appName field of res4.
% Output: ds : ds structure with changes to ds.infids, ds.res4, ds.newds.
% If the input ds structure does not indicate that iot was created by
% writeCTFds (originalCreatorSoftware), ds=struct([]) is returned.
% Adds comment (clinical use message) and creator software name to infods, newds and hist files.
if ~isfield(ds,'infods');
fprintf(['addCTFtrial (updateCreatorSoftware): Structure ds does not include',...
' field infods.\n']);
whos ds
ds=struct([]); % Force an error in the calling program
return
end
% The infods tags and red4 fields that display creator software must also indicate that
% the dataset was created by originalCreatorSoftware.
% infods tags that will display the creator software.
addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',...
'_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE');
% res4 text fields that will display the creator software.
addCreatorField=strvcat('appName','run_description');
addCreatorLength=[256 -1]'; % -1 indicates variable length
if exist('creatorSoftware')~=1;
creatorSoftware=char([]);
elseif ~ischar(creatorSoftware)
creatorSoftware=char([]);
else
creatorSoftware=deblank(creatorSoftware);
end
if exist('originalCreatorSoftware')~=1;
originalCreatorSoftware=char([]);
elseif ~ischar(originalCreatorSoftware)
originalCreatorSoftware=char([]);
else
originalCreatorSoftware=deblank(originalCreatorSoftware);
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check that the string originalCreatorSoftware appears in the infods and res4 files.
tagName=getArrayField(ds.infods,'name')';
if length(ds.infods)==1;tagName=tagName';end
% Update the infods fields.
for k=1:size(addCreatorTag,1)
q=strmatch(deblank(addCreatorTag(k,:)),tagName);
if isempty(q);
fprintf('addCTFtrial (updateCreatorSoftware): Tag %s is missing from ds.infods.\n',...
deblank(addCreatorTag(k,:)));
ds=struct([]);
return
elseif length(q)>1
fprintf(['addCTFtrial (updateCreatorSoftware): Tag %s appears %d times in ',...
'ds.infods.\n'],deblank(addCreatorTag(k,:)),length(q));
ds=struct([]);
return
else
strng=ds.infods(q).data;
% Strng must contain originalCreatorSoftware
nChar=length(strng);
if length(originalCreatorSoftware)>0
qpos=strfind(strng,originalCreatorSoftware);
if isempty(qpos)
fprintf(['addCTFtrial (updateCreatorSoftware): String %s does not appear in',...
' ds.infods tag %s\n'],originalCreatorSoftware,addCreatorTag(k,:));
fprintf([' This dataset was not created ',...
'by CTF MATLAB Export software.\n']);
ds=struct([]);
return
end
qpos=qpos+length(originalCreatorSoftware)-1;
else
qpos=length(strng);
end
% Add creatorSoftware string if it is not already present.
if isempty(strfind(strng,creatorSoftware))
ds.infods(q).data=[strng(1:qpos) ' ' creatorSoftware ' ' strng(qpos+1:nChar)];
end
end
end
% Update the res4 fields: add creatorSoftware message.
% Don't check field length. Truncate later.
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
nChar=length(strng);
if length(originalCreatorSoftware)>0
qpos=strfind(strng,originalCreatorSoftware);
if isempty(qpos)
fprintf(['addCTFtrial (updateCreatorSoftware): String %s does not appear in',...
' ds.res4.%s\n'],originalCreatorSoftware,deblank(addCreatorField(q,:)));
fprintf([' This dataset was not created ',...
'by CTF MATLAB Export software.\n']);
ds=struct([]);
return
end
qpos=qpos+length(originalCreatorSoftware);
else
qpos=nChar;
end
% Add creatorSoftware string if it is not already present.
if isempty(strfind(strng,creatorSoftware))
newStrng=[strng(1:qpos) ' ' creatorSoftware ' ' strng(qpos+1:nChar)];
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng);
end
end
clear q strng nChar strng0 ns newStrng;
% Update res4.run_description
ds.res4.run_description=[deblank(ds.res4.run_description),char(0)];
ds.res4.rdlen=length(ds.res4.run_description);
% Truncate the .res4. fields. Leave room for a final char(0).
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),...
strng(length(strng)+[-addCreatorLength(q)+2:0]));
end
end
clear q strng;
% Add the creator and comment information to the newds file
if isfield(ds,'newds');
nChar=length(ds.newds);
% Keyword positions
aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)]));
if isempty(aNpos)
fprintf(['addCTFtrial (updateCreatorSoftware): Keyword ''appName'' ',...
'does not appear in ds.newds.\n',...
' set ds.newds=[].\n']);
ds.newds=char([]);
else
eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]);
wPos=min(strfind(ds.newds(aNpos+[1:eol]),originalCreatorSoftware));
addPos=min(strfind(ds.newds(aNpos+[1:eol]),creatorSoftware));
if isempty(addPos)
if isempty(wPos)
ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ...
ds.newds((aNpos+eol):length(ds.newds))];
else
ds.newds=[ds.newds(1:(aNpos+wPos+length(originalCreatorSoftware)-1)) ', ' ...
creatorSoftware ...
ds.newds((aNpos+wPos+length(originalCreatorSoftware)):length(ds.newds))];
end
end
clear eol wPos addPos;
end
clear nChar aNpos;
end
return
%%%%%%%%%%%%%% End of update_creatorSoftware %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [infods,status]=updateHLC(infods,HLCdata,HLC0,nTrial0);
% Adds notes and continuous-head-localization tags to .infods file.
% Updates MAXHEADMOTION tags when called from addCTFtrial
% Inputs : infods : Structure of tags to be written to output infods file.
% HLCdata : 0 or [] or not defined - There are no HLC channels
% (head-coil position) in the data. Just pass the existing tags to
% the output dataset.
% HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial]
% Calculate the head motion tags.
% HLC0 : Head coil positions (m) in dewar coordinates at the start of the run.
% size(HLC0)=[3 Ncoil]
% nTrial0=No. of trials of data already written to the dataset.
% Outputs : status : 0: Everything looks OK
% 1: Couldn't find _DATASET tags.
% <0: There is a problem with the new infods file.
% Calls:
% - getArrayField: Extracts field names from structure array S.
% Defaults for the head localization tags.
% Might do this better with a structure.
HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006
% Should be -1.
% New dataset tags for HLC specification.
addTag=strvcat('_DATASET_HZ_MODE',...
'_DATASET_MOTIONTOLERANCE',...
'_DATASET_MAXHEADMOTION',...
'_DATASET_MAXHEADMOTIONTRIAL',...
'_DATASET_MAXHEADMOTIONCOIL');
addTagType=[5 4 4 7 10]';
if exist('nTrial0')~=1
nTrial0=0;
elseif isempty(nTrial0)
nTrial0=0;
elseif min(nTrial0)<0
nTrial0=0;
end
% Check HLCdata array. HLCdata=[] indicates no continuous head localization.
if exist('HLCdata')~=1
HLCdata=[];
elseif ~isempty(HLCdata)
[samplesPerTrial nDim Ncoil nTrial]=size(HLCdata);
if nDim~=3;
fprintf('addCTFtrial (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata));
fprintf(']\n');
fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim);
HLCdata=[];
end
end
if exist('HLC0')~=1
HLC0=[];
elseif ~isequal(size(HLC0),[3 size(HLCdata,3)])
HLC0=[];
end
if isempty(HLC0) & ~isempty(HLCdata)
HLC0=squeeze(HLCdata(1,:,:,1));
end
% Assume that all the tag names are different. There is no checking when a tag listed in
% addTag matches more than one entry in array name.
name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag]
DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag]
if isempty(DATASET_tags)
status=1; % No _DATASET tags. Don't add anything.
else
status=0;
if isempty(HLCdata)
TagValue(1)=HZ_MODE_UNKNOWN;
TextTagValue=char(0);
addTag=addTag(1,:); % Remove the other HLC tags
addTagType=addTagType(1);
else % ~isempty(HLCdata)
% Remove HLC offsets.
for q=1:Ncoil
for k=1:3
HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLC0(k,q);
end
end
% Calculate motions as displacement from the start of the dataset.
absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial]
maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial]
maxHeadMotion=max(max(maxCoilMotion));
[mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2));
[mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1));
% Create a list of head motion tag values
TagValue(1)=5; % Indicates continuous head localization
TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE
TagValue(3)=maxHeadMotion;
TagValue(4)=maxHeadMotionTrial-1+nTrial0; % _DATASET_MAXHEADMOTIONTRIAL
TextTagValue=strvcat(char(zeros(4,1)),sprintf('%d',maxHeadMotionCoil));
% Does the existing infods have the head-motion tags?
TagNo2=strmatch(deblank(addTag(2,:)),name,'exact');
TagNo3=strmatch(deblank(addTag(3,:)),name,'exact');
TagNo4=strmatch(deblank(addTag(4,:)),name,'exact');
TagNo5=strmatch(deblank(addTag(5,:)),name,'exact');
if ~isempty(TagNo2) & ~isempty(TagNo3) & ~isempty(TagNo4) & ...
~isempty(TagNo5) & nTrial0>0
% Structure infods already has the head-motions tags from previous data.
TagValue(2)=max(TagValue(2),infods(TagNo2).data);
if TagValue(3)<=infods(TagNo3).data
TagValue(3)=infods(TagNo3).data;
TagValue(4)=infods(TagNo4).data;
TextTagValue=strvcat(char(zeros(4,1)),infods(TagNo5).data);
end
elseif (~isempty(TagNo2) | ~isempty(TagNo3) | ~isempty(TagNo4) | ...
~isempty(TagNo5)) & nTrial0>0
fprintf(['addCTFtrial (updateHLC): Some, but not all, of the ds.infods CHL ',...
'tags are defined.\n',...
' Infods will be defines with information from the %d new ',...
'trial(s) being added.\n'],size(HLCdata,4));
end
TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string.
end
% Add or insert tags.
for q=1:size(addTag,1)
nTag=length(infods);
tagName=deblank(addTag(q,:));
TagNo=strmatch(tagName,name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
infods((TagNo+1):(nTag+1))=infods(TagNo:nTag);
name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
end
if addTagType(q)~=10
infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q));
else
infods(TagNo)=struct('name',tagName,'type',addTagType(q),...
'data',deblank(TextTagValue(q,:)));
end
end % End loop over head position and head motion tags.
clear q TagNo TextTagValue TagValue;
end % End section add _DATASET tags
return
%%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=getArrayField(S,yfield)
% Extracts one field of a structure array.
% Inputs: S : structure array.
% yfield: name of field of S (string)
% Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)]
% Field sizes: Two options:
% 1. size(S(n).yfield) is the same for all n. Any size allowed.
% 2. S(n).yfield is a 2-D array for all structure elements S(n).
% Then yfield of different array elements S(n) can have different sizes.
% The array returned will be large enough to accomodate all of the data.
sizeS=size(S);
nS=prod(sizeS);
S=reshape(S,1,nS);
% Determine which array-size option to use.
sizey=size(getfield(S,{1},yfield));
option1=1;
option2=(length(sizey)==2);
for n=2:nS
sizeyn=size(getfield(S,{n},yfield));
option1=option1 & isequal(sizey,sizeyn);
option2=option2 & length(sizeyn)==2;
if option2
sizey=max([sizey;sizeyn],[],1);
end
end
if option1 % All fields have the same size
nY=prod(sizey);
if isnumeric(getfield(S,{1},yfield))
x=zeros(nY,nS);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros(nY,nS));
end
for n=1:nS
x(:,n)=reshape(getfield(S,{n},yfield),nY,1);
end
x=reshape(x,[sizey nS]);
elseif option2 % All fields have only two dimensions
if isnumeric(getfield(S,{1},yfield))
x=zeros([sizey nS]);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros([sizey nS]));
end
for n=1:nS
y=getfield(S,{n},yfield);
sizeyn=size(y);
x(1:sizeyn(1),1:sizeyn(2),n)=y;
end
else
fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',...
'and not all field have the same size.\n'],yfield);
x=[];
end
x=squeeze(x);
return
%%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
setCTFDataBalance.m
|
.m
|
antx-master/xspm8/external/ctf/setCTFDataBalance.m
| 32,056 |
utf_8
|
894c3744554abe635876ce6944dca0cd
|
function [data,ds]=setCTFDataBalance(data,ds,balance1,unit,chanList,messages);
% Version 1.1 13 April 2007 Mod to chanList: If chanList is omitted and
% size(data,2)<ds.res4.no_channels, then setCTFDataBalance
% sets chanList=1:size(data,2) and prints a warning the first
% time it happens.
% 7 Dec. 2006. Fixed a bug. Changed calls to getCTFBalanceCoefs so
% setCTFDataBalance would balance and unbalance reference gradiometers.
% Version 1.0 27 October 2006
% Adjusts the gradient order balance from balance0 to balance1.
% Inputs :
% data : Array of data to be balanced. precision= single or double.
% size(data)=[Npt Nchan Ntrial]. If chanList is not supplied, it is assumed that
% array data has dataset channels 1:Nchan (i.e. data is not just SQUID sensors
% although only SQUID channels are affected by setCTFDataBalance.)
% ds : Structure produced by readCTFds that describes the dataset.
% balance1 : Character array defining balance of the output data.
% Parameter balance1 must be specified, even if it is only balance1=[];
% balance1=[],' ' or 'NONE' : Output is unbalanced.
% size(balance,1)=1 : MEG balancing. Assume no reference balancing.
% size(balance,1)=2 : MEG balance = balance(1,:).
% Gref balance = balance(2,:)
% unit : Options : [],' ', 'fT', or 'T' : Physical unit
% 'int' or 'phi0' : Raw units.
% If the unit argument is not included, unit is set to 'fT'.
% chanList : Optional list of dataset channels included in array data.
% Channel numbering is referred to structure ds (the output of readCTFds).
% If length(chanList)=Nchan.
% data(:,k,q)=trial q of channel chanList(k) of the dataset.
% If chanList=[],<0 or not defined : Array data has dataset channels 1:Nchan.
% Otherwise, length(chanList)=Nchan=size(data,2).
% If length(chanList)~=size(data,2) : Error.
% messages=0: Don't print tracing message
% =1: Print a message when there is a change in requested balance.
% =2: Always print a message
% Outputs: data: Data with balanced SQUID signals. Set data=[] on failure.
% ds: ds structure for balanced data. Set ds=-1 on failure.
% In any event, print error messages.if exist('messages')~=1;messages=1;end
% The balance and unbalance is made complicated because this code allows for situations
% where the reference gradiometers are also balanced (although this option seems never
% to be used).
% Function calls: Most functions are called only once, and are intended to be
% called only by setCTFDataBalance or its subprograms.
% - getCTFBalanceCoefs. Called by balance_data and unbalance_data. Gets the balance
% tables from structure ds.
% Included in this listing:
% - getDsBalance: Gets the current balance state of the data and checks for error in
% the grad_order_no field of ds.rs4.senres.
% - check_balance : Makes balance1 into [2 4] character arrays.
% - unbalance_data : Converts data from balance0 to unbalanced.
% - balance_data: Converts data from unbalanced to balance1.
% - reindex : Called by functions unbalance_data and balance_data to re-order indices
% when chanList does not include all the channels, or the channels have
% been reordered in array data.
% If virtual memory is a problem, consider bringing functions balance_data and
% unbalance_data into the code. In the present configuration, a copy of array data is
% made when these functions are called.
% In the event of an error, returns data=[], ds1=-1 This should force an error in the
% calling program.
persistent chanListWarning
if nargout==0 & nargin==0
fprintf(['\nsetCTFDataBalance: Version 1.1 13 April 2007 ',...
'Balances MEG data.\n',...
'\t\tCall : ',...
'[data1,ds1]=setCTFDataBalance(data0,ds0,balance1,unit,chanList,messages);\n\n']);
return
end
buffsize=6e6; % process blocks of buffsize words (=8*buffsize bytes) at a time
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR');
unit_options=strvcat('fT','T','phi0','int');
default_unit='fT';
% Check that the inputs are sensible.
if nargin<3
fprintf(['\nsetCTFDataBalance: Only %d input arguments? ',...
'Must specify at least data, ds and balance.\n\n'],nargin);
data=[];ds=-1;
return
elseif ~any(strmatch(class(data),strvcat('single','double'))) | isempty(data) | ...
~isstruct(ds) | isempty(ds) | isempty(balance1) |~ischar(balance1)
fprintf('\nsetCTFDataBalance: Wrong argument types or sizes.\n\n');
whos data ds balance1
data=[];ds=-1;
return
elseif ~isfield(ds,'res4')
fprintf('\nsetCTFDataBalance: Field res4 is missing from structure ds.\n\n');
ds
data=[];ds=-1;
return
end
if nargout~=2
fprintf(['\nsetCTFDataBalance: %d output arguments specified. ',...
'Must have 2 outputs (data,ds).\n\n'],nargout);
data=[];ds=-1;
return
end
% Single or double precision data.
prec=class(data);
% Force upper-case characters
balance1=upper(balance1);
% Check that arrays data and chanList are consistent and sensible
if size(data,2)>ds.res4.no_channels
fprintf('\nsetCTFDataBalance: ds.res4.no_channels=%d, but size data=[',...
ds.res4.no_channels);
fprintf(' %d',size(data));fprintf(']\n\n');
data=[];ds=-1;
return
end
if exist('chanList')~=1;chanList=[];end
if ~isempty(chanList) % chanList~=[]. Check chanList
if ~isnumeric(chanList)
fprintf('\nsetCTFDataBalance: chanList has the wrong type.\n\n');
whos data ds balance1 chanList
data=[];ds=-1;
return
else % chanList is numeric and non-empty
% Check that chanList is a vector
if sum(size(chanList)>1)>1
fprintf('\nsetCTFDataBalance: size(chanList)=[');fprintf(' %d',size(chanList));
fprintf('] Not a vector.\n\n');
data=[];ds=-1; % Force an error in the calling program
return
else
chanList=reshape(chanList,1,length(chanList)); % chanList is a row vector.
if any(chanList<=0) | any(chanList>ds.res4.no_channels) | ...
length(chanList)~=size(data,2)
fprintf('setCTFDataBalance: Error in input chanList:\n');
fprintf(' min(chanList)=%d max(chanList)=%d Dataset has %d channels.\n',...
min(chanList),max(chanList),ds.res4.no_channels);
fprintf('length(chanList)=%d size(data)=[',length(chanList));
fprintf(' %d',size(data));
fprintf('] Must have length(chanList)=size(data,2)\n');
data=[];ds=-1; % Force an error in the calling program
return
end
end
end
else % chanList=[]. Array data must include all of the channels.
if size(data,2)<ds.res4.no_channels
if isempty(chanListWarning)
fprintf('setCTFDataBalance: No chanList supplied and size(data)=[');
fprintf(' %d',size(data));fprintf(']\n');
fprintf(' Set chanList=1:%d\n',size(data,2));
fprintf(' No. of channels=ds.res4.no_channels=%d\n',...
ds.res4.no_channels);
chanListWarning=1;
end
chanList=1:size(data,2);
end
end
% Check the data units, convert to lower case and flag incorrect unit specification
if ~exist('unit');
unit=default_unit;
elseif isempty(unit);
unit=default_unit;
elseif ~ischar(unit)
fprintf('\nsetCTFDataBalance: Input unit has the wrong type: class(unit)=%s\n\n',...
class(unit));
data=[];ds=-1;
return
end
unit=lower(unit);
if isempty(strmatch(unit,lower(unit_options)))
fprintf('\nsetCTFDataBalance: unit=%s. Must be one of',unit);
for k=1:size(unit_options,1);fprintf(' %s',unit_options(k,:));end;fprintf('\n');
data=[];ds=-1; % Force an error in the calling program
return
end
% Make sure message request is sensible. This is important only as a way of checking
% that the input list is sensible. The value of messages does not affect the output of
% setCTFDataBalance.
if exist('messages')~=1;messages=1;end
if ~isnumeric(messages)
fprintf(['\nsetCTFDataBalance: Input messages has the wrong type: ',...
'class(messages)=%s\n\n'],class(messages));
data=[];ds=-1;
return
elseif isempty(messages);
messages=1;
elseif ~isequal(size(messages),[1 1])
fprintf('\nsetCTFDataBalance: Input messages doesn''t make sense. size(messages)=[');
fprintf(' %d',size(messages));fprintf('] (Must be [1 1])\n\n');
data=[];ds=-1;
return
elseif messages<0 | messages>2
fprintf('\nsetCTFDataBalance: Input messages=%d. Must be [], 0, 1 or 2.\n\n',messages);
data=[];ds=-1;
return
end
% Process data in blocks of nChBlock channels to reduce virtual memory demand.
nChBlock=max(1,floor(buffsize/size(data,1)));
% badGref = list of bad reference gradiometers referred to dataset channel numbering.
% badGMEG = list of bad MEG gradiometers referred to dataset channel numbering.
% These gradiometers are considered bad because their grad_order_no is wrong, not
% because thay are listed in ds.BadChannels
[balance0,badGref,badGMEG,Greflist,GMEGlist]=getDsBalance(ds);
if strmatch('BAD',balance0)
fprintf(['\nsetCTFDataBalance: The balance order of the Grefs and/or the MEG ',...
'channels cannot be determined.\n',...
' Check ds.res4.senres().grad_order_no.\n\n']);
data=[];ds=-1; % Force an error in the calling program
return
end
% Check balance1 and put in a standard form.
balance1=check_balance(balance1);
if isempty(balance1) | isempty(balance0)
fprintf(['\nsetCTFDataBalance: size(ds balance) =[%d %d] (after call to ',...
'getDsBalance.)\n',...
' size(new balance)=[%d %d] (after call to check_balance.)\n\n'],...
size(balance0),size(balance1));
data=[];ds=-1; % Force an error in the calling program
return
end
% Print a message?
chanset=strvcat('MEGs','Grefs');
for k=1:2
if messages==2 | (messages==1 & ~strcmp(balance0(k,:),balance1(k,:)))
fprintf('setCTFDataBalance: Adjusting %s from balance=%s to balance=%s.\n',...
chanset(k,:),balance0(k,:),balance1(k,:));
end
end
clear k chanset;
if isequal(balance0,balance1)
return
end
% Convert from balance0 to unbalanced.
if ~isequal(balance0,strvcat('NONE','NONE'));
data=unbalance_data(data,ds,balance0,unit,nChBlock,chanList,badGref);
% unbalance_data returns data=[] when list badGref includes a Gref that is required for
% balancing.
if isempty(data);ds=-1;return;end
end
% Convert from unbalanced to balance1.
if ~isequal(balance1,strvcat('NONE','NONE'));
% balance_data returns data=[] when badGref includes a Gref that is required for
% balancing.
data=balance_data(data,ds,balance1,unit,nChBlock,chanList,badGref,messages);
if isempty(data);ds=-1;return;end
end
% Mark the balance order in structure ds.
% Make sure that the bad channels are marked with a different order. This will force
% errors if these data are used later. Set the data in the bad channels to zero, and add
% the bad channels to ds.BadChannels.
Gorder=strmatch(balance1(2,:),balanceOptions)-1;
MEGorder=strmatch(balance1(1,:),balanceOptions)-1;
for k=setdiff(Greflist,badGref)
ds.res4.senres(k).grad_order_no=Gorder;
end
for k=setdiff(GMEGlist,badGMEG)
ds.res4.senres(k).grad_order_no=MEGorder;
end
for k=badGref
ds.res4.senres(k).grad_order_no=0;
end
for k=badGMEG
ds.res4.senres(k).grad_order_no=round(3-MEGorder);
end
% Set channels with bad balance order parameter to zero.
kBad=[badGref badGMEG];
if ~isempty(chanList)
kBad=reindex(chanList,intersect(chanList,kBad));
end
for k=kBad
if strcmp(prec,'single')
data(:,k,:)=single(zeros(size(data,1),1,size(data,3)));
else
data(:,k,:)=zeros(size(data,1),1,size(data,3));
end
end
clear k Gorder MEGorder;
if isempty([badGref badGMEG]);return;end
% Add bad channels to ds.BadChannels
if ~isfield(ds,'BadChannels');ds.BadChannels=char([]);end
BadList=union(badGref,badGMEG);
if ~isempty(ds.BadChannels)
for k=1:size(ds.BadChannels,1)
BadList=[BadList strmatch(deblank(ds.BadChannels(k,:)),ds.res4.chanNames)];
end
ds.BadChannels=char([]);
end
for k=sort(BadList)
ds.BadChannels=strvcat(ds.BadChannels,strtok(ds.res4.chanNames(k,:),'- '));
end
return
% ************** End of function setCTFDataBalance **********************************
% **********************************************************************************
% ********************************************************************************
% ******************* function getDsBalance **************************************
function [dsbalance,badGref,badGMEG,Greflist,GMEGlist]=getDsBalance(ds);
% Get the current balance state from structure ds. Check for channels that are marked
% as bad by having a different grad_order_no.
% Check whether things make sense.
% Return the balance and lists of bad gradiometers.
% Also return the complete list of reference gradiometers and MEG gradiometers since
% setCTFDataBalance uses them.
% In normal operation, getDsBalance will return badGref=[], badGMEG=[];
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR');
Greflist=[]; % List of reference gradiometers (sensorTypeIndex=1)
Greforder=[];
GMEGlist=[]; % List of MEG gradiometers (sensorTypeIndex=5)
GMEGorder=[];
% Make lists of sensors and gradient balancing.
for k=1:ds.res4.no_channels
if ds.res4.senres(k).sensorTypeIndex==1
Greflist=[Greflist k];
Greforder=[Greforder ds.res4.senres(k).grad_order_no];
elseif ds.res4.senres(k).sensorTypeIndex==5
GMEGlist=[GMEGlist k];
GMEGorder=[GMEGorder ds.res4.senres(k).grad_order_no];
end
end
% Reference balance OK?
dsbalance=char(zeros(2,4));
if any(Greforder<0) | any(Greforder>1)
fprintf(['\nsetCTFDataBalance: The reference gradiometer balance orders make no ',...
'sense.\n %2d Gref channels. %2d have grad_order_no=0\n'],...
length(Greflist),sum(Greforder==0));
fprintf(' %2d have grad_order_no=1\n',sum(Greforder==1));
fprintf(' %2d have grad_order_no<0 or >1\n',...
sum(Greforder>1)+sum(Greforder<0));
dsbalance=strvcat(dsbalance(1,:),'BAD');
badGref=Greflist; % Mark everything bad
elseif sum(Greforder==0)>sum(Greforder==1)
dsbalance=strvcat(dsbalance(1,:),balanceOptions(1,:));
badGref=Greflist(find(Greforder~=0));
else
dsbalance=strvcat(dsbalance(1,:),balanceOptions(2,:));
badGref=Greflist(find(Greforder~=1));
end
% Sort MEG gradiometer balance. In correct operation, all MEG channels should have the
% same balance (0,1,2 or 3).
for bal=0:3
nMEGbal(bal+1)=sum(GMEGorder==bal);
end
[maxbal MEGorder]=max(nMEGbal);
MEGorder=MEGorder-1;
if maxbal>ceil(0.5*length(GMEGlist)) & all(GMEGorder>=0) & all(GMEGorder<=3)
dsbalance(1,:)=balanceOptions(MEGorder+1,:);
badGMEG=GMEGlist(GMEGorder~=MEGorder);
else
fprintf('\nsetCTFDataBalance: The MEG-sensor balance orders make no sense.\n');
fprintf(' %3d MEG gradiometer channels.\n',length(GMEGlist));
fprintf(' %3d have grad_order_no=%d\n',[nMEGbal;0:3]);
if sum(nMEGbal)<length(GMEGlist)
fprintf(' %3d have grad_order_no<0 or >3\n\n',...
length(GMEGlist)-sum(nMEGbal));
end
dsbalance=strvcat('BAD',dsbalance(2,:));
badGMEG=GMEGlist; % Mark everything bad`
end
return
% ************** End of function getDsBalance **********************************
% **********************************************************************************
% ********************************************************************************
% ******************* function check_balance **************************************
function balance=check_balance(balance);
% make sure that character array balance has the correct format.
balance_options=strvcat('NONE','G1BR','G2BR','G3BR');
% Make balance into a [4 2] character array
if ~ischar(balance) & ~isempty(balance)
fprintf('setCTFDataBalance (check_balance): balance is not a character array.\n');
balance=char([]); % Force an error.
return;
elseif isempty(deblank(balance))
balance=strvcat('NONE','NONE');
return
elseif size(balance,1)==1
balance=strvcat(balance,'NONE'); % No Gref balancing
elseif size(balance,1)>2
fprintf('setCTFDataBalance (check_balance): size(balance)=[%d %d]?\n',size(balance));
balance=char([]); % Force an error.
return
end
balance=upper(balance);
if size(balance,2)>4;balance=balance(:,1:4);end
for k=1:2 % k=1:MEGs, k=2:Grefs
if isempty(deblank(balance(k,:)));
balance(k,:)='NONE';
elseif isempty(strmatch(balance(k,:),balance_options(1:(6-2*k),:)))
fprintf('check_balance: balance(%d,:)=%s Not an allowed option.\n',k,balance(k,:));
balance=char([]); % Force an error?
return
end
end
return
% ************** End of function check_balance **********************************
% **********************************************************************************
% ************************************************************************
% ****** Convert from balanced to unbalanced data **********************
function data=unbalance_data(data,ds,balance0,unit,nChBlock,chanList,badGref);
% Inputs: data: Data array. size(data)=[Npt Nchan Ntrial]
% ds: ds strtcuture for the data.
% balance0: balance0(1,:) = MEG balance before unbalancing
% balance0(2,:) = Gref balance before unbalancing
% unit : 'ft','t' (physical units)
% 'int', 'phi0'
% chanList: List if channels included in array data (referred to the channel
% numbering in structure ds)
% badGref: A list of gRef channels markes as bad because they seen to have the
% wrong grad_order_no.
if ~exist('chanList');chanList=[];end
prec=class(data);
% Read the balance tables for both MEG and reference gradiometers.
% Usually balance0(2,:)='NONE', and it returns alphaGref=[].
[alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=...
getCTFBalanceCoefs(ds,balance0,unit);
% Unbalance the Grefs first. In almost all cases, balance0(2,:)='NONE',
% so the program will skip this section.
if ~strcmp(upper(balance0(2,:)),'NONE')
% The index lists give channel numbers referred to data set channel numbering
if isempty(Grefindex) | isempty(Gbalanceindex)
fprintf('setCTFDataBalance (unbalance_data): balance=%s\n',...
'\t\tsize(Grefindex)=[%d %d] size(Gbalanceindex)=[%d %d] ??\n',balance0(2,:),...
size(Grefindex),size(Gbalanceindex));
data=[]; % Force an error in the calling program
return
end
% Are there any badGref in the Gbalanceindex list?
if ~isempty(intersect(Gbalanceindex,badGref))
fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s Gref balancing.\n'],balance0(2,:));
fprintf(' Gbalanceindex=');fprintf(' %d',Gbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
if isequal(chanList,1:max(max(Gbalanceindex),max(Grefindex)));chanList=[];end
if ~isempty(chanList)
if ~isempty(setdiff(Gbalanceindex,chanList))
fprintf(['setCTFDataBalance (unbalance_data): List chanList does not include ',...
'all of the reference sensors in the %s table for reference gradiometers.\n'],...
balance0(2,:));
data=[];
return
end
[Gbalanceindex,Grefindex,alphaGref]=...
reindex(chanList,Gbalanceindex,Grefindex,alphaGref);
end
% Balancing reference gradiometers:
% balanced_data(:,Grefindex)
% =raw_data(:,Grefindex)-raw_data(:,Gbalanceindex)*alphaGref
% size(alphaGref)=[length(Gbalanceindex) length(Grefindex)]
% Note : not all of the sensors in list Gbalanceindex are gradiometers.
% Rewrite as a matrix equation:
% balanced_data(:,Gindex)=raw_data(:,Gindex)*Gbalmat
% Gindex=list of all the sensors involved in balancing the reference
% gradiometers.
% size(Gbalmat)=[length(Gindex) length(Gindex)]
[Gindex]=union(Gbalanceindex,Grefindex);
[Cx,Fbal]=intersect(Gindex,Gbalanceindex); % Gindex(Fbal)=Gbalanceindex
[Cx,Fref]=intersect(Gindex,Grefindex); % Gindex(Fref)=Grefindex
Gbalmat=eye(length(Gindex));
Gbalmat(Fbal,Fref)=Gbalmat(Fbal,Fref)-alphaGref;
clear Fbal Fref Cx Grefindex Gbalanceindex alphaGref;
% Convert to unbalanced reference gradiometers
for pt=1:size(data,3)
if strcmp(prec,'single')
data(:,Gindex,pt)=single(double(data(:,Gindex,pt))/Gbalmat);
else
data(:,Gindex,pt)=data(:,Gindex,pt)/Gbalmat;
end
end
clear Gbalmat pt;
end % Finished unbalancing the reference gradiometers
if strcmp(upper(balance0(1,:)),'NONE');
return; % No unbalancing required for MEG gradiometers
end
% Are there any badGref in the MEGbalanceindex list?
if ~isempty(intersect(MEGbalanceindex,badGref))
fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s MEG balancing.\n'],balance0(1,:));
fprintf(' MEGbalanceindex=');fprintf(' %d',MEGbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
% Don't bother with chanList if it obviously includes all the SQUID channels and in
% the dataset ordering.
if isequal(chanList,1:max(max(MEGindex),max(MEGbalanceindex)));chanList=[];end
if isempty(alphaMEG) | isempty(MEGindex) | isempty(MEGbalanceindex)
return;
elseif ~isequal(size(alphaMEG),[length(MEGbalanceindex) length(MEGindex)])
fprintf(['setCTFDataBalance (unbalance_data): size(alphaMEG)=[%d %d] ',...
'length(MEGbalanceindex)=%d length(MEGindex)=%d\n'],...
size(alphaMEG),length(MEGbalanceindex),length(MEGindex));
data=[];
return
elseif all(reshape(alphaMEG,1,length(MEGbalanceindex)*length(MEGindex))==0)
return
end
% Make the index lists refer to the entries in chanList.
if ~isempty(chanList)
if ~isempty(setdiff(MEGbalanceindex,chanList))
fprintf(['setCTFDataBalance (unbalance_data): List chanList does not include ',...
'all of the reference sensors in the %s table for MEG gradiometers.\n'],...
balance0(1,:));
data=[];
return
end
[MEGbalanceindex,MEGindex,alphaMEG]=...
reindex(chanList,MEGbalanceindex,MEGindex,alphaMEG);
end
% Reverse the balance applied to the MEG channels. Needs unbalanced reference data.
if ~isempty(alphaMEG) & ...
~isequal(alphaMEG,zeros(length(MEGbalanceindex),length(MEGindex)))
% Unbalance MEG data trial-by-trial and in blocks of nChBlock channels
for pt=1:size(data,3)
for m=1:nChBlock:length(MEGindex)
mptr=m:min(m+nChBlock-1,length(MEGindex));
MEGblock=MEGindex(mptr);
if strcmp(prec,'single');
data(:,MEGblock,pt)=single(double(data(:,MEGblock,pt))+...
double(data(:,MEGbalanceindex,pt))*alphaMEG(:,mptr));
else
data(:,MEGblock,pt)=data(:,MEGblock,pt)+...
data(:,MEGbalanceindex,pt)*alphaMEG(:,mptr);
end
end
end
clear pt m mptr MEGblock;
end
return
% ******************* End of function unbalance_data ****************************
% ***********************************************************************************
% ***********************************************************************************
% *************** Convert from unbalanced data to balanced data *******************
function data=balance_data(data,ds,balance,unit,nChBlock,chanList,badGref,messages);
% Extracts the balance table from structure ds and balances data as specified in balance.
% If the balancing requires a reference gradiometer marked in the badGref list, an error
% message is printed and the data array is set to [].
% If a MEG channel is missing from the balance table, then the channel is set to zero.
% Inputs: data: The aray of data to be balanced.
% ds: The ds structure read by readCTFds that contains the balance table.
% balance: The desired output balance state.
% balance(1,:) = MEG balance
% balance(2,:) = Gref balance
% unit : Data units ('fT','T','phio','int')
% nChBlock : rad the data in blocks of nChBlock to reduce memory requirements.
% chanList: List of the channels that actual;ly appear in data. referred to the
% dataset channel numbering (not to te list of SQUID channels)
% badGref: List of reference gradiometer channels that cannot be used for
% balancing.
if ~exist('chanList');chanList=[];end
prec=class(data);
[alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=...
getCTFBalanceCoefs(ds,balance,unit);
if ~strcmp(lower(balance(1,:)),'NONE');
% Are there any MEG channels missing from list MEGindex (i.e. missing from the balance table)?
% Make a list of MEG channels referred to dataset channel numbering.
MEGlist=[];
for k=1:ds.res4.no_channels
if ds.res4.senres(k).sensorTypeIndex==5;MEGlist=[MEGlist k];end
end
missingMEG=setdiff(MEGlist,MEGindex);
if ~isempty(missingMEG) & messages~=0 & ...
(isempty(chanList) | intersect(missingMEG,chanList))
fprintf('setCTFDataBalance (balance_data): Channel(s) missing from the balance table:\n');
for k=missingMEG
fprintf('\t%3d: %s\n',k,strtok(ds.res4.chanNames(k,:),'- '));
end
end
clear MEGlist k;
% Are there any badGref in the MEGbalanceindex list?
if ~isempty(intersect(MEGbalanceindex,badGref))
fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s MEG balancing.\n'],balance(1,:));
fprintf(' MEGbalanceindex=');fprintf(' %d',MEGbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
if isequal(chanList,1:max(max(MEGindex),max(MEGbalanceindex)));
chanList=[];
end
% Check if alphaMEG is all zeros or is improperly defined.
do_balance=~isempty(alphaMEG) & ~isempty(MEGindex) & ~isempty(MEGbalanceindex);
if do_balance
if ~isequal(size(alphaMEG),[length(MEGbalanceindex) length(MEGindex)]);
fprintf(['setCTFDataBalance (balance_data): size(alphaMEG)=[%d %d] ',...
'length(MEGbalanceindex)=%d length(MEGindex)=%d\n'],...
size(alphaMEG),length(MEGbalanceindex),length(MEGindex));
data=[];
return
elseif isempty(chanList) & size(data,2)<max(MEGindex)
fprintf(['setCTFDataBalance (balance_data): chanList=[], but size(data,2)=%d ',...
'max(MEGindex)=%d ?\n'],size(data,2),max(MEGindex));
data=[];
return
end
do_balance=~all(reshape(alphaMEG,1,length(MEGbalanceindex)*length(MEGindex))==0);
end
if do_balance
if ~isempty(chanList)
% Re-sort the reference sensor indices and make them refer to chanList
[MEGbalanceindex,MEGindex,alphaMEG]=...
reindex(chanList,MEGbalanceindex,MEGindex,alphaMEG);
% Refer the missing MEG channels to chanList
if ~isempty(missingMEG);missingMEG=reindex(chanList,missingMEG);end
end
% Balance MEGs data trial-by-trial and in blocks of nChBlock channels
for pt=1:size(data,3)
for m=1:nChBlock:length(MEGindex)
mptr=m:min(m+nChBlock-1,length(MEGindex));
MEGblock=MEGindex(mptr);
if strcmp(prec,'single')
data(:,MEGblock,pt)=single(double(data(:,MEGblock,pt))-...
double(data(:,MEGbalanceindex,pt))*alphaMEG(:,mptr));
else
data(:,MEGblock,pt)=data(:,MEGblock,pt)-...
data(:,MEGbalanceindex,pt)*alphaMEG(:,mptr);
end
end
% Zero the channel with missing coefficients. They cannot possibly be correct.
for m=missingMEG
if strcmp(prec,'single')
data(:,m,pt)=single(zeros(size(data,1),1,1));
else
data(:,m,pt)=zeros(size(data,1),1,1);
end
end
end
end
clear alphaMEG MEGindex MEGbalanceindex Ix pt m mptr MEGblock do_balance missingMEG;
end % Finished balancing the MEG data
% Is Gref balancing requested? In most cases, balance(2,:)='NONE'
if size(balance,1)==1;return;end
if strcmp(balance(2,:),'NONE');return;end
% Are there any bad Gref sensors in the Gbalanceindex list?
if ~isempty(intersect(Gbalanceindex,badGref))
fprintf(['setCTFDataBalance (balance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s Gref balancing.\n'],balance(2,:));
fprintf(' Gbalanceindex=');fprintf(' %d',Gbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
% Make the index lists refer to the entries in chanList.
if ~isempty(chanList)
[Gbalanceindex,Grefindex,alphaGref]=...
reindex(chanList,Gbalanceindex,Grefindex,alphaGref);
end
% Balance the reference channels
for pt=1:size(data,3)
for m=1:nChBlock:length(Grefindex)
mptr=m:min(m+nChBlock-1,length(Grefindex));
Grefblock=Grefindex(mptr);
if strcmp(prec,'single');
data(:,Grefblock,pt)=single(double(data(:,Grefblock,pt))-...
double(data(:,Gbalanceindex,pt))*alphaGref(:,mptr));
else
data(:,Grefblock,pt)=data(:,Grefblock,pt)-...
data(:,Gbalanceindex,pt)*alphaGref(:,mptr);
end
end
end
clear pt m mptr Grefblock Grefindex Gbalanceindex;
return
% ******************** End of function balance_data ****************************
% ***********************************************************************************
% ***********************************************************************************
% ************** Reassign indices in sensor and reference lists. ******************
function [refindex,sensorindex,alfa2]=reindex(chanlist,reflist,sensorlist,alfa);
% Reindex lists reflist and sensor list, and reorders 2nd index of matrix alfa.
% Inputs : Lists of sensor and references for balancing and matrix of balance
% coefficients.
% Outputs : index lists: chanlist(refindex)=reflist
% chanlist(sensorindex)=sensorlist
% alfa2=The part of alfa that refers to the part of sensorlist
% that appears in chanlist.
refindex=[];sensorindex=[];alfa2=[]; % Force an error on an early return.
% Sensible argument lists?
if nargout>nargin-1 | nargout==0
fprintf('reindex: %d outputs, but only %d inputs.\n',nargout,nargin);
return
end
[X c1 c2]=intersect(chanlist,reflist);
[Y ylist]=sort(c2);
refindex=c1(ylist);
if length(refindex)~=length(reflist)
fprintf('setCTFDataBalance (reindex): length(refindex)=%d length(reflist)=%d\n',...
length(refindex),length(reflist));
fprintf(' Some references are not included in chanlist.\n');
return
end
if nargin>=3 & nargout>=2
[X c1 c2]=intersect(chanlist,sensorlist);
[Y ylist]=sort(c2);
sensorindex=c1(ylist);
end
if nargin>=4 & nargout>=3
alfa2=alfa(:,Y);
end
return
% ***********************************************************************************
|
github
|
philippboehmsturm/antx-master
|
writeCTFMRI.m
|
.m
|
antx-master/xspm8/external/ctf/writeCTFMRI.m
| 8,517 |
utf_8
|
c6bdbc15d67e3621b8109f6b399f5eae
|
function writeCTFMRI(fileName,MRItags,MRIdata);
% Version 1.2 25 April 2007 Module writeCPersist changed, and removed from this text
% file.
% Version 1.1 19 April 2007 : No changes from v1.0
% Version 1.0 27 Oct. 2006
% Write a CTF MRI in v4 format.
% For file format and a defineition fo CPersist objects, see document
% "CTF MEG FIle Formats", PN900-0088
% Input: fileName : Name of MRI file including path and extension.
% Outputs: MRItags : CPersist tags describing the MRI in the format of the structure array
% produced by readMRI. There must be no start and stop tags.
% Clnical use messages are added to _PATIENT_ID, _PATIENT_NAME,
% _STUDY_COMMENTS, _CTFMRI_COMMENTS.
% I.e name='WS1_', type=0, data=[] and
% name='EndOfParameters', type -1, data=[]
% MRIdata: 256x256x256 array. No value may exceed 2^15-1 since the data are
% converted to int16.
% MRIdata(j,k,n) = pixel(j,k) of slice n.
% j = coronal slice. j=1:anterior, j=256:posterior
% k = axial slice. k=1:superior, k=256:inferior
% n = sagittal slice. j=1:left, j=256:right
% Calls: writeCPersist (not included in this listing)
% update_MRI_descriptors (included in this listing)
persistent printWarning
clinical_use_message='NOT FOR CLINICAL USE';
creatorSoftware='writeCTFMRI.m'; % Added to .infods file
NpxNot256Warning=1; % Print a warning if the no. of slices is not 256
if nargin==0 & nargout==0
fprintf(['writeCTFMRI: Version 1.2 25 April 2007 Creates MRIs in CTFMRI v4 format.\n',...
'\twriteCTFMRI(MRIfilename,MRItags,MRIdata);\n',...
'\t\tMRIfilename = complete name including path and extension .mri\n',...
'\t\tMRItags= structure array listing descriptors in the format produced',...
'by function readMRI.\n',...
'\t\tMRIdata = MRI data array.\n\n',...
'\tSee document "CTF MEG FIle Formats", PN900-0088\n']);
return
end
if nargin~=3
fprintf(['writeCTFMRI: Found %d input arguments. ',...
'Must have 3 inputs (filename,MRItags,MRIdata).\n'],nargin);
return
elseif ~ischar(fileName) | isempty(fileName) | ~isstruct(MRItags) | isempty(MRItags) |...
~isnumeric(MRIdata) | isempty(MRIdata)
fprintf('writeCTFMRI : Wrong argument type, or argument(s) empty.\n');
whos fileName MRItags MRIdata;
return
elseif ~isfield(MRItags,'name') | ~isfield(MRItags,'type') | ~isfield(MRItags,'data')
fprintf('writeCTFMRI: MRItags does not have the correct fields (name, type,data).\n');
MRItags
return
elseif ndims(MRIdata)~=3 | ~all(size(MRIdata)==size(MRIdata,1))
fprintf('writeCTFMRI: size(MRIdata)=[');fprintf(' %d',size(MRIdata));...
fprintf('] Must be Npx*[1 1 1] in CTF MRI format.\n');
return
elseif exist(fileName)==2
fprintf('writeCTFMRI: File %s already exists.\n',fileName);
return
end
% Verify that this really is a CTF MRI.
name=char([]);
for k=1:length(MRItags);
name=strvcat(name,MRItags(k).name);
end
isCTFMRI=(~isempty(strmatch('_CTFMRI_',name)));
MRIsize=size(MRIdata,1); % assume square slices
nSlice=size(MRIdata,3);
if NpxNot256Warning & MRIsize~=256
fprintf(['\nwriteCTFMRI: size(MRIdata)=%d*[1 1 1]. CTF MRI format standard is ',...
'256*[1 1 1].\n\t\t\tThis file may not work with MRIViewer.\n\n'],MRIsize);
end
if isCTFMRI
sizeTag=strmatch('_CTFMRI_SIZE',name,'exact');
if length(sizeTag)~=1
isCTFMRI=0;
else
MRItags(sizeTag).data=MRIsize;
end
clear sizeTag;
end
if ~isCTFMRI
fprintf(['writeCTFMRI: Structure array MRItags does not contain the tags ',...
'for a CTF MRI file (v4 format).\n'],fileName);
return
end
clear isCTFMRI
% Add clinical use and creator software messgaes
MRItags=update_MRI_descriptors(MRItags,clinical_use_message,creatorSoftware);
% Add MRIdata to MRItags, and add start and end tags
nTag=length(MRItags);
MRItags(2:nTag+1)=MRItags(1:nTag);
MRItags(1)=struct('name','WS1_','type',0,'data',[]); % Start tag
nTag=nTag+1;
for k=1:nSlice
MRItags(nTag+k)=struct('name',['_CTFMRI_SLICE_DATA#',num2str(k,'%5.5d')],'type',3,...
'data',int16(reshape(MRIdata(:,:,k),MRIsize^2,1)));
end
nTag=nTag+nSlice;
MRItags(nTag+1)=struct('name','EndOfParameters','type',-1,'data',[]); % End tag
clear MRIdata k nSlice MRIsize nTag;
if isempty(printWarning)
fprintf(['\nwriteCTFMRI: The MRI you are creating has been processed by software not\n',...
'\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',...
'\tfor clinical applications. This MRI should not be later employed for clinical\n',...
'\tand/or diagnostic purposes.\n']);
printWarning=1;
end
% Create the MRI file.
writeCPersist(fileName,MRItags);
return
%%%%%%%%%%%%%% end of readMRI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function update_MRI_descriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MRItags=update_MRI_descriptors(MRItags,comment,creatorSoftware);
% Makes sure that certain tags are in structure MRItags.
% Inputs: MRItags : Structure array produced by readCTFMRI.
% comment : Character string that is added to infods tags listed in addCommentTag.
% creatorSoftware : Character string indicating that the MRI set was
% created by writeCTFMRI. Added to the tags listed in addCreatorTag.
% Adds comment (clinical use message) and creator software name to
% MRI tags that will display the comment.
addCommentTag=strvcat('_PATIENT_ID','_PATIENT_NAME',...
'_STUDY_COMMENTS','_CTFMRI_COMMENT');
% MRI tags that will display the creator software.
addCreatorTag=strvcat('_CTFMRI_COMMENT');
% Check that the comment and creator tags are in structure MRItags. If not, issue an
% error message and set MRItags to [].
addTag=strvcat(addCommentTag,addCreatorTag);
addIndex=zeros(1,size(addTag,1));
k=0;
for k=1:length(MRItags)
tagIndex=strmatch(MRItags(k).name,addTag,'exact');
addIndex(tagIndex)=k;
if all(addIndex)~=0;break;end
end
% addTag(j) is MRItags(addIndex(j))
if any(addIndex==0)
% At least one of the addTags is missing. Print an error message and return.
fprintf(['writeCTFMRI (update_MRI_descriptors): At least one tag is missing from ',...
'structure array MRItags.\n']);
for k=1:size(addTag,1)
if isempty(strmatch(addTag(k,:),addTag(1:k-1,:),'exact'))
fprintf('\t\t\t%s\n',deblank(addTag(k,:)));
end
end
MRItags=struct([]); % Force an error in the calling program.
return
end
% Check that all of the addTags are text strings
type=[MRItags.type];
if any(type(addIndex)~=9 & type(addIndex)~=10)
fprintf('writeCTFMRI (update_MRI_descriptors): At least one of the new tags is not a character string.\n');
for k=1:length(addTag)
if isempty(strmatch(addTag(k,:),addTag(1:k-1,:),'exact'))
fprintf('\t\t\t%s type=%d\n',deblank(addTag(k,:)),type(addIndex(k)));
end
end
MRItags=struct([]); % Force an error in the calling program.
return
end
addCommentIndex=addIndex(1:size(addCommentTag,1));
addCreatorIndex=addIndex(size(addCommentTag,1)+[1:size(addCreatorTag,1)]);
if exist('creatorSoftware')~=1;
creatorSoftware=char([]);
elseif ~ischar(creatorSoftware)
creatorSoftware=char([]);
else
creatorSoftware=deblank(creatorSoftware);
end
if exist('comment')~=1;
comment=char([]);
elseif ~ischar(comment)
comment=char([]);
else
comment=deblank(comment);
end
for k=addCreatorIndex
if isempty(MRItags(k).data)
MRItags(k).data=creatorSoftware;
else
MRItags(k).data=[creatorSoftware ' ' MRItags(k).data];
end
end
for k=addCommentIndex
if isempty(MRItags(k).data)
MRItags(k).data=comment;
else
MRItags(k).data=[comment ' ' MRItags(k).data];
end
end
% Shorten type 9 (CStr32) strings to 31 characters plus a terminating null.
for k=addIndex
if MRItags(k).type==9 & length(MRItags(k).data)>31;
MRItags(k).data=[MRItags(k).data(1:31) char(0)];
end
end
return
%%%%%%%%%%%%%% End of update_MRI_descriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
readCTFds.m
|
.m
|
antx-master/xspm8/external/ctf/readCTFds.m
| 36,570 |
utf_8
|
e228d972ce0710af61be4d1d0c89f3fe
|
function ds=readCTFds(datasetname)
% ************************************************************************
%
% This program is provided to users of CTF MEG systems as a courtesy only.
% It's operation has not been verified for clinical use.
% Please do not redistribute it without permission from CTF Systems Inc.
%
% ************************************************************************
% readCTFds opens a CTF data set and creates a MATLAB structure with the information
% in the .res4, .infods, .newds, .acq, .hc, .hist, .EEG, bad.segments, BadChannels,
% ClassFile.cls andMarkerFile.mrk files. It confirms the existence of a .meg4 file
% with the correct size.
% See document CTF MEG File Formats, PN900-0088 for a description of the formats of
% dataset files.
% Author : Harold Wilson
% ***************** Revisions and bug fixes **************************************
% Version 1.3 4 October 2007
% 1. readCTFds v1.2 failed when run in MATLAB 7.2, but ran correctly in
% MATLAB 6.5 and 7.3. The failure occurred when calls to fscanf with a
% final '\n' in the format string were followed by fgetl. In MATLAB 6.5 and 7.3,
% this returns the next line of a text file, but in MATLAB 7.2, this
% returns an empty charatcer string.
% Changes were made to subprograms
% - readHc,
% - readClassFile
% - readMarkerFile.
% 2. In v1.1 and 1.2, if any of the head coil positions exceeded 100 cm, readHc
% reported an error and returned hc=struct([]). In v1.3, is reports the error,
% and returns the erroneaous values.
% Version 1.2: 24 April 2007
% - readHc modified to read fMEG .hc files.
% - readCPersist modified to handle extra bytes that appear in some .acq files.
% Version 1.1: 13 April 2007
% readCTFds is modified to handle cases where the data files exceed a total of 2^31-8
% bytes. In these cases files .1_meg4,.2_meg4,... appear in the dataset.
% ***********************************************************************************
% Inputs : datasetname : Complete name of the data set directory. Includes the complete
% path and the .ds extension.
% Output: ds : A structure that gives data set parameters.
% Function calls included in this listing:
% - readRes4
% - readHc
% - readEEG
% - readMarkerFile
% - readClassFile
% - readBadSegments
% - readVirtualChannels
% External functions: - readCPersist Reads infods and acq files.
% - The data directory is datasetname.
% - path is the complete path to the directory including the last file delimiter.
% - baseName is the directory name, less the last file extension.
% - datasetname=[path,baseName,'.ds'];
persistent printWarning multipleMeg4Files
if nargin==0 & nargout==0 % Print a version number
fprintf(['\treadCTFds: Version 1.3 4 October 2007 ',...
'Reads v4.1 and v4.2 CTF data sets including fMEG .hc files.\n',...
'\tCall: ds=readCTFds(datasetname)\n',...
'\t\tdatasetname = Name of the dataset including the path.\n',...
'\t\tds = Structure containing all dataset information except for data in ',...
'the .meg4 file.\n\n']);
return
end
MAX_COILS=8;
MAX_BALANCING=50; % max. no. of balancing coefficients
SENSOR_LABEL=31; % No. of characters in sensor labels in the balancing
% coefficient tables
len_sensor_name=32;
% length of sensor coefficient records in bytes. See listing for MEGDefs.h
%senres_lenrec=len_sensor_name+8+2+MAX_BALANCING*SENSOR_LABEL+8*MAX_BALANCING;
% Allowed 8-byte headers for res4 and meg4 files.
res4Headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]);
meg4Headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]);
delim=filesep;
ds=struct([]);
% Check that the data set exists.
if exist('datasetname')~=1
fprintf('\nreadCTFds: No input datasetname specified.\n\n');
return
elseif ~ischar(datasetname) | isempty(datasetname) | size(datasetname,1)~=1
fprintf('\nreadCTFds: Dataset name is not a string, or is empty, or is an array.\n\n');
whos datasetname
return
else
% Separate datasetname into a path and the baseName and add extension .ds.
datasetname=deblank(datasetname);
ksep=max([0 findstr(datasetname,delim)]);
baseName=datasetname((ksep+1):length(datasetname));
path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]).
% Remove the last .ds from baseName.
kdot=max(findstr(baseName,'.ds'));
if kdot==(length(baseName)-2)
baseName=baseName(1:(max(kdot)-1));
else
datasetname=[datasetname,'.ds'];
end
clear ksep kdot;
if exist(datasetname)~=7
fprintf('\nreadCTFds: Cannot find dataset %s.\n\n',datasetname);
return
end
end
% Check that the res4 and meg4 files exist.
res4File=[datasetname,delim,baseName,'.res4'];
meg4File=[datasetname,delim,baseName,'.meg4'];
if exist(res4File)~=2 | exist(meg4File)~=2
fprintf('readCTFds: In directory %s, cannot find .res4 and/or .meg4 files.\n',...
datasetname);
return
end
% Check the headers on .meg4, .1_meg4, ...
qFile=0;
meg4Ext='.meg4';
meg4Size=[];
while 1
if qFile>0;
meg4Ext=['.',int2str(qFile),'_meg4'];
meg4File=[datasetname,delim,baseName,meg4Ext];
end
if qFile>1 & isempty(multipleMeg4Files)
fprintf('readCTFds: This dataset has multiple meg4 files.\n');
multipleMeg4Files=1;
end
fid=fopen(meg4File,'r','ieee-be');
if fid<=0;break;end
D=dir([datasetname,delim,baseName,meg4Ext]);
meg4Size=[meg4Size D.bytes];
meg4Header=char(fread(fid,8,'uint8')');
fclose(fid);
if isempty(strmatch(meg4Header,meg4Headers,'exact'))
fprintf('\nreadCTFds: %s file header=%s Valid header options:',meg4Ext,meg4Header);
for k=1:size(meg4Headers,1);fprintf(' %s',meg4Headers(k,:));end
fprintf('\n\n');
ds=struct([]);
return
end
qFile=qFile+1;
end
Nmeg4=length(meg4Size);
clear D fid qFile;
% Add baseName and path to structure ds.
ds=struct('baseName',baseName,'path',path);
% Read the res4 file
ds.res4=readRes4(res4File,res4Headers,...
MAX_COILS,MAX_BALANCING,SENSOR_LABEL,len_sensor_name);
if isempty(ds.res4);ds=struct([]);return;end
dataBytes=4*ds.res4.no_trials*ds.res4.no_channels*ds.res4.no_samples;
% Assemble ds.meg4.
ds.meg4.fileSize=sum(meg4Size);
ds.meg4.header=meg4Header;
clear meg4Header meg4Size;
% Does the size of the .meg4 file match the size specified by the .res4 file?
if ds.meg4.fileSize~=8*Nmeg4+dataBytes
fprintf(['\nreadCTFds: Data set error : size of meg4 file(s)\n\t\t',...
'%10d bytes (from dir command)\n'],ds.meg4.fileSize);
fprintf('\t\t%10d bytes (from res4 file)\n\n',8*Nmeg4+dataBytes);
return
end
if isempty(printWarning)
fprintf(['\nreadCTFds: You are reading CTF data for use with a software-application tool\n',...
'\tthat is not manufactured by VSM MedTech Ltd. and has not received marketing\n',...
'\tclearance for clinical applications. If CTF MEG data are processed by this tool,\n',...
'\tthey should not be later employed for clinical and/or diagnostic purposes.\n\n']);
printWarning=1;
end
% .infods file
if exist([datasetname,delim,baseName,'.infods'])==2
ds.infods=readCPersist([datasetname,delim,baseName,'.infods']);
end
% .newds file
if exist([datasetname,delim,baseName,'.newds'])==2
fid=fopen([datasetname,delim,baseName,'.newds'],'r','ieee-be');
ds.newds=char(fread(fid,'uint8'))';
fclose(fid);
clear fid;
end
% .acq file
if exist([datasetname,delim,baseName,'.acq'])==2
ds.acq=readCPersist([datasetname,delim,baseName,'.acq']);
end
% .hist file
if exist([datasetname,delim,baseName,'.hist'])==2
fid=fopen([datasetname,delim,baseName,'.hist'],'r','ieee-be');
ds.hist=char(fread(fid,'uint8'))';
fclose(fid);
end
% .hc file
if exist([datasetname,delim,baseName,'.hc'])==2
ds.hc=readHc([datasetname,delim,baseName,'.hc']);
end
% .eeg file
if exist([datasetname,delim,baseName,'.eeg'])==2
ds.eeg=readEEG([datasetname,delim,baseName,'.eeg']);
if isempty(ds.eeg);ds=rmfield(ds,'eeg');end
end
% marker file
if exist([datasetname,delim,'MarkerFile.mrk'])==2
ds.mrk=readMarkerFile([datasetname,delim,'MarkerFile.mrk']);
end
% ClassFile
if exist([datasetname,delim,'ClassFile.cls'])==2
ds.TrialClass=readClassFile([datasetname,delim,'ClassFile.cls']);
end
% bad.segments
if exist([datasetname,delim,'bad.segments'])==2
ds.badSegments=readBadSegments([datasetname,delim,'bad.segments']);
end
% BadChannels
if exist([datasetname,delim,'BadChannels'])==2
fid=fopen([datasetname,delim,'BadChannels'],'r','ieee-be');
ds.BadChannels=char([]);
while 1
strng=fscanf(fid,'%s\n',1);
if isempty(strng);break;end
ds.BadChannels=strvcat(ds.BadChannels,strng);
end
fclose(fid);
clear fid;
end
% VirtualChannels Assume this is the name of the file. Modify to accept *.vc?
if exist([datasetname,delim,'VirtualChannels'])==2
ds.Virtual=readVirtualChannels([datasetname,delim,'VirtualChannels']);
end
% processing.cfg
if exist([datasetname,delim,'processing.cfg'])==2
fid=fopen([datasetname,delim,'processing.cfg']);
ds.processing=char(fread(fid,'uint8'))';
fclose(fid);
clear fid;
end
return
%%%%%%%%%%%%%%%%% End of readCTFds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readRes4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res4=readRes4(res4File,res4Headers,...
MAX_COILS,MAX_BALANCING,SENSOR_LABEL,len_sensor_name);
% Open the res4 file
fid=fopen(res4File,'r','ieee-be');
% Check header.
res4.header=char(fread(fid,8,'uint8')');
if isempty(strmatch(res4.header,res4Headers,'exact'))
fprintf(['\nreadCTFds (readRes4):res4 file header = %s. ',...
'Valid header options:'],res4.header);
for k=1:size(res4Headers,1);fprintf(' %s',res4Headers(k,:));end;fprintf('\n\n');
res4=struct([]);
fclose(fid);
return
end
% Remove trailing blanks, but include a final null (char(0)).
res4.appName=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.dataOrigin=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.dataDescription=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.no_trials_avgd=fread(fid,1,'int16');
res4.data_time=[deblank(char(fread(fid,255,'uint8')')) char(0)];
res4.data_date=[deblank(char(fread(fid,255,'uint8')')) char(0)];
% new_general_setup_rec_ext part of meg41GeneralResRec
res4.no_samples=fread(fid,1,'int32');
temp=fread(fid,2,'int16');
res4.no_channels=temp(1);
res4.sample_rate=fread(fid,1,'float64');
res4.epoch_time=fread(fid,1,'float64');
temp=fread(fid,2,'int16');
res4.no_trials=temp(1);
res4.preTrigPts=fread(fid,1,'int32');
res4.no_trials_done=fread(fid,1,'int16');
res4.no_trials_display=fread(fid,1,'int16');
res4.save_trials=fread(fid,1,'int32');
% meg41TriggerData part of new_general_setup_rec_ext 10 bytes total
res4.primaryTrigger=fread(fid,1,'int32');
res4.triggerPolarityMask=fread(fid,1,'int32');
temp=fread(fid,1,'int16'); %Skip 2 bytes of padding
% end of meg41TriggerData part of new_general_setup_rec_ext
temp=fread(fid,3,'int16'); %Skip 2 bytes of padding
res4.trigger_mode=temp(2);
res4.accept_reject_Flag=fread(fid,1,'int32');
temp=fread(fid,2,'int16'); %Skip 2 bytes of padding
res4.run_time_display=temp(1);
res4.zero_Head_Flag=fread(fid,1,'int32');
res4.artifact_mode=fread(fid,1,'int32');
% end of new_general_setup_rec_ext part of meg41GeneralResRec
% meg4FileSetup part of meg41GeneralResRec
% Remove trailing blanks, but include a final null (char(0))
res4.nf_run_name=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_run_title=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.nf_instruments=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_collect_descriptor=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_subject_id=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_operator=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_sensorFileName=[deblank(char(fread(fid,56,'uint8')')) char(0)];
temp=fread(fid,3,'int32');
res4.rdlen=temp(2);
res4.run_description=[deblank(char(fread(fid,res4.rdlen,'uint8')')) char(0)];
% end of meg4FileSetup part of meg41GeneralResRec
% Filter descriptions. Set field res4.filters=[] if no filters are
% defined.
res4.num_filters=fread(fid,1,'int16');
if res4.num_filters==0
res4.filters=[];
else
for kfilt=1:res4.num_filters
res4.filters(kfilt).freq=fread(fid,1,'float64');
res4.filters(kfilt).fClass=fread(fid,1,'int32');
res4.filters(kfilt).fType=fread(fid,1,'int32');
res4.filters(kfilt).numParam=fread(fid,1,'int16');
for kparm=1:res4.filters(kfilt).numParam
res4.filters(kfilt).Param(kparm)=fread(fid,1,'float64');
end
end
clear kfilt kparm;
end
% Read channel names. Must have size(res4.chanNames)=[channels 32]
% Clean up the channel names. The MEG system software leaves junk
% bytes in the channel name following the first zero.
res4.chanNames=char(zeros(res4.no_channels,32));
for kchan=1:res4.no_channels
xname=strtok(char(fread(fid,32,'uint8')'),char(0));
res4.chanNames(kchan,1:length(xname))=xname;
end
clear kchan xname;
% Read sensor resource table. Floating point values are 'double'
% but the code could be changed to convert to 'single' to save memory.
for kchan=1:res4.no_channels
res4.senres(kchan).sensorTypeIndex=fread(fid,1,'int16');
res4.senres(kchan).originalRunNum=fread(fid,1,'int16');
res4.senres(kchan).coilShape=fread(fid,1,'int32');
res4.senres(kchan).properGain=fread(fid,1,'double');
res4.senres(kchan).qGain=fread(fid,1,'double');
res4.senres(kchan).ioGain=fread(fid,1,'double');
res4.senres(kchan).ioOffset=fread(fid,1,'double');
res4.senres(kchan).numCoils=fread(fid,1,'int16');
numCoils=res4.senres(kchan).numCoils;
temp=fread(fid,3,'int16');
res4.senres(kchan).grad_order_no=temp(1);
% Special code to take care of situations where someone wants to label bad channels
% by setting their gain to zero.
invgain=(res4.senres(kchan).ioGain*...
res4.senres(kchan).properGain*res4.senres(kchan).qGain);
if abs(invgain)>1e-50
res4.senres(kchan).gain=1/invgain;
else
res4.senres(kchan).gain=sign(invgain)*1e50;
end
if res4.senres(kchan).sensorTypeIndex>=0 & res4.senres(kchan).sensorTypeIndex<=7
% Nominal gain (fT/integer step)
res4.senres(kchan).gain=1e15*res4.senres(kchan).gain;
end
% Data that was included in res4.senres(kchan).coilTbl in earlier versions of readCTFds
res4.senres(kchan).pos0=zeros(3,res4.senres(kchan).numCoils);
res4.senres(kchan).ori0=zeros(3,res4.senres(kchan).numCoils);
res4.senres(kchan).area=zeros(1,res4.senres(kchan).numCoils);
res4.senres(kchan).numturns=zeros(1,res4.senres(kchan).numCoils);
for qx=1:numCoils
buff=fread(fid,8,'double');
res4.senres(kchan).pos0(:,qx)=buff(1:3);
res4.senres(kchan).ori0(:,qx)=buff(5:7);
temp=fread(fid,4,'int16');
res4.senres(kchan).numturns(qx)=temp(1);
res4.senres(kchan).area(qx)=fread(fid,1,'double');
end
if numCoils<MAX_COILS % Skip the rest of the coilTbl
buff=fread(fid,10*(MAX_COILS-numCoils),'double');
end
% Data that was included in res4.senres(kchan).HdcoilTbl in earlier versions of readCTFds
res4.senres(kchan).pos=zeros(3,res4.senres(kchan).numCoils);
res4.senres(kchan).ori=zeros(3,res4.senres(kchan).numCoils);
for qx=1:numCoils
buff=fread(fid,8,'double');
res4.senres(kchan).pos(:,qx)=buff(1:3);
res4.senres(kchan).ori(:,qx)=buff(5:7);
temp=fread(fid,2,'double'); % Don't bother with area and numturns. Already read.
end
if numCoils<MAX_COILS % Skip the rest of the HdcoilTbl
buff=fread(fid,10*(MAX_COILS-numCoils),'double');
end
end
clear kchan buff numCoils temp qx;
% End reading sensor resource table
res4.numcoef=fread(fid,1,'int16'); % Number of coefficient records
% Create structure array res4.scrr which holds the balancing tables.
for nx=1:res4.numcoef
res4.scrr(nx).sensorName=uint8(fread(fid,len_sensor_name,'uint8'))';
buff=fread(fid,8,'uint8');
res4.scrr(nx).coefType=uint8(buff(1:4))'; % discard bytes 5-8
res4.scrr(nx).numcoefs=double(fread(fid,1,'int16'));
numcoef=res4.scrr(nx).numcoefs;
buff=fread(fid,SENSOR_LABEL*MAX_BALANCING,'uint8');
buff=reshape(buff,SENSOR_LABEL,MAX_BALANCING);
res4.scrr(nx).sensor=[uint8(buff(:,1:numcoef)) ...
uint8(zeros(SENSOR_LABEL,MAX_BALANCING-numcoef))];
buff=fread(fid,MAX_BALANCING,'double');
res4.scrr(nx).coefs=[buff(1:numcoef);zeros(MAX_BALANCING-numcoef,1)];
end
fclose(fid); % Close the res4 file
return
%%%%%%%%%% End of readRes4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readHc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hc=readHc(hcFile);
% Reads the .hc file and returns a structure with head-coil posiiotns.
% The hc file format is given in document CTF MEG File Formats (PN900-0088).
% .hc file format: Coils and positions are specified by 4 lines of text:
% Line 1: A B coil position relative to C (cm):
% " 2: [tag]x = F
% " 3: [tag]y = F
% " 4: [tag]z = F
% A = 'standard' or 'stadard' or 'measured'. 'stadard' is a typographical error that
% appeared in v4 of the CTF Acq. The first set of coil positions is 'standard' or
% 'stanard'. The next two sets are 'measured'.
% B = coil label. For MEG systems, the first three coils must have the names 'nasion',
% 'left ear', 'right ear'. They may be followed by other coil names.
% For fMEG systems, there is no fixed standard for coil names.b readHc will
% accept any coil names. Typically the coils are 'back','left hip','right hip',
% 'sternum', 'belly'. In some UAMS data the names are 'nasion',...
% The string 'coil position relative to' appears in all valid .hc files. It marks
% the end of the coil label and the start ot the coordinate-system.
% C = coordinate system = 'dewar' and 'head'(MEG) or 'abdomen' (fMEG). No variations
% are permitted. The first two sets of coil positions are in dewar coordinates.
% The last set is in 'head' or 'abdomen' coordinates.
% Units : For .hc to be a valid coil position file, the coordinates must be in cm.
% The program searches for the string '(cm):'.
% F = coordinate (numeric)
% There are exactly 3 sets of coil positions in the file appearing in the order
% (1) A='standard', C='dewar'
% (2) A='measured', C='dewar'
% (3) A='measured', C='head' or 'abdomen'
% The coils must appear in the same order in each set.
% Input : Name of hc file (including complete path and .hc extension)
% Output : Structure hc containing standard, dewar and CTF coordinates of the
% nasion,left,right coils.
% hc.name= names of the coils size(hc.name)=[nCoil x]
% MEG: hc.standard, hc.dewar, hc.head : size=[3 nCoil] : coil positions in cm
% fMEG: hc.standard, hc.dewar, hc.abdomen : size=[3 nCoil] : coil positions in cm
if nargin==0 & nargout==0
fprintf(['readHc: Version 1.3 4 Oct. 2007\n',...
'\thc=readHc(hcFile) reads head-coil file hcFile and returns the head coil',...
'\t positions in structure hc\n\n',...
'\tThe file format is defined in document CTF MEG File Formats, PN900-0088.\n\n']);
return
end
basicString='coil position relative to';
% In MEG systems, the first three coil names are fixed.
MEGCoilLabel=strvcat('nasion','left ear','right ear');
C3options=strvcat('head','abdomen');
unitString='(cm):';
maxRCoil=200; % Report an error if any coil position is > maxRCoil cm.
printWarning=1;
hc=struct([]); % Return in event of an error.
if exist(hcFile)~=2
return
end
prec=1e-6; % Round positions.
% Decide if this is a MEG or an fMEG system. Find the first line that contains the
% string 'coil position relative to'.
% MEG system: This line contains 'nasion'.
% fMEG system: This line does not contains 'nasion'.
fhc=fopen(hcFile,'rt','ieee-be');
% Decide system type and generate arrays for strings A and C.
% Search for first line. Allow for the posibility that extra text lines migt be added at
% the start of the file.
strngA=char([]);
while 1
textline=fgetl(fhc);
if isequal(textline,-1)
break
elseif strfind(textline,'coil position relative to');
stringA=strtok(textline);
% Fix typographic error in some releases of Acq, not in all coils.
if strcmp(stringA,'stadard')
stringA = 'standard';
end
if ~strcmp(stringA,'standard')
break
end
stringA=strvcat(stringA,'measured','measured');
break;
end
end
if isequal(textline,-1) | size(stringA,1)<3
fprintf('readHc: File %s does not have the head position file format.\n',hcFile);
fclose(fhc);
return
end
% Set stringC(3,:)='head' or 'abdomen' later.
stringC=strvcat('dewar','dewar');
% textline is the first useful line of the head coil file.
coilLabel=char([]); % Names given to the coils
rhc=zeros(3,0); % Coil positions (cm)
coil=0;
nCoil=0;
lastPositionSet=1;
while ~isequal(textline,-1)
% Parse the line
[A,R]=strtok(textline);
% Fix typographic error in some releases of Acq, not in all coils.
if strcmp(A,'stadard')
A = 'standard';
end
kpos=strfind(R,basicString);
coilName=deblank(R(2:kpos-1));
[C,R]=strtok(R(kpos+length(basicString):length(R)));
if strmatch(C,C3options)
stringC=strvcat(stringC,C);
end
[unit,R]=strtok(R);
if isempty(A) & isempty(C) % This can happen on empty line after reading all the information, and would cause positionSet to be [1; 2; 3], problematic for loop below.
break;
end
positionSet=intersect(strmatch(A,stringA),strmatch(C,stringC)); % strmatch matches empty strings to everything.
if isempty(positionSet) | ~strcmp(unit,unitString) | ~isempty(R)
break;
end
if positionSet==lastPositionSet
coil=coil+1;
else
coil=1;
end
if positionSet==1
% Assemble list of coil names
coilLabel=strvcat(coilLabel,coilName);
nCoil=coil;
elseif ~strcmp(coilName,deblank(coilLabel(coil,:)));
break;
end
% The line describing the coil and coordinate frame is OK.
% Get the coordinates by reading 3 lines.
buff=fscanf(fhc,'%s%s%f',9);
if ~isequal(size(buff),[9 1])
break
end
rhc=[rhc prec*round(buff(3:3:9)/prec)];
fgetl(fhc); % Skip to the start of the next line.
textline=fgetl(fhc);
lastPositionSet=positionSet;
end
fclose(fhc);
clear lastPositionSet coil textline fhc;
clear stringA A C R kpos coilName unit buff;
if size(rhc,2)~=positionSet*nCoil
fprintf('readHc: File %s does not have %d complete sets of %d coils.\n',...
hcFile,positionSet,nCoil);
return
end
if max(max(abs(rhc)))>maxRCoil & printWarning
fprintf('readHc: Head Coil file %s\n max(coil position)>%d.\n',...
hcFile,round(maxRCoil));
end
% Assemble structure hc.
hc=struct('names',coilLabel);
coilCoords=deblank(strvcat('standard','dewar',stringC(3,:)));
for q=1:positionSet
hc=setfield(hc,deblank(coilCoords(q,:)),rhc(:,nCoil*(q-1)+[1:nCoil]));
end
return
%%%%%%%%% End of readHc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function EEG=readEEG(EEGfile);
% Reads the EEG file of a dataset and stores the infoemation in strucure array EEG.
% EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number)
% EEG(k).name = channel name given by the user (e.g. Fp4)
% EEG(k).pos = electrode position in cm in CTF head coordinates
if exist(EEGfile)~=2
EEG=struct([]);
return
end
fid=fopen(EEGfile,'r');
EEG=struct('chanNum',[],'name',char([]),'pos',[]);
nEEG=0;
while 1
chanNum=fscanf(fid,'%d',1);
name=fscanf(fid,'%s',1);
pos=fscanf(fid,'%f',3);
if isempty(pos);break;end
nEEG=nEEG+1;
EEG(nEEG)=struct('chanNum',chanNum,'name',name,'pos',pos);
end
fclose(fid);
return
%%%%%%%%% End of readEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function TrialClass=readClassFile(ClassFileName);
% Reads a CTF ClassFile and stores information in a structure.
% The class file allows a user to store a list of classsified trials in a data set.
% The ClassFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid and readClassFile assumes that the ClassFile has the format
% current in October 2006.
% Inputs :
% ClassFileName : marker file including the full path and extension .mrk.
% trialList : List of trials to read. Trial numbering : 1,2,...
% If omitted or empty, read all markers.
% Output : Structure array marker. Output trial numbering starts at 1.
% See CTF MEG File Formats, (PN900-0088) for the meaning of the structure
% fields. A trial mat=y start before the t=0 point, so it is possible to have
% markers with time<0 (see ds.res4.preTrigPts).
TrialClass=struct([]);
if exist(ClassFileName)~=2
return % File doesn't exist.
end
fid=fopen(ClassFileName,'r','ieee-be');
for k=1:5;fgetl(fid);end % Skip 5 lines (including path info)
nClass=sscanf(fgetl(fid),'%d',1); %Read value and skip to the start of the next non-blank line.
if nClass<=0
fprintf('readClassFile: File %s has %d classes.\n',nClass);
return
end
TrialClass=struct('ClassGroupId',[],'Name',char([]),...
'Comment',char([]),'Color',char([]),'Editable',char([]),'ClassId',[],'trial',[]);
for k=1:nClass
% Find the start of the next class identification
% There is no need to check for end of file because the loop ends before an attempt
% is made to read class nClass+1.
while ~strcmp('CLASSGROUPID:',fgetl(fid));end
ClassGroupId=sscanf(fgetl(fid),'%d',1);
fgetl(fid);
Name=deblank(fgetl(fid));
fgetl(fid);
Comment=deblank(fgetl(fid));
fgetl(fid);
Color=deblank(fgetl(fid));
fgetl(fid);
Editable=deblank(fgetl(fid));
fgetl(fid);
ClassId=sscanf(fgetl(fid),'%d',1);
fgetl(fid);
No_of_Trials=sscanf(fgetl(fid),'%d',1);
fgetl(fid);fgetl(fid);
if No_of_Trials>0
trial=reshape(fscanf(fid,'%d',No_of_Trials),1,No_of_Trials);
else
trial=[];
end
% Adjust trial numbering so it starts at 1.
TrialClass(k)=struct('ClassGroupId',ClassGroupId,'Name',Name,...
'Comment',Comment,'Color',Color,'Editable',Editable,'ClassId',ClassId,...
'trial',trial+1);
end
fclose(fid);
return
%%%%%%%%% End of readClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function badSegments=readBadSegments(badSegmentsFile);
% Reads the bad.segements file of a CTF data set and stores the information in structure
% bad_segments.
% badSegments.trial = List of trial numbers
% badSegments.StartTime = List of bad segment start times (relative to trial).
% badSegments.EndTime = List of bad segment end times.
% Reads the file one line at a time. Each line has three numbers.
% 1st: Trial number=integer. Trial numbering for bad.segments starts at 1.
% 2nd,3rd : Start, End times (s).
if exist(badSegmentsFile)~=2
badSegments=struct([]);
return
end
fid=fopen(badSegmentsFile,'r','ieee-be');
badSegments=struct('chanName',char([]),'name',char([]),'pos',[]);
nLine=0;
data=zeros(3,0);
while 1
txt=fgetl(fid);
if isequal(txt,-1);break;end
nLine=nLine+1;
[buff,count]=sscanf(txt,'%f');
% Are the data good?
badline=(count~=3);
if ~badline;badline=(abs((buff(1)-round(buff(1)))>0.0001) | buff(3)<buff(2));end
if badline
fprintf('readCTFds (readBadSegments): Format error in file bad.segments.\n');
fprintf('\tLine %d has %d numbers: ',nLine,count);fprintf('\t %g',buff);fprintf('\n');
fprintf('\tMust have 3 numbers on each line: #1=integer, #2,#3=float, #3>=#2.\n');
badSegments=struct([]);
return
end
data=[data buff];
end
fclose(fid);
badSegments=struct('trial',data(1,:),'StartTime',data(2,:),'EndTime',data(3,:));
return
%%%%%%%%% End of readBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Virtual=readVirtualChannels(VirtualChannelsName);
% Reads the Virtual channels file associated with a data set
Virtual=struct([]);
% Check VirtualChannelsName
if exist('VirtualChannelsName')~=1;VirtualChannelsName=char([]);end
if isempty(VirtualChannelsName)
fprintf('readVirtualChannels: Must specify a VirtualChannels file.\n');
return
elseif ~ischar(VirtualChannelsName)
fprintf('readVirtualChannels: VirtualChannelsName must be a character string.\n');
return
elseif exist(VirtualChannelsName)~=2
fprintf('readVirtualChannels: Cannot find file %s\n',VirtualChannelsName);
return
end
fid=fopen(VirtualChannelsName,'r');
count=0;
Virtual=struct('Name',char([]),'Unit',char([]),'chan',char([]),'wt',[]);
strng=textread(VirtualChannelsName,'%s','delimiter',',\t');
k=0;
while k<length(strng)
k=k+1;
if strmatch('VirtualChannel',strng{k});
Refcount=0;
chan=char([]);
wt=[];
elseif strmatch('Name:',strng{k});
k=k+1;
Name=strng{k};
if isempty(Name);break;end
elseif strmatch('Unit:',strng{k});
k=k+1;
Unit=strng{k};
elseif strmatch('Ref:',strng{k});
chan=strvcat(chan,strng{k+1});
wt=[wt;str2num(strng{k+2})];
k=k+2;
elseif strmatch('}',strng{k});
count=count+1;
Virtual(count)=struct('Name',Name,'Unit',Unit,'chan',chan,'wt',wt);
clear Name Unit chan wt Refcount;
end
end
fclose(fid);
if isempty(Virtual(1).Name)
Virtual=struct([]);
end
return
%%%%%%%%% End of readVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readMarkerFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function marker=readMarkerFile(MarkerFileName,trialList);
% Version 1.3 4 Oct. 2007
% Reads specified trials of a CTF MarkerFile.
% The MarkerFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid and readMarkerFile assumes that the MarkerFile has the format
% current in October 2006. The document lists 4 Class Groups, but only CLASSGROUPID=0
% (triggers) and CLASSGROUPID=3 (Manual) are actually used. read_MArkerFile reads only
% these two groups, but it prints a message if the other groups are encountered.
% Trigger markers (CLASSGROUPID=0) have an additional 4 pieces of information supplied:
% BITNUMBER(int), POLARITY(+ or 1),SOURCE(text) and THRESHOLD (float). FOr
% CLASSGROUPID=3, these fields are left empty.
% Inputs :
% MarkerFileName : marker file including the full path and extension .mrk.
% trialList : List of trials to read. Trial numbering : 1,2,...
% If omitted or empty, read all markers.
% Output : marker: Structure array. Output trial numbering starts at 1.
% See CTF MEG File Formats, (PN900-0088) for the meaning of the structure
% fields. A trial may start before the t=0 point, so it is possible to have
% markers with time<0 (see ds.res4.preTrigPts).
% Fields: ClassGroupId, Name,Comment,Color,Editable,ClassId,trial,time;
% Other fields that appear with ClassGroupId=0 are not included.
if nargin==0 & nargout==0
fprintf(['readMarkerFile: Version 1.3 4 Oct. 2007\n',...
'\tReads a CTF dataset MarkerFile and returns a structure array.\n',...
'\tmarker=readMarkerFile(FileName) reads ',...
'a marker file and returns the trials and times.\n',...
'\tmarker=readMarkerFile(FileName,trialList) reads a marker file and returns only\n',...
'\t\t\tthe markers for trials listed in vector trialList.\n\n',...
'\treadMarkerFile increments trial numbers by 1 so first trial in a dataset has trial=1.\n\n',...
'\tThe MarkerFile format is defined in document CTF MEG File Formats, PN900-0088.\n\n']);
return
end
marker=struct([]);
% Check MarkerFileName
if exist('MarkerFileName')~=1;MarkerFileName=char([]);end
if exist(MarkerFileName)~=2 % No MarkerFile present
fprintf('readMarkerFile: Could not find MarkerFile.\n');
MarkerFileName
return
end
% Check input trialList
if exist('trialList')~=1
trialList=[];
else
trialList=reshape(trialList,1,length(trialList));
if any((trialList-round(trialList))>0.1) | any(round(trialList)<=0)
fprintf('readMarkerFile: trialList must have only positive integers.\n');
return
end
end
fid=fopen(MarkerFileName,'r','ieee-be');
for k=1:5;fgetl(fid);end % Skip 5 lines (including path info)
nMarker=sscanf(fgetl(fid),'%d',1); %Read value and skip to the start of the next non-blank line.
if nMarker<=0
fprintf('readMarkerFile: File %s has %d markers.\n',nMarker);
fclose(fid);
return
end
marker=struct('ClassGroupId',[],'Name',char([]),...
'Comment',char([]),'Color',char([]),'Editable',char([]),'ClassId',[],...
'BitNumber',[],'Polarity',char([]),'Source',char([]),'Threshold',[],...
'trial',[],'time',[]);
for k=1:nMarker
% Find the start of the next marker identification
% There is no need to check for end of file because the loop ends before an attempt
% is made to read marker class nClass+1.
while ~strcmp('CLASSGROUPID:',fgetl(fid));end
ClassGroupId=sscanf(fgetl(fid),'%d',1);
if ~any(ClassGroupId==[0 3])
fprintf('read_MarkerFile: Skipping a marker with CLASSGROUPID=%d\n',ClassGroupId);
continue;
end
fgetl(fid);
Name=deblank(fgetl(fid));
fgetl(fid);
Comment=deblank(fgetl(fid));
fgetl(fid);
Color=deblank(fgetl(fid));
fgetl(fid);
Editable=deblank(fgetl(fid));
fgetl(fid);
ClassId=sscanf(fgetl(fid),'%d',1);
if ClassGroupId==0
fgetl(fid);
BitNumber=sscanf(fgetl(fid),'%d',1);
fgetl(fid);
Polarity=deblank(fgetl(fid));
fgetl(fid);
Source=deblank(fgetl(fid));
fgetl(fid);
Threshold=sscanf(fgetl(fid),'%f',1);
else
BitNumber=[];
Polarity=char([]);
Source=char([]);
Threshold=[];
end
fgetl(fid);
No_of_Samples=sscanf(fgetl(fid),'%d',1);
fgetl(fid);fgetl(fid);
trial=zeros(1,No_of_Samples);
time=zeros(1,No_of_Samples);
if No_of_Samples>0
buff=fscanf(fid,'%d %f\n',2*No_of_Samples);
trial=reshape(buff(1:2:2*No_of_Samples-1),1,No_of_Samples)+1; % Trial numbering starts at 1.
time=reshape(buff(2:2:2*No_of_Samples),1,No_of_Samples);
clear buff;
end
% Keep only the specified trials.
if ~isempty(trialList)
index=[];
for q=trialList;
index=[index find(trial==q)];
end
trial=trial(index);
time=time(index);
No_of_Samples=length(index);
clear q index;
end
marker(k)=struct('ClassGroupId',ClassGroupId,'Name',Name,...
'Comment',Comment,'Color',Color,'Editable',Editable,'ClassId',ClassId,...
'BitNumber',BitNumber,'Polarity',Polarity,'Source',Source,'Threshold',Threshold,...
'trial',trial,'time',time);
end
fclose(fid);
%clear k ClassGroupId Name Comment Color Editable ClassID No_of_Samples trial time;
return
%%%%%%%%%%%% End of readMarkerFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
ft_prepare_layout.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_prepare_layout.m
| 32,267 |
utf_8
|
18d451bdbc116b579311470991ea5e7e
|
function [lay, cfg] = ft_prepare_layout(cfg, data)
% FT_PREPARE_LAYOUT loads or creates a 2-D layout of the channel locations. This layout
% is required for plotting the topographical distribution of the potential
% or field distribution, or for plotting timecourses in a topographical
% arrangement.
%
% Use as
% lay = ft_prepare_layout(cfg, data)
%
% There are several ways in which a 2-D layout can be made: it can be read
% directly from a *.mat file containing a variable 'lay', it can be created
% based on 3-D electrode or gradiometer positions in the configuration or
% in the data, or it can be created based on the specification of an electrode
% or gradiometer file. Layouts can also come from an ASCII *.lay file, but
% this type of layout is no longer recommended.
%
% You can specify any one of the following configuration options
% cfg.layout filename containg the layout (.mat or .lay file)
% can also be a layout structure, which is simply returned
% as-is (see below for details)
% cfg.rotate number, rotation around the z-axis in degrees (default = [], which means automatic)
% cfg.projection string, 2D projection method can be 'stereographic', 'orthographic', 'polar', 'gnomic' or 'inverse' (default = 'polar')
% cfg.elec structure with electrode positions, or
% cfg.elecfile filename containing electrode positions
% cfg.grad structure with gradiometer definition, or
% cfg.gradfile filename containing gradiometer definition
% cfg.output filename to which the layout will be written (default = [])
% cfg.montage 'no' or a montage structure (default = 'no')
% cfg.image filename, use an image to construct a layout (e.g. usefull for ECoG grids)
% cfg.bw if an image is used and bw = 1 transforms the image in black and white (default = 0, do not transform)
% cfg.overlap string, how to deal with overlapping channels when
% layout is constructed from a sensor configuration
% structure (can be 'shift' (shift the positions in 2D
% space to remove the overlap (default)), 'keep' (don't shift,
% retain the overlap), 'no' (throw error when overlap is
% present))
%
% Alternatively the layout can be constructed from either
% data.elec structure with electrode positions
% data.grad structure with gradiometer definition
%
% Alternatively you can specify the following layouts which will be
% generated for all channels present in the data. Note that these layouts
% are suitable for multiplotting, but not for topoplotting.
% cfg.layout = 'ordered' will give you a NxN ordered layout
% cfg.layout = 'vertical' will give you a Nx1 ordered layout
% cfg.layout = 'butterfly' will give you a layout with all channels on top of each other
%
% The output layout structure will contain the following fields
% lay.label = Nx1 cell-array with channel labels
% lay.pos = Nx2 matrix with channel positions
% lay.width = Nx1 vector with the width of each box for multiplotting
% lay.height = Nx1 matrix with the height of each box for multiplotting
% lay.mask = optional cell-array with line segments that determine the area for topographic interpolation
% lay.outline = optional cell-array with line segments that represent the head, nose, ears, sulci or other anatomical features
%
% See also FT_LAYOUTPLOT, FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR
% TODO switch to using planarchannelset function
% undocumented and non-recommended option (for SPM only)
% cfg.style string, '2d' or '3d' (default = '2d')
% Copyright (C) 2007-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_prepare_layout.m 7387 2013-01-23 13:36:54Z eelspa $
revision = '$Id: ft_prepare_layout.m 7387 2013-01-23 13:36:54Z eelspa $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% basic check/initialization of input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2
data = [];
end
% ft_checkdata used to be called here in case data nargin>1, I moved this
% down to the branches of the big if-else-tree where data was actually
% used. speedup ~500ms (ES, dec2012)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set default configuration options
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(cfg, 'rotate'), cfg.rotate = []; end % [] => rotation is determined based on the type of sensors
if ~isfield(cfg, 'style'), cfg.style = '2d'; end
if ~isfield(cfg, 'projection'), cfg.projection = 'polar'; end
if ~isfield(cfg, 'layout'), cfg.layout = []; end
if ~isfield(cfg, 'grad'), cfg.grad = []; end
if ~isfield(cfg, 'elec'), cfg.elec = []; end
if ~isfield(cfg, 'gradfile'), cfg.gradfile = []; end
if ~isfield(cfg, 'elecfile'), cfg.elecfile = []; end
if ~isfield(cfg, 'output'), cfg.output = []; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'montage'), cfg.montage = 'no'; end
if ~isfield(cfg, 'image'), cfg.image = []; end
if ~isfield(cfg, 'bw'), cfg.bw = 0; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'skipscale'), cfg.skipscale = 'no'; end
if ~isfield(cfg, 'skipcomnt'), cfg.skipcomnt = 'no'; end
if ~isfield(cfg, 'overlap'), cfg.overlap = 'shift'; end
cfg = ft_checkconfig(cfg);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to generate the layout structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
skipscale = strcmp(cfg.skipscale, 'yes'); % in general a scale is desired
skipcomnt = strcmp(cfg.skipcomnt, 'yes'); % in general a comment desired
if isa(cfg.layout, 'config')
% convert the nested config-object back into a normal structure
cfg.layout = struct(cfg.layout);
end
% ensure that there is a label field in the data, which is needed for
% ordered/vertical/butterfly modes
if nargin>1 && ~isfield(data, 'label') && isfield(data, 'labelcmb')
data.label = unique(data.labelcmb(:));
end
% check whether cfg.layout already contains a valid layout structure (this can
% happen when higher level plotting functions are called with cfg.layout set to
% a lay structure)
if isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && isfield(cfg.layout, 'width') && isfield(cfg.layout, 'height')
lay = cfg.layout;
elseif isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && (~isfield(cfg.layout, 'width') || ~isfield(cfg.layout, 'height'))
lay = cfg.layout;
% add width and height for multiplotting
d = dist(lay.pos');
nchans = length(lay.label);
for i=1:nchans
d(i,i) = inf; % exclude the diagonal
end
mindist = min(d(:));
lay.width = ones(nchans,1) * mindist * 0.8;
lay.height = ones(nchans,1) * mindist * 0.6;
elseif isequal(cfg.layout, 'butterfly')
if nargin>1 && ~isempty(data)
% look at the data to determine the overlapping channels
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
nchan = length(data.label(chanindx));
lay.label = data.label(chanindx);
else
nchan = length(cfg.channel);
lay.label = cfg.channel;
end
lay.pos = zeros(nchan,2); % centered at (0,0)
lay.width = ones(nchan,1) * 1.0;
lay.height = ones(nchan,1) * 1.0;
lay.mask = {};
lay.outline = {};
skipscale = true; % a scale is not desired
skipcomnt = true; % a comment is initially not desired, or at least requires more thought
elseif isequal(cfg.layout, 'vertical')
if nargin>1 && ~isempty(data)
% look at the data to determine the overlapping channels
data = ft_checkdata(data);
cfg.channel = ft_channelselection(data.label, cfg.channel); % with this order order of channels stays the same
[dum chanindx] = match_str(cfg.channel, data.label); % order of channels according to cfg specified by user
nchan = length(data.label(chanindx));
lay.label = data.label(chanindx);
else
nchan = length(cfg.channel);
lay.label = cfg.channel;
end
for i=1:(nchan+2)
x = 0.5;
y = 1-i/(nchan+1+2);
lay.pos (i,:) = [x y];
lay.width (i,1) = 0.9;
lay.height(i,1) = 0.9 * 1/(nchan+1+2);
if i==(nchan+1)
lay.label{i} = 'SCALE';
elseif i==(nchan+2)
lay.label{i} = 'COMNT';
end
end
lay.mask = {};
lay.outline = {};
elseif isequal(cfg.layout, 'ordered')
if nargin>1 && ~isempty(data)
% look at the data to determine the overlapping channels
data = ft_checkdata(data);
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
nchan = length(data.label(chanindx));
lay.label = data.label(chanindx);
else
nchan = length(cfg.channel);
lay.label = cfg.channel;
end
ncol = ceil(sqrt(nchan))+1;
nrow = ceil(sqrt(nchan))+1;
k = 0;
for i=1:nrow
for j=1:ncol
k = k+1;
if k<=nchan
x = (j-1)/ncol;
y = (nrow-i-1)/nrow;
lay.pos(k,:) = [x y];
lay.width(k,1) = 0.8 * 1/ncol;
lay.height(k,1) = 0.8 * 1/nrow;
end
end
end
lay.label{end+1} = 'SCALE';
lay.width(end+1) = 0.8 * 1/ncol;
lay.height(end+1) = 0.8 * 1/nrow;
x = (ncol-2)/ncol;
y = 0/nrow;
lay.pos(end+1,:) = [x y];
lay.label{end+1} = 'COMNT';
lay.width(end+1) = 0.8 * 1/ncol;
lay.height(end+1) = 0.8 * 1/nrow;
x = (ncol-1)/ncol;
y = 0/nrow;
lay.pos(end+1,:) = [x y];
% try to generate layout from other configuration options
elseif ischar(cfg.layout)
% layout file name specified
if isempty(strfind(cfg.layout, '.'))
cfg.layout = [cfg.layout '.mat'];
if exist(cfg.layout, 'file')
fprintf('layout file without .mat (or .lay) extension specified, appending .mat\n');
lay = ft_prepare_layout(cfg);
else
cfg.layout = [cfg.layout(1:end-3) 'lay'];
lay = ft_prepare_layout(cfg);
end
elseif ft_filetype(cfg.layout, 'matlab')
fprintf('reading layout from file %s\n', cfg.layout);
if ~exist(cfg.layout, 'file')
error('the specified layout file %s was not found', cfg.layout);
end
load(cfg.layout, 'lay');
elseif ft_filetype(cfg.layout, 'layout')
if exist(cfg.layout, 'file')
fprintf('reading layout from file %s\n', cfg.layout);
lay = readlay(cfg.layout);
else
warning_once(sprintf('layout file %s was not found on your path, attempting to use a similarly named .mat file instead',cfg.layout));
cfg.layout = [cfg.layout(1:end-3) 'mat'];
lay = ft_prepare_layout(cfg);
end
elseif ~ft_filetype(cfg.layout, 'layout')
% assume that cfg.layout is an electrode file
fprintf('creating layout from electrode file %s\n', cfg.layout);
lay = sens2lay(ft_read_sens(cfg.layout), cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
end
elseif ischar(cfg.elecfile)
fprintf('creating layout from electrode file %s\n', cfg.elecfile);
lay = sens2lay(ft_read_sens(cfg.elecfile), cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
elseif ~isempty(cfg.elec) && isstruct(cfg.elec)
fprintf('creating layout from cfg.elec\n');
lay = sens2lay(cfg.elec, cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
elseif isfield(data, 'elec') && isstruct(data.elec)
fprintf('creating layout from data.elec\n');
data = ft_checkdata(data);
lay = sens2lay(data.elec, cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
elseif ischar(cfg.gradfile)
fprintf('creating layout from gradiometer file %s\n', cfg.gradfile);
lay = sens2lay(ft_read_sens(cfg.gradfile), cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
elseif ~isempty(cfg.grad) && isstruct(cfg.grad)
fprintf('creating layout from cfg.grad\n');
lay = sens2lay(cfg.grad, cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
elseif isfield(data, 'grad') && isstruct(data.grad)
fprintf('creating layout from data.grad\n');
data = ft_checkdata(data);
lay = sens2lay(data.grad, cfg.rotate, cfg.projection, cfg.style, cfg.overlap);
elseif ~isempty(cfg.image) && isempty(cfg.layout)
fprintf('reading background image from %s\n', cfg.image);
img = imread(cfg.image);
img = flipdim(img, 1); % in combination with "axis xy"
figure
bw = cfg.bw;
if bw
% convert to greyscale image
img = mean(img, 3);
imagesc(img);
colormap gray
else
% plot as RGB image
image(img);
end
hold on
axis equal
axis off
axis xy
% get the electrode positions
pos = zeros(0,2);
electrodehelp = [ ...
'-----------------------------------------------------\n' ...
'specify electrode locations\n' ...
'press the right mouse button to add another electrode\n' ...
'press backspace on the keyboard to remove the last electrode\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(electrodehelp)
disp(round(pos)); % values are integers/pixels
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
pos = cat(1, pos, [x y]);
% add it to the figure
plot(x, y, 'b.');
plot(x, y, 'yo');
case 8
if size(pos,1)>0
% remove the last point
pos = pos(1:end-1,:);
% completely redraw the figure
cla
h = image(img);
hold on
axis equal
axis off
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
end
case 'q'
again = 0;
otherwise
warning('invalid button (%d)', k);
end
end
% get the mask outline
polygon = {};
thispolygon = 1;
polygon{thispolygon} = zeros(0,2);
maskhelp = [ ...
'------------------------------------------------------------------------\n' ...
'specify polygons for masking the topgraphic interpolation\n' ...
'press the right mouse button to add another point to the current polygon\n' ...
'press backspace on the keyboard to remove the last point\n' ...
'press "c" on the keyboard to close this polygon and start with another\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(maskhelp);
fprintf('\n');
for i=1:length(polygon)
fprintf('polygon %d has %d points\n', i, size(polygon{i},1));
end
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
if size(polygon{thispolygon},1)>1
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
end
plot(x, y, 'g.-');
case 8 % backspace
if size(polygon{thispolygon},1)>0
% remove the last point
polygon{thispolygon} = polygon{thispolygon}(1:end-1,:);
% completely redraw the figure
cla
h = image(img);
hold on
axis equal
axis off
% plot the electrode positions
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
for i=1:length(polygon)
x = polygon{i}(:,1);
y = polygon{i}(:,2);
if i~=thispolygon
% close the polygon in the figure
x(end) = x(1);
y(end) = y(1);
end
plot(x, y, 'g.-');
end
end
case 'c'
if size(polygon{thispolygon},1)>0
% close the polygon
polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:);
% close the polygon in the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'g.-');
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'q'
if size(polygon{thispolygon},1)>0
% close the polygon
polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:);
% close the polygon in the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'g.-');
end
again = 0;
otherwise
warning('invalid button (%d)', k);
end
end
% remember this set of polygons as the mask
mask = polygon;
% get the outline, e.g. head shape and sulci
polygon = {};
thispolygon = 1;
polygon{thispolygon} = zeros(0,2);
maskhelp = [ ...
'-----------------------------------------------------------------------------------\n' ...
'specify polygons for adding outlines (e.g. head shape and sulci) to the layout\n' ...
'press the right mouse button to add another point to the current polygon\n' ...
'press backspace on the keyboard to remove the last point\n' ...
'press "c" on the keyboard to close this polygon and start with another\n' ...
'press "n" on the keyboard to start with another without closing the current polygon\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(maskhelp);
fprintf('\n');
for i=1:length(polygon)
fprintf('polygon %d has %d points\n', i, size(polygon{i},1));
end
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
if size(polygon{thispolygon},1)>1
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
end
plot(x, y, 'm.-');
case 8 % backspace
if size(polygon{thispolygon},1)>0
% remove the last point
polygon{thispolygon} = polygon{thispolygon}(1:end-1,:);
% completely redraw the figure
cla
h = image(img);
hold on
axis equal
axis off
% plot the electrode positions
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
for i=1:length(polygon)
x = polygon{i}(:,1);
y = polygon{i}(:,2);
if i~=thispolygon
% close the polygon in the figure
x(end) = x(1);
y(end) = y(1);
end
plot(x, y, 'm.-');
end
end
case 'c'
if size(polygon{thispolygon},1)>0
x = polygon{thispolygon}(1,1);
y = polygon{thispolygon}(1,2);
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'm.-');
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'n'
if size(polygon{thispolygon},1)>0
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'q'
again = 0;
otherwise
warning('invalid button (%d)', k);
end
end
% remember this set of polygons as the outline
outline = polygon;
% convert electrode positions into a layout structure
lay.pos = pos;
nchans = size(pos,1);
for i=1:nchans
lay.label{i,1} = sprintf('chan%03d', i);
end
% add width and height for multiplotting
d = dist(pos');
for i=1:nchans
d(i,i) = inf; % exclude the diagonal
end
mindist = min(d(:));
lay.width = ones(nchans,1) * mindist * 0.8;
lay.height = ones(nchans,1) * mindist * 0.6;
% add mask and outline polygons
lay.mask = mask;
lay.outline = outline;
else
error('no layout detected, please specify cfg.layout')
end
% FIXME there is a conflict between the use of cfg.style here and in topoplot
if ~strcmp(cfg.style, '3d')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check whether outline and mask are available
% if not, add default "circle with triangle" to resemble the head
% in case of "circle with triangle", the electrode positions should also be
% scaled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(lay, 'outline') || ~isfield(lay, 'mask')
rmax = 0.5;
l = 0:2*pi/100:2*pi;
HeadX = cos(l).*rmax;
HeadY = sin(l).*rmax;
NoseX = [0.18*rmax 0 -0.18*rmax];
NoseY = [rmax-.004 rmax*1.15 rmax-.004];
EarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489];
EarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199];
% Scale the electrode positions to fit within a unit circle, i.e. electrode radius = 0.45
ind_scale = strmatch('SCALE', lay.label);
ind_comnt = strmatch('COMNT', lay.label);
sel = setdiff(1:length(lay.label), [ind_scale ind_comnt]); % these are excluded for scaling
x = lay.pos(sel,1);
y = lay.pos(sel,2);
xrange = range(x);
yrange = range(y);
% First scale the width and height of the box for multiplotting
lay.width = lay.width./xrange;
lay.height = lay.height./yrange;
% Then shift and scale the electrode positions
lay.pos(:,1) = 0.9*((lay.pos(:,1)-min(x))/xrange-0.5);
lay.pos(:,2) = 0.9*((lay.pos(:,2)-min(y))/yrange-0.5);
% Define the outline of the head, ears and nose
lay.outline{1} = [HeadX(:) HeadY(:)];
lay.outline{2} = [NoseX(:) NoseY(:)];
lay.outline{3} = [ EarX(:) EarY(:)];
lay.outline{4} = [-EarX(:) EarY(:)];
% Define the anatomical mask based on a circular head
lay.mask{1} = [HeadX(:) HeadY(:)];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply the montage, i.e. combine bipolar channels into a new representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~strcmp(cfg.montage, 'no')
Norg = length(cfg.montage.labelorg);
Nnew = length(cfg.montage.labelnew);
for i=1:Nnew
cfg.montage.tra(i,:) = abs(cfg.montage.tra(i,:));
cfg.montage.tra(i,:) = cfg.montage.tra(i,:) ./ sum(cfg.montage.tra(i,:));
end
% pretend it is a sensor structure, this achieves averaging after channel matching
tmp.tra = lay.pos;
tmp.label = lay.label;
new = ft_apply_montage(tmp, cfg.montage);
lay.pos = new.tra;
lay.label = new.label;
% do the same for the width and height
tmp.tra = lay.width(:);
new = ft_apply_montage(tmp, cfg.montage);
lay.width = new.tra;
tmp.tra = lay.height(:);
new = ft_apply_montage(tmp, cfg.montage);
lay.height = new.tra;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add axes positions for comments and scale information if required
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~any(strcmp('COMNT', lay.label)) && strcmpi(cfg.style, '2d') && ~skipcomnt
% add a placeholder for the comment in the upper left corner
lay.label{end+1} = 'COMNT';
lay.width(end+1) = mean(lay.width);
lay.height(end+1) = mean(lay.height);
X = min(lay.pos(:,1));
Y = max(lay.pos(:,2));
Y = min(lay.pos(:,2));
lay.pos(end+1,:) = [X Y];
elseif any(strcmp('COMNT', lay.label)) && skipcomnt
% remove the scale entry
sel = find(strcmp('COMNT', lay.label));
lay.label(sel) = [];
lay.pos(sel,:) = [];
lay.width(sel) = [];
lay.height(sel) = [];
end
if ~any(strcmp('SCALE', lay.label)) && strcmpi(cfg.style, '2d') && ~skipscale
% add a placeholder for the scale in the upper right corner
lay.label{end+1} = 'SCALE';
lay.width(end+1) = mean(lay.width);
lay.height(end+1) = mean(lay.height);
X = max(lay.pos(:,1));
Y = max(lay.pos(:,2));
Y = min(lay.pos(:,2));
lay.pos(end+1,:) = [X Y];
elseif any(strcmp('SCALE', lay.label)) && skipscale
% remove the scale entry
sel = find(strcmp('SCALE', lay.label));
lay.label(sel) = [];
lay.pos(sel,:) = [];
lay.width(sel) = [];
lay.height(sel) = [];
end
% to plot the layout for debugging, you can use this code snippet
if strcmp(cfg.feedback, 'yes') && strcmpi(cfg.style, '2d')
tmpcfg = [];
tmpcfg.layout = lay;
ft_layoutplot(tmpcfg);
end
% to write the layout to a text file, you can use this code snippet
if ~isempty(cfg.output) && strcmpi(cfg.style, '2d')
fprintf('writing layout to ''%s''\n', cfg.output);
fid = fopen(cfg.output, 'wt');
for i=1:numel(lay.label)
fprintf(fid, '%d %f %f %f %f %s\n', i, lay.pos(i,1), lay.pos(i,2), lay.width(i), lay.height(i), lay.label{i});
end
fclose(fid);
elseif ~isempty(cfg.output) && strcmpi(cfg.style, '3d')
% the layout file format does not support 3D positions, furthermore for
% a 3D layout the width and height are currently set to NaN
error('writing a 3D layout to an output file is not supported');
end
% ensure proper format of some of label (see bug 1909 -roevdmei)
lay.label = lay.label(:);
% do the general cleanup and bookkeeping at the end of the function
ft_postamble provenance
ft_postamble previous data
ft_postamble history lay
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
% read the layout information from the ascii file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function lay = readlay(filename)
if ~exist(filename, 'file')
error(sprintf('could not open layout file: %s', filename));
end
[chNum,X,Y,Width,Height,Lbl,Rem] = textread(filename,'%f %f %f %f %f %q %q');
if length(Rem)<length(Lbl)
Rem{length(Lbl)} = [];
end
for i=1:length(Lbl)
if ~isempty(Rem{i})
% this ensures that channel names with a space in them are also supported (i.e. Neuromag)
Lbl{i} = [Lbl{i} ' ' Rem{i}];
end
end
lay.pos = [X Y];
lay.width = Width;
lay.height = Height;
lay.label = Lbl;
return % function readlay
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
% convert 3D electrode positions into 2D layout
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function lay = sens2lay(sens, rz, method, style, overlap)
% remove the balancing from the sensor definition, e.g. 3rd order gradients, PCA-cleaned data or ICA projections
% this should not be necessary anymore, because the sensor description is
% up-to-date, i.e. explicit information with respect to the channel
% positions is present
%sens = undobalancing(sens);
fprintf('creating layout for %s system\n', ft_senstype(sens));
% apply rotation
if isempty(rz)
switch ft_senstype(sens)
case {'ctf151', 'ctf275', 'bti148', 'bti248', 'ctf151_planar', 'ctf275_planar', 'bti148_planar', 'bti248_planar', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar', 'magnetometer', 'meg'}
rz = 90;
case {'neuromag122', 'neuromag306'}
rz = 0;
case 'electrode'
rz = 90;
otherwise
rz = 0;
end
end
sens.chanpos = warp_apply(rotate([0 0 rz]), sens.chanpos, 'homogenous');
% determine the 3D channel positions
pnt = sens.chanpos;
label = sens.label;
if strcmpi(style, '3d')
lay.pos = pnt;
lay.label = label;
else
prj = elproj(pnt, method);
% this copy will be used to determine the minimum distance between channels
% we need a copy because prj retains the original positions, and
% prjForDist might need to be changed if the user wants to keep
% overlapping channels
prjForDist = prj;
% check whether many channels occupy identical positions, if so shift
% them around if requested
if size(unique(prj,'rows'),1) / size(prj,1) < 0.8
if strcmp(overlap, 'shift')
warning_once('the specified sensor configuration has many overlapping channels, creating a layout by shifting them around (use a template layout for better control over the positioning)');
prj = shiftxy(prj', 0.2)';
prjForDist = prj;
elseif strcmp(overlap, 'no')
error('the specified sensor configuration has many overlapping channels, you specified not to allow that');
elseif strcmp(overlap, 'keep')
prjForDist = unique(prj, 'rows');
else
error('unknown value for cfg.overlap = ''%s''', overlap);
end
end
d = dist(prjForDist');
d(logical(eye(size(d)))) = inf;
% This is a fix for .sfp files, containing positions of 'fiducial
% electrodes'. Their presence determines the minimum distance between
% projected electrode positions, leading to very small boxes.
% This problem has been detected and reported by Matt Mollison.
% FIXME: consider changing the box-size being determined by mindist
% by a mean distance or so; this leads to overlapping boxes, but that
% also exists for some .lay files
if any(strmatch('Fid', label))
tmpsel = strmatch('Fid', label);
d(tmpsel, :) = inf;
d(:, tmpsel) = inf;
end
% take mindist as the median of the first quartile of closest channel pairs with non-zero distance
mindist = min(d); % get closest neighbour for all channels
mindist = sort(mindist(mindist>1e-6),'ascend');
mindist = mindist(1:round(numel(label)/4));
mindist = median(mindist);
X = prj(:,1);
Y = prj(:,2);
Width = ones(size(X)) * mindist * 0.8;
Height = ones(size(X)) * mindist * 0.6;
lay.pos = [X Y];
lay.width = Width;
lay.height = Height;
lay.label = label;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
% shift 2D positions around so that the minimum distance between any pair
% is mindist
%
% Credit for this code goes to Laurence Hunt at UCL.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xy = shiftxy(xy,mindist)
x = xy(1,:);
y = xy(2,:);
l=1;
i=1; %filler
mindist = mindist/0.999; % limits the number of loops
while (~isempty(i) && l<50)
xdiff = repmat(x,length(x),1) - repmat(x',1,length(x));
ydiff = repmat(y,length(y),1) - repmat(y',1,length(y));
xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs
[i,j] = find(xydist<mindist*0.999);
rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j
for m = 1:length(i);
if (xydist(i(m),j(m)) == 0)
diffvec = [mindist./sqrt(2) mindist./sqrt(2)];
else
xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))];
diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff;
end
x(i(m)) = x(i(m)) - diffvec(1)/2;
y(i(m)) = y(i(m)) - diffvec(2)/2;
x(j(m)) = x(j(m)) + diffvec(1)/2;
y(j(m)) = y(j(m)) + diffvec(2)/2;
end
l = l+1;
end
xy = [x; y];
|
github
|
philippboehmsturm/antx-master
|
ft_analysispipeline.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_analysispipeline.m
| 20,188 |
utf_8
|
d09d01943d4f0a9fb448ce59b763a52a
|
function [pipeline] = ft_analysispipeline(cfg, data)
% FT_ANALYSIPIPELINE reconstructs the complete analysis pipeline that was used to create
% the input FieldTrip data structure. The pipeline will be visualized as a flowchart.
% In the future it will be possible to output the complete pipeline as a MATLAB script
% or in a specialized pipeline format (e.g. PSOM, JIST, LONI, Taverna).
%
% Use as
% output = ft_analysisprotocol(cfg, data)
%
% The first cfg input contains the settings that apply to the behaviour of this
% particular function and the second data input argument can be the output of any
% FieldTrip function, e.g. FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS,
% FT_FREQSTATISTICS or whatever you like.
%
% Alternatively, for the second input argument you can also only give the configuration
% of the processed data (i.e. "data.cfg") instead of the full data.
%
% The configuration options that apply to the behaviour of this function are
% cfg.filename = string, filename of m-file to which the script will be
% written (default = [])
% cfg.feedback = string, 'no', 'text', 'gui' or 'yes', whether text and/or
% graphical feedback should be presented (default = 'yes')
% cfg.showinfo = string or cell array of strings, information to display
% in the gui boxes, can be any combination of
% 'functionname', 'revision', 'matlabversion',
% 'computername', 'username', 'calltime', 'timeused',
% 'memused', 'workingdir', 'scriptpath' (default =
% 'functionname', only display function name). Can also
% be 'all', show all pipeline. Please note that if you want
% to show a lot of information, this will require a lot
% of screen real estate.
% cfg.remove = cell-array with strings, determines which objects will
% be removed from the configuration prior to writing it to
% file. For readibility of the script, you may want to
% remove the large objectssuch as event structure, trial
% definition, source positions
% cfg.keepremoved = 'yes' or 'no', determines whether removed fields are
% completely removed, or only replaced by a short textual
% description (default = 'no')
%
% This function uses the nested cfg and cfg.previous that are present in
% the data structure. It will use the configuration and the nested previous
% configurations to climb all the way back into the tree. This funtction
% will print a complete Matlab script to screen (and optionally to file).
% Furthermore, it will show an interactive graphical flowchart
% representation of the steps taken during the pipeline(i). In the flowchart
% you can click on one of the steps to see the configuration details of
% that pipeline(i).
%
% Note that the nested cfg and cfg.previous in your data might not contain
% all details that are required to reconstruct a complete and valid
% analysis script.
%
% See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQANALYSIS, FT_SOURCEANALYSIS,
% FT_CONNECTIVITYANALYSIS, FT_NETWORKANALYSIS
revision = '$Id: ft_analysispipeline.m 7367 2013-01-21 13:25:44Z roboos $';
% callinfo feedback is highly annoying in this recursive function
% do this here, otherwise ft_defaults will override our setting
if ~isfield(cfg, 'showcallinfo'), cfg.showcallinfo = 'no'; end
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% set the defaults
if ~isfield(cfg, 'filename'), cfg.filename = []; end
if ~isfield(cfg, 'showinfo'), cfg.showinfo = {'functionname'}; end
if ~isfield(cfg, 'keepremoved'), cfg.keepremoved = 'no'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'yes'; end
if ~isfield(cfg, 'prune'), cfg.prune = 'yes'; end
if ~isfield(cfg, 'remove')
% this is the default list of configuration elements to be removed. These
% elements would be very large to print and make the script difficult to
% read. To get a correctly behaving script, you may have to change this.
cfg.remove = {
'sgncmb'
'channelcmb'
'event'
'trl'
'trlold'
'artfctdef.eog.trl'
'artfctdef.jump.trl'
'artfctdef.muscle.trl'
'pos'
'inside'
'outside'
'grid.pos'
'grid.inside'
'grid.outside'
'vol.bnd.pnt'
'vol.bnd.tri'
};
elseif ~iscell(cfg.remove)
cfg.remove = {cfg.remove};
end
if strcmp(cfg.showinfo, 'all')
cfg.showinfo = {
'functionname'
'revision'
'matlabversion'
'computername'
'architecture'
'username'
'calltime'
'timeused'
'memused'
'workingdir'
'scriptpath'
};
end
if ~isfield(cfg, 'showinfo')
cfg.showinfo = {'functionname'};
elseif ~iscell(cfg.showinfo)
cfg.showinfo = {cfg.showinfo};
end
% we are only interested in the cfg-part of the data
if isfield(data, 'cfg')
datacfg = data.cfg;
else
datacfg = data;
end
clear data
% walk the tree, gather information about each node
pipeline = walktree(datacfg);
% convert the cell array into a structure array
for i=1:length(pipeline)
tmp(i) = pipeline{i};
end
pipeline = tmp;
if strcmp(cfg.prune, 'yes')
% prune the double occurences
[dummy, indx] = unique({pipeline.this});
pipeline = pipeline(sort(indx));
end
% start at the end of the tree and determine the level of each of the parents
hasparent = false(size(pipeline));
haschild = false(size(pipeline));
for i=1:length(pipeline)
hasparent(i) = ~isempty(pipeline(i).parent) || ~isempty(pipeline(i).parentcfg);
haschild(i) = any(strcmp(pipeline(i).this, [pipeline.parent pipeline.parentcfg]));
end
% construct a matrix with all pipeline steps
width = zeros(size(pipeline));
height = zeros(size(pipeline));
level = 1;
% the items without children start at height 1
sel = find(~haschild);
while ~isempty(sel)
height(sel) = level;
% find the parents of the items at this level
sel = match_str({pipeline.this}, [pipeline(sel).parent pipeline(sel).parentcfg]);
% the parents should be at least one level higher
height(sel) = level + 1;
% continue with the next level
level = level + 1;
end
for i=1:max(height)
sel = find(height==i);
width(sel) = 1:length(sel);
end
for i=1:length(pipeline)
pipeline(i).position = [height(i) width(i)];
end
% sort according to a decreasing level, i.e. the last pipeline(i) at the end
[dummy, indx] = sortrows(-[height(:) width(:)]);
pipeline = pipeline(indx);
plotflowchart(cfg, pipeline);
if ~isempty(cfg.filename)
exportmatlabscript(cfg, pipeline);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for recursive walking along the cfg.previous.previous info
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function info = walktree(cfg)
this = getnode(cfg);
% parse all previous steps
if isfield(cfg, 'previous') && ~isempty(cfg.previous) && iscell(cfg.previous)
previous = cellfun(@walktree, cfg.previous, 'UniformOutput', false);
if iscell(previous{1})
previous = cat(1, previous{:});
end
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) && isstruct(cfg.previous)
previous = walktree(cfg.previous);
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous)
error('unexpected content in cfg.previous');
else
previous = {};
end
% parse the side branches, e.g. cfg.vol and cfg.layout
fn = fieldnames(cfg);
branch = {};
for i=1:numel(fn)
if isstruct(cfg.(fn{i})) && isfield(cfg.(fn{i}), 'cfg')
branch = [branch walktree(cfg.(fn{i}).cfg)];
this.parentcfg{end+1} = branch{end}.this;
end
end
info = [previous {this} branch];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for gathering the information about each pipeline(i)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function node = getnode(cfg)
[p, f, x] = myfileparts(getvalue(cfg, 'version.name'));
node.cfg = cfg;
node.name = f;
node.id = getvalue(cfg, 'version.id');
node.this = CalcMD5(mxSerialize(cfg));
node.parentcfg = {}; % this will be assigned by walktree if needed
if isfield(cfg, 'previous') && ~isempty(cfg.previous) && iscell(cfg.previous)
node.parent = cellfun(@CalcMD5, cellfun(@mxSerialize, cfg.previous, 'UniformOutput', false), 'UniformOutput', false);
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) && isstruct(cfg.previous)
node.parent = {CalcMD5(mxSerialize(cfg.previous))};
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous)
error('unexpected content in cfg.previous');
else
node.parent = {};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function v = getvalue(s, f)
if issubfield(s, f)
v = getsubfield(s, f);
else
v = 'unknown';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [p, f, x] = myfileparts(filename)
if ispc
filename(filename=='/') = filesep;
else
filename(filename=='\') = filesep;
end
[p, f, x] = fileparts(filename);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = button(h, eventdata, handles, varargin)
pos = get(get(gcbo, 'CurrentAxes'), 'CurrentPoint');
x = pos(1,1);
y = pos(1,2);
pipeline = guidata(h);
for i=1:numel(pipeline)
if (x >= pipeline(i).x(1) && x <= pipeline(i).x(2) && y >= pipeline(i).y(1) && y <= pipeline(i).y(3))
cfg = pipeline(i).cfg;
if isfield(cfg, 'previous')
cfg = rmfield(cfg, 'previous');
end
script = printstruct('cfg', cfg);
uidisplaytext(script, pipeline(i).name);
break;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotflowchart(cfg, pipeline)
layout = cell(numel(pipeline));
for i=1:length(pipeline)
% get the vertical and horizontal position in integer values
% high numbers are towards the begin, low numbers are towards the end of the pipeline
v = pipeline(i).position(1);
h = pipeline(i).position(2);
layout{v,h} = pipeline(i).this;
end
% remove the empty columns
maxheight = max(sum(~cellfun(@isempty, layout),1));
maxwidth = max(sum(~cellfun(@isempty, layout),2));
layout = layout(1:maxheight,1:maxwidth);
fig = figure;
hold on
axis manual; % the axis should not change during the contruction of the arrows, otherwise the arrowheads will be distorted
set(gca,'Units','normalized'); % use normalized units
set(gcf, 'ToolBar', 'none');
axis([0 1 0 1])
axis off;
axis tight;
for i=1:numel(pipeline)
% create the text information to display
label = {};
for k = 1:numel(cfg.showinfo)
switch cfg.showinfo{k}
case 'functionname'
% label{end+1} = ['{\bf ' pipeline(i).name '}'];
label{end+1} = pipeline(i).name;
if k == 1 % add blank line if function name is on top, looks nice
label{end+1} = '';
firstLabelIsName = 1;
end
case 'revision'
if isfield(pipeline(i).cfg, 'version') && isfield(pipeline(i).cfg.version, 'id')
label{end+1} = pipeline(i).cfg.version.id;
else
label{end+1} = '<revision unknown>';
end
case 'matlabversion'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'matlab')
label{end+1} = ['MATLAB ' pipeline(i).cfg.callinfo.matlab];
else
label{end+1} = '<MATLAB version unknown>';
end
case 'computername'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'hostname')
label{end+1} = ['Computer name: ' pipeline(i).cfg.callinfo.hostname];
else
label{end+1} = '<hostname unknown>';
end
case 'architecture'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'hostname')
label{end+1} = ['Architecture: ' pipeline(i).cfg.callinfo.computer];
else
label{end+1} = '<architecture unknown>';
end
case 'username'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'user')
label{end+1} = ['Username: ' pipeline(i).cfg.callinfo.user];
else
label{end+1} = '<username unknown>';
end
case 'calltime'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'calltime')
label{end+1} = ['Function called at ' datestr(pipeline(i).cfg.callinfo.calltime)];
else
label{end+1} = '<function call time unknown>';
end
case 'timeused'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'proctime')
label{end+1} = sprintf('Function call required %d seconds.', round(pipeline(i).cfg.callinfo.proctime));
else
label{end+1} = '<processing time unknown>';
end
case 'memused'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'procmem')
label{end+1} = sprintf('Function call required %d MB.', round(pipeline(i).cfg.callinfo.procmem/1024/1024));
else
label{end+1} = '<memory requirement unknown>';
end
case 'workingdir'
if isfield(pipeline(i).cfg, 'callinfo') && isfield(pipeline(i).cfg.callinfo, 'pwd')
label{end+1} = sprintf('Working directory was %s.', pipeline(i).cfg.callinfo.pwd);
else
label{end+1} = '<working directory unknown>';
end
case 'scriptpath'
if isfield(pipeline(i).cfg, 'version') && isfield(pipeline(i).cfg.version, 'name')
label{end+1} = sprintf('Full path to script was %s.', pipeline(i).cfg.version.name);
else
label{end+1} = '<script path unknown>';
end
end
end % for numel(showinfo)
% dublicate backslashes to escape tex interpreter (in case of windows filenames)
label = strrep(label, '\', '\\');
label = strrep(label, '{\\bf', '{\bf'); % undo for bold formatting
% escape underscores
label = strrep(label, '_', '\_');
% strip blank line if present and not needed
if strcmp(label{end},'')
label(end) = [];
end
% compute width and height of each box, note that axis Units are set to Normalized
boxsize = 1./[maxwidth+1 maxheight+1];
% create the 4 corners for our patch, close the patch by returning to the start point
x = ([0 1 1 0 0]-0.5) .* boxsize(1);
y = ([0 0 1 1 0]-0.5) .* boxsize(2);
% position the patch
location = pipeline(i).position([2 1]);
location(1) = (location(1)-0.5)/maxwidth;
location(2) = (location(2)-0.5)/maxheight;
% the location specifies the center of the patch
x = x + location(1);
y = y + location(2);
p = patch(x', y', 0);
set(p, 'Facecolor', [1 1 0.6])
pipeline(i).x = x;
pipeline(i).y = y;
guidata(fig, pipeline);
if length(label)==1
textloc = location;
l = text(textloc(1), textloc(2), label);
set(l, 'HorizontalAlignment', 'center');
set(l, 'VerticalAlignment', 'middle');
set(l, 'fontUnits', 'points');
set(l, 'fontSize', 10);
set(l, 'interpreter', 'tex');
else
textloc = location;
textloc(1) = textloc(1)-boxsize(1)/2;
textloc(2) = textloc(2)+boxsize(2)/2;
l = text(textloc(1), textloc(2), label);
set(l, 'HorizontalAlignment', 'left');
set(l, 'VerticalAlignment', 'top');
set(l, 'fontUnits', 'points');
set(l, 'fontSize', 10);
set(l, 'interpreter', 'tex');
end
% draw an arrow if appropriate
n1 = length(pipeline(i).parentcfg);
n2 = length(pipeline(i).parent);
n = n1+n2;
for j=1:n1
[parentlocation(2), parentlocation(1)] = ind2sub([maxheight, maxwidth], find(strcmp(layout(:), pipeline(i).parentcfg{j}), 1, 'first'));
% parentlocation = info(find(strcmp({pipeline.this}, analysis.parent{j}), 1, 'first')).position;
parentlocation(1) = (parentlocation(1)-0.5)/maxwidth;
parentlocation(2) = (parentlocation(2)-0.5)/maxheight;
base = parentlocation + [0 -0.5].*boxsize;
if n>1
% distribute the inputs evenly over the box
rel = 2*(j-1)/(n-1)-1; % relative location between -1.0 and 1.0
rel = rel*(n-1)/(n+3); % compress the relative location
tip = location + [0 0.5].*boxsize + [rel 0].*boxsize/2;
else
% put it in the centre
tip = location + [0 0.5].*boxsize;
end
arrow(base, tip, 'length', 8, 'lineWidth', 1, 'lineStyle', ':');
end
for j=1:n2
[parentlocation(2), parentlocation(1)] = ind2sub([maxheight, maxwidth], find(strcmp(layout(:), pipeline(i).parent{j}), 1, 'first'));
% parentlocation = info(find(strcmp({pipeline.this}, analysis.parent{j}), 1, 'first')).position;
parentlocation(1) = (parentlocation(1)-0.5)/maxwidth;
parentlocation(2) = (parentlocation(2)-0.5)/maxheight;
base = parentlocation + [0 -0.5].*boxsize;
if n>1
% distribute the inputs evenly over the box
rel = 2*(j+n1-1)/(n-1)-1; % relative location between -1.0 and 1.0
rel = rel*(n-1)/(n+3); % compress the relative location
tip = location + [0 0.5].*boxsize + [rel 0].*boxsize/2;
else
% put it in the centre
tip = location + [0 0.5].*boxsize;
end
arrow(base, tip, 'length', 8, 'lineWidth', 1);
end
end % for numel(info)
set(fig, 'WindowButtonUpFcn', @button);
% set(fig, 'KeyPressFcn', @key);
% add a menu to the figure
% ftmenu = uicontextmenu; set(gcf, 'uicontextmenu', ftmenu)
ftmenu = uimenu(fig, 'Label', 'FieldTrip');
ftmenu1 = uimenu(ftmenu, 'Label', 'Save pipeline');
ftmenu2 = uimenu(ftmenu, 'Label', 'Share pipeline');
uimenu(ftmenu, 'Label', 'About', 'Separator', 'on', 'Callback', @menu_about);
uimenu(ftmenu1, 'Label', 'Save as MATLAB script');
uimenu(ftmenu1, 'Label', 'Save as PSOM pipeline');
uimenu(ftmenu1, 'Label', 'Save as HTML page');
uimenu(ftmenu2, 'Label', 'Share within DCCN');
uimenu(ftmenu2, 'Label', 'Share on PasteBin.com');
uimenu(ftmenu2, 'Label', 'Share on MyExperiment.org');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function exportmatlabscript(cfg, pipeline)
varname = {};
varhash = {};
for i=1:length(pipeline)
varname{end+1} = sprintf('variable_%d_%d', pipeline(i).position(1), pipeline(i).position(2));
varhash{end+1} = pipeline(i).this;
end
for i=1:length(pipeline)
pipeline(i).inputvar = {};
pipeline(i).outputvar = varname{strcmp(varhash, pipeline(i).this)};
for j=1:length(pipeline(i).parent)
pipeline(i).inputvar{j} = varname{strcmp(varhash, pipeline(i).parent{j})};
end
end
sep = sprintf('\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n');
script = sep;
for i=1:length(pipeline)
thiscfg = pipeline(i).cfg;
if isfield(thiscfg, 'previous')
thiscfg = rmfield(thiscfg, 'previous');
end
cfgstr = printstruct('cfg', thiscfg);
if ~isempty(pipeline(i).inputvar)
inputvar = sprintf(', %s', pipeline(i).inputvar{:});
else
inputvar = '';
end
cmd = sprintf('\n%s = %s(cfg%s);', pipeline(i).outputvar, pipeline(i).name, inputvar);
script = cat(2, script, cfgstr, cmd, sep);
end
[p, f, x] = fileparts(cfg.filename);
filename = fullfile(p, [f '.m']);
% write the complete script to file
fprintf('exporting MATLAB script to file ''%s''\n', filename);
fid = fopen(filename, 'wb');
fprintf(fid, '%s', script);
fclose(fid);
|
github
|
philippboehmsturm/antx-master
|
ft_freqbaseline.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_freqbaseline.m
| 6,365 |
utf_8
|
8e3f594a996245ab60e43110c92934ef
|
function [freq] = ft_freqbaseline(cfg, freq)
% FT_FREQBASELINE performs baseline normalization for time-frequency data
%
% Use as
% [freq] = ft_freqbaseline(cfg, freq)
% where the freq data comes from FT_FREQANALYSIS and the configuration
% should contain
% cfg.baseline = [begin end] (default = 'no')
% cfg.baselinetype = 'absolute', 'relchange' or 'relative' (default = 'absolute')
% cfg.parameter = field for which to apply baseline normalization, or
% cell array of strings to specify multiple fields to normalize
% (default = 'powspctrm')
%
% See also FT_FREQANALYSIS, FT_TIMELOCKBASELINE, FT_FREQCOMPARISON
% Undocumented local options:
% cfg.inputfile = one can specifiy preanalysed saved data as input
% cfg.outputfile = one can specify output as file to save to disk
% Copyright (C) 2004-2006, Marcel Bastiaansen
% Copyright (C) 2005-2006, Robert Oostenveld
% Copyright (C) 2011, Eelke Spaak
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_freqbaseline.m 7398 2013-01-23 15:50:59Z jorhor $
revision = '$Id: ft_freqbaseline.m 7398 2013-01-23 15:50:59Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar freq
% check if the input data is valid for this function
freq = ft_checkdata(freq, 'datatype', 'freq', 'feedback', 'yes');
% update configuration fieldnames
cfg = ft_checkconfig(cfg, 'renamed', {'param', 'parameter'});
% set the defaults
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute');
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
% check validity of input options
cfg = ft_checkopt(cfg, 'baseline', {'char', 'doublevector'});
cfg = ft_checkopt(cfg, 'baselinetype', 'char', {'absolute', 'relative', 'relchange'});
cfg = ft_checkopt(cfg, 'parameter', {'char', 'charcell'});
% make sure cfg.parameter is a cell array of strings
if (~isa(cfg.parameter, 'cell'))
cfg.parameter = {cfg.parameter};
end
% is input consistent?
if ischar(cfg.baseline) && strcmp(cfg.baseline, 'no') && ~isempty(cfg.baselinetype)
warning('no baseline correction done');
end
% process possible yes/no value of cfg.baseline
if ischar(cfg.baseline) && strcmp(cfg.baseline, 'yes')
% default is to take the prestimulus interval
cfg.baseline = [-inf 0];
elseif ischar(cfg.baseline) && strcmp(cfg.baseline, 'no')
% nothing to do
return
end
% check if the field of interest is present in the data
if (~all(isfield(freq, cfg.parameter)))
error('cfg.parameter should be a string or cell array of strings referring to (a) field(s) in the freq input structure')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Computation of output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% initialize output structure
freqOut = [];
freqOut.label = freq.label;
freqOut.freq = freq.freq;
freqOut.dimord = freq.dimord;
freqOut.time = freq.time;
if isfield(freq, 'grad')
freqOut.grad = freq.grad;
end
if isfield(freq, 'elec')
freqOut.elec = freq.elec;
end
if isfield(freq, 'trialinfo')
freqOut.trialinfo = freq.trialinfo;
end
% loop over all fields that should be normalized
for k = 1:numel(cfg.parameter)
par = cfg.parameter{k};
if strcmp(freq.dimord, 'chan_freq_time')
freqOut.(par) = ...
performNormalization(freq.time, freq.(par), cfg.baseline, cfg.baselinetype);
elseif strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'chan_chan_freq_time')
freqOut.(par) = zeros(size(freq.(par)));
% loop over trials, perform normalization per trial
for l = 1:size(freq.(par), 1)
tfdata = freq.(par)(l,:,:,:);
siz = size(tfdata);
tfdata = reshape(tfdata, siz(2:end));
freqOut.(par)(l,:,:,:) = ...
performNormalization(freq.time, tfdata, cfg.baseline, cfg.baselinetype);
end
else
error('unsupported data dimensions: %s', freq.dimord);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Output scaffolding
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous freq
% rename the output variable to accomodate the savevar postamble
freq = freqOut;
ft_postamble history freq
ft_postamble savevar freq
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that actually performs the normalization on an arbitrary quantity
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = performNormalization(timeVec, data, baseline, baselinetype)
baselineTimes = (timeVec >= baseline(1) & timeVec <= baseline(2));
if length(size(data)) ~= 3,
error('time-frequency matrix should have three dimensions (chan,freq,time)');
end
% compute mean of time/frequency quantity in the baseline interval,
% ignoring NaNs, and replicate this over time dimension
meanVals = repmat(nanmean(data(:,:,baselineTimes), 3), [1 1 size(data, 3)]);
if (strcmp(baselinetype, 'absolute'))
data = data - meanVals;
elseif (strcmp(baselinetype, 'relative'))
data = data ./ meanVals;
elseif (strcmp(baselinetype, 'relchange'))
data = (data - meanVals) ./ meanVals;
else
error('unsupported method for baseline normalization: %s', baselinetype);
end
|
github
|
philippboehmsturm/antx-master
|
ft_sourceinterpolate.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_sourceinterpolate.m
| 18,972 |
utf_8
|
e8e4f5c04c87d8718c7769028703cede
|
function [interp] = ft_sourceinterpolate(cfg, functional, anatomical)
% FT_SOURCEINTERPOLATE interpolates the source reconstructed activity
% or a statistical distribution onto the voxels or vertices of an
% anatomical description of the brain. Both the functional and the
% anatomical data can either describe a 3-dimensional volume, a
% triangulated description of the cortical sheet or an arbitrary cloud
% of points.
%
% The following scenarios are possible:
%
% -The functional data is defined on a low resolution 2-dimensional triangulated
% mesh, the vertices being a subset of the high resolution 2-dimensional
% triangulated anatomical mesh. This allows for mesh based interpolation. The
% algorithm currently implemented is so-called 'smudging' as it is also
% applied by the MNE-suite software.
%
% -Both the functional and the anatomical data are defined on an irregular
% point cloud (can be a 2D triangulated mesh).
%
% -The functional data is defined on an irregular point cloud (can be a 2D
% triangulated mesh), and the anatomical data is a volumetric image.
%
% -The functional data is defined on a 3D regular grid of source positions
% and the anatomical data is defined on an irregular point cloud (can be a
% 2D triangulated mesh).
%
% -The functional data is defined on a 3D regular grid of source positions
% and the anatomical data is a volumetric image.
%
% The functional and anatomical data should be expressed in the same
% coordinate sytem, i.e. either both in CTF coordinates (NAS/LPA/RPA)
% or both in SPM coordinates (AC/PC).
%
% The output data will contain a description of the functional data
% at the locations at which the anatomical data are defined. For
% example, if the anatomical data was volumetric, the output data is
% a volume-structure, containing the resliced source and the anatomical
% volume that can be plotted together, using FT_SOURCEPLOT or, or that can
% be written to file using FT_SOURCEWRITE.
%
% Use as
% [interp] = ft_sourceinterpolate(cfg, source, anatomy)
% [interp] = ft_sourceinterpolate(cfg, stat, anatomy)
% where
% source is the output of FT_SOURCEANALYSIS
% stat is the output of FT_SOURCESTATISTICS
% anatomy is the output of FT_READ_MRI or one of the FT_VOLUMExxx functions,
% a cortical sheet that was read with FT_READ_HEADSHAPE, or a regular
% 3D grid created with FT_PREPARE_SOURCEMODEL.
% and cfg is a structure with any of the following fields
% cfg.parameter = string (or cell-array) of the parameter(s) to be interpolated
% cfg.interpmethod = when interpolating two 3D volumes onto each
% other: 'linear', 'cubic', 'nearest' or 'spline'
% (default = 'linear')
% when interpolating a point
% cloud onto a 3D volume, a 3D volume onto a point
% cloud, or a point cloud with another point cloud:
% 'nearest', 'sphere_avg' or 'smudge' (default =
% 'nearest')
% cfg.downsample = integer number (default = 1, i.e. no downsampling)
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS, FT_READ_MRI,
% FT_READ_HEADSHAPE
% Undocumented options
% cfg.voxelcoord = 'yes' (default) or 'no' determines whether the
% downsampled output anatomical MRI will have the x/y/zgrid converted or
% the homogeneous transformation matrix
% Copyright (C) 2003-2007, Robert Oostenveld
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourceinterpolate.m 7398 2013-01-23 15:50:59Z jorhor $
revision = '$Id: ft_sourceinterpolate.m 7398 2013-01-23 15:50:59Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar functional anatomical
% this is not supported any more as of 26/10/2011
if ischar(anatomical),
error('please use cfg.inputfile instead of specifying the input variable as a sting');
end
% ft_checkdata is done further down
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'unused', {'keepinside'});
cfg = ft_checkconfig(cfg, 'deprecated', {'sourceunits', 'mriunits'});
cfg = ft_checkconfig(cfg, 'required', 'parameter');
% set the defaults
cfg.downsample = ft_getopt(cfg, 'downsample', 1);
cfg.voxelcoord = ft_getopt(cfg, 'voxelcoord', 'yes');
cfg.feedback = ft_getopt(cfg, 'feedback', 'text');
% cfg.interpmethod depends on how the interpolation should be done and will
% be specified below
if ~isa(cfg.parameter, 'cell')
cfg.parameter = {cfg.parameter};
end
if isfield(anatomical, 'transform') && isfield(anatomical, 'dim')
% anatomical volume
is2Dana = 0;
elseif isfield(anatomical, 'pos') && isfield(anatomical, 'dim')
% 3D regular grid
is2Dana = 0;
elseif isfield(anatomical, 'pos') || isfield(anatomical, 'pnt')
% anatomical data consists of a mesh, but no smudging possible
is2Dana = 1;
end
if isfield(functional, 'dim') && numel(functional.dim)==3
is2Dfun = 0;
else
is2Dfun = 1;
end
if is2Dfun && is2Dana && isfield(anatomical, 'orig') && isfield(anatomical.orig, 'pnt') && isfield(anatomical.orig, 'tri'),
% anatomical data consists of a decimated triangulated mesh, containing
% the original description, allowing for smudging. The coordinate systems
% do not necessarily have to align. Should this be imposed?
dosmudge = 1;
else
dosmudge = 0;
end
if dosmudge && is2Dana && is2Dfun
% smudge the low resolution functional data according to the strategy in
% MNE-suite (chapter 8.3 of the manual)
% hmmmm, if the input data contains a time dimension, then the output
% may be terribly blown up; most convenient would be to output only the
% smudging matrix, and project the data when plotting
if ~isfield(anatomical, 'orig')
error('this is not yet implemented');
end
interpmat = interp_ungridded(anatomical.pnt, anatomical.orig.pnt, 'projmethod', 'smudge', 'triout', anatomical.orig.tri);
interp = [];
interp.pos = anatomical.orig.pnt;
interp.tri = anatomical.orig.tri;
if isfield(interp, 'dim'),
interp = rmfield(interp, 'dim');
end
interp.inside = (1:size(interp.pos,1))';
interp.outside = [];
for k = 1:numel(cfg.parameter)
interp = setsubfield(interp, cfg.parameter{k}, interpmat*getsubfield(functional, cfg.parameter{k}));
end
% elseif is2Dana && is2Dfun
elseif (~is2Dana && is2Dfun) || (is2Dana && is2Dfun)
% set default interpmethod for this situation
cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');
cfg.sphereradius = ft_getopt(cfg, 'sphereradius', 0.5);
% interpolate onto a 3D volume, ensure that the anatomical is indeed a volume
if ~is2Dana
anatomical = ft_checkdata(anatomical, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
% get voxel indices, convert to positions and use interp_ungridded
dim = anatomical.dim;
[x,y,z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3));
pos = warp_apply(anatomical.transform, [x(:) y(:) z(:)]);
clear x y z
else
anatomical = ft_checkdata(anatomical, 'hasunits', 'yes');
if isfield(anatomical, 'pos')
pos = anatomical.pos;
elseif isfield(anatomical, 'pnt')
pos = anatomical.pos;
else
error('the input data sould contain either a pos or pnt field');
end
end
functional = ft_convert_units(functional, anatomical.unit);
interpmat = interp_ungridded(functional.pos, pos, ...
'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius); %FIXME include other key-value pairs as well
interp = [];
if isfield(functional, 'time')
interp.time = functional.time;
end
if isfield(functional, 'freq')
interp.freq = functional.freq;
end
interpmat(~anatomical.inside(:), :) = 0;
% identify the inside voxels after interpolation
nzeros = sum(interpmat~=0,2);
newinside = find(nzeros~=0);
newoutside = find(nzeros==0);
for k = 1:numel(cfg.parameter)
tmp = getsubfield(functional, cfg.parameter{k});
tmp = interpmat*tmp;
tmp(newoutside,:) = nan;
interp = setsubfield(interp, cfg.parameter{k}, tmp);
end
interp.pos = pos;
if ~is2Dana, interp.dim = dim; end
interp.inside = newinside(:)';
interp.outside = newoutside(:)';
elseif is2Dana && ~is2Dfun
% ensure the functional data to be in double precision
functional = ft_struct2double(functional);
% ensure to keep the fields if these exist (will be lost in ft_checkdata)
if isfield(functional, 'time'), time = functional.time; end
if isfield(functional, 'freq'), freq = functional.freq; end
% set default interpmethod for this situation
cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');
cfg.sphereradius = ft_getopt(cfg, 'sphereradius', []);
% interpolate the 3D volume onto the anatomy
anatomical = ft_convert_units(anatomical);
%functional = ft_checkdata(functional, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
functional = ft_convert_units(functional, anatomical.unit);
% get voxel indices and use interp_ungridded
dim = functional.dim;
%[X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3));
%interpmat = interp_ungridded([X(:) Y(:) Z(:)], warp_apply(inv(functional.transform), anatomical.pnt), ...,
% 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius);
%clear X Y Z;
interpmat = interp_ungridded(functional.pos, anatomical.pnt, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'inside', functional.inside);
interp = [];
interp.pos = anatomical.pnt;
interp.inside = (1:size(anatomical.pnt,1))';
interp.outside = [];
if isfield(anatomical, 'tri'), interp.tri = anatomical.tri; end
if exist('time', 'var'), interp.time = time; end
if exist('freq', 'var'), interp.freq = freq; end
for k = 1:numel(cfg.parameter)
tmp = getsubfield(functional, cfg.parameter{k});
interp = setsubfield(interp, cfg.parameter{k}, interpmat*reshape(tmp, [prod(dim) numel(tmp)./prod(dim)]));
end
elseif ~is2Dana && ~is2Dfun
% original implementation interpolate a 3D volume onto another 3D volume
% set default interpmethod for this situation
cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'linear');
% check if the input data is valid for this function and ensure that the structures correctly describes a volume
functional = ft_checkdata(functional, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
anatomical = ft_checkdata(anatomical, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
% ensure that the functional data has the same unit as the anatomical
% data
functional = ft_convert_units(functional, anatomical.unit);
if ~isequal(cfg.downsample, 1)
% downsample the anatomical volume
tmpcfg = [];
tmpcfg.downsample = cfg.downsample;
tmpcfg.parameter = 'anatomy';
anatomical = ft_volumedownsample(tmpcfg, anatomical);
end
% collect the functional volumes that should be converted
vol_name = {};
vol_data = {};
for i=1:length(cfg.parameter)
if ~issubfield(functional, cfg.parameter{i}) && issubfield(functional, ['avg.' cfg.parameter{i}])
% the data is located in the avg sub-structure
cfg.parameter{i} = ['avg.' cfg.parameter{i}];
end
if ~iscell(getsubfield(functional, cfg.parameter{i}))
vol_name{end+1} = cfg.parameter{i};
vol_data{end+1} = getsubfield(functional, cfg.parameter{i});
else
fprintf('not interpolating %s, since it is not a scalar field\n', cfg.parameter{i});
end
end
% remember the coordinate trandsformation for both
transform_ana = anatomical.transform;
transform_fun = functional.transform;
% convert the anatomical voxel positions into voxel indices into the functional volume
anatomical.transform = functional.transform \ anatomical.transform;
functional.transform = eye(4);
[fx, fy, fz] = voxelcoords(functional);
[ax, ay, az] = voxelcoords(anatomical);
% estimate the subvolume of the anatomy that is spanned by the functional volume
minfx = 1;
minfy = 1;
minfz = 1;
maxfx = functional.dim(1);
maxfy = functional.dim(2);
maxfz = functional.dim(3);
sel = ax(:)>=minfx & ...
ax(:)<=maxfx & ...
ay(:)>=minfy & ...
ay(:)<=maxfy & ...
az(:)>=minfz & ...
az(:)<=maxfz;
fprintf('selecting subvolume of %.1f%%\n', 100*sum(sel)./prod(anatomical.dim));
% start with an empty output structure
interp = [];
dimf = [functional.dim 1 1];
allav = zeros([anatomical.dim dimf(4:end)]);
functional.inside = functional.inside(:,:,:,1,1);
if all(functional.inside(:))
% keep all voxels marked as inside
interp.inside = true(anatomical.dim);
else
% reslice and interpolate inside
interp.inside = zeros(anatomical.dim);
% interpolate with method nearest
interp.inside( sel) = my_interpn(double(functional.inside), ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback);
interp.inside(~sel) = 0;
interp.inside = logical(interp.inside);
end
% prepare the grid that is used in the interpolation
fg = [fx(:) fy(:) fz(:)];
clear fx fy fz
% reslice and interpolate all functional volumes
for i=1:length(vol_name)
fprintf('reslicing and interpolating %s\n', vol_name{i});
for k=1:dimf(4)
for m=1:dimf(5)
fv = vol_data{i}(:,:,:,k,m);
if ~isa(fv, 'double')
% only convert if needed, this saves memory
fv = double(fv);
end
av = zeros(anatomical.dim);
% av( sel) = my_interpn(fx, fy, fz, fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback);
if islogical(vol_data{i})
% interpolate always with method nearest
av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback);
av = logical(av);
else
if ~all(functional.inside(:))
% extrapolate the outside of the functional volumes for better interpolation at the edges
fv(~functional.inside) = griddatan(fg(functional.inside(:), :), fv(functional.inside(:)), fg(~functional.inside(:), :), 'nearest');
end
% interpolate functional onto anatomical grid
av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback);
clear fv
av(~sel) = nan;
av(~interp.inside) = nan;
end
allav(:,:,:,k,m) = av;
clear av
end
end
interp = setsubfield(interp, vol_name{i}, allav);
end
% add the other parameters to the output
interp.dim = anatomical.dim;
interp.transform = transform_ana; % the original coordinate system
if ~any(strcmp(cfg.parameter, 'anatomy')) && isfield(anatomical, 'anatomy')
% copy the anatomy into the functional data
interp.anatomy = anatomical.anatomy;
end
end
% these stay the same as the input anatomical MRI
if isfield(anatomical, 'coordsys')
interp.coordsys = anatomical.coordsys;
end
if isfield(anatomical, 'unit')
interp.unit = anatomical.unit;
end
if exist('interpmat', 'var')
cfg.interpmat = interpmat;
cfg.interpmat; % access it once to fool the cfg-tracking
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous functional anatomical
ft_postamble history interp
ft_postamble savevar interp
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION this function computes the location of all voxels in head
% coordinates in a memory efficient manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x, y, z] = voxelcoords(volume)
dim = volume.dim;
transform = volume.transform;
if isfield(volume, 'xgrid')
xgrid = volume.xgrid;
ygrid = volume.ygrid;
zgrid = volume.zgrid;
else
xgrid = 1:dim(1);
ygrid = 1:dim(2);
zgrid = 1:dim(3);
end
npix = prod(dim(1:2)); % number of voxels in a single slice
x = zeros(dim);
y = zeros(dim);
z = zeros(dim);
X = zeros(1,npix);
Y = zeros(1,npix);
Z = zeros(1,npix);
E = ones(1,npix);
% determine the voxel locations per slice
for i=1:dim(3)
[X(:), Y(:), Z(:)] = ndgrid(xgrid, ygrid, zgrid(i));
tmp = transform*[X; Y; Z; E];
x((1:npix)+(i-1)*npix) = tmp(1,:);
y((1:npix)+(i-1)*npix) = tmp(2,:);
z((1:npix)+(i-1)*npix) = tmp(3,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for memory efficient interpolation
% the only reason for this function is that it does the interpolation in smaller chuncks
% this prevents memory problems that I often encountered here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [av] = my_interpn(fx, fy, fz, fv, ax, ay, az, interpmethod, feedback);
function [av] = my_interpn(fv, ax, ay, az, interpmethod, feedback)
num = numel(ax); % total number of voxels
blocksize = floor(num/20); % number of voxels to interpolate at once, split it into 20 chuncks
lastblock = 0; % boolean flag for while loop
sel = 1:blocksize; % selection of voxels that are interpolated, this is the first chunck
av = zeros(size(ax));
ft_progress('init', feedback, 'interpolating');
while (1)
ft_progress(sel(1)/num, 'interpolating %.1f%%\n', 100*sel(1)/num);
if sel(end)>=num
sel = sel(1):num;
lastblock = 1;
end
av(sel) = interpn(fv, ax(sel), ay(sel), az(sel), interpmethod);
if lastblock
break
end
sel = sel + blocksize;
end
ft_progress('close');
|
github
|
philippboehmsturm/antx-master
|
ft_megplanar.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_megplanar.m
| 14,646 |
utf_8
|
af259a2e1ff9a0dca3919e64523a12c3
|
function [data] = ft_megplanar(cfg, data)
% FT_MEGPLANAR computes planar MEG gradients gradients for raw data or average
% event-related field data. It can also convert frequency-domain data that was computed
% using FT_FREQANALYSIS, as long as it contains the complex-valued fourierspcrm and not
% only the powspctrm.
%
% Use as
% [interp] = ft_megplanar(cfg, data)
% where the input data corresponds to the output from FT_PREPROCESSING,
% FT_TIMELOCKANALYSIS or FT_FREQANALYSIS (with output='fourierspcrm').
%
% The configuration should contain
% cfg.planarmethod = string, can be 'sincos', 'orig', 'fitplane', 'sourceproject' (default = 'sincos')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'), see FT_CHANNELSELECTION for details
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
%
% The methods orig, sincos and fitplane are all based on a neighbourhood interpolation.
% For these methods you need to specify
% cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS
%
% In the 'sourceproject' method a minumum current estimate is done using a large number
% of dipoles that are placed in the upper layer of the brain surface, followed by a
% forward computation towards a planar gradiometer array. This requires the
% specification of a volume conduction model of the head and of a source model. The
% 'sourceproject' method is not supported for frequency domain data.
%
% A dipole layer representing the brain surface must be specified with
% cfg.inwardshift = depth of the source layer relative to the head model surface (default = 2.5 cm, which is appropriate for a skin-based head model)
% cfg.spheremesh = number of dipoles in the source layer (default = 642)
% cfg.pruneratio = for singular values, default is 1e-3
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
% If no headshape is specified, the dipole layer will be based on the inner compartment
% of the volume conduction model.
%
% The volume conduction model of the head should be specified as
% cfg.vol = structure with volume conduction model, see FT_PREPARE_HEADMODEL
% cfg.hdmfile = name of file containing the volume conduction model, see FT_READ_VOL
%
% The following cfg fields are optional:
% cfg.feedback
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_COMBINEPLANAR, FT_NEIGHBOURSELECTION
% This function depends on FT_PREPARE_BRAIN_SURFACE which has the following options:
% cfg.headshape (default set in FT_MEGPLANAR: cfg.headshape = 'headmodel'), documented
% cfg.inwardshift (default set in FT_MEGPLANAR: cfg.inwardshift = 2.5), documented
% cfg.spheremesh (default set in FT_MEGPLANAR: cfg.spheremesh = 642), documented
%
% This function depends on FT_PREPARE_VOL_SENS which has the following options:
% cfg.channel
% cfg.elec
% cfg.elecfile
% cfg.grad
% cfg.gradfile
% cfg.hdmfile, documented
% cfg.order
% cfg.vol, documented
% Copyright (C) 2004, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_megplanar.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_megplanar.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar data
% store the original input representation of the data, this is used later on to convert it back
isfreq = ft_datatype(data, 'freq');
israw = ft_datatype(data, 'raw');
istlck = ft_datatype(data, 'timelock'); % this will be temporary converted into raw
% check if the input data is valid for this function, this converts the data if needed
data = ft_checkdata(data, 'datatype', {'raw' 'freq'}, 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes', 'senstype', {'ctf151', 'ctf275', 'bti148', 'bti248', 'itab153', 'yokogawa160', 'yokogawa64'});
if istlck
% the timelocked data has just been converted to a raw representation
% and will be converted back to timelocked at the end of this function
israw = true;
end
if isfreq,
if ~isfield(data, 'fourierspctrm'), error('freq data should contain Fourier spectra'); end
end
% set the default configuration
cfg.channel = ft_getopt(cfg, 'channel', 'MEG');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.planarmethod = ft_getopt(cfg, 'planarmethod', 'sincos');
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
cfg.outputfile = ft_getopt(cfg, 'outputfile', []);
cfg.feedback = ft_getopt(cfg, 'feedback', 'text');
% check if the input cfg is valid for this function
if ~strcmp(cfg.planarmethod, 'sourceproject')
cfg = ft_checkconfig(cfg, 'required', {'neighbours'});
end
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
% put the low-level options pertaining to the dipole grid in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'});
cfg = ft_checkconfig(cfg, 'renamedvalue', {'headshape', 'headmodel', []});
% select trials of interest
if ~strcmp(cfg.trials, 'all')
fprintf('selecting %d trials\n', length(cfg.trials));
data = ft_selectdata(data, 'rpt', cfg.trials);
end
if strcmp(cfg.planarmethod, 'sourceproject')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Do an inverse computation with a simplified distributed source model
% and compute forward again with the axial gradiometer array replaced by
% a planar one.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% method specific configuration options
cfg.headshape = ft_getopt(cfg, 'headshape', []);
cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 2.5); % this number assumes that all other inputs are in cm
cfg.pruneratio = ft_getopt(cfg, 'pruneratio', 1e-3);
cfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642);
if isfreq
error('the method ''sourceproject'' is not supported for frequency data as input');
end
Nchan = length(data.label);
Ntrials = length(data.trial);
% FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the
% volume model labels (in case of a localspheres model) and result in a gradiometer
% definition that only contains the gradiometers that are present in the data.
[vol, axial.grad, cfg] = prepare_headmodel(cfg, data);
% determine the dipole layer that represents the surface of the brain
if isempty(cfg.headshape)
% construct from the inner layer of the volume conduction model
pos = headsurface(vol, axial.grad, 'surface', 'cortex', 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh);
else
% get the surface describing the head shape
if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')
% use the headshape surface specified in the configuration
headshape = cfg.headshape;
elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3
% use the headshape points specified in the configuration
headshape.pnt = cfg.headshape;
elseif ischar(cfg.headshape)
% read the headshape from file
headshape = ft_read_headshape(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.pnt = unique(headshape.pnt, 'rows');
headshape.tri = projecttri(headshape.pnt);
end
% construct from the head surface
pos = headsurface([], [], 'headshape', headshape, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh);
end
% compute the forward model for the axial gradiometers
fprintf('computing forward model for %d dipoles\n', size(pos,1));
lfold = ft_compute_leadfield(pos, axial.grad, vol);
% construct the planar gradient definition and compute its forward model
% this will not work for a localspheres model, compute_leadfield will catch
% the error
planar.grad = constructplanargrad([], axial.grad);
lfnew = ft_compute_leadfield(pos, planar.grad, vol);
% compute the interpolation matrix
transform = lfnew * prunedinv(lfold, cfg.pruneratio);
planarmontage = [];
planarmontage.tra = transform;
planarmontage.labelorg = axial.grad.label;
planarmontage.labelnew = planar.grad.label;
% apply the linear transformation to the data
interp = ft_apply_montage(data, planarmontage, 'keepunused', 'yes');
% also apply the linear transformation to the gradiometer definition
interp.grad = ft_apply_montage(data.grad, planarmontage, 'balancename', 'planar', 'keepunused', 'yes');
% ensure there is a type string describing the gradiometer definition
if ~isfield(interp.grad, 'type')
% put the original gradiometer type in (will get _planar appended)
interp.grad.type = ft_senstype(data.grad);
end
interp.grad.type = [interp.grad.type '_planar'];
% % interpolate the data towards the planar gradiometers
% for i=1:Ntrials
% fprintf('interpolating trial %d to planar gradiometer\n', i);
% interp.trial{i} = transform * data.trial{i}(dataindx,:);
% end % for Ntrials
%
% % all planar gradiometer channels are included in the output
% interp.grad = planar.grad;
% interp.label = planar.grad.label;
%
% % copy the non-gradiometer channels back into the output data
% other = setdiff(1:Nchan, dataindx);
% for i=other
% interp.label{end+1} = data.label{i};
% for j=1:Ntrials
% interp.trial{j}(end+1,:) = data.trial{j}(i,:);
% end
% end
%
else
% generically call megplanar_orig megplanar_sincos or megplanar_fitplante
fun = ['megplanar_' cfg.planarmethod];
if ~exist(fun, 'file')
error('unknown method for computation of planar gradient');
end
sens = ft_convert_units(data.grad);
if any(isnan(sens.chanpos(:)))
error('The channel positions contain NaNs; this prohibits correct behavior of the function. Please replace the input channel definition with one that contains valid channel positions');
end
cfg.channel = ft_channelselection(cfg.channel, sens.label);
cfg.channel = ft_channelselection(cfg.channel, data.label);
% ensure channel order according to cfg.channel (there might be one check
% too much in here somewhere or in the subfunctions, but I don't care.
% Better one too much than one too little - JMH @ 09/19/12
[neighbsel] = match_str({cfg.neighbours.label}, cfg.channel);
cfg.neighbours = cfg.neighbours(neighbsel);
cfg.neighbsel = channelconnectivity(cfg);
% determine
fprintf('average number of neighbours is %.2f\n', mean(sum(cfg.neighbsel)));
Ngrad = length(sens.label);
cfg.distance = zeros(Ngrad,Ngrad);
for i=1:size(cfg.neighbsel,1)
j=find(cfg.neighbsel(i, :));
d = sqrt(sum((sens.chanpos(j,:) - repmat(sens.chanpos(i, :), numel(j), 1)).^2, 2));
distance(i,j) = d;
distance(j,i) = d;
end
fprintf('minimum distance between neighbours is %6.2f %s\n', min(distance(distance~=0)), sens.unit);
fprintf('maximum distance between gradiometers is %6.2f %s\n', max(distance(distance~=0)), sens.unit);
planarmontage = eval([fun '(cfg, data.grad)']);
% apply the linear transformation to the data
interp = ft_apply_montage(data, planarmontage, 'keepunused', 'yes', 'feedback', cfg.feedback);
% also apply the linear transformation to the gradiometer definition
interp.grad = ft_apply_montage(data.grad, planarmontage, 'balancename', 'planar', 'keepunused', 'yes');
% ensure there is a type string describing the gradiometer definition
if ~isfield(interp.grad, 'type')
% put the original gradiometer type in (will get _planar appended)
interp.grad.type = ft_senstype(data.grad);
end
interp.grad.type = [interp.grad.type '_planar'];
% add the chanpos info back into the gradiometer description
tmplabel = interp.grad.label;
for k = 1:numel(tmplabel)
if strcmp(tmplabel{k}(end-2:end), '_dV') || strcmp(tmplabel{k}(end-2:end), '_dH')
tmplabel{k} = tmplabel{k}(1:end-3);
end
end
[ix,iy] = match_str(tmplabel, data.grad.label);
interp.grad.chanpos(ix,:) = data.grad.chanpos(iy,:);
end
if istlck
% convert the raw structure back into a timelock structure
interp = ft_checkdata(interp, 'datatype', 'timelock');
israw = false;
end
% copy the trial specific information into the output
if isfield(data, 'trialinfo')
interp.trialinfo = data.trialinfo;
end
% copy the sampleinfo field as well
if isfield(data, 'sampleinfo')
interp.sampleinfo = data.sampleinfo;
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
% rename the output variable to accomodate the savevar postamble
data = interp;
ft_postamble history data
ft_postamble savevar data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that computes the inverse using a pruned SVD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lfi] = prunedinv(lf, r)
[u, s, v] = svd(lf);
p = find(s<(s(1,1)*r) & s~=0);
fprintf('pruning %d out of %d singular values\n', length(p), min(size(s)));
s(p) = 0;
s(find(s~=0)) = 1./s(find(s~=0));
lfi = v * s' * u';
|
github
|
philippboehmsturm/antx-master
|
ft_movieplotTFR.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_movieplotTFR.m
| 15,885 |
utf_8
|
4629b5114994ea433b22443e6dabab05
|
function [cfg] = ft_movieplotTFR(cfg, data)
% FT_MOVIEPLOTTFR makes a movie of a time frequency representation of power or coherence
%
% Use as
% ft_movieplotTFR(cfg, data)
% where the input data comes from FT_FREQANALYSIS or FT_FREQDESCRIPTIVES and the
% configuration is a structure that can contain
% cfg.parameter = string, parameter that is color coded (default = 'avg')
% cfg.xlim = selection boundaries over first dimension in data (e.g., time)
% 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = selection boundaries over second dimension in data (e.g., freq)
% 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.zlim = plotting limits for color dimension, 'maxmin',
% 'maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.samperframe = number, samples per fram (default = 1)
% cfg.framespersec = number, frames per second (default = 5)
% cfg.framesfile = [] (optional), no file saved, or 'string', filename of saved frames.mat (default = []);
% cfg.moviefreq = number, movie frames are all time points at the fixed frequency moviefreq (default = []);
% cfg.movietime = number, movie frames are all frequencies at the fixed time movietime (default = []);
% cfg.layout = specification of the layout, see below
% cfg.interactive = 'no' or 'yes', make it interactive
%
% the layout defines how the channels are arranged. you can specify the
% layout in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.mat
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% if you do not specify any of these and the data structure contains an
% electrode or gradiometer structure, that will be used for creating a
% layout. if you want to have more fine-grained control over the layout
% of the subplots, you should create your own layout file.
%
% to facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% if you specify this option the input data will be read from a *.mat
% file on disk. this mat files should contain only a single variable named 'data',
% corresponding to the input structure.
% Copyright (c) 2009, Ingrid Nieuwenhuis
% Copyright (c) 2011, jan-Mathijs Schoffelen, Robert Oostenveld, Cristiano Micheli
%
% this file is part of fieldtrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% fieldtrip is free software: you can redistribute it and/or modify
% it under the terms of the gnu general public license as published by
% the free software foundation, either version 3 of the license, or
% (at your option) any later version.
%
% fieldtrip is distributed in the hope that it will be useful,
% but without any warranty; without even the implied warranty of
% merchantability or fitness for a particular purpose. see the
% gnu general public license for more details.
%
% you should have received a copy of the gnu general public license
% along with fieldtrip. if not, see <http://www.gnu.org/licenses/>.
%
% $id: ft_movieploter.m 4354 2011-10-05 15:06:02z crimic $
revision = '$Id: ft_movieplotTFR.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar data
% check the input dtaa, this function is also called from ft_movieplotER
data = ft_checkdata(data, 'datatype', {'timelock', 'freq'});
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'});
% set the defaults
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); % use power as default
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
cfg.samperframe = ft_getopt(cfg, 'samperframe', 1);
cfg.framespersec = ft_getopt(cfg, 'framespersec', 5);
cfg.framesfile = ft_getopt(cfg, 'framesfile', []);
cfg.moviefreq = ft_getopt(cfg, 'moviefreq', []);
cfg.movietime = ft_getopt(cfg, 'movietime', []);
cfg.movierpt = ft_getopt(cfg, 'movierpt', 1);
cfg.interactive = ft_getopt(cfg, 'interactive', 'yes');
dointeractive = istrue(cfg.interactive);
xparam = 'time';
if isfield(data, 'freq')
yparam = 'freq';
end
% read or create the layout that will be used for plotting:
layout = ft_prepare_layout(cfg);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xvalues = data.(xparam);
parameter = data.(cfg.parameter);
if exist('yparam', 'var')
yvalues = data.(yparam);
end
% check consistency of xparam and yparam
% NOTE: i set two different defaults for the 'chan_time' and the 'chan_freq_time' case
if isfield(data,'dimord')
if strcmp(data.dimord,'chan_freq_time')
if length(xvalues)~=size(parameter,3)
error('inconsistent size of "%s" compared to "%s"', cfg.parameter, xparam);
end
if length(yvalues)~=size(parameter,2)
error('inconsistent size of "%s" compared to "%s"', cfg.parameter, yparam);
end
elseif strcmp(data.dimord,'chan_time')
if length(xvalues)~=size(parameter,2)
error('inconsistent size of "%s" compared to "%s"', cfg.parameter, xparam);
end
else
error('input data is incompatible')
end
end
if ischar(cfg.xlim) && strcmp(cfg.xlim, 'maxmin')
cfg.xlim = [];
cfg.xlim(1) = min(xvalues);
cfg.xlim(2) = max(xvalues);
end
xbeg = nearest(xvalues, cfg.xlim(1));
xend = nearest(xvalues, cfg.xlim(2));
% update the configuration
cfg.xlim = xvalues([xbeg xend]);
if exist('yparam', 'var')
if ischar(cfg.ylim) && strcmp(cfg.ylim, 'maxmin')
cfg.ylim = [];
cfg.ylim(1) = min(yvalues);
cfg.ylim(2) = max(yvalues);
end
ybeg = nearest(yvalues, cfg.ylim(1));
yend = nearest(yvalues, cfg.ylim(2));
% update the configuration
cfg.ylim = yvalues([ybeg yend]);
hasyparam = true;
else
% this allows us not to worry about the yparam any more
yvalues = nan;
yparam = nan;
ybeg = 1;
yend = 1;
cfg.ylim = [];
hasyparam = false;
end
% select the channels in the data that match with the layout:
[seldat, sellay] = match_str(data.label, layout.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
% make a subselection of the data
xvalues = xvalues(xbeg:xend);
yvalues = yvalues(ybeg:yend);
if all(isnan(yvalues))
parameter = parameter(seldat, xbeg:xend);
else
parameter = parameter(seldat, ybeg:yend, xbeg:xend);
end
clear xbeg xend ybeg yend
% get the x and y coordinates and labels of the channels in the data
chanx = layout.pos(sellay,1);
chany = layout.pos(sellay,2);
% get the z-range
if ischar(cfg.zlim) && strcmp(cfg.zlim, 'maxmin')
cfg.zlim = [];
cfg.zlim(1) = min(parameter(:));
cfg.zlim(2) = max(parameter(:));
elseif ischar(cfg.zlim) && strcmp(cfg.zlim,'maxabs')
cfg.zlim = [];
cfg.zlim(1) = -max(abs(parameter(:)));
cfg.zlim(2) = max(abs(parameter(:)));
end
h = gcf;
pos = get(gcf, 'position');
set(h, 'toolbar', 'figure');
if dointeractive
% add the gui elements for changing the speed
p = uicontrol('style', 'text');
set(p, 'position', [20 75 50 20]);
set(p, 'string', 'speed')
button_slower = uicontrol('style', 'pushbutton');
set(button_slower, 'position', [75 75 20 20]);
set(button_slower, 'string', '-')
set(button_slower, 'callback', @cb_speed);
button_faster = uicontrol('style', 'pushbutton');
set(button_faster, 'position', [100 75 20 20]);
set(button_faster, 'string', '+')
set(button_faster, 'callback', @cb_speed);
% add the gui elements for changing the color limits
p = uicontrol('style', 'text');
set(p, 'position', [20 100 50 20]);
set(p, 'string', 'zlim')
button_slower = uicontrol('style', 'pushbutton');
set(button_slower, 'position', [75 100 20 20]);
set(button_slower, 'string', '-')
set(button_slower, 'callback', @cb_zlim);
button_faster = uicontrol('style', 'pushbutton');
set(button_faster, 'position', [100 100 20 20]);
set(button_faster, 'string', '+')
set(button_faster, 'callback', @cb_zlim);
sx = uicontrol('style', 'slider');
set(sx, 'position', [20 5 pos(3)-160 20]);
% note that "sx" is needed further down
sy = uicontrol('style', 'slider');
set(sy, 'position', [20 30 pos(3)-160 20]);
% note that "sy" is needed further down
p = uicontrol('style', 'pushbutton');
set(p, 'position', [20 50 50 20]);
set(p, 'string', 'play')
% note that "p" is needed further down
hx = uicontrol('style', 'text');
set(hx, 'position', [pos(3)-140 5 120 20]);
set(hx, 'string', sprintf('%s = ', xparam));
set(hx, 'horizontalalignment', 'left');
hy = uicontrol('style', 'text');
set(hy, 'position', [pos(3)-140 30 120 20]);
set(hy, 'string', sprintf('%s = ', yparam));
set(hy, 'horizontalalignment', 'left');
if ~hasyparam
set(hy, 'visible', 'off')
set(sy, 'visible', 'off')
end
t = timer;
set(t, 'timerfcn', {@cb_timer, h}, 'period', 0.1, 'executionmode', 'fixedspacing');
% collect the data and the options to be used in the figure
opt.lay = layout;
opt.chanx = chanx;
opt.chany = chany;
opt.xvalues = xvalues; % freq
opt.yvalues = yvalues; % time
opt.xparam = xparam;
opt.yparam = yparam;
opt.dat = parameter;
opt.zlim = cfg.zlim;
opt.speed = 1;
opt.cfg = cfg;
opt.sx = sx; % slider freq
opt.sy = sy; % slider time
opt.p = p;
opt.t = t;
if ~hasyparam
opt.timdim = 2;
else
opt.timdim = 3;
end
[dum, hs] = ft_plot_topo(chanx, chany, zeros(numel(chanx),1), 'mask', layout.mask, 'outline', layout.outline, 'interpmethod', 'v4', 'interplim', 'mask');
caxis(cfg.zlim);
axis off;
% add sum stuff at a higher level for quicker access in the callback
% routine
opt.xdata = get(hs, 'xdata');
opt.ydata = get(hs, 'ydata');
opt.nanmask = get(hs, 'cdata');
% add the handle to the mesh
opt.hs = hs;
% add the text-handle to the guidata
opt.hx = hx;
opt.hy = hy;
guidata(h, opt);
% from now it is safe to hand over the control to the callback function
set(sx, 'callback', @cb_slider);
set(sy, 'callback', @cb_slider);
% from now it is safe to hand over the control to the callback function
set(p, 'callback', @cb_playbutton);
else
% non interactive mode
[tmp, hs] = ft_plot_topo(chanx, chany, zeros(numel(chanx),1), 'mask', layout.mask, 'outline', layout.outline, 'interpmethod', 'v4');
caxis(cfg.zlim);
axis off;
xdata = get(hs, 'xdata');
ydata = get(hs, 'ydata');
nanmask = get(hs, 'cdata');
% frequency/time selection
if exist('yparam', 'var') && any(~isnan(yvalues))
if ~isempty(cfg.movietime)
indx = cfg.movietime;
for iFrame = 1:floor(size(parameter, 2)/cfg.samperframe)
indy = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe;
datavector = squeeze(mean(parameter(:, indy,indx), 2));
datamatrix = griddata(chanx, chany, datavector, xdata, ydata, 'v4');
set(hs, 'cdata', datamatrix + nanmask);
F(iFrame) = getframe;
end
elseif ~isempty(cfg.moviefreq)
indy = cfg.moviefreq;
for iFrame = 1:floor(size(parameter, 3)/cfg.samperframe)
indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe;
datavector = squeeze(mean(parameter(:, indy,indx), 3));
datamatrix = griddata(chanx, chany, datavector, xdata, ydata, 'v4');
set(hs, 'cdata', datamatrix + nanmask);
F(iFrame) = getframe;
end
else
error('Either moviefreq or movietime should contain a bin number')
end
else
for iFrame = 1:floor(size(parameter, 2)/cfg.samperframe)
indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe;
datavector = mean(parameter(:, indx), 2);
datamatrix = griddata(chanx, chany, datavector, xdata, ydata, 'v4');
set(hs, 'cdata', datamatrix + nanmask);
F(iFrame) = getframe;
end
end
% save movie
if ~isempty(cfg.framesfile)
save(cfg.framesfile, 'F');
end
% play movie
movie(F, cfg.movierpt, cfg.framespersec);
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_slider(h, eventdata)
opt = guidata(h);
xdim = opt.timdim;
valx = get(opt.sx, 'value');
valx = round(valx*(size(opt.dat,xdim)-1))+1;
valx = min(valx, size(opt.dat,xdim));
valx = max(valx, 1);
if valx>size(opt.dat,opt.timdim)
valx = size(opt.dat,opt.timdim)-1;
end
if length(size(opt.dat))>2
ydim = 2;
valy = get(opt.sy, 'value');
valy = round(valy*(size(opt.dat,ydim)-1))+1;
valy = min(valy, size(opt.dat,ydim));
valy = max(valy, 1);
set(opt.hx, 'string', sprintf('%s = %f\n', opt.xparam, opt.xvalues(valx)));
set(opt.hy, 'string', sprintf('%s = %f\n', opt.yparam, opt.yvalues(valy)));
% update data, interpolate and render
datamatrix = griddata(opt.chanx, opt.chany, opt.dat(:,valy,valx), opt.xdata, opt.ydata, 'v4');
else
set(opt.hx, 'string', sprintf('%s = %f\n', opt.xparam, opt.xvalues(valx)));
% update data, interpolate and render
datamatrix = griddata(opt.chanx, opt.chany, opt.dat(:,valx), opt.xdata, opt.ydata, 'v4');
end
set(opt.hs, 'cdata', datamatrix + opt.nanmask);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_playbutton(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
switch get(h, 'string')
case 'play'
set(h, 'string', 'stop');
start(opt.t);
case 'stop'
set(h, 'string', 'play');
stop(opt.t);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_timer(obj, event, h)
if ~ishandle(h)
return
end
opt = guidata(h);
delta = opt.speed/size(opt.dat,opt.timdim);
val = get(opt.sx, 'value');
val = val + delta;
% to avoid the slider to go out of range when the speed is too high
if val+delta>2
val = get(opt.sx, 'value');
end
if val>1
val = val-1;
end
set(opt.sx, 'value', val);
cb_slider(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_zlim(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
switch get(h, 'string')
case '+'
caxis(caxis*sqrt(2));
case '-'
caxis(caxis/sqrt(2));
end % switch
guidata(h, opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_speed(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
switch get(h, 'string')
case '+'
opt.speed = opt.speed*sqrt(2);
case '-'
opt.speed = opt.speed/sqrt(2);
% opt.speed = max(opt.speed, 1); % should not be smaller than 1
end % switch
guidata(h, opt);
|
github
|
philippboehmsturm/antx-master
|
ft_volumerealign.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_volumerealign.m
| 36,731 |
utf_8
|
393894855ca91a6ebaba17f940cea0b8
|
function [realign, h] = ft_volumerealign(cfg, mri, target)
% FT_VOLUMEREALIGN spatially aligns an anatomical MRI with head coordinates
% based on external fiducials or anatomical landmarks. This function does
% not change the volume itself, but adjusts the homogeneous transformation
% matrix that describes the coordinate system. It also appends a
% coordsys-field to the mri, which specifies the coordinate system.
%
% This function only changes the coordinate system of an anatomical MRI, it
% does not change the MRI as such. For spatial normalisation (i.e. warping)
% of an MRI to a template brain you should use the FT_VOLUMENORMALISE
% function.
%
% Use as
% [mri] = ft_volumerealign(cfg, mri)
% [mri] = ft_volumerealign(cfg, mri, target);
% where the input mri should be a single anatomical or functional MRI
% volume that was for example read with FT_READ_MRI.
%
% The configuration can contain the following options
% cfg.method = different methods for aligning the volume
% 'interactive', 'fiducial', 'landmark', 'headshape'
% 'volume' (see below)
% cfg.coordsys = 'ctf' (default when specifying cfg.method =
% 'interactive' or 'fiducial') or 'spm' (default
% when specifying cfg.method = 'landmark').
% Specifies the output coordinate system of the head. This
% string specifies the origin and the axes of the
% coordinate system. supported coordinate systems
% are: 'ctf', '4d', 'yokogawa', 'neuromag', 'itab'
% 'spm', 'tal'.
% cfg.clim = [min max], scaling of the anatomy color (default
% is to adjust to the minimum and maximum)
% cfg.parameter = 'anatomy' the parameter which is used for the
% visualization
%
% When cfg.method = 'fiducial', the following cfg-option is required:
% cfg.fiducial.nas = [i j k], position of nasion
% cfg.fiducial.lpa = [i j k], position of LPA
% cfg.fiducial.rpa = [i j k], position of RPA
% cfg.fiducial.zpoint = [i j k], a point on the positive z-axis. This is
% an optional 'fiducial', and can be used to determine whether the
% input voxel coordinate axes are left-handed (i.e. flipped in one of
% the dimensions). If this additional point is specified, and the voxel
% coordinate axes are left handed, the volume is flipped to yield right
% handed voxel axes.
%
% When cfg.method = 'landmark', the following cfg-option is required:
% cfg.landmark.ac = [i j k], position of anterior commissure
% cfg.landmark.pc = [i j k], position of posterior commissure
% cfg.landmark.xzpoint = [i j k], point on the midsagittal-plane with
% positive Z-coordinate, i.e. interhemispheric point above ac and pc
% The coordinate system will be according to the RAS_Tal convention i.e.
% the origin corresponds with the anterior commissure the Y-axis is along
% the line from the posterior commissure to the anterior commissure the
% Z-axis is towards the vertex, in between the hemispheres the X-axis is
% orthogonal to the YZ-plane, positive to the right
%
% When cfg.method = 'interactive', a user interface allows for the
% specification of the fiducials or landmarks using the mouse, cursor keys
% and keyboard. Using the n/l/r keys the fiducials can be specified, the
% landmarks can be specified with a/p/z. When pressing q the interactive
% mode will stop and the transformation matrix is computed. This method
% also supports the cfg-option:
% cfg.snapshot = 'no' ('yes'), making a snapshot of the image once a
% fiducial or landmark location is selected. For each of the
% fiducials/landmarks a new figure is created. The optional second
% output argument to the function will contain the handles to these
% figures.
%
% When cfg.method = 'headshape', the following cfg-option is required:
% cfg.headshape = string pointing to a file describing a headshape, that
% can be loaded with ft_read_headshape, or a fieldtrip-structure describing
% a headshape
%
% When cfg.method = 'volume', a third input argument is required. The input volume is
% coregistered to this target volume, using fsl's flirt program. This
% assumes fsl to be installed. Options pertaining to the behavior of fsl
% should be defined in the subcfg cfg.fsl:
% cfg.fsl.path = string, specifying the path to fsl
% cfg.fsl.costfun = string, specifying the cost-function used for
% coregistration
% cfg.fsl.interpmethod = string, specifying the interpolation method
% ('trilinear', 'nearestneighbour', 'sinc')
% cfg.fsl.dof = scalar, specifying the number of parameters for the
% affine transformation. 6 (rigid body), 7 (global
% rescale), 9 (traditional) or 12.
% cfg.fsl.reslice = string, specifying whether the output image will be
% resliced conform the target image (default = 'yes')
%
% With the 'interactive' and 'fiducial' methods it is possible to define an
% additional point (with the key 'z'), which should be a point on the
% positive side of the xy-plane, i.e. with a positive z-coordinate in world
% coordinates. This point will subsequently be used to check whether the
% input coordinate system is left or right-handed. For the 'interactive'
% and 'landmark' methods you can also specify an additional control point
% (with the key 'r'), that should be a point with a positive coordinate on
% the left-right axis.
%
% To facilitate data-handling and distributed computing with the
% peer-to-peer module, this function has the following options:
% cfg.inputfile = ... cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a
% *.mat file on disk and/or the output data will be written to a *.mat
% file. These mat files should contain only a single variable,
% corresponding with the input/output structure.
%
% See also FT_READ_MRI, FT_ELECTRODEREALIGN HEADCOORDINATES
% Copyright (C) 2006-2011, Robert Oostenveld, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see
% http://www.ru.nl/neuroimaging/fieldtrip for the documentation and
% details.
%
% FieldTrip is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation, either version 3 of the License, or (at your
% option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_volumerealign.m 7398 2013-01-23 15:50:59Z jorhor $
revision = '$Id: ft_volumerealign.m 7398 2013-01-23 15:50:59Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar mri
% check if the input data is valid for this function
mri = ft_checkdata(mri, 'datatype', 'volume', 'feedback', 'yes');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'});
% set the defaults
cfg.coordsys = ft_getopt(cfg, 'coordsys', '');
cfg.method = ft_getopt(cfg, 'method', ''); % deal with this below
cfg.fiducial = ft_getopt(cfg, 'fiducial', []);
cfg.landmark = ft_getopt(cfg, 'landmark', []);
cfg.parameter = ft_getopt(cfg, 'parameter', 'anatomy');
cfg.clim = ft_getopt(cfg, 'clim', []);
cfg.snapshot = ft_getopt(cfg, 'snapshot', false);
if strcmp(cfg.method, '')
if isempty(cfg.landmark) && isempty(cfg.fiducial)
cfg.method = 'interactive';
elseif ~isempty(cfg.fiducial)
cfg.method = 'fiducial';
elseif ~isempty(cfg.landmark)
cfg.method = 'landmark';
end
end
if strcmp(cfg.coordsys, '')
if strcmp(cfg.method, 'landmark')
cfg.coordsys = 'spm';
elseif strcmp(cfg.method, 'fiducial')
cfg.coordsys = 'ctf';
else
cfg.coordsys = '';
end
end
basedonmrk = strcmp(cfg.method, 'landmark');
basedonfid = strcmp(cfg.method, 'fiducial');
% these two have to be simultaneously true for a snapshot to be taken
dosnapshot = istrue(cfg.snapshot);
takesnapshot = false;
% select the parameter that should be displayed
cfg.parameter = parameterselection(cfg.parameter, mri);
if iscell(cfg.parameter) && ~isempty(cfg.parameter)
cfg.parameter = cfg.parameter{1};
elseif iscell(cfg.parameter) && isempty(cfg.parameter)
% cfg.parameter has been cleared by parameterselection due to a
% dimensionality mismatch. Most probable cause here is the fact that a 4D
% volume (e.g. DTI data) is in the input. This needs to be patched in a
% more structural way at some point, but for the time being we'll use a
% workaround here.
% assume anatomy to be the parameter of interest
siz = size(mri.anatomy);
if all(siz(1:3)==mri.dim) && numel(siz)==4,
% it's OK
cfg.parameter= 'anatomy';
else
error('there''s an unexpected dimension mismatch');
end
end
transform = [];
coordsys = [];
switch cfg.method
case 'fiducial'
% do nothing
case 'landmark'
% do nothing
case 'interactive'
h = figure;
h1 = subplot('position',[0.02 0.55 0.44 0.44]);%subplot(2,2,1);
h2 = subplot('position',[0.52 0.55 0.44 0.44]);%subplot(2,2,2);
h3 = subplot('position',[0.02 0.05 0.44 0.44]);%subplot(2,2,3);
handles = {h1 h2 h3};
showcrosshair = true;
showmarkers = 1;
dat = mri.(cfg.parameter);
nas = [];
lpa = [];
rpa = [];
antcomm = [];
pstcomm = [];
xzpoint = [];
x = 1:mri.dim(1);
y = 1:mri.dim(2);
z = 1:mri.dim(3);
xc = round(mri.dim(1)/2);
yc = round(mri.dim(2)/2);
zc = round(mri.dim(3)/2);
updatepanel = [1 2 3];
pnt = zeros(0,3);
markerpos = zeros(0,3);
markerlabel = {};
markercolor = {};
fprintf(strcat(...
'1. To change the slice viewed in one plane, either:\n',...
' a. click (left mouse) in the image on a different plane. Eg, to view a more\n',...
' superior slice in the horizontal plane, click on a superior position in the\n',...
' coronal plane, or\n',...
' b. use the arrow keys to increase or decrease the slice number by one\n',...
'2. To mark a fiducial position or anatomical landmark, do BOTH:\n',...
' (this can be done multiple times, until you are satisfied with the positions.\n',...
' for each type of point, the most recent selection is stored.)\n',...
' a. select the position by clicking on it in any slice with the left mouse\n',...
' button\n',...
' b. identify it by pressing either n/l/r for fiducials, or a/p/z for\n',...
' anatomical landmarks\n',...
' c. additional control point for the fiducials can be a point along the\n',...
' positive z-axis, press z\n',...
' d. additional control point for the landmarks can be a point along the\n',...
' positive x-axis (to the participant''s right), press r\n',...
'3. To change the display:\n',...
' a. press c or C on keyboard to show/hide crosshair\n',...
' b. press m or M on keyboard to show/hide marked positions\n',...
'4. To finalize markers and quit interactive mode, press q on keyboard\n'));
%'3. To unmark or remark a location\n',...
%' a. click with the middle mouse button to unmark last position\n',...
%' b. select new position with right mouse button and identify it using the\n',...
%' keyboard\n',...
while true % break when 'q' is pressed
% fprintf('click with the left mouse button to reslice the display to a new position\n');
% fprintf('click with the right mouse button to mark a position\n');
% fprintf('click with the middle mouse button to unmark the last marked position\n');
% fprintf('press n/l/r on keyboard to record the current position as fiducial location\n');
% fprintf('press a/p/z on keyboard to record the current position as anatomical landmark\n');
% fprintf('press the arrow keys on the keyboard to increment or decrement the slice number by one\n');
% fprintf('press c or C on the keyboard to show or hide the crosshair\n');
% fprintf('press m or M on the keyboard to show or hide the marked positions\n');
% fprintf('press q on keyboard to quit interactive mode\n');
xc = round(xc); xc = max(1,xc); xc = min(mri.dim(1),xc);
yc = round(yc); yc = max(1,yc); yc = min(mri.dim(2),yc);
zc = round(zc); zc = max(1,zc); zc = min(mri.dim(3),zc);
markers = {markerpos markerlabel markercolor};
[h1, h2, h3] = volplot(x, y, z, dat, [xc yc zc], cfg.clim, showcrosshair, updatepanel, handles, showmarkers, markers);
drawnow;
if dosnapshot && takesnapshot
% create a new figure and draw right away, this will keep the old one on the screen
h(end+1) = figure;
h1 = subplot('position',[0.02 0.55 0.44 0.44]);%subplot(2,2,1);
h2 = subplot('position',[0.52 0.55 0.44 0.44]);%subplot(2,2,2);
h3 = subplot('position',[0.02 0.05 0.44 0.44]);%subplot(2,2,3);
handles = {h1 h2 h3};
[h1, h2, h3] = volplot(x, y, z, dat, [xc yc zc], cfg.clim, showcrosshair, updatepanel, handles, showmarkers, markers);
drawnow;
end
takesnapshot = false;
try, [d1, d2, key] = ginput(1); catch, key='q'; end
switch key
case 113 % 'q'
delete(h(end));
h = h(1:end-1);
break;
case 108 % 'l'
lpa = [xc yc zc];
takesnapshot = true;
case 114 % 'r'
rpa = [xc yc zc];
takesnapshot = true;
case 110 % 'n'
nas = [xc yc zc];
takesnapshot = true;
case 97 % 'a'
antcomm = [xc yc zc];
takesnapshot = true;
case 112 % 'p'
pstcomm = [xc yc zc];
takesnapshot = true;
case 122 % 'z'
xzpoint = [xc yc zc];
takesnapshot = true;
case 99 % 'c'
showcrosshair = true;
case 67 % 'C'
showcrosshair = false;
case 109 % 'm'
showmarkers = 2;
case 77 % 'M'
showmarkers = 0;
case 1 % left mouse click
% update the view to a new position
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
switch l1,
case 'i'
xc = d1;
case 'j'
yc = d1;
case 'k'
zc = d1;
otherwise
continue;
end
switch l2,
case 'i'
xc = d2;
case 'j'
yc = d2;
case 'k'
zc = d2;
otherwise
continue;
end
if l1=='i' && l2=='j'
updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
updatepanel = [3 1 2];
end
case 3 % right mouse click
% add point to a list
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
switch l1,
case 'i'
xc = d1;
case 'j'
yc = d1;
case 'k'
zc = d1;
end
switch l2,
case 'i'
xc = d2;
case 'j'
yc = d2;
case 'k'
zc = d2;
end
pnt = [pnt; xc yc zc];
if l1=='i' && l2=='j'
updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
updatepanel = [3 1 2];
end
case 2 % middle mouse click
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
% remove the previous point
if size(pnt,1)>0
pnt(end,:) = [];
end
if l1=='i' && l2=='j'
updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
updatepanel = [3 1 2];
end
case 28 % arrow left
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
xc = xc-1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
xc = xc-1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
yc = yc-1; updatepanel = [3 1 2];
end
case 30 % arrow up
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
yc = yc+1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
zc = zc+1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
zc = zc+1; updatepanel = [3 1 2];
end
case 29 % arrow right
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
xc = xc+1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
xc = xc+1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
yc = yc+1; updatepanel = [3 1 2];
end
case 31 % arrow down
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
yc = yc-1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
zc = zc-1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
zc = zc-1; updatepanel = [3 1 2];
end
otherwise
% do nothing
end
if all(round([xc yc zc])<=mri.dim) && all(round([xc yc zc])>0)
fprintf('============================================================================\n');
str = sprintf('voxel %d, indices [%d %d %d]', sub2ind(mri.dim(1:3), round(xc), round(yc), round(zc)), round([xc yc zc]));
if isfield(mri, 'coordsys') && isfield(mri, 'unit')
str = sprintf('%s, %s coordinates [%.1f %.1f %.1f] %s', str, mri.coordsys, warp_apply(mri.transform, [xc yc zc]), mri.unit);
elseif ~isfield(mri, 'coordsys') && isfield(mri, 'unit')
str = sprintf('%s, location [%.1f %.1f %.1f] %s', str, warp_apply(mri.transform, [xc yc zc]), mri.unit);
elseif isfield(mri, 'coordsys') && ~isfield(mri, 'unit')
str = sprintf('%s, %s coordinates [%.1f %.1f %.1f]', str, mri.coordsys, warp_apply(mri.transform, [xc yc zc]));
elseif ~isfield(mri, 'coordsys') && ~isfield(mri, 'unis')
str = sprintf('%s, location [%.1f %.1f %.1f]', str, warp_apply(mri.transform, [xc yc zc]));
end
fprintf('%s\n', str);
% fprintf('cur_voxel = [%f %f %f], cur_head = [%f %f %f]\n', [xc yc zc], warp_apply(mri.transform, [xc yc zc]));
end
markerpos = zeros(0,3);
markerlabel = {};
markercolor = {};
if ~isempty(nas),
fprintf('nas_voxel = [%f %f %f], nas_head = [%f %f %f]\n', nas, warp_apply(mri.transform, nas));
markerpos = [markerpos; nas];
markerlabel = [markerlabel; {'nas'}];
markercolor = [markercolor; {'b'}];
end
if ~isempty(lpa),
fprintf('lpa_voxel = [%f %f %f], lpa_head = [%f %f %f]\n', lpa, warp_apply(mri.transform, lpa));
markerpos = [markerpos; lpa];
markerlabel = [markerlabel; {'lpa'}];
markercolor = [markercolor; {'g'}];
end
if ~isempty(rpa),
fprintf('rpa_voxel = [%f %f %f], rpa_head = [%f %f %f]\n', rpa, warp_apply(mri.transform, rpa));
markerpos = [markerpos; rpa];
markerlabel = [markerlabel; {'rpa'}];
markercolor = [markercolor; {'r'}];
end
if ~isempty(antcomm),
fprintf('antcomm_voxel = [%f %f %f], antcomm_head = [%f %f %f]\n', antcomm, warp_apply(mri.transform, antcomm));
markerpos = [markerpos; antcomm];
markerlabel = [markerlabel; {'antcomm'}];
markercolor = [markercolor; {'b'}];
end
if ~isempty(pstcomm),
fprintf('pstcomm_voxel = [%f %f %f], pstcomm_head = [%f %f %f]\n', pstcomm, warp_apply(mri.transform, pstcomm));
markerpos = [markerpos; pstcomm];
markerlabel = [markerlabel; {'pstcomm'}];
markercolor = [markercolor; {'g'}];
end
if ~isempty(xzpoint),
fprintf('xzpoint_voxel = [%f %f %f], xzpoint_head = [%f %f %f]\n', xzpoint, warp_apply(mri.transform, xzpoint));
markerpos = [markerpos; xzpoint];
markerlabel = [markerlabel; {'xzpoint'}];
markercolor = [markercolor; {'y'}];
end
if ~isempty(pnt)
fprintf('%f extra points selected\n', size(pnt,1));
markerpos = [markerpos; pnt];
markerlabel = [markerlabel; repmat({''}, size(pnt,1), 1)];
markercolor = [markercolor; repmat({'m'}, size(pnt,1), 1)];
end
end % while true
cfg.fiducial.nas = nas;
cfg.fiducial.lpa = lpa;
cfg.fiducial.rpa = rpa;
cfg.fiducial.zpoint = xzpoint;
cfg.landmark.ac = antcomm;
cfg.landmark.pc = pstcomm;
cfg.landmark.xzpoint = xzpoint;
cfg.landmark.rpoint = rpa;
if ~isempty(nas) && ~isempty(lpa) && ~isempty(rpa)
basedonfid = 1;
if isempty(cfg.coordsys)
cfg.coordsys = 'ctf';
end
end
if ~isempty(antcomm) && ~isempty(pstcomm) && ~isempty(xzpoint)
basedonmrk = 1;
end
case 'headshape'
if ischar(cfg.headshape)
shape = ft_read_headshape(cfg.headshape);
else
shape = cfg.headshape;
end
shape = ft_convert_units(shape, 'mm');
% extract skull surface from image
tmpcfg = [];
tmpcfg.output = 'scalp';
tmpcfg.smooth = 2;
if isfield(cfg, 'template')
tmpcfg.template = cfg.template;
end
seg = ft_volumesegment(tmpcfg, mri);
cfg = [];
cfg.method = 'singleshell';
cfg.numvertices = 20000;
scalp = ft_prepare_headmodel(cfg, seg);
scalp = ft_convert_units(scalp, 'mm');
% weight the points with z-coordinate more than the rest. These are the
% likely points that belong to the nose and eye rims
weights = ones(size(shape.pnt,1),1);
weights(shape.pnt(:,3)<0) = 100; % this value seems to work
% construct the coregistration matrix
[R, t, corr, D, data2] = icp2(scalp.bnd.pnt', shape.pnt', 20, [], weights); % icp2 is a helper function implementing the iterative closest point algorithm
transform = inv([R t;0 0 0 1]);
% warp the extracted scalp points to the new positions
scalp.bnd.pnt = warp_apply(transform, scalp.bnd.pnt);
% create headshape structure for mri-based surface point cloud
if isfield(mri, 'coordsys')
scalp.coordsys = mri.coordsys;
end
% coordsys is the same as input mri
coordsys = mri.coordsys;
% mrifid.pnt = warp_apply(transform*mri.transform, [fiducials.nas;fiducials.lpa;fiducials.rpa]);
% mrifid.label = {'NZinteractive';'Linteractive';'Rinteractive'};
% shapemri.fid = mrifid;
% update the cfg
cfg.headshape = shape;
cfg.headshapemri = scalp;
% touch it to survive trackconfig
cfg.headshapemri;
case 'volume'
if ~isfield(cfg, 'fsl'), cfg.fsl = []; end
cfg.fsl.path = ft_getopt(cfg.fsl, 'path', '');
cfg.fsl.costfun = ft_getopt(cfg.fsl, 'costfun', 'mutualinfo');
cfg.fsl.interpmethod = ft_getopt(cfg.fsl, 'interpmethod', 'trilinear');
cfg.fsl.dof = ft_getopt(cfg.fsl, 'dof', 6);
cfg.fsl.reslice = ft_getopt(cfg.fsl, 'reslice', 'yes');
% write the input and target to a temporary file
% and create some additional temporary file names to contain the output
tmpname1 = tempname;
tmpname2 = tempname;
tmpname3 = tempname;
tmpname4 = tempname;
tmpcfg = [];
tmpcfg.parameter = 'anatomy';
tmpcfg.filename = tmpname1;
tmpcfg.filetype = 'nifti';
fprintf('writing the input volume to a temporary file: %s\n', [tmpname1,'.nii']);
ft_volumewrite(tmpcfg, mri);
tmpcfg.filename = tmpname2;
fprintf('writing the target volume to a temporary file: %s\n', [tmpname2,'.nii']);
ft_volumewrite(tmpcfg, target);
% create the command to call flirt
fprintf('using flirt for the coregistration\n');
str = sprintf('%s/flirt -in %s -ref %s -out %s -omat %s -bins 256 -cost %s -searchrx -180 180 -searchry -180 180 -searchrz -180 180 -dof %s -interp %s',...
cfg.fsl.path, tmpname1, tmpname2, tmpname3, tmpname4, cfg.fsl.costfun, num2str(cfg.fsl.dof), cfg.fsl.interpmethod);
if isempty(cfg.fsl.path), str = str(2:end); end % remove the first filesep, assume path to flirt to be known
% system call
system(str);
% process the output
if ~istrue(cfg.fsl.reslice)
% get the transformation that corresponds to the coregistration and
% reconstruct the mapping from the target's world coordinate system
% to the input's voxel coordinate system
fid = fopen(tmpname4);
tmp = textscan(fid, '%f');
fclose(fid);
% this transforms from input voxels to target voxels
vox2vox = reshape(tmp{1},4,4)';
if det(target.transform(1:3,1:3))>0
% flirt apparently flips along the x-dim if the det < 0
% if images are not radiological, the x-axis is flipped, see:
% https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind0810&L=FSL&P=185638
% https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind0903&L=FSL&P=R93775
% flip back
flipmat = eye(4); flipmat(1,1) = -1; flipmat(1,4) = target.dim(1)-1;
vox2vox = flipmat*vox2vox;
end
if det(mri.transform(1:3,1:3))>0
% flirt apparently flips along the x-dim if the det < 0
% flip back
flipmat = eye(4); flipmat(1,1) = -1; flipmat(1,4) = mri.dim(1)-1;
vox2vox = vox2vox*flipmat;
end
% very not sure about this (e.g. is vox2vox really doing what I think
% it is doing? should I care about 0 and 1 based conventions?)
% changing handedness?
mri.transform = target.transform*vox2vox;
transform = eye(4);
if isfield(target, 'coordsys')
coordsys = target.coordsys;
else
coordsys = 'unknown';
end
else
% get the updated anatomy
mrinew = ft_read_mri([tmpname3, '.nii.gz']);
mri.anatomy = mrinew.anatomy;
mri.transform = mrinew.transform;
mri.dim = mrinew.dim;
transform = eye(4);
if isfield(target, 'coordsys')
coordsys = target.coordsys;
else
coordsys = 'unknown';
end
end
delete([tmpname1,'.nii']);
delete([tmpname2,'.nii']);
delete([tmpname3,'.nii.gz']);
delete(tmpname4);
otherwise
error('unsupported method');
end
if basedonfid && basedonmrk
basedonmrk = 0;
warning('both fiducials and anatomical landmarks have been defined interactively: using the fiducials for realignment');
end
if basedonfid
% the fiducial locations are now specified in voxels, convert them to head
% coordinates according to the existing transform matrix
nas_head = warp_apply(mri.transform, cfg.fiducial.nas);
lpa_head = warp_apply(mri.transform, cfg.fiducial.lpa);
rpa_head = warp_apply(mri.transform, cfg.fiducial.rpa);
if isfield(cfg.fiducial, 'zpoint') && ~isempty(cfg.fiducial.zpoint)
zpnt_head = warp_apply(mri.transform, cfg.fiducial.zpoint);
[transform, coordsys] = headcoordinates(nas_head, lpa_head, rpa_head, zpnt_head, cfg.coordsys);
else
% compute the homogeneous transformation matrix describing the new coordinate system
[transform, coordsys] = headcoordinates(nas_head, lpa_head, rpa_head, cfg.coordsys);
end
elseif basedonmrk
% the fiducial locations are now specified in voxels, convert them to head
% coordinates according to the existing transform matrix
ac = warp_apply(mri.transform, cfg.landmark.ac);
pc = warp_apply(mri.transform, cfg.landmark.pc);
xzpoint= warp_apply(mri.transform, cfg.landmark.xzpoint);
if isfield(cfg.landmark, 'rpoint') && ~isempty(cfg.landmark.rpoint)
rpnt_head = warp_apply(mri.transform, cfg.landmark.rpoint);
[transform, coordsys] = headcoordinates(ac, pc, xzpoint, rpnt_head, 'spm');
else
% compute the homogenous transformation matrix describing the new coordinate system
[transform, coordsys] = headcoordinates(ac, pc, xzpoint, 'spm');
end
else
% something else has created a transform and coordsys
end % if basedonXXX
% copy the input anatomical or functional volume
realign = mri;
if ~isempty(transform)
% combine the additional transformation with the original one
realign.transformorig = mri.transform;
realign.transform = transform * mri.transform;
realign.coordsys = coordsys;
else
warning('no coordinate system realignment has been done');
end
if exist('pnt', 'var') && ~isempty(pnt)
realign.marker = pnt;
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous mri
ft_postamble history realign
ft_postamble savevar realign
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to show three orthogonal slices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h1, h2, h3] = volplot(x, y, z, dat, c, cscale, showcrosshair, updatepanel, handles, showmarkers, markers)
xi = c(1);
yi = c(2);
zi = c(3);
% manual color scaling of anatomy data is usefull in case of some pixel noise
if nargin<6 || isempty(cscale)
cmin = min(dat(:));
cmax = max(dat(:));
else
cmin = cscale(1);
cmax = cscale(2);
end
if nargin<8
updatepanel = [1 2 3];
end
if nargin<9
h1 = [];
h2 = [];
h3 = [];
else
h1 = handles{1};
h2 = handles{2};
h3 = handles{3};
end
if showmarkers==1
markerpos = round(markers{1});
markercolor = markers{3};
sel1 = find(markerpos(:,2)==repmat(c(2),size(markerpos,1),1));
sel2 = find(markerpos(:,1)==repmat(c(1),size(markerpos,1),1));
sel3 = find(markerpos(:,3)==repmat(c(3),size(markerpos,1),1));
elseif showmarkers==2
markerpos = round(markers{1});
markercolor = markers{3};
sel1 = 1:size(markerpos,1);
sel2 = 1:size(markerpos,1);
sel3 = 1:size(markerpos,1);
end
for k = 1:numel(updatepanel)
update = updatepanel(k);
if update==1
subplot(h1);
imagesc(x, z, squeeze(dat(:,yi,:))'); set(gca, 'ydir', 'normal')
xlabel('i'); ylabel('k');
caxis([cmin cmax]);
if showcrosshair
crosshair([x(xi) z(zi)], 'color', 'yellow');
end
if showmarkers && numel(sel1)>0
hold on;
for kk = 1:numel(sel1)
plot(markerpos(sel1(kk),1), markerpos(sel1(kk),3), 'marker', '.', 'color', markercolor{sel1(kk)});
end
hold off;
end
axis equal; axis tight;
end
if update==2
subplot(h2);
imagesc(y, z, squeeze(dat(xi,:,:))'); set(gca, 'ydir', 'normal')
xlabel('j'); ylabel('k');
caxis([cmin cmax]);
if showcrosshair
crosshair([y(yi) z(zi)], 'color', 'yellow');
end
if showmarkers && numel(sel2)>0
hold on;
for kk = 1:numel(sel2)
plot(markerpos(sel2(kk),2), markerpos(sel2(kk),3), 'marker', '.', 'color', markercolor{sel2(kk)});
end
hold off;
end
axis equal; axis tight;
end
if update==3
subplot(h3);
imagesc(x, y, squeeze(dat(:,:,zi))'); set(gca, 'ydir', 'normal')
xlabel('i'); ylabel('j');
caxis([cmin cmax]);
if showcrosshair
crosshair([x(xi) y(yi)], 'color', 'yellow');
end
if showmarkers && numel(sel3)>0
hold on;
for kk = 1:numel(sel3)
plot(markerpos(sel3(kk),1), markerpos(sel3(kk),2), 'marker', '.', 'color', markercolor{sel3(kk)});
end
hold off;
end
axis equal; axis tight;
end
end
colormap gray
h = gca;
function [R, t, corr, error, data2] = icp2(data1, data2, res, tri, weights)
% [R, t, corr, error, data2] = icp2(data1, data2, res, tri)
%
% This is an implementation of the Iterative Closest Point (ICP) algorithm.
% The function takes two data sets and registers data2 with data1. It is
% assumed that data1 and data2 are in approximation registration. The code
% iterates till no more correspondences can be found.
%
% This is a modified version (12 April, 2005). It is more accurate and has
% less chances of getting stuck in a local minimum as opposed to my earlier
% version icp.m
%
% Arguments: data1 - 3 x n matrix of the x, y and z coordinates of data set 1
% data2 - 3 x m matrix of the x, y and z coordinates of data set 2
% res - the tolerance distance for establishing closest point
% correspondences. Normally set equal to the resolution
% of data1
% tri - optional argument. obtained by tri = delaunayn(data1');
%
% Returns: R - 3 x 3 accumulative rotation matrix used to register data2
% t - 3 x 1 accumulative translation vector used to register data2
% corr - p x 3 matrix of the index no.s of the corresponding points of
% data1 and data2 and their corresponding Euclidean distance
% error - the mean error between the corresponding points of data1
% and data2 (normalized with res)
% data2 - 3 x m matrix of the registered data2
%
%
% Copyright : This code is written by Ajmal Saeed Mian {[email protected]}
% Computer Science, The University of Western Australia. The code
% may be used, modified and distributed for research purposes with
% acknowledgement of the author and inclusion of this copyright information.
maxIter = 500;
c1 = 0;
c2 = 1;
R = eye(3);
t = zeros(3,1);
if nargin < 4 || isempty(tri)
tri = delaunayn(data1');
end
n = 0;
while c2 ~= c1
c1 = c2;
[corr, D] = dsearchn(data1', tri, data2');
corr(:,2:3) = [(1 : length(corr))' D];
corr(D>2*res,:) = [];
corr = -sortrows(-corr,3);
corr = sortrows(corr,1);
[B, Bi, Bj] = unique(corr(:,1));
corr = corr(Bi,:);
[R1, t1] = reg(data1, data2, corr, weights);
data2 = R1*data2;
data2 = [data2(1,:)+t1(1); data2(2,:)+t1(2); data2(3,:)+t1(3)];
R = R1*R;
t = R1*t + t1;
c2 = length(corr);
n = n + 1;
if n > maxIter
break;
end
end
e1 = 1000001;
e2 = 1000000;
n = 0;
noChangeCount = 0;
while noChangeCount < 10
e1 = e2;
[corr, D] = dsearchn(data1', tri, data2');
corr(:,2:3) = [(1:length(corr))' D];
corr(D>2*res,:) = [];
corr = -sortrows(-corr,3);
corr = sortrows(corr,1);
[B, Bi, Bj] = unique(corr(:,1));
corr = corr(Bi,:);
[R1 t1] = reg(data1, data2, corr, weights);
data2 = R1*data2;
data2 = [data2(1,:)+t1(1); data2(2,:)+t1(2); data2(3,:)+t1(3)];
R = R1*R;
t = R1*t + t1;
e2 = sum(corr(:,3))/(length(corr)*res);
n = n + 1;
if n > maxIter
break;
end
if abs(e2-e1)<res/10000
noChangeCount = noChangeCount + 1;
end
end
error = min(e1,e2);
%-----------------------------------------------------------------
function [R1, t1] = reg(data1, data2, corr, weights)
n = length(corr);
if nargin<4
weights = ones(n,1);
end
M = data1(:,corr(:,1));
mm = mean(M,2);
S = data2(:,corr(:,2));%*sparse(diag(weights(corr(:,2))));
ms = mean(S,2);
Sshifted = [S(1,:)-ms(1); S(2,:)-ms(2); S(3,:)-ms(3)];
Mshifted = [M(1,:)-mm(1); M(2,:)-mm(2); M(3,:)-mm(3)];
K = Sshifted*sparse(diag(weights(corr(:,2))))*Mshifted';
K = K/n;
[U A V] = svd(K);
R1 = V*U';
if det(R1)<0
B = eye(3);
B(3,3) = det(V*U');
R1 = V*B*U';
end
t1 = mm - R1*ms;
|
github
|
philippboehmsturm/antx-master
|
ft_qualitycheck.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_qualitycheck.m
| 25,639 |
utf_8
|
e995fba1c9f2599395608faaf67621ec
|
function [varargout] = ft_qualitycheck(cfg)
% FT_QUALITYCHECK performs a quality inspection of a given MEG/EEG dataset,
% stores (.mat), and visualizes the result (.png and .pdf).
%
% This function segments the data into 10-second pieces and performs the
% following analyses:
% 1) reads the properties of the dataset
% 2) computes the headpositions and distance covered from recording onset
% (CTF only)
% 3) computes the mean, max, min, and range of the signal amplitude
% 4) detects trigger events
% 5) detects jump artifacts
% 6) computes the powerspectrum
% 7) estimates the low-frequency (<2 Hz) and line noise (~50 Hz)
%
% Use as
% [info, timelock, freq, summary, headpos] = ft_qualitycheck(cfg)
% where info contains the dataset properties, timelock the timelocked data,
% freq the powerspectra, summary the mean descriptives, and headpos the
% headpositions throughout the recording
%
% The configuration should contain:
% cfg.dataset = a string (e.g. 'dataset.ds')
%
% The following parameters can be used:
% cfg.analyze = string, 'yes' or 'no' to analyze the dataset (default = 'yes')
% cfg.savemat = string, 'yes' or 'no' to save the analysis (default = 'yes')
% cfg.matfile = string, filename (e.g. 'previousoutput.mat'), preferably in combination
% with analyze = 'no'
% cfg.visualize = string, 'yes' or 'no' to visualize the analysis (default = 'yes')
% cfg.saveplot = string, 'yes' or 'no' to save the visualization (default = 'yes')
% cfg.linefreq = scalar, frequency of power line (default = 50)
% cfg.plotunit = scalar, the length of time to be plotted in one panel (default = 3600)
%
% See also FT_PREPROCESSING, FT_READ_HEADER, FT_READ_DATA, FT_READ_EVENT
% Copyright (C) 2010-2011, Arjen Stolk, Bram Daams, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id:%
revision = '$Id: ft_qualitycheck.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% set the defaults
cfg.analyze = ft_getopt(cfg, 'analyze', 'yes');
cfg.savemat = ft_getopt(cfg, 'savemat', 'yes');
cfg.matfile = ft_getopt(cfg, 'matfile', []);
cfg.visualize = ft_getopt(cfg, 'visualize', 'yes');
cfg.saveplot = ft_getopt(cfg, 'saveplot', 'yes');
cfg.linefreq = ft_getopt(cfg, 'linefreq', 50);
cfg.plotunit = ft_getopt(cfg, 'plotunit', 3600);
%% ANALYSIS
if strcmp(cfg.analyze,'yes')
tic
% checks
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); % translate into datafile+headerfile
% these will be replaced by more appropriate values
info.datasetname = 'unknown';
info.starttime = 'unknown';
info.startdate = 'unknown';
info.stoptime = 'unknown';
info.stopdate = 'unknown';
% the exportname is also used in the cron job
exportname = qualitycheck_exportname(cfg.dataset);
[iseeg, ismeg, isctf, fltp] = filetyper(cfg.dataset);
if isctf
try
% update the info fields
info = read_ctf_hist(cfg.dataset);
end
end
% add info
info.event = ft_read_event(cfg.dataset);
info.hdr = ft_read_header(cfg.dataset);
info.filetype = fltp;
% trial definition
cfgdef = [];
cfgdef.dataset = cfg.dataset;
cfgdef.trialdef.triallength = 10;
%cfgdef.trialdef.ntrials = 3;
cfgdef.continuous = 'yes';
cfgdef = ft_definetrial(cfgdef);
ntrials = size(cfgdef.trl,1)-1; % remove last trial
timeunit = cfgdef.trialdef.triallength;
% channelselection for jump detection (all) and for FFT (brain)
if ismeg
allchans = ft_channelselection({'MEG','MEGREF'}, info.hdr.label);
chans = ft_channelselection('MEG', info.hdr.label); % brain
allchanindx = match_str(info.hdr.label, allchans);
chanindx = match_str(chans, allchans);
jumpthreshold = 1e-10;
elseif iseeg
allchans = ft_channelselection('EEG', info.hdr.label);
chans = allchans; % brain
allchanindx = match_str(info.hdr.label, allchans);
chanindx = match_str(chans, allchans);
jumpthreshold = 1e4;
end
% find headcoil channels
if isctf % this fails for older CTF data sets
Nx = strmatch('HLC0011', info.hdr.label); % x nasion coil
Ny = strmatch('HLC0012', info.hdr.label); % y nasion
Nz = strmatch('HLC0013', info.hdr.label); % z nasion
Lx = strmatch('HLC0021', info.hdr.label); % x left coil
Ly = strmatch('HLC0022', info.hdr.label); % y left
Lz = strmatch('HLC0023', info.hdr.label); % z left
Rx = strmatch('HLC0031', info.hdr.label); % x right coil
Ry = strmatch('HLC0032', info.hdr.label); % y right
Rz = strmatch('HLC0033', info.hdr.label); % z right
headpos.dimord = 'chan_time';
headpos.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2);
headpos.label = {'Nx';'Ny';'Nz';'Lx';'Ly';'Lz';'Rx';'Ry';'Rz'};
headpos.avg = NaN(length(headpos.label), ntrials);
headpos.grad = info.hdr.grad;
if numel(cat(1,Nx,Ny,Nz,Lx,Ly,Lz,Rx,Ry,Rz))==9
hasheadpos = true;
else
hasheadpos = false;
end
end % if
% analysis settings
cfgredef = [];
cfgredef.length = 1;
cfgredef.overlap = 0;
cfgfreq = [];
cfgfreq.output = 'pow';
cfgfreq.channel = allchans;
cfgfreq.method = 'mtmfft';
cfgfreq.taper = 'hanning';
cfgfreq.keeptrials = 'no';
cfgfreq.foilim = [0 min(info.hdr.Fs/2, 400)];
% output variables
timelock.dimord = 'chan_time';
timelock.label = allchans;
timelock.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2);
timelock.avg = NaN(length(allchans), ntrials); % updated in loop
timelock.median = NaN(length(allchans), ntrials); % updated in loop
timelock.jumps = NaN(length(allchans), ntrials); % updated in loop
timelock.range = NaN(length(allchans), ntrials); % updated in loop
timelock.min = NaN(length(allchans), ntrials); % updated in loop
timelock.max = NaN(length(allchans), ntrials); % updated in loop
freq.dimord = 'chan_freq_time';
freq.label = allchans;
freq.freq = (cfgfreq.foilim(1):cfgfreq.foilim(2));
freq.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2);
freq.powspctrm = NaN(length(allchans), length(freq.freq), ntrials); % updated in loop
summary.dimord = 'chan_time';
summary.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2);
summary.label = {'Mean';'Median';'Min';'Max';'Range';'HmotionN';'HmotionL';'HmotionR';'LowFreqPower';'LineFreqPower';'Jumps'};
summary.avg = NaN(length(summary.label), ntrials); % updated in loop
% try add gradiometer info
if isfield(info.hdr, 'grad'),
timelock.grad = info.hdr.grad;
freq.grad = info.hdr.grad;
summary.grad = info.hdr.grad;
end
% process trial by trial
for t = 1:ntrials
fprintf('analyzing trial %s of %s \n', num2str(t), num2str(ntrials));
% preprocess
cfgpreproc = cfgdef;
cfgpreproc.trl = cfgdef.trl(t,:);
data = ft_preprocessing(cfgpreproc); clear cfgpreproc;
% determine headposition
if isctf && hasheadpos
headpos.avg(1,t) = mean(data.trial{1,1}(Nx,:) * 100); % meter to cm
headpos.avg(2,t) = mean(data.trial{1,1}(Ny,:) * 100);
headpos.avg(3,t) = mean(data.trial{1,1}(Nz,:) * 100);
headpos.avg(4,t) = mean(data.trial{1,1}(Lx,:) * 100);
headpos.avg(5,t) = mean(data.trial{1,1}(Ly,:) * 100);
headpos.avg(6,t) = mean(data.trial{1,1}(Lz,:) * 100);
headpos.avg(7,t) = mean(data.trial{1,1}(Rx,:) * 100);
headpos.avg(8,t) = mean(data.trial{1,1}(Ry,:) * 100);
headpos.avg(9,t) = mean(data.trial{1,1}(Rz,:) * 100);
end
% update values
timelock.avg(:,t) = mean(data.trial{1}(allchanindx,:),2);
timelock.median(:,t) = median(data.trial{1}(allchanindx,:),2);
timelock.range(:,t) = max(data.trial{1}(allchanindx,:),[],2) - min(data.trial{1}(allchanindx,:),[],2);
timelock.min(:,t) = min(data.trial{1}(allchanindx,:),[],2);
timelock.max(:,t) = max(data.trial{1}(allchanindx,:),[],2);
% detect jumps
for c = 1:size(data.trial{1}(allchanindx,:),1)
timelock.jumps(c,t) = length(find(diff(data.trial{1,1}(allchanindx(c),:)) > jumpthreshold));
end
% FFT and noise estimation
redef = ft_redefinetrial(cfgredef, data); clear data;
FFT = ft_freqanalysis(cfgfreq, redef); clear redef;
freq.powspctrm(:,:,t) = FFT.powspctrm;
summary.avg(9,t) = mean(mean(findpower(0, 2, FFT, chanindx))); % Low Freq Power
summary.avg(10,t) = mean(mean(findpower(cfg.linefreq-1, cfg.linefreq+1, FFT, chanindx))); clear FFT; % Line Freq Power
toc
end % end of trial loop
% determine headmotion: distance from initial trial (in cm)
if isctf && hasheadpos
summary.avg(6,:) = sqrt(sum((headpos.avg(1:3,:)-repmat(headpos.avg(1:3,1),1,size(headpos.avg,2))).^2,1)); % N
summary.avg(7,:) = sqrt(sum((headpos.avg(4:6,:)-repmat(headpos.avg(4:6,1),1,size(headpos.avg,2))).^2,1)); % L
summary.avg(8,:) = sqrt(sum((headpos.avg(7:9,:)-repmat(headpos.avg(7:9,1),1,size(headpos.avg,2))).^2,1)); % R
end
% summarize/mean and store variables of brain info only
summary.avg(1,:) = mean(timelock.avg(chanindx,:),1);
summary.avg(2,:) = mean(timelock.median(chanindx,:),1);
summary.avg(3,:) = mean(timelock.min(chanindx,:),1);
summary.avg(4,:) = mean(timelock.max(chanindx,:),1);
summary.avg(5,:) = mean(timelock.range(chanindx,:),1);
summary.avg(11,:) = mean(timelock.jumps(chanindx,:),1);
% save to .mat
if strcmp(cfg.savemat, 'yes')
if isctf && hasheadpos
headpos.cfg = cfg;
save(exportname, 'info','timelock','freq','summary','headpos');
else
save(exportname, 'info','timelock','freq','summary');
end
end
end % end of analysis
%% VISUALIZATION
if strcmp(cfg.visualize, 'yes')
% load data
if strcmp(cfg.analyze, 'no')
if ~isempty(cfg.matfile)
exportname = cfg.matfile;
else
exportname = qualitycheck_exportname(cfg.dataset);
end
fprintf('loading %s \n', exportname);
load(exportname);
end
% determine number of 1-hour plots to be made
nplots = ceil(length(freq.time)/(cfg.plotunit/10));
% create GUI-like figure(s)
for p = 1:nplots
fprintf('visualizing %s of %s \n', num2str(p), num2str(nplots));
toi = [p*cfg.plotunit-(cfg.plotunit-5) p*cfg.plotunit-5]; % select 1-hour chunks
if exist('headpos','var')
temp_timelock = ft_selectdata(timelock, 'toilim', toi);
temp_timelock.cfg = cfg; % be sure to add the cfg here
temp_freq = ft_selectdata(freq, 'toilim', toi);
temp_summary = ft_selectdata(summary, 'toilim', toi);
temp_headpos = ft_selectdata(headpos, 'toilim', toi);
draw_figure(info, temp_timelock, temp_freq, temp_summary, temp_headpos, toi);
clear temp_timelock; clear temp_freq; clear temp_summary; clear temp_headpos; clear toi;
else
temp_timelock = ft_selectdata(timelock, 'toilim', toi);
temp_timelock.cfg = cfg; % be sure to add the cfg here
temp_freq = ft_selectdata(freq, 'toilim', toi);
temp_summary = ft_selectdata(summary, 'toilim', toi);
draw_figure(info, temp_timelock, temp_freq, temp_summary, toi);
clear temp_timelock; clear temp_freq; clear temp_summary; clear toi;
end
% export to .PNG and .PDF
if strcmp(cfg.saveplot, 'yes')
[pathstr,name,extr] = fileparts(exportname);
if p == 1
exportfilename = name;
else
exportfilename = strcat(name,'_pt',num2str(p));
end
fprintf('exporting %s of %s \n', num2str(p), num2str(nplots));
set(gcf, 'PaperType', 'a4');
print(gcf, '-dpng', strcat(exportfilename,'.png'));
orient landscape;
print(gcf, '-dpdf', strcat(exportfilename,'.pdf'));
close
end
end % end of nplots
end % end of visualization
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble history timelock % add the input cfg to multiple outputs
ft_postamble history freq % add the input cfg to multiple outputs
ft_postamble history summary % add the input cfg to multiple outputs
%% VARARGOUT
if nargout>0
mOutputArgs{1} = info;
mOutputArgs{2} = timelock;
mOutputArgs{3} = freq;
mOutputArgs{4} = summary;
try
mOutputArgs{5} = headpos;
end
[varargout{1:nargout}] = mOutputArgs{:};
clearvars -except varargout
else
clear
end
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function [x] = clipat(x, v, v2)
v = [v v2]; % clip between value v and v2
if length(v) == 1
x(x>v) = v;
elseif length(v) == 2
x(x<v(1)) = v(1);
x(x>v(2)) = v(2);
end
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function [iseeg, ismeg, isctf, fltp] = filetyper(dataset)
fltp = ft_filetype(dataset);
iseeg = ft_filetype(dataset,'brainvision_eeg') | ...
ft_filetype(dataset,'ns_eeg') | ...
ft_filetype(dataset,'bci2000_dat') | ...
ft_filetype(dataset,'neuroprax_eeg') | ...
ft_filetype(dataset,'egi_sbin') | ...
ft_filetype(dataset,'biosemi_bdf');
ismeg = ft_filetype(dataset,'ctf_ds') | ...
ft_filetype(dataset,'4d') | ...
ft_filetype(dataset,'neuromag_fif') | ...
ft_filetype(dataset,'itab_raw');
isctf = ft_filetype(dataset, 'ctf_ds');
if ~ismeg && ~iseeg % if none found, try less strict checks
[p, f, ext] = fileparts(dataset);
if strcmp(ext, '.eeg')
fltp = 'brainvision_eeg';
iseeg = 1;
elseif strcmp(ext, '.bdf')
fltp = 'biosemi_bdf';
iseeg = 1;
elseif strcmp(ext, '.ds')
fltp = 'ctf_ds';
ismeg = 1;
else % otherwise use eeg settings for stability reasons
iseeg = 1;
end
end
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function [power, freq] = findpower(low, high, freqinput, chans)
% replace value with the index of the nearest bin
xmin = nearest(getsubfield(freqinput, 'freq'), low);
xmax = nearest(getsubfield(freqinput, 'freq'), high);
% select the freq range
power = freqinput.powspctrm(chans, xmin:xmax);
freq = freqinput.freq(:, xmin:xmax);
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function draw_figure(varargin)
% deal with input
if nargin == 6
info = varargin{1};
timelock = varargin{2};
freq = varargin{3};
summary = varargin{4};
headpos = varargin{5};
toi = varargin{6};
elseif nargin == 5
info = varargin{1};
timelock = varargin{2};
freq = varargin{3};
summary = varargin{4};
toi = varargin{5};
end
% determine whether it is EEG or MEG
[iseeg, ismeg, isctf, fltp] = filetyper(timelock.cfg.dataset);
if ismeg
scaling = 1e15; % assuming data is in T and needs to become fT
powscaling = scaling^2;
ylab = 'fT';
elseif iseeg
scaling = 1e0; % assuming data is in muV already
powscaling = scaling^2;
ylab = '\muV';
end
% PARENT FIGURE
h.MainFigure = figure(...
'MenuBar','none',...
'Name','ft_qualitycheck',...
'Units','normalized',...
'color','white',...
'Position',[0.01 0.01 .99 .99]); % nearly fullscreen
if strcmp(info.startdate,'unknown')
tmp = 'unknown';
else
[d,w] = weekday(info.startdate);
tmp = [w ' ' info.startdate];
end
h.MainText = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',tmp,...
'Backgroundcolor','white',...
'Position',[.06 .96 .15 .02]);
h.MainText2 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Jump artefacts',...
'Backgroundcolor','white',...
'Position',[.08 .46 .12 .02]);
h.MainText3 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Mean powerspectrum',...
'Backgroundcolor','white',...
'Position',[.4 .3 .15 .02]);
h.MainText4 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Timecourses',...
'Backgroundcolor','white',...
'Position',[.5 .96 .11 .02]);
h.MainText5 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Events',...
'Backgroundcolor','white',...
'Position',[.81 .3 .06 .02]);
% HEADMOTION PANEL
h.HmotionPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.01 .5 .25 .47]);
h.DataText = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',info.datasetname,...
'Backgroundcolor','white',...
'Position',[.01 .85 .99 .1]);
h.TimeText = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',[info.starttime ' - ' info.stoptime],...
'Backgroundcolor','white',...
'Position',[.01 .78 .99 .1]);
if ismeg
allchans = ft_senslabel(ft_senstype(timelock));
misschans = setdiff(ft_channelselection('MEG', info.hdr.label), allchans);
nchans = num2str(size(ft_channelselection('MEG', info.hdr.label),1));
else
misschans = '';
nchans = num2str(size(ft_channelselection('EEG', info.hdr.label),1));
end
h.DataText2 = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',[fltp ', fs: ' num2str(info.hdr.Fs) ', nchans: ' nchans],...
'Backgroundcolor','white',...
'Position',[.01 .71 .99 .1]);
h.DataText3 = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['missing chans: ' misschans'],...
'Backgroundcolor','white',...
'Position',[.01 .64 .99 .1]);
% boxplot headmotion (*10; cm-> mm) per coil
if exist('headpos','var')
h.HmotionAxes = axes(...
'Parent',h.HmotionPanel,...
'Units','normalized',...
'color','white',...
'Position',[.05 .08 .9 .52]);
hmotions = ([summary.avg(8,:)' summary.avg(7,:)' summary.avg(6,:)'])*10;
boxplot(h.HmotionAxes, hmotions, 'orientation', 'horizontal', 'notch', 'on');
set(h.HmotionAxes,'YTick',1:3);
set(h.HmotionAxes,'YTickLabel',{'R','L','N'});
xlim(h.HmotionAxes, [0 10]);
xlabel(h.HmotionAxes, 'Headmotion from start [mm]');
end
% TIMECOURSE PANEL
h.SignalPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.28 .34 .71 .63]);
h.SignalAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .36 .89 .3]);
h.LinenoiseAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .23 .89 .1]);
h.LowfreqnoiseAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .1 .89 .1]);
% plot hmotion timecourses per coil (*10; cm-> mm)
if exist('headpos','var')
h.HmotionTimecourseAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .73 .89 .22]);
plot(h.HmotionTimecourseAxes, summary.time, clipat(summary.avg(6,:)*10, 0, 10), ...
summary.time, clipat(summary.avg(7,:)*10, 0, 10), ...
summary.time, clipat(summary.avg(8,:)*10, 0, 10), 'LineWidth',2);
ylim(h.HmotionTimecourseAxes,[0 10]);
ylabel(h.HmotionTimecourseAxes, 'Coil distance [mm]');
xlim(h.HmotionTimecourseAxes,toi);
grid(h.HmotionTimecourseAxes,'on');
legend(h.HmotionTimecourseAxes, 'N','L','R');
end
% plot mean and range of the raw signal
plot(h.SignalAxes, summary.time, summary.avg(5,:)*scaling, summary.time, summary.avg(1,:)*scaling, 'LineWidth', 2);
set(h.SignalAxes,'Nextplot','add');
plot(h.SignalAxes, summary.time, summary.avg(3,:)*scaling, summary.time, summary.avg(4,:)*scaling, 'LineWidth', 1, 'Color', [255/255 127/255 39/255]);
grid(h.SignalAxes,'on');
ylabel(h.SignalAxes, ['Amplitude [' ylab ']']);
xlim(h.SignalAxes,toi);
legend(h.SignalAxes,'Range','Mean','Min','Max');
set(h.SignalAxes,'XTickLabel','');
% plot linenoise
semilogy(h.LinenoiseAxes, summary.time, clipat(summary.avg(10,:)*powscaling, 1e2, 1e4), 'LineWidth',2);
grid(h.LinenoiseAxes,'on');
legend(h.LinenoiseAxes, ['LineFreq [' ylab '^2/Hz]']);
set(h.LinenoiseAxes,'XTickLabel','');
xlim(h.LinenoiseAxes,toi);
ylim(h.LinenoiseAxes,[1e2 1e4]); % before april 28th this was 1e0 - 1e3
% plot lowfreqnoise
semilogy(h.LowfreqnoiseAxes, summary.time, clipat(summary.avg(9,:)*powscaling, 1e10, 1e12), 'LineWidth',2);
grid(h.LowfreqnoiseAxes,'on');
xlim(h.LowfreqnoiseAxes,toi);
ylim(h.LowfreqnoiseAxes,[1e10 1e12]);
legend(h.LowfreqnoiseAxes, ['LowFreq [' ylab '^2/Hz]']);
xlabel(h.LowfreqnoiseAxes, 'Time [seconds]'); % before april 28th this was 1e0 - 1e10
% EVENT PANEL
h.EventPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.7 .01 .29 .3]);
% event details
eventtypes = {};
eventtriggers = {};
eventvalues = {};
if ~isempty(info.event)
[a,b,c] = unique({info.event.type});
for j=1:length(a)
eventtypes{j,1} = a{j};
eventtriggers{j,1} = sum(c==j);
eventvalues{j,1} = length(unique([info.event(c==j).value]));
end
end
if isempty(eventtypes)
eventtypes{1,1} = 'no triggers found';
end
h.EventText = uicontrol(...
'Parent',h.EventPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['Types'; ' '; eventtypes],...
'Backgroundcolor','white',...
'Position',[.05 .05 .4 .85]);
h.EventText2 = uicontrol(...
'Parent',h.EventPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['Triggers'; ' '; eventtriggers],...
'Backgroundcolor','white',...
'Position',[.55 .05 .2 .85]);
h.EventText3 = uicontrol(...
'Parent',h.EventPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['Values'; ' '; eventvalues],...
'Backgroundcolor','white',...
'Position',[.8 .05 .15 .85]);
% POWERSPECTRUM PANEL
h.SpectrumPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.28 .01 .4 .3]);
h.SpectrumAxes = axes(...
'Parent',h.SpectrumPanel,...
'Units','normalized',...
'color','white',...
'Position',[.15 .2 .8 .7]);
% plot powerspectrum
loglog(h.SpectrumAxes, freq.freq, squeeze(mean(mean(freq.powspctrm,1),3))*powscaling,'r','LineWidth',2);
xlabel(h.SpectrumAxes, 'Frequency [Hz]');
ylabel(h.SpectrumAxes, ['Power [' ylab '^2/Hz]']);
% ARTEFACT PANEL
h.JumpPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.01 .01 .25 .46]);
% jump details
jumpchans = {};
jumpcounts = {};
[jumps,i] = find(timelock.jumps>0); % find all jumps
[a,b,c] = unique(jumps);
for j=1:length(a)
jumpchans{j,1} = timelock.label{a(j)};
jumpcounts{j,1} = sum(c==j);
end
if isempty(jumpchans)
jumpchans{1,1} = 'no jumps detected';
end
h.JumpText = uicontrol(...
'Parent',h.JumpPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',jumpchans,...
'Backgroundcolor','white',...
'Position',[.15 .5 .25 .4]);
h.JumpText2 = uicontrol(...
'Parent',h.JumpPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',jumpcounts,...
'Backgroundcolor','white',...
'Position',[.65 .5 .2 .4]);
% plot jumps on the dewar sensors
if ismeg
h.TopoMEG = axes(...
'Parent',h.JumpPanel,...
'color','white',...
'Units','normalized',...
'Position',[0.4 0.05 0.55 0.4]);
MEGchans = ft_channelselection('MEG', timelock.label);
MEGchanindx = match_str(timelock.label, MEGchans);
cfgtopo = [];
cfgtopo.marker = 'off';
cfgtopo.colorbar = 'no';
cfgtopo.comment = 'no';
cfgtopo.style = 'blank';
cfgtopo.layout = ft_prepare_layout(timelock);
cfgtopo.highlight = 'on';
cfgtopo.highlightsymbol = '.';
cfgtopo.highlightsize = 14;
cfgtopo.highlightchannel = find(sum(timelock.jumps(MEGchanindx,:),2)>0);
data.label = MEGchans;
data.powspctrm = sum(timelock.jumps(MEGchanindx,:),2);
data.dimord = 'chan_freq';
data.freq = 1;
axes(h.TopoMEG);
ft_topoplotTFR(cfgtopo, data); clear data;
end
|
github
|
philippboehmsturm/antx-master
|
ft_denoise_pca.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_denoise_pca.m
| 16,673 |
utf_8
|
8eba524b752f9743586ca6d1507aa9fb
|
function data = ft_denoise_pca(cfg, varargin)
% FT_DENOISE_PCA performs a principal component analysis (PCA) on specified
% reference channels and subtracts the projection of the data of interest onto
% this orthogonal basis from the data of interest. This is the algorithm which
% is applied by 4D to compute noise cancellation weights on a dataset of
% interest. This function has been designed for 4D MEG data, but can also be
% applied to data from other MEG systems.
%
% Use as
% [dataout] = ft_denoise_pca(cfg, data)
% or
% [dataout] = ft_denoise_pca(cfg, data, refdata)
%
% where data is a raw data-structure with MEG data that was obtained with
% FT_PREPROCESSING. If an additional data-structure refdata is in the input, the
% specified reference channels for the regression will be taken from this second
% data structure. This can be useful when reference channel specific
% preprocessing needs to be done (e.g. low-pass filtering).
%
% The output structure dataout contains the denoised data in a format that is
% consistent with the output of FT_PREPROCESSING.
%
% The configuration should be according to
% cfg.refchannel = the channels used as reference signal (default = 'MEGREF')
% cfg.channel = the channels to be denoised (default = 'MEG')
% cfg.truncate = optional truncation of the singular value spectrum (default = 'no')
% cfg.zscore = standardise reference data prior to PCA (default = 'no')
% cfg.pertrial = 'no' (default) or 'yes'. Regress out the references on
% a per trial basis
% cfg.trials = list of trials that are used (default = 'all')
%
% if cfg.truncate is integer n > 1, n will be the number of singular values kept.
% if 0 < cfg.truncate < 1, the singular value spectrum will be thresholded at the
% fraction cfg.truncate of the largest singular value.
%
% See also FT_PREPROCESSING, FT_DENOISE_SYNTHETIC
% Undocumented cfg-option: cfg.pca the output structure of an earlier call
% to the function. Can be used regress out the reference channels from
% another data set.
% Copyright (c) 2008-2009, Jan-Mathijs Schoffelen, CCNi Glasgow
% Copyright (c) 2010-2011, Jan-Mathijs Schoffelen, DCCN Nijmegen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_denoise_pca.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_denoise_pca.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% check if the input data is valid for this function
for i=1:length(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'raw');
end
% set the defaults
cfg.refchannel = ft_getopt(cfg, 'refchannel', 'MEGREF');
cfg.channel = ft_getopt(cfg, 'channel', 'MEG');
cfg.truncate = ft_getopt(cfg, 'truncate', 'no');
cfg.zscore = ft_getopt(cfg, 'zscore', 'no');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.pertrial = ft_getopt(cfg, 'pertrial', 'no');
cfg.feedback = ft_getopt(cfg, 'feedback', 'none');
if strcmp(cfg.pertrial, 'yes'),
tmpcfg = cfg;
tmpcfg.pertrial = 'no';
tmp = cell(numel(varargin{1}.trial),1);
for k = 1:numel(varargin{1}.trial)
tmpcfg.trials = k;
tmp{k,1} = ft_denoise_pca(tmpcfg, varargin{:});
end
data = ft_appenddata([], tmp{:});
return;
end
computeweights = ~isfield(cfg, 'pca');
if length(varargin)==1,
% channel data and reference channel data are in 1 data structure
data = varargin{1};
megchan = ft_channelselection(cfg.channel, data.label);
refchan = ft_channelselection(cfg.refchannel, data.label);
% split data into data and refdata
tmpcfg = [];
tmpcfg.channel = refchan;
tmpcfg.feedback = cfg.feedback;
refdata = ft_preprocessing(tmpcfg, data);
tmpcfg.channel = megchan;
data = ft_preprocessing(tmpcfg, data);
else
% channel data and reference channel data are in 2 data structures
data = varargin{1};
refdata = varargin{2};
megchan = ft_channelselection(cfg.channel, data.label);
refchan = ft_channelselection(cfg.refchannel, refdata.label);
% split data into data and refdata
tmpcfg = [];
tmpcfg.channel = refchan;
tmpcfg.feedback = cfg.feedback;
refdata = ft_preprocessing(tmpcfg, refdata);
tmpcfg.channel = megchan;
data = ft_preprocessing(tmpcfg, data);
%FIXME do compatibility check on data vs refdata with respect to dimensions (time-trials)
end
% select trials of interest
if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end % set the default
if ~strcmp(cfg.trials, 'all')
fprintf('selecting %d trials\n', length(cfg.trials));
data = ft_selectdata(data, 'rpt', cfg.trials);
refdata = ft_selectdata(refdata, 'rpt', cfg.trials);
end
refchan = ft_channelselection(cfg.refchannel, refdata.label);
refindx = match_str(refdata.label, refchan);
megchan = ft_channelselection(cfg.channel, data.label);
megindx = match_str(data.label, megchan);
if ~computeweights
else
% do nothing
end
nref = length(refindx);
ntrl = length(data.trial);
if ischar(cfg.truncate) && strcmp(cfg.truncate, 'no'),
cfg.truncate = length(refindx);
elseif ischar(cfg.truncate) || (cfg.truncate>1 && cfg.truncate/round(cfg.truncate)~=1) || ...
cfg.truncate>length(refindx),
error('cfg.truncate should be either ''no'', an integer number <= the number of references, or a number between 0 and 1');
%FIXME the default truncation applied by 4D is 1x10^-8
end
% compute and remove mean from data
fprintf('removing the mean from the channel data and reference channel data\n');
m = cellmean(data.trial, 2);
data.trial = cellvecadd(data.trial, -m);
m = cellmean(refdata.trial, 2);
refdata.trial = cellvecadd(refdata.trial, -m);
% compute std of data before the regression
stdpre = cellstd(data.trial, 2);
if computeweights,
% zscore
if strcmp(cfg.zscore, 'yes'),
fprintf('zscoring the reference channel data\n');
[refdata.trial, sdref] = cellzscore(refdata.trial, 2, 0); %forced demeaned already
else
sdref = ones(nref,1);
end
% compute covariance of refchannels and do svd
fprintf('performing pca on the reference channel data\n');
crefdat = cellcov(refdata.trial, [], 2, 0);
[u,s,v] = svd(crefdat);
% determine the truncation and rotation
if cfg.truncate<1
% keep all singular vectors with singular values >= cfg.truncate*s(1,1)
s1 = s./max(s(:));
keep = find(diag(s1)>cfg.truncate);
else
keep = 1:cfg.truncate;
end
fprintf('keeping %d out of %d components\n',numel(keep),size(u,2));
rotmat = u(:, keep)';
% rotate the refdata
fprintf('projecting the reference data onto the pca-subspace\n');
refdata.trial = cellfun(@mtimes, repmat({rotmat}, 1, ntrl), refdata.trial, 'UniformOutput', 0);
% project megdata onto the orthogonal basis
fprintf('computing the regression weights\n');
nom = cellcov(data.trial, refdata.trial, 2, 0);
denom = cellcov(refdata.trial, [], 2, 0);
rw = (pinv(denom)*nom')';
%subtract projected data
fprintf('subtracting the reference channel data from the channel data\n');
for k = 1:ntrl
data.trial{k} = data.trial{k} - rw*refdata.trial{k};
end
%rotate back and 'unscale'
pca.w = rw*rotmat*diag(1./sdref);
pca.label = data.label;
pca.reflabel = refdata.label;
pca.rotmat = rotmat;
cfg.pca = pca;
else
fprintf('applying precomputed weights to the data\n');
% check whether the weight table contains the specified references
% ensure the ordering of the meg-data to be consistent with the weights
% ensure the ordering of the ref-data to be consistent with the weights
[i1,i2] = match_str(refchan, cfg.pca.reflabel);
[i3,i4] = match_str(megchan, cfg.pca.label);
if length(i2)~=length(cfg.pca.reflabel),
error('you specified fewer references to use as there are in the precomputed weight table');
end
refindx = refindx(i1);
megindx = megindx(i3);
cfg.pca.w = cfg.pca.w(i4,i2);
cfg.pca.label = cfg.pca.label(i4);
cfg.pca.reflabel= cfg.pca.reflabel(i2);
if isfield(cfg.pca, 'rotmat'),
cfg.pca = rmfield(cfg.pca, 'rotmat'); % dont know
end
for k = 1:ntrl
data.trial{k} = data.trial{k} - cfg.pca.w*refdata.trial{k};
end
pca = cfg.pca;
end
% compute std of data after
stdpst = cellstd(data.trial, 2);
% demean FIXME is this needed
m = cellmean(data.trial, 2);
data.trial = cellvecadd(data.trial, -m);
% apply weights to the gradiometer-array
if isfield(data, 'grad')
fprintf('applying the weights to the gradiometer balancing matrix\n');
montage = [];
labelnew = pca.label;
nlabelnew = length(labelnew);
%add columns of refchannels not yet present in labelnew
%[id, i1] = setdiff(pca.reflabel, labelnew);
%labelorg = [labelnew; pca.reflabel(sort(i1))];
labelorg = data.grad.label;
nlabelorg = length(labelorg);
%start with identity
montage.tra = eye(nlabelorg);
%subtract weights
[i1, i2] = match_str(labelorg, pca.reflabel);
[i3, i4] = match_str(labelorg, pca.label);
montage.tra(i3,i1) = montage.tra(i3,i1) - pca.w(i4,i2);
montage.labelorg = labelorg;
montage.labelnew = labelorg;
data.grad = ft_apply_montage(data.grad, montage, 'keepunused', 'yes', 'balancename', 'pca');
% order the fields
fnames = fieldnames(data.grad.balance);
tmp = false(1,numel(fnames));
for k = 1:numel(fnames)
tmp(k) = isstruct(data.grad.balance.(fnames{k}));
end
[tmp, ix] = sort(tmp,'descend');
data.grad.balance = orderfields(data.grad.balance, fnames(ix));
else
warning('fieldtrip:ft_denoise_pca:WeightsNotAppliedToSensors', 'weights have been applied to the data only, not to the sensors');
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
ft_postamble history data
ft_postamble savevar data
%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS
%%%%%%%%%%%%%%%%%
%-----cellcov
function [c] = cellcov(x, y, dim, flag)
% [C] = CELLCOV(X, DIM) computes the covariance, across all cells in x along
% the dimension dim. When there are three inputs, covariance is computed between
% all cells in x and y
%
% X (and Y) should be linear cell-array(s) of matrices for which the size in at
% least one of the dimensions should be the same for all cells
if nargin==2,
flag = 1;
dim = y;
y = [];
elseif nargin==3,
flag = 1;
end
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if nargin==1,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute covariance for');
end
end
if flag,
mx = cellmean(x, 2);
x = cellvecadd(x, -mx);
if ~isempty(y),
my = cellmean(y, 2);
y = cellvecadd(y, -my);
end
end
nx = max(nx);
nsmp = cellfun('size', x, dim);
if isempty(y),
csmp = cellfun(@covc, x, repmat({dim},1,nx), 'UniformOutput', 0);
else
csmp = cellfun(@covc, x, y, repmat({dim},1,nx), 'UniformOutput', 0);
end
nc = size(csmp{1});
c = sum(reshape(cell2mat(csmp), [nc(1) nc(2) nx]), 3)./sum(nsmp);
function [c] = covc(x, y, dim)
if nargin==2,
dim = y;
y = x;
end
if dim==1,
c = x'*y;
elseif dim==2,
c = x*y';
end
%-----cellmean
function [m] = cellmean(x, dim)
% [M] = CELLMEAN(X, DIM) computes the mean, across all cells in x along
% the dimension dim.
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if nargin==1,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
end
nx = max(nx);
nsmp = cellfun('size', x, dim);
ssmp = cellfun(@sum, x, repmat({dim},1,nx), 'UniformOutput', 0);
m = sum(cell2mat(ssmp), dim)./sum(nsmp);
%-----cellstd
function [sd] = cellstd(x, dim, flag)
% [M] = CELLSTD(X, DIM, FLAG) computes the standard deviation, across all cells in x along
% the dimension dim, normalising by the total number of samples
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells. If flag==1, the mean will
% be subtracted first (default behaviour, but to save time on already demeaned data, it
% can be set to 0).
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellstd');
end
if nargin<2,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
elseif nargin==2,
flag = 1;
end
if flag,
m = cellmean(x, dim);
x = cellvecadd(x, -m);
end
nx = max(nx);
nsmp = cellfun('size', x, dim);
ssmp = cellfun(@sumsq, x, repmat({dim},1,nx), 'UniformOutput', 0);
sd = sqrt(sum(cell2mat(ssmp), dim)./sum(nsmp));
function [s] = sumsq(x, dim)
s = sum(x.^2, dim);
%-----cellvecadd
function [y] = cellvecadd(x, v)
% [Y]= CELLVECADD(X, V) - add vector to all rows or columns of each matrix
% in cell-array X
% check once and for all to save time
persistent bsxfun_exists;
if isempty(bsxfun_exists);
bsxfun_exists=exist('bsxfun','builtin');
if ~bsxfun_exists;
error('bsxfun not found.');
end
end
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if ~iscell(v),
v = repmat({v}, nx);
end
y = cellfun(@bsxfun, repmat({@plus}, nx), x, v, 'UniformOutput', 0);
%-----cellvecmult
function [y] = cellvecmult(x, v)
% [Y]= CELLVECMULT(X, V) - multiply vectors in cell-array V
% to all rows or columns of each matrix in cell-array X
% V can be a vector or a cell-array of vectors
% check once and for all to save time
persistent bsxfun_exists;
if isempty(bsxfun_exists);
bsxfun_exists=exist('bsxfun','builtin');
if ~bsxfun_exists;
error('bsxfun not found.');
end
end
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if ~iscell(v),
v = repmat({v}, nx);
end
sx1 = cellfun('size', x, 1);
sx2 = cellfun('size', x, 2);
sv1 = cellfun('size', v, 1);
sv2 = cellfun('size', v, 2);
if all(sx1==sv1) && all(sv2==1),
elseif all(sx2==sv2) && all(sv1==1),
elseif all(sv1==1) && all(sv2==1),
else error('inconsistent input');
end
y = cellfun(@bsxfun, repmat({@times}, nx), x, v, 'UniformOutput', 0);
%-----cellzscore
function [z, sd, m] = cellzscore(x, dim, flag)
% [Z, SD] = CELLZSCORE(X, DIM, FLAG) computes the zscore, across all cells in x along
% the dimension dim, normalising by the total number of samples
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells. If flag==1, the mean will
% be subtracted first (default behaviour, but to save time on already demeaned data, it
% can be set to 0). SD is a vector containing the standard deviations, used for the normalisation.
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellstd');
end
if nargin<2,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
elseif nargin==2,
flag = 1;
end
if flag,
m = cellmean(x, dim);
x = cellvecadd(x, -m);
end
sd = cellstd(x, dim, 0);
z = cellvecmult(x, 1./sd);
|
github
|
philippboehmsturm/antx-master
|
ft_sensorrealign.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_sensorrealign.m
| 31,763 |
utf_8
|
a8c06b8f47f8da67954655edab1ec82a
|
function [elec_realigned] = ft_sensorrealign(cfg, elec_original)
% FT_SENSORREALIGN rotates and translates electrode and gradiometer
% sensor positions to template electrode positions or towards the head
% surface. It can either perform a rigid body transformation, in which only
% the coordinate system is changed, or it can apply additional deformations
% to the input sensors. Different methods for aligning the input electrodes
% to the subjects head are implemented, which are described in detail
% below.
%
% FIDUCIAL - You can apply a rigid body realignment based on three fiducial
% locations. After realigning, the fiducials in the input electrode set
% (typically nose, left and right ear) are along the same axes as the
% fiducials in the template electrode set.
%
% TEMPLATE - You can apply a spatial transformation/deformation that
% automatically minimizes the distance between the electrodes or
% gradiometers and a template or sensor array. The warping methods use a
% non-linear search to minimize the distance between the input sensor
% positions and the corresponding template sensors.
%
% HEADSHAPE - You can apply a spatial transformation/deformation that
% automatically minimizes the distance between the electrodes and the head
% surface. The warping methods use a non-linear search to minimize the
% distance between the input sensor positions and the projection of the
% electrodes on the head surface.
%
% INTERACTIVE - You can display the skin surface together with the
% electrode or gradiometer positions, and manually (using the graphical
% user interface) adjust the rotation, translation and scaling parameters,
% so that the electrodes correspond with the skin.
%
% MANUAL - You can display the skin surface and manually determine the
% electrode positions by clicking on the skin surface.
%
% Use as
% [sensor] = ft_sensorrealign(cfg) or
% [sensor] = ft_sensorrealign(cfg, sensor)
% where you specify the electrodes or gradiometers in the configuration
% structure (see below) or as the second input argument.
%
% The configuration can contain the following options
% cfg.method = string representing the method for aligning or placing the electrodes
% 'fiducial' realign using three fiducials (e.g. NAS, LPA and RPA)
% 'template' realign the sensors to match a template set
% 'headshape' realign the sensors to fit the head surface
% 'interactive' realign manually using a graphical user interface
% 'manual' manual positioning of the electrodes by clicking in a graphical user interface
% cfg.warp = string describing the spatial transformation for the template method
% 'rigidbody' apply a rigid-body warp (default)
% 'globalrescale' apply a rigid-body warp with global rescaling
% 'traditional' apply a rigid-body warp with individual axes rescaling
% 'nonlin1' apply a 1st order non-linear warp
% 'nonlin2' apply a 2nd order non-linear warp
% 'nonlin3' apply a 3rd order non-linear warp
% 'nonlin4' apply a 4th order non-linear warp
% 'nonlin5' apply a 5th order non-linear warp
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.fiducial = cell-array with the name of three fiducials used for
% realigning (default = {'nasion', 'lpa', 'rpa'})
% cfg.casesensitive = 'yes' or 'no', determines whether string comparisons
% between electrode labels are case sensitive (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
%
% The EEG or MEG sensor positions can be present in the second input argument or can be specified as
% cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS
% cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS
% cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS
% cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS
%
% To realign the sensors using the fiducials, the target has to contain the
% three template fiducials, e.g.
% cfg.target.pnt(1,:) = [110 0 0] % location of the nose
% cfg.target.pnt(2,:) = [0 90 0] % location of the left ear
% cfg.target.pnt(3,:) = [0 -90 0] % location of the right ear
% cfg.target.label = {'NAS', 'LPA', 'RPA'}
%
% To align the sensors to a single template set or to multiple electrode
% sets (which will be averaged), you should specify the target as
% cfg.target = single electrode or gradiometer set that serves as standard
% or
% cfg.target(1..N) = list of electrode or gradiometer sets that are averaged into the standard
% The target electrode or gradiometer sets can be specified either as
% structures (i.e. when they are already read in memory) or as file names.
%
% To align existing electrodes to the head surface, or to manually position
% new electrodes using the head surface, you should specify
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% See also FT_READ_SENS, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN
% Copyright (C) 2005-2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sensorrealign.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_sensorrealign.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% the interactive method uses a global variable to get the data from the figure when it is closed
global norm
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'coordsys'), cfg.coordsys = []; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end
if ~isfield(cfg, 'warp'), cfg.warp = 'rigidbody'; end
if ~isfield(cfg, 'label'), cfg.label = 'off'; end
cfg = ft_checkconfig(cfg, 'renamed', {'template', 'target'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'});
cfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogenous', 'rigidbody'});
cfg = ft_checkconfig(cfg, 'forbidden', 'outline');
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
if ~isempty(cfg.coordsys)
switch lower(cfg.coordsys)
case 'ctf'
cfg.target = [];
cfg.target.pnt(1,:) = [100 0 0];
cfg.target.pnt(2,:) = [0 80 0];
cfg.target.pnt(3,:) = [0 -80 0];
cfg.target.label{1} = 'NAS';
cfg.target.label{2} = 'LPA';
cfg.target.label{3} = 'RPA';
otherwise
error('the %s coordinate system is not automatically supported, please specify the details in cfg.target')
end
end
% ensure that the right cfg options have been set corresponding to the method
switch cfg.method
case 'template' % realign the sensors to match a template set
cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape');
case 'headshape' % realign the sensors to fit the head surface
cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target');
case 'fiducial' % realign using the NAS, LPA and RPA fiducials
cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape');
case 'interactive' % realign manually using a graphical user interface
cfg = ft_checkconfig(cfg, 'required', 'headshape');
case 'manual' % manual positioning of the electrodes by clicking in a graphical user interface
cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target');
end % switch cfg.method
% get the electrode definition that should be warped
if nargin==1
try % try to get the description from the cfg
elec_original = ft_fetch_sens(cfg);
catch lasterr
% start with an empty set of electrodes, this is useful for manual positioning
elec_original = [];
elec_original.pnt = zeros(0,3);
elec_original.label = cell(0,1);
elec_original.unit = 'mm';
warning(lasterr.message, lasterr.identifier);
end
elseif nargin>1
% the input electrodes were specified as second input argument
end
% ensure that the units are specified
elec_original = ft_convert_units(elec_original);
elec_original = ft_datatype_sens(elec_original); % ensure up-to-date sensor description (Oct 2011)
% remember the original electrode locations and labels and do all the work
% with a temporary copy, this involves channel selection and changing to
% lower case
elec = elec_original;
if strcmp(cfg.method, 'fiducial') && isfield(elec, 'fid')
% instead of working with all sensors, only work with the fiducials
% this is useful for gradiometer structures
fprintf('using the fiducials instead of the sensor positions\n');
elec.fid.unit = elec.unit;
elec = elec.fid;
end
usetemplate = isfield(cfg, 'target') && ~isempty(cfg.target);
useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape);
if usetemplate
% get the template electrode definitions
if ~iscell(cfg.target)
cfg.target = {cfg.target};
end
Ntemplate = length(cfg.target);
for i=1:Ntemplate
if isstruct(cfg.target{i})
template(i) = cfg.target{i};
else
template(i) = ft_read_sens(cfg.target{i});
end
end
clear tmp
for i=1:Ntemplate
tmp(i) = ft_datatype_sens(template(i)); % ensure up-to-date sensor description
tmp(i) = ft_convert_units(template(i), elec.unit); % ensure that the units are consistent with the electrodes
end
template = tmp;
end
if useheadshape
% get the surface describing the head shape
if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')
% use the headshape surface specified in the configuration
headshape = cfg.headshape;
elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3
% use the headshape points specified in the configuration
headshape.pnt = cfg.headshape;
elseif ischar(cfg.headshape)
% read the headshape from file
headshape = ft_read_headshape(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.pnt = unique(headshape.pnt, 'rows');
headshape.tri = projecttri(headshape.pnt);
end
headshape = ft_convert_units(headshape, elec.unit); % ensure that the units are consistent with the electrodes
end
% convert all labels to lower case for string comparisons
% this has to be done AFTER keeping the original labels and positions
if strcmp(cfg.casesensitive, 'no')
for i=1:length(elec.label)
elec.label{i} = lower(elec.label{i});
end
for j=1:length(template)
for i=1:length(template(j).label)
template(j).label{i} = lower(template(j).label{i});
end
end
end
if strcmp(cfg.feedback, 'yes')
% create an empty figure, continued below...
figure
axis equal
axis vis3d
hold on
xlabel('x')
ylabel('y')
zlabel('z')
end
% start with an empty structure, this will be returned at the end
norm = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.method, 'template')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
for i=1:Ntemplate
cfg.channel = ft_channelselection(cfg.channel, template(i).label);
end
% make consistent subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.chanpos = elec.chanpos(datsel,:);
for i=1:Ntemplate
[cfgsel, datsel] = match_str(cfg.channel, template(i).label);
template(i).label = template(i).label(datsel);
template(i).pnt = template(i).pnt(datsel,:);
end
% compute the average of the template electrode positions
average = ft_average_sens(template);
fprintf('warping electrodes to average template... '); % the newline comes later
[norm.chanpos, norm.m] = warp_optim(elec.chanpos, average.chanpos, cfg.warp);
norm.label = elec.label;
dpre = mean(sqrt(sum((average.chanpos - elec.chanpos).^2, 2)));
dpost = mean(sqrt(sum((average.chanpos - norm.chanpos).^2, 2)));
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot all electrodes before warping
ft_plot_sens(elec, 'r*');
% plot all electrodes after warping
ft_plot_sens(norm, 'm.', 'label', 'label');
% plot the template electrode locations
ft_plot_sens(average, 'b.');
% plot lines connecting the input and the realigned electrode locations with the template locations
my_line3(elec.chanpos, average.chanpos, 'color', 'r');
my_line3(norm.chanpos, average.chanpos, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'headshape')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.chanpos = elec.chanpos(datsel,:);
fprintf('warping electrodes to skin surface... '); % the newline comes later
[norm.chanpos, norm.m] = warp_optim(elec.chanpos, headshape, cfg.warp);
norm.label = elec.label;
dpre = warp_error([], elec.chanpos, headshape, cfg.warp);
dpost = warp_error(norm.m, elec.chanpos, headshape, cfg.warp);
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'fiducial')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the fiducials have to be present in the electrodes and in the template set
label = intersect(lower(elec.label), lower(template.label));
if ~isfield(cfg, 'fiducial') || isempty(cfg.fiducial)
% try to determine the names of the fiducials automatically
option1 = {'nasion' 'left' 'right'};
option2 = {'nasion' 'lpa' 'rpa'};
option3 = {'nz' 'left' 'right'};
option4 = {'nz' 'lpa' 'rpa'};
option5 = {'nas' 'left' 'right'};
option6 = {'nas' 'lpa' 'rpa'};
if length(match_str(label, option1))==3
cfg.fiducial = option1;
elseif length(match_str(label, option2))==3
cfg.fiducial = option2;
elseif length(match_str(label, option3))==3
cfg.fiducial = option3;
elseif length(match_str(label, option4))==3
cfg.fiducial = option4;
elseif length(match_str(label, option5))==3
cfg.fiducial = option5;
elseif length(match_str(label, option6))==3
cfg.fiducial = option6;
else
error('could not determine consistent fiducials in the input and the target, please specify cfg.fiducial or cfg.coordsys')
end
end
fprintf('matching fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3});
% determine electrode selection
cfg.channel = ft_channelselection(cfg.channel, elec.label);
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.chanpos = elec.chanpos(datsel,:);
if length(cfg.fiducial)~=3
error('you must specify three fiducials');
end
% do case-insensitive search for fiducial locations
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error('not all fiducials were found in the electrode set');
end
elec_nas = elec.chanpos(nas_indx,:);
elec_lpa = elec.chanpos(lpa_indx,:);
elec_rpa = elec.chanpos(rpa_indx,:);
% FIXME change the flow in the remainder
% if one or more template electrode sets are specified, then align to the average of those
% if no template is specified, then align so that the fiducials are along the axis
% find the matching fiducials in the template and average them
templ_nas = nan(Ntemplate,3);
templ_lpa = nan(Ntemplate,3);
templ_rpa = nan(Ntemplate,3);
for i=1:Ntemplate
nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error(sprintf('not all fiducials were found in template %d', i));
end
templ_nas(i,:) = template(i).pnt(nas_indx,:);
templ_lpa(i,:) = template(i).pnt(lpa_indx,:);
templ_rpa(i,:) = template(i).pnt(rpa_indx,:);
end
templ_nas = mean(templ_nas,1);
templ_lpa = mean(templ_lpa,1);
templ_rpa = mean(templ_rpa,1);
% realign both to a common coordinate system
elec2common = headcoordinates(elec_nas, elec_lpa, elec_rpa);
templ2common = headcoordinates(templ_nas, templ_lpa, templ_rpa);
% compute the combined transform and realign the electrodes to the template
norm = [];
norm.m = elec2common * inv(templ2common);
norm.chanpos = warp_apply(norm.m, elec.chanpos, 'homogeneous');
norm.label = elec.label;
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
dpre = mean(sqrt(sum((elec.chanpos([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3}));
dpost = mean(sqrt(sum((norm.chanpos([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot the first three electrodes before transformation
my_plot3(elec.chanpos(1,:), 'r*');
my_plot3(elec.chanpos(2,:), 'r*');
my_plot3(elec.chanpos(3,:), 'r*');
my_text3(elec.chanpos(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.chanpos(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.chanpos(3,:), elec.label{3}, 'color', 'r');
% plot the template fiducials
my_plot3(templ_nas, 'b*');
my_plot3(templ_lpa, 'b*');
my_plot3(templ_rpa, 'b*');
my_text3(templ_nas, ' nas', 'color', 'b');
my_text3(templ_lpa, ' lpa', 'color', 'b');
my_text3(templ_rpa, ' rpa', 'color', 'b');
% plot all electrodes after transformation
my_plot3(norm.chanpos, 'm.');
my_plot3(norm.chanpos(1,:), 'm*');
my_plot3(norm.chanpos(2,:), 'm*');
my_plot3(norm.chanpos(3,:), 'm*');
my_text3(norm.chanpos(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.chanpos(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.chanpos(3,:), norm.label{3}, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'interactive')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% give the user instructions
disp('Use the mouse to rotate the head and the electrodes around, and click "redisplay"');
disp('Close the figure when you are done');
% open a figure
fig = figure;
% add the data to the figure
set(fig, 'CloseRequestFcn', @cb_close);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', eye(4));
if useheadshape
setappdata(fig, 'headshape', headshape);
end
if usetemplate
% FIXME interactive realigning to template electrodes is not yet supported
% this requires a consistent handling of channel selection etc.
setappdata(fig, 'template', template);
end
% add the GUI elements
cb_creategui(gca);
cb_redraw(gca);
rotate3d on
waitfor(fig);
% get the data from the figure that was left behind as global variable
tmp = norm;
clear global norm
norm = tmp;
clear tmp
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'manual')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% give the user instructions
disp('Use the mouse to click on the desired electrode positions');
disp('Afterwards you manually have to assign the electrode names to "elec.label"');
disp('Close the figure or press "q" when you are done');
% open a figure
figure;
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7);
lighting gouraud
material shiny
camlight
% rotate3d on
xyz = ft_select_point3d(headshape, 'multiple', true);
norm.chanpos = xyz;
for i=1:size(norm.chanpos,1)
norm.label{i,1} = sprintf('%d', i);
end
else
error('unknown method');
end
% apply the spatial transformation to all electrodes, and replace the
% electrode labels by their case-sensitive original values
switch cfg.method
case {'template', 'headshape'}
try
% convert the vector with fitted parameters into a 4x4 homogenous transformation
% apply the transformation to the original complete set of sensors
elec_realigned = ft_transform_sens(feval(cfg.warp, norm.m), elec_original);
catch
% the previous section will fail for nonlinear transformations
elec_realigned.label = elec_original.label;
elec_realigned.chanpos = warp_apply(norm.m, elec_original.chanpos, cfg.warp);
end
% remember the transformation
elec_realigned.(cfg.warp) = norm.m;
case {'fiducial', 'interactive'}
% the transformation is a 4x4 homogenous matrix
homogenous = norm.m;
% apply the transformation to the original complete set of sensors
elec_realigned = ft_transform_sens(homogenous, elec_original);
% remember the transformation
elec_realigned.homogenous = norm.m;
case 'manual'
% the positions are already assigned in correspondence with the mesh
elec_realigned = norm;
otherwise
error('unknown method');
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous elec_original
ft_postamble history elec_realigned
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% some simple SUBFUNCTIONs that facilitate 3D plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = my_plot3(xyz, varargin)
h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function h = my_text3(xyz, varargin)
h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function my_line3(xyzB, xyzE, varargin)
for i=1:size(xyzB,1)
line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to layout a moderately complex graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = layoutgui(fig, geometry, position, style, string, value, tag, callback)
horipos = geometry(1); % lower left corner of the GUI part in the figure
vertpos = geometry(2); % lower left corner of the GUI part in the figure
width = geometry(3); % width of the GUI part in the figure
height = geometry(4); % height of the GUI part in the figure
horidist = 0.05;
vertdist = 0.05;
options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle'
Nrow = size(position,1);
h = cell(Nrow,1);
for i=1:Nrow
if isempty(position{i})
continue;
end
position{i} = position{i} ./ sum(position{i});
Ncol = size(position{i},2);
ybeg = (Nrow-i )/Nrow + vertdist/2;
yend = (Nrow-i+1)/Nrow - vertdist/2;
for j=1:Ncol
xbeg = sum(position{i}(1:(j-1))) + horidist/2;
xend = sum(position{i}(1:(j ))) - horidist/2;
pos(1) = xbeg*width + horipos;
pos(2) = ybeg*height + vertpos;
pos(3) = (xend-xbeg)*width;
pos(4) = (yend-ybeg)*height;
h{i}{j} = uicontrol(fig, ...
options{:}, ...
'position', pos, ...
'style', style{i}{j}, ...
'string', string{i}{j}, ...
'tag', tag{i}{j}, ...
'value', value{i}{j}, ...
'callback', callback{i}{j} ...
);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_creategui(hObject, eventdata, handles)
% define the position of each GUI element
position = {
[2 1 1 1]
[2 1 1 1]
[2 1 1 1]
[1]
[1]
[1]
[1]
[1 1]
};
% define the style of each GUI element
style = {
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'pushbutton'}
{'pushbutton'}
{'toggle'}
{'toggle'}
{'text' 'edit'}
};
% define the descriptive string of each GUI element
string = {
{'rotate' 0 0 0}
{'translate' 0 0 0}
{'scale' 1 1 1}
{'redisplay'}
{'apply'}
{'toggle labels'}
{'toggle axes'}
{'opacity' 0.7}
};
% define the value of each GUI element
value = {
{[] [] [] []}
{[] [] [] []}
{[] [] [] []}
{[]}
{[]}
{0}
{0}
{[] []}
};
% define a tag for each GUI element
tag = {
{'' 'rx' 'ry' 'rz'}
{'' 'tx' 'ty' 'tz'}
{'' 'sx' 'sy' 'sz'}
{''}
{''}
{'toggle labels'}
{'toggle axes'}
{'' 'alpha'}
};
% define the callback function of each GUI element
callback = {
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{@cb_redraw}
{@cb_apply}
{@cb_redraw}
{@cb_redraw}
{[] @cb_redraw}
};
fig = get(hObject, 'parent');
layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_redraw(hObject, eventdata, handles)
fig = get(hObject, 'parent');
headshape = getappdata(fig, 'headshape');
elec = getappdata(fig, 'elec');
template = getappdata(fig, 'template');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_sens(H, elec);
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
if ~isempty(template)
disp('Plotting the template electrodes in blue');
if size(template.chanpos, 2)==2
hs = plot(template.chanpos(:,1), template.chanpos(:,2), 'b.', 'MarkerSize', 20);
else
hs = plot3(template.chanpos(:,1), template.chanpos(:,2), template.chanpos(:,3), 'b.', 'MarkerSize', 20);
end
end
if ~isempty(headshape)
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7);
lighting gouraud
material shiny
camlight
end
if isfield(elec, 'fid') && ~isempty(elec.fid.pnt)
disp('Plotting the fiducials in red');
ft_plot_sens(elec.fid,'style', 'r*');
end
if get(findobj(fig, 'tag', 'toggle axes'), 'value')
axis on
grid on
else
axis off
grid on
end
hold on
if get(findobj(fig, 'tag', 'toggle labels'), 'value')
ft_plot_sens(elec,'label', 'on');
else
ft_plot_sens(elec,'label', 'off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_apply(hObject, eventdata, handles)
fig = get(hObject, 'parent');
elec = getappdata(fig, 'elec');
transform = getappdata(fig, 'transform');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_headshape(H, elec);
transform = H * transform;
set(findobj(fig, 'tag', 'rx'), 'string', 0);
set(findobj(fig, 'tag', 'ry'), 'string', 0);
set(findobj(fig, 'tag', 'rz'), 'string', 0);
set(findobj(fig, 'tag', 'tx'), 'string', 0);
set(findobj(fig, 'tag', 'ty'), 'string', 0);
set(findobj(fig, 'tag', 'tz'), 'string', 0);
set(findobj(fig, 'tag', 'sx'), 'string', 1);
set(findobj(fig, 'tag', 'sy'), 'string', 1);
set(findobj(fig, 'tag', 'sz'), 'string', 1);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', transform);
cb_redraw(hObject);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_close(hObject, eventdata, handles)
% make the current transformation permanent and subsequently allow deleting the figure
cb_apply(gca);
% get the updated electrode from the figure
fig = hObject;
% hmmm, this is ugly
global norm
norm = getappdata(fig, 'elec');
norm.m = getappdata(fig, 'transform');
set(fig, 'CloseRequestFcn', @delete);
delete(fig);
|
github
|
philippboehmsturm/antx-master
|
ft_databrowser.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_databrowser.m
| 74,844 |
utf_8
|
5bf9df5cccb44bd8eeead55f5453f237
|
function [cfg] = ft_databrowser(cfg, data)
% FT_DATABROWSER can be used for visual inspection of data. Artifacts that
% were detected by artifact functions (see FT_ARTIFACT_xxx functions where
% xxx is the type of artifact) are marked. Additionally data pieces can be
% marked and unmarked as artifact by manual selection. The output cfg
% contains the updated specification of the artifacts. When visually selection
% data, a right-click will bring up a context-menu containing functions to be
% executed on the selected data. You can use your own function using cfg.selfun
% and cfg.selcfg. You can use multiple functions by giving the names/cfgs as a
% cell-array.
%
% Use as
% cfg = ft_databrowser(cfg)
% where the configuration structure contains the reference to the dataset
% on your hard disk (see below), or use as
% cfg = ft_databrowser(cfg, data)
% where the input data is a structure as obtained from FT_PREPROCESSING or
% from FT_COMPONENTANALYSIS.
%
% If you want to browse data that is on disk, you have to specify
% cfg.dataset = string with the filename
% Instead of specifying the dataset, you can also explicitely specify the
% name of the file containing the header information and the name of the
% file containing the data, using
% cfg.datafile = string with the filename
% cfg.headerfile = string with the filename
%
% The following configuration options are supported:
% cfg.ylim = vertical scaling, can be 'maxmin', 'maxabs' or [ymin ymax] (default = 'maxabs')
% cfg.zlim = color scaling to apply to component topographies, 'minmax', 'maxabs' (default = 'maxmin')
% cfg.blocksize = duration in seconds for cutting the data up
% cfg.trl = structure that defines the data segments of interest, only applicable for trial-based data
% cfg.continuous = 'yes' or 'no' whether the data should be interpreted as continuous or trial-based
% cfg.channel = cell-array with channel labels, see FT_CHANNELSELECTION
% cfg.plotlabels = 'yes' (default), 'no', 'some'; whether
% to plot channel labels in vertical viewmode ('some' plots one in every ten
% labels; useful when plotting a large number of channels at a time)
% cfg.ploteventlabels = 'type=value', 'colorvalue' (default = 'type=value');
% cfg.viewmode = string, 'butterfly', 'vertical', 'component' for visualizing components e.g. from an ICA (default is 'butterfly')
% cfg.artfctdef.xxx.artifact = Nx2 matrix with artifact segments see FT_ARTIFACT_xxx functions
% cfg.selectfeature = string, name of feature to be selected/added (default = 'visual')
% cfg.selectmode = 'markartifact', 'markpeakevent', 'marktroughevent' (default = 'markartifact')
% cfg.colorgroups = 'sequential' 'allblack' 'labelcharx' (x = xth character in label), 'chantype' or
% vector with length(data/hdr.label) defining groups (default = 'sequential')
% cfg.channelcolormap = COLORMAP (default = customized lines map with 15 colors)
% cfg.selfun = string, name of function which is evaluated using the right-click context menu
% The selected data and cfg.selcfg are passed on to this function.
% cfg.selcfg = configuration options for function in cfg.selfun
% cfg.eegscale = number, scaling to apply to the EEG channels prior to display
% cfg.eogscale = number, scaling to apply to the EOG channels prior to display
% cfg.ecgscale = number, scaling to apply to the ECG channels prior to display
% cfg.emgscale = number, scaling to apply to the EMG channels prior to display
% cfg.megscale = number, scaling to apply to the MEG channels prior to display
% cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor)
% cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor)
% cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan
% cfg.mychan = Nx1 cell-array with selection of channels
% cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel
% cfg.compscale = string, 'global' or 'local', defines whether the colormap for the topographic scaling is
% applied per topography or on all visualized components (default 'global')
%
% In case of component viewmode, a layout is required. If no layout is
% give, an attempt is made to construct one from the sensor definition.
% EEG or MEG sensor positions can be present in the data or can be specified as
% cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS
% cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS
% cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS
% cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS
%
% The scaling to the EEG, EOG, ECG, EMG and MEG channels is optional and
% can be used to bring the absolute numbers of the different channel types
% in the same range (e.g. fT and uV). The channel types are determined from
% the input data using FT_CHANNELSELECTION.
%
% The "artifact" field in the output cfg is a Nx2 matrix comparable to the
% "trl" matrix of FT_DEFINETRIAL. The first column of which specifying the
% beginsamples of an artifact period, the second column contains the
% endsamples of the artifactperiods.
%
% NOTE for debugging: in case the databrowser crashes, use delete(gcf) to
% kill the figure.
%
% See also FT_PREPROCESSING, FT_REJECTARTIFACT, FT_ARTIFACT_EOG,
% FT_ARTIFACT_MUSCLE, FT_ARTIFACT_JUMP, FT_ARTIFACT_MANUAL,
% FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG,
% FT_COMPONENTANALYSIS
% Copyright (C) 2009-2011, Robert Oostenveld, Ingrid Nieuwenhuis
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_databrowser.m 7188 2012-12-13 21:26:34Z roboos $
% Undocumented options
%
% FIXME these should be removed
% FIXME document these
% cfg.preproc
% cfg.channelcolormap
% cfg.colorgroups
revision = '$Id: ft_databrowser.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
hasdata = (nargin>1);
hascomp = hasdata && ft_datatype(data, 'comp');
% for backward compatibility
cfg = ft_checkconfig(cfg, 'unused', {'comps', 'inputfile', 'outputfile'});
cfg = ft_checkconfig(cfg, 'renamed', {'zscale', 'ylim'});
cfg = ft_checkconfig(cfg, 'renamedval', {'ylim', 'auto', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'selectmode', 'mark', 'markartifact'});
% ensure that the preproc specific options are located in the cfg.preproc substructure
cfg = ft_checkconfig(cfg, 'createsubcfg', {'preproc'});
% set the defaults
if ~isfield(cfg, 'ylim'), cfg.ylim = 'maxabs'; end
if ~isfield(cfg, 'artfctdef'), cfg.artfctdef = struct; end
if ~isfield(cfg, 'selectfeature'), cfg.selectfeature = 'visual'; end % string or cell-array
if ~isfield(cfg, 'selectmode'), cfg.selectmode = 'markartifact'; end
if ~isfield(cfg, 'blocksize'), cfg.blocksize = []; end % now used for both continuous and non-continuous data, defaulting done below
if ~isfield(cfg, 'preproc'), cfg.preproc = []; end % see preproc for options
if ~isfield(cfg, 'selfun'), cfg.selfun = []; end % default functions: 'simpleFFT','multiplotER','topoplotER','topoplotVAR','movieplotER'
if ~isfield(cfg, 'selcfg'), cfg.selcfg = []; end % defaulting done below, requires layouts/etc to be processed
if ~isfield(cfg, 'colorgroups'), cfg.colorgroups = 'sequential'; end
if ~isfield(cfg, 'channelcolormap'), cfg.channelcolormap = [0.75 0 0;0 0 1;0 1 0;0.44 0.19 0.63;0 0.13 0.38;0.5 0.5 0.5;1 0.75 0;1 0 0;0.89 0.42 0.04;0.85 0.59 0.58;0.57 0.82 0.31;0 0.69 0.94;1 0 0.4;0 0.69 0.31;0 0.44 0.75]; end
if ~isfield(cfg, 'eegscale'), cfg.eegscale = []; end
if ~isfield(cfg, 'eogscale'), cfg.eogscale = []; end
if ~isfield(cfg, 'ecgscale'), cfg.ecgscale = []; end
if ~isfield(cfg, 'emgscale'), cfg.emgscale = []; end
if ~isfield(cfg, 'megscale'), cfg.megscale = []; end
if ~isfield(cfg, 'magscale'), cfg.magscale = []; end
if ~isfield(cfg, 'gradscale'), cfg.gradscale = []; end
if ~isfield(cfg, 'chanscale'), cfg.chanscale = []; end
if ~isfield(cfg, 'mychanscale'), cfg.mychanscale = []; end
if ~isfield(cfg, 'layout'), cfg.layout = []; end
if ~isfield(cfg, 'plotlabels'), cfg.plotlabels = 'yes'; end
if ~isfield(cfg, 'event'), cfg.event = []; end % this only exists for backward compatibility and should not be documented
if ~isfield(cfg, 'continuous'), cfg.continuous = []; end % the default is set further down in the code, conditional on the input data
if ~isfield(cfg, 'ploteventlabels'), cfg.ploteventlabels = 'type=value'; end
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.compscale = ft_getopt(cfg, 'compscale', 'global');
if ~isfield(cfg, 'viewmode')
% butterfly, vertical, component
if hascomp
cfg.viewmode = 'component';
else
cfg.viewmode = 'butterfly';
end
end
if ~isempty(cfg.chanscale)
if ~isfield(cfg,'channel')
warning('ignoring cfg.chanscale; this should only be used when an explicit channel selection is being made');
cfg.chanscale = [];
elseif numel(cfg.channel) ~= numel(cfg.chanscale)
error('cfg.chanscale should have the same number of elements as cfg.channel');
end
% make sure chanscale is a column vector, not a row vector
if size(cfg.chanscale,2) > size(cfg.chanscale,1)
cfg.chanscale = cfg.chanscale';
end
end
if ~isempty(cfg.mychanscale) && ~isfield(cfg,'mychan')
warning('ignoring cfg.mychanscale; no channels specified in cfg.mychan');
cfg.mychanscale = [];
end
if ~isfield(cfg, 'channel'),
if hascomp
if size(data.topo,2)>9
cfg.channel = 1:10;
else
cfg.channel = 1:size(data.topo,2);
end
else
cfg.channel = 'all';
end
end
if strcmp(cfg.viewmode, 'component')
% read or create the layout that will be used for the topoplots
tmpcfg = [];
tmpcfg.layout = cfg.layout;
if isempty(cfg.layout)
warning('No layout specified - will try to construct one using sensor positions');
if ft_datatype(data, 'meg')
tmpcfg.grad = ft_fetch_sens(cfg, data);
elseif ft_datatype(data, 'eeg')
tmpcfg.elec = ft_fetch_sens(cfg, data);
else
error('cannot infer sensor type');
end
end
cfg.layout = ft_prepare_layout(tmpcfg);
elseif ~isempty(cfg.layout)
tmpcfg = [];
tmpcfg.layout = cfg.layout;
cfg.layout = ft_prepare_layout(tmpcfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set the defaults and do some preparation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if hasdata
% save whether data came from a timelock structure
istimelock = strcmp(ft_datatype(data),'timelock');
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', {'raw', 'comp'}, 'feedback', 'yes', 'hassampleinfo', 'yes');
% fetch the header from the data structure in memory
hdr = ft_fetch_header(data);
if isfield(data, 'cfg') && ~isempty(ft_findcfg(data.cfg, 'origfs'))
% don't use the events in case the data has been resampled
warning('the data has been resampled, not showing the events');
event = [];
elseif ~isempty(cfg.event)
% use the events that the user passed in the configuration
event = cfg.event;
else
% fetch the events from the data structure in memory
event = ft_fetch_event(data);
end
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chansel = match_str(data.label, cfg.channel);
Nchans = length(chansel);
if isempty(cfg.continuous)
if numel(data.trial) == 1 && ~istimelock
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
else
if strcmp(cfg.continuous, 'yes') && (numel(data.trial) > 1)
warning('interpreting trial-based data as continous, time-axis is no longer appropriate. t(0) now corresponds to the first sample of the first trial, and t(end) to the last sample of the last trial')
end
end
% this is how the input data is segmented
trlorg = zeros(numel(data.trial), 3);
trlorg(:,[1 2]) = data.sampleinfo;
% recreate offset vector (databrowser depends on this for visualisation)
for ntrl = 1:numel(data.trial)
trlorg(ntrl,3) = time2offset(data.time{ntrl}, data.fsample);
end
Ntrials = size(trlorg, 1);
else
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'dataset2files', {'yes'});
cfg = ft_checkconfig(cfg, 'required', {'headerfile', 'datafile'});
cfg = ft_checkconfig(cfg, 'renamed', {'datatype', 'continuous'});
cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'});
% read the header from file
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
if isempty(cfg.continuous)
if hdr.nTrials==1
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
end
if ~isempty(cfg.event)
% use the events that the user passed in the configuration
event = cfg.event;
else
% read the events from file
event = ft_read_event(cfg.dataset);
end
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chansel = match_str(hdr.label, cfg.channel);
Nchans = length(chansel);
if strcmp(cfg.continuous, 'yes')
Ntrials = 1;
else
Ntrials = hdr.nTrials;
end
% FIXME in case of continuous=yes the trl should be [1 hdr.nSamples*nTrials 0]
% and a scrollbar should be used
% construct trl-matrix for data from file on disk
trlorg = zeros(Ntrials,3);
if strcmp(cfg.continuous, 'yes')
trlorg(1, [1 2]) = [1 hdr.nSamples*hdr.nTrials];
else
for k = 1:Ntrials
trlorg(k,[1 2]) = [1 hdr.nSamples] + [hdr.nSamples hdr.nSamples] .* (k-1);
end
end
end % if hasdata
if strcmp(cfg.continuous,'no') && isempty(cfg.blocksize)
cfg.blocksize = (trlorg(1,2) - trlorg(1,1)+1) ./ hdr.Fs;
elseif strcmp(cfg.continuous,'yes') && isempty(cfg.blocksize)
cfg.blocksize = 1;
end
% FIXME make a check for the consistency of cfg.continous, cfg.blocksize, cfg.trl and the data header
if Nchans == 0
error('no channels to display');
end
if Ntrials == 0
error('no trials to display');
end
if ischar(cfg.selectfeature)
% ensure that it is a cell array
cfg.selectfeature = {cfg.selectfeature};
end
if ~isempty(cfg.selectfeature)
for i=1:length(cfg.selectfeature)
if ~isfield(cfg.artfctdef, cfg.selectfeature{i})
cfg.artfctdef.(cfg.selectfeature{i}) = [];
cfg.artfctdef.(cfg.selectfeature{i}).artifact = zeros(0,2);
end
end
end
% determine the vertical scaling
if ischar(cfg.ylim)
if hasdata
% the first trial is used to determine the vertical scaling
dat = data.trial{1}(chansel,:);
else
% one second of data is read from file to determine the vertical scaling
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', 1, 'endsample', round(hdr.Fs), 'chanindx', chansel, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat);
end % if hasdata
minval = min(dat(:));
maxval = max(dat(:));
switch cfg.ylim
case 'maxabs'
maxabs = max(abs([minval maxval]));
scalefac = 10^(fix(log10(maxabs)));
maxabs = (round(maxabs / scalefac * 100) / 100) * scalefac;
cfg.ylim = [-maxabs maxabs];
case 'maxmin'
cfg.ylim = [minval maxval];
otherwise
error('unsupported value for cfg.ylim');
end % switch ylim
% zoom in a bit when viemode is vertical
if strcmp(cfg.viewmode,'vertical')
cfg.ylim = cfg.ylim/10;
end
else
if (numel(cfg.ylim) ~= 2) || ~isnumeric(cfg.ylim)
error('cfg.ylim needs to be a 1x2 vector [ymin ymax], describing the upper and lower limits')
end
end
% determine coloring of channels
if hasdata
labels_all = data.label;
else
labels_all= hdr.label;
end
if size(cfg.channelcolormap,2) ~= 3
error('cfg.channelcolormap is not valid, size should be Nx3')
end
if isnumeric(cfg.colorgroups)
% groups defined by user
if length(labels_all) ~= length(cfg.colorgroups)
error('length(cfg.colorgroups) should be length(data/hdr.label)')
end
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups, 'allblack')
chancolors = zeros(length(labels_all),3);
elseif strcmp(cfg.colorgroups, 'chantype')
type = ft_chantype(labels_all);
[tmp1 tmp2 cfg.colorgroups] = unique(type);
fprintf('%3d colorgroups were identified\n',length(tmp1))
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups(1:9), 'labelchar')
% groups determined by xth letter of label
labelchar_num = str2double(cfg.colorgroups(10));
vec_letters = num2str(zeros(length(labels_all),1));
for iChan = 1:length(labels_all)
vec_letters(iChan) = labels_all{iChan}(labelchar_num);
end
[tmp1 tmp2 cfg.colorgroups] = unique(vec_letters);
fprintf('%3d colorgroups were identified\n',length(tmp1))
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups, 'sequential')
% no grouping
chancolors = lines(length(labels_all));
else
error('do not understand cfg.colorgroups')
end
% collect the artifacts that have been detected from cfg.artfctdef.xxx.artifact
artlabel = fieldnames(cfg.artfctdef);
sel = zeros(size(artlabel));
artifact = cell(size(artlabel));
for i=1:length(artlabel)
sel(i) = isfield(cfg.artfctdef.(artlabel{i}), 'artifact');
if sel(i)
artifact{i} = cfg.artfctdef.(artlabel{i}).artifact;
fprintf('detected %3d %s artifacts\n', size(artifact{i}, 1), artlabel{i});
end
end
% get the subset of the artfctdef fields that seem to contain artifacts
artifact = artifact(sel==1);
artlabel = artlabel(sel==1);
if length(artlabel) > 9
error('only up to 9 artifacts groups supported')
end
% make artdata representing all artifacts in a "raw data" format
datendsample = max(trlorg(:,2));
artdata = [];
artdata.trial{1} = convert_event(artifact, 'boolvec', 'endsample', datendsample); % every artifact is a "channel"
artdata.time{1} = offset2time(0, hdr.Fs, datendsample);
artdata.label = artlabel;
artdata.fsample = hdr.Fs;
artdata.cfg.trl = [1 datendsample 0];
% determine amount of unique event types (for cfg.ploteventlabels)
if ~isempty(event) && isstruct(event)
eventtypes = unique({event.type});
else
eventtypes = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set up default defselfuns
% use two cfg sections
% cfg.selfun - labels that are presented in rightclick menu, and is appended using ft_getuserfun(..., 'browse') later on to create a function handle
% cfg.selcfg - cfgs for functions to be executed
defselfun = [];
defselcfg = [];
% simplefft
defselfun{1} = 'simpleFFT';
tmpcfg = [];
tmpcfg.chancolors = chancolors;
defselcfg{1} = tmpcfg;
% multiplotER
defselfun{2} = 'multiplotER';
tmpcfg = [];
tmpcfg.layout = cfg.layout;
defselcfg{2} = tmpcfg;
% topoplotER
defselfun{3} = 'topoplotER';
tmpcfg = [];
tmpcfg.layout = cfg.layout;
defselcfg{3} = tmpcfg;
% topoplotVAR
defselfun{4} = 'topoplotVAR';
tmpcfg = [];
tmpcfg.layout = cfg.layout;
defselcfg{4} = tmpcfg;
% movieplotER
defselfun{5} = 'movieplotER';
tmpcfg = [];
tmpcfg.layout = cfg.layout;
tmpcfg.interactive = 'yes';
defselcfg{5} = tmpcfg;
% add defselfuns to user-specified defselfuns
if ~iscell(cfg.selfun) && ~isempty(cfg.selfun)
cfg.selfun = {cfg.selfun};
cfg.selfun = [cfg.selfun defselfun];
% do the same for the cfgs
cfg.selcfg = {cfg.selcfg}; % assume the cfg isnt a cell
cfg.selcfg = [cfg.selcfg defselcfg];
else
cfg.selfun = defselfun;
cfg.selcfg = defselcfg;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set up the data structures used in the GUI
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% opt represents the global data/settings, it should contain
% - the original data, epoched or continuous
% - the artifacts represented as continuous data
% - the redraw_cb settings
% - the preproc settings
% - the select_range_cb settings (also used in keyboard_cb)
% these elements are stored inside the figure so that the callback routines can modify them
opt = [];
if hasdata
opt.orgdata = data;
else
opt.orgdata = []; % this means that it will look in cfg.dataset
end
if strcmp(cfg.continuous, 'yes')
opt.trialviewtype = 'segment';
else
opt.trialviewtype = 'trial';
end
opt.artdata = artdata;
opt.hdr = hdr;
opt.event = event;
opt.trlop = 1; % the active trial being displayed
opt.ftsel = find(strcmp(artlabel,cfg.selectfeature)); % current artifact/feature being selected
opt.trlorg = trlorg;
opt.fsample = hdr.Fs;
opt.artcolors = [0.9686 0.7608 0.7686; 0.7529 0.7098 0.9647; 0.7373 0.9725 0.6824;0.8118 0.8118 0.8118; 0.9725 0.6745 0.4784; 0.9765 0.9176 0.5686; 0.6863 1 1; 1 0.6863 1; 0 1 0.6000];
opt.chancolors = chancolors;
opt.cleanup = false; % this is needed for a corrent handling if the figure is closed (either in the corner or by "q")
opt.chanindx = []; % this is used to check whether the component topographies need to be redrawn
opt.eventtypes = eventtypes;
opt.eventtypescolors = [0 0 0; 1 0 0; 0 0 1; 0 1 0; 1 0 1; 0.5 0.5 0.5; 0 1 1; 1 1 0];
opt.eventtypecolorlabels = {'black', 'red', 'blue', 'green', 'cyan', 'grey', 'light blue', 'yellow'};
opt.nanpaddata = []; % this is used to allow horizontal scaling to be constant (when looking at last segment continous data, or when looking at segmented/zoomed-out non-continous data)
opt.trllock = []; % this is used when zooming into trial based data
% save original layout when viewmode = component
if strcmp(cfg.viewmode,'component')
opt.layorg = cfg.layout;
end
% determine labelling of channels
if strcmp(cfg.plotlabels, 'yes')
opt.plotLabelFlag = 1;
elseif strcmp(cfg.plotlabels, 'some')
opt.plotLabelFlag = 2;
else
opt.plotLabelFlag = 0;
end
h = figure;
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
% set the figure window title
funcname = mfilename();
if nargin < 2
if isfield(cfg, 'dataset')
dataname = cfg.dataset;
elseif isfield(cfg, 'datafile')
dataname = cfg.datafile;
else
dataname = [];
end
else
dataname = inputname(2);
end
set(gcf, 'Name', sprintf('%d: %s: %s', gcf, funcname, join_str(', ',dataname)));
set(gcf, 'NumberTitle', 'off');
% set zoom option to on
% zoom(h,'on')
% set(zoom(h),'actionPostCallback',@zoom_drawlabels_cb)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set up the figure and callbacks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
set(h, 'KeyPressFcn', @keyboard_cb);
set(h, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'contextmenu', cfg.selfun, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonDownFcn'});
set(h, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'contextmenu', cfg.selfun, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonUpFcn'});
set(h, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'contextmenu', cfg.selfun, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonMotionFcn'});
% make the user interface elements for the data view
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', opt.trialviewtype, 'userdata', 't')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow')
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel','userdata', 'c')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'uparrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'downarrow')
uicontrol('tag', 'group1a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'horizontal', 'userdata', 'h')
uicontrol('tag', 'group2a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+leftarrow')
uicontrol('tag', 'group2a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+rightarrow')
ft_uilayout(h, 'tag', 'group1a', 'visible', 'on', 'retag', 'group1');
ft_uilayout(h, 'tag', 'group2a', 'visible', 'on', 'retag', 'group2');
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'vertical', 'userdata', 'v')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+downarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+uparrow')
% legend artifacts/features
for iArt = 1:length(artlabel)
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', artlabel{iArt}, 'userdata', num2str(iArt), 'position', [0.91, 0.9 - ((iArt-1)*0.09), 0.08, 0.04], 'backgroundcolor', opt.artcolors(iArt,:))
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', ['shift+' num2str(iArt)], 'position', [0.91, 0.855 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcolors(iArt,:))
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', ['control+' num2str(iArt)], 'position', [0.96, 0.855 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcolors(iArt,:))
end
if strcmp(cfg.viewmode, 'butterfly')
% button to find label of nearest channel to datapoint
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'identify', 'userdata', 'i', 'position', [0.91, 0.1, 0.08, 0.05], 'backgroundcolor', [1 1 1])
end
% 'edit preproc'-button
uicontrol('tag', 'preproccfg', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string','preproc cfg','position', [0.91, 0.55 - ((iArt-1)*0.09), 0.08, 0.04],'callback',@preproc_cfg1_cb)
ft_uilayout(h, 'tag', 'group1', 'width', 0.10, 'height', 0.05);
ft_uilayout(h, 'tag', 'group2', 'width', 0.05, 'height', 0.05);
ft_uilayout(h, 'tag', 'group1', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group2', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group3', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group1', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'group2', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0);
definetrial_cb(h);
redraw_cb(h);
% %% Scrollbar
%
% % set initial scrollbar value
% dx = maxtime;
%
% % set scrollbar position
% fig_pos=get(gca,'position');
% scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02];
%
% % define callback
% S=['set(gca,''xlim'',get(gcbo,''value'')+[ ' num2str(mintime) ',' num2str(maxtime) '])'];
%
% % Creating Uicontrol
% s=uicontrol('style','slider',...
% 'units','normalized','position',scroll_pos,...
% 'callback',S,'min',0,'max',0, ...
% 'visible', 'off'); %'value', xmin
% set initial scrollbar value
% dx = maxtime;
%
% % set scrollbar position
% fig_pos=get(gca,'position');
% scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02];
%
% % define callback
% S=['set(gca,''xlim'',get(gcbo,''value'')+[ ' num2str(mintime) ',' num2str(maxtime) '])'];
%
% % Creating Uicontrol
% s=uicontrol('style','slider',...
% 'units','normalized','position',scroll_pos,...
% 'callback',S,'min',0,'max',0, ...
% 'visible', 'off'); %'value', xmin
%initialize postion of plot
% set(gca,'xlim',[xmin xmin+dx]);
if nargout
% wait until the user interface is closed, get the user data with the updated artifact details
set(h, 'CloseRequestFcn', @cleanup_cb);
while ishandle(h)
uiwait(h);
opt = getappdata(h, 'opt');
if opt.cleanup
delete(h);
end
end
% add the updated artifact definitions to the output cfg
for i=1:length(opt.artdata.label)
cfg.artfctdef.(opt.artdata.label{i}).artifact = convert_event(opt.artdata.trial{1}(i,:), 'artifact');
end
% add the updated preproc to the output
try
browsecfg = getappdata(h, 'cfg');
cfg.preproc = browsecfg.preproc;
end
% add the update event to the output cfg
cfg.event = opt.event;
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
end % if nargout
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanup_cb(h, eventdata)
opt = getappdata(h, 'opt');
opt.cleanup = true;
setappdata(h, 'opt', opt);
uiresume
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function definetrial_cb(h, eventdata)
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
if strcmp(cfg.continuous, 'no')
% when zooming in, lock the trial! one can only go to the next trial when horizontal scaling doesn't segment the data - from ft-meeting: this might be relaxed later on - roevdmei
if isempty(opt.trllock)
opt.trllock = opt.trlop;
end
locktrllen = ((opt.trlorg(opt.trllock,2)-opt.trlorg(opt.trllock,1)+1) ./ opt.fsample);
% if cfg.blocksize is close to the length of the locked trial, set it to that
if (abs(locktrllen-cfg.blocksize) / locktrllen) < 0.1
cfg.blocksize = locktrllen;
end
%%%%%%%%%
% trial is locked, change subdivision of trial
if cfg.blocksize < locktrllen
% lock the trial if it wasn't locked (and thus trlop refers to the actual trial)
if isempty(opt.trllock)
opt.trllock = trlop;
end
% save current position if already
if isfield(opt, 'trlvis')
thissegbeg = opt.trlvis(opt.trlop,1);
end
datbegsample = min(opt.trlorg(opt.trllock,1));
datendsample = max(opt.trlorg(opt.trllock,2));
smpperseg = round(opt.fsample * cfg.blocksize);
begsamples = datbegsample:smpperseg:datendsample;
endsamples = datbegsample+smpperseg-1:smpperseg:datendsample;
offset = (((1:numel(begsamples))-1)*smpperseg) + opt.trlorg(opt.trllock,3);
if numel(endsamples)<numel(begsamples)
endsamples(end+1) = datendsample;
end
trlvis = [];
trlvis(:,1) = begsamples';
trlvis(:,2) = endsamples';
trlvis(:,3) = offset;
% determine length of each trial, and determine the offset with the current requested zoom-level
trllen = (trlvis(:,2) - trlvis(:,1)+1);
sizediff = smpperseg - trllen;
opt.nanpaddata = sizediff;
if isfield(opt, 'trlvis')
% update the current trial counter and try to keep the current sample the same
opt.trlop = nearest(begsamples, thissegbeg);
end
% update trialviewtype
opt.trialviewtype = 'trialsegment';
% update button
set(findobj(get(h,'children'),'string','trial'),'string','segment');
%%%%%%%%%
%%%%%%%%%
% trial is not locked, go to original trial division and zoom out
elseif cfg.blocksize >= locktrllen
trlvis = opt.trlorg;
% set current trlop to locked trial if it was locked before
if ~isempty(opt.trllock)
opt.trlop = opt.trllock;
end
smpperseg = round(opt.fsample * cfg.blocksize);
% determine length of each trial, and determine the offset with the current requested zoom-level
trllen = (trlvis(:,2) - trlvis(:,1)+1);
sizediff = smpperseg - trllen;
opt.nanpaddata = sizediff;
% update trialviewtype
opt.trialviewtype = 'trial';
% update button
set(findobj(get(h,'children'),'string','trialsegment'),'string',opt.trialviewtype);
% release trial lock
opt.trllock = [];
%%%%%%%%%
end
% save trlvis
opt.trlvis = trlvis;
else
% construct a trial definition for visualisation
if isfield(opt, 'trlvis') % if present, remember where we were
thistrlbeg = opt.trlvis(opt.trlop,1);
end
% look at cfg.blocksize and make opt.trl accordingly
datbegsample = min(opt.trlorg(:,1));
datendsample = max(opt.trlorg(:,2));
smpperseg = round(opt.fsample * cfg.blocksize);
begsamples = datbegsample:smpperseg:datendsample;
endsamples = datbegsample+smpperseg-1:smpperseg:datendsample;
if numel(endsamples)<numel(begsamples)
endsamples(end+1) = datendsample;
end
trlvis = [];
trlvis(:,1) = begsamples';
trlvis(:,2) = endsamples';
% compute the offset. In case if opt.trlorg has multiple trials, the first sample is t=0, otherwise use the offset in opt.trlorg
if size(opt.trlorg,1)==1
offset = begsamples - repmat(begsamples(1),[1 numel(begsamples)]); % offset for all segments compared to the first
offset = offset + opt.trlorg(1,3);
trlvis(:,3) = offset;
else
offset = begsamples - repmat(begsamples(1),[1 numel(begsamples)]);
trlvis(:,3) = offset;
end
if isfield(opt, 'trlvis')
% update the current trial counter and try to keep the current sample the same
% opt.trlop = nearest(round((begsamples+endsamples)/2), thissample);
opt.trlop = nearest(begsamples, thistrlbeg);
end
opt.trlvis = trlvis;
% NaN-padding when horizontal scaling is bigger than the data
% two possible situations, 1) zoomed out so far that all data is one segment, or 2) multiple segments but last segment is smaller than the rest
sizediff = smpperseg-(endsamples-begsamples+1);
opt.nanpaddata = sizediff;
end % if continuous
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function help_cb(h, eventdata)
fprintf('------------------------------------------------------------------------------------\n')
fprintf('You can use the following keyboard buttons in the databrowser\n')
fprintf('1-9 : select artifact type 1-9\n');
fprintf('shift 1-9 : select previous artifact of type 1-9\n');
fprintf(' (does not work with numpad keys)\n');
fprintf('control 1-9 : select next artifact of type 1-9\n');
fprintf('alt 1-9 : select next artifact of type 1-9\n');
fprintf('arrow-left : previous trial\n');
fprintf('arrow-right : next trial\n');
fprintf('shift arrow-up : increase vertical scaling\n');
fprintf('shift arrow-down : decrease vertical scaling\n');
fprintf('shift arrow-left : increase horizontal scaling\n');
fprintf('shift arrow-down : decrease horizontal scaling\n');
fprintf('s : toggles between cfg.selectmode options\n');
fprintf('q : quit\n');
fprintf('------------------------------------------------------------------------------------\n')
fprintf('\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_range_cb(h, range, cmenulab) %range 1X4 in sec relative to current trial
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
% the range should be in the displayed box
range(1) = max(opt.hpos-opt.width/2, range(1));
range(2) = max(opt.hpos-opt.width/2, range(2));
range(1) = min(opt.hpos+opt.width/2, range(1));
range(2) = min(opt.hpos+opt.width/2, range(2));
range = (range-(opt.hpos-opt.width/2)) / opt.width; % left side of the box becomes 0, right side becomes 1
range = range * (opt.hlim(2) - opt.hlim(1)) + opt.hlim(1); % 0 becomes hlim(1), 1 becomes hlim(2)
begsample = opt.trlvis(opt.trlop,1);
endsample = opt.trlvis(opt.trlop,2);
offset = opt.trlvis(opt.trlop,3);
% determine the selection
begsel = round(range(1)*opt.fsample+begsample-offset-1);
endsel = round(range(2)*opt.fsample+begsample-offset);
% artifact selection is now always based on begsample/endsample/offset
% -roevdmei
% the selection should always be confined to the current trial
begsel = max(begsample, begsel);
endsel = min(endsample, endsel);
% mark or execute selfun
if isempty(cmenulab)
% the left button was clicked INSIDE a selected range, update the artifact definition or event
if strcmp(cfg.selectmode, 'markartifact')
% mark or unmark artifacts
artval = opt.artdata.trial{1}(opt.ftsel, begsel:endsel);
artval = any(artval,1);
if any(artval)
fprintf('there is overlap with the active artifact (%s), disabling this artifact\n',opt.artdata.label{opt.ftsel});
opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 0;
else
fprintf('there is no overlap with the active artifact (%s), marking this as a new artifact\n',opt.artdata.label{opt.ftsel});
opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 1;
end
% redraw only when marking (so the focus doesn't go back to the databrowser after calling selfuns
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h);
elseif strcmp(cfg.selectmode, 'markpeakevent') || strcmp(cfg.selectmode, 'marktroughevent')
%mark or unmark events, marking at peak/trough of window
if any(intersect(begsel:endsel, [opt.event.sample]))
fprintf('there is overlap with one or more event(s), disabling this/these event(s)\n');
ind_rem = intersect(begsel:endsel, [opt.event.sample]);
for iRemove = 1:length(ind_rem)
opt.event([opt.event.sample]==ind_rem(iRemove)) = [];
end
else
fprintf('there is no overlap with any event, adding an event to the peak/trough value\n');
% check if only 1 chan, other wise not clear max in which channel. %
% ingnie: would be cool to add the option to select the channel when multiple channels
if size(opt.curdat.trial{1},1) > 1
error('cfg.selectmode = ''markpeakevent'' and ''marktroughevent'' only supported with 1 channel in the data')
end
if strcmp(cfg.selectmode, 'markpeakevent')
[dum ind_minmax] = max(opt.curdat.trial{1}(begsel-begsample+1:endsel-begsample+1));
val = 'peak';
elseif strcmp(cfg.selectmode, 'marktroughevent')
[dum ind_minmax] = min(opt.curdat.trial{1}(begsel-begsample+1:endsel-begsample+1));
val = 'trough';
end
samp_minmax = begsel + ind_minmax - 1;
event_new.type = 'ft_databrowser_manual';
event_new.sample = samp_minmax;
event_new.value = val;
event_new.duration = 1;
event_new.offset = 0;
% add new event to end opt.event
% check if events are in order now
if min(diff([opt.event.sample]))>0
% add new event in line with old ones
nearest_event = nearest([opt.event.sample], samp_minmax);
if opt.event(nearest_event).sample > samp_minmax
%place new event before nearest
ind_event_new = nearest_event;
else
%place new event after nearest
ind_event_new = nearest_event +1;
end
event_lastpart = opt.event(ind_event_new:end);
opt.event(ind_event_new) = event_new;
opt.event(ind_event_new+1:end+1) = event_lastpart;
else
%just add to end
opt.event(end+1) = event_new;
end
clear event_new ind_event_new event_lastpart val dum ind_minmax
end
% redraw only when marking (so the focus doesn't go back to the databrowser after calling selfuns
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h);
end
else
% the right button was used to activate the context menu and the user made a selection from that menu
% execute the corresponding function
% get index into cfgs
selfunind = strcmp(cfg.selfun, cmenulab);
% cut out the requested data segment
seldata.label = opt.curdat.label;
seldata.time{1} = offset2time(offset+begsel-begsample, opt.fsample, endsel-begsel+1);
seldata.trial{1} = ft_fetch_data(opt.curdat, 'begsample', begsel, 'endsample', endsel);
seldata.fsample = opt.fsample;
seldata.cfg.trl = [begsel endsel offset];
% prepare input
funhandle = ft_getuserfun(cmenulab,'browse');
funcfg = cfg.selcfg{selfunind};
% get windowname and give as input (can be used for the other functions as well, not implemented yet)
if ~strcmp(opt.trialviewtype,'trialsegment')
str = sprintf('%s %d/%d, time from %g to %g s', opt.trialviewtype, opt.trlop, size(opt.trlvis,1), seldata.time{1}(1), seldata.time{1}(end));
else
str = sprintf('trial %d/%d: segment: %d/%d , time from %g to %g s', opt.trllock, size(opt.trlorg,1), opt.trlop, size(opt.trlvis,1), seldata.time{1}(1), seldata.time{1}(end));
end
funcfg.figurename = [cmenulab ': ' str];
feval(funhandle, funcfg, seldata);
end
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function preproc_cfg1_cb(h,eventdata)
parent = get(h,'parent');
cfg = getappdata(parent, 'cfg');
% parse cfg.preproc
if ~isempty(cfg.preproc)
tmpcfg = cfg.preproc;
cfg = [];
cfg.preproc = tmpcfg;
code = printstruct('cfg', cfg);
else
code = [];
end
% add descriptive lines
sep = sprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
descrip = sprintf('%% Add/change cfg options for on-the-fly preprocessing\n%% Use as cfg.preproc.xxx\n');
code = [sep descrip sep code];
% make figure displaying the edit box
pph = figure;
axis off
% add save button
uicontrol('tag', 'preproccfg_l2', 'parent', pph, 'units', 'normalized', 'style', 'pushbutton', 'string','save and close','position', [0.81, 0.6 , 0.18, 0.10],'callback',@preproc_cfg2_cb);
% add edit box
ppeh = uicontrol('style', 'edit');
set(pph, 'toolBar', 'none')
set(pph, 'menuBar', 'none')
set(pph, 'Name', 'cfg.preproc editor')
set(pph, 'NumberTitle', 'off')
set(ppeh, 'Units', 'normalized');
set(ppeh, 'Position', [0 0 .8 1]);
set(ppeh, 'backgroundColor', [1 1 1]);
set(ppeh, 'horizontalAlign', 'left');
set(ppeh, 'max', 2);
set(ppeh, 'min', 0);
set(ppeh, 'FontName', 'Courier');
set(ppeh, 'FontSize', 12);
set(ppeh, 'string', code);
% add handle for the edit style to figure
setappdata(pph,'superparent', parent); % superparent is the main ft_databrowser window
setappdata(pph,'ppeh', ppeh);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function preproc_cfg2_cb(h,eventdata)
parent = get(h,'parent');
superparent = getappdata(parent,'superparent');
ppeh = getappdata(parent,'ppeh');
code = get(ppeh, 'string');
% remove descriptive lines (so they don't display on command line)
code = cellstr(code(5:end,:));
% get rid of empty lines and white space
remind = [];
for iline = 1:numel(code)
code{iline} = strtrim(code{iline});
if isempty(code{iline})
remind = [remind iline];
end
end
code(remind) = [];
if ~isempty(code)
ispreproccfg = strncmp(code,'cfg.preproc.',12);
if ~all(ispreproccfg)
errordlg('cfg-options must be specified as cfg.preproc.xxx','cfg.preproc editor','modal')
end
% eval the code
for icomm = 1:numel(code)
eval([code{icomm} ';']);
end
% check for cfg and output into the original appdata-window
if ~exist('cfg','var')
cfg = [];
cfg.preproc = [];
end
maincfg = getappdata(superparent,'cfg');
maincfg.preproc = cfg.preproc;
setappdata(superparent,'cfg',maincfg)
end
close(parent)
redraw_cb(superparent)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function keyboard_cb(h, eventdata)
if isempty(eventdata)
% determine the key that corresponds to the uicontrol element that was activated
key = get(h, 'userdata');
else
% determine the key that was pressed on the keyboard
key = parseKeyboardEvent(eventdata);
end
% get focus back to figure
if ~strcmp(get(h, 'type'), 'figure')
set(h, 'enable', 'off');
drawnow;
set(h, 'enable', 'on');
end
h = getparent(h);
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
switch key
case {'1' '2' '3' '4' '5' '6' '7' '8' '9'}
% switch to another artifact type
opt.ftsel = str2double(key);
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
fprintf('switching to the "%s" artifact\n', opt.artdata.label{opt.ftsel});
redraw_cb(h, eventdata);
end
case {'shift+1' 'shift+2' 'shift+3' 'shift+4' 'shift+5' 'shift+6' 'shift+7' 'shift+8' 'shift+9'}
% go to previous artifact
opt.ftsel = str2double(key(end));
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
cursam = opt.trlvis(opt.trlop,1);
artsam = find(opt.artdata.trial{1}(opt.ftsel,1:cursam-1), 1, 'last');
if isempty(artsam)
fprintf('no earlier "%s" artifact found\n', opt.artdata.label{opt.ftsel});
else
fprintf('going to previous "%s" artifact\n', opt.artdata.label{opt.ftsel});
if opt.trlvis(nearest(opt.trlvis(:,1),artsam),1) < artsam
arttrl = nearest(opt.trlvis(:,1),artsam);
else
arttrl = nearest(opt.trlvis(:,1),artsam)-1;
end
opt.trlop = arttrl;
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
end
case {'control+1' 'control+2' 'control+3' 'control+4' 'control+5' 'control+6' 'control+7' 'control+8' 'control+9' 'alt+1' 'alt+2' 'alt+3' 'alt+4' 'alt+5' 'alt+6' 'alt+7' 'alt+8' 'alt+9'}
% go to next artifact
opt.ftsel = str2double(key(end));
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
cursam = opt.trlvis(opt.trlop,2);
artsam = find(opt.artdata.trial{1}(opt.ftsel,cursam+1:end), 1, 'first') + cursam;
if isempty(artsam)
fprintf('no later "%s" artifact found\n', opt.artdata.label{opt.ftsel});
else
fprintf('going to next "%s" artifact\n', opt.artdata.label{opt.ftsel});
if opt.trlvis(nearest(opt.trlvis(:,1),artsam),1) < artsam
arttrl = nearest(opt.trlvis(:,1),artsam);
else
arttrl = nearest(opt.trlvis(:,1),artsam)-1;
end
opt.trlop = arttrl;
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
end
case 'leftarrow'
opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'rightarrow'
opt.trlop = min(opt.trlop + 1, size(opt.trlvis,1)); % should not be larger than the number of trials
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'uparrow'
chansel = match_str(opt.hdr.label, cfg.channel);
minchan = min(chansel);
numchan = length(chansel);
chansel = minchan - numchan : minchan - 1;
if min(chansel)<1
chansel = chansel - min(chansel) + 1;
end
% convert numeric array into cell-array with channel labels
cfg.channel = opt.hdr.label(chansel);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'downarrow'
chansel = match_str(opt.hdr.label, cfg.channel);
maxchan = max(chansel);
numchan = length(chansel);
chansel = maxchan + 1 : maxchan + numchan;
if max(chansel)>length(opt.hdr.label)
chansel = chansel - (max(chansel) - length(opt.hdr.label));
end
% convert numeric array into cell-array with channel labels
cfg.channel = opt.hdr.label(chansel);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'shift+leftarrow'
cfg.blocksize = cfg.blocksize*sqrt(2);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'shift+rightarrow'
cfg.blocksize = cfg.blocksize/sqrt(2);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'shift+uparrow'
cfg.ylim = cfg.ylim/sqrt(2);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'shift+downarrow'
cfg.ylim = cfg.ylim*sqrt(2);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'q'
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
cleanup_cb(h);
case 't'
% select the trial to display
if ~strcmp(opt.trialviewtype,'trialsegment')
str = sprintf('%s to display (current trial = %d/%d)', opt.trialviewtype, opt.trlop, size(opt.trlvis,1));
else
str = sprintf('segment to display (current segment = %d/%d)', opt.trlop, size(opt.trlvis,1));
end
response = inputdlg(str, 'specify', 1, {num2str(opt.trlop)});
if ~isempty(response)
opt.trlop = str2double(response);
opt.trlop = min(opt.trlop, size(opt.trlvis,1)); % should not be larger than the number of trials
opt.trlop = max(opt.trlop, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
case 'h'
% select the horizontal scaling
response = inputdlg('horizontal scale', 'specify', 1, {num2str(cfg.blocksize)});
if ~isempty(response)
cfg.blocksize = str2double(response);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
end
case 'v'
% select the vertical scaling
response = inputdlg('vertical scale, [ymin ymax], ''maxabs'' or ''maxmin''', 'specify', 1, {['[ ' num2str(cfg.ylim) ' ]']});
if ~isempty(response)
response = ['[' response{1} ']']; % convert to string and add brackets, just to ensure that str2num will work
if strcmp(response, '[maxmin]')
minval = min(opt.curdat.trial{1}(:));
maxval = max(opt.curdat.trial{1}(:));
cfg.ylim = [minval maxval];
elseif strcmp(response, '[maxabs]')
minval = min(opt.curdat.trial{1}(:));
maxval = max(opt.curdat.trial{1}(:));
cfg.ylim = [-max(abs([minval maxval])) max(abs([minval maxval]))];
else
tmp = str2num(response);
if numel(tmp)==2
cfg.ylim = tmp;
else
warning('incorrect specification of cfg.ylim, not changing the limits for the vertical axes')
end
end
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
case 'c'
% select channels
select = match_str(opt.hdr.label, cfg.channel);
select = select_channel_list(opt.hdr.label, select);
cfg.channel = opt.hdr.label(select);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'i'
if strcmp(cfg.viewmode, 'butterfly')
delete(findobj(h,'tag', 'identify'));
% click in data and get name of nearest channel
fprintf('click in the figure to identify the name of the closest channel\n');
val = ginput(1);
pos = val(1);
% transform 'val' to match data
val(1) = val(1) * range(opt.hlim) + opt.hlim(1);
val(2) = val(2) * range(opt.vlim) + opt.vlim(1);
channame = val2nearestchan(opt.curdat,val);
channb = match_str(opt.curdat.label,channame);
fprintf('channel name: %s\n',channame);
redraw_cb(h, eventdata);
ft_plot_text(pos, 0.9, channame, 'FontSize', 16, 'tag', 'identify','interpreter','none');
if ~ishold
hold on
ft_plot_vector(opt.curdat.time{1}, opt.curdat.trial{1}(channb,:), 'box', false, 'tag', 'identify', ...
'hpos', opt.laytime.pos(1,1), 'vpos', opt.laytime.pos(1,2), 'width', opt.laytime.width(1), 'height', opt.laytime.height(1), 'hlim', opt.hlim, 'vlim', opt.vlim, ...
'color', 'k', 'linewidth', 2);
hold off
else
ft_plot_vector(opt.curdat.time{1}, opt.curdat.trial{1}(channb,:), 'box', false, 'tag', 'identify', ...
'hpos', opt.laytime.pos(1,1), 'vpos', opt.laytime.pos(1,2), 'width', opt.laytime.width(1), 'height', opt.laytime.height(1), 'hlim', opt.hlim, 'vlim', opt.vlim, ...
'color', 'k', 'linewidth', 2);
end
else
warning('only supported with cfg.viewmode=''butterfly''');
end
case 's'
% toggle between selectmode options: switch from 'markartifact', to 'markpeakevent' to 'marktroughevent' and back with on screen feedback
curstate = find(strcmp(cfg.selectmode, {'markartifact', 'markpeakevent', 'marktroughevent'}));
if curstate == 1
cfg.selectmode = 'markpeakevent';
elseif curstate == 2
cfg.selectmode = 'marktroughevent';
elseif curstate == 3
cfg.selectmode = 'markartifact';
end
fprintf('switching to selectmode = %s\n',cfg.selectmode);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'control+control'
% do nothing
case 'shift+shift'
% do nothing
case 'alt+alt'
% do nothing
otherwise
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
help_cb(h);
end
uiresume(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function toggle_viewmode_cb(h, eventdata, varargin)
% FIXME should be used
opt = guidata(getparent(h));
if ~isempty(varargin) && ischar(varargin{1})
cfg.viewmode = varargin{1};
end
guidata(getparent(h), opt);
redraw_cb(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = getparent(h)
p = h;
while p~=0
h = p;
p = get(h, 'parent');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function redraw_cb(h, eventdata)
h = getparent(h);
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
figure(h); % ensure that the calling figure is in the front
%fprintf('redrawing with viewmode %s\n', cfg.viewmode);
begsample = opt.trlvis(opt.trlop, 1);
endsample = opt.trlvis(opt.trlop, 2);
offset = opt.trlvis(opt.trlop, 3);
chanindx = match_str(opt.hdr.label, cfg.channel);
if ~isempty(opt.event) && isstruct(opt.event)
% select only the events in the current time window
event = opt.event;
evtsample = [event(:).sample];
event = event(evtsample>=begsample & evtsample<=endsample);
else
event = [];
end
if isempty(opt.orgdata)
dat = ft_read_data(cfg.datafile, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat);
else
dat = ft_fetch_data(opt.orgdata, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'allowoverlap', true); % ALLOWING OVERLAPPING TRIALS
end
art = ft_fetch_data(opt.artdata, 'begsample', begsample, 'endsample', endsample);
% apply preprocessing and determine the time axis
[dat, lab, tim] = preproc(dat, opt.hdr.label(chanindx), offset2time(offset, opt.fsample, size(dat,2)), cfg.preproc);
% add NaNs to data for plotting purposes. NaNs will be added when requested horizontal scaling is longer than the data.
nsamplepad = opt.nanpaddata(opt.trlop);
if nsamplepad>0
dat = [dat NaN(numel(lab), opt.nanpaddata(opt.trlop))];
tim = [tim linspace(tim(end),tim(end)+nsamplepad*mean(diff(tim)),nsamplepad)]; % possible machine precision error here
end
opt.curdat.label = lab;
opt.curdat.time{1} = tim;
opt.curdat.trial{1} = dat;
opt.curdat.fsample = opt.fsample;
opt.curdat.sampleinfo = [begsample endsample offset];
% apply scaling to selected channels
% using wildcard to support subselection of channels
if ~isempty(cfg.eegscale)
chansel = match_str(lab, ft_channelselection('EEG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.eegscale;
end
if ~isempty(cfg.eogscale)
chansel = match_str(lab, ft_channelselection('EOG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.eogscale;
end
if ~isempty(cfg.ecgscale)
chansel = match_str(lab, ft_channelselection('ECG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.ecgscale;
end
if ~isempty(cfg.emgscale)
chansel = match_str(lab, ft_channelselection('EMG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.emgscale;
end
if ~isempty(cfg.megscale)
type = opt.hdr.grad.type;
chansel = match_str(lab, ft_channelselection('MEG', lab, type));
dat(chansel,:) = dat(chansel,:) .* cfg.megscale;
end
if ~isempty(cfg.magscale)
chansel = match_str(lab, ft_channelselection('MEGMAG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.magscale;
end
if ~isempty(cfg.gradscale)
chansel = match_str(lab, ft_channelselection('MEGGRAD', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.gradscale;
end
if ~isempty(cfg.chanscale)
chansel = match_str(lab, ft_channelselection(cfg.channel, lab));
dat(chansel,:) = dat(chansel,:) .* repmat(cfg.chanscale,1,size(dat,2));
end
if ~isempty(cfg.mychanscale)
chansel = match_str(lab, ft_channelselection(cfg.mychan, lab));
dat(chansel,:) = dat(chansel,:) .* cfg.mychanscale;
end
% to assure current feature is plotted on top
ordervec = 1:length(opt.artdata.label);
ordervec(opt.ftsel) = [];
ordervec(end+1) = opt.ftsel;
% FIXME speedup ft_prepare_layout
if strcmp(cfg.viewmode, 'butterfly')
laytime = [];
laytime.label = {'dummy'};
laytime.pos = [0.5 0.5];
laytime.width = 1;
laytime.height = 1;
opt.laytime = laytime;
else
% this needs to be reconstructed if the channel selection changes
tmpcfg = [];
tmpcfg.layout = 'vertical';
tmpcfg.channel = cfg.channel;
tmpcfg.skipcomnt = 'yes';
tmpcfg.skipscale = 'yes';
tmpcfg.showcallinfo = 'no';
opt.laytime = ft_prepare_layout(tmpcfg, opt.orgdata);
end
% determine the position of the channel/component labels relative to the real axes
% FIXME needs a shift to the left for components
labelx = opt.laytime.pos(:,1) - opt.laytime.width/2 - 0.01;
labely = opt.laytime.pos(:,2);
% determine the total extent of all virtual axes relative to the real axes
ax(1) = min(opt.laytime.pos(:,1) - opt.laytime.width/2);
ax(2) = max(opt.laytime.pos(:,1) + opt.laytime.width/2);
ax(3) = min(opt.laytime.pos(:,2) - opt.laytime.height/2);
ax(4) = max(opt.laytime.pos(:,2) + opt.laytime.height/2);
axis(ax)
% determine a single local axis that encompasses all channels
% this is in relative figure units
opt.hpos = (ax(1)+ax(2))/2;
opt.vpos = (ax(3)+ax(4))/2;
opt.width = ax(2)-ax(1);
opt.height = ax(4)-ax(3);
% these determine the scaling inside the virtual axes
% the hlim will be in seconds, the vlim will be in Tesla or Volt
opt.hlim = [tim(1) tim(end)];
opt.vlim = cfg.ylim;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fprintf('plotting artifacts...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'artifact'));
for j = ordervec
tmp = diff([0 art(j,:) 0]);
artbeg = find(tmp==+1);
artend = find(tmp==-1) - 1;
for k=1:numel(artbeg)
h_artifact = ft_plot_box([tim(artbeg(k)) tim(artend(k)) -1 1], 'facecolor', opt.artcolors(j,:), 'edgecolor', 'none', 'tag', 'artifact', ...
'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]);
end
end % for each of the artifact channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%fprintf('plotting events...\n');
if strcmp(cfg.ploteventlabels , 'colorvalue') && ~isempty(opt.event)
eventlabellegend = [];
for iType = 1:length(opt.eventtypes)
eventlabellegend = [eventlabellegend sprintf('%s = %s\n',opt.eventtypes{iType},opt.eventtypecolorlabels{iType})];
end
fprintf(eventlabellegend);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'event'));
% save stuff to able to shift event labels downwards when they occur at the same time-point
eventcol = cell(1,numel(event));
eventstr = cell(1,numel(event));
eventtim = NaN(1,numel(event));
% gather event info and plot lines
for ievent = 1:numel(event)
try
if strcmp(cfg.ploteventlabels , 'type=value')
if isempty(event(ievent).value)
eventstr{ievent} = '';
else
eventstr{ievent} = sprintf('%s = %s', event(ievent).type, num2str(event(ievent).value)); % value can be both number and string
end
eventcol{ievent} = 'k';
elseif strcmp(cfg.ploteventlabels , 'colorvalue')
eventcol{ievent} = opt.eventtypescolors(match_str(opt.eventtypes, event(ievent).type),:);
eventstr{ievent} = sprintf('%s', num2str(event(ievent).value)); % value can be both number and string
end
catch
eventstr{ievent} = 'unknown';
eventcol{ievent} = 'k';
end
eventtim(ievent) = (event(ievent).sample-begsample)/opt.fsample + opt.hlim(1);
ft_plot_line([eventtim(ievent) eventtim(ievent)], [-1 1], 'tag', 'event', 'color', eventcol{ievent}, ...
'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]);
end
% count the consecutive occurrence of each time point
concount = NaN(1,numel(event));
for ievent = 1:numel(event)
concount(ievent) = sum(eventtim(ievent)==eventtim(1:ievent-1));
end
% plot labels
for ievent = 1:numel(event)
ft_plot_text(eventtim(ievent), 0.9-concount(ievent)*.06, eventstr{ievent}, 'tag', 'event', 'Color', eventcol{ievent}, ...
'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1],'interpreter','none');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%fprintf('plotting data...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'timecourse'));
delete(findobj(h,'tag', 'identify'));
if strcmp(cfg.viewmode, 'butterfly')
set(gca,'ColorOrder',opt.chancolors(chanindx,:)) % plot vector does not clear axis, therefore this is possible
ft_plot_vector(tim, dat, 'box', false, 'tag', 'timecourse', ...
'hpos', opt.laytime.pos(1,1), 'vpos', opt.laytime.pos(1,2), 'width', opt.laytime.width(1), 'height', opt.laytime.height(1), 'hlim', opt.hlim, 'vlim', opt.vlim);
% two ticks per channel
yTick = sort([opt.laytime.pos(:,2)+(opt.laytime.height/2); ...
opt.laytime.pos(:,2)+(opt.laytime.height/4); ...
opt.laytime.pos(:,2); ...
opt.laytime.pos(:,2)-(opt.laytime.height/4); ...
opt.laytime.pos(:,2)-(opt.laytime.height/2)]);
yTickLabel = {num2str(yTick.*range(opt.vlim) + opt.vlim(1))};
set(gca, 'yTick', yTick);
set(gca, 'yTickLabel', yTickLabel)
elseif any(strcmp(cfg.viewmode, {'vertical' 'component'}))
% determine channel indices into data outside of loop
laysels = match_str(opt.laytime.label, opt.hdr.label);
for i = 1:length(chanindx)
if strcmp(cfg.viewmode, 'component')
color = 'k';
else
color = opt.chancolors(chanindx(i),:);
end
datsel = i;
laysel = laysels(i);
if ~isempty(datsel) && ~isempty(laysel)
if opt.plotLabelFlag == 1 || (opt.plotLabelFlag == 2 && mod(i,10)==0)
ft_plot_text(labelx(laysel), labely(laysel), opt.hdr.label(chanindx(i)), 'tag', 'timecourse', 'HorizontalAlignment', 'right','interpreter','none');
end
ft_plot_vector(tim, dat(datsel, :), 'box', false, 'color', color, 'tag', 'timecourse', ...
'hpos', opt.laytime.pos(laysel,1), 'vpos', opt.laytime.pos(laysel,2), 'width', opt.laytime.width(laysel), 'height', opt.laytime.height(laysel), 'hlim', opt.hlim, 'vlim', opt.vlim);
end
end
if length(chanindx)>19
% no space for yticks
yTick = [];
yTickLabel = [];
elseif length(chanindx)> 6
% one tick per channel
yTick = sort([opt.laytime.pos(:,2)+(opt.laytime.height(laysel)/4); ...
opt.laytime.pos(:,2)-(opt.laytime.height(laysel)/4)]);
yTickLabel = {[.25 .75] .* range(opt.vlim) + opt.vlim(1)};
else
% two ticks per channel
yTick = sort([opt.laytime.pos(:,2)+(opt.laytime.height(laysel)/2); ...
opt.laytime.pos(:,2)+(opt.laytime.height(laysel)/4); ...
opt.laytime.pos(:,2)-(opt.laytime.height(laysel)/4); ...
opt.laytime.pos(:,2)-(opt.laytime.height(laysel)/2)]);
yTickLabel = {[.0 .25 .75 1] .* range(opt.vlim) + opt.vlim(1)};
end
yTickLabel = repmat(yTickLabel, 1, length(chanindx));
set(gca, 'yTick', yTick);
set(gca, 'yTickLabel', yTickLabel);
else
error('unknown viewmode "%s"', cfg.viewmode);
end % if strcmp viewmode
nticks = 11;
xTickLabel = cellstr(num2str( linspace(tim(1), tim(end), nticks)' , '%1.2f'))';
if nsamplepad>0
nlabindat = sum(linspace(tim(1), tim(end), nticks) < tim(end-nsamplepad));
xTickLabel(nlabindat+1:end) = repmat({' '},[1 nticks-nlabindat]);
end
set(gca, 'xTick', linspace(ax(1), ax(2), nticks))
set(gca, 'xTickLabel', xTickLabel)
if strcmp(cfg.viewmode, 'component')
% determine the position of each of the original channels for the topgraphy
laychan = opt.layorg;
% determine the position of each of the topographies
laytopo.pos(:,1) = opt.laytime.pos(:,1) - opt.laytime.width/2 - opt.laytime.height;
laytopo.pos(:,2) = opt.laytime.pos(:,2) + opt.laytime.height/2;
laytopo.width = opt.laytime.height;
laytopo.height = opt.laytime.height;
laytopo.label = opt.laytime.label;
if ~isequal(opt.chanindx, chanindx)
opt.chanindx = chanindx;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fprintf('plotting component topographies...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'topography'));
[sel1, sel2] = match_str(opt.orgdata.topolabel, laychan.label);
chanx = laychan.pos(sel2,1);
chany = laychan.pos(sel2,2);
if strcmp(cfg.compscale, 'global')
for i=1:length(chanindx) % loop through all components to get max and min
zmin(i) = min(opt.orgdata.topo(sel1,chanindx(i)));
zmax(i) = max(opt.orgdata.topo(sel1,chanindx(i)));
end
if strcmp(cfg.zlim, 'maxmin')
zmin = min(zmin);
zmax = max(zmax);
elseif strcmp(cfg.zlim, 'maxabs')
zmax = max([abs(zmin) abs(zmax)]);
zmin = -zmax;
else
error('configuration option for component scaling could not be recognized');
end
end
for i=1:length(chanindx)
% plot the topography of this component
laysel = match_str(opt.laytime.label, opt.hdr.label(chanindx(i)));
chanz = opt.orgdata.topo(sel1,chanindx(i));
if strcmp(cfg.compscale, 'local')
% compute scaling factors here
if strcmp(cfg.zlim, 'maxmin')
zmin = min(chanz);
zmax = max(chanz);
elseif strcmp(cfg.zlim, 'maxabs')
zmax = max(abs(chanz));
zmin = -zmax;
end
end
% scaling
chanz = (chanz - zmin) ./ (zmax- zmin);
% laychan is the actual topo layout, in pixel units for .mat files
% laytopo is a vertical layout determining where to plot each topo,
% with one entry per component
ft_plot_topo(chanx, chany, chanz, 'mask', ...
laychan.mask, 'interplim', 'mask', 'outline', ...
laychan.outline, 'tag', 'topography', ...
'hpos', laytopo.pos(laysel,1)-laytopo.width(laysel)/2,...
'vpos', laytopo.pos(laysel,2)-laytopo.height(laysel)/2,...
'width', laytopo.width(laysel), 'height', laytopo.height(laysel), 'gridscale', 45);
%axis equal
%drawnow
end
caxis([0 1]);
end % if redraw_topo
set(gca, 'yTick', [])
ax(1) = min(laytopo.pos(:,1) - laytopo.width);
ax(2) = max(opt.laytime.pos(:,1) + opt.laytime.width/2);
ax(3) = min(opt.laytime.pos(:,2) - opt.laytime.height/2);
ax(4) = max(opt.laytime.pos(:,2) + opt.laytime.height/2);
axis(ax)
end % plotting topographies
startim = tim(1);
if nsamplepad>0
endtim = tim(end-nsamplepad);
else
endtim = tim(end);
end
if ~strcmp(opt.trialviewtype,'trialsegment')
str = sprintf('%s %d/%d, time from %g to %g s', opt.trialviewtype, opt.trlop, size(opt.trlvis,1), startim, endtim);
else
str = sprintf('trial %d/%d: segment: %d/%d , time from %g to %g s', opt.trllock, size(opt.trlorg,1), opt.trlop, size(opt.trlvis,1), startim, endtim);
end
title(str);
xlabel('time');
% possibly adds some responsiveness if the 'thing' is clogged
drawnow
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key = parseKeyboardEvent(eventdata)
key = eventdata.Key;
% handle possible numpad events (different for Windows and UNIX systems)
% NOTE: shift+numpad number does not work on UNIX, since the shift
% modifier is always sent for numpad events
if isunix()
shiftInd = match_str(eventdata.Modifier, 'shift');
if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd)
% now we now it was a numpad keystroke (numeric character sent AND
% shift modifier present)
key = eventdata.Character;
eventdata.Modifier(shiftInd) = []; % strip the shift modifier
end
elseif ispc()
if strfind(eventdata.Key, 'numpad')
key = eventdata.Character;
end
end
if ~isempty(eventdata.Modifier)
key = [eventdata.Modifier{1} '+' key];
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_singleplotER.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_singleplotER.m
| 26,306 |
utf_8
|
5939ca528f41ee990267b9257eb92fe5
|
function [cfg] = ft_singleplotER(cfg, varargin)
% FT_SINGLEPLOTER plots the event-related fields or potentials of a single
% channel or the average over multiple channels. Multiple datasets can be
% overlayed.
%
% Use as
% ft_singleplotER(cfg, data)
% or
% ft_singleplotER(cfg, data1, data2, ..., datan)
%
% The data can be an erp/erf produced by FT_TIMELOCKANALYSIS, a power
% spectrum produced by FT_FREQANALYSIS or connectivity spectrum produced by
% FT_CONNECTIVITYANALYSIS.
%
% The configuration can have the following parameters:
% cfg.parameter = field to be plotted on y-axis (default depends on data.dimord)
% 'avg', 'powspctrm' or 'cohspctrm'
% cfg.maskparameter = field in the first dataset to be used for masking of data
% (not possible for mean over multiple channels, or when input contains multiple subjects
% or trials)
% cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.channel = nx1 cell-array with selection of channels (default = 'all'),
% see ft_channelselection for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see ft_timelockbaseline
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xn vector (default = 'all')
% cfg.fontsize = font size of title (default = 8)
% cfg.hotkeys = enables hotkeys (up/down/left/right arrows) for dynamic x/y axis translation (Ctrl+) and zoom adjustment
% cfg.interactive = interactive plot 'yes' or 'no' (default = 'no')
% in a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. multiple areas
% can be selected by holding down the shift key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.linestyle = linestyle/marker type, see options of the matlab plot function (default = '-')
% can be a single style for all datasets, or a cell-array containing one style for each dataset
% cfg.linewidth = linewidth in points (default = 0.5)
% cfg.graphcolor = color(s) used for plotting the dataset(s) (default = 'brgkywrgbkywrgbkywrgbkyw')
% alternatively, colors can be specified as nx3 matrix of rgb values
% cfg.directionality = '', 'inflow' or 'outflow' specifies for
% connectivity measures whether the inflow into a
% node, or the outflow from a node is plotted. The
% (default) behavior of this option depends on the dimor
% of the input data (see below).
%
% For the plotting of directional connectivity data the cfg.directionality
% option determines what is plotted. The default value and the supported
% functionality depend on the dimord of the input data. If the input data
% is of dimord 'chan_chan_XXX', the value of directionality determines
% whether, given the reference channel(s), the columns (inflow), or rows
% (outflow) are selected for plotting. In this situation the default is
% 'inflow'. Note that for undirected measures, inflow and outflow should
% give the same output. If the input data is of dimord 'chancmb_XXX', the
% value of directionality determines whether the rows in data.labelcmb are
% selected. With 'inflow' the rows are selected if the refchannel(s) occur in
% the right column, with 'outflow' the rows are selected if the
% refchannel(s) occur in the left column of the labelcmb-field. Default in
% this case is '', which means that all rows are selected in which the
% refchannel(s) occur. This is to robustly support linearly indexed
% undirected connectivity metrics. In the situation where undirected
% connectivity measures are linearly indexed, specifying 'inflow' or
% 'outflow' can result in unexpected behavior.
%
% to facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% if you specify this option the input data will be read from a *.mat
% file on disk. this mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also FT_SINGLEPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR
% this function depends on ft_timelockbaseline which has the following options:
% cfg.baseline, documented
% cfg.channel
% cfg.baselinewindow
% cfg.previous
% cfg.version
% Undocumented local options:
% cfg.zlim/xparam (set to a specific frequency range or time range [zmax zmin] for an average
% over the frequency/time bins for TFR data. Use in conjunction with e.g. xparam = 'time', and cfg.parameter = 'powspctrm').
% copyright (c) 2003-2006, ole jensen
%
% this file is part of fieldtrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% fieldtrip is free software: you can redistribute it and/or modify
% it under the terms of the gnu general public license as published by
% the free software foundation, either version 3 of the license, or
% (at your option) any later version.
%
% fieldtrip is distributed in the hope that it will be useful,
% but without any warranty; without even the implied warranty of
% merchantability or fitness for a particular purpose. see the
% gnu general public license for more details.
%
% you should have received a copy of the gnu general public license
% along with fieldtrip. if not, see <http://www.gnu.org/licenses/>.
%
% $id: ft_singleplotER.m 3147 2011-03-17 12:38:09z jansch $
revision = '$Id: ft_singleplotER.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar varargin
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelindex', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelname', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'});
% set the defaults
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.comment = ft_getopt(cfg, 'comment', strcat([date '\n']));
cfg.axes = ft_getopt(cfg,' axes', 'yes');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.graphcolor = ft_getopt(cfg, 'graphcolor', 'brgkywrgbkywrgbkywrgbkyw');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter',[]);
cfg.linestyle = ft_getopt(cfg, 'linestyle', '-');
cfg.linewidth = ft_getopt(cfg, 'linewidth', 0.5);
cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'box');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.directionality = ft_getopt(cfg, 'directionality', []);
cfg.figurename = ft_getopt(cfg, 'figurename', []);
Ndata = numel(varargin);
% interactive plotting is not allowed with more than 1 input
% if Ndata >1 && strcmp(cfg.interactive, 'yes')
% error('interactive plotting is not supported with more than 1 input data set');
% end
% FIXME rename directionality and cohrefchannel in more meaningful options
if ischar(cfg.graphcolor)
graphcolor = ['k' cfg.graphcolor];
elseif isnumeric(cfg.graphcolor)
graphcolor = [0 0 0; cfg.graphcolor];
end
% check for linestyle being a cell-array, check it's length, and lengthen it if does not have enough styles in it
if ischar(cfg.linestyle)
cfg.linestyle = {cfg.linestyle};
end
if Ndata > 1
if (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) > 1)
error('either specify cfg.linestyle as a cell-array with one cell for each dataset, or only specify one linestyle')
elseif (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) == 1)
tmpstyle = cfg.linestyle{1};
cfg.linestyle = cell(Ndata , 1);
for idataset = 1:Ndata
cfg.linestyle{idataset} = tmpstyle;
end
end
end
% ensure that the input is correct, also backward compatibility with old data structures:
dtype = cell(Ndata, 1);
for i=1:Ndata
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq'});
dtype{i} = ft_datatype(varargin{i});
% this is needed for correct treatment of graphcolor later on
if nargin>1,
if ~isempty(inputname(i+1))
iname{i+1} = inputname(i+1);
else
iname{i+1} = ['input',num2str(i,'%02d')];
end
else
iname{i+1} = cfg.inputfile{i};
end
end
if Ndata >1,
if ~all(strcmp(dtype{1}, dtype))
error('input data are of different type; this is not supported');
end
end
dtype = dtype{1};
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
% set x/y/parameter defaults according to datatype and dimord
switch dtype
case 'timelock'
xparam = 'time';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'avg');
case 'freq'
if sum(ismember(dimtok, 'time'))
xparam = 'time';
yparam = 'freq';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
elseif sum(ismember(dimtok, 'time'))
xparam = 'freq';
yparam = 'time';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
else
xparam = 'freq';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
end
case 'comp'
% not supported
otherwise
% not supported
end
% user specified own fields, but no yparam (which is not asked in help)
if exist('xparam', 'var') && isfield(cfg, 'parameter') && ~exist('yparam', 'var')
yparam = '';
end
if isfield(cfg, 'channel') && isfield(varargin{1}, 'label')
cfg.channel = ft_channelselection(cfg.channel, varargin{1}.label);
elseif isfield(cfg, 'channel') && isfield(varargin{1}, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:)));
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = sum(ismember(dimtok, {'rpt' 'subj'}));
if strcmp(dtype, 'timelock') && hasrpt,
tmpcfg = [];
tmpcfg.trials = cfg.trials;
for i=1:Ndata
varargin{i} = ft_timelockanalysis(tmpcfg, varargin{i});
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
elseif strcmp(dtype, 'freq') && hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
for i=1:Ndata
if isfield(varargin{i}, 'crsspctrm'),
varargin{i} = rmfield(varargin{i}, 'crsspctrm');
end
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
for i=1:Ndata
if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = varargin{i}.dimord;
tempdata.freq = varargin{i}.freq;
tempdata.label = varargin{i}.label;
tempdata.powspctrm = varargin{i}.(cfg.parameter);
tempdata.cfg = varargin{i}.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
varargin{i}.(cfg.parameter) = tempdata.powspctrm;
clear tempdata
else
varargin{i} = ft_freqdescriptives(tmpcfg, varargin{i});
end
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
end
% apply baseline correction
if ~strcmp(cfg.baseline, 'no')
for i=1:Ndata
if strcmp(dtype, 'timelock') && strcmp(xparam, 'time')
varargin{i} = ft_timelockbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(xparam, 'time')
varargin{i} = ft_freqbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(xparam, 'freq')
error('baseline correction is not supported for spectra without a time dimension');
else
warning('baseline correction not applied, please set xparam');
end
end
end
% handle the bivariate case
% check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% check for bivariate metric with a labelcmb
haslabelcmb = isfield(varargin{1}, 'labelcmb');
if (isfull || haslabelcmb) && isfield(varargin{1}, cfg.parameter)
% a reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if haslabelcmb
cfg.refchannel = ft_channelselection(cfg.refchannel, unique(varargin{1}.labelcmb(:)));
else
cfg.refchannel = ft_channelselection(cfg.refchannel, varargin{1}.label);
end
if (isfull && ~any(ismember(varargin{1}.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(varargin{1}.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
error('cfg.refchannel = ''gui'' is not supported in ft_singleplotER');
end
for i=1:Ndata
if ~isfull,
% convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.directionality)
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'inflow')
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter);
if length(sel1)+length(sel2)==0
error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality');
end
varargin{i}.(cfg.parameter) = varargin{i}.(cfg.parameter)([sel1;sel2],:,:);
varargin{i}.label = [varargin{i}.labelcmb(sel1,1);varargin{i}.labelcmb(sel2,2)];
varargin{i}.labelcmb = varargin{i}.labelcmb([sel1;sel2],:);
varargin{i} = rmfield(varargin{i}, 'labelcmb');
else
% general case
sel = match_str(varargin{i}.label, cfg.refchannel);
siz = [size(varargin{i}.(cfg.parameter)) 1];
if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.directionality, 'outflow')
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.directionality, 'ff-fd')
error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotER');
elseif strcmp(cfg.directionality, 'fd-ff')
error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotER');
end %if directionality
end %if ~isfull
end %for i
end %handle the bivariate data
% get physical min/max range of x
if strcmp(cfg.xlim,'maxmin')
% find maxmin throughout all varargins:
xmin = [];
xmax = [];
for i=1:Ndata
xmin = min([xmin varargin{i}.(xparam)]);
xmax = max([xmax varargin{i}.(xparam)]);
end
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% get the index of the nearest bin
for i=1:Ndata
xidmin(i,1) = nearest(varargin{i}.(xparam), xmin);
xidmax(i,1) = nearest(varargin{i}.(xparam), xmax);
end
if strcmp('freq',yparam) && strcmp('freq',dtype)
for i=1:Ndata
varargin{i} = ft_selectdata(varargin{i},'param',cfg.parameter,'foilim',cfg.zlim,'avgoverfreq','yes');
end
elseif strcmp('time',yparam) && strcmp('freq',dtype)
for i=1:Ndata
varargin{i} = ft_selectdata(varargin{i},'param',cfg.parameter,'toilim',cfg.zlim,'avgovertime','yes');
end
end
cla
hold on;
colorlabels = [];
% plot each data set:
for i=1:Ndata
if isfield(varargin{1}, 'label')
selchannel = ft_channelselection(cfg.channel, varargin{i}.label);
elseif isfield(varargin{1}, 'labelcmb')
selchannel = ft_channelselection(cfg.channel, unique(varargin{i}.labelcmb(:)));
else
error('the input data does not contain a label or labelcmb-field');
end
% make vector dat with one value for each channel
dat = varargin{i}.(cfg.parameter);
% get dimord dimensions
dims = textscan(varargin{i}.dimord,'%s', 'Delimiter', '_');
dims = dims{1};
ydim = find(strcmp(yparam, dims));
xdim = find(strcmp(xparam, dims));
zdim = setdiff(1:ndims(dat), [ydim xdim]);
% and permute to make sure that dimensions are in the correct order
dat = permute(dat, [zdim(:)' ydim xdim]);
xval = varargin{i}.(xparam);
% take subselection of channels
% this works for bivariate data with labelcmb because at this point the
% data has a label-field
sellab = match_str(varargin{i}.label, selchannel);
% if ~isempty(yparam)
% if isfull
% dat = dat(sel1, sel2, ymin:ymax, xidmin(i):xidmax(i));
% dat = nanmean(nanmean(dat, meandir), 3);
% siz = size(dat);
% %fixmedat = reshape(dat, [siz(1:2) siz(4)]);
% dat = reshape(dat, [siz(1) siz(3)]);
% dat = dat(sellab, :);
% elseif haslabelcmb
% dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i));
% dat = nanmean(dat, 2);
% siz = size(dat);
% dat = reshape(dat, [siz(1) siz(3)]);
% else
% dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i));
% dat = nanmean(nanmean(dat, 3), 2);
% siz = size(dat);
% dat = reshape(dat, [siz(1) siz(3)]);
% end
% else
if isfull
dat = dat(sel1, sel2, xidmin(i):xidmax(i));
dat = nanmean(dat, meandir);
siz = size(dat);
siz(find(siz(1:2)==1)) = [];
dat = reshape(dat, siz);
dat = dat(sellab, :);
elseif haslabelcmb
dat = dat(sellab, xidmin(i):xidmax(i));
else
dat = dat(sellab, xidmin(i):xidmax(i));
end
% end
xval = xval(xidmin(i):xidmax(i));
datavector = reshape(mean(dat, 1), [1 numel(xval)]); % average over channels
% make mask
if ~isempty(cfg.maskparameter)
datmask = varargin{1}.(cfg.maskparameter)(sellab,:);
datmask = datmask(xidmin(i):xidmax(i));
maskdatavector = reshape(mean(datmask,1), [1 numel(xval)]);
else
maskdatavector = [];
end
if Ndata > 1
if ischar(graphcolor); colorlabels = [colorlabels iname{i+1} '=' graphcolor(i+1) '\n'];
elseif isnumeric(graphcolor); colorlabels = [colorlabels iname{i+1} '=' num2str(graphcolor(i+1,:)) '\n'];
end
end
if ischar(graphcolor); color = graphcolor(i+1);
elseif isnumeric(graphcolor); color = graphcolor(i+1,:);
end
% update ymin and ymax for the current data set:
if strcmp(cfg.ylim,'maxmin')
if i==1
ymin = [];
ymax = [];
end
% select the channels in the data that match with the layout:
ymin = min([ymin min(datavector)]);
ymax = max([ymax max(datavector)]);
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% only plot the mask once, for the first line (it's the same anyway for
% all lines, and if plotted multiple times, it will overlay the others
if i>1 && strcmp(cfg.maskstyle, 'box')
ft_plot_vector(xval, datavector, 'style', cfg.linestyle{i}, 'color', color, ...
'linewidth', cfg.linewidth, 'hlim', cfg.xlim, 'vlim', cfg.ylim);
else
ft_plot_vector(xval, datavector, 'style', cfg.linestyle{i}, 'color', color, ...
'highlight', maskdatavector, 'highlightstyle', cfg.maskstyle, 'linewidth', cfg.linewidth, ...
'hlim', cfg.xlim, 'vlim', cfg.ylim);
end
end
% set xlim and ylim:
xlim([xmin xmax]);
ylim([ymin ymax]);
% adjust mask box extents to ymin/ymax
if ~isempty(cfg.maskparameter)
ptchs = findobj(gcf,'type','patch');
for i = 1:length(ptchs)
YData = get(ptchs(i),'YData');
YData(YData == min(YData)) = ymin;
YData(YData == max(YData)) = ymax;
set(ptchs(i),'YData',YData);
end
end
if strcmp('yes',cfg.hotkeys)
% attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'keypressfcn', {@key_sub, xmin, xmax, ymin, ymax})
end
% set the figure window title, add channel labels if number is small
if length(sellab) < 5
chans = join_str(',', cfg.channel);
else
chans = '<multiple channels>';
end
if isfield(cfg, 'dataname')
dataname = cfg.dataname;
elseif nargin > 1
dataname = inputname(2);
for k = 2:Ndata
dataname = [dataname ', ' inputname(k+1)];
end
else
dataname = cfg.inputfile;
end
if isempty(cfg.figurename)
set(gcf, 'Name', sprintf('%d: %s: %s (%s)', gcf, mfilename, join_str(', ',dataname), chans));
set(gcf, 'NumberTitle', 'off');
else
set(gcf, 'name', cfg.figurename);
set(gcf, 'NumberTitle', 'off');
end
% make the figure interactive
if strcmp(cfg.interactive, 'yes')
set(gcf, 'windowbuttonupfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg, varargin{:}}, 'event', 'windowbuttonupfcn'});
set(gcf, 'windowbuttondownfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg, varargin{:}}, 'event', 'windowbuttondownfcn'});
set(gcf, 'windowbuttonmotionfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg, varargin{:}}, 'event', 'windowbuttonmotionfcn'});
end
% create title text containing channel name(s) and channel number(s):
if length(sellab) == 1
t = [char(cfg.channel) ' / ' num2str(sellab) ];
else
t = sprintf('mean(%0s)', join_str(',', cfg.channel));
end
h = title(t,'fontsize', cfg.fontsize);
% set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction which is called after selecting a time range
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_topoplotER(cfg, varargin)
% first to last callback-input of ft_select_range is range
% last callback-input of ft_select_range is contextmenu label, if used
range = varargin{end-1};
varargin = varargin(1:end-2); % remove range and last
cfg.comment = 'auto';
cfg.xlim = range(1:2);
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
if isfield(cfg, 'showlabels')
% this is not allowed in topoplotER
cfg = rmfield(cfg, 'showlabels');
end
fprintf('selected cfg.xlim = [%f %f]\n', cfg.xlim(1), cfg.xlim(2));
p = get(gcf, 'position');
f = figure;
set(f, 'position', p);
ft_topoplotTFR(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
xlimits = xlim;
ylimits = ylim;
incr_x = abs(xlimits(2) - xlimits(1)) /10;
incr_y = abs(ylimits(2) - ylimits(1)) /10;
% TRANSLATE by 10%
if length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'leftarrow')
xlim([xlimits(1)+incr_x xlimits(2)+incr_x])
elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'rightarrow')
xlim([xlimits(1)-incr_x xlimits(2)-incr_x])
elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'uparrow')
ylim([ylimits(1)-incr_y ylimits(2)-incr_y])
elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'downarrow')
ylim([ylimits(1)+incr_y ylimits(2)+incr_y])
% ZOOM by 10%
elseif strcmp(eventdata.Key,'leftarrow')
xlim([xlimits(1)-incr_x xlimits(2)+incr_x])
elseif strcmp(eventdata.Key,'rightarrow')
xlim([xlimits(1)+incr_x xlimits(2)-incr_x])
elseif strcmp(eventdata.Key,'uparrow')
ylim([ylimits(1)-incr_y ylimits(2)+incr_y])
elseif strcmp(eventdata.Key,'downarrow')
ylim([ylimits(1)+incr_y ylimits(2)-incr_y])
% resort to minmax of data for x-axis and y-axis
elseif strcmp(eventdata.Key,'m')
xlim([varargin{1} varargin{2}])
ylim([varargin{3} varargin{4}])
end
|
github
|
philippboehmsturm/antx-master
|
ft_analysisprotocol.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_analysisprotocol.m
| 20,299 |
utf_8
|
aa755691c86b456eef58b268f25d837a
|
function [script, details] = ft_analysisprotocol(cfg, data)
% FT_ANALYSISPROTOCOL tries to reconstruct the complete analysis protocol that
% was used to create an arbitrary FieldTrip data structure. It will create
% a Matlab script (as text file) and a flowchart with a graphical
% representation.
%
% Use as
% ft_analysisprotocol(cfg, data)
%
% where the first cfg input contains the settings that apply to the
% behaviour of this particular function and the second data input argument
% can be the output of any FieldTrip function, e.g. FT_PREPROCESSING,
% FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS, FT_FREQSTATISTICS or whatever you like.
%
% Alternatively, for the second input argument you can also only give the
% configuration of the processed data (i.e. "data.cfg") instead of the full
% data.
%
% The configuration options that apply to the behaviour of this function are
% cfg.feedback = 'no', 'text', 'gui' or 'yes', whether text and/or
% graphical feedback should be presented (default = 'yes')
% cfg.showinfo = string or cell array of strings, information to display
% in the gui boxes, can be any combination of
% 'functionname', 'revision', 'matlabversion',
% 'computername', 'username', 'calltime', 'timeused',
% 'memused', 'workingdir', 'scriptpath' (default =
% 'functionname', only display function name). Can also
% be 'all', show all info. Please note that if you want
% to show a lot of information, this will require a lot
% of screen real estate.
% cfg.filename = string, filename of m-file to which the script will be
% written (default = [])
% cfg.remove = cell-array with strings, determines which objects will
% be removed from the configuration prior to writing it to
% file. For readibility of the script, you may want to
% remove the large objectssuch as event structure, trial
% definition, source positions
% cfg.keepremoved = 'yes' or 'no', determines whether removed fields are
% completely removed, or only replaced by a short textual
% description (default = 'no')
%
% This function uses the nested cfg and cfg.previous that are present in
% the data structure. It will use the configuration and the nested previous
% configurations to climb all the way back into the tree. This funtction
% will print a complete Matlab script to screen (and optionally to file).
% Furthermore, it will show an interactive graphical flowchart
% representation of the steps taken during the analysis. In the flowchart
% you can click on one of the steps to see the configuration details of
% that step.
%
% Note that the nested cfg and cfg.previous in your data might not contain
% all details that are required to reconstruct a complete and valid
% analysis script.
%
% See also FT_PREPROCESSING,FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS, FT_FREQSTATISTICS
% TODO the output of this function can perhaps be used as input for the wizard function
% Copyright (C) 2006-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_analysisprotocol.m 7203 2012-12-15 16:12:16Z roboos $
persistent depth % this corresponds to the vertical direction in the figure
persistent branch % this corresponds to the horizontal direction in the figure
persistent parent
persistent info
revision = '$Id: ft_analysisprotocol.m 7203 2012-12-15 16:12:16Z roboos $';
% callinfo feedback is highly annoying in this recursive function
% do this here, otherwise ft_defaults will override our setting
if ~isfield(cfg, 'showcallinfo'), cfg.showcallinfo = 'no'; end
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% set the defaults
if ~isfield(cfg, 'filename'), cfg.filename = []; end
if ~isfield(cfg, 'showinfo'), cfg.showinfo = {'functionname'}; end
if ~isfield(cfg, 'keepremoved'), cfg.keepremoved = 'no'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'yes'; end
if ~isfield(cfg, 'remove')
% this is the default list of configuration elements to be removed. These
% elements would be very large to print and make the script difficult to
% read. To get a correctly behaving script, you may have to change this.
cfg.remove = {
'sgncmb'
'channelcmb'
'event'
'trl'
'trlold'
'artfctdef.eog.trl'
'artfctdef.jump.trl'
'artfctdef.muscle.trl'
'pos'
'inside'
'outside'
'grid.pos'
'grid.inside'
'grid.outside'
'vol.bnd.pnt'
'vol.bnd.tri'
};
elseif ~iscell(cfg.remove)
cfg.remove = {cfg.remove};
end
if strcmp(cfg.showinfo, 'all')
cfg.showinfo = {
'functionname'
'revision'
'matlabversion'
'computername'
'architecture'
'username'
'calltime'
'timeused'
'memused'
'workingdir'
'scriptpath'
};
end
if ~isfield(cfg, 'showinfo')
cfg.showinfo = {'functionname'};
elseif ~iscell(cfg.showinfo)
cfg.showinfo = {cfg.showinfo};
end
feedbackgui = strcmp(cfg.feedback, 'gui') || strcmp(cfg.feedback, 'yes');
feedbacktext = strcmp(cfg.feedback, 'text') || strcmp(cfg.feedback, 'yes') || strcmp(cfg.feedback, 'verbose');
feedbackverbose = strcmp(cfg.feedback, 'verbose');
% we are only interested in the cfg-part of the data
if isfield(data, 'cfg')
datacfg = data.cfg;
else
datacfg = data;
end
% set up the persistent variables
if isempty(depth), depth = 1; end
if isempty(branch), branch = 1; end
if depth==1 && branch==1 && feedbacktext
fprintf('steps found in analysis pipeline:\n\n');
end
% start with an empty script
script = '';
% get the function call details before they are removed
try
thisname = getsubfield(datacfg, 'version.name');
if isstruct(thisname)
% I think that this was needed for Matlab 6.5
thisname = thisname.name;
end
[p, f] = fileparts(thisname);
thisname = f;
catch
thisname = 'unknown';
end
try
thisid = getsubfield(datacfg, 'version.id');
catch
thisid = 'unknown';
end
if feedbackverbose
% give some feedback on screen
fprintf('\n');
fprintf('recursion depth = %d, branch = %d\n', depth, branch);
disp(thisname)
disp(thisid)
elseif feedbacktext
% give abridged feedback
fprintf('%-30s depth = %2d branch = %2d\n', thisname, depth, branch);
end
% remove the fields that are too large or not interesting
for i=1:length(cfg.remove)
if issubfield(datacfg, cfg.remove{i})
if feedbackverbose
fprintf('removing %s\n', cfg.remove{i});
end
siz = size(getsubfield(datacfg, cfg.remove{i}));
if strcmp(cfg.keepremoved, 'yes')
% keep the field, but replace the value with a descriptive string
datacfg = setsubfield(datacfg, cfg.remove{i}, sprintf('empty - this was cleared by analysisprotocol, original size = [%s]', num2str(siz)));
else
datacfg = rmsubfield(datacfg, cfg.remove{i});
end
end
end
% convert this part of the configuration to a matlab script
if isfield(datacfg, 'previous')
thiscfg = rmfield(datacfg, 'previous');
else
thiscfg = datacfg;
end
code = printstruct('cfg', thiscfg);
nl = sprintf('\n');
emptycfg = sprintf('cfg = [];\n');
sep = sprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
head1 = sprintf('%% version name = %s\n', thisname);
head2 = sprintf('%% version id = %s\n', thisid);
thisscript = [nl sep head1 head2 sep emptycfg code nl];
% remember this part of the configuration info
info(branch,depth).name = thisname;
info(branch,depth).id = thisid;
info(branch,depth).cfg = thiscfg;
info(branch,depth).script = thisscript;
info(branch,depth).this = [branch depth];
info(branch,depth).parent = parent;
info(branch,depth).children = {}; % this will be determined later
% this will keep track of whether an extra branch has been found in this
% step
extraBranchesFound = 0;
prev = parent;
parent = [branch depth]; % this will be used in the recursive call
if isfield(datacfg, 'previous')
if isstruct(datacfg.previous)
% single previous cfg, no branching here
% increment the depth counter
depth = depth + 1;
% increment the branch counter
branch = branch + extraBranchesFound;
extraBranchesFound = 1;
% use recursion to parse the previous section of the tree
ft_analysisprotocol(cfg, datacfg.previous);
elseif iscell(datacfg.previous)
% multiple previous cfgs, branch
for i=1:length(datacfg.previous(:))
% increment the depth counter
depth = depth + 1;
% increment the branch counter
branch = branch + extraBranchesFound;
extraBranchesFound = 1;
% use recursion to parse each previous section of the tree
ft_analysisprotocol(cfg, datacfg.previous{i});
end
end
end
% check all fields of the cfg to see if any of them have a sub-cfg that
% would be appropriate to include as a branch
if isempty(datacfg)
fn = {};
else
fn = fieldnames(datacfg);
end
for i=1:length(fn)
if isa(datacfg.(fn{i}), 'struct') && isfield(datacfg.(fn{i}), 'cfg')
% increment the depth counter
depth = depth + 1;
% increment the branch counter
branch = branch + extraBranchesFound;
extraBranchesFound = 1;
ft_analysisprotocol(cfg, datacfg.(fn{i}).cfg);
end
end
% revert to the orignal parent
parent = prev;
if depth==1
% the recursion has finished, we are again at the top level
% record total processing time and maximum memory requirement
totalproctime = 0;
maxmemreq = 0;
% the parents were determined while climbing up the tree
% now it is time to descend and determine the children
for branch=1:size(info,1)
for depth=1:size(info,2)
if ~isempty(info(branch, depth).parent)
parentbranch = info(branch, depth).parent(1);
parentdepth = info(branch, depth).parent(2);
info(parentbranch, parentdepth).children{end+1} = [branch depth];
if isfield(info(branch,depth).cfg, 'callinfo') && isfield(info(branch,depth).cfg.callinfo, 'proctime')
totalproctime = totalproctime + info(branch,depth).cfg.callinfo.proctime;
end
if isfield(info(branch,depth).cfg, 'callinfo') && isfield(info(branch,depth).cfg.callinfo, 'procmem')
maxmemreq = max(maxmemreq, info(branch,depth).cfg.callinfo.procmem);
end
end
end
end
% complement the individual scripts with the input and output variables
% and the actual function call
for branch=1:size(info,1)
for depth=1:size(info,2)
outputvar = sprintf('var_%d_%d', info(branch, depth).this);
inputvar = '';
commandline = sprintf('%s = %s(cfg%s);', outputvar, info(branch, depth).name, inputvar);
% this seems pointless?
%disp(commandline);
end
end
if nargout>0
% return the complete script as output argument
script = '';
for branch=1:size(info,1)
for depth=1:size(info,2)
script = [info(branch,depth).script script];
end
end
end
if nargout>1
% return the information details as output argument
details = info;
end
if feedbackgui
fig = figure;
hold on
% the axis should not change during the contruction of the arrows,
% otherwise the arrowheads will be distorted
axis manual;
set(gca,'Units','normalized'); % use normalized units
for branch=1:size(info,1)
for depth=1:size(info,2)
plotinfo(cfg,info(branch,depth),size(info,1),size(info,2));
end
end
axis off;
axis tight;
set(fig, 'WindowButtonUpFcn', @button);
set(fig, 'KeyPressFcn', @key);
end % feedbackgui
if ~isempty(cfg.filename)
% write the complete script to file
fprintf('writing result to file ''%s''\n', cfg.filename);
fid = fopen(cfg.filename, 'wb');
fprintf(fid, '%s', script);
fclose(fid);
end
% give a report on the total time used and max. memory required
if totalproctime > 3600
proclabel = sprintf('%5.2g hours', totalproctime./3600);
else
proclabel = sprintf('%d seconds', round(totalproctime));
end
fprintf('\nthe entire analysis pipeline took %s to run\n', proclabel);
fprintf('the maximum memory requirement of the analysis pipeline was %d MB\n\n',...
round(maxmemreq./1024./1024));
% clear all persistent variables
depth = [];
branch = [];
info = [];
parent = [];
else
% this level of recursion has finished, decrease the depth
depth = depth - 1;
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotinfo(cfg,element,numbranch,numdepth)
if isempty(element.name)
return
end
% cfg.showinfo is a string or a cell-array of strings that instructs which information
% to display in the gui boxes
% create the text information to display
label = {};
for k = 1:numel(cfg.showinfo)
switch cfg.showinfo{k}
case 'functionname'
label{end+1} = ['{\bf ' element.name '}'];
if k == 1 % add blank line if function name is on top, looks nice
label{end+1} = '';
firstLabelIsName = 1;
end
case 'revision'
if isfield(element.cfg, 'version') && isfield(element.cfg.version, 'id')
label{end+1} = element.cfg.version.id;
else
label{end+1} = '<revision unknown>';
end
case 'matlabversion'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'matlab')
label{end+1} = ['MATLAB ' element.cfg.callinfo.matlab];
else
label{end+1} = '<MATLAB version unknown>';
end
case 'computername'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'hostname')
label{end+1} = ['Computer name: ' element.cfg.callinfo.hostname];
else
label{end+1} = '<hostname unknown>';
end
case 'architecture'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'hostname')
label{end+1} = ['Architecture: ' element.cfg.callinfo.computer];
else
label{end+1} = '<architecture unknown>';
end
case 'username'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'user')
label{end+1} = ['Username: ' element.cfg.callinfo.user];
else
label{end+1} = '<username unknown>';
end
case 'calltime'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'calltime')
label{end+1} = ['Function called at ' datestr(element.cfg.callinfo.calltime)];
else
label{end+1} = '<function call time unknown>';
end
case 'timeused'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'proctime')
label{end+1} = sprintf('Function call required %d seconds.', round(element.cfg.callinfo.proctime));
else
label{end+1} = '<processing time unknown>';
end
case 'memused'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'procmem')
label{end+1} = sprintf('Function call required %d MB.', round(element.cfg.callinfo.procmem/1024/1024));
else
label{end+1} = '<memory requirement unknown>';
end
case 'workingdir'
if isfield(element.cfg, 'callinfo') && isfield(element.cfg.callinfo, 'pwd')
label{end+1} = sprintf('Working directory was %s.', element.cfg.callinfo.pwd);
else
label{end+1} = '<working directory unknown>';
end
case 'scriptpath'
if isfield(element.cfg, 'version') && isfield(element.cfg.version, 'name')
label{end+1} = sprintf('Full path to script was %s.', element.cfg.version.name);
else
label{end+1} = '<script path unknown>';
end
end
end
% dublicate backslashes to escape tex interpreter (in case of windows filenames)
label = strrep(label, '\', '\\');
label = strrep(label, '{\\bf', '{\bf'); % undo for bold formatting
% escape underscores
label = strrep(label, '_', '\_');
% strip blank line if present and not needed
if strcmp(label{end},'')
label(end) = [];
end
% compute width and height of each box
% note that axis Units are set to Normalized
wh = [1./numbranch 1./numdepth];
boxpadding = wh ./ 5 ./ numel(label);
boxmargin = wh ./ 5;
% adjust actual, inner, width/height for computed padding and margin
wh = wh - boxpadding.*2 - boxmargin.*2;
% create the 4 corners for our patch
x = [0 1 1 0] .* (wh(1)+boxpadding(1).*2);
y = [0 0 1 1] .* (wh(2)+boxpadding(2).*2);
% close the patch
x = [x x(end)];
y = [y y(end)];
% move the patch
location = (element.this-1).*(wh+boxpadding.*2) + element.this.*boxmargin;
% location is at bottom left corner of patch
x = x + location(1);
y = y + location(2);
p = patch(x', y', 0);
set(p, 'Facecolor', [1 1 0.6])
% store data for this patch
tmpGuidata = guidata(p);
if ~isfield(tmpGuidata, 'patches')
tmpGuidata.patches = {};
end
tmpGuidata.patches{end+1} = [];
tmpGuidata.patches{end}.x = x';
tmpGuidata.patches{end}.y = y';
tmpGuidata.patches{end}.element = element;
guidata(p, tmpGuidata);
if numel(label) == 1
% center of patch
textloc = location+boxpadding+wh./2;
l = text(textloc(1), textloc(2), label);
set(l, 'HorizontalAlignment', 'center');
set(l, 'VerticalAlignment', 'middle');
set(l, 'fontUnits', 'points');
set(l, 'fontSize', 10);
else
% top left corner of patch, inside padding
textloc = [location(1)+boxpadding(1) location(2)+wh(2)];
l = text(textloc(1), textloc(2), label);
set(l, 'HorizontalAlignment', 'left');
set(l, 'VerticalAlignment', 'top');
set(l, 'fontUnits', 'points');
set(l, 'fontSize', 10);
end
set(l, 'interpreter', 'tex');
% draw an arrow if appropriate
if ~isempty(element.parent)
parentlocation = (element.parent-1).*(wh+boxpadding.*2) + element.parent.*boxmargin;
tip = parentlocation + [0.5 1].*wh + [1 2].*boxpadding;
base = location + [0.5 0].*wh + [1 0].*boxpadding;
arrow(base,tip,'Length',8);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = key(h, eventdata, handles, varargin)
% this is just a placeholder for future functionality
% at the moment it does not do anything
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = button(h, eventdata, handles, varargin)
pos = get(get(gcbo, 'CurrentAxes'), 'CurrentPoint');
x = pos(1,1);
y = pos(1,2);
patches = guidata(h);
patches = patches.patches; % stupid matlab syntax doesn't allow guidata(h).patches
for k = 1:numel(patches)
patchX = patches{k}.x;
patchY = patches{k}.y;
if (x >= patchX(1) && x <= patchX(2) ...
&& y >= patchY(1) && y <= patchY(3))
uidisplaytext(patches{k}.element.script, patches{k}.element.name);
break;
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_mvaranalysis.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_mvaranalysis.m
| 17,631 |
utf_8
|
170b19b1e29004c2c509ef166d2c2e7e
|
function [mvardata] = ft_mvaranalysis(cfg, data)
% FT_MVARANALYSIS performs multivariate autoregressive modeling on
% time series data over multiple trials.
%
% Use as
% [mvardata] = ft_mvaranalysis(cfg, data)
%
% The input data should be organised in a structure as obtained from
% the FT_PREPROCESSING function. The configuration depends on the type
% of computation that you want to perform.
% The output is a data structure of datatype 'mvar' which contains the
% multivariate autoregressive coefficients in the field coeffs, and the
% covariance of the residuals in the field noisecov.
%
% The configuration should contain:
% cfg.toolbox = the name of the toolbox containing the function for the
% actual computation of the ar-coefficients
% this can be 'biosig' (default) or 'bsmart'
% you should have a copy of the specified toolbox in order
% to use mvaranalysis (both can be downloaded directly).
% cfg.mvarmethod = scalar (only required when cfg.toolbox = 'biosig').
% default is 2, relates to the algorithm used for the
% computation of the AR-coefficients by mvar.m
% cfg.order = scalar, order of the autoregressive model (default=10)
% cfg.channel = 'all' (default) or list of channels for which an mvar model
% is fitted. (Do NOT specify if cfg.channelcmb is
% defined)
% cfg.channelcmb = specify channel combinations as a
% two-column cell array with channels in each column between
% which a bivariate model will be fit (overrides
% cfg.channel)
% cfg.keeptrials = 'no' (default) or 'yes' specifies whether the coefficients
% are estimated for each trial seperately, or on the
% concatenated data
% cfg.jackknife = 'no' (default) or 'yes' specifies whether the coefficients
% are estimated for all leave-one-out sets of trials
% cfg.zscore = 'no' (default) or 'yes' specifies whether the channel data
% are z-transformed prior to the model fit. This may be
% necessary if the magnitude of the signals is very different
% e.g. when fitting a model to combined MEG/EMG data
% cfg.demean = 'yes' (default) or 'no' explicit removal of DC-offset
% cfg.ems = 'no' (default) or 'yes' explicit removal ensemble mean
%
% ft_mvaranalysis can be used to obtain one set of coefficients for
% the whole common time axis defined in the data. It will throw an error
% if the trials are of variable length, or if the time axes of the trials
% are not equal to one another.
%
% ft_mvaranalysis can be also used to obtain time-dependent sets of
% coefficients based on a sliding window. In this case the input cfg
% should contain:
%
% cfg.t_ftimwin = the width of the sliding window on which the coefficients
% are estimated
% cfg.toi = [t1 t2 ... tx] the time points at which the windows are
% centered
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_PREPROCESSING, FT_SOURCESTATISTICS, FT_FREQSTATISTICS,
% FT_TIMELOCKSTATISTICS
% Undocumented local options:
% cfg.keeptapers
% cfg.taper
% Copyright (C) 2009, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_mvaranalysis.m 7393 2013-01-23 14:33:27Z jorhor $
revision = '$Id: ft_mvaranalysis.m 7393 2013-01-23 14:33:27Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar data
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'raw', 'hassampleinfo', 'yes');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'blc', 'demean'});
cfg = ft_checkconfig(cfg, 'renamed', {'blcwindow', 'baselinewindow'});
% set default configurations
if ~isfield(cfg, 'toolbox'), cfg.toolbox = 'biosig'; end
if ~isfield(cfg, 'mvarmethod'), cfg.mvarmethod = 2; end
if ~isfield(cfg, 'order'), cfg.order = 10; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end
if ~isfield(cfg, 'jackknife'), cfg.jackknife = 'no'; end
if ~isfield(cfg, 'zscore'), cfg.zscore = 'no'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end
if ~isfield(cfg, 'demean'), cfg.demean = 'yes'; end
if ~isfield(cfg, 'ems'), cfg.ems = 'no'; end
if ~isfield(cfg, 'toi'), cfg.toi = []; end
if ~isfield(cfg, 't_ftimwin'), cfg.t_ftimwin = []; end
if ~isfield(cfg, 'keeptapers'), cfg.keeptapers = 'yes'; end
if ~isfield(cfg, 'taper'), cfg.taper = 'rectwin'; end
% check that cfg.channel and cfg.channelcmb are not both specified
if ~any(strcmp(cfg.channel, 'all')) && isfield(cfg, 'channelcmb')
warning('cfg.channelcmb defined, overriding cfg.channel setting and computing over bivariate pairs');
end
% check whether the requested toolbox is present and check the configuration
switch cfg.toolbox
case 'biosig'
% check the configuration
cfg = ft_checkconfig(cfg, 'required', 'mvarmethod');
ft_hastoolbox('biosig', 1);
nnans = cfg.order;
case 'bsmart'
ft_hastoolbox('bsmart', 1);
nnans = 0;
otherwise
error('toolbox %s is not yet supported', cfg.toolbox);
end
if isempty(cfg.toi) && isempty(cfg.t_ftimwin)
% fit model to entire data segment
ok = 1;
for k = 1:numel(data.trial)
% if any(data.time{k}~=data.time{1}),
if size(data.trial{k},2) ~= size(data.trial{1},2)
ok = 0;
break
end
end
if ~ok
error('time axes of all trials should be identical');
else
cfg.toi = mean(data.time{1}([1 end])) + 0.5/data.fsample;
cfg.t_ftimwin = data.time{1}(end)-data.time{1}(1) + 1/data.fsample;
end
elseif ~isempty(cfg.toi) && ~isempty(cfg.t_ftimwin)
% do sliding window approach
else
error('cfg should contain both cfg.toi and cfg.t_ftimwin');
end
cfg.channel = ft_channelselection(cfg.channel, data.label);
keeprpt = strcmp(cfg.keeptrials, 'yes');
keeptap = strcmp(cfg.keeptapers, 'yes');
dojack = strcmp(cfg.jackknife, 'yes');
dozscore = strcmp(cfg.zscore, 'yes');
dobvar = isfield(cfg, 'channelcmb');
if ~keeptap, error('not keeping tapers is not possible yet'); end
if dojack && keeprpt, error('you cannot simultaneously keep trials and do jackknifing'); end
tfwin = round(data.fsample.*cfg.t_ftimwin);
ntrl = length(data.trial);
ntoi = length(cfg.toi);
if ~dobvar
chanindx = match_str(data.label, cfg.channel);
nchan = length(chanindx);
label = data.label(chanindx);
ncmb = nchan*nchan;
cmbindx1 = repmat(chanindx(:), [1 nchan]);
cmbindx2 = repmat(chanindx(:)', [nchan 1]);
labelcmb = [data.label(cmbindx1(:)) data.label(cmbindx2(:))];
else
cfg.channelcmb = ft_channelcombination(cfg.channelcmb, data.label);
cmbindx = zeros(size(cfg.channelcmb));
for k = 1:size(cmbindx,1)
[tmp, cmbindx(k,:)] = match_str(cfg.channelcmb(k,:)', data.label);
end
nchan = 2;
label = data.label(cmbindx);
ncmb = nchan*nchan;
labelcmb = cell(0,2);
cmb = cfg.channelcmb;
for k = 1:size(cmbindx,1)
labelcmb{end+1,1} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end+1,1} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end+1,1} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end+1,1} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
end
end
%---think whether this makes sense at all
if strcmp(cfg.taper, 'dpss')
% create a sequence of DPSS (Slepian) tapers
% ensure that the input arguments are double precision
tap = double_dpss(tfwin,tfwin*(cfg.tapsmofrq./data.fsample))';
tap = tap(1,:); %only use first 'zero-order' taper
elseif strcmp(cfg.taper, 'sine')
tap = sine_taper(tfwin, tfwin*(cfg.tapsmofrq./data.fsample))';
tap = tap(1,:);
else
tap = window(cfg.taper, tfwin)';
tap = tap./norm(tap);
end
ntap = size(tap,1);
%---preprocess data if necessary
%---cut off the uninteresting data segments
tmpcfg = [];
tmpcfg.toilim = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5];
data = ft_redefinetrial(tmpcfg, data);
%---demean
if strcmp(cfg.demean, 'yes'),
tmpcfg = [];
tmpcfg.demean = 'yes';
tmpcfg.baselinewindow = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5];
data = ft_preprocessing(tmpcfg, data);
else
%do nothing
end
%---ensemble mean subtraction
if strcmp(cfg.ems, 'yes')
% to be implemented
end
%---zscore
if dozscore,
zwindow = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5];
sumval = 0;
sumsqr = 0;
numsmp = 0;
trlindx = [];
for k = 1:ntrl
begsmp = nearest(data.time{k}, zwindow(1));
endsmp = nearest(data.time{k}, zwindow(2));
if endsmp>=begsmp,
sumval = sumval + sum(data.trial{k}(:, begsmp:endsmp), 2);
sumsqr = sumsqr + sum(data.trial{k}(:, begsmp:endsmp).^2, 2);
numsmp = numsmp + endsmp - begsmp + 1;
trlindx = [trlindx; k];
end
end
datavg = sumval./numsmp;
datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2);
data.trial = data.trial(trlindx);
data.time = data.time(trlindx);
ntrl = length(trlindx);
for k = 1:ntrl
rvec = ones(1,size(data.trial{k},2));
data.trial{k} = (data.trial{k} - datavg*rvec)./(datstd*rvec);
end
else
%do nothing
end
%---generate time axis
maxtim = -inf;
mintim = inf;
for k = 1:ntrl
maxtim = max(maxtim, data.time{k}(end));
mintim = min(mintim, data.time{k}(1));
end
timeaxis = mintim:1/data.fsample:maxtim;
%---allocate memory
if ~dobvar && (keeprpt || dojack)
coeffs = zeros(length(data.trial), nchan, nchan, cfg.order, ntoi, ntap);
noisecov = zeros(length(data.trial), nchan, nchan, ntoi, ntap);
elseif ~dobvar
coeffs = zeros(1, nchan, nchan, cfg.order, ntoi, ntap);
noisecov = zeros(1, nchan, nchan, ntoi, ntap);
elseif dobvar && (keeprpt || dojack)
% not yet implemented
error('doing bivariate model fits in combination with multiple replicates is not yet possible');
elseif dobvar
coeffs = zeros(1, size(cmbindx,1), 2*nchan, cfg.order, ntoi, ntap);
noisecov = zeros(1, size(cmbindx,1), 2*nchan, ntoi, ntap);
end
%---loop over the tois
ft_progress('init', cfg.feedback, 'computing AR-model');
for j = 1:ntoi
ft_progress(j/ntoi, 'processing timewindow %d from %d\n', j, ntoi);
sample = nearest(timeaxis, cfg.toi(j));
cfg.toi(j) = timeaxis(sample);
tmpcfg = [];
tmpcfg.toilim = [timeaxis(sample-floor(tfwin/2)) timeaxis(sample+ceil(tfwin/2)-1)];
tmpcfg.feedback = 'no';
tmpcfg.minlength= 'maxperlen';
tmpdata = ft_redefinetrial(tmpcfg, data);
cfg.toi(j) = mean(tmpdata.time{1}([1 end]))+0.5./data.fsample; %FIXME think about this
%---create cell-array indexing which original trials should go into each replicate
rpt = {};
nrpt = numel(tmpdata.trial);
if dojack
rpt = cell(nrpt,1);
for k = 1:nrpt
rpt{k,1} = setdiff(1:nrpt,k);
end
elseif keeprpt
for k = 1:nrpt
rpt{k,1} = k;
end
else
rpt{1} = 1:numel(tmpdata.trial);
nrpt = 1;
end
for rlop = 1:nrpt
if dobvar % bvar
for m = 1:ntap
%---construct data-matrix
for k = 1:size(cmbindx,1)
dat = catnan(tmpdata.trial, cmbindx(k,:), rpt{rlop}, tap(m,:), nnans, dobvar);
%---estimate autoregressive model
switch cfg.toolbox
case 'biosig'
[ar, rc, pe] = mvar(dat', cfg.order, cfg.mvarmethod);
%---compute noise covariance
tmpnoisecov = pe(:,nchan*cfg.order+1:nchan*(cfg.order+1));
case 'bsmart'
[ar, tmpnoisecov] = armorf(dat, numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order);
ar = -ar; %convention is swapped sign with respect to biosig
%FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E
%the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E
end
coeffs(rlop,k,:,:,j,m) = reshape(ar, [nchan*2 cfg.order]);
%---rescale noisecov if necessary
if dozscore, % FIX ME for bvar
noisecov(rlop,k,:,:,j,m) = diag(datstd)*tmpnoisecov*diag(datstd);
else
noisecov(rlop,k,:,j,m) = reshape(tmpnoisecov,[1 4]);
end
dof(rlop,:,j) = numel(rpt{rlop});
end
end
else % mvar
for m = 1:ntap
%---construct data-matrix
dat = catnan(tmpdata.trial, chanindx, rpt{rlop}, tap(m,:), nnans, dobvar);
%---estimate autoregressive model
switch cfg.toolbox
case 'biosig'
[ar, rc, pe] = mvar(dat', cfg.order, cfg.mvarmethod);
%---compute noise covariance
tmpnoisecov = pe(:,nchan*cfg.order+1:nchan*(cfg.order+1));
case 'bsmart'
[ar, tmpnoisecov] = armorf(dat, numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order);
ar = -ar; %convention is swapped sign with respect to biosig
%FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E
%the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E
end
coeffs(rlop,:,:,:,j,m) = reshape(ar, [nchan nchan cfg.order]);
%---rescale noisecov if necessary
if dozscore,
noisecov(rlop,:,:,j,m) = diag(datstd)*tmpnoisecov*diag(datstd);
else
noisecov(rlop,:,:,j,m) = tmpnoisecov;
end
dof(rlop,:,j) = numel(rpt{rlop});
end %---tapers
end
end %---replicates
end %---tois
ft_progress('close');
%---create output-structure
mvardata = [];
if ~dobvar && dojack,
mvardata.dimord = 'rptjck_chan_chan_lag';
elseif ~dobvar && keeprpt,
mvardata.dimord = 'rpt_chan_chan_lag';
elseif ~dobvar
mvardata.dimord = 'chan_chan_lag';
mvardata.label = label;
siz = [size(coeffs) 1];
coeffs = reshape(coeffs, siz(2:end));
siz = [size(noisecov) 1];
noisecov = reshape(noisecov, siz(2:end));
elseif dobvar
mvardata.dimord = 'chancmb_lag';
siz = [size(coeffs) 1];
coeffs = reshape(coeffs, [siz(2) * siz(3) siz(4) siz(5)]);
siz = [size(noisecov) 1];
noisecov = reshape(noisecov, [siz(2) * siz(3) siz(4)]);
mvardata.labelcmb = labelcmb;
end
mvardata.coeffs = coeffs;
mvardata.noisecov = noisecov;
mvardata.dof = dof;
if numel(cfg.toi)>1
mvardata.time = cfg.toi;
mvardata.dimord = [mvardata.dimord,'_time'];
end
mvardata.fsampleorig = data.fsample;
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
ft_postamble history mvardata
ft_postamble savevar mvardata
%----------------------------------------------------
%subfunction to concatenate data with nans in between
function [datamatrix] = catnan(datacells, chanindx, trials, taper, nnans, dobvar)
nchan = length(chanindx);
nsmp = size(datacells{1}, 2);
nrpt = numel(trials);
%---initialize
datamatrix = nan(nchan, nsmp*nrpt + nnans*(nrpt-1));
%---fill the matrix
for k = 1:nrpt
if k==1,
begsmp = (k-1)*nsmp + 1;
endsmp = k *nsmp ;
else
begsmp = (k-1)*(nsmp+nnans) + 1;
endsmp = k *(nsmp+nnans) - nnans;
end
if ~dobvar
datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx,:).*taper(ones(nchan,1),:);
else
datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx',:).*taper(ones(nchan,1),:);
end
end
%------------------------------------------------------
%---subfunction to ensure that the first two input arguments are of double
% precision this prevents an instability (bug) in the computation of the
% tapers for Matlab 6.5 and 7.0
function [tap] = double_dpss(a, b, varargin)
tap = dpss(double(a), double(b), varargin{:});
|
github
|
philippboehmsturm/antx-master
|
ft_megrealign.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_megrealign.m
| 18,641 |
utf_8
|
1cda98807ec99633822ecdf42991629d
|
function [data] = ft_megrealign(cfg, data)
% FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations
% by projecting the individual timelocked data towards a coarse source
% reconstructed representation and computing the magnetic field on
% the standard gradiometer locations.
%
% Use as
% [interp] = ft_megrealign(cfg, data)
%
% Required configuration options:
% cfg.template
% cfg.inwardshift
%
% The new gradiometer definition is obtained from a template dataset,
% or can be constructed by averaging the gradiometer positions over
% multiple datasets.
% cfg.template = single dataset that serves as template
% cfg.template(1..N) = datasets that are averaged into the standard
%
% The realignment is done by computing a minumum norm estimate using a
% large number of dipoles that are placed in the upper layer of the brain
% surface, followed by a forward computation towards the template
% gradiometer array. This requires the specification of a volume conduction
% model of the head and of a source model.
%
% A volume conduction model of the head should be specified with
% cfg.vol = structure, see FT_PREPARE_HEADMODEL
%
% A source model (i.e. a superficial layer with distributed sources) can be
% constructed from a headshape file, or from the volume conduction model
% cfg.spheremesh = number of dipoles in the source layer (default = 642)
% cfg.inwardshift = depth of the source layer relative to the headshape
% surface or volume conduction model (no default
% supplied, see below)
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% If you specify a headshape and it describes the skin surface, you should specify an
% inward shift of 2.5 cm.
%
% For a single-sphere or a local-spheres volume conduction model based on the skin
% surface, an inward shift of 2.5 cm is reasonable.
%
% For a single-sphere or a local-spheres volume conduction model based on the brain
% surface, you should probably use an inward shift of about 1 cm.
%
% For a realistic single-shell volume conduction model based on the brain surface, you
% should probably use an inward shift of about 1 cm.
%
% Other options are
% cfg.pruneratio = for singular values, default is 1e-3
% cfg.verify = 'yes' or 'no', show the percentage difference (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'),
% see FT_CHANNELSELECTION for details
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
%
% This implements the method described by T.R. Knosche, Transformation
% of whole-head MEG recordings between different sensor positions.
% Biomed Tech (Berl). 2002 Mar;47(3):59-62. For more information and
% related methods, see Stolk et al., Online and offline tools for head
% movement compensation in MEG. NeuroImage, 2012.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL
% This function depends on FT_PREPARE_DIPOLE_GRID
%
% This function depends on FT_PREPARE_VOL_SENS which has the following options:
% cfg.channel
% cfg.elec
% cfg.elecfile
% cfg.grad
% cfg.gradfile
% cfg.hdmfile, documented
% cfg.order
% cfg.vol, documented
% Copyright (C) 2004-2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_megrealign.m 7194 2012-12-14 15:04:05Z arjsto $
revision = '$Id: ft_megrealign.m 7194 2012-12-14 15:04:05Z arjsto $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar data
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'plot3d', 'feedback'});
cfg = ft_checkconfig(cfg, 'renamedval', {'headshape', 'headmodel', []});
cfg = ft_checkconfig(cfg, 'required', {'inwardshift', 'template'});
% set the default configuration
if ~isfield(cfg, 'headshape'), cfg.headshape = []; end
if ~isfield(cfg, 'pruneratio'), cfg.pruneratio = 1e-3; end
if ~isfield(cfg, 'spheremesh'), cfg.spheremesh = 642; end
if ~isfield(cfg, 'verify'), cfg.verify = 'yes'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'yes'; end
if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end
if ~isfield(cfg, 'channel'), cfg.channel = 'MEG'; end
if ~isfield(cfg, 'topoparam'), cfg.topoparam = 'rms'; end
% store original datatype
dtype = ft_datatype(data);
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes');
% do realignment per trial
pertrial = all(ismember({'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}, data.label));
% put the low-level options pertaining to the dipole grid in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'});
% select trials of interest
if ~strcmp(cfg.trials, 'all')
fprintf('selecting %d trials\n', length(cfg.trials));
data = ft_selectdata(data, 'rpt', cfg.trials);
end
Ntrials = length(data.trial);
% retain only the MEG channels in the data and temporarily store
% the rest, these will be added back to the transformed data later.
cfg.channel = ft_channelselection(cfg.channel, data.label);
dataindx = match_str(data.label, cfg.channel);
restindx = setdiff(1:length(data.label),dataindx);
if ~isempty(restindx)
fprintf('removing %d non-MEG channels from the data\n', length(restindx));
rest.label = data.label(restindx); % first remember the rest
data.label = data.label(dataindx); % then reduce the data
for i=1:Ntrials
rest.trial{i} = data.trial{i}(restindx,:); % first remember the rest
data.trial{i} = data.trial{i}(dataindx,:); % then reduce the data
end
else
rest.label = {};
rest.trial = {};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the average template gradiometer array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Ntemplate = length(cfg.template);
for i=1:Ntemplate
if ischar(cfg.template{i}),
fprintf('reading template sensor position from %s\n', cfg.template{i});
template(i) = ft_read_sens(cfg.template{i});
elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'coilpos') && isfield(cfg.template{i}, 'coilori') && isfield(cfg.template{i}, 'tra'),
template(i) = cfg.template{i};
elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'pnt') && isfield(cfg.template{i}, 'ori') && isfield(cfg.template{i}, 'tra'),
% it seems to be a pre-2011v1 type gradiometer structure, update it
template(i) = ft_datatype_sens(cfg.template{i});
else
error('unrecognized template input');
end
end
grad = ft_average_sens(template);
% construct the final template gradiometer definition
template = [];
template.grad = grad;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the
% volume model labels (in case of a localspheres model) and result in a gradiometer
% definition that only contains the gradiometers that are present in the data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
volcfg = [];
if isfield(cfg, 'hdmfile')
volcfg.hdmfile = cfg.hdmfile;
elseif isfield(cfg, 'vol')
volcfg.vol = cfg.vol;
end
volcfg.grad = data.grad;
volcfg.channel = data.label; % this might be a subset of the MEG channels
gradorig = data.grad; % this is needed later on for plotting. As of
% yet the next step is not entirely correct, because it does not keep track
% of the balancing of the gradiometer array. FIXME this may require some
% thought because the leadfields are computed with low level functions and
% do not easily accommodate for matching the correct channels with each
% other (in order to compute the projection matrix).
[volold, data.grad] = prepare_headmodel(volcfg);
% note that it is neccessary to keep the two volume conduction models
% seperate, since the single-shell Nolte model contains gradiometer specific
% precomputed parameters. Note that this is not guaranteed to result in a
% good projection for local sphere models.
volcfg.grad = template.grad;
volcfg.channel = 'MEG'; % include all MEG channels
[volnew, template.grad] = prepare_headmodel(volcfg);
if strcmp(ft_senstype(data.grad), ft_senstype(template.grad))
[id, it] = match_str(data.grad.label, template.grad.label);
fprintf('mean distance towards template gradiometers is %.2f %s\n', mean(sum((data.grad.chanpos(id,:)-template.grad.chanpos(it,:)).^2, 2).^0.5), template.grad.unit);
else
% the projection is from one MEG system to another MEG system, which makes a comparison of the data difficult
cfg.feedback = 'no';
cfg.verify = 'no';
end
% create the dipole grid on which the data will be projected
tmpcfg = [];
tmpcfg.vol = volold;
tmpcfg.grad = data.grad;
% copy all options that are potentially used in ft_prepare_sourcemodel
try, tmpcfg.grid = cfg.grid; end
try, tmpcfg.mri = cfg.mri; end
try, tmpcfg.headshape = cfg.headshape; end
try, tmpcfg.tightgrid = cfg.tightgrid; end
try, tmpcfg.symmetry = cfg.symmetry; end
try, tmpcfg.smooth = cfg.smooth; end
try, tmpcfg.threshold = cfg.threshold; end
try, tmpcfg.spheremesh = cfg.spheremesh; end
try, tmpcfg.inwardshift = cfg.inwardshift; end
try, tmpcfg.sourceunits = cfg.sourceunits; end
grid = ft_prepare_sourcemodel(tmpcfg);
pos = grid.pos;
% sometimes some of the dipole positions are nan, due to problems with the headsurface triangulation
% remove them to prevent problems with the forward computation
sel = find(any(isnan(pos(:,1)),2));
pos(sel,:) = [];
% compute the forward model for the new gradiometer positions
fprintf('computing forward model for %d dipoles\n', size(pos,1));
lfnew = ft_compute_leadfield(pos, template.grad, volnew);
if ~pertrial,
%this needs to be done only once
lfold = ft_compute_leadfield(pos, data.grad, volold);
[realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);
else
%the forward model and realignment matrices have to be computed for each trial
%this also goes for the singleshell volume conductor model
%x = which('rigidbodyJM'); %this function is needed
%if isempty(x),
% error('you are trying out experimental code for which you need some extra functionality which is currently not in the release version of fieldtrip. if you are interested in trying it out, contact jan-mathijs');
%end
end
% interpolate the data towards the template gradiometers
for i=1:Ntrials
fprintf('realigning trial %d\n', i);
if pertrial,
%warp the gradiometer array according to the motiontracking data
sel = match_str(rest.label, {'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'});
hmdat = rest.trial{i}(sel,:);
if ~all(hmdat==repmat(hmdat(:,1),[1 size(hmdat,2)]))
error('only one position per trial is at present allowed');
else
%M = rigidbodyJM(hmdat(:,1))
M = headcoordinates(hmdat(1:3,1),hmdat(4:6,1),hmdat(7:9,1));
grad = ft_transform_sens(M, data.grad);
end
volcfg.grad = grad;
%compute volume conductor
[volold, grad] = prepare_headmodel(volcfg);
%compute forward model
lfold = ft_compute_leadfield(pos, grad, volold);
%compute projection matrix
[realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);
end
data.realign{i} = realign * data.trial{i};
if strcmp(cfg.verify, 'yes')
% also compute the residual variance when interpolating
[id,it] = match_str(data.grad.label, template.grad.label);
rvrealign = rv(data.trial{i}(id,:), data.realign{i}(it,:));
fprintf('original -> template RV %.2f %%\n', 100 * mean(rvrealign));
datnoalign = noalign * data.trial{i};
datbkalign = bkalign * data.trial{i};
rvnoalign = rv(data.trial{i}, datnoalign);
rvbkalign = rv(data.trial{i}, datbkalign);
fprintf('original -> original RV %.2f %%\n', 100 * mean(rvnoalign));
fprintf('original -> template -> original RV %.2f %%\n', 100 * mean(rvbkalign));
end
end
% plot the topography before and after the realignment
if strcmp(cfg.feedback, 'yes')
warning('showing MEG topography (RMS value over time) in the first trial only');
Nchan = length(data.grad.label);
[id,it] = match_str(data.grad.label, template.grad.label);
pnt1 = data.grad.chanpos(id,:);
pnt2 = template.grad.chanpos(it,:);
prj1 = elproj(pnt1); tri1 = delaunay(prj1(:,1), prj1(:,2));
prj2 = elproj(pnt2); tri2 = delaunay(prj2(:,1), prj2(:,2));
switch cfg.topoparam
case 'rms'
p1 = sqrt(mean(data.trial{1}(id,:).^2, 2));
p2 = sqrt(mean(data.realign{1}(it,:).^2, 2));
case 'svd'
[u, s, v] = svd(data.trial{1}(id,:)); p1 = u(:,1);
[u, s, v] = svd(data.realign{1}(it,:)); p2 = u(:,1);
otherwise
error('unsupported cfg.topoparam');
end
X = [pnt1(:,1) pnt2(:,1)]';
Y = [pnt1(:,2) pnt2(:,2)]';
Z = [pnt1(:,3) pnt2(:,3)]';
% show figure with old an new helmets, volume model and dipole grid
figure
hold on
ft_plot_vol(volold);
plot3(grid.pos(:,1),grid.pos(:,2),grid.pos(:,3),'b.');
plot3(pnt1(:,1), pnt1(:,2), pnt1(:,3), 'r.') % original positions
plot3(pnt2(:,1), pnt2(:,2), pnt2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
view(-90, 90);
% show figure with data on old helmet location
figure
hold on
plot3(pnt1(:,1), pnt1(:,2), pnt1(:,3), 'r.') % original positions
plot3(pnt2(:,1), pnt2(:,2), pnt2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
axis equal; axis vis3d
bnd1 = [];
bnd1.pnt = pnt1;
bnd1.tri = tri1;
ft_plot_mesh(bnd1,'vertexcolor',p1,'edgecolor','none')
title('RMS, before realignment')
view(-90, 90)
% show figure with data on new helmet location
figure
hold on
plot3(pnt1(:,1), pnt1(:,2), pnt1(:,3), 'r.') % original positions
plot3(pnt2(:,1), pnt2(:,2), pnt2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
axis equal; axis vis3d
bnd2 = [];
bnd2.pnt = pnt2;
bnd2.tri = tri2;
ft_plot_mesh(bnd2,'vertexcolor',p2,'edgecolor','none')
title('RMS, after realignment')
view(-90, 90)
end
% store the realigned data in a new structure
interp.label = template.grad.label;
interp.grad = template.grad; % replace with the template gradiometer array
interp.trial = data.realign; % remember the processed data
interp.fsample = data.fsample;
interp.time = data.time;
% add the rest channels back to the data, these were not interpolated
if ~isempty(rest.label)
fprintf('adding %d non-MEG channels back to the data (', length(rest.label));
fprintf('%s, ', rest.label{1:end-1});
fprintf('%s)\n', rest.label{end});
for trial=1:length(rest.trial)
interp.trial{trial} = [interp.trial{trial}; rest.trial{trial}];
end
interp.label = [interp.label; rest.label];
end
% copy the trial specific information into the output
if isfield(data, 'trialinfo')
interp.trialinfo = data.trialinfo;
end
% copy the sampleinfo field as well
if isfield(data, 'sampleinfo')
interp.sampleinfo = data.sampleinfo;
end
% convert back to input type if necessary
switch dtype
case 'timelock'
interp = ft_checkdata(interp, 'datatype', 'timelock');
otherwise
% keep the output as it is
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
% rename the output variable to accomodate the savevar postamble
data = interp;
ft_postamble history data
ft_postamble savevar data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that computes the projection matrix(ces)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [realign, noalign, bkalign] = computeprojection(lfold, lfnew, pruneratio, verify)
% compute this inverse only once, although it is used twice
tmp = prunedinv(lfold, pruneratio);
% compute the three interpolation matrices
fprintf('computing interpolation matrix #1\n');
realign = lfnew * tmp;
if strcmp(verify, 'yes')
fprintf('computing interpolation matrix #2\n');
noalign = lfold * tmp;
fprintf('computing interpolation matrix #3\n');
bkalign = lfold * prunedinv(lfnew, pruneratio) * realign;
else
noalign = [];
bkalign = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that computes the inverse using a pruned SVD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lfi] = prunedinv(lf, r)
[u, s, v] = svd(lf);
if r<1,
% treat r as a ratio
p = find(s<(s(1,1)*r) & s~=0);
else
% treat r as the number of spatial components to keep
diagels = 1:(min(size(s))+1):(min(size(s)).^2);
p = diagels((r+1):end);
end
fprintf('pruning %d from %d, i.e. removing the %d smallest spatial components\n', length(p), min(size(s)), length(p));
s(p) = 0;
s(find(s~=0)) = 1./s(find(s~=0));
lfi = v * s' * u';
|
github
|
philippboehmsturm/antx-master
|
ft_volumelookup.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_volumelookup.m
| 11,852 |
utf_8
|
916f8874426446763ab71bbde375fd7b
|
function [output] = ft_volumelookup(cfg, volume)
% FT_VOLUMELOOKUP can be used in to combine an anatomical or functional
% atlas with source recunstruction. You can use it for forward and reverse
% lookup.
%
% Given the anatomical or functional label, it looks up the locations and
% creates a mask (as a binary volume) based on the label, or creates a
% sphere or box around a point of interest. In this case the function is to
% be used as:
% mask = ft_volumelookup(cfg, volume)
%
% Given a binary volume that indicates a region of interest, it looks up
% the corresponding anatomical or functional labels from a given atlas. In
% this case the function is to be used as follows:
% labels = ft_volumelookup(cfg, volume)
%
% In both cases the input volume can be:
% mri is the output of FT_READ_MRI
% source is the output of FT_SOURCEANALYSIS
% stat is the output of FT_SOURCESTATISTICS
%
% The configuration options for a mask according to an atlas:
% cfg.inputcoord = 'mni' or 'tal', coordinate system of the mri/source/stat
% cfg.atlas = string, filename of atlas to use, either the AFNI
% brik file that is available from http://afni.nimh.nih.gov/afni/doc/misc/ttatlas_tlrc,
% or the WFU atlasses available from http://fmri.wfubmc.edu. see FT_PREPARE_ATLAS
% cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas
%
% The configuration options for a spherical/box mask around a point of interest:
% cfg.roi = Nx3 vector, coordinates of the points of interest
% cfg.sphere = radius of each sphere in cm/mm dep on unit of input
% cfg.box = Nx3 vector, size of each box in cm/mm dep on unit of input
% cfg.round2nearestvoxel = 'yes' or 'no' (default = 'no'), voxel closest to point of interest is calculated
% and box/sphere is centered around coordinates of that voxel
%
% The configuration options for labels from a mask:
% cfg.inputcoord = 'mni' or 'tal', coordinate system of the mri/source/stat
% cfg.atlas = string, filename of atlas to use, either the AFNI
% brik file that is available from http://afni.nimh.nih.gov/afni/doc/misc/ttatlas_tlrc,
% or the WFU atlasses available from http://fmri.wfubmc.edu. see FT_PREPARE_ATLAS
% cfg.maskparameter = string, field in volume to be lookedup, data in field should be logical
% cfg.maxqueryrange = number, should be 1, 3, 5 (default = 1)
%
% The label output has a field "names", a field "count" and a field "usedqueryrange"
% To get a list of areas of the given mask you can do for instance:
% [tmp ind] = sort(labels.count,1,'descend');
% sel = find(tmp);
% for j = 1:length(sel)
% found_areas{j,1} = [num2str(labels.count(ind(j))) ': ' labels.name{ind(j)}];
% end
% in found_areas you can then see how many times which labels are found
% NB in the AFNI brick one location can have 2 labels!
%
% Dependent on the input coordinates and the coordinates of the atlas, the
% input MRI is transformed betweem MNI and Talairach-Tournoux coordinates
% See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details.
%
% See also FT_PREPARE_ATLAS, FT_SOURCEPLOT
% Copyright (C) 2008, Robert Oostenveld, Ingrid Nieuwenhuis
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_volumelookup.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_volumelookup.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar volume
% the handling of the default cfg options is done further down
% the checking of the input data is done further down
cfg.maxqueryrange = ft_getopt(cfg,'maxqueryrange', 1);
roi2mask = 0;
mask2label = 0;
if isfield(cfg, 'roi');
roi2mask = 1;
elseif isfield(cfg, 'maskparameter')
mask2label = 1;
else
error('either specify cfg.roi, or cfg.maskparameter')
end
if roi2mask
% only for volume data
volume = ft_checkdata(volume, 'datatype', 'volume');
cfg.round2nearestvoxel = ft_getopt(cfg, 'round2nearestvoxel', 'no');
isatlas = iscell(cfg.roi) || ischar(cfg.roi);
ispoi = isnumeric(cfg.roi);
if isatlas+ispoi ~= 1
error('do not understand cfg.roi')
end
if isatlas
ft_checkconfig(cfg, 'forbidden', {'sphere' 'box'}, ...
'required', {'atlas' 'inputcoord'});
elseif ispoi
ft_checkconfig(cfg, 'forbidden', {'atlas' 'inputcoord'});
if isempty(ft_getopt(cfg, 'sphere')) && isempty(ft_getopt(cfg, 'box'))
% either needs to be there
error('either specify cfg.sphere or cfg.box')
end
end
elseif mask2label
% convert to source representation (easier to work with)
volume = ft_checkdata(volume, 'datatype', 'source');
ft_checkconfig(cfg, 'required', {'atlas' 'inputcoord'});
if isempty(intersect(cfg.maxqueryrange, [1 3 5]))
error('incorrect query range, should be one of [1 3 5]');
end
end
if roi2mask
% determine location of each anatomical voxel in its own voxel coordinates
dim = volume.dim;
i = 1:dim(1);
j = 1:dim(2);
k = 1:dim(3);
[I, J, K] = ndgrid(i, j, k);
ijk = [I(:) J(:) K(:) ones(prod(dim),1)]';
% determine location of each anatomical voxel in head coordinates
xyz = volume.transform * ijk; % note that this is 4xN
if isatlas
atlas = ft_prepare_atlas(cfg);
if ischar(cfg.roi)
cfg.roi = {cfg.roi};
end
sel = [];
for i = 1:length(cfg.roi)
sel = [sel; strmatch(cfg.roi{i}, atlas.descr.name, 'exact')];
end
fprintf('found %d matching anatomical labels\n', length(sel));
brick = atlas.descr.brick(sel);
value = atlas.descr.value(sel);
% convert between MNI head coordinates and TAL head coordinates
% coordinates should be expressed compatible with the atlas
if strcmp(cfg.inputcoord, 'mni') && strcmp(atlas.coord, 'tal')
xyz(1:3,:) = mni2tal(xyz(1:3,:));
elseif strcmp(cfg.inputcoord, 'mni') && strcmp(atlas.coord, 'mni')
% nothing to do
elseif strcmp(cfg.inputcoord, 'tal') && strcmp(atlas.coord, 'tal')
% nothing to do
elseif strcmp(cfg.inputcoord, 'tal') && strcmp(atlas.coord, 'mni')
xyz(1:3,:) = tal2mni(xyz(1:3,:));
end
% determine location of each anatomical voxel in atlas voxel coordinates
ijk = inv(atlas.transform) * xyz;
ijk = round(ijk(1:3,:))';
inside_vol = ijk(:,1)>=1 & ijk(:,1)<=atlas.dim(1) & ...
ijk(:,2)>=1 & ijk(:,2)<=atlas.dim(2) & ...
ijk(:,3)>=1 & ijk(:,3)<=atlas.dim(3);
inside_vol = find(inside_vol);
% convert the selection inside the atlas volume into linear indices
ind = sub2ind(atlas.dim, ijk(inside_vol,1), ijk(inside_vol,2), ijk(inside_vol,3));
brick0_val = zeros(prod(dim),1);
brick1_val = zeros(prod(dim),1);
% search the two bricks for the value of each voxel
brick0_val(inside_vol) = atlas.brick0(ind);
brick1_val(inside_vol) = atlas.brick1(ind);
mask = zeros(prod(dim),1);
for i=1:length(sel)
fprintf('constructing mask for %s\n', atlas.descr.name{sel(i)});
if brick(i)==0
mask = mask | (brick0_val==value(i));
elseif brick(i)==1
mask = mask | (brick1_val==value(i));
end
end
elseif ispoi
if istrue(cfg.round2nearestvoxel)
for i=1:size(cfg.roi,1)
cfg.roi(i,:) = poi2voi(cfg.roi(i,:), xyz);
end
end
% sphere(s)
if isfield(cfg, 'sphere')
mask = zeros(1,prod(dim));
for i=1:size(cfg.roi,1)
dist = sqrt( (xyz(1,:) - cfg.roi(i,1)).^2 + (xyz(2,:) - cfg.roi(i,2)).^2 + (xyz(3,:) - cfg.roi(i,3)).^2 );
mask = mask | (dist <= cfg.sphere(i));
end
% box(es)
elseif isfield(cfg, 'box')
mask = zeros(1, prod(dim));
for i=1:size(cfg.roi,1)
mask = mask | ...
(xyz(1,:) <= (cfg.roi(i,1) + cfg.box(i,1)./2) & xyz(1,:) >= (cfg.roi(i,1) - cfg.box(i,1)./2)) & ...
(xyz(2,:) <= (cfg.roi(i,2) + cfg.box(i,2)./2) & xyz(2,:) >= (cfg.roi(i,2) - cfg.box(i,2)./2)) & ...
(xyz(3,:) <= (cfg.roi(i,3) + cfg.box(i,3)./2) & xyz(3,:) >= (cfg.roi(i,3) - cfg.box(i,3)./2));
end
end
end
mask = reshape(mask, dim);
fprintf('%i voxels in mask, which is %.3f %% of total volume\n', sum(mask(:)), 100*mean(mask(:)));
output = mask;
elseif mask2label
atlas = ft_prepare_atlas(cfg.atlas);
sel = find(volume.(cfg.maskparameter)(:));
labels.name = atlas.descr.name;
labels.name{end+1} = 'no_label_found';
labels.count = zeros(length(labels.name),1);
for iLab = 1:length(labels.name)
labels.usedqueryrange{iLab} = [];
end
for iVox = 1:length(sel)
usedQR = 1;
label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 1);
if isempty(label) && cfg.maxqueryrange > 1
label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 3);
usedQR = 3;
end
if isempty(label) && cfg.maxqueryrange > 3
label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 5);
usedQR = 5;
end
if isempty(label)
label = {'no_label_found'};
elseif length(label) == 1
label = {label};
end
ind_lab = [];
for iLab = 1:length(label)
ind_lab = [ind_lab find(strcmp(label{iLab}, labels.name))];
end
labels.count(ind_lab) = labels.count(ind_lab) + (1/length(ind_lab));
for iFoundLab = 1:length(ind_lab)
if isempty(labels.usedqueryrange{ind_lab(iFoundLab)})
labels.usedqueryrange{ind_lab(iFoundLab)} = usedQR;
else
labels.usedqueryrange{ind_lab(iFoundLab)} = [labels.usedqueryrange{ind_lab(iFoundLab)} usedQR];
end
end
end %iVox
output = labels;
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION point of interest to voxel of interest
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function voi = poi2voi(poi, xyz)
xmin = min(abs(xyz(1,:) - poi(1))); xcl = round(abs(xyz(1,:) - poi(1))) == round(xmin);
ymin = min(abs(xyz(2,:) - poi(2))); ycl = round(abs(xyz(2,:) - poi(2))) == round(ymin);
zmin = min(abs(xyz(3,:) - poi(3))); zcl = round(abs(xyz(3,:) - poi(3))) == round(zmin);
xyzcls = xcl + ycl + zcl; ind_voi = xyzcls == 3;
if sum(ind_voi) > 1;
fprintf('%i voxels at same distance of poi, taking first voxel\n', sum(ind_voi))
ind_voi_temp = find(ind_voi); ind_voi_temp = ind_voi_temp(1);
ind_voi = zeros(size(ind_voi));
ind_voi(ind_voi_temp) = 1;
ind_voi = logical(ind_voi);
end
voi = xyz(1:3,ind_voi);
fprintf('coordinates of voi: %.1f %.1f %.1f\n', voi(1), voi(2), voi(3));
|
github
|
philippboehmsturm/antx-master
|
ft_multiplotTFR.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_multiplotTFR.m
| 29,967 |
utf_8
|
539fb58a4046a8166a5781efb53b569c
|
function [cfg] = ft_multiplotTFR(cfg, data)
% FT_MULTIPLOTTFR plots time-frequency representations of power or
% coherence in a topographical layout. The plots of the indivual sensors
% are arranged according to their location specified in the layout.
%
% Use as
% ft_multiplotTFR(cfg, data)
%
% The data can be a time-frequency representation of power or coherence
% that was computed using the FT_FREQANALYSIS or FT_FREQDESCRIPTIVES
% functions.
%
% The configuration can have the following parameters:
% cfg.parameter = field to be represented as color (default depends on data.dimord)
% 'powspctrm' or 'cohspctrm'
% cfg.maskparameter = field in the data to be used for opacity masking of data
% cfg.maskstyle = style used to masking, 'opacity' or 'saturation' (default = 'opacity')
% use 'saturation' when saving to vector-format (like *.eps) to avoid all
% sorts of image-problems (currently only possible with a white backgroud)
% cfg.maskalpha = alpha value used for masking areas dictated by cfg.maskparameter (0 - 1, default = 1)
% cfg.masknans = 'yes' or 'no' (default = 'yes')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.zlim = 'maxmin','maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display
% cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE
% cfg.baselinetype = 'absolute', 'relative' or 'relchange' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.box = 'yes', 'no' (default = 'no' if maskparameter given default = 'yes')
% Draw a box around each graph
% cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment
% cfg.colorbar = 'yes', 'no' (default = 'no')
% cfg.colormap = any sized colormap, see COLORMAP
% cfg.comment = string of text (default = date + zlimits)
% Add 'comment' to graph (according to COMNT in the layout)
% cfg.showlabels = 'yes', 'no' (default = 'no')
% cfg.showoutline = 'yes', 'no' (default = 'no')
% cfg.fontsize = font size of comment and labels (if present) (default = 8)
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.directionality = '', 'inflow' or 'outflow' specifies for
% connectivity measures whether the inflow into a
% node, or the outflow from a node is plotted. The
% (default) behavior of this option depends on the dimor
% of the input data (see below).
% cfg.layout = specify the channel layout for plotting using one of
% the supported ways (see below).
%
% For the plotting of directional connectivity data the cfg.directionality
% option determines what is plotted. The default value and the supported
% functionality depend on the dimord of the input data. If the input data
% is of dimord 'chan_chan_XXX', the value of directionality determines
% whether, given the reference channel(s), the columns (inflow), or rows
% (outflow) are selected for plotting. In this situation the default is
% 'inflow'. Note that for undirected measures, inflow and outflow should
% give the same output. If the input data is of dimord 'chancmb_XXX', the
% value of directionality determines whether the rows in data.labelcmb are
% selected. With 'inflow' the rows are selected if the refchannel(s) occur in
% the right column, with 'outflow' the rows are selected if the
% refchannel(s) occur in the left column of the labelcmb-field. Default in
% this case is '', which means that all rows are selected in which the
% refchannel(s) occur. This is to robustly support linearly indexed
% undirected connectivity metrics. In the situation where undirected
% connectivity measures are linearly indexed, specifying 'inflow' or
% 'outflow' can result in unexpected behavior.
%
% The layout defines how the channels are arranged and what the size of each
% subplot is. You can specify the layout in a variety of ways:
% - you can provide a pre-computed layout structure (see ft_prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure (common for MEG data, since the header
% of the MEG datafile contains the gradiometer information), that will be
% used for creating a layout. If you want to have more fine-grained control
% over the layout of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the
% data should be provided as a cell array.
%
% See also:
% FT_MULTIPLOTER, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR,
% FT_PREPARE_LAYOUT
% Undocumented local options:
% cfg.channel
% cfg.layoutname
%
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype, documented
% Copyright (C) 2003-2006, Ole Jensen
% Copyright (C) 2007-2011, Roemer van der Meij & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_multiplotTFR.m 7398 2013-01-23 15:50:59Z jorhor $
revision = '$Id: ft_multiplotTFR.m 7398 2013-01-23 15:50:59Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar data
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'freq');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam', 'yparam'});
% set the defaults
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.magscale = ft_getopt(cfg, 'magscale', 1);
cfg.gradscale = ft_getopt(cfg, 'gradscale', 1);
cfg.colorbar = ft_getopt(cfg, 'colorbar', 'no');
cfg.comment = ft_getopt(cfg, 'comment', date);
cfg.showlabels = ft_getopt(cfg, 'showlabels', 'no');
cfg.showoutline = ft_getopt(cfg, 'showoutline', 'no');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []); % let matlab decide on default
cfg.maskalpha = ft_getopt(cfg, 'maskalpha', 1);
cfg.masknans = ft_getopt(cfg, 'masknans', 'yes');
cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []);
cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'opacity');
cfg.directionality = ft_getopt(cfg, 'directionality', '');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.figurename = ft_getopt(cfg, 'figurename', []);
if ~isfield(cfg,'box')
if ~isempty(cfg.maskparameter)
cfg.box = 'yes';
else
cfg.box = 'no';
end
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
% Set x/y/parameter defaults
if ~any(ismember(dimtok, 'time'))
error('input data needs a time dimension');
else
xparam = 'time';
yparam = 'freq';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
end
if isfield(cfg, 'channel') && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% perform channel selection but only allow this when cfg.interactive = 'no'
if isfield(data, 'label') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, data.label);
elseif isfield(data, 'labelcmb') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = any(ismember(dimtok, {'rpt' 'subj'}));
if hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
if isfield(data, 'crsspctrm'),
data = rmfield(data, 'crsspctrm');
end
% keep mask-parameter if it is set
if ~isempty(cfg.maskparameter)
tempmask = data.(cfg.maskparameter);
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = data.dimord;
tempdata.freq = data.freq;
tempdata.label = data.label;
tempdata.powspctrm = data.(cfg.parameter);
tempdata.cfg = data.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
data.(cfg.parameter) = tempdata.powspctrm;
clear tempdata
else
data = ft_freqdescriptives(tmpcfg, data);
end
% put mask-parameter back if it is set
if ~isempty(cfg.maskparameter)
data.(cfg.maskparameter) = tempmask;
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
end % if hasrpt
% Read or create the layout that will be used for plotting:
clf;
hold on
lay = ft_prepare_layout(cfg, data);
cfg.layout = lay;
% Apply baseline correction:
if ~strcmp(cfg.baseline, 'no')
% keep mask-parameter if it is set
if ~isempty(cfg.maskparameter)
tempmask = data.(cfg.maskparameter);
end
data = ft_freqbaseline(cfg, data);
% put mask-parameter back if it is set
if ~isempty(cfg.maskparameter)
data.(cfg.maskparameter) = tempmask;
end
end
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb
haslabelcmb = isfield(data, 'labelcmb');
if (isfull || haslabelcmb) && isfield(data, cfg.parameter)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if haslabelcmb
cfg.refchannel = ft_channelselection(cfg.refchannel, unique(data.labelcmb(:)));
else
cfg.refchannel = ft_channelselection(cfg.refchannel, data.label);
end
if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
% Open a single figure with the channel layout, the user can click on a reference channel
h = clf;
ft_plot_lay(lay, 'box', false);
title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(h, info);
%set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
return
end
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.directionality)
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'inflow')
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter);
if length(sel1)+length(sel2)==0
error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality');
end
data.(cfg.parameter) = data.(cfg.parameter)([sel1;sel2],:,:);
data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)];
data.labelcmb = data.labelcmb([sel1;sel2],:);
data = rmfield(data, 'labelcmb');
else
% General case
sel = match_str(data.label, cfg.refchannel);
siz = [size(data.(cfg.parameter)) 1];
if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%in FieldTrip the row index 'causes' the column index channel
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.directionality, 'outflow')
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.directionality, 'ff-fd')
error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotTFR');
elseif strcmp(cfg.directionality, 'fd-ff')
error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotTFR');
end %if directionality
end %if ~isfull
end %handle the bivariate data
% Get physical x-axis range:
if strcmp(cfg.xlim,'maxmin')
xmin = min(data.(xparam));
xmax = max(data.(xparam));
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(xparam)
xmin = nearest(data.(xparam), xmin);
xmax = nearest(data.(xparam), xmax);
end
% Get physical y-axis range:
if strcmp(cfg.ylim,'maxmin')
ymin = min(data.(yparam));
ymax = max(data.(yparam));
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(yparam)
ymin = nearest(data.(yparam), ymin);
ymax = nearest(data.(yparam), ymax);
end
% test if X and Y are linearly spaced (to within 10^-12): % FROM UIMAGE
x = data.(xparam)(xmin:xmax);
y = data.(yparam)(ymin:ymax);
dx = min(diff(x)); % smallest interval for X
dy = min(diff(y)); % smallest interval for Y
evenx = all(abs(diff(x)/dx-1)<1e-12); % true if X is linearly spaced
eveny = all(abs(diff(y)/dy-1)<1e-12); % true if Y is linearly spaced
if ~evenx || ~eveny
warning('(one of the) axis is/are not evenly spaced, but plots are made as if axis are linear')
end
% Take subselection of channels, this only works
% in the interactive mode
if exist('selchannel', 'var')
sellab = match_str(data.label, selchannel);
label = data.label(sellab);
else
sellab = 1:numel(data.label);
label = data.label;
end
dat = data.(cfg.parameter);
% get dimord dimensions
dims = textscan(data.dimord,'%s', 'Delimiter', '_');
dims = dims{1};
ydim = find(strcmp(yparam, dims));
xdim = find(strcmp(xparam, dims));
zdim = setdiff(1:ndims(dat), [ydim xdim]);
% and permute
dat = permute(dat, [zdim(:)' ydim xdim]);
if isfull
dat = dat(sel1, sel2, ymin:ymax, xmin:xmax);
dat = nanmean(dat, meandir);
siz = size(dat);
dat = reshape(dat, [max(siz(1:2)) siz(3) siz(4)]);
dat = dat(sellab, :, :);
% this makes no sense, so COMMENTED OUT AS OF FEBURARY 22 2012
% elseif haslabelcmb
% dat = dat(sellab, ymin:ymax, xmin:xmax);
else
dat = dat(sellab, ymin:ymax, xmin:xmax);
end
if ~isempty(cfg.maskparameter)
mask = data.(cfg.maskparameter);
mask = permute(mask, [zdim(:)' ydim xdim]);
if isfull && cfg.maskalpha == 1
mask = mask(sel1, sel2, ymin:ymax, xmin:xmax);
mask = nanmean(nanmean(nanmean(mask, meandir), 4), 3);
elseif haslabelcmb && cfg.maskalpha == 1
mask = mask(sellab, ymin:ymax, xmin:xmax);
%mask = nanmean(nanmean(mask, 3), 2);
elseif cfg.maskalpha == 1
mask = mask(sellab, ymin:ymax, xmin:xmax);
%mask = nanmean(nanmean(mask, 3), 2);
elseif isfull && cfg.maskalpha ~= 1
maskl = mask(sel1, sel2, ymin:ymax, xmin:xmax); %% check this for full representation
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif haslabelcmb && cfg.maskalpha ~= 1
maskl = mask(sellab, ymin:ymax, xmin:xmax);
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif cfg.maskalpha ~= 1
maskl = mask(sellab, ymin:ymax, xmin:xmax);
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
end
end
% Select the channels in the data that match with the layout:
[chanseldat, chansellay] = match_str(label, lay.label);
if isempty(chanseldat)
error('labels in data and labels in layout do not match');
end
% if magnetometer/gradiometer scaling is requested, get indices for
% channels
if (cfg.magscale ~= 1)
magInd = match_str(label, ft_channelselection('MEGMAG', label));
end
if (cfg.gradscale ~= 1)
gradInd = match_str(label, ft_channelselection('MEGGRAD', label));
end
datsel = dat(chanseldat,:,:);
if ~isempty(cfg.maskparameter)
maskdat = mask(chanseldat,:,:);
end
% Select x and y coordinates and labels of the channels in the data
chanX = lay.pos(chansellay, 1);
chanY = lay.pos(chansellay, 2);
chanWidth = lay.width(chansellay);
chanHeight = lay.height(chansellay);
% Get physical z-axis range (color axis):
if strcmp(cfg.zlim,'maxmin')
zmin = min(datsel(:));
zmax = max(datsel(:));
elseif strcmp(cfg.zlim,'maxabs')
zmin = -max(abs(datsel(:)));
zmax = max(abs(datsel(:)));
else
zmin = cfg.zlim(1);
zmax = cfg.zlim(2);
end
% set colormap
if isfield(cfg,'colormap')
if size(cfg.colormap,2)~=3, error('multiplotTFR(): Colormap must be a n x 3 matrix'); end
set(gcf,'colormap',cfg.colormap);
end;
% Plot channels:
for k=1:length(chanseldat)
% Get cdata:
cdata = squeeze(datsel(k,:,:));
if ~isempty(cfg.maskparameter)
mdata = squeeze(maskdat(k,:,:));
end
% scale if needed
if (cfg.magscale ~= 1 && any(magInd == chanseldat(k)))
cdata = cdata .* cfg.magscale;
end
if (cfg.gradscale ~= 1 && any(gradInd == chanseldat(k)))
cdata = cdata .* cfg.gradscale;
end
% Draw plot (and mask Nan's with maskfield if requested)
if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter)
nans_mask = ~isnan(cdata);
mask = double(nans_mask);
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask, 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k))
elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter)
nans_mask = ~isnan(cdata);
mask = nans_mask .* mdata;
mask = double(mask);
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask, 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k))
elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter)
mask = mdata;
mask = double(mask);
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask, 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k))
else
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip', 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k))
end
% Currently the handle isn't being used below, this is here for possible use in the future
h = findobj('tag','cip');
end
% write comment:
k = cellstrmatch('COMNT',lay.label);
if ~isempty(k)
comment = cfg.comment;
comment = sprintf('%0s\nxlim=[%.3g %.3g]', comment, data.(xparam)(xmin), data.(xparam)(xmax));
comment = sprintf('%0s\nylim=[%.3g %.3g]', comment, data.(yparam)(ymin), data.(yparam)(ymax));
comment = sprintf('%0s\nzlim=[%.3g %.3g]', comment, zmin, zmax);
ft_plot_text(lay.pos(k,1), lay.pos(k,2), sprintf(comment), 'Fontsize', cfg.fontsize);
end
% plot scale:
k = cellstrmatch('SCALE',lay.label);
if ~isempty(k)
% Get average cdata across channels:
cdata = squeeze(mean(datsel, 1));
% Draw plot (and mask Nan's with maskfield if requested)
if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter)
mask = ~isnan(cdata);
mask = double(mask);
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask, 'hpos', lay.pos(k,1), 'vpos', lay.pos(k,2), 'width', lay.width(k,1), 'height', lay.height(k,1))
elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter)
mask = ~isnan(cdata);
mask = mask .* mdata;
mask = double(mask);
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask, 'hpos', lay.pos(k,1), 'vpos', lay.pos(k,2), 'width', lay.width(k,1), 'height', lay.height(k,1))
elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter)
mask = mdata;
mask = double(mask);
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask, 'hpos', lay.pos(k,1), 'vpos', lay.pos(k,2), 'width', lay.width(k,1), 'height', lay.height(k,1))
else
ft_plot_matrix(cdata,'clim',[zmin zmax],'tag','cip', 'hpos', lay.pos(k,1), 'vpos', lay.pos(k,2), 'width', lay.width(k,1), 'height', lay.height(k,1))
end
% Currently the handle isn't being used below, this is here for possible use in the future
h = findobj('tag','cip');
end
% plot layout
boxflg = istrue(cfg.box);
labelflg = istrue(cfg.showlabels);
outlineflg = istrue(cfg.showoutline);
ft_plot_lay(lay, 'box', boxflg, 'label',labelflg, 'outline', outlineflg, 'point','no', 'mask', 'no');
% plot colorbar:
if isfield(cfg, 'colorbar') && (strcmp(cfg.colorbar, 'yes'))
colorbar;
end
% Set colour axis
caxis([zmin zmax]);
if strcmp('yes',cfg.hotkeys)
% Attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax})
end
% set the figure window title
if isfield(cfg,'funcname')
funcname = cfg.funcname;
else
funcname = mfilename;
end
if isfield(cfg,'dataname')
dataname = cfg.dataname;
elseif nargin > 1
dataname = inputname(2);
else % data provided through cfg.inputfile
dataname = cfg.inputfile;
end
if isempty(cfg.figurename)
set(gcf, 'Name', sprintf('%d: %s: %s', gcf, funcname, dataname));
set(gcf, 'NumberTitle', 'off');
else
set(gcf, 'name', cfg.figurename);
set(gcf, 'NumberTitle', 'off');
end
% Make the figure interactive:
if strcmp(cfg.interactive, 'yes')
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
info.dataname = dataname;
guidata(gcf, info);
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
end
axis tight
axis off
orient landscape
hold off
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function l = cellstrmatch(str,strlist)
l = [];
for k=1:length(strlist)
if strcmp(char(str),char(strlist(k)))
l = [l k];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called by ft_select_channel in case cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_multiplotTFR(label, cfg, varargin)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
% put data name in here, this cannot be resolved by other means
info = guidata(gcf);
cfg.dataname = info.dataname;
cfg.refchannel = label;
fprintf('selected cfg.refchannel = ''%s''\n', join_str(',', cfg.refchannel));
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_multiplotTFR(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotTFR(label, cfg, varargin)
if ~isempty(label)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
cfg.channel = label;
% make sure ft_singleplotTFR does not apply a baseline correction again
cfg.baseline = 'no';
% put data name in here, this cannot be resolved by other means
info = guidata(gcf);
cfg.dataname = info.dataname;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotTFR(cfg, varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
incr = (max(caxis)-min(caxis)) /10;
% symmetrically scale color bar down by 10 percent
if strcmp(eventdata.Key,'uparrow')
caxis([min(caxis)-incr max(caxis)+incr]);
% symmetrically scale color bar up by 10 percent
elseif strcmp(eventdata.Key,'downarrow')
caxis([min(caxis)+incr max(caxis)-incr]);
% resort to minmax of data for colorbar
elseif strcmp(eventdata.Key,'m')
caxis([varargin{1} varargin{2}]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_defaults.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_defaults.m
| 9,592 |
utf_8
|
ca5df74513e83b199c1f0ed30f718519
|
function ft_defaults
% FT_DEFAULTS (ending with "s") sets some general settings in the global variable
% ft_default (without the "s") and takes care of the required path settings. This
% function is called at the begin of all FieldTrip functions.
%
% The configuration defaults are stored in the global "ft_default" structure.
% The ft_checkconfig function that is called by many FieldTrip functions will
% merge this global ft_default structure with the cfg ctructure that you pass to
% the FieldTrip function that you are calling.
%
% The global options and their default values are
% ft_default.trackconfig string, can be cleanup, report, off (default = 'off')
% ft_default.checkconfig string, can be pedantic, loose, silent (default = 'loose')
% ft_default.checksize number in bytes, can be inf (default = 1e5)
% ft_default.showcallinfo string, can be yes or no (default = 'yes')
% ft_default.debug string, can be 'display', 'displayonerror', 'displayonsuccess',
% 'save', 'saveonerror', saveonsuccess' or 'no' (default = 'no')
%
% See also FT_HASTOOLBOX, FT_CHECKCONFIG
% Note that this should be a function and not a script, otherwise the
% ft_hastoolbox function appears not be found in fieldtrip/private.
% Copyright (C) 2009-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_defaults.m 7378 2013-01-23 12:36:49Z jorhor $
global ft_default
persistent initialized
% Set the defaults in a global variable, ft_checkconfig will copy these over into the local configuration.
% Note that ft_getopt might not be available on the path at this moment and can therefore not yet be used.
if ~isfield(ft_default, 'trackconfig'), ft_default.trackconfig = 'off'; end % cleanup, report, off
if ~isfield(ft_default, 'checkconfig'), ft_default.checkconfig = 'loose'; end % pedantic, loose, silent
if ~isfield(ft_default, 'checksize'), ft_default.checksize = 1e5; end % number in bytes, can be inf
if ~isfield(ft_default, 'showcallinfo'), ft_default.showcallinfo = 'no'; end % yes or no, this is used in ft_pre/postamble_provenance
if ~isfield(ft_default, 'debug'), ft_default.debug = 'no'; end % no, save, saveonerror, display, displayonerror, this is used in ft_pre/postamble_debug
% these options allow to disable parts of the provenance
if ~isfield(ft_default, 'trackcallinfo'), ft_default.trackcallinfo = 'no'; end % yes or no
if ~isfield(ft_default, 'trackdatainfo'), ft_default.trackdatainfo = 'no'; end % yes or no, this is still under development
if ~isfield(ft_default, 'trackparaminfo'), ft_default.trackparaminfo = 'no'; end % yes or no, this is still under development
% track whether we have executed ft_defaults already. Note that we should
% not use ft_default itself directly, because the user might have set stuff
% in that struct already before ft_defaults is called for the first time.
if initialized
return;
end
% Ensure that the path containing ft_defaults is on the path.
% This allows people to do "cd path_to_fieldtrip; ft_defaults"
ftPath = fileparts(mfilename('fullpath')); % get path, strip away 'ft_defaults'
ftPath = strrep(ftPath, '\', '\\');
if isempty(regexp(path, [ftPath pathsep '|' ftPath '$'], 'once'))
warning('FieldTrip is not yet on your MATLAB path, adding %s', ftPath);
addpath(ftPath);
end
% Some people mess up their path settings and then have
% different versions of certain toolboxes on the path.
% The following will issue a warning
checkMultipleToolbox('FieldTrip', 'ft_defaults.m');
checkMultipleToolbox('spm', 'spm.m');
checkMultipleToolbox('mne', 'fiff_copy_tree.m');
checkMultipleToolbox('eeglab', 'eeglab2fieldtrip.m');
checkMultipleToolbox('dipoli', 'write_tri.m');
checkMultipleToolbox('eeprobe', 'read_eep_avr.mexa64');
checkMultipleToolbox('yokogawa', 'GetMeg160ChannelInfoM.p');
checkMultipleToolbox('simbio', 'sb_compile_vista.m');
checkMultipleToolbox('fns', 'fns_region_read.m');
checkMultipleToolbox('bemcp', 'bem_Cii_cst.mexa64');
checkMultipleToolbox('bci2000', 'load_bcidat.m');
checkMultipleToolbox('openmeeg', 'openmeeg_helper.m');
checkMultipleToolbox('freesurfer', 'vox2ras_ksolve.m');
checkMultipleToolbox('fastica', 'fastica.m');
checkMultipleToolbox('besa', 'readBESAmul.m');
checkMultipleToolbox('neuroshare', 'ns_GetAnalogData.m');
checkMultipleToolbox('ctf', 'setCTFDataBalance.m');
checkMultipleToolbox('afni', 'WriteBrikHEAD.m');
checkMultipleToolbox('gifti', '@gifti/display.m');
checkMultipleToolbox('sqdproject', 'sqdread.m');
checkMultipleToolbox('xml4mat', 'xml2mat.m');
checkMultipleToolbox('cca', 'ccabss.m');
checkMultipleToolbox('bsmart', 'armorf.m');
checkMultipleToolbox('iso2mesh', 'iso2meshver.m');
checkMultipleToolbox('bct', 'degrees_und.m');
checkMultipleToolbox('yokogawa_meg_reader', 'getYkgwHdrEvent.p');
checkMultipleToolbox('biosig', 'sopen.m');
checkMultipleToolbox('icasso', 'icassoEst.m');
if ~isdeployed
if isempty(which('ft_hastoolbox'))
% the fieldtrip/utilities directory contains the ft_hastoolbox function
% which is required for the remainder of this script
addpath(fullfile(fileparts(which('ft_defaults')), 'utilities'));
end
try
% this directory contains the backward compatibility wrappers for the ft_xxx function name change
ft_hastoolbox('compat', 3, 1); % not required
end
try
% this directory contains the backward compatibility wrappers for the fieldtrip/utilities functions
ft_hastoolbox('utilities/compat', 3, 1);
end
try
% these contains template layouts, neighbour structures, MRIs and cortical meshes
ft_hastoolbox('template/layout', 1, 1);
ft_hastoolbox('template/anatomy', 1, 1);
ft_hastoolbox('template/headmodel', 1, 1);
ft_hastoolbox('template/electrode', 1, 1);
ft_hastoolbox('template/neighbours', 1, 1);
ft_hastoolbox('template/sourcemodel', 1, 1);
end
try
% this is used in statistics
ft_hastoolbox('statfun', 1, 1);
end
try
% this is used in definetrial
ft_hastoolbox('trialfun', 1, 1);
end
try
% this contains the low-level reading functions
ft_hastoolbox('fileio', 1, 1);
ft_hastoolbox('fileio/compat', 3, 1); % not required
end
try
% this is for filtering time-series data
ft_hastoolbox('preproc', 1, 1);
ft_hastoolbox('preproc/compat', 3, 1); % not required
end
try
% this contains forward models for the EEG and MEG volume conduction problem
ft_hastoolbox('forward', 1, 1);
ft_hastoolbox('forward/compat', 3, 1); % not required
end
try
% numerous functions depend on this module
ft_hastoolbox('inverse', 1, 1);
end
try
% this contains intermediate-level plotting functions, e.g. multiplots and 3-d objects
ft_hastoolbox('plotting', 1, 1);
ft_hastoolbox('plotting/compat', 1, 1);
end
try
% this contains the functions to compute connecitivy metrics
ft_hastoolbox('connectivity', 1,1);
end
try
% this contains the functions for spike and spike-field analysis
ft_hastoolbox('spike', 1,1);
end
try
% this contains specific code and examples for realtime processing
ft_hastoolbox('realtime/example', 3, 1); % not required
ft_hastoolbox('realtime/online_mri', 3, 1); % not required
ft_hastoolbox('realtime/online_meg', 3, 1); % not required
ft_hastoolbox('realtime/online_eeg', 3, 1); % not required
end
try
% this contains intermediate-level functions for spectral analysis
ft_hastoolbox('specest', 1, 1);
end
end
% remember that the function has executed in a persistent variable
initialized = true;
end % function ft_default
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function checkMultipleToolbox(toolbox, keyfile)
list = which(keyfile, '-all');
if length(list)>1
[ws, warned] = warning_once(sprintf('Multiple versions of %s on your path will confuse FieldTrip', toolbox));
if warned % only throw the warning once
for i=1:length(list)
warning('one version of %s is found here: %s', toolbox, list{i});
end
end
warning_once('You probably used addpath(genpath(''path_to_fieldtrip'')), this can lead to unexpected behaviour. See http://fieldtrip.fcdonders.nl/faq/should_i_add_fieldtrip_with_all_subdirectories_to_my_matlab_path');
end
end % function checkMultipleToolbox
|
github
|
philippboehmsturm/antx-master
|
ft_prepare_neighbours.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_prepare_neighbours.m
| 12,121 |
utf_8
|
246abb4a5696ac99d7b95ab9afa6585c
|
function [neighbours, cfg] = ft_prepare_neighbours(cfg, data)
% FT_PREPARE_NEIGHBOURS finds the neighbours of the channels based on three
% different methods. Using the 'distance'-method, prepare_neighbours is
% based on a minimum neighbourhood distance (in cfg.neighbourdist). The
% 'triangulation'-method calculates a triangulation based on a
% two-dimenstional projection of the sensor position. The 'template'-method
% loads a default template for the given data type. prepare_neighbours
% should be verified using cfg.feedback ='yes' or by calling
% ft_neighbourplot
%
% The positions of the channel are specified in a gradiometer or electrode configuration or
% from a layout. The sensor configuration can be passed into this function in three ways:
% (1) in a configuration field,
% (2) in a file whose name is passed in a configuration field, and that can be imported using FT_READ_SENS, or
% (3) in a data field.
%
% Use as
% neighbours = ft_prepare_neighbours(cfg, data)
%
% The configuration can contain
% cfg.method = 'distance', 'triangulation' or 'template' (default = 'distance')
% cfg.neighbourdist = number, maximum distance between neighbouring sensors (only for 'distance')
% cfg.template = name of the template file, e.g. CTF275_neighb.mat
% cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT
% cfg.channel = channels for which neighbours should be found
% cfg.feedback = 'yes' or 'no' (default = 'no')
%
% The EEG or MEG sensor positions can be present in the data or can be specified as
% cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS
% cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS
% cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS
% cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS
%
% The output is an array of structures with the "neighbours" which is
% structured like this:
% neighbours(1).label = 'Fz';
% neighbours(1).neighblabel = {'Cz', 'F3', 'F3A', 'FzA', 'F4A', 'F4'};
% neighbours(2).label = 'Cz';
% neighbours(2).neighblabel = {'Fz', 'F4', 'RT', 'RTP', 'P4', 'Pz', 'P3', 'LTP', 'LT', 'F3'};
% neighbours(3).label = 'Pz';
% neighbours(3).neighblabel = {'Cz', 'P4', 'P4P', 'Oz', 'P3P', 'P3'};
% etc.
% Note that a channel is not considered to be a neighbour of itself.
%
% See also FT_NEIGHBOURPLOT
% Copyright (C) 2006-2011, Eric Maris, Jorn M. Horschig, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_prepare_neighbours.m 7398 2013-01-23 15:50:59Z jorhor $
revision = '$Id: ft_prepare_neighbours.m 7398 2013-01-23 15:50:59Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'required', {'method'});
% set the defaults
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
hasdata = nargin>1;
if hasdata, data = ft_checkdata(data); end
if strcmp(cfg.method, 'template')
neighbours = [];
fprintf('Trying to load sensor neighbours from a template\n');
% determine from where to load the neighbour template
if ~isfield(cfg, 'template')
% if data has been put in, try to estimate the sensor type
if hasdata
fprintf('Estimating sensor type of data to determine the layout filename\n');
senstype = ft_senstype(data.label);
fprintf('Data is of sensor type ''%s''\n', senstype);
if ~exist([senstype '_neighb.mat'], 'file')
if exist([senstype '.lay'], 'file')
cfg.layout = [senstype '.lay'];
else
fprintf('Name of sensor type does not match name of layout- and template-file\n');
end
else
cfg.template = [senstype '_neighb.mat'];
end
end
end
% if that failed
if ~isfield(cfg, 'template')
% check whether a layout can be used
if ~isfield(cfg, 'layout')
% error if that fails as well
error('You need to define a template or layout or give data as an input argument when ft_prepare_neighbours is called with cfg.method=''template''');
end
fprintf('Using the 2-D layout filename to determine the template filename\n');
cfg.template = [strtok(cfg.layout, '.') '_neighb.mat'];
end
% adjust filename
if ~exist(cfg.template, 'file')
cfg.template = lower(cfg.template);
end
% add necessary extensions
if numel(cfg.template) < 4 || ~isequal(cfg.template(end-3:end), '.mat')
if numel(cfg.template) < 7 || ~isequal(cfg.template(end-6:end), '_neighb')
cfg.template = [cfg.template, '_neighb'];
end
cfg.template = [cfg.template, '.mat'];
end
% check for existence
if ~exist(cfg.template, 'file')
error('Template file could not be found - please check spelling or contact jm.horschig(at)donders.ru.nl if you want to create and share your own template! See also http://fieldtrip.fcdonders.nl/faq/how_can_i_define_my_own_neighbourhood_template');
end
load(cfg.template);
fprintf('Successfully loaded neighbour structure from %s\n', cfg.template);
else
% get the the grad or elec if not present in the data
if hasdata
sens = ft_fetch_sens(cfg, data);
else
sens = ft_fetch_sens(cfg);
end
switch lower(cfg.method)
case 'distance'
% use a smart default for the distance
if ~isfield(cfg, 'neighbourdist')
sens = ft_checkdata(sens, 'hasunits', 'yes');
if isfield(sens, 'unit') && strcmp(sens.unit, 'm')
cfg.neighbourdist = 0.04;
elseif isfield(sens, 'unit') && strcmp(sens.unit, 'dm')
cfg.neighbourdist = 0.4;
elseif isfield(sens, 'unit') && strcmp(sens.unit, 'cm')
cfg.neighbourdist = 4;
elseif isfield(sens, 'unit') && strcmp(sens.unit, 'mm')
cfg.neighbourdist = 40;
else
% don't provide a default in case the dimensions of the sensor array are unknown
error('Sensor distance is measured in an unknown unit type');
end
fprintf('using a distance threshold of %g\n', cfg.neighbourdist);
end
neighbours = compneighbstructfromgradelec(sens, cfg.neighbourdist);
case {'triangulation', 'tri'} % the latter for reasons of simplicity
if size(sens.chanpos, 2)==2 || all(sens.chanpos(:,3)==0)
% the sensor positions are already on a 2D plane
prj = sens.chanpos(:,1:2);
else
% project sensor on a 2D plane
prj = elproj(sens.chanpos);
end
% make a 2d delaunay triangulation of the projected points
tri = delaunay(prj(:,1), prj(:,2));
tri_x = delaunay(prj(:,1)./2, prj(:,2));
tri_y = delaunay(prj(:,1), prj(:,2)./2);
tri = [tri; tri_x; tri_y];
neighbours = compneighbstructfromtri(sens, tri);
otherwise
error('Method ''%s'' not known', cfg.method);
end
end
% removed as from Nov 09 2011 - hope there are no problems with this
% if iscell(neighbours)
% warning('Neighbourstructure is in old format - converting to structure array');
% neighbours = fixneighbours(neighbours);
% end
% only select those channels that are in the data
neighb_chans = {neighbours(:).label};
if isfield(cfg, 'channel') && ~isempty(cfg.channel)
if hasdata
desired = ft_channelselection(cfg.channel, data.label);
else
desired = ft_channelselection(cfg.channel, neighb_chans);
end
elseif (hasdata)
desired = data.label;
else
desired = neighb_chans;
end
% in any case remove SCALE and COMNT
desired = ft_channelselection({'all', '-SCALE', '-COMNT'}, desired);
neighb_idx = ismember(neighb_chans, desired);
neighbours = neighbours(neighb_idx);
k = 0;
for i=1:length(neighbours)
if isempty(neighbours(i).neighblabel)
warning('FIELDTRIP:NoNeighboursFound', 'no neighbours found for %s\n', neighbours(i).label);
else % only selected desired channels
neighbours(i).neighblabel = neighbours(i).neighblabel(ismember(neighbours(i).neighblabel, desired));
end
k = k + length(neighbours(i).neighblabel);
end
if k==0, error('No neighbours were found!'); end;
fprintf('there are on average %.1f neighbours per channel\n', k/length(neighbours));
if strcmp(cfg.feedback, 'yes')
% give some graphical feedback
cfg.neighbours = neighbours;
if hasdata
ft_neighbourplot(cfg, data);
else
ft_neighbourplot(cfg);
end
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
if hasdata
ft_postamble previous data
end
ft_postamble history neighbours
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that compute the neighbourhood geometry from the
% gradiometer/electrode positions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [neighbours]=compneighbstructfromgradelec(sens,neighbourdist)
nsensors = length(sens.label);
% compute the distance between all sensors
dist = zeros(nsensors,nsensors);
for i=1:nsensors
dist(i,:) = sqrt(sum((sens.chanpos(1:nsensors,:) - repmat(sens.chanpos(i,:), nsensors, 1)).^2,2))';
end;
% find the neighbouring electrodes based on distance
% later we have to restrict the neighbouring electrodes to those actually selected in the dataset
channeighbstructmat = (dist<neighbourdist);
% electrode istelf is not a neighbour
channeighbstructmat = (channeighbstructmat .* ~eye(nsensors));
% construct a structured cell array with all neighbours
neighbours=struct;
for i=1:nsensors
neighbours(i).label = sens.label{i};
neighbours(i).neighblabel = sens.label(find(channeighbstructmat(i,:)));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that computes the neighbourhood geometry from the
% triangulation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [neighbours]=compneighbstructfromtri(sens,tri)
nsensors = length(sens.label);
channeighbstructmat = zeros(nsensors,nsensors);
% mark neighbours according to triangulation
for i=1:size(tri, 1)
channeighbstructmat(tri(i, 1), tri(i, 2)) = 1;
channeighbstructmat(tri(i, 1), tri(i, 3)) = 1;
channeighbstructmat(tri(i, 2), tri(i, 1)) = 1;
channeighbstructmat(tri(i, 3), tri(i, 1)) = 1;
channeighbstructmat(tri(i, 2), tri(i, 3)) = 1;
channeighbstructmat(tri(i, 3), tri(i, 2)) = 1;
end
% construct a structured cell array with all neighbours
neighbours=struct;
alldist = [];
for i=1:nsensors
neighbours(i).label = sens.label{i};
neighbidx = find(channeighbstructmat(i,:));
neighbours(i).dist = sqrt(sum((repmat(sens.chanpos(i, :), numel(neighbidx), 1) - sens.chanpos(neighbidx, :)).^2, 2));
alldist = [alldist; neighbours(i).dist];
neighbours(i).neighblabel = sens.label(neighbidx);
end
% remove neighbouring channels that are too far away (imporntant e.g. in
% case of missing sensors)
neighbdist = mean(alldist)+3*std(alldist);
for i=1:nsensors
idx = neighbours(i).dist > neighbdist;
neighbours(i).dist(idx) = [];
neighbours(i).neighblabel(idx) = [];
end
neighbours = rmfield(neighbours, 'dist');
|
github
|
philippboehmsturm/antx-master
|
ft_conjunctionanalysis.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_conjunctionanalysis.m
| 8,590 |
utf_8
|
a03da23d74c832a62651ec40acffd376
|
function [conjunction] = ft_conjunctionanalysis(cfg, varargin)
% FT_CONJUNCTIONANALYSIS finds the minimum statistic common across two or
% more contrasts, i.e. data following ft_xxxstatistics. Furthermore, it
% finds the overlap of sensors/voxels that show statistically significant
% results (a logical AND on the mask fields).
%
% Alternatively, it finds minimalistic mean power values in the
% input datasets. Here, a type 'relative change' baselinecorrection
% prior to conjunction is advised.
%
% Use as
% [stat] = ft_conjunctionanalysis(cfg, stat1, stat2, .., statN)
%
% where the input data is the result from either FT_TIMELOCKSTATISTICS,
% FT_FREQSTATISTICS, or FT_SOURCESTATISTICS
%
% No configuration options are yet implemented.
%
% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS
% Copyright (C) 2010-2012, Arjen Stolk
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
revision = '$Id: ft_conjunctionanalysis.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar varargin
% input check
ndatasets = length(varargin);
if ndatasets<2
error('not enough input arguments; there should be at least two');
end
% check if the input data is valid for this function
for i = 1:ndatasets
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq', 'source'}, 'feedback', 'yes');
end
fprintf('performing conjunction analysis on %d input datasets \n', ndatasets);
conjunction = [];
% determine datatype
isfreq = ft_datatype(varargin{1}, 'freq');
istimelock = ft_datatype(varargin{1}, 'timelock');
issource = ft_datatype(varargin{1}, 'source');
% conjunction loop, in case ndatasets > 2
for i = 1:ndatasets-1
% align input arguments for conjunction
if isempty(conjunction)
data1 = varargin{i};
data2 = varargin{i+1};
else
data1 = conjunction; % use already conjunct output
data2 = varargin{i+1};
end
%% SOURCE DATA
if issource
if isfield(data1, 'stat') % conjunction on t-values
fprintf('minimum statistics on voxel T values \n');
% equal size input check
if ~isequal(size(data1.stat), size(data2.stat))
error('the input arguments have different sizes');
end
conjunction = data1;
conjunction.stat = minimumstatistics(data1.stat, data2.stat);
if isfield(data1, 'posclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on positive clusters \n');
conjunction.posclusterslabelmat = minimumstatistics(data1.posclusterslabelmat, data2.posclusterslabelmat);
end
if isfield(data1, 'negclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on negative clusters \n');
conjunction.negclusterslabelmat = minimumstatistics(data1.negclusterslabelmat, data2.negclusterslabelmat);
end
if isfield(data1, 'prob') % conjunction on probabilities
fprintf('minimum statistics on probabilities \n');
conjunction.prob = maximumprobabilities(data1.prob, data2.prob);
end
if isfield(data1, 'mask') % conjunction on mask parameters
fprintf('logical AND on masking parameters \n');
conjunction.mask = logicalAND(data1.mask, data2.mask);
end
elseif isfield(data1, 'avg') % conjunction on mean power values
fprintf('minimum statistics on mean voxel power \n');
% equal size input check
if ~isequal(size(data1.avg.pow), size(data2.avg.pow))
error('the input arguments have different sizes');
end
conjunction = data1;
conjunction.avg.pow = minimumstatistics(data1.avg.pow, data2.avg.pow);
elseif isfield(data1, 'trial')
fprintf('please first compute the averages with ft_sourcedescriptives \n');
else
fprintf('this source level data does not fit conjunction analysis \n');
end
end % end of source level conjunction
%% SENSOR DATA
if isfreq || istimelock
if isfield(data1, 'stat') % conjunction on t-values
fprintf('minimum statistics on sensor T values \n');
% equal size input check
if ~isequal(size(data1.stat), size(data2.stat))
error('the input arguments have different sizes');
end
conjunction = data1;
conjunction.stat = minimumstatistics(data1.stat, data2.stat);
if isfield(data1, 'posclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on positive clusters \n');
conjunction.posclusterslabelmat = minimumstatistics(data1.posclusterslabelmat, data2.posclusterslabelmat);
end
if isfield(data1, 'negclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on negative clusters \n');
conjunction.negclusterslabelmat = minimumstatistics(data1.negclusterslabelmat, data2.negclusterslabelmat);
end
if isfield(data1, 'prob') % conjunction on probabilities
fprintf('minimum statistics on probabilities \n');
conjunction.prob = maximumprobabilities(data1.prob, data2.prob);
end
if isfield(data1, 'mask') % conjunction on mask parameters
fprintf('logical AND on masking parameters \n');
conjunction.mask = logicalAND(data1.mask, data2.mask);
end
elseif isfield(data1, 'powspctrm') % conjunction on mean power values
fprintf('minimum statistics on mean sensor power \n');
% equal size input check
if ~isequal(size(data1.powspctrm), size(data2.powspctrm))
error('the input arguments have different sizes');
end
conjunction = data1;
conjunction.powspctrm = minimumstatistics(data1.powspctrm, data2.powspctrm);
elseif isfield(data1, 'avg') % conjunction on mean signal amplitudes
fprintf('minimum statistics on mean sensor amplitudes \n');
% equal size input check
if ~isequal(size(data1.avg), size(data2.avg))
error('the input arguments have different sizes');
end
conjunction = data1;
conjunction.avg = minimumstatistics(data1.avg, data2.avg);
elseif isfield(data1, 'trial')
fprintf('please first compute the averages with ft_timelockdescriptives/ft_freqdescriptives \n');
else
fprintf('this sensor level data does not fit conjunction analysis \n');
end
end % end of sensor level conjunction
clear data1; clear data2;
end % end of conjunction loop
%% UNIDENTIFIED DATA
if istimelock == 0 && isfreq == 0 && issource == 0
fprintf('this data is not appropriate for conjunction analysis\n');
conjunction = [];
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
ft_postamble history conjunction
ft_postamble savevar conjunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [minstat] = minimumstatistics(variable1, variable2)
minAbsT = min(abs(variable1), abs(variable2)); % minimum of the absolute values
equalSign = (sign(variable1) == sign(variable2)); % 1 is signs are equal, 0 otherwise
origSign = sign(variable1); % sign(varagin2) gives same result
minstat = minAbsT.*equalSign.*origSign;
function [maxprob] = maximumprobabilities(variable1, variable2)
maxprob = max(variable1, variable2); % maximum of the probabilities
function [logic] = logicalAND(variable1, variable2)
logic = (variable1 & variable2); % compute logical AND
|
github
|
philippboehmsturm/antx-master
|
ft_sliceinterp.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_sliceinterp.m
| 18,439 |
utf_8
|
bd145a75e58dc47cf4ea80eb8999f6dd
|
function [outim]=ft_sliceinterp(cfg, ininterp)
% FT_SLICEINTERP plots a 2D-montage of source reconstruction and anatomical MRI
% after these have been interpolated onto the same grid.
%
% Use as
% ft_sliceinterp(cfg, interp)
% or
% [rgbimage] = ft_sliceinterp(cfg, interp), rgbimage is the monatage image
%
% where interp is the output of sourceinterpolate and cfg is a structure
% with any of the following fields:
%
% cfg.funparameter string with the functional parameter of interest (default = 'source')
% cfg.maskparameter parameter used as opacity mask (default = 'none')
% cfg.clipmin value or 'auto' (clipping of source data)
% cfg.clipmax value or 'auto' (clipping of source data)
% cfg.clipsym 'yes' or 'no' (default) symmetrical clipping
% cfg.colormap colormap for source overlay (default is jet(128))
% cfg.colmin source value mapped to the lowest color (default = 'auto')
% cfg.colmax source value mapped to the highest color (default = 'auto')
% cfg.maskclipmin value or 'auto' (clipping of mask data)
% cfg.maskclipmax value or 'auto' (clipping of mask data)
% cfg.maskclipsym 'yes' or 'no' (default) symmetrical clipping
% cfg.maskmap opacitymap for source overlay
% (default is linspace(0,1,128))
% cfg.maskcolmin mask value mapped to the lowest opacity, i.e.
% completely transparent (default ='auto')
% cfg.maskcolmin mask value mapped to the highest opacity, i.e.
% non-transparent (default = 'auto')
% cfg.alpha value between 0 and 1 or 'adaptive' (default)
% cfg.nslices integer value, default is 20
% cfg.dim integer value, default is 3 (dimension to slice)
% cfg.spacemin 'auto' (default) or integer (first slice position)
% cfg.spacemax 'auto' (default) or integer (last slice position)
% cfg.resample integer value, default is 1 (for resolution reduction)
% cfg.rotate number of ccw 90 deg slice rotations (default = 0)
% cfg.title optional title (default is '')
% cfg.whitebg 'yes' or 'no' (default = 'yes')
% cfg.flipdim flip data along the sliced dimension, 'yes' or 'no'
% (default = 'no')
% cfg.marker [Nx3] array defining N marker positions to display
% cfg.markersize radius of markers (default = 5);
% cfg.markercolor [1x3] marker color in RGB (default = [1 1 1], i.e. white)
% cfg.interactive 'yes' or 'no' (default), interactive coordinates
% and source values
%
% if cfg.alpha is set to 'adaptive' the opacity of the source overlay
% linearly follows the source value: maxima are opaque and minima are
% transparent.
%
% if cfg.spacemin and/or cfg.spacemax are set to 'auto' the sliced
% space is automatically restricted to the evaluated source-space
%
% if cfg.colmin and/or cfg.colmax are set to 'auto' the colormap is mapped
% to source values the following way: if source values are either all
% positive or all negative the colormap is mapped to from
% min(source) to max(source). If source values are negative and positive
% the colormap is symmetrical mapped around 0 from -max(abs(source)) to
% +max(abs(source)).
%
% If cfg.maskparameter specifies a parameter to be used as an opacity mask
% cfg.alpha is not used. Instead the mask values are maped to an opacitymap
% that can be specified using cfg.maskmap. The mapping onto that
% opacitymap is controlled as for the functional data using the
% corresponding clipping and min/max options.
%
% if cfg.whitebg is set to 'yes' the function estimates the head volume and
% displays a white background outside the head, which can save a lot of black
% printer toner.
%
% if cfg.interactive is set to 'yes' a button will be displayed for
% interactive data evaluation and coordinate reading. After clicking the
% button named 'coords' you can click on any position in the slice montage.
% After clicking these coordinates and their source value are displayed in
% a text box below the button. The coordinates correspond to indeces in the
% input data array:
%
% f = interp.source(coord_1,coord_2,coord_3)
%
% The coordinates are not affected by any transformations used for displaying
% the data such as cfg.dim, cfg.rotate,cfg.flipdim or cfg.resample.
%
% See also FT_SOURCEANALYSIS, FT_VOLUMERESLICE
% Copyright (C) 2004, Markus Siegel, [email protected]
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sliceinterp.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_sliceinterp.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar ininterp
% check if the input data is valid for this function
ininterp = ft_checkdata(ininterp, 'datatype', 'volume', 'feedback', 'yes');
% set the defaults
if ~isfield(cfg, 'clipmin'); cfg.clipmin = 'auto'; end
if ~isfield(cfg, 'clipmax'); cfg.clipmax = 'auto'; end
if ~isfield(cfg, 'clipsym'); cfg.clipsym = 'no'; end
if ~isfield(cfg, 'alpha'); cfg.alpha = 'adaptive'; end
if ~isfield(cfg, 'nslices'); cfg.nslices = 20; end
if ~isfield(cfg, 'dim'); cfg.dim = 3; end
if ~isfield(cfg, 'colormap'); cfg.colormap = jet(128); end
if ~isfield(cfg, 'spacemin'); cfg.spacemin = 'auto'; end
if ~isfield(cfg, 'spacemax'); cfg.spacemax = 'auto'; end
if ~isfield(cfg, 'colmin'); cfg.colmin = 'auto'; end
if ~isfield(cfg, 'colmax'); cfg.colmax = 'auto'; end
if ~isfield(cfg, 'resample'); cfg.resample = 1; end
if ~isfield(cfg, 'rotate'); cfg.rotate = 0; end
if ~isfield(cfg, 'title'); cfg.title = ''; end
if ~isfield(cfg, 'whitebg'); cfg.whitebg = 'no'; end
if ~isfield(cfg, 'flipdim'); cfg.flipdim = 'no'; end
if ~isfield(cfg, 'marker'); cfg.marker = []; end
if ~isfield(cfg, 'markersize'); cfg.markersize = 5; end
if ~isfield(cfg, 'markercolor'); cfg.markercolor = [1,1,1]; end
if ~isfield(cfg, 'interactive'); cfg.interactive = 'no'; end
if ~isfield(cfg, 'maskclipmin'); cfg.maskclipmin = 'auto'; end
if ~isfield(cfg, 'maskclipmax'); cfg.maskclipmax = 'auto'; end
if ~isfield(cfg, 'maskclipsym'); cfg.maskclipsym = 'no'; end
if ~isfield(cfg, 'maskmap'); cfg.maskmap = linspace(0,1,128); end
if ~isfield(cfg, 'maskcolmin'); cfg.maskcolmin = 'auto'; end
if ~isfield(cfg, 'maskcolmax'); cfg.maskcolmax = 'auto'; end
if ~isfield(cfg, 'maskparameter');cfg.maskparameter = []; end
% perform some checks on the configuration for backward compatibility
if ~isfield(cfg, 'funparameter') && isfield(ininterp, 'source')
% if present, the default behavior should be to use this field for plotting
cfg.funparameter = 'source';
end
% make the selection of functional and mask data consistent with the data
cfg.funparameter = parameterselection(cfg.funparameter, ininterp);
cfg.maskparameter = parameterselection(cfg.maskparameter, ininterp);
% only a single parameter should be selected
try, cfg.funparameter = cfg.funparameter{1}; end
try, cfg.maskparameter = cfg.maskparameter{1}; end
% check anatomical data
if isfield(ininterp,'anatomy');
interp.anatomy = reshape(ininterp.anatomy, ininterp.dim);
else
error('no anatomical data supplied');
end
% check functional data
if ~isempty(cfg.funparameter)
interp.source = double(reshape(getsubfield(ininterp, cfg.funparameter), ininterp.dim));
else
error('no functional data supplied');
end
% check mask data
if ~isempty(cfg.maskparameter)
interp.mask = double(reshape(getsubfield(ininterp,cfg.maskparameter), ininterp.dim));
maskdat = 1;
else
fprintf('no opacity mask data supplied\n');
interp.mask = [];
maskdat = 0;
end
% only work with the copy of the relevant parameters in "interp"
clear ininterp;
% convert anatomy data type and optimize contrast
if isa(interp.anatomy, 'uint8') || isa(interp.anatomy, 'uint16')
fprintf('converting anatomy to floating point values...');
interp.anatomy = double(interp.anatomy);
fprintf('done\n');
end
fprintf('optimizing contrast of anatomical data ...');
minana = min(interp.anatomy(:));
maxana = max(interp.anatomy(:));
interp.anatomy = (interp.anatomy-minana)./(maxana-minana);
fprintf('done\n');
% store original data if 'interactive' mode
if strcmp(cfg.interactive,'yes')
data.source = interp.source;
end
% place markers
marker = zeros(size(interp.anatomy));
if ~isempty(cfg.marker)
fprintf('placing markers ...');
[x,y,z] = ndgrid([1:size(interp.anatomy,1)],[1:size(interp.anatomy,2)],[1:size(interp.anatomy,3)]);
for imarker = 1:size(cfg.marker,1)
marker(find(sqrt((x-cfg.marker(imarker,1)).^2 + (y-cfg.marker(imarker,2)).^2 + (z-cfg.marker(imarker,3)).^2)<=cfg.markersize)) = 1;
end
fprintf('done\n');
end
% shift dimensions
fprintf('sorting dimensions...');
interp.anatomy = shiftdim(interp.anatomy,cfg.dim-1);
interp.source = shiftdim(interp.source,cfg.dim-1);
interp.mask = shiftdim(interp.mask,cfg.dim-1);
marker = shiftdim(marker,cfg.dim-1);
fprintf('done\n');
% flip dimensions
if strcmp(cfg.flipdim,'yes')
fprintf('flipping dimensions...');
interp.anatomy = flipdim(interp.anatomy,1);
interp.source = flipdim(interp.source,1);
interp.mask = flipdim(interp.mask,1);
marker = flipdim(marker,1);
fprintf('done\n');
end
% set slice space
if ischar(cfg.spacemin)
fprintf('setting first slice position...');
spacemin = min(find(~isnan(max(max(interp.source,[],3),[],2))));
fprintf('%d...done\n',spacemin);
else
spacemin = cfg.spacemin;
end
if ischar(cfg.spacemax)
fprintf('setting last slice position...');
spacemax = max(find(~isnan(max(max(interp.source,[],3),[],2))));
fprintf('%d...done\n',spacemax);
else
spacemax = cfg.spacemax;
end
% clip funtional data
if ~ischar(cfg.clipmin)
fprintf('clipping functional minimum...');
switch cfg.clipsym
case 'no'
interp.source(find(interp.source<cfg.clipmin)) = nan;
case 'yes'
interp.source(find(abs(interp.source)<cfg.clipmin)) = nan;
end
fprintf('done\n');
end
if ~ischar(cfg.clipmax)
fprintf('clipping functional maximum...');
switch cfg.clipsym
case 'no'
interp.source(find(interp.source>cfg.clipmax)) = nan;
case 'yes'
interp.source(find(abs(interp.source)>cfg.clipmax)) = nan;
end
fprintf('done\n');
end
% clip mask data
if maskdat
if ~ischar(cfg.maskclipmin)
fprintf('clipping mask minimum...');
switch cfg.maskclipsym
case 'no'
interp.mask(find(interp.mask<cfg.maskclipmin)) = nan;
case 'yes'
interp.mask(find(abs(interp.mask)<cfg.maskclipmin)) = nan;
end
fprintf('done\n');
end
if ~ischar(cfg.maskclipmax)
fprintf('clipping mask maximum...');
switch cfg.maskclipsym
case 'no'
interp.mask(find(interp.mask>cfg.maskclipmax)) = nan;
case 'yes'
interp.mask(find(abs(interp.mask)>cfg.maskclipmax)) = nan;
end
fprintf('done\n');
end
end
% scale functional data
fprintf('scaling functional data...');
fmin = min(interp.source(:));
fmax = max(interp.source(:));
if ~ischar(cfg.colmin)
fcolmin = cfg.colmin;
else
if sign(fmin)==sign(fmax)
fcolmin = fmin;
else
fcolmin = -max(abs([fmin,fmax]));
end
end
if ~ischar(cfg.colmax)
fcolmax = cfg.colmax;
else
if sign(fmin)==sign(fmax)
fcolmax = fmax;
else
fcolmax = max(abs([fmin,fmax]));
end
end
interp.source = (interp.source-fcolmin)./(fcolmax-fcolmin);
if ~ischar(cfg.colmax)
interp.source(find(interp.source>1)) = 1;
end
if ~ischar(cfg.colmin)
interp.source(find(interp.source<0)) = 0;
end
fprintf('done\n');
% scale mask data
if maskdat
fprintf('scaling mask data...');
fmin = min(interp.mask(:));
fmax = max(interp.mask(:));
if ~ischar(cfg.maskcolmin)
mcolmin = cfg.maskcolmin;
else
if sign(fmin)==sign(fmax)
mcolmin = fmin;
else
mcolmin = -max(abs([fmin,fmax]));
end
end
if ~ischar(cfg.maskcolmax)
mcolmax = cfg.maskcolmax;
else
if sign(fmin)==sign(fmax)
mcolmax = fmax;
else
mcolmax = max(abs([fmin,fmax]));
end
end
interp.mask = (interp.mask-mcolmin)./(mcolmax-mcolmin);
if ~ischar(cfg.maskcolmax)
interp.mask(find(interp.mask>1)) = 1;
end
if ~ischar(cfg.maskcolmin)
interp.mask(find(interp.mask<0)) = 0;
end
fprintf('done\n');
end
% merge anatomy, functional data and mask
fprintf('constructing overlay...');
if ischar(cfg.colormap)
% replace string by colormap using standard Matlab function
cfg.colormap = colormap(cfg.colormap);
end
cmap = cfg.colormap;
cmaplength = size(cmap,1);
maskmap = cfg.maskmap(:);
maskmaplength = size(maskmap,1);
indslice = round(linspace(spacemin,spacemax,cfg.nslices));
nvox1 = length(1:cfg.resample:size(interp.anatomy,2));
nvox2 = length(1:cfg.resample:size(interp.anatomy,3));
if mod(cfg.rotate,2)
dummy = nvox1;
nvox1 = nvox2;
nvox2 = dummy;
end
out = zeros(nvox1,nvox2,3,cfg.nslices);
for islice = 1:cfg.nslices
dummy1 = squeeze(interp.anatomy(indslice(islice),1:cfg.resample:end,1:cfg.resample:end));
dummy2 = squeeze(interp.source(indslice(islice),1:cfg.resample:end,1:cfg.resample:end));
indmarker = find(squeeze(marker(indslice(islice),1:cfg.resample:end,1:cfg.resample:end)));
indsource = find(~isnan(dummy2));
if maskdat
dummymask = squeeze(interp.mask(indslice(islice),1:cfg.resample:end,1:cfg.resample:end));
indsource = find(~isnan(dummy2) & ~isnan(dummymask));
end
for icol = 1:3
dummy3 = dummy1;
if not(maskdat)
if ~ischar(cfg.alpha)
try
dummy3(indsource) = ...
(1-cfg.alpha) * dummy3(indsource) + ...
cfg.alpha * cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol);
end
else
try
dummy3(indsource) = ...
(1-dummy2(indsource)) .* dummy3(indsource) + ...
dummy2(indsource) .* cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol);
end
end
else
dummy3(indsource) = ...
(1-maskmap(round(dummymask(indsource)*(maskmaplength-1))+1)).* ...
dummy3(indsource) + ...
maskmap(round(dummymask(indsource)*(maskmaplength-1))+1) .* ...
cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol);
end
dummy3(indmarker) = cfg.markercolor(icol);
out(:,:,icol,islice) = rot90(dummy3,cfg.rotate);
end
if strcmp(cfg.whitebg,'yes')
bgmask = zeros(nvox1,nvox2);
bgmask(find(conv2(mean(out(:,:,:,islice),3),ones(round((nvox1+nvox2)/8))/(round((nvox1+nvox2)/8).^2),'same')<0.1)) = 1;
for icol = 1:3
out(:,:,icol,islice) = bgmask.*ones(nvox1,nvox2) + (1-bgmask).* out(:,:,icol,islice);
end
end
end
fprintf('done\n');
clf;
fprintf('plotting...');
axes('position',[0.9 0.3 0.02 0.4]);
image(permute(cmap,[1 3 2]));
set(gca,'YAxisLocation','right');
set(gca,'XTick',[]);
set(gca,'YDir','normal');
set(gca,'YTick',linspace(1,cmaplength,5));
set(gca,'YTickLabel',linspace(fcolmin,fcolmax,5));
set(gca,'Box','on');
axes('position',[0.01 0.01 0.88 0.90]);
[h,nrows,ncols]=slicemon(out);
xlim=get(gca,'XLim');
ylim=get(gca,'YLim');
text(diff(xlim)/2,-diff(ylim)/100,cfg.title,'HorizontalAlignment','center','Interpreter','none');
drawnow;
fprintf('done\n');
if nargout > 0
outim=get(h,'CData');
end
if strcmp(cfg.interactive,'yes')
data.sin = size(interp.source);
data.nrows = nrows;
data.ncols = ncols;
data.out = out;
data.indslice = indslice;
data.cfg = cfg;
data.hfig = gcf;
uicontrol('Units','norm', 'Position', [0.9 0.2 0.08 0.05], 'Style','pushbutton', 'String','coords',...
'Callback',@getcoords,'FontSize',7);
data.hcoords = uicontrol('Units','norm', 'Position', [0.9 0.05 0.08 0.13], 'Style','text', 'String','','HorizontalAlign','left','FontSize',7);
guidata(data.hfig,data);
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
% ---------------- subfunctions ----------------
function getcoords(h,eventdata,handles,varargin)
data = guidata(gcf);
[xi,yi] = ginput(1);
co(2,1) = round(mod(yi,size(data.out,1)));
co(3,1) = round(mod(xi,size(data.out,2)));
switch mod(data.cfg.rotate,4)
case 1,
t1 = co(2);
co(2) = co(3);
co(3) = data.sin(3)-t1;
case 2,
co(2) = data.sin(2)-co(2);
co(3) = data.sin(3)-co(3);
case 3,
t1 = co(3);
co(3) = co(2);
co(2) = data.sin(2)-t1;
end
try
co(1) = data.indslice(fix(xi/size(data.out,2)) + fix(yi/size(data.out,1))*data.ncols + 1);
catch
co(1) = NaN;
end
if strcmp(data.cfg.flipdim, 'yes')
co(1) = data.sin(1) - co(1) + 1;
end
co = co(:);
co(2:3) = round(co(2:3)*data.cfg.resample);
for ishift = 1:data.cfg.dim-1
co = [co(3);co(1);co(2)];
end
set(data.hcoords,'String',sprintf('1: %d\n2: %d\n3: %d\nf: %0.4f',co(1),co(2),co(3),data.source(co(1),co(2),co(3))));
function [h,nrows,ncols] = slicemon(a) % display the montage w/o image_toolbox
siz = [size(a,1) size(a,2) size(a,4)];
nn = sqrt(prod(siz))/siz(2);
mm = siz(3)/nn;
if (ceil(nn)-nn) < (ceil(mm)-mm),
nn = ceil(nn); mm = ceil(siz(3)/nn);
else
mm = ceil(mm); nn = ceil(siz(3)/mm);
end
b = a(1,1);
b(1,1) = 0;
b = repmat(b, [mm*siz(1), nn*siz(2), size(a,3), 1]);
rows = 1:siz(1); cols = 1:siz(2);
for i=0:mm-1,
for j=0:nn-1,
k = j+i*nn+1;
if k<=siz(3),
b(rows+i*siz(1),cols+j*siz(2),:) = a(:,:,:,k);
end
end
end
hh = image(b);
axis image;
box off;
set(gca,'XTick',[],'YTick',[],'Visible','off');
if nargout > 0
h = hh;
nrows = mm;
ncols = nn;
end
|
github
|
philippboehmsturm/antx-master
|
ft_clusterplot.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_clusterplot.m
| 16,789 |
utf_8
|
c4c3bbddd939a0c172b983f111def76a
|
function [cfg] = ft_clusterplot(cfg, stat)
% FT_CLUSTERPLOT plots a series of topoplots with found clusters highlighted.
% stat is 2D or 1D data from FT_TIMELOCKSTATISTICS or FT_FREQSTATISTICS with 'cluster'
% as cfg.correctmc. 2D: stat from FT_TIMELOCKSTATISTICS not averaged over
% time, or stat from FT_FREQSTATISTICS averaged over frequency not averaged over
% time. 1D: averaged over time as well.
%
% Use as
% ft_clusterplot(cfg, stat)
%
% Where the configuration options can be
% cfg.alpha = number, highest cluster p-value to be plotted
% max 0.3 (default = 0.05)
% cfg.highlightseries = 1x5 cell-array, highlight option series ('on','labels','numbers')
% default {'on','on','on','on','on'} for p < [0.01 0.05 0.1 0.2 0.3]
% cfg.highlightsymbolseries = 1x5 vector, highlight marker symbol series
% default ['*','x','+','o','.'] for p < [0.01 0.05 0.1 0.2 0.3]
% cfg.highlightsizeseries = 1x5 vector, highlight marker size series
% default [6 6 6 6 6] for p < [0.01 0.05 0.1 0.2 0.3]
% cfg.highlightcolorpos = color of highlight marker for positive clusters
% default = [0 0 0]
% cfg.highlightcolorneg = color of highlight marker for negative clusters
% default = [0 0 0]
% cfg.saveaspng = string, filename of the output figures (default = 'no')
%
% It is also possible to specify other cfg options that apply to FT_TOPOPLOTTFR.
% You CANNOT specify cfg.xlim, any of the FT_TOPOPLOTTFR highlight
% options, cfg.comment and cfg.commentpos.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also:
% FT_TOPOPLOTTFR, FT_TOPOPLOTER, FT_SINGLEPLOTER
% Copyright (C) 2007, Ingrid Nieuwenhuis, F.C. Donders Centre
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_clusterplot.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_clusterplot.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar stat
% check if the given data is appropriate
if isfield(stat,'freq') && length(stat.freq) > 1
error('stat contains multiple frequencies which is not allowed because it should be averaged over frequencies')
end
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkerseries', 'highlightsymbolseries'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkersizeseries', 'highlightsizeseries'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlcolorpos', 'highlightcolorpos'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlcolorneg', 'highlightcolorneg'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'deprecated', {'hllinewidthseries'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam', 'yparam'});
% added several forbidden options
cfg = ft_checkconfig(cfg, 'forbidden', {'highlight', ...
'highlightchannel', ...
'highlightsymbol', ...
'highlightcolor', ...
'highlightsize', ...
'highlightfontsize', ...
'xlim', ...
'comment', ...
'commentpos'});
% set the defaults
if ~isfield(cfg,'alpha'), cfg.alpha = 0.05; end;
if ~isfield(cfg,'highlightseries'), cfg.highlightseries = {'on','on','on','on','on'}; end;
if ~isfield(cfg,'highlightsymbolseries'), cfg.highlightsymbolseries = ['*','x','+','o','.']; end;
if ~isfield(cfg,'highlightsizeseries'), cfg.highlightsizeseries = [6 6 6 6 6]; end;
if ~isfield(cfg,'hllinewidthseries'), cfg.hllinewidthseries = [1 1 1 1 1]; end;
if ~isfield(cfg,'highlightcolorpos'), cfg.highlightcolorpos = [0 0 0]; end;
if ~isfield(cfg,'highlightcolorneg'), cfg.highlightcolorneg = [0 0 0]; end;
if ~isfield(cfg,'parameter'), cfg.parameter = 'stat'; end;
if ~isfield(cfg,'saveaspng'), cfg.saveaspng = 'no'; end;
% error if cfg.highlightseries is not a cell, for possible confusion with cfg-options
if ~iscell(cfg.highlightseries)
error('cfg.highlightseries should be a cell-array of strings')
end
% set additional options for topoplotting
if isfield(cfg, 'marker'), cfgtopo.marker = cfg.marker ; end
if ~isfield(cfg,'marker'), cfgtopo.marker = 'off'; end
if isfield(cfg, 'markersymbol'), cfgtopo.markersymbol = cfg.markersymbol; end
if isfield(cfg, 'markercolor'), cfgtopo.markercolor = cfg.markercolor; end
if isfield(cfg, 'markersize'), cfgtopo.markersize = cfg.markersize; end
if isfield(cfg, 'markerfontsize'), cfgtopo.markerfontsize = cfg.markerfontsize; end
if isfield(cfg, 'style'), cfgtopo.style = cfg.style ; end
if isfield(cfg, 'gridscale'), cfgtopo.gridscale = cfg.gridscale; end
if isfield(cfg, 'interplimits'), cfgtopo.interplimits = cfg.interplimits; end
if isfield(cfg, 'interpolation'), cfgtopo.interpolation = cfg.interpolation; end
if isfield(cfg, 'contournum'), cfgtopo.contournum = cfg.contournum; end
if isfield(cfg, 'colorbar'), cfgtopo.colorbar = cfg.colorbar; end
if isfield(cfg, 'shading'), cfgtopo.shading = cfg.shading'; end
if isfield(cfg, 'zlim'), cfgtopo.zlim = cfg.zlim; end
cfgtopo.parameter = cfg.parameter;
% prepare the layout, this only has to be done once
cfgtopo.layout = ft_prepare_layout(cfg, stat);
% detect 2D or 1D
is2D = isfield(stat,'time');
% add .time field to 1D data, topoplotER wants it
if ~is2D
stat.time = 0; %doesn't matter what it is, so just choose 0
end;
% find significant clusters
sigpos = [];
signeg = [];
haspos = isfield(stat,'posclusters');
hasneg = isfield(stat,'negclusters');
if haspos == 0 && hasneg == 0
fprintf('%s\n','no significant clusters in data; nothing to plot')
else
if haspos
for iPos = 1:length(stat.posclusters)
sigpos(iPos) = stat.posclusters(iPos).prob < cfg.alpha;
end
end
if hasneg
for iNeg = 1:length(stat.negclusters)
signeg(iNeg) = stat.negclusters(iNeg).prob < cfg.alpha;
end
end
sigpos = find(sigpos == 1);
signeg = find(signeg == 1);
Nsigpos = length(sigpos);
Nsigneg = length(signeg);
Nsigall = Nsigpos + Nsigneg;
if Nsigall == 0
error('no clusters present with a p-value lower than the specified alpha, nothing to plot')
end
% make clusterslabel matrix per significant cluster
posCLM = squeeze(stat.posclusterslabelmat);
sigposCLM = zeros(size(posCLM));
probpos = [];
for iPos = 1:length(sigpos)
sigposCLM(:,:,iPos) = (posCLM == sigpos(iPos));
probpos(iPos) = stat.posclusters(iPos).prob;
hlsignpos(iPos) = prob2hlsign(probpos(iPos), cfg.highlightsymbolseries);
end
negCLM = squeeze(stat.negclusterslabelmat);
signegCLM = zeros(size(negCLM));
probneg = [];
for iNeg = 1:length(signeg)
signegCLM(:,:,iNeg) = (negCLM == signeg(iNeg));
probneg(iNeg) = stat.negclusters(iNeg).prob;
hlsignneg(iNeg) = prob2hlsign(probneg(iNeg), cfg.highlightsymbolseries);
end
fprintf('%s%i%s%g%s\n','There are ',Nsigall,' clusters smaller than alpha (',cfg.alpha,')')
if is2D
% define time window per cluster
for iPos = 1:length(sigpos)
possum_perclus = sum(sigposCLM(:,:,iPos),1); %sum over Chans for each timepoint
ind_min = min(find(possum_perclus~=0));
ind_max = max(find(possum_perclus~=0));
time_perclus = [stat.time(ind_min) stat.time(ind_max)];
fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')',', t = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2)))
end
for iNeg = 1:length(signeg)
negsum_perclus = sum(signegCLM(:,:,iNeg),1);
ind_min = min(find(negsum_perclus~=0));
ind_max = max(find(negsum_perclus~=0));
time_perclus = [stat.time(ind_min) stat.time(ind_max)];
fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')',', t = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2)))
end
% define timewindow containing all significant clusters
possum = sum(sigposCLM,3); %sum over Chans for timevector
possum = sum(possum,1);
negsum = sum(signegCLM,3);
negsum = sum(negsum,1);
allsum = possum + negsum;
ind_timewin_min = min(find(allsum~=0));
ind_timewin_max = max(find(allsum~=0));
timewin = stat.time(ind_timewin_min:ind_timewin_max);
else
for iPos = 1:length(sigpos)
fprintf('%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')')
end
for iNeg = 1:length(signeg)
fprintf('%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')')
end
end
% setup highlight options for all clusters and make comment for 1D data
compos = [];
comneg = [];
for iPos = 1:length(sigpos)
if stat.posclusters(sigpos(iPos)).prob < 0.01
cfgtopo.highlight{iPos} = cfg.highlightseries{1};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(1);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(1);
elseif stat.posclusters(sigpos(iPos)).prob < 0.05
cfgtopo.highlight{iPos} = cfg.highlightseries{2};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(2);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(2);
elseif stat.posclusters(sigpos(iPos)).prob < 0.1
cfgtopo.highlight{iPos} = cfg.highlightseries{3};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(3);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(3);
elseif stat.posclusters(sigpos(iPos)).prob < 0.2
cfgtopo.highlight{iPos} = cfg.highlightseries{4};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(4);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(4);
elseif stat.posclusters(sigpos(iPos)).prob < 0.3
cfgtopo.highlight{iPos} = cfg.highlightseries{5};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(5);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(5);
end
cfgtopo.highlightcolor{iPos} = cfg.highlightcolorpos;
compos = strcat(compos,cfgtopo.highlightsymbol{iPos}, 'p=',num2str(probpos(iPos)),' '); % make comment, only used for 1D data
end
for iNeg = 1:length(signeg)
if stat.negclusters(signeg(iNeg)).prob < 0.01
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{1};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(1);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(1);
elseif stat.negclusters(signeg(iNeg)).prob < 0.05
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{2};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(2);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(2);
elseif stat.negclusters(signeg(iNeg)).prob < 0.1
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{3};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(3);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(3);
elseif stat.negclusters(signeg(iNeg)).prob < 0.2
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{4};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(4);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(4);
elseif stat.negclusters(signeg(iNeg)).prob < 0.3
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{5};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(5);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(5);
end
cfgtopo.highlightcolor{length(sigpos)+iNeg} = cfg.highlightcolorneg;
comneg = strcat(comneg,cfgtopo.highlightsymbol{length(sigpos)+iNeg}, 'p=',num2str(probneg(iNeg)),' '); % make comment, only used for 1D data
end
if is2D
Npl = length(timewin);
else
Npl = 1;
end
Nfig = ceil(Npl/15);
% put channel indexes in list
if is2D
for iPl = 1:Npl
for iPos = 1:length(sigpos)
list{iPl}{iPos} = find(sigposCLM(:,ind_timewin_min+iPl-1,iPos) == 1);
end
for iNeg = 1:length(signeg)
list{iPl}{length(sigpos)+iNeg} = find(signegCLM(:,ind_timewin_min+iPl-1,iNeg) == 1);
end
end
else
for iPl = 1:Npl
for iPos = 1:length(sigpos)
list{iPl}{iPos} = find(sigposCLM(:,iPos) == 1);
end
for iNeg = 1:length(signeg)
list{iPl}{length(sigpos)+iNeg} = find(signegCLM(:,iNeg) == 1);
end
end
end
% make plots
for iPl = 1:Nfig
figure;
if is2D
if iPl < Nfig
for iT = 1:15
PlN = (iPl-1)*15 + iT; %plotnumber
cfgtopo.xlim = [stat.time(ind_timewin_min+PlN-1) stat.time(ind_timewin_min+PlN-1)];
cfgtopo.highlightchannel = list{PlN};
cfgtopo.comment = strcat('time: ',num2str(stat.time(ind_timewin_min+PlN-1)), ' s');
cfgtopo.commentpos = 'title';
subplot(3,5,iT);
ft_topoplotTFR(cfgtopo, stat);
end
elseif iPl == Nfig
for iT = 1:Npl-(15*(Nfig-1))
PlN = (iPl-1)*15 + iT; %plotnumber
cfgtopo.xlim = [stat.time(ind_timewin_min+PlN-1) stat.time(ind_timewin_min+PlN-1)];
cfgtopo.highlightchannel = list{PlN};
cfgtopo.comment = strcat('time: ',num2str(stat.time(ind_timewin_min+PlN-1)), ' s');
cfgtopo.commentpos = 'title';
subplot(3,5,iT);
ft_topoplotTFR(cfgtopo, stat);
end
end
else
cfgtopo.highlightchannel = list{1};
cfgtopo.xparam = 'time';
cfgtopo.yparam = '';
cfgtopo.comment = strcat(compos,comneg);
cfgtopo.commentpos = 'title';
ft_topoplotTFR(cfgtopo, stat);
end
% save figure
if isequal(cfg.saveaspng,'no');
else
filename = strcat(cfg.saveaspng, '_fig', num2str(iPl));
print(gcf,'-dpng',filename);
end
end
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous stat
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sign = prob2hlsign(prob, hlsign)
if prob < 0.01
sign = hlsign(1);
elseif prob < 0.05
sign = hlsign(2);
elseif prob < 0.1
sign = hlsign(3);
elseif prob < 0.2
sign = hlsign(4);
elseif prob < 0.3
sign = hlsign(5);
end
|
github
|
philippboehmsturm/antx-master
|
ft_sourcemovie.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_sourcemovie.m
| 21,618 |
utf_8
|
ec436384a67196b47d56edfc701a3099
|
function [cfg, M] = ft_sourcemovie(cfg, source, source2)
% FT_SOURCEMOVIE displays the source reconstruction on a cortical mesh
% and allows the user to scroll through time with a movie
%
% Use as
% ft_sourcemovie(cfg, source)
% where the input source data is obtained from FT_SOURCEANALYSIS and cfg is
% a configuratioun structure that should contain
%
% cfg.funparameter = string, functional parameter that is color coded (default = 'avg.pow')
% cfg.maskparameter = string, functional parameter that is used for opacity (default = [])
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also FT_SOURCEPLOT, FT_SOURCEINTERPOLATE
% Copyright (C) 2011, Robert Oostenveld
%
% $Id: ft_sourcemovie.m 7188 2012-12-13 21:26:34Z roboos $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial part deals with parsing the input options and data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
revision = '$Id: ft_sourcemovie.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar source
% ensure that the input data is valiud for this function, this will also do
% backward-compatibility conversions of old data that for example was
% read from an old *.mat file
source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'funparameter'});
cfg = ft_checkconfig(cfg, 'renamed', {'parameter', 'funparameter'});
cfg = ft_checkconfig(cfg, 'renamed', {'mask', 'maskparameter'});
% these are not needed any more, once the source structure has a proper dimord
% cfg = ft_checkconfig(cfg, 'deprecated', 'xparam');
% cfg = ft_checkconfig(cfg, 'deprecated', 'yparam');
% get the options
xlim = ft_getopt(cfg, 'xlim');
ylim = ft_getopt(cfg, 'ylim');
zlim = ft_getopt(cfg, 'zlim');
olim = ft_getopt(cfg, 'alim'); % don't use alim as variable name
xparam = ft_getopt(cfg, 'xparam', 'time'); % use time as default
yparam = ft_getopt(cfg, 'yparam'); % default is dealt with below
funparameter = ft_getopt(cfg, 'funparameter', 'avg.pow'); % use power as default
maskparameter = ft_getopt(cfg, 'maskparameter');
if isempty(yparam) && isfield(source, 'freq')
% the default is freq (if present)
yparam = 'freq';
end
% update the configuration
cfg.funparameter = funparameter;
cfg.maskparameter = maskparameter;
cfg.xparam = xparam;
cfg.yparam = yparam;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fun = getsubfield(source, funparameter); % might be avg.pow
if nargin>2, fun2 = getsubfield(source2, funparameter); end
if size(source.pos)~=size(fun,1)
error('inconsistent number of vertices in the cortical mesh');
end
if ~isfield(source, 'tri')
error('source.tri missing, this function requires a triangulated cortical sheet as source model');
end
if ~isempty(maskparameter) && ischar(maskparameter)
mask = double(getsubfield(source, maskparameter));
else
mask = 0.5*ones(size(fun));
end
xparam = source.(xparam);
if length(xparam)~=size(fun,2)
error('inconsistent size of "%s" compared to "%s"', cfg.funparameter, cfg.xparam);
end
if ~isempty(yparam)
yparam = source.(yparam);
if length(yparam)~=size(fun,3)
error('inconsistent size of "%s" compared to "%s"', cfg.funparameter, cfg.yparam);
end
end
if isempty(xlim)
xlim(1) = min(xparam);
xlim(2) = max(xparam);
end
xbeg = nearest(xparam, xlim(1));
xend = nearest(xparam, xlim(2));
% update the configuration
cfg.xlim = xparam([xbeg xend]);
if ~isempty(yparam)
if isempty(ylim)
ylim(1) = min(yparam);
ylim(2) = max(yparam);
end
ybeg = nearest(yparam, ylim(1));
yend = nearest(yparam, ylim(2));
% update the configuration
cfg.ylim = xparam([ybeg yend]);
hasyparam = true;
else
% this allows us not to worry about the yparam any more
yparam = nan;
ybeg = 1;
yend = 1;
cfg.ylim = [];
hasyparam = false;
end
% make a subselection of the data
xparam = xparam(xbeg:xend);
yparam = yparam(ybeg:yend);
fun = fun(:,xbeg:xend,ybeg:yend);
if nargin>2, fun2 = fun2(:,xbeg:xend,ybeg:yend); end
mask = mask(:,xbeg:xend,ybeg:yend);
clear xbeg xend ybeg yend
if isempty(zlim)
zlim(1) = min(fun(:));
zlim(2) = max(fun(:));
% update the configuration
cfg.zlim = zlim;
end
if isempty(olim)
olim(1) = min(mask(:));
olim(2) = max(mask(:));
if olim(1)==olim(2)
olim(1) = 0;
olim(2) = 1;
end
% update the configuration
cfg.alim = olim;
end
% collect the data and the options to be used in the figure
opt.cfg = cfg;
opt.xparam = xparam;
opt.yparam = yparam;
opt.xval = 0;
opt.yval = 0;
opt.dat = fun;
opt.mask = mask;
opt.pos = source.pos;
opt.tri = source.tri;
opt.vindx = source.inside(:);
opt.speed = 1;
opt.record = 0;
opt.threshold = 0;
opt.frame = 0;
opt.cleanup = false;
% add functional data of optional third input to the opt structure
% FIXME here we should first check whether the meshes correspond!
if nargin>2
opt.dat2 = fun2;
end
% get a handle to a figure
h = gcf;
set(h, 'color', [1 1 1]);
set(h, 'toolbar', 'figure');
set(h, 'visible', 'on');
set(h, 'CloseRequestFcn', @cb_quitbutton);
set(h, 'position', [100 200 700 500]);
set(h, 'windowbuttondownfcn', @cb_getposition);
% get timer object
t = timer;
set(t, 'timerfcn', {@cb_timer, h}, 'period', 0.1, 'executionmode', 'fixedSpacing');
% make the user interface elements
cambutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'light', 'userdata', 'C');
playbutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'play', 'userdata', 'p');
recordbutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'record', 'userdata', 'r');
quitbutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'quit', 'userdata', 'q');
thrmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'downarrow');
thr = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'threshold', 'userdata', 't');
thrplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'uparrow');
spdmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'shift+downarrow');
spd = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'speed','userdata', 's');
spdplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'shift+uparrow');
climmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow');
clim = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'colorlim', 'userdata', 'z');
climplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow');
sliderx = uicontrol('parent', h, 'units', 'normalized', 'style', 'slider', 'string', sprintf('%s = ', cfg.xparam));
stringx = uicontrol('parent', h, 'units', 'normalized', 'style', 'text');
slidery = uicontrol('parent', h, 'units', 'normalized', 'style', 'slider', 'string', sprintf('%s = ', cfg.yparam));
stringy = uicontrol('parent', h, 'units', 'normalized', 'style', 'text');
stringz = uicontrol('parent', h, 'units', 'normalized', 'style', 'text');
set(cambutton, 'position', [0.095 0.28 0.09 0.05], 'callback', @cb_keyboard);
set(quitbutton, 'position', [0.005 0.28 0.09 0.05], 'callback', @cb_keyboard);
set(playbutton, 'position', [0.005 0.22 0.09 0.05], 'callback', @cb_keyboard);
set(recordbutton, 'position', [0.095 0.22 0.09 0.05], 'callback', @cb_keyboard);
set(thrmin, 'position', [0.005 0.16 0.03 0.05], 'callback', @cb_keyboard);
set(thr, 'position', [0.035 0.16 0.12 0.05], 'callback', @cb_keyboard);
set(thrplus, 'position', [0.155 0.16 0.03 0.05], 'callback', @cb_keyboard);
set(climmin, 'position', [0.005 0.10 0.03 0.05], 'callback', @cb_keyboard);
set(clim, 'position', [0.035 0.10 0.12 0.05], 'callback', @cb_keyboard);
set(climplus, 'position', [0.155 0.10 0.03 0.05], 'callback', @cb_keyboard);
set(spdmin, 'position', [0.005 0.04 0.03 0.05], 'callback', @cb_keyboard);
set(spd, 'position', [0.035 0.04 0.12 0.05], 'callback', @cb_keyboard);
set(spdplus, 'position', [0.155 0.04 0.03 0.05], 'callback', @cb_keyboard);
set(sliderx, 'position', [0.01 0.4 0.26 0.03], 'callback', @cb_slider);%[0.200 0.04 0.78 0.03], 'callback', @cb_slider);
set(slidery, 'position', [0.200 0.005 0.78 0.03], 'callback', @cb_slider);
set(stringx, 'position', [0.800 0.93 0.18 0.03]);
set(stringy, 'position', [0.800 0.90 0.18 0.03]);
set(stringz, 'position', [0.650 0.96 0.33 0.03]);
set(stringx, 'string', sprintf('%s = ', cfg.xparam));
set(stringy, 'string', sprintf('%s = ', cfg.yparam));
set(stringz, 'string', sprintf('position = '));
set(stringx, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]);
set(stringy, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]);
set(stringz, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]);
% create axes object to contain the mesh
hx = axes;
set(hx, 'position', [0.4 0.08 0.6 0.8]);
set(hx, 'tag', 'mesh');
if isfield(source, 'sulc')
vdat = source.sulc;
vdat = vdat-min(vdat)+1;
vdat = vdat./max(vdat);
vdat = 0.8.*repmat(vdat,[1 3]);
hs1 = ft_plot_mesh(source, 'edgecolor', 'none', 'vertexcolor', vdat);
else
hs1 = ft_plot_mesh(source, 'edgecolor', 'none', 'facecolor', [0.5 0.5 0.5]);
end
lighting gouraud
hs = ft_plot_mesh(source, 'edgecolor', 'none', 'vertexcolor', 0*opt.dat(:,1,1), 'facealpha', 0*opt.mask(:,1,1));
lighting gouraud
cam1 = camlight('left');
cam2 = camlight('right');
caxis(cfg.zlim);
alim(cfg.alim);
% create axis object to contain a time course
hy = axes;
set(hy, 'position', [0.02 0.5 0.3 0.35]);
set(hy, 'yaxislocation', 'right');
if ~hasyparam
tline = plot(opt.xparam, mean(opt.dat(opt.vindx,:))); hold on;
abc = axis;
axis([opt.xparam(1) opt.xparam(end) abc(3:4)]);
vline = plot(opt.xparam(1)*[1 1], abc(3:4), 'r');
if nargin>2
tline2 = plot(opt.xparam, mean(opt.dat2(opt.vindx,:)), 'r'); hold on;
end
else
error('not yet implemented');
end
set(hy, 'tag', 'timecourse');
% remember the various handles
opt.h = h; % handle to the figure
opt.hs = hs; % handle to the mesh
opt.hx = hx; % handle to the axes containing the mesh
opt.hy = hy; % handle to the axes containing the timecourse
opt.cam = [cam1 cam2]; % handles to the light objects
opt.vline = vline; % handle to the line in the ERF plot
opt.tline = tline; % handle to the ERF
if nargin>2, opt.tline2 = tline2; end
opt.playbutton = playbutton; % handle to the playbutton
opt.recordbutton = recordbutton; % handle to the recordbutton
opt.quitbutton = quitbutton; % handle to the quitbutton
%opt.p = p;
opt.t = t;
%opt.hx = hx;
%opt.hy = hy;
opt.sliderx = sliderx;
opt.slidery = slidery;
opt.stringx = stringx;
opt.stringy = stringy;
opt.stringz = stringz;
if ~hasyparam
set(opt.slidery, 'visible', 'off');
set(opt.stringy, 'visible', 'off');
end
setappdata(h, 'opt', opt);
while opt.cleanup==0
uiwait(h);
opt = getappdata(h, 'opt');
end
stop(opt.t);
if nargout
M = opt.movie;
end
delete(h);
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble callinfo
ft_postamble previous source
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_slider(h, eventdata)
persistent previous_valx previous_valy previous_vindx
if isempty(previous_valx)
previous_valx = 0;
end
if isempty(previous_valy)
previous_valy = 0;
end
h = getparent(h);
opt = getappdata(h, 'opt');
valx = get(opt.sliderx, 'value');
valx = round(valx*(size(opt.dat,2)-1))+1;
valx = min(valx, size(opt.dat,2));
valx = max(valx, 1);
valy = get(opt.slidery, 'value');
valy = round(valy*(size(opt.dat,3)-1))+1;
valy = min(valy, size(opt.dat,3));
valy = max(valy, 1);
mask = squeeze(opt.mask(:,valx,valy));
mask(opt.dat(:,valx,valy)<opt.threshold) = 0;
% update stuff
if previous_valx~=valx || previous_valy~=valy
% update strings
set(opt.stringx, 'string', sprintf('%s = %3.3f\n', opt.cfg.xparam, opt.xparam(valx)));
set(opt.stringy, 'string', sprintf('%s = %3.3f\n', opt.cfg.yparam, opt.yparam(valy)));
% update data in mesh
set(opt.hs, 'FaceVertexCData', squeeze(opt.dat(:,valx,valy)));
set(opt.hs, 'FaceVertexAlphaData', mask);
set(opt.vline, 'xdata', [1 1]*opt.xparam(valx));
end
% update ERF-plot
set(opt.hy, 'ylim', opt.cfg.zlim);
set(opt.vline, 'ydata', opt.cfg.zlim);
if ~(numel(previous_vindx)==numel(opt.vindx) && all(previous_vindx==opt.vindx))
tmp = mean(opt.dat(opt.vindx,:,valy),1);
set(opt.tline, 'ydata', tmp);
%set(opt.hy, 'ylim', [min(tmp(:)) max(tmp(:))]);
%set(opt.vline, 'ydata', [min(tmp(:)) max(tmp(:))]);
if isfield(opt, 'dat2')
tmp = mean(opt.dat2(opt.vindx,:,valy),1);
set(opt.tline2, 'ydata', tmp);
end
set(opt.hy, 'yaxislocation', 'right');
set(opt.stringz, 'string', sprintf('position = [%2.1f, %2.1f, %2.1f]', opt.pos(opt.vindx,:)));
end
if opt.record
opt.frame = opt.frame + 1;
opt.movie(opt.frame) = getframe(opt.h);
end
setappdata(h, 'opt', opt);
previous_valx = valx;
previous_valy = valy;
previous_vindx = opt.vindx;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_playbutton(h, eventdata)
opt = getappdata(h, 'opt');
if strcmp(get(opt.playbutton, 'string'), 'pause')
stop(opt.t);
set(opt.playbutton, 'string', 'play');
else
start(opt.t);
set(opt.playbutton, 'string', 'pause');
end
setappdata(h, 'opt', opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_quitbutton(h, eventdata)
opt = getappdata(h, 'opt');
opt.cleanup = 1;
setappdata(h, 'opt', opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_recordbutton(h, eventdata)
opt = getappdata(h, 'opt');
if strcmp(get(opt.recordbutton, 'string'), 'stop')
opt.record = 0;
set(opt.recordbutton, 'string', 'record');
else
opt.record = 1;
set(opt.recordbutton, 'string', 'stop');
end
setappdata(h, 'opt', opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_timer(obj, info, h)
opt = getappdata(h, 'opt');
delta = opt.speed/size(opt.dat,2);
val = get(opt.sliderx, 'value');
val = val + delta;
if val>1
val = val-1;
end
set(opt.sliderx, 'value', val);
setappdata(h, 'opt', opt);
cb_slider(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_alim(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
switch get(h, 'String')
case '+'
alim(alim*sqrt(2));
case '-'
alim(alim/sqrt(2));
end % switch
guidata(h, opt);
uiresume;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_getposition(h, eventdata)
h = getparent(h);
opt = getappdata(h, 'opt');
if strcmp(get(get(h, 'currentaxes'), 'tag'), 'timecourse')
% get the current point
% pos = get(opt.hy, 'currentpoint');
% set(opt.sliderx, 'value') = pos(1);
%
elseif strcmp(get(get(h, 'currentaxes'), 'tag'), 'mesh')
% get the current point, which is defined as the intersection through the
% axis-box (in 3D)
pos = get(opt.hx, 'currentpoint');
% get the intersection with the mesh
[ipos, d] = intersect_line(opt.pos, opt.tri, pos(1,:), pos(2,:));
[md, ix] = min(abs(d));
dpos = opt.pos - ipos(ix*ones(size(opt.pos,1),1),:);
opt.vindx = nearest(sum(dpos.^2,2),0);
end
setappdata(h, 'opt', opt);
cb_slider(h);
uiresume;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_keyboard(h, eventdata)
if isempty(eventdata)
% determine the key that corresponds to the uicontrol element that was activated
key = get(h, 'userdata');
else
% determine the key that was pressed on the keyboard
key = parseKeyboardEvent(eventdata);
end
% get focus back to figure
if ~strcmp(get(h, 'type'), 'figure')
set(h, 'enable', 'off');
drawnow;
set(h, 'enable', 'on');
end
h = getparent(h);
opt = getappdata(h, 'opt');
switch key
case 'leftarrow' % change colorlim
opt.cfg.zlim(2) = (opt.cfg.zlim(2)-opt.cfg.zlim(1))./sqrt(2);
setappdata(h, 'opt', opt);
caxis(opt.cfg.zlim);
case 'rightarrow' % change colorlim
opt.cfg.zlim(2) = max(opt.cfg.zlim(2).*sqrt(2), opt.cfg.zlim(1));
setappdata(h, 'opt', opt);
caxis(opt.cfg.zlim);
case 'shift+leftarrow'
case 'shift+rightarrow'
case 'uparrow' % enhance threshold
opt.threshold = opt.threshold+0.01.*max(opt.dat(:));
setappdata(h, 'opt', opt);
case 'downarrow' % lower threshold
opt.threshold = opt.threshold-0.01.*max(opt.dat(:));
setappdata(h, 'opt', opt);
case 'shift+uparrow' % change speed
opt.speed = opt.speed*sqrt(2);
setappdata(h, 'opt', opt);
case 'shift+downarrow'
opt.speed = opt.speed/sqrt(2);
opt.speed = max(opt.speed, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
case 'ctrl+uparrow' % change channel
case 'C' % update camera position
camlight(opt.cam(1), 'left');
camlight(opt.cam(2), 'right');
case 'p'
cb_playbutton(h);
case 'q'
cb_quitbutton(h);
case 'r'
cb_recordbutton(h);
case 's'
% select the speed
response = inputdlg('speed', 'specify', 1, {num2str(opt.speed)});
if ~isempty(response)
opt.speed = str2double(response);
setappdata(h, 'opt', opt);
end
case 't'
% select the threshold
response = inputdlg('threshold', 'specify', 1, {num2str(opt.threshold)});
if ~isempty(response)
opt.threshold = str2double(response);
setappdata(h, 'opt', opt);
end
case 'z'
% select the threshold
response = inputdlg('colorlim', 'specify', 1, {num2str(opt.cfg.zlim(2))});
if ~isempty(response)
opt.cfg.zlim(2) = str2double(response);
setappdata(h, 'opt', opt);
end
case 'control+control'
% do nothing
case 'shift+shift'
% do nothing
case 'alt+alt'
% do nothing
otherwise
setappdata(h, 'opt', opt);
cb_help(h);
end
cb_slider(h);
uiresume(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = getparent(h)
p = h;
while p~=0
h = p;
p = get(h, 'parent');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key = parseKeyboardEvent(eventdata)
key = eventdata.Key;
% handle possible numpad events (different for Windows and UNIX systems)
% NOTE: shift+numpad number does not work on UNIX, since the shift
% modifier is always sent for numpad events
if isunix()
shiftInd = match_str(eventdata.Modifier, 'shift');
if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd)
% now we now it was a numpad keystroke (numeric character sent AND
% shift modifier present)
key = eventdata.Character;
eventdata.Modifier(shiftInd) = []; % strip the shift modifier
end
elseif ispc()
if strfind(eventdata.Key, 'numpad')
key = eventdata.Character;
end
end
if ~isempty(eventdata.Modifier)
key = [eventdata.Modifier{1} '+' key];
end
|
github
|
philippboehmsturm/antx-master
|
ft_sourcestatistics.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_sourcestatistics.m
| 20,635 |
utf_8
|
1595794cee3bcfd803961c94261f78ba
|
function [stat] = ft_sourcestatistics(cfg, varargin)
% FT_SOURCESTATISTICS computes the probability for a given null-hypothesis using
% a parametric statistical test or using a non-parametric randomization test.
%
% Use as
% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)
% where the input data is the result from FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES
% or FT_SOURCEGRANDAVERAGE. The source structures should be spatially alligned
% to each other and should have the same positions for the source grid.
%
% The configuration should contain the following option for data selection
% cfg.parameter = string, describing the functional data to be processed, e.g. 'pow', 'nai' or 'coh'
%
% Furthermore, the configuration should contain:
% cfg.method = different methods for calculating the probability of the null-hypothesis,
% 'montecarlo' uses a non-parametric randomization test to get a Monte-Carlo estimate of the probability,
% 'analytic' uses a parametric test that results in analytic probability,
% 'stats' (soon deprecated) uses a parametric test from the Matlab statistics toolbox,
%
% You can restrict the statistical analysis to regions of interest (ROIs)
% or to the average value inside ROIs using the following options:
% cfg.atlas = filename of the atlas
% cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas
% cfg.avgoverroi = 'yes' or 'no' (default = 'no')
% cfg.hemisphere = 'left', 'right', 'both', 'combined', specifying this is
% required when averaging over regions
% cfg.inputcoord = 'mni' or 'tal', the coordinate system in which your source
% reconstruction is expressed
%
% The other cfg options depend on the method that you select. You
% should read the help of the respective subfunction FT_STATISTICS_XXX
% for the corresponding configuration options and for a detailed
% explanation of each method.
%
% See also FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES, FT_SOURCEGRANDAVERAGE
% Deprecated cfg.method options:
% 'parametric' uses the Matlab statistics toolbox (very similar to 'stats'),
% 'randomization' uses randomization of the data prior to source reconstruction,
% 'randcluster' uses randomization of the data prior to source reconstruction
% in combination with spatial clusters.
% Copyright (C) 2005-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourcestatistics.m 7393 2013-01-23 14:33:27Z jorhor $
revision = '$Id: ft_sourcestatistics.m 7393 2013-01-23 14:33:27Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar varargin
% this wrapper should be compatible with the already existing statistical
% functions that only work for source input data
if ~isfield(cfg, 'implementation'), cfg.implementation = 'old'; end
cfg = ft_checkconfig(cfg, 'forbidden', {'trials'});
if strcmp(cfg.implementation, 'old'),
%--------------------------------
% use the original implementation
% check if the input data is valid for this function
for i=1:length(varargin)
if isfield(cfg, 'roi') && ~isempty(cfg.roi)
varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'source', 'feedback', 'no', 'inside', 'index');
else
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'source', 'volume'}, 'feedback', 'no', 'inside', 'index');
end
end
if strcmp(cfg.method, 'parametric')
% use the source-specific statistical subfunction
error('This cfg.method option is deprecated');
stat = sourcestatistics_parametric(cfg, varargin{:});
elseif strcmp(cfg.method, 'randomization')
% use the source-specific statistical subfunction
error('This cfg.method option is deprecated');
stat = sourcestatistics_randomization(cfg, varargin{:});
elseif strcmp(cfg.method, 'randcluster')
% use the source-specific statistical subfunction
error('This cfg.method option is deprecated');
stat = sourcestatistics_randcluster(cfg, varargin{:});
else
[stat, cfg] = statistics_wrapper(cfg, varargin{:});
end
elseif strcmp(cfg.implementation, 'new')
%---------------------------
% use the new implementation
issource = ft_datatype(varargin{1}, 'source');
isvolume = ft_datatype(varargin{1}, 'volume');
% check if the input data is valid for this function
for i=1:length(varargin)
if isfield(cfg, 'roi') && ~isempty(cfg.roi)
% FIXME implement roi-based statistics for the new implementation
% (code is copied over from the old implementation but not yet tested
error('roi based sourcestatistics is not yet implemented for the new implementation');
varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'source', 'feedback', 'no', 'inside', 'index');
else
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'source', 'volume'}, 'feedback', 'no', 'inside', 'index', 'sourcerepresentation', 'new');
if strcmp(cfg.parameter, 'pow') && ~isfield(varargin{i}, 'pow'),
varargin{i} = ft_checkdata(varargin{i}, 'sourcerepresentation', 'new', 'haspow', 'yes');
end
end
end
if any(strcmp(cfg.method, {'parametric' 'randomization' 'randcluster'}))
% FIXME only supported for old-style source representation
for i = 1:numel(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'sourcerepresentation', 'old');
end
if exist(['ft_statistics_',cfg.method]),
statmethod = str2func(['ft_statistics_' cfg.method]);
else
error(sprintf('could not find the corresponding function for cfg.method="%s"\n', cfg.method));
end
stat = statmethod(cfg, varargin{:});
else
% convert representation of input data to new style
for i = 1:numel(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'sourcerepresentation', 'new');
end
% check the input configuration
cfg = ft_checkconfig(cfg, 'renamed', {'approach', 'method'});
cfg = ft_checkconfig(cfg, 'required', {'method', 'parameter'});
cfg = ft_checkconfig(cfg, 'forbidden', {'transform'});
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'latency'), cfg.latency = 'all'; end
if ~isfield(cfg, 'frequency'), cfg.frequency = 'all'; end
if ~isfield(cfg, 'roi'), cfg.roi = []; end
if ~isfield(cfg, 'avgoverchan'), cfg.avgoverchan = 'no'; end
if ~isfield(cfg, 'avgovertime'), cfg.avgovertime = 'no'; end
if ~isfield(cfg, 'avgoverfreq'), cfg.avgoverfreq = 'no'; end
if ~isfield(cfg, 'avgoverroi'), cfg.avgoverroi = 'no'; end
% test that all source inputs have the same dimensions and are spatially aligned
for i=2:length(varargin)
if isfield(varargin{1}, 'dim') && (numel(varargin{i}.dim)~=length(varargin{1}.dim) || ~all(varargin{i}.dim==varargin{1}.dim))
error('dimensions of the source reconstructions do not match, use VOLUMENORMALISE first');
end
if isfield(varargin{1}, 'pos') && (numel(varargin{i}.pos(:))~=numel(varargin{1}.pos(:)) || ~all(varargin{i}.pos(:)==varargin{1}.pos(:)))
error('grid locations of the source reconstructions do not match, use VOLUMENORMALISE first');
end
end
Nsource = length(varargin);
Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside);
%FIXME ft_selectdata should be used for the subselection
%FIXME ft_selectdata has to be adjusted to work with new style source data
%if isfield(varargin{1}, 'freq') && ~strcmp(cfg.frequency, 'all'),
% for i=1:length(varargin)
% varargin{i} = ft_selectdata(varargin{i}, 'foilim', cfg.frequency, ...
% 'avgoverfreq', cfg.avgoverfreq);
% end
%end
% this part contains the functionality of the old statistics_wrapper
% with source data in the input
if ~isempty(cfg.roi)
if ischar(cfg.roi)
cfg.roi = {cfg.roi};
end
% the source representation should specify the position of each voxel in MNI coordinates
x = varargin{1}.pos(:,1); % this is from left (negative) to right (positive)
% determine the mask to restrict the subsequent analysis
% process each of the ROIs, and optionally also left and/or right seperately
roimask = {};
roilabel = {};
for i=1:length(cfg.roi)
tmpcfg.roi = cfg.roi{i};
tmpcfg.inputcoord = cfg.inputcoord;
tmpcfg.atlas = cfg.atlas;
tmp = ft_volumelookup(tmpcfg, varargin{1});
if strcmp(cfg.avgoverroi, 'no') && ~isfield(cfg, 'hemisphere')
% no reason to deal with seperated left/right hemispheres
cfg.hemisphere = 'combined';
end
if strcmp(cfg.hemisphere, 'left')
tmp(x>=0) = 0; % exclude the right hemisphere
roimask{end+1} = tmp;
roilabel{end+1} = ['Left ' cfg.roi{i}];
elseif strcmp(cfg.hemisphere, 'right')
tmp(x<=0) = 0; % exclude the right hemisphere
roimask{end+1} = tmp;
roilabel{end+1} = ['Right ' cfg.roi{i}];
elseif strcmp(cfg.hemisphere, 'both')
% deal seperately with the voxels on the left and right side of the brain
tmpL = tmp; tmpL(x>=0) = 0; % exclude the right hemisphere
tmpR = tmp; tmpR(x<=0) = 0; % exclude the left hemisphere
roimask{end+1} = tmpL;
roimask{end+1} = tmpR;
roilabel{end+1} = ['Left ' cfg.roi{i}];
roilabel{end+1} = ['Right ' cfg.roi{i}];
clear tmpL tmpR
elseif strcmp(cfg.hemisphere, 'combined')
% all voxels of the ROI can be combined
roimask{end+1} = tmp;
roilabel{end+1} = cfg.roi{i};
else
error('incorrect specification of cfg.hemisphere');
end
clear tmp
end % for each roi
% note that avgoverroi=yes is implemented differently at a later stage
% avgoverroi=no is implemented using the inside/outside mask
if strcmp(cfg.avgoverroi, 'no')
for i=2:length(roimask)
% combine them all in the first mask
roimask{1} = roimask{1} | roimask{i};
end
roimask = roimask{1}; % only keep the combined mask
% the source representation should have an inside and outside vector containing indices
sel = find(~roimask);
varargin{1}.inside = setdiff(varargin{1}.inside, sel);
varargin{1}.outside = union(varargin{1}.outside, sel);
clear roimask roilabel
end % if avgoverroi=no
end % if ~isempty cfg.roi
% get the required source level data
[dat, cfg] = getfunctional(cfg, varargin{:});
% note that avgoverroi=no is implemented differently at an earlier stage
if strcmp(cfg.avgoverroi, 'yes')
tmp = zeros(length(roimask), size(dat,2));
for i=1:length(roimask)
% the data only reflects those points that are inside the brain,
% the atlas-based mask reflects points inside and outside the brain
roi = roimask{i}(varargin{1}.inside);
tmp(i,:) = mean(dat(roi,:), 1);
end
% replace the original data with the average over each ROI
dat = tmp;
clear tmp roi roimask
% remember the ROIs
cfg.dimord = 'roi';
end
end
%get the design from the information in the cfg and data
if ~isfield(cfg, 'design'),
cfg.design = data.design;
cfg = prepare_design(cfg);
end
if size(cfg.design, 2)~=size(dat, 2)
cfg.design = transpose(cfg.design);
end
% determine the function handle to the intermediate-level statistics function
if exist(['ft_statistics_' cfg.method])
statmethod = str2func(['ft_statistics_' cfg.method]);
else
error(sprintf('could not find the corresponding function for cfg.method="%s"\n', cfg.method));
end
fprintf('using "%s" for the statistical testing\n', func2str(statmethod));
% check that the design completely describes the data
if size(dat,2) ~= size(cfg.design,2)
error('the size of the design matrix does not match the number of observations in the data');
end
% determine the number of output arguments
try
% the nargout function in Matlab 6.5 and older does not work on function handles
num = nargout(statmethod);
catch
num = 1;
end
% perform the statistical test
if strcmp(func2str(statmethod),'ft_statistics_montecarlo')
% because ft_statistics_montecarlo (or to be precise, clusterstat)
% requires to know whether it is getting source data,
% the following (ugly) work around is necessary
if num>1
[stat, cfg] = statmethod(cfg, dat, cfg.design, 'issource', 1);
else
[stat] = statmethod(cfg, dat, cfg.design, 'issource', 1);
end
else
if num>1
[stat, cfg] = statmethod(cfg, dat, cfg.design);
else
[stat] = statmethod(cfg, dat, cfg.design);
end
end
if isstruct(stat)
% the statistical output contains multiple elements, e.g. F-value, beta-weights and probability
statfield = fieldnames(stat);
else
% only the probability was returned as a single matrix, reformat into a structure
dum = stat; stat = []; % this prevents a Matlab warning that appears from release 7.0.4 onwards
stat.prob = dum;
statfield = fieldnames(stat);
end
% add descriptive information to the output and rehape into the input format
if isempty(cfg.roi) || strcmp(cfg.avgoverroi, 'no')
% remember the definition of the volume, assume that they are identical for all input arguments
try, stat.dim = varargin{1}.dim; end
try, stat.xgrid = varargin{1}.xgrid; end
try, stat.ygrid = varargin{1}.ygrid; end
try, stat.zgrid = varargin{1}.zgrid; end
try, stat.inside = varargin{1}.inside; end
try, stat.outside = varargin{1}.outside; end
try, stat.pos = varargin{1}.pos; end
try, stat.transform = varargin{1}.transform; end
else
stat.inside = 1:length(roilabel);
stat.outside = [];
stat.label = roilabel(:);
end
% additional descriptive fields
hasfreq = strcmp(cfg.avgoverfreq, 'no') && isfield(varargin{1},'freq');
hastime = strcmp(cfg.avgovertime, 'no') && isfield(varargin{1},'time');
stat.dimord = 'pos_';
if hasfreq,
stat.dimord = [stat.dimord, 'freq_'];
stat.freq = varargin{1}.freq;
nfreq = numel(varargin{1}.freq);
else
nfreq = 1;
end
if hastime,
stat.dimord = [stat.dimord, 'time_'];
stat.time = varargin{1}.time;
ntime = numel(varargin{1}.time);
else
ntime = 1;
end
stat.dimord = stat.dimord(1:end-1);
if issource,
if hasfreq,
newdim = [size(stat.pos,1) nfreq ntime];
else
newdim = [size(stat.pos,1) ntime];
end
elseif isvolume,
if hasfreq,
newdim = [stat.dim nfreq ntime];
else
newdim = [stat.dim ntime];
end
end
for i=1:length(statfield)
tmp = getsubfield(stat, statfield{i});
tmp2 = [];
ntmp = numel(tmp);
if hasfreq,
tmpdim = [ntmp/(nfreq*ntime) nfreq ntime];
else
tmpdim = [ntmp/ntime ntime];
end
if isfield(varargin{1}, 'inside') && numel(tmp)==nfreq*ntime*length(varargin{1}.inside)
% the statistic was only computed on voxels that are inside the brain
% sort the inside and outside voxels back into their original place
if islogical(tmp)
if hasfreq,
tmp2 = logical(zeros(prod(varargin{1}.dim),nfreq,ntime));
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/(nfreq*ntime) nfreq ntime]);
else
tmp2 = logical(zeros(prod(varargin{1}.dim),nfreq,ntime));
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/ntime ntime]);
end
else
if hasfreq,
tmp2 = nan(prod(varargin{1}.dim),nfreq,ntime);
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/(nfreq*ntime) nfreq ntime]);
else
tmp2 = nan(prod(varargin{1}.dim),nfreq,ntime);
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/ntime ntime]);
end
end
end
if numel(tmp2)==prod(newdim)
% reshape the statistical volumes into the original format
stat = setsubfield(stat, statfield{i}, reshape(tmp2, newdim));
end
end
else
error('cfg.implementation can be only old or new');
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
ft_postamble history stat
ft_postamble savevar stat
%-----------------------------------------------------
%subfunction to extract functional data from the input
%and convert it into a 2D representation
function [dat, cfg] = getfunctional(cfg, varargin)
%FIXME think of how this generalizes to volumetric data (boolean inside etc)
Nsource = numel(varargin);
Nvox = size(varargin{1}.pos, 1);
inside = varargin{1}.inside;
Ninside = numel(inside);
dimord = varargin{1}.([cfg.parameter,'dimord']);
dimtok = tokenize(dimord, '_');
%check whether the requested parameter is represented as cell-array
x1 = strfind(dimord, '{');
x2 = strfind(dimord, '}');
if ~isempty(x1) && ~isempty(x2)
cellparam = 1;
cellsiz = size(varargin{1}.(cfg.parameter));
%this only explicitly keeps the first singleton dimension
%the last to be removed
cellsiz(find(cellsiz(2:end)==1)+1) = [];
cellsiz(cellsiz==Nvox) = Ninside;
else
cellparam = 0;
end
%check whether there are single observations/subjects in the data
rptdim = ~cellfun(@isempty, strfind(dimtok, 'rpt')) | ~cellfun(@isempty, strfind(dimtok, 'subj'));
hasrpt = sum(rptdim);
if hasrpt && Nsource>1,
error('only a single input with multiple observations or multiple inputs with a single observation are supported');
end
if hasrpt,
if cellparam,
tmpsiz = [cellsiz size(varargin{1}.(cfg.parameter){inside(1)})];
tmp = zeros(tmpsiz);
%FIXME what about volumetric data?
for k = 1:Ninside
tmp(k,:,:,:,:,:) = varargin{1}.(cfg.parameter){inside(k)};
end
%tmp = cell2mat(varargin{1}.(cfg.parameter)(inside,:,:,:,:));
else
if find(rptdim)==1,
tmp = varargin{1}.(cfg.parameter)(:,inside,:,:,:);
else
tmp = varargin{1}.(cfg.parameter)(inside,:,:,:,:);
end
end
if numel(rptdim)==1,
rptdim = [rptdim 0];
end
%put the repetition dimension to the last dimension
tmp = permute(tmp, [find(rptdim==0) find(rptdim==1)]);
%reshape the data to 2D
siz = size(tmp);
dat = reshape(tmp, [prod(siz(1:end-1)) siz(end)]);
else
for k = 1:Nsource
%check for cell-array representation in the input data
%FIXME this assumes positions to be in the first dimension always
%FIXME what about volumetric dadta
if cellparam
tmp = cell2mat(varargin{k}.(cfg.parameter)(inside,:,:,:,:));
else
tmp = varargin{k}.(cfg.parameter)(inside,:,:,:,:);
end
%allocate memory
if k==1, dat = zeros(numel(tmp), Nsource); end
%reshape the data
siz = size(tmp);
dat(:,k) = tmp(:);
end
end
%cfg.dim = varargin{1}.dim;
%cfg.inside = varargin{1}.inside; %FIXME take the intersection between all inputs
%FIXME don't do the previous lines in order to take the unfolded inside
%across the dimensions in the input and to get the 4D dimensionality
%correct
cfg.dimord = 'voxel';
cfg.origdim = [cfg.dim siz(2:end-1)];
|
github
|
philippboehmsturm/antx-master
|
ft_sourcedescriptives.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_sourcedescriptives.m
| 48,234 |
utf_8
|
df813b6e3dc10a6821632c72738012e6
|
function [source] = ft_sourcedescriptives(cfg, source)
% FT_SOURCEDESCRIPTIVES computes descriptive parameters of the source
% analysis results.
%
% Use as
% [source] = ft_sourcedescriptives(cfg, source)
%
% where cfg is a structure with the configuration details and source is the
% result from a beamformer source estimation. The configuration can contain
% cfg.cohmethod = 'regular', 'lambda1', 'canonical'
% cfg.powmethod = 'regular', 'lambda1', 'trace', 'none'
% cfg.supmethod = 'chan_dip', 'chan', 'dip', 'none' (default)
% cfg.projectmom = 'yes' or 'no' (default = 'no')
% cfg.eta = 'yes' or 'no' (default = 'no')
% cfg.kurtosis = 'yes' or 'no' (default = 'no')
% cfg.keeptrials = 'yes' or 'no' (default = 'no')
% cfg.keepcsd = 'yes' or 'no' (default = 'no')
% cfg.keepnoisecsd = 'yes' or 'no' (default = 'no')
% cfg.keepmom = 'yes' or 'no' (default = 'yes')
% cfg.keepnoisemom = 'yes' or 'no' (default = 'yes')
% cfg.resolutionmatrix = 'yes' or 'no' (default = 'no')
% cfg.feedback = 'no', 'text' (default), 'textbar', 'gui'
%
%
% The following option only applies to LCMV single-trial timecourses.
% cfg.fixedori = 'within_trials' or 'over_trials' (default = 'over_trials')
%
% You can apply a custom mathematical transformation such as a log-transform
% on the estimated power using
% cfg.transform = string describing the transformation (default is [])
% The nai, i.e. neural activity index (power divided by projected noise),
% is computed prior to applying the optional transformation. Subsequently,
% the transformation is applied on the power and on the projected noise
% using "feval". A useful transformation is for example 'log' or 'log10'.
%
% If repeated trials are present that have undergone some sort of
% resampling (i.e. jackknife, bootstrap, singletrial or rawtrial), the mean,
% variance and standard error of mean will be computed for all source
% parameters. This is done after applying the optional transformation
% on the power and projected noise.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS
% Copyright (C) 2004-2007, Robert Oostenveld & Jan-Mathijs Schoffelen
% Copyright (C) 2010, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourcedescriptives.m 7393 2013-01-23 14:33:27Z jorhor $
revision = '$Id: ft_sourcedescriptives.m 7393 2013-01-23 14:33:27Z jorhor $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar source
% check if the input data is valid for this function
source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes');
cfg = ft_checkconfig(cfg, 'forbidden', {'trials'});
% set the defaults
cfg.transform = ft_getopt(cfg, 'transform', []);
cfg.projectmom = ft_getopt(cfg, 'projectmom', 'no');% if yes -> svdfft
cfg.numcomp = ft_getopt(cfg, 'numcomp', 1);
cfg.powmethod = ft_getopt(cfg, 'powmethod', []);% see below
cfg.cohmethod = ft_getopt(cfg, 'cohmethod', []);% see below
cfg.feedback = ft_getopt(cfg, 'feedback', 'textbar');
cfg.supmethod = ft_getopt(cfg, 'supmethod', 'none');
cfg.resolutionmatrix = ft_getopt(cfg, 'resolutionmatrix', 'no');
cfg.eta = ft_getopt(cfg, 'eta', 'no');
cfg.fa = ft_getopt(cfg, 'fa', 'no');
cfg.kurtosis = ft_getopt(cfg, 'kurtosis', 'no');
cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no');
cfg.keepcsd = ft_getopt(cfg, 'keepcsd', 'no');
cfg.keepmom = ft_getopt(cfg, 'keepmom', 'yes');
cfg.keepnoisecsd = ft_getopt(cfg, 'keepnoisecsd', 'no');
cfg.keepnoisemom = ft_getopt(cfg, 'keepnoisemom', 'yes');
cfg.fwhm = ft_getopt(cfg, 'fwhm', 'no');
cfg.fwhmremovecenter = ft_getopt(cfg, 'fwhmremovecenter', 0);
cfg.fixedori = ft_getopt(cfg, 'fixedori', 'over_trials');
% only works for minimumnormestimate
cfg.demean = ft_getopt(cfg, 'demean', 'yes');
cfg.baselinewindow = ft_getopt(cfg, 'baselinewindow', [-inf 0]);
cfg.zscore = ft_getopt(cfg, 'zscore', 'yes');
zscore = strcmp(cfg.zscore, 'yes');
demean = strcmp(cfg.demean, 'yes');
% get desired method from source structure
source.method = ft_getopt(source,'method',[]);
% this is required for backward compatibility with the old sourceanalysis
if isfield(source, 'method') && strcmp(source.method, 'randomized')
source.method = 'randomization';
elseif isfield(source, 'method') && strcmp(source.method, 'permuted')
source.method = 'permutation';
elseif isfield(source, 'method') && strcmp(source.method, 'jacknife')
source.method = 'jackknife';
end
% determine the type of data, this is only relevant for a few specific types
ispccdata = isfield(source, 'avg') && isfield(source.avg, 'csdlabel');
islcmvavg = isfield(source, 'avg') && isfield(source, 'time') && isfield(source.avg, 'mom') && size(source.avg.pow, 2)==1;
islcmvtrl = isfield(source, 'trial') && isfield(source, 'time') && isfield(source.trial, 'mom');
ismneavg = isfield(source, 'avg') && isfield(source, 'time') && isfield(source.avg, 'mom') && size(source.avg.pow, 2)==numel(source.time);
% check the consistency of the defaults
if strcmp(cfg.projectmom, 'yes')
if isempty(cfg.powmethod)
cfg.powmethod = 'regular'; % set the default
elseif ~strcmp(cfg.powmethod, 'regular')
error('unsupported powmethod in combination with projectmom');
end
if isempty(cfg.cohmethod)
cfg.cohmethod = 'regular';% set the default
elseif ~strcmp(cfg.cohmethod, 'regular')
error('unsupported cohmethod in combination with projectmom');
end
else
if isempty(cfg.powmethod)
cfg.powmethod = 'lambda1'; % set the default
end
if isempty(cfg.cohmethod)
cfg.cohmethod = 'lambda1'; % set the default
end
end
% this is required for backward compatibility with an old version of sourcedescriptives
if isfield(cfg, 'singletrial'), cfg.keeptrials = cfg.singletrial; end
% do a validity check on the input data and specified options
if strcmp(cfg.resolutionmatrix, 'yes')
if ~isfield(source.avg, 'filter')
error('The computation of the resolution matrix requires keepfilter=''yes'' in sourceanalysis.');
elseif ~isfield(source, 'leadfield')
error('The computation of the resolution matrix requires keepleadfield=''yes'' in sourceanalysis.');
end
end
if strcmp(cfg.fwhm, 'yes')
if ~isfield(source.avg, 'filter')
error('The computation of the fwhm requires keepfilter=''yes'' in sourceanalysis.');
end
end
if strcmp(cfg.eta, 'yes') && strcmp(cfg.cohmethod, 'svdfft'),
error('eta cannot be computed in combination with the application of svdfft');
end
if strcmp(cfg.keeptrials, 'yes') && ~strcmp(cfg.supmethod, 'none'),
error('you cannot keep trials when you want to partialize something');
end
% set some flags for convenience
isnoise = isfield(source, 'avg') && isfield(source.avg, 'noisecsd');
keeptrials = strcmp(cfg.keeptrials, 'yes');
projectmom = strcmp(cfg.projectmom, 'yes');
% determine the subfunction used for computing power
switch cfg.powmethod
case 'regular'
powmethodfun = @powmethod_regular;
case 'lambda1'
powmethodfun = @powmethod_lambda1;
case 'trace'
powmethodfun = @powmethod_trace;
case 'none'
powmethodfun = [];
otherwise
error('unsupported powmethod');
end
if ispccdata
% the source reconstruction was computed using the pcc beamformer
Ndipole = length(source.inside) + length(source.outside);
dipsel = match_str(source.avg.csdlabel, 'scandip');
refchansel = match_str(source.avg.csdlabel, 'refchan');
refdipsel = match_str(source.avg.csdlabel, 'refdip');
supchansel = match_str(source.avg.csdlabel, 'supchan');
supdipsel = match_str(source.avg.csdlabel, 'supdip');
% cannot handle reference channels and reference dipoles simultaneously
if length(refchansel)>0 && length(refdipsel)>0
error('cannot simultaneously handle reference channels and reference dipole');
end
% these are only used to count the number of reference/suppression dipoles and channels
refsel = [refdipsel refchansel];
supsel = [supdipsel supchansel];
if projectmom
source.avg.ori = cell(1, Ndipole);
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'projecting dipole moment %d/%d\n', diplop, length(source.inside));
i = source.inside(diplop);
mom = source.avg.mom{i}(dipsel, :);
ref = source.avg.mom{i}(refdipsel, :);
sup = source.avg.mom{i}(supdipsel, :);
refchan = source.avg.mom{i}(refchansel, :);
supchan = source.avg.mom{i}(supchansel, :);
% compute the projection of the scanning dipole along the direction of the dominant amplitude
if length(dipsel)>1, [mom, rmom] = svdfft(mom, cfg.numcomp, source.cumtapcnt); else rmom = []; end
source.avg.ori{source.inside(diplop)} = rmom;
% compute the projection of the reference dipole along the direction of the dominant amplitude
if length(refdipsel)>1, [ref, rref] = svdfft(ref, 1, source.cumtapcnt); else rref = []; end
% compute the projection of the supression dipole along the direction of the dominant amplitude
if length(supdipsel)>1, [sup, rsup] = svdfft(sup, 1, source.cumtapcnt); else rsup = []; end
% compute voxel-level fourier-matrix
source.avg.mom{i} = cat(1, mom, ref, sup, refchan, supchan);
% create rotation-matrix
rotmat = zeros(0, length(source.avg.csdlabel));
if ~isempty(rmom),
rotmat = [rotmat; rmom zeros(1,length([refsel(:);supsel(:)]))];
end
if ~isempty(rref),
rotmat = [rotmat; zeros(1, length([dipsel])), rref, zeros(1,length([refchansel(:);supsel(:)]))];
end
if ~isempty(rsup),
rotmat = [rotmat; zeros(1, length([dipsel(:);refdipsel(:)])), rsup, zeros(1,length([refchansel(:);supchansel(:)]))];
end
for j=1:length(supchansel)
rotmat(end+1,:) = 0;
rotmat(end,length([dipsel(:);refdipsel(:);supdipsel(:)])+j) = 1;
end
for j=1:length(refchansel)
rotmat(end+1,:) = 0;
rotmat(end,length([dipsel(:);refdipsel(:);supdipsel(:);supchansel(:)])+j) = 1;
end
% compute voxel-level csd-matrix
if isfield(source.avg, 'csd'), source.avg.csd{i} = rotmat * source.avg.csd{i} * rotmat'; end
% compute voxel-level noisecsd-matrix
if isfield(source.avg, 'noisecsd'), source.avg.noisecsd{i} = rotmat * source.avg.noisecsd{i} * rotmat'; end
% compute rotated filter
if isfield(source.avg, 'filter'), source.avg.filter{i} = rotmat * source.avg.filter{i}; end
% compute rotated leadfield
% FIXME in the presence of a refdip and/or supdip, this does not work; leadfield is Nx3
if isfield(source, 'leadfield'),
%FIXME this is a proposed dirty fix
n1 = size(source.leadfield{i},2);
%n2 = size(rotmat,2) - n1;
n2 = size(rotmat,2) - n1 +1; %added 1 JM
source.leadfield{i} = source.leadfield{i} * rotmat(1:n2, 1:n1)';
end
end %for diplop
ft_progress('close');
% remember what the interpretation is of all CSD output components
scandiplabel = repmat({'scandip'}, 1, cfg.numcomp); % only one dipole orientation remains
refdiplabel = repmat({'refdip'}, 1, length(refdipsel)>0); % for svdfft at max. only one dipole orientation remains
supdiplabel = repmat({'supdip'}, 1, length(supdipsel)>0); % for svdfft at max. only one dipole orientation remains
refchanlabel = repmat({'refchan'}, 1, length(refchansel));
supchanlabel = repmat({'supchan'}, 1, length(supchansel));
% concatenate all the labels
source.avg.csdlabel = cat(2, scandiplabel, refdiplabel, supdiplabel, refchanlabel, supchanlabel);
% update the indices
dipsel = match_str(source.avg.csdlabel, 'scandip');
refchansel = match_str(source.avg.csdlabel, 'refchan');
refdipsel = match_str(source.avg.csdlabel, 'refdip');
supchansel = match_str(source.avg.csdlabel, 'supchan');
supdipsel = match_str(source.avg.csdlabel, 'supdip');
refsel = [refdipsel refchansel];
supsel = [supdipsel supchansel];
end % if projectmom
if keeptrials
cumtapcnt = source.cumtapcnt(:);
sumtapcnt = cumsum([0;cumtapcnt]);
Ntrial = length(cumtapcnt);
ft_progress('init', cfg.feedback, 'computing singletrial voxel-level cross-spectral densities');
for triallop = 1:Ntrial
source.trial(triallop).csd = cell(Ndipole, 1); % allocate memory for this trial
source.trial(triallop).mom = cell(Ndipole, 1); % allocate memory for this trial
ft_progress(triallop/Ntrial, 'computing singletrial voxel-level cross-spectral densities %d%d\n', triallop, Ntrial);
for diplop=1:length(source.inside)
i = source.inside(diplop);
dat = source.avg.mom{i};
tmpmom = dat(:, sumtapcnt(triallop)+1:sumtapcnt(triallop+1));
tmpcsd = [tmpmom * tmpmom'] ./cumtapcnt(triallop);
source.trial(triallop).mom{i} = tmpmom;
source.trial(triallop).csd{i} = tmpcsd;
end %for diplop
end % for triallop
ft_progress('close');
% remove the average, continue with separate trials
source = rmfield(source, 'avg');
else
fprintf('using average voxel-level cross-spectral densities\n');
end % if keeptrials
hasrefdip = ~isempty(refdipsel);
hasrefchan = ~isempty(refchansel);
hassupdip = ~isempty(supdipsel);
hassupchan = ~isempty(supchansel);
if keeptrials
% do the processing of the CSD matrices for each trial
if ~strcmp(cfg.supmethod, 'none')
error('suppression is only supported for average CSD');
end
dipselcell = mat2cell(repmat(dipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(dipsel));
if hasrefdip, refdipselcell = mat2cell(repmat(refdipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(refdipsel)); end
if hasrefchan, refchanselcell = mat2cell(repmat(refchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(refchansel)); end
if hassupdip, supdipselcell = mat2cell(repmat(supdipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(supdipsel)); end
if hassupchan, supchanselcell = mat2cell(repmat(supchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(supchansel)); end
ft_progress('init', cfg.feedback, 'computing singletrial voxel-level power');
for triallop = 1:Ntrial
%initialize the variables
source.trial(triallop).pow = zeros(Ndipole, 1);
if hasrefdip, source.trial(triallop).refdippow = zeros(Ndipole, 1); end
if hasrefchan, source.trial(triallop).refchanpow = zeros(Ndipole, 1); end
if hassupdip, source.trial(triallop).supdippow = zeros(Ndipole, 1); end
if hassupchan, source.trial(triallop).supchanpow = zeros(Ndipole, 1); end
ft_progress(triallop/Ntrial, 'computing singletrial voxel-level power %d%d\n', triallop, Ntrial);
source.trial(triallop).pow(source.inside) = cellfun(powmethodfun, source.trial(triallop).csd(source.inside), dipselcell(source.inside));
if hasrefdip, source.trial(triallop).refdippow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refdipselcell(source.inside)); end
if hassupdip, source.trial(triallop).supdippow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supdipselcell(source.inside)); end
if hasrefchan, source.trial(triallop).refchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refchanselcell(source.inside)); end
if hassupchan, source.trial(triallop).supchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supchanselcell(source.inside)); end
%FIXME kan volgens mij niet
if isnoise && isfield(source.trial(triallop), 'noisecsd'),
% compute the power of the noise projected on each source component
source.trial(triallop).noise = cellfun(powmethodfun,source.trial(triallop).csd, dipselcell);
if hasrefdip, source.trial(triallop).refdipnoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refdipselcell); end
if hassupdip, source.trial(triallop).supdipnoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supdipselcell); end
if hasrefchan, source.trial(triallop).refchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refchanselcell); end
if hassupchan, source.trial(triallop).supchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supchanselcell); end
end % if isnoise
end % for triallop
ft_progress('close');
if strcmp(cfg.keepcsd, 'no')
source.trial = rmfield(source.trial, 'csd');
end
else
% do the processing of the average CSD matrix
for diplop = 1:length(source.inside)
i = source.inside(diplop);
switch cfg.supmethod
case 'chan_dip'
supindx = [supdipsel supchansel];
if diplop==1, refsel = refsel - length(supdipsel); end%adjust index only once
case 'chan'
supindx = [supchansel];
case 'dip'
supindx = [supdipsel];
if diplop==1, refsel = refsel - length(supdipsel); end
case 'none'
% do nothing
supindx = [];
end
tmpcsd = source.avg.csd{i};
scnindx = setdiff(1:size(tmpcsd,1), supindx);
tmpcsd = tmpcsd(scnindx, scnindx) - [tmpcsd(scnindx, supindx)*pinv(tmpcsd(supindx, supindx))*tmpcsd(supindx, scnindx)];
source.avg.csd{i} = tmpcsd;
end % for diplop
source.avg.csdlabel = source.avg.csdlabel(scnindx);
if isnoise && ~strcmp(cfg.supmethod, 'none')
source.avg = rmfield(source.avg, 'noisecsd');
end
% initialize the variables
source.avg.pow = nan(Ndipole, 1);
if ~isempty(refdipsel), source.avg.refdippow = nan(Ndipole, 1); end
if ~isempty(refchansel), source.avg.refchanpow = nan(Ndipole, 1); end
if ~isempty(supdipsel), source.avg.supdippow = nan(Ndipole, 1); end
if ~isempty(supchansel), source.avg.supchanpow = nan(Ndipole, 1); end
if isnoise
source.avg.noise = nan(Ndipole, 1);
if ~isempty(refdipsel), source.avg.refdipnoise = nan(Ndipole, 1); end
if ~isempty(refchansel), source.avg.refchannoise = nan(Ndipole, 1); end
if ~isempty(supdipsel), source.avg.supdipnoise = nan(Ndipole, 1); end
if ~isempty(supchansel), source.avg.supchannoise = nan(Ndipole, 1); end
end % if isnoise
if ~isempty(refsel), source.avg.coh = nan(Ndipole, 1); end
if strcmp(cfg.eta, 'yes'),
source.avg.eta = nan(Ndipole, 1);
source.avg.ori = cell(1, Ndipole);
end
if strcmp(cfg.eta, 'yes') && ~isempty(refsel),
source.avg.etacsd = nan(Ndipole, 1);
source.avg.ucsd = cell(1, Ndipole);
end
if strcmp(cfg.fa, 'yes'),
source.avg.fa = nan(Ndipole, 1);
end
for diplop = 1:length(source.inside)
i = source.inside(diplop);
% compute the power of each source component
if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1,
source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipsel,dipsel), 1);
else
source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipsel,dipsel));
end
if ~isempty(refdipsel), source.avg.refdippow(i) = powmethodfun(source.avg.csd{i}(refdipsel,refdipsel)); end
if ~isempty(supdipsel), source.avg.supdippow(i) = powmethodfun(source.avg.csd{i}(supdipsel,supdipsel)); end
if ~isempty(refchansel), source.avg.refchanpow(i) = powmethodfun(source.avg.csd{i}(refchansel,refchansel)); end
if ~isempty(supchansel), source.avg.supchanpow(i) = powmethodfun(source.avg.csd{i}(supchansel,supchansel)); end
if isnoise
% compute the power of the noise projected on each source component
if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1,
source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipsel,dipsel), 1);
else
source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipsel,dipsel));
end
if ~isempty(refdipsel), source.avg.refdipnoise(i) = powmethodfun(source.avg.noisecsd{i}(refdipsel,refdipsel)); end
if ~isempty(supdipsel), source.avg.supdipnoise(i) = powmethodfun(source.avg.noisecsd{i}(supdipsel,supdipsel)); end
if ~isempty(refchansel), source.avg.refchannoise(i) = powmethodfun(source.avg.noisecsd{i}(refchansel,refchansel)); end
if ~isempty(supchansel), source.avg.supchannoise(i) = powmethodfun(source.avg.noisecsd{i}(supchansel,supchansel)); end
end % if isnoise
if ~isempty(refsel)
% compute coherence
csd = source.avg.csd{i};
switch cfg.cohmethod
case 'regular'
% assume that all dipoles have been projected along the direction of maximum power
Pd = abs(csd(dipsel, dipsel));
Pr = abs(csd(refsel, refsel));
Cdr = csd(dipsel, refsel);
source.avg.coh(i) = (Cdr.^2) ./ (Pd*Pr);
case 'lambda1'
%compute coherence on Joachim Gross' way
Pd = lambda1(csd(dipsel, dipsel));
Pr = lambda1(csd(refsel, refsel));
Cdr = lambda1(csd(dipsel, refsel));
source.avg.coh(i) = abs(Cdr).^2 ./ (Pd*Pr);
case 'canonical'
[ccoh, c2, v1, v2] = cancorr(csd, dipsel, refsel);
[cmax, indmax] = max(ccoh);
source.avg.coh(i) = ccoh(indmax);
otherwise
error('unsupported cohmethod');
end % cohmethod
end
% compute eta
if strcmp(cfg.eta, 'yes')
[source.avg.eta(i), source.avg.ori{i}] = csd2eta(source.avg.csd{i}(dipsel,dipsel));
if ~isempty(refsel),
%FIXME this only makes sense when only a reference signal OR a dipole is selected
[source.avg.etacsd(i), source.avg.ucsd{i}] = csd2eta(source.avg.csd{i}(dipsel,refsel));
end
end
%compute fa
if strcmp(cfg.fa, 'yes')
source.avg.fa(i) = csd2fa(source.avg.csd{i}(dipsel,dipsel));
end
end % for diplop
if strcmp(cfg.keepcsd, 'no')
source.avg = rmfield(source.avg, 'csd');
end
if strcmp(cfg.keepnoisecsd, 'no') && isnoise
source.avg = rmfield(source.avg, 'noisecsd');
end
end
elseif ismneavg
%the source reconstruction was computed using the minimumnormestimate and contains an average timecourse
if demean
begsmp = nearest(source.time, cfg.baselinewindow(1));
endsmp = nearest(source.time, cfg.baselinewindow(2));
ft_progress('init', cfg.feedback, 'baseline correcting dipole moments');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'baseline correcting dipole moments %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
mom = ft_preproc_baselinecorrect(mom, begsmp, endsmp);
source.avg.mom{source.inside(diplop)} = mom;
end
ft_progress('close');
end
if projectmom
if isfield(source, 'tri')
nrm = normals(source.pos, source.tri, 'vertex');
source.avg.phi = zeros(size(source.pos,1),1);
end
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'projecting dipole moment %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
[mom, rmom] = svdfft(mom, 1);
source.avg.mom{source.inside(diplop)} = mom;
source.avg.ori{source.inside(diplop)} = rmom;
end
if isfield(source, 'tri')
for diplop = source.inside(:)'
source.avg.phi(diplop) = source.avg.ori{diplop}*nrm(diplop,:)';
end
end
if isfield(source.avg, 'noisecov')
source.avg.noise = nan+zeros(size(source.pos,1),1);
for diplop=1:length(source.inside)
rmom = source.avg.ori{source.inside(diplop)};
source.avg.noise(source.inside(diplop)) = rmom*source.avg.noisecov{source.inside(diplop)}*rmom';
end
end
ft_progress('close');
end
if zscore
begsmp = nearest(source.time, cfg.baselinewindow(1));
endsmp = nearest(source.time, cfg.baselinewindow(2));
% zscore using baselinewindow for power
ft_progress('init', cfg.feedback, 'computing power');
%source.avg.absmom = source.avg.pow;
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'computing power %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
mmom = mean(mom(:,begsmp:endsmp),2);
smom = std(mom(:,begsmp:endsmp),[],2);
pow = sum(((mom-mmom(:,ones(size(mom,2),1)))./smom(:,ones(size(mom,2),1))).^2,1);
source.avg.pow(source.inside(diplop),:) = pow;
%source.avg.absmom(source.inside(diplop),:) = sum((mom-mmom)./smom,1);
end
ft_progress('close');
else
% just square for power
ft_progress('init', cfg.feedback, 'computing power');
%source.avg.absmom = source.avg.pow;
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'computing power %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
pow = sum(mom.^2,1);
source.avg.pow(source.inside(diplop),:) = pow;
%source.avg.absmom(source.inside(diplop),:) = sum(mom,1);
end
ft_progress('close');
end
if strcmp(cfg.kurtosis, 'yes')
fprintf('computing kurtosis based on dipole timecourse\n');
source.avg.k2 = nan(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.avg.mom{source.inside(diplop)};
if length(mom)~=prod(size(mom))
error('kurtosis can only be computed for projected dipole moment');
end
source.avg.k2(source.inside(diplop)) = kurtosis(mom);
end
end
elseif islcmvavg
% the source reconstruction was computed using the lcmv beamformer and contains an average timecourse
if projectmom
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'projecting dipole moment %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
[mom, rmom] = svdfft(mom, 1);
source.avg.mom{source.inside(diplop)} = mom;
source.avg.ori{source.inside(diplop)} = rmom;
end
ft_progress('close');
end
if ~strcmp(cfg.powmethod, 'none')
fprintf('recomputing power based on dipole timecourse\n')
source.avg.pow = nan(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.avg.mom{source.inside(diplop)};
cov = mom * mom';
source.avg.pow(source.inside(diplop)) = powmethodfun(cov);
end
end
if strcmp(cfg.kurtosis, 'yes')
fprintf('computing kurtosis based on dipole timecourse\n');
source.avg.k2 = nan(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.avg.mom{source.inside(diplop)};
if length(mom)~=prod(size(mom))
error('kurtosis can only be computed for projected dipole moment');
end
source.avg.k2(source.inside(diplop)) = kurtosis(mom);
end
end
elseif islcmvtrl
% the source reconstruction was computed using the lcmv beamformer and contains a single-trial timecourse
ntrial = length(source.trial);
if projectmom && strcmp(cfg.fixedori, 'within_trials')
% the dipole orientation is re-determined for each trial
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for trllop=1:ntrial
ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\n', trllop, ntrial);
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
[mom, rmom] = svdfft(mom, 1);
source.trial(trllop).mom{source.inside(diplop)} = mom;
source.trial(trllop).ori{source.inside(diplop)} = rmom; % remember the orientation
end
end
ft_progress('close');
elseif projectmom && strcmp(cfg.fixedori, 'over_trials')
ft_progress('init', cfg.feedback, 'projecting dipole moment');
% compute average covariance over all trials
for trllop=1:ntrial
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
if trllop==1
cov{diplop} = mom*mom'./size(mom,2);
else
cov{diplop} = mom*mom'./size(mom,2) + cov{diplop};
end
end
end
% compute source orientation over all trials
for diplop=1:length(source.inside)
[dum, ori{diplop}] = svdfft(cov{diplop}, 1);
end
% project the data in each trial
for trllop=1:ntrial
ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\n', trllop, ntrial);
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
mom = ori{diplop}*mom;
source.trial(trllop).mom{source.inside(diplop)} = mom;
source.trial(trllop).ori{source.inside(diplop)} = ori{diplop};
end
end
ft_progress('close');
end
if ~strcmp(cfg.powmethod, 'none')
fprintf('recomputing power based on dipole timecourse\n')
for trllop=1:ntrial
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
cov = mom * mom';
source.trial(trllop).pow(source.inside(diplop)) = powmethodfun(cov);
end
end
end
if strcmp(cfg.kurtosis, 'yes')
fprintf('computing kurtosis based on dipole timecourse\n');
for trllop=1:ntrial
source.trial(trllop).k2 = nan(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
if length(mom)~=prod(size(mom))
error('kurtosis can only be computed for projected dipole moment');
end
source.trial(trllop).k2(source.inside(diplop)) = kurtosis(mom);
end
end
end
end % dealing with pcc or lcmv input
if isfield(source, 'avg') && isfield(source.avg, 'pow') && isfield(source.avg, 'noise') && ~ismneavg
% compute the neural activity index for the average
source.avg.nai = source.avg.pow(:) ./ source.avg.noise(:);
end
if isfield(source, 'trial') && isfield(source.trial, 'pow') && isfield(source.trial, 'noise')
% compute the neural activity index for the trials
ntrials = length(source.trial);
for trlop=1:ntrials
source.trial(trlop).nai = source.trial(trlop).pow ./ source.trial(trlop).noise;
end
end
if strcmp(source.method, 'randomization') || strcmp(source.method, 'permutation')
% compute the neural activity index for the two randomized conditions
source.avgA.nai = source.avgA.pow ./ source.avgA.noise;
source.avgB.nai = source.avgB.pow ./ source.avgB.noise;
for trlop=1:length(source.trialA)
source.trialA(trlop).nai = source.trialA(trlop).pow ./ source.trialA(trlop).noise;
end
for trlop=1:length(source.trialB)
source.trialB(trlop).nai = source.trialB(trlop).pow ./ source.trialB(trlop).noise;
end
end
if ~isempty(cfg.transform)
fprintf('applying %s transformation on the power and projected noise\n', cfg.transform);
% apply the specified transformation on the power
if isfield(source, 'avg' ) && isfield(source.avg , 'pow'), source.avg .pow = feval(cfg.transform, source.avg .pow); end
if isfield(source, 'avgA' ) && isfield(source.avgA , 'pow'), source.avgA.pow = feval(cfg.transform, source.avgA.pow); end
if isfield(source, 'avgB' ) && isfield(source.avgB , 'pow'), source.avgB.pow = feval(cfg.transform, source.avgB.pow); end
if isfield(source, 'trial' ) && isfield(source.trial , 'pow'), for i=1:length(source.trial ), source.trial (i).pow = feval(cfg.transform, source.trial (i).pow); end; end
if isfield(source, 'trialA') && isfield(source.trialA, 'pow'), for i=1:length(source.trialA), source.trialA(i).pow = feval(cfg.transform, source.trialA(i).pow); end; end
if isfield(source, 'trialB') && isfield(source.trialB, 'pow'), for i=1:length(source.trialB), source.trialB(i).pow = feval(cfg.transform, source.trialB(i).pow); end; end
% apply the specified transformation on the projected noise
if isfield(source, 'avg' ) && isfield(source.avg , 'noise'), source.avg .noise = feval(cfg.transform, source.avg .noise); end
if isfield(source, 'avgA' ) && isfield(source.avgA , 'noise'), source.avgA.noise = feval(cfg.transform, source.avgA.noise); end
if isfield(source, 'avgB' ) && isfield(source.avgB , 'noise'), source.avgB.noise = feval(cfg.transform, source.avgB.noise); end
if isfield(source, 'trial' ) && isfield(source.trial , 'noise'), for i=1:length(source.trial ), source.trial (i).noise = feval(cfg.transform, source.trial (i).noise); end; end
if isfield(source, 'trialA') && isfield(source.trialA, 'noise'), for i=1:length(source.trialA), source.trialA(i).noise = feval(cfg.transform, source.trialA(i).noise); end; end
if isfield(source, 'trialB') && isfield(source.trialB, 'noise'), for i=1:length(source.trialB), source.trialB(i).noise = feval(cfg.transform, source.trialB(i).noise); end; end
end
if strcmp(source.method, 'pseudovalue')
% compute the pseudovalues for the beamformer output
avg = source.trial(1); % the first is the complete average
Ntrials = length(source.trial)-1; % the remaining are the leave-one-out averages
pseudoval = [];
if isfield(source.trial, 'pow')
allavg = getfield(avg, 'pow');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'pow');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).pow = thisval;
end
end
if isfield(source.trial, 'coh')
allavg = getfield(avg, 'coh');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'coh');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).coh = thisval;
end
end
if isfield(source.trial, 'nai')
allavg = getfield(avg, 'nai');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'nai');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).nai = thisval;
end
end
if isfield(source.trial, 'noise')
allavg = getfield(avg, 'noise');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'noise');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).noise = thisval;
end
end
% store the pseudovalues instead of the original values
source.trial = pseudoval;
end
if strcmp(source.method, 'jackknife') || strcmp(source.method, 'bootstrap') || strcmp(source.method, 'pseudovalue') || strcmp(source.method, 'singletrial') || strcmp(source.method, 'rawtrial')
% compute descriptive statistics (mean, var, sem) for multiple trial data
% compute these for as many source parameters as possible
% for convenience copy the trials out of the source structure
dip = source.trial;
% determine the (original) number of trials in the data
if strcmp(source.method, 'bootstrap') %VERANDERD ER ZAT GEEN .RESAMPLE IN SOURCE
Ntrials = size(source.trial,2);% WAS size(source.resample, 2);
else
Ntrials = length(source.trial);
end
fprintf('original data contained %d trials\n', Ntrials);
% allocate memory for all elements in the dipole structure
sumdip = [];
if isfield(dip(1), 'var'), sumdip.var = zeros(size(dip(1).var )); sumdip.var(source.outside)=nan; end
if isfield(dip(1), 'pow'), sumdip.pow = zeros(size(dip(1).pow )); sumdip.pow(source.outside)=nan; end
if isfield(dip(1), 'coh'), sumdip.coh = zeros(size(dip(1).coh )); sumdip.coh(source.outside)=nan; end
if isfield(dip(1), 'rv'), sumdip.rv = zeros(size(dip(1).rv )); sumdip.rv(source.outside)=nan; end
if isfield(dip(1), 'noise'), sumdip.noise = zeros(size(dip(1).noise)); sumdip.noise(source.outside)=nan; end
if isfield(dip(1), 'nai'), sumdip.nai = zeros(size(dip(1).nai )); sumdip.nai(source.outside)=nan; end
sqrdip = [];
if isfield(dip(1), 'var'), sqrdip.var = zeros(size(dip(1).var )); sqrdip.var(source.outside)=nan; end
if isfield(dip(1), 'pow'), sqrdip.pow = zeros(size(dip(1).pow )); sqrdip.pow(source.outside)=nan; end
if isfield(dip(1), 'coh'), sqrdip.coh = zeros(size(dip(1).coh )); sqrdip.coh(source.outside)=nan; end
if isfield(dip(1), 'rv'), sqrdip.rv = zeros(size(dip(1).rv )); sqrdip.rv(source.outside)=nan; end
if isfield(dip(1), 'noise'), sqrdip.noise = zeros(size(dip(1).noise)); sqrdip.noise(source.outside)=nan; end
if isfield(dip(1), 'nai'), sqrdip.nai = zeros(size(dip(1).nai )); sqrdip.nai(source.outside)=nan; end
if isfield(dip(1), 'mom')
sumdip.mom = cell(size(dip(1).mom));
sqrdip.mom = cell(size(dip(1).mom));
for i=1:length(dip(1).mom)
sumdip.mom{i} = nan(size(dip(1).mom{i}));
sqrdip.mom{i} = nan(size(dip(1).mom{i}));
end
end
if isfield(dip(1), 'csd')
sumdip.csd = cell(size(dip(1).csd));
sqrdip.csd = cell(size(dip(1).csd));
for i=1:length(dip(1).csd)
sumdip.csd{i} = nan(size(dip(1).csd{i}));
sqrdip.csd{i} = nan(size(dip(1).csd{i}));
end
end
for trial=1:length(dip)
% compute the sum of all values
if isfield(dip(trial), 'var'), sumdip.var = sumdip.var + dip(trial).var; end
if isfield(dip(trial), 'pow'), sumdip.pow = sumdip.pow + dip(trial).pow; end
if isfield(dip(trial), 'coh'), sumdip.coh = sumdip.coh + dip(trial).coh; end
if isfield(dip(trial), 'rv'), sumdip.rv = sumdip.rv + dip(trial).rv; end
if isfield(dip(trial), 'noise'), sumdip.noise = sumdip.noise + dip(trial).noise; end
if isfield(dip(trial), 'nai'), sumdip.nai = sumdip.nai + dip(trial).nai; end
% compute the sum of squared values
if isfield(dip(trial), 'var'), sqrdip.var = sqrdip.var + (dip(trial).var ).^2; end
if isfield(dip(trial), 'pow'), sqrdip.pow = sqrdip.pow + (dip(trial).pow ).^2; end
if isfield(dip(trial), 'coh'), sqrdip.coh = sqrdip.coh + (dip(trial).coh ).^2; end
if isfield(dip(trial), 'rv'), sqrdip.rv = sqrdip.rv + (dip(trial).rv ).^2; end
if isfield(dip(trial), 'noise'), sqrdip.noise = sqrdip.noise + (dip(trial).noise).^2; end
if isfield(dip(trial), 'nai'), sqrdip.nai = sqrdip.nai + (dip(trial).nai ).^2; end
% do the same for the cell array with mom
if isfield(dip(trial), 'mom')
for i=1:length(dip(1).mom)
sumdip.mom{i} = sumdip.mom{i} + dip(trial).mom{i};
sqrdip.mom{i} = sqrdip.mom{i} + (dip(trial).mom{i}).^2;
end
end
% do the same for the cell array with csd
if isfield(dip(trial), 'csd')
for i=1:length(dip(1).csd)
sumdip.csd{i} = sumdip.csd{i} + dip(trial).csd{i};
sqrdip.csd{i} = sqrdip.csd{i} + (dip(trial).csd{i}).^2;
end
end
end
% compute the mean over all repetitions
if isfield(sumdip, 'var'), dipmean.var = sumdip.var / length(dip); end
if isfield(sumdip, 'pow'), dipmean.pow = sumdip.pow / length(dip); end
if isfield(sumdip, 'coh'), dipmean.coh = sumdip.coh / length(dip); end
if isfield(sumdip, 'rv'), dipmean.rv = sumdip.rv / length(dip); end
if isfield(sumdip, 'noise'), dipmean.noise = sumdip.noise / length(dip); end
if isfield(sumdip, 'nai'), dipmean.nai = sumdip.nai / length(dip); end
% for the cell array with mom, this is done further below
% for the cell array with csd, this is done further below
% the estimates for variance and SEM are biased if we are working with the jackknife/bootstrap
% determine the proper variance scaling that corrects for this bias
% note that Ntrials is not always the same as the length of dip, especially in case of the bootstrap
if strcmp(source.method, 'singletrial')
bias = 1;
elseif strcmp(source.method, 'rawtrial')
bias = 1;
elseif strcmp(source.method, 'jackknife')
% Effron gives SEM estimate for the jackknife method in equation 11.5 (paragraph 11.2)
% to get the variance instead of SEM, we also have to multiply with the number of trials
bias = (Ntrials - 1)^2;
elseif strcmp(source.method, 'bootstrap')
% Effron gives SEM estimate for the bootstrap method in algorithm 6.1 (equation 6.6)
% to get the variance instead of SEM, we also have to multiply with the number of trials
bias = Ntrials;
elseif strcmp(source.method, 'pseudovalue')
% note that I have not put any thought in this aspect yet
warning('don''t know how to compute bias for pseudovalue resampling');
bias = 1;
end
% compute the variance over all repetitions
if isfield(sumdip, 'var'), dipvar.var = bias*(sqrdip.var - (sumdip.var .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'pow'), dipvar.pow = bias*(sqrdip.pow - (sumdip.pow .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'coh'), dipvar.coh = bias*(sqrdip.coh - (sumdip.coh .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'rv' ), dipvar.rv = bias*(sqrdip.rv - (sumdip.rv .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'noise' ), dipvar.noise = bias*(sqrdip.noise - (sumdip.noise .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'nai' ), dipvar.nai = bias*(sqrdip.nai - (sumdip.nai .^2)/length(dip))/(length(dip)-1); end
% compute the SEM over all repetitions
if isfield(sumdip, 'var'), dipsem.var = (dipvar.var /Ntrials).^0.5; end
if isfield(sumdip, 'pow'), dipsem.pow = (dipvar.pow /Ntrials).^0.5; end
if isfield(sumdip, 'coh'), dipsem.coh = (dipvar.coh /Ntrials).^0.5; end
if isfield(sumdip, 'rv' ), dipsem.rv = (dipvar.rv /Ntrials).^0.5; end
if isfield(sumdip, 'noise' ), dipsem.noise = (dipvar.noise /Ntrials).^0.5; end
if isfield(sumdip, 'nai' ), dipsem.nai = (dipvar.nai /Ntrials).^0.5; end
% compute the mean and SEM over all repetitions for the cell array with mom
if isfield(dip(trial), 'mom')
for i=1:length(dip(1).mom)
dipmean.mom{i} = sumdip.mom{i}/length(dip);
dipvar.mom{i} = bias*(sqrdip.mom{i} - (sumdip.mom{i}.^2)/length(dip))/(length(dip)-1);
dipsem.mom{i} = (dipvar.mom{i}/Ntrials).^0.5;
end
end
% compute the mean and SEM over all repetitions for the cell array with csd
if isfield(dip(trial), 'csd')
for i=1:length(dip(1).csd)
dipmean.csd{i} = sumdip.csd{i}/length(dip);
dipvar.csd{i} = bias*(sqrdip.csd{i} - (sumdip.csd{i}.^2)/length(dip))/(length(dip)-1);
dipsem.csd{i} = (dipvar.csd{i}/Ntrials).^0.5;
end
end
if strcmp(source.method, 'pseudovalue')
% keep the trials, since they have been converted to pseudovalues
% and hence the trials contain the interesting data
elseif keeptrials
% keep the trials upon request
else
% remove the original trials
source = rmfield(source, 'trial');
% assign the descriptive statistics to the output source structure
source.avg = dipmean;
source.var = dipvar;
source.sem = dipsem;
end
end
if strcmp(cfg.resolutionmatrix, 'yes')
% this is only implemented for pcc and no refdips/chans at the moment
Nchan = size(source.leadfield{source.inside(1)}, 1);
Ninside = length(source.inside);
allfilter = zeros(Ninside,Nchan);
allleadfield = zeros(Nchan,Ninside);
dipsel = match_str(source.avg.csdlabel, 'scandip');
ft_progress('init', cfg.feedback, 'computing resolution matrix');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'computing resolution matrix %d/%d\n', diplop, length(source.inside));
i = source.inside(diplop);
% concatenate all filters
allfilter(diplop,:) = source.avg.filter{i}(dipsel,:);
% concatenate all leadfields
allleadfield(:,diplop) = source.leadfield{i};
end
ft_progress('close');
% multiply the filters and leadfields to obtain the resolution matrix
% see equation 1 and 2 in De Peralta-Menendez RG, Gonzalez-Andino SL: A critical analysis of linear inverse solutions to the neuroelectromagnetic inverse problem. IEEE Transactions on Biomedical Engineering 45: 440-448, 1998.
source.resolution = nan(Ndipole, Ndipole);
source.resolution(source.inside, source.inside) = allfilter*allleadfield;
end
% compute fwhm
if strcmp(cfg.fwhm, 'yes')
fprintf('computing fwhm of spatial filters\n');
source = estimate_fwhm1(source, cfg.fwhmremovecenter);
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous source
ft_postamble history source
ft_postamble savevar source
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute eta from a csd-matrix
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [eta, u] = csd2eta(csd)
[u,s,v] = svd(real(csd));
eta = s(2,2)./s(1,1);
u = u'; %orientation is defined in the rows
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute fa from a csd-matrix
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fa] = csd2fa(csd)
s = svd(real(csd));
ns = rank(real(csd));
s = s(1:ns);
ms = mean(s);
fa = sqrt( (ns./(ns-1)) .* (sum((s-ms).^2))./(sum(s.^2)) );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = powmethod_lambda1(x, ind)
if nargin==1,
ind = 1:size(x,1);
end
s = svd(x(ind,ind));
p = s(1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = powmethod_trace(x, ind)
if nargin==1,
ind = 1:size(x,1);
end
p = trace(x(ind,ind));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = powmethod_regular(x, ind)
if nargin==1,
ind = 1:size(x,1);
end
p = abs(x(ind,ind));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value or trace of the
% source CSD matrices resulting from DICS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = lambda1(x)
s = svd(x);
s = s(1);
|
github
|
philippboehmsturm/antx-master
|
ft_freqanalysis_mvar.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_freqanalysis_mvar.m
| 6,212 |
utf_8
|
b7a476d517585098dfe29498494e1061
|
function [freq] = ft_freqanalysis_mvar(cfg, data)
% FT_FREQANALYSIS_MVAR performs frequency analysis on
% mvar data, by fourier transformation of the coefficients. The output
% contains cross-spectral density, spectral transfer matrix, and the
% covariance of the innovation noise. The dimord = 'chan_chan(_freq)(_time)
%
% The function is stand-alone, but is typically called through
% FT_FREQANALYSIS, specifying cfg.method = 'mvar'.
%
% Use as
% [freq] = ft_freqanalysis(cfg, data), with cfg.method = 'mvar'
%
% or
%
% [freq] = ft_freqanalysis_mvar(cfg, data)
%
% The input data structure should be a data structure created by
% FT_MVARANALYSIS, i.e. a data-structure of type 'mvar'.
%
% The configuration can contain:
% cfg.foi = vector with the frequencies at which the spectral quantities
% are estimated (in Hz). Default: 0:1:Nyquist
% cfg.feedback = 'none', or any of the methods supported by FT_PROGRESS,
% for providing feedback to the user in the command
% window.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_MVARANALYSIS, FT_DATATYPE_MVAR, FT_PROGRESS
% Copyright (C) 2009, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_freqanalysis_mvar.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_freqanalysis_mvar.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar data
cfg.foi = ft_getopt(cfg, 'foi', 'all');
cfg.feedback = ft_getopt(cfg, 'feedback', 'none');
%cfg.channel = ft_getopt(cfg, 'channel', 'all');
%cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no');
%cfg.jackknife = ft_getopt(cfg, 'jackknife', 'no');
%cfg.keeptapers = ft_getopt(cfg, 'keeptapers', 'yes');
if strcmp(cfg.foi, 'all'),
cfg.foi = (0:1:data.fsampleorig/2);
end
cfg.channel = ft_channelselection('all', data.label);
%cfg.channel = ft_channelselection(cfg.channel, data.label);
%keeprpt = strcmp(cfg.keeptrials, 'yes');
%keeptap = strcmp(cfg.keeptapers, 'yes');
%dojack = strcmp(cfg.jackknife, 'yes');
%dozscore = strcmp(cfg.zscore, 'yes');
%if ~keeptap, error('not keeping tapers is not possible yet'); end
%if dojack && keeprpt, error('you cannot simultaneously keep trials and do jackknifing'); end
nfoi = length(cfg.foi);
if isfield(data, 'time')
ntoi = numel(data.time);
else
ntoi = 1;
end
nlag = size(data.coeffs,3); %change in due course
chanindx = match_str(data.label, cfg.channel);
nchan = length(chanindx);
label = data.label(chanindx);
%---allocate memory
h = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi));
a = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi));
crsspctrm = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi));
%FIXME build in repetitions
%---loop over the tois
ft_progress('init', cfg.feedback, 'computing MAR-model based TFR');
for j = 1:ntoi
ft_progress(j/ntoi, 'processing timewindow %d from %d\n', j, ntoi);
%---compute transfer function
ar = reshape(data.coeffs(:,:,:,j), [nchan nchan*nlag]);
[h(:,:,:,j), a(:,:,:,j)] = ar2h(ar, cfg.foi, data.fsampleorig);
%---compute cross-spectra
nc = data.noisecov(:,:,j);
for k = 1:nfoi
tmph = h(:,:,k,j);
crsspctrm(:,:,k,j) = tmph*nc*tmph';
end
end
ft_progress('close');
%---create output-structure
freq = [];
freq.label = label;
freq.freq = cfg.foi;
%freq.cumtapcnt= ones(ntrl, 1)*ntap;
if ntoi>1
freq.time = data.time;
freq.dimord = 'chan_chan_freq_time';
else
freq.dimord = 'chan_chan_freq';
end
freq.transfer = h;
%freq.itransfer = a;
freq.noisecov = data.noisecov;
freq.crsspctrm = crsspctrm;
freq.dof = data.dof;
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
ft_postamble history freq
ft_postamble savevar freq
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to compute transfer-function from ar-parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h, zar] = ar2h(ar, foi, fsample)
nchan = size(ar,1);
ncmb = nchan*nchan;
nfoi = length(foi);
%---z-transform frequency axis
zfoi = exp(-2.*pi.*1i.*(foi./fsample));
%---reorganize the ar-parameters
ar = reshape(ar, [ncmb size(ar,2)./nchan]);
ar = fliplr([reshape(eye(nchan), [ncmb 1]) -ar]);
zar = complex(zeros(ncmb, nfoi), zeros(ncmb, nfoi));
for k = 1:ncmb
zar(k,:) = polyval(ar(k,:),zfoi);
end
zar = reshape(zar, [nchan nchan nfoi]);
h = zeros(size(zar));
for k = 1:nfoi
h(:,:,k) = inv(zar(:,:,k));
end
h = sqrt(2).*h; %account for the negative frequencies, normalization necessary for
%comparison with non-parametric (fft based) results in fieldtrip
%FIXME probably the normalization for the zero Hz bin is incorrect
zar = zar./sqrt(2);
|
github
|
philippboehmsturm/antx-master
|
ft_math.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_math.m
| 7,107 |
utf_8
|
56b3b1a3236eeb3c5433a72fb65e3ba8
|
function data = ft_math(cfg, varargin)
% FT_MATH performs mathematical operations on FieldTrip data structures,
% such as addition, subtraction, division, etc.
%
% Use as
% data = ft_examplefunction(cfg, data1, data2, ...)
% with one or multiple FieldTrip data structures as input and where cfg is a
% configuration structure that should contain
%
% cfg.operation = string, can be 'add', 'subtract', 'divide', 'multiply'
% cfg.parameter = string, input data field on which the operation is performed
%
% If you specify only a single input data structure, the configuration should contain
% cfg.value = scalar value to be used in the operation
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_DATATYPE
% Copyright (C) 2012, Robert Oostenveld
%
% $Id: ft_math.m 7188 2012-12-13 21:26:34Z roboos $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial part deals with parsing the input options and data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
revision = '$Id: ft_math.m 7188 2012-12-13 21:26:34Z roboos $';
ft_defaults % this ensures that the path is correct and that the ft_defaults global variable is available
ft_preamble help % this will show the function help if nargin==0 and return an error
ft_preamble provenance % this records the time and memory usage at teh beginning of the function
ft_preamble trackconfig % this converts the cfg structure in a config object, which tracks the cfg options that are being used
ft_preamble debug
ft_preamble loadvar varargin % this reads the input data in case the user specified the cfg.inputfile option
type = ft_datatype(varargin{1});
for i=1:length(varargin)
% check that all data types are equal, and update old data structures
varargin{i} = ft_checkdata(varargin{1}, 'datatype', type);
end
% ensure that the required options are present
cfg = ft_checkconfig(cfg, 'required', {'operation', 'parameter'});
if length(varargin)>1
% perform the operation on two or multiple input data structures
cfg = ft_checkconfig(cfg, 'forbidden', {'value'});
else
% the operation involves the data structure and the specified value
% or the operation is a transformation such as log10
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(varargin{1}, cfg.parameter)
error('the requested parameter is not present in the data');
end
% ensure that the data in all inputs has the same channels, time-axis, etc.
tmpcfg = [];
tmpcfg.parameter = cfg.parameter;
[varargin{:}, tmpcfg] = ft_selectdata(tmpcfg, varargin{:});
if isfield(varargin{1}, [cfg.parameter 'dimord'])
dimord = varargin{1}.([cfg.parameter 'dimord']);
elseif isfield(varargin{1}, 'dimord')
dimord = varargin{1}.dimord;
else
error('the dimord of the requested parameter is unknown');
end
dimtok = tokenize(dimord, '_');
% this determines which descriptive fields will get copied over
haschan = any(strcmp(dimtok, 'chan'));
hasfreq = any(strcmp(dimtok, 'freq'));
hastime = any(strcmp(dimtok, 'time'));
% construct the output data structure
data = [];
if haschan
data.label = varargin{1}.label;
end
if hasfreq
data.freq = varargin{1}.freq;
end
if hastime
data.time = varargin{1}.time;
end
fprintf('selecting %s from the first input argument\n', cfg.parameter);
tmp = varargin{1}.(cfg.parameter);
if length(varargin)==1
switch cfg.operation
case 'add'
fprintf('adding %f to the %s\n', cfg.value, cfg.parameter);
tmp = tmp + cfg.value;
case 'subtract'
fprintf('subtracting %f from the %s\n', cfg.value, cfg.parameter);
tmp = tmp - cfg.value;
case 'multiply'
fprintf('multiplying %s with %f\n', cfg.parameter, cfg.value);
tmp = tmp .* cfg.value;
case 'divide'
fprintf('dividing %s by %f\n', cfg.parameter, cfg.value);
tmp = tmp ./ cfg.value;
case 'log10'
fprintf('taking the log10 of %s\n', cfg.parameter);
tmp = log10(tmp);
otherwise
error('unsupported operation "%s"', cfg.operation);
end % switch
else
switch cfg.operation
case 'add'
for i=2:length(varargin)
fprintf('adding the %s input argument\n', nth(i));
tmp = tmp + varargin{2}.(cfg.parameter);
end
case 'multiply'
for i=2:length(varargin)
fprintf('multiplying with the %s input argument\n', nth(i));
tmp = tmp .* varargin{2}.(cfg.parameter);
end
case 'subtract'
if length(varargin)>2
error('the operation "%s" requires exactly 2 input arguments', cfg.operation);
end
fprintf('subtracting the 2nd input argument from the 1st\n');
tmp = tmp - varargin{2}.(cfg.parameter);
case 'divide'
if length(varargin)>2
error('the operation "%s" requires exactly 2 input arguments', cfg.operation);
end
fprintf('dividing the 1st input argument by the 2nd\n');
tmp = tmp ./ varargin{2}.(cfg.parameter);
otherwise
error('unsupported operation "%s"', cfg.operation);
end % switch
end % one or multiple input data structures
% store the result of the operation in the output structure
data.(cfg.parameter) = tmp;
data.dimord = dimord;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ft_postamble debug
ft_postamble trackconfig % this converts the config object back into a struct and can report on the unused fields
ft_postamble provenance % this records the time and memory at the end of the function, prints them on screen and adds this information together with the function name and matlab version etc. to the output cfg
ft_postamble previous varargin % this copies the datain.cfg structure into the cfg.previous field. You can also use it for multiple inputs, or for "varargin"
ft_postamble history data % this adds the local cfg structure to the output data structure, i.e. dataout.cfg = cfg
ft_postamble savevar data % this saves the output data structure to disk in case the user specified the cfg.outputfile option
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = nth(n)
if n==1
s = sprintf('%dst', n);
elseif n==2
s = sprintf('%dnd', n);
elseif n==3
s = sprintf('%drd', n);
else
s = sprintf('%dth', n);
end
|
github
|
philippboehmsturm/antx-master
|
ft_removetmsartifact.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_removetmsartifact.m
| 7,826 |
utf_8
|
3f77889260456f76aa0f2bad5b4e70f1
|
function data = ft_removetmsartifact(cfg, data)
% FT_REMOVETMSARTIFACT removes TMS artifacts from EEG data
%
% Use as
% data = ft_removetmsartifact(cfg, data)
% where the input data is a raw data, for example obtained from FT_PREPROCESSING, and
% cfg is a configuratioun structure that should contain
% cfg.method = string, can be 'twopassfilter', 'interpolatepulse'
% cfg.pulseonset = value or vector, time in seconds of the TMS pulse in seconds
%
% The following options pertain to the 'replace' method
% cfg.pulsewidth = value, pulse pulsewidth to be removed in seconds
%
% The following options pertain to the 'twopassfilter' method
% cfg.hpfreq = number in Hz
% cfg.hpfiltord = lowpass filter order
% cfg.hpfilttype = digital filter type, 'but' or 'fir' or 'firls' (default = 'but')
%
% See also FT_REJECTARTIFACT, FT_REJECTCOMPONENT
% Copyrights (C) 2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_removetmsartifact.m 7396 2013-01-23 15:18:20Z jimher $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial part deals with parsing the input options and data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
revision = '$Id: ft_removetmsartifact.m 7396 2013-01-23 15:18:20Z jimher $';
% do the general setup of the function
ft_defaults % this ensures that the path is correct and that the ft_defaults global variable is available
ft_preamble help % this will show the function help if nargin==0 and return an error
ft_preamble provenance % this records the time and memory usage at teh beginning of the function
ft_preamble trackconfig % this converts the cfg structure in a config object, which tracks the cfg options that are being used
ft_preamble debug
ft_preamble loadvar datain % this reads the input data in case the user specified the cfg.inputfile option
% ensure that the input data is valid for this function, this will also do
% backward-compatibility conversions of old data that for example was
% read from an old *.mat file
data = ft_checkdata(data, 'datatype', {'raw'}, 'feedback', 'yes');
% ensure that the required options are present
cfg = ft_checkconfig(cfg, 'required', {'method'});
% get the options
cfg.method = ft_getopt(cfg, 'method'); % there is no default
cfg.pulseonset = ft_getopt(cfg, 'pulseonset');
cfg.pulsewidth = ft_getopt(cfg, 'pulsewidth');
cfg.hpfiltord = ft_getopt(cfg, 'hpfiltord', 2);
cfg.hpfilttype = ft_getopt(cfg, 'hpfilttype', 'but');
cfg.hpfreq = ft_getopt(cfg, 'hpfreq', 30);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
numtrl = length(data.trial);
if ~isfield(data, 'fsample')
fsample = 1/mean(diff(data.time{1}));
else
fsample = data.fsample;
end
if isempty(cfg.pulseonset) || isempty(cfg.pulsewidth)
for i=1:numtrl
[onset, width] = pulsedetect(data.trial{i});
% these should be expressed in seconds
cfg.pulseonset{i} = data.time{i}(onset);
cfg.pulsewidth{i} = width/fsample;
fprintf('detected %d pulses in trial %s\n', length(onset), i);
end
end % estimate pulse onset and width
if isnumeric(cfg.pulseonset) && numel(cfg.pulseonset)==1
% copy it for all trials
cfg.pulseonset = repmat(cfg.pulseonset, 1, numtrl);
end
if ~iscell(cfg.pulseonset)
cfg.pulseonset = num2cell(cfg.pulseonset);
end
switch cfg.method
case 'twopassfilter'
for i=1:numtrl
tmssample = nearest(data.time{i}, cfg.pulseonset{i});
% get the part of the data that is left and right of the TMS pulse artifact
dat1 = data.trial{i}(:,1:tmssample);
dat2 = data.trial{i}(:,(tmssample+1:end));
% filter the two pieces, prevent filter artifacts
[filt1] = ft_preproc_lowpassfilter(dat1,fsample,cfg.hpfreq,cfg.hpfiltord,cfg.hpfilttype,'onepass');
[filt2] = ft_preproc_lowpassfilter(dat2,fsample,cfg.hpfreq,cfg.hpfiltord,cfg.hpfilttype,'onepass-reverse');
% stitch the left and right parts of the data back together
data.trial{i} = [filt1 filt2];
end
case 'interpolatepulse'
for i=1:numtrl
for j=1:length(cfg.pulseonset{i})
pulseonset = cfg.pulseonset{i}(j);
pulsewidth = cfg.pulsewidth{i}(j);
% express it in samples,
pulseonset = nearest(data.time{i}, pulseonset);
pulsewidth = round(pulsewidth*fsample);
begsample = pulseonset;
endsample = pulseonset + pulsewidth - 1;
% determine a short window before the TMS pulse
begsample1 = begsample - pulsewidth;
endsample1 = begsample - 1;
dat1 = data.trial{i}(:,begsample1:endsample1);
fill = dat1(:,randperm(size(dat1,2))); % randomly shuffle the data points
% FIXME an alternative would be to replace it with an interpolated version of the signal just around it
% FIXME an alternative would be to replace it with nan
% FIXME an alternative would be to replace it with random noise
% replace the data in the pulse window with a random shuffled version of the data just around it
data.trial{i}(:,begsample:endsample) = 0;
end % for pulses
end % for trials
otherwise
error('unsupported method');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ft_postamble debug
ft_postamble trackconfig % this converts the config object back into a struct and can report on the unused fields
ft_postamble provenance % this records the time and memory at the end of the function, prints them on screen and adds this information together with the function name and matlab version etc. to the output cfg
ft_postamble previous data % this copies the datain.cfg structure into the cfg.previous field. You can also use it for multiple inputs, or for "varargin"
ft_postamble history data % this adds the local cfg structure to the output data structure, i.e. dataout.cfg = cfg
ft_postamble savevar data % this saves the output data structure to disk in case the user specified the cfg.outputfile option
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that detects the onset and pulsewidth of one or multiple TMS pulses
% that are present as artifact in a segment of multi-channel EEG data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [onset, pulsewidth] = pulsedetect(dat)
[nchan, ntime] = size(dat);
for i=1:nchan
dat(i,:) = dat(i,:) - median(dat(i,:));
end
dat = sum(abs(dat),1);
threshold = 0.5 * max(dat);
dat = dat>threshold;
dat = [0 diff(dat) 0];
onset = find(dat== 1);
offset = find(dat==-1) - 1;
pulsewidth = offset - onset;
% make the pulse a bit wider
offset = offset - 2*pulsewidth;
pulsewidth = pulsewidth*5;
|
github
|
philippboehmsturm/antx-master
|
ft_interactiverealign.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_interactiverealign.m
| 15,020 |
utf_8
|
29855615aa0bf4f359855c52a73878b6
|
function cfg = ft_interactiverealign(cfg)
% FT_INTERACTIVEREALIGN interactively rotates, scales and translates
% electrode positions to template electrode positions or towards
% the head surface.
%
% Use as
% [cfg] = ft_interactiverealign(cfg)
%
% The configuration structure should contain the individuals geometrical
% objects that have to be realigned as
% cfg.individual.vol
% cfg.individual.elec
% cfg.individual.grad
% cfg.individual.headshape
% cfg.individual.headshapestyle = 'vertex' (default), 'surface' or 'both'
% cfg.individual.volstyle = 'edge' (default), 'surface' or 'both'
%
% The configuration structure should also contain the geometrical
% objects of a template that serves as target
% cfg.template.vol
% cfg.template.elec
% cfg.template.grad
% cfg.template.headshape
% cfg.template.headshapestyle = 'surface' (default), 'vertex' or 'both'
% cfg.individual.volstyle = 'surface' (default), 'edge' or 'both'
%
% See also FT_VOLUMEREALIGN, FT_ELECTRODEREALIGN, FT_READ_SENS, FT_READ_VOL, FT_READ_HEADSHAPE
% Copyright (C) 2008, Vladimir Litvak
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_interactiverealign.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_interactiverealign.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'required', {'individual', 'template'});
if ~isfield(cfg.individual, 'vol'), cfg.individual.vol = []; end
if ~isfield(cfg.individual, 'elec'), cfg.individual.elec = []; end
if ~isfield(cfg.individual, 'grad'), cfg.individual.grad = []; end
if ~isfield(cfg.individual, 'headshape'), cfg.individual.headshape = []; end
if ~isfield(cfg.individual, 'headshapestyle'), cfg.individual.headshapestyle = 'vertex'; end
if ~isfield(cfg.individual, 'volstyle'), cfg.individual.volstyle = 'edge'; end
if ~isfield(cfg.template, 'vol'), cfg.template.vol = []; end
if ~isfield(cfg.template, 'elec'), cfg.template.elec = []; end
if ~isfield(cfg.template, 'grad'), cfg.template.grad = []; end
if ~isfield(cfg.template, 'headshape'), cfg.template.headshape = []; end
if ~isfield(cfg.template, 'headshapestyle'), cfg.template.headshapestyle = 'surface'; end
if ~isfield(cfg.template, 'volstyle'), cfg.template.volstyle = 'surface'; end
template = cfg.template;
individual = cfg.individual;
if ~isempty(template.headshape)
if ~isfield(template.headshape, 'tri') || isempty(template.headshape.tri)
template.headshape.tri = projecttri(template.headshape.pnt);
end
end
if ~isempty(individual.headshape) && isfield(individual.headshape, 'pnt') && ...
~isempty(individual.headshape.pnt)
if ~isfield(individual.headshape, 'tri') || isempty(individual.headshape.tri)
individual.headshape.tri = projecttri(individual.headshape.pnt);
end
end
% open a figure
fig = figure;
% add the data to the figure
set(fig, 'CloseRequestFcn', @cb_close);
setappdata(fig, 'individual', individual);
setappdata(fig, 'template', template);
setappdata(fig, 'transform', eye(4));
% add the GUI elements
cb_creategui(gca);
cb_redraw(gca);
rotate3d on
waitfor(fig);
% get the data from the figure that was left behind as global variable
% FIXME pass this as appdata
global norm
tmp = norm;
clear global norm
norm = tmp;
clear tmp
% remember the transform
cfg.m = norm.m;
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% some simple SUBFUNCTIONs that facilitate 3D plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = my_plot3(xyz, varargin)
h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function h = my_text3(xyz, varargin)
h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function my_line3(xyzB, xyzE, varargin)
for i=1:size(xyzB,1)
line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to layout a moderately complex graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = layoutgui(fig, geometry, position, style, string, value, tag, callback);
horipos = geometry(1); % lower left corner of the GUI part in the figure
vertpos = geometry(2); % lower left corner of the GUI part in the figure
width = geometry(3); % width of the GUI part in the figure
height = geometry(4); % height of the GUI part in the figure
horidist = 0.05;
vertdist = 0.05;
options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle'
Nrow = size(position,1);
h = cell(Nrow,1);
for i=1:Nrow
if isempty(position{i})
continue;
end
position{i} = position{i} ./ sum(position{i});
Ncol = size(position{i},2);
ybeg = (Nrow-i )/Nrow + vertdist/2;
yend = (Nrow-i+1)/Nrow - vertdist/2;
for j=1:Ncol
xbeg = sum(position{i}(1:(j-1))) + horidist/2;
xend = sum(position{i}(1:(j ))) - horidist/2;
pos(1) = xbeg*width + horipos;
pos(2) = ybeg*height + vertpos;
pos(3) = (xend-xbeg)*width;
pos(4) = (yend-ybeg)*height;
h{i}{j} = uicontrol(fig, ...
options{:}, ...
'position', pos, ...
'style', style{i}{j}, ...
'string', string{i}{j}, ...
'tag', tag{i}{j}, ...
'value', value{i}{j}, ...
'callback', callback{i}{j} ...
);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_creategui(hObject, eventdata, handles);
% define the position of each GUI element
position = {
[2 1 1 1]
[2 1 1 1]
[2 1 1 1]
[1]
[1]
[1]
[1]
[1 1]
};
% define the style of each GUI element
style = {
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'pushbutton'}
{'pushbutton'}
{'toggle'}
{'toggle'}
{'text' 'edit'}
};
% define the descriptive string of each GUI element
string = {
{'rotate' 0 0 0}
{'translate' 0 0 0}
{'scale' 1 1 1}
{'redisplay'}
{'apply'}
{'toggle grid'}
{'toggle axes'}
{'alpha' 0.7}
};
% define the value of each GUI element
value = {
{[] [] [] []}
{[] [] [] []}
{[] [] [] []}
{[]}
{[]}
{0}
{0}
{[] []}
};
% define a tag for each GUI element
tag = {
{'' 'rx' 'ry' 'rz'}
{'' 'tx' 'ty' 'tz'}
{'' 'sx' 'sy' 'sz'}
{''}
{''}
{'toggle grid'}
{'toggle axes'}
{'' 'alpha'}
};
% define the callback function of each GUI element
callback = {
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{@cb_redraw}
{@cb_apply}
{@cb_redraw}
{@cb_redraw}
{[] @cb_redraw}
};
fig = get(hObject, 'parent');
layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_redraw(hObject, eventdata, handles)
fig = get(hObject, 'parent');
individual = getappdata(fig, 'individual');
template = getappdata(fig, 'template');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
hold on
% the "individual" struct is a local copy, so it is safe to change it here
if ~isempty(individual.vol)
individual.vol = ft_transform_vol(H, individual.vol);
end
if ~isempty(individual.elec)
individual.elec = ft_transform_sens(H, individual.elec);
end
if ~isempty(individual.grad)
individual.grad = ft_transform_sens(H, individual.grad);
end
if ~isempty(individual.headshape)
individual.headshape = ft_transform_headshape(H, individual.headshape);
end
if ~isempty(template.elec)
if isfield(template.elec, 'line')
tmpbnd = [];
tmpbnd.pnt = template.elec.chanpos;
tmpbnd.tri = template.elec.line;
ft_plot_mesh(tmpbnd,'vertexcolor','b','facecolor','none','edgecolor','b','vertexsize',10)
else
ft_plot_mesh(template.elec.chanpos,'vertexcolor','b','vertexsize',10);
end
end
if ~isempty(individual.elec)
if isfield(individual.elec, 'line')
tmpbnd = [];
tmpbnd.pnt = individual.elec.chanpos;
tmpbnd.tri = individual.elec.line;
ft_plot_mesh(tmpbnd,'vertexcolor','r','facecolor','none','edgecolor','r','vertexsize',10)
else
ft_plot_mesh(individual.elec.chanpos,'vertexcolor','r','vertexsize',10);
end
end
if ~isempty(template.grad)
ft_plot_mesh(template.grad.chanpos,'vertexcolor','b','vertexsize',10);
% FIXME also plot lines?
end
if ~isempty(individual.grad)
ft_plot_mesh(individual.grad.chanpos,'vertexcolor','r','vertexsize',10);
% FIXME also plot lines?
end
if ~isempty(template.vol)
% FIXME this only works for boundary element models
for i = 1:numel(template.vol.bnd)
if strcmp(template.volstyle, 'edge') || ...
strcmp(template.volstyle, 'both')
ft_plot_mesh(template.vol.bnd(i),'facecolor','none','vertexcolor','b')
end
if strcmp(template.volstyle, 'surface') || ...
strcmp(template.volstyle, 'both')
ft_plot_mesh(template.vol.bnd(i),'facecolor','b','edgecolor','none')
lighting gouraud
material shiny
camlight
end
end
end
if ~isempty(individual.vol)
% FIXME this only works for boundary element models
for i = 1:numel(individual.vol.bnd)
if strcmp(individual.volstyle, 'edge') || ...
strcmp(individual.volstyle, 'both')
ft_plot_mesh(individual.vol.bnd(i),'facecolor','none','vertexcolor','r')
end
if strcmp(individual.volstyle, 'surface') || ...
strcmp(individual.volstyle, 'both')
ft_plot_mesh(individual.vol.bnd(i),'facecolor','r','edgecolor','none')
lighting gouraud
material shiny
camlight
end
end
end
if ~isempty(template.headshape)
if isfield(template.headshape, 'pnt') && ~isempty(template.headshape.pnt)
if strcmp(template.headshapestyle, 'surface') || ...
strcmp(template.headshapestyle, 'both')
ft_plot_mesh(template.headshape,'facecolor','b','edgecolor','none')
lighting gouraud
material shiny
camlight
alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string')));
end
if strcmp(template.headshapestyle, 'vertex') || ...
strcmp(template.headshapestyle, 'both')
ft_plot_mesh(template.headshape.pnt,'vertexcolor','b')
end
end
if isfield(template.headshape, 'fid') && ~isempty(template.headshape.fid.pnt)
ft_plot_mesh(template.headshape.fid.pnt,'vertexcolor','b','vertexsize',20)
end
end
if ~isempty(individual.headshape)
if isfield(individual.headshape, 'pnt') && ~isempty(individual.headshape.pnt)
if strcmp(individual.headshapestyle, 'surface') || ...
strcmp(individual.headshapestyle, 'both')
ft_plot_mesh(individual.headshape,'facecolor','r','edgecolor','none')
lighting gouraud
material shiny
camlight
alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string')));
end
if strcmp(individual.headshapestyle, 'vertex') || ...
strcmp(individual.headshapestyle, 'both')
ft_plot_mesh(individual.headshape.pnt,'vertexcolor','r')
end
end
if isfield(individual.headshape, 'fid') && ~isempty(individual.headshape.fid.pnt)
ft_plot_mesh(individual.headshape.fid.pnt,'vertexcolor','r','vertexsize',20)
end
end
if get(findobj(fig, 'tag', 'toggle axes'), 'value')
axis on
else
axis off
end
if get(findobj(fig, 'tag', 'toggle grid'), 'value')
grid on
else
grid off
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_apply(hObject, eventdata, handles);
fig = get(hObject, 'parent');
transform = getappdata(fig, 'transform');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
transform = H * transform;
set(findobj(fig, 'tag', 'rx'), 'string', 0);
set(findobj(fig, 'tag', 'ry'), 'string', 0);
set(findobj(fig, 'tag', 'rz'), 'string', 0);
set(findobj(fig, 'tag', 'tx'), 'string', 0);
set(findobj(fig, 'tag', 'ty'), 'string', 0);
set(findobj(fig, 'tag', 'tz'), 'string', 0);
set(findobj(fig, 'tag', 'sx'), 'string', 1);
set(findobj(fig, 'tag', 'sy'), 'string', 1);
set(findobj(fig, 'tag', 'sz'), 'string', 1);
setappdata(fig, 'transform', transform);
cb_redraw(hObject);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_close(hObject, eventdata, handles);
% make the current transformation permanent and subsequently allow deleting the figure
cb_apply(gca);
% get the updated electrode from the figure
fig = hObject;
% hmmm, this is ugly
global norm
norm.m = getappdata(fig, 'transform');
set(fig, 'CloseRequestFcn', @delete);
delete(fig);
|
github
|
philippboehmsturm/antx-master
|
ft_neighbourplot.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_neighbourplot.m
| 13,837 |
utf_8
|
ca95890c5dd526a7238dfeb645702897
|
function [cfg] = ft_neighbourplot(cfg, data)
% FT_NEIGHBOURPLOT visualizes neighbouring channels in a particular channel
% configuration. The positions of the channel are specified in a
% gradiometer or electrode configuration or from a layout.
%
% Use as
% ft_neighbourplot(cfg)
% or as
% ft_neighbourplot(cfg, data)
%
% where the configuration can contain
% cfg.verbose = 'yes' or 'no', if 'yes' then the plot callback will include text output
% cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS (optional)
% cfg.enableedit = 'yes' or 'no' (default). allows the user to
% flexibly add or remove edges between vertices
% or one of the following options
% cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT
% cfg.elec = structure with EEG electrode positions
% cfg.grad = structure with MEG gradiometer positions
% cfg.elecfile = filename containing EEG electrode positions
% cfg.gradfile = filename containing MEG gradiometer positions
%
% If cfg.neighbours is not defined, this function will call
% FT_PREPARE_NEIGHBOURS to determine the channel neighbours. The
% following data fields may also be used by FT_PREPARE_NEIGHBOURS
% data.elec = structure with EEG electrode positions
% data.grad = structure with MEG gradiometer positions
% If cfg.neighbours is empty, no neighbouring sensors are assumed.
%
% Use cfg.enableedit to create or extend your own neighbourtemplate
%
% See also FT_PREPARE_NEIGHBOURS, FT_PREPARE_LAYOUT
% Copyright (C) 2011, J?rn M. Horschig, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
revision = '$Id: ft_neighbourplot.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
hasdata = nargin>1;
if hasdata, data = ft_checkdata(data); end
cfg.enableedit = ft_getopt(cfg, 'enableedit', 'no');
if isfield(cfg, 'neighbours')
cfg.neighbours = cfg.neighbours;
elseif hasdata
cfg.neighbours = ft_prepare_neighbours(cfg, data);
else
cfg.neighbours = ft_prepare_neighbours(cfg);
end
if ~isfield(cfg, 'verbose')
cfg.verbose = 'no';
elseif strcmp(cfg.verbose, 'yes')
cfg.verbose = true;
end
% get the the grad or elec
if hasdata
sens = ft_fetch_sens(cfg, data);
else
sens = ft_fetch_sens(cfg);
end
% insert sensors that are not in neighbourhood structure
if isempty(cfg.neighbours)
nsel = 1:numel(sens.label);
else
nsel = find(~ismember(sens.label, {cfg.neighbours.label}));
end
for i=1:numel(nsel)
cfg.neighbours(end+1).label = sens.label{nsel(i)};
cfg.neighbours(end).neighblabel = {};
end
[tmp, sel] = match_str(sens.label, {cfg.neighbours.label});
cfg.neighbours = cfg.neighbours(sel);
% give some graphical feedback
if all(sens.chanpos(:,3)==0)
% the sensor positions are already projected on a 2D plane
proj = sens.chanpos(:,1:2);
else
% use 3-dimensional data for plotting
proj = sens.chanpos;
end
hf = figure;
axis equal
axis off
hold on;
hl = [];
for i=1:length(cfg.neighbours)
this = cfg.neighbours(i);
sel1 = match_str(sens.label, this.label);
sel2 = match_str(sens.label, this.neighblabel);
% account for missing sensors
this.neighblabel = sens.label(sel2);
for j=1:length(this.neighblabel)
x1 = proj(sel1,1);
y1 = proj(sel1,2);
x2 = proj(sel2(j),1);
y2 = proj(sel2(j),2);
X = [x1 x2];
Y = [y1 y2];
if size(proj, 2) == 2
hl(sel1, sel2(j)) = line(X, Y, 'color', 'r');
elseif size(proj, 2) == 3
z1 = proj(sel1,3);
z2 = proj(sel2(j),3);
Z = [z1 z2];
hl(sel1, sel2(j)) = line(X, Y, Z, 'color', 'r');
end
end
end
% this is for putting the channels on top of the connections
hs = [];
for i=1:length(cfg.neighbours)
this = cfg.neighbours(i);
sel1 = match_str(sens.label, this.label);
sel2 = match_str(sens.label, this.neighblabel);
% account for missing sensors
this.neighblabel = sens.label(sel2);
if isempty(sel1)
continue;
end
if size(proj, 2) == 2
hs(i) = line(proj(sel1, 1), proj(sel1, 2), ...
'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'k', ...
'Marker', 'o', ...
'MarkerSize', .125*(2+numel(cfg.neighbours(i).neighblabel))^2, ...
'UserData', i, ...
'ButtonDownFcn', @showLabelInTitle);
elseif size(proj, 2) == 3
hs(i) = line(proj(sel1, 1), proj(sel1, 2), proj(sel1, 3), ...
'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'k', ...
'Marker', 'o', ...
'MarkerSize', .125*(2+numel(cfg.neighbours(i).neighblabel))^2, ...
'UserData', i, ...
'ButtonDownFcn', @showLabelInTitle);
else
error('Channel coordinates are too high dimensional');
end
end
hold off;
title('[Click on a sensor to see its label]');
% store what is needed in UserData of figure
userdata.lastSensId = [];
userdata.cfg = cfg;
userdata.sens = sens;
userdata.hs = hs;
userdata.hl = hl;
userdata.quit = false;
hf = getparent(hf);
set(hf, 'UserData', userdata);
if istrue(cfg.enableedit)
set(hf, 'CloseRequestFcn', @cleanup_cb);
while ~userdata.quit
uiwait(hf);
userdata = get(hf, 'UserData');
end
cfg = userdata.cfg;
hf = getparent(hf);
delete(hf);
end
% in any case remove SCALE and COMNT
desired = ft_channelselection({'all', '-SCALE', '-COMNT'}, {cfg.neighbours.label});
neighb_idx = ismember({cfg.neighbours.label}, desired);
cfg.neighbours = cfg.neighbours(neighb_idx);
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function showLabelInTitle(gcbo, EventData, handles)
userdata = get(gcf, 'UserData');
lastSensId = userdata.lastSensId;
cfg = userdata.cfg;
hs = userdata.hs;
curSensId = get(gcbo, 'UserData');
if lastSensId == curSensId
title('[Click on a sensor to see its label]');
set(hs(curSensId), 'MarkerFaceColor', 'k');
userdata.lastSensId = [];
elseif isempty(lastSensId) || ~istrue(cfg.enableedit)
userdata.lastSensId = curSensId;
if istrue(cfg.enableedit)
title(['Selected channel: ' cfg.neighbours(curSensId).label ' click on another to (dis-)connect']);
else
title(['Selected channel: ' cfg.neighbours(curSensId).label]);
end
if cfg.verbose
str = sprintf('%s, ', cfg.neighbours(curSensId).neighblabel{:});
if length(str)>2
% remove the last comma and space
str = str(1:end-2);
end
fprintf('Selected channel %s, which has %d neighbours: %s\n', ...
cfg.neighbours(curSensId).label, ...
length(cfg.neighbours(curSensId).neighblabel), ...
str);
end
set(hs(curSensId), 'MarkerFaceColor', 'g');
set(hs(lastSensId), 'MarkerFaceColor', 'k');
elseif istrue(cfg.enableedit)
hl = userdata.hl;
sens = userdata.sens;
if all(sens.chanpos(:,3)==0)
% the sensor positions are already projected on a 2D plane
proj = sens.chanpos(:,1:2);
else
% use 3-dimensional data for plotting
proj = sens.chanpos;
end
% find out whether they are connected
connected1 = ismember(cfg.neighbours(curSensId).neighblabel, cfg.neighbours(lastSensId).label);
connected2 = ismember(cfg.neighbours(lastSensId).neighblabel, cfg.neighbours(curSensId).label);
if any(connected1) % then disconnect
cfg.neighbours(curSensId).neighblabel(connected1) = [];
cfg.neighbours(lastSensId).neighblabel(connected2) = [];
title(['Disconnected channels ' cfg.neighbours(curSensId).label ' and ' cfg.neighbours(lastSensId).label]);
delete(hl(curSensId, lastSensId));
hl(curSensId, lastSensId) = 0;
delete(hl(lastSensId, curSensId));
hl(lastSensId, curSensId) = 0;
else % then connect
cfg.neighbours(curSensId).neighblabel{end+1} = cfg.neighbours(lastSensId).label;
cfg.neighbours(lastSensId).neighblabel{end+1} = cfg.neighbours(curSensId).label;
title(['Connected channels ' cfg.neighbours(curSensId).label ' and ' cfg.neighbours(lastSensId).label]);
% draw new edge
x1 = proj(curSensId,1);
y1 = proj(curSensId,2);
x2 = proj(lastSensId,1);
y2 = proj(lastSensId,2);
X = [x1 x2];
Y = [y1 y2];
hl(curSensId, lastSensId) = line(X, Y, 'color', 'r');
hl(lastSensId, curSensId) = line(X, Y, 'color', 'r');
end
% draw nodes on top again
delete(hs(curSensId));
delete(hs(lastSensId));
if size(proj, 2) == 2
hs(curSensId) = line(proj(curSensId, 1), proj(curSensId, 2), ...
'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'k', ...
'Marker', 'o', ...
'MarkerSize', .125*(2+numel(cfg.neighbours(curSensId).neighblabel))^2, ...
'UserData', curSensId, ...
'ButtonDownFcn', @showLabelInTitle);
hs(lastSensId) = line(proj(lastSensId, 1), proj(lastSensId, 2), ...
'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'k', ...
'Marker', 'o', ...
'MarkerSize', .125*(2+numel(cfg.neighbours(lastSensId).neighblabel))^2, ...
'UserData', lastSensId, ...
'ButtonDownFcn', @showLabelInTitle);
elseif size(proj, 2) == 3
hs(curSensId) = line(proj(curSensId, 1), proj(curSensId, 2), proj(curSensId, 3), ...
'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'k', ...
'Marker', 'o', ...
'MarkerSize', .125*(2+numel(cfg.neighbours(curSensId).neighblabel))^2, ...
'UserData', curSensId, ...
'ButtonDownFcn', @showLabelInTitle);
hs(lastSensId) = line(proj(lastSensId, 1), proj(lastSensId, 2), proj(lastSensId, 3), ...
'MarkerEdgeColor', 'k', ...
'MarkerFaceColor', 'k', ...
'Marker', 'o', ...
'MarkerSize', .125*(2+numel(cfg.neighbours(lastSensId).neighblabel))^2, ...
'UserData', lastSensId, ...
'ButtonDownFcn', @showLabelInTitle);
else
error('Channel coordinates are too high dimensional');
end
if cfg.verbose
str = sprintf('%s, ', cfg.neighbours(curSensId).neighblabel{:});
if length(str)>2
% remove the last comma and space
str = str(1:end-2);
end
fprintf('Selected channel %s, which has %d neighbours: %s\n', ...
cfg.neighbours(curSensId).label, ...
length(cfg.neighbours(curSensId).neighblabel), ...
str);
end
set(hs(curSensId), 'MarkerFaceColor', 'g');
set(hs(lastSensId), 'MarkerFaceColor', 'k');
userdata.lastSensId = curSensId;
userdata.hl = hl;
userdata.hs = hs;
userdata.cfg = cfg;
set(gcf, 'UserData', userdata);
return;
else
% can never happen, so do nothing
end
set(gcf, 'UserData', userdata);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanup_cb(h, eventdata)
userdata = get(h, 'UserData');
h = getparent(h);
userdata.quit = true;
set(h, 'UserData', userdata);
uiresume
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = getparent(h)
p = h;
while p~=0
h = p;
p = get(h, 'parent');
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_topoplotTFR.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_topoplotTFR.m
| 44,990 |
utf_8
|
68581358241f3de5de9302c9b0807e29
|
function [cfg] = ft_topoplotTFR(cfg, varargin)
% FT_TOPOPLOTTFR plots the topographic distribution over the head
% of a 3-dimensional data representations such as time-frequency
% representation of the power or coherence spectrum.
%
% Use as
% ft_topoplotTFR(cfg, freq)
%
% The input freq structrure should contain a time-resolved power or
% coherence spectrum from FT_FREQANALYSIS or FT_FREQDESCRIPTIVES.
%
% The configuration can have the following parameters:
% cfg.parameter = field that contains the data to be plotted as color
% 'avg', 'powspctrm' or 'cohspctrm' (default depends on data.dimord)
% cfg.xlim = selection boundaries over first dimension in data (e.g., time)
% 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.colormap = any sized colormap, see COLORMAP
% cfg.marker = 'on', 'labels', 'numbers', 'off'
% cfg.markersymbol = channel marker symbol (default = 'o')
% cfg.markercolor = channel marker color (default = [0 0 0] (black))
% cfg.markersize = channel marker size (default = 2)
% cfg.markerfontsize = font size of channel labels (default = 8 pt)
% cfg.highlight = 'on', 'labels', 'numbers', 'off'
% cfg.highlightchannel = Nx1 cell-array with selection of channels, or vector containing channel indices see FT_CHANNELSELECTION
% cfg.highlightsymbol = highlight marker symbol (default = 'o')
% cfg.highlightcolor = highlight marker color (default = [0 0 0] (black))
% cfg.highlightsize = highlight marker size (default = 6)
% cfg.highlightfontsize = highlight marker size (default = 8)
% cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment
% cfg.colorbar = 'yes'
% 'no' (default)
% 'North' inside plot box near top
% 'South' inside bottom
% 'East' inside right
% 'West' inside left
% 'NorthOutside' outside plot box near top
% 'SouthOutside' outside bottom
% 'EastOutside' outside right
% 'WestOutside' outside left
% cfg.interplimits = limits for interpolation (default = 'head')
% 'electrodes' to furthest electrode
% 'head' to edge of head
% cfg.interpolation = 'linear','cubic','nearest','v4' (default = 'v4') see GRIDDATA
% cfg.style = plot style (default = 'both')
% 'straight' colormap only
% 'contour' contour lines only
% 'both' (default) both colormap and contour lines
% 'fill' constant color between lines
% 'blank' only the head shape
% cfg.gridscale = scaling grid size (default = 67)
% determines resolution of figure
% cfg.shading = 'flat' 'interp' (default = 'flat')
% cfg.comment = string 'no' 'auto' or 'xlim' (default = 'auto')
% 'auto': date, xparam and parameter limits are printed
% 'xlim': only xparam limits are printed
% cfg.commentpos = string or two numbers, position of comment (default 'leftbottom')
% 'lefttop' 'leftbottom' 'middletop' 'middlebottom' 'righttop' 'rightbottom'
% 'title' to place comment as title
% 'layout' to place comment as specified for COMNT in layout
% [x y] coordinates
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.directionality = '', 'inflow' or 'outflow' specifies for
% connectivity measures whether the inflow into a
% node, or the outflow from a node is plotted. The
% (default) behavior of this option depends on the dimor
% of the input data (see below).
% cfg.layout = specify the channel layout for plotting using one of
% the supported ways (see below).
%
% For the plotting of directional connectivity data the cfg.directionality
% option determines what is plotted. The default value and the supported
% functionality depend on the dimord of the input data. If the input data
% is of dimord 'chan_chan_XXX', the value of directionality determines
% whether, given the reference channel(s), the columns (inflow), or rows
% (outflow) are selected for plotting. In this situation the default is
% 'inflow'. Note that for undirected measures, inflow and outflow should
% give the same output. If the input data is of dimord 'chancmb_XXX', the
% value of directionality determines whether the rows in data.labelcmb are
% selected. With 'inflow' the rows are selected if the refchannel(s) occur in
% the right column, with 'outflow' the rows are selected if the
% refchannel(s) occur in the left column of the labelcmb-field. Default in
% this case is '', which means that all rows are selected in which the
% refchannel(s) occur. This is to robustly support linearly indexed
% undirected connectivity metrics. In the situation where undirected
% connectivity measures are linearly indexed, specifying 'inflow' or
% 'outflow' can result in unexpected behavior.
%
% The layout defines how the channels are arranged. You can specify the
% layout in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure, that will be used for creating a
% layout. If you want to have more fine-grained control over the layout
% of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the input should be
% structured as a cell array.
%
% See also:
% FT_TOPOPLOTER, FT_TOPOPLOTIC, FT_SINGLEPLOTTFR, FT_MULTIPLOTTFR, FT_PREPARE_LAYOUT
% It is possible to use multiple highlight-selections (e.g.: multiple statistical clusters of channels)
% To do this, all the content of the highlight-options (including cfg.highlight) should be placed in a cell-array
% (even if the normal content was already in a cell-array). Specific marker settings (e.g. color, size) are defaulted when
% not present.
% Example (3 selections):
% cfg.highlight = {'labels', 'labels', 'numbers'}
% cfg.highlightchannel = {{'MZF03','MZC01','MRT54'}, [1:5], 'C*'}
% cfg.highlightsymbol = {'o',[],'+'} % the empty option will be defaulted
% cfg.highlightcolor = {'r',[0 0 1]}; % the missing option will be defaulted
% cfg.highlightsize = []; % will be set to default, as will the missing cfg.highlightfontsize
%
% Other options:
% cfg.labeloffset (offset of labels to their marker, default = 0.005)
% This function depends on FT_TIMELOCKBASELINE which has the following options:
% cfg.baseline, documented
% cfg.channel
% cfg.baselinewindow
%
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype
% Copyright (C) 2005-2011, F.C. Donders Centre
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_topoplotTFR.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_topoplotTFR.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar varargin
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel' 'refchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'});
Ndata = numel(varargin);
if ~isempty(varargin) && isnumeric(varargin{end})
Ndata = Ndata - 1;
indx = varargin{end};
else
indx = 1;
end
% the call with multiple inputs is done by ft_topoplotIC and recursively by ft_topoplotTFR itself
if Ndata>1 && ~isnumeric(varargin{end})
for k=1:Ndata
if k>1
% create a new figure for the additional input arguments
% ensure new figures are all in the same size/position
p = get(gcf, 'Position');
f = figure();
set(f, 'Position', p);
end
if isfield(cfg, 'inputfile')
cfg = rmfield(cfg, 'inputfile');
end
% the indexing is necessary if ft_topoplotTFR is called from
% ft_singleplotER when more input data structures exist. somehow we need to
% keep track of which of the data arguments is to be plotted (otherwise the
% first data argument is only plotted). yet, we cannot throw away the
% other data structures, because in the interactive mode
% ft_singleplotER needs all data again and the entry into
% ft_singleplotER will be through one of the figures (which thus needs
% to have all data avalaible. at the moment I couldn't think of
% anything better than using an additional indx variable and letting the
% function recursively call itself.
ft_topoplotTFR(cfg, varargin{1:Ndata}, indx);
indx = indx + 1;
end
return
end
data = varargin{indx};
data = ft_checkdata(data, 'datatype', {'timelock', 'freq', 'comp'});
% check for option-values to be renamed
cfg = ft_checkconfig(cfg, 'renamedval', {'electrodes', 'dotnum', 'numbers'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'});
% check for renamed options
cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'});
cfg = ft_checkconfig(cfg, 'renamed', {'electrodes', 'marker'});
cfg = ft_checkconfig(cfg, 'renamed', {'emarker', 'markersymbol'});
cfg = ft_checkconfig(cfg, 'renamed', {'ecolor', 'markercolor'});
cfg = ft_checkconfig(cfg, 'renamed', {'emarkersize', 'markersize'});
cfg = ft_checkconfig(cfg, 'renamed', {'efontsize', 'markerfontsize'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarker', 'highlightsymbol'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlcolor', 'highlightcolor'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkersize', 'highlightsize'});
cfg = ft_checkconfig(cfg, 'renamed', {'maplimits', 'zlim'});
% old ft_checkconfig adapted partially from topoplot.m (backwards backwards compatability)
cfg = ft_checkconfig(cfg, 'renamed', {'grid_scale', 'gridscale'});
cfg = ft_checkconfig(cfg, 'renamed', {'interpolate', 'interpolation'});
cfg = ft_checkconfig(cfg, 'renamed', {'numcontour', 'contournum'});
cfg = ft_checkconfig(cfg, 'renamed', {'electrod', 'marker'});
cfg = ft_checkconfig(cfg, 'renamed', {'electcolor', 'markercolor'});
cfg = ft_checkconfig(cfg, 'renamed', {'emsize', 'markersize'});
cfg = ft_checkconfig(cfg, 'renamed', {'efsize', 'markerfontsize'});
cfg = ft_checkconfig(cfg, 'renamed', {'headlimits', 'interplimits'});
% check for forbidden options
cfg = ft_checkconfig(cfg, 'forbidden', {'hllinewidth', ...
'headcolor', ...
'hcolor', ...
'hlinewidth', ...
'contcolor', ...
'outline', ...
'highlightfacecolor', ...
'showlabels'});
% Set other config defaults:
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.style = ft_getopt(cfg, 'style', 'both');
cfg.gridscale = ft_getopt(cfg, 'gridscale', 67);
cfg.interplimits = ft_getopt(cfg, 'interplimits', 'head');
cfg.interpolation = ft_getopt(cfg, 'interpolation', 'v4');
cfg.contournum = ft_getopt(cfg, 'contournum', 6);
cfg.colorbar = ft_getopt(cfg, 'colorbar', 'no');
cfg.shading = ft_getopt(cfg, 'shading', 'flat');
cfg.comment = ft_getopt(cfg, 'comment', 'auto');
cfg.commentpos = ft_getopt(cfg, 'commentpos', 'leftbottom');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); %to avoid warning in timelock/freqbaseline
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []); % matlab sets the default
cfg.marker = ft_getopt(cfg, 'marker', 'on');
cfg.markersymbol = ft_getopt(cfg, 'markersymbol', 'o');
cfg.markercolor = ft_getopt(cfg, 'markercolor', [0 0 0]);
cfg.markersize = ft_getopt(cfg, 'markersize', 2);
cfg.markerfontsize = ft_getopt(cfg, 'markerfontsize', 8);
cfg.highlight = ft_getopt(cfg, 'highlight', 'off');
cfg.highlightchannel = ft_getopt(cfg, 'highlightchannel', 'all', 1); % highlight may be 'on', making highlightchannel {} meaningful
cfg.highlightsymbol = ft_getopt(cfg, 'highlightsymbol', '*');
cfg.highlightcolor = ft_getopt(cfg, 'highlightcolor', [0 0 0]);
cfg.highlightsize = ft_getopt(cfg, 'highlightsize', 6);
cfg.highlightfontsize = ft_getopt(cfg, 'highlightfontsize', 8);
cfg.labeloffset = ft_getopt(cfg, 'labeloffset', 0.005);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []);
cfg.component = ft_getopt(cfg, 'component', []);
cfg.directionality = ft_getopt(cfg, 'directionality', []);
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.figurename = ft_getopt(cfg, 'figurename', []);
% compatibility for previous highlighting option
if isnumeric(cfg.highlight)
cfg.highlightchannel = cfg.highlight;
cfg.highlight = 'on';
warning('cfg.highlight is now used for specifying highlighting-mode, use cfg.highlightchannel instead of cfg.highlight for specifying channels')
elseif iscell(cfg.highlight)
if ~iscell(cfg.highlightchannel)
cfg.highlightchannel = cell(1,length(cfg.highlight));
end
for icell = 1:length(cfg.highlight)
if isnumeric(cfg.highlight{icell})
cfg.highlightchannel{icell} = cfg.highlight{icell};
cfg.highlight{icell} = 'on';
warning('cfg.highlight is now used for specifying highlighting-mode, use cfg.highlightchannel instead of cfg.highlight for specifying channels')
end
end
end
% Converting all highlight options to cell-arrays if they're not cell-arrays,
% to make defaulting, checking for backwards compatibility and error
% checking easier
if ~iscell(cfg.highlight), cfg.highlight = {cfg.highlight}; end
if isempty(cfg.highlightchannel), cfg.highlightchannel = ''; end
if ~iscell(cfg.highlightchannel), cfg.highlightchannel = {cfg.highlightchannel}; end
if ischar(cfg.highlightchannel{1}), cfg.highlightchannel = {cfg.highlightchannel}; end % {'all'} is valid input to channelselection, {1:5} isn't
if ~iscell(cfg.highlightsymbol), cfg.highlightsymbol = {cfg.highlightsymbol}; end
if ~iscell(cfg.highlightcolor), cfg.highlightcolor = {cfg.highlightcolor}; end
if ~iscell(cfg.highlightsize), cfg.highlightsize = {cfg.highlightsize}; end
if ~iscell(cfg.highlightfontsize), cfg.highlightfontsize = {cfg.highlightfontsize}; end
% then make sure all cell-arrays for options have length ncellhigh and default the last element if not present
ncellhigh = length(cfg.highlight);
if length(cfg.highlightsymbol) < ncellhigh, cfg.highlightsymbol{ncellhigh} = 'o'; end
if length(cfg.highlightcolor) < ncellhigh, cfg.highlightcolor{ncellhigh} = [0 0 0]; end
if length(cfg.highlightsize) < ncellhigh, cfg.highlightsize{ncellhigh} = 6; end
if length(cfg.highlightfontsize) < ncellhigh, cfg.highlightfontsize{ncellhigh} = 8; end
% then default all empty cells
for icell = 1:ncellhigh
if isempty(cfg.highlightsymbol{icell}), cfg.highlightsymbol{icell} = 'o'; end
if isempty(cfg.highlightcolor{icell}), cfg.highlightcolor{icell} = [0 0 0]; end
if isempty(cfg.highlightsize{icell}), cfg.highlightsize{icell} = 6; end
if isempty(cfg.highlightfontsize{icell}), cfg.highlightfontsize{icell} = 8; end
end
% for backwards compatability
if strcmp(cfg.marker,'highlights')
warning('using cfg.marker option -highlights- is no longer used, please use cfg.highlight')
cfg.marker = 'off';
end
% check colormap is proper format and set it
if isfield(cfg,'colormap')
if size(cfg.colormap,2)~=3, error('topoplot(): Colormap must be a n x 3 matrix'); end
colormap(cfg.colormap);
end;
dtype = ft_datatype(data);
% identify the interpretation of the functional data
switch dtype
case 'raw'
data = ft_checkdata(data, 'datatype', 'timelock');
dtype = ft_datatype(data);
dimord = data.dimord;
case {'timelock' 'freq' 'chan' 'unknown'}
dimord = data.dimord;
case 'comp'
dimord = 'chan_comp';
otherwise
end
dimtok = tokenize(dimord, '_');
% Set x/y/parameter defaults according to datatype and dimord
switch dtype
case 'timelock'
xparam = 'time';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'avg');
case 'freq'
if any(ismember(dimtok, 'time'))
xparam = 'time';
yparam = 'freq';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
else
xparam = 'freq';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
end
case 'comp'
% Add a pseudo-axis with the component numbers:
data.comp = 1:size(data.topo,2);
% Specify the components
if ~isempty(cfg.component)
data.comp = cfg.component;
data.topo = data.topo(:,cfg.component);
end
% Rename the field with topographic label information:
data.label = data.topolabel;
xparam = 'comp';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'topo');
otherwise
% if the input data is not one of the standard data types, or if
% the functional data is just one value per channel
% in this case xparam, yparam are not defined
% and the user should define the parameter
if ~isfield(data, 'label'), error('the input data should at least contain a label-field'); end
if ~isfield(cfg, 'parameter'), error('the configuration should at least contain a ''parameter'' field'); end
if ~isfield(cfg, 'xparam'),
cfg.xlim = [1 1];
xparam = '';
end
end
if isfield(cfg, 'parameter') && ~isfield(data, cfg.parameter)
error('cfg.parameter=%s is not present in data structure', cfg.parameter);
end
% user specified own fields, but no yparam (which is not asked in help)
if exist('xparam', 'var') && isfield(cfg, 'parameter') && ~exist('yparam', 'var')
yparam = '';
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = any(ismember(dimtok, {'rpt' 'subj'}));
if strcmp(dtype, 'timelock') && hasrpt,
tmpcfg = [];
tmpcfg.trials = cfg.trials;
data = ft_timelockanalysis(tmpcfg, data);
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
elseif strcmp(dtype, 'freq') && hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
if isfield(data, 'crsspctrm'), data = rmfield(data, 'crsspctrm'); end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = data.dimord;
tempdata.freq = data.freq;
tempdata.label = data.label;
tempdata.powspctrm = data.(cfg.parameter);
tempdata.cfg = data.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
data.(cfg.parameter) = tempdata.powspctrm;
clear tempdata
else
data = ft_freqdescriptives(tmpcfg, data);
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
end
if isfield(cfg, 'channel') && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% perform channel selection but only allow this when cfg.interactive = 'no'
if isfield(data, 'label') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, data.label);
elseif isfield(data, 'labelcmb') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% Read or create the layout that will be used for plotting:
lay = ft_prepare_layout(cfg, data);
cfg.layout = lay;
% Create time-series of small topoplots:
if ~ischar(cfg.xlim) && length(cfg.xlim)>2
% Switch off interactive mode:
cfg.interactive = 'no';
xlims = cfg.xlim;
% Iteratively call topoplotER with different xlim values:
nplots = numel(xlims)-1;
nyplot = ceil(sqrt(nplots));
nxplot = ceil(nplots./nyplot);
for i=1:length(xlims)-1
subplot(nxplot, nyplot, i);
cfg.xlim = xlims(i:i+1);
ft_topoplotTFR(cfg, data);
end
return
end
% Apply baseline correction:
if ~strcmp(cfg.baseline, 'no')
if strcmp(xparam, 'freq') || strcmp(yparam, 'freq')
data = ft_freqbaseline(cfg, data);
else
data = ft_timelockbaseline(cfg, data);
end
end
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord:
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb field:
haslabelcmb = isfield(data, 'labelcmb');
if (isfull || haslabelcmb) && isfield(data, cfg.parameter)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if haslabelcmb
cfg.refchannel = ft_channelselection(cfg.refchannel, unique(data.labelcmb(:)));
else
cfg.refchannel = ft_channelselection(cfg.refchannel, data.label);
end
if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
% Open a single figure with the channel layout, the user can click on a reference channel
h = clf;
ft_plot_lay(lay, 'box', false);
title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(h, info);
%set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg, data}, 'event', 'WindowButtonMotionFcn'});
return
end
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.directionality)
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'inflow')
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter);
if length(sel1)+length(sel2)==0
error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality');
end
data.(cfg.parameter) = data.(cfg.parameter)([sel1;sel2],:,:);
data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)];
data.labelcmb = data.labelcmb([sel1;sel2],:);
data = rmfield(data, 'labelcmb');
else
% General case
sel = match_str(data.label, cfg.refchannel);
siz = [size(data.(cfg.parameter)) 1];
if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%in FieldTrip the row index 'causes' the column index channel
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.directionality, 'outflow')
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.directionality, 'inflow-outflow')
% do the subtraction and recursively call the function again
tmpcfg = cfg;
tmpcfg.directionality = 'inflow';
tmpdata = data;
tmp = data.(tmpcfg.parameter);
siz = [size(tmp) 1];
for k = 1:siz(3)
for m = 1:siz(4)
tmp(:,:,k,m) = tmp(:,:,k,m)-tmp(:,:,k,m)';
end
end
tmpdata.(tmpcfg.parameter) = tmp;
ft_topoplotTFR(tmpcfg, tmpdata);
return;
elseif strcmp(cfg.directionality, 'outflow-inflow')
% do the subtraction and recursively call the function again
tmpcfg = cfg;
tmpcfg.directionality = 'outflow';
tmpdata = data;
tmp = data.(tmpcfg.parameter);
siz = [size(tmp) 1];
for k = 1:siz(3)
for m = 1:siz(4)
tmp(:,:,k,m) = tmp(:,:,k,m)-tmp(:,:,k,m)';
end
end
tmpdata.(tmpcfg.parameter) = tmp;
ft_topoplotTFR(tmpcfg, tmpdata);
return;
end
end
end
% Get physical min/max range of x:
if strcmp(cfg.xlim,'maxmin')
xmin = min(data.(xparam));
xmax = max(data.(xparam));
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(xparam)
xmin = nearest(data.(xparam), xmin);
xmax = nearest(data.(xparam), xmax);
end
% Get physical min/max range of y:
if ~isempty(yparam)
if strcmp(cfg.ylim,'maxmin')
ymin = min(data.(yparam));
ymax = max(data.(yparam));
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% Replace value with the index of the nearest bin:
ymin = nearest(data.(yparam), ymin);
ymax = nearest(data.(yparam), ymax);
end
% Take subselection of channels, this only works
% if the interactive mode is switched off
if exist('selchannel', 'var')
sellab = match_str(data.label, selchannel);
label = data.label(sellab);
else
sellab = 1:numel(data.label);
label = data.label;
end
if isfull
sel1 = intersect(sel1, sellab);
sel2 = intersect(sel2, sellab);
end
% Make vector dat with one value for each channel
dat = data.(cfg.parameter);
% get dimord dimensions
dims = textscan(data.dimord,'%s', 'Delimiter', '_');
dims = dims{1};
ydim = find(strcmp(yparam, dims));
xdim = find(strcmp(xparam, dims));
zdim = setdiff(1:ndims(dat), [ydim xdim]);
% and permute
dat = permute(dat, [zdim(:)' ydim xdim]);
if ~isempty(yparam)
if isfull
dat = dat(sel1, sel2, ymin:ymax, xmin:xmax);
dat = nanmean(nanmean(nanmean(dat, meandir), 4), 3);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xmin:xmax);
dat = nanmean(nanmean(dat, 3), 2);
else
dat = dat(sellab, ymin:ymax, xmin:xmax);
dat = nanmean(nanmean(dat, 3), 2);
end
elseif ~isempty(cfg.component)
else
if isfull
dat = dat(sel1, sel2, xmin:xmax);
dat = nanmean(nanmean(dat, meandir), 3);
elseif haslabelcmb
dat = dat(sellab, xmin:xmax);
dat = nanmean(dat, 2);
else
dat = dat(sellab, xmin:xmax);
dat = nanmean(dat, 2);
end
end
dat = dat(:);
% Select the channels in the data that match with the layout:
[seldat, sellay] = match_str(label, cfg.layout.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
datavector = dat(seldat);
% Select x and y coordinates and labels of the channels in the data
chanX = cfg.layout.pos(sellay,1);
chanY = cfg.layout.pos(sellay,2);
chanLabels = cfg.layout.label(sellay);
% make datmask structure with one value for each channel
if ~isempty(cfg.maskparameter)
datmask = data.(cfg.maskparameter);
if numel(datmask) ~= length(data.label)
error('data in cfg.maskparameter should be vector with one value per channel')
end
datmask = datmask(:);
% Select the channels in the maskdata that match with the layout:
maskdatavector = datmask(sellab(seldat));
%maskdatavector = datmask(seldat);
else
maskdatavector = [];
end
% Get physical min/max range of z:
if strcmp(cfg.zlim,'maxmin')
zmin = min(datavector);
zmax = max(datavector);
elseif strcmp(cfg.zlim,'maxabs')
zmin = -max(max(abs(datavector)));
zmax = max(max(abs(datavector)));
else
zmin = cfg.zlim(1);
zmax = cfg.zlim(2);
end
% make comment
if strcmp(cfg.comment, 'auto')
comment = date;
if ~isempty(xparam)
if strcmp(cfg.xlim,'maxmin')
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, xparam, data.(xparam)(xmin), data.(xparam)(xmax));
else
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, xparam, cfg.xlim(1), cfg.xlim(2));
end
end
if ~isempty(yparam)
if strcmp(cfg.ylim,'maxmin')
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, yparam, data.(yparam)(ymin), data.(yparam)(ymax));
else
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, yparam, cfg.ylim(1), cfg.ylim(2));
end
end
if ~isempty(cfg.parameter)
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.parameter, zmin, zmax);
end
cfg.comment = comment;
elseif strcmp(cfg.comment, 'xlim')
if strcmp(cfg.xlim,'maxmin')
comment = sprintf('%0s=[%.3g %.3g]', xparam, data.(xparam)(xmin), data.(xparam)(xmax));
else
comment = sprintf('%0s=[%.3g %.3g]', xparam, cfg.xlim(1), cfg.xlim(2));
end
cfg.comment = comment;
elseif ~ischar(cfg.comment)
error('cfg.comment must be string');
end
if isfield(cfg,'refchannel')
if iscell(cfg.refchannel)
cfg.comment = sprintf('%s\nreference=%s %s', comment, cfg.refchannel{:});
else
cfg.comment = sprintf('%s\nreference=%s %s', comment, cfg.refchannel);
end
end
% Specify the x and y coordinates of the comment
if strcmp(cfg.commentpos,'layout')
ind_comment = strmatch('COMNT', cfg.layout.label);
x_comment = cfg.layout.pos(ind_comment,1);
y_comment = cfg.layout.pos(ind_comment,2);
elseif strcmp(cfg.commentpos,'lefttop')
x_comment = -0.7;
y_comment = 0.6;
HorAlign = 'left';
VerAlign = 'top';
elseif strcmp(cfg.commentpos,'leftbottom')
x_comment = -0.6;
y_comment = -0.6;
HorAlign = 'left';
VerAlign = 'bottom';
elseif strcmp(cfg.commentpos,'middletop')
x_comment = 0;
y_comment = 0.75;
HorAlign = 'center';
VerAlign = 'top';
elseif strcmp(cfg.commentpos,'middlebottom')
x_comment = 0;
y_comment = -0.7;
HorAlign = 'center';
VerAlign = 'bottom';
elseif strcmp(cfg.commentpos,'righttop')
x_comment = 0.65;
y_comment = 0.6;
HorAlign = 'right';
VerAlign = 'top';
elseif strcmp(cfg.commentpos,'rightbottom')
x_comment = 0.6;
y_comment = -0.6;
HorAlign = 'right';
VerAlign = 'bottom';
elseif isnumeric(cfg.commentpos)
x_comment = cfg.commentpos(1);
y_comment = cfg.commentpos(2);
HorAlign = 'left';
VerAlign = 'middle';
x_comment = 0.9*((x_comment-min(x))/(max(x)-min(x))-0.5);
y_comment = 0.9*((y_comment-min(y))/(max(y)-min(y))-0.5);
end
% Draw topoplot
cla
hold on
% Set ft_plot_topo specific options
if strcmp(cfg.interplimits,'head'), interplimits = 'mask';
else interplimits = cfg.interplimits; end
if strcmp(cfg.style,'both'); style = 'surfiso'; end
if strcmp(cfg.style,'straight'); style = 'surf'; end
if strcmp(cfg.style,'contour'); style = 'iso'; end
if strcmp(cfg.style,'fill'); style = 'isofill'; end
% check for nans
nanInds = isnan(datavector);
if any(nanInds)
warning('removing NaNs from the data');
chanX(nanInds) = [];
chanY(nanInds) = [];
datavector(nanInds) = [];
end
% Draw plot
if ~strcmp(cfg.style,'blank')
ft_plot_topo(chanX,chanY,datavector,'interpmethod',cfg.interpolation,...
'interplim',interplimits,...
'gridscale',cfg.gridscale,...
'outline',cfg.layout.outline,...
'shading',cfg.shading,...
'isolines',cfg.contournum,...
'mask',cfg.layout.mask,...
'style',style,...
'datmask', maskdatavector);
elseif ~strcmp(cfg.style,'blank')
ft_plot_lay(lay,'box','no','label','no','point','no')
end
% Plotting markers for channels and/or highlighting a selection of channels
highlightchansel = []; % used for remembering selection of channels
templay.outline = lay.outline;
templay.mask = lay.mask;
% For Highlight (channel-selection)
for icell = 1:length(cfg.highlight)
if ~strcmp(cfg.highlight{icell},'off')
[dum labelindex] = match_str(ft_channelselection(cfg.highlightchannel{icell}, data.label), lay.label);
highlightchansel = [highlightchansel; match_str(data.label,ft_channelselection(cfg.highlightchannel{icell}, data.label))];
templay.pos = lay.pos(labelindex,:);
templay.width = lay.width(labelindex);
templay.height = lay.height(labelindex);
templay.label = lay.label(labelindex);
if strcmp(cfg.highlight{icell}, 'labels') || strcmp(cfg.highlight{icell}, 'numbers')
labelflg = 1;
else
labelflg = 0;
end
if strcmp(cfg.highlight{icell}, 'numbers')
for ichan = 1:length(labelindex)
templay.label{ichan} = num2str(match_str(data.label,templay.label{ichan}));
end
end
ft_plot_lay(templay,'box','no','label',labelflg,'point','yes',...
'pointsymbol',cfg.highlightsymbol{icell},...
'pointcolor',cfg.highlightcolor{icell},...
'pointsize',cfg.highlightsize{icell},...
'labelsize',cfg.highlightfontsize{icell},...
'labeloffset',cfg.labeloffset)
end
end % for icell
% For Markers (all channels)
if ~strcmp(cfg.marker,'off')
channelsToMark = 1:length(data.label);
channelsToMark(nanInds) = [];
channelsToMark(highlightchansel) = [];
[dum labelindex] = match_str(ft_channelselection(channelsToMark, data.label),lay.label);
templay.pos = lay.pos(labelindex,:);
templay.width = lay.width(labelindex);
templay.height = lay.height(labelindex);
templay.label = lay.label(labelindex);
if strcmp(cfg.marker, 'labels') || strcmp(cfg.marker, 'numbers')
labelflg = 1;
else
labelflg = 0;
end
if strcmp(cfg.marker, 'numbers')
for ichan = 1:length(labelindex)
templay.label{ichan} = num2str(match_str(data.label,templay.label{ichan}));
end
end
ft_plot_lay(templay,'box','no','label',labelflg,'point','yes',...
'pointsymbol',cfg.markersymbol,...
'pointcolor',cfg.markercolor,...
'pointsize',cfg.markersize,...
'labelsize',cfg.markerfontsize,...
'labeloffset',cfg.labeloffset)
end
% Write comment
if ~strcmp(cfg.comment,'no')
if strcmp(cfg.commentpos, 'title')
title(cfg.comment, 'Fontsize', cfg.fontsize);
else
ft_plot_text(x_comment,y_comment, cfg.comment, 'Fontsize', cfg.fontsize, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'bottom');
end
end
% plot colorbar:
if isfield(cfg, 'colorbar')
if strcmp(cfg.colorbar, 'yes')
colorbar;
elseif ~strcmp(cfg.colorbar, 'no')
colorbar('location',cfg.colorbar);
end
end
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% The remainder of the code is meant to make the figure interactive
hold on;
% Set colour axis
if ~strcmp(cfg.style, 'blank')
caxis([zmin zmax]);
end
if strcmp('yes',cfg.hotkeys)
% Attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax})
end
% Make the figure interactive
if strcmp(cfg.interactive, 'yes')
% add the channel position information to the figure
% this section is required for ft_select_channel to do its work
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(gcf, info);
if any(strcmp(data.dimord, {'chan_time', 'chan_freq', 'subj_chan_time', 'rpt_chan_time', 'chan_chan_freq'}))
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonMotionFcn'});
elseif any(strcmp(data.dimord, {'chan_freq_time', 'subj_chan_freq_time', 'rpt_chan_freq_time', 'rpttap_chan_freq_time', 'chan_chan_freq_time'}))
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonMotionFcn'});
else
error('unsupported dimord "%" for interactive plotting', data.dimord);
end
end
% set the figure window title
if isfield(cfg,'funcname')
funcname = cfg.funcname;
else
funcname = mfilename;
end
if isfield(cfg,'dataname')
if iscell(cfg.dataname)
dataname = cfg.dataname{indx};
else
dataname = cfg.dataname;
end
elseif nargin > 1
dataname = {inputname(2)};
for k = 2:Ndata
dataname{end+1} = inputname(k+1);
end
else % data provided through cfg.inputfile
dataname = cfg.inputfile;
end
if isempty(cfg.figurename)
set(gcf, 'Name', sprintf('%d: %s: %s', gcf, funcname, join_str(', ',dataname)));
set(gcf, 'NumberTitle', 'off');
else
set(gcf, 'name', cfg.figurename);
set(gcf, 'NumberTitle', 'off');
end
axis off
hold off
axis equal
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_topoplotER(label, cfg, varargin)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
cfg.refchannel = label;
fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel{:});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
cfg.highlight = 'on';
cfg.highlightsymbol = '.';
cfg.highlightcolor = 'r';
cfg.highlightsize = 20;
cfg.highlightchannel = cfg.refchannel;
ft_topoplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotER(label, cfg, varargin)
if ~isempty(label)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
cfg.xlim = 'maxmin';
cfg.channel = label;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotER(cfg, varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotTFR(label, cfg, varargin)
if ~isempty(label)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
cfg.xlim = 'maxmin';
cfg.ylim = 'maxmin';
cfg.channel = label;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotTFR(cfg, varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
incr = (max(caxis)-min(caxis)) /10;
% symmetrically scale color bar down by 10 percent
if strcmp(eventdata.Key,'uparrow')
caxis([min(caxis)-incr max(caxis)+incr]);
% symmetrically scale color bar up by 10 percent
elseif strcmp(eventdata.Key,'downarrow')
caxis([min(caxis)+incr max(caxis)-incr]);
% resort to minmax of data for colorbar
elseif strcmp(eventdata.Key,'m')
caxis([varargin{1} varargin{2}]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_appendfreq.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_appendfreq.m
| 12,697 |
utf_8
|
d808aa3cf94695d0e5f63462ebf5869f
|
function [freq] = ft_appendfreq(cfg, varargin)
% FT_APPENDFREQ concatenates multiple frequency or time-frequency data
% structures that have been processed separately. If the input data
% structures contain different channels, it will be concatenated along the
% channel direction. If the channels are identical in the input data
% structures, the data will be concatenated along the repetition dimension.
%
% Use as
% combined = ft_appendfreq(cfg, freq1, freq2, ...)
%
% cfg.parameter = String. Specifies the name of the field to concatenate.
% For example, to concatenate freq1.powspctrm,
% freq2.powspecrum etc, use cft.parameter = 'powspctrm'.
%
% The configuration can optionally contain
% cfg.appenddim = String. The dimension to concatenate over (default:
% 'auto').
% cfg.tolerance = Double. Tolerance determines how different the units of
% frequency structures are allowed to be to be considered
% compatible (default: 1e-5).
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a
% *.mat file on disk and/or the output data will be written to a *.mat file.
% These mat files should contain only a single variable, corresponding with
% the input/output structure.
%
% See also FT_FREQANALYSIS, FT_APPENDDATA, FT_APPENDTIMELOCK, FT_APPENDSOURCE
% Copyright (C) 2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_appendfreq.m 7405 2013-01-23 16:48:06Z roboos $
revision = '$Id: ft_appendfreq.m 7405 2013-01-23 16:48:06Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar varargin
% check if the input data is valid for this function
for i=1:length(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'freq', 'feedback', 'yes');
end
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'required', 'parameter');
% set the defaults
cfg.appenddim = ft_getopt(cfg, 'appenddim', 'auto');
cfg.tolerance = ft_getopt(cfg, 'tolerance', 1e-5);
% do a basic check to see whether the dimords match
Ndata = length(varargin);
dimord = cell(1,Ndata);
for i=1:Ndata
dimord{i} = varargin{i}.dimord;
end
dimordmatch = all(strcmp(dimord{1}, dimord));
if ~dimordmatch
error('the dimords of the input data structures are not equal');
end
% create the output structure from scratch
freq = [];
tol = cfg.tolerance;
dimtok = tokenize(dimord{1}, '_');
switch cfg.appenddim
case 'auto'
% determine the appenddim and recursively call ft_appendfreq
tmpcfg = cfg;
% only allow to append across observations if these are present in the data
if any(strcmp(dimtok, 'rpt'))
tmpcfg.appenddim = 'rpt';
elseif any(strcmp(dimtok, 'rpttap'))
tmpcfg.appenddim = 'rpttap';
elseif any(strcmp(dimtok, 'subj'))
tmpcfg.appenddim = 'subj';
else
% we need to check whether the other dimensions are the same.
% if not, consider some tolerance.
boolval1 = checkchan(varargin{:}, 'identical');
boolval2 = checkfreq(varargin{:}, 'identical', tol);
if isfield(varargin{1}, 'time'),
boolval3 = checktime(varargin{:}, 'identical', tol);
if boolval1 && boolval2 && boolval3
% each of the input datasets contains a single repetition (perhaps an average), these can be concatenated
tmpcfg.appenddim = 'rpt';
elseif ~boolval1 && boolval2 && boolval3
tmpcfg.appenddim = 'chan';
elseif boolval1 && ~boolval2 && boolval3
tmpcfg.appenddim = 'freq';
elseif boolval1 && boolval2 && ~boolval3
tmpcfg.appenddim = 'time';
end
else
if boolval1 && boolval2
% each of the input datasets contains a single repetition (perhaps an average), these can be concatenated
tmpcfg.appenddim = 'rpt';
elseif ~boolval1 && boolval2
tmpcfg.appenddim = 'chan';
elseif boolval1 && ~boolval2
tmpcfg.appenddim = 'freq';
end
end
freq = ft_appendfreq(tmpcfg, varargin{:});
return;
end % determining the dimension for appending
% otherwise we need to check whether the other dimensions are the same. if
% not, consider some tolerance.
boolval1 = checkchan(varargin{:}, 'identical');
boolval2 = checkfreq(varargin{:}, 'identical', tol);
if isfield(varargin{1}, 'time'),
boolval3 = checktime(varargin{:}, 'identical', tol);
if boolval1 && boolval2 && boolval3
tmpcfg.appenddim = 'rpt';
elseif ~boolval1 && boolval2 && boolval3
tmpcfg.appenddim = 'chan';
elseif boolval1 && ~boolval2 && boolval3
tmpcfg.appenddim = 'freq';
elseif boolval1 && boolval2 && ~boolval3
tmpcfg.appenddim = 'time';
end
else
if boolval1 && boolval2
tmpcfg.appenddim = 'rpt';
elseif ~boolval1 && boolval2
tmpcfg.appenddim = 'chan';
elseif boolval1 && ~boolval2
tmpcfg.appenddim = 'freq';
end
end
freq = ft_appendfreq(tmpcfg, varargin{:});
return;
case {'rpt' 'rpttap' 'subj'}
catdim = find(ismember(dimtok, {'rpt' 'rpttap' 'subj'}));
if numel(catdim)==0
catdim = 0;
elseif numel(catdim)==1
% this is OK
elseif numel(catdim)>1
error('ambiguous dimord for concatenation');
end
% if any of these are present, concatenate
% if not prepend the dimord with rpt (and thus shift the dimensions)
% here we need to check whether the other dimensions are the same. if
% not, consider some tolerance.
boolval1 = checkchan(varargin{:}, 'identical');
boolval2 = checkfreq(varargin{:}, 'identical', tol);
if isfield(varargin{1}, 'time'),
boolval3 = checktime(varargin{:}, 'identical', tol);
else
boolval3 = true;
end
if any([boolval1 boolval2 boolval3]==false)
error('appending across observations is not possible, because the dimensions are incompatible');
end
% update the dimord
if catdim==0
freq.dimord = ['rpt_',varargin{1}.dimord];
% FIXME append dof
else
freq.dimord = varargin{1}.dimord;
% FIXME append cumtapcnt cumsumcnt trialinfo dof
end
% fill in the rest of the descriptive fields
freq.label = varargin{1}.label;
freq.freq = varargin{1}.freq;
if isfield(varargin{1}, 'time'), freq.time = varargin{1}.time; end
case 'chan'
catdim = strmatch('chan', dimtok);
if isempty(catdim)
% try chancmb
catdim = strmatch('chancmb', dimtok);
elseif numel(catdim)>1
error('ambiguous dimord for concatenation');
end
% check whether all channels are unique and throw an error if not
[boolval, list] = checkchan(varargin{:}, 'unique');
if ~boolval
error('the input data structures have non-unique channels, concatenation across channel is not possible');
end
% update the channel description
freq.label = list;
% fill in the rest of the descriptive fields
freq.freq = varargin{1}.freq;
if isfield(varargin{1}, 'time'), freq.time = varargin{1}.time; end
freq.dimord = varargin{1}.dimord;
case 'freq'
catdim = strmatch('freq', dimtok);
% check whether all frequencies are unique and throw an error if not
[boolval, list] = checkfreq(varargin{:}, 'unique', tol);
if ~boolval
error('the input data structures have non-unique frequency bins, concatenation across frequency is not possible');
end
% update the frequency description
freq.freq = list(:)';
% fill in the rest of the descriptive fields
freq.label = varargin{1}.label;
freq.dimord = varargin{1}.dimord;
if isfield(varargin{1}, 'time'), freq.time = varargin{1}.time; end
case 'time'
catdim = strmatch('time', dimtok);
% check whether all time points are unique and throw an error if not
[boolval, list] = checktime(varargin{:}, 'unique', tol);
if ~boolval
error('the input data structures have non-unique time bins, concatenation across time is not possible');
end
% update the time description
freq.time = list(:)';
% fill in the rest of the descriptive fields
freq.label = varargin{1}.label;
freq.freq = varargin{1}.freq;
freq.dimord = varargin{1}.dimord;
otherwise
end
% FIXME do a check on whether the parameters are present in all datasets
param = cfg.parameter;
if ~iscell(param), param = {param}; end
% concatenate the numeric data
for k = 1:numel(param)
tmp = cell(1,Ndata);
% get the numeric data 'param{k}' if present
for m = 1:Ndata
tmp{m} = varargin{m}.(param{k});
end
if catdim==0,
ndim = length(size(tmp{1}));
freq.(param{k}) = permute(cat(ndim+1,tmp{:}),[ndim+1 1:ndim]);
else
freq.(param{k}) = cat(catdim,tmp{:});
end
end % for k = 1:numel(param)
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
ft_postamble history freq
ft_postamble savevar freq
%---------------------------------------------
% subfunction to check uniqueness of freq bins
function [boolval, faxis] = checkfreq(varargin)
% last input is always the required string
tol = varargin{end};
required = varargin{end-1};
varargin = varargin(1:end-2);
Ndata = numel(varargin);
Nfreq = zeros(1,Ndata);
faxis = zeros(1,0);
for i=1:Ndata
Nfreq(i) = numel(varargin{i}.freq);
faxis = [faxis;varargin{i}.freq(:)];
end
if strcmp(required, 'unique')
boolval = numel(unique(faxis))==numel(faxis) && ~all(isnan(faxis));
% the second condition is included when the freq is set to dummy nan
elseif strcmp(required, 'identical')
% the number of frequency bins needs at least to be the same across
% inputs
boolval = all(Nfreq==Nfreq(1));
if boolval
% then check whether the axes are equal
faxis = reshape(faxis, Nfreq(1), []);
boolval = all(all(abs(faxis - repmat(faxis(:,1), 1, Ndata))<tol)==1);
faxis = faxis(:,1);
end
end
%---------------------------------------------
% subfunction to check uniqueness of time bins
function [boolval, taxis] = checktime(varargin)
% last input is always the required string
tol = varargin{end};
required = varargin{end-1};
varargin = varargin(1:end-2);
Ndata = numel(varargin);
Ntime = zeros(1,Ndata);
taxis = zeros(1,0);
for i=1:Ndata
Ntime(i) = numel(varargin{i}.time);
taxis = [taxis;varargin{i}.time(:)];
end
if strcmp(required, 'unique')
boolval = numel(unique(taxis))==numel(taxis) && ~all(isnan(taxis));
% the second condition is included when the time is set to dummy nan
elseif strcmp(required, 'identical')
% the number of time bins needs at least to be the same across
% inputs
boolval = all(Ntime==Ntime(1));
if boolval
% then check whether the axes are equal
taxis = reshape(taxis, Ntime(1), []);
boolval = all(all(abs(taxis - repmat(taxis(:,1), 1, Ndata))<tol)==1);
taxis = taxis(:,1);
end
end
%--------------------------------------------------
% subfunction to check uniqueness of channel labels
function [boolval, list] = checkchan(varargin)
% last input is always the required string
required = varargin{end};
varargin = varargin(1:end-1);
Ndata = numel(varargin);
Nchan = zeros(1,Ndata);
list = cell(0,1);
for i=1:Ndata
Nchan(i) = numel(varargin{i}.label);
list = [list;varargin{i}.label(:)];
end
if strcmp(required, 'unique')
boolval = numel(unique(list))==numel(list);
elseif strcmp(required, 'identical')
boolval = 1;
end
|
github
|
philippboehmsturm/antx-master
|
ft_electroderealign.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_electroderealign.m
| 28,137 |
utf_8
|
06410d99f7ae866c70c2aed5f814bd24
|
function [norm] = ft_electroderealign(cfg)
% FT_ELECTRODEREALIGN rotates and translates electrode positions to
% template electrode positions or towards the head surface. It can
% either perform a rigid body transformation, in which only the
% coordinate system is changed, or it can apply additional deformations
% to the input electrodes.
%
% Use as
% [elec] = ft_electroderealign(cfg)
%
% Different methods for aligning the input electrodes to the subjects head
% are implemented, which are described in detail below:
%
% TEMPLATE - You can apply a spatial transformation/deformation that
% automatically minimizes the distance between the electrodes and the
% template or standard electrode set. The warping methods use a non-linear
% search to minimize the error between the input electrodes and
% corresponding template electrodes or between the input electrodes and a
% head surface.
%
% FIDUCIAL - You can apply a rigid body realignment based on three fiducial
% locations. Realigning using the fiducials only ensures that the fiducials
% (typically nose, left and right ear) are along the same axes in the input
% eectrode set as in the template electrode set.
%
% INTERACTIVE - You can display the skin surface together with the
% electrode position, and manually (using the graphical user interface)
% adjust the rotation, translation and scaling parameters, so that the
% electrodes correspond with the skin.
%
% MANUAL - You can display the skin surface and manually determine the
% electrode positions by clicking on the skin surface.
%
% The configuration can contain the following options
% cfg.method = string representing the method for aligning or placing the electrodes
% 'template' realign the electrodes to a template electrode set
% 'fiducial' realign using the NAS, LPA and RPA fiducials
% 'interactive' realign manually using a graphical user interface
% 'manual' manual positioning of the electrodes by clicking in a graphical user interface
% cfg.warp = string describing the spatial transformation for the template method
% 'rigidbody' apply a rigid-body warp (default)
% 'globalrescale' apply a rigid-body warp with global rescaling
% 'traditional' apply a rigid-body warp with individual axes rescaling
% 'nonlin1' apply a 1st order non-linear warp
% 'nonlin2' apply a 2nd order non-linear warp
% 'nonlin3' apply a 3rd order non-linear warp
% 'nonlin4' apply a 4th order non-linear warp
% 'nonlin5' apply a 5th order non-linear warp
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.fiducial = cell-array with the name of three fiducials used for
% realigning (default = {'nasion', 'lpa', 'rpa'})
% cfg.casesensitive = 'yes' or 'no', determines whether string comparisons
% between electrode labels are case sensitive (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
%
% The EEG sensor positions can be present in the data or can be specified as
% cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS
% cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS
%
% If you want to align the electrodes to a single template electrode set
% or to multiple electrode sets (which will be averaged), you should
% specify the template electrode sets as
% cfg.template = single electrode set that serves as standard
% or
% cfg.template{1..N} = list of electrode sets that are averaged into the standard
% The template electrode sets can be specified either as electrode
% structures (i.e. when they are already read in memory) or as electrode
% files.
%
% If you only want to realign using the fiducials, the template has to contain
% the three fiducials, e.g.
% cfg.template.chanpos(1,:) = [110 0 0] % location of the nose
% cfg.template.chanpos(2,:) = [0 90 0] % left ear
% cfg.template.chanpos(3,:) = [0 -90 0] % right ear
% cfg.template.label = {'nasion', 'lpa', 'rpa'}
%
% If you want to align existing electrodes to the head surface or position
% new electrodes on the head surface, you should specify the head surface as
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% See also FT_READ_SENS, FT_VOLUMEREALIGN
% Copyright (C) 2005-2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_electroderealign.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_electroderealign.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% text output
disp('Close the figure to output new sensor positions');
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end
if ~isfield(cfg, 'headshape'), cfg.headshape = []; end % for triangulated head surface, without labels
if ~isfield(cfg, 'template'), cfg.template = []; end % for electrodes or fiducials, always with labels
if ~isfield(cfg, 'warp'), cfg.warp = 'rigidbody'; end
if ~isfield(cfg, 'label'), cfg.label = 'off'; end % show labels
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'});
cfg = ft_checkconfig(cfg, 'forbidden', 'outline');
cfg = ft_checkconfig(cfg, 'renamedval',{'warp', 'homogenous', 'rigidbody'});
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
% get the electrode definition that should be warped
if nargin==1
try % try to get the description from the cfg
elec = ft_fetch_sens(cfg);
catch lasterr
% start with an empty set of electrodes, this is useful for manual positioning
elec = [];
elec.pnt = zeros(0,3);
elec.label = cell(0,1);
elec.unit = 'mm';
warning(lasterr.message, lasterr.identifier);
end
elseif nargin>1
% the input electrodes were specified as second input argument
end
elec = ft_convert_units(elec); % ensure that the units are specified
usetemplate = isfield(cfg, 'template') && ~isempty(cfg.template);
useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape);
if usetemplate
% get the template electrode definitions
if ~iscell(cfg.template)
cfg.template = {cfg.template};
end
Ntemplate = length(cfg.template);
for i=1:Ntemplate
if isstruct(cfg.template{i})
template(i) = cfg.template{i};
else
template(i) = ft_read_sens(cfg.template{i});
end
end
clear tmp
for i=1:Ntemplate
tmp(i) = ft_convert_units(template(i), elec.unit); % ensure that the units are consistent with the electrodes
tmp2(i) = ft_datatype_sens(tmp(i)); % ensure up-to-date sensor descriptions (Oct 2011)
end
template = tmp2;
end
if useheadshape
% get the surface describing the head shape
if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')
% use the headshape surface specified in the configuration
headshape = cfg.headshape;
elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3
% use the headshape points specified in the configuration
headshape.pnt = cfg.headshape;
elseif ischar(cfg.headshape)
% read the headshape from file
headshape = ft_read_headshape(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.pnt = unique(headshape.pnt, 'rows');
headshape.tri = projecttri(headshape.pnt);
end
headshape = ft_convert_units(headshape, elec.unit); % ensure that the units are consistent with the electrodes
end
% remember the original electrode locations and labels
orig = elec;
% convert all labels to lower case for string comparisons
% this has to be done AFTER keeping the original labels and positions
if strcmp(cfg.casesensitive, 'no')
for i=1:length(elec.label)
elec.label{i} = lower(elec.label{i});
end
for j=1:length(template)
for i=1:length(template(j).label)
template(j).label{i} = lower(template(j).label{i});
end
end
end
if strcmp(cfg.feedback, 'yes')
% create an empty figure, continued below...
figure
axis equal
axis vis3d
hold on
xlabel('x')
ylabel('y')
zlabel('z')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.method, 'template') && usetemplate
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
for i=1:Ntemplate
cfg.channel = ft_channelselection(cfg.channel, template(i).label);
end
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.chanpos = elec.chanpos(datsel,:);
for i=1:Ntemplate
[cfgsel, datsel] = match_str(cfg.channel, template(i).label);
template(i).label = template(i).label(datsel);
template(i).chanpos = template(i).chanpos(datsel,:);
end
% compute the average of the template electrode positions
all = [];
for i=1:Ntemplate
all = cat(3, all, template(i).chanpos);
end
avg = mean(all,3);
stderr = std(all, [], 3);
fprintf('warping electrodes to template... '); % the newline comes later
[norm.chanpos, norm.m] = warp_optim(elec.chanpos, avg, cfg.warp);
norm.label = elec.label;
dpre = mean(sqrt(sum((avg - elec.chanpos).^2, 2)));
dpost = mean(sqrt(sum((avg - norm.chanpos).^2, 2)));
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot all electrodes before warping
my_plot3(elec.chanpos, 'r.');
my_plot3(elec.chanpos(1,:), 'r*');
my_plot3(elec.chanpos(2,:), 'r*');
my_plot3(elec.chanpos(3,:), 'r*');
my_text3(elec.chanpos(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.chanpos(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.chanpos(3,:), elec.label{3}, 'color', 'r');
% plot all electrodes after warping
my_plot3(norm.chanpos, 'm.');
my_plot3(norm.chanpos(1,:), 'm*');
my_plot3(norm.chanpos(2,:), 'm*');
my_plot3(norm.chanpos(3,:), 'm*');
my_text3(norm.chanpos(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.chanpos(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.chanpos(3,:), norm.label{3}, 'color', 'm');
% plot the template electrode locations
my_plot3(avg, 'b.');
my_plot3(avg(1,:), 'b*');
my_plot3(avg(2,:), 'b*');
my_plot3(avg(3,:), 'b*');
my_text3(avg(1,:), norm.label{1}, 'color', 'b');
my_text3(avg(2,:), norm.label{2}, 'color', 'b');
my_text3(avg(3,:), norm.label{3}, 'color', 'b');
% plot lines connecting the input/warped electrode locations with the template locations
my_line3(elec.chanpos, avg, 'color', 'r');
my_line3(norm.chanpos, avg, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'template') && useheadshape
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.chanpos = elec.chanpos(datsel,:);
fprintf('warping electrodes to head shape... '); % the newline comes later
[norm.chanpos, norm.m] = warp_optim(elec.chanpos, headshape, cfg.warp);
norm.label = elec.label;
dpre = warp_error([], elec.chanpos, headshape, cfg.warp);
dpost = warp_error(norm.m, elec.chanpos, headshape, cfg.warp);
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'fiducial')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to determine the fiducials automatically if not specified
if ~isfield(cfg, 'fiducial')
option1 = {'nasion' 'left' 'right'};
option2 = {'nasion' 'lpa' 'rpa'};
option3 = {'nz' 'lpa' 'rpa'};
if length(match_str(elec.label, option1))==3
cfg.fiducial = option1;
elseif length(match_str(elec.label, option2))==3
cfg.fiducial = option2;
elseif length(match_str(elec.label, option3))==3
cfg.fiducial = option3;
else
error('could not determine three fiducials, please specify cfg.fiducial')
end
end
fprintf('using fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3});
% determine electrode selection
cfg.channel = ft_channelselection(cfg.channel, elec.label);
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.chanpos = elec.chanpos(datsel,:);
if length(cfg.fiducial)~=3
error('you must specify three fiducials');
end
% do case-insensitive search for fiducial locations
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error('not all fiducials were found in the electrode set');
end
elec_nas = elec.chanpos(nas_indx,:);
elec_lpa = elec.chanpos(lpa_indx,:);
elec_rpa = elec.chanpos(rpa_indx,:);
% FIXME change the flow in the remainder
% if one or more template electrode sets are specified, then align to the average of those
% if no template is specified, then align so that the fiducials are along the axis
% find the matching fiducials in the template and average them
templ_nas = [];
templ_lpa = [];
templ_rpa = [];
for i=1:Ntemplate
nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error(sprintf('not all fiducials were found in template %d', i));
end
templ_nas(end+1,:) = template(i).chanpos(nas_indx,:);
templ_lpa(end+1,:) = template(i).chanpos(lpa_indx,:);
templ_rpa(end+1,:) = template(i).chanpos(rpa_indx,:);
end
templ_nas = mean(templ_nas,1);
templ_lpa = mean(templ_lpa,1);
templ_rpa = mean(templ_rpa,1);
% realign both to a common coordinate system
elec2common = headcoordinates(elec_nas, elec_lpa, elec_rpa);
templ2common = headcoordinates(templ_nas, templ_lpa, templ_rpa);
% compute the combined transform and realign the electrodes to the template
norm = [];
norm.m = elec2common * inv(templ2common);
norm.chanpos = warp_apply(norm.m, elec.chanpos, 'homogeneous');
norm.label = elec.label;
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
dpre = mean(sqrt(sum((elec.chanpos([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3}));
dpost = mean(sqrt(sum((norm.chanpos([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot the first three electrodes before transformation
my_plot3(elec.chanpos(1,:), 'r*');
my_plot3(elec.chanpos(2,:), 'r*');
my_plot3(elec.chanpos(3,:), 'r*');
my_text3(elec.chanpos(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.chanpos(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.chanpos(3,:), elec.label{3}, 'color', 'r');
% plot the template fiducials
my_plot3(templ_nas, 'b*');
my_plot3(templ_lpa, 'b*');
my_plot3(templ_rpa, 'b*');
my_text3(templ_nas, ' nas', 'color', 'b');
my_text3(templ_lpa, ' lpa', 'color', 'b');
my_text3(templ_rpa, ' rpa', 'color', 'b');
% plot all electrodes after transformation
my_plot3(norm.chanpos, 'm.');
my_plot3(norm.chanpos(1,:), 'm*');
my_plot3(norm.chanpos(2,:), 'm*');
my_plot3(norm.chanpos(3,:), 'm*');
my_text3(norm.chanpos(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.chanpos(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.chanpos(3,:), norm.label{3}, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'interactive')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open a figure
fig = figure;
% add the data to the figure
set(fig, 'CloseRequestFcn', @cb_close);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', eye(4));
if useheadshape
setappdata(fig, 'headshape', headshape);
end
if usetemplate
% FIXME interactive realigning to template electrodes is not yet supported
% this requires a consistent handling of channel selection etc.
setappdata(fig, 'template', template);
end
% add the GUI elements
cb_creategui(gca);
cb_redraw(gca);
rotate3d on
waitfor(fig);
% get the data from the figure that was left behind as global variable
global norm
tmp = norm;
clear global norm
norm = tmp;
clear tmp
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'manual')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open a figure
fig = figure;
rotate3d on
ft_plot_mesh(headshape, 'edgecolor', 'k')
xyz = ft_select_point3d(headshape, 'multiple', true);
orig.chanpos = xyz;
for i=1:size(orig.chanpos,1)
orig.label{i,1} = 'unknown';
end
else
error('unknown method');
end
% apply the spatial transformation to all electrodes, and replace the
% electrode labels by their case-sensitive original values
switch cfg.method
case 'template'
norm.chanpos = warp_apply(norm.m, orig.chanpos, cfg.warp);
case {'fiducial' 'interactive'}
norm.chanpos = warp_apply(norm.m, orig.chanpos);
case 'manual'
% the positions are already assigned in correspondence with the mesh
norm = orig;
otherwise
error('unknown method');
end
if isfield(orig, 'label')
norm.label = orig.label;
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble history norm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% some simple SUBFUNCTIONs that facilitate 3D plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = my_plot3(xyz, varargin)
h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function h = my_text3(xyz, varargin)
h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function my_line3(xyzB, xyzE, varargin)
for i=1:size(xyzB,1)
line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to layout a moderately complex graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = layoutgui(fig, geometry, position, style, string, value, tag, callback);
horipos = geometry(1); % lower left corner of the GUI part in the figure
vertpos = geometry(2); % lower left corner of the GUI part in the figure
width = geometry(3); % width of the GUI part in the figure
height = geometry(4); % height of the GUI part in the figure
horidist = 0.05;
vertdist = 0.05;
options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle'
Nrow = size(position,1);
h = cell(Nrow,1);
for i=1:Nrow
if isempty(position{i})
continue;
end
position{i} = position{i} ./ sum(position{i});
Ncol = size(position{i},2);
ybeg = (Nrow-i )/Nrow + vertdist/2;
yend = (Nrow-i+1)/Nrow - vertdist/2;
for j=1:Ncol
xbeg = sum(position{i}(1:(j-1))) + horidist/2;
xend = sum(position{i}(1:(j ))) - horidist/2;
pos(1) = xbeg*width + horipos;
pos(2) = ybeg*height + vertpos;
pos(3) = (xend-xbeg)*width;
pos(4) = (yend-ybeg)*height;
h{i}{j} = uicontrol(fig, ...
options{:}, ...
'position', pos, ...
'style', style{i}{j}, ...
'string', string{i}{j}, ...
'tag', tag{i}{j}, ...
'value', value{i}{j}, ...
'callback', callback{i}{j} ...
);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_creategui(hObject, eventdata, handles);
% define the position of each GUI element
position = {
[2 1 1 1]
[2 1 1 1]
[2 1 1 1]
[1]
[1]
[1]
[1]
[1 1]
};
% define the style of each GUI element
style = {
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'pushbutton'}
{'pushbutton'}
{'toggle'}
{'toggle'}
{'text' 'edit'}
};
% define the descriptive string of each GUI element
string = {
{'rotate' 0 0 0}
{'translate' 0 0 0}
{'scale' 1 1 1}
{'redisplay'}
{'apply'}
{'toggle labels'}
{'toggle axes'}
{'alpha' 0.7}
};
% define the value of each GUI element
value = {
{[] [] [] []}
{[] [] [] []}
{[] [] [] []}
{[]}
{[]}
{0}
{0}
{[] []}
};
% define a tag for each GUI element
tag = {
{'' 'rx' 'ry' 'rz'}
{'' 'tx' 'ty' 'tz'}
{'' 'sx' 'sy' 'sz'}
{''}
{''}
{'toggle labels'}
{'toggle axes'}
{'' 'alpha'}
};
% define the callback function of each GUI element
callback = {
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{@cb_redraw}
{@cb_apply}
{@cb_redraw}
{@cb_redraw}
{[] @cb_redraw}
};
fig = get(hObject, 'parent');
layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_redraw(hObject, eventdata, handles);
fig = get(hObject, 'parent');
headshape = getappdata(fig, 'headshape');
bnd.pnt = headshape.pnt; %ft_plot_mesh wants headshape in bnd fields
bnd.tri = headshape.tri;
elec = getappdata(fig, 'elec');
template = getappdata(fig, 'template');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_sens(H, elec);
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
if ~isempty(template)
if size(template.chanpos, 2)==2
hs = plot(template.chanpos(:,1), template.chanpos(:,2), 'b.', 'MarkerSize', 20);
else
hs = plot3(template.chanpos(:,1), template.chanpos(:,2), template.chanpos(:,3), 'b.', 'MarkerSize', 20);
end
end
if ~isempty(headshape)
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
brain = [202 100 100]/255;
cortex = [255 213 119]/255;
ft_plot_mesh(bnd,'facecolor', skin,'EdgeColor','none','facealpha',0.7);
lighting gouraud
material shiny
camlight
end
if isfield(elec, 'fid') && ~isempty(elec.fid.chanpos)
ft_plot_sens(elec.fid,'style', 'r*');
end
if get(findobj(fig, 'tag', 'toggle axes'), 'value')
axis on
grid on
else
axis off
grid on
end
if get(findobj(fig, 'tag', 'toggle labels'), 'value')
cfg.label = 'on';
else
cfg.label = 'off';
end
hold on
ft_plot_sens(elec,'label',cfg.label);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_apply(hObject, eventdata, handles);
fig = get(hObject, 'parent');
elec = getappdata(fig, 'elec');
transform = getappdata(fig, 'transform');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_headshape(H, elec);
transform = H * transform;
set(findobj(fig, 'tag', 'rx'), 'string', 0);
set(findobj(fig, 'tag', 'ry'), 'string', 0);
set(findobj(fig, 'tag', 'rz'), 'string', 0);
set(findobj(fig, 'tag', 'tx'), 'string', 0);
set(findobj(fig, 'tag', 'ty'), 'string', 0);
set(findobj(fig, 'tag', 'tz'), 'string', 0);
set(findobj(fig, 'tag', 'sx'), 'string', 1);
set(findobj(fig, 'tag', 'sy'), 'string', 1);
set(findobj(fig, 'tag', 'sz'), 'string', 1);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', transform);
cb_redraw(hObject);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_close(hObject, eventdata, handles);
% make the current transformation permanent and subsequently allow deleting the figure
cb_apply(gca);
% get the updated electrode from the figure
fig = hObject;
% hmmm, this is ugly
global norm
norm = getappdata(fig, 'elec');
norm.m = getappdata(fig, 'transform');
set(fig, 'CloseRequestFcn', @delete);
delete(fig);
|
github
|
philippboehmsturm/antx-master
|
ft_singleplotTFR.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_singleplotTFR.m
| 23,569 |
utf_8
|
89516bc37d55606231d19db09c9d982f
|
function [cfg] = ft_singleplotTFR(cfg, data)
% FT_SINGLEPLOTTFR plots the time-frequency representation of power of a
% single channel or the average over multiple channels.
%
% Use as
% ft_singleplotTFR(cfg,data)
%
% The input freq structure should be a a time-frequency representation of
% power or coherence that was computed using the FT_FREQANALYSIS function.
%
% The configuration can have the following parameters:
% cfg.parameter = field to be plotted on z-axis, e.g. 'powspcrtrm' (default depends on data.dimord)
% cfg.maskparameter = field in the data to be used for masking of data
% (not possible for mean over multiple channels, or when input contains multiple subjects
% or trials)
% cfg.maskstyle = style used to masking, 'opacity' or 'saturation' (default = 'opacity')
% use 'saturation' when saving to vector-format (like *.eps) to avoid all sorts of image-problems
% cfg.maskalpha = alpha value used for masking areas dictated by cfg.maskparameter (0 - 1, default = 1)
% cfg.masknans = 'yes' or 'no' (default = 'yes')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.zlim = 'maxmin','maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE
% cfg.baselinetype = 'absolute', 'relative' or 'relchange' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.fontsize = font size of title (default = 8)
% cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment
% cfg.colormap = any sized colormap, see COLORMAP
% cfg.colorbar = 'yes', 'no' (default = 'yes')
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.directionality = '', 'inflow' or 'outflow' specifies for
% connectivity measures whether the inflow into a
% node, or the outflow from a node is plotted. The
% (default) behavior of this option depends on the dimor
% of the input data (see below).
%
% For the plotting of directional connectivity data the cfg.directionality
% option determines what is plotted. The default value and the supported
% functionality depend on the dimord of the input data. If the input data
% is of dimord 'chan_chan_XXX', the value of directionality determines
% whether, given the reference channel(s), the columns (inflow), or rows
% (outflow) are selected for plotting. In this situation the default is
% 'inflow'. Note that for undirected measures, inflow and outflow should
% give the same output. If the input data is of dimord 'chancmb_XXX', the
% value of directionality determines whether the rows in data.labelcmb are
% selected. With 'inflow' the rows are selected if the refchannel(s) occur in
% the right column, with 'outflow' the rows are selected if the
% refchannel(s) occur in the left column of the labelcmb-field. Default in
% this case is '', which means that all rows are selected in which the
% refchannel(s) occur. This is to robustly support linearly indexed
% undirected connectivity metrics. In the situation where undirected
% connectivity measures are linearly indexed, specifying 'inflow' or
% 'outflow' can result in unexpected behavior.
%
% See also FT_SINGLEPLOTER, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype, documented
% Copyright (C) 2005-2006, F.C. Donders Centre
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_singleplotTFR.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_singleplotTFR.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'freq');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelindex', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelname', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam', 'yparam'});
% Set the defaults:
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.colorbar = ft_getopt(cfg, 'colorbar', 'yes');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []);
cfg.maskalpha = ft_getopt(cfg, 'maskalpha', 1);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []);
cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'opacity');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.masknans = ft_getopt(cfg, 'masknans', 'yes');
cfg.directionality = ft_getopt(cfg, 'directionality',[]);
cfg.figurename = ft_getopt(cfg, 'figurename', []);
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
% Set x/y/parameter defaults
if ~any(ismember(dimtok, 'time'))
error('input data needs a time dimension');
else
xparam = 'time';
yparam = 'freq';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
end
if isfield(cfg, 'channel') && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
if isempty(cfg.channel)
error('no channels selected');
end
if ~isfield(data, cfg.parameter)
error('data has no field ''%s''', cfg.parameter);
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = any(ismember(dimtok, {'rpt' 'subj'}));
if hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
if isfield(data, 'crsspctrm'),
data = rmfield(data, 'crsspctrm');
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
% keep mask-parameter if it is set
if ~isempty(cfg.maskparameter)
tempmask = data.(cfg.maskparameter);
end
if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = data.dimord;
tempdata.freq = data.freq;
tempdata.label = data.label;
tempdata.powspctrm = data.(cfg.parameter);
tempdata.cfg = data.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
data.(cfg.parameter) = tempdata.powspctrm;
clear tempdata
else
data = ft_freqdescriptives(tmpcfg, data);
end
% put mask-parameter back if it is set
if ~isempty(cfg.maskparameter)
data.(cfg.maskparameter) = tempmask;
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
end % if hasrpt
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb
haslabelcmb = isfield(data, 'labelcmb');
% check whether the bivariate metric is the one requested to plot
shouldPlotCmb = (haslabelcmb && ...
size(data.(cfg.parameter),selchan(1)) == size(data.labelcmb,1)) ...
|| isfull; % this should work because if dimord has multiple chans (so isfull=1)
% then we can never plot anything without reference channel
% this is different when haslabelcmb=1; then the parameter
% requested to plot might well be a simple powspctrm
if (isfull || haslabelcmb) && shouldPlotCmb
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if haslabelcmb
cfg.refchannel = ft_channelselection(cfg.refchannel, unique(data.labelcmb(:)));
else
cfg.refchannel = ft_channelselection(cfg.refchannel, data.label);
end
if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
error('coh.refchannel = ''gui'' is not supported at the moment for ft_singleplotTFR');
%
% % Open a single figure with the channel layout, the user can click on a reference channel
% h = clf;
% ft_plot_lay(lay, 'box', false);
% title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% % add the channel information to the figure
% info = guidata(gcf);
% info.x = lay.pos(:,1);
% info.y = lay.pos(:,2);
% info.label = lay.label;
% guidata(h, info);
% %set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
% set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
% set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
% set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
% return
end
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.directionality)
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'inflow')
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter);
if length(sel1)+length(sel2)==0
error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality');
end
data.(cfg.parameter) = data.(cfg.parameter)([sel1;sel2],:,:);
data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)];
data.labelcmb = data.labelcmb([sel1;sel2],:);
data = rmfield(data, 'labelcmb');
else
% General case
sel = match_str(data.label, cfg.refchannel);
siz = [size(data.(cfg.parameter)) 1];
if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.directionality, 'outflow')
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.directionality, 'ff-fd')
error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotTFR');
elseif strcmp(cfg.directionality, 'fd-ff')
error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotTFR');
end %if directionality
end %if ~isfull
end %handle the bivariate data
% Apply baseline correction:
if ~strcmp(cfg.baseline, 'no')
% keep mask-parameter if it is set
if ~isempty(cfg.maskparameter)
tempmask = data.(cfg.maskparameter);
end
data = ft_freqbaseline(cfg, data);
% put mask-parameter back if it is set
if ~isempty(cfg.maskparameter)
data.(cfg.maskparameter) = tempmask;
end
end
% Get physical x-axis range:
if strcmp(cfg.xlim,'maxmin')
xmin = min(data.(xparam));
xmax = max(data.(xparam));
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(xparam)
xmin = nearest(data.(xparam), xmin);
xmax = nearest(data.(xparam), xmax);
end
% Get physical y-axis range:
if strcmp(cfg.ylim,'maxmin')
ymin = min(data.(yparam));
ymax = max(data.(yparam));
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(yparam)
ymin = nearest(data.(yparam), ymin);
ymax = nearest(data.(yparam), ymax);
end
% % test if X and Y are linearly spaced (to within 10^-12): % FROM UIMAGE
% x = data.(xparam)(xmin:xmax);
% y = data.(yparam)(ymin:ymax);
% dx = min(diff(x)); % smallest interval for X
% dy = min(diff(y)); % smallest interval for Y
% evenx = all(abs(diff(x)/dx-1)<1e-12); % true if X is linearly spaced
% eveny = all(abs(diff(y)/dy-1)<1e-12); % true if Y is linearly spaced
%
% % masking only possible for evenly spaced axis
% if strcmp(cfg.masknans, 'yes') && (~evenx || ~eveny)
% warning('(one of the) axis are not evenly spaced -> nans cannot be masked out -> cfg.masknans is set to ''no'';')
% cfg.masknans = 'no';
% end
%
% if ~isempty(cfg.maskparameter) && (~evenx || ~eveny)
% warning('(one of the) axis are not evenly spaced -> no masking possible -> cfg.maskparameter cleared')
% cfg.maskparameter = [];
% end
% perform channel selection
selchannel = ft_channelselection(cfg.channel, data.label);
sellab = match_str(data.label, selchannel);
% cfg.maskparameter only possible for single channel
if length(sellab) > 1 && ~isempty(cfg.maskparameter)
warning('no masking possible for average over multiple channels -> cfg.maskparameter cleared')
cfg.maskparameter = [];
end
dat = data.(cfg.parameter);
% get dimord dimensions
dims = textscan(data.dimord,'%s', 'Delimiter', '_');
dims = dims{1};
ydim = find(strcmp(yparam, dims));
xdim = find(strcmp(xparam, dims));
zdim = setdiff(1:ndims(dat), [ydim xdim]);
% and permute
dat = permute(dat, [zdim(:)' ydim xdim]);
if isfull
dat = dat(sel1, sel2, ymin:ymax, xmin:xmax);
dat = nanmean(dat, meandir);
siz = size(dat);
dat = reshape(dat, [max(siz(1:2)) siz(3) siz(4)]);
dat = dat(sellab, :, :);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xmin:xmax);
else
dat = dat(sellab, ymin:ymax, xmin:xmax);
end
if ~isempty(cfg.maskparameter)
mask = data.(cfg.maskparameter);
if isfull && cfg.maskalpha == 1
mask = mask(sel1, sel2, ymin:ymax, xmin:xmax);
mask = nanmean(mask, meandir);
siz = size(mask);
mask = reshape(mask, [max(siz(1:2)) siz(3) siz(4)]);
mask = reshape(mask(sellab, :, :), [siz(3) siz(4)]);
elseif haslabelcmb && cfg.maskalpha == 1
mask = squeeze(mask(sellab, ymin:ymax, xmin:xmax));
elseif cfg.maskalpha == 1
mask = squeeze(mask(sellab, ymin:ymax, xmin:xmax));
elseif isfull && cfg.maskalpha ~= 1 %% check me
maskl = mask(sel1, sel2, ymin:ymax, xmin:xmax);
maskl = nanmean(maskl, meandir);
siz = size(maskl);
maskl = reshape(maskl, [max(siz(1:2)) siz(3) siz(4)]);
maskl = squeeze(reshape(maskl(sellab, :, :), [siz(3) siz(4)]));
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif haslabelcmb && cfg.maskalpha ~= 1
maskl = squeeze(mask(sellab, ymin:ymax, xmin:xmax));
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif cfg.maskalpha ~= 1
maskl = squeeze(mask(sellab, ymin:ymax, xmin:xmax));
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
end
end
siz = size(dat);
datamatrix = reshape(mean(dat, 1), [siz(2:end) 1]);
xvector = data.(xparam)(xmin:xmax);
yvector = data.(yparam)(ymin:ymax);
% Get physical z-axis range (color axis):
if strcmp(cfg.zlim,'maxmin')
zmin = min(datamatrix(:));
zmax = max(datamatrix(:));
elseif strcmp(cfg.zlim,'maxabs')
zmin = -max(abs(datamatrix(:)));
zmax = max(abs(datamatrix(:)));
else
zmin = cfg.zlim(1);
zmax = cfg.zlim(2);
end
% set colormap
if isfield(cfg,'colormap')
if size(cfg.colormap,2)~=3, error('singleplotTFR(): Colormap must be a n x 3 matrix'); end
set(gcf,'colormap',cfg.colormap);
end;
% Draw plot (and mask NaN's if requested):
cla
if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter)
nans_mask = ~isnan(datamatrix);
mask = double(nans_mask);
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter)
nans_mask = ~isnan(datamatrix);
mask = mask .* nans_mask;
mask = double(mask);
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter)
mask = double(mask);
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
else
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip')
end
hold on
axis xy;
% set(gca,'Color','k')
if isequal(cfg.colorbar,'yes')
colorbar;
end
% Set adjust color axis
if strcmp('yes',cfg.hotkeys)
% Attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax})
end
% Make the figure interactive:
if strcmp(cfg.interactive, 'yes')
set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
end
% Create title text containing channel name(s) and channel number(s):
if length(sellab) == 1
t = [char(cfg.channel) ' / ' num2str(sellab) ];
else
t = sprintf('mean(%0s)', join_str(',', cfg.channel));
end
h = title(t,'fontsize', cfg.fontsize);
% set the figure window title, add channel labels if number is small
if length(sellab) < 5
chans = join_str(',', cfg.channel);
else
chans = '<multiple channels>';
end
if isfield(cfg,'dataname')
dataname = cfg.dataname;
elseif nargin > 1
dataname = inputname(2);
else
dataname = cfg.inputfile;
end
if isempty(cfg.figurename)
set(gcf, 'Name', sprintf('%d: %s: %s (%s)', gcf, mfilename, dataname, chans));
set(gcf, 'NumberTitle', 'off');
else
set(gcf, 'name', cfg.figurename);
set(gcf, 'NumberTitle', 'off');
end
axis tight;
hold off;
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting a time range
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_topoplotTFR(cfg, varargin)
% first to last callback-input of ft_select_range is range
% last callback-input of ft_select_range is contextmenu label, if used
range = varargin{end-1};
varargin = varargin(1:end-2); % remove range and last
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
cfg.comment = 'auto';
cfg.xlim = range(1:2);
cfg.ylim = range(3:4);
% compatibility fix for new ft_topoplotER/TFR cfg options
if isfield(cfg,'showlabels') && strcmp(cfg.showlabels,'yes')
cfg = rmfield(cfg,'showlabels');
cfg.marker = 'labels';
elseif isfield(cfg,'showlabels') && strcmp(cfg.showlabels,'no')
cfg = rmfield(cfg,'showlabels');
cfg.marker = 'on';
end
fprintf('selected cfg.xlim = [%f %f]\n', cfg.xlim(1), cfg.xlim(2));
fprintf('selected cfg.ylim = [%f %f]\n', cfg.ylim(1), cfg.ylim(2));
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_topoplotTFR(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
incr = (max(caxis)-min(caxis)) /10;
% symmetrically scale color bar down by 10 percent
if strcmp(eventdata.Key,'uparrow')
caxis([min(caxis)-incr max(caxis)+incr]);
% symmetrically scale color bar up by 10 percent
elseif strcmp(eventdata.Key,'downarrow')
caxis([min(caxis)+incr max(caxis)-incr]);
% resort to minmax of data for colorbar
elseif strcmp(eventdata.Key,'m')
caxis([varargin{1} varargin{2}]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_multiplotER.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_multiplotER.m
| 31,382 |
utf_8
|
1bd80c2bfc256430d7fae96db74f6f5c
|
function [cfg] = ft_multiplotER(cfg, varargin)
% FT_MULTIPLOTER plots the event-related fields or potentials versus time
% or of oscillatory activity (power or coherence) versus frequency. Multiple
% datasets can be overlayed. The plots are arranged according to their
% location specified in the layout.
%
% Use as
% ft_multiplotER(cfg, data)
% or
% ft_multiplotER(cfg, data, data2, ..., dataN)
%
% The data can be an ERP/ERF produced by FT_TIMELOCKANALYSIS, a powerspectrum
% produced by FT_FREQANALYSIS or a coherencespectrum produced by FT_FREQDESCRIPTIVES.
% If you specify multiple datasets they must contain the same channels, etc.
%
% The configuration can have the following parameters:
% cfg.parameter = field to be plotted on y-axis (default depends on data.dimord)
% 'avg', 'powspctrm' or 'cohspctrm'
% cfg.maskparameter = field in the first dataset to be used for marking significant data
% cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin', 'maxabs', or [ymin ymax] (default = 'maxmin')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.axes = 'yes', 'no' (default = 'yes')
% Draw x- and y-axes for each graph
% cfg.box = 'yes', 'no' (default = 'no')
% Draw a box around each graph
% cfg.comment = string of text (default = date + colors)
% Add 'comment' to graph (according to COMNT in the layout)
% cfg.showlabels = 'yes', 'no' (default = 'no')
% cfg.showoutline = 'yes', 'no' (default = 'no')
% cfg.fontsize = font size of comment and labels (if present) (default = 8)
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.linestyle = linestyle/marker type, see options of the matlab PLOT function (default = '-')
% can be a single style for all datasets, or a cell-array containing one style for each dataset
% cfg.linewidth = linewidth in points (default = 0.5)
% cfg.graphcolor = color(s) used for plotting the dataset(s) (default = 'brgkywrgbkywrgbkywrgbkyw')
% alternatively, colors can be specified as Nx3 matrix of RGB values
% cfg.directionality = '', 'inflow' or 'outflow' specifies for
% connectivity measures whether the inflow into a
% node, or the outflow from a node is plotted. The
% (default) behavior of this option depends on the dimor
% of the input data (see below).
% cfg.layout = specify the channel layout for plotting using one of
% the supported ways (see below).
%
% For the plotting of directional connectivity data the cfg.directionality
% option determines what is plotted. The default value and the supported
% functionality depend on the dimord of the input data. If the input data
% is of dimord 'chan_chan_XXX', the value of directionality determines
% whether, given the reference channel(s), the columns (inflow), or rows
% (outflow) are selected for plotting. In this situation the default is
% 'inflow'. Note that for undirected measures, inflow and outflow should
% give the same output. If the input data is of dimord 'chancmb_XXX', the
% value of directionality determines whether the rows in data.labelcmb are
% selected. With 'inflow' the rows are selected if the refchannel(s) occur in
% the right column, with 'outflow' the rows are selected if the
% refchannel(s) occur in the left column of the labelcmb-field. Default in
% this case is '', which means that all rows are selected in which the
% refchannel(s) occur. This is to robustly support linearly indexed
% undirected connectivity metrics. In the situation where undirected
% connectivity measures are linearly indexed, specifying 'inflow' or
% 'outflow' can result in unexpected behavior.
%
% The layout defines how the channels are arranged and what the size of each
% subplot is. You can specify the layout in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure, that will be used for creating a
% layout. If you want to have more fine-grained control over the layout
% of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the
% data should be provided as a cell array.
%
% See also FT_MULTIPLOTTFR, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER,
% FT_TOPOPLOTTFR, FT_PREPARE_LAYOUT
% Undocumented local options:
% cfg.layoutname
% cfg.zlim/xparam (set to a specific frequency range or time range [zmax zmin] for an average
% over the frequency/time bins for TFR data. Use in conjunction with e.g. xparam = 'time', and cfg.parameter = 'powspctrm').
% This function depends on FT_TIMELOCKBASELINE which has the following options:
% cfg.baseline, documented
% cfg.channel
% cfg.baselinewindow
% cfg.previous
% cfg.version
%
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype
% Copyright (C) 2003-2006, Ole Jensen
% Copyright (C) 2007-2011, Roemer van der Meij & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_multiplotER.m 7202 2012-12-15 16:11:16Z roboos $
revision = '$Id: ft_multiplotER.m 7202 2012-12-15 16:11:16Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar varargin
ft_preamble provenance varargin
for i=1:length(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq'});
end
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});
cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'});
% set the defaults
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.comment = ft_getopt(cfg, 'comment', strcat([date '\n']));
cfg.axes = ft_getopt(cfg, 'axes', 'yes');
cfg.showlabels = ft_getopt(cfg, 'showlabels', 'no');
cfg.showoutline = ft_getopt(cfg, 'showoutline', 'no');
cfg.box = ft_getopt(cfg, 'box', 'no');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.graphcolor = ft_getopt(cfg, 'graphcolor', 'brgkywrgbkywrgbkywrgbkyw');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []);
cfg.linestyle = ft_getopt(cfg, 'linestyle', '-');
cfg.linewidth = ft_getopt(cfg, 'linewidth', 0.5);
cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'box');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.directionality = ft_getopt(cfg, 'directionality', '');
cfg.figurename = ft_getopt(cfg, 'figurename', []);
Ndata = numel(varargin);
%FIXME rename directionality and refchannel in more meaningful options
if ischar(cfg.graphcolor)
GRAPHCOLOR = ['k' cfg.graphcolor];
elseif isnumeric(cfg.graphcolor)
GRAPHCOLOR = [0 0 0; cfg.graphcolor];
end
% check for linestyle being a cell-array, check it's length, and lengthen it if does not have enough styles in it
if ischar(cfg.linestyle)
cfg.linestyle = {cfg.linestyle};
end
if Ndata>1
if (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) > 1)
error('either specify cfg.linestyle as a cell-array with one cell for each dataset, or only specify one linestyle')
elseif (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) == 1)
tmpstyle = cfg.linestyle{1};
cfg.linestyle = cell(Ndata , 1);
for idataset = 1:Ndata
cfg.linestyle{idataset} = tmpstyle;
end
end
end
% % interactive plotting is not allowed with more than 1 input
% if numel(varargin)>1 && strcmp(cfg.interactive, 'yes')
% error('interactive plotting is not supported with more than 1 input data set');
% end
% ensure that the inputs are consistent with each other
for i=1:Ndata
dtype{i} = ft_datatype(varargin{i});
end
if ~all(strcmp(dtype{1}, dtype))
error('input data are of different type; this is not supported');
end
dtype = dtype{1};
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
for i=1:Ndata
% this is needed for correct treatment of GRAPHCOLOR later on
if nargin>1,
if ~isempty(inputname(i+1))
iname{i+1} = inputname(i+1);
else
iname{i+1} = ['input',num2str(i,'%02d')];
end
else
iname{i+1} = cfg.inputfile{i};
end
end
% Set x/y/parameter defaults according to datatype and dimord
switch dtype
case 'timelock'
xparam = 'time';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'avg');
case 'freq'
if any(ismember(dimtok, 'time'))
xparam = 'time';
yparam = 'freq';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
else
xparam = 'freq';
yparam = '';
cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm');
end
case 'comp'
% not supported
otherwise
% not supported
end
% user specified own fields, but no yparam (which is not asked in help)
if exist('xparam', 'var') && isfield(cfg, 'parameter') && ~exist('yparam', 'var')
yparam = '';
end
if isfield(cfg, 'channel') && isfield(varargin{1}, 'label')
cfg.channel = ft_channelselection(cfg.channel, varargin{1}.label);
elseif isfield(cfg, 'channel') && isfield(varargin{1}, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:)));
end
% perform channel selection, unless in the other plotting functions this
% can always be done because ft_multiplotER is the entry point into the
% interactive stream, but will not be revisited
for i=1:Ndata
if isfield(varargin{i}, 'label')
% only do the channel selection when it can actually be done,
% i.e. when the data are bivariate ft_selectdata will crash, moreover
% the bivariate case is handled below
varargin{i} = ft_selectdata(varargin{i}, 'channel', cfg.channel);
end
end
if isfield(varargin{1}, 'label') % && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, varargin{1}.label);
elseif isfield(varargin{1}, 'labelcmb') % && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:)));
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = sum(ismember(dimtok, {'rpt' 'subj'}));
if strcmp(dtype, 'timelock') && hasrpt,
tmpcfg = [];
tmpcfg.trials = cfg.trials;
for i=1:Ndata
% save mask (timelockanalysis will remove it)
if ~isempty(cfg.maskparameter)
tmpmask = varargin{i}.(cfg.maskparameter);
end
varargin{i} = ft_timelockanalysis(tmpcfg, varargin{i});
% put back mask
if ~isempty(cfg.maskparameter)
varargin{i}.(cfg.maskparameter) = tmpmask;
end
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
elseif strcmp(dtype, 'freq') && hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
for i=1:Ndata
if isfield(varargin{i}, 'crsspctrm'),
varargin{i} = rmfield(varargin{i}, 'crsspctrm');
end
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
for i=1:Ndata
if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = varargin{i}.dimord;
tempdata.freq = varargin{i}.freq;
tempdata.label = varargin{i}.label;
tempdata.powspctrm = varargin{i}.(cfg.parameter);
tempdata.cfg = varargin{i}.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
varargin{i}.(cfg.parameter) = tempdata.powspctrm;
clear tempdata
else
varargin{i} = ft_freqdescriptives(tmpcfg, varargin{i});
end
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
end
% Read or create the layout that will be used for plotting
cla
lay = ft_prepare_layout(cfg, varargin{1});
cfg.layout = lay;
ft_plot_lay(lay, 'box', false,'label','no','point','no');
% Apply baseline correction
if ~strcmp(cfg.baseline, 'no')
for i=1:Ndata
if strcmp(dtype, 'timelock') && strcmp(xparam, 'time')
varargin{i} = ft_timelockbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(xparam, 'time')
varargin{i} = ft_freqbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(xparam, 'freq')
error('Baseline correction is not supported for spectra without a time dimension');
else
warning('Baseline correction not applied, please set xparam');
end
end
end
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb
haslabelcmb = isfield(varargin{1}, 'labelcmb');
if (isfull || haslabelcmb) && isfield(varargin{1}, cfg.parameter)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if haslabelcmb
cfg.refchannel = ft_channelselection(cfg.refchannel, unique(varargin{1}.labelcmb(:)));
else
cfg.refchannel = ft_channelselection(cfg.refchannel, varargin{1}.label);
end
if (isfull && ~any(ismember(varargin{1}.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(varargin{1}.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
% Open a single figure with the channel layout, the user can click on a reference channel
h = clf;
ft_plot_lay(lay, 'box', false);
title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(h, info);
%set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonMotionFcn'});
return
end
for i=1:Ndata
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.directionality)
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.directionality, 'inflow')
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter);
if length(sel1)+length(sel2)==0
error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality');
end
varargin{i}.(cfg.parameter) = varargin{i}.(cfg.parameter)([sel1;sel2],:,:);
varargin{i}.label = [varargin{i}.labelcmb(sel1,1);varargin{i}.labelcmb(sel2,2)];
varargin{i}.labelcmb = varargin{i}.labelcmb([sel1;sel2],:);
varargin{i} = rmfield(varargin{i}, 'labelcmb');
else
% General case
sel = match_str(varargin{i}.label, cfg.refchannel);
siz = [size(varargin{i}.(cfg.parameter)) 1];
if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%in FieldTrip the row index 'causes' the column index channel
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.directionality, 'outflow')
%data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.directionality, 'ff-fd')
error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotER');
elseif strcmp(cfg.directionality, 'fd-ff')
error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotER');
end %if directionality
end %if ~isfull
end %for i
end %handle the bivariate data
% Get physical min/max range of x
if strcmp(cfg.xlim,'maxmin')
% Find maxmin throughout all varargins:
xmin = [];
xmax = [];
for i=1:length(varargin)
xmin = min([xmin varargin{i}.(xparam)]);
xmax = max([xmax varargin{i}.(xparam)]);
end
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Get the index of the nearest bin
for i=1:Ndata
xidmin(i,1) = nearest(varargin{i}.(xparam), xmin);
xidmax(i,1) = nearest(varargin{i}.(xparam), xmax);
end
if strcmp('freq',yparam) && strcmp('freq',dtype)
for i=1:Ndata
varargin{i} = ft_selectdata(varargin{i},'param',cfg.parameter,'foilim',cfg.zlim,'avgoverfreq','yes');
end
elseif strcmp('time',yparam) && strcmp('freq',dtype)
for i=1:Ndata
varargin{i} = ft_selectdata(varargin{i},'param',cfg.parameter,'toilim',cfg.zlim,'avgovertime','yes');
end
end
% Get physical y-axis range (ylim / parameter):
if strcmp(cfg.ylim, 'maxmin') || strcmp(cfg.ylim, 'maxabs')
% Find maxmin throughout all varargins:
ymin = [];
ymax = [];
for i=1:length(varargin)
% Select the channels in the data that match with the layout and that
% are selected for plotting:
dat = [];
dat = varargin{i}.(cfg.parameter);
seldat1 = match_str(varargin{i}.label, lay.label); % indexes labels corresponding in input and layout
seldat2 = match_str(varargin{i}.label, cfg.channel); % indexes labels corresponding in input and plot-selection
if isempty(seldat1)
error('labels in data and labels in layout do not match');
end
data = dat(intersect(seldat1,seldat2),:);
ymin = min([ymin min(min(min(data)))]);
ymax = max([ymax max(max(max(data)))]);
end
% handle maxabs, make y-axis center on 0
if strcmp(cfg.ylim, 'maxabs')
ymax = max([abs(ymax) abs(ymin)]);
ymin = -ymax;
end
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% convert the layout to Ole's style of variable names
X = lay.pos(:,1);
Y = lay.pos(:,2);
width = lay.width;
height = lay.height;
Lbl = lay.label;
% Create empty channel coordinates and labels arrays:
chanX(1:length(Lbl)) = NaN;
chanY(1:length(Lbl)) = NaN;
chanLabels = cell(1,length(Lbl));
hold on;
colorLabels = [];
if isfield(lay, 'outline') && strcmp(cfg.showoutline, 'yes')
for i=1:length(lay.outline)
if ~isempty(lay.outline{i})
tmpX = lay.outline{i}(:,1);
tmpY = lay.outline{i}(:,2);
h = line(tmpX, tmpY);
set(h, 'color', 'k');
set(h, 'linewidth', 2);
end
end
end
% Plot each data set:
for i=1:Ndata
% Make vector dat with one value for each channel
dat = varargin{i}.(cfg.parameter);
% get dimord dimensions
dims = textscan(varargin{i}.dimord,'%s', 'Delimiter', '_');
dims = dims{1};
ydim = find(strcmp(yparam, dims));
xdim = find(strcmp(xparam, dims));
zdim = setdiff(1:ndims(dat), [ydim xdim]);
% and permute
dat = permute(dat, [zdim(:)' ydim xdim]);
xval = varargin{i}.(xparam);
% Take subselection of channels, this only works
% in the non-interactive mode
if exist('selchannel', 'var')
sellab = match_str(varargin{i}.label, selchannel);
label = varargin{i}.label(sellab);
else
sellab = 1:numel(varargin{i}.label);
label = varargin{i}.label;
end
if isfull
dat = dat(sel1, sel2, xidmin(i):xidmax(i));
dat = nanmean(dat, meandir);
elseif haslabelcmb
dat = dat(sellab, xidmin(i):xidmax(i));
else
dat = dat(sellab, xidmin(i):xidmax(i));
end
xval = xval(xidmin(i):xidmax(i));
% Select the channels in the data that match with the layout:
[seldat, sellay] = match_str(label, cfg.layout.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
% gather the data of multiple input arguments
datamatrix{i} = dat(seldat, :);
% Select x and y coordinates and labels of the channels in the data
layX = cfg.layout.pos(sellay,1);
layY = cfg.layout.pos(sellay,2);
layLabels = cfg.layout.label(sellay);
if ~isempty(cfg.maskparameter)
% one value for each channel, or one value for each channel-time point
maskmatrix = varargin{1}.(cfg.maskparameter)(seldat,:);
maskmatrix = maskmatrix(:,xidmin:xidmax);
else
% create an Nx0 matrix
maskmatrix = zeros(length(seldat), 0);
end
if Ndata > 1
if ischar(GRAPHCOLOR); colorLabels = [colorLabels iname{i+1} '=' GRAPHCOLOR(i+1) '\n'];
elseif isnumeric(GRAPHCOLOR); colorLabels = [colorLabels iname{i+1} '=' num2str(GRAPHCOLOR(i+1,:)) '\n'];
end
end
end % for number of input data
for m=1:length(layLabels)
% Plot ER
if ischar(GRAPHCOLOR); color = GRAPHCOLOR(2:end);
elseif isnumeric(GRAPHCOLOR); color = GRAPHCOLOR(2:end,:);
end
mask = maskmatrix(m,:);
for i=1:Ndata
yval(i,:) = datamatrix{i}(m,:);
end
% Clip out of bounds y values:
yval(yval > ymax) = ymax;
yval(yval < ymin) = ymin;
if strcmp(cfg.showlabels,'yes')
label = layLabels(m);
else
% don't show labels
label = [];
end
ft_plot_vector(xval, yval, 'width', width(m), 'height', height(m), 'hpos', layX(m), 'vpos', layY(m), 'hlim', [xmin xmax], 'vlim', [ymin ymax], 'color', color, 'style', cfg.linestyle{i}, 'linewidth', cfg.linewidth, 'axis', cfg.axes, 'highlight', mask, 'highlightstyle', cfg.maskstyle, 'label', label, 'box', cfg.box);
if i==1,
% Keep ER plot coordinates (at centre of ER plot), and channel labels (will be stored in the figure's UserData struct):
chanX(m) = X(m) + 0.5 * width(m);
chanY(m) = Y(m) + 0.5 * height(m);
chanLabels{m} = Lbl{m};
end
end % for number of channels
% Add the colors of the different datasets to the comment:
cfg.comment = [cfg.comment colorLabels];
% Write comment text:
l = cellstrmatch('COMNT',Lbl);
if ~isempty(l)
ft_plot_text(X(l),Y(l),sprintf(cfg.comment),'Fontsize',cfg.fontsize,'interpreter','none');
end
% Plot scales:
l = cellstrmatch('SCALE',Lbl);
if ~isempty(l)
plotScales([xmin xmax],[ymin ymax],X(l),Y(l),width(1),height(1),cfg)
end
% set the figure window title
if nargin > 1
dataname = {inputname(2)};
for k = 2:Ndata
dataname{end+1} = inputname(k+1);
end
else % data provided through cfg.inputfile
dataname = cfg.inputfile;
end
if isempty(cfg.figurename)
set(gcf, 'Name', sprintf('%d: %s: %s', gcf, mfilename, join_str(', ',dataname)));
set(gcf, 'NumberTitle', 'off');
else
set(gcf, 'name', cfg.figurename);
set(gcf, 'NumberTitle', 'off');
end
% Make the figure interactive:
if strcmp(cfg.interactive, 'yes')
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
info.dataname = dataname;
guidata(gcf, info);
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonMotionFcn'});
end
axis tight
axis off
if strcmp(cfg.box, 'yes')
abc = axis;
axis(abc + [-1 +1 -1 +1]*mean(abs(abc))/10)
end
orient landscape
hold off
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous varargin
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotScales(xlim,ylim,xpos,ypos,width,height,cfg)
x1 = xpos;
x2 = xpos+width;
y1 = ypos;
y2 = ypos+width;
ft_plot_box([xpos xpos+width ypos ypos+height],'edgecolor','b')
if xlim(1) <= 0 && xlim(2) >= 0
xs = xpos+width*([0 0]-xlim(1))/(xlim(2)-xlim(1));
ys = ypos+height*(ylim-ylim(1))/(ylim(2)-ylim(1));
ft_plot_vector(xs,ys,'color','b');
end
if ylim(1) <= 0 && ylim(2) >= 0
xs = xpos+width*(xlim-xlim(1))/(xlim(2)-xlim(1));
ys = ypos+height*([0 0]-ylim(1))/(ylim(2)-ylim(1));
ft_plot_vector(xs,ys,'color','b');
end
ft_plot_text( x1,y1,num2str(xlim(1),3),'rotation',90,'HorizontalAlignment','Right','VerticalAlignment','middle','Fontsize',cfg.fontsize);
ft_plot_text( x2,y1,num2str(xlim(2),3),'rotation',90,'HorizontalAlignment','Right','VerticalAlignment','middle','Fontsize',cfg.fontsize);
ft_plot_text( x2,y1,num2str(ylim(1),3),'HorizontalAlignment','Left','VerticalAlignment','bottom','Fontsize',cfg.fontsize);
ft_plot_text( x2,y2,num2str(ylim(2),3),'HorizontalAlignment','Left','VerticalAlignment','bottom','Fontsize',cfg.fontsize);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function l = cellstrmatch(str,strlist)
l = [];
for k=1:length(strlist)
if strcmp(char(str),char(strlist(k)))
l = [l k];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_multiplotER(label, cfg, varargin)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
% put data name in here, this cannot be resolved by other means
info = guidata(gcf);
cfg.dataname = info.dataname;
if iscell(label)
label = label{1};
end
cfg.refchannel = label; %FIXME this only works with label being a string
fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel);
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_multiplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotER(label, cfg, varargin)
if ~isempty(label)
if isfield(cfg, 'inputfile')
% the reading has already been done and varargin contains the data
cfg = rmfield(cfg, 'inputfile');
end
cfg.xlim = 'maxmin';
cfg.channel = label;
% put data name in here, this cannot be resolved by other means
info = guidata(gcf);
cfg.dataname = info.dataname;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotER(cfg, varargin{:});
end
|
github
|
philippboehmsturm/antx-master
|
ft_prepare_mesh.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_prepare_mesh.m
| 10,173 |
utf_8
|
fbd785246b232a3602fdd438fd772878
|
function [bnd, cfg] = ft_prepare_mesh(cfg, mri)
% FT_PREPARE_MESH creates a triangulated surface mesh for the volume
% conduction model. The mesh can either be selected manually from raw
% mri data or can be generated starting from a segmented volume
% information stored in the mri structure. The result is a bnd
% structure which contains the information about all segmented surfaces
% related to mri and are expressed in world coordinates.
%
% Use as
% bnd = ft_prepare_mesh(cfg, volume)
% bnd = ft_prepare_mesh(cfg, segmentation)
%
% Configuration options:
% cfg.interactive = 'no' (default) or 'yes' (manual interaction)
% cfg.tissue = cell-array with tissue types or numeric vector with integer values
% cfg.numvertices = numeric vector, should have same number of elements as cfg.tissue
% cfg.downsample = integer number (default = 1, i.e. no downsampling), see FT_VOLUMEDOWNSAMPLE
% cfg.headshape = (optional) a filename containing headshape, a Nx3 matrix with surface
% points, or a structure with a single or multiple boundaries
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% Example
% mri = ft_read_mri('Subject01.mri');
%
% cfg = [];
% cfg.output = {'scalp', 'skull', 'brain'};
% segmentation = ft_volumesegment(cfg, mri);
%
% cfg = [];
% cfg.tissue = {'scalp', 'skull', 'brain'};
% cfg.numvertices = [800, 1600, 2400];
% bnd = ft_prepare_mesh(cfg, segmentation);
%
% See also FT_VOLUMESEGMENT, FT_PREPARE_HEADMODEL, FT_PLOT_MESH
% Undocumented functionality: at this moment it allows for either
% bnd = ft_prepare_mesh(cfg) or
% bnd = ft_prepare_mesh(cfg, headmodel)
% but more consistent would be to specify a volume conduction model with
% cfg.vol = structure with volume conduction model, see FT_PREPARE_HEADMODEL
% cfg.headshape = name of file containing the volume conduction model, see FT_READ_VOL
% Copyrights (C) 2009-2012, Cristiano Micheli & Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_prepare_mesh.m 7385 2013-01-23 13:21:45Z johzum $
revision = '$Id: ft_prepare_mesh.m 7385 2013-01-23 13:21:45Z johzum $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar mri
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'forbidden', {'numcompartments', 'outputfile', 'sourceunits', 'mriunits'});
% get the defaults
cfg.headshape = ft_getopt(cfg, 'headshape'); % input option
cfg.interactive = ft_getopt(cfg, 'interactive', 'no'); % to interact with the volume
% cfg.tissue = ft_getopt(cfg, 'tissue'); % to perform the meshing on a specific tissue
cfg.numvertices = ft_getopt(cfg, 'numvertices'); % resolution of the mesh
cfg.downsample = ft_getopt(cfg, 'downsample', 1);
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
% here we cannot use nargin, because the data might have been loaded from cfg.inputfile
hasdata = exist('mri', 'var');
if ~hasdata
mri = [];
elseif ~ft_voltype(mri, 'unknown')
% The input appears to be a headmodel. This is deprecated, but at this
% moment (2012-09-28) we decided not to break the old functionality yet.
else
mri = ft_checkdata(mri, 'datatype', {'volume', 'segmentation'});
end
if hasdata
% try to estimate the units, these will also be assigned to the output meshes
mri = ft_convert_units(mri);
end
if hasdata
% determine the type of input data
basedonmri = ft_datatype(mri, 'volume');
basedonseg = ft_datatype(mri, 'segmentation');
basedonheadshape = 0;
basedonbnd = isfield(mri, 'bnd');
basedonsphere = all(isfield(mri, {'r', 'o'}));
elseif isfield(cfg,'headshape') && ~isempty(cfg.headshape)
% in absence of input data
basedonmri = false;
basedonseg = false;
basedonheadshape = true;
basedonbnd = false;
basedonsphere = false;
else
error('inconsistent configuration and input data');
end
if isfield(cfg, 'method') && strcmp(cfg.method, 'hexahedral')
% the MRI is assumed to contain a segmentation, call the helper function
bnd = prepare_mesh_hexahedral(cfg, mri); %should go fieldtrip/private
% ensure that non of the other options gets executed
basedonmri = false;
basedonseg = false;
basedonheadshape = false;
basedonbnd = false;
basedonsphere = false;
elseif isfield(cfg, 'method') && strcmp(cfg.method, 'tetrahedral')
% the MRI is assumed to contain a segmentation, call the helper function
bnd = prepare_mesh_tetrahedral(cfg, mri);
% ensure that non of the other options gets executed
basedonmri = false;
basedonseg = false;
basedonheadshape = false;
basedonbnd = false;
basedonsphere = false;
elseif basedonseg || basedonmri
if all(isfield(mri, {'gray', 'white', 'csf'}))
cfg.tissue = ft_getopt(cfg, 'tissue', 'brain');
cfg.numvertices = ft_getopt(cfg, 'numvertices', 3000);
else
cfg.tissue = ft_getopt(cfg, 'tissue');
end
cfg = ft_checkconfig(cfg, 'required', {'tissue', 'numvertices'});
end
if (basedonseg || basedonmri) && cfg.downsample~=1
% optionally downsample the anatomical MRI and/or the tissue segmentation
tmpcfg = [];
tmpcfg.downsample = cfg.downsample;
mri = ft_volumedownsample(tmpcfg, mri);
end
if (basedonmri || basedonseg) && istrue(cfg.interactive)
% this only makes sense with a (segmented) MRI as input
fprintf('using the manual approach\n');
bnd = prepare_mesh_manual(cfg, mri);
elseif basedonseg
% FIXME this should be renamed to prepare_mesh_triangulation
fprintf('using the segmentation approach\n');
bnd = prepare_mesh_segmentation(cfg, mri);
elseif basedonmri && iscell(cfg.tissue) && all(isfield(mri, cfg.tissue))
% the input is not detected as segmentation, but it does have all fields
% that the user requests to have triangulated, so assume that it is a
% segmentation after all
fprintf('using the segmentation approach\n');
bnd = prepare_mesh_segmentation(cfg, mri);
elseif basedonmri
error('Unsegmented MRI only allowed in combination with cfg.interactive=yes')
elseif basedonheadshape
fprintf('using the head shape to construct a triangulated mesh\n');
bnd = prepare_mesh_headshape(cfg);
elseif basedonbnd
fprintf('using the mesh specified in the input volume conductor\n');
bnd = mri.bnd;
elseif basedonsphere
fprintf('triangulating the sphere in the volume conductor\n');
vol = mri;
[pnt, tri] = makesphere(cfg.numvertices);
switch ft_voltype(vol)
case {'singlesphere' 'concentricspheres'}
bnd = [];
for i=1:length(vol.r)
bnd(i).pnt(:,1) = pnt(:,1)*vol.r(i) + vol.o(1);
bnd(i).pnt(:,2) = pnt(:,2)*vol.r(i) + vol.o(2);
bnd(i).pnt(:,3) = pnt(:,3)*vol.r(i) + vol.o(3);
bnd(i).tri = tri;
end
case 'localspheres'
% FIXME this should be replaced by an outline of the head, see private/headsurface
bnd = [];
for i=1:length(vol.label)
bnd(i).pnt(:,1) = pnt(:,1)*vol.r(i) + vol.o(i,1);
bnd(i).pnt(:,2) = pnt(:,2)*vol.r(i) + vol.o(i,2);
bnd(i).pnt(:,3) = pnt(:,3)*vol.r(i) + vol.o(i,3);
bnd(i).tri = tri;
end
end
elseif isfield(cfg, 'method') && strcmp(cfg.method, 'hexahedral')
% do nothing
elseif isfield(cfg, 'method') && strcmp(cfg.method, 'tetrahedral')
% do nothing
else
error('unsupported cfg.method and/or input')
end
% copy the geometrical units from the input to the output
if ~isfield(bnd, 'unit') && hasdata
for i=1:numel(bnd)
bnd(i).unit = mri.unit;
end
elseif ~isfield(bnd, 'unit')
bnd = ft_convert_units(bnd);
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HELPER FUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pnt, tri] = makesphere(numvertices)
if isempty(numvertices)
[pnt,tri] = icosahedron162;
fprintf('using the mesh specified by icosaedron162\n');
elseif numvertices==42
[pnt,tri] = icosahedron42;
fprintf('using the mesh specified by icosaedron%d\n',size(pnt,1));
elseif numvertices==162
[pnt,tri] = icosahedron162;
fprintf('using the mesh specified by icosaedron%d\n',size(pnt,1));
elseif numvertices==642
[pnt,tri] = icosahedron642;
fprintf('using the mesh specified by icosaedron%d\n',size(pnt,1));
elseif numvertices==2562
[pnt,tri] = icosahedron2562;
fprintf('using the mesh specified by icosaedron%d\n',size(pnt,1));
else
[pnt, tri] = msphere(numvertices);
fprintf('using the mesh specified by msphere with %d vertices\n',size(pnt,1));
end
|
github
|
philippboehmsturm/antx-master
|
ft_compile_mex.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_compile_mex.m
| 7,313 |
utf_8
|
99f0549ed011b3639df37378d6aa4305
|
function ft_compile_mex(force)
% FT_COMPILE_MEX can be used for compiling most of the FieldTrip MEX files
% Note that this function does not put the MEX files in the correct
% location in the private folders, this is managed by SVN autosync. In case
% you are not working with SVN and you want to recompile the mex files for
% your platform, you can find all mex files for your platform and move them
% to a backup directory that is not on your MATLAB path. Subsequently you
% can rtun this function to recompile it on your platform with your
% compiler settings
%
% The standards procedure for compiling mex files is detailled on
% http://fieldtrip.fcdonders.nl/code_guidelines#compiling_mex_files
%
% Please note that this script does NOT set up your MEX environment for
% you, so in case you haven't selected the C compiler on Windows yet, you
% need to type 'mex -setup' first to choose either the LCC, Borland or
% Microsoft compiler. If you want to use MinGW, you also need to install
% Gnumex (http://gnumex.sourceforget.net), which comes with its own
% procedure for setting up the MEX environment.
%
% The logic in this script is to first build a list of files that actually
% need compilation for the particular platform that Matlab is running on,
% and then to go through that list. Functions are added to the list by
% giving their destination directory and (relative to that) the name of the
% source file (without the .c). Optionally, you can specify a list of
% platform this file needs to be compiled on only, and a list of platforms
% where you don't compile it on. Finally, you can give extra arguments to
% the MEX command, e.g., for including other c-sources or giving compiler
% flags.
%
% See also MEX
% Copyright (C) 2010, Stefan Klanke
%
% $Id: ft_compile_mex.m 7123 2012-12-06 21:21:38Z roboos $
if nargin<1
force=false;
end
% Possible COMPUTER types
% GLNX86
% GLNXA64
% PCWIN
% PCWIN64
% MAC
% MACI
% MACI64
L = [];
L = add_mex_source(L,'fileio/@uint64','abs');
L = add_mex_source(L,'fileio/@uint64','min');
L = add_mex_source(L,'fileio/@uint64','max');
L = add_mex_source(L,'fileio/@uint64','plus');
L = add_mex_source(L,'fileio/@uint64','minus');
L = add_mex_source(L,'fileio/@uint64','times');
L = add_mex_source(L,'fileio/@uint64','rdivide');
L = add_mex_source(L,'@config/private','deepcopy');
L = add_mex_source(L,'@config/private','increment');
L = add_mex_source(L,'@config/private','setzero');
L = add_mex_source(L,'realtime/online_mri','ft_omri_smooth_volume');
L = add_mex_source(L,'realtime/acquisition/siemens', 'sap2matlab',[],[],'siemensap.c -I.');
L = add_mex_source(L,'src','ft_getopt');
L = add_mex_source(L,'src','read_16bit');
L = add_mex_source(L,'src','read_24bit');
L = add_mex_source(L,'src','read_ctf_shm', {'GLNX86'}); % only compile on GLNX86
L = add_mex_source(L,'src','write_ctf_shm', {'GLNX86'}); % only compile on GLNX86
L = add_mex_source(L,'src','lmoutr',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','ltrisect',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','plinproj',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','ptriproj',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','routlm',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','solid_angle',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','rfbevent',[],{'PCWIN', 'PCWIN64'},'d3des.c -I.'); % do not compile on WIN32 and WIN64
L = add_mex_source(L,'src','meg_leadfield1');
L = add_mex_source(L,'src','splint_gh');
L = add_mex_source(L,'src','plgndr');
L = add_mex_source(L,'src','ft_spike_sub_crossx');
L = add_mex_source(L,'src','rename');
L = add_mex_source(L,'src','getpid');
L = add_mex_source(L,'src','nanmean');
L = add_mex_source(L,'src','nanstd');
L = add_mex_source(L,'src','nanvar');
L = add_mex_source(L,'src','nansum');
L = add_mex_source(L,'src','nanstd');
L = add_mex_source(L,'src','det2x2');
L = add_mex_source(L,'src','inv2x2');
L = add_mex_source(L,'src','mtimes2x2');
L = add_mex_source(L,'src','sandwich2x2');
L = add_mex_source(L,'src','mxSerialize');
L = add_mex_source(L,'src','mxDeserialize');
L = add_mex_source(L,'src','CalcMD5');
oldDir = pwd;
[baseDir, myName] = fileparts(mfilename('fullpath'));
try
compile_mex_list(L, baseDir, force);
catch
% the "catch me" syntax is broken on MATLAB74, this fixes it
me = lasterror;
cd(oldDir);
rethrow(me);
end
cd(oldDir);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%
% Use as
% list = add_mex_source(list, directory, relName, includePlatform, excludePlatform, extras)
%
% The list is a structure array of directory names, source file names, and
% extra arguments required for the compilation of MEX files. This function will
% create a new element of this structure and append it to L.
%
% directory = target directory of the mex-file
% relName = source file relative to 'directory'
% includePlatform = list of platforms this MEX file should only be compiled for.
% use an empty matrix [] to compile for all platforms
% excludePlatform = list of platforms this MEX file should NOT be compiled for.
% extras = extra arguments to the MEX command, e.g. additional source files
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function L = add_mex_source(L, directory, relName, includePlatform, excludePlatform, extras)
% Check if this file only needs compilation on certain platforms (including this one)
if nargin>3 && ~isempty(includePlatform)
ok = false;
for k=1:numel(includePlatform)
if strcmp(includePlatform{k}, computer)
ok = true;
break;
end
end
if ~ok
return
end
end
% Check if this file cannot be compiled on certain platforms (including this one)
if nargin>4 && ~isempty(excludePlatform)
ok = true;
for k=1:numel(excludePlatform)
if strcmp(excludePlatform{k}, computer)
return;
end
end
end
L(end+1).dir = directory;
L(end).relName = relName;
if nargin>5
L(end).extras = extras;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%
% Use as
% compile_mex_list(L, baseDir)
%
% Compile a list of MEX files as determined by the input argument L.
% The second argument 'baseDir' is the common base directory for the
% files listed in L. The third argument is a flag that determines
% whether to force (re-)compilation even if the MEX file is up-to-date.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function compile_mex_list(L, baseDir, force)
for i=1:length(L)
[relDir, name] = fileparts(L(i).relName);
sfname = [baseDir filesep L(i).dir filesep L(i).relName '.c'];
SF = dir(sfname);
if numel(SF)<1
fprintf(1,'Error: source file %s cannot be found.', sfname);
continue;
end
if ~force
mfname = [baseDir filesep L(i).dir filesep name '.' mexext];
MF = dir(mfname);
if numel(MF)==1 && datenum(SF.date) <= datenum(MF.date)
fprintf(1,'Skipping up-to-date MEX file %s/%s\n', L(i).dir, name);
continue;
end
end
fprintf(1,'Compiling MEX file %s/%s ...\n', L(i).dir, name);
cd([baseDir '/' L(i).dir]);
cmd = sprintf('mex %s.c %s', L(i). relName, L(i).extras);
eval(cmd);
end
|
github
|
philippboehmsturm/antx-master
|
fieldtrip2fiff.m
|
.m
|
antx-master/xspm8/external/fieldtrip/fieldtrip2fiff.m
| 8,464 |
utf_8
|
64f159942bcde33deaf3ee377c4fcf68
|
function fieldtrip2fiff(filename, data)
% FIELDTRIP2FIFF saves a FieldTrip raw data structure as a fiff-file,
% in order to be useable by the Neuromag software, or in the MNE suite
% software.
%
% Use as
% fieldtrip2fiff(filename, data)
% where filename is the name of the output file, and data is a raw
% data structure as obtained from FT_PREPROCESSING, or a timelock
% structure obtained from FT_TIMELOCKANALYSIS.
%
% See also FT_DATATYPE_RAW, FT_DATATYPE_TIMELOCK
% Copyright (C) 2012, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: fieldtrip2fiff.m 7123 2012-12-06 21:21:38Z roboos $
revision = '$Id: fieldtrip2fiff.m 7123 2012-12-06 21:21:38Z roboos $';
ft_defaults % this ensures that the path is correct and that the ft_defaults global variable is available
ft_preamble help % this will show the function help if nargin==0 and return an error
ft_preamble callinfo % this records the time and memory usage at teh beginning of the function
% ensure that the filename has the correct extension
[pathstr,name,ext] = fileparts(filename);
if isempty(ext),
filename = [filename, '.fif'];
elseif ~strcmp(ext, 'fif')
error('if the filename is specified with extension, this should read .fif');
end
% ensure the mne-toolbox to be on the path
ft_hastoolbox('mne', 1);
% check the input data
data = ft_checkdata(data, 'datatype', {'raw', 'timelock'}, 'feedback', 'yes');
istlck = ft_datatype(data, 'timelock');
israw = ft_datatype(data, 'raw');
% Create a fiff-header, or take it from the original header if possible
if ft_senstype(data, 'neuromag') && isfield(data, 'hdr')
% Tune the original FIFF header to match with the data
info = data.hdr.orig;
info.sfreq = fsample;
if info.nchan ~= size(dataout{1},1);
fprintf('WARNING: A non-matching number of channels in the FT data structure and original file header. Integrity of the data might be compromised\');
info.nchan = size(dataout{1},1);
info.chs = info.chs(1:size(dataout{1},1)); % FIXME: Terrible hack to tolerate removal of channels
end
else
info.meas_id.version = nan;
info.meas_id.machid = [nan;nan];
info.meas_id.secs = nan;
info.meas_id.usecs = nan;
info.meas_date = [nan;nan];
info.nchan = numel(data.label);
info.highpass = nan;
info.lowpass = nan;
info.dev_head_t = [];
info.ctf_head_t = [];
info.dig = [];
info.projs = [];
info.comps = [];
info.bads = [];
info.ch_names = data.label(:)';
info.chs = grad2fiff(data);
if istlck,
info.sfreq = 1./mean(diff(data.time));
info.isaverage = 1;
info.isepoched = 0;
info.iscontinuous = 0;
elseif israw,
info.sfreq = 1./mean(diff(data.time{1}));
info.isaverage = 0;
info.isepoched = 1;
info.iscontinuous = 0;
end
end
if istlck
evoked.aspect_kind = 100;
evoked.is_smsh = 0;
evoked.nave = max(data.dof(:));
evoked.first = round(data.time(1)*info.sfreq);
evoked.last = round(data.time(end)*info.sfreq);
evoked.times = data.time;
evoked.comment = sprintf('FieldTrip data averaged');
evoked.epochs = data.avg;
elseif israw
for j = 1:length(dataout)
evoked(j).aspect_kind = 100;
evoked(j).is_smsh = 0; % FIXME: How could we tell?
evoked(j).nave = 1; % FIXME: Use the real value
evoked(j).first = round(data.time{j}(1)*info.sfreq);
evoked(j).last = round(data.time{j}(end)*info.sfreq);
evoked(j).times = data.time{j};
evoked(j).comment = sprintf('FieldTrip data, category/trial %d', j);
evoked(j).epochs = data.trial{j};
end
end
fiffdata.info = info;
fiffdata.evoked = evoked;
fiff_write_evoked(filename, fiffdata);
ft_postamble callinfo % this records the time and memory at the end of the function, prints them on screen and adds this information together with the function name and matlab version etc. to the output cfg
ft_postamble previous datain % this copies the datain.cfg structure into the cfg.previous field. You can also use it for multiple inputs, or for "varargin"
ft_postamble history dataout % this adds the local cfg structure to the output data structure, i.e. dataout.cfg = cfg
ft_postamble savevar dataout % this saves the output data structure to disk in case the user specified the cfg.outputfile option
%-------------------
% subfunction
function [chs] = grad2fiff(data)
if isfield(data, 'grad')
hasgrad = true;
else
hasgrad = false;
end
for k = 1:numel(data.label)
% create a struct for each channel
chs(1,k).scanno = 1;
chs(1,k).logno = 1;
chs(1,k).kind = nan;
chs(1,k).range = 1;
chs(1,k).cal = 1;
chs(1,k).coil_type = nan;
chs(1,k).loc = zeros(12,1);
chs(1,k).coil_trans = eye(4);
chs(1,k).eeg_loc = [];
chs(1,k).coord_frame = nan;
chs(1,k).unit = nan;
chs(1,k).unit_mul = 0;
chs(1,k).ch_name = data.label{k};
end
if hasgrad
% the position information can be recovered, too
[i1,i2] = match_str(data.label, data.grad.label);
for k = 1:numel(i1)
chs(1,i1(k)).kind = 1;
chs(1,i1(k)).coil_type = 3022;
chs(1,i1(k)).unit = 112;
chs(1,i1(k)).coord_frame = int32(4); % head coordinates
chs(1,i1(k)).loc(1:3) = data.grad.chanpos(i2(k),:);
chs(1,i1(k)).loc(4:end) = reshape(eye(3),[9 1]);
end
end
% Below the documentation to the original code contributed by Lauri
% Parkkonen
%
% fieldtrip2fiff(filename, data)
%
% Write the data in the FieldTrip structure 'data' to a FIFF file
% 'filename'. If an average
%
% Caveats:
%
% - the FIFF tag indicating the number of trials in average is set to unity
% as there is no generic way to determine a proper value.
%
% - the FIFF tag indicating the use of 'MaxShield' is set to 'no'.
%
% - if channels have been removed in FieldTrip, channel information for
% a matching number of channels is copied from the original FIFF
% header. If channels have been removed from anywhere else except from
% the end, this simple hack screws up the pairing of signals and channel
% identities. BEWARE!
% (C)opyright Lauri Parkkonen, 2010 - 2011
%
% $Log$
%
% % Construct the evoked data aspect for each category
% ave = isfield(data, 'average');
% trl = isfield(data, 'trial');
%
% if ave && trl
% fprintf('WARNING: Data structure contains both an average and individual trials; writing out the average');
% dataout = data.average;
% elseif ave && ~trl
% dataout = data.average;
% elseif ~ave && trl
% dataout = data.trial;
% else
% error('No average or trial data to write out');
% end
%
% % Tune the original FIFF header to match with the data
% info = data.hdr.orig;
% info.sfreq = data.fsample;
% if info.nchan ~= size(dataout{1},1);
% fprintf('WARNING: A non-matching number of channels in the FT data structure and original file header. Integrity of the data might be compromised\');
% info.nchan = size(dataout{1},1);
% info.chs = info.chs(1:size(dataout{1},1)); % FIXME: Terrible hack to tolerate removal of channels
% end
%
%
% for c = 1:length(dataout)
% evoked(c).aspect_kind = 100;
% evoked(c).is_smsh = 0; % FIXME: How could we tell?
% evoked(c).nave = 1; % FIXME: Use the real value
% evoked(c).first = round(data.time{1}(1) * data.fsample);
% evoked(c).last = round(data.time{1}(end) * data.fsample);
% evoked(c).times = data.time{1};
% evoked(c).comment = sprintf('FieldTrip data, category/trial %d', c);
% evoked(c).epochs = dataout{c};
% end
%
% fiffdata.info = info;
% fiffdata.evoked = evoked;
%
% fiff_write_evoked(filename, fiffdata);
%
% end
|
github
|
philippboehmsturm/antx-master
|
ft_artifact_zvalue.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_artifact_zvalue.m
| 44,375 |
utf_8
|
328e4d904f0da260a5ef1d676bee355a
|
function [cfg, artifact] = ft_artifact_zvalue(cfg, data)
% FT_ARTIFACT_ZVALUE reads the interesting segments of data from file and
% identifies artifacts by means of thresholding the z-transformed value
% of the preprocessed raw data. Depending on the preprocessing options,
% this method will be sensitive to EOG, muscle or jump artifacts.
% This procedure only works on continuously recorded data.
%
% Use as
% [cfg, artifact] = ft_artifact_zvalue(cfg)
% or
% [cfg, artifact] = ft_artifact_zvalue(cfg, data)
%
% The output argument "artifact" is a Nx2 matrix comparable to the
% "trl" matrix of FT_DEFINETRIAL. The first column of which specifying the
% beginsamples of an artifact period, the second column contains the
% endsamples of the artifactperiods.
%
% If you are calling FT_ARTIFACT_ZVALUE with only the configuration as first
% input argument and the data still has to be read from file, you should
% specify
% cfg.headerfile
% cfg.datafile
% and optionally
% cfg.headerformat
% cfg.dataformat
%
% If you are calling FT_ARTIFACT_ZVALUE with also the second input argument
% "data", then that should contain data that was already read from file
% a call to FT_PREPROCESSING.
%
% If you encounter difficulties with memory usage, you can use
% cfg.memory = 'low' or 'high', whether to be memory or computationally efficient, respectively (default = 'high')
%
% The required configuration settings are:
% cfg.trl
% cfg.continuous
% cfg.artfctdef.zvalue.channel
% cfg.artfctdef.zvalue.cutoff
% cfg.artfctdef.zvalue.trlpadding
% cfg.artfctdef.zvalue.fltpadding
% cfg.artfctdef.zvalue.artpadding
%
% If you specify
% cfg.artfctdef.zvalue.interactive = 'yes', a GUI will be started and you
% can manually accept/reject detected artifacts, and/or change the threshold
%
% If you specify
% cfg.artfctdef.zvalue.artfctpeak='yes', the maximum value of the artifact
% within its range will be found; saved into cfg.artfctdef.zvalue.peaks
% Use also, e.g. as input to DSS option of ft_componentanalysis:
% cfg.artfctdef.zvalue.artfctpeakrange= [-0.25 0.25]; (in seconds), (for example)
% to indicate range around peak to include, saved into cfg.artfctdef.zvalue.dssartifact
% Default values: [0 0]
% Range will respect trial boundaries (i.e. be shorter if peak is near beginning or end of trial)
% Samples between trials will be removed; thus this won't match .sampleinfo of the data structure
%
% Configuration settings related to the preprocessing of the data are
% cfg.artfctdef.zvalue.lpfilter = 'no' or 'yes' lowpass filter
% cfg.artfctdef.zvalue.hpfilter = 'no' or 'yes' highpass filter
% cfg.artfctdef.zvalue.bpfilter = 'no' or 'yes' bandpass filter
% cfg.artfctdef.zvalue.lnfilter = 'no' or 'yes' line noise removal using notch filter
% cfg.artfctdef.zvalue.dftfilter = 'no' or 'yes' line noise removal using discrete fourier transform
% cfg.artfctdef.zvalue.medianfilter = 'no' or 'yes' jump preserving median filter
% cfg.artfctdef.zvalue.lpfreq = lowpass frequency in Hz
% cfg.artfctdef.zvalue.hpfreq = highpass frequency in Hz
% cfg.artfctdef.zvalue.bpfreq = bandpass frequency range, specified as [low high] in Hz
% cfg.artfctdef.zvalue.lnfreq = line noise frequency in Hz, default 50Hz
% cfg.artfctdef.zvalue.lpfiltord = lowpass filter order
% cfg.artfctdef.zvalue.hpfiltord = highpass filter order
% cfg.artfctdef.zvalue.bpfiltord = bandpass filter order
% cfg.artfctdef.zvalue.lnfiltord = line noise notch filter order
% cfg.artfctdef.zvalue.medianfiltord = length of median filter
% cfg.artfctdef.zvalue.lpfilttype = digital filter type, 'but' (default) or 'fir'
% cfg.artfctdef.zvalue.hpfilttype = digital filter type, 'but' (default) or 'fir'
% cfg.artfctdef.zvalue.bpfilttype = digital filter type, 'but' (default) or 'fir'
% cfg.artfctdef.zvalue.detrend = 'no' or 'yes'
% cfg.artfctdef.zvalue.demean = 'no' or 'yes'
% cfg.artfctdef.zvalue.baselinewindow = [begin end] in seconds, the default is the complete trial
% cfg.artfctdef.zvalue.hilbert = 'no' or 'yes'
% cfg.artfctdef.zvalue.rectify = 'no' or 'yes'
%
% See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG,
% FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE
% Copyright (C) 2003-2011, Jan-Mathijs Schoffelen & Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_artifact_zvalue.m 7123 2012-12-06 21:21:38Z roboos $
revision = '$Id: ft_artifact_zvalue.m 7123 2012-12-06 21:21:38Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble loadvar data
% set default rejection parameters
cfg.headerformat = ft_getopt(cfg, 'headerformat', []);
cfg.dataformat = ft_getopt(cfg, 'dataformat', []);
cfg.memory = ft_getopt(cfg, 'memory', 'high');
cfg.artfctdef = ft_getopt(cfg, 'artfctdef', []);
cfg.artfctdef.zvalue = ft_getopt(cfg.artfctdef, 'zvalue', []);
cfg.artfctdef.zvalue.method = ft_getopt(cfg.artfctdef.zvalue, 'method', 'all');
cfg.artfctdef.zvalue.ntrial = ft_getopt(cfg.artfctdef.zvalue, 'ntrial', 10);
cfg.artfctdef.zvalue.channel = ft_getopt(cfg.artfctdef.zvalue, 'channel', {});
cfg.artfctdef.zvalue.trlpadding = ft_getopt(cfg.artfctdef.zvalue, 'trlpadding', 0);
cfg.artfctdef.zvalue.fltpadding = ft_getopt(cfg.artfctdef.zvalue, 'fltpadding', 0);
cfg.artfctdef.zvalue.artpadding = ft_getopt(cfg.artfctdef.zvalue, 'artpadding', 0);
cfg.artfctdef.zvalue.interactive = ft_getopt(cfg.artfctdef.zvalue, 'interactive', 'no');
cfg.artfctdef.zvalue.cumulative = ft_getopt(cfg.artfctdef.zvalue, 'cumulative', 'yes');
cfg.artfctdef.zvalue.artfctpeak = ft_getopt(cfg.artfctdef.zvalue, 'artfctpeak', 'no');
cfg.artfctdef.zvalue.artfctpeakrange = ft_getopt(cfg.artfctdef.zvalue, 'artfctpeakrange',[0 0]);
% for backward compatibility
cfg.artfctdef = ft_checkconfig(cfg.artfctdef, 'renamed', {'blc', 'demean'});
cfg.artfctdef = ft_checkconfig(cfg.artfctdef, 'renamed', {'blcwindow' 'baselinewindow'});
cfg.artfctdef.zvalue = ft_checkconfig(cfg.artfctdef.zvalue, 'renamed', {'sgn', 'channel'});
cfg.artfctdef.zvalue = ft_checkconfig(cfg.artfctdef.zvalue, 'renamed', {'feedback', 'interactive'});
if isfield(cfg.artfctdef.zvalue, 'artifact')
fprintf('zvalue artifact detection has already been done, retaining artifacts\n');
artifact = cfg.artfctdef.zvalue.artifact;
return
end
% flag whether to compute z-value per trial or not, rationale being that if
% there are fluctuations in the variance across trials (e.g. due to
% position differences in MEG measurements) which don't have to do with the artifact per se,
% the detection is compromised (although the data quality is questionable
% when there is a lot of movement to begin with).
pertrial = strcmp(cfg.artfctdef.zvalue.method, 'trial');
if pertrial
if isfield(cfg.artfctdef.zvalue, 'ntrial') && cfg.artfctdef.zvalue.ntrial>0
pertrial = cfg.artfctdef.zvalue.ntrial;
else
error('you should specify cfg.artfctdef.zvalue.ntrial, and it should be > 0');
end
end
if nargin > 1
% data given as input
isfetch = 1;
hdr = ft_fetch_header(data);
data = ft_checkdata(data, 'datatype', 'raw', 'hassampleinfo', 'yes');
elseif nargin == 1
% only cfg given
isfetch = 0;
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
% check whether the value for trlpadding makes sense; negative trlpadding
% only allowed with in-memory data
if cfg.artfctdef.zvalue.trlpadding < 0
error('negative trlpadding is only allowed with in-memory data');
end
end
% set default cfg.continuous
if ~isfield(cfg, 'continuous')
if hdr.nTrials==1
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
end
if isfield(cfg,'trl')
trl = cfg.trl;
else
trl = data.sampleinfo;
end
trlpadding = round(cfg.artfctdef.zvalue.trlpadding*hdr.Fs);
fltpadding = round(cfg.artfctdef.zvalue.fltpadding*hdr.Fs);
artpadding = round(cfg.artfctdef.zvalue.artpadding*hdr.Fs);
trl(:,1) = trl(:,1) - trlpadding; % pad the trial with some samples, in order to detect
trl(:,2) = trl(:,2) + trlpadding; % artifacts at the edges of the relevant trials.
if size(trl, 2) >= 3
trl(:,3) = trl(:,3) - trlpadding; % the offset can ofcourse be adjusted as well
elseif isfetch
% reconstruct offset
for tr=1:size(trl, 1)
% account for 0 might not be in data.time
t0 = interp1(data.time{tr}, 1:numel(data.time{tr}), 0, 'linear', 'extrap');
trl(tr, 3) = -t0+1 - trlpadding;
end
else
% assuming that the trial starts at t=0s
trl(:, 3) = trl(:, 1);
end
trllength = trl(:,2) - trl(:,1) + 1; % length of each trial
numtrl = size(trl,1);
cfg.artfctdef.zvalue.trl = trl; % remember where we are going to look for artifacts
cfg.artfctdef.zvalue.channel = ft_channelselection(cfg.artfctdef.zvalue.channel, hdr.label);
sgnind = match_str(hdr.label, cfg.artfctdef.zvalue.channel);
numsgn = length(sgnind);
thresholdsum = strcmp(cfg.artfctdef.zvalue.cumulative, 'yes');
if numsgn<1
error('no channels selected');
else
fprintf('searching for artifacts in %d channels\n', numsgn);
end
% read the data and apply preprocessing options
sumval = zeros(numsgn, 1);
sumsqr = zeros(numsgn, 1);
numsmp = zeros(numsgn, 1);
fprintf('searching trials');
for trlop = 1:numtrl
fprintf('.');
if strcmp(cfg.memory, 'low') % store nothing in memory
if isfetch
dat = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'));
else
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'dataformat', cfg.dataformat);
end
dat = preproc(dat, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(dat,2)), cfg.artfctdef.zvalue, fltpadding, fltpadding);
if trlop==1 && ~pertrial
sumval = zeros(size(dat,1), 1);
sumsqr = zeros(size(dat,1), 1);
numsmp = zeros(size(dat,1), 1);
numsgn = size(dat,1);
elseif trlop==1 && pertrial
sumval = zeros(size(dat,1), numtrl);
sumsqr = zeros(size(dat,1), numtrl);
numsmp = zeros(size(dat,1), numtrl);
numsgn = size(dat,1);
end
if ~pertrial
% accumulate the sum and the sum-of-squares
sumval = sumval + sum(dat,2);
sumsqr = sumsqr + sum(dat.^2,2);
numsmp = numsmp + size(dat,2);
else
% store per trial the sum and the sum-of-squares
sumval(:,trlop) = sum(dat,2);
sumsqr(:,trlop) = sum(dat.^2,2);
numsmp(:,trlop) = size(dat,2);
end
else % store all data in memory, saves computation time
if isfetch
dat{trlop} = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'));
else
dat{trlop} = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'dataformat', cfg.dataformat);
end
dat{trlop} = preproc(dat{trlop}, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(dat{trlop},2)), cfg.artfctdef.zvalue, fltpadding, fltpadding);
if trlop==1 && ~pertrial
sumval = zeros(size(dat{1},1), 1);
sumsqr = zeros(size(dat{1},1), 1);
numsmp = zeros(size(dat{1},1), 1);
numsgn = size(dat{1},1);
elseif trlop==1 && pertrial
sumval = zeros(size(dat{1},1), numtrl);
sumsqr = zeros(size(dat{1},1), numtrl);
numsmp = zeros(size(dat{1},1), numtrl);
numsgn = size(dat{1},1);
end
if ~pertrial
% accumulate the sum and the sum-of-squares
sumval = sumval + sum(dat{trlop},2);
sumsqr = sumsqr + sum(dat{trlop}.^2,2);
numsmp = numsmp + size(dat{trlop},2);
else
% store per trial the sum and the sum-of-squares
sumval(:,trlop) = sum(dat{trlop},2);
sumsqr(:,trlop) = sum(dat{trlop}.^2,2);
numsmp(:,trlop) = size(dat{trlop},2);
end
end
end % for trlop
if pertrial>1
sumval = ft_preproc_smooth(sumval, pertrial)*pertrial;
sumsqr = ft_preproc_smooth(sumsqr, pertrial)*pertrial;
numsmp = ft_preproc_smooth(numsmp, pertrial)*pertrial;
end
% compute the average and the standard deviation
datavg = sumval./numsmp;
datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2);
if strcmp(cfg.memory, 'low')
fprintf('\n');
end
zmax = cell(1, numtrl);
zsum = cell(1, numtrl);
zindx = cell(1, numtrl);
% create a vector that indexes the trials, or is all 1, in order
% to a per trial z-scoring, or use a static std and mean (used in lines 317
% and 328)
if pertrial
indvec = 1:numtrl;
else
indvec = ones(1,numtrl);
end
for trlop = 1:numtrl
if strcmp(cfg.memory, 'low') % store nothing in memory (note that we need to preproc AGAIN... *yawn*
fprintf('.');
if isfetch
dat = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'));
else
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'dataformat', cfg.dataformat);
end
dat = preproc(dat, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(dat,2)), cfg.artfctdef.zvalue, fltpadding, fltpadding);
zmax{trlop} = -inf + zeros(1,size(dat,2));
zsum{trlop} = zeros(1,size(dat,2));
zindx{trlop} = zeros(1,size(dat,2));
nsmp = size(dat,2);
zdata = (dat - datavg(:,indvec(trlop)*ones(1,nsmp)))./datstd(:,indvec(trlop)*ones(1,nsmp)); % convert the filtered data to z-values
zsum{trlop} = nansum(zdata,1); % accumulate the z-values over channels
[zmax{trlop},ind] = max(zdata,[],1); % find the maximum z-value and remember it
zindx{trlop} = sgnind(ind); % also remember the channel number that has the largest z-value
else
% initialize some matrices
zmax{trlop} = -inf + zeros(1,size(dat{trlop},2));
zsum{trlop} = zeros(1,size(dat{trlop},2));
zindx{trlop} = zeros(1,size(dat{trlop},2));
nsmp = size(dat{trlop},2);
zdata = (dat{trlop} - datavg(:,indvec(trlop)*ones(1,nsmp)))./datstd(:,indvec(trlop)*ones(1,nsmp)); % convert the filtered data to z-values
zsum{trlop} = nansum(zdata,1); % accumulate the z-values over channels
[zmax{trlop},ind] = max(zdata,[],1); % find the maximum z-value and remember it
zindx{trlop} = sgnind(ind); % also remember the channel number that has the largest z-value
end
% This alternative code does the same, but it is much slower
% for i=1:size(zmax{trlop},2)
% if zdata{trlop}(i)>zmax{trlop}(i)
% % update the maximum value and channel index
% zmax{trlop}(i) = zdata{trlop}(i);
% zindx{trlop}(i) = sgnind(sgnlop);
% end
% end
end % for trlop
%for sgnlop=1:numsgn
% % read the data and apply preprocessing options
% sumval = 0;
% sumsqr = 0;
% numsmp = 0;
% fprintf('searching channel %s ', cfg.artfctdef.zvalue.channel{sgnlop});
% for trlop = 1:numtrl
% fprintf('.');
% if isfetch
% dat{trlop} = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind(sgnlop), 'checkboundary', strcmp(cfg.continuous,'no'));
% else
% dat{trlop} = read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind(sgnlop), 'checkboundary', strcmp(cfg.continuous,'no'));
% end
% dat{trlop} = preproc(dat{trlop}, cfg.artfctdef.zvalue.channel(sgnlop), hdr.Fs, cfg.artfctdef.zvalue, [], fltpadding, fltpadding);
% % accumulate the sum and the sum-of-squares
% sumval = sumval + sum(dat{trlop},2);
% sumsqr = sumsqr + sum(dat{trlop}.^2,2);
% numsmp = numsmp + size(dat{trlop},2);
% end % for trlop
%
% % compute the average and the standard deviation
% datavg = sumval./numsmp;
% datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2);
%
% for trlop = 1:numtrl
% if sgnlop==1
% % initialize some matrices
% zdata{trlop} = zeros(size(dat{trlop}));
% zmax{trlop} = -inf + zeros(size(dat{trlop}));
% zsum{trlop} = zeros(size(dat{trlop}));
% zindx{trlop} = zeros(size(dat{trlop}));
% end
% zdata{trlop} = (dat{trlop} - datavg)./datstd; % convert the filtered data to z-values
% zsum{trlop} = zsum{trlop} + zdata{trlop}; % accumulate the z-values over channels
% zmax{trlop} = max(zmax{trlop}, zdata{trlop}); % find the maximum z-value and remember it
% zindx{trlop}(zmax{trlop}==zdata{trlop}) = sgnind(sgnlop); % also remember the channel number that has the largest z-value
%
% % This alternative code does the same, but it is much slower
% % for i=1:size(zmax{trlop},2)
% % if zdata{trlop}(i)>zmax{trlop}(i)
% % % update the maximum value and channel index
% % zmax{trlop}(i) = zdata{trlop}(i);
% % zindx{trlop}(i) = sgnind(sgnlop);
% % end
% % end
% end
% fprintf('\n');
%end % for sgnlop
for trlop = 1:numtrl
zsum{trlop} = zsum{trlop} ./ sqrt(numsgn);
end
% always create figure
h = figure;
set(h, 'visible', 'off');
opt.artcfg = cfg.artfctdef.zvalue;
opt.artval = {};
opt.artpadding = artpadding;
opt.cfg = cfg;
opt.channel = 'artifact';
opt.hdr = hdr;
opt.numtrl = size(trl,1);
opt.quit = 0;
opt.threshold = cfg.artfctdef.zvalue.cutoff;
opt.thresholdsum = thresholdsum;
opt.trialok = true(1,opt.numtrl); % OK by means of objective criterion
opt.keep = zeros(1,opt.numtrl); % OK overruled by user +1 to keep, -1 to reject, start all zeros for callback to work
opt.trl = trl;
opt.trlop = 1;
opt.updatethreshold = true;
opt.zmax = zmax;
opt.zsum = zsum;
if ~thresholdsum
opt.zval = zmax;
else
opt.zval = zsum;
end
opt.zindx = zindx;
if nargin==1
opt.data = {};
else
opt.data = data;
end
if strcmp(cfg.artfctdef.zvalue.interactive, 'yes')
set(h, 'visible', 'on');
set(h, 'CloseRequestFcn', @cleanup_cb);
% give graphical feedback and allow the user to modify the threshold
set(h, 'position', [100 200 900 400]);
h1 = axes('position', [0.05 0.15 0.4 0.8]);
h2 = axes('position', [0.5 0.57 0.45 0.38]);
h3 = axes('position', [0.5 0.15 0.45 0.32]);
opt.h1 = h1;
opt.h2 = h2;
opt.h3 = h3;
setappdata(h, 'opt', opt);
artval_cb(h);
redraw_cb(h);
% make the user interface elements for the data view
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'stop', 'userdata', 'q')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'downarrow')
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'threshold', 'userdata', 'z')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'uparrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'shift+downarrow')
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'artifact','userdata', 'a')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'shift+uparrow')
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'keep trial', 'userdata', 'k')
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'reject part', 'userdata', 'r')
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'reject full', 'userdata', 'R')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<<', 'userdata', 'shift+leftarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow')
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'trial', 'userdata', 't')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>>', 'userdata', 'shift+rightarrow')
%uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'ctrl+uparrow')
%uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel','userdata', 'c')
%uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'ctrl+downarrow')
ft_uilayout(h, 'tag', 'group1', 'width', 0.10, 'height', 0.05);
ft_uilayout(h, 'tag', 'group2', 'width', 0.05, 'height', 0.05);
ft_uilayout(h, 'tag', 'group3', 'width', 0.12, 'height', 0.05);
ft_uilayout(h, 'tag', 'group1', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group2', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group3', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group1', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'group2', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'group3', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0.005);
while opt.quit==0
uiwait(h);
opt = getappdata(h, 'opt');
end
else
% compute the artifacts given the settings in the cfg
setappdata(h, 'opt', opt);
artval_cb(h);
end
h = getparent(h);
opt = getappdata(h, 'opt');
% convert to one long vector
dum = zeros(1,max(opt.trl(:,2)));
for trlop=1:opt.numtrl
dum(opt.trl(trlop,1):opt.trl(trlop,2)) = opt.artval{trlop};
end
artval = dum;
% find the padded artifacts and put them in a Nx2 trl-like matrix
artbeg = find(diff([0 artval])== 1);
artend = find(diff([artval 0])==-1);
artifact = [artbeg(:) artend(:)];
if strcmp(cfg.artfctdef.zvalue.artfctpeak,'yes')
cnt=1;
shift=opt.trl(1,1)-1;
for tt=1:opt.numtrl
if tt==1
tind{tt}=find(artifact(:,2)<opt.trl(tt,2));
else
tind{tt}=intersect(find(artifact(:,2)<opt.trl(tt,2)),find(artifact(:,2)>opt.trl(tt-1,2)));
end
artbegend=[(artifact(tind{tt},1)-opt.trl(tt,1)+1) (artifact(tind{tt},2)-opt.trl(tt,1)+1)];
for rr=1:size(artbegend,1)
[mx,mxnd]=max(opt.zval{tt}(artbegend(rr,1):artbegend(rr,2)));
peaks(cnt)=artifact(tind{tt}(rr),1)+mxnd-1;
dssartifact(cnt,1)=max(peaks(cnt)+cfg.artfctdef.zvalue.artfctpeakrange(1)*hdr.Fs,opt.trl(tt,1));
dssartifact(cnt,2)=min(peaks(cnt)+cfg.artfctdef.zvalue.artfctpeakrange(2)*hdr.Fs,opt.trl(tt,2));
peaks(cnt)=peaks(cnt)-shift;
dssartifact(cnt,:)=dssartifact(cnt,:)-shift;
cnt=cnt+1;
end
if tt<opt.numtrl
shift=shift+opt.trl(tt+1,1)-opt.trl(tt,2)-1;
end
clear artbegend
end
cfg.artfctdef.zvalue.peaks=peaks';
cfg.artfctdef.zvalue.dssartifact=dssartifact;
end
% remember the artifacts that were found
cfg.artfctdef.zvalue.artifact = artifact;
% also update the threshold
cfg.artfctdef.zvalue.cutoff = opt.threshold;
fprintf('detected %d artifacts\n', size(artifact,1));
delete(h);
% do the general cleanup and bookkeeping at the end of the function
ft_postamble provenance
ft_postamble previous data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function artval_cb(h, eventdata)
opt = getappdata(h, 'opt');
artval = cell(1,opt.numtrl);
for trlop=1:opt.numtrl
if opt.thresholdsum,
% threshold the accumulated z-values
artval{trlop} = opt.zsum{trlop}>opt.threshold;
else
% threshold the max z-values
artval{trlop} = opt.zmax{trlop}>opt.threshold;
end
% pad the artifacts
artbeg = find(diff([0 artval{trlop}])== 1);
artend = find(diff([artval{trlop} 0])==-1);
artbeg = artbeg - opt.artpadding;
artend = artend + opt.artpadding;
artbeg(artbeg<1) = 1;
artend(artend>length(artval{trlop})) = length(artval{trlop});
for artlop=1:length(artbeg)
artval{trlop}(artbeg(artlop):artend(artlop)) = 1;
end
opt.trialok(trlop) = isempty(artbeg);
end
for trlop = find(opt.keep==1 & opt.trialok==0)
% overrule the objective criterion, i.e. keep the trial when the user
% wants to keep it
artval{trlop}(:) = 0;
end
for trlop = find(opt.keep<0 & opt.trialok==1)
% if the user specifies that the trial is not OK
% reject the whole trial if there is no extra-threshold data,
% otherwise use the artifact as found by the thresholding
if opt.thresholdsum && opt.keep(trlop)==-1,
% threshold the accumulated z-values
artval{trlop} = opt.zsum{trlop}>opt.threshold;
elseif opt.keep(trlop)==-1
% threshold the max z-values
artval{trlop} = opt.zmax{trlop}>opt.threshold;
elseif opt.keep(trlop)==-2
artval{trlop}(:) = 1;
end
% pad the artifacts
artbeg = find(diff([0 artval{trlop}])== 1);
artend = find(diff([artval{trlop} 0])==-1);
artbeg = artbeg - opt.artpadding;
artend = artend + opt.artpadding;
artbeg(artbeg<1) = 1;
artend(artend>length(artval{trlop})) = length(artval{trlop});
if ~isempty(artbeg)
for artlop=1:length(artbeg)
artval{trlop}(artbeg(artlop):artend(artlop)) = 1;
end
else
artval{trlop}(:) = 1;
end
end
for trlop = find(opt.keep==-2 & opt.trialok==0)
% if the user specifies the whole trial to be rejected define the whole
% segment to be bad
artval{trlop}(:) = 1;
% pad the artifacts
artbeg = find(diff([0 artval{trlop}])== 1);
artend = find(diff([artval{trlop} 0])==-1);
artbeg = artbeg - opt.artpadding;
artend = artend + opt.artpadding;
artbeg(artbeg<1) = 1;
artend(artend>length(artval{trlop})) = length(artval{trlop});
if ~isempty(artbeg)
for artlop=1:length(artbeg)
artval{trlop}(artbeg(artlop):artend(artlop)) = 1;
end
else
artval{trlop}(:) = 1;
end
end
opt.artval = artval;
setappdata(h, 'opt', opt);
uiresume;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function keyboard_cb(h, eventdata)
if isempty(eventdata)
% determine the key that corresponds to the uicontrol element that was activated
key = get(h, 'userdata');
else
% determine the key that was pressed on the keyboard
key = parseKeyboardEvent(eventdata);
end
% get focus back to figure
if ~strcmp(get(h, 'type'), 'figure')
set(h, 'enable', 'off');
drawnow;
set(h, 'enable', 'on');
end
h = getparent(h);
opt = getappdata(h, 'opt');
switch key
case 'leftarrow' % change trials
opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'shift+leftarrow'
opt.trlop = max(opt.trlop - 10, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'rightarrow'
opt.trlop = min(opt.trlop + 1, opt.numtrl); % should not be larger than the number of trials
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'shift+rightarrow'
opt.trlop = min(opt.trlop + 10, opt.numtrl); % should not be larger than the number of trials
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'uparrow' % change threshold
opt.threshold = opt.threshold+0.5;
opt.updatethreshold = true;
setappdata(h, 'opt', opt);
artval_cb(h, eventdata);
redraw_cb(h, eventdata);
opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks
opt.updatethreshold = false;
setappdata(h, 'opt', opt);
case 'downarrow'
opt.threshold = opt.threshold-0.5;
opt.updatethreshold = true;
setappdata(h, 'opt', opt);
artval_cb(h, eventdata);
redraw_cb(h, eventdata);
opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks
opt.updatethreshold = false;
setappdata(h, 'opt', opt);
case 'shift+uparrow' % change artifact
artfctindx = find(opt.trialok == 0);
sel = find(artfctindx>opt.trlop);
if ~isempty(sel)
opt.trlop = artfctindx(sel(1));
end
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'shift+downarrow'
artfctindx = find(opt.trialok == 0);
sel = find(artfctindx<opt.trlop);
if ~isempty(sel)
opt.trlop = artfctindx(sel(end));
end
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'ctrl+uparrow' % change channel
if strcmp(opt.channel, 'artifact')
[dum, indx] = max(opt.zval);
sgnind = opt.zindx(indx);
else
if ~isempty(opt.data)
sgnind = match_str(opt.channel, opt.data.label);
selchan = match_str(opt.artcfg.channel, opt.channel);
else
sgnind = match_str(opt.channel, opt.hdr.label);
selchan = match_str(opt.artcfg.channel, opt.channel);
end
end
numchan = numel(opt.artcfg.channel);
chansel = min(selchan+1, numchan);
% convert numeric array into cell-array with channel labels
opt.channel = tmpchan(chansel);
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'ctrl+downarrow'
tmpchan = [opt.artcfg.channel;{'artifact'}]; % append the 'artifact' channel
chansel = match_str(tmpchan, opt.channel);
chansel = max(chansel-1, 1);
% convert numeric array into cell-array with channel labels
opt.channel = tmpchan(chansel);
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
case 'a'
% select the artifact to display
response = inputdlg(sprintf('artifact trial to display'), 'specify', 1, {num2str(opt.trlop)});
if ~isempty(response)
artfctindx = find(opt.trialok == 0);
sel = str2double(response);
sel = min(numel(artfctindx), sel);
sel = max(1, sel);
opt.trlop = artfctindx(sel);
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
end
case 'c'
% select channels
% select = match_str([opt.artcfg.channel;{'artifact'}], opt.channel);
% opt.channel = select_channel_list([opt.artcfg.channel;{'artifact'}], select);
% setappdata(h, 'opt', opt);
% redraw_cb(h, eventdata);
case 'q'
setappdata(h, 'opt', opt);
cleanup_cb(h);
case 't'
% select the trial to display
response = inputdlg(sprintf('trial to display'), 'specify', 1, {num2str(opt.trlop)});
if ~isempty(response)
opt.trlop = str2double(response);
opt.trlop = min(opt.trlop, opt.numtrl); % should not be larger than the number of trials
opt.trlop = max(opt.trlop, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
redraw_cb(h, eventdata);
end
case 'z'
% select the threshold
response = inputdlg('z-threshold', 'specify', 1, {num2str(opt.threshold)});
if ~isempty(response)
opt.threshold = str2double(response);
opt.updatethreshold = true;
setappdata(h, 'opt', opt);
artval_cb(h, eventdata);
redraw_cb(h, eventdata);
opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks
opt.updatethreshold = false;
setappdata(h, 'opt', opt);
end
case 'k'
opt.keep(opt.trlop) = 1;
setappdata(h, 'opt', opt);
artval_cb(h);
redraw_cb(h);
opt = getappdata(h, 'opt');
case 'r'
% only of the trial contains a partial artifact
if opt.trialok(opt.trlop) == 0
opt.keep(opt.trlop) = -1;
end
setappdata(h, 'opt', opt);
artval_cb(h);
redraw_cb(h);
opt = getappdata(h, 'opt');
case 'R'
opt.keep(opt.trlop) = -2;
setappdata(h, 'opt', opt);
artval_cb(h);
redraw_cb(h);
opt = getappdata(h, 'opt');
case 'control+control'
% do nothing
case 'shift+shift'
% do nothing
case 'alt+alt'
% do nothing
otherwise
setappdata(h, 'opt', opt);
help_cb(h);
end
uiresume(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function redraw_cb(h, eventdata)
h = getparent(h);
opt = getappdata(h, 'opt');
% make a local copy of the relevant variables
trlop = opt.trlop;
artval = opt.artval{trlop};
zindx = opt.zindx{trlop};
zval = opt.zval{trlop};
cfg = opt.cfg;
artcfg = opt.artcfg;
hdr = opt.hdr;
trl = opt.trl;
trlpadsmp = round(artcfg.trlpadding*hdr.Fs);
channel = opt.channel;
% determine the channel with the highest z-value to be displayed
% this is default behaviour but can be overruled in the gui
if strcmp(channel, 'artifact')
[dum, indx] = max(zval);
sgnind = zindx(indx);
else
if ~isempty(opt.data)
sgnind = match_str(channel, opt.data.label);
else
sgnind = match_str(channel, hdr.label);
end
end
if ~isempty(opt.data)
data = ft_fetch_data(opt.data, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'));
else
data = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'));
end
%data = preproc(data, '', hdr.Fs, artcfg, [], artcfg.fltpadding, artcfg.fltpadding);
str = sprintf('trial %3d, channel %s', opt.trlop, hdr.label{sgnind});
fprintf('showing %s\n', str);
%-----------------------------
% plot summary in left subplot
subplot(opt.h1);hold on;
% plot as a blue line only once
if isempty(get(opt.h1, 'children'))
for k = 1:opt.numtrl
xval = opt.trl(k,1):opt.trl(k,2);
if opt.thresholdsum,
yval = opt.zsum{k};
else
yval = opt.zmax{k};
end
plot(opt.h1, xval, yval, 'linestyle', '-', 'color', 'b', 'displayname', 'data');
xlabel('samples');
ylabel('z-value');
end
end
h1children = get(opt.h1, 'children');
% plot trial box
boxhandle = findall(h1children, 'displayname', 'highlight');
if isempty(boxhandle)
% draw it
xval = trl(opt.trlop,1):trl(opt.trlop,2);
if opt.thresholdsum,
yval = opt.zsum{opt.trlop};
else
yval = opt.zmax{opt.trlop};
end
plot(opt.h1, xval, yval, 'linestyle', '-', 'color', 'm', 'linewidth', 2, 'displayname', 'highlight');
else
% update it
xval = trl(opt.trlop,1):trl(opt.trlop,2);
if opt.thresholdsum,
yval = opt.zsum{opt.trlop};
else
yval = opt.zmax{opt.trlop};
end
set(boxhandle, 'XData', xval);
set(boxhandle, 'YData', yval);
end
% plot as red lines the suprathreshold data points
thrhandle = findall(h1children, 'displayname', 'reddata');
if isempty(thrhandle)
% they have to be drawn
for k = 1:opt.numtrl
xval = trl(k,1):trl(k,2);
if opt.thresholdsum,
yval = opt.zsum{k};
else
yval = opt.zmax{k};
end
dum = yval<=opt.threshold;
yval(dum) = nan;
plot(opt.h1, xval, yval, 'linestyle', '-', 'color', [1 0 0], 'displayname', 'reddata');
end
hline(opt.threshold, 'color', 'r', 'linestyle', ':', 'displayname', 'threshline');
elseif ~isempty(thrhandle) && opt.updatethreshold
% they can be updated
for k = 1:opt.numtrl
xval = trl(k,1):trl(k,2);
if opt.thresholdsum,
yval = opt.zsum{k};
else
yval = opt.zmax{k};
end
dum = yval<=opt.threshold;
yval(dum) = nan;
set(thrhandle(k), 'XData', xval);
set(thrhandle(k), 'YData', yval);
end
set(findall(h1children, 'displayname', 'threshline'), 'YData', [1 1].*opt.threshold);
end
%--------------------------------------------------
% get trial specific x-axis values and padding info
xval = ((trl(opt.trlop,1):trl(opt.trlop,2))-trl(opt.trlop,1)+trl(opt.trlop,3))./opt.hdr.Fs;
if trlpadsmp>0
sel = trlpadsmp:(size(data,2)-trlpadsmp);
selpad = 1:size(data,2);
else
sel = 1:size(data,2);
selpad = sel;
end
% plot data of most aberrant channel in upper subplot
subplot(opt.h2); hold on
if isempty(get(opt.h2, 'children'))
% do the plotting
plot(xval(selpad), data(selpad), 'color', [0.5 0.5 1], 'displayname', 'line1');
plot(xval(sel), data(sel), 'color', [0 0 1], 'displayname', 'line2');
vline(xval( 1)+(trlpadsmp-1/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline1');
vline(xval(end)-(trlpadsmp/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline2');
data(~artval) = nan;
plot(xval, data, 'r-', 'displayname', 'line3');
xlabel('time(s)');
ylabel('uV or Tesla');
xlim([xval(1) xval(end)]);
title(str);
else
% update in the existing handles
h2children = get(opt.h2, 'children');
set(findall(h2children, 'displayname', 'vline1'), 'visible', 'off');
set(findall(h2children, 'displayname', 'vline2'), 'visible', 'off');
set(findall(h2children, 'displayname', 'line1'), 'XData', xval(selpad));
set(findall(h2children, 'displayname', 'line1'), 'YData', data(selpad));
set(findall(h2children, 'displayname', 'line2'), 'XData', xval(sel));
set(findall(h2children, 'displayname', 'line2'), 'YData', data(sel));
data(~artval) = nan;
set(findall(h2children, 'displayname', 'line3'), 'XData', xval);
set(findall(h2children, 'displayname', 'line3'), 'YData', data);
abc2 = axis(opt.h2);
set(findall(h2children, 'displayname', 'vline1'), 'XData', [1 1]*xval( 1)+(trlpadsmp-1/opt.hdr.Fs));
set(findall(h2children, 'displayname', 'vline1'), 'YData', abc2(3:4));
set(findall(h2children, 'displayname', 'vline2'), 'XData', [1 1]*xval(end)-(trlpadsmp/opt.hdr.Fs));
set(findall(h2children, 'displayname', 'vline2'), 'YData', abc2(3:4));
set(findall(h2children, 'displayname', 'vline1'), 'visible', 'on');
set(findall(h2children, 'displayname', 'vline2'), 'visible', 'on');
str = sprintf('trial %3d, channel %s', opt.trlop, hdr.label{sgnind});
title(str);
xlim([xval(1) xval(end)]);
end
% plot z-values in lower subplot
subplot(opt.h3); hold on;
if isempty(get(opt.h3, 'children'))
% do the plotting
plot(xval(selpad), zval(selpad), 'color', [0.5 0.5 1], 'displayname', 'line1b');
plot(xval(sel), zval(sel), 'color', [0 0 1], 'displayname', 'line2b');
hline(opt.threshold, 'color', 'r', 'linestyle', ':', 'displayname', 'threshline');
vline(xval( 1)+(trlpadsmp-1/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline1b');
vline(xval(end)-(trlpadsmp/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline2b');
zval(~artval) = nan;
plot(xval, zval, 'r-', 'displayname', 'line3b');
xlabel('time(s)');
ylabel('z-value');
xlim([xval(1) xval(end)]);
else
% update in the existing handles
h3children = get(opt.h3, 'children');
set(findall(h3children, 'displayname', 'vline1b'), 'visible', 'off');
set(findall(h3children, 'displayname', 'vline2b'), 'visible', 'off');
set(findall(h3children, 'displayname', 'line1b'), 'XData', xval(selpad));
set(findall(h3children, 'displayname', 'line1b'), 'YData', zval(selpad));
set(findall(h3children, 'displayname', 'line2b'), 'XData', xval(sel));
set(findall(h3children, 'displayname', 'line2b'), 'YData', zval(sel));
zval(~artval) = nan;
set(findall(h3children, 'displayname', 'line3b'), 'XData', xval);
set(findall(h3children, 'displayname', 'line3b'), 'YData', zval);
set(findall(h3children, 'displayname', 'threshline'), 'YData', [1 1].*opt.threshold);
set(findall(h3children, 'displayname', 'threshline'), 'XData', xval([1 end]));
abc = axis(opt.h3);
set(findall(h3children, 'displayname', 'vline1b'), 'XData', [1 1]*xval( 1)+(trlpadsmp-1/opt.hdr.Fs));
set(findall(h3children, 'displayname', 'vline1b'), 'YData', abc(3:4));
set(findall(h3children, 'displayname', 'vline2b'), 'XData', [1 1]*xval(end)-(trlpadsmp/opt.hdr.Fs));
set(findall(h3children, 'displayname', 'vline2b'), 'YData', abc(3:4));
set(findall(h3children, 'displayname', 'vline1b'), 'visible', 'on');
set(findall(h3children, 'displayname', 'vline2b'), 'visible', 'on');
xlim([xval(1) xval(end)]);
end
setappdata(h, 'opt', opt);
uiresume
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanup_cb(h, eventdata)
opt = getappdata(h, 'opt');
opt.quit = true;
setappdata(h, 'opt', opt);
uiresume
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = getparent(h)
p = h;
while p~=0
h = p;
p = get(h, 'parent');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key = parseKeyboardEvent(eventdata)
key = eventdata.Key;
% handle possible numpad events (different for Windows and UNIX systems)
% NOTE: shift+numpad number does not work on UNIX, since the shift
% modifier is always sent for numpad events
if isunix()
shiftInd = match_str(eventdata.Modifier, 'shift');
if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd)
% now we now it was a numpad keystroke (numeric character sent AND
% shift modifier present)
key = eventdata.Character;
eventdata.Modifier(shiftInd) = []; % strip the shift modifier
end
elseif ispc()
if strfind(eventdata.Key, 'numpad')
key = eventdata.Character;
end
end
if ~isempty(eventdata.Modifier)
key = [eventdata.Modifier{1} '+' key];
end
|
github
|
philippboehmsturm/antx-master
|
besa2fieldtrip.m
|
.m
|
antx-master/xspm8/external/fieldtrip/besa2fieldtrip.m
| 16,161 |
utf_8
|
16dbde9bd7a8b61a3207953ffb97ae31
|
function [data] = besa2fieldtrip(input)
% BESA2FIELDTRIP reads and converts various BESA datafiles into a FieldTrip
% data structure, which subsequently can be used for statistical analysis
% or other analysis methods implemented in Fieldtrip.
%
% Use as
% [data] = besa2fieldtrip(filename)
% where the filename should point to a BESA datafile (or data that
% is exported by BESA). The output is a Matlab structure that is
% compatible with FieldTrip.
%
% The format of the output structure depends on the type of datafile:
% *.avr is converted to a structure similar to the output of TIMELOCKANALYSIS
% *.mul is converted to a structure similar to the output of TIMELOCKANALYSIS
% *.swf is converted to a structure similar to the output of TIMELOCKANALYSIS (*)
% *.tfc is converted to a structure similar to the output of FREQANALYSIS (*)
% *.dat is converted to a structure similar to the output of SOURCANALYSIS
% *.dat combined with a *.gen or *.generic is converted to a structure similar to the output of PREPROCESSING
%
% Note (*): If the BESA toolbox by Karsten Hochstatter is found on your
% Matlab path, the readBESAxxx functions will be used (where xxx=tfc/swf),
% alternatively the private functions from FieldTrip will be used.
%
% See also EEGLAB2FIELDTRIP
% Copyright (C) 2005-2010, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: besa2fieldtrip.m 7123 2012-12-06 21:21:38Z roboos $
revision = '$Id: besa2fieldtrip.m 7123 2012-12-06 21:21:38Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble callinfo
if isstruct(input) && numel(input)>1
% use a recursive call to convert multiple inputs
data = cell(size(input));
for i=1:numel(input)
data{i} = besa2fieldtrip(input(i));
end
return
end
if isstruct(input)
fprintf('besa2fieldtrip: converting structure\n');
%---------------------TFC-------------------------------------------------%
if strcmp(input.structtype, 'besa_tfc')
%fprintf('BESA tfc\n');
data.time = input.latencies;
data.freq = input.frequencies;
temp_chans = char(input.channellabels');
Nchan = size(temp_chans,1);
%{
if strcmp(input.type,'COHERENCE_SQUARED')
% it contains coherence between channel pairs
fprintf('reading coherence between %d channel pairs\n', Nchan);
for i=1:Nchan
tmp = tokenize(deblank(temp_chans(i,:)), '-');
data.labelcmb{i,1} = deblank(tmp{1});
data.labelcmb{i,2} = deblank(tmp{2});
data.label{i,1} = deblank(temp_chans(i,:));
end
data.cohspctrm = input.data;
else
%}
% it contains power on channels
fprintf('reading power on %d channels\n', Nchan);
for i=1:Nchan
data.label{i,1} = deblank(temp_chans(i,:));
end
data.powspctrm = input.data;
data.dimord = 'chan_freq_time';
data.condition = input.condition; %not original Fieldtrip fieldname
%end
clear temp;
%--------------------Image------------------------------------------------%
elseif strcmp(input.structtype, 'besa_image')
%fprintf('BESA image\n');
data.avg.pow = input.data;
xTemp = input.xcoordinates;
yTemp = input.ycoordinates;
zTemp = input.zcoordinates;
data.xgrid = xTemp;
data.ygrid = yTemp;
data.zgrid = zTemp;
nx = size(data.xgrid,2);
ny = size(data.ygrid,2);
nz = size(data.zgrid,2);
% Number of points in each dimension
data.dim = [nx ny nz];
% Array with all possible positions (x,y,z)
data.pos = WritePosArray(xTemp,yTemp,zTemp,nx,ny,nz);
data.inside = 1:prod(data.dim);%as in Fieldtrip - not correct
data.outside = [];
%--------------------Source Waveform--------------------------------------%
elseif strcmp(input.structtype, 'besa_sourcewaveforms')
%fprintf('BESA source waveforms\n');
data.label = input.labels'; %not the same as Fieldtrip!
data.dimord = 'chan_time';
data.fsample = input.samplingrate;
data.time = input.latencies / 1000.0;
data.avg = input.waveforms';
data.cfg.filename = input.datafile;
%--------------------Data Export------------------------------------------%
elseif strcmp(input.structtype, 'besa_channels')
%fprintf('BESA data export\n');
if isfield(input,'datatype')
switch input.ft_datatype
case {'Raw_Data','Epoched_Data','Segment'}
data.fsample = input.samplingrate;
data.label = input.channellabels';
for k=1:size(input.data,2)
data.time{1,k} = input.data(k).latencies / 1000.0';
data.trial{1,k} = input.data(k).amplitudes';
end
otherwise
fprintf('ft_datatype other than Raw_Data, Epoched or Segment');
end
else
fprintf('workspace created with earlier MATLAB version');
end
%--------------------else-------------------------------------------------%
else
error('unrecognized format of the input structure');
end
elseif ischar(input)
fprintf('besa2fieldtrip: reading from file\n');
% This function can either use the reading functions included in FieldTrip
% (with contributions from Karsten, Vladimir and Robert), or the official
% released functions by Karsten Hoechstetter from BESA. The functions in the
% official toolbox have precedence.
hasbesa = ft_hastoolbox('besa',1, 1);
type = ft_filetype(input);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(type, 'besa_avr') && hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = readBESAavr(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = [];
if isfield(tmp, 'ChannelLabels'),
data.label = fixlabels(tmp.ChannelLabels);
end;
data.avg = tmp.Data;
data.time = tmp.Time / 1000; % convert to seconds
data.fsample = 1000/tmp.DI;
data.dimord = 'chan_time';
elseif strcmp(type, 'besa_avr') && ~hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = read_besa_avr(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = fixlabels(tmp.label);
data.avg = tmp.data;
data.time = (0:(tmp.npnt-1)) * tmp.di + tmp.tsb;
data.time = data.time / 1000; % convert to seconds
data.fsample = 1000/tmp.di;
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_mul') && hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = readBESAmul(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = tmp.ChannelLabels(:);
data.avg = tmp.data';
data.time = (0:(tmp.Npts-1)) * tmp.DI + tmp.TSB;
data.time = data.time / 1000; %convert to seconds
data.fsample = 1000/tmp.DI;
data.dimord = 'chan_time';
elseif strcmp(type, 'besa_mul') && ~hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = read_besa_mul(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = tmp.label(:);
data.avg = tmp.data;
data.time = (0:(tmp.TimePoints-1)) * tmp.SamplingInterval_ms_ + tmp.BeginSweep_ms_;
data.time = data.time / 1000; % convert to seconds
data.fsample = 1000/tmp.SamplingInterval_ms_;
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_sb')
if hasbesa
fprintf('reading preprocessed channel data using BESA toolbox\n');
else
error('this data format requires the BESA toolbox');
end
[p, f, x] = fileparts(input);
input = fullfile(p, [f '.dat']);
[time,buf,ntrial] = readBESAsb(input);
time = time/1000; % convert from ms to sec
nchan = size(buf,1);
ntime = size(buf,3);
% convert into a PREPROCESSING compatible data structure
data = [];
data.trial = {};
data.time = {};
for i=1:ntrial
data.trial{i} = reshape(buf(:,i,:), [nchan, ntime]);
data.time{i} = time;
end
data.label = {};
for i=1:size(buf,1)
data.label{i,1} = sprintf('chan%03d', i);
end
data.fsample = 1./mean(diff(time)); % time is already in seconds
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_tfc') && hasbesa
fprintf('reading time-frequency representation using BESA toolbox\n');
% this should be similar to the output of FREQANALYSIS
tfc = readBESAtfc(input);
Nchan = size(tfc.ChannelLabels,1);
% convert into a FREQANALYSIS compatible data structure
data = [];
data.time = tfc.Time(:)';
data.freq = tfc.Frequency(:)';
if isfield(tfc, 'DataType') && strcmp(tfc.DataType, 'COHERENCE_SQUARED')
% it contains coherence between channel pairs
fprintf('reading coherence between %d channel pairs\n', Nchan);
for i=1:Nchan
tmp = tokenize(deblank(tfc.ChannelLabels(i,:)), '-');
data.labelcmb{i,1} = tmp{1};
data.labelcmb{i,2} = tmp{2};
end
data.cohspctrm = permute(tfc.Data, [1 3 2]);
else
% it contains power on channels
fprintf('reading power on %d channels\n', Nchan);
for i=1:Nchan
data.label{i,1} = deblank(tfc.ChannelLabels(i,:));
end
data.powspctrm = permute(tfc.Data, [1 3 2]);
end
data.dimord = 'chan_freq_time';
data.condition = tfc.ConditionName;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_tfc') && ~hasbesa
fprintf('reading time-frequency representation\n');
% this should be similar to the output of FREQANALYSIS
[ChannelLabels, Time, Frequency, Data, Info] = read_besa_tfc(input);
Nchan = size(ChannelLabels,1);
% convert into a FREQANALYSIS compatible data structure
data = [];
data.time = Time * 1e-3; % convert to seconds;
data.freq = Frequency;
if isfield(Info, 'DataType') && strcmp(Info.DataType, 'COHERENCE_SQUARED')
% it contains coherence between channel pairs
fprintf('reading coherence between %d channel pairs\n', Nchan);
for i=1:Nchan
tmp = tokenize(deblank(ChannelLabels(i,:)), '-');
data.labelcmb{i,1} = tmp{1};
data.labelcmb{i,2} = tmp{2};
end
data.cohspctrm = permute(Data, [1 3 2]);
else
% it contains power on channels
fprintf('reading power on %d channels\n', Nchan);
for i=1:Nchan
data.label{i} = deblank(ChannelLabels(i,:));
end
data.powspctrm = permute(Data, [1 3 2]);
end
data.dimord = 'chan_freq_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_swf') && hasbesa
fprintf('reading source waveform using BESA toolbox\n');
swf = readBESAswf(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = fixlabels(swf.waveName);
data.avg = swf.data;
data.time = swf.Time * 1e-3; % convert to seconds
data.fsample = 1/mean(diff(data.time));
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_swf') && ~hasbesa
fprintf('reading source waveform\n');
% hmm, I guess that this should be similar to the output of TIMELOCKANALYSIS
tmp = read_besa_swf(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = fixlabels(tmp.label);
data.avg = tmp.data;
data.time = (0:(tmp.npnt-1)) * tmp.di + tmp.tsb;
data.time = data.time / 1000; % convert to seconds
data.fsample = 1000/tmp.di;
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_src') && hasbesa
src = readBESAimage(input);
data.xgrid = src.Coordinates.X;
data.ygrid = src.Coordinates.Y;
data.zgrid = src.Coordinates.Z;
data.avg.pow = src.Data;
data.dim = size(src.Data);
[X, Y, Z] = ndgrid(data.xgrid, data.ygrid, data.zgrid);
data.pos = [X(:) Y(:) Z(:)];
% cannot determine which voxels are inside the brain volume
data.inside = 1:prod(data.dim);
data.outside = [];
elseif strcmp(type, 'besa_src') && ~hasbesa
src = read_besa_src(input);
data.xgrid = linspace(src.X(1), src.X(2), src.X(3));
data.ygrid = linspace(src.Y(1), src.Y(2), src.Y(3));
data.zgrid = linspace(src.Z(1), src.Z(2), src.Z(3));
data.avg.pow = src.vol;
data.dim = size(src.vol);
[X, Y, Z] = ndgrid(data.xgrid, data.ygrid, data.zgrid);
data.pos = [X(:) Y(:) Z(:)];
% cannot determine which voxels are inside the brain volume
data.inside = 1:prod(data.dim);
data.outside = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_pdg')
% hmmm, I have to think about this one...
error('sorry, pdg is not yet supported');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else
error('unrecognized file format for importing BESA data');
end
end % isstruct || ischar
% construct and add a configuration to the output
cfg = [];
if isstruct(input) && isfield(input,'datafile')
cfg.filename = input.datafile;
elseif isstruct(input) && ~isfield(input,'datafile')
cfg.filename = 'Unknown';
elseif ischar(input)
cfg.filename = input;
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble callinfo
ft_postamble history data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that fixes the channel labels, should be a cell-array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [newlabels] = fixlabels(labels)
if iscell(labels) && length(labels)>1
% seems to be ok
newlabels = labels;
elseif iscell(labels) && length(labels)==1
% could be a cell with a single long string in it
if length(tokenize(labels{1}, ' '))>1
% seems like a long string that accidentaly ended up in a single
cell
newlabels = tokenize(labels{1}, ' ');
else
% seems to be ok
newlabels = labels;
end
elseif ischar(labels) && any(size(labels)==1)
newlabels = tokenize(labels(:)', ' '); % also ensure that it is a row-string
elseif ischar(labels) && ~any(size(labels)==1)
for i=1:size(labels)
newlabels{i} = strtrim(labels(i,:));
end
end
% convert to column
newlabels = newlabels(:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [PArray] = WritePosArray(x,y,z,mx,my,mz)
A1 = repmat(x,1,my*mz);
A21 = repmat(y,mx,mz);
A2 = reshape(A21,1,mx*my*mz);
A31 = repmat(z,mx*my,1);
A3 = reshape(A31,1,mx*my*mz);
PArray = [A1;A2;A3]';
|
github
|
philippboehmsturm/antx-master
|
ft_topoplotCC.m
|
.m
|
antx-master/xspm8/external/fieldtrip/ft_topoplotCC.m
| 10,121 |
utf_8
|
e97031b4c8c292d5ba9f6f0a48e87f29
|
function [cfg] = ft_topoplotCC(cfg, freq)
% FT_TOPOPLOTCC plots the coherence between channel pairs
%
% Use as
% ft_topoplotCC(cfg, freq)
%
% The configuration should contain:
% cfg.feedback = string (default = 'textbar')
% cfg.layout = specification of the layout, see FT_PREPARE_LAYOUT
% cfg.foi = the frequency of interest which is to be plotted (default is the first frequency bin)
% cfg.widthparam = string, parameter to be used to control the line width (see below)
% cfg.alphaparam = string, parameter to be used to control the opacity (see below)
% cfg.colorparam = string, parameter to be used to control the line color
%
% The widthparam should be indicated in pixels, e.g. usefull numbers are 1
% and larger.
%
% The alphaparam should be indicated as opacity between 0 (fully transparent)
% and 1 (fully opaque).
%
% The default is to plot the connections as lines, but you can also use
% bidirectional arrows:
% cfg.arrowhead = string, 'none', 'stop', 'start', 'both' (default = 'none')
% cfg.arrowsize = scalar, size of the arrow head in figure units,
% i.e. the same units as the layout (default is automatically determined)
% cfg.arrowoffset = scalar, amount that the arrow is shifted to the side in figure units,
% i.e. the same units as the layout (default is automatically determined)
% cfg.arrowlength = scalar, amount by which the length is reduced relative to the complete line (default = 0.8)
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the input should be
% structured as a cell array.
%
% See also FT_PREPARE_LAYOUT, FT_MULTIPLOTCC, FT_CONNECTIVITYPLOT
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_topoplotCC.m 7188 2012-12-13 21:26:34Z roboos $
revision = '$Id: ft_topoplotCC.m 7188 2012-12-13 21:26:34Z roboos $';
% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble provenance
ft_preamble trackconfig
ft_preamble debug
ft_preamble loadvar freq
% check if the input data is valid for this function
freq = ft_checkdata(freq, 'cmbrepresentation', 'sparse');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'required', {'foi', 'layout'});
% set the defaults
if ~isfield(cfg, 'feedback'), cfg.feedback = 'text'; end
if ~isfield(cfg, 'alphaparam'), cfg.alphaparam = []; end
if ~isfield(cfg, 'widthparam'), cfg.widthparam = []; end
if ~isfield(cfg, 'colorparam'), cfg.colorparam = 'cohspctrm'; end
if ~isfield(cfg, 'newfigure'), cfg.newfigure = 'yes'; end
if ~isfield(cfg, 'arrowhead'), cfg.arrowhead = 'none'; end % none, stop, start, both
if ~isfield(cfg, 'arrowsize'), cfg.arrowsize = nan; end % length of the arrow head, should be in in figure units, i.e. the same units as the layout
if ~isfield(cfg, 'arrowoffset'), cfg.arrowoffset = nan; end % absolute, should be in figure units, i.e. the same units as the layout
if ~isfield(cfg, 'arrowlength'), cfg.arrowlength = 0.8; end % relative to the complete line
lay = ft_prepare_layout(cfg, freq);
beglabel = freq.labelcmb(:,1);
endlabel = freq.labelcmb(:,2);
ncmb = size(freq.labelcmb,1);
% select the data to be used in the figure
fbin = nearest(freq.freq, cfg.foi);
if isfield(freq, cfg.widthparam)
widthparam = freq.(cfg.widthparam)(:,fbin);
else
widthparam = ones(ncmb,1);
end
if isfield(freq, cfg.alphaparam)
alphaparam = freq.(cfg.alphaparam)(:,fbin);
else
alphaparam = [];
end
if isfield(freq, cfg.colorparam)
colorparam = freq.(cfg.colorparam)(:,:,fbin);
else
colorparam = [];
end
if strcmp(cfg.newfigure, 'yes')
figure
end
hold on
axis equal
% set the figure window title
funcname = mfilename();
if nargin < 2
dataname = cfg.inputfile;
else
dataname = inputname(2);
end
set(gcf, 'Name', sprintf('%d: %s: %s', gcf, funcname, join_str(', ',dataname)));
set(gcf, 'NumberTitle', 'off');
if isnan(cfg.arrowsize)
% use the size of the figure to estimate a decent number
siz = axis;
cfg.arrowsize = (siz(2) - siz(1))/50;
warning('using an arrowsize of %f', cfg.arrowsize);
end
if isnan(cfg.arrowoffset)
% use the size of the figure to estimate a decent number
siz = axis;
cfg.arrowoffset = (siz(2) - siz(1))/100;
warning('using an arrowoffset of %f', cfg.arrowoffset);
end
rgb = colormap;
if ~isempty(colorparam)
cmin = min(colorparam(:));
cmax = max(colorparam(:));
colorparam = (colorparam - cmin)./(cmax-cmin);
colorparam = round(colorparam * (size(rgb,1)-1) + 1);
end
if strcmp(cfg.newfigure, 'yes')
% also plot the position of the electrodes
ft_plot_vector(lay.pos(:,1), lay.pos(:,2), 'style','k.');
% also plot the outline, i.e. head shape or sulci
if isfield(lay, 'outline')
fprintf('solid lines indicate the outline, e.g. head shape or sulci\n');
for i=1:length(lay.outline)
if ~isempty(lay.outline{i})
X = lay.outline{i}(:,1);
Y = lay.outline{i}(:,2);
ft_plot_line(X, Y, 'color', 'k', 'linewidth', 1.5, 'linestyle', '-');
end
end
end
% also plot the mask, i.e. global outline for masking the topoplot
if isfield(lay, 'mask')
fprintf('dashed lines indicate the mask for topograpic interpolation\n');
for i=1:length(lay.mask)
if ~isempty(lay.mask{i})
X = lay.mask{i}(:,1);
Y = lay.mask{i}(:,2);
% the polygon representing the mask should be closed
X(end+1) = X(1);
Y(end+1) = Y(1);
ft_plot_line(X, Y, 'color', 'k', 'linewidth', 1.5, 'linestyle', '-');
end
end
end
end % if newfigure
% fix the limits for the axis
axis(axis);
ft_progress('init', cfg.feedback, 'plotting connections...');
for i=1:ncmb
if strcmp(beglabel{i}, endlabel{i})
% skip autocombinations
continue
end
ft_progress(i/ncmb, 'plotting connection %d from %d (%s -> %s)\n', i, ncmb, beglabel{i}, endlabel{i});
if widthparam(i)>0
begindx = strcmp(beglabel{i}, lay.label);
endindx = strcmp(endlabel{i}, lay.label);
xbeg = lay.pos(begindx,1);
ybeg = lay.pos(begindx,2);
xend = lay.pos(endindx,1);
yend = lay.pos(endindx,2);
if strcmp(cfg.arrowhead, 'none')
x = [xbeg xend]';
y = [ybeg yend]';
% h = line(x, y);
h = patch(x, y, 1);
else
arrowbeg = [xbeg ybeg];
arrowend = [xend yend];
center = (arrowbeg+arrowend)/2;
direction = (arrowend - arrowbeg);
direction = direction/norm(direction);
offset = [direction(2) -direction(1)];
arrowbeg = cfg.arrowlength * (arrowbeg-center) + center + cfg.arrowoffset * offset;
arrowend = cfg.arrowlength * (arrowend-center) + center + cfg.arrowoffset * offset;
h = arrow(arrowbeg, arrowend, 'Ends', cfg.arrowhead, 'length', 0.05);
end % if arrow
if ~isempty(widthparam)
set(h, 'LineWidth', widthparam(i));
end
if ~isempty(alphaparam)
set(h, 'EdgeAlpha', alphaparam(i));
set(h, 'FaceAlpha', alphaparam(i)); % for arrowheads
end
if ~isempty(colorparam)
set(h, 'EdgeColor', rgb(colorparam(i),:));
set(h, 'FaceColor', rgb(colorparam(i),:)); % for arrowheads
end
end
end
ft_progress('close');
% improve the fit in the axis
axis tight
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble provenance
ft_postamble previous freq
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for plotting arrows, see also fieldtrip/private/arrow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = arrow(arrowbeg, arrowend, varargin)
ends = ft_getopt(varargin, 'ends');
length = ft_getopt(varargin, 'length'); % the length of the arrow head, in figure units
color = [0 0 0]; % in RGB
direction = (arrowend - arrowbeg);
direction = direction/norm(direction);
offset = [direction(2) -direction(1)];
pnt1 = arrowbeg;
pnt2 = arrowend;
h = patch([pnt1(1) pnt2(1)], [pnt1(2) pnt2(2)], color);
switch ends
case 'stop'
pnt1 = arrowend - length*direction + 0.4*length*offset;
pnt2 = arrowend;
pnt3 = arrowend - length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
case 'start'
pnt1 = arrowbeg + length*direction + 0.4*length*offset;
pnt2 = arrowbeg;
pnt3 = arrowbeg + length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
case 'both'
pnt1 = arrowend - length*direction + 0.4*length*offset;
pnt2 = arrowend;
pnt3 = arrowend - length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
pnt1 = arrowbeg + length*direction + 0.4*length*offset;
pnt2 = arrowbeg;
pnt3 = arrowbeg + length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
case 'none'
% don't draw arrow heads
end
|
github
|
philippboehmsturm/antx-master
|
ft_struct2single.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_struct2single.m
| 2,973 |
utf_8
|
c154a80ca65e233f13e2245801ed532a
|
function [x] = ft_struct2single(x, maxdepth);
% FT_STRUCT2SINGLE converts all double precision numeric data in a structure
% into single precision, which takes up half the amount of memory compared
% to double precision. It will also convert plain matrices and cell-arrays.
%
% Use as
% x = ft_struct2single(x);
%
% Starting from Matlab 7.0, you can use single precision data in your
% computations, i.e. you do not have to convert back to double precision.
%
% Matlab version 6.5 and older only support single precision for storing
% data in memory or on disk, but do not allow computations on single
% precision data. After reading a single precision structure from file, you
% can convert it back with FT_STRUCT2DOUBLE.
%
% See also FT_STRUCT2DOUBLE
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_struct2single.m 7123 2012-12-06 21:21:38Z roboos $
if nargin<2
maxdepth = inf;
end
% convert the data, work recursively through the complete structure
x = convert(x, 0, maxdepth);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this subfunction does the actual work
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a] = convert(a, depth, maxdepth);
if depth>maxdepth
error('recursive depth exceeded');
end
switch class(a)
case 'struct'
% process all fields of the structure recursively
fna = fieldnames(a);
% process all elements of the array
for j=1:length(a(:))
% warning, this is a recursive call to traverse nested structures
for i=1:length(fna)
fn = fna{i};
ra = getfield(a(j), fn);
ra = convert(ra, depth+1, maxdepth);
a(j) = setfield(a(j), fn, ra);
end
end
case 'cell'
% process all elements of the cell-array recursively
% warning, this is a recursive call to traverse nested structures
for i=1:length(a(:))
a{i} = convert(a{i}, depth+1, maxdepth);
end
case {'double' 'int32' 'uint32' 'int16' 'uint16'}
% convert the values to single precision
if ~issparse(a)
a = single(a);
end
otherwise
warning_once(sprintf('not converting class %s', class(a)));
% do nothing
end
|
github
|
philippboehmsturm/antx-master
|
ft_datatype_sens.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_datatype_sens.m
| 8,876 |
utf_8
|
776724d18f8a763419894019a25ee4de
|
function [sens] = ft_datatype_sens(sens, varargin)
% FT_DATATYPE_SENS describes the FieldTrip structure that represents
% an EEG, ECoG, or MEG sensor array. This structure is commonly called
% "elec" for EEG and "grad" for MEG, or more general "sens" for either
% one.
%
% The structure for MEG gradiometers and/or magnetometers contains
% sens.label = Mx1 cell-array with channel labels
% sens.chanpos = Mx3 matrix with channel positions
% sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation
% sens.tra = MxN matrix to combine coils into channels
% sens.coilpos = Nx3 matrix with coil positions
% sens.coilori = Nx3 matrix with coil orientations
% sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE
%
% The structure for EEG or ECoG channels contains
% sens.label = Mx1 cell-array with channel labels
% sens.chanpos = Mx3 matrix with channel positions
% sens.tra = MxN matrix to combine electrodes into channels
% sens.elecpos = Nx3 matrix with electrode positions
% In case sens.tra is not present in the EEG sensor array, the channels
% are assumed to be average referenced.
%
% The following fields are optional
% sens.type = string with the MEG or EEG acquisition system, see FT_SENSTYPE
% sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE
% sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'T', 'fT' or 'fT/cm'
% sens.fid = structure with fiducial information
%
% Revision history:
%
% (2011v2/latest) The chantype and chanunit have been added for MEG.
%
% (2011v1) To facilitate determining the position of channels (e.g. for plotting)
% in case of balanced MEG or bipolar EEG, an explicit distinction has been made
% between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos
% (for EEG). The pnt and ori fields are removed
%
% (2010) Added support for bipolar or otherwise more complex linear combinations
% of EEG electrodes using sens.tra, similar to MEG.
%
% (2009) Noice reduction has been added for MEG systems in the balance field.
%
% (2006) The optional fields sens.type and sens.unit were added.
%
% (2003) The initial version was defined, which looked like this for EEG
% sens.pnt = Mx3 matrix with electrode positions
% sens.label = Mx1 cell-array with channel labels
% and like this for MEG
% sens.pnt = Nx3 matrix with coil positions
% sens.ori = Nx3 matrix with coil orientations
% sens.tra = MxN matrix to combine coils into channels
% sens.label = Mx1 cell-array with channel labels
%
% See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD,
% BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD
% Copyright (C) 2011, Robert Oostenveld & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_datatype_sens.m 7247 2012-12-21 11:37:09Z roboos $
% these are for remembering the type on subsequent calls with the same input arguments
persistent previous_argin previous_argout
current_argin = [{sens} varargin];
if isequal(current_argin, previous_argin)
% don't do the whole cheking again, but return the previous output from cache
sens = previous_argout{1};
end
% get the optional input arguments, which should be specified as key-value pairs
version = ft_getopt(varargin, 'version', 'latest');
if strcmp(version, 'latest')
version = '2011v2';
end
if isempty(sens)
return;
end
switch version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case '2011v2'
% This speeds up subsequent calls to ft_senstype and channelposition.
% However, if it is not more precise than MEG or EEG, don't keep it in
% the output (see further down).
if ~isfield(sens, 'type')
sens.type = ft_senstype(sens);
end
% there are many cases which deal with either eeg or meg
ismeg = ft_senstype(sens, 'meg');
if isfield(sens, 'pnt')
if ismeg
% sensor description is a MEG sensor-array, containing oriented coils
sens.coilpos = sens.pnt; sens = rmfield(sens, 'pnt');
sens.coilori = sens.ori; sens = rmfield(sens, 'ori');
else
% sensor description is something else, EEG/ECoG etc
sens.elecpos = sens.pnt; sens = rmfield(sens, 'pnt');
end
end
if ~isfield(sens, 'chanpos')
if ismeg
% sensor description is a MEG sensor-array, containing oriented coils
[chanpos, chanori, lab] = channelposition(sens, 'channel', 'all');
% the channel order can be different in the two representations
[selsens, selpos] = match_str(sens.label, lab);
sens.chanpos = nan(length(sens.label), 3);
sens.chanori = nan(length(sens.label), 3);
% insert the determined position/orientation on the appropriate rows
sens.chanpos(selsens,:) = chanpos(selpos,:);
sens.chanori(selsens,:) = chanori(selpos,:);
if length(selsens)~=length(sens.label)
warning('cannot determine the position and orientation for all channels');
end
else
% sensor description is something else, EEG/ECoG etc
% note that chanori will be all NaNs
[chanpos, chanori, lab] = channelposition(sens, 'channel', 'all');
% the channel order can be different in the two representations
[selsens, selpos] = match_str(sens.label, lab);
sens.chanpos = nan(length(sens.label), 3);
% insert the determined position/orientation on the appropriate rows
sens.chanpos(selsens,:) = chanpos(selpos,:);
if length(selsens)~=length(sens.label)
warning('cannot determine the position and orientation for all channels');
end
end
end
if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown'))
if ismeg
sens.chantype = ft_chantype(sens);
else
% FIXME for EEG we have not yet figured out how to deal with this
end
end
if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown'))
if ismeg
sens.chanunit = ft_chanunit(sens);
else
% FIXME for EEG we have not yet figured out how to deal with this
end
end
if ~isfield(sens, 'unit')
sens = ft_convert_units(sens);
end
if any(strcmp(sens.type, {'meg', 'eeg', 'magnetometer', 'electrode', 'unknown'}))
% this is not sufficiently informative, so better remove it
% see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1806
sens = rmfield(sens, 'type');
end
if size(sens.chanpos,1)~=length(sens.label) || ...
isfield(sens, 'tra') && size(sens.tra,1)~=length(sens.label) || ...
isfield(sens, 'tra') && isfield(sens, 'elecpos') && size(sens.tra,2)~=size(sens.elecpos,1) || ...
isfield(sens, 'tra') && isfield(sens, 'coilpos') && size(sens.tra,2)~=size(sens.coilpos,1) || ...
isfield(sens, 'tra') && isfield(sens, 'coilori') && size(sens.tra,2)~=size(sens.coilori,1) || ...
isfield(sens, 'chanpos') && size(sens.chanpos,1)~=length(sens.label) || ...
isfield(sens, 'chanori') && size(sens.chanori,1)~=length(sens.label)
error('inconsistent number of channels in sensor description');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
otherwise
error('converting to version %s is not supported', version);
end % switch
% this makes the display with the "disp" command look better
sens = sortfieldnames(sens);
% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout = {sens};
previous_argin = current_argin;
previous_argout = current_argout;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function b = sortfieldnames(a)
fn = sort(fieldnames(a));
for i=1:numel(fn)
b.(fn{i}) = a.(fn{i});
end
|
github
|
philippboehmsturm/antx-master
|
ft_datatype.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_datatype.m
| 7,749 |
utf_8
|
975852e96f4caa3ccb50bbbd5f8c5248
|
function [type, dimord] = ft_datatype(data, desired)
% FT_DATATYPE determines the type of data represented in a FieldTrip data
% structure and returns a string with raw, freq, timelock source, comp,
% spike, source, volume, dip.
%
% Use as
% [type, dimord] = ft_datatype(data)
% [status] = ft_datatype(data, desired)
%
% See also FT_DATATYPE_COMP FT_DATATYPE_FREQ FT_DATATYPE_MVAR
% FT_DATATYPE_SEGMENTATION FT_DATATYPE_PARCELLATION FT_DATATYPE_SOURCE
% FT_DATATYPE_TIMELOCK FT_DATATYPE_DIP FT_DATATYPE_HEADMODEL
% FT_DATATYPE_RAW FT_DATATYPE_SENS FT_DATATYPE_SPIKE FT_DATATYPE_VOLUME
% Copyright (C) 2008-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_datatype.m 7123 2012-12-06 21:21:38Z roboos $
% determine the type of input data, this can be raw, freq, timelock, comp, spike, source, volume, dip, segmentation, parcellation
israw = isfield(data, 'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && ~isfield(data,'trialtime');
isfreq = (isfield(data, 'label') || isfield(data, 'labelcmb')) && isfield(data, 'freq') && ~isfield(data,'trialtime') && ~isfield(data,'origtrial'); %&& (isfield(data, 'powspctrm') || isfield(data, 'crsspctrm') || isfield(data, 'cohspctrm') || isfield(data, 'fourierspctrm') || isfield(data, 'powcovspctrm'));
istimelock = isfield(data, 'label') && isfield(data, 'time') && ~isfield(data, 'freq') && ~isfield(data,'trialtime'); %&& ((isfield(data, 'avg') && isnumeric(data.avg)) || (isfield(data, 'trial') && isnumeric(data.trial) || (isfield(data, 'cov') && isnumeric(data.cov))));
iscomp = isfield(data, 'label') && isfield(data, 'topo') || isfield(data, 'topolabel');
isvolume = isfield(data, 'transform') && isfield(data, 'dim');
issource = isfield(data, 'pos');
isdip = isfield(data, 'dip');
ismvar = isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'lag'));
isfreqmvar = isfield(data, 'freq') && isfield(data, 'transfer');
ischan = isfield(data, 'dimord') && strcmp(data.dimord, 'chan') && ~isfield(data, 'time') && ~isfield(data, 'freq');
issegmentation = check_segmentation(data);
isparcellation = check_parcellation(data);
if ~isfreq
% this applies to a ferq structure from 2003 up to early 2006
isfreq = all(isfield(data, {'foi', 'label', 'dimord'})) && ~isempty(strfind(data.dimord, 'frq'));
end
% check if it is a spike structure
spk_hastimestamp = isfield(data,'label') && isfield(data, 'timestamp') && isa(data.timestamp, 'cell');
spk_hastrials = isfield(data,'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && isfield(data, 'trialtime') && isa(data.trialtime, 'numeric');
spk_hasorig = isfield(data,'origtrial') && isfield(data,'origtime'); % for compatibility
isspike = isfield(data, 'label') && (spk_hastimestamp || spk_hastrials || spk_hasorig);
% check if it is a sensor array
isgrad = isfield(data, 'label') && isfield(data, 'coilpos') && isfield(data, 'chanpos') && isfield(data, 'coilori');
iselec = isfield(data, 'label') && isfield(data, 'elecpos') && isfield(data, 'chanpos');
if iscomp
% comp should conditionally go before raw, otherwise the returned ft_datatype will be raw
type = 'comp';
elseif israw
type = 'raw';
elseif isfreqmvar
% freqmvar should conditionally go before freq, otherwise the returned ft_datatype will be freq in the case of frequency mvar data
type = 'freqmvar';
elseif isfreq
type = 'freq';
elseif ismvar
type = 'mvar';
elseif isdip
% dip should conditionally go before timelock, otherwise the ft_datatype will be timelock
type = 'dip';
elseif istimelock
type = 'timelock';
elseif isspike
type = 'spike';
elseif issegmentation
% a segmentation data structure is a volume data structure, but in general not vice versa
% segmentation should conditionally go before volume, otherwise the returned ft_datatype will be volume
type = 'segmentation';
elseif isvolume
type = 'volume';
elseif isparcellation
% a parcellation data structure is a source data structure, but in general not vice versa
% parcellation should conditionally go before source, otherwise the returned ft_datatype will be source
type = 'parcellation';
elseif issource
type = 'source';
elseif ischan
% this results from avgovertime/avgoverfreq after timelockstatistics or freqstatistics
type = 'chan';
elseif iselec
type = 'elec';
elseif isgrad
type = 'grad';
else
type = 'unknown';
end
if nargin>1
% return a boolean value
switch desired
case 'raw'
type = any(strcmp(type, {'raw', 'comp'}));
case 'volume'
type = any(strcmp(type, {'volume', 'segmentation'}));
case 'source'
type = any(strcmp(type, {'source', 'parcellation'}));
case 'sens'
type = any(strcmp(type, {'elec', 'grad'}));
otherwise
type = strcmp(type, desired);
end % switch
end
if nargout>1
% also return the dimord of the input data
if isfield(data, 'dimord')
dimord = data.dimord;
else
dimord = 'unknown';
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [res] = check_segmentation(volume)
res = false;
if ~isfield(volume, 'dim')
return
end
if isfield(volume, 'pos')
return
end
if any(isfield(volume, {'seg', 'csf', 'white', 'gray', 'skull', 'scalp', 'brain'}))
res = true;
return
end
fn = fieldnames(volume);
for i=1:length(fn)
if isfield(volume, [fn{i} 'label'])
res = true;
return
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [res] = check_parcellation(source)
res = false;
if ~isfield(source, 'pos')
return
end
fn = fieldnames(source);
fb = false(size(fn));
npos = size(source.pos,1);
for i=1:numel(fn)
% for each of the fields check whether it might be a logical array with the size of the number of sources
tmp = source.(fn{i});
fb(i) = numel(tmp)==npos && islogical(tmp);
end
if sum(fb)>1
% the presence of multiple logical arrays suggests it is a parcellation
res = true;
end
if res == false % check if source has more D elements
check = 0;
for i = 1: length(fn)
fname = fn{i};
switch fname
case 'tri'
npos = size(source.tri,1);
check = 1;
case 'hex'
npos = size(source.hex,1);
check = 1;
case 'tet'
npos = size(source.tet,1);
check = 1;
end
end
if check == 1 % check if elements are labelled
for i=1:numel(fn)
tmp = source.(fn{i});
fb(i) = numel(tmp)==npos && islogical(tmp);
end
if sum(fb)>1
res = true;
end
end
end
fn = fieldnames(source);
for i=1:length(fn)
if isfield(source, [fn{i} 'label'])
res = true;
return
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_checkconfig.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_checkconfig.m
| 24,347 |
utf_8
|
545c5f8e319ccf687bd339ea79cbe228
|
function [cfg] = ft_checkconfig(cfg, varargin)
% FT_CHECKCONFIG checks the input cfg of the main FieldTrip functions.
%
% 1: It checks whether the cfg contains all the required options, it gives
% a warning when renamed or deprecated options are used, and it makes sure
% no forbidden options are used. If necessary and possible, this function
% will adjust the cfg to the input requirements. If the input cfg does NOT
% correspond to the requirements, this function gives an elaborate warning
% message.
%
% 2: It controls the relevant cfg options that are being passed on to other
% functions, by putting them into substructures or converting them into the
% required format.
%
% 3: It controls the output cfg (data.cfg) such that it only contains
% relevant and used fields. The size of fields in the output cfg is also
% controlled: fields exceeding a certain maximum size are emptied.
% This part of the functionality is still under construction!
%
% Use as
% [cfg] = ft_checkconfig(cfg, ...)
%
% The behaviour of checkconfig can be controlled by the following cfg options,
% which can be set as global fieldtrip defaults (see FT_DEFAULTS)
% cfg.checkconfig = 'pedantic', 'loose' or 'silent' (control the feedback behaviour of checkconfig)
% cfg.trackconfig = 'cleanup', 'report' or 'off'
% cfg.checksize = number in bytes, can be inf (set max size allowed for output cfg fields)
%
% Optional input arguments should be specified as key-value pairs and can include
% renamed = {'old', 'new'} % list the old and new option
% renamedval = {'opt', 'old', 'new'} % list option and old and new value
% allowedval = {'opt', 'allowed1'...} % list of allowed values for a particular option, anything else will throw an error
% required = {'opt1', 'opt2', etc.} % list the required options
% allowed = {'opt1', 'opt2', etc.} % list the allowed options, all other options are forbidden
% forbidden = {'opt1', 'opt2', etc.} % list the forbidden options, these result in an error
% deprecated = {'opt1', 'opt2', etc.} % list the deprecated options
% unused = {'opt1', 'opt2', etc.} % list the unused options, these will be removed and a warning is issued
% createsubcfg = {'subname', etc.} % list the names of the subcfg
% dataset2files = 'yes', 'no' % converts dataset into headerfile and datafile
% checksize = 'yes', 'no' % remove large fields from the cfg
% trackconfig = 'on', 'off' % start/end config tracking
%
% See also FT_CHECKDATA, FT_DEFAULTS
% Copyright (C) 2007-2012, Robert Oostenveld, Saskia Haegens
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_checkconfig.m 7406 2013-01-25 11:43:01Z jansch $
global ft_default
% merge the default configuration with the input configuration
cfg = mergeconfig(cfg, ft_default);
renamed = ft_getopt(varargin, 'renamed');
allowed = ft_getopt(varargin, 'allowed');
required = ft_getopt(varargin, 'required');
deprecated = ft_getopt(varargin, 'deprecated');
unused = ft_getopt(varargin, 'unused');
forbidden = ft_getopt(varargin, 'forbidden');
renamedval = ft_getopt(varargin, 'renamedval');
allowedval = ft_getopt(varargin, 'allowedval');
createsubcfg = ft_getopt(varargin, 'createsubcfg');
checkfilenames = ft_getopt(varargin, 'dataset2files');
checksize = ft_getopt(varargin, 'checksize', 'off');
trackconfig = ft_getopt(varargin, 'trackconfig');
if ~isempty(trackconfig) && strcmp(trackconfig, 'on')
% infer from the user configuration whether tracking should be enabled
if isfield(cfg, 'trackconfig') && (strcmp(cfg.trackconfig, 'report') || strcmp(cfg.trackconfig, 'cleanup'))
trackconfig = 'on'; % turn on configtracking if user requests report/cleanup
else
trackconfig = []; % disable configtracking if user doesn't request report/cleanup
end
end
% these should be cell arrays and not strings
if ischar(required), required = {required}; end
if ischar(deprecated), deprecated = {deprecated}; end
if ischar(unused), unused = {unused}; end
if ischar(forbidden), forbidden = {forbidden}; end
if ischar(createsubcfg), createsubcfg = {createsubcfg}; end
if isfield(cfg, 'checkconfig')
silent = strcmp(cfg.checkconfig, 'silent');
loose = strcmp(cfg.checkconfig, 'loose');
pedantic = strcmp(cfg.checkconfig, 'pedantic');
else
silent = false;
loose = true;
pedantic = false;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rename old to new options, give warning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(renamed)
if issubfield(cfg, renamed{1})
cfg = setsubfield(cfg, renamed{2}, (getsubfield(cfg, renamed{1})));
cfg = rmsubfield(cfg, renamed{1});
if silent
% don't mention it
elseif loose
warning('use cfg.%s instead of cfg.%s', renamed{2}, renamed{1});
elseif pedantic
error('use cfg.%s instead of cfg.%s', renamed{2}, renamed{1});
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rename old to new value, give warning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(renamedval) && issubfield(cfg, renamedval{1})
if strcmpi(getsubfield(cfg, renamedval{1}), renamedval{2})
cfg = setsubfield(cfg, renamedval{1}, renamedval{3});
if silent
% don't mention it
elseif loose
warning('use cfg.%s=''%s'' instead of cfg.%s=''%s''', renamedval{1}, renamedval{3}, renamedval{1}, renamedval{2});
elseif pedantic
error('use cfg.%s=''%s'' instead of cfg.%s=''%s''', renamedval{1}, renamedval{3}, renamedval{1}, renamedval{2});
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for required fields, give error when missing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(required)
fieldsused = fieldnames(cfg);
[c, ia, ib] = setxor(required, fieldsused);
if ~isempty(ia)
error('The field cfg.%s is required\n', required{ia});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for deprecated fields, give warning when present
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(deprecated)
fieldsused = fieldnames(cfg);
if any(ismember(deprecated, fieldsused))
if silent
% don't mention it
elseif loose
warning('The option cfg.%s is deprecated, support is no longer guaranteed\n', deprecated{ismember(deprecated, fieldsused)});
elseif pedantic
error('The option cfg.%s is not longer supported\n', deprecated{ismember(deprecated, fieldsused)});
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for unused fields, give warning when present and remove them
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(unused)
fieldsused = fieldnames(cfg);
if any(ismember(unused, fieldsused))
cfg = rmfield(cfg, unused(ismember(unused, fieldsused)));
if silent
% don't mention it
elseif loose
warning('The field cfg.%s is unused, it will be removed from your configuration\n', unused{ismember(unused, fieldsused)});
elseif pedantic
error('The field cfg.%s is unused\n', unused{ismember(unused, fieldsused)});
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for required fields, give error when missing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(allowed)
% there are some general options that should always be allowed
allowed = union(allowed, {
'trackconfig'
'checkconfig'
'checksize'
'showcallinfo'
'trackcallinfo'
'trackdatainfo'
'trackparaminfo'
'debug'
});
fieldsused = fieldnames(cfg);
[c, i] = setdiff(fieldsused, allowed);
if ~isempty(c)
error('The field cfg.%s is not allowed\n', c{1});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for forbidden fields, give error when present
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(forbidden)
fieldsused = fieldnames(cfg);
if any(ismember(forbidden, fieldsused))
cfg = rmfield(cfg, forbidden(ismember(forbidden, fieldsused)));
if silent
% don't mention it
elseif loose
warning('The field cfg.%s is forbidden, it will be removed from your configuration\n', forbidden{ismember(forbidden, fieldsused)});
elseif pedantic
error('The field cfg.%s is forbidden\n', forbidden{ismember(forbidden, fieldsused)});
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for allowed values, give error if non-allowed value is specified
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(allowedval) && isfield(cfg, allowedval{1}) ...
&& ~any(strcmp(cfg.(allowedval{1}), allowedval(2:end)))
s = ['The only allowed values for cfg.' allowedval{1} ' are: '];
for k = 2:numel(allowedval)
s = [s allowedval{k} ', '];
end
s = s(1:end-2); % strip last comma
error(s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% backward compatibility for the gradiometer and electrode definition
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(cfg, 'grad') && ~isempty(cfg.grad)
cfg.grad = ft_datatype_sens(cfg.grad);
end
if isfield(cfg, 'elec')&& ~isempty(cfg.elec)
cfg.elec = ft_datatype_sens(cfg.elec);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% backward compatibility for old neighbourstructures
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(cfg, 'neighbours') && iscell(cfg.neighbours)
warning('Neighbourstructure is in old format - converting to structure array');
cfg.neighbours= fixneighbours(cfg.neighbours);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% createsubcfg
%
% This collects the optional arguments for some of the low-level
% functions and puts them in a separate substructure. This function is to
% ensure backward compatibility of end-user scripts, fieldtrip functions
% and documentation that do not use the nested detailled configuration
% but that use a flat configuration.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(createsubcfg)
for j=1:length(createsubcfg)
subname = createsubcfg{j};
if isfield(cfg, subname)
% get the options that are already specified in the substructure
subcfg = getfield(cfg, subname);
else
% start with an empty substructure
subcfg = [];
end
% add all other relevant options to the substructure
switch subname
case 'preproc'
fieldname = {
'reref'
'refchannel'
'implicitref'
'detrend'
'bpfiltdir'
'bpfilter'
'bpfiltord'
'bpfilttype'
'bpfreq'
'bsfiltdir'
'bsfilter'
'bsfiltord'
'bsfilttype'
'bsfreq'
'demean'
'baselinewindow'
'denoise'
'dftfilter'
'dftfreq'
'hpfiltdir'
'hpfilter'
'hpfiltord'
'hpfilttype'
'hpfreq'
'lpfiltdir'
'lpfilter'
'lpfiltord'
'lpfilttype'
'lpfreq'
'medianfilter'
'medianfiltord'
'hilbert'
'derivative'
'rectify'
'boxcar'
'absdiff'
};
case 'grid'
fieldname = {
'xgrid'
'ygrid'
'zgrid'
'resolution'
'filter'
'leadfield'
'inside'
'outside'
'pos'
'dim'
'tight'
};
case 'dics'
fieldname = {
'feedback'
'fixedori'
'keepcsd'
'keepfilter'
'keepmom'
'keepsubspace'
'lambda'
'normalize'
'normalizeparam'
'powmethod'
'projectnoise'
'reducerank'
'realfilter'
'subspace'
};
case 'lcmv'
fieldname = {
'feedback'
'fixedori'
'keepcov'
'keepfilter'
'keepmom'
'keepsubspace'
'lambda'
'normalize'
'normalizeparam'
'powmethod'
'projectnoise'
'projectmom'
'reducerank'
'subspace'
};
case 'pcc'
fieldname = {
'feedback'
'keepfilter'
'keepmom'
'lambda'
'normalize'
'normalizeparam'
%'powmethod'
'projectnoise'
'reducerank'
'keepcsd'
'realfilter'
'fixedori'
};
case {'loreta', 'rv'}
fieldname = {
'feedback'
'lambda'
};
case 'mne'
fieldname = {
'feedback'
'lambda'
'keepfilter'
'prewhiten'
'snr'
'scalesourcecov'
};
case 'music'
fieldname = {
'feedback'
'numcomponent'
};
case 'sam'
fieldname = {
'meansphereorigin'
'feedback'
'lambda'
'fixedori'
'reducerank'
'normalize'
'normalizeparam'
};
case 'mvl'
fieldname = {};
case {'npsf', 'granger'}
% non-parametric spectral factorization -> csd2transfer
fieldname = {
'block'
'blockindx'
'channelcmb'
'numiteration'
'tol'
'sfmethod'
'svd'
'init'
};
otherwise
error('unexpected name of the subfunction');
fieldname = {};
end % switch subname
for i=1:length(fieldname)
if ~isfield(subcfg, fieldname{i}) && isfield(cfg, fieldname{i})
if silent
% don't mention it
elseif loose
warning('The field cfg.%s is deprecated, please specify it as cfg.%s.%s instead of cfg.%s', fieldname{i}, subname, fieldname{i});
elseif pedantic
error('The field cfg.%s is not longer supported, use cfg.%s.%s instead\n', fieldname{i}, subname, fieldname{i});
end
subcfg = setfield(subcfg, fieldname{i}, getfield(cfg, fieldname{i})); % set it in the subconfiguration
cfg = rmfield(cfg, fieldname{i}); % remove it from the main configuration
end
end
% copy the substructure back into the main configuration structure
cfg = setfield(cfg, subname, subcfg);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% checkfilenames, i.e. dataset2files
%
% Converts cfg.dataset into cfg.headerfile and cfg.datafile if neccessary.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(checkfilenames) && strcmp(checkfilenames, 'yes')
% start with empty fields if they are not present
if ~isfield(cfg, 'dataset')
cfg.dataset = [];
end
if ~isfield(cfg, 'datafile')
cfg.datafile = [];
end
if ~isfield(cfg, 'headerfile')
cfg.headerfile = [];
end
if ~isempty(cfg.dataset)
if strcmp(cfg.dataset, 'gui') || strcmp(cfg.dataset, 'uigetfile')
% display a graphical file selection dialog
[f, p] = uigetfile('*.*', 'Select a data file');
if isequal(f, 0)
error('User pressed cancel');
else
d = fullfile(p, f);
end
cfg.dataset = d;
elseif strcmp(cfg.dataset, 'uigetdir')
% display a graphical directory selection dialog
d = uigetdir('*.*', 'Select a data directory');
if isequal(d, 0)
error('User pressed cancel');
end
cfg.dataset = d;
end
% ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset
% this requires correct autodetection of the format
[cfg.dataset, cfg.headerfile, cfg.datafile] = dataset2files(cfg.dataset, []);
% fill dataformat if unspecified
if ~isfield(cfg,'dataformat') || isempty(cfg.dataformat)
cfg.dataformat = ft_filetype(cfg.datafile);
end
% fill dataformat if unspecified
if ~isfield(cfg,'headerformat') || isempty(cfg.headerformat)
cfg.headerformat = ft_filetype(cfg.headerfile);
end
elseif ~isempty(cfg.datafile) && isempty(cfg.headerfile);
% assume that the datafile also contains the header
cfg.headerfile = cfg.datafile;
elseif isempty(cfg.datafile) && ~isempty(cfg.headerfile);
% assume that the headerfile also contains the data
cfg.datafile = cfg.headerfile;
end
% remove empty fields (otherwise a subsequent check on required fields doesn't make any sense)
if isempty(cfg.dataset), cfg=rmfield(cfg, 'dataset'); end
if isempty(cfg.headerfile), cfg=rmfield(cfg, 'headerfile'); end
if isempty(cfg.datafile), cfg=rmfield(cfg, 'datafile'); end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% configtracking
%
% switch configuration tracking on/off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(trackconfig)
try
if strcmp(trackconfig, 'on') && isa(cfg, 'struct')
% turn ON configuration tracking
cfg = config(cfg);
% remember that configtracking has been turned on
cfg.trkcfgcount = 1;
elseif strcmp(trackconfig, 'on') && isa(cfg, 'config')
% remember how many times configtracking has been turned on
cfg.trkcfgcount = cfg.trkcfgcount+1; % count the 'ONs'
end
if strcmp(trackconfig, 'off') && isa(cfg, 'config')
% turn OFF configuration tracking, optionally give report and/or cleanup
cfg.trkcfgcount=cfg.trkcfgcount-1; % count(down) the 'OFFs'
if cfg.trkcfgcount==0 % only proceed when number of 'ONs' matches number of 'OFFs'
cfg=rmfield(cfg, 'trkcfgcount');
if strcmp(cfg.trackconfig, 'report') || strcmp(cfg.trackconfig, 'cleanup')
% gather information about the tracked results
r = access(cfg, 'reference');
o = access(cfg, 'original');
key = fieldnames(cfg);
key = key(:)';
ignorefields = {'checksize', 'trl', 'trlold', 'event', 'artifact', 'artfctdef', 'previous', 'debug'}; % these fields should never be removed!
skipsel = match_str(key, ignorefields);
key(skipsel) = [];
used = zeros(size(key));
original = zeros(size(key));
for i=1:length(key)
used(i) = (r.(key{i})>0);
original(i) = (o.(key{i})>0);
end
if ~silent
% give report on screen
fprintf('\nThe following config fields were specified by YOU and were USED\n');
sel = find(used & original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
fprintf('\nThe following config fields were specified by YOU and were NOT USED\n');
sel = find(~used & original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
fprintf('\nThe following config fields were set to DEFAULTS and were USED\n');
sel = find(used & ~original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
fprintf('\nThe following config fields were set to DEFAULTS and were NOT USED\n');
sel = find(~used & ~original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
end % report
end % report/cleanup
if strcmp(cfg.trackconfig, 'cleanup')
% remove the unused options from the configuration
unusedkey = key(~used);
for i=1:length(unusedkey)
cfg = rmfield(cfg, unusedkey{i});
end
end
% convert the configuration back to a struct
cfg = struct(cfg);
end
end % off
catch
disp(lasterr);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check the size of fields in the cfg, remove large fields
% the max allowed size should be specified in cfg.checksize (this can be
% set with ft_defaults)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(checksize, 'yes') && ~isinf(cfg.checksize)
cfg = checksizefun(cfg, cfg.checksize);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [cfg] = checksizefun(cfg, max_size)
% first check the total size of the cfg
s = whos('cfg');
if (s.bytes <= max_size)
return;
end
ignorefields = {'checksize', 'trl', 'trlold', 'event', 'artifact', 'artfctdef', 'previous'}; % these fields should never be removed
norecursion = {'event'}; % these fields should not be handled recursively
fieldsorig = fieldnames(cfg);
for i=1:numel(fieldsorig)
for k=1:numel(cfg) % process each structure in a struct-array
if any(strcmp(fieldsorig{i}, ignorefields))
% keep this field, regardless of its size
continue
elseif iscell(cfg(k).(fieldsorig{i}))
% run recursively on each struct element that is contained in the cell-array
for j=1:numel(cfg(k).(fieldsorig{i}))
if isstruct(cfg(k).(fieldsorig{i}){j})
cfg(k).(fieldsorig{i}){j} = checksizefun(cfg(k).(fieldsorig{i}){j}, max_size);
end
end
elseif isstruct(cfg(k).(fieldsorig{i})) && ~any(strcmp(fieldsorig{i}, norecursion))
% run recursively on a struct field
cfg(k).(fieldsorig{i}) = checksizefun(cfg(k).(fieldsorig{i}), max_size);
else
% determine the size of the field and remove it if too large
temp = cfg(k).(fieldsorig{i});
s = whos('temp');
if s.bytes>max_size
cfg(k).(fieldsorig{i}) = 'empty - this was cleared by checkconfig';
end
clear temp
end
end % for numel(cfg)
end % for each of the fieldsorig
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION converts a cell array of structure arrays into a structure array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newNeighbours = fixneighbours(neighbours)
newNeighbours = struct;
for i=1:numel(neighbours)
if i==1, newNeighbours = neighbours{i}; end;
newNeighbours(i) = neighbours{i};
end
|
github
|
philippboehmsturm/antx-master
|
ft_determine_coordsys.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_determine_coordsys.m
| 11,594 |
utf_8
|
02a948edaf44283cf81dfeee7d66f5a6
|
function [data] = ft_determine_coordsys(data, varargin)
% FT_DETERMINE_COORDSYS plots a geometrical object, allowing you to perform
% a visual check on the coordinatesystem, the units and on the anatomical
% labels for the coordinate system axes.
%
% Use as
% [dataout] = ft_determine_coordsys(datain, ...)
% where the input data structure can be
% - an anatomical MRI
% - an electrode or gradiometer definition
% - a volume conduction model of the head
% or most other FieldTrip structures that represent geometrical information.
%
% Additional optional input arguments should be specified as key-value pairs
% and can include
% interactive = string, 'yes' or 'no' (default = 'yes')
% axisscale = scaling factor for the reference axes and sphere (default = 1)
%
% This function wil pop up a figure that allows you to check whether the
% alignment of the object relative to the coordinate system axes is correct
% and what the anatomical labels of the coordinate system axes are. You
% should switch on the 3D rotation option in the figure panel to rotate and
% see the figure from all angles. To change the anatomical labels of the
% coordinate system, you should press the corresponding keyboard button.
%
% Recognized and supported coordinate systems include: ctf, 4d, bti, itab,
% neuromag, spm, mni, als, ras. T
%
% See also FT_VOLUMEREALIGN, FT_VOLUMERESLICE
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_determine_coordsys.m 7123 2012-12-06 21:21:38Z roboos $
dointeractive = ft_getopt(varargin, 'interactive', 'yes');
axisscale = ft_getopt(varargin, 'axisscale', 1); % this is used to scale the axmax and rbol
data = ft_checkdata(data);
dtype = ft_datatype(data);
data = ft_convert_units(data);
unit = data.unit;
% the high-level data structures are detected with ft_datatype, but there are
% also some low-level data structures that need to be supproted here
if strcmp(dtype, 'unknown')
if isfield(data, 'fid') || (isfield(data, 'tri') && isfield(data, 'pnt'))
dtype = 'headshape';
elseif isfield(data, 'tet') && isfield(data, 'pnt')
dtype = 'mesh';
elseif ~strcmp(ft_voltype(data), 'unknown')
dtype = 'headmodel';
elseif ~strcmp(ft_senstype(data), 'unknown')
dtype = 'sens';
end
end
% determine the size of the "unit" sphere in the origin and the length of the axes
switch unit
case 'mm'
axmax = 150;
rbol = 5;
case 'cm'
axmax = 15;
rbol = 0.5;
case 'm'
axmax = 0.15;
rbol = 0.005;
otherwise
error('unknown units (%s)', unit);
end
% this is useful if the anatomy is from a non-human primate or rodent
axmax = axisscale*axmax;
rbol = axisscale*rbol;
if isfield(data, 'coordsys') && ~isempty(data.coordsys)
label = cell(3,1);
if length(data.coordsys)==3 && length(intersect(data.coordsys, 'rlasif'))==3
for i=1:3
switch data.coordsys(i)
case 'l'
label{i} = 'the left';
case 'r'
label{i} = 'the right';
case 'i'
label{i} = 'inferior';
case 's'
label{i} = 'superior';
case 'a'
label{i} = 'anterior';
case 'p'
label{i} = 'posterior';
otherwise
error('incorrect letter in the coordsys');
end % switch
end % for each of the three axes
elseif strcmpi(data.coordsys, 'itab') || strcmpi(data.coordsys, 'neuromag')
label{1} = 'the right';
label{2} = 'anterior';
label{3} = 'superior';
elseif strcmpi(data.coordsys, 'ctf') || strcmpi(data.coordsys, '4d') || strcmpi(data.coordsys, 'bti')
label{1} = 'anterior';
label{2} = 'the left';
label{3} = 'superior';
elseif strcmpi(data.coordsys, 'tal') || strcmpi(data.coordsys, 'mni') || strcmpi(data.coordsys, 'spm')
label{1} = 'the right';
label{2} = 'anterior';
label{3} = 'superior';
else
error('unsupported coordsys');
end
fprintf('The positive x-axis is pointing towards %s\n', label{1});
fprintf('The positive y-axis is pointing towards %s\n', label{2});
fprintf('The positive z-axis is pointing towards %s\n', label{3});
end
% create the labels that are to be plotted along the axes
if isfield(data, 'coordsys')
[labelx, labely, labelz] = xyz2label(data.coordsys);
else
[labelx, labely, labelz] = xyz2label('unknown');
end
% plot the geometrical object
% the plotting style depends on the data content
figure;
switch dtype
case 'volume'
funparam = [];
if isfield(data, 'anatomy')
funparam = data.anatomy;
elseif isfield(data, 'gray')
funparam = data.gray;
elseif isfield(data, 'white')
funparam = data.white;
elseif isfield(data, 'brick0')
funparam = data.brick0; % used for an atlas
elseif isfield(data, 'brick1')
funparam = data.brick1; % used for an atlas
else
% try to determine it automatically
fn = fieldnames(data);
for i=1:length(fn)
if isequal(size(data.(fn{i})), data.dim)
funparam = data.(fn{i});
break;
end
end
end
if isempty(funparam)
error('don''t know which volumetric parameter to plot');
end
% the volumetric data needs to be interpolated onto three orthogonal planes
% determine a resolution that is close to, or identical to the original resolution
[corner_vox, corner_head] = cornerpoints(data.dim, data.transform);
diagonal_head = norm(range(corner_head));
diagonal_vox = norm(range(corner_vox));
resolution = diagonal_head/diagonal_vox; % this is in units of "data.unit"
clear ft_plot_slice
ft_plot_ortho(funparam, 'transform', data.transform, 'resolution', resolution, 'style', 'intersect');
axis vis3d
view([110 36]);
case 'source'
if isfield(data, 'inside') && ~isfield(data, 'tri')
% only plot the source locations that are inside the volume conduction model
ft_plot_mesh(data.pos(data.inside, :));
else
ft_plot_mesh(data, 'edgecolor','none', 'facecolor', [0.6 0.8 0.6], 'facealpha', 0.6);
end
camlight;
case 'dip'
ft_plot_mesh(data, 'edgecolor','none', 'facecolor', 'none');
camlight;
case 'headshape'
ft_plot_headshape(data);
camlight;
case 'mesh'
ft_plot_mesh(data);
camlight;
case 'headmodel'
ft_plot_vol(data);
camlight;
case 'sens'
ft_plot_sens(data);
camlight;
case {'raw', 'timelock', 'freq', 'mvar', 'freqmvar', 'comp'}
% the data may contain a gradiometer or electrode definition
if isfield(data, 'grad')
ft_plot_sens(data.grad);
elseif isfield(data, 'elec')
ft_plot_sens(data.elec);
end
case 'unknown'
end % switch dtype{k}
% get the xyz-axes
xdat = [-axmax 0 0; axmax 0 0];
ydat = [0 -axmax 0; 0 axmax 0];
zdat = [0 0 -axmax; 0 0 axmax];
% get the xyz-axes dotted
xdatdot = (-axmax:(axmax/15):axmax);
xdatdot = xdatdot(1:floor(numel(xdatdot)/2)*2);
xdatdot = reshape(xdatdot, [2 numel(xdatdot)/2]);
n = size(xdatdot,2);
ydatdot = [zeros(2,n) xdatdot zeros(2,n)];
zdatdot = [zeros(2,2*n) xdatdot];
xdatdot = [xdatdot zeros(2,2*n)];
% plot axes
hl = line(xdat, ydat, zdat);
set(hl(1), 'linewidth', 1, 'color', 'r');
set(hl(2), 'linewidth', 1, 'color', 'g');
set(hl(3), 'linewidth', 1, 'color', 'b');
hld = line(xdatdot, ydatdot, zdatdot);
for k = 1:n
set(hld(k ), 'linewidth', 3, 'color', 'r');
set(hld(k+n*1), 'linewidth', 3, 'color', 'g');
set(hld(k+n*2), 'linewidth', 3, 'color', 'b');
end
% create the ball at the origin
[O.pnt, O.tri] = icosahedron42;
O.pnt = O.pnt.*rbol;
ft_plot_mesh(O, 'edgecolor', 'none');
% add the labels to the axis
text(xdat(1,1),ydat(1,1),zdat(1,1),labelx{1},'color','y','fontsize',15,'linewidth',2);
text(xdat(1,2),ydat(1,2),zdat(1,2),labely{1},'color','y','fontsize',15,'linewidth',2);
text(xdat(1,3),ydat(1,3),zdat(1,3),labelz{1},'color','y','fontsize',15,'linewidth',2);
text(xdat(2,1),ydat(2,1),zdat(2,1),labelx{2},'color','y','fontsize',15,'linewidth',2);
text(xdat(2,2),ydat(2,2),zdat(2,2),labely{2},'color','y','fontsize',15,'linewidth',2);
text(xdat(2,3),ydat(2,3),zdat(2,3),labelz{2},'color','y','fontsize',15,'linewidth',2);
if istrue(dointeractive),
if ~isfield(data, 'coordsys') || isempty(data.coordsys)
% default is yes
value = smartinput('Do you want to change the anatomical labels for the axes [Y, n]? ', 'y');
else
% default is no
value = smartinput('Do you want to change the anatomical labels for the axes [y, N]? ', 'n');
end
if strcmpi(value, 'n')
return
end
% interactively determine orientation
orientation = ' ';
while ~any(strcmp(orientation(1), {'r', 'l', 'a', 'p', 's', 'i'}))
orientation(1) = smartinput('What is the anatomical label for the positive X-axis [r, l, a, p, s, i]? ', '');
end
while ~any(strcmp(orientation(2), {'r', 'l', 'a', 'p', 's', 'i'}))
orientation(2) = smartinput('What is the anatomical label for the positive Y-axis [r, l, a, p, s, i]? ', '');
end
while ~any(strcmp(orientation(3), {'r', 'l', 'a', 'p', 's', 'i'}))
orientation(3) = smartinput('What is the anatomical label for the positive Z-axis [r, l, a, p, s, i]? ', '');
end
% interactively determine origin
origin = ' ';
while ~any(strcmp(origin, {'a', 'i', 'n'}))
origin = input('Is the origin of the coordinate system at the a(nterior commissure), i(nterauricular), n(ot a landmark)? ', 's');
end
if origin=='a' && strcmp(orientation, 'ras')
coordsys = 'spm';
elseif origin=='i' && strcmp(orientation, 'als')
coordsys = 'ctf';
elseif origin=='i' && strcmp(orientation, 'ras')
coordsys = 'neuromag'; % also used for itab
else
% just use the orientation
coordsys = orientation;
end
data.coordsys = coordsys;
end % if interactive
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to go from aplrsi to better interpretable format
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [labelx, labely, labelz] = xyz2label(str)
if ~isempty(str) && ~strcmp(str, 'unknown')
% the first part is important for the orientations
% the second part optionally contains information on the origin
strx = tokenize(str, '_');
switch lower(strx{1})
case {'ras' 'itab' 'neuromag' 'spm' 'mni'}
labelx = {'-X (left)' '+X (right)' };
labely = {'-Y (posterior)' '+Y (anterior)'};
labelz = {'-Z (inferior)' '+Z (superior)'};
case {'als' 'ctf' '4d', 'bti'}
labelx = {'-X (posterior)' '+X (anterior)'};
labely = {'-Y (right)' '+Y (left)'};
labelz = {'-Z (inferior)' '+Z (superior)'};
otherwise
error('unknown coordsys');
end
else
labelx = {'-X (unknown)' '+X (unknown)'};
labely = {'-Y (unknown)' '+Y (unknown)'};
labelz = {'-Z (unknown)' '+Z (unknown)'};
end
|
github
|
philippboehmsturm/antx-master
|
ft_selectdata_new.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_selectdata_new.m
| 19,469 |
utf_8
|
bf4cdb4378072b367c7cd985e5c4ecce
|
function [varargout] = ft_selectdata(cfg, varargin)
% FT_SELECTDATA makes a selection in the input data along specific data
% dimensions, such as channels, time, frequency, trials, etc. It can also
% be used to average the data along each of the specific dimensions.
%
% Use as
% [data] = ft_selectdata_new(cfg, data, ...)
% Copyright (C) 2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_selectdata_new.m 7123 2012-12-06 21:21:38Z roboos $
ft_defaults
ft_preamble help
% determine the characteristics of the input data
dtype = ft_datatype(varargin{1});
for i=2:length(varargin)
% ensure that all subsequent inputs are of the same type
ok = ft_datatype(varargin{i}, dtype);
if ~ok, error('input data should be of the same datatype'); end
end
cfg = ft_checkconfig(cfg, 'renamed', {'toilim' 'latency'});
if strcmp(dtype, 'raw')
% use selfromraw
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.latency = ft_getopt(cfg, 'latency', 'all');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
for i=1:length(varargin)
varargin{i} = selfromraw(varargin{i}, 'rpt', cfg.trials, 'chan', cfg.channel, 'latency', cfg.latency);
end
else
cfg.trials = ft_getopt(cfg, 'trials', 'all');
if length(varargin)>1 && ~isequal(cfg.trials, 'all')
error('it is ambiguous to a subselection of trials while concatenating data')
end
hastime = isfield(varargin{1}, 'time');
hasfreq = isfield(varargin{1}, 'freq');
hasdimord = ~all(cellfun(@isempty, regexp(fieldnames(varargin{1}), '.*dimord')));
avgoverchan = istrue(ft_getopt(cfg, 'avgoverchan', false));
avgoverfreq = istrue(ft_getopt(cfg, 'avgoverfreq', false));
avgovertime = istrue(ft_getopt(cfg, 'avgovertime', false));
avgoverrpt = istrue(ft_getopt(cfg, 'avgoverrpt', false));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PART 2:
% ensure that the cfg is fully contained in the data and consistent over all inputs
% get the selection along each of the dimensions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(cfg, 'parameter') && isfield(varargin{1}, [cfg.parameter 'dimord'])
dimord = [cfg.parameter 'dimord'];
elseif isfield(varargin{1}, 'dimord')
dimord = varargin{1}.dimord;
end
dimtok = tokenize(dimord, '_');
dimsiz = nan(size(dimtok));
dimfields = cell(size(dimtok));
for i=1:numel(dimtok)
% this switch-list is consistent with fixdimord
switch dimtok{i}
case 'time'
dimsiz(i) = length(varargin{1}.time);
dimfields{i} = 'time';
case 'freq'
dimsiz(i) = length(varargin{1}.freq);
dimfields{i} = 'freq';
case 'chan'
dimsiz(i) = length(varargin{1}.label);
dimfields{i} = 'label';
case 'chancmb'
dimsiz(i) = size(varargin{1}.labelcmb,1);
dimfields{i} = 'labelcmb';
case 'pos'
dimsiz(i) = size(varargin{1}.pos,1);
dimfields{i} = 'pos';
case 'comp'
dimsiz(i) = length(varargin{1}.label);
dimfields{i} = 'label';
case 'subj'
% the number of elements along this dimension is implicit
dimsiz(i) = nan;
dimfields{i} = 'implicit';
case 'rpt'
% the number of elements along this dimension is implicit
dimsiz(i) = nan;
dimfields{i} = 'implicit';
case 'rpttap'
% the number of elements along this dimension is implicit
dimsiz(i) = nan;
dimfields{i} = 'implicit';
case 'refchan'
error('FIXME');
case 'voxel'
error('FIXME');
case 'ori'
error('FIXME');
otherwise
% try to guess the size from the corresponding field
if isfield(varargin{1}, dimtok{i})
siz = varargin{1}.(dimtok{i});
if length(siz)==2 && any(siz==1)
dimsiz(i) = prod(siz);
dimfields{i} = dimtok{i};
end
end
end % switch
end % for dimtok
dimfields{end+1} = 'dimord'; % also keep the dimord
% deal with the data dimensions whose size is only implicitly represented
if any(strcmp(dimfields, 'implicit'))
fn = fieldnames(varargin{1})';
sel = false(size(fn));
for i=1:numel(fn)
if isequalwithoutnans(size(varargin{1}.(fn{i})), dimsiz)
warning('using the "%s" field to determine the size along the unknown dimensions', fn{i});
% update the size of all dimensions
dimsiz = size(varargin{1}.(fn{i}));
% update the fieldname of each dimension
dimfields(strcmp(dimfields, 'implicit')) = dimtok(strcmp(dimfields, 'implicit'));
break
end
end
if any(strcmp(dimfields, 'implicit'))
% it failed
error('could not determine the size of the implicit "%s" dimension', dimfields{strcmp(dimfields, 'implicit')});
end
end
fn = fieldnames(varargin{1})';
sel = false(size(fn));
for i=1:numel(fn)
sel(i) = isequal(size(varargin{1}.(fn{i})), dimsiz);
end
% select the fields that represent the data
datfields = fn(sel);
switch dtype
% this switch-list is consistent with ft_datatype
case 'timelock'
for i=1:numel(varargin)
% trim the selection to all inputs
[selchan, cfg] = getselection_chan(cfg, varargin{i});
[seltime, cfg] = getselection_time(cfg, varargin{i});
[selrpt, cfg] = getselection_rpt (cfg, varargin{i}, 'datfields', datfields);
end % varargin
for i=1:numel(varargin)
% get the selection from all inputs
[selchan, cfg] = getselection_chan(cfg, varargin{i});
[seltime, cfg] = getselection_time(cfg, varargin{i});
[selrpt, cfg] = getselection_rpt (cfg, varargin{i}, 'datfields', datfields);
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'chan')), selchan, avgoverchan, datfields);
varargin{i} = makeselection_chan(varargin{i}, selchan, avgoverchan); % update the label field
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'time')), seltime, avgovertime, datfields);
varargin{i} = makeselection_time(varargin{i}, seltime, avgovertime); % update the time field
if ~any(isnan(selrpt))
% FIXME could also be subject
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'rpt')), selrpt, avgoverrpt, datfields);
end
end % varargin
case 'freq'
for i=1:numel(varargin)
% trim the selection to all inputs
[selchan, cfg] = getselection_chan(cfg, varargin{i});
[selfreq, cfg] = getselection_freq(cfg, varargin{i});
if hastime
[seltime, cfg] = getselection_time(cfg, varargin{i});
end
end % varargin
for i=1:numel(varargin)
% get the selection from all inputs
[selchan, cfg] = getselection_chan(cfg, varargin{i});
[selfreq, cfg] = getselection_freq(cfg, varargin{i});
[selrpt, cfg] = getselection_rpt (cfg, varargin{i});
if hastime
[seltime, cfg] = getselection_time(cfg, varargin{i});
end
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'chan')), selchan, avgoverchan, datfields);
varargin{i} = makeselection_chan(varargin{i}, selchan, avgoverchan); % update the label field
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'freq')), selfreq, avgoverfreq, datfields);
varargin{i} = makeselection_freq(varargin{i}, selfreq, avgoverfreq); % update the freq field
if ~any(isnan(selrpt))
% FIXME could also be rpttap
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'rpt')), selfreq, avgoverrpt, datfields);
end
if hastime
varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'time')), seltime, avgovertime, datfields);
varargin{i} = makeselection_time(varargin{i}, seltime, avgovertime); % update the time field
end
end % varargin
case 'comp'
for i=1:numel(varargin)
% trim the selection to all inputs
[selchan, cfg] = getselection_chan(cfg, varargin{i});
end % varargin
keyboard
case 'raw'
for i=1:numel(varargin)
% trim the selection to all inputs
[selchan, cfg] = getselection_chan(cfg, varargin{i});
end % varargin
keyboard
case 'freqmvar'
error('FIXME');
case 'mvar'
error('FIXME');
case 'spike'
error('FIXME');
case 'volume'
error('FIXME');
case 'source'
error('FIXME');
case 'dip'
error('FIXME');
case 'chan'
% this results from avgovertime/avgoverfreq after timelockstatistics or freqstatistics
error('FIXME');
otherwise
% try to get the selection based on the field name
seldim = cell(size(dimtok));
for j=1:numel(seldim)
seldim(j) = feval(['getselection_' dimtok{j}], cfg, varargin{i});
end
end % switch dtype
% update the dimord
if avgovertime
dimtok = setdiff(dimtok, 'time');
end
if avgoverfreq
dimtok = setdiff(dimtok, 'freq');
end
if avgoverrpt
% FIXME could also be rpttap or subject
dimtok = setdiff(dimtok, 'rpt');
end
for i=1:numel(varargin)
varargin{i}.dimord = sprintf('%s_', dimtok{:});
varargin{i}.dimord = varargin{i}.dimord(1:end-1); % remove the last '_'
end
% remove all fields from the data that do not pertain to the selection
for i=1:numel(varargin)
varargin{i} = keepfields(varargin{i}, [datfields dimfields {'cfg' 'grad'}]);
end
end % if raw or something else
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PART 3:
% if desired, concatenate over repetitions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin>2 && nargout==2
% concatenate all input data into a single structure
error('FIXME');
else
% no reason to concatenate
varargout = varargin;
varargout{end+1} = cfg;
end
end % function ft_selectdata
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = keepfields(data, fn)
fn = setdiff(fieldnames(data), fn);
for i=1:numel(fn)
data = rmfield(data, fn{i});
end
end % function keepfields
function data = makeselection(data, seldim, selindx, avgoverdim, datfields)
if numel(seldim) > 1
for k = 1:numel(seldim)
data = makeselection(data, seldim(k), selindx, datfields);
end
end
for i=1:numel(datfields)
if ~isnan(selindx)
% the value NaN indicates that it is not needed to make a selection, rather take all values
switch seldim
case 1
data.(datfields{i}) = data.(datfields{i})(selindx,:,:,:,:,:);
case 2
data.(datfields{i}) = data.(datfields{i})(:,selindx,:,:,:,:);
case 3
data.(datfields{i}) = data.(datfields{i})(:,:,selindx,:,:,:);
case 4
data.(datfields{i}) = data.(datfields{i})(:,:,:,selindx,:,:);
case 5
data.(datfields{i}) = data.(datfields{i})(:,:,:,:,selindx,:);
case 6
data.(datfields{i}) = data.(datfields{i})(:,:,:,:,:,selindx);
otherwise
error('unsupported dimension (%d) for making a selection for %s', seldim, datfields{i});
end % switch
end
if avgoverdim
data.(datfields{i}) = mean(data.(datfields{i}), seldim);
end
end % for datfields
end % function makeselection
function data = makeselection_chan(data, selchan, avgoverchan)
if avgoverchan && all(isnan(selchan))
data.label = sprintf('%s+', data.label{:}); % concatenate all channel labels
data.label = data.label(1:end-1); % remove the last '+'
elseif avgoverchan && ~any(isnan(selchan))
data.label = sprintf('%s+', data.label{selchan}); % concatenate all channel labels
data.label = data.label(1:end-1); % remove the last '+'
elseif ~isnan(selchan)
data.label = data.label(selchan);
end
end % function makeselection_chan
function data = makeselection_freq(data, selfreq, avgoverfreq)
if avgoverfreq
data = rmfield(data, 'freq');
elseif ~isnan(selfreq)
data.freq = data.time(selfreq);
end
end % function makeselection_freq
function data = makeselection_time(data, seltime, avgovertime)
if avgovertime
data = rmfield(data, 'time');
elseif ~isnan(seltime)
data.time = data.time(seltime);
end
end % function makeselection_time
function [chanindx, cfg] = getselection_chan(cfg, data)
% this return value specifies that no selection was specified
chanindx = nan;
if isfield(cfg, 'channel')
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
end
if isequal(chanindx, 1:length(data.label))
% the cfg was updated, but no selection is needed for the data
chanindx = nan;
end
end % function getselection_chan
function [timeindx, cfg] = getselection_time(cfg, data)
% possible specifications are
% cfg.latency = value -> can be 'all'
% cfg.latency = [beg end]
assert(isfield(data, 'time'), 'the input data should have a time axis');
% this return value specifies that no selection was specified
timeindx = nan;
if isfield(cfg, 'latency')
% deal with string selection
if ischar(cfg.latency)
if strcmp(cfg.latency, 'all')
cfg.latency = [min(data.time) max(data.time)];
else
error('incorrect specification of cfg.latency');
end
end
% deal with numeric selection
if numel(cfg.latency)==1
% this single value should be within the time axis of each input data structure
tbin = nearest(data.time, cfg.latency, true, true);
cfg.latency = data.time(tbin);
timeindx = tbin;
elseif numel(cfg.latency)==2
% the [min max] range can be specifed with +inf or -inf, but should
% at least partially overlap with the time axis of the input data
mintime = min(data.time);
maxtime = max(data.time);
if all(cfg.latency<mintime) || all(cfg.latency>maxtime)
error('the selected time range falls outside the time axis in the data');
end
tbeg = nearest(data.time, cfg.latency(1), false, false);
tend = nearest(data.time, cfg.latency(2), false, false);
cfg.latency = data.time([tbeg tend]);
timeindx = tbeg:tend;
elseif size(cfg.latency,2)==2
% this may be used for specification of the computation, not for data selection
else
error('incorrect specification of cfg.latency');
end
end % if cfg.latency
% % Note: cfg.toilim handling removed as it was renamed to cfg.latency
if isequal(timeindx, 1:length(data.time))
% the cfg was updated, but no selection is needed for the data
timeindx = nan;
end
end % function getselection_time
function [freqindx, cfg] = getselection_freq(cfg, data)
% possible specifications are
% cfg.frequency = value -> can be 'all'
% cfg.frequency = [beg end] -> this is less common, preferred is to use foilim
% cfg.foilim = [beg end]
assert(isfield(data, 'freq'), 'the input data should have a frequency axis');
% this return value specifies that no selection was specified
freqindx = nan;
if isfield(cfg, 'frequency')
% deal with string selection
if ischar(cfg.frequency)
if strcmp(cfg.frequency, 'all')
cfg.frequency = [min(data.freq) max(data.freq)];
else
error('incorrect specification of cfg.frequency');
end
end
% deal with numeric selection
if numel(cfg.frequency)==1
% this single value should be within the time axis of each input data structure
fbin = nearest(data.freq, cfg.frequency, true, true);
cfg.frequency = data.freq(fbin);
freqindx = fbin;
elseif numel(cfg.frequency)==2
% the [min max] range can be specifed with +inf or -inf, but should
% at least partially overlap with the freq axis of the input data
minfreq = min(data.freq);
maxfreq = max(data.freq);
if all(cfg.frequency<minfreq) || all(cfg.frequency>maxfreq)
error('the selected range falls outside the time axis in the data');
end
fbeg = nearest(data.freq, cfg.frequency(1), false, false);
fend = nearest(data.freq, cfg.frequency(2), false, false);
cfg.frequency = data.freq([fbeg fend]);
freqindx = fbeg:fend;
elseif size(cfg.frequency,2)==2
% this may be used for specification of the computation, not for data selection
else
error('incorrect specification of cfg.frequency');
end
end % if cfg.frequency
if isfield(cfg, 'foilim')
if ~ischar(cfg.foilim) && numel(cfg.foilim)==2
% the [min max] range can be specifed with +inf or -inf, but should
% at least partially overlap with the time axis of the input data
minfreq = min(data.freq);
maxfreq = max(data.freq);
if all(cfg.foilim<minfreq) || all(cfg.foilim>maxfreq)
error('the selected range falls outside the frequency axis in the data');
end
fbin = nan(1,2);
fbin(1) = nearest(data.freq, cfg.foilim(1), false, false);
fbin(2) = nearest(data.freq, cfg.foilim(2), false, false);
cfg.foilim = data.freq(fbin);
else
error('incorrect specification of cfg.foilim');
end
end % cfg.foilim
if isequal(freqindx, 1:length(data.freq))
% the cfg was updated, but no selection is needed for the data
freqindx = nan;
end
end % function getselection_freq
function [rptindx, cfg] = getselection_rpt(cfg, data, varargin)
% this should deal with cfg.trials
datfields = ft_getopt(varargin, 'datfields');
if isfield(cfg, 'trials') && ~isequal(cfg.trials, 'all') && ~isempty(datfields)
dimtok = tokenize(data.dimord, '_');
rptdim = [];
if isempty(rptdim)
rptdim = find(strcmp(dimtok, 'rpt'));
end
if isempty(rptdim)
rptdim = find(strcmp(dimtok, 'rpttap'));
end
if isempty(rptdim)
rptdim = find(strcmp(dimtok, 'subj'));
end
if isempty(rptdim)
% this return value specifies that no selection was specified
rptindx = nan;
return
else
rptsiz = size(data.(datfields{1}), rptdim);
rptindx = ft_getopt(cfg, 'trials');
rptindx = unique(sort(rptindx));
if rptindx(1)<1
error('cannot select rpt/subj/rpttap smaller than 1');
elseif rptindx(end)>rptsiz
error('cannot select rpt/subj/rpttap larger than the number of repetitions in the data');
end
cfg.trials = rptindx;
return
end
else
rptindx = nan;
end % if isfield cfg.trials
end % function getselection_rpt
function ok = isequalwithoutnans(a, b)
if numel(a)~=numel(b)
ok = false;
else
c = ~isnan(a(:)) & ~isnan(b(:));
ok = isequal(a(c), b(c));
end
end % function isequalwithoutnans
|
github
|
philippboehmsturm/antx-master
|
ft_hastoolbox.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_hastoolbox.m
| 21,701 |
utf_8
|
04ca07a96e26de4cd2386496621c8d96
|
function [status] = ft_hastoolbox(toolbox, autoadd, silent)
% FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally
% it will try to determine the path to the toolbox and install it
% automatically.
%
% Use as
% [status] = ft_hastoolbox(toolbox, autoadd, silent)
%
% autoadd = 0 means that it will not be added
% autoadd = 1 means that give an error if it cannot be added
% autoadd = 2 means that give a warning if it cannot be added
% autoadd = 3 means that it remains silent if it cannot be added
%
% silent = 0 means that it will give some feedback about adding the toolbox
% silent = 1 means that it will not give feedback
% Copyright (C) 2005-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_hastoolbox.m 7171 2012-12-13 11:50:47Z roboos $
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
% persistent previous previouspath
%
% if ~isequal(previouspath, path)
% previous = [];
% end
%
% if isempty(previous)
% previous = struct;
% elseif isfield(previous, fixname(toolbox))
% status = previous.(fixname(toolbox));
% return
% end
% this points the user to the website where he/she can download the toolbox
url = {
'AFNI' 'see http://afni.nimh.nih.gov'
'DSS' 'see http://www.cis.hut.fi/projects/dss'
'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab'
'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox'
'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm'
'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd'
'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com'
'BIOSIG' 'see http://biosig.sourceforge.net'
'EEG' 'see http://eeg.sourceforge.net'
'EEGSF' 'see http://eeg.sourceforge.net' % alternative name
'MRI' 'see http://eeg.sourceforge.net' % alternative name
'NEUROSHARE' 'see http://www.neuroshare.org'
'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter'
'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde'
'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead'
'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm'
'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld'
'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld'
'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth'
'4D-VERSION' 'contact Christian Wienbruch'
'SIGNAL' 'see http://www.mathworks.com/products/signal'
'OPTIM' 'see http://www.mathworks.com/products/optim'
'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES
'SPLINES' 'see http://www.mathworks.com/products/splines'
'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/'
'COMPILER' 'see http://www.mathworks.com/products/compiler'
'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica'
'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm'
'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PREPROC' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'FORWARD' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'INVERSE' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'SPECEST' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'REALTIME' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'SPIKE' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'CONNECTIVITY' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PEER' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne'
'BCI2000' 'see http://bci2000.org'
'NLXNETCOM' 'see http://www.neuralynx.com'
'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external'
'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php'
'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter'
'BEMCP' 'contact Christophe Phillips'
'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435'
'PRTOOLS' 'see http://www.prtools.org'
'ITAB' 'contact Stefania Della Penna'
'BSMART' 'see http://www.brain-smart.org'
'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer'
'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki'
'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page'
'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html'
'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS'
'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti'
'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0'
'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab'
'BCT' 'see http://www.brain-connectivity-toolbox.net/'
'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga'
'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI'
'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre'
'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177'
'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector'
'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang'
'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272'
'IBTB' 'see http://www.ibtb.org'
'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso'
'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework'
'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip'
};
if nargin<2
% default is not to add the path automatically
autoadd = 0;
end
if nargin<3
% default is not to be silent
silent = 0;
end
% determine whether the toolbox is installed
toolbox = upper(toolbox);
% set fieldtrip trunk path, used for determining ft-subdirs are on path
fttrunkpath = unixpath(fileparts(which('ft_defaults')));
switch toolbox
case 'AFNI'
status = (exist('BrikLoad') && exist('BrikInfo'));
case 'DSS'
status = exist('denss', 'file') && exist('dss_create_state', 'file');
case 'EEGLAB'
status = exist('runica', 'file');
case 'NWAY'
status = exist('parafac', 'file');
case 'SPM'
status = exist('spm.m'); % any version of SPM is fine
case 'SPM99'
status = exist('spm.m') && strcmp(spm('ver'),'SPM99');
case 'SPM2'
status = exist('spm.m') && strcmp(spm('ver'),'SPM2');
case 'SPM5'
status = exist('spm.m') && strcmp(spm('ver'),'SPM5');
case 'SPM8'
status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4);
case 'SPM12'
status = exist('spm.m') && strncmp(spm('ver'),'SPM12', 5);
case 'MEG-PD'
status = (exist('rawdata') && exist('channames'));
case 'MEG-CALC'
status = (exist('megmodel') && exist('megfield') && exist('megtrans'));
case 'BIOSIG'
status = (exist('sopen') && exist('sread'));
case 'EEG'
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'EEGSF' % alternative name
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'MRI' % other functions in the mri section
status = (exist('avw_hdr_read') && exist('avw_img_read'));
case 'NEUROSHARE'
status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData'));
case 'BESA'
status = (exist('readBESAtfc') && exist('readBESAswf'));
case 'EEPROBE'
status = (exist('read_eep_avr') && exist('read_eep_cnt'));
case 'YOKOGAWA'
status = hasyokogawa('16bitBeta6');
case 'YOKOGAWA12BITBETA3'
status = hasyokogawa('12bitBeta3');
case 'YOKOGAWA16BITBETA3'
status = hasyokogawa('16bitBeta3');
case 'YOKOGAWA16BITBETA6'
status = hasyokogawa('16bitBeta6');
case 'YOKOGAWA_MEG_READER'
status = hasyokogawa('1.4');
case 'BEOWULF'
status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf'));
case 'MENTAT'
status = (exist('pcompile') && exist('pfor') && exist('peval'));
case 'SON2'
status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel'));
case '4D-VERSION'
status = (exist('read4d') && exist('read4dhdr'));
case {'STATS', 'STATISTICS'}
status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license
case 'SIGNAL'
status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license
case 'IMAGE'
status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license
case {'DCT', 'DISTCOMP'}
status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license
case 'COMPILER'
status = license('checkout', 'compiler'); % also check the availability of a toolbox license
case 'FASTICA'
status = exist('fpica', 'file');
case 'BRAINSTORM'
status = exist('bem_xfer');
case 'DENOISE'
status = (exist('tsr', 'file') && exist('sns', 'file'));
case 'CTF'
status = (exist('getCTFBalanceCoefs') && exist('getCTFdata'));
case 'BCI2000'
status = exist('load_bcidat');
case 'NLXNETCOM'
status = (exist('MatlabNetComClient', 'file') && exist('NlxConnectToServer', 'file') && exist('NlxGetNewCSCData', 'file'));
case 'DIPOLI'
status = exist('dipoli.maci', 'file');
case 'MNE'
status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file'));
case 'TCP_UDP_IP'
status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file'));
case 'BEMCP'
status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file'));
case 'OPENMEEG'
status = exist('om_save_tri.m', 'file');
case 'PRTOOLS'
status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file'));
case 'ITAB'
status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file'));
case 'BSMART'
status = exist('bsmart');
case 'FREESURFER'
status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file');
case 'FNS'
status = exist('elecsfwd', 'file');
case 'SIMBIO'
status = exist('calc_stiff_matrix_val', 'file') && exist('sb_transfer', 'file');
case 'VGRID'
status = exist('vgrid.m', 'file');
case 'GIFTI'
status = exist('gifti', 'file');
case 'XML4MAT'
status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file');
case 'SQDPROJECT'
status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file');
case 'BCT'
status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file');
case 'CCA'
status = exist('ccabss.m', 'file');
case 'EGI_MFF'
status = exist('mff_getObject.m', 'file') && exist('mff_getSummaryInfo.m', 'file');
case 'TOOLBOX_GRAPH'
status = exist('toolbox_graph');
case 'NETCDF'
status = exist('netcdf');
case 'MYSQL'
status = exist(['mysql.' mexext], 'file'); % this only consists of a single mex file
case 'ISO2MESH'
status = exist('vol2surf.m', 'file') && exist('qmeshcut.m', 'file');
case 'QSUB'
status = exist('qsubfeval.m', 'file') && exist('qsubcellfun.m', 'file');
case 'ENGINE'
status = exist('enginefeval.m', 'file') && exist('enginecellfun.m', 'file');
case 'DATAHASH'
status = exist('DataHash.m', 'file');
case 'IBTB'
status = exist('make_ibtb.m', 'file') && exist('binr.m', 'file');
case 'ICASSO'
status = exist('icassoEst.m', 'file');
case 'XUNIT'
status = exist('initTestSuite.m', 'file') && exist('runtests.m', 'file');
case 'PLEXON'
status = exist('plx_adchan_gains.m', 'file') && exist('mexPlex');
% the following are fieldtrip modules/toolboxes
case 'FILEIO'
status = (exist('ft_read_header', 'file') && exist('ft_read_data', 'file') && exist('ft_read_event', 'file') && exist('ft_read_sens', 'file'));
case 'FORWARD'
status = (exist('ft_compute_leadfield', 'file') && exist('ft_prepare_vol_sens', 'file'));
case 'PLOTTING'
status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file'));
case 'PEER'
status = exist('peerslave', 'file') && exist('peermaster', 'file');
case 'CONNECTIVITY'
status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file');
case 'SPIKE'
status = exist('ft_spiketriggeredaverage.m', 'file') && exist('ft_spiketriggeredspectrum.m', 'file');
% these were missing, added them using the below style, see bug 1804 - roevdmei
case 'INVERSE'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/inverse'], 'once')); % INVERSE is not added above, consider doing it there -roevdmei
case 'REALTIME'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/realtime'], 'once')); % REALTIME is not added above, consider doing it there -roevdmei
case 'SPECEST'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/specest'], 'once')); % SPECEST is not added above, consider doing it there -roevdmei
case 'PREPROC'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc'], 'once')); % PREPROC is not added above, consider doing it there -roevdmei
% the following are not proper toolboxes, but only subdirectories in the fieldtrip toolbox
% these are added in ft_defaults and are specified with unix-style forward slashes
case 'COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/compat'], 'once'));
case 'STATFUN'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/statfun'], 'once'));
case 'TRIALFUN'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/trialfun'], 'once'));
case 'UTILITIES/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/utilities/compat'], 'once'));
case 'FILEIO/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/fileio/compat'], 'once'));
case 'PREPROC/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc/compat'], 'once'));
case 'FORWARD/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/forward/compat'], 'once'));
case 'PLOTTING/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/plotting/compat'], 'once'));
case 'TEMPLATE/LAYOUT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/layout'], 'once'));
case 'TEMPLATE/ANATOMY'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/anatomy'], 'once'));
case 'TEMPLATE/HEADMODEL'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/headmodel'], 'once'));
case 'TEMPLATE/ELECTRODE'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/electrode'], 'once'));
case 'TEMPLATE/NEIGHBOURS'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/neighbours'], 'once'));
case 'TEMPLATE/SOURCEMODEL'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/sourcemodel'], 'once'));
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
status = 0;
end
% it should be a boolean value
status = (status~=0);
% try to determine the path of the requested toolbox
if autoadd>0 && ~status
% for core fieldtrip modules
prefix = fileparts(which('ft_defaults'));
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for external fieldtrip modules
prefix = fullfile(fileparts(which('ft_defaults')), 'external');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for contributed fieldtrip extensions
prefix = fullfile(fileparts(which('ft_defaults')), 'contrib');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for linux computers in the Donders Centre for Cognitive Neuroimaging
prefix = '/home/common/matlab';
if ~status && isunix
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the Donders Centre for Cognitive Neuroimaging
prefix = 'h:\common\matlab';
if ~status && ispc
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% use the matlab subdirectory in your homedirectory, this works on linux and mac
prefix = fullfile(getenv('HOME'), 'matlab');
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
if ~status
% the toolbox is not on the path and cannot be added
sel = find(strcmp(url(:,1), toolbox));
if ~isempty(sel)
msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2});
else
msg = sprintf('the %s toolbox is not installed', toolbox);
end
if autoadd==1
error(msg);
elseif autoadd==2
warning(msg);
else
% fail silently
end
end
end
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
if status
previous.(fixname(toolbox)) = status;
end
% remember the previous path, allows us to determine on the next call
% whether the path has been modified outise of this function
previouspath = path;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = myaddpath(toolbox, silent)
if isdeployed
warning('cannot change path settings for %s in a compiled application', toolbox);
elseif exist(toolbox, 'dir')
if ~silent,
ws = warning('backtrace', 'off');
warning('adding %s toolbox to your Matlab path', toolbox);
warning(ws); % return to the previous warning level
end
addpath(toolbox);
status = 1;
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function path = unixpath(path)
path(path=='\') = '/'; % replace backward slashes with forward slashes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = hasfunction(funname, toolbox)
try
% call the function without any input arguments, which probably is inapropriate
feval(funname);
% it might be that the function without any input already works fine
status = true;
catch
% either the function returned an error, or the function is not available
% availability is influenced by the function being present and by having a
% license for the function, i.e. in a concurrent licensing setting it might
% be that all toolbox licenses are in use
m = lasterror;
if strcmp(m.identifier, 'MATLAB:license:checkouterror')
if nargin>1
warning('the %s toolbox is available, but you don''t have a license for it', toolbox);
else
warning('the function ''%s'' is available, but you don''t have a license for it', funname);
end
status = false;
elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction')
status = false;
else
% the function seems to be available and it gave an unknown error,
% which is to be expected with inappropriate input arguments
status = true;
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_checkdata.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_checkdata.m
| 68,446 |
utf_8
|
d4ad62d9da37d3069bf84c4d0d5e603a
|
function [data] = ft_checkdata(data, varargin)
% FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether
% the type of data strucure corresponds with the required data. If neccessary
% and possible, this function will adjust the data structure to the input
% requirements (e.g. change dimord, average over trials, convert inside from
% index into logical).
%
% If the input data does NOT correspond to the requirements, this function
% is supposed to give a elaborate warning message and if applicable point
% the user to external documentation (link to website).
%
% Use as
% [data] = ft_checkdata(data, ...)
%
% Optional input arguments should be specified as key-value pairs and can include
% feedback = yes, no
% datatype = raw, freq, timelock, comp, spike, source, dip, volume, segmentation, parcellation
% dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos
% senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode
% inside = logical, index
% ismeg = yes, no
% hastrials = yes, no
% hasunits = yes, no
% hassampleinfo = yes, no, ifmakessense (only applies to raw data)
% hascumtapcnt = yes, no (only applies to freq data)
% hasdim = yes, no
% hasdof = yes, no
% cmbrepresentation = sparse, full (applies to covariance and cross-spectral density)
% fsample = sampling frequency to use to go from SPIKE to RAW representation
% segmentationstyle = indexed, probabilistic (only applies to segmentation)
% parcellationstyle = indexed, probabilistic (only applies to parcellation)
% hasbrain = yes, no (only applies to segmentation)
%
% For some options you can specify multiple values, e.g.
% [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign
% [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis
% Copyright (C) 2007-2012, Robert Oostenveld
% Copyright (C) 2010-2012, Martin Vinck
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_checkdata.m 7393 2013-01-23 14:33:27Z jorhor $
% in case of an error this function could use dbstack for more detailled
% user feedback
%
% this function should replace/encapsulate
% fixdimord
% fixinside
% fixprecision
% fixvolume
% data2raw
% raw2data
% grid2transform
% transform2grid
% fourier2crsspctrm
% freq2cumtapcnt
% sensortype
% time2offset
% offset2time
% fixsens -> this is kept a separate function because it should also be
% called from other modules
%
% other potential uses for this function:
% time -> offset in freqanalysis
% average over trials
% csd as matrix
% get the optional input arguments
feedback = ft_getopt(varargin, 'feedback', 'no');
dtype = ft_getopt(varargin, 'datatype'); % should not conflict with the ft_datatype function
dimord = ft_getopt(varargin, 'dimord');
stype = ft_getopt(varargin, 'senstype'); % senstype is a function name which should not be masked
ismeg = ft_getopt(varargin, 'ismeg');
inside = ft_getopt(varargin, 'inside'); % can be 'logical' or 'index'
hastrials = ft_getopt(varargin, 'hastrials');
hasunits = ft_getopt(varargin, 'hasunits');
hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense');
hasdimord = ft_getopt(varargin, 'hasdimord', 'no');
hasdim = ft_getopt(varargin, 'hasdim');
hascumtapcnt = ft_getopt(varargin, 'hascumtapcnt');
hasdof = ft_getopt(varargin, 'hasdof', 'no');
haspow = ft_getopt(varargin, 'haspow', 'no');
cmbrepresentation = ft_getopt(varargin, 'cmbrepresentation');
channelcmb = ft_getopt(varargin, 'channelcmb');
sourcedimord = ft_getopt(varargin, 'sourcedimord');
sourcerepresentation = ft_getopt(varargin, 'sourcerepresentation');
fsample = ft_getopt(varargin, 'fsample');
segmentationstyle = ft_getopt(varargin, 'segmentationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function
parcellationstyle = ft_getopt(varargin, 'parcellationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function
hasbrain = ft_getopt(varargin, 'hasbrain');
% check whether people are using deprecated stuff
depHastrialdef = ft_getopt(varargin, 'hastrialdef');
if (~isempty(depHastrialdef))
warning_once('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead');
hassampleinfo = depHastrialdef;
end
if (~isempty(ft_getopt(varargin, 'hasoffset')))
warning_once('ft_checkdata option ''hasoffset'' has been removed and will be ignored');
end
% determine the type of input data
% this can be raw, freq, timelock, comp, spike, source, volume, dip
israw = ft_datatype(data, 'raw');
isfreq = ft_datatype(data, 'freq');
istimelock = ft_datatype(data, 'timelock');
iscomp = ft_datatype(data, 'comp');
isspike = ft_datatype(data, 'spike');
isvolume = ft_datatype(data, 'volume');
issegmentation = ft_datatype(data, 'segmentation');
isparcellation = ft_datatype(data, 'parcellation');
issource = ft_datatype(data, 'source');
isdip = ft_datatype(data, 'dip');
ismvar = ft_datatype(data, 'mvar');
isfreqmvar = ft_datatype(data, 'freqmvar');
ischan = ft_datatype(data, 'chan');
% FIXME use the istrue function on ismeg and hasxxx options
if ~isequal(feedback, 'no')
if iscomp
% it can be comp and raw at the same time, therefore this has to go first
ncomp = length(data.label);
nchan = length(data.topolabel);
fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan);
elseif israw
nchan = length(data.label);
ntrial = length(data.trial);
fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial);
elseif istimelock
nchan = length(data.label);
ntime = length(data.time);
fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime);
elseif isfreq
nchan = length(data.label);
nfreq = length(data.freq);
if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end
fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime);
elseif isspike
nchan = length(data.label);
fprintf('the input is spike data with %d channels\n', nchan);
elseif isvolume
if issegmentation
subtype = 'segmented volume';
else
subtype = 'volume';
end
fprintf('the input is %s data with dimensions [%d %d %d]\n', subtype, data.dim(1), data.dim(2), data.dim(3));
clear subtype
elseif issource
nsource = size(data.pos, 1);
if isparcellation
subtype = 'parcellated source';
else
subtype = 'source';
end
if isfield(data, 'dim')
fprintf('the input is %s data with %d positions on a [%d %d %d] grid\n', subtype, nsource, data.dim(1), data.dim(2), data.dim(3));
elseif isfield(data, 'tri')
fprintf('the input is %s data with %d vertex positions and %d triangles\n', subtype, nsource, size(data.tri, 1));
else
fprintf('the input is %s data with %d positions\n', subtype, nsource);
end
clear subtype
elseif isdip
fprintf('the input is dipole data\n');
elseif ismvar
fprintf('the input is mvar data\n');
elseif isfreqmvar
fprintf('the input is freqmvar data\n');
elseif ischan
nchan = length(data.label);
fprintf('the input is chan data\n');
end
end % give feedback
if issource && isvolume
% it should be either one or the other: the choice here is to
% represent it as volume description since that is simpler to handle
% the conversion is done by remove the grid positions
data = rmfield(data, 'pos');
issource = false;
end
% the ft_datatype_XXX functions ensures the consistency of the XXX datatype
% and provides a detailed description of the dataformat and its history
if isfreq
data = ft_datatype_freq(data);
elseif istimelock
data = ft_datatype_timelock(data);
elseif isspike
data = ft_datatype_spike(data);
elseif iscomp % this should go before israw
data = ft_datatype_comp(data, 'hassampleinfo', hassampleinfo);
elseif israw
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
elseif issegmentation % this should go before isvolume
data = ft_datatype_segmentation(data, 'segmentationstyle', segmentationstyle, 'hasbrain', hasbrain);
elseif isvolume
data = ft_datatype_volume(data);
elseif isparcellation % this should go before issource
data = ft_datatype_parcellation(data, 'parcellationstyle', parcellationstyle);
elseif issource
data = ft_datatype_source(data);
elseif isdip
data = ft_datatype_dip(data);
elseif ismvar || isfreqmvar
data = ft_datatype_mvar(data);
end
if ~isempty(dtype)
if ~isa(dtype, 'cell')
dtype = {dtype};
end
okflag = 0;
for i=1:length(dtype)
% check that the data matches with one or more of the required ft_datatypes
switch dtype{i}
case 'raw'
okflag = okflag + israw;
case 'freq'
okflag = okflag + isfreq;
case 'timelock'
okflag = okflag + istimelock;
case 'comp'
okflag = okflag + iscomp;
case 'spike'
okflag = okflag + isspike;
case 'volume'
okflag = okflag + isvolume;
case 'source'
okflag = okflag + issource;
case 'dip'
okflag = okflag + isdip;
case 'mvar'
okflag = okflag + ismvar;
case 'freqmvar'
okflag = okflag + isfreqmvar;
case 'chan'
okflag = okflag + ischan;
case 'segmentation'
okflag = okflag + issegmentation;
case 'parcellation'
okflag = okflag + isparcellation;
end % switch dtype
end % for dtype
if ~okflag
% try to convert the data
for iCell = 1:length(dtype)
if isequal(dtype(iCell), {'source'}) && isvolume
data = volume2source(data);
data = ft_datatype_source(data);
isvolume = 0;
issource = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'volume'}) && issource
data = source2volume(data);
data = ft_datatype_volume(data);
isvolume = 1;
issource = 0;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && issource
data = data2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
issource = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && istimelock
data = timelock2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
istimelock = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && iscomp % this should go before israw
data = comp2raw(data);
data = raw2timelock(data);
data = ft_datatype_timelock(data);
iscomp = 0;
israw = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && israw
data = raw2timelock(data);
data = ft_datatype_timelock(data);
israw = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && isfreq
data = freq2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
isfreq = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && iscomp
% this is never executed, because when iscomp==true, then also israw==true
data = comp2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
iscomp = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && ischan
data = chan2timelock(data);
data = ft_datatype_timelock(data);
ischan = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'freq'}) && ischan
data = chan2freq(data);
data = ft_datatype_freq(data);
ischan = 0;
isfreq = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'spike'}) && israw
data = raw2spike(data);
data = ft_datatype_spike(data);
israw = 0;
isspike = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && isspike
data = spike2raw(data,fsample);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
isspike = 0;
israw = 1;
okflag = 1;
end
end % for iCell
end % if okflag
if ~okflag
% construct an error message
if length(dtype)>1
str = sprintf('%s, ', dtype{1:(end-2)});
str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end});
else
str = dtype{1};
end
str = sprintf('This function requires %s data as input.', str);
error(str);
end % if okflag
end
if ~isempty(dimord)
if ~isa(dimord, 'cell')
dimord = {dimord};
end
if isfield(data, 'dimord')
okflag = any(strcmp(data.dimord, dimord));
else
okflag = 0;
end
if ~okflag
% construct an error message
if length(dimord)>1
str = sprintf('%s, ', dimord{1:(end-2)});
str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end});
else
str = dimord{1};
end
str = sprintf('This function requires data with a dimord of %s.', str);
error(str);
end % if okflag
end
if ~isempty(stype)
if ~isa(stype, 'cell')
stype = {stype};
end
if isfield(data, 'grad') || isfield(data, 'elec')
if any(strcmp(ft_senstype(data), stype));
okflag = 1;
else
okflag = 0;
end
else
okflag = 0;
end
if ~okflag
% construct an error message
if length(stype)>1
str = sprintf('%s, ', stype{1:(end-2)});
str = sprintf('%s%s or %s', str, stype{end-1}, stype{end});
else
str = stype{1};
end
str = sprintf('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data));
error(str);
end % if okflag
end
if ~isempty(ismeg)
if isequal(ismeg, 'yes')
okflag = isfield(data, 'grad');
elseif isequal(ismeg, 'no')
okflag = ~isfield(data, 'grad');
end
if ~okflag && isequal(ismeg, 'yes')
error('This function requires MEG data with a ''grad'' field');
elseif ~okflag && isequal(ismeg, 'no')
error('This function should not be given MEG data with a ''grad'' field');
end % if okflag
end
if ~isempty(inside)
% TODO absorb the fixinside function into this code
data = fixinside(data, inside);
okflag = isfield(data, 'inside');
if ~okflag
% construct an error message
error('This function requires data with an ''inside'' field.');
end % if okflag
end
%if isvolume
% % ensure consistent dimensions of the volumetric data
% % reshape each of the volumes that is found into a 3D array
% param = parameterselection('all', data);
% dim = data.dim;
% for i=1:length(param)
% tmp = getsubfield(data, param{i});
% tmp = reshape(tmp, dim);
% data = setsubfield(data, param{i}, tmp);
% end
%end
if isequal(hasunits, 'yes') && ~isfield(data, 'units')
% calling convert_units with only the input data adds the units without converting
data = ft_convert_units(data);
end
if issource || isvolume,
% the following section is to make a dimord-consistent representation of
% volume and source data, taking trials, time and frequency into account
if isequal(hasdimord, 'yes') && (~isfield(data, 'dimord') || ~strcmp(data.dimord,sourcedimord))
% determine the size of the data
if isfield(data, 'dimord'),
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('time', dimtok)), Ntime = length(data.time); else Ntime = 1; end
if ~isempty(strmatch('freq', dimtok)), Nfreq = length(data.freq); else Nfreq = 1; end
else
Nfreq = 1;
Ntime = 1;
end
%convert old style source representation into new style
if isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpt_pos'),
%frequency domain source representation convert to single trial power
Npos = size(data.pos,1);
Nrpt = size(data.cumtapcnt,1);
tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2));
tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside});
tmppow = zeros(Npos, Nrpt);
tapcnt = [0;cumsum(data.cumtapcnt)];
for k = 1:Nrpt
Ntap = tapcnt(k+1)-tapcnt(k);
tmppow(data.inside,k) = sum(abs(tmpmom(data.inside,(tapcnt(k)+1):tapcnt(k+1))).^2,2)./Ntap;
end
data.pow = tmppow';
data = rmfield(data, 'avg');
if strcmp(inside, 'logical'),
data = fixinside(data, 'logical');
data.inside = repmat(data.inside(:)',[Nrpt 1]);
end
elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpttap_pos'),
%frequency domain source representation convert to single taper fourier coefficients
Npos = size(data.pos,1);
Nrpt = sum(data.cumtapcnt);
data.fourierspctrm = complex(zeros(Nrpt, Npos), zeros(Nrpt, Npos));
data.fourierspctrm(:, data.inside) = transpose(cat(1, data.avg.mom{data.inside}));
data = rmfield(data, 'avg');
elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'pos_time'),
Npos = size(data.pos,1);
Nrpt = 1;
tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2));
tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside});
data.mom = tmpmom;
if isfield(data.avg, 'noise'),
tmpnoise = data.avg.noise(:);
data.noise = tmpnoise(:,ones(1,size(tmpmom,2)));
end
data = rmfield(data, 'avg');
Ntime = length(data.time);
elseif isfield(data, 'trial') && isfield(data.trial(1), 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'rpt_pos_time'),
Npos = size(data.pos,1);
Nrpt = length(data.trial);
Ntime = length(data.time);
tmpmom = zeros(Nrpt, Npos, Ntime);
for k = 1:Nrpt
tmpmom(k,data.inside,:) = cat(1,data.trial(k).mom{data.inside});
end
data = rmfield(data, 'trial');
data.mom = tmpmom;
elseif isfield(data, 'trial') && isstruct(data.trial)
Nrpt = length(data.trial);
else
Nrpt = 1;
end
% start with an initial specification of the dimord and dim
if (~isfield(data, 'dim') || ~isfield(data, 'dimord'))
if issource
% at least it should have a Nx3 pos
data.dim = size(data.pos, 1);
data.dimord = 'pos';
elseif isvolume
% at least it should have a 1x3 dim
data.dim = data.dim;
data.dimord = 'dim1_dim2_dim3';
end
end
% add the additional dimensions
if Nfreq>1
data.dimord = [data.dimord '_freq'];
data.dim = [data.dim Nfreq];
end
if Ntime>1
data.dimord = [data.dimord '_time'];
data.dim = [data.dim Ntime];
end
if Nrpt>1 && strcmp(sourcedimord, 'rpt_pos'),
data.dimord = ['rpt_' data.dimord];
data.dim = [Nrpt data.dim ];
elseif Nrpt>1 && strcmp(sourcedimord, 'rpttap_pos'),
data.dimord = ['rpttap_' data.dimord];
data.dim = [Nrpt data.dim ];
end
% the nested trial structure is not compatible with dimord
if isfield(data, 'trial') && isstruct(data.trial)
param = fieldnames(data.trial);
for i=1:length(param)
if isa(data.trial(1).(param{i}), 'cell')
concat = cell(data.dim(1), prod(data.dim(2:end)));
else
concat = zeros(data.dim(1), prod(data.dim(2:end)));
end
for j=1:length(data.trial)
tmp = data.trial(j).(param{i});
concat(j,:) = tmp(:);
end % for each trial
data.trial = rmfield(data.trial, param{i});
data.(param{i}) = reshape(concat, data.dim);
end % for each param
data = rmfield(data, 'trial');
end
end
% ensure consistent dimensions of the source reconstructed data
% reshape each of the source reconstructed parameters
if issource && isfield(data, 'dim') && prod(data.dim)==size(data.pos,1)
dim = [prod(data.dim) 1];
%elseif issource && any(~cellfun('isempty',strfind(fieldnames(data), 'dimord')))
% dim = [size(data.pos,1) 1]; %sparsely represented source structure new style
elseif isfield(data, 'dim'),
dim = [data.dim 1];
elseif issource && ~isfield(data, 'dimord')
dim = [size(data.pos,1) 1];
elseif isfield(data, 'dimord'),
%HACK
dimtok = tokenize(data.dimord, '_');
for i=1:length(dimtok)
if strcmp(dimtok(i), 'pos')
dim(1,i) = size(getsubfield(data,dimtok{i}),1);
elseif strcmp(dimtok(i), 'rpt')
dim(1,i) = nan;
else
dim(1,i) = length(getsubfield(data,dimtok{i}));
end
end
i = find(isnan(dim));
if ~isempty(i)
n = fieldnames(data);
for ii=1:length(n)
numels(1,ii) = numel(getfield(data,n{ii}));
end
nrpt = numels./prod(dim(setdiff(1:length(dim),i)));
nrpt = nrpt(nrpt==round(nrpt));
dim(i) = max(nrpt);
end
if numel(dim)==1, dim(1,2) = 1; end;
end
% these fields should not be reshaped
exclude = {'cfg' 'fwhm' 'leadfield' 'q' 'rough' 'pos'};
if ~isempty(inside) && ~strcmp(inside, 'logical')
% also exclude the inside/outside from being reshaped
exclude = cat(2, exclude, {'inside' 'outside'});
end
param = setdiff(parameterselection('all', data), exclude);
for i=1:length(param)
if any(param{i}=='.')
% the parameter is nested in a substructure, which can have multiple elements (e.g. source.trial(1).pow, source.trial(2).pow, ...)
% loop over the substructure array and reshape for every element
tok = tokenize(param{i}, '.');
sub1 = tok{1}; % i.e. this would be 'trial'
sub2 = tok{2}; % i.e. this would be 'pow'
tmp1 = getfield(data, sub1);
for j=1:numel(tmp1)
tmp2 = getfield(tmp1(j), sub2);
if prod(dim)==numel(tmp2)
tmp2 = reshape(tmp2, dim);
end
tmp1(j) = setfield(tmp1(j), sub2, tmp2);
end
data = setfield(data, sub1, tmp1);
else
tmp = getfield(data, param{i});
if prod(dim)==numel(tmp)
tmp = reshape(tmp, dim);
end
data = setfield(data, param{i}, tmp);
end
end
end
if isequal(hastrials, 'yes')
okflag = isfield(data, 'trial');
if ~okflag && isfield(data, 'dimord')
% instead look in the dimord for rpt or subj
okflag = ~isempty(strfind(data.dimord, 'rpt')) || ...
~isempty(strfind(data.dimord, 'rpttap')) || ...
~isempty(strfind(data.dimord, 'subj'));
end
if ~okflag
error('This function requires data with a ''trial'' field');
end % if okflag
end
if isequal(hasdim, 'yes') && ~isfield(data, 'dim')
data.dim = pos2dim(data.pos);
elseif isequal(hasdim, 'no') && isfield(data, 'dim')
data = rmfield(data, 'dim');
end % if hasdim
if isequal(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt')
error('This function requires data with a ''cumtapcnt'' field');
elseif isequal(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt')
data = rmfield(data, 'cumtapcnt');
end % if hascumtapcnt
if isequal(hasdof, 'yes') && ~isfield(data, 'hasdof')
error('This function requires data with a ''dof'' field');
elseif isequal(hasdof, 'no') && isfield(data, 'hasdof')
data = rmfield(data, 'cumtapcnt');
end % if hasdof
if ~isempty(cmbrepresentation)
if istimelock
data = fixcov(data, cmbrepresentation);
elseif isfreq
data = fixcsd(data, cmbrepresentation, channelcmb);
elseif isfreqmvar
data = fixcsd(data, cmbrepresentation, channelcmb);
else
error('This function requires data with a covariance, coherence or cross-spectrum');
end
end % cmbrepresentation
if issource && ~isempty(sourcerepresentation)
data = fixsource(data, 'type', sourcerepresentation);
end
if issource && ~strcmp(haspow, 'no')
data = fixsource(data, 'type', sourcerepresentation, 'haspow', haspow);
end
if isfield(data, 'grad')
% ensure that the gradiometer balancing is specified
if ~isfield(data.grad, 'balance') || ~isfield(data.grad.balance, 'current')
data.grad.balance.current = 'none';
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% represent the covariance matrix in a particular manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = fixcov(data, desired)
if isfield(data, 'cov') && ~isfield(data, 'labelcmb')
current = 'full';
elseif isfield(data, 'cov') && isfield(data, 'labelcmb')
current = 'sparse';
else
error('Could not determine the current representation of the covariance matrix');
end
if isequal(current, desired)
% nothing to do
elseif strcmp(current, 'full') && strcmp(desired, 'sparse')
% FIXME should be implemented
error('not yet implemented');
elseif strcmp(current, 'sparse') && strcmp(desired, 'full')
% FIXME should be implemented
error('not yet implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% represent the cross-spectral density matrix in a particular manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = fixcsd(data, desired, channelcmb)
% FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate
% representation (crsspctrm), or changes the representation of bivariate frequency
% domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or
% fourierspctrm)
% Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld
if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm')
current = 'sparsewithpow';
elseif isfield(data, 'powspctrm')
current = 'sparsewithpow';
elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb')
current = 'fourier';
elseif ~isfield(data, 'labelcmb')
current = 'full';
elseif isfield(data, 'labelcmb')
current = 'sparse';
else
error('Could not determine the current representation of the %s matrix', param);
end
% first go from univariate fourier to the required bivariate representation
if strcmp(current, 'fourier') && strcmp(desired, 'fourier')
% nothing to do
elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt,1);
flag = 0;
else
nrpt = 1;
end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1));
flag = nrpt==1; % needed to truncate the singleton dimension upfront
%create auto-spectra
nchan = length(data.label);
if fastflag
% all trials have the same amount of tapers
powspctrm = zeros(nrpt,nchan,nfrq,ntim);
ntap = data.cumtapcnt(1);
for p = 1:ntap
powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2;
end
powspctrm = powspctrm./ntap;
else
% different amount of tapers
powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim);
sumtapcnt = [0;cumsum(data.cumtapcnt(:))];
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat = data.fourierspctrm(indx,:,:,:);
powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p);
end
end
%create cross-spectra
if ~isempty(channelcmb),
ncmb = size(channelcmb,1);
cmbindx = zeros(ncmb,2);
labelcmb = cell(ncmb,2);
for k = 1:ncmb
ch1 = find(strcmp(data.label, channelcmb(k,1)));
ch2 = find(strcmp(data.label, channelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(k,:) = [ch1 ch2];
labelcmb(k,:) = data.label([ch1 ch2])';
end
end
crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim);
if fastflag
for p = 1:ntap
tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:);
tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:);
crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2);
end
crsspctrm = crsspctrm./ntap;
else
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:);
tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:);
crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p);
end
end
data.crsspctrm = crsspctrm;
data.labelcmb = labelcmb;
end
data.powspctrm = powspctrm;
data = rmfield(data, 'fourierspctrm');
if ntim>1,
data.dimord = 'chan_freq_time';
else
data.dimord = 'chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse')
if isempty(channelcmb), error('no channel combinations are specified'); end
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt,1);
flag = 0;
else
nrpt = 1;
end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
flag = nrpt==1; % flag needed to squeeze first dimension if singleton
ncmb = size(channelcmb,1);
cmbindx = zeros(ncmb,2);
labelcmb = cell(ncmb,2);
for k = 1:ncmb
ch1 = find(strcmp(data.label, channelcmb(k,1)));
ch2 = find(strcmp(data.label, channelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(k,:) = [ch1 ch2];
labelcmb(k,:) = data.label([ch1 ch2])';
end
end
sumtapcnt = [0;cumsum(data.cumtapcnt(:))];
fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1));
if fastflag && nrpt>1
ntap = data.cumtapcnt(1);
% compute running sum across tapers
siz = [size(data.fourierspctrm) 1];
for p = 1:ntap
indx = p:ntap:nrpt*ntap;
if p==1.
tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ...
1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4));
end
for k = 1:size(cmbindx,1)
tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ...
conj(data.fourierspctrm(indx,cmbindx(k,2),:,:));
end
if p==1
crsspctrm = tmpc;
else
crsspctrm = tmpc + crsspctrm;
end
end
crsspctrm = crsspctrm./ntap;
else
crsspctrm = zeros(nrpt, ncmb, nfrq, ntim);
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:);
tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:);
crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p);
end
end
data.crsspctrm = crsspctrm;
data.labelcmb = labelcmb;
data = rmfield(data, 'fourierspctrm');
data = rmfield(data, 'label');
if ntim>1,
data.dimord = 'chan_freq_time';
else
data.dimord = 'chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'full')
% this is how it is currently and the desired functionality of prepare_freq_matrices
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt, 1);
flag = 0;
else
nrpt = 1;
flag = 1;
end
if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end
nchan = length(data.label);
crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim);
sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))];
for k = 1:ntim
for m = 1:nfrq
for p = 1:nrpt
%FIXME speed this up in the case that all trials have equal number of tapers
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat = transpose(data.fourierspctrm(indx,:,m,k));
crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p);
clear tmpdat;
end
end
end
data.crsspctrm = crsspctrm;
data = rmfield(data, 'fourierspctrm');
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
% remove first singleton dimension
if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'),
dimtok = tokenize(data.dimord, '_');
nrpt = size(data.fourierspctrm, 1);
nchn = numel(data.label);
nfrq = numel(data.freq);
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]);
data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0;
crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim));
for k = 1:nfrq*ntim
tmp = transpose(data.fourierspctrm(:,:,k));
n = sum(tmp~=0,2);
crsspctrm(:,:,k) = tmp*tmp'./n(1);
end
data = rmfield(data, 'fourierspctrm');
data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]);
if isfield(data, 'time'),
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end;
if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end;
if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end;
if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end;
end % convert to the requested bivariate representation
% from one bivariate representation to another
if isequal(current, desired)
% nothing to do
elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ...
(strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ...
(strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier'))
% this is not possible
error('converting the cross-spectrum into a Fourier representation is not possible');
elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow')
error('not yet implemented');
elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow')
% convert back to crsspctrm/powspctrm representation: useful for plotting functions etc
indx = labelcmb2indx(data.labelcmb);
autoindx = indx(indx(:,1)==indx(:,2), 1);
cmbindx = setdiff([1:size(indx,1)]', autoindx);
if strcmp(data.dimord(1:3), 'rpt')
data.powspctrm = data.crsspctrm(:, autoindx, :, :);
data.crsspctrm = data.crsspctrm(:, cmbindx, :, :);
else
data.powspctrm = data.crsspctrm(autoindx, :, :);
data.crsspctrm = data.crsspctrm(cmbindx, :, :);
end
data.label = data.labelcmb(autoindx,1);
data.labelcmb = data.labelcmb(cmbindx, :);
if isempty(cmbindx)
data = rmfield(data, 'crsspctrm');
data = rmfield(data, 'labelcmb');
end
elseif strcmp(current, 'full') && strcmp(desired, 'sparse')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
nchan = length(data.label);
ncmb = nchan*nchan;
labelcmb = cell(ncmb, 2);
cmbindx = zeros(nchan, nchan);
k = 1;
for j=1:nchan
for m=1:nchan
labelcmb{k, 1} = data.label{m};
labelcmb{k, 2} = data.label{j};
cmbindx(m,j) = k;
k = k+1;
end
end
% reshape all possible fields
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt>1,
data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim);
else
data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim);
end
end
end
% remove obsolete fields
data = rmfield(data, 'label');
try, data = rmfield(data, 'dof'); end
% replace updated fields
data.labelcmb = labelcmb;
if ntim>1,
data.dimord = 'chancmb_freq_time';
else
data.dimord = 'chancmb_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse')
% this representation for sparse data contains autospectra
% as e.g. {'A' 'A'} in labelcmb
if isfield(data, 'crsspctrm'),
dimtok = tokenize(data.dimord, '_');
catdim = match_str(dimtok, {'chan' 'chancmb'});
data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm);
data.labelcmb = [data.label(:) data.label(:); data.labelcmb];
data = rmfield(data, 'powspctrm');
else
data.crsspctrm = data.powspctrm;
data.labelcmb = [data.label(:) data.label(:)];
data = rmfield(data, 'powspctrm');
end
data = rmfield(data, 'label');
elseif strcmp(current, 'sparse') && strcmp(desired, 'full')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
if ~isfield(data, 'label')
% ensure that the bivariate spectral factorization results can be
% processed. FIXME this is experimental and will not work if the user
% did something weird before
for k = 1:numel(data.labelcmb)
tmp = tokenize(data.labelcmb{k}, '[');
data.labelcmb{k} = tmp{1};
end
data.label = unique(data.labelcmb(:));
end
nchan = length(data.label);
ncmb = size(data.labelcmb,1);
cmbindx = zeros(nchan,nchan);
for k = 1:size(data.labelcmb,1)
ch1 = find(strcmp(data.label, data.labelcmb(k,1)));
ch2 = find(strcmp(data.label, data.labelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(ch1,ch2) = k;
end
end
complete = all(cmbindx(:)~=0);
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt==1,
data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]);
end
tmpall = nan(nrpt,nchan,nchan,nfrq,ntim);
for j = 1:nrpt
for k = 1:ntim
for m = 1:nfrq
tmpdat = nan(nchan,nchan);
indx = find(cmbindx);
if ~complete
% this realizes the missing combinations to be represented as the
% conjugate of the corresponding combination across the diagonal
tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]);
tmpdat = ctranspose(tmpdat);
end
tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]);
tmpall(j,:,:,m,k) = tmpdat;
end % for m
end % for k
end % for j
% replace the data in the old representation with the new representation
if nrpt>1,
data.(fn{ii}) = tmpall;
else
data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]);
end
end % if numel
end % for ii
% remove obsolete fields
try, data = rmfield(data, 'powspctrm'); end
try, data = rmfield(data, 'labelcmb'); end
try, data = rmfield(data, 'dof'); end
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
if ~isfield(data, 'label')
data.label = unique(data.labelcmb(:));
end
nchan = length(data.label);
ncmb = size(data.labelcmb,1);
cmbindx = zeros(nchan,nchan);
for k = 1:size(data.labelcmb,1)
ch1 = find(strcmp(data.label, data.labelcmb(k,1)));
ch2 = find(strcmp(data.label, data.labelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(ch1,ch2) = k;
end
end
complete = all(cmbindx(:)~=0);
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt==1,
data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]);
end
tmpall = nan(nchan,nchan,nfrq,ntim);
for k = 1:ntim
for m = 1:nfrq
tmpdat = nan(nchan,nchan);
indx = find(cmbindx);
if ~complete
% this realizes the missing combinations to be represented as the
% conjugate of the corresponding combination across the diagonal
tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]);
tmpdat = ctranspose(tmpdat);
end
tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]);
tmpall(:,:,m,k) = tmpdat;
end % for m
end % for k
% replace the data in the old representation with the new representation
if nrpt>1,
data.(fn{ii}) = tmpall;
else
data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]);
end
end % if numel
end % for ii
% remove obsolete fields
try, data = rmfield(data, 'powspctrm'); end
try, data = rmfield(data, 'labelcmb'); end
try, data = rmfield(data, 'dof'); end
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'full')
% this is how is currently done in prepare_freq_matrices
data = ft_checkdata(data, 'cmbrepresentation', 'sparse');
data = ft_checkdata(data, 'cmbrepresentation', 'full');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert to new source representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output] = fixsource(input, varargin)
% FIXSOURCE converts old style source structures into new style source structures and the
% other way around
%
% Use as:
% fixsource(input, type)
% where input is a source structure,
%
% Typically, old style source structures contain
% avg.XXX or trial.XXX fields
%
% The new style source structure contains:
% source.pos
% source.dim (optional, if the list of positions describes a 3D volume
% source.XXX the old style subfields in avg/trial
% source.XXXdimord string how to interpret the respective XXX field:
% e.g. source.leadfield = cell(1,Npos), source.leadfielddimord = '{pos}_chan_ori'
% source.mom = cell(1,Npos), source.momdimord = '{pos}_ori_rpttap'
type = ft_getopt(varargin, 'type');
haspow = ft_getopt(varargin, 'haspow');
if isempty(type), type = 'old'; end
if isempty(haspow), haspow = 'no'; end
fnames = fieldnames(input);
tmp = cell2mat(strfind(fnames, 'dimord')); %get dimord like fields
if any(tmp>1),
current = 'new';
elseif any(tmp==1),
%don't know what to do yet data is JM's own invention
current = 'old';
else
current = 'old';
end
if strcmp(current, type),
%do nothing
output = input;
%return
elseif strcmp(current, 'old') && strcmp(type, 'new'),
%go from old to new
if isfield(input, 'avg'),
stuff = getfield(input, 'avg');
output = rmfield(input, 'avg');
elseif isfield(input, 'trial'),
stuff = getfield(input, 'trial');
output = rmfield(input, 'trial');
else
%this could occur later in the pipeline, e.g. when doing group statistics using individual subject
%descriptive statistics
error('the input does not contain an avg or trial field');
end
%-------------------------------------------------
%remove and rename the specified fields if present
removefields = {'xgrid';'ygrid';'zgrid';'method'};
renamefields = {'frequency' 'freq'; 'csdlabel' 'orilabel'};
fnames = fieldnames(output);
for k = 1:numel(fnames)
ix = strmatch(fnames{k}, removefields);
if ~isempty(ix),
output = rmfield(output, fnames{k});
end
ix = strmatch(fnames{k}, renamefields(:,1), 'exact');
if ~isempty(ix),
output = setfield(output, renamefields{ix,2}, ...
getfield(output, renamefields{ix,1}));
output = rmfield(output, fnames{k});
end
end
%----------------------------------------------------------------------
%put the stuff originally in avg or trial one level up in the structure
fnames = fieldnames(stuff(1));
npos = size(input.pos,1);
nrpt = numel(stuff);
for k = 1:numel(fnames)
if nrpt>1,
%multiple trials
%(or subjects FIXME not yet implemented, nor tested)
tmp = getfield(stuff(1), fnames{k});
siz = size(tmp);
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom')
%pcc based mom is orixrpttap
%tranpose to keep manageable
for kk = 1:numel(input.inside)
indx = input.inside(kk);
tmp{indx} = permute(tmp{indx}, [2 1 3]);
end
nrpttap = sum(input.cumtapcnt);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox(2:end)];
elseif strcmp(fnames{k}, 'mom'),
%this is then probably not a frequency based mom
nrpttap = numel(stuff);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox];
elseif iscell(tmp)
nrpttap = numel(stuff);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox];
end
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
if iscell(tmp)
%allocate memory for cell-array
tmpall = cell(npos,1);
for n = 1:numel(input.inside)
tmpall{input.inside(n)} = zeros(sizvox);
end
else
%allocate memory for matrix
tmpall = zeros([npos nrpt siz(2:end)]);
end
cnt = 0;
for m = 1:nrpt
tmp = getfield(stuff(m), fnames{k});
siz = size(tmp);
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
if ~iscell(tmp),
tmpall(:,m,:,:,:) = tmp;
else
for n = 1:numel(input.inside)
indx = input.inside(n);
tmpdat = tmp{indx};
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom'),
if n==1, siz1 = size(tmpdat,2); end
else
if n==1, siz1 = 1; end
end
tmpall{indx}(cnt+[1:siz1],:,:,:,:) = tmpdat;
if n==numel(input.inside), cnt = cnt + siz1; end
end
end
end
output = setfield(output, fnames{k}, tmpall);
newdimord = createdimord(output, fnames{k}, 1);
if ~isempty(newdimord)
output = setfield(output, [fnames{k},'dimord'], newdimord);
end
else
tmp = getfield(stuff, fnames{k});
siz = size(tmp);
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom')
%pcc based mom is orixrpttap
%tranpose to keep manageable
for kk = 1:numel(input.inside)
indx = input.inside(kk);
tmp{indx} = permute(tmp{indx}, [2 1 3]);
end
end
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
output = setfield(output, fnames{k}, tmp);
newdimord = createdimord(output, fnames{k});
if ~isempty(newdimord)
output = setfield(output, [fnames{k},'dimord'], newdimord);
end
end
end
if isfield(output, 'csdlabel')
output = setfield(output, 'orilabel', getfield(output, 'csdlabel'));
output = rmfield(output, 'csdlabel');
end
if isfield(output, 'leadfield')
% add dimord to leadfield as well. since the leadfield is not in
% the original .avg or .trial field it has not yet been taken care of
output.leadfielddimord = createdimord(output, 'leadfield');
end
if isfield(output, 'ori')
% convert cell-array ori into matrix
ori = nan(3,npos);
try,
ori(:,output.inside) = cat(2, output.ori{output.inside});
catch
%when oris are in wrong orientation (row rather than column)
for k = 1:numel(output.inside)
ori(:,output.inside(k)) = output.ori{output.inside(k)}';
end
end
output.ori = ori;
end
current = 'new';
elseif strcmp(current, 'new') && strcmp(type, 'old')
%go from new to old
error('not implemented yet');
end
if strcmp(current, 'new') && strcmp(haspow, 'yes'),
%----------------------------------------------
%convert mom into pow if requested and possible
convert = 0;
if isfield(output, 'mom') && size(output.mom{output.inside(1)},2)==1,
convert = 1;
else
warning('conversion from mom to pow is not possible, either because there is no mom in the data, or because the dimension of mom>1. in that case call ft_sourcedescriptives first with cfg.projectmom');
end
if isfield(output, 'cumtapcnt')
convert = 1 & convert;
else
warning('conversion from mom to pow will not be done, because cumtapcnt is missing');
end
if convert,
npos = size(output.pos,1);
nrpt = size(output.cumtapcnt,1);
tmpmom = cat(2,output.mom{output.inside});
tmppow = zeros(npos, nrpt);
tapcnt = [0;cumsum(output.cumtapcnt(:))];
for k = 1:nrpt
ntap = tapcnt(k+1)-tapcnt(k);
tmppow(output.inside,k) = sum(abs(tmpmom((tapcnt(k)+1):tapcnt(k+1),:)).^2,1)./ntap;
end
output.pow = tmppow;
output.powdimord = ['pos_rpt_freq'];
end
elseif strcmp(current, 'old') && strcmp(haspow, 'yes')
warning('construction of single trial power estimates is not implemented here using old style source representation');
end
%--------------------------------------------------------
function [dimord] = createdimord(output, fname, rptflag);
if nargin==2, rptflag = 0; end
tmp = getfield(output, fname);
dimord = '';
dimnum = 1;
hasori = isfield(output, 'ori'); %if not, this is probably singleton and not relevant at the end
if iscell(tmp) && (size(output.pos,1)==size(tmp,dimnum) || size(output.pos,1)==size(tmp,2))
dimord = [dimord,'{pos}'];
dimnum = dimnum + 1;
elseif ~iscell(tmp) && size(output.pos,1)==size(tmp,dimnum)
dimord = [dimord,'pos'];
dimnum = dimnum + 1;
end
switch fname
case 'cov'
if hasori, dimord = [dimord,'_ori_ori']; end;
case 'csd'
if hasori, dimord = [dimord,'_ori_ori']; end;
case 'csdlabel'
dimord = dimord;
case 'filter'
dimord = [dimord,'_ori_chan'];
case 'leadfield'
%if hasori,
dimord = [dimord,'_chan_ori'];
%else
% dimord = [dimord,'_chan'];
%end
case 'mom'
if isfield(output, 'cumtapcnt') && sum(output.cumtapcnt)==size(tmp{output.inside(1)},1)
if hasori,
dimord = [dimord,'_rpttap_ori'];
else
dimord = [dimord,'_rpttap'];
end
elseif isfield(output, 'time')
if rptflag,
dimord = [dimord,'_rpt'];
dimnum = dimnum + 1;
end
if numel(output.time)==size(tmp{output.inside(1)},dimnum)
dimord = [dimord,'_ori_time'];
end
end
if isfield(output, 'freq') && numel(output.freq)>1,
dimord = [dimord,'_freq'];
end
case 'nai'
if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
end
case 'noise'
if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
end
case 'noisecsd'
if hasori, dimord = [dimord,'_ori_ori']; end
case 'ori'
dimord = '';
case 'pow'
if isfield(output, 'cumtapcnt') && size(output.cumtapcnt,1)==size(tmp,dimnum)
dimord = [dimord,'_rpt'];
dimnum = dimnum + 1;
end
if isfield(output, 'freq') && numel(output.freq)>1 && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
dimnum = dimnum+1;
end
if isfield(output, 'time') && numel(output.time)>1 && numel(output.time)==size(tmp,dimnum)
dimord = [dimord,'_time'];
dimnum = dimnum+1;
end
otherwise
warning('skipping unknown fieldname %s', fname);
%error(sprintf('unknown fieldname %s', fname));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = comp2raw(data)
% remove the fields that are specific to the comp representation
fn = fieldnames(data);
fn = intersect(fn, {'topo' 'topolabel' 'unmixing'});
data = rmfield(data, fn);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = volume2source(data)
if isfield(data, 'dimord')
% it is a modern source description
else
% it is an old-fashioned source description
xgrid = 1:data.dim(1);
ygrid = 1:data.dim(2);
zgrid = 1:data.dim(3);
[x y z] = ndgrid(xgrid, ygrid, zgrid);
data.pos = warp_apply(data.transform, [x(:) y(:) z(:)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = source2volume(data)
if isfield(data, 'dimord')
% it is a modern source description
%this part depends on the assumption that the list of positions is describing a full 3D volume in
%an ordered way which allows for the extraction of a transformation matrix
%i.e. slice by slice
try,
if isfield(data, 'dim'),
data.dim = pos2dim(data.pos, data.dim);
else
data.dim = pos2dim(data);
end
catch
end
end
if isfield(data, 'dim') && length(data.dim)>=3,
% it is an old-fashioned source description, or the source describes a regular 3D volume in pos
xgrid = 1:data.dim(1);
ygrid = 1:data.dim(2);
zgrid = 1:data.dim(3);
[x y z] = ndgrid(xgrid, ygrid, zgrid);
ind = [x(:) y(:) z(:)]; % these are the positions expressed in voxel indices along each of the three axes
pos = data.pos; % these are the positions expressed in head coordinates
% represent the positions in a manner that is compatible with the homogeneous matrix multiplication,
% i.e. pos = H * ind
ind = ind'; ind(4,:) = 1;
pos = pos'; pos(4,:) = 1;
% recompute the homogeneous transformation matrix
data.transform = pos / ind;
end
% remove the unwanted fields
if isfield(data, 'pos'), data = rmfield(data, 'pos'); end
if isfield(data, 'xgrid'), data = rmfield(data, 'xgrid'); end
if isfield(data, 'ygrid'), data = rmfield(data, 'ygrid'); end
if isfield(data, 'zgrid'), data = rmfield(data, 'zgrid'); end
% make inside a volume
data = fixinside(data, 'logical');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = freq2raw(freq)
if strcmp(freq.dimord, 'rpt_chan_freq_time')
dat = freq.powspctrm;
elseif strcmp(freq.dimord, 'rpttap_chan_freq_time')
warning('converting fourier representation into raw data format. this is experimental code');
dat = freq.fourierspctrm;
else
error('this only works for dimord=''rpt_chan_freq_time''');
end
nrpt = size(dat,1);
nchan = size(dat,2);
nfreq = size(dat,3);
ntime = size(dat,4);
data = [];
% create the channel labels like "MLP11@12Hz""
k = 0;
for i=1:nfreq
for j=1:nchan
k = k+1;
data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i));
end
end
% reshape and copy the data as if it were timecourses only
for i=1:nrpt
data.time{i} = freq.time;
data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime);
if any(isnan(data.trial{i}(1,:))),
tmp = data.trial{i}(1,:);
begsmp = find(isfinite(tmp),1, 'first');
endsmp = find(isfinite(tmp),1, 'last' );
data.trial{i} = data.trial{i}(:, begsmp:endsmp);
data.time{i} = data.time{i}(begsmp:endsmp);
end
end
nsmp = cellfun('size',data.time,2);
seln = find(nsmp>1,1, 'first');
if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = raw2timelock(data)
nsmp = cellfun('size',data.time,2);
data = ft_checkdata(data, 'hassampleinfo', 'yes');
ntrial = numel(data.trial);
nchan = numel(data.label);
if ntrial==1
data.time = data.time{1};
data.avg = data.trial{1};
data = rmfield(data, 'trial');
data.dimord = 'chan_time';
else
begtime = cellfun(@min,data.time);
endtime = cellfun(@max,data.time);
% this part is just about the number of samples, not about the time-axis
for i = 1:ntrial
time = data.time{i};
mint = min([ 0, begtime(i)]);
maxt = max([-max(abs(2*endtime)) * eps, endtime(i)]);
% extrapolate so that we get near 0
if (mint==0)
tmptime = -1*(fliplr(-maxt:mean(diff(time)):-mint));
else
tmptime = mint:mean(diff(time)):maxt;
end
ix(i) = sum(tmptime<0); % number of samples pre-zero
iy(i) = sum(tmptime>=0); % number of samples post-zero
% account for strictly positive or negative time-axes by removing those
% elements that are near 0 but should not be in the time-axis
if ix(i)==0
ix(i) = 1-nearest(tmptime, begtime(i));
end
if iy(i)==0
iy(i) = nearest(tmptime, endtime(i))-length(tmptime);
end
end
[mx,ix2] = max(ix);
[my,iy2] = max(iy);
nsmp = mx+my;
% create temporary time-axis
time = linspace(min(begtime), max(endtime), nsmp);
% remove any time-points before 0 iff not needed - see bug 1477
time(nearest(time, max(endtime))+1:end) = [];
% concatenate all trials
tmptrial = nan(ntrial, nchan, length(time));
for i=1:ntrial
begsmp(i) = nearest(time, data.time{i}(1));
endsmp(i) = nearest(time, data.time{i}(end));
tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i};
end
% update the sampleinfo
begpad = begsmp - min(begsmp);
endpad = max(endsmp) - endsmp;
if isfield(data, 'sampleinfo')
data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)];
end
% construct the output timelocked data
% data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime));
% data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime))
% data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime));
data.trial = tmptrial;
data.time = time;
data.dimord = 'rpt_chan_time';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = timelock2raw(data)
try
nsmp = cellfun('size',data.time,2);
catch
nsmp = size(data.time,2);
end
switch data.dimord
case 'chan_time'
data.trial{1} = data.avg;
data.time = {data.time};
data = rmfield(data, 'avg');
seln = find(nsmp>1,1, 'first');
case 'rpt_chan_time'
tmptrial = {};
tmptime = {};
ntrial = size(data.trial,1);
nchan = size(data.trial,2);
ntime = size(data.trial,3);
for i=1:ntrial
tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]);
tmptime{i} = data.time;
end
data = rmfield(data, 'trial');
data.trial = tmptrial;
data.time = tmptime;
seln = find(nsmp>1,1, 'first');
case 'subj_chan_time'
tmptrial = {};
tmptime = {};
ntrial = size(data.individual,1);
nchan = size(data.individual,2);
ntime = size(data.individual,3);
for i=1:ntrial
tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]);
tmptime{i} = data.time;
end
data = rmfield(data, 'individual');
data.trial = tmptrial;
data.time = tmptime;
seln = find(nsmp>1,1, 'first');
otherwise
error('unsupported dimord');
end
% remove the unwanted fields
if isfield(data, 'avg'), data = rmfield(data, 'avg'); end
if isfield(data, 'var'), data = rmfield(data, 'var'); end
if isfield(data, 'cov'), data = rmfield(data, 'cov'); end
if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end
if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end
if isfield(data, 'dof'), data = rmfield(data, 'dof'); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = chan2freq(data)
data.dimord = [data.dimord '_freq'];
data.freq = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = chan2timelock(data)
data.dimord = [data.dimord '_time'];
data.time = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [spike] = raw2spike(data)
fprintf('converting raw data into spike data\n');
nTrials = length(data.trial);
[spikelabel] = detectspikechan(data);
spikesel = match_str(data.label, spikelabel);
nUnits = length(spikesel);
if nUnits==0
error('cannot convert raw data to spike format since the raw data structure does not contain spike channels');
end
trialTimes = zeros(nTrials,2);
for iUnit = 1:nUnits
unitIndx = spikesel(iUnit);
spikeTimes = []; % we dont know how large it will be, so use concatenation inside loop
trialInds = [];
for iTrial = 1:nTrials
% read in the spike times
[spikeTimesTrial] = getspiketimes(data, iTrial, unitIndx);
nSpikes = length(spikeTimesTrial);
spikeTimes = [spikeTimes; spikeTimesTrial(:)];
trialInds = [trialInds; ones(nSpikes,1)*iTrial];
% get the begs and ends of trials
hasNum = find(~isnan(data.time{iTrial}));
if iUnit==1, trialTimes(iTrial,:) = data.time{iTrial}([hasNum(1) hasNum(end)]); end
end
spike.label{iUnit} = data.label{unitIndx};
spike.waveform{iUnit} = [];
spike.time{iUnit} = spikeTimes(:)';
spike.trial{iUnit} = trialInds(:)';
if iUnit==1, spike.trialtime = trialTimes; end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sub function for detection channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [spikelabel, eeglabel] = detectspikechan(data)
maxRate = 2000; % default on what we still consider a neuronal signal: this firing rate should never be exceeded
% autodetect the spike channels
ntrial = length(data.trial);
nchans = length(data.label);
spikechan = zeros(nchans,1);
for i=1:ntrial
for j=1:nchans
hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:)));
hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0);
T = nansum(diff(data.time{i})); % total time
fr = nansum(data.trial{i}(j,:)) ./ T;
spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate);
end
end
spikechan = (spikechan==ntrial);
spikelabel = data.label(spikechan);
eeglabel = data.label(~spikechan);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [spikeTimes] = getspiketimes(data, trial, unit)
spikeIndx = logical(data.trial{trial}(unit,:));
spikeCount = data.trial{trial}(unit,spikeIndx);
spikeTimes = data.time{trial}(spikeIndx);
if isempty(spikeTimes), return; end
multiSpikes = find(spikeCount>1);
% get the additional samples and spike times, we need only loop through the bins
[addSamples, addTimes] = deal([]);
for iBin = multiSpikes(:)' % looping over row vector
addTimes = [addTimes ones(1,spikeCount(iBin))*spikeTimes(iBin)];
addSamples = [addSamples ones(1,spikeCount(iBin))*spikeIndx(iBin)];
end
% before adding these times, first remove the old ones
spikeTimes(multiSpikes) = [];
spikeTimes = sort([spikeTimes(:); addTimes(:)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = spike2raw(spike, fsample)
if nargin<2 || isempty(fsample)
timeDiff = abs(diff(sort([spike.time{:}])));
fsample = 1/min(timeDiff(timeDiff>0));
warning('Desired sampling rate for spike data not specified, automatically resampled to %f', fsample);
end
% get some sizes
nUnits = length(spike.label);
nTrials = size(spike.trialtime,1);
% preallocate
data.trial(1:nTrials) = {[]};
data.time(1:nTrials) = {[]};
for iTrial = 1:nTrials
% make bins: note that the spike.time is already within spike.trialtime
x = [spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)];
timeBins = [x x(end)+1/fsample] - (0.5/fsample);
time = (spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2));
% convert to continuous
trialData = zeros(nUnits,length(time));
for iUnit = 1:nUnits
% get the timestamps and only select those timestamps that are in the trial
ts = spike.time{iUnit};
hasTrial = spike.trial{iUnit}==iTrial;
ts = ts(hasTrial);
N = histc(ts,timeBins);
if isempty(N)
N = zeros(1,length(timeBins)-1);
else
N(end) = [];
end
% store it in a matrix
trialData(iUnit,:) = N;
end
data.trial{iTrial} = trialData;
data.time{iTrial} = time;
end
% create the associated labels and other aspects of data such as the header
data.label = spike.label;
data.fsample = fsample;
if isfield(spike,'hdr'), data.hdr = spike.hdr; end
if isfield(spike,'cfg'), data.cfg = spike.cfg; end
|
github
|
philippboehmsturm/antx-master
|
nearest.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/nearest.m
| 5,600 |
utf_8
|
31bee361ec4ba27b1c1a0595b6c40e2d
|
function [indx] = nearest(array, val, insideflag, toleranceflag)
% NEAREST return the index of an array nearest to a scalar
%
% Use as
% [indx] = nearest(array, val, insideflag, toleranceflag)
%
% The second input val can be a scalar, or a [minval maxval] vector for
% limits selection.
%
% If not specified or if left empty, the insideflag and the toleranceflag
% will default to false.
%
% The boolean insideflag can be used to specify whether the value should be
% within the array or not. For example nearest(1:10, -inf) will return 1,
% but nearest(1:10, -inf, true) will return an error because -inf is not
% within the array.
%
% The boolean toleranceflag is used when insideflag is true. It can be used
% to specify whether some tolerance should be allowed for values that are
% just outside the array. For example nearest(1:10, 0.99, true, false) will
% return an error, but nearest(1:10, 0.99, true, true) will return 1. The
% tolerance that is allowed is half the distance between the subsequent
% values in the array.
% Copyright (C) 2002-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: nearest.m 7397 2013-01-23 15:49:54Z roboos $
mbreal(array);
mbreal(val);
mbvector(array);
assert(all(~isnan(val)), 'incorrect value (NaN)');
if numel(val)==2
% interpret this as a range specification like [minval maxval]
% see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1431
intervaltol=eps;
sel = find(array>=val(1) & array<=val(2));
if isempty(sel)
error('The limits you selected are outside the range available in the data');
end
indx(1) = sel(1);
indx(2) = sel(end);
if indx(1)>1 && abs(array(indx(1)-1)-val(1))<=intervaltol
indx(1)=indx(1)-1;
end
if indx(2)<length(array) && abs(array(indx(2)+1)-val(2))<=intervaltol
indx(2)=indx(2)+1;
end
return
end
mbscalar(val);
if nargin<3 || isempty(insideflag)
insideflag = false;
end
if nargin<4 || isempty(toleranceflag)
toleranceflag = false;
end
% ensure that it is a column vector
array = array(:);
% determine the most extreme values in the array
minarray = min(array);
maxarray = max(array);
% do some strict checks whether the value lies within the min-max range
if insideflag
if ~toleranceflag
if val<minarray || val>maxarray
error('the value %g should be within the range of the array from %g to %g', val, minarray, maxarray);
end
else
if ~isequal(array, sort(array))
error('the array should be sorted from small to large');
end
if numel(array)<2
error('the array have multiple elements to compute the tolerance');
end
mintolerance = (array(2)-array(1))/2;
maxtolerance = (array(end)-array(end-1))/2;
if val<(minarray-mintolerance) || val>(maxarray+maxtolerance)
error('the value %g should be within the range of the array from %g to %g with a tolerance of %g and %g on both sides', val, minarray, maxarray, mintolerance, maxtolerance);
end
end % toleragceflag
end % insideflag
% FIXME it would be possible to do some soft checks and potentially give a
% warning in case the user did not explicitly specify the inside and
% tolerance flags
% note that [dum, indx] = min([1 1 2]) will return indx=1
% and that [dum, indx] = max([1 2 2]) will return indx=2
% whereas it is desired to have consistently the match that is most towards the side of the array
if val>maxarray
% return the last occurence of the largest number
[dum, indx] = max(flipud(array));
indx = numel(array) + 1 - indx;
elseif val<minarray
% return the first occurence of the smallest number
[dum, indx] = min(array);
else
% implements a threshold to correct for errors due to numerical precision
% see http://bugzilla.fcdonders.nl/show_bug.cgi?id=498 and http://bugzilla.fcdonders.nl/show_bug.cgi?id=1943
if maxarray==minarray
precision = 1;
else
precision = (maxarray-minarray) / 10^6;
end
% return the first occurence of the nearest number
[dum, indx] = min(round((abs(array(:) - val)./precision)).*precision);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbreal(a)
if ~isreal(a)
error('Argument to mbreal must be real');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbscalar(a)
if ~all(size(a)==1)
error('Argument to mbscalar must be scalar');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbvector(a)
if ndims(a) > 2 || (size(a, 1) > 1 && size(a, 2) > 1)
error('Argument to mbvector must be a vector');
end
|
github
|
philippboehmsturm/antx-master
|
ft_checkopt.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_checkopt.m
| 5,140 |
utf_8
|
38274e2a1d9d0ac029879a9ec80e61c9
|
function opt = ft_checkopt(opt, key, allowedtype, allowedval)
% FT_CHECKOPT does a validity test on the types and values of a configuration
% structure or cell-array with key-value pairs.
%
% Use as
% opt = ft_checkopt(opt, key)
% opt = ft_checkopt(opt, key, allowedtype)
% opt = ft_checkopt(opt, key, allowedtype, allowedval)
%
% For allowedtype you can specify a string or a cell-array with multiple
% strings. All the default MATLAB types can be specified, such as
% 'double'
% 'logical'
% 'char'
% 'single'
% 'float'
% 'int16'
% 'cell'
% 'struct'
% 'function_handle'
% Furthermore, the following custom types can be specified
% 'doublescalar'
% 'doublevector'
% 'doublebivector' i.e. [1 1] or [1 2]
% 'ascendingdoublevector' i.e. [1 2 3 4 5], but not [1 3 2 4 5]
% 'ascendingdoublebivector' i.e. [1 2], but not [2 1]
% 'doublematrix'
% 'numericscalar'
% 'numericvector'
% 'numericmatrix'
% 'charcell'
%
% For allowedval you can specify a single value or a cell-array
% with multiple values.
%
% This function will give an error or it returns the input configuration
% structure or cell-array without modifications. A match on any of the
% allowed types and any of the allowed values is sufficient to let this
% function pass.
%
% See also FT_GETOPT, FT_SETOPT
% Copyright (C) 2011-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_checkopt.m 7123 2012-12-06 21:21:38Z roboos $
if nargin<3
allowedtype = {};
end
if ~iscell(allowedtype)
allowedtype = {allowedtype};
end
if nargin<4
allowedval = {};
end
if ~iscell(allowedval)
allowedval = {allowedval};
end
% get the value that belongs to this key
val = ft_getopt(opt, key); % the default will be []
if isempty(val) && ~any(strcmp(allowedtype, 'empty'))
if isnan(ft_getopt(opt, key, nan))
error('the option "%s" was not specified or was empty', key);
end
end
% check that the type of the option is allowed
ok = isempty(allowedtype);
for i=1:length(allowedtype)
switch allowedtype{i}
case 'empty'
ok = isempty(val);
case 'charcell'
ok = isa(val, 'cell') && all(cellfun(@ischar, val(:)));
case 'doublescalar'
ok = isa(val, 'double') && numel(val)==1;
case 'doublevector'
ok = isa(val, 'double') && sum(size(val)>1)==1;
case 'ascendingdoublevector'
ok = isa(val,'double') && issorted(val);
case 'doublebivector'
ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2;
case 'ascendingdoublebivector'
ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2 && val(2)>val(1);
case 'doublematrix'
ok = isa(val, 'double') && sum(size(val)>1)>1;
case 'numericscalar'
ok = isnumeric(val) && numel(val)==1;
case 'numericvector'
ok = isnumeric(val) && sum(size(val)>1)==1;
case 'numericmatrix'
ok = isnumeric(val) && sum(size(val)>1)>1;
otherwise
ok = isa(val, allowedtype{i});
end
if ok
% no reason to do additional checks
break
end
end % for allowedtype
% construct a string that describes the type of the input variable
if isnumeric(val) && numel(val)==1
valtype = sprintf('%s scalar', class(val));
elseif isnumeric(val) && numel(val)==length(val)
valtype = sprintf('%s vector', class(val));
elseif isnumeric(val) && length(size(val))==2
valtype = sprintf('%s matrix', class(val));
elseif isnumeric(val)
valtype = sprintf('%s array', class(val));
else
valtype = class(val);
end
if ~ok
if length(allowedtype)==1
error('the type of the option "%s" is invalid, it should be "%s" instead of "%s"', key, allowedtype{1}, valtype);
else
error('the type of the option "%s" is invalid, it should be any of %s instead of "%s"', key, printcell(allowedtype), valtype);
end
end
% check that the type of the option is allowed
ok = isempty(allowedval);
for i=1:length(allowedval)
ok = isequal(val, allowedval{i});
if ok
% no reason to do additional checks
break
end
end % for allowedtype
if ~ok
error('the value of the option "%s" is invalid', key);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = printcell(c)
if ~isempty(c)
s = sprintf('%s, ', c{:});
s = sprintf('{%s}', s(1:end-2));
else
s = '{}';
end
|
github
|
philippboehmsturm/antx-master
|
ft_struct2double.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/ft_struct2double.m
| 2,907 |
utf_8
|
95c620e84c2559c8b004c80743b12b95
|
function [x] = ft_struct2double(x, maxdepth);
% FT_STRUCT2DOUBLE converts all single precision numeric data in a structure
% into double precision. It will also convert plain matrices and
% cell-arrays.
%
% Use as
% x = ft_struct2double(x);
%
% Starting from Matlab 7.0, you can use single precision data in your
% computations, i.e. you do not have to convert back to double precision.
%
% Matlab version 6.5 and older only support single precision for storing
% data in memory or on disk, but do not allow computations on single
% precision data. Therefore you should converted your data from single to
% double precision after reading from file.
%
% See also FT_STRUCT2SINGLE
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_struct2double.m 7123 2012-12-06 21:21:38Z roboos $
if nargin<2
maxdepth = inf;
end
% convert the data, work recursively through the complete structure
x = convert(x, 0, maxdepth);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this subfunction does the actual work
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a] = convert(a, depth, maxdepth);
if depth>maxdepth
error('recursive depth exceeded');
end
switch class(a)
case 'struct'
% process all fields of the structure recursively
fna = fieldnames(a);
% process all elements of the array
for j=1:length(a(:))
% warning, this is a recursive call to traverse nested structures
for i=1:length(fna)
fn = fna{i};
ra = getfield(a(j), fn);
ra = convert(ra, depth+1, maxdepth);
a(j) = setfield(a(j), fn, ra);
end
end
case 'cell'
% process all elements of the cell-array recursively
% warning, this is a recursive call to traverse nested structures
for i=1:length(a(:))
a{i} = convert(a{i}, depth+1, maxdepth);
end
case {'single' 'int32' 'uint32' 'int16' 'uint16'}
% convert the values to double precision
a = double(a);
case 'double'
% keep as it is
otherwise
warning_once(sprintf('not converting class %s', class(a)));
% do nothing
end
|
github
|
philippboehmsturm/antx-master
|
printstruct.m
|
.m
|
antx-master/xspm8/external/fieldtrip/utilities/printstruct.m
| 6,214 |
utf_8
|
7d5e93679920b5cd933fb3e92cc3eddd
|
function str = printstruct(name, val)
% PRINTSTRUCT converts a Matlab structure to text which can be interpreted by MATLAB,
% resulting in the original structure.
%
% Use as
% str = printstruct(val)
% or
% str = printstruct(name, val)
% where "val" is any MATLAB variable, e.g. a scalar, vector, matrix, structure, or
% cell-array. If you pass the name of the variable, the output is a piece of MATLAB code
% that you can execute, i.e. an ASCII serialized representation of the variable.
%
% Example
% a.field1 = 1;
% a.field2 = 2;
% s = printstruct(a)
%
% b = rand(3);
% s = printstruct(b)
% Copyright (C) 2006-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: printstruct.m 7270 2012-12-29 12:09:08Z roboos $
if nargin==1
val = name;
name = inputname(1);
end
str = [];
if isstruct(val)
if numel(val)>1
str = cell(size(val));
for i=1:numel(val)
str{i} = printstruct(sprintf('%s(%d)', name, i), val(i));
end
str = cat(2, str{:});
return
else
% print it as a named structure
fn = fieldnames(val);
for i=1:length(fn)
fv = val.(fn{i});
switch class(fv)
case 'char'
% line = sprintf('%s = ''%s'';\n', fn{i}, fv);
% line = [name '.' line];
line = printstr([name '.' fn{i}], fv);
str = [str line];
case {'single' 'double'}
line = printmat([name '.' fn{i}], fv);
str = [str line];
case {'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64' 'logical'}
line = printmat([name '.' fn{i}], fv);
str = [str line];
case 'cell'
line = printcell([name '.' fn{i}], fv);
str = [str line];
case 'struct'
line = printstruct([name '.' fn{i}], fv);
str = [str line];
case 'function_handle'
printstr([name '.' fn{i}], func2str(fv));
str = [str line];
otherwise
error('unsupported');
end
end
end
elseif ~isstruct(val)
% print it as a named variable
switch class(val)
case 'char'
str = printstr(name, val);
case 'double'
str = printmat(name, val);
case {'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64'}
str = printmat(name, val);
case 'cell'
str = printcell(name, val);
otherwise
error('unsupported');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = printcell(name, val)
str = [];
siz = size(val);
if isempty(val)
str = sprintf('%s = {};\n', name);
return;
end
for i=1:prod(siz)
typ{i} = class(val{i});
end
for i=2:prod(siz)
if ~strcmp(typ{i}, typ{1})
warning('different elements in cell array');
% return
end
end
if all(size(val)==1)
str = sprintf('%s = { %s };\n', name, printval(val{1}));
else
str = sprintf('%s = {\n', name);
for i=1:siz(1)
dum = '';
for j=1:(siz(2)-1)
dum = [dum ' ' printval(val{i,j}) ',']; % add the element with a comma
end
dum = [dum ' ' printval(val{i,siz(2)})]; % add the last one without comma
str = sprintf('%s%s\n', str, dum);
end
str = sprintf('%s};\n', str);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = printmat(name, val)
str = [];
siz = size(val);
if any(size(val)==0)
str = sprintf('%s = [];\n', name);
elseif all(size(val)==1)
str = sprintf('%s = %s;\n', name, printval(val));
elseif size(val,1)==1
dum = sprintf('%g ', str, val(:));
str = sprintf('%s = [%s];\n', name, dum);
else
str = sprintf('%s = [\n', name);
for i=1:siz(1)
dum = sprintf('%g ', val(i,:));
str = sprintf('%s %s\n', str, dum);
end
str = sprintf('%s];\n', str);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = printstr(name, val)
str = [];
siz = size(val);
if siz(1)>1
str = sprintf('%s = \n', name);
for i=1:siz(1)
str = [str sprintf(' %s\n', printval(val(i,:)))];
end
elseif siz(1)==1
str = sprintf('%s = %s;\n', name, printval(val));
else
str = sprintf('%s = '''';\n', name);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = printval(val)
str = '';
siz = size(val);
switch class(val)
case 'char'
str = sprintf('''%s''', val);
case {'single' 'double'}
if all(siz==0)
str = '[]';
elseif all(siz==1)
str = sprintf('%g', val);
elseif length(siz)==2
for i=1:siz(1);
str = [ str sprintf('%g ', val(i,:)) '; ' ];
end
str = sprintf('[ %s ]', str(1:end-3));
else
error('multidimensional arrays are not supported');
end
case {'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64'}
% this is the same as for double, except for the %d instead of %g
if all(siz==1)
str = sprintf('%d', val);
elseif length(siz)==2
for i=1:siz(1);
str = [ str sprintf('%d ', val(i,:)) '; ' ];
end
str = sprintf('[ %s ]', str(1:end-3));
else
error('multidimensional arrays are not supported');
end
case 'logical'
if val
str = 'true';
else
str = 'false';
end
case 'function_handle'
str = sprintf('@%s', func2str(val));
case 'struct'
warning('cannot print structure at this level');
str = '''FIXME''';
otherwise
warning('cannot print unknown object at this level');
str = '''FIXME''';
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.